content stringlengths 23 1.05M |
|---|
private with STM32_SVD.SYSCFG;
package STM32.COMP is
type Comparator is limited private;
procedure Enable (This : in out Comparator)
with Post => Enabled (This);
procedure Disable (This : in out Comparator)
with Post => not Enabled (This);
function Enabled (This : Comparator) return Boolean;
type Inverting_Input_Port is
(One_Quarter_Vrefint,
One_Half_Vrefint,
Three_Quarter_Vrefint,
Vrefint,
PA4_DAC1_CH1,
DAC1_CH2,
Option_7,
Option_8,
DAC2_CH1)
with Size => 4;
-- These bits allows to select the source connected to the inverting input
-- of the comparator:
-- Option COMP2 COMP4 COMP6
-- 7 PA2
-- 8 PB2 PB15
procedure Set_Inverting_Input_Port
(This : in out Comparator;
Input : Inverting_Input_Port)
with Post => Get_Inverting_Input_Port (This) = Input;
-- Select the source connected to the inverting input of the comparator.
function Get_Inverting_Input_Port
(This : Comparator) return Inverting_Input_Port;
-- Return the source connected to the inverting input of the comparator.
type Output_Selection is
(No_Selection,
TIM1_BRK_ACTH,
TIM1_BRK2,
Option_7,
Option_8,
Option_9,
Option_10,
Option_11,
Option_12)
with Size => 4;
-- These bits select which Timer input must be connected with the
-- comparator output:
-- Option COMP2 COMP4 COMP6
-- 7 TIM1_OCREF_CLR TIM3_CAP3 TIM2_CAP2
-- 8 TIM1_CAP1
-- 9 TIM2_CAP4 TIM15_CAP2 TIM2_OCREF_CLR
-- 10 TIM2_OCREF_CLR TIM16_OCREF_CLR
-- 11 TIM3_CAP1 TIM15_OCREF_CLR TIM16_CAP1
-- 12 TIM3_OCREF_CLR TIM3_OCREF_CLR
for Output_Selection use
(No_Selection => 2#0000#,
TIM1_BRK_ACTH => 2#0001#,
TIM1_BRK2 => 2#0010#,
Option_7 => 2#0110#,
Option_8 => 2#0111#,
Option_9 => 2#1000#,
Option_10 => 2#1001#,
Option_11 => 2#1010#,
Option_12 => 2#1011#);
procedure Set_Output_Timer
(This : in out Comparator;
Output : Output_Selection)
with Post => Get_Output_Timer (This) = Output;
-- Select which Timer input must be connected with the comparator output.
function Get_Output_Timer (This : Comparator) return Output_Selection;
-- Return which Timer input is connected with the comparator output.
type Output_Polarity is
(Not_Inverted,
Inverted);
-- This bit is used to invert the comparator output.
procedure Set_Output_Polarity
(This : in out Comparator;
Output : Output_Polarity)
with Post => Get_Output_Polarity (This) = Output;
-- Used to invert the comparator output.
function Get_Output_Polarity (This : Comparator) return Output_Polarity;
-- Return the comparator output polarity.
type Output_Blanking is
(No_Blanking,
Option_2,
Option_3,
Option_4,
Option_5)
with Size => 3;
-- These bits select which Timer output controls the comparator output
-- blanking:
-- Option COMP2 COMP4 COMP6
-- 2 TIM1_OC5 TIM3_OC4
-- 3 TIM2_OC3
-- 4 TIM3_OC3 TIM15_OC1 TIM2_OC4
-- 5 TIM15_OC2
procedure Set_Output_Blanking
(This : in out Comparator;
Output : Output_Blanking)
with Post => Get_Output_Blanking (This) = Output;
-- Select which Timer output controls the comparator output blanking.
function Get_Output_Blanking (This : Comparator) return Output_Blanking;
-- Return which Timer output controls the comparator output blanking.
type Init_Parameters is record
Input_Minus : Inverting_Input_Port;
Output_Timer : Output_Selection;
Output_Pol : Output_Polarity;
Blanking_Source : Output_Blanking;
end record;
procedure Configure_Comparator
(This : in out Comparator;
Param : in Init_Parameters);
type Comparator_Output is (Low, High);
function Get_Comparator_Output (This : Comparator) return Comparator_Output;
-- Read the comparator output:
-- Low = non-inverting input is below inverting input,
-- High = (non-inverting input is above inverting input
procedure Set_Lock_Comparator (This : in out Comparator)
with Post => Get_Lock_Comparator (This) = True;
-- Allows to have COMPx_CSR register as read-only. It can only be cleared
-- by a system reset.
function Get_Lock_Comparator (This : Comparator) return Boolean;
-- Return the comparator lock bit state.
private
-- representation for the whole Comparator type -----------------
type Comparator is limited record
CSR : STM32_SVD.SYSCFG.COMP2_CSR_Register;
end record with Volatile, Size => 1 * 32;
for Comparator use record
CSR at 16#00# range 0 .. 31;
end record;
end STM32.COMP;
|
with Ada.Text_IO; use Ada.Text_IO;
package body Cellular is
procedure Generate(Previous : in out CellularArray) is
Generator : Boolean_Random.Generator;
begin
Reset(Generator);
for I in Previous'Range loop
Previous(I) := Random(Generator);
end loop;
end Generate;
function "="(Left, Right : in CellularArray) return Boolean is
begin
if Left'Size /= Right'Size then
return False;
end if;
for I in Left'Range loop
if Left(I) /= Right(I) then
return False;
end if;
end loop;
return True;
end;
function NextStep(Left, Cell, Right : in Boolean) return Boolean is
begin
return (not Left and (Cell or Right)) or
(Left and not Cell and not Right);
end NextStep;
function NextArray(Previous : in CellularArray) return CellularArray is
Result : CellularArray(Previous'Range) := (
Others => False
);
begin
for I in Previous'Range loop
if I > Previous'First and I < Previous'Last then
Result(I) := NextStep(Previous(I-1), Previous(I), Previous(I+1));
else
Result(I) := Previous(I);
end if;
end loop;
return Result;
end NextArray;
procedure Put(Line : in CellularArray) is
begin
for I in Line'Range loop
if Line(I) then
Put("@");
else
Put(".");
end if;
end loop;
end Put;
end Cellular;
|
--
-- Copyright 2021 (C) Jeremy Grosser <jeremy@synack.me>
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with HAL.Real_Time_Clock;
with HAL.I2C;
with HAL;
package DS3231 is
Default_Address : constant HAL.I2C.I2C_Address := 2#1101000#;
type DS3231_Device
(I2C_Port : not null HAL.I2C.Any_I2C_Port;
I2C_Address : HAL.I2C.I2C_Address)
is limited new HAL.Real_Time_Clock.RTC_Device with private;
overriding
procedure Set
(This : in out DS3231_Device;
Time : HAL.Real_Time_Clock.RTC_Time;
Date : HAL.Real_Time_Clock.RTC_Date);
overriding
procedure Get
(This : in out DS3231_Device;
Time : out HAL.Real_Time_Clock.RTC_Time;
Date : out HAL.Real_Time_Clock.RTC_Date);
overriding
function Get_Time
(This : DS3231_Device)
return HAL.Real_Time_Clock.RTC_Time;
overriding
function Get_Date
(This : DS3231_Device)
return HAL.Real_Time_Clock.RTC_Date;
-- Raised if any I2C error occurs
DS3231_Error : exception;
private
type DS3231_Device
(I2C_Port : not null HAL.I2C.Any_I2C_Port;
I2C_Address : HAL.I2C.I2C_Address)
is limited new HAL.Real_Time_Clock.RTC_Device with null record;
subtype All_Registers is HAL.UInt8_Array (16#00# .. 16#12#);
procedure Read_All
(This : DS3231_Device;
Val : out All_Registers);
function To_Integer
(BCD : HAL.UInt8)
return Integer;
function To_BCD
(N : Integer)
return HAL.UInt8;
end DS3231;
|
with Text_IO; use Text_IO;
procedure hello is
begin
Put_Line("Hello, world!");
end hello;
|
-- part of FreeTypeAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
package FT.Faces is
pragma Preelaborate;
-- reference-counted smart pointer
type Face_Reference is new Ada.Finalization.Controlled with private;
type Face_Index_Type is new Interfaces.C.long;
type Char_Index_Type is new UInt;
type Encoding is (None, Adobe_Custom, Adobe_Expert, Adobe_Standard,
Apple_Roman, Big5, GB2312, Johab, Adobe_Latin_1,
Old_Latin_2, SJIS, MS_Symbol, Unicode, Wansung);
type Load_Flag is (Load_Default, Load_No_Scale, Load_No_Hinting, Load_Render,
Load_No_Bitmap, Load_Vertical_Layout, Load_Force_Autohint,
Load_Crop_Bitmap, Load_Pedantic, Load_Advance_Only,
Load_Ignore_Global_Advance_Width, Load_No_Recourse,
Load_Ignore_Transform, Load_Monochrome, Load_Linear_Design,
Load_SBits_Only, Load_No_Autohint, Load_Load_Colour,
Load_Compute_Metrics, Load_Bitmap_Metrics_Only);
type Render_Mode is (Render_Mode_Normal, Render_Mode_Light,
Render_Mode_Mono, Render_Mode_LCD,
Render_Mode_LCD_V, Render_Mode_Max);
procedure New_Face (Library : Library_Reference; File_Path_Name : String;
Face_Index : Face_Index_Type;
Object : in out Face_Reference);
function Initialized (Object : Face_Reference) return Boolean;
-- may be called manually to remove the managed pointer and decrease the
-- reference-count early. idempotent.
--
-- post-condation : Object.Initialized = False
overriding procedure Finalize (Object : in out Face_Reference);
function Size (Object : Face_Reference) return Bitmap_Size;
procedure Kerning (Object : Face_Reference; Left_Glyph : UInt;
Right_Glyph : UInt; Kern_Mode : UInt;
aKerning : access Vector);
function Character_Index (Object : Face_Reference; Char_Code : ULong)
return Char_Index_Type;
procedure Load_Glyph (Object : Face_Reference; Glyph_Index : Char_Index_Type;
Flags : Load_Flag);
procedure Load_Character (Object : Face_Reference; Char_Code : ULong;
Flags : Load_Flag);
function Metrics (Object : Face_Reference) return Size_Metrics;
procedure Set_Pixel_Sizes (Object : Face_Reference;
Pixel_Width : UInt;
Pixel_Height : UInt);
function Glyph_Slot (Object : Face_Reference) return Glyph_Slot_Reference;
Image_Error : exception;
Undefined_Character_Code : constant Char_Index_Type;
private
for Face_Index_Type'Size use Interfaces.C.long'Size;
for Char_Index_Type'Size use UInt'Size;
procedure Check_Face_Ptr (Object : Face_Reference);
type Face_Reference is new Ada.Finalization.Controlled with record
Data : aliased Face_Ptr;
-- deallocation of the library will trigger deallocation of all Face_Ptr
-- objects. therefore, we keep a reference to the library here to make
-- sure the library outlives the Face_Reference.
Library : Library_Reference;
end record;
overriding procedure Adjust (Object : in out Face_Reference);
-- Encoding courtesy of OpenGLAda.src.ftgl.ftgl.ads type Charset
-- (Felix Krause <contact@flyx.org>, 2013)
for Encoding use (None => 0,
MS_Symbol => Character'Pos ('s') * 2 ** 24 +
Character'Pos ('y') * 2 ** 16 +
Character'Pos ('m') * 2 ** 8 +
Character'Pos ('b'),
Unicode => Character'Pos ('u') * 2 ** 24 +
Character'Pos ('n') * 2 ** 16 +
Character'Pos ('i') * 2 ** 8 +
Character'Pos ('c'),
SJIS => Character'Pos ('s') * 2 ** 24 +
Character'Pos ('j') * 2 ** 16 +
Character'Pos ('i') * 2 ** 8 +
Character'Pos ('s'),
GB2312 => Character'Pos ('g') * 2 ** 24 +
Character'Pos ('b') * 2 ** 16 +
Character'Pos (' ') * 2 ** 8 +
Character'Pos (' '),
Big5 => Character'Pos ('b') * 2 ** 24 +
Character'Pos ('i') * 2 ** 16 +
Character'Pos ('g') * 2 ** 8 +
Character'Pos ('5'),
Wansung => Character'Pos ('w') * 2 ** 24 +
Character'Pos ('a') * 2 ** 16 +
Character'Pos ('n') * 2 ** 8 +
Character'Pos ('s'),
Johab => Character'Pos ('j') * 2 ** 24 +
Character'Pos ('o') * 2 ** 16 +
Character'Pos ('h') * 2 ** 8 +
Character'Pos ('a'),
Adobe_Standard => Character'Pos ('A') * 2 ** 24 +
Character'Pos ('D') * 2 ** 16 +
Character'Pos ('O') * 2 ** 8 +
Character'Pos ('B'),
Adobe_Expert => Character'Pos ('A') * 2 ** 24 +
Character'Pos ('D') * 2 ** 16 +
Character'Pos ('B') * 2 ** 8 +
Character'Pos ('E'),
Adobe_Custom => Character'Pos ('A') * 2 ** 24 +
Character'Pos ('D') * 2 ** 16 +
Character'Pos ('B') * 2 ** 8 +
Character'Pos ('C'),
Adobe_Latin_1 => Character'Pos ('l') * 2 ** 24 +
Character'Pos ('a') * 2 ** 16 +
Character'Pos ('t') * 2 ** 8 +
Character'Pos ('1'),
Old_Latin_2 => Character'Pos ('l') * 2 ** 24 +
Character'Pos ('a') * 2 ** 16 +
Character'Pos ('t') * 2 ** 8 +
Character'Pos ('2'),
Apple_Roman => Character'Pos ('a') * 2 ** 24 +
Character'Pos ('r') * 2 ** 16 +
Character'Pos ('m') * 2 ** 8 +
Character'Pos ('n'));
for Load_Flag use
(Load_Default => 16#000000#,
Load_No_Scale => 16#000001#,
Load_No_Hinting => 16#000002#,
Load_Render => 16#000004#,
Load_No_Bitmap => 16#000008#,
Load_Vertical_Layout => 16#000010#,
Load_Force_Autohint => 16#000020#,
Load_Crop_Bitmap => 16#000040#,
Load_Pedantic => 16#000080#,
Load_Advance_Only => 16#000100#,
Load_Ignore_Global_Advance_Width => 16#000200#,
Load_No_Recourse => 16#000400#,
Load_Ignore_Transform => 16#000800#,
Load_Monochrome => 16#001000#,
Load_Linear_Design => 16#002000#,
Load_SBits_Only => 16#0004000#,
Load_No_Autohint => 16#008000#,
Load_Load_Colour => 16#100000#,
Load_Compute_Metrics => 16#200000#,
Load_Bitmap_Metrics_Only => 16#400000#);
for Load_Flag'Size use 32;
Undefined_Character_Code : constant Char_Index_Type := 0;
end FT.Faces;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Nodes.Array_Component_Association_Vectors;
with Program.Nodes.Aspect_Specification_Vectors;
with Program.Nodes.Element_Vectors;
with Program.Nodes.Expression_Vectors;
with Program.Nodes.Case_Expression_Path_Vectors;
with Program.Nodes.Case_Path_Vectors;
with Program.Nodes.Component_Clause_Vectors;
with Program.Nodes.Defining_Identifier_Vectors;
with Program.Nodes.Discrete_Range_Vectors;
with Program.Nodes.Discriminant_Association_Vectors;
with Program.Nodes.Discriminant_Specification_Vectors;
with Program.Nodes.Elsif_Path_Vectors;
with Program.Nodes.Enumeration_Literal_Specification_Vectors;
with Program.Nodes.Exception_Handler_Vectors;
with Program.Nodes.Formal_Package_Association_Vectors;
with Program.Nodes.Identifier_Vectors;
with Program.Nodes.Parameter_Association_Vectors;
with Program.Nodes.Parameter_Specification_Vectors;
with Program.Nodes.Record_Component_Association_Vectors;
with Program.Nodes.Select_Path_Vectors;
with Program.Nodes.Variant_Vectors;
with Program.Storage_Pools;
package body Program.Element_Vector_Factories is
type Array_Component_Association_Vector_Access is
not null access Program.Nodes.Array_Component_Association_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Aspect_Specification_Vector_Access is
not null access Program.Nodes.Aspect_Specification_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Case_Expression_Path_Vector_Access is
not null access Program.Nodes.Case_Expression_Path_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Case_Path_Vector_Access is
not null access Program.Nodes.Case_Path_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Component_Clause_Vector_Access is
not null access Program.Nodes.Component_Clause_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Defining_Identifier_Vector_Access is
not null access Program.Nodes.Defining_Identifier_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Discrete_Range_Vector_Access is
not null access Program.Nodes.Discrete_Range_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Discriminant_Association_Vector_Access is
not null access Program.Nodes.Discriminant_Association_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Discriminant_Specification_Vector_Access is
not null access Program.Nodes.Discriminant_Specification_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Element_Vector_Access is
not null access Program.Nodes.Element_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Elsif_Path_Vector_Access is
not null access Program.Nodes.Elsif_Path_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Enumeration_Literal_Specification_Vector_Access is not null access
Program.Nodes.Enumeration_Literal_Specification_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Exception_Handler_Vector_Access is
not null access Program.Nodes.Exception_Handler_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Expression_Vector_Access is
not null access Program.Nodes.Expression_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Formal_Package_Association_Vector_Access is not null access
Program.Nodes.Formal_Package_Association_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Identifier_Vector_Access is not null access
Program.Nodes.Identifier_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Parameter_Association_Vector_Access is not null access
Program.Nodes.Parameter_Association_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Parameter_Specification_Vector_Access is not null access
Program.Nodes.Parameter_Specification_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Record_Component_Association_Vector_Access is not null access
Program.Nodes.Record_Component_Association_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Select_Path_Vector_Access is not null access
Program.Nodes.Select_Path_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
type Variant_Vector_Access is not null access
Program.Nodes.Variant_Vectors.Vector
with Storage_Pool => Program.Storage_Pools.Pool;
-----------------------------------------------
-- Create_Array_Component_Association_Vector --
-----------------------------------------------
not overriding function Create_Array_Component_Association_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Array_Component_Associations
.Array_Component_Association_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Array_Component_Association_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Array_Component_Association_Vectors.Vector'
(Program.Nodes.Array_Component_Association_Vectors.Create
(Each));
begin
return Program.Elements.Array_Component_Associations
.Array_Component_Association_Vector_Access (Result);
end;
end Create_Array_Component_Association_Vector;
----------------------------------------
-- Create_Aspect_Specification_Vector --
----------------------------------------
not overriding function Create_Aspect_Specification_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Aspect_Specification_Vector_Access :=
new
(Self.Subpool) Program.Nodes.Aspect_Specification_Vectors.Vector'
(Program.Nodes.Aspect_Specification_Vectors.Create (Each));
begin
return Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access (Result);
end;
end Create_Aspect_Specification_Vector;
----------------------------------------
-- Create_Case_Expression_Path_Vector --
----------------------------------------
not overriding function Create_Case_Expression_Path_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Case_Expression_Paths
.Case_Expression_Path_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Case_Expression_Path_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Case_Expression_Path_Vectors.Vector'
(Program.Nodes.Case_Expression_Path_Vectors.Create (Each));
begin
return Program.Elements.Case_Expression_Paths
.Case_Expression_Path_Vector_Access (Result);
end;
end Create_Case_Expression_Path_Vector;
-----------------------------
-- Create_Case_Path_Vector --
-----------------------------
not overriding function Create_Case_Path_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Case_Paths.Case_Path_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Case_Path_Vector_Access :=
new (Self.Subpool) Program.Nodes.Case_Path_Vectors.Vector'
(Program.Nodes.Case_Path_Vectors.Create (Each));
begin
return Program.Elements.Case_Paths .Case_Path_Vector_Access (Result);
end;
end Create_Case_Path_Vector;
------------------------------------
-- Create_Component_Clause_Vector --
------------------------------------
not overriding function Create_Component_Clause_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Component_Clauses
.Component_Clause_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Component_Clause_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Component_Clause_Vectors.Vector'
(Program.Nodes.Component_Clause_Vectors.Create (Each));
begin
return Program.Elements.Component_Clauses
.Component_Clause_Vector_Access (Result);
end;
end Create_Component_Clause_Vector;
---------------------------------------
-- Create_Defining_Identifier_Vector --
---------------------------------------
not overriding function Create_Defining_Identifier_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Defining_Identifiers
.Defining_Identifier_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Defining_Identifier_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Defining_Identifier_Vectors.Vector'
(Program.Nodes.Defining_Identifier_Vectors.Create (Each));
begin
return Program.Elements.Defining_Identifiers
.Defining_Identifier_Vector_Access (Result);
end;
end Create_Defining_Identifier_Vector;
----------------------------------
-- Create_Discrete_Range_Vector --
----------------------------------
not overriding function Create_Discrete_Range_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Discrete_Ranges.Discrete_Range_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Discrete_Range_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Discrete_Range_Vectors.Vector'
(Program.Nodes.Discrete_Range_Vectors.Create (Each));
begin
return Program.Elements.Discrete_Ranges
.Discrete_Range_Vector_Access (Result);
end;
end Create_Discrete_Range_Vector;
--------------------------------------------
-- Create_Discriminant_Association_Vector --
--------------------------------------------
not overriding function Create_Discriminant_Association_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Discriminant_Associations
.Discriminant_Association_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Discriminant_Association_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Discriminant_Association_Vectors.Vector'
(Program.Nodes.Discriminant_Association_Vectors.Create (Each));
begin
return Program.Elements.Discriminant_Associations
.Discriminant_Association_Vector_Access (Result);
end;
end Create_Discriminant_Association_Vector;
----------------------------------------------
-- Create_Discriminant_Specification_Vector --
----------------------------------------------
not overriding function Create_Discriminant_Specification_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Discriminant_Specifications
.Discriminant_Specification_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Discriminant_Specification_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Discriminant_Specification_Vectors.Vector'
(Program.Nodes.Discriminant_Specification_Vectors.Create
(Each));
begin
return Program.Elements.Discriminant_Specifications
.Discriminant_Specification_Vector_Access (Result);
end;
end Create_Discriminant_Specification_Vector;
---------------------------
-- Create_Element_Vector --
---------------------------
not overriding function Create_Element_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Element_Vectors.Element_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Element_Vector_Access :=
new (Self.Subpool) Program.Nodes.Element_Vectors.Vector'
(Program.Nodes.Element_Vectors.Create (Each));
begin
return Program.Element_Vectors.Element_Vector_Access (Result);
end;
end Create_Element_Vector;
------------------------------
-- Create_Elsif_Path_Vector --
------------------------------
not overriding function Create_Elsif_Path_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Elsif_Paths.Elsif_Path_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Elsif_Path_Vector_Access :=
new (Self.Subpool) Program.Nodes.Elsif_Path_Vectors.Vector'
(Program.Nodes.Elsif_Path_Vectors.Create (Each));
begin
return Program.Elements.Elsif_Paths.Elsif_Path_Vector_Access (Result);
end;
end Create_Elsif_Path_Vector;
-----------------------------------------------------
-- Create_Enumeration_Literal_Specification_Vector --
-----------------------------------------------------
not overriding function Create_Enumeration_Literal_Specification_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Enumeration_Literal_Specifications
.Enumeration_Literal_Specification_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Enumeration_Literal_Specification_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Enumeration_Literal_Specification_Vectors.Vector'
(Program.Nodes.Enumeration_Literal_Specification_Vectors.Create
(Each));
begin
return Program.Elements.Enumeration_Literal_Specifications
.Enumeration_Literal_Specification_Vector_Access (Result);
end;
end Create_Enumeration_Literal_Specification_Vector;
-------------------------------------
-- Create_Exception_Handler_Vector --
-------------------------------------
not overriding function Create_Exception_Handler_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Exception_Handler_Vector_Access :=
new (Self.Subpool) Program.Nodes.Exception_Handler_Vectors.Vector'
(Program.Nodes.Exception_Handler_Vectors.Create (Each));
begin
return Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access (Result);
end;
end Create_Exception_Handler_Vector;
------------------------------
-- Create_Expression_Vector --
------------------------------
not overriding function Create_Expression_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Expressions.Expression_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Expression_Vector_Access :=
new (Self.Subpool) Program.Nodes.Expression_Vectors.Vector'
(Program.Nodes.Expression_Vectors.Create (Each));
begin
return Program.Elements.Expressions.Expression_Vector_Access (Result);
end;
end Create_Expression_Vector;
----------------------------------------------
-- Create_Formal_Package_Association_Vector --
----------------------------------------------
not overriding function Create_Formal_Package_Association_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Formal_Package_Associations
.Formal_Package_Association_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Formal_Package_Association_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Formal_Package_Association_Vectors.Vector'
(Program.Nodes.Formal_Package_Association_Vectors.Create
(Each));
begin
return Program.Elements.Formal_Package_Associations
.Formal_Package_Association_Vector_Access (Result);
end;
end Create_Formal_Package_Association_Vector;
------------------------------
-- Create_Identifier_Vector --
------------------------------
not overriding function Create_Identifier_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Identifiers
.Identifier_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Identifier_Vector_Access :=
new (Self.Subpool) Program.Nodes.Identifier_Vectors.Vector'
(Program.Nodes.Identifier_Vectors.Create (Each));
begin
return Program.Elements.Identifiers.Identifier_Vector_Access (Result);
end;
end Create_Identifier_Vector;
-----------------------------------------
-- Create_Parameter_Association_Vector --
-----------------------------------------
not overriding function Create_Parameter_Association_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Parameter_Association_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Parameter_Association_Vectors.Vector'
(Program.Nodes.Parameter_Association_Vectors.Create (Each));
begin
return Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access (Result);
end;
end Create_Parameter_Association_Vector;
-------------------------------------------
-- Create_Parameter_Specification_Vector --
-------------------------------------------
not overriding function Create_Parameter_Specification_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Parameter_Specification_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Parameter_Specification_Vectors.Vector'
(Program.Nodes.Parameter_Specification_Vectors.Create (Each));
begin
return Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access (Result);
end;
end Create_Parameter_Specification_Vector;
------------------------------------------------
-- Create_Record_Component_Association_Vector --
------------------------------------------------
not overriding function Create_Record_Component_Association_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Record_Component_Associations
.Record_Component_Association_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Record_Component_Association_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Record_Component_Association_Vectors.Vector'
(Program.Nodes.Record_Component_Association_Vectors.Create
(Each));
begin
return Program.Elements.Record_Component_Associations
.Record_Component_Association_Vector_Access (Result);
end;
end Create_Record_Component_Association_Vector;
-------------------------------
-- Create_Select_Path_Vector --
-------------------------------
not overriding function Create_Select_Path_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Select_Paths.Select_Path_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Select_Path_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Select_Path_Vectors.Vector'
(Program.Nodes.Select_Path_Vectors.Create (Each));
begin
return Program.Elements.Select_Paths.Select_Path_Vector_Access
(Result);
end;
end Create_Select_Path_Vector;
---------------------------
-- Create_Variant_Vector --
---------------------------
not overriding function Create_Variant_Vector
(Self : Element_Vector_Factory;
Each : Program.Element_Vectors.Iterators.Forward_Iterator'Class)
return Program.Elements.Variants.Variant_Vector_Access
is
Cursor : constant Program.Element_Vectors.Element_Cursor := Each.First;
begin
if not Program.Element_Vectors.Has_Element (Cursor) then
return null;
end if;
declare
Result : constant Variant_Vector_Access :=
new (Self.Subpool)
Program.Nodes.Variant_Vectors.Vector'
(Program.Nodes.Variant_Vectors.Create (Each));
begin
return Program.Elements.Variants.Variant_Vector_Access (Result);
end;
end Create_Variant_Vector;
end Program.Element_Vector_Factories;
|
with Tareas;
use Tareas;
procedure Crea_Tarea is
--T1 : Tarea_1;
T2 : Tarea_2;
T3 : Tarea_3;
begin
-- Insert code here.
null;
end Crea_Tarea;
|
-- 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 main body
-- AUTHOR: John Self (UCI)
-- DESCRIPTION driver routines for aflex. Calls drivers for all
-- high level routines from other packages.
-- $Header: /dc/uc/self/arcadia/aflex/ada/src/RCS/mainB.a,v 1.26 1992/12/29 22:46:15 self Exp self $
with Ada.Characters.Conversions;
with Ada.Command_Line;
with Ada.Integer_Wide_Wide_Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Wide_Wide_Unbounded.Wide_Wide_Text_IO;
with Ada.Wide_Wide_Text_IO;
with MISC_DEFS, MISC, ECS, PARSER;
with MAIN_BODY, SKELETON_MANAGER, EXTERNAL_FILE_MANAGER;
use MISC_DEFS;
with Parser_Tokens;
package body Main_Body is
use Ada.Characters.Conversions;
use Ada.Command_Line;
use Ada.Integer_Wide_Wide_Text_IO;
use Ada.Strings.Unbounded;
use Ada.Strings.Wide_Wide_Unbounded;
use Ada.Strings.Wide_Wide_Unbounded.Wide_Wide_Text_IO;
use Ada.Wide_Wide_Text_IO;
function "+" (Item : Unbounded_String) return String renames To_String;
function "+" (Item : String) return Unbounded_String
renames To_Unbounded_String;
Aflex_Version : constant Wide_Wide_String := "1.4a";
Start_Time : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
End_Time : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
---------------
-- Aflex_End --
---------------
procedure Aflex_End (Status : Integer) is
TBLSIZ : Integer;
begin
Termination_Status := Status;
Put_Line ("end " & Misc.Basename & ";");
-- we'll return this value of the OS.
if Is_Open (SkelFile) then
Close (SkelFile);
end if;
if Is_Open (Temp_Action_File) then
Delete (Temp_Action_File);
end if;
if Is_Open (Def_File) then
Delete (Def_File);
end if;
if Backtrack_Report then
if Num_Backtracking = 0 then
Put_Line (Backtrack_File, "No backtracking.");
else
if FullTbl then
Put (Backtrack_File, Num_Backtracking, 0);
Put_Line
(Backtrack_File, " backtracking (non-accepting) states.");
else
Put_Line
(Backtrack_File, "Compressed tables always backtrack.");
end if;
end if;
Close (Backtrack_File);
end if;
if PrintStats then
End_Time := Misc.Aflex_Get_Time;
Put_Line
(Standard_Error,
"aflex version " & Aflex_Version & " usage statistics:");
Put_Line
(Standard_Error,
" started at " & Start_Time & ", finished at " & End_Time);
Put (Standard_Error, " ");
Put (Standard_Error, LastNFA, 0);
Put (Standard_Error, '/');
Put (Standard_Error, Current_MNS, 0);
Put_Line (Standard_Error, " NFA states");
Put (Standard_Error, " ");
Put (Standard_Error, LastDFA, 0);
Put (Standard_Error, '/');
Put (Standard_Error, Current_Max_DFAS, 0);
Put (Standard_Error, " DFA states (");
Put (Standard_Error, TotNST, 0);
Put (Standard_Error, " words)");
PUT (Standard_Error, " ");
PUT (Standard_Error, Num_Rules - 1, 0);
-- - 1 for def. rule
Put_Line (Standard_Error, " rules");
if Num_Backtracking = 0 then
Put_Line (Standard_Error, " No backtracking");
else
if FullTbl then
Put (Standard_Error, " ");
Put (Standard_Error, Num_Backtracking, 0);
Put_Line
(Standard_Error, " backtracking (non-accepting) states");
else
Put_Line
(Standard_Error, " compressed tables always backtrack");
end if;
end if;
if Bol_Needed then
Put_Line (Standard_Error, " Beginning-of-line patterns used");
end if;
Put (Standard_Error, " ");
Put (Standard_Error, LASTSC, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CURRENT_MAX_SCS, 0);
Put_Line (Standard_Error, " start conditions");
Put (Standard_Error, " ");
Put (Standard_Error, NUMEPS, 0);
Put (Standard_Error, " epsilon states, ");
Put (Standard_Error, EPS2, 0);
Put_Line (Standard_Error, " double epsilon states");
if LASTCCL = 0 then
Put_Line (Standard_Error, " no character classes");
else
Put (Standard_Error, " ");
Put (Standard_Error, LASTCCL, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CURRENT_MAXCCLS, 0);
Put (Standard_Error, " character classes needed ");
Put (Standard_Error, CCLMAP(LASTCCL) + CCLLEN(LASTCCL), 0);
Put (Standard_Error, '/');
Put (Standard_Error, Current_Max_CCL_Table_Size, 0);
Put (Standard_Error, " words of storage, ");
Put (Standard_Error, CCLREUSE, 0);
Put_Line (Standard_Error, "reused");
end if;
Put (Standard_Error, " ");
Put (Standard_Error, NUMSNPAIRS, 0);
Put_Line (Standard_Error, " state/nextstate pairs created");
Put (Standard_Error, " ");
Put (Standard_Error, NUMUNIQ, 0);
Put (Standard_Error, '/');
Put (Standard_Error, NUMDUP, 0);
Put_Line (Standard_Error, " unique/duplicate transitions");
if FULLTBL then
TBLSIZ := LASTDFA*NUMECS;
Put (Standard_Error, " ");
Put (Standard_Error, TBLSIZ, 0);
Put_Line (Standard_Error, " table entries");
else
TBLSIZ := 2*(LASTDFA + NUMTEMPS) + 2*TBLEND;
Put (Standard_Error, " ");
Put (Standard_Error, LASTDFA + NUMTEMPS, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CURRENT_MAX_DFAS, 0);
Put_Line (Standard_Error, " base-def entries created");
Put (Standard_Error, " ");
Put (Standard_Error, TBLEND, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CURRENT_MAX_XPAIRS, 0);
Put (Standard_Error, " (peak ");
Put (Standard_Error, PEAKPAIRS, 0);
Put_Line (Standard_Error, ") nxt-chk entries created");
Put (Standard_Error, " ");
Put (Standard_Error, NUMTEMPS*NUMMECS, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CURRENT_MAX_TEMPLATE_XPAIRS, 0);
Put (Standard_Error, " (peak ");
Put (Standard_Error, NUMTEMPS*NUMECS, 0);
Put_Line (Standard_Error, ") template nxt-chk entries created");
Put (Standard_Error, " ");
Put (Standard_Error, NUMMT, 0);
Put_Line (Standard_Error, " empty table entries");
Put (Standard_Error, " ");
Put (Standard_Error, NUMPROTS, 0);
Put_Line (Standard_Error, " protos created");
Put (Standard_Error, " ");
Put (Standard_Error, NUMTEMPS, 0);
Put (Standard_Error, " templates created, ");
Put (Standard_Error, TMPUSES, 0);
Put_Line (Standard_Error, "uses");
end if;
if USEECS then
TBLSIZ := TBLSIZ + CSIZE;
Put_Line (Standard_Error, " ");
Put (Standard_Error, NUMECS, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CSIZE, 0);
Put_Line (Standard_Error, " equivalence classes created");
end if;
if USEMECS then
TBLSIZ := TBLSIZ + NUMECS;
Put (Standard_Error, " ");
Put (Standard_Error, NUMMECS, 0);
Put (Standard_Error, '/');
Put (Standard_Error, CSIZE, 0);
Put_Line (Standard_Error, " meta-equivalence classes created");
end if;
Put (Standard_Error, " ");
Put (Standard_Error, HSHCOL, 0);
Put (Standard_Error, " (");
Put (Standard_Error, HSHSAVE, 0);
Put_Line (Standard_Error, " saved) hash collisions, ");
Put (Standard_Error, DFAEQL, 0);
Put_Line (Standard_Error, " DFAs equal");
Put (Standard_Error, " ");
Put (Standard_Error, NUM_REALLOCS, 0);
Put_Line (Standard_Error, " sets of reallocations needed");
Put (Standard_Error, " ");
Put (Standard_Error, TBLSIZ, 0);
Put_Line (Standard_Error, " total table entries needed");
end if;
if Status /= 0 then
raise Aflex_Terminate;
end if;
end Aflex_End;
----------------
-- Aflex_Init --
----------------
procedure Aflex_Init is
USE_STDOUT : BOOLEAN;
OUTPUT_SPEC_FILE : Ada.Wide_Wide_Text_IO.FILE_TYPE;
INPUT_FILE : Ada.Wide_Wide_Text_IO.FILE_TYPE;
Arg_Num : INTEGER;
FLAG_POS : INTEGER;
Arg : Unbounded_String;
SKELNAME : Unbounded_String;
SKELNAME_USED : BOOLEAN := FALSE;
begin
PRINTSTATS := FALSE;
SYNTAXERROR := FALSE;
TRACE := FALSE;
SPPRDFLT := FALSE;
INTERACTIVE := FALSE;
CASEINS := FALSE;
BACKTRACK_REPORT := FALSE;
PERFORMANCE_REPORT := FALSE;
DDEBUG := FALSE;
FULLTBL := FALSE;
CONTINUED_ACTION := FALSE;
GEN_LINE_DIRS := TRUE;
USEMECS := TRUE;
USEECS := TRUE;
USE_STDOUT := FALSE;
-- do external files setup
EXTERNAL_FILE_MANAGER.INITIALIZE_FILES;
-- loop through the list of arguments
Arg_Num := 1;
while Arg_Num <= Argument_Count loop
if Argument (Arg_Num)'Length < 2
or else Argument (Arg_Num) (1) /= '-'
then
exit;
end if;
-- loop through the flags in this argument.
Arg := +Argument (Arg_Num);
FLAG_POS := 2;
while FLAG_POS <= Length (Arg) loop
case Element (Arg, FLAG_POS) is
when 'b' =>
BACKTRACK_REPORT := TRUE;
when 'd' =>
DDEBUG := TRUE;
when 'f' =>
USEECS := FALSE;
USEMECS := FALSE;
FULLTBL := TRUE;
when 'I' =>
INTERACTIVE := TRUE;
when 'i' =>
CASEINS := TRUE;
when 'L' =>
GEN_LINE_DIRS := FALSE;
when 'p' =>
PERFORMANCE_REPORT := TRUE;
when 'S' =>
if FLAG_POS /= 2 then
Misc.Aflex_Error ("-S flag must be given separately");
end if;
SKELNAME :=
Unbounded_Slice (Arg, FLAG_POS + 1, Length (Arg));
SKELNAME_USED := TRUE;
goto GET_NEXT_ARG;
when 's' =>
SPPRDFLT := TRUE;
when 't' =>
USE_STDOUT := TRUE;
when 'T' =>
TRACE := TRUE;
when 'v' =>
PRINTSTATS := TRUE;
-- UMASS CODES :
-- Added an flag to indicate whether or not the aflex generated
-- codes will be used by Ayacc extension. Ayacc extension has
-- more power in error recovery.
when 'E' =>
Ayacc_Extension_Flag := TRUE;
-- END OF UMASS CODES.
when others =>
Misc.Aflex_Error
("unknown flag "
& To_Wide_Wide_Character (Element (Arg, FLAG_POS)));
end case;
FLAG_POS := FLAG_POS + 1;
end loop;
<<GET_NEXT_ARG>> Arg_Num := Arg_Num + 1;
-- go on to next argument from list.
end loop;
if FULLTBL and USEMECS then
Misc.Aflex_Error ("full table and -cm don't make sense together");
end if;
if FULLTBL and INTERACTIVE then
Misc.Aflex_Error ("full table and -I are (currently) incompatible");
end if;
if Arg_Num <= Argument_Count then
begin
if (Arg_Num - Argument_Count + 1 > 1) then
Misc.Aflex_Error ("extraneous argument(s) given");
end if;
-- Tell aflex where to read input from.
In_File_Name := +Argument (Arg_Num);
OPEN (INPUT_FILE, IN_FILE, Argument (Arg_Num), "wcem=8");
SET_INPUT (INPUT_FILE);
exception
when NAME_ERROR =>
Misc.Aflex_Fatal
("can't open "
& To_Wide_Wide_String (To_String (In_File_Name)));
end;
end if;
if not USE_STDOUT then
EXTERNAL_FILE_MANAGER.GET_SCANNER_SPEC_FILE (OUTPUT_SPEC_FILE);
end if;
if BACKTRACK_REPORT then
EXTERNAL_FILE_MANAGER.GET_BACKTRACK_FILE (BACKTRACK_FILE);
end if;
LASTCCL := 0;
LASTSC := 0;
-- initialize the statistics
Start_Time := Misc.Aflex_Get_Time;
begin
-- open the skeleton file
if SKELNAME_USED then
OPEN(SKELFILE, IN_FILE, +SKELNAME, "wcem=8");
SKELETON_MANAGER.SET_EXTERNAL_SKELETON;
end if;
exception
when USE_ERROR | NAME_ERROR =>
Misc.Aflex_Fatal
("couldn't open skeleton file "
& To_Wide_Wide_String (To_String (SKELNAME)));
end;
-- without a third argument create make an anonymous temp file.
begin
CREATE(TEMP_ACTION_FILE, OUT_FILE, "", "wcem=8");
CREATE(DEF_FILE, OUT_FILE, "", "wcem=8");
exception
when USE_ERROR | NAME_ERROR =>
Misc.Aflex_Fatal ("can't create temporary file");
end;
LASTDFA := 0;
LASTNFA := 0;
NUM_RULES := 0;
NUMAS := 0;
NUMSNPAIRS := 0;
TMPUSES := 0;
NUMECS := 0;
NUMEPS := 0;
EPS2 := 0;
NUM_REALLOCS := 0;
HSHCOL := 0;
DFAEQL := 0;
TOTNST := 0;
NUMUNIQ := 0;
NUMDUP := 0;
HSHSAVE := 0;
EOFSEEN := FALSE;
DATAPOS := 0;
DATALINE := 0;
NUM_BACKTRACKING := 0;
ONESP := 0;
NUMPROTS := 0;
VARIABLE_TRAILING_CONTEXT_RULES := FALSE;
BOL_NEEDED := FALSE;
LINENUM := 1;
SECTNUM := 1;
FIRSTPROT := NIL;
-- used in mkprot() so that the first proto goes in slot 1
-- of the proto queue
LASTPROT := 1;
if USEECS then
-- set up doubly-linked equivalence classes
ECGROUP(1) := NIL;
for CNT in 2 .. CSIZE loop
ECGROUP(CNT) := CNT - 1;
NEXTECM(CNT - 1) := CNT;
end loop;
NEXTECM(CSIZE) := NIL;
else
-- put everything in its own equivalence class
for CNT in 1 .. CSIZE loop
ECGROUP(CNT) := CNT;
NEXTECM(CNT) := BAD_SUBSCRIPT; -- to catch errors
end loop;
end if;
SET_UP_INITIAL_ALLOCATIONS;
end Aflex_Init;
-- readin - read in the rules section of the input file(s)
procedure READIN is
begin
SKELETON_MANAGER.SKEL_OUT;
MISC.LINE_DIRECTIVE_OUT;
PARSER.YYPARSE;
if (USEECS) then
ECS.CRE8ECS(NEXTECM, ECGROUP, CSIZE, NUMECS);
ECS.CCL2ECL;
else
NUMECS := CSIZE;
end if;
exception
when Parser_Tokens.Syntax_Error =>
Misc.Aflex_Error
("fatal parse error at line " & Integer'Wide_Wide_Image (LINENUM));
Main_Body.Aflex_End (1);
end READIN;
-- set_up_initial_allocations - allocate memory for internal tables
procedure SET_UP_INITIAL_ALLOCATIONS is
begin
CURRENT_MNS := INITIAL_MNS;
FIRSTST := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
LASTST := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
FINALST := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
TRANSCHAR := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
TRANS1 := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
TRANS2 := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
ACCPTNUM := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
ASSOC_RULE := ALLOCATE_INTEGER_ARRAY(CURRENT_MNS);
STATE_TYPE := ALLOCATE_STATE_ENUM_ARRAY(CURRENT_MNS);
CURRENT_MAX_RULES := INITIAL_MAX_RULES;
RULE_TYPE := ALLOCATE_RULE_ENUM_ARRAY(CURRENT_MAX_RULES);
RULE_LINENUM := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_RULES);
CURRENT_MAX_SCS := INITIAL_MAX_SCS;
SCSET := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_SCS);
SCBOL := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_SCS);
SCXCLU := ALLOCATE_BOOLEAN_ARRAY(CURRENT_MAX_SCS);
SCEOF := ALLOCATE_BOOLEAN_ARRAY(CURRENT_MAX_SCS);
SCNAME := ALLOCATE_VSTRING_ARRAY(CURRENT_MAX_SCS);
ACTVSC := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_SCS);
CURRENT_MAXCCLS := INITIAL_MAX_CCLS;
CCLMAP := ALLOCATE_INTEGER_ARRAY(CURRENT_MAXCCLS);
CCLLEN := ALLOCATE_INTEGER_ARRAY(CURRENT_MAXCCLS);
CCLNG := ALLOCATE_INTEGER_ARRAY(CURRENT_MAXCCLS);
CCL_Sets := Allocate_Wide_Wide_Character_Set_Array (CURRENT_MAXCCLS);
Current_Max_CCL_Table_Size := Initial_Max_CCL_Table_Size;
CCLTBL := Allocate_Unicode_Character_Array (Current_Max_CCL_Table_Size);
CURRENT_MAX_DFA_SIZE := INITIAL_MAX_DFA_SIZE;
CURRENT_MAX_XPAIRS := INITIAL_MAX_XPAIRS;
NXT := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_XPAIRS);
CHK := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_XPAIRS);
CURRENT_MAX_TEMPLATE_XPAIRS := INITIAL_MAX_TEMPLATE_XPAIRS;
TNXT := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_TEMPLATE_XPAIRS);
CURRENT_MAX_DFAS := INITIAL_MAX_DFAS;
BASE := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFAS);
DEF := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFAS);
DFASIZ := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFAS);
ACCSIZ := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFAS);
DHASH := ALLOCATE_INTEGER_ARRAY(CURRENT_MAX_DFAS);
DSS := ALLOCATE_INT_PTR_ARRAY(CURRENT_MAX_DFAS);
DFAACC := ALLOCATE_DFAACC_UNION(CURRENT_MAX_DFAS);
end SET_UP_INITIAL_ALLOCATIONS;
end Main_Body;
|
$NetBSD: patch-src__editor_src_src__editor__view.adb,v 1.2 2014/04/30 16:32:20 marino Exp $
Disambiguation required to compile with FSF GNAT 4.9.0
--- src_editor/src/src_editor_view.adb.orig 2012-07-02 09:23:20.000000000 +0000
+++ src_editor/src/src_editor_view.adb
@@ -1789,6 +1789,7 @@ package body Src_Editor_View is
is
View : constant Source_View := Source_View (Widget);
Dummy_Gint : Gint;
+ Dummy2_Gint : Gint;
W, H, D : Gint;
Button_Y : Gint;
Lower, Upper : Gdouble;
@@ -1807,7 +1808,7 @@ package body Src_Editor_View is
Button_Y := Gint (Get_Y (Event));
Get_Geometry
- (Get_Window (View.Area), Dummy_Gint, Dummy_Gint, W, H, D);
+ (Get_Window (View.Area), Dummy_Gint, Dummy2_Gint, W, H, D);
Adj := Get_Vadjustment (View.Scroll);
Lower := Get_Lower (Adj);
|
-- This spec has been automatically generated from cm7.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
-- Floating Point Unit
package Cortex_M_SVD.FPU is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Access privileges for coprocessor 10.
type CPACR_CP10_Field is
(
-- Any attempted access generates a NOCP UsageFault.
Access_Denied,
-- Privileged access only. An unprivileged addess generates a NOCP
-- UsageFault.
Privileged,
-- Full access.
Full_Access)
with Size => 2;
for CPACR_CP10_Field use
(Access_Denied => 0,
Privileged => 1,
Full_Access => 3);
-- CPACR_CP array
type CPACR_CP_Field_Array is array (10 .. 11) of CPACR_CP10_Field
with Component_Size => 2, Size => 4;
-- Type definition for CPACR_CP
type CPACR_CP_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- CP as a value
Val : HAL.UInt4;
when True =>
-- CP as an array
Arr : CPACR_CP_Field_Array;
end case;
end record
with Unchecked_Union, Size => 4;
for CPACR_CP_Field use record
Val at 0 range 0 .. 3;
Arr at 0 range 0 .. 3;
end record;
-- Coprocessor Access Control Register
type CPACR_Register is record
-- unspecified
Reserved_0_19 : HAL.UInt20 := 16#0#;
-- Access privileges for coprocessor 10.
CP : CPACR_CP_Field := (As_Array => False, Val => 16#0#);
-- unspecified
Reserved_24_31 : HAL.UInt8 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CPACR_Register use record
Reserved_0_19 at 0 range 0 .. 19;
CP at 0 range 20 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
-- Floating-Point Context Control Register
type FPCCR_Register is record
-- Lazy state preservation activation.
LSPACT : Boolean := False;
-- Read-only. If set, privilege level was user when the floating-point
-- stack frame was allocated.
USER : Boolean := False;
-- unspecified
Reserved_2_2 : HAL.Bit := 16#0#;
-- Read-only. If set, the mode was Thread Mode when the floating-point
-- stack frame was allocated.
THREAD : Boolean := False;
-- Read-only. If set, priority permitted setting the HardFault handler
-- to the pending state when the floating-point stack frame was
-- allocated.
HFRDY : Boolean := False;
-- Read-only. If set, MemManage is enabled and priority permitted
-- setting the MemManage handler to the pending state when the
-- floating-point stack frame was allocated.
MMRDY : Boolean := False;
-- Read-only. If set, BusFault is enabled and priority permitted setting
-- the BusFault handler to the pending state when the floating-point
-- stack frame was allocated.
BFRDY : Boolean := False;
-- unspecified
Reserved_7_7 : HAL.Bit := 16#0#;
-- Read-only. If set, DebugMonitor is enabled and priority permitted
-- setting the DebugMonitor handler to the pending state when the
-- floating-point stack frame was allocated.
MONRDY : Boolean := False;
-- unspecified
Reserved_9_29 : HAL.UInt21 := 16#0#;
-- Enables automatic lazy state preservation for floating-point context.
LSPEN : Boolean := True;
-- Enables CONTROL.FPCA setting on execution of a floating point
-- instruction. This results in automatic hardware state preservation
-- and restoration, for floating-point context, on exception entry and
-- exit.
ASPEN : Boolean := True;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for FPCCR_Register use record
LSPACT at 0 range 0 .. 0;
USER at 0 range 1 .. 1;
Reserved_2_2 at 0 range 2 .. 2;
THREAD at 0 range 3 .. 3;
HFRDY at 0 range 4 .. 4;
MMRDY at 0 range 5 .. 5;
BFRDY at 0 range 6 .. 6;
Reserved_7_7 at 0 range 7 .. 7;
MONRDY at 0 range 8 .. 8;
Reserved_9_29 at 0 range 9 .. 29;
LSPEN at 0 range 30 .. 30;
ASPEN at 0 range 31 .. 31;
end record;
subtype FPCAR_ADDRESS_Field is HAL.UInt29;
-- Floating-Point Context Address Register
type FPCAR_Register is record
-- unspecified
Reserved_0_2 : HAL.UInt3 := 16#0#;
-- The FPCAR register holds the location of the unpopulated
-- floating-point register space allocated on an exception stack frame.
ADDRESS : FPCAR_ADDRESS_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for FPCAR_Register use record
Reserved_0_2 at 0 range 0 .. 2;
ADDRESS at 0 range 3 .. 31;
end record;
subtype FPDSCR_RMode_Field is HAL.UInt2;
-- Floating-Point Default Status Control Register
type FPDSCR_Register is record
-- unspecified
Reserved_0_21 : HAL.UInt22 := 16#0#;
-- Default value for FPSCR.RMode.
RMode : FPDSCR_RMode_Field := 16#0#;
-- Default value for FPSCR.FZ.
FZ : Boolean := False;
-- Default value for FPSCR.DN.
DN : Boolean := False;
-- Default value for FPSCR.AHP.
AHP : Boolean := False;
-- unspecified
Reserved_27_31 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for FPDSCR_Register use record
Reserved_0_21 at 0 range 0 .. 21;
RMode at 0 range 22 .. 23;
FZ at 0 range 24 .. 24;
DN at 0 range 25 .. 25;
AHP at 0 range 26 .. 26;
Reserved_27_31 at 0 range 27 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Floating Point Unit
type FPU_Peripheral is record
-- Coprocessor Access Control Register
CPACR : aliased CPACR_Register;
-- Floating-Point Context Control Register
FPCCR : aliased FPCCR_Register;
-- Floating-Point Context Address Register
FPCAR : aliased FPCAR_Register;
-- Floating-Point Default Status Control Register
FPDSCR : aliased FPDSCR_Register;
end record
with Volatile;
for FPU_Peripheral use record
CPACR at 16#0# range 0 .. 31;
FPCCR at 16#1AC# range 0 .. 31;
FPCAR at 16#1B0# range 0 .. 31;
FPDSCR at 16#1B4# range 0 .. 31;
end record;
-- Floating Point Unit
FPU_Periph : aliased FPU_Peripheral
with Import, Address => FPU_Base;
end Cortex_M_SVD.FPU;
|
package body surface.elements is
procedure quad (X,Y, Width, Height : Integer ; Border : Boolean := False) is
use raylib;
begin
raylib.shapes.draw_rectangle (
posX => int(X),
posY => int(Y),
width => int(Width),
height => int(Height),
c => raylib.LIGHTGRAY);
if Border then
raylib.shapes.draw_rectangle_lines_ex (
rec => (float(X), float(Y), float(Width), float(Height)),
line_thick => 2,
c => GOLD);
end if;
end quad;
procedure print (X,Y : Integer; Text : String; Size : Integer := 16) is
begin
raylib.text.draw_ex (
raylib.text.get_font_default,
text,
(Float(X), Float(Y)),
Float(Size),
1.0,
raylib.BLACK);
end print;
end surface.elements;
|
package Private_Enum is
type Pet is private;
private
type Pet is (cat, dog);
end Private_Enum;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012, 2013, 2016 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Strings;
with ADO.Objects;
with ADO.Queries;
with ADO.SQL;
with ADO.Statements;
with ADO.Sessions.Entities;
with AWA.Services.Contexts;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Permissions;
with AWA.Storages.Stores.Files;
package body AWA.Storages.Services is
use AWA.Services;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Storages.Services");
-- ------------------------------
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
-- ------------------------------
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access is
begin
return Service.Stores (Kind);
end Get_Store;
-- ------------------------------
-- Initializes the storage service.
-- ------------------------------
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class) is
Root : constant String := Module.Get_Config (Stores.Files.Root_Directory_Parameter.P);
Tmp : constant String := Module.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
begin
AWA.Modules.Module_Manager (Service).Initialize (Module);
Service.Stores (Storages.Models.DATABASE) := Service.Database_Store'Unchecked_Access;
Service.Stores (Storages.Models.FILE) := AWA.Storages.Stores.Files.Create_File_Store (Root);
Service.Stores (Storages.Models.TMP) := AWA.Storages.Stores.Files.Create_File_Store (Tmp);
Service.Database_Store.Tmp := Service.Stores (Storages.Models.TMP);
end Initialize;
-- ------------------------------
-- Create or save the folder.
-- ------------------------------
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
begin
if not Folder.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Folder.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Folder.Set_Workspace (Workspace);
end if;
-- Check that the user has the create folder permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Folder.Permission,
Entity => Workspace);
Ctx.Start;
if not Folder.Is_Inserted then
Folder.Set_Create_Date (Ada.Calendar.Clock);
Folder.Set_Owner (Ctx.Get_User);
end if;
Folder.Save (DB);
Ctx.Commit;
end Save_Folder;
-- ------------------------------
-- Load the folder instance identified by the given identifier.
-- ------------------------------
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Folder.Load (Session => DB, Id => Id);
end Load_Folder;
-- ------------------------------
-- Load the storage instance identified by the given identifier.
-- ------------------------------
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
begin
Storage.Load (Session => DB, Id => Id);
end Load_Storage;
-- ------------------------------
-- Load the storage instance stored in a folder and identified by a name.
-- ------------------------------
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Folder : in ADO.Identifier;
Name : in String;
Found : out Boolean) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.SQL.Query;
begin
Query.Bind_Param ("folder_id", Folder);
Query.Bind_Param ("name", Name);
Query.Set_Filter ("folder_id = :folder_id AND name = :name AND original_id IS NULL");
Storage.Find (Session => DB,
Query => Query,
Found => Found);
if not Found then
Log.Warn ("Storage file {0} not found in folder {1}",
Name, ADO.Identifier'Image (Folder));
end if;
end Load_Storage;
-- ------------------------------
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, Data.Get_Local_Filename, Storage);
end Save;
-- ------------------------------
-- Save the file described <b>File</b> in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
File : in AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type) is
begin
Storage_Service'Class (Service).Save (Into, AWA.Storages.Get_Path (File), Storage);
end Save;
-- ------------------------------
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
-- ------------------------------
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type) is
use type AWA.Storages.Models.Storage_Type;
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Workspace : AWA.Workspaces.Models.Workspace_Ref;
Store : Stores.Store_Access;
Created : Boolean;
begin
Log.Info ("Save {0} in storage space", Path);
Into.Set_Storage (Storage);
Store := Storage_Service'Class (Service).Get_Store (Into.Get_Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
if not Into.Is_Null then
Workspace := AWA.Workspaces.Models.Workspace_Ref (Into.Get_Workspace);
end if;
if Workspace.Is_Null then
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, Workspace);
Into.Set_Workspace (Workspace);
end if;
-- Check that the user has the create storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Storage.Permission,
Entity => Workspace);
Ctx.Start;
Created := not Into.Is_Inserted;
if Created then
Into.Set_Create_Date (Ada.Calendar.Clock);
Into.Set_Owner (Ctx.Get_User);
end if;
Into.Save (DB);
Store.Save (DB, Into, Path);
Into.Save (DB);
-- Notify the listeners.
if Created then
Storage_Lifecycle.Notify_Create (Service, Into);
else
Storage_Lifecycle.Notify_Update (Service, Into);
end if;
Ctx.Commit;
end Save;
-- ------------------------------
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
-- ------------------------------
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
use type AWA.Storages.Models.Storage_Type;
use type AWA.Storages.Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (Models.Query_Storage_Get_Data);
Kind : AWA.Storages.Models.Storage_Type;
begin
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Name := Query.Get_Unbounded_String (2);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (4));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (5);
else
declare
Store : Stores.Store_Access;
Storage : AWA.Storages.Models.Storage_Ref;
File : AWA.Storages.Storage_File (TMP);
Found : Boolean;
begin
Store := Storage_Service'Class (Service).Get_Store (Kind);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Kind));
end if;
Storage.Load (DB, From, Found);
if not Found then
Log.Warn ("Storage entity {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Store.Load (DB, Storage, File);
Into := ADO.Create_Blob (AWA.Storages.Get_Path (File));
end;
end if;
end Load;
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : in out Storage_File) is
use type Stores.Store_Access;
use type Models.Storage_Type;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Query : ADO.Queries.Context;
Found : Boolean;
Storage : AWA.Storages.Models.Storage_Ref;
Local : AWA.Storages.Models.Store_Local_Ref;
Store : Stores.Store_Access;
begin
if Into.Storage = AWA.Storages.DATABASE then
Log.Error ("'DATABASE' is not a valid storage type for local file");
return;
end if;
if Mode = READ then
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Local);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Local.Find (DB, Query, Found);
if Found then
Into.Path := Local.Get_Path;
Log.Info ("Load local file {0} path {1}", ADO.Identifier'Image (From),
Ada.Strings.Unbounded.To_String (Into.Path));
return;
end if;
end if;
Query.Set_Query (AWA.Storages.Models.Query_Storage_Get_Storage);
Query.Bind_Param ("store_id", From);
Query.Bind_Param ("user_id", User);
ADO.Sessions.Entities.Bind_Param (Query, "table",
AWA.Workspaces.Models.WORKSPACE_TABLE, DB);
Storage.Find (DB, Query, Found);
if not Found then
Log.Info ("File Id {0} not found", ADO.Identifier'Image (From));
raise ADO.Objects.NOT_FOUND;
end if;
Ctx.Start;
Store := Storage_Service'Class (Service).Get_Store (Storage.Get_Storage);
Store.Load (Session => DB,
From => Storage,
Into => Into);
Ctx.Commit;
Log.Info ("Load local file {0} path {1}", ADO.Identifier'Image (From),
Ada.Strings.Unbounded.To_String (Into.Path));
end Get_Local_File;
procedure Create_Local_File (Service : in out Storage_Service;
Into : in out AWA.Storages.Storage_File) is
use Ada.Strings.Unbounded;
Tmp : constant String := Service.Get_Config (Stores.Files.Tmp_Directory_Parameter.P);
Value : Integer;
begin
Util.Concurrent.Counters.Increment (Service.Temp_Id, Value);
Into.Path := To_Unbounded_String (Tmp & "/tmp-" & Util.Strings.Image (Value));
end Create_Local_File;
-- ------------------------------
-- Create a temporary file path.
-- ------------------------------
procedure Create (Service : in out Storage_Service;
Into : out AWA.Storages.Storage_File;
Storage : in AWA.Storages.Models.Storage_Type) is
use type Stores.Store_Access;
Store : Stores.Store_Access;
begin
Store := Storage_Service'Class (Service).Get_Store (Storage);
if Store = null then
Log.Error ("There is no store for storage {0}", Models.Storage_Type'Image (Storage));
end if;
end Create;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class) is
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Id : constant ADO.Identifier := ADO.Objects.Get_Value (Storage.Get_Key);
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Id));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
Storage_Lifecycle.Notify_Delete (Service, Storage);
Storage.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Deletes the storage instance.
-- ------------------------------
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier) is
use type Stores.Store_Access;
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
S : AWA.Storages.Models.Storage_Ref;
Query : ADO.Statements.Query_Statement
:= DB.Create_Statement (AWA.Storages.Models.Query_Storage_Delete_Local);
Store : Stores.Store_Access;
begin
Log.Info ("Delete storage {0}", ADO.Identifier'Image (Storage));
-- Check that the user has the delete storage permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Storage);
Ctx.Start;
S.Load (Id => Storage, Session => DB);
Store := Storage_Service'Class (Service).Get_Store (S.Get_Storage);
if Store = null then
Log.Error ("There is no store associated with storage item {0}",
ADO.Identifier'Image (Storage));
else
Store.Delete (DB, S);
end if;
Storage_Lifecycle.Notify_Delete (Service, S);
-- Delete the storage instance and all storage that refer to it.
declare
Stmt : ADO.Statements.Delete_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Stmt.Set_Filter (Filter => "id = ? OR original_id = ?");
Stmt.Add_Param (Value => Storage);
Stmt.Add_Param (Value => Storage);
Stmt.Execute;
end;
-- Delete the local storage instances.
Query.Bind_Param ("store_id", Storage);
Query.Execute;
S.Delete (DB);
Ctx.Commit;
end Delete;
-- ------------------------------
-- Publish or not the storage instance.
-- ------------------------------
procedure Publish (Service : in Storage_Service;
Id : in ADO.Identifier;
State : in Boolean;
File : in out AWA.Storages.Models.Storage_Ref'Class) is
pragma Unreferenced (Service);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
begin
Ctx.Start;
-- Check that the user has the permission to publish for the given comment.
AWA.Permissions.Check (Permission => ACL_Delete_Storage.Permission,
Entity => Id);
File.Load (DB, Id);
File.Set_Is_Public (State);
File.Save (DB);
declare
Update : ADO.Statements.Update_Statement
:= DB.Create_Statement (AWA.Storages.Models.STORAGE_TABLE);
begin
Update.Set_Filter (Filter => "original_id = ?");
Update.Save_Field ("is_public", State);
Update.Add_Param (Id);
Update.Execute;
end;
Ctx.Commit;
end Publish;
end AWA.Storages.Services;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 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.
package body Orka.Rendering.Buffers.Mapped is
overriding
function Length (Object : Mapped_Buffer) return Natural is
(Object.Buffer.Length);
procedure Map
(Object : in out Mapped_Buffer;
Length : Size;
Flags : GL.Objects.Buffers.Access_Bits) is
begin
case Object.Kind is
-- Numeric types
when UByte_Type =>
Pointers.UByte.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_UByte);
when UShort_Type =>
Pointers.UShort.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_UShort);
when UInt_Type =>
Pointers.UInt.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_UInt);
when Byte_Type =>
Pointers.Byte.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Byte);
when Short_Type =>
Pointers.Short.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Short);
when Int_Type =>
Pointers.Int.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Int);
when Half_Type =>
Pointers.Half.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Half);
when Single_Type =>
Pointers.Single.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Single);
when Double_Type =>
Pointers.Double.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_Double);
-- Composite types
when Single_Vector_Type =>
Pointers.Single_Vector4.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_SV);
when Double_Vector_Type =>
Pointers.Double_Vector4.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_DV);
when Single_Matrix_Type =>
Pointers.Single_Matrix4.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_SM);
when Double_Matrix_Type =>
Pointers.Double_Matrix4.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_DM);
when Arrays_Command_Type =>
Pointers.Arrays_Command.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_AC);
when Elements_Command_Type =>
Pointers.Elements_Command.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_EC);
when Dispatch_Command_Type =>
Pointers.Dispatch_Command.Map_Range
(Object.Buffer.Buffer, Flags, 0, Length, Object.Pointer_DC);
end case;
end Map;
-----------------------------------------------------------------------------
overriding
procedure Bind
(Object : Mapped_Buffer;
Target : Indexed_Buffer_Target;
Index : Natural)
is
Buffer_Target : access constant GL.Objects.Buffers.Buffer_Target;
Offset : constant Size := Size (Object.Offset);
Length : constant Size := Size (Mapped_Buffer'Class (Object).Length);
begin
case Target is
when Uniform =>
Buffer_Target := GL.Objects.Buffers.Uniform_Buffer'Access;
when Shader_Storage =>
Buffer_Target := GL.Objects.Buffers.Shader_Storage_Buffer'Access;
when Atomic_Counter =>
Buffer_Target := GL.Objects.Buffers.Atomic_Counter_Buffer'Access;
end case;
case Object.Kind is
-- Numeric types
when UByte_Type =>
Pointers.UByte.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when UShort_Type =>
Pointers.UShort.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when UInt_Type =>
Pointers.UInt.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Byte_Type =>
Pointers.Byte.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Short_Type =>
Pointers.Short.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Int_Type =>
Pointers.Int.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Half_Type =>
Pointers.Half.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Single_Type =>
Pointers.Single.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Double_Type =>
Pointers.Double.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
-- Composite types
when Single_Vector_Type =>
Pointers.Single_Vector4.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Double_Vector_Type =>
Pointers.Double_Vector4.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Single_Matrix_Type =>
Pointers.Single_Matrix4.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Double_Matrix_Type =>
Pointers.Double_Matrix4.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Arrays_Command_Type =>
Pointers.Arrays_Command.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Elements_Command_Type =>
Pointers.Elements_Command.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
when Dispatch_Command_Type =>
Pointers.Dispatch_Command.Bind_Range
(Buffer_Target.all, Object.Buffer.Buffer, Index, Offset, Length);
end case;
end Bind;
overriding
procedure Bind (Object : Mapped_Buffer; Target : Buffer_Target) is
begin
case Target is
when Index =>
GL.Objects.Buffers.Element_Array_Buffer.Bind (Object.Buffer.Buffer);
when Dispatch_Indirect =>
GL.Objects.Buffers.Dispatch_Indirect_Buffer.Bind (Object.Buffer.Buffer);
when Draw_Indirect =>
GL.Objects.Buffers.Draw_Indirect_Buffer.Bind (Object.Buffer.Buffer);
when Parameter =>
GL.Objects.Buffers.Parameter_Buffer.Bind (Object.Buffer.Buffer);
when Pixel_Pack =>
GL.Objects.Buffers.Pixel_Pack_Buffer.Bind (Object.Buffer.Buffer);
when Pixel_Unpack =>
GL.Objects.Buffers.Pixel_Unpack_Buffer.Bind (Object.Buffer.Buffer);
when Query =>
GL.Objects.Buffers.Query_Buffer.Bind (Object.Buffer.Buffer);
end case;
end Bind;
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Data : UByte_Array;
Offset : Natural := 0) is
begin
Pointers.UByte.Set_Mapped_Data
(Object.Pointer_UByte, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : UShort_Array;
Offset : Natural := 0) is
begin
Pointers.UShort.Set_Mapped_Data
(Object.Pointer_UShort, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : UInt_Array;
Offset : Natural := 0) is
begin
Pointers.UInt.Set_Mapped_Data
(Object.Pointer_UInt, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Byte_Array;
Offset : Natural := 0) is
begin
Pointers.Byte.Set_Mapped_Data
(Object.Pointer_Byte, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Short_Array;
Offset : Natural := 0) is
begin
Pointers.Short.Set_Mapped_Data
(Object.Pointer_Short, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Int_Array;
Offset : Natural := 0) is
begin
Pointers.Int.Set_Mapped_Data
(Object.Pointer_Int, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Half_Array;
Offset : Natural := 0) is
begin
Pointers.Half.Set_Mapped_Data
(Object.Pointer_Half, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Single_Array;
Offset : Natural := 0) is
begin
Pointers.Single.Set_Mapped_Data
(Object.Pointer_Single, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Double_Array;
Offset : Natural := 0) is
begin
Pointers.Double.Set_Mapped_Data
(Object.Pointer_Double, Size (Object.Offset + Offset), Data);
end Write_Data;
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Singles.Vector4_Array;
Offset : Natural := 0) is
begin
Pointers.Single_Vector4.Set_Mapped_Data
(Object.Pointer_SV, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Singles.Matrix4_Array;
Offset : Natural := 0) is
begin
Pointers.Single_Matrix4.Set_Mapped_Data
(Object.Pointer_SM, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Doubles.Vector4_Array;
Offset : Natural := 0) is
begin
Pointers.Double_Vector4.Set_Mapped_Data
(Object.Pointer_DV, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Orka.Types.Doubles.Matrix4_Array;
Offset : Natural := 0) is
begin
Pointers.Double_Matrix4.Set_Mapped_Data
(Object.Pointer_DM, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Arrays_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Pointers.Arrays_Command.Set_Mapped_Data
(Object.Pointer_AC, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Elements_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Pointers.Elements_Command.Set_Mapped_Data
(Object.Pointer_EC, Size (Object.Offset + Offset), Data);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Data : Indirect.Dispatch_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Pointers.Dispatch_Command.Set_Mapped_Data
(Object.Pointer_DC, Size (Object.Offset + Offset), Data);
end Write_Data;
-----------------------------------------------------------------------------
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Singles.Vector4;
Offset : Natural) is
begin
Pointers.Single_Vector4.Set_Mapped_Data
(Object.Pointer_SV, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Singles.Matrix4;
Offset : Natural) is
begin
Pointers.Single_Matrix4.Set_Mapped_Data
(Object.Pointer_SM, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Doubles.Vector4;
Offset : Natural) is
begin
Pointers.Double_Vector4.Set_Mapped_Data
(Object.Pointer_DV, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Orka.Types.Doubles.Matrix4;
Offset : Natural) is
begin
Pointers.Double_Matrix4.Set_Mapped_Data
(Object.Pointer_DM, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Arrays_Indirect_Command;
Offset : Natural) is
begin
Pointers.Arrays_Command.Set_Mapped_Data
(Object.Pointer_AC, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Elements_Indirect_Command;
Offset : Natural) is
begin
Pointers.Elements_Command.Set_Mapped_Data
(Object.Pointer_EC, Size (Object.Offset + Offset), Value);
end Write_Data;
procedure Write_Data
(Object : Mapped_Buffer;
Value : Indirect.Dispatch_Indirect_Command;
Offset : Natural) is
begin
Pointers.Dispatch_Command.Set_Mapped_Data
(Object.Pointer_DC, Size (Object.Offset + Offset), Value);
end Write_Data;
-----------------------------------------------------------------------------
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UByte_Array;
Offset : Natural := 0) is
begin
Data := Pointers.UByte.Get_Mapped_Data
(Object.Pointer_UByte, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UShort_Array;
Offset : Natural := 0) is
begin
Data := Pointers.UShort.Get_Mapped_Data
(Object.Pointer_UShort, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out UInt_Array;
Offset : Natural := 0) is
begin
Data := Pointers.UInt.Get_Mapped_Data
(Object.Pointer_UInt, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Byte_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Byte.Get_Mapped_Data
(Object.Pointer_Byte, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Short_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Short.Get_Mapped_Data
(Object.Pointer_Short, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Int_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Int.Get_Mapped_Data
(Object.Pointer_Int, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Half_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Half.Get_Mapped_Data
(Object.Pointer_Half, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Single_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Single.Get_Mapped_Data
(Object.Pointer_Single, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Double_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Double.Get_Mapped_Data
(Object.Pointer_Double, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
-----------------------------------------------------------------------------
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Singles.Vector4_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Single_Vector4.Get_Mapped_Data
(Object.Pointer_SV, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Singles.Matrix4_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Single_Matrix4.Get_Mapped_Data
(Object.Pointer_SM, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Doubles.Vector4_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Double_Vector4.Get_Mapped_Data
(Object.Pointer_DV, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Orka.Types.Doubles.Matrix4_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Double_Matrix4.Get_Mapped_Data
(Object.Pointer_DM, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Arrays_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Arrays_Command.Get_Mapped_Data
(Object.Pointer_AC, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Elements_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Elements_Command.Get_Mapped_Data
(Object.Pointer_EC, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
procedure Read_Data
(Object : Mapped_Buffer;
Data : out Indirect.Dispatch_Indirect_Command_Array;
Offset : Natural := 0) is
begin
Data := Pointers.Dispatch_Command.Get_Mapped_Data
(Object.Pointer_DC, Size (Object.Offset + Offset), Data'Length);
end Read_Data;
end Orka.Rendering.Buffers.Mapped;
|
with Ada.Sequential_IO;
with Expressions; use Expressions;
procedure RandomArt is
type Byte is mod 256;
for Byte'Size use 8;
package Byte_IO is new Ada.Sequential_IO(Byte);
Scale : constant := 150;
Size : constant := 2*Scale + 1;
procedure GreyScale(node : not null Expression_Node_Access) is
file : Byte_IO.File_Type;
filename : constant String := "test.pgm";
header : constant String := "P5 301 301 255";
begin
Byte_IO.Create(File => file, Name => filename);
for i in header'Range loop
Byte_IO.Write(file, Byte(Character'Pos(header(i))));
end loop;
Byte_IO.Write(file, 10); -- newline
for yi in -Scale .. Scale loop
for xi in -Scale .. Scale loop
declare
x : constant Expression_Value := Float(xi) / Float(Scale);
y : constant Expression_Value := Float(yi) / Float(Scale);
intensity : constant Byte := Byte(127.5 + 127.5*Evaluate_Expression(node, x, y));
begin
Byte_IO.Write(file, intensity);
end;
end loop;
end loop;
end GreyScale;
gen : Rand.Generator;
root : Expression_Node_Access;
begin
Rand.reset(gen);
root := Build_Expression_tree(10, gen);
GreyScale(root);
end RandomArt;
|
--
-- 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.Strings.Unbounded;
with Setup;
with Types;
package Commands is
use Ada.Strings.Unbounded;
function "-" (Source : String) return Unbounded_String
renames To_Unbounded_String;
type Help_Line is
record
Command : Unbounded_String;
Comment : Unbounded_String;
end record;
Help_Lines : constant array (Positive range <>) of Help_Line :=
((-"help", -"Print this help text"),
(-"quit", -"Quit program"),
(-"ls", -"Show current list"),
(-"view", -"Show current list"),
(-"top", -"Show top level jobs"),
(-"cd", -"Show top level jobs"),
(-"set JOB", -"Set JOB to current"),
(-"show", -"Show jobs details"),
(-"cat", -"Show jobs details"),
(-"add job TITLE", -"Add job to current list"),
(-"add list NAME", -"Add list to database"),
(-"split serial JOB COUNT",
-"Split job into count serial jobs"),
(-"split parallel JOB COUNT ",
-"Split job into count parallel jobs"),
(-"text TEXT",
-"Add free text to current job"),
(-"move LIST",
-"Move current job to other list"),
(-"trans LIST",
-"Transfer current job to other list"),
(-"event KIND", -"Add event to current job"),
(-"export", -"Export jobs to csv file ("
& Setup.Program_Name & ".csv)"));
procedure Create_Job (Job : in Types.Job_Id;
Title : in String;
Parent : in Types.Job_Id);
procedure Set_Current_Job (Job : in Types.Job_Id);
end Commands;
|
with Ada.Text_IO;
with Ada.Directories;
with Ada.Command_Line;
with Templates_Parser;
with CLIC.TTY;
with Filesystem;
with Commands;
with GNAT.Strings;
with Ada.Characters.Conversions;
with Generator;
with Globals;
package body Init_Project is
package IO renames Ada.Text_IO;
package TT renames CLIC.TTY;
use Ada.Characters.Conversions;
use Ada.Directories;
use GNAT.Strings;
use Generator.aString;
Errors : constant Boolean := False;
Filter : constant Filter_Type :=
(Ordinary_File => True, Special_File => False, Directory => True);
procedure Init (Path : String; Blueprint : String; ToDo : Action) is
Blueprint_Folder : constant String := Get_Blueprint_Folder;
App_Blueprint_Folder : constant String :=
Compose (Blueprint_Folder, "site");
Blueprint_Path : XString;
Name : constant String := Simple_Name (Path);
begin
if Blueprint /= "" then
Blueprint_Path := To_XString (
To_Wide_Wide_String (Compose (App_Blueprint_Folder, Blueprint)));
else
Blueprint_Path := To_XString (
To_Wide_Wide_String (Compose (App_Blueprint_Folder,
Globals.Blueprint_Default)));
end if;
Templates_Parser.Insert
(Commands.Translations, Templates_Parser.Assoc ("SITENAME", Name));
if Exists (To_String (To_String (Blueprint_Path)))
then
IO.Put_Line
(TT.Italic ("Creating a new project") & " " & TT.Bold (Path) & ":");
Iterate (To_String (To_String (Blueprint_Path)), Path, ToDo);
IO.New_Line;
if Errors then
IO.Put_Line
(TT.Warn ("Created site") & " " & TT.Bold
(Name) & " " & "with errors.");
else
IO.Put_Line (TT.Success ("Successfully created site")
& " " & TT.Warn (TT.Bold (Name)));
end if;
IO.New_Line;
IO.Put_Line
(TT.Info
(TT.Description ("Build your site using") & " " &
TT.Terminal ("wg publish")));
IO.Put_Line
(TT.Info
(TT.Description ("Add components and other items using") & " " &
TT.Terminal ("wg generate")));
else
IO.Put_Line (TT.Error ("Blueprint not found: " &
To_String (To_String (Blueprint_Path))));
end if;
end Init;
end Init_Project; |
Pragma Ada_2012;
----------------------------------
-- Miscellaneous Dependencies --
----------------------------------
with
GNAT.CRC32,
Ada.Characters.Latin_1,
Ada.Containers.Indefinite_Vectors,
Ada.Strings.Fixed,
Ada.Text_IO;
--------------------------------
-- Risi_Script Dependencies --
--------------------------------
with
-- Risi_Script.Script,
Risi_Script.Types.Patterns,
Risi_Script.Types.Identifier.Scope,
Risi_Script.Types.Implementation;--,
-- Risi_Script.Interpreter;
------------------
-- Visibility --
------------------
use
Ada.Characters.Latin_1;
procedure Risi is
begin
-- -- REPL:
-- -- loop
-- -- declare
-- -- use Ada.Strings.Fixed, Ada.Strings, Ada.Text_IO;
-- -- Input : String:= Trim(Get_Line, Side => Both);
-- -- begin
-- -- Put_Line( '[' & Input & ']' );
-- -- end;
-- -- end loop REPL;
--
-- -- declare
-- -- package ET is new Ada.Text_IO.Enumeration_IO( Risi_Script.Types.Enumeration );
-- -- package IT is new Ada.Text_IO.Enumeration_IO( Risi_Script.Types.Indicator );
-- -- Use ET, IT, Ada.Text_IO;
-- -- Use Type Risi_Script.Types.Enumeration, Risi_Script.Types.Indicator;
-- -- begin
-- -- for Item in Risi_Script.Types.Enumeration loop
-- -- Put( +Item );
-- -- Put( ASCII.HT );
-- -- Put( Item );
-- -- New_Line;
-- -- end loop;
-- -- end;
-- declare
-- Use Risi_Script.Script;
-- File_Name : Constant String:= "Test_2.ris";
--
-- Function Get_File(Name : String:= File_Name) return Ada.Text_IO.File_Type is
-- begin
-- Return Result : Ada.Text_IO.File_Type do
-- Ada.Text_IO.Open( File => Result,
-- Mode => Ada.Text_IO.In_File,
-- Name => Name
-- );
-- end return;
-- end Get_File;
--
--
-- Data_File : Ada.Text_IO.File_Type:= Get_File( File_Name );
-- Script_Object : Script:= Load( Data_File );
-- X : String_Array renames Script_Object.Strings;
-- V : Risi_Script.Interpreter.VM:= Risi_Script.Interpreter.Init;
-- begin
-- Ada.Text_IO.Put_Line( '['& "Count:"&Natural'Image(X'Length) &']' );
-- for Datum of X loop
-- Ada.Text_IO.Put_Line( Datum.All );
-- end loop;
--
-- Ada.Text_IO.Put_Line( "Checksum:["& Script_Object.CRC &"]" );
--
-- end;
For Sigil in Risi_Script.Types.Enumeration loop
declare
Use Risi_Script.Types, Ada.Text_IO;
Type_Name : Constant String := Enumeration'Image( Sigil );
Sigil_Img : Constant Character:= +(+Sigil);
begin
Put_Line( Type_Name & ' ' & Sigil_Img );
end;
end loop;
declare
Package ID renames Risi_Script.Types.Identifier;
Use ID.Scope, Ada.Text_IO;
Temp : Scope;
Ident : constant ID.Identifier:= "a_a";
begin
pragma Warnings(Off);
Temp.Append( "Temporary" );
Temp.Append( "Scope" );
Temp.Append( "Test" );
pragma Warnings(On);
Put_Line( "Qualified Path: [" & Image(Temp) & ']' );
end;
declare
Package Patterns renames Risi_Script.Types.Patterns;
Use Patterns, Ada.Text_IO, Risi_Script.Types,
Risi_Script.Types.Implementation;
A : Representation:= Create( RT_Fixed );
B : Representation:= Create( RT_Boolean );
C : Representation:= Create( RT_String );
Temp_1 : Patterns.Half_Pattern:= Create((A,B,C));
Temp_2 : Indicator_String:= "`?$$";
begin
Put_Line( "Pattern: [" & (+Temp_1) & ']' );
Put_Line( "Sigils: [" & (+Temp_2) & ']' );
Put_Line( "Match: " & Match(Temp_1, Temp_2)'Img );
end;
Ada.Text_IO.Put_Line( Ada.Characters.Latin_1.LC_German_Sharp_S & "" );
end Risi;
|
package generic_procedure_renaming_declaration is
generic
procedure test(X : Integer);
generic procedure newtest renames test;
end generic_procedure_renaming_declaration;
|
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with GL.Attributes;
with GL.Buffers;
with GL.Culling;
with GL.Immediate;
with GL.Objects.Buffers;
with GL.Objects.Programs;
with GL.Objects.Vertex_Arrays;
with GL.Objects.Shaders.Lists;
with GL.Raster;
with GL.Rasterization;
with GL.Text;
with GL.Toggles;
with GL.Types; use GL.Types;
with GL.Types.Colors;
with GL.Uniforms;
with Glfw;
with Glfw.Input;
with Glfw.Input.Keys;
with Glfw.Input.Mouse;
with GL.Window;
with Glfw.Windows.Context;
with Glfw.Windows.Hints;
with Maths;
with Program_Loader;
with Utilities;
with C3GA;
with C3GA_Draw;
with GA_Draw;
with GA_Utilities;
with GL_Util;
with E2GA;
with E2GA_Draw;
with E3GA;
with E3GA_Utilities;
with GA_Maths;
with Multivectors;
with Silo;
with Text_Management;
with Graphic_Data;
procedure Main_Loop (Main_Window : in out Glfw.Windows.Window) is
subtype tVec4f is Singles.Vector4;
Black : constant Colors.Color := (0.0, 0.0, 0.0, 1.0);
Red : constant Colors.Color := (1.0, 0.0, 0.0, 1.0);
Green : constant Colors.Color := (0.0, 1.0, 0.0, 1.0);
Blue : constant Colors.Color := (0.0, 0.0, 1.0, 1.0);
Yellow : constant Colors.Color := (1.0, 1.0, 0.0, 1.0);
White : constant Colors.Color := (1.0, 1.0, 1.0, 0.0);
Key_Pressed : boolean := False;
Prev_Mouse_Pos : E3GA.Vector_Coords_3D := (0.0, 0.0, 0.0);
Rotate_Model : Boolean := False;
Rotate_Model_Out_Of_Plane : boolean := False;
Init_Model_Needed : Boolean := True;
Model_Name : Ada.Strings.Unbounded.Unbounded_String :=
Ada.Strings.Unbounded.To_Unbounded_String ("Sphere");
Model_Rotor : Multivectors.Rotor;
Polygons_2D : Multivectors.Vector;
Vertices_2D : Multivectors.Vector;
--
Prev_Statistics_Model_Name : Ada.Strings.Unbounded.Unbounded_String :=
Ada.Strings.Unbounded.To_Unbounded_String ("");
-- -------------------------------------------------------------------------
procedure Display (Window : in out Glfw.Windows.Window;
Render_Program : GL.Objects.Programs.Program) is
use GL.Objects.Buffers;
use GL.Types.Colors;
use GL.Types.Singles; -- for matrix multiplication
use Maths.Single_Math_Functions;
use E2GA;
use GA_Maths;
use GA_Maths.Float_Functions;
Window_Width : Glfw.Size;
Window_Height : Glfw.Size;
Pick : GL_Util.GL_Pick;
Vertex_Buffer : GL.Objects.Buffers.Buffer;
Vertex_Array_Object : GL.Objects.Vertex_Arrays.Vertex_Array_Object;
BV : Multivectors.Bivector;
begin
Window.Get_Framebuffer_Size (Window_Width, Window_Height);
GL.Window.Set_Viewport (0, 0, GL.Types.Int (Window_Width),
GL.Types.Int (Window_Height));
Utilities.Clear_Background_Colour_And_Depth (White);
GL.Objects.Programs.Use_Program (Render_Program);
Vertex_Buffer.Initialize_Id;
Vertex_Array_Object.Initialize_Id;
Vertex_Array_Object.Bind;
Array_Buffer.Bind (Vertex_Buffer);
if Init_Model_Needed then
Graphic_Data.Get_GLUT_Model_2D (Render_Program, Model_Name, Model_Rotor);
Init_Model_Needed := False;
end if;
-- DONT cull faces (we will do this ourselves!)
GL.Toggles.Disable (GL.Toggles.Cull_Face);
-- fill all polygons (otherwise they get turned into LINES
GL.Rasterization.Set_Polygon_Mode (GL.Rasterization.Fill);
exception
when anError : others =>
Put_Line ("An exception occurred in Main_Loop.Display.");
raise;
end Display;
-- ------------------------------------------------------------------------
procedure Setup_Graphic (Window : in out Glfw.Windows.Window;
Render_Program : out GL.Objects.Programs.Program) is
use Glfw.Input;
use GL.Objects.Buffers;
use GL.Objects.Shaders;
use Program_Loader;
begin
-- Line width > 1.0 fails. It may be clamped to an implementation-dependent maximum.
-- Call glGet with GL_ALIASED_LINE_WIDTH_RANGE to determine the
-- maximum width.
GL.Rasterization.Set_Line_Width (1.0);
GA_Draw.Set_Point_Size (0.9);
-- GA_Draw.Set_Point_Size (0.005);
Model_Rotor := Multivectors.New_Rotor;
Render_Program := Program_Loader.Program_From
((Src ("src/shaders/vertex_shader.glsl", Vertex_Shader),
Src ("src/shaders/fragment_shader.glsl", Fragment_Shader)));
exception
when anError : others =>
Put_Line ("An exception occurred in Main_Loop.Setup_Graphic.");
raise;
end Setup_Graphic;
-- ----------------------------------------------------------------------------
use Glfw.Input;
Render_Program : GL.Objects.Programs.Program;
Running : Boolean := True;
Key_Now : Button_State;
begin
Utilities.Clear_Background_Colour_And_Depth (White);
Main_Window.Set_Input_Toggle (Sticky_Keys, True);
Glfw.Input.Poll_Events;
Setup_Graphic (Main_Window, Render_Program);
while Running loop
-- Swap_Buffers first to display background colour on start up.
Glfw.Windows.Context.Swap_Buffers (Main_Window'Access);
Display (Main_Window, Render_Program);
Glfw.Input.Poll_Events;
Key_Now := Main_Window.Key_State (Glfw.Input.Keys.Space);
if not Key_Pressed and Key_Now = Glfw.Input.Pressed then
Key_Pressed := True;
else
Key_Pressed := Key_Now = Glfw.Input.Pressed;
end if;
Running := Running and then
not (Main_Window.Key_State (Glfw.Input.Keys.Escape) = Glfw.Input.Pressed);
Running := Running and then not Main_Window.Should_Close;
end loop;
end Main_Loop;
|
-- 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 Tk.Winfo.Test_Data.Tests is
type Test is new GNATtest_Generated.GNATtest_Standard.Tk.Winfo.Test_Data
.Test with
null record;
procedure Test_Atom_8a3ab9_cb4226(Gnattest_T: in out Test);
-- tk-winfo.ads:163:4:Atom:Test_Winfo_Atom
procedure Test_Atom_Name_ffa709_5ba3e0(Gnattest_T: in out Test);
-- tk-winfo.ads:193:4:Atom_Name:Test_Winfo_Atom_Name
procedure Test_Cells_13d387_f11487(Gnattest_T: in out Test);
-- tk-winfo.ads:216:4:Cells:Test_Winfo_Cells
procedure Test_Children_87e2ce_9a2e0c(Gnattest_T: in out Test);
-- tk-winfo.ads:237:4:Children:Test_Winfo_Children
procedure Test_Class_1df3af_850207(Gnattest_T: in out Test);
-- tk-winfo.ads:257:4:Class:Test_Winfo_Class
procedure Test_Color_Map_Full_f60f4e_3de321(Gnattest_T: in out Test);
-- tk-winfo.ads:282:4:Color_Map_Full:Test_Winfo_Color_Map_Full
procedure Test_Containing_916a42_e3dd46(Gnattest_T: in out Test);
-- tk-winfo.ads:313:4:Containing:Test_Winfo_Containing
procedure Test_Colors_Depth_27cc4a_1900bc(Gnattest_T: in out Test);
-- tk-winfo.ads:339:4:Colors_Depth:Test_Winfo_Depth
procedure Test_Exists_a87cb0_7a630c(Gnattest_T: in out Test);
-- tk-winfo.ads:361:4:Exists:Test_Winfo_Exists
procedure Test_Floating_Point_Pixels_e16a1c_9b10a0(Gnattest_T: in out Test);
-- tk-winfo.ads:389:4:Floating_Point_Pixels:Test_Winfo_Floating_Point_Pixels
procedure Test_Geometry_74d873_9e4b51(Gnattest_T: in out Test);
-- tk-winfo.ads:411:4:Geometry:Test_Winfo_Geometry
procedure Test_Height_b50988_c88298(Gnattest_T: in out Test);
-- tk-winfo.ads:434:4:Height:Test_Winfo_Height
procedure Test_Id_e14e13_d4cbde(Gnattest_T: in out Test);
-- tk-winfo.ads:455:4:Id:Test_Winfo_Id
procedure Test_Interpreters_aa8c94_a1d488(Gnattest_T: in out Test);
-- tk-winfo.ads:482:4:Interpreters:Test_Winfo_Interpreters
procedure Test_Is_Mapped_086085_173a11(Gnattest_T: in out Test);
-- tk-winfo.ads:503:4:Is_Mapped:Test_Winfo_Is_Mapped
procedure Test_Manager_0c5ddb_cd7633(Gnattest_T: in out Test);
-- tk-winfo.ads:529:4:Manager:Test_Winfo_Manager
procedure Test_Name_0da7b9_ba0234(Gnattest_T: in out Test);
-- tk-winfo.ads:550:4:Name:Test_Winfo_Name
procedure Test_Parent_252286_c941bb(Gnattest_T: in out Test);
-- tk-winfo.ads:571:4:Parent:Test_Winfo_Parent
procedure Test_Path_Name_c74192_a4034c(Gnattest_T: in out Test);
-- tk-winfo.ads:602:4:Path_Name:Test_Winfo_Path_Name
procedure Test_Pixels_60cc8c_ac6879(Gnattest_T: in out Test);
-- tk-winfo.ads:627:4:Pixels:Test_Winfo_Pixels
procedure Test_Pointer_X_54c935_e5ce32(Gnattest_T: in out Test);
-- tk-winfo.ads:650:4:Pointer_X:Test_Winfo_Pointer_X
procedure Test_Pointer_X_Y_e6a4c1_ad38ab(Gnattest_T: in out Test);
-- tk-winfo.ads:674:4:Pointer_X_Y:Test_Winfo_Pointer_X_Y
procedure Test_Pointer_Y_37e90e_63e9b1(Gnattest_T: in out Test);
-- tk-winfo.ads:697:4:Pointer_Y:Test_Winfo_Pointer_Y
procedure Test_Requested_Height_dc94e9_a6c984(Gnattest_T: in out Test);
-- tk-winfo.ads:719:4:Requested_Height:Test_Winfo_Requested_Height
procedure Test_Requested_Width_701192_2835fe(Gnattest_T: in out Test);
-- tk-winfo.ads:741:4:Requested_Width:Test_Winfo_Requested_Width
procedure Test_Rgb_b213e0_a478a9(Gnattest_T: in out Test);
-- tk-winfo.ads:762:4:Rgb:Test_Winfo_Rgb
procedure Test_Root_X_a9154b_0f2cf6(Gnattest_T: in out Test);
-- tk-winfo.ads:785:4:Root_X:Test_Winfo_Root_X
procedure Test_Root_Y_b2f35d_2266c1(Gnattest_T: in out Test);
-- tk-winfo.ads:808:4:Root_Y:Test_Winfo_Root_Y
procedure Test_Screen_6fc5d3_32e1e9(Gnattest_T: in out Test);
-- tk-winfo.ads:828:4:Screen:Test_Winfo_Screen
procedure Test_Screen_Cells_37d289_147863(Gnattest_T: in out Test);
-- tk-winfo.ads:857:4:Screen_Cells:Test_Winfo_Screen_Cells
procedure Test_Screen_Depth_60dc8d_a34485(Gnattest_T: in out Test);
-- tk-winfo.ads:880:4:Screen_Depth:Test_Winfo_Screen_Depth
procedure Test_Screen_Height_0d8e96_07a2f4(Gnattest_T: in out Test);
-- tk-winfo.ads:903:4:Screen_Height:Test_Winfo_Screen_Height
procedure Test_Screen_Milimeters_Height_64f6ac_98364e
(Gnattest_T: in out Test);
-- tk-winfo.ads:926:4:Screen_Milimeters_Height:Test_Winfo_Screen_Milimeters_Height
procedure Test_Screen_Milimeters_Width_aa8ee0_a6bf9c
(Gnattest_T: in out Test);
-- tk-winfo.ads:950:4:Screen_Milimeters_Width:Test_Winfo_Screen_Milimeters_Width
procedure Test_Screen_Visual_fa94d0_1d67c8(Gnattest_T: in out Test);
-- tk-winfo.ads:975:4:Screen_Visual:Test_Winfo_Screen_Visual
procedure Test_Screen_Width_8321ec_7e95f9(Gnattest_T: in out Test);
-- tk-winfo.ads:1003:4:Screen_Width:Test_Winfo_Screen_Width
procedure Test_Server_e424b7_78bc02(Gnattest_T: in out Test);
-- tk-winfo.ads:1023:4:Server:Test_Winfo_Server
procedure Test_Toplevel_5fee9d_a31831(Gnattest_T: in out Test);
-- tk-winfo.ads:1048:4:Toplevel:Test_Winfo_Toplevel
procedure Test_Viewable_7e17e3_8c7bbb(Gnattest_T: in out Test);
-- tk-winfo.ads:1073:4:Viewable:Test_Winfo_Viewable
procedure Test_Visual_Id_bfbe6b_3ec6f0(Gnattest_T: in out Test);
-- tk-winfo.ads:1097:4:Visual_Id:Test_Winfo_Visual_Id
procedure Test_Visuals_Available_a6aadc_de5564(Gnattest_T: in out Test);
-- tk-winfo.ads:1121:4:Visuals_Available:Test_Winfo_Visuals_Available
procedure Test_Virtual_Root_Height_c10eb6_0cf3d9(Gnattest_T: in out Test);
-- tk-winfo.ads:1147:4:Virtual_Root_Height:Test_Winfo_Virtual_Root_Height
procedure Test_Virtual_Root_Width_34af8b_13e28c(Gnattest_T: in out Test);
-- tk-winfo.ads:1171:4:Virtual_Root_Width:Test_Winfo_Virtual_Root_Width
procedure Test_Virtual_Root_X_6cfaed_207bc9(Gnattest_T: in out Test);
-- tk-winfo.ads:1196:4:Virtual_Root_X:Test_Winfo_Virtual_Root_X
procedure Test_Virtual_Root_Y_6a3724_e36110(Gnattest_T: in out Test);
-- tk-winfo.ads:1221:4:Virtual_Root_Y:Test_Winfo_Virtual_Root_Y
procedure Test_Width_fa2186_53745f(Gnattest_T: in out Test);
-- tk-winfo.ads:1243:4:Width:Test_Winfo_Width
procedure Test_X_91dd91_776ecc(Gnattest_T: in out Test);
-- tk-winfo.ads:1266:4:X:Test_Winfo_X
procedure Test_Y_07f0ff_4d9e51(Gnattest_T: in out Test);
-- tk-winfo.ads:1289:4:Y:Test_Winfo_Y
end Tk.Winfo.Test_Data.Tests;
-- end read only
|
package body ACO.Utils.DS.Generic_Queue is
function Is_Full (This : Queue) return Boolean is
(This.Count >= This.Max_Nof_Items);
function Is_Empty (This : Queue) return Boolean is
(This.Count = 0);
function Length (This : Queue) return Natural is
(This.Count);
function Free_Slots (This : Queue) return Natural is
(This.Max_Nof_Items - This.Count);
procedure Inc
(This : in Queue;
I : in out Index)
is
begin
if I >= This.Items'Last then
I := This.Items'First;
else
I := Index'Succ (I);
end if;
end Inc;
procedure Put
(This : in out Queue;
Item : in Item_Type)
is
begin
This.Items (This.Next) := Item;
This.Inc (This.Next);
This.Count := This.Count + 1;
end Put;
procedure Put
(This : in out Queue;
Items : in Item_Array)
is
begin
for Item of Items loop
This.Put (Item);
end loop;
end Put;
procedure Get
(This : in out Queue;
Item : out Item_Type)
is
begin
Item := This.Items (This.Old);
This.Inc (This.Old);
This.Count := This.Count - 1;
end Get;
procedure Get
(This : in out Queue;
Items : out Item_Array)
is
begin
for Item of Items loop
This.Get (Item);
end loop;
end Get;
procedure Flush
(This : in out Queue)
is
begin
This.Count := 0;
This.Old := This.Next;
end Flush;
function Peek (This : Queue) return Item_Type is
(This.Items (This.Old));
function Peek (This : Queue) return Item_Array
is
Items : Item_Array (Index'First .. Index'First + This.Count - 1);
I : Index := This.Old;
begin
for Item of Items loop
Item := This.Items (I);
This.Inc (I);
end loop;
return Items;
end Peek;
end ACO.Utils.DS.Generic_Queue;
|
-- { dg-do run }
procedure Array9 is
V1 : String(1..10) := "1234567890";
V2 : String(1..-1) := "";
procedure Compare (S : String) is
begin
if S'Size /= 8*S'Length then
raise Program_Error;
end if;
end;
begin
Compare ("");
Compare ("1234");
Compare (V1);
Compare (V2);
end;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
private with Ada.Containers.Hashed_Maps;
with Yaml.Events.Store;
package Yaml.Events.Context is
type Reference is tagged private;
type Cursor is private;
type Local_Scope_Cursor is private;
type Generated_Store_Cursor is private;
type Symbol_Cursor is private;
type Location_Type is (Generated, Local, Document, Stream, External, None);
function Create (External : Store.Reference := Store.New_Store)
return Reference;
function External_Store (Object : Reference) return Store.Accessor;
function Stream_Store (Object : Reference) return Store.Accessor;
function Document_Store (Object : Reference) return Store.Accessor;
function Transformed_Store (Object : Reference) return Store.Accessor;
function Local_Store (Object : Reference; Position : Local_Scope_Cursor)
return Store.Accessor;
function Local_Store_Ref (Object : Reference; Position : Local_Scope_Cursor)
return Store.Optional_Reference;
function Generated_Store (Object : Reference;
Position : Generated_Store_Cursor)
return Store.Accessor;
function Generated_Store_Ref (Object : Reference;
Position : Generated_Store_Cursor)
return Store.Optional_Reference;
function Position (Object : Reference; Alias : Text.Reference) return Cursor;
function Location (Position : Cursor) return Location_Type;
procedure Create_Local_Store (Object : Reference;
Position : out Local_Scope_Cursor);
procedure Create_Local_Symbol_Scope (Object : Reference;
Position : out Local_Scope_Cursor);
procedure Release_Local_Store (Object : Reference;
Position : Local_Scope_Cursor);
procedure Create_Generated_Store (Object : Reference;
Position : out Generated_Store_Cursor);
procedure Release_Generated_Store (Object : Reference;
Position : Generated_Store_Cursor);
procedure Create_Symbol (Object : Reference;
Scope : Local_Scope_Cursor;
Name : Text.Reference;
Position : out Symbol_Cursor);
procedure Update_Symbol (Object : Reference;
Scope : Local_Scope_Cursor;
Position : Symbol_Cursor;
New_Value : Cursor);
function Symbol_Name (Position : Symbol_Cursor) return Text.Reference;
No_Element : constant Cursor;
No_Local_Store : constant Local_Scope_Cursor;
function Is_Anchored (Pos : Cursor) return Boolean;
function Retrieve (Pos : Cursor) return Store.Stream_Reference
with Pre => Pos /= No_Element;
function First (Pos : Cursor) return Event with Pre => Pos /= No_Element;
function Exists_In_Ouput (Position : Cursor) return Boolean;
procedure Set_Exists_In_Output (Position : in out Cursor);
procedure Get_Store_And_Cursor
(Position : Cursor; Target : out Store.Optional_Reference;
Element_Position : out Events.Store.Element_Cursor);
function To_Cursor (Object : Reference;
Parent : Store.Optional_Reference;
Element_Position : Events.Store.Element_Cursor)
return Cursor;
private
type Cursor is record
Target : Store.Optional_Reference;
Anchored_Position : Events.Store.Anchor_Cursor;
Element_Position : Events.Store.Element_Cursor;
Target_Location : Location_Type;
end record;
package Symbol_Tables is new Ada.Containers.Hashed_Maps
(Text.Reference, Cursor, Text.Hash, Text."=");
type Symbol_Table_Pointer is access Symbol_Tables.Map;
type Local_Scope is record
Events : Store.Optional_Reference;
Symbols : Symbol_Table_Pointer;
end record;
type Scope_Array is array (Positive range <>) of Local_Scope;
type Scope_Array_Pointer is access Scope_Array;
type Data_Array is array (Positive range <>) of Store.Optional_Reference;
type Data_Array_Pointer is access Data_Array;
type Instance is limited new Refcount_Base with record
Generated_Data : Data_Array_Pointer;
Document_Data, Stream_Data, External_Data, Transformed_Data :
Store.Reference;
Local_Scopes : Scope_Array_Pointer := null;
Local_Scope_Count, Generated_Data_Count : Natural := 0;
end record;
type Instance_Access is access all Instance;
overriding procedure Finalize (Object : in out Instance);
type Local_Scope_Cursor is new Natural;
type Generated_Store_Cursor is new Natural;
type Symbol_Cursor is new Symbol_Tables.Cursor;
type Reference is new Ada.Finalization.Controlled with record
Data : not null Instance_Access := raise Constraint_Error with "uninitialized context instance!";
end record;
overriding procedure Adjust (Object : in out Reference);
overriding procedure Finalize (Object : in out Reference);
No_Element : constant Cursor :=
(Target => Store.Null_Reference,
Element_Position => Events.Store.No_Element,
Anchored_Position => Events.Store.No_Anchor,
Target_Location => None);
No_Local_Store : constant Local_Scope_Cursor := 0;
end Yaml.Events.Context;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . F O R M A L _ O R D E R E D _ S E T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2010-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
------------------------------------------------------------------------------
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations;
pragma Elaborate_All
(Ada.Containers.Red_Black_Trees.Generic_Bounded_Operations);
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys;
pragma Elaborate_All (Ada.Containers.Red_Black_Trees.Generic_Bounded_Keys);
with Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations;
pragma Elaborate_All
(Ada.Containers.Red_Black_Trees.Generic_Bounded_Set_Operations);
with System; use type System.Address;
package body Ada.Containers.Formal_Ordered_Sets with
SPARK_Mode => Off
is
------------------------------
-- Access to Fields of Node --
------------------------------
-- These subprograms provide functional notation for access to fields
-- of a node, and procedural notation for modifiying these fields.
function Color (Node : Node_Type) return Red_Black_Trees.Color_Type;
pragma Inline (Color);
function Left_Son (Node : Node_Type) return Count_Type;
pragma Inline (Left_Son);
function Parent (Node : Node_Type) return Count_Type;
pragma Inline (Parent);
function Right_Son (Node : Node_Type) return Count_Type;
pragma Inline (Right_Son);
procedure Set_Color
(Node : in out Node_Type;
Color : Red_Black_Trees.Color_Type);
pragma Inline (Set_Color);
procedure Set_Left (Node : in out Node_Type; Left : Count_Type);
pragma Inline (Set_Left);
procedure Set_Right (Node : in out Node_Type; Right : Count_Type);
pragma Inline (Set_Right);
procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type);
pragma Inline (Set_Parent);
-----------------------
-- Local Subprograms --
-----------------------
-- Comments needed???
generic
with procedure Set_Element (Node : in out Node_Type);
procedure Generic_Allocate
(Tree : in out Tree_Types.Tree_Type'Class;
Node : out Count_Type);
procedure Free (Tree : in out Set; X : Count_Type);
procedure Insert_Sans_Hint
(Container : in out Set;
New_Item : Element_Type;
Node : out Count_Type;
Inserted : out Boolean);
procedure Insert_With_Hint
(Dst_Set : in out Set;
Dst_Hint : Count_Type;
Src_Node : Node_Type;
Dst_Node : out Count_Type);
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Greater_Element_Node);
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Less_Element_Node);
function Is_Less_Node_Node (L, R : Node_Type) return Boolean;
pragma Inline (Is_Less_Node_Node);
procedure Replace_Element
(Tree : in out Set;
Node : Count_Type;
Item : Element_Type);
--------------------------
-- Local Instantiations --
--------------------------
package Tree_Operations is
new Red_Black_Trees.Generic_Bounded_Operations
(Tree_Types,
Left => Left_Son,
Right => Right_Son);
use Tree_Operations;
package Element_Keys is
new Red_Black_Trees.Generic_Bounded_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Element_Type,
Is_Less_Key_Node => Is_Less_Element_Node,
Is_Greater_Key_Node => Is_Greater_Element_Node);
package Set_Ops is
new Red_Black_Trees.Generic_Bounded_Set_Operations
(Tree_Operations => Tree_Operations,
Set_Type => Set,
Assign => Assign,
Insert_With_Hint => Insert_With_Hint,
Is_Less => Is_Less_Node_Node);
---------
-- "=" --
---------
function "=" (Left, Right : Set) return Boolean is
Lst : Count_Type;
Node : Count_Type;
ENode : Count_Type;
begin
if Length (Left) /= Length (Right) then
return False;
end if;
if Is_Empty (Left) then
return True;
end if;
Lst := Next (Left, Last (Left).Node);
Node := First (Left).Node;
while Node /= Lst loop
ENode := Find (Right, Left.Nodes (Node).Element).Node;
if ENode = 0
or else Left.Nodes (Node).Element /= Right.Nodes (ENode).Element
then
return False;
end if;
Node := Next (Left, Node);
end loop;
return True;
end "=";
------------
-- Assign --
------------
procedure Assign (Target : in out Set; Source : Set) is
procedure Append_Element (Source_Node : Count_Type);
procedure Append_Elements is
new Tree_Operations.Generic_Iteration (Append_Element);
--------------------
-- Append_Element --
--------------------
procedure Append_Element (Source_Node : Count_Type) is
SN : Node_Type renames Source.Nodes (Source_Node);
procedure Set_Element (Node : in out Node_Type);
pragma Inline (Set_Element);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Unconditional_Insert_Sans_Hint is
new Element_Keys.Generic_Unconditional_Insert (Insert_Post);
procedure Unconditional_Insert_Avec_Hint is
new Element_Keys.Generic_Unconditional_Insert_With_Hint
(Insert_Post,
Unconditional_Insert_Sans_Hint);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Target, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := SN.Element;
end Set_Element;
-- Local variables
Target_Node : Count_Type;
-- Start of processing for Append_Element
begin
Unconditional_Insert_Avec_Hint
(Tree => Target,
Hint => 0,
Key => SN.Element,
Node => Target_Node);
end Append_Element;
-- Start of processing for Assign
begin
if Target'Address = Source'Address then
return;
end if;
if Target.Capacity < Source.Length then
raise Constraint_Error
with "Target capacity is less than Source length";
end if;
Tree_Operations.Clear_Tree (Target);
Append_Elements (Source);
end Assign;
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Item : Element_Type) return Cursor is
Node : constant Count_Type := Element_Keys.Ceiling (Container, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Ceiling;
-----------
-- Clear --
-----------
procedure Clear (Container : in out Set) is
begin
Tree_Operations.Clear_Tree (Container);
end Clear;
-----------
-- Color --
-----------
function Color (Node : Node_Type) return Red_Black_Trees.Color_Type is
begin
return Node.Color;
end Color;
--------------
-- Contains --
--------------
function Contains
(Container : Set;
Item : Element_Type) return Boolean
is
begin
return Find (Container, Item) /= No_Element;
end Contains;
----------
-- Copy --
----------
function Copy (Source : Set; Capacity : Count_Type := 0) return Set is
Node : Count_Type;
N : Count_Type;
Target : Set (Count_Type'Max (Source.Capacity, Capacity));
begin
if 0 < Capacity and then Capacity < Source.Capacity then
raise Capacity_Error;
end if;
if Length (Source) > 0 then
Target.Length := Source.Length;
Target.Root := Source.Root;
Target.First := Source.First;
Target.Last := Source.Last;
Target.Free := Source.Free;
Node := 1;
while Node <= Source.Capacity loop
Target.Nodes (Node).Element :=
Source.Nodes (Node).Element;
Target.Nodes (Node).Parent :=
Source.Nodes (Node).Parent;
Target.Nodes (Node).Left :=
Source.Nodes (Node).Left;
Target.Nodes (Node).Right :=
Source.Nodes (Node).Right;
Target.Nodes (Node).Color :=
Source.Nodes (Node).Color;
Target.Nodes (Node).Has_Element :=
Source.Nodes (Node).Has_Element;
Node := Node + 1;
end loop;
while Node <= Target.Capacity loop
N := Node;
Formal_Ordered_Sets.Free (Tree => Target, X => N);
Node := Node + 1;
end loop;
end if;
return Target;
end Copy;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Position : in out Cursor) is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with "Position cursor has no element";
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Delete");
Tree_Operations.Delete_Node_Sans_Free (Container,
Position.Node);
Formal_Ordered_Sets.Free (Container, Position.Node);
Position := No_Element;
end Delete;
procedure Delete (Container : in out Set; Item : Element_Type) is
X : constant Count_Type := Element_Keys.Find (Container, Item);
begin
if X = 0 then
raise Constraint_Error with "attempt to delete element not in set";
end if;
Tree_Operations.Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end Delete;
------------------
-- Delete_First --
------------------
procedure Delete_First (Container : in out Set) is
X : constant Count_Type := Container.First;
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end if;
end Delete_First;
-----------------
-- Delete_Last --
-----------------
procedure Delete_Last (Container : in out Set) is
X : constant Count_Type := Container.Last;
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end if;
end Delete_Last;
----------------
-- Difference --
----------------
procedure Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Difference (Target, Source);
end Difference;
function Difference (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Empty_Set;
end if;
if Length (Left) = 0 then
return Empty_Set;
end if;
if Length (Right) = 0 then
return Left.Copy;
end if;
return S : Set (Length (Left)) do
Assign (S, Set_Ops.Set_Difference (Left, Right));
end return;
end Difference;
-------------
-- Element --
-------------
function Element (Container : Set; Position : Cursor) return Element_Type is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with "Position cursor has no element";
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Element");
return Container.Nodes (Position.Node).Element;
end Element;
-------------------------
-- Equivalent_Elements --
-------------------------
function Equivalent_Elements (Left, Right : Element_Type) return Boolean is
begin
if Left < Right
or else Right < Left
then
return False;
else
return True;
end if;
end Equivalent_Elements;
---------------------
-- Equivalent_Sets --
---------------------
function Equivalent_Sets (Left, Right : Set) return Boolean is
function Is_Equivalent_Node_Node
(L, R : Node_Type) return Boolean;
pragma Inline (Is_Equivalent_Node_Node);
function Is_Equivalent is
new Tree_Operations.Generic_Equal (Is_Equivalent_Node_Node);
-----------------------------
-- Is_Equivalent_Node_Node --
-----------------------------
function Is_Equivalent_Node_Node (L, R : Node_Type) return Boolean is
begin
if L.Element < R.Element then
return False;
elsif R.Element < L.Element then
return False;
else
return True;
end if;
end Is_Equivalent_Node_Node;
-- Start of processing for Equivalent_Sets
begin
return Is_Equivalent (Left, Right);
end Equivalent_Sets;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Item : Element_Type) is
X : constant Count_Type := Element_Keys.Find (Container, Item);
begin
if X /= 0 then
Tree_Operations.Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end if;
end Exclude;
----------
-- Find --
----------
function Find (Container : Set; Item : Element_Type) return Cursor is
Node : constant Count_Type := Element_Keys.Find (Container, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Find;
-----------
-- First --
-----------
function First (Container : Set) return Cursor is
begin
if Length (Container) = 0 then
return No_Element;
end if;
return (Node => Container.First);
end First;
-------------------
-- First_Element --
-------------------
function First_Element (Container : Set) return Element_Type is
Fst : constant Count_Type := First (Container).Node;
begin
if Fst = 0 then
raise Constraint_Error with "set is empty";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Nodes;
begin
return N (Fst).Element;
end;
end First_Element;
-----------
-- Floor --
-----------
function Floor (Container : Set; Item : Element_Type) return Cursor is
begin
declare
Node : constant Count_Type := Element_Keys.Floor (Container, Item);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end;
end Floor;
------------------
-- Formal_Model --
------------------
package body Formal_Model is
-------------------------
-- E_Bigger_Than_Range --
-------------------------
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (E.Get (Container, I) < Item) then
return False;
end if;
end loop;
return True;
end E_Bigger_Than_Range;
-------------------------
-- E_Elements_Included --
-------------------------
function E_Elements_Included
(Left : E.Sequence;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Left) loop
if not E.Contains (Right, 1, E.Length (Right), E.Get (Left, I))
then
return False;
end if;
end loop;
return True;
end E_Elements_Included;
function E_Elements_Included
(Left : E.Sequence;
Model : M.Set;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Left) loop
declare
Item : constant Element_Type := E.Get (Left, I);
begin
if M.Contains (Model, Item) then
if not E.Contains (Right, 1, E.Length (Right), Item) then
return False;
end if;
end if;
end;
end loop;
return True;
end E_Elements_Included;
function E_Elements_Included
(Container : E.Sequence;
Model : M.Set;
Left : E.Sequence;
Right : E.Sequence) return Boolean
is
begin
for I in 1 .. E.Length (Container) loop
declare
Item : constant Element_Type := E.Get (Container, I);
begin
if M.Contains (Model, Item) then
if not E.Contains (Left, 1, E.Length (Left), Item) then
return False;
end if;
else
if not E.Contains (Right, 1, E.Length (Right), Item) then
return False;
end if;
end if;
end;
end loop;
return True;
end E_Elements_Included;
---------------
-- E_Is_Find --
---------------
function E_Is_Find
(Container : E.Sequence;
Item : Element_Type;
Position : Count_Type) return Boolean
is
begin
for I in 1 .. Position - 1 loop
if Item < E.Get (Container, I) then
return False;
end if;
end loop;
if Position < E.Length (Container) then
for I in Position + 1 .. E.Length (Container) loop
if E.Get (Container, I) < Item then
return False;
end if;
end loop;
end if;
return True;
end E_Is_Find;
--------------------------
-- E_Smaller_Than_Range --
--------------------------
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Item < E.Get (Container, I)) then
return False;
end if;
end loop;
return True;
end E_Smaller_Than_Range;
----------
-- Find --
----------
function Find
(Container : E.Sequence;
Item : Element_Type) return Count_Type
is
begin
for I in 1 .. E.Length (Container) loop
if Equivalent_Elements (Item, E.Get (Container, I)) then
return I;
end if;
end loop;
return 0;
end Find;
--------------
-- Elements --
--------------
function Elements (Container : Set) return E.Sequence is
Position : Count_Type := Container.First;
R : E.Sequence;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R := E.Add (R, Container.Nodes (Position).Element);
Position := Tree_Operations.Next (Container, Position);
end loop;
return R;
end Elements;
----------------------------
-- Lift_Abstraction_Level --
----------------------------
procedure Lift_Abstraction_Level (Container : Set) is null;
-----------------------
-- Mapping_Preserved --
-----------------------
function Mapping_Preserved
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map) return Boolean
is
begin
for C of P_Left loop
if not P.Has_Key (P_Right, C)
or else P.Get (P_Left, C) > E.Length (E_Left)
or else P.Get (P_Right, C) > E.Length (E_Right)
or else E.Get (E_Left, P.Get (P_Left, C)) /=
E.Get (E_Right, P.Get (P_Right, C))
then
return False;
end if;
end loop;
return True;
end Mapping_Preserved;
------------------------------
-- Mapping_Preserved_Except --
------------------------------
function Mapping_Preserved_Except
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map;
Position : Cursor) return Boolean
is
begin
for C of P_Left loop
if C /= Position
and (not P.Has_Key (P_Right, C)
or else P.Get (P_Left, C) > E.Length (E_Left)
or else P.Get (P_Right, C) > E.Length (E_Right)
or else E.Get (E_Left, P.Get (P_Left, C)) /=
E.Get (E_Right, P.Get (P_Right, C)))
then
return False;
end if;
end loop;
return True;
end Mapping_Preserved_Except;
-------------------------
-- P_Positions_Shifted --
-------------------------
function P_Positions_Shifted
(Small : P.Map;
Big : P.Map;
Cut : Positive_Count_Type;
Count : Count_Type := 1) return Boolean
is
begin
for Cu of Small loop
if not P.Has_Key (Big, Cu) then
return False;
end if;
end loop;
for Cu of Big loop
declare
Pos : constant Positive_Count_Type := P.Get (Big, Cu);
begin
if Pos < Cut then
if not P.Has_Key (Small, Cu)
or else Pos /= P.Get (Small, Cu)
then
return False;
end if;
elsif Pos >= Cut + Count then
if not P.Has_Key (Small, Cu)
or else Pos /= P.Get (Small, Cu) + Count
then
return False;
end if;
else
if P.Has_Key (Small, Cu) then
return False;
end if;
end if;
end;
end loop;
return True;
end P_Positions_Shifted;
-----------
-- Model --
-----------
function Model (Container : Set) return M.Set is
Position : Count_Type := Container.First;
R : M.Set;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R :=
M.Add
(Container => R,
Item => Container.Nodes (Position).Element);
Position := Tree_Operations.Next (Container, Position);
end loop;
return R;
end Model;
---------------
-- Positions --
---------------
function Positions (Container : Set) return P.Map is
I : Count_Type := 1;
Position : Count_Type := Container.First;
R : P.Map;
begin
-- Can't use First, Next or Element here, since they depend on models
-- for their postconditions.
while Position /= 0 loop
R := P.Add (R, (Node => Position), I);
pragma Assert (P.Length (R) = I);
Position := Tree_Operations.Next (Container, Position);
I := I + 1;
end loop;
return R;
end Positions;
end Formal_Model;
----------
-- Free --
----------
procedure Free (Tree : in out Set; X : Count_Type) is
begin
Tree.Nodes (X).Has_Element := False;
Tree_Operations.Free (Tree, X);
end Free;
----------------------
-- Generic_Allocate --
----------------------
procedure Generic_Allocate
(Tree : in out Tree_Types.Tree_Type'Class;
Node : out Count_Type)
is
procedure Allocate is
new Tree_Operations.Generic_Allocate (Set_Element);
begin
Allocate (Tree, Node);
Tree.Nodes (Node).Has_Element := True;
end Generic_Allocate;
------------------
-- Generic_Keys --
------------------
package body Generic_Keys with SPARK_Mode => Off is
-----------------------
-- Local Subprograms --
-----------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Greater_Key_Node);
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean;
pragma Inline (Is_Less_Key_Node);
--------------------------
-- Local Instantiations --
--------------------------
package Key_Keys is
new Red_Black_Trees.Generic_Bounded_Keys
(Tree_Operations => Tree_Operations,
Key_Type => Key_Type,
Is_Less_Key_Node => Is_Less_Key_Node,
Is_Greater_Key_Node => Is_Greater_Key_Node);
-------------
-- Ceiling --
-------------
function Ceiling (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type := Key_Keys.Ceiling (Container, Key);
begin
if Node = 0 then
return No_Element;
end if;
return (Node => Node);
end Ceiling;
--------------
-- Contains --
--------------
function Contains (Container : Set; Key : Key_Type) return Boolean is
begin
return Find (Container, Key) /= No_Element;
end Contains;
------------
-- Delete --
------------
procedure Delete (Container : in out Set; Key : Key_Type) is
X : constant Count_Type := Key_Keys.Find (Container, Key);
begin
if X = 0 then
raise Constraint_Error with "attempt to delete key not in set";
end if;
Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end Delete;
-------------
-- Element --
-------------
function Element (Container : Set; Key : Key_Type) return Element_Type is
Node : constant Count_Type := Key_Keys.Find (Container, Key);
begin
if Node = 0 then
raise Constraint_Error with "key not in set";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Nodes;
begin
return N (Node).Element;
end;
end Element;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys (Left, Right : Key_Type) return Boolean is
begin
if Left < Right
or else Right < Left
then
return False;
else
return True;
end if;
end Equivalent_Keys;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Set; Key : Key_Type) is
X : constant Count_Type := Key_Keys.Find (Container, Key);
begin
if X /= 0 then
Delete_Node_Sans_Free (Container, X);
Formal_Ordered_Sets.Free (Container, X);
end if;
end Exclude;
----------
-- Find --
----------
function Find (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type := Key_Keys.Find (Container, Key);
begin
return (if Node = 0 then No_Element else (Node => Node));
end Find;
-----------
-- Floor --
-----------
function Floor (Container : Set; Key : Key_Type) return Cursor is
Node : constant Count_Type := Key_Keys.Floor (Container, Key);
begin
return (if Node = 0 then No_Element else (Node => Node));
end Floor;
------------------
-- Formal_Model --
------------------
package body Formal_Model is
-------------------------
-- E_Bigger_Than_Range --
-------------------------
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Generic_Keys.Key (E.Get (Container, I)) < Key) then
return False;
end if;
end loop;
return True;
end E_Bigger_Than_Range;
---------------
-- E_Is_Find --
---------------
function E_Is_Find
(Container : E.Sequence;
Key : Key_Type;
Position : Count_Type) return Boolean
is
begin
for I in 1 .. Position - 1 loop
if Key < Generic_Keys.Key (E.Get (Container, I)) then
return False;
end if;
end loop;
if Position < E.Length (Container) then
for I in Position + 1 .. E.Length (Container) loop
if Generic_Keys.Key (E.Get (Container, I)) < Key then
return False;
end if;
end loop;
end if;
return True;
end E_Is_Find;
--------------------------
-- E_Smaller_Than_Range --
--------------------------
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
is
begin
for I in Fst .. Lst loop
if not (Key < Generic_Keys.Key (E.Get (Container, I))) then
return False;
end if;
end loop;
return True;
end E_Smaller_Than_Range;
----------
-- Find --
----------
function Find
(Container : E.Sequence;
Key : Key_Type) return Count_Type
is
begin
for I in 1 .. E.Length (Container) loop
if Equivalent_Keys
(Key, Generic_Keys.Key (E.Get (Container, I)))
then
return I;
end if;
end loop;
return 0;
end Find;
-----------------------
-- M_Included_Except --
-----------------------
function M_Included_Except
(Left : M.Set;
Right : M.Set;
Key : Key_Type) return Boolean
is
begin
for E of Left loop
if not Contains (Right, E)
and not Equivalent_Keys (Generic_Keys.Key (E), Key)
then
return False;
end if;
end loop;
return True;
end M_Included_Except;
end Formal_Model;
-------------------------
-- Is_Greater_Key_Node --
-------------------------
function Is_Greater_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean
is
begin
return Key (Right.Element) < Left;
end Is_Greater_Key_Node;
----------------------
-- Is_Less_Key_Node --
----------------------
function Is_Less_Key_Node
(Left : Key_Type;
Right : Node_Type) return Boolean
is
begin
return Left < Key (Right.Element);
end Is_Less_Key_Node;
---------
-- Key --
---------
function Key (Container : Set; Position : Cursor) return Key_Type is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with
"Position cursor has no element";
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Key");
declare
N : Tree_Types.Nodes_Type renames Container.Nodes;
begin
return Key (N (Position.Node).Element);
end;
end Key;
-------------
-- Replace --
-------------
procedure Replace
(Container : in out Set;
Key : Key_Type;
New_Item : Element_Type)
is
Node : constant Count_Type := Key_Keys.Find (Container, Key);
begin
if not Has_Element (Container, (Node => Node)) then
raise Constraint_Error with
"attempt to replace key not in set";
else
Replace_Element (Container, Node, New_Item);
end if;
end Replace;
end Generic_Keys;
-----------------
-- Has_Element --
-----------------
function Has_Element (Container : Set; Position : Cursor) return Boolean is
begin
if Position.Node = 0 then
return False;
else
return Container.Nodes (Position.Node).Has_Element;
end if;
end Has_Element;
-------------
-- Include --
-------------
procedure Include (Container : in out Set; New_Item : Element_Type) is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, New_Item, Position, Inserted);
if not Inserted then
declare
N : Tree_Types.Nodes_Type renames Container.Nodes;
begin
N (Position.Node).Element := New_Item;
end;
end if;
end Include;
------------
-- Insert --
------------
procedure Insert
(Container : in out Set;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
is
begin
Insert_Sans_Hint (Container, New_Item, Position.Node, Inserted);
end Insert;
procedure Insert
(Container : in out Set;
New_Item : Element_Type)
is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, New_Item, Position, Inserted);
if not Inserted then
raise Constraint_Error with
"attempt to insert element already in set";
end if;
end Insert;
----------------------
-- Insert_Sans_Hint --
----------------------
procedure Insert_Sans_Hint
(Container : in out Set;
New_Item : Element_Type;
Node : out Count_Type;
Inserted : out Boolean)
is
procedure Set_Element (Node : in out Node_Type);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Conditional_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Container, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := New_Item;
end Set_Element;
-- Start of processing for Insert_Sans_Hint
begin
Conditional_Insert_Sans_Hint
(Container,
New_Item,
Node,
Inserted);
end Insert_Sans_Hint;
----------------------
-- Insert_With_Hint --
----------------------
procedure Insert_With_Hint
(Dst_Set : in out Set;
Dst_Hint : Count_Type;
Src_Node : Node_Type;
Dst_Node : out Count_Type)
is
Success : Boolean;
pragma Unreferenced (Success);
procedure Set_Element (Node : in out Node_Type);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Insert_Post);
procedure Local_Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Insert_Post, Insert_Sans_Hint);
procedure Allocate is new Generic_Allocate (Set_Element);
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
Result : Count_Type;
begin
Allocate (Dst_Set, Result);
return Result;
end New_Node;
-----------------
-- Set_Element --
-----------------
procedure Set_Element (Node : in out Node_Type) is
begin
Node.Element := Src_Node.Element;
end Set_Element;
-- Start of processing for Insert_With_Hint
begin
Local_Insert_With_Hint
(Dst_Set,
Dst_Hint,
Src_Node.Element,
Dst_Node,
Success);
end Insert_With_Hint;
------------------
-- Intersection --
------------------
procedure Intersection (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Intersection (Target, Source);
end Intersection;
function Intersection (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Left.Copy;
end if;
return S : Set (Count_Type'Min (Length (Left), Length (Right))) do
Assign (S, Set_Ops.Set_Intersection (Left, Right));
end return;
end Intersection;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Set) return Boolean is
begin
return Length (Container) = 0;
end Is_Empty;
-----------------------------
-- Is_Greater_Element_Node --
-----------------------------
function Is_Greater_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean
is
begin
-- Compute e > node same as node < e
return Right.Element < Left;
end Is_Greater_Element_Node;
--------------------------
-- Is_Less_Element_Node --
--------------------------
function Is_Less_Element_Node
(Left : Element_Type;
Right : Node_Type) return Boolean
is
begin
return Left < Right.Element;
end Is_Less_Element_Node;
-----------------------
-- Is_Less_Node_Node --
-----------------------
function Is_Less_Node_Node (L, R : Node_Type) return Boolean is
begin
return L.Element < R.Element;
end Is_Less_Node_Node;
---------------
-- Is_Subset --
---------------
function Is_Subset (Subset : Set; Of_Set : Set) return Boolean is
begin
return Set_Ops.Set_Subset (Subset, Of_Set => Of_Set);
end Is_Subset;
----------
-- Last --
----------
function Last (Container : Set) return Cursor is
begin
return (if Length (Container) = 0
then No_Element
else (Node => Container.Last));
end Last;
------------------
-- Last_Element --
------------------
function Last_Element (Container : Set) return Element_Type is
begin
if Last (Container).Node = 0 then
raise Constraint_Error with "set is empty";
end if;
declare
N : Tree_Types.Nodes_Type renames Container.Nodes;
begin
return N (Last (Container).Node).Element;
end;
end Last_Element;
--------------
-- Left_Son --
--------------
function Left_Son (Node : Node_Type) return Count_Type is
begin
return Node.Left;
end Left_Son;
------------
-- Length --
------------
function Length (Container : Set) return Count_Type is
begin
return Container.Length;
end Length;
----------
-- Move --
----------
procedure Move (Target : in out Set; Source : in out Set) is
N : Tree_Types.Nodes_Type renames Source.Nodes;
X : Count_Type;
begin
if Target'Address = Source'Address then
return;
end if;
if Target.Capacity < Length (Source) then
raise Constraint_Error with -- ???
"Source length exceeds Target capacity";
end if;
Clear (Target);
loop
X := Source.First;
exit when X = 0;
Insert (Target, N (X).Element); -- optimize???
Tree_Operations.Delete_Node_Sans_Free (Source, X);
Formal_Ordered_Sets.Free (Source, X);
end loop;
end Move;
----------
-- Next --
----------
function Next (Container : Set; Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if not Has_Element (Container, Position) then
raise Constraint_Error;
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Next");
return (Node => Tree_Operations.Next (Container, Position.Node));
end Next;
procedure Next (Container : Set; Position : in out Cursor) is
begin
Position := Next (Container, Position);
end Next;
-------------
-- Overlap --
-------------
function Overlap (Left, Right : Set) return Boolean is
begin
return Set_Ops.Set_Overlap (Left, Right);
end Overlap;
------------
-- Parent --
------------
function Parent (Node : Node_Type) return Count_Type is
begin
return Node.Parent;
end Parent;
--------------
-- Previous --
--------------
function Previous (Container : Set; Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if not Has_Element (Container, Position) then
raise Constraint_Error;
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Previous");
declare
Node : constant Count_Type :=
Tree_Operations.Previous (Container, Position.Node);
begin
return (if Node = 0 then No_Element else (Node => Node));
end;
end Previous;
procedure Previous (Container : Set; Position : in out Cursor) is
begin
Position := Previous (Container, Position);
end Previous;
-------------
-- Replace --
-------------
procedure Replace (Container : in out Set; New_Item : Element_Type) is
Node : constant Count_Type := Element_Keys.Find (Container, New_Item);
begin
if Node = 0 then
raise Constraint_Error with
"attempt to replace element not in set";
end if;
Container.Nodes (Node).Element := New_Item;
end Replace;
---------------------
-- Replace_Element --
---------------------
procedure Replace_Element
(Tree : in out Set;
Node : Count_Type;
Item : Element_Type)
is
pragma Assert (Node /= 0);
function New_Node return Count_Type;
pragma Inline (New_Node);
procedure Local_Insert_Post is
new Element_Keys.Generic_Insert_Post (New_Node);
procedure Local_Insert_Sans_Hint is
new Element_Keys.Generic_Conditional_Insert (Local_Insert_Post);
procedure Local_Insert_With_Hint is
new Element_Keys.Generic_Conditional_Insert_With_Hint
(Local_Insert_Post,
Local_Insert_Sans_Hint);
NN : Tree_Types.Nodes_Type renames Tree.Nodes;
--------------
-- New_Node --
--------------
function New_Node return Count_Type is
N : Node_Type renames NN (Node);
begin
N.Element := Item;
N.Color := Red;
N.Parent := 0;
N.Right := 0;
N.Left := 0;
return Node;
end New_Node;
Hint : Count_Type;
Result : Count_Type;
Inserted : Boolean;
-- Start of processing for Insert
begin
if Item < NN (Node).Element
or else NN (Node).Element < Item
then
null;
else
NN (Node).Element := Item;
return;
end if;
Hint := Element_Keys.Ceiling (Tree, Item);
if Hint = 0 then
null;
elsif Item < NN (Hint).Element then
if Hint = Node then
NN (Node).Element := Item;
return;
end if;
else
pragma Assert (not (NN (Hint).Element < Item));
raise Program_Error with "attempt to replace existing element";
end if;
Tree_Operations.Delete_Node_Sans_Free (Tree, Node);
Local_Insert_With_Hint
(Tree => Tree,
Position => Hint,
Key => Item,
Node => Result,
Inserted => Inserted);
pragma Assert (Inserted);
pragma Assert (Result = Node);
end Replace_Element;
procedure Replace_Element
(Container : in out Set;
Position : Cursor;
New_Item : Element_Type)
is
begin
if not Has_Element (Container, Position) then
raise Constraint_Error with
"Position cursor has no element";
end if;
pragma Assert (Vet (Container, Position.Node),
"bad cursor in Replace_Element");
Replace_Element (Container, Position.Node, New_Item);
end Replace_Element;
---------------
-- Right_Son --
---------------
function Right_Son (Node : Node_Type) return Count_Type is
begin
return Node.Right;
end Right_Son;
---------------
-- Set_Color --
---------------
procedure Set_Color
(Node : in out Node_Type;
Color : Red_Black_Trees.Color_Type)
is
begin
Node.Color := Color;
end Set_Color;
--------------
-- Set_Left --
--------------
procedure Set_Left (Node : in out Node_Type; Left : Count_Type) is
begin
Node.Left := Left;
end Set_Left;
----------------
-- Set_Parent --
----------------
procedure Set_Parent (Node : in out Node_Type; Parent : Count_Type) is
begin
Node.Parent := Parent;
end Set_Parent;
---------------
-- Set_Right --
---------------
procedure Set_Right (Node : in out Node_Type; Right : Count_Type) is
begin
Node.Right := Right;
end Set_Right;
--------------------------
-- Symmetric_Difference --
--------------------------
procedure Symmetric_Difference (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Symmetric_Difference (Target, Source);
end Symmetric_Difference;
function Symmetric_Difference (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Empty_Set;
end if;
if Length (Right) = 0 then
return Left.Copy;
end if;
if Length (Left) = 0 then
return Right.Copy;
end if;
return S : Set (Length (Left) + Length (Right)) do
Assign (S, Set_Ops.Set_Symmetric_Difference (Left, Right));
end return;
end Symmetric_Difference;
------------
-- To_Set --
------------
function To_Set (New_Item : Element_Type) return Set is
Node : Count_Type;
Inserted : Boolean;
begin
return S : Set (Capacity => 1) do
Insert_Sans_Hint (S, New_Item, Node, Inserted);
pragma Assert (Inserted);
end return;
end To_Set;
-----------
-- Union --
-----------
procedure Union (Target : in out Set; Source : Set) is
begin
Set_Ops.Set_Union (Target, Source);
end Union;
function Union (Left, Right : Set) return Set is
begin
if Left'Address = Right'Address then
return Left.Copy;
end if;
if Length (Left) = 0 then
return Right.Copy;
end if;
if Length (Right) = 0 then
return Left.Copy;
end if;
return S : Set (Length (Left) + Length (Right)) do
Assign (S, Source => Left);
Union (S, Right);
end return;
end Union;
end Ada.Containers.Formal_Ordered_Sets;
|
-- The Cupcake GUI Toolkit
-- (c) Kristian Klomsten Skordal 2012 <kristian.skordal@gmail.com>
-- Report bugs and issues on <http://github.com/skordal/cupcake/issues>
-- vim:ts=3:sw=3:et:si:sta
package Cupcake.Colors is
-- Color component type:
subtype Color_Component_Type is Float range 0.0 .. 1.0;
-- Color type:
type Color is record
R, G, B : Color_Component_Type;
end record;
-- Multiplies all color components of a Color with a constant:
function "*" (Left : in Color; Right : in Float) return Color;
function "*" (Left : in Float; Right : in Color) return Color with Inline;
-- Predefined color constants:
BLACK : constant Color := (0.0, 0.0, 0.0);
WHITE : constant Color := (1.0, 1.0, 1.0);
RED : constant Color := (1.0, 0.0, 0.0);
GREEN : constant Color := (0.0, 1.0, 0.0);
BLUE : constant Color := (0.0, 0.0, 1.0);
DEFAULT_BACKGROUND_COLOR : constant Color := (0.85, 0.85, 0.85);
DEFAULT_FOREGROUND_COLOR : constant Color := BLACK;
end Cupcake.Colors;
|
package body Json is
F : Ada.Text_IO.File_Type;
Now : Ada.Calendar.Time := Ada.Calendar.Clock;
OutputFileName : String := "films-watched.json";
----------------
-- AppendFilm --
----------------
procedure AppendFilm (title, year, score, imdb : String) is
begin
Ada.Text_IO.Open(F, Ada.Text_IO.Append_File, OutputFileName);
Ada.Text_IO.Put_Line(F, " {");
Ada.Text_IO.Put(F, " ""title"": """);
Ada.Text_IO.Put(F, title);
Ada.Text_IO.Put(F, """,");
Ada.Text_IO.New_Line(F);
Ada.Text_IO.Put(F, " ""year"": """);
Ada.Text_IO.Put(F, year);
Ada.Text_IO.Put(F, """,");
Ada.Text_IO.New_Line(F);
Ada.Text_IO.Put(F, " ""score"": """);
Ada.Text_IO.Put(F, score);
Ada.Text_IO.Put(F, """,");
Ada.Text_IO.New_Line(F);
Ada.Text_IO.Put(F, " ""imdb"": """);
Ada.Text_IO.Put(F, imdb);
Ada.Text_IO.Put(F, """");
Ada.Text_IO.New_Line(F);
Ada.Text_IO.Put_Line(F, " },");
Ada.Text_IO.Close(F);
end AppendFilm;
----------
-- Init --
----------
procedure Init is
begin
Ada.Text_IO.Create(F, Ada.Text_IO.Out_File, OutputFileName);
Ada.Text_IO.Put_Line(F, "{");
Ada.Text_IO.Put(F, " ""name"": ""Films watched");
Ada.Text_IO.Put(F, Integer'Image(Ada.Calendar.Day(Now)));
Ada.Text_IO.Put(F, Integer'Image(Ada.Calendar.Month(Now)));
Ada.Text_IO.Put(F, Integer'Image(Ada.Calendar.Year(Now)));
Ada.Text_IO.Put(F, """,");
Ada.Text_IO.New_Line(F);
Ada.Text_IO.Put_Line(F, " ""films"": [");
Ada.Text_IO.Close(F);
end Init;
-----------
-- Close --
-----------
procedure Close is
begin
Ada.Text_IO.Open(F, Ada.Text_IO.Append_File, OutputFileName);
Ada.Text_IO.Put_Line(F, " ]");
Ada.Text_IO.Put_Line(F, "}");
Ada.Text_IO.Close(F);
end Close;
end Json;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.Types;
package GL.Low_Level is
pragma Preelaborate;
use GL.Types;
-- This package contains some low-level types that are used by the raw C
-- interface of the OpenGL API. They are converted to types that are easier
-- to handle by the wrapper and thus are not needed for using the wrapper.
-- However, they might be used by other APIs that use OpenGL and thus are
-- exposed publicly here.
-- Boolean with the representation used by the OpenGL API (unsigned char).
-- Is converted to a standard Boolean by the wrapper.
type Bool is new Boolean;
-- This type is never used directly. However, enumerations refer to it for
-- defining their Size attribute.
subtype Enum is C.unsigned;
-- Bitfields are usually converted to a record with Boolean fields in the
-- wrapper. However, for interacting with the OpenGL library, these records
-- are converted back to the raw Bitfield type (by means of
-- Unchecked_Conversion). Using the record directly with the C interface
-- requires it to have the C_Pass_By_Value conversion, which for some reason
-- breaks linking on Windows with StdCall convention (possibly a GNAT bug).
subtype Bitfield is C.unsigned;
-- These types totally are not pointers. No idea why they are named like this.
subtype IntPtr is C.long;
subtype SizeIPtr is C.long;
type Char_Access_Array is array (Size range <>) of access C.char;
-- used in API calls
type Size_Access is access all Types.Size;
type Bool_Access is access all Bool;
subtype Zero is Int range 0 .. 0;
private
for Bool use (False => 0, True => 1);
for Bool'Size use C.unsigned_char'Size;
pragma Convention (C, Size_Access);
pragma Convention (C, Bool_Access);
pragma Convention (C, Char_Access_Array);
end GL.Low_Level;
|
with Morse; use Morse;
procedure Morse_Tx is
begin
Morsebeep (Convert ("Science sans Conscience"));
end Morse_Tx;
|
-----------------------------------------------------------------------
-- awa-votes-beans -- Beans for module votes
-- Copyright (C) 2013, 2015 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 Util.Beans.Basic;
with AWA.Votes.Modules;
with AWA.Votes.Models;
-- === Vote Beans ===
-- The <tt>Vote_Bean</tt> is a bean intended to be used in presentation files (XHTML facelet
-- files) to vote for an item. The managed bean can be easily configured in the application XML
-- configuration file. The <b>permission</b> and <b>entity_type</b> are the two properties
-- that should be defined in the configuration. The <b>permission</b> is the name of the
-- permission that must be used to verify that the user is allowed to vote for the item.
-- The <b>entity_type</b> is the name of the entity (table name) used by the item.
-- The example below defines the bean <tt>questionVote</tt> defined by the question module.
--
-- <managed-bean>
-- <description>The vote bean that allows to vote for a question.</description>
-- <managed-bean-name>questionVote</managed-bean-name>
-- <managed-bean-class>AWA.Votes.Beans.Votes_Bean</managed-bean-class>
-- <managed-bean-scope>request</managed-bean-scope>
-- <managed-property>
-- <property-name>permission</property-name>
-- <property-class>String</property-class>
-- <value>answer-create</value>
-- </managed-property>
-- <managed-property>
-- <property-name>entity_type</property-name>
-- <property-class>String</property-class>
-- <value>awa_question</value>
-- </managed-property>
-- </managed-bean>
--
-- The vote concerns entities for the <tt>awa_question</tt> entity table.
-- The permission <tt>answer-create</tt> is used to verify that the vote is allowed.
--
-- [images/awa_votes_bean.png]
--
-- The managed bean defines three operations that can be called: <tt>vote_up</tt>,
-- <tt>vote_down</tt> and <tt>vote</tt> to setup specific ratings.
package AWA.Votes.Beans is
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with private;
type Vote_Bean_Access is access all Vote_Bean'Class;
-- Action to vote up.
overriding
procedure Vote_Up (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote down.
overriding
procedure Vote_Down (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Action to vote.
overriding
procedure Vote (Bean : in out Vote_Bean;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String);
-- Create the Votes_Bean bean instance.
function Create_Vote_Bean (Module : in AWA.Votes.Modules.Vote_Module_Access)
return Util.Beans.Basic.Readonly_Bean_Access;
private
type Vote_Bean is new AWA.Votes.Models.Vote_Bean with record
Module : AWA.Votes.Modules.Vote_Module_Access := null;
end record;
end AWA.Votes.Beans;
|
-- C85014C.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT THE PRESENCE OR ABSENCE OF A RESULT TYPE IS USED TO
-- DETERMINE WHICH SUBPROGRAM OR ENTRY IS BEING RENAMED.
-- HISTORY:
-- JET 03/24/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C85014C IS
I, J : INTEGER;
TASK TYPE T IS
ENTRY Q (I1 : INTEGER);
END T;
TASK0 : T;
PACKAGE FUNC IS
FUNCTION Q (I1 : INTEGER) RETURN INTEGER;
FUNCTION FUNC RETURN T;
END FUNC;
USE FUNC;
PROCEDURE PROC (I1: INTEGER) IS
BEGIN
I := I1;
END PROC;
FUNCTION PROC (I1: INTEGER) RETURN INTEGER IS
BEGIN
I := I1 + 1;
RETURN 0;
END PROC;
TASK BODY T IS
BEGIN
ACCEPT Q (I1 : INTEGER) DO
I := I1;
END Q;
END T;
PACKAGE BODY FUNC IS
FUNCTION Q (I1 : INTEGER) RETURN INTEGER IS
BEGIN
I := I1 + 1;
RETURN 0;
END Q;
FUNCTION FUNC RETURN T IS
BEGIN
RETURN TASK0;
END FUNC;
END FUNC;
BEGIN
TEST ("C85014C", "CHECK THAT THE PRESENCE OR ABSENCE OF A " &
"RESULT TYPE IS USED TO DETERMINE WHICH " &
"SUBPROGRAM OR ENTRY IS BEING RENAMED");
DECLARE
PROCEDURE PROC1 (J1: INTEGER) RENAMES PROC;
FUNCTION PROC2 (J1: INTEGER) RETURN INTEGER RENAMES PROC;
BEGIN
PROC1(1);
IF I /= IDENT_INT(1) THEN
FAILED("INCORRECT VALUE OF I AFTER PROC1");
END IF;
J := PROC2(1);
IF I /= IDENT_INT(2) THEN
FAILED("INCORRECT VALUE OF I AFTER PROC2");
END IF;
END;
DECLARE
PROCEDURE FUNC1 (J1 : INTEGER) RENAMES FUNC.FUNC.Q;
FUNCTION FUNC2 (J1 : INTEGER) RETURN INTEGER RENAMES FUNC.Q;
BEGIN
FUNC1(1);
IF I /= IDENT_INT(1) THEN
FAILED("INCORRECT VALUE OF I AFTER FUNC1");
END IF;
J := FUNC2(1);
IF I /= IDENT_INT(2) THEN
FAILED("INCORRECT VALUE OF I AFTER FUNC2");
END IF;
END;
RESULT;
END C85014C;
|
-- Copyright 2017-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ada.Directories;
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Text_IO.Text_Streams;
with Ada.Text_IO;
with DOM.Core; use DOM.Core;
with DOM.Core.Documents; use DOM.Core.Documents;
with DOM.Core.Elements; use DOM.Core.Elements;
with DOM.Core.Nodes; use DOM.Core.Nodes;
with DOM.Readers;
with Input_Sources.File;
with Bases;
with Bases.SaveLoad; use Bases.SaveLoad;
with Careers;
with Config; use Config;
with Crafts; use Crafts;
with Events; use Events;
with Goals; use Goals;
with Log; use Log;
with Maps; use Maps;
with Messages; use Messages;
with Missions; use Missions;
with Ships; use Ships;
with Ships.SaveLoad; use Ships.SaveLoad;
with Statistics; use Statistics;
with Stories; use Stories;
with Utils;
package body Game.SaveLoad is
-- ****iv* GSaveLoad/GSaveLoad.Save_Version
-- FUNCTION
-- Current version of the save game
-- SOURCE
Save_Version: constant Positive := 5;
-- ****
procedure Save_Game(Pretty_Print: Boolean := False) is
use Ada.Strings.Fixed;
use Ada.Text_IO;
use Ada.Text_IO.Text_Streams;
--## rule off IMPROPER_INITIALIZATION
Save: DOM_Implementation;
--## rule on IMPROPER_INITIALIZATION
Category_Node, Main_Node: DOM.Core.Element;
Raw_Value: Unbounded_String := Null_Unbounded_String;
Save_File: File_Type;
Save_Data: Document;
procedure Save_Statistics
(Statistics_Vector: in out Statistics_Container.Vector;
Stat_Name: String) is
Stat_Node: DOM.Core.Element;
begin
Save_Statistics_Loop :
for Statistic of Statistics_Vector loop
Stat_Node :=
Append_Child
(N => Category_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => Stat_Name));
Set_Attribute
(Elem => Stat_Node, Name => "index",
Value => To_String(Source => Statistic.Index));
Raw_Value :=
To_Unbounded_String(Source => Integer'Image(Statistic.Amount));
Set_Attribute
(Elem => Stat_Node, Name => "amount",
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
end loop Save_Statistics_Loop;
end Save_Statistics;
procedure Save_Number
(Value: Integer; Name: String;
Node: DOM.Core.Element := Category_Node) is
Number_String: constant String :=
Trim(Source => Integer'Image(Value), Side => Ada.Strings.Left);
begin
Set_Attribute(Elem => Node, Name => Name, Value => Number_String);
end Save_Number;
--## rule off TYPE_INITIAL_VALUES
type Difficulty_Data is record
Name: Unbounded_String;
Value: Bonus_Type;
end record;
--## rule on TYPE_INITIAL_VALUES
Difficulties: constant array(1 .. 8) of Difficulty_Data :=
(1 =>
(Name => To_Unbounded_String(Source => "enemydamagebonus"),
Value => New_Game_Settings.Enemy_Damage_Bonus),
2 =>
(Name => To_Unbounded_String(Source => "playerdamagebonus"),
Value => New_Game_Settings.Player_Damage_Bonus),
3 =>
(Name => To_Unbounded_String(Source => "enemymeleedamagebonus"),
Value => New_Game_Settings.Enemy_Melee_Damage_Bonus),
4 =>
(Name => To_Unbounded_String(Source => "playermeleedamagebonus"),
Value => New_Game_Settings.Player_Melee_Damage_Bonus),
5 =>
(Name => To_Unbounded_String(Source => "experiencebonus"),
Value => New_Game_Settings.Experience_Bonus),
6 =>
(Name => To_Unbounded_String(Source => "reputationbonus"),
Value => New_Game_Settings.Reputation_Bonus),
7 =>
(Name => To_Unbounded_String(Source => "upgradecostbonus"),
Value => New_Game_Settings.Upgrade_Cost_Bonus),
8 =>
(Name => To_Unbounded_String(Source => "pricesbonus"),
Value => New_Game_Settings.Prices_Bonus));
begin
Log_Message
(Message =>
"Start saving game in file " & To_String(Source => Save_Name) & ".",
Message_Type => EVERYTHING);
--## rule off IMPROPER_INITIALIZATION
Save_Data := Create_Document(Implementation => Save);
--## rule on IMPROPER_INITIALIZATION
Main_Node :=
Append_Child
(N => Save_Data,
New_Child => Create_Element(Doc => Save_Data, Tag_Name => "save"));
-- Write save game version
Set_Attribute
(Elem => Main_Node, Name => "version",
Value =>
Trim
(Source => Positive'Image(Save_Version),
Side => Ada.Strings.Left));
-- Save game difficulty settings
Log_Message
(Message => "Saving game difficulty settings...",
Message_Type => EVERYTHING, New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "difficulty"));
Save_Difficulty_Loop :
for Difficulty of Difficulties loop
Raw_Value :=
To_Unbounded_String(Source => Bonus_Type'Image(Difficulty.Value));
Set_Attribute
(Elem => Category_Node,
Name => To_String(Source => Difficulty.Name),
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
end loop Save_Difficulty_Loop;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save game date
Log_Message
(Message => "Saving game time...", Message_Type => EVERYTHING,
New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "gamedate"));
Save_Number(Value => Game_Date.Year, Name => "year");
Save_Number(Value => Game_Date.Month, Name => "month");
Save_Number(Value => Game_Date.Day, Name => "day");
Save_Number(Value => Game_Date.Hour, Name => "hour");
Save_Number(Value => Game_Date.Minutes, Name => "minutes");
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save map
Log_Message
(Message => "Saving map...", Message_Type => EVERYTHING,
New_Line => False);
Save_Map_Block :
declare
Field_Node: DOM.Core.Element;
begin
Save_Map_X_Loop :
for X in SkyMap'Range(1) loop
Save_Map_Y_Loop :
for Y in SkyMap'Range(2) loop
if SkyMap(X, Y).Visited then
Field_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element
(Doc => Save_Data, Tag_Name => "field"));
Save_Number(Value => X, Name => "x", Node => Field_Node);
Save_Number(Value => Y, Name => "y", Node => Field_Node);
end if;
end loop Save_Map_Y_Loop;
end loop Save_Map_X_Loop;
end Save_Map_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save bases
Log_Message
(Message => "Saving bases...", Message_Type => EVERYTHING,
New_Line => False);
SaveBases(SaveData => Save_Data, MainNode => Main_Node);
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save player ship
Log_Message
(Message => "Saving player ship...", Message_Type => EVERYTHING,
New_Line => False);
SavePlayerShip(SaveData => Save_Data, MainNode => Main_Node);
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save known recipes
Log_Message
(Message => "Saving known recipes...", Message_Type => EVERYTHING,
New_Line => False);
Save_Known_Recipes_Block :
declare
Recipe_Node: DOM.Core.Element;
begin
Save_Known_Recipes_Loop :
for Recipe of Known_Recipes loop
Recipe_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "recipe"));
Set_Attribute
(Elem => Recipe_Node, Name => "index",
Value => To_String(Source => Recipe));
end loop Save_Known_Recipes_Loop;
end Save_Known_Recipes_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save messages
Log_Message
(Message => "Saving messages...", Message_Type => EVERYTHING,
New_Line => False);
Save_Messages_Block :
declare
Messages_To_Save: constant Natural :=
(if Game_Settings.Saved_Messages > MessagesAmount then
MessagesAmount
else Game_Settings.Saved_Messages);
Start_Loop: Positive := 1;
Message_Node: DOM.Core.Element;
Message: Message_Data :=
(Message => Null_Unbounded_String, MType => Default,
Color => WHITE);
Message_Text: Text;
begin
if Messages_To_Save > 0 then
Start_Loop := MessagesAmount - Messages_To_Save + 1;
Save_Messages_Loop :
for I in Start_Loop .. MessagesAmount loop
Message := GetMessage(MessageIndex => I);
Message_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "message"));
Save_Number
(Value => Message_Type'Pos(Message.MType), Name => "type",
Node => Message_Node);
Save_Number
(Value => Message_Color'Pos(Message.Color), Name => "color",
Node => Message_Node);
--## rule off ASSIGNMENTS
Message_Text :=
Create_Text_Node
(Doc => Save_Data,
Data => To_String(Source => Message.Message));
Message_Text :=
Append_Child(N => Message_Node, New_Child => Message_Text);
--## rule on ASSIGNMENTS
end loop Save_Messages_Loop;
end if;
end Save_Messages_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save events
Log_Message
(Message => "Saving events...", Message_Type => EVERYTHING,
New_Line => False);
Save_Known_Events_Block :
declare
Event_Node: DOM.Core.Element;
begin
Save_Events_Loop :
for Event of Events_List loop
Event_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "event"));
Save_Number
(Value => Events_Types'Pos(Event.EType), Name => "type",
Node => Event_Node);
Save_Number(Value => Event.SkyX, Name => "x", Node => Event_Node);
Save_Number(Value => Event.SkyY, Name => "y", Node => Event_Node);
Save_Number
(Value => Event.Time, Name => "time", Node => Event_Node);
case Event.EType is
when DoublePrice =>
Raw_Value := Event.ItemIndex;
when AttackOnBase | EnemyShip | EnemyPatrol | Trader |
FriendlyShip =>
Raw_Value := Event.ShipIndex;
when others =>
Raw_Value :=
To_Unbounded_String(Source => Integer'Image(Event.Data));
end case;
Set_Attribute
(Elem => Event_Node, Name => "data",
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
end loop Save_Events_Loop;
end Save_Known_Events_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save game statistics
Log_Message
(Message => "Saving game statistics...", Message_Type => EVERYTHING,
New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "statistics"));
Save_Statistics
(Statistics_Vector => GameStats.DestroyedShips,
Stat_Name => "destroyedships");
Save_Number(Value => GameStats.BasesVisited, Name => "visitedbases");
Save_Number(Value => GameStats.MapVisited, Name => "mapdiscovered");
Save_Number
(Value => GameStats.DistanceTraveled, Name => "distancetraveled");
Save_Statistics
(Statistics_Vector => GameStats.CraftingOrders,
Stat_Name => "finishedcrafts");
Save_Number
(Value => GameStats.AcceptedMissions, Name => "acceptedmissions");
Save_Statistics
(Statistics_Vector => GameStats.FinishedMissions,
Stat_Name => "finishedmissions");
Save_Statistics
(Statistics_Vector => GameStats.FinishedGoals,
Stat_Name => "finishedgoals");
Save_Statistics
(Statistics_Vector => GameStats.KilledMobs, Stat_Name => "killedmobs");
Save_Number(Value => GameStats.Points, Name => "points");
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save current goal
Log_Message
(Message => "Saving current goal...", Message_Type => EVERYTHING,
New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "currentgoal"));
Set_Attribute
(Elem => Category_Node, Name => "index",
Value => To_String(Source => CurrentGoal.Index));
Save_Number(Value => GoalTypes'Pos(CurrentGoal.GType), Name => "type");
Save_Number(Value => CurrentGoal.Amount, Name => "amount");
Set_Attribute
(Elem => Category_Node, Name => "target",
Value => To_String(Source => CurrentGoal.TargetIndex));
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Save current story
if CurrentStory.Index /= Null_Unbounded_String then
Log_Message
(Message => "Saving current story...", Message_Type => EVERYTHING,
New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "currentstory"));
Set_Attribute
(Elem => Category_Node, Name => "index",
Value => To_String(Source => CurrentStory.Index));
Raw_Value :=
To_Unbounded_String(Source => Positive'Image(CurrentStory.Step));
Set_Attribute
(Elem => Category_Node, Name => "step",
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
case CurrentStory.CurrentStep is
when 0 =>
Set_Attribute
(Elem => Category_Node, Name => "currentstep",
Value => "start");
when -1 =>
Set_Attribute
(Elem => Category_Node, Name => "currentstep",
Value => "finish");
when others =>
Set_Attribute
(Elem => Category_Node, Name => "currentstep",
Value =>
To_String
(Source =>
Stories_List(CurrentStory.Index).Steps
(CurrentStory.CurrentStep)
.Index));
end case;
Save_Number(Value => CurrentStory.MaxSteps, Name => "maxsteps");
if CurrentStory.ShowText then
Set_Attribute
(Elem => Category_Node, Name => "showtext", Value => "Y");
else
Set_Attribute
(Elem => Category_Node, Name => "showtext", Value => "N");
end if;
if CurrentStory.Data /= Null_Unbounded_String then
Set_Attribute
(Elem => Category_Node, Name => "data",
Value => To_String(Source => CurrentStory.Data));
end if;
Save_Number
(Value => StepConditionType'Pos(CurrentStory.FinishedStep),
Name => "finishedstep");
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
end if;
-- Save finished stories data
Save_Finished_Stories_Block :
declare
Step_Node: DOM.Core.Element;
Step_Text: Text;
begin
Log_Message
(Message => "Saving finished stories...",
Message_Type => EVERYTHING, New_Line => False);
Save_Finished_Stories_Loop :
for FinishedStory of FinishedStories loop
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element
(Doc => Save_Data, Tag_Name => "finishedstory"));
Set_Attribute
(Elem => Category_Node, Name => "index",
Value => To_String(Source => FinishedStory.Index));
Save_Number
(Value => FinishedStory.StepsAmount, Name => "stepsamount");
Save_Story_Steps_Loop :
for Step of FinishedStory.StepsTexts loop
Step_Node :=
Append_Child
(N => Category_Node,
New_Child =>
Create_Element
(Doc => Save_Data, Tag_Name => "steptext"));
--## rule off ASSIGNMENTS
Step_Text :=
Create_Text_Node
(Doc => Save_Data, Data => To_String(Source => Step));
Step_Text :=
Append_Child(N => Step_Node, New_Child => Step_Text);
--## rule on ASSIGNMENTS
end loop Save_Story_Steps_Loop;
end loop Save_Finished_Stories_Loop;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
end Save_Finished_Stories_Block;
-- Save missions accepted by player
Save_Missions_Loop :
for Mission of AcceptedMissions loop
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element
(Doc => Save_Data, Tag_Name => "acceptedmission"));
Save_Number
(Value => Missions_Types'Pos(Mission.MType), Name => "type");
Raw_Value :=
(if Mission.MType = Deliver then Mission.ItemIndex
elsif Mission.MType = Passenger then
To_Unbounded_String(Source => Integer'Image(Mission.Data))
elsif Mission.MType = Destroy then Mission.ShipIndex
else To_Unbounded_String(Source => Integer'Image(Mission.Target)));
Set_Attribute
(Elem => Category_Node, Name => "target",
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
Save_Number(Value => Mission.Time, Name => "time");
Save_Number(Value => Mission.TargetX, Name => "targetx");
Save_Number(Value => Mission.TargetY, Name => "targety");
Save_Number(Value => Mission.Reward, Name => "reward");
Save_Number(Value => Mission.StartBase, Name => "startbase");
if Mission.Finished then
Set_Attribute
(Elem => Category_Node, Name => "finished", Value => "Y");
else
Set_Attribute
(Elem => Category_Node, Name => "finished", Value => "N");
end if;
if Mission.Multiplier /= 1.0 then
Raw_Value :=
To_Unbounded_String
(Source => RewardMultiplier'Image(Mission.Multiplier));
Set_Attribute
(Elem => Category_Node, Name => "multiplier",
Value =>
To_String
(Source =>
Trim(Source => Raw_Value, Side => Ada.Strings.Left)));
end if;
end loop Save_Missions_Loop;
-- Save player career
Log_Message
(Message => "Saving player career...", Message_Type => EVERYTHING,
New_Line => False);
Category_Node :=
Append_Child
(N => Main_Node,
New_Child =>
Create_Element(Doc => Save_Data, Tag_Name => "playercareer"));
Set_Attribute
(Elem => Category_Node, Name => "index",
Value => To_String(Source => Player_Career));
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
Create
(File => Save_File, Mode => Out_File,
Name => To_String(Source => Save_Name));
Write
(Stream => Stream(File => Save_File), N => Save_Data,
Pretty_Print => Pretty_Print);
Close(File => Save_File);
Log_Message
(Message => "Finished saving game.", Message_Type => EVERYTHING);
end Save_Game;
procedure Load_Game is
use Ada.Exceptions;
use DOM.Readers;
use Input_Sources.File;
use Careers;
Save_File: File_Input;
--## rule off IMPROPER_INITIALIZATION
Reader: Tree_Reader;
Child_Nodes_List: Node_List;
--## rule on IMPROPER_INITIALIZATION
Nodes_List: Node_List;
Saved_Node: Node;
Save_Data: Document;
begin
Log_Message
(Message =>
"Start loading game from file " & To_String(Source => Save_Name) &
".",
Message_Type => EVERYTHING);
Open(Filename => To_String(Source => Save_Name), Input => Save_File);
--## rule off IMPROPER_INITIALIZATION
Parse(Parser => Reader, Input => Save_File);
Close(Input => Save_File);
Save_Data := Get_Tree(Read => Reader);
--## rule off IMPROPER_INITIALIZATION
-- Check save game compatybility
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "save");
Saved_Node := Item(List => Nodes_List, Index => 0);
if Get_Attribute(Elem => Saved_Node, Name => "version") /= "" then
if Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "version")) >
Save_Version then
raise Save_Game_Invalid_Data
with "This save is incompatible with this version of the game";
end if;
end if;
-- Load game difficulty settings
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "difficulty");
if Length(List => Nodes_List) > 0 then
Log_Message
(Message => "Loading game difficulty settings...",
Message_Type => EVERYTHING, New_Line => False);
Saved_Node := Item(List => Nodes_List, Index => 0);
New_Game_Settings.Enemy_Damage_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "enemydamagebonus"));
New_Game_Settings.Player_Damage_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "playerdamagebonus"));
New_Game_Settings.Enemy_Melee_Damage_Bonus :=
Bonus_Type'Value
(Get_Attribute
(Elem => Saved_Node, Name => "enemymeleedamagebonus"));
New_Game_Settings.Player_Melee_Damage_Bonus :=
Bonus_Type'Value
(Get_Attribute
(Elem => Saved_Node, Name => "playermeleedamagebonus"));
New_Game_Settings.Experience_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "experiencebonus"));
New_Game_Settings.Reputation_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "reputationbonus"));
New_Game_Settings.Upgrade_Cost_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "upgradecostbonus"));
if Get_Attribute(Elem => Saved_Node, Name => "pricesbonus") /= "" then
New_Game_Settings.Prices_Bonus :=
Bonus_Type'Value
(Get_Attribute(Elem => Saved_Node, Name => "pricesbonus"));
end if;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
end if;
-- Load game date
Log_Message
(Message => "Loading game time...", Message_Type => EVERYTHING,
New_Line => False);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "gamedate");
Saved_Node := Item(List => Nodes_List, Index => 0);
Game_Date.Year :=
Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "year"));
Game_Date.Month :=
Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "month"));
Game_Date.Day :=
Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "day"));
Game_Date.Hour :=
Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "hour"));
Game_Date.Minutes :=
Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "minutes"));
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load sky map
Log_Message
(Message => "Loading map...", Message_Type => EVERYTHING,
New_Line => False);
SkyMap :=
(others =>
(others =>
(BaseIndex => 0, Visited => False, EventIndex => 0,
MissionIndex => 0)));
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "field");
Load_Map_Block :
declare
X, Y: Positive;
begin
Load_Map_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Saved_Node := Item(List => Nodes_List, Index => I);
X := Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "x"));
Y := Natural'Value(Get_Attribute(Elem => Saved_Node, Name => "y"));
SkyMap(X, Y).Visited := True;
end loop Load_Map_Loop;
end Load_Map_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load sky bases
Log_Message
(Message => "Loading bases...", Message_Type => EVERYTHING,
New_Line => False);
LoadBases(SaveData => Save_Data);
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load player ship
Log_Message
(Message => "Loading player ship...", Message_Type => EVERYTHING,
New_Line => False);
LoadPlayerShip(SaveData => Save_Data);
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load known recipes
Log_Message
(Message => "Loading known recipes...", Message_Type => EVERYTHING,
New_Line => False);
Known_Recipes.Clear;
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "recipe");
Load_Known_Recipes_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Known_Recipes.Append
(New_Item =>
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Item(List => Nodes_List, Index => I),
Name => "index")));
end loop Load_Known_Recipes_Loop;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load messages
Log_Message
(Message => "Loading messages...", Message_Type => EVERYTHING,
New_Line => False);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "message");
ClearMessages;
Load_Messages_Block :
declare
Text: Unbounded_String;
M_Type: Message_Type;
Color: Message_Color;
begin
Load_Messages_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Saved_Node := Item(List => Nodes_List, Index => I);
Text :=
To_Unbounded_String
(Source => Node_Value(N => First_Child(N => Saved_Node)));
M_Type :=
Message_Type'Val
(Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "type")));
Color :=
Message_Color'Val
(Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "color")));
RestoreMessage(Message => Text, MType => M_Type, Color => Color);
end loop Load_Messages_Loop;
end Load_Messages_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load events
Log_Message
(Message => "Loading events...", Message_Type => EVERYTHING,
New_Line => False);
Events_List.Clear;
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "event");
Load_Events_Block :
declare
E_Type: Events_Types;
X, Y, Time: Integer;
Data: Unbounded_String;
begin
Load_Events_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Saved_Node := Item(List => Nodes_List, Index => I);
E_Type :=
Events_Types'Val
(Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "type")));
X := Integer'Value(Get_Attribute(Elem => Saved_Node, Name => "x"));
Y := Integer'Value(Get_Attribute(Elem => Saved_Node, Name => "y"));
Time :=
Integer'Value(Get_Attribute(Elem => Saved_Node, Name => "time"));
Data :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Saved_Node, Name => "data"));
case E_Type is
when EnemyShip =>
Events_List.Append
(New_Item =>
(EType => EnemyShip, SkyX => X, SkyY => Y, Time => Time,
ShipIndex => Data));
when AttackOnBase =>
Events_List.Append
(New_Item =>
(EType => AttackOnBase, SkyX => X, SkyY => Y,
Time => Time, ShipIndex => Data));
when Disease =>
Events_List.Append
(New_Item =>
(EType => Disease, SkyX => X, SkyY => Y, Time => Time,
Data => Integer'Value(To_String(Source => Data))));
when DoublePrice =>
Events_List.Append
(New_Item =>
(EType => DoublePrice, SkyX => X, SkyY => Y,
Time => Time, ItemIndex => Data));
when FullDocks =>
Events_List.Append
(New_Item =>
(EType => FullDocks, SkyX => X, SkyY => Y, Time => Time,
Data => Integer'Value(To_String(Source => Data))));
when EnemyPatrol =>
Events_List.Append
(New_Item =>
(EType => EnemyPatrol, SkyX => X, SkyY => Y,
Time => Time, ShipIndex => Data));
when Trader =>
Events_List.Append
(New_Item =>
(EType => Trader, SkyX => X, SkyY => Y, Time => Time,
ShipIndex => Data));
when FriendlyShip =>
Events_List.Append
(New_Item =>
(EType => FriendlyShip, SkyX => X, SkyY => Y,
Time => Time, ShipIndex => Data));
when None | BaseRecovery =>
null;
end case;
SkyMap(Events_List(I + 1).SkyX, Events_List(I + 1).SkyY)
.EventIndex :=
I + 1;
end loop Load_Events_Loop;
end Load_Events_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load game statistics
Log_Message
(Message => "Loading game statistics...", Message_Type => EVERYTHING,
New_Line => False);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "statistics");
Load_Statistics_Block :
declare
Stat_Index, Nodename: Unbounded_String;
Stat_Amount: Positive;
begin
Saved_Node := Item(List => Nodes_List, Index => 0);
GameStats.BasesVisited :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "visitedbases"));
GameStats.MapVisited :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "mapdiscovered"));
GameStats.DistanceTraveled :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "distancetraveled"));
GameStats.AcceptedMissions :=
Natural'Value
(Get_Attribute(Elem => Saved_Node, Name => "acceptedmissions"));
GameStats.Points :=
Positive'Value(Get_Attribute(Elem => Saved_Node, Name => "points"));
Child_Nodes_List := Child_Nodes(N => Saved_Node);
Load_Statistics_Loop :
for I in 0 .. Length(List => Child_Nodes_List) - 1 loop
Nodename :=
To_Unbounded_String
(Source =>
Node_Name(N => Item(List => Child_Nodes_List, Index => I)));
if To_String(Source => Nodename) /= "#text" then
Stat_Index :=
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Item(List => Child_Nodes_List, Index => I),
Name => "index"));
Stat_Amount :=
Positive'Value
(Get_Attribute
(Elem => Item(List => Child_Nodes_List, Index => I),
Name => "amount"));
end if;
if To_String(Source => Nodename) = "destroyedships" then
GameStats.DestroyedShips.Append
(New_Item => (Index => Stat_Index, Amount => Stat_Amount));
elsif To_String(Source => Nodename) = "finishedcrafts" then
GameStats.CraftingOrders.Append
(New_Item => (Index => Stat_Index, Amount => Stat_Amount));
elsif To_String(Source => Nodename) = "finishedmissions" then
GameStats.FinishedMissions.Append
(New_Item => (Index => Stat_Index, Amount => Stat_Amount));
elsif To_String(Source => Nodename) = "finishedgoals" then
GameStats.FinishedGoals.Append
(New_Item => (Index => Stat_Index, Amount => Stat_Amount));
elsif To_String(Source => Nodename) = "killedmobs" then
GameStats.KilledMobs.Append
(New_Item => (Index => Stat_Index, Amount => Stat_Amount));
end if;
end loop Load_Statistics_Loop;
end Load_Statistics_Block;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load current goal
Log_Message
(Message => "Loading current goal...", Message_Type => EVERYTHING,
New_Line => False);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "currentgoal");
CurrentGoal.Index :=
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Item(List => Nodes_List, Index => 0),
Name => "index"));
CurrentGoal.GType :=
GoalTypes'Val
(Integer'Value
(Get_Attribute
(Elem => Item(List => Nodes_List, Index => 0),
Name => "type")));
CurrentGoal.Amount :=
Integer'Value
(Get_Attribute
(Elem => Item(List => Nodes_List, Index => 0), Name => "amount"));
CurrentGoal.TargetIndex :=
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Item(List => Nodes_List, Index => 0),
Name => "target"));
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
-- Load current story
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "currentstory");
if Length(List => Nodes_List) > 0 then
Log_Message
(Message => "Loading current story...", Message_Type => EVERYTHING,
New_Line => False);
Saved_Node := Item(List => Nodes_List, Index => 0);
CurrentStory.Index :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Saved_Node, Name => "index"));
CurrentStory.Step :=
Positive'Value(Get_Attribute(Elem => Saved_Node, Name => "step"));
if Get_Attribute(Elem => Saved_Node, Name => "currentstep") =
"start" then
CurrentStory.CurrentStep := 0;
elsif Get_Attribute(Elem => Saved_Node, Name => "currentstep") =
"finish" then
CurrentStory.CurrentStep := -1;
else
Load_Story_Steps_Loop :
for I in Stories_List(CurrentStory.Index).Steps.Iterate loop
if Stories_List(CurrentStory.Index).Steps(I).Index =
To_Unbounded_String
(Source =>
Get_Attribute
(Elem => Saved_Node, Name => "currentstep")) then
CurrentStory.CurrentStep :=
Steps_Container.To_Index(Position => I);
exit Load_Story_Steps_Loop;
end if;
end loop Load_Story_Steps_Loop;
end if;
CurrentStory.MaxSteps :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "maxsteps"));
CurrentStory.ShowText :=
(if Get_Attribute(Elem => Saved_Node, Name => "showtext") = "Y" then
True
else False);
if Get_Attribute(Elem => Saved_Node, Name => "data") /= "" then
CurrentStory.Data :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Saved_Node, Name => "data"));
end if;
CurrentStory.FinishedStep :=
StepConditionType'Val
(Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "finishedstep")));
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
end if;
-- Load finished stories data
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "finishedstory");
Load_Finished_Stories_Block :
declare
Steps_Amount: Positive;
Temp_Texts: UnboundedString_Container.Vector;
Story_Index: Unbounded_String;
begin
Log_Message
(Message => "Loading finished stories...",
Message_Type => EVERYTHING, New_Line => False);
Load_Finished_Stories_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Saved_Node := Item(List => Nodes_List, Index => I);
Story_Index :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Saved_Node, Name => "index"));
Steps_Amount :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "stepsamount"));
Temp_Texts.Clear;
Child_Nodes_List := Child_Nodes(N => Saved_Node);
Load_Stories_Text_Loop :
for J in 0 .. Length(List => Child_Nodes_List) - 1 loop
Temp_Texts.Append
(New_Item =>
To_Unbounded_String
(Source =>
Node_Value
(N =>
First_Child
(N =>
Item
(List => Child_Nodes_List,
Index => J)))));
end loop Load_Stories_Text_Loop;
FinishedStories.Append
(New_Item =>
(Index => Story_Index, StepsAmount => Steps_Amount,
StepsTexts => Temp_Texts));
end loop Load_Finished_Stories_Loop;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
end Load_Finished_Stories_Block;
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "acceptedmission");
Load_Accepted_Missions_Block :
declare
use Bases;
M_Type: Missions_Types;
Target_X, Target_Y, Start_Base: Natural;
Time, Reward, M_Index: Positive;
Finished: Boolean;
Target: Natural;
Index: Unbounded_String;
Multiplier: RewardMultiplier;
begin
Log_Message
(Message => "Loading accepted missions...",
Message_Type => EVERYTHING, New_Line => False);
Load_Missions_Loop :
for I in 0 .. Length(List => Nodes_List) - 1 loop
Saved_Node := Item(List => Nodes_List, Index => I);
M_Type :=
Missions_Types'Val
(Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "type")));
if M_Type in Deliver | Destroy then
Index :=
To_Unbounded_String
(Source =>
Get_Attribute(Elem => Saved_Node, Name => "target"));
else
Target :=
Integer'Value
(Get_Attribute(Elem => Saved_Node, Name => "target"));
end if;
Time :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "time"));
Target_X :=
Natural'Value
(Get_Attribute(Elem => Saved_Node, Name => "targetx"));
Target_Y :=
Natural'Value
(Get_Attribute(Elem => Saved_Node, Name => "targety"));
Reward :=
Positive'Value
(Get_Attribute(Elem => Saved_Node, Name => "reward"));
Start_Base :=
Natural'Value
(Get_Attribute(Elem => Saved_Node, Name => "startbase"));
Multiplier :=
(if Get_Attribute(Elem => Saved_Node, Name => "multiplier") /= ""
then
RewardMultiplier'Value
(Get_Attribute(Elem => Saved_Node, Name => "multiplier"))
else 1.0);
Finished :=
(if
Get_Attribute
(Elem => Item(List => Nodes_List, Index => I),
Name => "finished") =
"Y"
then True
else False);
case M_Type is
when Deliver =>
AcceptedMissions.Append
(New_Item =>
(MType => Deliver, ItemIndex => Index, Time => Time,
TargetX => Target_X, TargetY => Target_Y,
Reward => Reward, StartBase => Start_Base,
Finished => Finished, Multiplier => Multiplier));
when Destroy =>
AcceptedMissions.Append
(New_Item =>
(MType => Destroy, ShipIndex => Index, Time => Time,
TargetX => Target_X, TargetY => Target_Y,
Reward => Reward, StartBase => Start_Base,
Finished => Finished, Multiplier => Multiplier));
when Patrol =>
AcceptedMissions.Append
(New_Item =>
(MType => Patrol, Target => Target, Time => Time,
TargetX => Target_X, TargetY => Target_Y,
Reward => Reward, StartBase => Start_Base,
Finished => Finished, Multiplier => Multiplier));
when Explore =>
AcceptedMissions.Append
(New_Item =>
(MType => Explore, Target => Target, Time => Time,
TargetX => Target_X, TargetY => Target_Y,
Reward => Reward, StartBase => Start_Base,
Finished => Finished, Multiplier => Multiplier));
when Passenger =>
if Target > 91 then
Target := 91;
end if;
AcceptedMissions.Append
(New_Item =>
(MType => Passenger, Data => Target, Time => Time,
TargetX => Target_X, TargetY => Target_Y,
Reward => Reward, StartBase => Start_Base,
Finished => Finished, Multiplier => Multiplier));
end case;
M_Index := AcceptedMissions.Last_Index;
if Finished then
SkyMap
(Sky_Bases(AcceptedMissions(M_Index).StartBase).Sky_X,
Sky_Bases(AcceptedMissions(M_Index).StartBase).Sky_Y)
.MissionIndex :=
M_Index;
else
SkyMap
(AcceptedMissions(M_Index).TargetX,
AcceptedMissions(M_Index).TargetY)
.MissionIndex :=
M_Index;
end if;
end loop Load_Missions_Loop;
end Load_Accepted_Missions_Block;
-- Load player career
Log_Message
(Message => "Loading player career...", Message_Type => EVERYTHING,
New_Line => False);
Nodes_List :=
DOM.Core.Documents.Get_Elements_By_Tag_Name
(Doc => Save_Data, Tag_Name => "playercareer");
if Length(List => Nodes_List) > 0 then
Saved_Node := Item(List => Nodes_List, Index => 0);
Player_Career :=
To_Unbounded_String
(Source => Get_Attribute(Elem => Saved_Node, Name => "index"));
else
Player_Career :=
Careers_Container.Key(Position => Careers_List.First);
end if;
Log_Message
(Message => "done.", Message_Type => EVERYTHING, New_Line => True,
Time_Stamp => False);
Free(Read => Reader);
Log_Message
(Message => "Finished loading game.", Message_Type => EVERYTHING);
exception
when An_Exception : others =>
Free(Read => Reader);
Player_Ship.Crew.Clear;
raise Save_Game_Invalid_Data
with Exception_Message(X => An_Exception);
end Load_Game;
procedure Generate_Save_Name(Rename_Save: Boolean := False) is
use Ada.Directories;
use Utils;
Old_Save_Name: constant String := To_String(Source => Save_Name);
begin
Generate_Save_Name_Loop :
loop
Save_Name :=
Save_Directory & Player_Ship.Crew(1).Name & "_" & Player_Ship.Name &
"_" & Positive'Image(Get_Random(Min => 100, Max => 999))(2 .. 4) &
".sav";
exit Generate_Save_Name_Loop when not Exists
(Name => To_String(Source => Save_Name)) and
Save_Name /= Old_Save_Name;
end loop Generate_Save_Name_Loop;
if Rename_Save then
if Exists(Name => Old_Save_Name) then
Rename
(Old_Name => Old_Save_Name,
New_Name => To_String(Source => Save_Name));
end if;
end if;
end Generate_Save_Name;
end Game.SaveLoad;
|
with Ada.Streams; use Ada.Streams;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Ada.Streams.Stream_IO.Standard_Files; use Ada.Streams.Stream_IO.Standard_Files;
procedure streamcat is
E : Stream_Element_Array (1 .. 1);
Last : Stream_Element_Offset;
begin
while not End_Of_File (Standard_Input.all) loop
Read (Standard_Input.all, E, Last);
Write (Standard_Output.all, E);
end loop;
end streamcat;
|
-----------------------------------------------------------------------
-- akt-commands-password-remove -- Remove a wallet password
-- 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 Ada.Text_IO;
package body AKT.Commands.Password.Remove is
use type Keystore.Header_Slot_Count_Type;
use type Keystore.Passwords.Keys.Key_Provider_Access;
function Get_Slot (Value : in String) return Keystore.Key_Slot;
function Get_Slot (Value : in String) return Keystore.Key_Slot is
begin
return Keystore.Key_Slot'Value (Value);
exception
when others =>
AKT.Commands.Log.Error (-("Invalid key slot number. "
& "It must be a number in range 1..7."));
raise Error;
end Get_Slot;
-- ------------------------------
-- Remove the wallet password.
-- ------------------------------
overriding
procedure Execute (Command : in out Command_Type;
Name : in String;
Args : in Argument_List'Class;
Context : in out Context_Type) is
pragma Unreferenced (Name);
Path : constant String := Context.Get_Keystore_Path (Args);
Slot : constant Keystore.Key_Slot := Get_Slot (Command.Slot.all);
begin
Setup_Password_Provider (Context);
Setup_Key_Provider (Context);
Context.Wallet.Open (Path => Path,
Info => Context.Info);
if not Context.No_Password_Opt or else Context.Info.Header_Count = 0 then
if Context.Key_Provider /= null then
Context.Wallet.Set_Master_Key (Context.Key_Provider.all);
end if;
Context.Wallet.Unlock (Context.Provider.all, Context.Slot);
Context.Wallet.Remove_Key (Password => Context.Provider.all,
Slot => Slot,
Force => Command.Force);
else
Context.GPG.Load_Secrets (Context.Wallet);
Context.Wallet.Set_Master_Key (Context.GPG);
Context.Wallet.Unlock (Context.GPG, Context.Slot);
Context.Wallet.Remove_Key (Password => Context.GPG,
Slot => Slot,
Force => Command.Force);
end if;
Ada.Text_IO.Put_Line (-("The password was successfully removed."));
exception
when Keystore.Used_Key_Slot =>
AKT.Commands.Log.Error (-("Refusing to erase the key slot used by current password."));
AKT.Commands.Log.Error (-("Use the --force option if you really want "
& "to erase this slot."));
raise Error;
end Execute;
-- ------------------------------
-- Setup the command before parsing the arguments and executing it.
-- ------------------------------
procedure Setup (Command : in out Command_Type;
Config : in out GNAT.Command_Line.Command_Line_Configuration;
Context : in out Context_Type) is
package GC renames GNAT.Command_Line;
begin
Drivers.Command_Type (Command).Setup (Config, Context);
GC.Define_Switch (Config => Config,
Output => Command.Force'Access,
Switch => "-f",
Long_Switch => "--force",
Help => -("Force erase of password used to unlock the keystore"));
GC.Define_Switch (Config => Config,
Output => Command.Slot'Access,
Switch => "-s:",
Long_Switch => "--slot:",
Argument => "SLOT",
Help => -("Defines the key slot to erase (1..7)"));
end Setup;
end AKT.Commands.Password.Remove;
|
------------------------------------------------------------------------------
-- --
-- J E W L . C A N V A S _ I M P L E M E N T A T I O N --
-- --
-- This is the body of a private package containing the internal --
-- implementation details of canvases, as defined in JEWL.Windows. --
-- --
-- Copyright (C) John English 2000. Contact address: je@brighton.ac.uk --
-- This software is released under the terms of the GNU General Public --
-- License and is intended primarily for educational use. Please contact --
-- the author to report bugs, suggestions and modifications. --
-- --
------------------------------------------------------------------------------
-- $Id: jewl-canvas_implementation.adb 1.7 2007/01/08 17:00:00 JE Exp $
------------------------------------------------------------------------------
--
-- $Log: jewl-canvas_implementation.adb $
-- Revision 1.7 2007/01/08 17:00:00 JE
-- * Fixed linker options in JEWL.Win32_Interface to accommodate changes to GNAT
-- GPL 2006 compiler (thanks to John McCormick for this)
-- * Added delay in message loop to avoid the appearance of hogging 100% of CPU
-- time
--
-- Revision 1.6 2001/11/02 16:00:00 JE
-- * Fixed canvas bug when saving an empty canvas
-- * Restore with no prior save now acts as erase
-- * Removed redundant variable declaration in Image function
--
-- Revision 1.5 2001/08/22 15:00:00 JE
-- * Minor bugfix to Get_Text for combo boxes
-- * Minor changes to documentation (including new example involving dialogs)
--
-- Revision 1.4 2001/01/25 09:00:00 je
-- Changes visible to the user:
--
-- * Added support for drawing bitmaps on canvases (Draw_Image operations
-- and new type Image_Type)
-- * Added Play_Sound
-- * Added several new operations on all windows: Get_Origin, Get_Width,
-- Get_Height, Set_Origin, Set_Size and Focus
-- * Added several functions giving screen and window dimensions: Screen_Width,
-- Screen_Height, Frame_Width, Frame_Height, Dialog_Width, Dialog_Height and
-- Menu_Height
-- * Canvases can now handle keyboard events: new constructor and Key_Code added
-- * Added procedure Play_Sound
-- * Operations "+" and "-" added for Point_Type
-- * Pens can now be zero pixels wide
-- * The absolute origin of a frame can now have be specified when the frame
-- is created
-- * Added new File_Dialog operations Add_Filter and Set_Directory
-- * Added Get_Line renames to JEWL.IO for compatibility with Ada.Text_IO
-- * Added all the Get(File,Item) operations mentioned in documentation but
-- unaccountably missing :-(
-- * Documentation updated to reflect the above changes
-- * HTML versions of public package specifications added with links from
-- main documentation pages
--
-- Other internal changes:
--
-- * Canvas fonts, pens etc. now use JEWL.Reference_Counted_Type rather than
-- reinventing this particular wheel, as do images
-- * Various minor code formatting changes: some code reordered for clarity,
-- some comments added or amended,
-- * Changes introduced in 1.2 to support GNAT 3.10 have been reversed, since
-- GNAT 3.10 still couldn't compile this code correctly... ;-(
--
-- Outstanding issues:
--
-- * Optimisation breaks the code (workaround: don't optimise)
--
-- Revision 1.3 2000/07/07 12:00:00 je
-- * JEWL.Simple_Windows added; JEWL.IO modified to use JEWL.Simple_Windows.
-- * JEWL.IO bug fix: Put_Line to file wrote newline to standard output
-- instead of to the file (thanks to Jeff Carter for pointing this out).
-- * Panels fixed so that mouse clicks are passed on correctly to subwindows.
-- * Memos fixed so that tabs are handled properly.
-- * Password feature added to editboxes.
-- * Minor typos fixed in comments within the package sources.
-- * Documentation corrected and updated following comments from Moti Ben-Ari
-- and Don Overheu.
--
-- Revision 1.2 2000/04/18 20:00:00 je
-- * Minor code changes to enable compilation by GNAT 3.10
-- * Minor documentation errors corrected
-- * Some redundant "with" clauses removed
--
-- Revision 1.1 2000/04/09 21:00:00 je
-- Initial revision
--
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Text_IO;
package body JEWL.Canvas_Implementation is
use JEWL.Win32_Interface;
procedure Free is new Ada.Unchecked_Deallocation
(Canvas_Object_Type'Class, Canvas_Object_Ptr);
----------------------------------------------------------------------------
--
-- C A N V A S _ M O N I T O R
--
-- This protected type mediates between the canvas operations and the
-- message loop task.
--
----------------------------------------------------------------------------
protected body Canvas_Monitor is
--------------------------------------------------------------------------
--
-- Clear: delete all objects on the drawing list by restoring to the
-- beginning of the list.
--
procedure Clear is
begin
Save_Pointer := null;
Restore;
end Clear;
--------------------------------------------------------------------------
--
-- Save: record the current position in the drawing list.
--
procedure Save is
begin
Save_Pointer := Last_Object;
end Save;
--------------------------------------------------------------------------
--
-- Restore: truncate the drawing list back to the saved position (or
-- the beginning, if the saved position is null) and delete
-- any objects removed in the process.
--
procedure Restore is
P,Q : Canvas_Object_Ptr;
begin
if Save_Pointer = null then
P := First_Object;
First_Object := null;
Last_Object := null;
else
Last_Object := Save_Pointer;
P := Last_Object.Next;
Last_Object.Next := null;
end if;
while P /= null loop
Q := P;
P := P.Next;
Free (Q);
end loop;
end Restore;
--------------------------------------------------------------------------
--
-- Draw: draw all objects on the drawing list.
--
procedure Draw (Handle : in Win32_HWND;
Font : in Win32_HFONT) is
P : Canvas_Object_Ptr := First_Object;
D : Win32_HDC;
H : Win32_HANDLE;
S : aliased Win32_PAINTSTRUCT;
I : Win32_INT;
L : aliased Win32_LOGBRUSH;
B : Win32_HBRUSH;
begin
L.lbStyle := BS_HOLLOW;
B := CreateBrushIndirect(L'Unchecked_Access);
-- Start drawing using the initial tool set: a transparent brush,
-- standard black pen, and the canvas font
D := BeginPaint (Handle, S'Access);
H := SelectObject(D, B);
H := SelectObject(D, GetStockObject(BLACK_PEN));
H := SelectObject(D, Font);
I := SetBkMode (D, TRANSPARENT);
-- Draw the objects in the drawing list
while P /= null loop
Draw (P.all, D);
P := P.Next;
end loop;
-- Finish painting and destroy the brush
Bool_Dummy := EndPaint (Handle, S'Access);
Bool_Dummy := DeleteObject (B);
end Draw;
--------------------------------------------------------------------------
--
-- Add: add a new object to the end of the drawing list.
--
procedure Add (Object : in Canvas_Object_Ptr) is
begin
if Last_Object = null then
First_Object := Object;
else
Last_Object.Next := Object;
end if;
Last_Object := Object;
Object.Next := null;
end Add;
--------------------------------------------------------------------------
--
-- Set_Brush: store the brush used to erase the background.
--
procedure Set_Brush (Brush : in Win32_HBRUSH) is
begin
Bool_Dummy := DeleteObject(BG_Brush);
BG_Brush := Brush;
end Set_Brush;
--------------------------------------------------------------------------
--
-- Background: get the background brush. This is called by the message
-- loop task in response to a WM_ERASEBKGND message.
--
function Background return Win32_HBRUSH is
begin
return BG_Brush;
end Background;
--------------------------------------------------------------------------
--
-- Set_Start: store the position where the mouse button was pressed.
-- This is called by the message loop task in response to
-- a WM_LBUTTONDOWN message. The end position is initially
-- set to match the start position.
--
procedure Set_Start (X, Y : in Integer) is
begin
Start_X := X;
Start_Y := Y;
End_X := X;
End_Y := Y;
Moved := False;
end Set_Start;
--------------------------------------------------------------------------
--
-- Get_Start: get the position where the mouse button was pressed.
--
procedure Get_Start (X, Y : out Integer) is
begin
X := Start_X;
Y := Start_Y;
end Get_Start;
--------------------------------------------------------------------------
--
-- Set_End: store the current mouse position. This is called by
-- the message loop task in response to a WM_MOUSEMOVE
-- or WM_LBUTTONUP message. The Moved flag is set true
-- to indicate that the mouse has moved.
--
procedure Set_End (X, Y : in Integer) is
begin
End_X := X;
End_Y := Y;
Moved := True;
end Set_End;
--------------------------------------------------------------------------
--
-- Get_End: get the current mouse position. The Moved flag is reset
-- so that Mouse_Moved will return False until the mouse is
-- moved again.
--
procedure Get_End (X, Y : out Integer) is
begin
X := End_X;
Y := End_Y;
Moved := False;
end Get_End;
--------------------------------------------------------------------------
--
-- Set_Button: store the current mouse button state. This is called
-- from the message loop task in response to WM_LBUTTONUP
-- or WM_LBUTTONDOWN messages.
--
procedure Set_Button (B : in Boolean) is
begin
Button := B;
end Set_Button;
--------------------------------------------------------------------------
--
-- Mouse_Down: get the current mouse button state.
--
function Mouse_Down return Boolean is
begin
return Button;
end Mouse_Down;
--------------------------------------------------------------------------
--
-- Mouse_Moved: test if the mouse has moved since the last time that
-- Get_End was called.
--
function Mouse_Moved return Boolean is
begin
return Moved;
end Mouse_Moved;
--------------------------------------------------------------------------
--
-- Set_Key: store the character corresponding to a key that has been
-- pressed. This is called from the message loop in response
-- to WM_CHAR messages.
--
procedure Set_Key (C : in Character) is
begin
Keycode := C;
end Set_Key;
--------------------------------------------------------------------------
--
-- Get_Key: return the character corresponding to a key that has been
-- pressed.
--
procedure Get_Key (C : out Character) is
begin
C := Keycode;
Keycode := ASCII.NUL;
end Get_Key;
end Canvas_Monitor;
----------------------------------------------------------------------------
--
-- D R A W I N G O P E R A T I O N S
--
-- The following procedures are the implementations of Draw for the
-- different types of canvas objects. They are called by Draw in the
-- canvas monitor, which dispatches to the appropriate procedure for
-- each object in the drawing list.
--
----------------------------------------------------------------------------
--
-- Draw a text string
--
procedure Draw (Object : in out Text_Type;
Window : in Win32_HDC) is
I : Win32_INT;
R : aliased Win32_RECT;
W : Win32_UINT;
S : Win32_String := To_Array(Object.Text);
begin
-- Calculate the bounding rectangle
R.Left := Win32_LONG(Object.From.X);
R.Top := Win32_LONG(Object.From.Y);
R.Right := Win32_LONG(Object.To.X);
R.Bottom := Win32_LONG(Object.To.Y);
-- Select the appropriate alignment flag (-1 is used to indicate
-- that the text is not clipped by the bounding rectangle, and 0
-- upwards are values generated by Alignment_Type'Pos).
if Object.Align < 0 then
W := DT_NOCLIP;
elsif Object.Align = 0 then
W := DT_LEFT;
elsif Object.Align = 1 then
W := DT_CENTER;
else
W := DT_RIGHT;
end if;
-- Now draw the text
I := DrawText (Window, To_LPCSTR(S), Win32_INT(Object.Length),
R'Unchecked_Access, W);
end Draw;
----------------------------------------------------------------------------
--
-- Draw a line
--
procedure Draw (Object : in out Line_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := MoveToEx (Window, Win32_INT(Object.From.X),
Win32_INT(Object.From.Y),
null);
Bool_Dummy := LineTo (Window, Win32_INT(Object.To.X),
Win32_INT(Object.To.Y));
end Draw;
----------------------------------------------------------------------------
--
-- Draw a rectangle
--
procedure Draw (Object : in out Rectangle_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := Rectangle (Window, Win32_INT(Object.From.X),
Win32_INT(Object.From.Y),
Win32_INT(Object.To.X),
Win32_INT(Object.To.Y));
end Draw;
----------------------------------------------------------------------------
--
-- Draw a rectangle with rounded corners
--
procedure Draw (Object : in out Rounded_Rectangle_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := RoundRect (Window, Win32_INT(Object.From.X),
Win32_INT(Object.From.Y),
Win32_INT(Object.To.X),
Win32_INT(Object.To.Y),
Win32_INT(Object.Corner.X),
Win32_INT(Object.Corner.Y));
end Draw;
----------------------------------------------------------------------------
--
-- Draw an ellipse
--
procedure Draw (Object : in out Ellipse_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := Ellipse (Window, Win32_INT(Object.From.X),
Win32_INT(Object.From.Y),
Win32_INT(Object.To.X),
Win32_INT(Object.To.Y));
end Draw;
----------------------------------------------------------------------------
--
-- Draw a polyline
--
procedure Draw (Object : in out Polyline_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := Polyline (Window, Object.Points(1)'Unchecked_Access,
Win32_INT(Object.Count));
end Draw;
----------------------------------------------------------------------------
--
-- Draw a polygon
--
procedure Draw (Object : in out Polygon_Type;
Window : in Win32_HDC) is
begin
Bool_Dummy := Polygon (Window, Object.Points(1)'Unchecked_Access,
Win32_INT(Object.Count));
end Draw;
----------------------------------------------------------------------------
--
-- Draw a bitmap
--
procedure Draw (Object : in out Bitmap_Type;
Window : in Win32_HDC) is
H : Win32_HDC := CreateCompatibleDC (Window);
B : Win32_BITMAP;
P : aliased Win32_POINT;
Q : aliased Win32_POINT;
I : Image_Ptr := Image_Ptr(Object.Bitmap.Pointer);
W : Win32_HBITMAP := I.Image;
N : Win32_INT;
begin
Long_Dummy := To_LONG (SelectObject (H, W));
N := SetMapMode (H, GetMapMode(Window));
N := GetObject (W, Win32_INT(Win32_BITMAP'Size/Win32_BYTE'Size),
B'Address);
P := (X => B.bmWidth, Y => B.bmHeight);
Bool_Dummy := DPtoLP (Window, P'Unchecked_Access, 1);
Q := (0,0);
Bool_Dummy := DPtoLP (H, Q'Unchecked_Access, 1);
Bool_Dummy := StretchBlt (Window,
Win32_INT(Object.From.X), Win32_INT(Object.From.Y),
Win32_INT(Object.Width), Win32_INT(Object.Height),
H,
Win32_INT(Q.X), Win32_INT(Q.Y),
Win32_INT(I.Width), Win32_INT(I.Height));
Bool_Dummy := DeleteDC (H);
end Draw;
----------------------------------------------------------------------------
--
-- Select a drawing tool
--
procedure Draw (Object : in out Handle_Type;
Window : in Win32_HDC) is
H : Win32_HGDIOBJ;
W : Win32_HBITMAP :=
Counted_Handle_Type(Object.Handle.Pointer.all).Handle;
begin
H := SelectObject (Window, W);
end Draw;
----------------------------------------------------------------------------
--
-- C O N T R O L L E D T Y P E O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Cleanup: destroy a bitmap handle in an Image_Internals object.
--
procedure Cleanup (Object : in out Image_Internals) is
begin
Bool_Dummy := DeleteObject (Object.Image);
end Cleanup;
----------------------------------------------------------------------------
--
-- Cleanup: destroy a handle to a Windows GDI object.
--
procedure Cleanup (Object : in out Counted_Handle_Type) is
begin
Bool_Dummy := DeleteObject (Object.Handle);
end Cleanup;
----------------------------------------------------------------------------
--
-- Handle: create a reference counted object for a Windows handle.
--
function Handle (Object : Win32_HGDIOBJ) return JEWL.Controlled_Type is
C : JEWL.Controlled_Type;
begin
C.Pointer := new Counted_Handle_Type;
Counted_Handle_Type(C.Pointer.all).Handle := Object;
return C;
end Handle;
end JEWL.Canvas_Implementation;
|
-- simple_example
-- A simple example of the use of parse_args
-- Copyright (c) 2014, James Humphry
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-- PERFORMANCE OF THIS SOFTWARE.
with Parse_Args;
use Parse_Args;
with Parse_Args.Integer_Array_Options;
with Ada.Text_IO;
use Ada.Text_IO;
procedure Simple_Example is
AP : Argument_Parser;
begin
AP.Add_Option(Make_Boolean_Option(False), "help", 'h', Usage => "Display this help text");
AP.Add_Option(Make_Boolean_Option(False), "foo", 'f', Usage => "The foo option");
AP.Add_Option(Make_Boolean_Option(True), "bar", 'b', Usage => "The bar option");
AP.Add_Option(Make_Repeated_Option(0), "baz", 'z',
Usage => "The baz option (can be repeated for more baz)");
AP.Add_Option(Make_Boolean_Option(False), "long-only",
Long_Option => "long-only",
Usage => "The --long-only option has no short version");
AP.Add_Option(Make_Boolean_Option(False), "short-only",
Short_Option => 'x', Long_Option => "-",
Usage => "The -x option has no long version");
AP.Add_Option(Make_Natural_Option(0), "natural", 'n', Usage => "Specify a natural number argument");
AP.Add_Option(Make_Integer_Option(-1), "integer", 'i', Usage => "Specify an integer argument");
AP.Add_Option(Make_String_Option(""), "string", 's', Usage => "Specify a string argument");
AP.Add_Option(Integer_Array_Options.Make_Option, "array", 'a',
Usage => "Specify a comma-separated integer array argument");
AP.Append_Positional(Make_String_Option("INFILE"), "INFILE");
AP.Allow_Tail_Arguments("TAIL-ARGUMENTS");
AP.Set_Prologue("A demonstration of the basic features of the Parse_Args library.");
AP.Parse_Command_Line;
if AP.Parse_Success and then AP.Boolean_Value("help") then
AP.Usage;
elsif AP.Parse_Success then
Put_Line("Command name is: " & AP.Command_Name);
New_Line;
for I in AP.Iterate loop
Put_Line("Option "& Option_Name(I) & " was " &
(if AP(I).Set then "" else "not ") &
"set on the command line. Value: " &
AP(I).Image);
end loop;
New_Line;
Put_Line("There were: " & Integer'Image(Integer(AP.Tail.Length)) & " tail arguments.");
declare
I : Integer := 1;
begin
for J of AP.Tail loop
Put_Line("Argument" & Integer'Image(I) & " is: " & J);
I := I + 1;
end loop;
end;
else
Put_Line("Error while parsing command-line arguments: " & AP.Parse_Message);
end if;
end Simple_Example;
|
with C.stdlib;
with C.sys.types;
with C.sys.uio;
with C.unistd;
package body System.Termination is
pragma Suppress (All_Checks);
New_Line : aliased constant C.char := C.char'Val (10);
procedure Error_Put_Line (S : String) is
iovec : aliased array (0 .. 1) of aliased C.sys.uio.struct_iovec := (
(C.void_ptr (S'Address), S'Length),
(C.void_ptr (New_Line'Address), 1));
Dummy : C.sys.types.ssize_t;
begin
Dummy := C.sys.uio.writev (
C.unistd.STDERR_FILENO,
iovec (0)'Access,
iovec'Length);
end Error_Put_Line;
procedure Force_Abort is
begin
C.stdlib.C_abort;
end Force_Abort;
procedure Register_Exit (Handler : not null Exit_Handler) is
Dummy : C.signed_int;
begin
-- atexit requires handler that has C calling-convention,
-- but Ada procedure having no argument is same as C.
Dummy := C.stdlib.atexit (Handler);
end Register_Exit;
end System.Termination;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2017, 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 System.Storage_Elements;
with Interfaces.C;
with League.Characters;
with League.Strings.Internals;
with Matreshka.Internals.Strings.C;
with Matreshka.Internals.Utf16;
with Matreshka.Internals.Windows;
package body Matreshka.Internals.Settings.Registry is
use Matreshka.Internals.Windows;
use type League.Characters.Universal_Character;
-----------------
-- Windows API --
-----------------
type ACCESS_MASK is new Interfaces.C.unsigned_long;
type REGSAM is new ACCESS_MASK;
type PHKEY is access all HKEY;
type SECURITY_ATTRIBUTES is null record;
type LPSECURITY_ATTRIBUTES is access all SECURITY_ATTRIBUTES;
pragma Convention (C, LPSECURITY_ATTRIBUTES);
KEY_WRITE : constant REGSAM := 16#20006#;
KEY_READ : constant REGSAM := 16#20019#;
use type LONG;
type LPDWORD is access all DWORD;
REG_OPTION_NON_VOLATILE : constant DWORD := 0;
REG_SZ : constant DWORD := 1;
function A_To_HKEY (Value : System.Storage_Elements.Integer_Address)
return HKEY;
---------------
-- A_To_HKEY --
---------------
function A_To_HKEY (Value : System.Storage_Elements.Integer_Address)
return HKEY is
begin
return HKEY (System.Storage_Elements.To_Address (Value));
end A_To_HKEY;
No_HKEY : constant HKEY := HKEY (System.Null_Address);
HKEY_CLASSES_ROOT : constant HKEY := A_To_HKEY (16#8000_0000#);
HKEY_CURRENT_USER : constant HKEY := A_To_HKEY (16#8000_0001#);
HKEY_LOCAL_MACHINE : constant HKEY := A_To_HKEY (16#8000_0002#);
HKEY_USERS : constant HKEY := A_To_HKEY (16#8000_0003#);
function RegOpenKeyEx
(hKey : Registry.HKEY;
lpSubKey : Windows.LPCWSTR;
ulOptions : Interfaces.C.unsigned_long;
samDesired : REGSAM;
phkResult : PHKEY) return LONG;
pragma Import (Stdcall, RegOpenKeyEx, "RegOpenKeyExW");
function RegCreateKeyEx
(hKey : Registry.HKEY;
lpSubKey : Windows.LPCWSTR;
Reserved : Interfaces.C.unsigned_long;
lpClass : Windows.LPWSTR;
dwOptions : DWORD;
samDesired : REGSAM;
lpSecurityAttributes : LPSECURITY_ATTRIBUTES;
phkResult : PHKEY;
lpdwDisposition : LPDWORD) return LONG;
pragma Import (Stdcall, RegCreateKeyEx, "RegCreateKeyExW");
-- function RegCloseKey (hKey : Registry.HKEY) return LONG;
procedure RegCloseKey (hKey : Registry.HKEY);
pragma Import (Stdcall, RegCloseKey, "RegCloseKey");
-- function RegFlushKey (hKey : Registry.HKEY) return LONG;
procedure RegFlushKey (hKey : Registry.HKEY);
pragma Import (Stdcall, RegFlushKey, "RegFlushKey");
function RegSetValueEx
(hKey : Registry.HKEY;
lpSubKey : Windows.LPCWSTR;
Reserved : DWORD;
dwType : DWORD;
lpData : System.Address;
cbData : DWORD) return LONG;
pragma Import (Stdcall, RegSetValueEx, "RegSetValueExW");
function RegQueryValueEx
(hKey : Registry.HKEY;
lpSubKey : Windows.LPCWSTR;
Reserved : LPDWORD;
lpType : LPDWORD;
lpData : System.Address;
lpcbData : LPDWORD) return LONG;
pragma Import (Stdcall, RegQueryValueEx, "RegQueryValueExW");
function Create
(Manager : not null access Abstract_Manager'Class;
Name : League.Strings.Universal_String;
Root : HKEY;
Key : League.Strings.Universal_String;
Read_Only : Boolean) return not null Settings_Access;
-- Creates storage pointing to specified root and key. Read_Only means
-- that subtree is opened for reading only.
procedure Split_Path_Name
(Key : League.Strings.Universal_String;
Path : out League.Strings.Universal_String;
Name : out League.Strings.Universal_String);
-- Split key into path and name parts.
function Open_Or_Create
(Parent : HKEY;
Path : League.Strings.Universal_String) return HKEY;
-- Opens existing path or create new path and returns its handler.
function Open
(Parent : HKEY;
Path : League.Strings.Universal_String) return HKEY;
-- Opens existing path in read-only mode and returns its handler.
HKEY_CURRENT_USER_Name : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("HKEY_CURRENT_USER");
HKEY_LOCAL_MACHINE_Name : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("HKEY_LOCAL_MACHINE");
HKEY_CLASSES_ROOT_Name : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("HKEY_CLASSES_ROOT");
HKEY_USERS_Name : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("HKEY_USERS");
--------------
-- Contains --
--------------
overriding function Contains
(Self : Registry_Settings;
Key : League.Strings.Universal_String) return Boolean
is
Handler : HKEY;
Path : League.Strings.Universal_String;
Name : League.Strings.Universal_String;
Found : Boolean := True;
begin
-- Compute path to open
Split_Path_Name (Key, Path, Name);
-- Try to open path
Handler := Open (Self.Handler, Path);
if Handler /= No_HKEY then
-- Try to retrieve value
if RegQueryValueEx
(Handler,
League.Strings.Internals.Internal (Name).Value (0)'Access,
null,
null,
System.Null_Address,
null) /= 0
then
Found := False;
end if;
RegCloseKey (Handler);
else
Found := False;
end if;
return Found;
end Contains;
------------
-- Create --
------------
function Create
(Manager : not null access Abstract_Manager'Class;
Key : League.Strings.Universal_String;
Read_Only : Boolean) return not null Settings_Access
is
use type League.Strings.Universal_String;
Path : League.Strings.Universal_String := Key;
Separator : Natural;
begin
-- Remove leading backslash if any.
if Path.Element (1) = '\' then
Path := Path.Slice (2, Path.Length);
end if;
Separator := Path.Index ('\');
if Separator = 0 then
Separator := Path.Length + 1;
end if;
if Path.Slice (1, Separator - 1) = HKEY_CURRENT_USER_Name then
return
Create
(Manager,
'\' & Path,
HKEY_CURRENT_USER,
Path.Slice (Separator + 1, Path.Length),
Read_Only);
elsif Path.Slice (1, Separator - 1) = HKEY_LOCAL_MACHINE_Name then
return
Create
(Manager,
'\' & Path,
HKEY_LOCAL_MACHINE,
Path.Slice (Separator + 1, Path.Length),
Read_Only);
elsif Path.Slice (1, Separator - 1) = HKEY_CLASSES_ROOT_Name then
return
Create
(Manager,
'\' & Path,
HKEY_CLASSES_ROOT,
Path.Slice (Separator + 1, Path.Length),
Read_Only);
elsif Path.Slice (1, Separator - 1) = HKEY_USERS_Name then
return
Create
(Manager,
'\' & Path,
HKEY_USERS,
Path.Slice (Separator + 1, Path.Length),
Read_Only);
else
return
Create
(Manager,
'\' & HKEY_LOCAL_MACHINE_Name & '\' & Path,
HKEY_LOCAL_MACHINE,
Path,
Read_Only);
end if;
end Create;
------------
-- Create --
------------
function Create
(Manager : not null access Abstract_Manager'Class;
Name : League.Strings.Universal_String;
Root : HKEY;
Key : League.Strings.Universal_String;
Read_Only : Boolean) return not null Settings_Access is
begin
return Aux : constant not null Settings_Access
:= new Registry_Settings'
(Counter => <>,
Manager => Manager,
Name => Name,
Handler => <>,
Read_Only => Read_Only)
do
declare
Self : Registry_Settings'Class
renames Registry_Settings'Class (Aux.all);
begin
if Self.Read_Only then
-- Open registry to read when Read_Only mode is specified.
Self.Handler := Open (Root, Key);
else
-- In Read_Write mode, try to open first.
Self.Handler := Open_Or_Create (Root, Key);
if Self.Handler = No_HKEY then
-- Fallback to read-only mode and try to open it to read.
Self.Read_Only := True;
Self.Handler := Open (Root, Key);
end if;
end if;
end;
end return;
end Create;
--------------
-- Finalize --
--------------
overriding procedure Finalize
(Self : not null access Registry_Settings) is
begin
if Self.Handler /= No_HKEY then
RegCloseKey (Self.Handler);
Self.Handler := No_HKEY;
end if;
end Finalize;
----------
-- Name --
----------
overriding function Name
(Self : not null access Registry_Settings)
return League.Strings.Universal_String is
begin
return Self.Name;
end Name;
----------
-- Open --
----------
function Open
(Parent : HKEY;
Path : League.Strings.Universal_String) return HKEY
is
Handler : aliased HKEY;
begin
if RegOpenKeyEx
(Parent,
League.Strings.Internals.Internal (Path).Value (0)'Access,
0,
KEY_READ,
Handler'Unchecked_Access) /= 0
then
Handler := No_HKEY;
end if;
return Handler;
end Open;
--------------------
-- Open_Or_Create --
--------------------
function Open_Or_Create
(Parent : HKEY;
Path : League.Strings.Universal_String) return HKEY
is
Handler : aliased HKEY;
begin
if RegOpenKeyEx
(Parent,
League.Strings.Internals.Internal (Path).Value (0)'Access,
0,
KEY_READ or KEY_WRITE,
Handler'Unchecked_Access) /= 0
then
-- Try to create path
if RegCreateKeyEx
(Parent,
League.Strings.Internals.Internal (Path).Value (0)'Access,
0,
null,
REG_OPTION_NON_VOLATILE,
KEY_READ or KEY_WRITE,
null,
Handler'Unchecked_Access,
null) /= 0
then
-- Operation failed.
Handler := No_HKEY;
end if;
end if;
return Handler;
end Open_Or_Create;
------------
-- Remove --
------------
overriding procedure Remove
(Self : in out Registry_Settings;
Key : League.Strings.Universal_String) is
begin
null;
end Remove;
---------------
-- Set_Value --
---------------
overriding procedure Set_Value
(Self : in out Registry_Settings;
Key : League.Strings.Universal_String;
Value : League.Holders.Holder)
is
use type Matreshka.Internals.Utf16.Utf16_String_Index;
Handler : aliased HKEY;
Path : League.Strings.Universal_String;
Name : League.Strings.Universal_String;
V : League.Strings.Universal_String;
begin
if Self.Handler = No_HKEY or Self.Read_Only then
-- Registry can't be modified in read-only mode.
return;
end if;
-- Compute path to open
Split_Path_Name (Key, Path, Name);
-- Try to open path
Handler := Open_Or_Create (Self.Handler, Path);
if Handler = No_HKEY then
-- Operation failed, return.
return;
end if;
-- Extract value.
V := League.Holders.Element (Value);
-- Store string.
if RegSetValueEx
(Handler,
League.Strings.Internals.Internal (Name).Value (0)'Access,
0,
REG_SZ,
League.Strings.Internals.Internal (V).Value (0)'Address,
DWORD ((League.Strings.Internals.Internal (V).Unused + 1) * 2)) /= 0
then
null;
end if;
RegCloseKey (Handler);
end Set_Value;
---------------------
-- Split_Path_Name --
---------------------
procedure Split_Path_Name
(Key : League.Strings.Universal_String;
Path : out League.Strings.Universal_String;
Name : out League.Strings.Universal_String) is
begin
Path := League.Strings.Empty_Universal_String;
Name := Key;
for J in 1 .. Key.Length loop
if Key.Element (J) = '\' then
Path := Key.Slice (1, J - 1);
Name := Key.Slice (J + 1, Key.Length);
exit;
end if;
end loop;
end Split_Path_Name;
----------
-- Sync --
----------
overriding procedure Sync (Self : in out Registry_Settings) is
begin
if Self.Handler /= No_HKEY and not Self.Read_Only then
-- RegFlushKey requires KEY_QUERY_VALUE access right, this right is
-- part of KEY_READ.
RegFlushKey (Self.Handler);
end if;
end Sync;
-----------
-- Value --
-----------
overriding function Value
(Self : Registry_Settings;
Key : League.Strings.Universal_String)
return League.Holders.Holder
is
use Matreshka.Internals.Utf16;
use type DWORD;
Handler : HKEY;
Path : League.Strings.Universal_String;
Name : League.Strings.Universal_String;
V_Type : aliased DWORD;
V_Size : aliased DWORD;
Value : League.Holders.Holder;
begin
-- Compute path to open
Split_Path_Name (Key, Path, Name);
-- Try to open path
Handler := Open (Self.Handler, Path);
if Handler = No_HKEY then
return Value;
end if;
-- Try to retrieve value
if RegQueryValueEx
(Handler,
League.Strings.Internals.Internal (Name).Value (0)'Access,
null,
V_Type'Unchecked_Access,
System.Null_Address,
V_Size'Unchecked_Access) = 0
then
if V_Type = REG_SZ then
declare
V : Matreshka.Internals.Utf16.Utf16_String
(0
.. Matreshka.Internals.Utf16.Utf16_String_Index
(V_Size / 2));
begin
if RegQueryValueEx
(Handler,
League.Strings.Internals.Internal (Name).Value (0)'Access,
null,
V_Type'Unchecked_Access,
V'Address,
V_Size'Unchecked_Access) = 0
then
V (V'Last) := 0;
Value := League.Holders.To_Holder
(Matreshka.Internals.Strings.C.To_Valid_Universal_String
(V (0)'Unchecked_Access));
end if;
end;
end if;
end if;
RegCloseKey (Handler);
return Value;
end Value;
end Matreshka.Internals.Settings.Registry;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- ADA.NUMERICS.BIG_NUMBERS.BIG_REALS --
-- --
-- S p e c --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. In accordance with the copyright of that document, you can freely --
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Strings.Text_Output; use Ada.Strings.Text_Output;
package Ada.Numerics.Big_Numbers.Big_Reals
with Preelaborate
is
type Big_Real is private with
Real_Literal => From_String,
Put_Image => Put_Image;
function Is_Valid (Arg : Big_Real) return Boolean
with
Convention => Intrinsic,
Global => null;
subtype Valid_Big_Real is Big_Real
with Dynamic_Predicate => Is_Valid (Valid_Big_Real),
Predicate_Failure => raise Program_Error;
function "/"
(Num, Den : Big_Integers.Valid_Big_Integer) return Valid_Big_Real
with Global => null;
-- with Pre => (Big_Integers."/=" (Den, Big_Integers.To_Big_Integer (0))
-- or else Constraint_Error);
function Numerator
(Arg : Valid_Big_Real) return Big_Integers.Valid_Big_Integer
with Global => null;
function Denominator (Arg : Valid_Big_Real) return Big_Integers.Big_Positive
with
Post =>
(if Arg = To_Real (0)
then Big_Integers."=" (Denominator'Result,
Big_Integers.To_Big_Integer (1))
else Big_Integers."="
(Big_Integers.Greatest_Common_Divisor
(Numerator (Arg), Denominator'Result),
Big_Integers.To_Big_Integer (1))),
Global => null;
function To_Big_Real
(Arg : Big_Integers.Big_Integer)
return Valid_Big_Real is (Arg / Big_Integers.To_Big_Integer (1))
with Global => null;
function To_Real (Arg : Integer) return Valid_Big_Real is
(Big_Integers.To_Big_Integer (Arg) / Big_Integers.To_Big_Integer (1))
with Global => null;
function "=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function "<" (L, R : Valid_Big_Real) return Boolean with Global => null;
function "<=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function ">" (L, R : Valid_Big_Real) return Boolean with Global => null;
function ">=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function In_Range (Arg, Low, High : Big_Real) return Boolean is
(Low <= Arg and then Arg <= High)
with Global => null;
generic
type Num is digits <>;
package Float_Conversions is
function To_Big_Real (Arg : Num) return Valid_Big_Real
with Global => null;
function From_Big_Real (Arg : Big_Real) return Num
with
Pre => In_Range (Arg,
Low => To_Big_Real (Num'First),
High => To_Big_Real (Num'Last))
or else (raise Constraint_Error),
Global => null;
end Float_Conversions;
generic
type Num is delta <>;
package Fixed_Conversions is
function To_Big_Real (Arg : Num) return Valid_Big_Real
with Global => null;
function From_Big_Real (Arg : Big_Real) return Num
with
Pre => In_Range (Arg,
Low => To_Big_Real (Num'First),
High => To_Big_Real (Num'Last))
or else (raise Constraint_Error),
Global => null;
end Fixed_Conversions;
function To_String (Arg : Valid_Big_Real;
Fore : Field := 2;
Aft : Field := 3;
Exp : Field := 0) return String
with
Post => To_String'Result'First = 1,
Global => null;
function From_String (Arg : String) return Big_Real
with Global => null;
function To_Quotient_String (Arg : Big_Real) return String is
(Big_Integers.To_String (Numerator (Arg)) & " / "
& Big_Integers.To_String (Denominator (Arg)))
with Global => null;
function From_Quotient_String (Arg : String) return Valid_Big_Real
with Global => null;
procedure Put_Image (S : in out Sink'Class; V : Big_Real);
function "+" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "-" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "abs" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "+" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "-" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "*" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "/" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "**" (L : Valid_Big_Real; R : Integer) return Valid_Big_Real
with Global => null;
function Min (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function Max (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
private
type Big_Real is record
Num, Den : Big_Integers.Big_Integer;
end record;
end Ada.Numerics.Big_Numbers.Big_Reals;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ C H 1 1 --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Debug; use Debug;
with Einfo; use Einfo;
with Elists; use Elists;
with Errout; use Errout;
with Exp_Ch7; use Exp_Ch7;
with Exp_Intr; use Exp_Intr;
with Exp_Util; use Exp_Util;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Ch8; use Sem_Ch8;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames; use Snames;
with Stand; use Stand;
with Stringt; use Stringt;
with Targparm; use Targparm;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
package body Exp_Ch11 is
-----------------------
-- Local Subprograms --
-----------------------
procedure Warn_No_Exception_Propagation_Active (N : Node_Id);
-- Generates warning that pragma Restrictions (No_Exception_Propagation)
-- is in effect. Caller then generates appropriate continuation message.
-- N is the node on which the warning is placed.
procedure Warn_If_No_Propagation (N : Node_Id);
-- Called for an exception raise that is not a local raise (and thus cannot
-- be optimized to a goto). Issues warning if No_Exception_Propagation
-- restriction is set. N is the node for the raise or equivalent call.
---------------------------
-- Expand_At_End_Handler --
---------------------------
-- For a handled statement sequence that has a cleanup (At_End_Proc
-- field set), an exception handler of the following form is required:
-- exception
-- when all others =>
-- cleanup call
-- raise;
-- Note: this exception handler is treated rather specially by
-- subsequent expansion in two respects:
-- The normal call to Undefer_Abort is omitted
-- The raise call does not do Defer_Abort
-- This is because the current tasking code seems to assume that
-- the call to the cleanup routine that is made from an exception
-- handler for the abort signal is called with aborts deferred.
-- This expansion is only done if we have front end exception handling.
-- If we have back end exception handling, then the AT END handler is
-- left alone, and cleanups (including the exceptional case) are handled
-- by the back end.
-- In the front end case, the exception handler described above handles
-- the exceptional case. The AT END handler is left in the generated tree
-- and the code generator (e.g. gigi) must still handle proper generation
-- of cleanup calls for the non-exceptional case.
procedure Expand_At_End_Handler (HSS : Node_Id; Blk_Id : Entity_Id) is
Clean : constant Entity_Id := Entity (At_End_Proc (HSS));
Ohandle : Node_Id;
Stmnts : List_Id;
Loc : constant Source_Ptr := No_Location;
-- Location used for expansion. We quite deliberately do not set a
-- specific source location for the expanded handler. This makes
-- sense since really the handler is not associated with specific
-- source. We used to set this to Sloc (Clean), but that caused
-- useless and annoying bouncing around of line numbers in the
-- debugger in some circumstances.
begin
pragma Assert (Present (Clean));
pragma Assert (No (Exception_Handlers (HSS)));
-- Back end exception schemes don't need explicit handlers to
-- trigger AT-END actions on exceptional paths.
if Back_End_Exceptions then
return;
end if;
-- Don't expand an At End handler if we have already had configurable
-- run-time violations, since likely this will just be a matter of
-- generating useless cascaded messages
if Configurable_Run_Time_Violations > 0 then
return;
end if;
-- Don't expand an At End handler if we are not allowing exceptions
-- or if exceptions are transformed into local gotos, and never
-- propagated (No_Exception_Propagation).
if No_Exception_Handlers_Set then
return;
end if;
if Present (Blk_Id) then
Push_Scope (Blk_Id);
end if;
Ohandle :=
Make_Others_Choice (Loc);
Set_All_Others (Ohandle);
Stmnts := New_List (
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Clean, Loc)));
-- Generate reraise statement as last statement of AT-END handler,
-- unless we are under control of No_Exception_Propagation, in which
-- case no exception propagation is possible anyway, so we do not need
-- a reraise (the AT END handler in this case is only for normal exits
-- not for exceptional exits). Also, we flag the Reraise statement as
-- being part of an AT END handler to prevent signalling this reraise
-- as a violation of the restriction when it is not set.
if not Restriction_Active (No_Exception_Propagation) then
declare
Rstm : constant Node_Id := Make_Raise_Statement (Loc);
begin
Set_From_At_End (Rstm);
Append_To (Stmnts, Rstm);
end;
end if;
Set_Exception_Handlers (HSS, New_List (
Make_Implicit_Exception_Handler (Loc,
Exception_Choices => New_List (Ohandle),
Statements => Stmnts)));
Analyze_List (Stmnts, Suppress => All_Checks);
Expand_Exception_Handlers (HSS);
if Present (Blk_Id) then
Pop_Scope;
end if;
end Expand_At_End_Handler;
-------------------------------
-- Expand_Exception_Handlers --
-------------------------------
procedure Expand_Exception_Handlers (HSS : Node_Id) is
Handlrs : constant List_Id := Exception_Handlers (HSS);
Loc : constant Source_Ptr := Sloc (HSS);
Handler : Node_Id;
Others_Choice : Boolean;
Obj_Decl : Node_Id;
Next_Handler : Node_Id;
procedure Expand_Local_Exception_Handlers;
-- This procedure handles the expansion of exception handlers for the
-- optimization of local raise statements into goto statements.
procedure Prepend_Call_To_Handler
(Proc : RE_Id;
Args : List_Id := No_List);
-- Routine to prepend a call to the procedure referenced by Proc at
-- the start of the handler code for the current Handler.
procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id);
-- Raise_S is a raise statement (possibly expanded, and possibly of the
-- form of a Raise_xxx_Error node with a condition. This procedure is
-- called to replace the raise action with the (already analyzed) goto
-- statement passed as Goto_L1. This procedure also takes care of the
-- requirement of inserting a Local_Raise call where possible.
-------------------------------------
-- Expand_Local_Exception_Handlers --
-------------------------------------
-- There are two cases for this transformation. First the case of
-- explicit raise statements. For this case, the transformation we do
-- looks like this. Right now we have for example (where L1, L2 are
-- exception labels)
-- begin
-- ...
-- raise_exception (excep1'identity); -- was raise excep1
-- ...
-- raise_exception (excep2'identity); -- was raise excep2
-- ...
-- exception
-- when excep1 =>
-- estmts1
-- when excep2 =>
-- estmts2
-- end;
-- This gets transformed into:
-- begin
-- L1 : label; -- marked Exception_Junk
-- L2 : label; -- marked Exception_Junk
-- L3 : label; -- marked Exception_Junk
-- begin -- marked Exception_Junk
-- ...
-- local_raise (excep1'address); -- was raise excep1
-- goto L1;
-- ...
-- local_raise (excep2'address); -- was raise excep2
-- goto L2;
-- ...
-- exception
-- when excep1 =>
-- goto L1;
-- when excep2 =>
-- goto L2;
-- end;
-- goto L3; -- skip handler if no raise, marked Exception_Junk
-- <<L1>> -- local excep target label, marked Exception_Junk
-- begin -- marked Exception_Junk
-- estmts1
-- end;
-- goto L3; -- marked Exception_Junk
-- <<L2>> -- marked Exception_Junk
-- begin -- marked Exception_Junk
-- estmts2
-- end;
-- goto L3; -- marked Exception_Junk
-- <<L3>> -- marked Exception_Junk
-- end;
-- Note: the reason we wrap the original statement sequence in an
-- inner block is that there may be raise statements within the
-- sequence of statements in the handlers, and we must ensure that
-- these are properly handled, and in particular, such raise statements
-- must not reenter the same exception handlers.
-- If the restriction No_Exception_Propagation is in effect, then we
-- can omit the exception handlers.
-- begin
-- L1 : label; -- marked Exception_Junk
-- L2 : label; -- marked Exception_Junk
-- L3 : label; -- marked Exception_Junk
-- begin -- marked Exception_Junk
-- ...
-- local_raise (excep1'address); -- was raise excep1
-- goto L1;
-- ...
-- local_raise (excep2'address); -- was raise excep2
-- goto L2;
-- ...
-- end;
-- goto L3; -- skip handler if no raise, marked Exception_Junk
-- <<L1>> -- local excep target label, marked Exception_Junk
-- begin -- marked Exception_Junk
-- estmts1
-- end;
-- goto L3; -- marked Exception_Junk
-- <<L2>> -- marked Exception_Junk
-- begin -- marked Exception_Junk
-- estmts2
-- end;
-- <<L3>> -- marked Exception_Junk
-- end;
-- The second case is for exceptions generated by the back end in one
-- of three situations:
-- 1. Front end generates N_Raise_xxx_Error node
-- 2. Front end sets Do_xxx_Check flag in subexpression node
-- 3. Back end detects a situation where an exception is appropriate
-- In all these cases, the current processing in gigi is to generate a
-- call to the appropriate Rcheck_xx routine (where xx encodes both the
-- exception message and the exception to be raised, Constraint_Error,
-- Program_Error, or Storage_Error.
-- We could handle some subcases of 1 using the same front end expansion
-- into gotos, but even for case 1, we can't handle all cases, since
-- generating gotos in the middle of expressions is not possible (it's
-- possible at the gigi/gcc level, but not at the level of the GNAT
-- tree).
-- In any case, it seems easier to have a scheme which handles all three
-- cases in a uniform manner. So here is how we proceed in this case.
-- This procedure detects all handlers for these three exceptions,
-- Constraint_Error, Program_Error and Storage_Error (including WHEN
-- OTHERS handlers that cover one or more of these cases).
-- If the handler meets the requirements for being the target of a local
-- raise, then the front end does the expansion described previously,
-- creating a label to be used as a goto target to raise the exception.
-- However, no attempt is made in the front end to convert any related
-- raise statements into gotos, e.g. all N_Raise_xxx_Error nodes are
-- left unchanged and passed to the back end.
-- Instead, the front end generates three nodes
-- N_Push_Constraint_Error_Label
-- N_Push_Program_Error_Label
-- N_Push_Storage_Error_Label
-- The Push node is generated at the start of the statements
-- covered by the handler, and has as a parameter the label to be
-- used as the raise target.
-- N_Pop_Constraint_Error_Label
-- N_Pop_Program_Error_Label
-- N_Pop_Storage_Error_Label
-- The Pop node is generated at the end of the covered statements
-- and undoes the effect of the preceding corresponding Push node.
-- In the case where the handler does NOT meet the requirements, the
-- front end will still generate the Push and Pop nodes, but the label
-- field in the Push node will be empty signifying that for this region
-- of code, no optimization is possible.
-- These Push/Pop nodes are inhibited if No_Exception_Handlers is set
-- since they are useless in this case, and in CodePeer mode, where
-- they serve no purpose and can intefere with the analysis.
-- The back end must maintain three stacks, one for each exception case,
-- the Push node pushes an entry onto the corresponding stack, and Pop
-- node pops off the entry. Then instead of calling Rcheck_nn, if the
-- corresponding top stack entry has an non-empty label, a goto is
-- generated. This goto should be preceded by a call to Local_Raise as
-- described above.
-- An example of this transformation is as follows, given:
-- declare
-- A : Integer range 1 .. 10;
-- begin
-- A := B + C;
-- exception
-- when Constraint_Error =>
-- estmts
-- end;
-- gets transformed to:
-- declare
-- A : Integer range 1 .. 10;
-- begin
-- L1 : label;
-- L2 : label;
-- begin
-- %push_constraint_error_label (L1)
-- R1b : constant long_long_integer := long_long_integer?(b) +
-- long_long_integer?(c);
-- [constraint_error when
-- not (R1b in -16#8000_0000# .. 16#7FFF_FFFF#)
-- "overflow check failed"]
-- a := integer?(R1b);
-- %pop_constraint_error_Label
-- exception
-- ...
-- when constraint_error =>
-- goto L1;
-- end;
-- goto L2; -- skip handler when exception not raised
-- <<L1>> -- target label for local exception
-- estmts
-- <<L2>>
-- end;
-- Note: the generated labels and goto statements all have the flag
-- Exception_Junk set True, so that Sem_Ch6.Check_Returns will ignore
-- this generated exception stuff when checking for missing return
-- statements (see circuitry in Check_Statement_Sequence).
-- Note: All of the processing described above occurs only if
-- restriction No_Exception_Propagation applies or debug flag .g is
-- enabled.
CE_Locally_Handled : Boolean := False;
SE_Locally_Handled : Boolean := False;
PE_Locally_Handled : Boolean := False;
-- These three flags indicate whether a handler for the corresponding
-- exception (CE=Constraint_Error, SE=Storage_Error, PE=Program_Error)
-- is present. If so the switch is set to True, the Exception_Label
-- field of the corresponding handler is set, and appropriate Push
-- and Pop nodes are inserted into the code.
Local_Expansion_Required : Boolean := False;
-- Set True if we have at least one handler requiring local raise
-- expansion as described above.
procedure Expand_Local_Exception_Handlers is
procedure Add_Exception_Label (H : Node_Id);
-- H is an exception handler. First check for an Exception_Label
-- already allocated for H. If none, allocate one, set the field in
-- the handler node, add the label declaration, and set the flag
-- Local_Expansion_Required. Note: if Local_Raise_Not_OK is set
-- the call has no effect and Exception_Label is left empty.
procedure Add_Label_Declaration (L : Entity_Id);
-- Add an implicit declaration of the given label to the declaration
-- list in the parent of the current sequence of handled statements.
generic
Exc_Locally_Handled : in out Boolean;
-- Flag indicating whether a local handler for this exception
-- has already been generated.
with function Make_Push_Label (Loc : Source_Ptr) return Node_Id;
-- Function to create a Push_xxx_Label node
with function Make_Pop_Label (Loc : Source_Ptr) return Node_Id;
-- Function to create a Pop_xxx_Label node
procedure Generate_Push_Pop (H : Node_Id);
-- Common code for Generate_Push_Pop_xxx below, used to generate an
-- exception label and Push/Pop nodes for Constraint_Error,
-- Program_Error, or Storage_Error.
-------------------------
-- Add_Exception_Label --
-------------------------
procedure Add_Exception_Label (H : Node_Id) is
begin
if No (Exception_Label (H))
and then not Local_Raise_Not_OK (H)
and then not Special_Exception_Package_Used
then
Local_Expansion_Required := True;
declare
L : constant Entity_Id := Make_Temporary (Sloc (H), 'L');
begin
Set_Exception_Label (H, L);
Add_Label_Declaration (L);
end;
end if;
end Add_Exception_Label;
---------------------------
-- Add_Label_Declaration --
---------------------------
procedure Add_Label_Declaration (L : Entity_Id) is
P : constant Node_Id := Parent (HSS);
Decl_L : constant Node_Id :=
Make_Implicit_Label_Declaration (Loc,
Defining_Identifier => L);
begin
if Declarations (P) = No_List then
Set_Declarations (P, Empty_List);
end if;
Append (Decl_L, Declarations (P));
Analyze (Decl_L);
end Add_Label_Declaration;
-----------------------
-- Generate_Push_Pop --
-----------------------
procedure Generate_Push_Pop (H : Node_Id) is
begin
if Restriction_Active (No_Exception_Handlers)
or else CodePeer_Mode
then
return;
end if;
if Exc_Locally_Handled then
return;
else
Exc_Locally_Handled := True;
end if;
Add_Exception_Label (H);
declare
F : constant Node_Id := First (Statements (HSS));
L : constant Node_Id := Last (Statements (HSS));
Push : constant Node_Id := Make_Push_Label (Sloc (F));
Pop : constant Node_Id := Make_Pop_Label (Sloc (L));
begin
-- We make sure that a call to Get_Local_Raise_Call_Entity is
-- made during front end processing, so that when we need it
-- in the back end, it will already be available and loaded.
Discard_Node (Get_Local_Raise_Call_Entity);
-- Prepare and insert Push and Pop nodes
Set_Exception_Label (Push, Exception_Label (H));
Insert_Before (F, Push);
Set_Analyzed (Push);
Insert_After (L, Pop);
Set_Analyzed (Pop);
end;
end Generate_Push_Pop;
-- Local declarations
Loc : constant Source_Ptr := Sloc (HSS);
Stmts : List_Id := No_List;
Choice : Node_Id;
Excep : Entity_Id;
procedure Generate_Push_Pop_For_Constraint_Error is
new Generate_Push_Pop
(Exc_Locally_Handled => CE_Locally_Handled,
Make_Push_Label => Make_Push_Constraint_Error_Label,
Make_Pop_Label => Make_Pop_Constraint_Error_Label);
-- If no Push/Pop has been generated for CE yet, then set the flag
-- CE_Locally_Handled, allocate an Exception_Label for handler H (if
-- not already done), and generate Push/Pop nodes for the exception
-- label at the start and end of the statements of HSS.
procedure Generate_Push_Pop_For_Program_Error is
new Generate_Push_Pop
(Exc_Locally_Handled => PE_Locally_Handled,
Make_Push_Label => Make_Push_Program_Error_Label,
Make_Pop_Label => Make_Pop_Program_Error_Label);
-- If no Push/Pop has been generated for PE yet, then set the flag
-- PE_Locally_Handled, allocate an Exception_Label for handler H (if
-- not already done), and generate Push/Pop nodes for the exception
-- label at the start and end of the statements of HSS.
procedure Generate_Push_Pop_For_Storage_Error is
new Generate_Push_Pop
(Exc_Locally_Handled => SE_Locally_Handled,
Make_Push_Label => Make_Push_Storage_Error_Label,
Make_Pop_Label => Make_Pop_Storage_Error_Label);
-- If no Push/Pop has been generated for SE yet, then set the flag
-- SE_Locally_Handled, allocate an Exception_Label for handler H (if
-- not already done), and generate Push/Pop nodes for the exception
-- label at the start and end of the statements of HSS.
-- Start of processing for Expand_Local_Exception_Handlers
begin
-- No processing if all exception handlers will get removed
if Debug_Flag_Dot_X then
return;
end if;
-- See for each handler if we have any local raises to expand
Handler := First_Non_Pragma (Handlrs);
while Present (Handler) loop
-- Note, we do not test Local_Raise_Not_OK here, because in the
-- case of Push/Pop generation we want to generate push with a
-- null label. The Add_Exception_Label routine has no effect if
-- Local_Raise_Not_OK is set, so this works as required.
if Present (Local_Raise_Statements (Handler)) then
Add_Exception_Label (Handler);
end if;
-- If we are doing local raise to goto optimization (restriction
-- No_Exception_Propagation set or debug flag .g set), then check
-- to see if handler handles CE, PE, SE and if so generate the
-- appropriate push/pop sequence for the back end.
if (Debug_Flag_Dot_G
or else Restriction_Active (No_Exception_Propagation))
and then Has_Local_Raise (Handler)
then
Choice := First (Exception_Choices (Handler));
while Present (Choice) loop
if Nkind (Choice) = N_Others_Choice
and then not All_Others (Choice)
then
Generate_Push_Pop_For_Constraint_Error (Handler);
Generate_Push_Pop_For_Program_Error (Handler);
Generate_Push_Pop_For_Storage_Error (Handler);
elsif Is_Entity_Name (Choice) then
Excep := Get_Renamed_Entity (Entity (Choice));
if Excep = Standard_Constraint_Error then
Generate_Push_Pop_For_Constraint_Error (Handler);
elsif Excep = Standard_Program_Error then
Generate_Push_Pop_For_Program_Error (Handler);
elsif Excep = Standard_Storage_Error then
Generate_Push_Pop_For_Storage_Error (Handler);
end if;
end if;
Next (Choice);
end loop;
end if;
Next_Non_Pragma (Handler);
end loop;
-- Nothing to do if no handlers requiring the goto transformation
if not (Local_Expansion_Required) then
return;
end if;
-- Prepare to do the transformation
declare
-- L3 is the label to exit the HSS
L3_Dent : constant Entity_Id := Make_Temporary (Loc, 'L');
Labl_L3 : constant Node_Id :=
Make_Label (Loc,
Identifier => New_Occurrence_Of (L3_Dent, Loc));
Blk_Stm : Node_Id;
Relmt : Elmt_Id;
begin
Set_Exception_Junk (Labl_L3);
Add_Label_Declaration (L3_Dent);
-- Wrap existing statements and handlers in an inner block
Blk_Stm :=
Make_Block_Statement (Loc,
Handled_Statement_Sequence => Relocate_Node (HSS));
Set_Exception_Junk (Blk_Stm);
Rewrite (HSS,
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (Blk_Stm),
End_Label => Relocate_Node (End_Label (HSS))));
-- Set block statement as analyzed, we don't want to actually call
-- Analyze on this block, it would cause a recursion in exception
-- handler processing which would mess things up.
Set_Analyzed (Blk_Stm);
-- Now loop through the exception handlers to deal with those that
-- are targets of local raise statements.
Handler := First_Non_Pragma (Handlrs);
while Present (Handler) loop
if Present (Exception_Label (Handler)) then
-- This handler needs the goto expansion
declare
Loc : constant Source_Ptr := Sloc (Handler);
-- L1 is the start label for this handler
L1_Dent : constant Entity_Id := Exception_Label (Handler);
Labl_L1 : constant Node_Id :=
Make_Label (Loc,
Identifier =>
New_Occurrence_Of (L1_Dent, Loc));
-- Jump to L1 to be used as replacement for the original
-- handler (used in the case where exception propagation
-- may still occur).
Name_L1 : constant Node_Id :=
New_Occurrence_Of (L1_Dent, Loc);
Goto_L1 : constant Node_Id :=
Make_Goto_Statement (Loc,
Name => Name_L1);
-- Jump to L3 to be used at the end of handler
Name_L3 : constant Node_Id :=
New_Occurrence_Of (L3_Dent, Loc);
Goto_L3 : constant Node_Id :=
Make_Goto_Statement (Loc,
Name => Name_L3);
H_Stmts : constant List_Id := Statements (Handler);
begin
Set_Exception_Junk (Labl_L1);
Set_Exception_Junk (Goto_L3);
-- Note: we do NOT set Exception_Junk in Goto_L1, since
-- this is a real transfer of control that we want the
-- Sem_Ch6.Check_Returns procedure to recognize properly.
-- Replace handler by a goto L1. We can mark this as
-- analyzed since it is fully formed, and we don't
-- want it going through any further checks. We save
-- the last statement location in the goto L1 node for
-- the benefit of Sem_Ch6.Check_Returns.
Set_Statements (Handler, New_List (Goto_L1));
Set_Analyzed (Goto_L1);
Set_Etype (Name_L1, Standard_Void_Type);
-- Now replace all the raise statements by goto L1
if Present (Local_Raise_Statements (Handler)) then
Relmt := First_Elmt (Local_Raise_Statements (Handler));
while Present (Relmt) loop
declare
Raise_S : constant Node_Id := Node (Relmt);
RLoc : constant Source_Ptr := Sloc (Raise_S);
Name_L1 : constant Node_Id :=
New_Occurrence_Of (L1_Dent, Loc);
Goto_L1 : constant Node_Id :=
Make_Goto_Statement (RLoc,
Name => Name_L1);
begin
-- Replace raise by goto L1
Set_Analyzed (Goto_L1);
Set_Etype (Name_L1, Standard_Void_Type);
Replace_Raise_By_Goto (Raise_S, Goto_L1);
end;
Next_Elmt (Relmt);
end loop;
end if;
-- Add a goto L3 at end of statement list in block. The
-- first time, this is what skips over the exception
-- handlers in the normal case. Subsequent times, it
-- terminates the execution of the previous handler code,
-- and skips subsequent handlers.
Stmts := Statements (HSS);
Insert_After (Last (Stmts), Goto_L3);
Set_Analyzed (Goto_L3);
Set_Etype (Name_L3, Standard_Void_Type);
-- Now we drop the label that marks the handler start,
-- followed by the statements of the handler.
Set_Etype (Identifier (Labl_L1), Standard_Void_Type);
Insert_After_And_Analyze (Last (Stmts), Labl_L1);
declare
Loc : constant Source_Ptr := Sloc (First (H_Stmts));
Blk : constant Node_Id :=
Make_Block_Statement (Loc,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => H_Stmts));
begin
Set_Exception_Junk (Blk);
Insert_After_And_Analyze (Last (Stmts), Blk);
end;
end;
-- Here if we have local raise statements but the handler is
-- not suitable for processing with a local raise. In this
-- case we have to generate possible diagnostics.
elsif Has_Local_Raise (Handler)
and then Local_Raise_Statements (Handler) /= No_Elist
then
Relmt := First_Elmt (Local_Raise_Statements (Handler));
while Present (Relmt) loop
Warn_If_No_Propagation (Node (Relmt));
Next_Elmt (Relmt);
end loop;
end if;
Next (Handler);
end loop;
-- Only remaining step is to drop the L3 label and we are done
Set_Etype (Identifier (Labl_L3), Standard_Void_Type);
-- If we had at least one handler, then we drop the label after
-- the last statement of that handler.
if Stmts /= No_List then
Insert_After_And_Analyze (Last (Stmts), Labl_L3);
-- Otherwise we have removed all the handlers (this results from
-- use of pragma Restrictions (No_Exception_Propagation), and we
-- drop the label at the end of the statements of the HSS.
else
Insert_After_And_Analyze (Last (Statements (HSS)), Labl_L3);
end if;
return;
end;
end Expand_Local_Exception_Handlers;
-----------------------------
-- Prepend_Call_To_Handler --
-----------------------------
procedure Prepend_Call_To_Handler
(Proc : RE_Id;
Args : List_Id := No_List)
is
Ent : constant Entity_Id := RTE (Proc);
begin
-- If we have no Entity, then we are probably in no run time mode or
-- some weird error has occurred. In either case do nothing. Note use
-- of No_Location to hide this code from the debugger, so single
-- stepping doesn't jump back and forth.
if Present (Ent) then
declare
Call : constant Node_Id :=
Make_Procedure_Call_Statement (No_Location,
Name => New_Occurrence_Of (RTE (Proc), No_Location),
Parameter_Associations => Args);
begin
Prepend_To (Statements (Handler), Call);
Analyze (Call, Suppress => All_Checks);
end;
end if;
end Prepend_Call_To_Handler;
---------------------------
-- Replace_Raise_By_Goto --
---------------------------
procedure Replace_Raise_By_Goto (Raise_S : Node_Id; Goto_L1 : Node_Id) is
Loc : constant Source_Ptr := Sloc (Raise_S);
Excep : Entity_Id;
LR : Node_Id;
Cond : Node_Id;
Orig : Node_Id;
begin
-- If we have a null statement, it means that there is no replacement
-- needed (typically this results from a suppressed check).
if Nkind (Raise_S) = N_Null_Statement then
return;
-- Test for Raise_xxx_Error
elsif Nkind (Raise_S) = N_Raise_Constraint_Error then
Excep := Standard_Constraint_Error;
Cond := Condition (Raise_S);
elsif Nkind (Raise_S) = N_Raise_Storage_Error then
Excep := Standard_Storage_Error;
Cond := Condition (Raise_S);
elsif Nkind (Raise_S) = N_Raise_Program_Error then
Excep := Standard_Program_Error;
Cond := Condition (Raise_S);
-- The only other possibility is a node that is or used to be a
-- simple raise statement. Note that the string expression in the
-- original Raise statement is ignored.
else
Orig := Original_Node (Raise_S);
pragma Assert (Nkind (Orig) = N_Raise_Statement
and then Present (Name (Orig)));
Excep := Entity (Name (Orig));
Cond := Empty;
end if;
-- Here Excep is the exception to raise, and Cond is the condition
-- First prepare the call to Local_Raise (excep'address).
if RTE_Available (RE_Local_Raise) then
LR :=
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Local_Raise), Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Address),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Excep, Loc),
Attribute_Name => Name_Identity))));
-- Use null statement if Local_Raise not available
else
LR :=
Make_Null_Statement (Loc);
end if;
-- If there is no condition, we rewrite as
-- begin
-- Local_Raise (excep'Identity);
-- goto L1;
-- end;
if No (Cond) then
Rewrite (Raise_S,
Make_Block_Statement (Loc,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (LR, Goto_L1))));
Set_Exception_Junk (Raise_S);
-- If there is a condition, we rewrite as
-- if condition then
-- Local_Raise (excep'Identity);
-- goto L1;
-- end if;
else
Rewrite (Raise_S,
Make_If_Statement (Loc,
Condition => Cond,
Then_Statements => New_List (LR, Goto_L1)));
end if;
Analyze (Raise_S);
end Replace_Raise_By_Goto;
-- Start of processing for Expand_Exception_Handlers
begin
Expand_Local_Exception_Handlers;
-- Loop through handlers
Handler := First_Non_Pragma (Handlrs);
Handler_Loop : while Present (Handler) loop
Process_Statements_For_Controlled_Objects (Handler);
Next_Handler := Next_Non_Pragma (Handler);
-- Remove source handler if gnat debug flag .x is set
if Debug_Flag_Dot_X and then Comes_From_Source (Handler) then
Remove (Handler);
-- Remove handler if no exception propagation, generating a warning
-- if a source generated handler was not the target of a local raise.
else
if not Has_Local_Raise (Handler)
and then Comes_From_Source (Handler)
then
Warn_If_No_Local_Raise (Handler);
end if;
if No_Exception_Propagation_Active then
Remove (Handler);
-- Exception handler is active and retained and must be processed
else
-- If an exception occurrence is present, then we must declare
-- it and initialize it from the value stored in the TSD
-- declare
-- name : Exception_Occurrence;
-- begin
-- Save_Occurrence (name, Get_Current_Excep.all)
-- ...
-- end;
-- This expansion is only performed when using front-end
-- exceptions. Gigi will insert a call to initialize the
-- choice parameter.
if Present (Choice_Parameter (Handler))
and then (Front_End_Exceptions
or else CodePeer_Mode)
then
declare
Cparm : constant Entity_Id := Choice_Parameter (Handler);
Cloc : constant Source_Ptr := Sloc (Cparm);
Hloc : constant Source_Ptr := Sloc (Handler);
Save : Node_Id;
begin
-- Note: No_Location used to hide code from the debugger,
-- so single stepping doesn't jump back and forth.
Save :=
Make_Procedure_Call_Statement (No_Location,
Name =>
New_Occurrence_Of
(RTE (RE_Save_Occurrence), No_Location),
Parameter_Associations => New_List (
New_Occurrence_Of (Cparm, No_Location),
Make_Explicit_Dereference (No_Location,
Prefix =>
Make_Function_Call (No_Location,
Name =>
Make_Explicit_Dereference (No_Location,
Prefix =>
New_Occurrence_Of
(RTE (RE_Get_Current_Excep),
No_Location))))));
Mark_Rewrite_Insertion (Save);
Prepend (Save, Statements (Handler));
Obj_Decl :=
Make_Object_Declaration (Cloc,
Defining_Identifier => Cparm,
Object_Definition =>
New_Occurrence_Of
(RTE (RE_Exception_Occurrence), Cloc));
Set_No_Initialization (Obj_Decl, True);
Rewrite (Handler,
Make_Exception_Handler (Hloc,
Choice_Parameter => Empty,
Exception_Choices => Exception_Choices (Handler),
Statements => New_List (
Make_Block_Statement (Hloc,
Declarations => New_List (Obj_Decl),
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Hloc,
Statements => Statements (Handler))))));
-- Local raise statements can't occur, since exception
-- handlers with choice parameters are not allowed when
-- No_Exception_Propagation applies, so set attributes
-- accordingly.
Set_Local_Raise_Statements (Handler, No_Elist);
Set_Local_Raise_Not_OK (Handler);
Analyze_List
(Statements (Handler), Suppress => All_Checks);
end;
end if;
-- For the normal case, we have to worry about the state of
-- abort deferral. Generally, we defer abort during runtime
-- handling of exceptions. When control is passed to the
-- handler, then in the normal case we undefer aborts. In
-- any case this entire handling is relevant only if aborts
-- are allowed.
if Abort_Allowed
and then not ZCX_Exceptions
then
-- There are some special cases in which we do not do the
-- undefer. In particular a finalization (AT END) handler
-- wants to operate with aborts still deferred.
-- We also suppress the call if this is the special handler
-- for Abort_Signal, since if we are aborting, we want to
-- keep aborts deferred (one abort is enough).
-- If abort really needs to be deferred the expander must
-- add this call explicitly, see
-- Expand_N_Asynchronous_Select.
Others_Choice :=
Nkind (First (Exception_Choices (Handler))) =
N_Others_Choice;
if (Others_Choice
or else Entity (First (Exception_Choices (Handler))) /=
Stand.Abort_Signal)
and then not
(Others_Choice
and then
All_Others (First (Exception_Choices (Handler))))
then
Prepend_Call_To_Handler (RE_Abort_Undefer);
end if;
end if;
end if;
end if;
Handler := Next_Handler;
end loop Handler_Loop;
-- If all handlers got removed, then remove the list. Note we cannot
-- reference HSS here, since expanding local handlers may have buried
-- the handlers in an inner block.
if Is_Empty_List (Handlrs) then
Set_Exception_Handlers (Parent (Handlrs), No_List);
end if;
end Expand_Exception_Handlers;
------------------------------------
-- Expand_N_Exception_Declaration --
------------------------------------
-- Generates:
-- exceptE : constant String := "A.B.EXCEP"; -- static data
-- except : exception_data :=
-- (Handled_By_Other => False,
-- Lang => 'A',
-- Name_Length => exceptE'Length,
-- Full_Name => exceptE'Address,
-- HTable_Ptr => null,
-- Foreign_Data => null,
-- Raise_Hook => null);
-- (protecting test only needed if not at library level)
-- exceptF : Boolean := True -- static data
-- if exceptF then
-- exceptF := False;
-- Register_Exception (except'Unchecked_Access);
-- end if;
procedure Expand_N_Exception_Declaration (N : Node_Id) is
Id : constant Entity_Id := Defining_Identifier (N);
Loc : constant Source_Ptr := Sloc (N);
procedure Force_Static_Allocation_Of_Referenced_Objects
(Aggregate : Node_Id);
-- A specialized solution to one particular case of an ugly problem
--
-- The given aggregate includes an Unchecked_Conversion as one of the
-- component values. The call to Analyze_And_Resolve below ends up
-- calling Exp_Ch4.Expand_N_Unchecked_Type_Conversion, which may decide
-- to introduce a (constant) temporary and then obtain the component
-- value by evaluating the temporary.
--
-- In the case of an exception declared within a subprogram (or any
-- other dynamic scope), this is a bad transformation. The exception
-- object is marked as being Statically_Allocated but the temporary is
-- not. If the initial value of a Statically_Allocated declaration
-- references a dynamically allocated object, this prevents static
-- initialization of the object.
--
-- We cope with this here by marking the temporary Statically_Allocated.
-- It might seem cleaner to generalize this utility and then use it to
-- enforce a rule that the entities referenced in the declaration of any
-- "hoisted" (i.e., Is_Statically_Allocated and not Is_Library_Level)
-- entity must also be either Library_Level or hoisted. It turns out
-- that this would be incompatible with the current treatment of an
-- object which is local to a subprogram, subject to an Export pragma,
-- not subject to an address clause, and whose declaration contains
-- references to other local (non-hoisted) objects (e.g., in the initial
-- value expression).
function Null_String return String_Id;
-- Build a null-terminated empty string
---------------------------------------------------
-- Force_Static_Allocation_Of_Referenced_Objects --
---------------------------------------------------
procedure Force_Static_Allocation_Of_Referenced_Objects
(Aggregate : Node_Id)
is
function Fixup_Node (N : Node_Id) return Traverse_Result;
-- If the given node references a dynamically allocated object, then
-- correct the declaration of the object.
----------------
-- Fixup_Node --
----------------
function Fixup_Node (N : Node_Id) return Traverse_Result is
begin
if Nkind (N) in N_Has_Entity
and then Present (Entity (N))
and then not Is_Library_Level_Entity (Entity (N))
-- Note: the following test is not needed but it seems cleaner
-- to do this test (this would be more important if procedure
-- Force_Static_Allocation_Of_Referenced_Objects recursively
-- traversed the declaration of an entity after marking it as
-- statically allocated).
and then not Is_Statically_Allocated (Entity (N))
then
Set_Is_Statically_Allocated (Entity (N));
end if;
return OK;
end Fixup_Node;
procedure Fixup_Tree is new Traverse_Proc (Fixup_Node);
-- Start of processing for Force_Static_Allocation_Of_Referenced_Objects
begin
Fixup_Tree (Aggregate);
end Force_Static_Allocation_Of_Referenced_Objects;
-----------------
-- Null_String --
-----------------
function Null_String return String_Id is
begin
Start_String;
Store_String_Char (Get_Char_Code (ASCII.NUL));
return End_String;
end Null_String;
-- Local variables
Ex_Id : Entity_Id;
Ex_Val : String_Id;
Flag_Id : Entity_Id;
L : List_Id;
-- Start of processing for Expand_N_Exception_Declaration
begin
-- Nothing to do when generating C code
if Modify_Tree_For_C then
return;
end if;
-- Definition of the external name: nam : constant String := "A.B.NAME";
Ex_Id :=
Make_Defining_Identifier (Loc, New_External_Name (Chars (Id), 'E'));
-- Do not generate an external name if the exception declaration is
-- subject to pragma Discard_Names. Use a null-terminated empty name
-- to ensure that Ada.Exceptions.Exception_Name functions properly.
if Global_Discard_Names or else Discard_Names (Ex_Id) then
Ex_Val := Null_String;
-- Otherwise generate the fully qualified name of the exception
else
Ex_Val := Fully_Qualified_Name_String (Id);
end if;
Insert_Action (N,
Make_Object_Declaration (Loc,
Defining_Identifier => Ex_Id,
Constant_Present => True,
Object_Definition => New_Occurrence_Of (Standard_String, Loc),
Expression => Make_String_Literal (Loc, Ex_Val)));
Set_Is_Statically_Allocated (Ex_Id);
-- Create the aggregate list for type Standard.Exception_Type:
-- Handled_By_Other component: False
L := Empty_List;
Append_To (L, New_Occurrence_Of (Standard_False, Loc));
-- Lang component: 'A'
Append_To (L,
Make_Character_Literal (Loc,
Chars => Name_uA,
Char_Literal_Value => UI_From_Int (Character'Pos ('A'))));
-- Name_Length component: Nam'Length
Append_To (L,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ex_Id, Loc),
Attribute_Name => Name_Length));
-- Full_Name component: Standard.A_Char!(Nam'Address)
-- The unchecked conversion causes capacity issues for CodePeer in some
-- cases and is never useful, so we set the Full_Name component to null
-- instead for CodePeer.
if CodePeer_Mode then
Append_To (L, Make_Null (Loc));
else
Append_To (L, Unchecked_Convert_To (Standard_A_Char,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ex_Id, Loc),
Attribute_Name => Name_Address)));
end if;
-- HTable_Ptr component: null
Append_To (L, Make_Null (Loc));
-- Foreign_Data component: null
Append_To (L, Make_Null (Loc));
-- Raise_Hook component: null
Append_To (L, Make_Null (Loc));
Set_Expression (N, Make_Aggregate (Loc, Expressions => L));
Analyze_And_Resolve (Expression (N), Etype (Id));
Force_Static_Allocation_Of_Referenced_Objects (Expression (N));
-- Register_Exception (except'Unchecked_Access);
if not No_Exception_Handlers_Set
and then not Restriction_Active (No_Exception_Registration)
then
L := New_List (
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Register_Exception), Loc),
Parameter_Associations => New_List (
Unchecked_Convert_To (RTE (RE_Exception_Data_Ptr),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Id, Loc),
Attribute_Name => Name_Unrestricted_Access)))));
Set_Register_Exception_Call (Id, First (L));
if not Is_Library_Level_Entity (Id) then
Flag_Id :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Id), 'F'));
Insert_Action (N,
Make_Object_Declaration (Loc,
Defining_Identifier => Flag_Id,
Object_Definition =>
New_Occurrence_Of (Standard_Boolean, Loc),
Expression =>
New_Occurrence_Of (Standard_True, Loc)));
Set_Is_Statically_Allocated (Flag_Id);
Append_To (L,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Flag_Id, Loc),
Expression => New_Occurrence_Of (Standard_False, Loc)));
Insert_After_And_Analyze (N,
Make_Implicit_If_Statement (N,
Condition => New_Occurrence_Of (Flag_Id, Loc),
Then_Statements => L));
else
Insert_List_After_And_Analyze (N, L);
end if;
end if;
end Expand_N_Exception_Declaration;
---------------------------------------------
-- Expand_N_Handled_Sequence_Of_Statements --
---------------------------------------------
procedure Expand_N_Handled_Sequence_Of_Statements (N : Node_Id) is
begin
-- Expand exception handlers
if Present (Exception_Handlers (N))
and then not Restriction_Active (No_Exception_Handlers)
then
Expand_Exception_Handlers (N);
end if;
-- If local exceptions are being expanded, the previous call will
-- have rewritten the construct as a block and reanalyzed it. No
-- further expansion is needed.
if Analyzed (N) then
return;
end if;
-- Add cleanup actions if required. No cleanup actions are needed in
-- thunks associated with interfaces, because they only displace the
-- pointer to the object. For extended return statements, we need
-- cleanup actions if the Handled_Statement_Sequence contains generated
-- objects of controlled types, for example. We do not want to clean up
-- the return object.
if Nkind (Parent (N)) not in N_Accept_Statement
| N_Extended_Return_Statement
| N_Package_Body
and then not Delay_Cleanups (Current_Scope)
and then not Is_Thunk (Current_Scope)
then
Expand_Cleanup_Actions (Parent (N));
elsif Nkind (Parent (N)) = N_Extended_Return_Statement
and then Handled_Statement_Sequence (Parent (N)) = N
and then not Delay_Cleanups (Current_Scope)
then
pragma Assert (not Is_Thunk (Current_Scope));
Expand_Cleanup_Actions (Parent (N));
else
Set_First_Real_Statement (N, First (Statements (N)));
end if;
end Expand_N_Handled_Sequence_Of_Statements;
-------------------------------------
-- Expand_N_Raise_Constraint_Error --
-------------------------------------
procedure Expand_N_Raise_Constraint_Error (N : Node_Id) is
begin
-- We adjust the condition to deal with the C/Fortran boolean case. This
-- may well not be necessary, as all such conditions are generated by
-- the expander and probably are all standard boolean, but who knows
-- what strange optimization in future may require this adjustment.
Adjust_Condition (Condition (N));
-- Now deal with possible local raise handling
Possible_Local_Raise (N, Standard_Constraint_Error);
end Expand_N_Raise_Constraint_Error;
-------------------------------
-- Expand_N_Raise_Expression --
-------------------------------
procedure Expand_N_Raise_Expression (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
RCE : Node_Id;
begin
Possible_Local_Raise (N, Entity (Name (N)));
-- Later we must teach the back end/gigi how to deal with this, but
-- for now we will assume the type is Standard_Boolean and transform
-- the node to:
-- do
-- raise X [with string]
-- in
-- raise Constraint_Error;
-- unless the flag Convert_To_Return_False is set, in which case
-- the transformation is to:
-- do
-- return False;
-- in
-- raise Constraint_Error;
-- The raise constraint error can never be executed. It is just a dummy
-- node that can be labeled with an arbitrary type.
RCE := Make_Raise_Constraint_Error (Loc, Reason => CE_Explicit_Raise);
Set_Etype (RCE, Typ);
if Convert_To_Return_False (N) then
Rewrite (N,
Make_Expression_With_Actions (Loc,
Actions => New_List (
Make_Simple_Return_Statement (Loc,
Expression => New_Occurrence_Of (Standard_False, Loc))),
Expression => RCE));
else
Rewrite (N,
Make_Expression_With_Actions (Loc,
Actions => New_List (
Make_Raise_Statement (Loc,
Name => Name (N),
Expression => Expression (N))),
Expression => RCE));
end if;
Analyze_And_Resolve (N, Typ);
end Expand_N_Raise_Expression;
----------------------------------
-- Expand_N_Raise_Program_Error --
----------------------------------
procedure Expand_N_Raise_Program_Error (N : Node_Id) is
begin
-- We adjust the condition to deal with the C/Fortran boolean case. This
-- may well not be necessary, as all such conditions are generated by
-- the expander and probably are all standard boolean, but who knows
-- what strange optimization in future may require this adjustment.
Adjust_Condition (Condition (N));
-- Now deal with possible local raise handling
Possible_Local_Raise (N, Standard_Program_Error);
end Expand_N_Raise_Program_Error;
------------------------------
-- Expand_N_Raise_Statement --
------------------------------
procedure Expand_N_Raise_Statement (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Ehand : Node_Id;
E : Entity_Id;
Str : String_Id;
H : Node_Id;
Src : Boolean;
begin
-- Processing for locally handled exception (exclude reraise case)
if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
if Debug_Flag_Dot_G
or else Restriction_Active (No_Exception_Propagation)
then
-- If we have a local handler, then note that this is potentially
-- able to be transformed into a goto statement.
H := Find_Local_Handler (Entity (Name (N)), N);
if Present (H) then
if Local_Raise_Statements (H) = No_Elist then
Set_Local_Raise_Statements (H, New_Elmt_List);
end if;
-- Append the new entry if it is not there already. Sometimes
-- we have situations where due to reexpansion, the same node
-- is analyzed twice and would otherwise be added twice.
Append_Unique_Elmt (N, Local_Raise_Statements (H));
Set_Has_Local_Raise (H);
-- If no local handler, then generate no propagation warning
else
Warn_If_No_Propagation (N);
end if;
end if;
end if;
-- If a string expression is present, then the raise statement is
-- converted to a call:
-- Raise_Exception (exception-name'Identity, string);
-- and there is nothing else to do.
if Present (Expression (N)) then
-- Adjust message to deal with Prefix_Exception_Messages. We only
-- add the prefix to string literals, if the message is being
-- constructed, we assume it already deals with uniqueness.
if Prefix_Exception_Messages
and then Nkind (Expression (N)) = N_String_Literal
then
declare
Buf : Bounded_String;
begin
Add_Source_Info (Buf, Loc, Name_Enclosing_Entity);
Append (Buf, ": ");
Append (Buf, Strval (Expression (N)));
Rewrite (Expression (N), Make_String_Literal (Loc, +Buf));
Analyze_And_Resolve (Expression (N), Standard_String);
end;
end if;
-- Avoid passing exception-name'identity in runtimes in which this
-- argument is not used. This avoids generating undefined references
-- to these exceptions when compiling with no optimization
if Configurable_Run_Time_On_Target
and then (Restriction_Active (No_Exception_Handlers)
or else
Restriction_Active (No_Exception_Propagation))
then
Rewrite (N,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
Parameter_Associations => New_List (
New_Occurrence_Of (RTE (RE_Null_Id), Loc),
Expression (N))));
else
Rewrite (N,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Name (N),
Attribute_Name => Name_Identity),
Expression (N))));
end if;
Analyze (N);
return;
end if;
-- Remaining processing is for the case where no string expression is
-- present.
-- Don't expand a raise statement that does not come from source if we
-- have already had configurable run-time violations, since most likely
-- it will be junk cascaded nonsense.
if Configurable_Run_Time_Violations > 0
and then not Comes_From_Source (N)
then
return;
end if;
-- Convert explicit raise of Program_Error, Constraint_Error, and
-- Storage_Error into the corresponding raise (in High_Integrity_Mode
-- all other raises will get normal expansion and be disallowed,
-- but this is also faster in all modes). Propagate Comes_From_Source
-- flag to the new node.
if Present (Name (N)) and then Nkind (Name (N)) = N_Identifier then
Src := Comes_From_Source (N);
if Entity (Name (N)) = Standard_Constraint_Error then
Rewrite (N,
Make_Raise_Constraint_Error (Loc, Reason => CE_Explicit_Raise));
Set_Comes_From_Source (N, Src);
Analyze (N);
return;
elsif Entity (Name (N)) = Standard_Program_Error then
Rewrite (N,
Make_Raise_Program_Error (Loc, Reason => PE_Explicit_Raise));
Set_Comes_From_Source (N, Src);
Analyze (N);
return;
elsif Entity (Name (N)) = Standard_Storage_Error then
Rewrite (N,
Make_Raise_Storage_Error (Loc, Reason => SE_Explicit_Raise));
Set_Comes_From_Source (N, Src);
Analyze (N);
return;
end if;
end if;
-- Case of name present, in this case we expand raise name to
-- Raise_Exception (name'Identity, location_string);
-- where location_string identifies the file/line of the raise
if Present (Name (N)) then
declare
Id : Entity_Id := Entity (Name (N));
Buf : Bounded_String;
begin
Build_Location_String (Buf, Loc);
-- If the exception is a renaming, use the exception that it
-- renames (which might be a predefined exception, e.g.).
if Present (Renamed_Object (Id)) then
Id := Renamed_Object (Id);
end if;
-- Build a C-compatible string in case of no exception handlers,
-- since this is what the last chance handler is expecting.
if No_Exception_Handlers_Set then
-- Generate an empty message if configuration pragma
-- Suppress_Exception_Locations is set for this unit.
if Opt.Exception_Locations_Suppressed then
Buf.Length := 0;
end if;
Append (Buf, ASCII.NUL);
end if;
if Opt.Exception_Locations_Suppressed then
Buf.Length := 0;
end if;
Str := String_From_Name_Buffer (Buf);
-- Convert raise to call to the Raise_Exception routine
Rewrite (N,
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_Raise_Exception), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Name (N),
Attribute_Name => Name_Identity),
Make_String_Literal (Loc, Strval => Str))));
end;
-- Case of no name present (reraise). We rewrite the raise to:
-- Reraise_Occurrence_Always (EO);
-- where EO is the current exception occurrence. If the current handler
-- does not have a choice parameter specification, then we provide one.
else
-- Bypass expansion to a run-time call when back-end exception
-- handling is active, unless the target is CodePeer or GNATprove.
-- In CodePeer, raising an exception is treated as an error, while in
-- GNATprove all code with exceptions falls outside the subset of
-- code which can be formally analyzed.
if not CodePeer_Mode
and then Back_End_Exceptions
then
return;
end if;
-- Find innermost enclosing exception handler (there must be one,
-- since the semantics has already verified that this raise statement
-- is valid, and a raise with no arguments is only permitted in the
-- context of an exception handler.
Ehand := Parent (N);
while Nkind (Ehand) /= N_Exception_Handler loop
Ehand := Parent (Ehand);
end loop;
-- Make exception choice parameter if none present. Note that we do
-- not need to put the entity on the entity chain, since no one will
-- be referencing this entity by normal visibility methods.
if No (Choice_Parameter (Ehand)) then
E := Make_Temporary (Loc, 'E');
Set_Choice_Parameter (Ehand, E);
Set_Ekind (E, E_Variable);
Set_Etype (E, RTE (RE_Exception_Occurrence));
Set_Scope (E, Current_Scope);
end if;
-- Now rewrite the raise as a call to Reraise. A special case arises
-- if this raise statement occurs in the context of a handler for
-- all others (i.e. an at end handler). in this case we avoid
-- the call to defer abort, cleanup routines are expected to be
-- called in this case with aborts deferred.
declare
Ech : constant Node_Id := First (Exception_Choices (Ehand));
Ent : Entity_Id;
begin
if Nkind (Ech) = N_Others_Choice
and then All_Others (Ech)
then
Ent := RTE (RE_Reraise_Occurrence_No_Defer);
else
Ent := RTE (RE_Reraise_Occurrence_Always);
end if;
Rewrite (N,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Ent, Loc),
Parameter_Associations => New_List (
New_Occurrence_Of (Choice_Parameter (Ehand), Loc))));
end;
end if;
Analyze (N);
end Expand_N_Raise_Statement;
----------------------------------
-- Expand_N_Raise_Storage_Error --
----------------------------------
procedure Expand_N_Raise_Storage_Error (N : Node_Id) is
begin
-- We adjust the condition to deal with the C/Fortran boolean case. This
-- may well not be necessary, as all such conditions are generated by
-- the expander and probably are all standard boolean, but who knows
-- what strange optimization in future may require this adjustment.
Adjust_Condition (Condition (N));
-- Now deal with possible local raise handling
Possible_Local_Raise (N, Standard_Storage_Error);
end Expand_N_Raise_Storage_Error;
--------------------------
-- Possible_Local_Raise --
--------------------------
procedure Possible_Local_Raise (N : Node_Id; E : Entity_Id) is
begin
-- Nothing to do if local raise optimization not active
if not Debug_Flag_Dot_G
and then not Restriction_Active (No_Exception_Propagation)
then
return;
end if;
-- Nothing to do if original node was an explicit raise, because in
-- that case, we already generated the required warning for the raise.
if Nkind (Original_Node (N)) = N_Raise_Statement then
return;
end if;
-- Otherwise see if we have a local handler for the exception
declare
H : constant Node_Id := Find_Local_Handler (E, N);
begin
-- If so, mark that it has a local raise
if Present (H) then
Set_Has_Local_Raise (H, True);
-- Otherwise, if the No_Exception_Propagation restriction is active
-- and the warning is enabled, generate the appropriate warnings.
-- ??? Do not do it for the Call_Marker nodes inserted by the ABE
-- mechanism because this generates too many false positives, or
-- for generic instantiations for the same reason.
elsif Warn_On_Non_Local_Exception
and then Restriction_Active (No_Exception_Propagation)
and then Nkind (N) /= N_Call_Marker
and then Nkind (N) not in N_Generic_Instantiation
then
Warn_No_Exception_Propagation_Active (N);
if Configurable_Run_Time_Mode then
Error_Msg_NE
("\?X?& may call Last_Chance_Handler", N, E);
else
Error_Msg_NE
("\?X?& may result in unhandled exception", N, E);
end if;
end if;
end;
end Possible_Local_Raise;
------------------------
-- Find_Local_Handler --
------------------------
function Find_Local_Handler
(Ename : Entity_Id;
Nod : Node_Id) return Node_Id
is
N : Node_Id;
P : Node_Id;
H : Node_Id;
C : Node_Id;
SSE : Scope_Stack_Entry renames Scope_Stack.Table (Scope_Stack.Last);
-- This is used to test for wrapped actions below
ERaise : Entity_Id;
EHandle : Entity_Id;
-- The entity Id's for the exception we are raising and handling, using
-- the renamed exception if a Renamed_Entity is present.
begin
-- Never any local handler if all handlers removed
if Debug_Flag_Dot_X then
return Empty;
end if;
-- Get the exception we are raising, allowing for renaming
ERaise := Get_Renamed_Entity (Ename);
-- We need to check if the node we are looking at is contained in
--
-- Loop to search up the tree
N := Nod;
loop
P := Parent (N);
-- If we get to the top of the tree, or to a subprogram, task, entry,
-- protected body, or accept statement without having found a
-- matching handler, then there is no local handler.
if No (P)
or else Nkind (P) = N_Subprogram_Body
or else Nkind (P) = N_Task_Body
or else Nkind (P) = N_Protected_Body
or else Nkind (P) = N_Entry_Body
or else Nkind (P) = N_Accept_Statement
then
return Empty;
-- Test for handled sequence of statements with at least one
-- exception handler which might be the one we are looking for.
elsif Nkind (P) = N_Handled_Sequence_Of_Statements
and then Present (Exception_Handlers (P))
then
-- Before we proceed we need to check if the node N is covered
-- by the statement part of P rather than one of its exception
-- handlers (an exception handler obviously does not cover its
-- own statements).
-- This test is more delicate than might be thought. It is not
-- just a matter of checking the Statements (P), because the node
-- might be waiting to be wrapped in a transient scope, in which
-- case it will end up in the block statements, even though it
-- is not there now.
if Is_List_Member (N) then
declare
LCN : constant List_Id := List_Containing (N);
begin
if LCN = Statements (P)
or else
LCN = SSE.Actions_To_Be_Wrapped (Before)
or else
LCN = SSE.Actions_To_Be_Wrapped (After)
or else
LCN = SSE.Actions_To_Be_Wrapped (Cleanup)
then
-- Loop through exception handlers
H := First (Exception_Handlers (P));
while Present (H) loop
-- Guard against other constructs appearing in the
-- list of exception handlers.
if Nkind (H) = N_Exception_Handler then
-- Loop through choices in one handler
C := First (Exception_Choices (H));
while Present (C) loop
-- Deal with others case
if Nkind (C) = N_Others_Choice then
-- Matching others handler, but we need
-- to ensure there is no choice parameter.
-- If there is, then we don't have a local
-- handler after all (since we do not allow
-- choice parameters for local handlers).
if No (Choice_Parameter (H)) then
return H;
else
return Empty;
end if;
-- If not others must be entity name
elsif Nkind (C) /= N_Others_Choice then
pragma Assert (Is_Entity_Name (C));
pragma Assert (Present (Entity (C)));
-- Get exception being handled, dealing with
-- renaming.
EHandle := Get_Renamed_Entity (Entity (C));
-- If match, then check choice parameter
if ERaise = EHandle then
if No (Choice_Parameter (H)) then
return H;
else
return Empty;
end if;
end if;
end if;
Next (C);
end loop;
end if;
Next (H);
end loop;
end if;
end;
end if;
end if;
N := P;
end loop;
end Find_Local_Handler;
---------------------------------
-- Get_Local_Raise_Call_Entity --
---------------------------------
-- Note: this is primarily provided for use by the back end in generating
-- calls to Local_Raise. But it would be too late in the back end to call
-- RTE if this actually caused a load/analyze of the unit. So what we do
-- is to ensure there is a dummy call to this function during front end
-- processing so that the unit gets loaded then, and not later.
Local_Raise_Call_Entity : Entity_Id;
Local_Raise_Call_Entity_Set : Boolean := False;
function Get_Local_Raise_Call_Entity return Entity_Id is
begin
if not Local_Raise_Call_Entity_Set then
Local_Raise_Call_Entity_Set := True;
if RTE_Available (RE_Local_Raise) then
Local_Raise_Call_Entity := RTE (RE_Local_Raise);
else
Local_Raise_Call_Entity := Empty;
end if;
end if;
return Local_Raise_Call_Entity;
end Get_Local_Raise_Call_Entity;
-----------------------------
-- Get_RT_Exception_Entity --
-----------------------------
function Get_RT_Exception_Entity (R : RT_Exception_Code) return Entity_Id is
begin
case Rkind (R) is
when CE_Reason => return Standard_Constraint_Error;
when PE_Reason => return Standard_Program_Error;
when SE_Reason => return Standard_Storage_Error;
end case;
end Get_RT_Exception_Entity;
---------------------------
-- Get_RT_Exception_Name --
---------------------------
procedure Get_RT_Exception_Name (Code : RT_Exception_Code) is
begin
case Code is
when CE_Access_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Access_Check");
when CE_Access_Parameter_Is_Null =>
Add_Str_To_Name_Buffer ("CE_Null_Access_Parameter");
when CE_Discriminant_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Discriminant_Check");
when CE_Divide_By_Zero =>
Add_Str_To_Name_Buffer ("CE_Divide_By_Zero");
when CE_Explicit_Raise =>
Add_Str_To_Name_Buffer ("CE_Explicit_Raise");
when CE_Index_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Index_Check");
when CE_Invalid_Data =>
Add_Str_To_Name_Buffer ("CE_Invalid_Data");
when CE_Length_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Length_Check");
when CE_Null_Exception_Id =>
Add_Str_To_Name_Buffer ("CE_Null_Exception_Id");
when CE_Null_Not_Allowed =>
Add_Str_To_Name_Buffer ("CE_Null_Not_Allowed");
when CE_Overflow_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Overflow_Check");
when CE_Partition_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Partition_Check");
when CE_Range_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Range_Check");
when CE_Tag_Check_Failed =>
Add_Str_To_Name_Buffer ("CE_Tag_Check");
when PE_Access_Before_Elaboration =>
Add_Str_To_Name_Buffer ("PE_Access_Before_Elaboration");
when PE_Accessibility_Check_Failed =>
Add_Str_To_Name_Buffer ("PE_Accessibility_Check");
when PE_Address_Of_Intrinsic =>
Add_Str_To_Name_Buffer ("PE_Address_Of_Intrinsic");
when PE_Aliased_Parameters =>
Add_Str_To_Name_Buffer ("PE_Aliased_Parameters");
when PE_All_Guards_Closed =>
Add_Str_To_Name_Buffer ("PE_All_Guards_Closed");
when PE_Bad_Predicated_Generic_Type =>
Add_Str_To_Name_Buffer ("PE_Bad_Predicated_Generic_Type");
when PE_Build_In_Place_Mismatch =>
Add_Str_To_Name_Buffer ("PE_Build_In_Place_Mismatch");
when PE_Current_Task_In_Entry_Body =>
Add_Str_To_Name_Buffer ("PE_Current_Task_In_Entry_Body");
when PE_Duplicated_Entry_Address =>
Add_Str_To_Name_Buffer ("PE_Duplicated_Entry_Address");
when PE_Explicit_Raise =>
Add_Str_To_Name_Buffer ("PE_Explicit_Raise");
when PE_Finalize_Raised_Exception =>
Add_Str_To_Name_Buffer ("PE_Finalize_Raised_Exception");
when PE_Implicit_Return =>
Add_Str_To_Name_Buffer ("PE_Implicit_Return");
when PE_Misaligned_Address_Value =>
Add_Str_To_Name_Buffer ("PE_Misaligned_Address_Value");
when PE_Missing_Return =>
Add_Str_To_Name_Buffer ("PE_Missing_Return");
when PE_Non_Transportable_Actual =>
Add_Str_To_Name_Buffer ("PE_Non_Transportable_Actual");
when PE_Overlaid_Controlled_Object =>
Add_Str_To_Name_Buffer ("PE_Overlaid_Controlled_Object");
when PE_Potentially_Blocking_Operation =>
Add_Str_To_Name_Buffer ("PE_Potentially_Blocking_Operation");
when PE_Stream_Operation_Not_Allowed =>
Add_Str_To_Name_Buffer ("PE_Stream_Operation_Not_Allowed");
when PE_Stubbed_Subprogram_Called =>
Add_Str_To_Name_Buffer ("PE_Stubbed_Subprogram_Called");
when PE_Unchecked_Union_Restriction =>
Add_Str_To_Name_Buffer ("PE_Unchecked_Union_Restriction");
when SE_Empty_Storage_Pool =>
Add_Str_To_Name_Buffer ("SE_Empty_Storage_Pool");
when SE_Explicit_Raise =>
Add_Str_To_Name_Buffer ("SE_Explicit_Raise");
when SE_Infinite_Recursion =>
Add_Str_To_Name_Buffer ("SE_Infinite_Recursion");
when SE_Object_Too_Large =>
Add_Str_To_Name_Buffer ("SE_Object_Too_Large");
end case;
end Get_RT_Exception_Name;
----------------------------
-- Warn_If_No_Local_Raise --
----------------------------
procedure Warn_If_No_Local_Raise (N : Node_Id) is
begin
if Restriction_Active (No_Exception_Propagation)
and then Warn_On_Non_Local_Exception
then
Warn_No_Exception_Propagation_Active (N);
Error_Msg_N
("\?X?this handler can never be entered, and has been removed", N);
end if;
end Warn_If_No_Local_Raise;
----------------------------
-- Warn_If_No_Propagation --
----------------------------
procedure Warn_If_No_Propagation (N : Node_Id) is
begin
if Restriction_Check_Required (No_Exception_Propagation)
and then Warn_On_Non_Local_Exception
then
Warn_No_Exception_Propagation_Active (N);
if Configurable_Run_Time_Mode then
Error_Msg_N
("\?X?Last_Chance_Handler will be called on exception", N);
else
Error_Msg_N
("\?X?execution may raise unhandled exception", N);
end if;
end if;
end Warn_If_No_Propagation;
------------------------------------------
-- Warn_No_Exception_Propagation_Active --
------------------------------------------
procedure Warn_No_Exception_Propagation_Active (N : Node_Id) is
begin
Error_Msg_N
("?X?pragma Restrictions (No_Exception_Propagation) in effect", N);
end Warn_No_Exception_Propagation_Active;
end Exp_Ch11;
|
with STM32.GPIO;
use STM32.GPIO;
with HAL.GPIO;
with STM32.Device;
package Pins_STM32F446 is
----------------------
-- ARDUINO UNO PINS --
----------------------
-- The following pins have been tested
-- Digital
Pin_D2 : GPIO_Point renames STM32.Device.PA10;
Pin_D3 : GPIO_Point renames STM32.Device.PB3;
Pin_D4 : GPIO_Point renames STM32.Device.PB5;
Pin_D5 : GPIO_Point renames STM32.Device.PB4;
Pin_D6 : GPIO_Point renames STM32.Device.PB10;
Pin_D7 : GPIO_Point renames STM32.Device.PA8;
Pin_D8 : GPIO_Point renames STM32.Device.PA9;
Pin_D9 : GPIO_Point renames STM32.Device.PC7;
Pin_D10 : GPIO_Point renames STM32.Device.PB6;
Pin_D11 : GPIO_Point renames STM32.Device.PA7;
Pin_D12 : GPIO_Point renames STM32.Device.PA6;
Pin_D13 : GPIO_Point renames STM32.Device.PA5;
-- Analog
Pin_A0 : GPIO_Point renames STM32.Device.PA0;
Pin_A1 : GPIO_Point renames STM32.Device.PA1;
Pin_A2 : GPIO_Point renames STM32.Device.PA4;
Pin_A3 : GPIO_Point renames STM32.Device.PB0; --It doesn't work
Pin_A4 : GPIO_Point renames STM32.Device.PC1; --It doesn't work
Pin_A5 : GPIO_Point renames STM32.Device.PC0; --It doesn't work
---------------
-- MORE PINS --
---------------
-- The following pins haven't been tested yet
Pin_C2 : GPIO_Point renames STM32.Device.PC2;
Pin_C4 : GPIO_Point renames STM32.Device.PC4;
Pin_C5 : GPIO_Point renames STM32.Device.PC5;
Pin_C6 : GPIO_Point renames STM32.Device.PC6;
Pin_C8 : GPIO_Point renames STM32.Device.PC8;
Pin_C9 : GPIO_Point renames STM32.Device.PC9;
Pin_C10 : GPIO_Point renames STM32.Device.PC10;
Pin_C11 : GPIO_Point renames STM32.Device.PC11;
Pin_C12 : GPIO_Point renames STM32.Device.PC12;
Pin_C13 : GPIO_Point renames STM32.Device.PC13;
Pin_C14 : GPIO_Point renames STM32.Device.PC14;
Pin_C15 : GPIO_Point renames STM32.Device.PC15;
Pin_B1 : GPIO_Point renames STM32.Device.PB1;
Pin_B2 : GPIO_Point renames STM32.Device.PB2;
Pin_B3 : GPIO_Point renames STM32.Device.PB3;
Pin_B4 : GPIO_Point renames STM32.Device.PB4;
Pin_B5 : GPIO_Point renames STM32.Device.PB5;
Pin_B7 : GPIO_Point renames STM32.Device.PB7;
Pin_B8 : GPIO_Point renames STM32.Device.PB8;
Pin_B9 : GPIO_Point renames STM32.Device.PB9;
Pin_B10 : GPIO_Point renames STM32.Device.PB10;
Pin_B12 : GPIO_Point renames STM32.Device.PB12;
Pin_B13 : GPIO_Point renames STM32.Device.PB13;
Pin_B14 : GPIO_Point renames STM32.Device.PB14;
Pin_B15 : GPIO_Point renames STM32.Device.PB15;
Pin_A10 : GPIO_Point renames STM32.Device.PA10;
Pin_A8 : GPIO_Point renames STM32.Device.PA8;
Pin_A11 : GPIO_Point renames STM32.Device.PA11;
Pin_A12 : GPIO_Point renames STM32.Device.PA12;
Pin_A13 : GPIO_Point renames STM32.Device.PA13;
Pin_A14 : GPIO_Point renames STM32.Device.PA14;
Pin_A15 : GPIO_Point renames STM32.Device.PA15;
Pin_H1 : GPIO_Point renames STM32.Device.PH1;
end Pins_STM32F446;
|
-----------------------------------------------------------------------
-- awa-mail -- Mail module
-- Copyright (C) 2011, 2012, 2017, 2018 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.Maps;
with ASF.Applications;
with AWA.Modules;
with AWA.Events;
with AWA.Mail.Clients;
-- == Configuration ==
-- The *mail* module needs some properties to configure the SMTP
-- server.
--
-- |Configuration | Default | Description |
-- | --------------- | --------- | ----------------------------------------------- |
-- |mail.smtp.host | localhost | Defines the SMTP server host name |
-- |mail.smtp.port | 25 | Defines the SMTP connection port |
-- |mail.smtp.enable | 1 | Defines whether sending email is enabled or not |
--
-- == Sending an email ==
-- Sending an email when an event is posted can be done by using
-- an XML configuration. Basically, the *mail* module uses the event
-- framework provided by AWA. The XML definition looks like:
--
-- <on-event name="user-register">
-- <action>#{userMail.send}</action>
-- <property name="template">/mail/register-user-message.xhtml</property>
-- </on-event>
--
-- With this definition, the mail template `/mail/register-user-message.xhtml`
-- is formatted by using the event and application context when the
-- `user-register` event is posted.
--
-- @include awa-mail-components.ads
-- @include awa-mail-components-recipients.ads
-- @include awa-mail-components-messages.ads
--
-- == Ada Beans ==
-- @include mail.xml
--
package AWA.Mail.Modules is
NAME : constant String := "mail";
type Mail_Module is new AWA.Modules.Module with private;
type Mail_Module_Access is access all Mail_Module'Class;
-- Initialize the mail module.
overriding
procedure Initialize (Plugin : in out Mail_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 Mail_Module;
Props : in ASF.Applications.Config);
-- Create a new mail message.
function Create_Message (Plugin : in Mail_Module)
return AWA.Mail.Clients.Mail_Message_Access;
-- Format and send an email.
procedure Send_Mail (Plugin : in Mail_Module;
Template : in String;
Props : in Util.Beans.Objects.Maps.Map;
Content : in AWA.Events.Module_Event'Class);
-- Get the mail module instance associated with the current application.
function Get_Mail_Module return Mail_Module_Access;
private
type Mail_Module is new AWA.Modules.Module with record
Mailer : AWA.Mail.Clients.Mail_Manager_Access;
end record;
end AWA.Mail.Modules;
|
-----------------------------------------------------------------------
-- security-auth-oauth -- OAuth based authentication
-- 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 Util.Log.Loggers;
package body Security.Auth.OAuth is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Auth.OAuth");
-- ------------------------------
-- OAuth Manager
-- ------------------------------
-- The <b>Manager</b> provides the core operations for the OAuth authorization process.
-- ------------------------------
-- Initialize the authentication realm.
-- ------------------------------
overriding
procedure Initialize (Realm : in out Manager;
Params : in Parameters'Class;
Provider : in String := PROVIDER_OPENID) is
begin
Realm.App.Set_Application_Identifier (Params.Get_Parameter (Provider & ".client_id"));
Realm.App.Set_Application_Secret (Params.Get_Parameter (Provider & ".secret"));
Realm.App.Set_Application_Callback (Params.Get_Parameter (Provider & ".callback_url"));
Realm.App.Set_Provider_URI (Params.Get_Parameter (Provider & ".request_url"));
Realm.Realm := To_Unbounded_String (Params.Get_Parameter (Provider & ".realm"));
Realm.Scope := To_Unbounded_String (Params.Get_Parameter (Provider & ".scope"));
Realm.Issuer := To_Unbounded_String (Params.Get_Parameter (Provider & ".issuer"));
end Initialize;
-- ------------------------------
-- Discover the OpenID provider that must be used to authenticate the user.
-- The <b>Name</b> can be an URL or an alias that identifies the provider.
-- A cached OpenID provider can be returned.
-- Read the XRDS document from the URI and initialize the OpenID provider end point.
-- (See OpenID Section 7.3 Discovery)
-- ------------------------------
overriding
procedure Discover (Realm : in out Manager;
Name : in String;
Result : out End_Point) is
pragma Unreferenced (Realm);
begin
Result.URL := To_Unbounded_String (Name);
end Discover;
-- ------------------------------
-- Associate the application (relying party) with the OpenID provider.
-- The association can be cached.
-- (See OpenID Section 8 Establishing Associations)
-- ------------------------------
overriding
procedure Associate (Realm : in out Manager;
OP : in End_Point;
Result : out Association) is
pragma Unreferenced (Realm, OP);
begin
Result.Assoc_Handle := To_Unbounded_String (Security.OAuth.Clients.Create_Nonce (128));
end Associate;
-- ------------------------------
-- Get the authentication URL to which the user must be redirected for authentication
-- by the authentication server.
-- ------------------------------
overriding
function Get_Authentication_URL (Realm : in Manager;
OP : in End_Point;
Assoc : in Association) return String is
Result : Unbounded_String := OP.URL;
State : constant String := Realm.App.Get_State (To_String (Assoc.Assoc_Handle));
Params : constant String := Realm.App.Get_Auth_Params (State, To_String (Realm.Scope));
begin
if Index (Result, "?") > 0 then
Append (Result, "&");
else
Append (Result, "?");
end if;
Append (Result, Params);
Append (Result, "&");
Append (Result, Security.OAuth.Response_Type);
Append (Result, "=code");
Log.Debug ("Params = {0}", Params);
return To_String (Result);
end Get_Authentication_URL;
-- ------------------------------
-- Verify the authentication result
-- ------------------------------
overriding
procedure Verify (Realm : in out Manager;
Assoc : in Association;
Request : in Parameters'Class;
Result : out Authentication) is
State : constant String := Request.Get_Parameter (Security.OAuth.State);
Code : constant String := Request.Get_Parameter (Security.OAuth.Code);
Error : constant String := Request.Get_Parameter (Security.OAuth.Error_Description);
begin
if Error'Length /= 0 then
Set_Result (Result, CANCEL, "Authentication refused: " & Error);
return;
end if;
-- First, verify that the state parameter matches our internal state.
if not Realm.App.Is_Valid_State (To_String (Assoc.Assoc_Handle), State) then
Set_Result (Result, INVALID_SIGNATURE, "invalid OAuth state parameter");
return;
end if;
-- Get the access token from the authorization code.
declare
use type Security.OAuth.Clients.Access_Token_Access;
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= Realm.App.Request_Access_Token (Code);
begin
if Acc = null then
Set_Result (Result, INVALID_SIGNATURE, "cannot change the code to an access_token");
return;
end if;
-- Last step, verify the access token and get the user identity.
Manager'Class (Realm).Verify_Access_Token (Assoc, Request, Acc, Result);
end;
end Verify;
end Security.Auth.OAuth;
|
with Ada.Containers.Linked_Lists;
package body Ada.Containers.Naked_Doubly_Linked_Lists is
function Next (Position : not null Node_Access) return Node_Access is
begin
return Position.Next;
end Next;
function Previous (Position : not null Node_Access) return Node_Access is
begin
return Position.Previous;
end Previous;
procedure Iterate (
First : Node_Access;
Process : not null access procedure (Position : not null Node_Access))
is
Position : Node_Access := First;
begin
while Position /= null loop
Process (Position);
Position := Position.Next;
end loop;
end Iterate;
procedure Reverse_Iterate (
Last : Node_Access;
Process : not null access procedure (Position : not null Node_Access))
is
procedure Reverse_Iterate_Body is
new Linked_Lists.Reverse_Iterate (Node, Node_Access);
pragma Inline_Always (Reverse_Iterate_Body);
begin
Reverse_Iterate_Body (Last, Process => Process);
end Reverse_Iterate;
function Find (
First : Node_Access;
Params : System.Address;
Equivalent : not null access function (
Right : not null Node_Access;
Params : System.Address)
return Boolean)
return Node_Access
is
I : Node_Access := First;
begin
while I /= null loop
if Equivalent (I, Params) then
return I;
end if;
I := I.Next;
end loop;
return null;
end Find;
function Reverse_Find (
Last : Node_Access;
Params : System.Address;
Equivalent : not null access function (
Right : not null Node_Access;
Params : System.Address)
return Boolean)
return Node_Access
is
function Reverse_Find_Body is
new Linked_Lists.Reverse_Find (Node, Node_Access);
pragma Inline_Always (Reverse_Find_Body);
begin
return Reverse_Find_Body (Last, Params, Equivalent => Equivalent);
end Reverse_Find;
function Is_Before (Before, After : Node_Access) return Boolean is
AN : Node_Access;
BN : Node_Access;
AP : Node_Access;
BP : Node_Access;
begin
if After = Before then
return False;
else
AN := After;
BN := Before;
AP := After.Previous;
BP := Before.Previous;
loop
if BP = null or else AP = BN then
return True;
elsif AP = null or else BP = AN then
return False;
end if;
AN := AN.Next;
BN := BN.Next;
if AN = null or else BN = AP then
return True;
elsif BN = null or else AN = BP then
return False;
end if;
AP := AP.Previous;
BP := BP.Previous;
end loop;
end if;
end Is_Before;
function Equivalent (
Left_Last, Right_Last : Node_Access;
Equivalent : not null access function (
Left, Right : not null Node_Access)
return Boolean)
return Boolean
is
function Equivalent_Body is
new Linked_Lists.Equivalent (Node, Node_Access);
pragma Inline_Always (Equivalent_Body);
begin
return Equivalent_Body (Left_Last, Right_Last, Equivalent => Equivalent);
end Equivalent;
procedure Free (
First : in out Node_Access;
Last : in out Node_Access;
Length : in out Count_Type;
Free : not null access procedure (Object : in out Node_Access))
is
procedure Free_Body is new Linked_Lists.Free (Node, Node_Access);
pragma Inline_Always (Free_Body);
begin
Free_Body (First, Last, Length, Free => Free);
end Free;
procedure Insert (
First : in out Node_Access;
Last : in out Node_Access;
Length : in out Count_Type;
Before : Node_Access;
New_Item : not null Node_Access) is
begin
if Before /= null then
New_Item.Previous := Before.Previous;
Before.Previous := New_Item;
else
New_Item.Previous := Last;
Last := New_Item;
end if;
New_Item.Next := Before;
if First = Before then
First := New_Item;
else
New_Item.Previous.Next := New_Item;
end if;
Length := Length + 1;
end Insert;
procedure Remove (
First : in out Node_Access;
Last : in out Node_Access;
Length : in out Count_Type;
Position : not null Node_Access;
Next : Node_Access)
is
pragma Assert (Next = Position.Next);
Previous : constant Node_Access := Position.Previous;
begin
if Previous /= null then
pragma Assert (First /= Position);
Previous.Next := Next;
else
pragma Assert (First = Position);
First := Next;
end if;
if Next /= null then
pragma Assert (Last /= Position);
Next.Previous := Previous;
else
pragma Assert (Last = Position);
Last := Previous;
end if;
Length := Length - 1;
end Remove;
procedure Swap_Links (
First : in out Node_Access;
Last : in out Node_Access;
I, J : not null Node_Access) is
begin
if I /= J then
declare
I_Previous : constant Node_Access := I.Previous;
I_Next : constant Node_Access := I.Next;
J_Previous : constant Node_Access := J.Previous;
J_Next : constant Node_Access := J.Next;
begin
if I_Previous = J then
pragma Assert (J_Next = I);
I.Next := J;
J.Previous := I;
else
I.Next := J_Next;
J.Previous := I_Previous;
if I_Previous /= null then
I_Previous.Next := J;
else
pragma Assert (I = First);
First := J;
end if;
if J_Next /= null then
J_Next.Previous := I;
else
pragma Assert (J = Last);
Last := I;
end if;
end if;
if J_Previous = I then
pragma Assert (I_Next = J);
J.Next := I;
I.Previous := J;
else
J.Next := I_Next;
I.Previous := J_Previous;
if J_Previous /= null then
J_Previous.Next := I;
else
pragma Assert (J = First);
First := I;
end if;
if I_Next /= null then
I_Next.Previous := J;
else
pragma Assert (I = Last);
Last := J;
end if;
end if;
end;
end if;
end Swap_Links;
procedure Splice (
Target_First : in out Node_Access;
Target_Last : in out Node_Access;
Length : in out Count_Type;
Before : Node_Access;
Source_First : in out Node_Access;
Source_Last : in out Node_Access;
Source_Length : in out Count_Type)
is
Previous : Node_Access;
begin
if Source_Last /= null then
if Before /= null then
Previous := Before.Previous;
Before.Previous := Source_Last;
Source_Last.Next := Before;
else
Previous := Target_Last;
Target_Last := Source_Last;
pragma Assert (Source_Last.Next = null);
end if;
Source_First.Previous := Previous;
if Previous /= null then
Previous.Next := Source_First;
else
pragma Assert (Target_First = null);
Target_First := Source_First;
end if;
Length := Length + Source_Length;
Source_First := null;
Source_Last := null;
Source_Length := 0;
end if;
end Splice;
procedure Split (
Target_First : out Node_Access;
Target_Last : out Node_Access;
Length : out Count_Type;
Source_First : in out Node_Access;
Source_Last : in out Node_Access;
Source_Length : in out Count_Type;
Count : Count_Type)
is
Before : Node_Access;
begin
if Count = 0 then
Target_First := null;
Target_Last := null;
Length := 0;
elsif Count = Source_Length then
Target_First := Source_First;
Target_Last := Source_Last;
Length := Source_Length;
Source_First := null;
Source_Last := null;
Source_Length := 0;
else
Before := Source_First;
for I in 1 .. Count loop
Before := Before.Next;
end loop;
Target_First := Source_First;
Target_Last := Before.Previous;
Source_First := Before;
Target_Last.Next := null;
Source_First.Previous := null;
Length := Count;
Source_Length := Source_Length - Count;
end if;
end Split;
procedure Copy (
Target_First : out Node_Access;
Target_Last : out Node_Access;
Length : out Count_Type;
Source_Last : Node_Access;
Copy : not null access procedure (
Target : out Node_Access;
Source : not null Node_Access))
is
procedure Copy_Body is new Linked_Lists.Copy (Node, Node_Access);
pragma Inline_Always (Copy_Body);
begin
Copy_Body (Target_First, Target_Last, Length, Source_Last, Copy => Copy);
end Copy;
procedure Reverse_Elements (
Target_First : in out Node_Access;
Target_Last : in out Node_Access;
Length : in out Count_Type)
is
procedure Reverse_Elements_Body is
new Linked_Lists.Reverse_Elements (Node, Node_Access);
pragma Inline_Always (Reverse_Elements_Body);
begin
Reverse_Elements_Body (Target_First, Target_Last, Length);
end Reverse_Elements;
function Is_Sorted (
Last : Node_Access;
LT : not null access function (
Left, Right : not null Node_Access)
return Boolean)
return Boolean
is
function Is_Sorted_Body is
new Linked_Lists.Is_Sorted (Node, Node_Access);
pragma Inline_Always (Is_Sorted_Body);
begin
return Is_Sorted_Body (Last, LT => LT);
end Is_Sorted;
procedure Merge (
Target_First : in out Node_Access;
Target_Last : in out Node_Access;
Length : in out Count_Type;
Source_First : in out Node_Access;
Source_Last : in out Node_Access;
Source_Length : in out Count_Type;
LT : not null access function (
Left, Right : not null Node_Access)
return Boolean)
is
procedure Merge_Body is new Linked_Lists.Merge (Node, Node_Access);
pragma Inline_Always (Merge_Body);
begin
Merge_Body (
Target_First,
Target_Last,
Length,
Source_First,
Source_Last,
Source_Length,
LT => LT);
end Merge;
procedure Merge_Sort (
Target_First : in out Node_Access;
Target_Last : in out Node_Access;
Length : in out Count_Type;
LT : not null access function (
Left, Right : not null Node_Access)
return Boolean)
is
procedure Merge_Sort_Body is
new Linked_Lists.Merge_Sort (Node, Node_Access);
-- no inline, Merge_Sort uses recursive calling
begin
Merge_Sort_Body (Target_First, Target_Last, Length, LT => LT);
end Merge_Sort;
end Ada.Containers.Naked_Doubly_Linked_Lists;
|
--------------------------------------------------------------------------------
-- Copyright (c) 2013, Felix Krause <contact@flyx.org>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with System;
with CL.API;
with CL.Helpers;
with CL.Enumerations;
package body CL.Platforms is
-----------------------------------------------------------------------------
-- Helper instantiations
-----------------------------------------------------------------------------
function Platform_String_Info is
new Helpers.Get_String (Parameter_T => Enumerations.Platform_Info,
C_Getter => API.Get_Platform_Info);
function UInt_Info is
new Helpers.Get_Parameter (Return_T => CL.UInt,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
function ULong_Info is
new Helpers.Get_Parameter (Return_T => CL.ULong,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
function Size_Info is
new Helpers.Get_Parameter (Return_T => Size,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
function Bool_Info is
new Helpers.Get_Parameter (Return_T => CL.Bool,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
function String_Info is
new Helpers.Get_String (Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
-----------------------------------------------------------------------------
-- Implementations
-----------------------------------------------------------------------------
function List return Platform_List is
Platform_Count : aliased UInt;
Error : Enumerations.Error_Code;
begin
Error := API.Get_Platform_IDs (0, System.Null_Address,
Platform_Count'Unchecked_Access);
Helpers.Error_Handler (Error);
declare
Raw_List : Address_List (1 .. Integer (Platform_Count));
Return_List : Platform_List (1 .. Integer (Platform_Count));
begin
Error := API.Get_Platform_IDs (Platform_Count,
Raw_List (1)'Address, null);
Helpers.Error_Handler (Error);
for Index in Raw_List'Range loop
Return_List (Index) := Platform'(Ada.Finalization.Controlled with
Location => Raw_List (Index));
end loop;
return Return_List;
end;
end List;
function Profile (Source : Platform) return String is
begin
return Platform_String_Info (Source, Enumerations.Profile);
end Profile;
function Version (Source : Platform) return String is
begin
return Platform_String_Info (Source, Enumerations.Version);
end Version;
function Name (Source : Platform) return String is
begin
return Platform_String_Info (Source, Enumerations.Name);
end Name;
function Vendor (Source : Platform) return String is
begin
return Platform_String_Info (Source, Enumerations.Vendor);
end Vendor;
function Extensions (Source : Platform) return String is
begin
return Platform_String_Info (Source, Enumerations.Extensions);
end Extensions;
function Devices (Source : Platform; Types : Device_Kind)
return Device_List is
Device_Count : aliased UInt;
Error : Enumerations.Error_Code;
function To_Bitfield is new
Ada.Unchecked_Conversion (Source => Device_Kind,
Target => Bitfield);
begin
Error := API.Get_Device_IDs (Source.Location, To_Bitfield (Types), 0,
System.Null_Address,
Device_Count'Unchecked_Access);
Helpers.Error_Handler (Error);
declare
Raw_List : Address_List (1 .. Integer (Device_Count));
Return_List : Device_List (1 .. Integer (Device_Count));
begin
Error := API.Get_Device_IDs (Source.Location, To_Bitfield (Types),
Device_Count,
Raw_List (1)'Address, null);
Helpers.Error_Handler (Error);
for Index in Raw_List'Range loop
Return_List (Index) := Device'(Ada.Finalization.Controlled with
Location => Raw_List (Index));
end loop;
return Return_List;
end;
end Devices;
function Vendor_ID (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Vendor_ID);
end Vendor_ID;
function Max_Compute_Units (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Compute_Units);
end Max_Compute_Units;
function Max_Work_Item_Dimensions (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Work_Item_Dimensions);
end Max_Work_Item_Dimensions;
function Preferred_Vector_Width_Char (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Char);
end Preferred_Vector_Width_Char;
function Preferred_Vector_Width_Short (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Short);
end Preferred_Vector_Width_Short;
function Preferred_Vector_Width_Int (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Int);
end Preferred_Vector_Width_Int;
function Preferred_Vector_Width_Long (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Long);
end Preferred_Vector_Width_Long;
function Preferred_Vector_Width_Float (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Float);
end Preferred_Vector_Width_Float;
function Preferred_Vector_Width_Double (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Double);
end Preferred_Vector_Width_Double;
function Max_Clock_Frequency (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Clock_Frequency);
end Max_Clock_Frequency;
function Address_Bits (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Address_Bits);
end Address_Bits;
function Max_Read_Image_Args (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Read_Image_Args);
end Max_Read_Image_Args;
function Max_Write_Image_Args (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Write_Image_Args);
end Max_Write_Image_Args;
function Max_Samplers (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Samplers);
end Max_Samplers;
function Mem_Base_Addr_Align (Source: Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Mem_Base_Addr_Align);
end Mem_Base_Addr_Align;
function Min_Data_Type_Align_Size (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Min_Data_Type_Align_Size);
end Min_Data_Type_Align_Size;
function Global_Mem_Cacheline_Size (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Global_Mem_Cacheline_Size);
end Global_Mem_Cacheline_Size;
function Max_Constant_Args (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Max_Constant_Args);
end Max_Constant_Args;
function Preferred_Vector_Width_Half (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Preferred_Vector_Width_Half);
end Preferred_Vector_Width_Half;
function Native_Vector_Width_Char (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Char);
end Native_Vector_Width_Char;
function Native_Vector_Width_Short (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Short);
end Native_Vector_Width_Short;
function Native_Vector_Width_Int (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Int);
end Native_Vector_Width_Int;
function Native_Vector_Width_Long (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Long);
end Native_Vector_Width_Long;
function Native_Vector_Width_Float (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Float);
end Native_Vector_Width_Float;
function Native_Vector_Width_Double (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Double);
end Native_Vector_Width_Double;
function Native_Vector_Width_Half (Source : Device) return UInt is
begin
return UInt_Info (Source, Enumerations.Native_Vector_Width_Half);
end Native_Vector_Width_Half;
function Max_Mem_Alloc_Size (Source : Device) return ULong is
begin
return ULong_Info (Source, Enumerations.Max_Mem_Alloc_Size);
end Max_Mem_Alloc_Size;
function Global_Mem_Cache_Size (Source : Device) return ULong is
begin
return ULong_Info (Source, Enumerations.Global_Mem_Cache_Size);
end Global_Mem_Cache_Size;
function Global_Mem_Size (Source : Device) return ULong is
begin
return ULong_Info (Source, Enumerations.Global_Mem_Size);
end Global_Mem_Size;
function Max_Constant_Buffer_Size (Source : Device) return ULong is
begin
return ULong_Info (Source, Enumerations.Max_Constant_Buffer_Size);
end Max_Constant_Buffer_Size;
function Local_Mem_Size (Source : Device) return ULong is
begin
return ULong_Info (Source, Enumerations.Local_Mem_Size);
end Local_Mem_Size;
function Max_Work_Group_Size (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Max_Work_Group_Size);
end Max_Work_Group_Size;
function Image2D_Max_Width (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Image2D_Max_Width);
end Image2D_Max_Width;
function Image2D_Max_Height (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Image2D_Max_Height);
end Image2D_Max_Height;
function Image3D_Max_Width (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Image3D_Max_Width);
end Image3D_Max_Width;
function Image3D_Max_Height (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Image3D_Max_Height);
end Image3D_Max_Height;
function Image3D_Max_Depth (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Image3D_Max_Depth);
end Image3D_Max_Depth;
function Max_Parameter_Size (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Max_Parameter_Size);
end Max_Parameter_Size;
function Profiling_Timer_Resolution (Source : Device) return Size is
begin
return Size_Info (Source, Enumerations.Profiling_Timer_Resolution);
end Profiling_Timer_Resolution;
function Image_Support (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Image_Support));
end Image_Support;
function Error_Correction_Support (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Error_Correction_Support));
end Error_Correction_Support;
function Endian_Little (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Endian_Little));
end Endian_Little;
function Available (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Available));
end Available;
function Compiler_Available (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Compiler_Available));
end Compiler_Available;
function Host_Unified_Memory (Source : Device) return Boolean is
begin
return Boolean (Bool_Info (Source, Enumerations.Host_Unified_Memory));
end Host_Unified_Memory;
function Name (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Name);
end Name;
function Vendor (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Vendor);
end Vendor;
function Driver_Version (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Driver_Version);
end Driver_Version;
function Profile (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Profile);
end Profile;
function Version (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Version);
end Version;
function Extensions (Source : Device) return String is
begin
return String_Info (Source, Enumerations.Extensions);
end Extensions;
function OpenCL_C_Version (Source : Device) return String is
begin
return String_Info (Source, Enumerations.OpenCL_C_Version);
end OpenCL_C_Version;
function Max_Work_Item_Sizes (Source : Device) return Size_List is
function Getter is
new Helpers.Get_Parameters (Return_Element_T => Size,
Return_T => Size_List,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Max_Work_Item_Sizes);
end Max_Work_Item_Sizes;
function Single_Floating_Point_Config (Source : Device)
return Floating_Point_Config is
function Getter is
new Helpers.Get_Parameter (Return_T => Floating_Point_Config,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Single_FP_Config);
end Single_Floating_Point_Config;
function Memory_Cache_Type (Source : Device) return Memory_Cache_Kind is
function Getter is
new Helpers.Get_Parameter (Return_T => Memory_Cache_Kind,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Global_Mem_Cache_Type);
end Memory_Cache_Type;
function Local_Memory_Type (Source : Device) return Local_Memory_Kind is
function Getter is
new Helpers.Get_Parameter (Return_T => Local_Memory_Kind,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Local_Mem_Type);
end Local_Memory_Type;
function Kind (Source : Device) return Device_Kind is
function Getter is
new Helpers.Get_Parameter (Return_T => Device_Kind,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Dev_Type);
end Kind;
function Execution_Capabilities (Source : Device)
return Capability_Vector is
function Getter is
new Helpers.Get_Parameter (Return_T => Capability_Vector,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Execution_Capabilities);
end Execution_Capabilities;
function Command_Queue_Properties (Source : Device)
return CQ_Property_Vector is
function Getter is
new Helpers.Get_Parameter (Return_T => CQ_Property_Vector,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Getter (Source, Enumerations.Queue_Properties);
end Command_Queue_Properties;
function Associated_Platform (Source : Device) return Platform'Class is
function Getter is
new Helpers.Get_Parameter (Return_T => System.Address,
Parameter_T => Enumerations.Device_Info,
C_Getter => API.Get_Device_Info);
begin
return Platform'(Ada.Finalization.Controlled with
Location => Getter (Source, Enumerations.Platform));
end Associated_Platform;
end CL.Platforms;
|
with Entry_Declaration;
procedure Entry_Call is
The_Task : Entry_Declaration.Task_With_Entry;
begin
The_Task.First_Entry;
end Entry_Call;
|
with Interfaces; use Interfaces;
-- @summary functions to provide a string image of numbers
-- overapproximating the length, otherwise too much code needed.
package Generic_Bounded_Image with SPARK_Mode is
generic
type T is (<>); -- any modular type or discrete
function Image_32 (item : T) return String
with Post => Image_32'Result'Length in 1 .. 32 and Image_32'Result'First = 1, Inline;
generic
type T is (<>); -- any modular type or discrete
function Image_4 (item : T) return String
with Post => Image_4'Result'Length in 1 .. 4 and Image_4'Result'First = 1, Inline;
end Generic_Bounded_Image;
|
package body Problem_4 is
function Solution_1 return Integer is
Minimum : constant Integer := 100;
Maximum : constant Integer := 999;
Max_Palindrome : Integer := 0;
Temp : Integer := 0;
begin
for I in Minimum .. Maximum loop
for J in Minimum .. Maximum loop
Temp := I * J;
if Is_Palindrome(Temp) = True then
if Temp > Max_Palindrome then
Max_Palindrome := Temp;
end if;
end if;
end loop;
end loop;
return Max_Palindrome;
end Solution_1;
function Is_Palindrome( Num : Integer ) return Boolean is
Reverse_Num : Integer := 0;
Input_Num : Integer := Num;
begin
while Input_Num > 1 loop
Reverse_Num := 10 * Reverse_Num;
Reverse_Num := Reverse_Num + (Input_Num mod 10);
Input_Num := Input_Num / 10;
end loop;
return Reverse_Num = Num;
end Is_Palindrome;
procedure Test_Solution_1 is
begin
Assert(Solution_1 = 906609);
end Test_Solution_1;
function Get_Solutions return Solution_Case is
Ret : Solution_Case;
begin
Set_Name( Ret, "problem 4");
Add_Test( Ret, Test_Solution_1'Access );
return Ret;
end Get_Solutions;
end Problem_4;
|
------------------------------------------------------------------------------
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
-- This package contains the types and operations related to the configuration
-- of an AURA subsystem
with Progress;
with Unit_Names;
with Registrar.Subsystems;
package Configuration is
------------------------
-- Configuration_Pass --
------------------------
procedure Configuration_Pass;
procedure Process_Root_Configuration;
Configuration_Progress: aliased Progress.Progress_Tracker;
-- For all Subsystems in the Regsitry of State Aquired, Configuration_Pass
-- attempts to promote the Subsystem to Available, if possible.
--
-- ** Any Subsystems checked-out from "System" repositories are promoted to
-- "Available" during Checkout, and will not be configured. These
-- subsystems were configured at build-time for the repository.
--
-- The Configuration_Pass process for each Subsystem is as follows:
--
-- 1. If a Registry entry for the expected configuration file (AURA.XYZ)
-- exists, its hash is compared with the hash of the same configuration
-- from Last_Run (if Last_Run exists). If the hash differs, the process
-- progresses immediately to Step 3.
--
-- If there is no configuration unit but a manifest exists, the process
-- progresses immediately to Step 2.
--
-- If the hash does not differ, the pre-loaded configuration information
-- is copied from Last_Run, and the process progresses immediately to
-- Step 4
--
-- If there is no configuration unit and no manifest, an empty
-- configuration unit is generated, and configuration is deemed complete.
--
-- -- Root Configuration special case -----------------------------------
-- The AURA subsystem is handled as a special case, particularily there
-- may be a configuration file with the unit name "aura.root" The root
-- configuration unit never has a manifest.
-- ----------------------------------------------------------------------
--
-- If Process_Root_Configuration is invoked, the AURA subsystem is
-- entered for configuration.
--
-- If the root configuration package exists, and the hash differs, then
-- Step 3 is invoked for it, otherwise Step 4 is invoked.
--
-- The Root Configuration package shall not have a Codepaths package.
--
-- 2. Step 2 installs the default configuration unit from the manifest.
--
-- Step 2 is always followed by Step 3
--
-- 3. Step 3 attempts to build, run, and extract the relevent values from
-- the configuration unit.
--
-- a) The configuration unit is scanned for relevent configuration
-- parameters. If no relevent parameters are found, configuration is
-- deemed complete.
--
-- Currently, relevent configuration parameters must always and only
-- be constant String objects. If this is violated, the process is
-- aborted.
--
-- b) The relevant configuration parameters are then used to auto-
-- generate a temporary program to extract the value of those
-- parameters. If the program fails to compile, the process is
-- aborted. If the program completes abnormally, the process is
-- aborted.
--
-- If the program completes successfully, the configuration values
-- have been loaded, Configuration is complete, and the Subsystem is
-- updated in the registry
--
-- 4. The subsystem's configuration data has been loaded. If there are any
-- codepaths configured, those subdirectories are entered with the
-- registrar. Configuration is deemed complete, and the Subsystem becomes
-- "Available"
--
-- Callers to Configuration_Pass should wait for
-- Registrar.Registration.Entry_Progress after Configuration_Progress,
-- except for Process_Root_Configuration
-- Utility functions
function Config_Unit_Name (Target: Registrar.Subsystems.Subsystem)
return Unit_Names.Unit_Name;
-- Returns the unit name of the configuration unit for a given subsystem
function Manifest_Unit_Name (Target: Registrar.Subsystems.Subsystem)
return Unit_Names.Unit_Name;
-- Returns the unit name of the manifest unit for a given subsystem
end Configuration;
|
with
ada.Numerics.Float_random,
ada.Numerics.Discrete_random;
package body any_Math.any_Random
is
use ada.Numerics;
package Boolean_random is new ada.numerics.discrete_Random (Boolean);
real_Generator : Float_random .Generator;
boolean_Generator : Boolean_random.Generator;
function random_Boolean return Boolean
is
begin
return Boolean_random.Random (boolean_Generator);
end random_Boolean;
function random_Real (Lower : in Real := Real'First;
Upper : in Real := Real'Last) return Real
is
base_Roll : constant Float := Float_random.Random (Real_Generator);
begin
return Lower
+ Real (base_Roll) * (Upper - Lower);
end random_Real;
function random_Integer (Lower : in Integer := Integer'First;
Upper : in Integer := Integer'Last) return Integer
is
Modulus : constant Positive := Upper - Lower + 1;
base_Roll : constant Float := Float_random.Random (Real_Generator);
begin
return Lower
+ Integer (Float (Modulus) * base_Roll) mod Modulus;
end random_Integer;
begin
Boolean_random.reset (boolean_Generator);
Float_random .reset ( real_Generator);
end any_math.any_Random;
|
-----------------------------------------------------------------------
-- util-commands-parsers.gnat_parser -- GNAT command line parser for command drivers
-- Copyright (C) 2018, 2019, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with GNAT.OS_Lib;
package body Util.Commands.Parsers.GNAT_Parser is
function To_OS_Lib_Argument_List (Args : in Argument_List'Class)
return GNAT.OS_Lib.Argument_List_Access;
function To_OS_Lib_Argument_List (Args : in Argument_List'Class)
return GNAT.OS_Lib.Argument_List_Access is
Count : constant Natural := Args.Get_Count;
New_Arg : GNAT.OS_Lib.Argument_List (1 .. Count);
begin
for I in 1 .. Count loop
New_Arg (I) := new String '(Args.Get_Argument (I));
end loop;
return new GNAT.OS_Lib.Argument_List '(New_Arg);
end To_OS_Lib_Argument_List;
-- ------------------------------
-- Get all the remaining arguments from the GNAT command line parse.
-- ------------------------------
procedure Get_Arguments (List : in out Dynamic_Argument_List;
Command : in String;
Parser : in GC.Opt_Parser := GC.Command_Line_Parser) is
begin
List.Name := Ada.Strings.Unbounded.To_Unbounded_String (Command);
loop
declare
S : constant String := GC.Get_Argument (Parser => Parser);
begin
exit when S'Length = 0;
List.List.Append (S);
end;
end loop;
end Get_Arguments;
procedure Execute (Config : in out Config_Type;
Args : in Util.Commands.Argument_List'Class;
Process : not null access
procedure (Cmd_Args : in Commands.Argument_List'Class)) is
use type GC.Command_Line_Configuration;
Empty : Config_Type;
begin
if Config /= Empty then
declare
Parser : GC.Opt_Parser;
Cmd_Args : Dynamic_Argument_List;
Params : GNAT.OS_Lib.Argument_List_Access
:= To_OS_Lib_Argument_List (Args);
begin
GC.Initialize_Option_Scan (Parser, Params);
GC.Getopt (Config => Config, Parser => Parser);
Get_Arguments (Cmd_Args, Args.Get_Command_Name, Parser);
Process (Cmd_Args);
GC.Free (Config);
GNAT.OS_Lib.Free (Params);
exception
when others =>
GNAT.OS_Lib.Free (Params);
GC.Free (Config);
raise;
end;
else
Process (Args);
end if;
end Execute;
procedure Usage (Name : in String;
Config : in out Config_Type) is
Opts : constant String := GC.Get_Switches (Config);
begin
if Opts'Length > 0 then
GC.Set_Usage (Config, Usage => Name & " [switches] [arguments]");
GC.Display_Help (Config);
end if;
end Usage;
end Util.Commands.Parsers.GNAT_Parser;
|
with System.Startup;
package body Ada.Command_Line is
-- implementation
function Argument (Number : Positive) return String is
pragma Check (Pre,
Check => Number <= Argument_Count or else raise Constraint_Error);
begin
return System.Native_Command_Line.Argument (Number);
end Argument;
function Has_Element (Position : Natural) return Boolean is
pragma Check (Pre,
Check => Position <= Argument_Count or else raise Constraint_Error);
begin
return Position > 0;
end Has_Element;
function Iterate return Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Iterate (1, Argument_Count);
end Iterate;
function Iterate (First : Positive; Last : Natural)
return Iterator_Interfaces.Reversible_Iterator'Class
is
pragma Check (Pre,
Check =>
(First <= Argument_Count + 1 and then Last <= Argument_Count)
or else raise Constraint_Error);
Actual_First : Natural := First;
Actual_Last : Natural := Last;
begin
if Actual_Last < Actual_First then
Actual_First := 0;
Actual_Last := 0;
end if;
return Iterator'(First => Actual_First, Last => Actual_Last);
end Iterate;
function Command_Name return String is
begin
return System.Native_Command_Line.Argument (0);
end Command_Name;
procedure Set_Exit_Status (Code : Exit_Status) is
begin
System.Startup.Exit_Status := Integer (Code);
end Set_Exit_Status;
-- implementation of the non-abstract iterator
overriding function First (Object : Concrete_Iterator) return Natural is
pragma Unreferenced (Object);
begin
if Argument_Count = 0 then
return 0;
else
return 1;
end if;
end First;
overriding function Next (Object : Concrete_Iterator; Position : Natural)
return Natural
is
pragma Unreferenced (Object);
begin
if Position >= Argument_Count then
return 0;
else
return Position + 1;
end if;
end Next;
-- implementation of the iterator
overriding function First (Object : Iterator) return Natural is
begin
return Object.First;
end First;
overriding function Next (Object : Iterator; Position : Natural)
return Natural is
begin
if Position >= Object.Last then
return 0;
else
return Position + 1;
end if;
end Next;
overriding function Last (Object : Iterator) return Natural is
begin
return Object.Last;
end Last;
overriding function Previous (Object : Iterator; Position : Natural)
return Natural is
begin
if Position <= Object.First then
return 0;
else
return Position - 1;
end if;
end Previous;
end Ada.Command_Line;
|
$NetBSD: patch-posix-signals.adb,v 1.5 2014/04/30 16:27:04 marino Exp $
Fix style check violation for GNAT 4.9
--- posix-signals.adb.orig 2012-05-10 13:32:11.000000000 +0000
+++ posix-signals.adb
@@ -340,16 +340,18 @@ package body POSIX.Signals is
begin
for Sig in Signal loop
if Reserved_Signal (Sig) then
- if Sig /= SIGKILL and then Sig /= SIGSTOP and then
- sigismember (Set.C'Unchecked_Access, int (Sig)) = 1 then
- Raise_POSIX_Error (Invalid_Argument);
+ if Sig /= SIGKILL and then Sig /= SIGSTOP then
+ if sigismember (Set.C'Unchecked_Access, int (Sig)) = 1 then
+ Raise_POSIX_Error (Invalid_Argument);
+ end if;
end if;
else
-- This signal might be attached to a
-- task entry or protected procedure
if sigismember (Set.C'Unchecked_Access, int (Sig)) = 1
- and then (SI.Is_Entry_Attached (SIID (Sig))
- or else SI.Is_Handler_Attached (SIID (Sig))) then
+ and then (SI.Is_Entry_Attached (SIID (Sig))
+ or else SI.Is_Handler_Attached (SIID (Sig)))
+ then
Raise_POSIX_Error (Invalid_Argument);
end if;
end if;
@@ -466,7 +468,8 @@ package body POSIX.Signals is
(Set : Signal_Set; Sig : Signal) return Boolean is
begin
if Sig = Signal_Null
- or else sigismember (Set.C'Unchecked_Access, int (Sig)) = 1 then
+ or else sigismember (Set.C'Unchecked_Access, int (Sig)) = 1
+ then
return True;
end if;
return False;
@@ -500,8 +503,7 @@ package body POSIX.Signals is
if not Reserved_Signal (Sig) then
-- It is OK to modify this signal's masking, using the
-- interfaces of System.Interrupts.
- if sigismember
- (New_Mask.C'Unchecked_Access, int (Sig)) = 1 then
+ if sigismember (New_Mask.C'Unchecked_Access, int (Sig)) = 1 then
if not SI.Is_Blocked (SIID (Sig)) then
Disposition (Sig) := SI_To_Mask;
end if;
@@ -551,8 +553,7 @@ package body POSIX.Signals is
if not Reserved_Signal (Sig) then
-- It is OK to modify this signal's masking, using the
-- interfaces of System.Interrupts.
- if sigismember
- (Mask_to_Add.C'Unchecked_Access, int (Sig)) = 1 then
+ if sigismember (Mask_to_Add.C'Unchecked_Access, int (Sig)) = 1 then
if not SI.Is_Blocked (SIID (Sig)) then
Disposition (Sig) := SI_To_Mask;
end if;
@@ -602,7 +603,8 @@ package body POSIX.Signals is
-- It is OK to modify this signal's masking, using the
-- interfaces of System.Interrupts.
if sigismember
- (Mask_to_Subtract.C'Unchecked_Access, int (Sig)) = 1 then
+ (Mask_to_Subtract.C'Unchecked_Access, int (Sig)) = 1
+ then
if SI.Is_Blocked (SIID (Sig)) then
Disposition (Sig) := SI_To_Unmask;
end if;
@@ -639,7 +641,8 @@ package body POSIX.Signals is
-- may be more values in POSIX.Signal
-- than System.Interrupts.Interrupt_ID
if pthread_sigmask
- (SIG_BLOCK, null, Old_Mask.C'Unchecked_Access) = 0 then
+ (SIG_BLOCK, null, Old_Mask.C'Unchecked_Access) = 0
+ then
null;
end if;
-- Delete any ublocked signals from System.Interrupts.
@@ -1004,8 +1007,7 @@ package body POSIX.Signals is
Result : aliased int;
begin
Check_Awaitable (Set);
- if sigwait
- (Set.C'Unchecked_Access, Result'Unchecked_Access) = -1 then
+ if sigwait (Set.C'Unchecked_Access, Result'Unchecked_Access) = -1 then
Raise_POSIX_Error (Fetch_Errno);
end if;
return Signal (Result);
@@ -1156,7 +1158,8 @@ begin
if Integer (Sig) <= Integer (SIID'Last) then
if SI.Is_Reserved (SIID (Sig)) and then (Sig /= SIGKILL
- and Sig /= SIGSTOP) then
+ and Sig /= SIGSTOP)
+ then
Reserved_Signal (Sig) := True;
end if;
else
|
--
-- \brief Tests for JWX.JSON
-- \author Alexander Senier
-- \date 2018-05-12
--
-- Copyright (C) 2018 Componolit GmbH
--
-- This file is part of JWX, which is distributed under the terms of the
-- GNU Affero General Public License version 3.
--
with AUnit; use AUnit;
with AUnit.Test_Cases; use AUnit.Test_Cases;
package JWX_JSON_Tests is
type Test_Case is new Test_Cases.Test_Case with null record;
procedure Register_Tests (T: in out Test_Case);
-- Register routines to be run
function Name (T : Test_Case) return Message_String;
-- Provide name identifying the test case
end JWX_JSON_Tests;
|
with Generic_AVL_Tree, Ada.Numerics.Discrete_Random;
with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line;
procedure Main is
Num_Insertions : Integer := 0;
Num_Queries : Integer;
Scratch : Boolean;
Rand : Integer;
procedure Integer_Put( Item: Integer ) is
begin
Put( Item );
end Integer_Put;
package Int_AVL_Tree is
new Generic_AVL_Tree( Element_Type => Integer,
Less_Than => "<",
Greater_Than => ">",
Put => Integer_Put );
package Random_Int is new Ada.Numerics.Discrete_Random(Integer);
List : Int_AVL_Tree.T;
G : Random_Int.Generator;
-- Sequence_File : Ada.Text_IO.File_Type;
procedure Print_Usage is
begin
New_Line;
Put("Usage: " & Command_Name & " <number of insertions> <number of queries>");
New_Line; New_Line;
end Print_Usage;
begin
if Argument_Count /= 2 then
Print_Usage;
else
begin
Num_Insertions := Positive'Value( Argument(1) );
Num_Queries := Natural'Value( Argument(2) );
exception
when Constraint_Error =>
Print_Usage;
raise;
when others =>
raise;
end;
end if;
if Num_Insertions > 0 then
-- Put("Inserting 2^(" & Integer'Image(Num_Insertions));
-- Put(") elements and then making 2^(" & Integer'Image(Num_Queries));
-- Put_Line(") queries.");
-- Open( Sequence_File, In_File, Name => "sequence.dat" );
Random_Int.Reset(G);
begin
for I in 1 .. 2**Num_Insertions loop
Rand := Random_Int.Random(G);
-- Put( Sequence_File, Rand ); New_Line( Sequence_File );
-- Get( Sequence_File, Rand );
Int_AVL_Tree.Insert( List, Rand );
end loop;
exception
when others =>
-- Close( Sequence_File );
raise;
end;
-- Close( Sequence_File );
for I in 1 .. 2**Num_Queries loop
Scratch := Int_AVL_Tree.Is_In_Tree( List, Random_Int.Random(G) );
end loop;
-- Put_Line("Done.");
end if;
end Main;
|
-- This unit is based on BBqueue.Buffers and uses markers in the buffer to
-- track the size of each commited write grants. The size of consequent read
-- grants will conrespond to the sizes of commited write grants.
--
-- It can be used to handle variable lenght packets:
--
-- Q : aliased Framed_Buffer (64);
-- WG : Write_Grant := Empty;
-- RG : Read_Grant := Empty;
-- S : Slice_Rec;
-- begin
-- Grant (Q, WG, 8); -- Get a worst case grant of size 8
-- Commit (Q, WG, 4); -- Only commit 4
-- Grant (Q, WG, 8); -- Get a worst case grant of size 8
-- Commit (Q, WG, 5); -- Only commit 5
-- Read (W, RG); -- Returns a grant of size 4
with System;
package BBqueue.Buffers.framed
with Preelaborate,
SPARK_Mode,
Abstract_State => null
is
Max_Frame_Header_Size : constant := 9;
subtype Framed_Count
is Count range Count'First .. Count'Last - Max_Frame_Header_Size;
-- The frame can take up to 9 bytes in addition to the allocated size. The
-- size of what can be allocated is therefore lower than for a non-framed
-- buffer.
type Framed_Buffer (Size : Buffer_Size)
is limited private;
-- Producer --
type Write_Grant is limited private;
procedure Grant (This : in out Framed_Buffer;
G : in out Write_Grant;
Size : Framed_Count)
with Pre => State (G) /= Valid,
Post => State (G) in Valid | Empty | Grant_In_Progress | Insufficient_Size
and then
(if State (G) = Valid then Write_Grant_In_Progress (This));
-- Request a contiguous writeable slice of the internal buffer
procedure Commit (This : in out Framed_Buffer;
G : in out Write_Grant;
Size : Framed_Count := Framed_Count'Last)
with Pre => State (G) = Valid,
Post => (if Write_Grant_In_Progress (This)'Old
then State (G) = Empty
else State (G) = Valid);
-- Commit a writeable slice. Size can be smaller than the granted slice for
-- partial commits. The commited slice is then available for Read.
generic
with procedure Process_Write (Data : out Storage_Array; To_Commit : out Count);
procedure Write_CB (This : in out Framed_Buffer;
Size : Framed_Count;
Result : out Result_Kind);
-- Write in the buffer using a "callback". This procedure will call
-- Process_Write () on the slice returned by Grant (), if the result
-- is Valid. It will then call Commit with the value To_Commit returned by
-- Process_Write ().
-- Consumer --
type Read_Grant is limited private;
procedure Read (This : in out Framed_Buffer;
G : in out Read_Grant)
with Pre => State (G) /= Valid,
Post => State (G) in Valid | Empty | Grant_In_Progress
and then
(if State (G) = Valid then Read_Grant_In_Progress (This));
-- Request contiguous readable slice from the internal buffer. The size of
-- the returned Read_Grant will be based on the size of previously commited
-- frames.
procedure Release (This : in out Framed_Buffer;
G : in out Read_Grant)
with Pre => State (G) = Valid,
Post => (if Read_Grant_In_Progress (This)'Old
then State (G) = Empty
else State (G) = Valid);
-- Release a readable slice. Partial releases not allowed, the full grant
-- will be released.
generic
with procedure Process_Read (Data : Storage_Array);
procedure Read_CB (This : in out Framed_Buffer;
Result : out Result_Kind);
-- Read from the buffer using a "callback". This procedure will call
-- Process_Read () on the slice returned by Read (), if the result is Valid.
-- Utils --
function Empty return Write_Grant
with Post => State (Empty'Result) = Empty;
function Empty return Read_Grant
with Post => State (Empty'Result) = Empty;
function State (G : Write_Grant) return Result_Kind;
function Slice (G : Write_Grant) return Slice_Rec
with Pre => State (G) = Valid;
function State (G : Read_Grant) return Result_Kind;
function Slice (G : Read_Grant) return Slice_Rec
with Pre => State (G) = Valid;
function Write_Grant_In_Progress (This : Framed_Buffer) return Boolean
with Ghost;
function Read_Grant_In_Progress (This : Framed_Buffer) return Boolean
with Ghost;
private
subtype Header_Count is Framed_Count range 0 .. Max_Frame_Header_Size;
type Framed_Buffer (Size : Buffer_Size) is limited record
Buffer : BBqueue.Buffers.Buffer (Size);
Current_Read_Size : Framed_Count := 0;
-- This stores the size of the current read frame, between Read and
-- Release. It is used to prove that the release size (Header_Size +
-- Current_Read_Size) doesn't overflow.
end record;
function Empty_Slicerec return Slice_Rec
is (0, System.Null_Address);
type Write_Grant is limited record
Grant : BBqueue.Buffers.Write_Grant;
Header_Size : Header_Count := 0;
end record;
type Read_Grant is limited record
Grant : BBqueue.Buffers.Read_Grant;
Header_Size : Header_Count := 0;
end record;
function State (G : Write_Grant) return Result_Kind
is (BBqueue.Buffers.State (G.Grant));
function Empty return Write_Grant
is (Grant => BBqueue.Buffers.Empty, others => <>);
function Slice (G : Write_Grant) return Slice_Rec
is (BBqueue.Buffers.Slice (G.Grant));
function State (G : Read_Grant) return Result_Kind
is (BBqueue.Buffers.State (G.Grant));
function Empty return Read_Grant
is (Grant => BBqueue.Buffers.Empty, others => <>);
function Slice (G : Read_Grant) return Slice_Rec
is (BBqueue.Buffers.Slice (G.Grant));
-----------------------------
-- Write_Grant_In_Progress --
-----------------------------
function Write_Grant_In_Progress (This : Framed_Buffer) return Boolean
is (Write_Grant_In_Progress (This.Buffer));
----------------------------
-- Read_Grant_In_Progress --
----------------------------
function Read_Grant_In_Progress (This : Framed_Buffer) return Boolean
is (Read_Grant_In_Progress (This.Buffer));
end BBqueue.Buffers.framed;
|
-- root package: ${self.name}
with Ada.Unchecked_Deallocation;
with Generic_List;
with Generic_FIFO;
with Ada.Tags;
with Application_Types;
use type Application_Types.Base_Integer_Type;
use type Application_Types.Base_Float_Type;
use type Application_Types.Base_Text_Type;
use type Application_Types.Time_Unit;
package ${self.name} is
------------------------------------------------------------------------
--********************* Object Definition *****************************
------------------------------------------------------------------------
Object_String : String := "${self.name} ";
type Object_Type;
type Object_Access is access all Object_Type'Class;
type Object_Type is tagged
record
Root_Object_Attribute: Integer;
Next_Object: Object_Access := null;
Previous_Object: Object_Access := null;
end record;
function Get_Next_Root_Object_Attribute return Integer;
------------------------------------------------------------------------
--********************* Object Management *****************************
------------------------------------------------------------------------
function Create return Object_Access;
procedure Description (This_Object: in Object_Type);
procedure Delete (Old_Object: in out Object_Access);
--------------------------------------------------------------------------
----************************ Event Stuff ********************************
--------------------------------------------------------------------------
function Get_Root_Event_Attribute return Integer;
function Get_Next_Root_Event_Attribute return Integer;
procedure Do_Events;
type Root_Event_Type;
type Root_Event_Access_Type is access Root_Event_Type'Class;
type Root_Event_Type is tagged
record
Root_Event_Attribute: Integer := Get_Next_Root_Event_Attribute;
Next_Event: Root_Event_Access_Type := null;
Previous_Event: Root_Event_Access_Type := null;
end record;
Root_Event_Number: Integer := 0;
procedure Process_Events (This_Event: in Root_Event_Type);
procedure Put_Event (Event: in Root_Object.Root_Event_Access_Type;
To_Class: in Object_Type;
Top: in Boolean := False);
procedure Event_Action (Dispatch_Event: in Root_Event_Type;
This_Event: in out Root_Event_Access_Type);
procedure Polymorphic_Put (This_Object: in out Object_Type; This_Event: in Root_Event_Access_Type);
procedure Free is new Ada.Unchecked_Deallocation (Root_Event_Type'Class, Root_Event_Access_Type );
package Object_List is new Generic_List (Object_Access);
------------------------------------------------------------------------
--******************* Navigation Utilities ****************************
------------------------------------------------------------------------
Access_Type_Size: Natural := Object_Access'Size;
function Size_Of_Access return Natural;
function Size_Of_Boolean return Natural;
type Formalised_Relationship_Write_Type is access
procedure (This_Object: in Object_Access;
Remote_Value: in Object_Access);
type Formalised_Relationship_Read_Type is access
function (This_Object: Object_Access) return Object_Access;
type Formalised_Multiple_Relationship_Write_Type is access
procedure (This_Object: in Object_Access;
Remote_Value: in Root_Object.Object_List.List_Header_Access_Type);
type Formalised_Multiple_Relationship_Read_Type is access
function (This_Object: Object_Access) return Root_Object.Object_List.List_Header_Access_Type;
end ${self.name};
|
pragma License (Unrestricted);
with Ada.Numerics.Generic_Elementary_Functions;
package Ada.Numerics.Elementary_Functions is
new Generic_Elementary_Functions (Float);
pragma Pure (Ada.Numerics.Elementary_Functions);
|
------------------------------------------------------------------------------
-- --
-- Giza --
-- --
-- Copyright (C) 2016 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 Giza.Widget.Composite; use Giza.Widget.Composite;
with Giza.Widget.Tiles;
with Giza.Widget.Button;
with Giza.Widget.Text;
use Giza.Widget;
package Giza.Widget.Keyboards is
subtype Parent is Giza.Widget.Composite.Instance;
type Instance is new Parent with private;
subtype Class is Instance'Class;
type Ref is access all Class;
procedure On_Init (This : in out Instance);
overriding
procedure Draw (This : in out Instance;
Ctx : in out Context.Class;
Force : Boolean := True);
overriding
function On_Position_Event
(This : in out Instance;
Evt : Position_Event_Ref;
Pos : Point_T) return Boolean;
procedure Set_Max_Entry_Length (This : in out Instance; Len : Natural);
function Get_Text (This : Instance) return String;
private
type Button_Type is
(Btn_1, Btn_2, Btn_3, Btn_4, Btn_5, Btn_6, Btn_7, Btn_8, Btn_9, Btn_0,
Btn_Q, Btn_W, Btn_E, Btn_R, Btn_T, Btn_Y, Btn_U, Btn_I, Btn_O, Btn_P,
Btn_Caps, Btn_A, Btn_S, Btn_D, Btn_F, Btn_G, Btn_H, Btn_J, Btn_K, Btn_L,
Btn_Nothing, Btn_Z, Btn_X, Btn_C, Btn_V, Btn_B, Btn_N, Btn_M, Btn_Del,
Btn_Return, Btn_Special, Btn_Space, Btn_OK);
type Button_Pos_Type is record
Line, Row : Natural;
end record;
Button_To_Pos : constant array (Button_Type) of Button_Pos_Type :=
(Btn_1 => (1, 1), Btn_2 => (1, 2), Btn_3 => (1, 3), Btn_4 => (1, 4),
Btn_5 => (1, 5), Btn_6 => (1, 6), Btn_7 => (1, 7), Btn_8 => (1, 8),
Btn_9 => (1, 9), Btn_0 => (1, 10),
Btn_Q => (2, 1), Btn_W => (2, 2), Btn_E => (2, 3), Btn_R => (2, 4),
Btn_T => (2, 5), Btn_Y => (2, 6), Btn_U => (2, 7), Btn_I => (2, 8),
Btn_O => (2, 9), Btn_P => (2, 10),
Btn_Caps => (3, 1), Btn_A => (3, 2), Btn_S => (3, 3), Btn_D => (3, 4),
Btn_F => (3, 5), Btn_G => (3, 6), Btn_H => (3, 7), Btn_J => (3, 8),
Btn_K => (3, 9), Btn_L => (3, 10),
Btn_Nothing => (4, 1), Btn_Z => (4, 2), Btn_X => (4, 3), Btn_C => (4, 4),
Btn_V => (4, 5), Btn_B => (4, 6), Btn_N => (4, 7), Btn_M => (4, 8),
Btn_Del => (4, 9), Btn_Return => (4, 10),
Btn_Special => (5, 1), Btn_Space => (5, 2), Btn_OK => (5, 3));
type Tiles_10_Array is array (Integer range <>) of
aliased Tiles.Instance (10, Tiles.Left_Right);
type Gbutton_Array is array (Button_Type) of
aliased Button.Instance;
type Instance is new Parent with record
Initialised : Boolean := False;
Max_Text_Len : Natural := 100;
Text_Display : aliased Text.Instance;
Cursor : Natural;
Root : aliased Tiles.Instance (5, Tiles.Top_Down);
Lines : Tiles_10_Array (1 .. 4);
Last_Line : aliased Tiles.Instance (3, Tiles.Left_Right);
Buttons : Gbutton_Array;
Caps : Boolean := False;
Special : Boolean := False;
end record;
end Giza.Widget.Keyboards;
|
-- =============================================================================
-- Package AVR.SPI
--
-- Handles the SPI.
-- =============================================================================
package AVR.SPI is
type SPI_Control_Register_Type is
record
SPR0 : Boolean;
SPR1 : Boolean;
CPHA : Boolean;
CPOL : Boolean;
MSTR : Boolean;
DORD : Boolean;
SPE : Boolean;
SPIE : Boolean;
end record;
pragma Pack (SPI_Control_Register_Type);
for SPI_Control_Register_Type'Size use BYTE_SIZE;
type SPI_Status_Register_Type is
record
SPI2X : Boolean;
Spare : Spare_Type (0 .. 4);
WCOL : Boolean;
SPIF : Boolean;
end record;
pragma Pack (SPI_Status_Register_Type);
for SPI_Status_Register_Type'Size use BYTE_SIZE;
type SPI_Data_Register_Type is new Byte_Type;
Reg_SPCR : SPI_Control_Register_Type;
for Reg_SPCR'Address use System'To_Address (16#4C#);
Reg_SPSR : SPI_Status_Register_Type;
for Reg_SPSR'Address use System'To_Address (16#4D#);
Reg_SPDR : SPI_Data_Register_Type;
for Reg_SPDR'Address use System'To_Address (16#4E#);
end AVR.SPI;
|
with Resource.Web;
with Resource.Config;
with Ada.Command_Line;
with Ada.Text_IO;
procedure Test3 is
use Resource;
C : Content_Access := Web.Get_Content ("main.html");
begin
if C = null then
Ada.Text_IO.Put_Line ("FAIL: No content 'main.html'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if C'Length /= 360 then
Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'main.html'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
C := Web.Get_Content ("images/wiki-create.png");
if C = null then
Ada.Text_IO.Put_Line ("FAIL: No content 'images/wiki-create.png'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if C'Length /= 3534 then
Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'images/wiki-create.png'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
C := Web.Get_Content ("not-included.xml");
if C /= null then
Ada.Text_IO.Put_Line ("FAIL: Content was included 'not-included.xml'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
C := Web.Get_Content ("preview/main-not-included.html");
if C /= null then
Ada.Text_IO.Put_Line ("FAIL: Content was included 'preview/main-not-included.html'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
C := Web.Get_Content ("js/main.js");
if C = null then
Ada.Text_IO.Put_Line ("FAIL: No content 'js/main.js'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if C'Length /= 90 then
Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'js/main.js'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
C := Web.Get_Content ("css/main.css");
if C = null then
Ada.Text_IO.Put_Line ("FAIL: No content 'css/main.css'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if C'Length /= 94 then
Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'css/main.css'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
C := Web.Get_Content ("not-included.txt");
if C /= null then
Ada.Text_IO.Put_Line ("FAIL: Content was included 'not-included.txt'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
C := Config.Get_Content ("test3.xml");
if C = null then
Ada.Text_IO.Put_Line ("FAIL: No content 'test3.xml'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
if C'Length /= 18 then
Ada.Text_IO.Put_Line ("FAIL: Invalid length for 'test3.xml'");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
end if;
Ada.Text_IO.Put ("PASS: ");
for Val of C.all loop
if Character'Val (Val) /= ASCII.LF then
Ada.Text_IO.Put (Character'Val (Val));
end if;
end loop;
Ada.Text_IO.New_Line;
end Test3;
|
-- { dg-do run }
with System.Storage_Elements; use System.Storage_Elements;
with Ada.Unchecked_Deallocation;
procedure Allocator_Maxalign1 is
Max_Alignment : constant := Standard'Maximum_Alignment;
type Block is record
X : Integer;
end record;
for Block'Alignment use Standard'Maximum_Alignment;
type Block_Access is access all Block;
procedure Free is new Ada.Unchecked_Deallocation (Block, Block_Access);
N_Blocks : constant := 500;
Blocks : array (1 .. N_Blocks) of Block_Access;
begin
if Block'Alignment /= Max_Alignment then
raise Program_Error;
end if;
for K in 1 .. 4 loop
for I in Blocks'Range loop
Blocks (I) := new Block;
if Blocks (I).all'Address mod Block'Alignment /= 0 then
raise Program_Error;
end if;
Blocks(I).all.X := I;
end loop;
for I in Blocks'Range loop
Free (Blocks (I));
end loop;
end loop;
end;
|
-- Project: Strato
-- System: Stratosphere Balloon Flight Controller
-- Author: Martin Becker (becker@rcs.ei.tum.de)
-- @summary String functions
package body MyStrings with SPARK_Mode is
procedure StrCpySpace (outstring : out String; instring : String) is
begin
if instring'Length >= outstring'Length then
-- trim
outstring := instring (instring'First .. instring'First - 1 + outstring'Length);
else
-- pad
declare
lastidx : constant Natural := outstring'First + instring'Length - 1;
begin
outstring := (others => ' ');
outstring (outstring'First .. lastidx) := instring;
end;
end if;
end StrCpySpace;
function RTrim (S : String) return String is
begin
for J in reverse S'Range loop
if S (J) /= ' ' then
return S (S'First .. J);
end if;
end loop;
return "";
end RTrim;
function LTrim (S : String) return String is
begin
for J in S'Range loop
if S (J) /= ' ' then
return S (J .. S'Last);
end if;
end loop;
return "";
end LTrim;
function Trim (S : String) return String is
begin
return LTrim (RTrim (S));
end Trim;
function StrChr (S : String; C : Character) return Integer is
begin
for idx in S'Range loop
if S (idx) = C then
return idx;
end if;
end loop;
return S'Last + 1;
end StrChr;
function Is_AlNum (c : Character) return Boolean is
begin
return (c in 'a' .. 'z') or (c in 'A' .. 'Z') or (c in '0' .. '9');
end Is_AlNum;
function Strip_Non_Alphanum (s : String) return String with SPARK_Mode => Off is
tmp : String (1 .. s'Length) := s;
len : Integer := 0;
begin
for c in s'Range loop
if Is_AlNum (s (c)) then
len := len + 1;
tmp (len) := s (c);
end if;
end loop;
declare
ret : constant String (1 .. len) := tmp (1 .. len); -- SPARK: "subtype constraint cannot depend on len"
begin
return ret;
end;
end Strip_Non_Alphanum;
end MyStrings;
|
with Ada.Text_IO;
use Ada.Text_IO;
procedure AdaHelloworld is
begin
Put_Line ("Hello world");
end AdaHelloWorld; |
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2013, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
package body Netutils is
function To_In_Addr (Addr : Ip_Addr) return In_Addr is
begin
return Shift_Left (Unsigned_32 (Addr (1)), 24)
or Shift_Left (Unsigned_32 (Addr (2)), 16)
or Shift_Left (Unsigned_32 (Addr (3)), 8)
or Shift_Left (Unsigned_32 (Addr (4)), 0);
end To_In_Addr;
function To_Ip_Addr (Addr : In_Addr) return Ip_Addr is
Res : Ip_Addr;
Tmp : In_Addr := Addr;
begin
for I in reverse Res'Range loop
Res (I) := Unsigned_8 (Tmp and 16#ff#);
Tmp := Shift_Right (Tmp, 8);
end loop;
return Res;
end To_Ip_Addr;
procedure Put_Dec (V : Unsigned_8) is
Res : String (1 .. 3);
P : Natural := Res'Last;
Val : Unsigned_8 := V;
begin
loop
Res (P) := Character'Val (Character'Pos ('0') + Val mod 10);
Val := Val / 10;
exit when Val = 0;
P := P - 1;
end loop;
Put (Res (P .. Res'Last));
end Put_Dec;
procedure Put_Dec (V : Unsigned_16) is
Res : String (1 .. 5);
P : Natural := Res'Last;
Val : Unsigned_16 := V;
begin
loop
Res (P) := Character'Val (Character'Pos ('0') + Val mod 10);
Val := Val / 10;
exit when Val = 0;
P := P - 1;
end loop;
Put (Res (P .. Res'Last));
end Put_Dec;
procedure Put_Hex (V : Unsigned_8) is
begin
pragma Warnings (Off, "loop range may be null");
for I in reverse 0 .. 1 loop
Put (Hex_Digits (Natural (Shift_Right (V, 4 * I) and 15)));
end loop;
pragma Warnings (On, "loop range may be null");
end Put_Hex;
procedure Put_Hex (V : Unsigned_16) is
begin
for I in reverse 0 .. 3 loop
Put (Hex_Digits (Natural (Shift_Right (V, 4 * I) and 15)));
end loop;
end Put_Hex;
procedure Put_Hex (V : Unsigned_32) is
begin
for I in reverse 0 .. 7 loop
Put (Hex_Digits (Natural (Shift_Right (V, 4 * I) and 15)));
end loop;
end Put_Hex;
procedure Disp_Ip_Addr (Addr : Ip_Addr) is
begin
for I in 1 .. 3 loop
Put_Dec (Addr (I));
Put ('.');
end loop;
Put_Dec (Addr (4));
end Disp_Ip_Addr;
procedure Disp_Ip_Addr (Addr : In_Addr) is
begin
Disp_Ip_Addr (To_Ip_Addr (Addr));
end Disp_Ip_Addr;
procedure Disp_Eth_Addr (Addr : Eth_Addr) is
begin
for I in Addr'Range loop
Put_Hex (Addr (I));
exit when I = Addr'Last;
Put (':');
end loop;
end Disp_Eth_Addr;
function Read_BE1 (Off : Natural) return Unsigned_8 is
begin
return Packet (Off);
end Read_BE1;
function Read_BE2 (Off : Natural) return Unsigned_16 is
begin
return Shift_Left (Unsigned_16 (Packet (Off)), 8)
or Unsigned_16 (Packet (Off + 1));
end Read_BE2;
function Read_BE4 (Off : Natural) return Unsigned_32 is
begin
return Shift_Left (Unsigned_32 (Packet (Off)), 24)
or Shift_Left (Unsigned_32 (Packet (Off + 1)), 16)
or Shift_Left (Unsigned_32 (Packet (Off + 2)), 8)
or Shift_Left (Unsigned_32 (Packet (Off + 3)), 0);
end Read_BE4;
function Read_Eth (Off : Natural) return Eth_Addr is
begin
return Eth_Addr (Packet (Off .. Off + 5));
end Read_Eth;
procedure Write_Eth (Addr : Eth_Addr) is
begin
Packet (Packet_Off .. Packet_Off + Addr'Length - 1) := Netbuf (Addr);
Packet_Off := Packet_Off + Addr'Length;
end Write_Eth;
procedure Write_BE1 (V : Unsigned_8; Off : Natural) is
begin
Packet (Off) := V;
end Write_BE1;
procedure Write_BE2 (V : Unsigned_16; Off : Natural) is
begin
Packet (Off + 0) := Unsigned_8 (Shift_Right (V, 8) and 16#ff#);
Packet (Off + 1) := Unsigned_8 (Shift_Right (V, 0) and 16#ff#);
end Write_BE2;
procedure Write_2 (V : Unsigned_16; Off : Natural) is
pragma Warnings (Off);
Tmp : Unsigned_16;
for Tmp'Address use Packet (Off)'Address;
pragma Warnings (On);
begin
Tmp := V;
end Write_2;
procedure Write_BE4 (V : Unsigned_32; Off : Natural) is
begin
Packet (Off + 0) := Unsigned_8 (Shift_Right (V, 24) and 16#ff#);
Packet (Off + 1) := Unsigned_8 (Shift_Right (V, 16) and 16#ff#);
Packet (Off + 2) := Unsigned_8 (Shift_Right (V, 8) and 16#ff#);
Packet (Off + 3) := Unsigned_8 (Shift_Right (V, 0) and 16#ff#);
end Write_BE4;
procedure Write_BE1 (V : Unsigned_8) is
begin
Write_BE1 (V, Packet_Off);
Packet_Off := Packet_Off + 1;
end Write_BE1;
procedure Write_BE2 (V : Unsigned_16) is
begin
Write_BE2 (V, Packet_Off);
Packet_Off := Packet_Off + 2;
end Write_BE2;
procedure Write_BE4 (V : Unsigned_32) is
begin
Write_BE4 (V, Packet_Off);
Packet_Off := Packet_Off + 4;
end Write_BE4;
end Netutils;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2016-2020, 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: 5687 $ $Date: 2017-01-12 15:33:13 +0300 (Thu, 12 Jan 2017) $
------------------------------------------------------------------------------
with Web.Window;
package body Web.UI.Widgets.GL_Widgets is
type GL_Widget_Access is access all Abstract_GL_Widget'Class;
Instance : GL_Widget_Access;
-- XXX Only one instance of Abstract_GL_Widget may be created for now.
Frame_Request_Id : Web.DOM_Unsigned_Long := 0;
-- Identifier of registered request of animation frame, then requested.
-- If there is no active requests it is equal to zero.
procedure Animation_Frame_Request_Handler
(Time : Web.DOM_High_Res_Time_Stamp)
with Convention => C;
-- Calls Animation_Frame procedure for all instances of Abstract_GL_Widget.
procedure Animation_Frame (Self : in out Abstract_GL_Widget'Class);
-- Handles animation frame and requests next animation frame. Animation
-- frames is used to do most of GL related processing, including:
-- - finish of initialization of widget's GL code;
-- - detection of resize of canvas;
-- - redrawing after finish of initialization, on detected resize of the
-- canvas and on request.
---------------------
-- Animation_Frame --
---------------------
procedure Animation_Frame (Self : in out Abstract_GL_Widget'Class) is
Ratio : constant Web.DOM_Double
:= Web.Window.Get_Device_Pixel_Ratio;
Display_Width : constant Web.DOM_Unsigned_Long
:= Web.DOM_Unsigned_Long
(Web.DOM_Double'Floor
(Web.DOM_Double (Self.Canvas.Get_Client_Width) * Ratio));
Display_Height : constant Web.DOM_Unsigned_Long
:= Web.DOM_Unsigned_Long
(Web.DOM_Double'Floor
(Web.DOM_Double (Self.Canvas.Get_Client_Height) * Ratio));
Resize_Needed : constant Boolean
:= not Self.Initialized
or Self.Canvas.Get_Width /= Display_Width
or Self.Canvas.Get_Height /= Display_Height;
-- Whether Resize_GL should be called due to change of canvas size.
begin
Self.Context.Make_Current;
-- Finish initialization of the widget's GL code.
if not Self.Initialized then
Self.Initialized := True;
Abstract_GL_Widget'Class (Self).Initialize_GL;
end if;
-- Complete resize of canvas and notify widget.
if Resize_Needed then
Self.Canvas.Set_Width (Display_Width);
Self.Canvas.Set_Height (Display_Height);
Self.Functions.Viewport
(X => 0,
Y => 0,
Width => OpenGL.GLsizei (Self.Canvas.Get_Width),
Height => OpenGL.GLsizei (Self.Canvas.Get_Height));
Abstract_GL_Widget'Class (Self).Resize_GL
(Integer (Self.Canvas.Get_Width), Integer (Self.Canvas.Get_Height));
end if;
-- Redraw content of canvas when necessary.
if Resize_Needed or Self.Redraw_Needed then
Self.Redraw_Needed := False;
Abstract_GL_Widget'Class (Self).Paint_GL;
Self.Functions.Flush;
end if;
end Animation_Frame;
-------------------------------------
-- Animation_Frame_Request_Handler --
-------------------------------------
procedure Animation_Frame_Request_Handler
(Time : Web.DOM_High_Res_Time_Stamp) is
begin
Frame_Request_Id := 0;
-- Frame request has been completed.
Instance.Animation_Frame;
end Animation_Frame_Request_Handler;
------------------
-- Constructors --
------------------
package body Constructors is
----------------
-- Initialize --
----------------
procedure Initialize
(Self : in out Abstract_GL_Widget'Class;
Canvas : in out Web.HTML.Canvases.HTML_Canvas_Element'Class) is
begin
Web.UI.Widgets.Constructors.Initialize (Self, Canvas);
Self.Canvas := Web.HTML.Canvases.HTML_Canvas_Element (Canvas);
Self.Canvas.Add_Event_Listener
(+"webglcontextlost", Self.Lost'Unchecked_Access, False);
Self.Canvas.Add_Event_Listener
(+"webglcontextrestored", Self.Lost'Unchecked_Access, False);
Self.Context := new OpenGL.Contexts.OpenGL_Context;
Self.Context.Create (Canvas);
Self.Context.Make_Current;
Instance := Self'Unchecked_Access;
Self.Update;
end Initialize;
end Constructors;
---------------
-- Functions --
---------------
function Functions
(Self : in out Abstract_GL_Widget'Class)
return access OpenGL.Functions.OpenGL_Functions'Class is
begin
return Self.Context.Functions;
end Functions;
------------------
-- Handle_Event --
------------------
overriding procedure Handle_Event
(Self : in out Context_Lost_Dispatcher;
Event : in out Web.DOM.Events.Event'Class) is
begin
Self.Owner.Context_Lost;
end Handle_Event;
------------------
-- Handle_Event --
------------------
overriding procedure Handle_Event
(Self : in out Context_Restored_Dispatcher;
Event : in out Web.DOM.Events.Event'Class) is
begin
Self.Owner.Context_Restored;
end Handle_Event;
------------
-- Update --
------------
procedure Update (Self : in out Abstract_GL_Widget) is
begin
-- Request redraw on processing of next animation frame.
Self.Redraw_Needed := True;
if Frame_Request_Id = 0 then
-- Register request of animation frame, if not registered.
-- Initialization of the GL related features will be continued
-- durin handling of the requested animation frame.
Frame_Request_Id :=
Web.Window.Request_Animation_Frame
(Animation_Frame_Request_Handler'Access);
end if;
end Update;
end Web.UI.Widgets.GL_Widgets;
|
-- 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.Text_IO; use Ada.Text_IO;
-- with Ada.Strings; use Ada.Strings;
-- with Ada.Strings.Fixed; use Ada.Strings.Fixed;
-- with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Debug_Logs; use Debug_Logs;
with Memory; use Memory;
package body Memory_Channels is
protected body BMC_DCH is
procedure Init (Debug_logging : in Boolean) is
begin
Is_Logging := Debug_logging;
Reset;
end Init;
procedure Reset is
begin
for R in Registers'Range loop
Registers (R) := 0;
end loop;
Registers (IO_Chan_Def_Reg) := IOC_CDR_1;
Registers (IO_Chan_Status_Reg) := IOC_SR_1A or IOC_SR_1B;
Registers (IO_Chan_Mask_Reg) :=
IOC_MR_MK1 or IOC_MR_MK2 or IOC_MR_MK3 or IOC_MR_MK4 or
IOC_MR_MK5 or IOC_MR_MK6;
Put_Line ("INFO: BMC_DCH Registers Reset");
end Reset;
procedure Set_Logging (Debug_Logging : in Boolean) is
begin
Is_Logging := Debug_Logging;
end Set_Logging;
function Read_Reg (Reg : in Integer) return Word_T is (Registers (Reg));
-- Write_Reg populates a given 16-bit register with the supplied data
-- N.B. Addressed by REGISTER not slot
procedure Write_Reg (Reg : in Integer; Datum : in Word_T) is
begin
if Is_Logging then
Loggers.Debug_Print
(Map_Log,
"Write_Reg with Register: " & Reg'Image & " Datum:" &
Datum'Image);
end if;
if Reg = IO_Chan_Def_Reg then
-- certain bits in the new data cause IOCDR bits to be flipped rather than set
for B in 0 .. 15 loop
case B is
when 3 | 4 | 7 | 8 | 14 =>
if Test_W_Bit (Datum, B) then
Flip_W_Bit (Registers (IO_Chan_Def_Reg), B);
end if;
when others =>
if Test_W_Bit (Datum, B) then
Set_W_Bit (Registers (IO_Chan_Def_Reg), B);
else
Clear_W_Bit (Registers (IO_Chan_Def_Reg), B);
end if;
end case;
end loop;
else
Registers (Reg) := Datum;
end if;
end Write_Reg;
-- Write_Slot populates a whole SLOT (pair of registers) with the supplied doubleword
-- N.B. Addressed by SLOT not register
procedure Write_Slot (Slot : in Integer; Datum : in Dword_T) is
begin
if Is_Logging then
Loggers.Debug_Print
(Map_Log,
"Write_Slot with Slot: " & Slot'Image & " Datum:" &
Datum'Image);
end if;
Registers (Slot * 2) := Upper_Word (Datum);
Registers ((Slot * 2) + 1) := DG_Types.Lower_Word (Datum);
end Write_Slot;
function Get_DCH_Mode return Boolean is
(Test_W_Bit (Registers (IO_Chan_Def_Reg), 14));
function Resolve_BMC_Mapped_Addr (M_Addr : in Phys_Addr_T) return Phys_Addr_T is
Slot : Integer := Integer(Shift_Right(M_Addr, 10));
P_Addr, P_Page : Phys_Addr_T;
begin
-- N.B. at some point between 1980 and 1987 the lower 5 bits of the odd word were
-- prepended to the even word to extend the mappable space
P_Page := Shift_Left (Phys_Addr_T(Registers(Slot * 2)) and 16#0000_001f#, 16) +
Shift_Left (Phys_Addr_T(Registers((Slot * 2) + 1)), 10);
P_Addr := (M_Addr and 16#0000_03ff#) or P_Page;
return P_Addr;
end Resolve_BMC_Mapped_Addr;
function Resolve_DCH_Mapped_Addr
(M_Addr : in Phys_Addr_T) return Phys_Addr_T
is
P_Addr, P_Page : Phys_Addr_T;
Slot : Integer;
Offset : Phys_Addr_T;
begin
-- the slot is up to 9 bits long
Slot :=
Integer (Shift_Right (M_Addr, 10) and 16#001f#) + First_DCH_Slot;
if (Slot < First_DCH_Slot) or
(Slot > (First_DCH_Slot + Num_DCH_Slots))
then
raise Invalid_DCH_Slot;
end if;
Offset := M_Addr and 16#0000_03ff#;
-- N.B. at some point between 1980 and 1987 the lower 5 bits of the odd word were
-- prepended to the even word to extend the mappable space
P_Page :=
Shift_Left
(Phys_Addr_T (Registers (Slot * 2) and 16#0000_001f#), 16) or
Phys_Addr_T (Registers ((Slot * 2) + 1));
P_Addr := Shift_Left (P_Page, 10) or Offset;
if Is_Logging then
Loggers.Debug_Print
(Map_Log,
"Resolve_DCH_Mapped_Addr got: " & M_Addr'Image &
" Returning: " & P_Addr'Image);
end if;
return P_Addr;
end Resolve_DCH_Mapped_Addr;
procedure Write_Word_DCH_Chan
(Unmapped : in out Phys_Addr_T; Datum : in Word_T)
is
P_Addr : Phys_Addr_T;
begin
if Get_DCH_Mode then
P_Addr := Resolve_DCH_Mapped_Addr (Unmapped);
else
P_Addr := Unmapped;
end if;
RAM.Write_Word (P_Addr, Datum);
-- auto-increment the supplied address
Unmapped := Unmapped + 1;
end Write_Word_DCH_Chan;
function Decode_BMC_Addr (Unmapped : in Phys_Addr_T) return BMC_Addr_T is
In_Addr : Phys_Addr_T := Shift_Left(Unmapped, 10);
Res : BMC_Addr_T;
begin
Res.Is_Logical := Test_DW_Bit (Dword_T(In_Addr), 0);
if Res.Is_Logical then
Res.TT := Natural(Get_DW_Bits(Dword_T(In_Addr), 2, 5));
Res.TTR := Natural(Get_DW_Bits(Dword_T(In_Addr), 7, 5));
Res.P_Low := Unmapped and 16#0000_3fff#;
else
Res.Bk := Natural(Get_DW_Bits(Dword_T(In_Addr), 1, 3));
Res.XCA := Natural(Get_DW_Bits(Dword_T(In_Addr), 4, 3));
Res.CA := Unmapped and 16#0000_7fff#;
end if;
return Res;
end Decode_BMC_Addr;
procedure Read_Word_BMC_16 (Unmapped : in out Word_T; Datum : out Word_T) is
P_Addr : Phys_Addr_T;
Decoded : BMC_Addr_T := Decode_BMC_Addr (Phys_Addr_T(Unmapped));
begin
if Decoded.Is_Logical then
P_Addr := Resolve_BMC_Mapped_Addr (Phys_Addr_T(Unmapped)); -- FIXME
else
P_Addr := Decoded.CA;
end if;
Datum := RAM.Read_Word (P_Addr);
Unmapped := Unmapped + 1;
end Read_Word_BMC_16;
procedure Write_Word_BMC_16 (Unmapped : in out Word_T; Datum : in Word_T) is
P_Addr : Phys_Addr_T;
Decoded : BMC_Addr_T := Decode_BMC_Addr (Phys_Addr_T(Unmapped));
begin
if Decoded.Is_Logical then
P_Addr := Resolve_BMC_Mapped_Addr (Phys_Addr_T(Unmapped)); -- FIXME
else
P_Addr := Decoded.CA;
end if;
RAM.Write_Word (P_Addr, Datum);
Unmapped := Unmapped + 1;
end Write_Word_BMC_16;
end BMC_DCH;
end Memory_Channels;
|
-----------------------------------------------------------------------
-- awa-settings -- Settings module
-- Copyright (C) 2013, 2018 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.
-----------------------------------------------------------------------
-- = Settings Module =
-- The `Settings` module provides management of application and user settings.
-- A setting is identified by a unique name in the application. It is saved in
-- the database and associated with a user.
--
-- == Getting a user setting ==
-- Getting a user setting is as simple as calling a function with the setting name
-- and the default value. If the setting was modified by the user and saved in the
-- database, the saved value will be returned. Otherwise, the default value is returned.
-- For example, if an application defines a `row-per-page` setting to define how
-- many rows are defined in a list, the user setting can be retrieved with:
--
-- Row_Per_Page : constant Integer := AWA.Settings.Get_User_Setting ("row-per-page", 10);
--
-- == Saving a user setting ==
-- When a user changes the setting value, we just have to save it in the database.
-- The setting value will either be updated if it exists or created.
--
-- AWA.Settings.Set_User_Setting ("row-per-page", 20);
--
-- @include awa-settings-modules.ads
--
-- == Data model ==
-- [images/awa_settings_model.png]
package AWA.Settings is
-- Get the user setting identified by the given name.
-- If the user does not have such setting, return the default value.
function Get_User_Setting (Name : in String;
Default : in String) return String;
-- Get the user setting identified by the given name.
-- If the user does not have such setting, return the default value.
function Get_User_Setting (Name : in String;
Default : in Integer) return Integer;
-- Set the user setting identified by the given name. If the user
-- does not have such setting, it is created and set to the given value.
-- Otherwise, the user setting is updated to hold the new value.
procedure Set_User_Setting (Name : in String;
Value : in String);
-- Set the user setting identified by the given name. If the user
-- does not have such setting, it is created and set to the given value.
-- Otherwise, the user setting is updated to hold the new value.
procedure Set_User_Setting (Name : in String;
Value : in Integer);
end AWA.Settings;
|
package body problem_1 is
function Solution_1( Max : Int128 ) return Int128 is
Sum : Int128 := 0;
begin
for I in 3 .. Max - 1 loop
if I mod 3 = 0 or else I mod 5 = 0 then
Sum := Sum + I;
end if;
end loop;
return Sum;
end Solution_1;
function Solution_2( Max : Int128 ) return Int128 is
Sum : Int128 := 0;
begin
Sum := Arithmetic_Sequence( 3, Max - 1);
Sum := Sum + Arithmetic_Sequence( 5, Max - 1);
Sum := Sum - Arithmetic_Sequence( 3*5, Max - 1);
return Sum;
end Solution_2;
function Arithmetic_Sequence( N, Top : Int128 ) return Int128 is
First_Term : constant Int128 := N;
Last_Term : constant Int128 := Top - ( Top mod N );
N_Terms : constant Int128 := Last_Term / N;
begin
return N_Terms * ( First_Term + Last_Term ) / 2;
end Arithmetic_Sequence;
procedure Test_Solution_1 is
Solution : constant Int128 := 233168;
begin
Assert( Solution_1(1000) = Solution );
end Test_Solution_1;
procedure Test_Solution_2 is
Solution : constant Int128 := 233168;
begin
Assert( Solution_1(1000) = Solution );
end Test_Solution_2;
function Get_Solutions return Solution_Case is
Ret : Solution_Case;
begin
Set_Name( Ret, "Problem 1");
Add_Test( Ret, Test_Solution_1'access );
Add_Test( Ret, Test_Solution_2'access );
return Ret;
end Get_Solutions;
end Problem_1;
|
pragma License (Unrestricted);
with System.WCh_Con;
generic
Encoding_Method : System.WCh_Con.WC_Encoding_Method;
package GNAT.Decode_String is
pragma Pure;
procedure Decode_Wide_Character (
Input : String;
Ptr : in out Natural;
Result : out Wide_Character);
procedure Decode_Wide_Wide_Character (
Input : String;
Ptr : in out Natural;
Result : out Wide_Wide_Character);
procedure Next_Wide_Character (Input : String; Ptr : in out Natural);
end GNAT.Decode_String;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . T E X T _ I O . G E T _ L I N E --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
-- The implementation of Ada.Text_IO.Get_Line is split into a subunit so that
-- different implementations can be used on different systems. This is the
-- standard implementation (it uses low level features not suitable for use
-- on virtual machines).
with System; use System;
with System.Storage_Elements; use System.Storage_Elements;
separate (Ada.Text_IO)
procedure Get_Line
(File : File_Type;
Item : out String;
Last : out Natural)
is
Chunk_Size : constant := 80;
-- We read into a fixed size auxiliary buffer. Because this buffer
-- needs to be pre-initialized, there is a trade-off between size and
-- speed. Experiments find returns are diminishing after 50 and this
-- size allows most lines to be processed with a single read.
ch : int;
N : Natural;
procedure memcpy (s1, s2 : chars; n : size_t);
pragma Import (C, memcpy);
function memchr (s : chars; ch : int; n : size_t) return chars;
pragma Import (C, memchr);
procedure memset (b : chars; ch : int; n : size_t);
pragma Import (C, memset);
function Get_Chunk (N : Positive) return Natural;
-- Reads at most N - 1 characters into Item (Last + 1 .. Item'Last),
-- updating Last. Raises End_Error if nothing was read (End_Of_File).
-- Returns number of characters still to read (either 0 or 1) in
-- case of success.
---------------
-- Get_Chunk --
---------------
function Get_Chunk (N : Positive) return Natural is
Buf : String (1 .. Chunk_Size);
S : constant chars := Buf (1)'Address;
P : chars;
begin
if N = 1 then
return N;
end if;
memset (S, 10, size_t (N));
if fgets (S, N, File.Stream) = Null_Address then
if ferror (File.Stream) /= 0 then
raise Device_Error;
-- If incomplete last line, pretend we found a LM
elsif Last >= Item'First then
return 0;
else
raise End_Error;
end if;
end if;
P := memchr (S, LM, size_t (N));
-- If no LM is found, the buffer got filled without reading a new
-- line. Otherwise, the LM is either one from the input, or else one
-- from the initialization, which means an incomplete end-of-line was
-- encountered. Only in first case the LM will be followed by a 0.
if P = Null_Address then
pragma Assert (Buf (N) = ASCII.NUL);
memcpy (Item (Last + 1)'Address,
Buf (1)'Address, size_t (N - 1));
Last := Last + N - 1;
return 1;
else
-- P points to the LM character. Set K so Buf (K) is the character
-- right before.
declare
K : Natural := Natural (P - S);
begin
-- If K + 2 is greater than N, then Buf (K + 1) cannot be a LM
-- character from the source file, as the call to fgets copied at
-- most N - 1 characters. Otherwise, either LM is a character from
-- the source file and then Buf (K + 2) should be 0, or LM is a
-- character put in Buf by memset and then Buf (K) is the 0 put in
-- by fgets. In both cases where LM does not come from the source
-- file, compensate.
if K + 2 > N or else Buf (K + 2) /= ASCII.NUL then
-- Incomplete last line, so remove the extra 0
pragma Assert (Buf (K) = ASCII.NUL);
K := K - 1;
end if;
memcpy (Item (Last + 1)'Address,
Buf (1)'Address, size_t (K));
Last := Last + K;
end;
return 0;
end if;
end Get_Chunk;
-- Start of processing for Get_Line
begin
FIO.Check_Read_Status (AP (File));
-- Set Last to Item'First - 1 when no characters are read, as mandated by
-- Ada RM. In the case where Item'First is negative or null, this results
-- in Constraint_Error being raised.
Last := Item'First - 1;
-- Immediate exit for null string, this is a case in which we do not
-- need to test for end of file and we do not skip a line mark under
-- any circumstances.
if Item'First > Item'Last then
return;
end if;
N := Item'Last - Item'First + 1;
-- Here we have at least one character, if we are immediately before
-- a line mark, then we will just skip past it storing no characters.
if File.Before_LM then
File.Before_LM := False;
File.Before_LM_PM := False;
-- Otherwise we need to read some characters
else
while N >= Chunk_Size loop
if Get_Chunk (Chunk_Size) = 0 then
N := 0;
else
N := N - Chunk_Size + 1;
end if;
end loop;
if N > 1 then
N := Get_Chunk (N);
end if;
-- Almost there, only a little bit more to read
if N = 1 then
ch := Getc (File);
-- If we get EOF after already reading data, this is an incomplete
-- last line, in which case no End_Error should be raised.
if ch = EOF then
if Last < Item'First then
raise End_Error;
else -- All done
return;
end if;
elsif ch /= LM then
-- Buffer really is full without having seen LM, update col
Last := Last + 1;
Item (Last) := Character'Val (ch);
File.Col := File.Col + Count (Last - Item'First + 1);
return;
end if;
end if;
end if;
-- We have skipped past, but not stored, a line mark. Skip following
-- page mark if one follows, but do not do this for a non-regular file
-- (since otherwise we get annoying wait for an extra character)
File.Line := File.Line + 1;
File.Col := 1;
if File.Before_LM_PM then
File.Line := 1;
File.Before_LM_PM := False;
File.Page := File.Page + 1;
elsif File.Is_Regular_File then
ch := Getc (File);
if ch = PM and then File.Is_Regular_File then
File.Line := 1;
File.Page := File.Page + 1;
else
Ungetc (ch, File);
end if;
end if;
end Get_Line;
|
-- Copyright (c) 2021 Devin Hill
-- zlib License -- see LICENSE for details.
with GBA.Numerics;
with GBA.Memory.IO_Registers;
use GBA.Memory.IO_Registers;
package GBA.Display is
type Video_Mode is
( Mode_0 -- 4 text BGs
, Mode_1 -- 2 text BGs + 1 rot/scale BGs
, Mode_2 -- 2 rot/scale bgs
, Mode_3 -- 15-bit color 240x160 bitmap
, Mode_4 -- 8-bit color 240x160 bitmap + buffering
, Mode_5 -- 15-bit color 160x128 bitmap + buffering
)
with Size => 3;
for Video_Mode use
( Mode_0 => 0
, Mode_1 => 1
, Mode_2 => 2
, Mode_3 => 3
, Mode_4 => 4
, Mode_5 => 5
);
type Character_Mapping_Style is
( Two_Dimensional -- Each row of tiles spans the same columns of tile data.
, One_Dimensional -- Each row of tiles immediately succeeds the last row.
);
for Character_Mapping_Style use
( Two_Dimensional => 0
, One_Dimensional => 1
);
type Vertical_Counter_Type is range 0 .. 227
with Size => 8;
type Display_Priority is range 0 .. 3
with Size => 2;
type Toggleable_Display_Element is
( Background_0
, Background_1
, Background_2
, Background_3
, Object_Sprites
, Window_0
, Window_1
, Object_Window
);
for Toggleable_Display_Element use
( Background_0 => 0
, Background_1 => 1
, Background_2 => 2
, Background_3 => 3
, Object_Sprites => 4
, Window_0 => 5
, Window_1 => 6
, Object_Window => 7
);
procedure Set_Display_Mode (Mode : Video_Mode; Forced_Blank : Boolean := False)
with Inline;
procedure Enable_Display_Element
(Element : Toggleable_Display_Element; Enable : Boolean := True)
with Inline;
procedure Request_VBlank_Interrupt (Request : Boolean := True)
with Inline;
procedure Request_HBlank_Interrupt (Request : Boolean := True)
with Inline;
type Displayed_Element_Flags is
array (Toggleable_Display_Element range <>) of Boolean
with Pack;
type Bitmap_Frame_Choice is mod 2;
type Display_Control_Info is
record
Mode : Video_Mode;
Bitmap_Frame : Bitmap_Frame_Choice; -- Only relevant for mode 4 and 5
Free_HBlank_Interval : Boolean;
Character_Mapping : Character_Mapping_Style;
Forced_Blank : Boolean;
Displayed_Elements : Displayed_Element_Flags (Toggleable_Display_Element);
end record
with Size => 16;
for Display_Control_Info use
record
Mode at 0 range 0 .. 2;
Bitmap_Frame at 0 range 4 .. 4;
Free_HBlank_Interval at 0 range 5 .. 5;
Character_Mapping at 0 range 6 .. 6;
Forced_Blank at 0 range 7 .. 7;
Displayed_Elements at 1 range 0 .. 7;
end record;
type Display_Status_Info is
record
Is_VBlank : Boolean;
Is_HBlank : Boolean;
Is_Matching_VCount : Boolean;
Request_VBlank_Interrupt : Boolean;
Request_HBlank_Interrupt : Boolean;
Request_VCount_Interrupt : Boolean;
VCount_Value_Setting : Vertical_Counter_Type;
end record
with Size => 16;
for Display_Status_Info use
record
Is_VBlank at 0 range 0 .. 0;
Is_HBlank at 0 range 1 .. 1;
Is_Matching_VCount at 0 range 2 .. 2;
Request_VBlank_Interrupt at 0 range 3 .. 3;
Request_HBlank_Interrupt at 0 range 4 .. 4;
Request_VCount_Interrupt at 0 range 5 .. 5;
VCount_Value_Setting at 1 range 0 .. 7;
end record;
Display_Control : Display_Control_Info
with Import, Volatile, Address => DISPCNT;
Display_Status : Display_Status_Info
with Import, Volatile, Address => DISPSTAT;
Vertical_Counter : Vertical_Counter_Type
with Import, Volatile, Address => VCOUNT;
Green_Swap : Boolean
with Import, Volatile, Address => GREENSWAP;
end GBA.Display; |
with System;
use System;
package body Pkg is
function "=" (x, y: Arithmetic) return Boolean is
begin
return (x'Address = y'Address);
end "=";
function Type_Name (x: Arithmetic) return String is
begin
return "PKG.ARITHMETIC";
end Type_Name;
function Cast (x: in Arithmetic; iface: String) return System.Address is
begin
if iface = "PKG.SEQUENCE" then
return Sequence(x)'Address;
end if;
if iface = "PKG.PRINTABLE" then
return Printable(x)'Address;
end if;
if iface = "PKG.ARITHMETIC" then
return Arithmetic(x)'Address;
end if;
return Null_Address;
end Cast;
function Value (n: Arithmetic) return Integer is
begin
return n.val;
end Value;
procedure Next (n: in out Arithmetic) is
begin
n.val := n.val + 1;
end Next;
procedure Print (n: Arithmetic) is
begin
return;
end Print;
end Pkg;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- ADA.CONTAINERS.FUNCTIONAL_MAPS --
-- --
-- B o d y --
-- --
-- Copyright (C) 2016-2019, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- 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/>. --
------------------------------------------------------------------------------
pragma Ada_2012;
package body Ada.Containers.Functional_Maps with SPARK_Mode => Off is
use Key_Containers;
use Element_Containers;
---------
-- "=" --
---------
function "=" (Left : Map; Right : Map) return Boolean is
(Left.Keys <= Right.Keys and Right <= Left);
----------
-- "<=" --
----------
function "<=" (Left : Map; Right : Map) return Boolean is
I2 : Count_Type;
begin
for I1 in 1 .. Length (Left.Keys) loop
I2 := Find (Right.Keys, Get (Left.Keys, I1));
if I2 = 0
or else Get (Right.Elements, I2) /= Get (Left.Elements, I1)
then
return False;
end if;
end loop;
return True;
end "<=";
---------
-- Add --
---------
function Add
(Container : Map;
New_Key : Key_Type;
New_Item : Element_Type) return Map
is
begin
return
(Keys =>
Add (Container.Keys, Length (Container.Keys) + 1, New_Key),
Elements =>
Add
(Container.Elements, Length (Container.Elements) + 1, New_Item));
end Add;
---------------------------
-- Elements_Equal_Except --
---------------------------
function Elements_Equal_Except
(Left : Map;
Right : Map;
New_Key : Key_Type) return Boolean
is
begin
for I in 1 .. Length (Left.Keys) loop
declare
K : constant Key_Type := Get (Left.Keys, I);
begin
if not Equivalent_Keys (K, New_Key)
and then
(Find (Right.Keys, K) = 0
or else Get (Right.Elements, Find (Right.Keys, K)) /=
Get (Left.Elements, I))
then
return False;
end if;
end;
end loop;
return True;
end Elements_Equal_Except;
function Elements_Equal_Except
(Left : Map;
Right : Map;
X : Key_Type;
Y : Key_Type) return Boolean
is
begin
for I in 1 .. Length (Left.Keys) loop
declare
K : constant Key_Type := Get (Left.Keys, I);
begin
if not Equivalent_Keys (K, X)
and then not Equivalent_Keys (K, Y)
and then
(Find (Right.Keys, K) = 0
or else Get (Right.Elements, Find (Right.Keys, K)) /=
Get (Left.Elements, I))
then
return False;
end if;
end;
end loop;
return True;
end Elements_Equal_Except;
---------
-- Get --
---------
function Get (Container : Map; Key : Key_Type) return Element_Type is
begin
return Get (Container.Elements, Find (Container.Keys, Key));
end Get;
-------------
-- Has_Key --
-------------
function Has_Key (Container : Map; Key : Key_Type) return Boolean is
begin
return Find (Container.Keys, Key) > 0;
end Has_Key;
-----------------
-- Has_Witness --
-----------------
function Has_Witness
(Container : Map;
Witness : Count_Type) return Boolean
is
(Witness in 1 .. Length (Container.Keys));
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Map) return Boolean is
begin
return Length (Container.Keys) = 0;
end Is_Empty;
-------------------
-- Keys_Included --
-------------------
function Keys_Included (Left : Map; Right : Map) return Boolean is
begin
for I in 1 .. Length (Left.Keys) loop
declare
K : constant Key_Type := Get (Left.Keys, I);
begin
if Find (Right.Keys, K) = 0 then
return False;
end if;
end;
end loop;
return True;
end Keys_Included;
--------------------------
-- Keys_Included_Except --
--------------------------
function Keys_Included_Except
(Left : Map;
Right : Map;
New_Key : Key_Type) return Boolean
is
begin
for I in 1 .. Length (Left.Keys) loop
declare
K : constant Key_Type := Get (Left.Keys, I);
begin
if not Equivalent_Keys (K, New_Key)
and then Find (Right.Keys, K) = 0
then
return False;
end if;
end;
end loop;
return True;
end Keys_Included_Except;
function Keys_Included_Except
(Left : Map;
Right : Map;
X : Key_Type;
Y : Key_Type) return Boolean
is
begin
for I in 1 .. Length (Left.Keys) loop
declare
K : constant Key_Type := Get (Left.Keys, I);
begin
if not Equivalent_Keys (K, X)
and then not Equivalent_Keys (K, Y)
and then Find (Right.Keys, K) = 0
then
return False;
end if;
end;
end loop;
return True;
end Keys_Included_Except;
------------
-- Length --
------------
function Length (Container : Map) return Count_Type is
begin
return Length (Container.Elements);
end Length;
---------------
-- Same_Keys --
---------------
function Same_Keys (Left : Map; Right : Map) return Boolean is
(Keys_Included (Left, Right)
and Keys_Included (Left => Right, Right => Left));
---------
-- Set --
---------
function Set
(Container : Map;
Key : Key_Type;
New_Item : Element_Type) return Map
is
(Keys => Container.Keys,
Elements =>
Set (Container.Elements, Find (Container.Keys, Key), New_Item));
-----------
-- W_Get --
-----------
function W_Get
(Container : Map;
Witness : Count_Type) return Element_Type
is
(Get (Container.Elements, Witness));
-------------
-- Witness --
-------------
function Witness (Container : Map; Key : Key_Type) return Count_Type is
(Find (Container.Keys, Key));
end Ada.Containers.Functional_Maps;
|
with Ada.Strings.Unbounded, Ada.Text_IO;
procedure Variadic is
subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
use type U_String;
function "+"(S: String) return U_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
function "-"(U: U_String) return String
renames Ada.Strings.Unbounded.To_String;
type Variadic_Array is array(Positive range <>) of U_String;
procedure Print_Line(Params: Variadic_Array) is
begin
for I in Params'Range loop
Ada.Text_IO.Put(-Params(I));
if I < Params'Last then
Ada.Text_IO.Put(" ");
end if;
end loop;
Ada.Text_IO.New_Line;
end Print_Line;
begin
Print_Line((+"Mary", +"had", +"a", +"little", +"lamb.")); -- print five strings
Print_Line((1 => +"Rosetta Code is cooool!")); -- print one string
end;
|
with Ada.Text_Io; use Ada.Text_Io;
with datos; use datos;
with eliminar_tercer_elemento_ordenada, escribir_lista;
procedure prueba_eliminar_tercer_elemento_ordenada is
-- este programa hace llamadas al subprograma eliminar_tercer_elemento
-- para comprobar si su funcionamiento es correcto
Lista1: Lista_Enteros;
begin
Lista1.Numeros(1) := 1;
Lista1.Numeros(2) := 2;
Lista1.Numeros(3) := 3;
Lista1.Numeros(4) := 4;
Lista1.Cont := 4;
put_line("Caso 1: lista de cuatro elementos: (1, 2, 3, 4)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 1 2 4 -1");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
-- faltan varios casos de prueba
Lista1.Numeros := (0, 5, 10, 15, 20, 25, 30, 35, 40, 45);
Lista1.Cont := 10;
put_line("Caso 1: lista de cuatro elementos: (0, 5, 10, 15, 20, 25, 30, 35, 40, 45)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 0 5 15 20 25 30 35 40 45 -1");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
Lista1.Numeros(1) := 1;
Lista1.Numeros(2) := 2;
Lista1.Cont := 2;
put_line("Caso 1: lista de cuatro elementos: (1, 2)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 1 2");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
end prueba_eliminar_tercer_elemento_ordenada;
|
with Ada.Text_IO, Hofstadter_Figure_Figure;
procedure Test_HSS is
use Hofstadter_Figure_Figure;
A: array(1 .. 1000) of Boolean := (others => False);
J: Positive;
begin
for I in 1 .. 10 loop
Ada.Text_IO.Put(Integer'Image(FFR(I)));
end loop;
Ada.Text_IO.New_Line;
for I in 1 .. 40 loop
J := FFR(I);
if A(J) then
raise Program_Error with Positive'Image(J) & " used twice";
end if;
A(J) := True;
end loop;
for I in 1 .. 960 loop
J := FFS(I);
if A(J) then
raise Program_Error with Positive'Image(J) & " used twice";
end if;
A(J) := True;
end loop;
for I in A'Range loop
if not A(I) then raise Program_Error with Positive'Image(I) & " unused";
end if;
end loop;
Ada.Text_IO.Put_Line("Test Passed: No overlap between FFR(I) and FFS(J)");
exception
when Program_Error => Ada.Text_IO.Put_Line("Test Failed"); raise;
end Test_HSS;
|
-- Copyright 2017-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ada.Exceptions; use Ada.Exceptions;
with Messages; use Messages;
with HallOfFame; use HallOfFame;
with ShipModules; use ShipModules;
with Ships.Cargo; use Ships.Cargo;
with Maps; use Maps;
with Events; use Events;
with Crew.Inventory; use Crew.Inventory;
with Utils; use Utils;
with Missions; use Missions;
with Factions; use Factions;
package body Ships.Crew is
function GetSkillLevel
(Member: Member_Data; SkillIndex: Skills_Amount_Range)
return Skill_Range is
SkillLevel: Integer := 0;
Damage: Damage_Factor := 0.0;
BaseSkillLevel: Natural range 0 .. 151;
begin
Get_Skill_Loop :
for Skill of Member.Skills loop
if Skill.Index = SkillIndex then
BaseSkillLevel :=
Skill.Level +
Member.Attributes
(Positive
(SkillsData_Container.Element(Skills_List, Skill.Index)
.Attribute))
.Level;
Damage := 1.0 - Damage_Factor(Float(Member.Health) / 100.0);
SkillLevel :=
SkillLevel +
(BaseSkillLevel -
Integer(Float(BaseSkillLevel) * Float(Damage)));
if Member.Thirst > 40 then
Damage := 1.0 - Damage_Factor(Float(Member.Thirst) / 100.0);
SkillLevel :=
SkillLevel - (Integer(Float(BaseSkillLevel) * Float(Damage)));
end if;
if Member.Hunger > 80 then
Damage := 1.0 - Damage_Factor(Float(Member.Hunger) / 100.0);
SkillLevel :=
SkillLevel - (Integer(Float(BaseSkillLevel) * Float(Damage)));
end if;
if Member.Morale(1) < 25 then
Damage := Damage_Factor(Float(Member.Morale(1)) / 100.0);
SkillLevel :=
SkillLevel - (Integer(Float(BaseSkillLevel) * Float(Damage)));
end if;
if SkillLevel < 1 then
SkillLevel := 1;
end if;
if SkillLevel > 100 then
SkillLevel := 100;
end if;
if Member.Morale(1) > 90 then
Damage := Damage_Factor(Float(SkillLevel) / 100.0);
SkillLevel :=
SkillLevel + (Integer(Float(BaseSkillLevel) * Float(Damage)));
if SkillLevel > 100 then
SkillLevel := 100;
end if;
end if;
return SkillLevel;
end if;
end loop Get_Skill_Loop;
return SkillLevel;
end GetSkillLevel;
procedure Death
(MemberIndex: Crew_Container.Extended_Index; Reason: Unbounded_String;
Ship: in out Ship_Record; CreateBody: Boolean := True) is
begin
if Ship = Player_Ship then
if MemberIndex > 1 then
AddMessage
(To_String(Ship.Crew(MemberIndex).Name) & " died from " &
To_String(Reason) & ".",
CombatMessage, RED);
else
AddMessage
("You died from " & To_String(Reason) & ".", CombatMessage, RED);
Player_Ship.Crew(MemberIndex).Order := Rest;
Player_Ship.Crew(MemberIndex).Health := 0;
Update_Hall_Of_Fame(Player_Ship.Crew(MemberIndex).Name, Reason);
return;
end if;
end if;
if CreateBody then
Ship.Cargo.Append
(New_Item =>
(ProtoIndex => Corpse_Index, Amount => 1,
Name =>
Ship.Crew(MemberIndex).Name &
To_Unbounded_String("'s corpse"),
Durability => 100, Price => 0));
end if;
DeleteMember(MemberIndex, Ship);
for I in Ship.Crew.Iterate loop
UpdateMorale(Ship, Crew_Container.To_Index(I), Get_Random(-25, -10));
end loop;
end Death;
procedure DeleteMember
(MemberIndex: Crew_Container.Extended_Index; Ship: in out Ship_Record) is
TempValue: Integer;
begin
Ship.Crew.Delete(Index => MemberIndex);
Module_Loop :
for Module of Ship.Modules loop
Owners_Loop :
for Owner of Module.Owner loop
if Owner = MemberIndex then
Owner := 0;
elsif Owner > MemberIndex then
Owner := Owner - 1;
end if;
end loop Owners_Loop;
end loop Module_Loop;
if Ship = Player_Ship then
Delete_Missions_Loop :
for I in
AcceptedMissions.First_Index .. AcceptedMissions.Last_Index loop
if AcceptedMissions(I).MType = Passenger
and then AcceptedMissions(I).Data = MemberIndex then
DeleteMission(I);
exit Delete_Missions_Loop;
end if;
end loop Delete_Missions_Loop;
Update_Missions_Loop :
for Mission of AcceptedMissions loop
if Mission.MType = Passenger
and then Mission.Data > MemberIndex then
TempValue := Mission.Data;
TempValue := TempValue - 1;
Mission.Data := TempValue;
end if;
end loop Update_Missions_Loop;
end if;
end DeleteMember;
function FindMember
(Order: Crew_Orders; Crew: Crew_Container.Vector := Player_Ship.Crew)
return Natural is
begin
Find_Member_Loop :
for I in Crew.Iterate loop
if Crew(I).Order = Order then
return Crew_Container.To_Index(I);
end if;
end loop Find_Member_Loop;
return 0;
end FindMember;
procedure GiveOrders
(Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index;
GivenOrder: Crew_Orders;
ModuleIndex: Modules_Container.Extended_Index := 0;
CheckPriorities: Boolean := True) is
use Tiny_String;
MemberName: constant String := To_String(Ship.Crew(MemberIndex).Name);
ToolsIndex: Inventory_Container.Extended_Index := 0;
RequiredTool: Unbounded_String;
ToolQuality: Items_Durability := Default_Item_Durability;
ModuleIndex2: Modules_Container.Extended_Index := 0;
begin
if GivenOrder = Ship.Crew(MemberIndex).Order then
if GivenOrder in Craft | Gunner then
Give_Orders_Modules_Loop :
for I in Ship.Modules.Iterate loop
if Modules_Container.To_Index(I) = ModuleIndex then
Owners_Loop :
for Owner of Ship.Modules(I).Owner loop
if Owner = MemberIndex then
return;
end if;
end loop Owners_Loop;
end if;
end loop Give_Orders_Modules_Loop;
else
return;
end if;
end if;
if GivenOrder /= Rest and
((Ship.Crew(MemberIndex).Morale(1) < 11 and Get_Random(1, 100) < 50) or
Ship.Crew(MemberIndex).Loyalty < 20) then
if Ship = Player_Ship then
raise Crew_Order_Error
with MemberName & " refuses to execute order.";
else
return;
end if;
end if;
if GivenOrder = Train
and then Ship.Modules(ModuleIndex).Trained_Skill = 0 then
raise Crew_Order_Error
with MemberName & " can't start training because " &
To_String(Ship.Modules(ModuleIndex).Name) & " isn't prepared.";
end if;
if GivenOrder in Pilot | Engineer | Upgrading | Talk then
Give_Crew_Orders_Loop :
for I in Ship.Crew.First_Index .. Ship.Crew.Last_Index loop
if Ship.Crew(I).Order = GivenOrder then
GiveOrders(Player_Ship, I, Rest, 0, False);
exit Give_Crew_Orders_Loop;
end if;
end loop Give_Crew_Orders_Loop;
elsif (GivenOrder in Gunner | Craft | Train) or
(GivenOrder = Heal and ModuleIndex > 0) then
declare
FreePosition: Boolean := False;
begin
Free_Position_Loop :
for Owner of Ship.Modules(ModuleIndex).Owner loop
if Owner = 0 then
FreePosition := True;
exit Free_Position_Loop;
end if;
end loop Free_Position_Loop;
if not FreePosition then
GiveOrders
(Player_Ship, Ship.Modules(ModuleIndex).Owner(1), Rest, 0,
False);
end if;
end;
end if;
if ModuleIndex = 0 and (GivenOrder in Pilot | Engineer | Rest) then
declare
MType: constant ModuleType :=
(case GivenOrder is when Pilot => COCKPIT,
when Engineer => ENGINE, when Rest => CABIN,
when others => ENGINE);
begin
Modules_Loop :
for I in Ship.Modules.Iterate loop
if MType /= CABIN then
if Modules_List(Ship.Modules(I).Proto_Index).MType =
MType and
Ship.Modules(I).Durability > 0 then
if Ship.Modules(I).Owner(1) /= 0 then
GiveOrders
(Player_Ship, Ship.Modules(I).Owner(1), Rest, 0,
False);
end if;
ModuleIndex2 := Modules_Container.To_Index(I);
exit Modules_Loop;
end if;
else
if Ship.Modules(I).M_Type = CABIN and
Ship.Modules(I).Durability > 0 then
Cabin_Owners_Loop :
for Owner of Ship.Modules(I).Owner loop
if MemberIndex = Owner then
ModuleIndex2 := Modules_Container.To_Index(I);
exit Modules_Loop;
end if;
end loop Cabin_Owners_Loop;
end if;
end if;
end loop Modules_Loop;
end;
else
ModuleIndex2 := ModuleIndex;
end if;
if ModuleIndex2 = 0 and Ship = Player_Ship then
case GivenOrder is
when Pilot =>
raise Crew_Order_Error
with MemberName &
" can't start piloting because the cockpit is destroyed or you don't have cockpit.";
when Engineer =>
raise Crew_Order_Error
with MemberName &
" can't start engineer's duty because all of the engines are destroyed or you don't have engine.";
when Gunner =>
raise Crew_Order_Error
with MemberName &
" can't start operating gun because all of the guns are destroyed or you don't have any installed.";
when Rest =>
Modules_Loop2 :
for Module of Ship.Modules loop
if Module.M_Type = CABIN and Module.Durability > 0 then
Owners_Loop2 :
for Owner of Module.Owner loop
if Owner = 0 then
Owner := MemberIndex;
AddMessage
(MemberName & " takes " & To_String(Module.Name) &
" as their own cabin.",
OtherMessage);
exit Modules_Loop2;
end if;
end loop Owners_Loop2;
end if;
end loop Modules_Loop2;
when others =>
null;
end case;
end if;
Modules_Loop3 :
for Module of Ship.Modules loop
if Module.M_Type /= CABIN then
Owners_Loop3 :
for Owner of Module.Owner loop
if Owner = MemberIndex then
Owner := 0;
exit Modules_Loop3;
end if;
end loop Owners_Loop3;
end if;
end loop Modules_Loop3;
if ToolsIndex > 0 and
Ship.Crew(MemberIndex).Equipment(7) /= ToolsIndex then
UpdateInventory
(MemberIndex, 1, Ship.Cargo(ToolsIndex).ProtoIndex,
Ship.Cargo(ToolsIndex).Durability);
UpdateCargo(Ship => Ship, Amount => -1, CargoIndex => ToolsIndex);
Ship.Crew(MemberIndex).Equipment(7) :=
FindItem
(Inventory => Ship.Crew(MemberIndex).Inventory,
ItemType => RequiredTool);
end if;
ToolsIndex := Ship.Crew(MemberIndex).Equipment(7);
if ToolsIndex > 0
and then
Items_List(Ship.Crew(MemberIndex).Inventory(ToolsIndex).ProtoIndex)
.IType /=
RequiredTool then
UpdateCargo
(Ship, Ship.Crew(MemberIndex).Inventory(ToolsIndex).ProtoIndex, 1,
Ship.Crew(MemberIndex).Inventory(ToolsIndex).Durability);
UpdateInventory
(MemberIndex => MemberIndex, Amount => -1,
InventoryIndex => ToolsIndex);
ToolsIndex := 0;
end if;
if GivenOrder in Upgrading | Repair | Clean |
Train then -- Check for tools
if GivenOrder = Clean then
RequiredTool := Cleaning_Tools;
elsif GivenOrder = Train then
RequiredTool :=
To_Unbounded_String
(To_String
(SkillsData_Container.Element
(Skills_List, Ship.Modules(ModuleIndex).Trained_Skill)
.Tool));
ToolQuality :=
GetTrainingToolQuality
(MemberIndex, Ship.Modules(ModuleIndex).Trained_Skill);
else
RequiredTool := Repair_Tools;
end if;
if RequiredTool /= Null_Unbounded_String then
if ToolsIndex = 0 then
ToolsIndex :=
FindItem
(Inventory => Ship.Cargo, ItemType => RequiredTool,
Quality => ToolQuality);
if ToolsIndex = 0 then
ToolsIndex :=
FindItem
(Inventory => Ship.Crew(MemberIndex).Inventory,
ItemType => RequiredTool, Quality => ToolQuality);
if ToolsIndex > 0 then
Ship.Crew(MemberIndex).Equipment(7) := ToolsIndex;
end if;
else
Ship.Crew(MemberIndex).Equipment(7) := 0;
end if;
end if;
if ToolsIndex = 0 then
case GivenOrder is
when Repair =>
raise Crew_Order_Error
with MemberName &
" can't start repairing ship because you don't have the proper tools.";
when Clean =>
raise Crew_Order_Error
with MemberName &
" can't start cleaning ship because you don't have any cleaning tools.";
when Upgrading =>
raise Crew_Order_Error
with MemberName &
" can't start upgrading module because you don't have the proper tools.";
when Train =>
raise Crew_Order_Error
with MemberName &
" can't start training because you don't have the proper tools.";
when others =>
return;
end case;
end if;
end if;
end if;
if GivenOrder = Rest then
Ship.Crew(MemberIndex).PreviousOrder := Rest;
if Ship.Crew(MemberIndex).Order in Repair | Clean | Upgrading |
Train then
ToolsIndex := Ship.Crew(MemberIndex).Equipment(7);
if ToolsIndex > 0 then
UpdateCargo
(Ship,
Ship.Crew(MemberIndex).Inventory(ToolsIndex).ProtoIndex, 1,
Ship.Crew(MemberIndex).Inventory(ToolsIndex).Durability);
UpdateInventory
(MemberIndex => MemberIndex, Amount => -1,
InventoryIndex => ToolsIndex);
end if;
end if;
end if;
if Ship = Player_Ship then
case GivenOrder is
when Pilot =>
AddMessage(MemberName & " starts piloting.", OrderMessage);
Ship.Modules(ModuleIndex2).Owner(1) := MemberIndex;
when Engineer =>
AddMessage
(MemberName & " starts engineer's duty.", OrderMessage);
when Gunner =>
AddMessage(MemberName & " starts operating gun.", OrderMessage);
Ship.Modules(ModuleIndex2).Owner(1) := MemberIndex;
when Rest =>
AddMessage(MemberName & " is going on a break.", OrderMessage);
when Repair =>
AddMessage
(MemberName & " starts repairing ship.", OrderMessage);
when Craft =>
AddMessage(MemberName & " starts manufacturing.", OrderMessage);
for Owner of Ship.Modules(ModuleIndex2).Owner loop
if Owner = 0 then
Owner := MemberIndex;
exit;
end if;
end loop;
when Upgrading =>
AddMessage
(MemberName & " starts upgrading " &
To_String(Ship.Modules(Ship.Upgrade_Module).Name) & ".",
OrderMessage);
when Talk =>
AddMessage
(MemberName & " is now assigned to talking in bases.",
OrderMessage);
when Heal =>
AddMessage
(MemberName & " starts healing wounded crew members.",
OrderMessage);
if ModuleIndex > 0 then
for Owner of Ship.Modules(ModuleIndex).Owner loop
if Owner = 0 then
Owner := MemberIndex;
exit;
end if;
end loop;
end if;
when Clean =>
AddMessage(MemberName & " starts cleaning ship.", OrderMessage);
when Boarding =>
AddMessage
(MemberName & " starts boarding the enemy ship.",
OrderMessage);
when Defend =>
AddMessage
(MemberName & " starts defending the ship.", OrderMessage);
when Train =>
AddMessage
(MemberName & " starts personal training.", OrderMessage);
for Owner of Ship.Modules(ModuleIndex2).Owner loop
if Owner = 0 then
Owner := MemberIndex;
exit;
end if;
end loop;
end case;
end if;
Ship.Crew(MemberIndex).Order := GivenOrder;
Ship.Crew(MemberIndex).OrderTime := 15;
if GivenOrder /= Rest then
UpdateMorale(Ship, MemberIndex, -1);
end if;
if CheckPriorities then
UpdateOrders(Ship);
end if;
exception
when An_Exception : Crew_No_Space_Error =>
if Ship = Player_Ship then
raise Crew_Order_Error with Exception_Message(An_Exception);
else
return;
end if;
end GiveOrders;
procedure UpdateOrders
(Ship: in out Ship_Record; Combat: Boolean := False) is
HavePilot, HaveEngineer, HaveUpgrade, HaveTrader, NeedClean, NeedRepairs,
NeedGunners, NeedCrafters, CanHeal, NeedTrader: Boolean := False;
EventIndex: constant Events_Container.Extended_Index :=
SkyMap(Ship.Sky_X, Ship.Sky_Y).EventIndex;
function UpdatePosition
(Order: Crew_Orders; MaxPriority: Boolean := True) return Boolean is
OrderIndex: Natural := 0;
MemberIndex: Crew_Container.Extended_Index := 0;
ModuleIndex: Modules_Container.Extended_Index := 0;
begin
OrderIndex :=
(if Crew_Orders'Pos(Order) < Crew_Orders'Pos(Defend) then
Crew_Orders'Pos(Order) + 1
else Crew_Orders'Pos(Order));
if MaxPriority then
Find_Member_Max_Priority_Loop :
for I in Ship.Crew.Iterate loop
if Ship.Crew(I).Orders(OrderIndex) = 2 and
Ship.Crew(I).Order /= Order and
Ship.Crew(I).PreviousOrder /= Order then
MemberIndex := Crew_Container.To_Index(I);
exit Find_Member_Max_Priority_Loop;
end if;
end loop Find_Member_Max_Priority_Loop;
else
Find_Member_Priority_Loop :
for I in Ship.Crew.Iterate loop
if Ship.Crew(I).Orders(OrderIndex) = 1 and
Ship.Crew(I).Order = Rest and
Ship.Crew(I).PreviousOrder = Rest then
MemberIndex := Crew_Container.To_Index(I);
exit Find_Member_Priority_Loop;
end if;
end loop Find_Member_Priority_Loop;
end if;
if MemberIndex = 0 then
return False;
end if;
if Order in Gunner | Craft | Heal | Pilot | Engineer | Train then
Find_Module_Index_Loop :
for I in Ship.Modules.Iterate loop
if Ship.Modules(I).Durability > 0 then
case Ship.Modules(I).M_Type is
when GUN =>
if Order = Gunner and Ship.Modules(I).Owner(1) = 0 then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Module_Index_Loop;
end if;
when WORKSHOP =>
if Order = Craft and
Ship.Modules(I).Crafting_Index /=
Null_Unbounded_String then
Find_Empty_Workplace_Loop :
for Owner of Ship.Modules(I).Owner loop
if Owner = 0 then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Empty_Workplace_Loop;
end if;
end loop Find_Empty_Workplace_Loop;
exit Find_Module_Index_Loop when ModuleIndex > 0;
end if;
when MEDICAL_ROOM =>
if Order = Heal then
Find_Empty_Medical_Loop :
for Owner of Ship.Modules(I).Owner loop
if Owner = 0 then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Empty_Medical_Loop;
end if;
end loop Find_Empty_Medical_Loop;
exit Find_Module_Index_Loop when ModuleIndex > 0;
end if;
when COCKPIT =>
if Order = Pilot then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Module_Index_Loop;
end if;
when ENGINE =>
if Order = Engineer then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Module_Index_Loop;
end if;
when TRAINING_ROOM =>
if Order = Train and
Ship.Modules(I).Trained_Skill > 0 then
Find_Empty_Training_Loop :
for Owner of Ship.Modules(I).Owner loop
if Owner = 0 then
ModuleIndex := Modules_Container.To_Index(I);
exit Find_Empty_Training_Loop;
end if;
end loop Find_Empty_Training_Loop;
exit Find_Module_Index_Loop when ModuleIndex > 0;
end if;
when others =>
null;
end case;
end if;
end loop Find_Module_Index_Loop;
if ModuleIndex = 0 then
return False;
end if;
end if;
if Ship.Crew(MemberIndex).Order /= Rest then
GiveOrders(Ship, MemberIndex, Rest, 0, False);
end if;
GiveOrders(Ship, MemberIndex, Order, ModuleIndex);
return True;
exception
when An_Exception : Crew_Order_Error | Crew_No_Space_Error =>
if Ship = Player_Ship then
AddMessage(Exception_Message(An_Exception), OrderMessage, RED);
end if;
return False;
end UpdatePosition;
begin
Crew_Members_Loop :
for Member of Ship.Crew loop
case Member.Order is
when Pilot =>
HavePilot := True;
when Engineer =>
HaveEngineer := True;
when Upgrading =>
HaveUpgrade := True;
when Talk =>
HaveTrader := True;
when others =>
null;
end case;
if Member.Health < 100 then
if FindItem
(Inventory => Ship.Cargo,
ItemType => Factions_List(Member.Faction).HealingTools) >
0 then
CanHeal := True;
end if;
end if;
end loop Crew_Members_Loop;
Modules_Need_Loop :
for Module of Ship.Modules loop
if Module.Durability > 0 then
case Module.M_Type is
when GUN =>
if Module.Owner(1) = 0 and not NeedGunners then
NeedGunners := True;
end if;
when WORKSHOP =>
if Module.Crafting_Index /= Null_Unbounded_String and
not NeedCrafters then
Find_Empty_Crafting_Loop :
for Owner of Module.Owner loop
if Owner = 0 then
NeedCrafters := True;
exit Find_Empty_Crafting_Loop;
end if;
end loop Find_Empty_Crafting_Loop;
end if;
when CABIN =>
if Module.Cleanliness < Module.Quality then
NeedClean := True;
end if;
when others =>
null;
end case;
end if;
if Module.Durability < Module.Max_Durability and not NeedRepairs then
Find_Need_Repairs_Loop :
for Item of Ship.Cargo loop
if Items_List(Item.ProtoIndex).IType =
Modules_List(Module.Proto_Index).RepairMaterial then
NeedRepairs := True;
exit Find_Need_Repairs_Loop;
end if;
end loop Find_Need_Repairs_Loop;
end if;
end loop Modules_Need_Loop;
if SkyMap(Ship.Sky_X, Ship.Sky_Y).BaseIndex > 0 then
NeedTrader := True;
end if;
if (not NeedTrader and EventIndex > 0)
and then
(Events_List(EventIndex).EType = Trader or
Events_List(EventIndex).EType = FriendlyShip) then
NeedTrader := True;
end if;
if not HavePilot and then UpdatePosition(Pilot) then
UpdateOrders(Ship);
end if;
if not HaveEngineer and then UpdatePosition(Engineer) then
UpdateOrders(Ship);
end if;
if NeedGunners and then UpdatePosition(Gunner) then
UpdateOrders(Ship);
end if;
if NeedCrafters and then UpdatePosition(Craft) then
UpdateOrders(Ship);
end if;
if not HaveUpgrade and Ship.Upgrade_Module > 0 and
FindItem(Inventory => Ship.Cargo, ItemType => Repair_Tools) > 0 then
if FindItem
(Inventory => Ship.Cargo,
ItemType =>
Modules_List(Ship.Modules(Ship.Upgrade_Module).Proto_Index)
.RepairMaterial) >
0
and then UpdatePosition(Upgrading) then
UpdateOrders(Ship);
end if;
end if;
if (not HaveTrader and NeedTrader) and then UpdatePosition(Talk) then
UpdateOrders(Ship);
end if;
if
(NeedClean and
FindItem(Inventory => Ship.Cargo, ItemType => Cleaning_Tools) > 0)
and then UpdatePosition(Clean) then
UpdateOrders(Ship);
end if;
if CanHeal and then UpdatePosition(Heal) then
UpdateOrders(Ship);
end if;
if
(NeedRepairs and
FindItem(Inventory => Ship.Cargo, ItemType => Repair_Tools) > 0)
and then UpdatePosition(Repair) then
UpdateOrders(Ship);
end if;
if Combat then
if UpdatePosition(Defend) then
UpdateOrders(Ship);
end if;
if UpdatePosition(Boarding) then
UpdateOrders(Ship);
end if;
end if;
if UpdatePosition(Train) then
UpdateOrders(Ship);
end if;
if not HavePilot and then UpdatePosition(Pilot, False) then
UpdateOrders(Ship);
end if;
if not HaveEngineer and then UpdatePosition(Engineer, False) then
UpdateOrders(Ship);
end if;
if NeedGunners and then UpdatePosition(Gunner, False) then
UpdateOrders(Ship);
end if;
if NeedCrafters and then UpdatePosition(Craft, False) then
UpdateOrders(Ship);
end if;
if not HaveUpgrade and Ship.Upgrade_Module > 0 and
FindItem(Inventory => Ship.Cargo, ItemType => Repair_Tools) > 0 then
if FindItem
(Inventory => Ship.Cargo,
ItemType =>
Modules_List(Ship.Modules(Ship.Upgrade_Module).Proto_Index)
.RepairMaterial) >
0
and then UpdatePosition(Upgrading, False) then
UpdateOrders(Ship);
end if;
end if;
if (not HaveTrader and SkyMap(Ship.Sky_X, Ship.Sky_Y).BaseIndex > 0)
and then UpdatePosition(Talk, False) then
UpdateOrders(Ship);
end if;
if
(NeedClean and
FindItem(Inventory => Ship.Cargo, ItemType => Cleaning_Tools) > 0)
and then UpdatePosition(Clean, False) then
UpdateOrders(Ship);
end if;
if CanHeal and then UpdatePosition(Heal, False) then
UpdateOrders(Ship);
end if;
if
(NeedRepairs and
FindItem(Inventory => Ship.Cargo, ItemType => Repair_Tools) > 0)
and then UpdatePosition(Repair, False) then
UpdateOrders(Ship);
end if;
if Combat then
if UpdatePosition(Defend, False) then
UpdateOrders(Ship);
end if;
if UpdatePosition(Boarding, False) then
UpdateOrders(Ship);
end if;
end if;
if UpdatePosition(Train, False) then
UpdateOrders(Ship, False);
end if;
end UpdateOrders;
procedure UpdateMorale
(Ship: in out Ship_Record; MemberIndex: Crew_Container.Extended_Index;
Value: Integer) is
NewMorale, NewLoyalty, NewValue: Integer;
FactionIndex: constant Unbounded_String :=
Ship.Crew(MemberIndex).Faction;
begin
if Factions_List(FactionIndex).Flags.Contains
(To_Unbounded_String("nomorale")) then
return;
end if;
NewValue := Value;
if Factions_List(FactionIndex).Flags.Contains
(To_Unbounded_String("fanaticism")) then
if Value > 0 then
NewValue := Value * 5;
else
NewValue := Value / 10;
if NewValue = 0 and then Get_Random(1, 10) <= abs (Value) then
NewValue := -1;
end if;
if NewValue = 0 then
return;
end if;
end if;
end if;
NewValue := Ship.Crew(MemberIndex).Morale(2) + NewValue;
NewMorale := Ship.Crew(MemberIndex).Morale(1);
Raise_Morale_Loop :
while NewValue >= 5 loop
NewValue := NewValue - 5;
NewMorale := NewMorale + 1;
end loop Raise_Morale_Loop;
Lower_Morale_Loop :
while NewValue < 0 loop
NewValue := NewValue + 5;
NewMorale := NewMorale - 1;
end loop Lower_Morale_Loop;
if NewMorale > 100 then
NewMorale := 100;
elsif NewMorale < 0 then
NewMorale := 0;
end if;
Ship.Crew(MemberIndex).Morale := (NewMorale, NewValue);
if Ship = Player_Ship and MemberIndex = 1 then
return;
end if;
NewLoyalty := Ship.Crew(MemberIndex).Loyalty;
if NewMorale > 75 and NewLoyalty < 100 then
NewLoyalty := NewLoyalty + 1;
end if;
if NewMorale < 25 and NewLoyalty > 0 then
NewLoyalty := NewLoyalty - Get_Random(5, 10);
end if;
if NewLoyalty > 100 then
NewLoyalty := 100;
elsif NewLoyalty < 0 then
NewLoyalty := 0;
end if;
Ship.Crew(MemberIndex).Loyalty := NewLoyalty;
end UpdateMorale;
end Ships.Crew;
|
-- SPDX-FileCopyrightText: 2022 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Regions.Contexts.Environments.Nodes;
with Regions.Entities.Packages;
with Regions.Shared_Hashed_Maps;
-- with Regions.Shared_Lists;
private
package Regions.Contexts.Environments.Package_Nodes is
pragma Preelaborate;
function Hash
(Value : Regions.Symbols.Symbol) return Ada.Containers.Hash_Type
is (Ada.Containers.Hash_Type'Mod (Value));
type List_Change_Count is mod 2 ** 32;
package Name_List_Maps is new Regions.Shared_Hashed_Maps
(Regions.Symbols.Symbol,
Selected_Entity_Name_Lists.List,
Ada.Containers.Hash_Type,
List_Change_Count,
Hash,
Regions.Symbols."=",
Selected_Entity_Name_Lists."=");
type Package_Node;
function Empty_Map (Self : access Package_Node)
return Name_List_Maps.Map;
type Package_Node is new Nodes.Entity_Node with record
Version : aliased List_Change_Count := 0;
Names : Name_List_Maps.Map :=
Empty_Map (Package_Node'Unchecked_Access);
end record;
type Package_Entity is new Environments.Nodes.Base_Entity
and Regions.Entities.Packages.Package_Entity
with null record;
overriding function Is_Package (Self : Package_Entity) return Boolean
is (True);
overriding function Immediate_Visible_Backward
(Self : Package_Entity;
Symbol : Symbols.Symbol)
return Regions.Entity_Iterator_Interfaces.Forward_Iterator'Class;
overriding function Immediate_Visible
(Self : Package_Entity;
Symbol : Symbols.Symbol)
return Regions.Entity_Iterator_Interfaces.Forward_Iterator'Class;
end Regions.Contexts.Environments.Package_Nodes;
|
-----------------------------------------------------------------------
-- html.lists -- List of items
-- Copyright (C) 2009, 2010, 2014 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.
-----------------------------------------------------------------------
package ASF.Components.Html.Lists is
-- The attribute that defines the layout of the list.
LAYOUT_ATTR_NAME : constant String := "layout";
-- The attribute that defines the CSS style to apply on the list.
STYLE_CLASS_ATTR_NAME : constant String := "styleClass";
-- The attribute representing the CSS to be applied on each item of the list.
ITEM_STYLE_CLASS_ATTR_NAME : constant String := "itemStyleClass";
type UIList is new UIHtmlComponent with private;
-- Get the list layout to use. The default is to use no layout or a div if some CSS style
-- is applied on the list or some specific list ID must be generated. Possible layout values
-- include:
-- "simple" : the list is rendered as is or as a div with each children as is,
-- "unorderedList" : the list is rendered as an HTML ul/li list,
-- "orderedList" : the list is rendered as an HTML ol/li list.
function Get_Layout (UI : in UIList;
Class : in String;
Context : in Faces_Context'Class) return String;
-- Get the value to write on the output.
function Get_Value (UI : in UIList) return EL.Objects.Object;
-- Set the value to write on the output.
procedure Set_Value (UI : in out UIList;
Value : in EL.Objects.Object);
-- Get the variable name
function Get_Var (UI : in UIList) return String;
-- Encode an item of the list with the given item layout and item class.
procedure Encode_Item (UI : in UIList;
Item_Layout : in String;
Item_Class : in String;
Context : in out Faces_Context'Class);
procedure Encode_Children (UI : in UIList;
Context : in out Faces_Context'Class);
private
type UIList is new UIHtmlComponent with record
Value : EL.Objects.Object;
end record;
end ASF.Components.Html.Lists;
|
with
glx.Pointers;
package GLX.Pointer_Pointers
is
use glx.Pointers;
type VisualID_Pointer_Pointer is access all VisualID_Pointer;
type XVisualInfo_Pointer_Pointer is access all XVisualInfo_Pointer;
type Pixmap_Pointer_Pointer is access all Pixmap_Pointer;
type Font_Pointer_Pointer is access all Font_Pointer;
type Window_Pointer_Pointer is access all Window_Pointer;
type Bool_Pointer_Pointer is access all Bool_Pointer;
type ContextRec_Pointer_Pointer is access all ContextRec_Pointer;
type XID_Pointer_Pointer is access all XID_Pointer;
type GLXPixmap_Pointer_Pointer is access all GLXPixmap_Pointer;
type Drawable_Pointer_Pointer is access all Drawable_Pointer;
type FBConfig_Pointer_Pointer is access all FBConfig_Pointer;
type FBConfigID_Pointer_Pointer is access all FBConfigID_Pointer;
type ContextID_Pointer_Pointer is access all ContextID_Pointer;
type GLXWindow_Pointer_Pointer is access all Window_Pointer;
type PBuffer_Pointer_Pointer is access all PBuffer_Pointer;
end GLX.Pointer_Pointers;
|
package Use_CPU is
procedure Work (Amount_MS : in Natural)
with Inline;
-- Amount of time in ms, truncated to tens of ms
end Use_CPU;
|
with Bit_Types;
package HAL.I2C is
pragma Preelaborate;
type Mode_Type is (MASTER, SLAVE);
type Speed_Type is (SLOW, FAST);
type Configuration_Type is record
Mode : Mode_Type;
Speed : Speed_Type;
end record
type Data_Type is array(Natural range <>) of Byte;
type Port_Type is (UNKNOWN, I2C1, I2C2);
type Address_Type is Bits_10;
type I2C_Device_Type is record
Port : Port_Type;
Address : Address_Type
end record;
procedure initialize(Port : in Port_Type; Configuration : in Configuration_Type);
-- writes data to tx buffer
procedure write (Device : in I2C_Device_Type; Data : in Data_Type);
-- reads data from the TX Buffer
procedure read (Device : in I2C_Device_Type; Data : out Data_Type);
-- writes and reads data
procedure transfer (Device : in I2C_Device_Type; Data_TX : in Data_Type; Data_RX : out Data_Type);
end HAL.I2C;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with WSDL.AST.Bindings;
pragma Unreferenced (WSDL.AST.Bindings);
-- GNAT Pro 7.2.0w (20130423): package is needed to access to type's
-- components.
with WSDL.AST.Operations;
pragma Unreferenced (WSDL.AST.Operations);
-- GNAT Pro 7.2.0w (20130423): package is needed to access to type's
-- components.
with WSDL.Constants;
package body WSDL.Parsers.SOAP is
use WSDL.Constants;
---------------------------
-- Start_Binding_Element --
---------------------------
procedure Start_Binding_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Node : not null WSDL.AST.Binding_Access;
Success : in out Boolean) is
begin
-- Analyze 'wsoap:version' attribute.
--
-- SOAPBinding-2069: "Every SOAP binding MUST indicate what version of
-- SOAP is in use for the operations of the interface that this binding
-- applies to."
--
-- "{soap version} The actual value of the wsoap:version attribute
-- information item, if present; otherwise "1.2"."
--
-- Thus, we don't need to check and issue error for SOAPBinding-2069,
-- but we need to set default value.
if Attributes.Is_Specified (SOAP_Namespace_URI, Version_Attribute) then
Node.SOAP.Version :=
Attributes.Value (SOAP_Namespace_URI, Version_Attribute);
else
Node.SOAP.Version := SOAP_Version_12_Literal;
end if;
-- Analyze 'wsoap:protocol' attribute.
--
-- SOAPBinding-2070: "Every SOAP binding MUST indicate what underlying
-- protocol is in use."
--
-- There is no default value for this property, thus report error when
-- this attribute is absent.
if not Attributes.Is_Specified
(SOAP_Namespace_URI, Protocol_Attribute)
then
raise Program_Error;
end if;
Node.SOAP.Underlying_Protocol :=
Attributes.Value (SOAP_Namespace_URI, Protocol_Attribute);
-- Analyze mepDefault attribute.
--
-- SOAPMEPDefault-2073: "A xs:anyURI, which is an absolute IRI as
-- defined by [IETF RFC 3987], to the Binding component."
--
-- XXX Check of SOAPMEPDefault-2073 assertion is not implemented.
Node.SOAP.MEP_Default :=
Attributes.Value (SOAP_Namespace_URI, MEP_Default_Attribute);
end Start_Binding_Element;
-------------------------------------
-- Start_Binding_Operation_Element --
-------------------------------------
procedure Start_Binding_Operation_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Node : not null WSDL.AST.Binding_Operation_Access;
Success : in out Boolean) is
begin
-- Analyze 'wsoap:mep' attribute.
--
-- SOAPMEP-2074: "A xs:anyURI, which is an absolute IRI as defined by
-- [IETF RFC 3987], to the Binding Operation component."
--
-- XXX Check of SOAPMEP-2074 assertion is not implemented.
Node.SOAP.MEP := Attributes.Value (SOAP_Namespace_URI, MEP_Attribute);
-- Analyze 'wsoap:action' attribute.
--
-- SOAPAction-2075: "A xs:anyURI, which is an absolute IRI as defined by
-- [IETF RFC 3987], to the Binding Operation component."
--
-- XXX Check of SOAPAction-2075 assertion is not implemented.
Node.SOAP.Action :=
Attributes.Value (SOAP_Namespace_URI, Action_Attribute);
end Start_Binding_Operation_Element;
end WSDL.Parsers.SOAP;
|
--
-- No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
--
-- The version of the OpenAPI document: 20220523
--
--
-- NOTE: This package is auto generated by OpenAPI-Generator 5.4.0.
-- https://openapi-generator.tech
-- Do not edit the class manually.
package body .Models is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*use clause for package*");
use Swagger.Streams;
end .Models;
|
-- C45291A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT THE MEMBERSHIP TESTS YIELD CORRECT RESULTS FOR TASK
-- TYPES, LIMITED PRIVATE TYPES, COMPOSITE LIMITED TYPES, AND
-- PRIVATE TYPES WITHOUT DISCRIMINANTS.
-- HISTORY:
-- JET 08/10/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C45291A IS
TASK TYPE TASK1 IS
ENTRY E;
END TASK1;
PACKAGE PACK IS
TYPE LIM_PRIV IS LIMITED PRIVATE;
TYPE LIM_COMP IS ARRAY (1..10) OF LIM_PRIV;
TYPE PRIV IS PRIVATE;
PROCEDURE INIT(LP : OUT LIM_PRIV;
LC : IN OUT LIM_COMP;
P : OUT PRIV);
PRIVATE
TYPE LIM_PRIV IS RANGE -100..100;
TYPE PRIV IS RECORD
I : INTEGER;
END RECORD;
END PACK;
SUBTYPE SUB_TASK1 IS TASK1;
SUBTYPE SUB_LIM_PRIV IS PACK.LIM_PRIV;
SUBTYPE SUB_LIM_COMP IS PACK.LIM_COMP;
SUBTYPE SUB_PRIV IS PACK.PRIV;
T1 : TASK1;
LP : PACK.LIM_PRIV;
LC : PACK.LIM_COMP;
P : PACK.PRIV;
TASK BODY TASK1 IS
BEGIN
ACCEPT E DO
NULL;
END E;
END TASK1;
PACKAGE BODY PACK IS
PROCEDURE INIT (LP : OUT LIM_PRIV;
LC : IN OUT LIM_COMP;
P : OUT PRIV) IS
BEGIN
LP := 0;
LC := (OTHERS => 0);
P := (I => 0);
END INIT;
END PACK;
BEGIN
TEST ("C45291A", "CHECK THAT THE MEMBERSHIP TESTS YIELD CORRECT " &
"RESULTS FOR TASK TYPES, LIMITED PRIVATE TYPES," &
" COMPOSITE LIMITED TYPES, AND PRIVATE TYPES " &
"WITHOUT DISCRIMINANTS");
PACK.INIT(LP, LC, P);
IF NOT IDENT_BOOL(T1 IN TASK1) THEN
FAILED ("INCORRECT VALUE OF 'T1 IN TASK1'");
END IF;
IF IDENT_BOOL(T1 NOT IN TASK1) THEN
FAILED ("INCORRECT VALUE OF 'T1 NOT IN TASK1'");
END IF;
IF NOT IDENT_BOOL(LP IN PACK.LIM_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'LP IN LIM_PRIV'");
END IF;
IF IDENT_BOOL(LP NOT IN PACK.LIM_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'LP NOT IN LIM_PRIV'");
END IF;
IF NOT IDENT_BOOL(LC IN PACK.LIM_COMP) THEN
FAILED ("INCORRECT VALUE OF 'LC IN LIM_COMP'");
END IF;
IF IDENT_BOOL(LC NOT IN PACK.LIM_COMP) THEN
FAILED ("INCORRECT VALUE OF 'LC NOT IN LIM_COMP'");
END IF;
IF NOT IDENT_BOOL(P IN PACK.PRIV) THEN
FAILED ("INCORRECT VALUE OF 'P IN PRIV'");
END IF;
IF IDENT_BOOL(P NOT IN PACK.PRIV) THEN
FAILED ("INCORRECT VALUE OF 'P NOT IN PRIV'");
END IF;
IF NOT IDENT_BOOL(T1 IN SUB_TASK1) THEN
FAILED ("INCORRECT VALUE OF 'T1 IN SUB_TASK1'");
END IF;
IF IDENT_BOOL(T1 NOT IN SUB_TASK1) THEN
FAILED ("INCORRECT VALUE OF 'T1 NOT IN SUB_TASK1'");
END IF;
IF NOT IDENT_BOOL(LP IN SUB_LIM_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'LP IN SUB_LIM_PRIV'");
END IF;
IF IDENT_BOOL(LP NOT IN SUB_LIM_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'LP NOT IN SUB_LIM_PRIV'");
END IF;
IF NOT IDENT_BOOL(LC IN SUB_LIM_COMP) THEN
FAILED ("INCORRECT VALUE OF 'LC IN SUB_LIM_COMP'");
END IF;
IF IDENT_BOOL(LC NOT IN SUB_LIM_COMP) THEN
FAILED ("INCORRECT VALUE OF 'LC NOT IN SUB_LIM_COMP'");
END IF;
IF NOT IDENT_BOOL(P IN SUB_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'P IN SUB_PRIV'");
END IF;
IF IDENT_BOOL(P NOT IN SUB_PRIV) THEN
FAILED ("INCORRECT VALUE OF 'P NOT IN SUB_PRIV'");
END IF;
T1.E;
RESULT;
END C45291A;
|
with
box2d_c.Binding,
c_math_c.Vector_2,
c_math_c.Conversion,
ada.unchecked_Deallocation,
ada.unchecked_Conversion;
package body box2d_Physics.Shape
is
use c_math_c.Conversion,
box2d_c .Binding;
-- Base Shape
--
overriding
procedure define (Self : in out Item)
is
begin
raise Error with "Shape not supported.";
end define;
overriding
procedure destruct (Self : in out Item)
is
begin
b2d_free_Shape (Self.C);
end destruct;
overriding
procedure Scale_is (Self : in out Item; Now : Vector_3)
is
begin
b2d_shape_Scale_is (Self.C, (c_math_c.Real (Now (1)),
c_math_c.Real (Now (2))));
end Scale_is;
-----------
-- Forge
--
-- 2D
--
type Circle_view is access Circle;
function new_circle_Shape (Radius : in Real) return physics.Shape.view
is
Self : constant Circle_view := new Circle;
-- Self : constant access Circle := new Circle;
-- c_Radius : aliased constant c_math_c.Real := +Radius;
begin
-- Self.C := b2d_new_Circle (c_Radius);
Self.Radius := Radius;
Self.define;
return physics.Shape.view (Self);
end new_circle_Shape;
overriding
procedure define (Self : in out Circle)
is
c_Radius : aliased constant c_math_c.Real := +Self.Radius;
begin
Self.C := b2d_new_Circle (c_Radius);
end define;
type Polygon_view is access Polygon;
function new_polygon_Shape (Vertices : in physics.Space.polygon_Vertices) return physics.Shape.view
is
-- P : Polygon (vertex_Count => Vertices'Length);
-- Self : constant Polygon_view := new Polygon' (P);
Self : constant Polygon_view := new Polygon (vertex_Count => Vertices'Length);
-- c_Verts : array (1 .. Vertices'Length) of aliased c_math_c.Vector_2.item;
begin
Self.Vertices := Vertices;
-- for i in c_Verts'Range
-- loop
-- c_Verts (i) := +Vertices (i);
-- end loop;
--
-- Self.C := b2d_new_Polygon (c_Verts (1)'Unchecked_Access,
-- c_Verts'Length);
Self.define;
return physics.Shape.view (Self);
end new_polygon_Shape;
overriding
procedure define (Self : in out Polygon)
is
c_Verts : array (1 .. Self.vertex_Count) of aliased c_math_c.Vector_2.item;
begin
for i in c_Verts'Range
loop
c_Verts (i) := +Self.Vertices (i);
end loop;
Self.C := b2d_new_Polygon (c_Verts (1)'unchecked_Access,
c_Verts'Length);
end define;
-- 3D
--
function new_box_Shape (half_Extents : in Vector_3) return physics.Shape.view
is
pragma unreferenced (half_Extents);
begin
raise physics.unsupported_Error;
return null;
end new_box_Shape;
function new_capsule_Shape (Radii : in Vector_2;
Height : in Real) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_capsule_Shape;
function new_cone_Shape (Radius,
Height : in Real) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_cone_Shape;
function new_convex_hull_Shape (Points : in physics.Vector_3_array) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_convex_hull_Shape;
function new_cylinder_Shape (half_Extents : in Vector_3) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_cylinder_Shape;
function new_heightfield_Shape (Width,
Depth : in Positive;
Heights : access constant Real;
min_Height,
max_Height : in Real;
Scale : in Vector_3) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_heightfield_Shape;
function new_multiSphere_Shape (Positions : in physics.Vector_3_array;
Radii : in Vector) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_multiSphere_Shape;
function new_plane_Shape (Normal : in Vector_3;
Offset : in Real) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_plane_Shape;
function new_sphere_Shape (Radius : in math.Real) return physics.Shape.view
is
begin
raise physics.unsupported_Error;
return null;
end new_sphere_Shape;
procedure free (the_Shape : in out physics.Shape.view)
is
procedure deallocate is new ada.unchecked_Deallocation (physics.Shape.item'Class,
physics.Shape.view);
begin
the_Shape.destruct;
deallocate (the_Shape);
end free;
end box2d_Physics.Shape;
|
-- pragma SPARK_Mode;
with Types; use Types;
with Interfaces.C; use Interfaces.C;
-- @summary
-- Interface to the robots 3-axis gyroscope
--
-- @description
-- This package exposes the interface to the robot's 3 axis gyroscope
--
package Zumo_L3gd20h is
-- The gain to apply to a sensor reading
Gain : constant := 0.07; -- degrees/s/digit
-- True if package is init'd
Initd : Boolean := False;
-- Inits the package. Pin muxing and whatnot.
procedure Init
with Global => (In_Out => Initd),
Pre => not Initd,
Post => Initd;
-- Read the temperature of the sensor
-- @return a byte value with the temperature
function Read_Temp return signed_char
with Pre => Initd;
-- Read the status of the sensor
-- @return a byte value with the status
function Read_Status return Byte
with Pre => Initd;
-- Read the gyro of the sensor
-- @param Data the read data from the sensor
procedure Read_Gyro (Data : out Axis_Data)
with Pre => Initd;
L3GD20H_Exception : exception;
private
-- Reads the WHOAMI register from the sensor and compares it against
-- the known value
procedure Check_WHOAMI;
-- The mapping of registers in the sensor
-- @value WHO_AM_I Device identification register
-- @value CTRL1 control 1 register
-- @value CTRL2 control 2 register
-- @value CTRL3 control 3 register
-- @value CTRL4 control 4 register
-- @value CTRL5 control 5 register
-- @value REFERENCE Digital high pass filter reference value
-- @value OUT_TEMP Temperature data (-1LSB/deg with 8 bit resolution).
-- The value is expressed as two's complement.
-- @value STATUS sensor status register
-- @value OUT_X_L X-axis angular rate data low register
-- @value OUT_X_H X-axis angular rate data high register
-- @value OUT_Y_L Y-axis angular rate data low register
-- @value OUT_Y_H Y-axis angular rate data high register
-- @value OUT_Z_L Z-axis angular rate data low register
-- @value OUT_Z_H Z-axis angular rate data high register
-- @value FIFO_CTRL fifo control register
-- @value FIFO_SRC stored data level in fifo
type Reg_Index is
(WHO_AM_I,
CTRL1,
CTRL2,
CTRL3,
CTRL4,
CTRL5,
REFERENCE,
OUT_TEMP,
STATUS,
OUT_X_L,
OUT_X_H,
OUT_Y_L,
OUT_Y_H,
OUT_Z_L,
OUT_Z_H,
FIFO_CTRL,
FIFO_SRC,
IG_CFG,
IG_SRC,
IG_THS_XH,
IG_THS_XL,
IG_THS_YH,
IG_THS_YL,
IG_THS_ZH,
IG_THS_ZL,
IG_DURATION,
LOW_ODR);
-- Mapping of register enums to actual register addresses
Regs : constant array (Reg_Index) of Byte := (WHO_AM_I => 16#0F#,
CTRL1 => 16#20#,
CTRL2 => 16#21#,
CTRL3 => 16#22#,
CTRL4 => 16#23#,
CTRL5 => 16#24#,
REFERENCE => 16#25#,
OUT_TEMP => 16#26#,
STATUS => 16#27#,
OUT_X_L => 16#28#,
OUT_X_H => 16#29#,
OUT_Y_L => 16#2A#,
OUT_Y_H => 16#2B#,
OUT_Z_L => 16#2C#,
OUT_Z_H => 16#2D#,
FIFO_CTRL => 16#2E#,
FIFO_SRC => 16#2F#,
IG_CFG => 16#30#,
IG_SRC => 16#31#,
IG_THS_XH => 16#32#,
IG_THS_XL => 16#33#,
IG_THS_YH => 16#34#,
IG_THS_YL => 16#35#,
IG_THS_ZH => 16#36#,
IG_THS_ZL => 16#37#,
IG_DURATION => 16#38#,
LOW_ODR => 16#39#);
type Register_Bytes is record
Register : Reg_Index;
Value : Byte;
end record;
type Register_Byte_Array is array (Natural range <>) of Register_Bytes;
end Zumo_L3gd20h;
|
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
procedure Random_Distribution is
Trials : constant := 1_000_000;
type Outcome is (Aleph, Beth, Gimel, Daleth, He, Waw, Zayin, Heth);
Pr : constant array (Outcome) of Uniformly_Distributed :=
(1.0/5.0, 1.0/6.0, 1.0/7.0, 1.0/8.0, 1.0/9.0, 1.0/10.0, 1.0/11.0, 1.0);
Samples : array (Outcome) of Natural := (others => 0);
Value : Uniformly_Distributed;
Dice : Generator;
begin
for Try in 1..Trials loop
Value := Random (Dice);
for I in Pr'Range loop
if Value <= Pr (I) then
Samples (I) := Samples (I) + 1;
exit;
else
Value := Value - Pr (I);
end if;
end loop;
end loop;
-- Printing the results
for I in Pr'Range loop
Put (Outcome'Image (I) & Character'Val (9));
Put (Float'Image (Float (Samples (I)) / Float (Trials)) & Character'Val (9));
if I = Heth then
Put_Line (" rest");
else
Put_Line (Uniformly_Distributed'Image (Pr (I)));
end if;
end loop;
end Random_Distribution;
|
package Lv.Area is
Lv_Coord_Max : constant := (16383);
Lv_Coord_Min : constant := (-16384);
subtype Coord_T is Int16_T;
type Point_T is record
X : aliased Coord_T;
Y : aliased Coord_T;
end record;
pragma Convention (C_Pass_By_Copy, Point_T);
type Point_Array is array (Natural range <>) of aliased Lv.Area.Point_T
with Convention => C;
type Area_T is record
X1 : aliased Coord_T;
Y1 : aliased Coord_T;
X2 : aliased Coord_T;
Y2 : aliased Coord_T;
end record;
pragma Convention (C_Pass_By_Copy, Area_T);
-- Initialize an area
-- @param area_p pointer to an area
-- @param x1 left coordinate of the area
-- @param y1 top coordinate of the area
-- @param x2 right coordinate of the area
-- @param y2 bottom coordinate of the area
procedure Set
(Area : access Area_T;
X1 : Coord_T;
Y1 : Coord_T;
X2 : Coord_T;
Y2 : Coord_T);
-- Copy an area
-- @param dest pointer to the destination area
-- @param src pointer to the source area
procedure Copy (Dest : access Area_T; Src : access constant Area_T);
-- Get the width of an area
-- @param area_p pointer to an area
-- @return the width of the area (if x1 == x2 -> width = 1)
function Get_Width (Area_P : access constant Area_T) return Coord_T;
-- Get the height of an area
-- @param area_p pointer to an area
-- @return the height of the area (if y1 == y2 -> height = 1)
function Get_Height (Area_P : access constant Area_T) return Coord_T;
-- Set the width of an area
-- @param area_p pointer to an area
-- @param w the new width of the area (w == 1 makes x1 == x2)
procedure Set_Width (Area_P : access Area_T; W : Coord_T);
-- Set the height of an area
-- @param area_p pointer to an area
-- @param h the new height of the area (h == 1 makes y1 == y2)
procedure Set_Height (Area_P : access Area_T; H : Coord_T);
-- Set the position of an area (width and height will be kept)
-- @param area_p pointer to an area
-- @param x the new x coordinate of the area
-- @param y the new y coordinate of the area
procedure Set_Pos (Area_P : access Area_T; X : Coord_T; Y : Coord_T);
-- Return with area of an area (x -- y)
-- @param area_p pointer to an area
-- @return size of area
function Get_Size (Area_P : access constant Area_T) return Uint32_T;
-- Get the common parts of two areas
-- @param res_p pointer to an area, the result will be stored her
-- @param a1_p pointer to the first area
-- @param a2_p pointer to the second area
-- @return false: the two area has NO common parts, res_p is invalid
function Intersect
(Res : access Area_T;
A1 : access constant Area_T;
A2 : access constant Area_T) return U_Bool;
-- Join two areas into a third which involves the other two
-- @param res_p pointer to an area, the result will be stored here
-- @param a1_p pointer to the first area
-- @param a2_p pointer to the second area
procedure Join
(Res : access Area_T;
A1 : access constant Area_T;
A2 : access constant Area_T);
-- Check if a point is on an area
-- @param a_p pointer to an area
-- @param p_p pointer to a point
-- @return false:the point is out of the area
function Is_Point_On
(A : access constant Area_T;
P : access constant Point_T) return U_Bool;
-- Check if two area has common parts
-- @param a1_p pointer to an area.
-- @param a2_p pointer to an other area
-- @return false: a1_p and a2_p has no common parts
function Is_On
(A1 : access constant Area_T;
A2 : access constant Area_T) return U_Bool;
-- Check if an area is fully on an other
-- @param ain_p pointer to an area which could be on aholder_p
-- @param aholder pointer to an area which could involve ain_p
-- @return
function Is_In
(A_In : access constant Area_T;
A_Holder : access constant Area_T) return U_Bool;
-------------
-- Imports --
-------------
pragma Import (C, Set, "lv_area_set");
pragma Import (C, Copy, "lv_area_copy_inline");
pragma Import (C, Get_Width, "lv_area_get_width_inline");
pragma Import (C, Get_Height, "lv_area_get_height_inline");
pragma Import (C, Set_Width, "lv_area_set_width");
pragma Import (C, Set_Height, "lv_area_set_height");
pragma Import (C, Set_Pos, "lv_area_set_pos");
pragma Import (C, Get_Size, "lv_area_get_size");
pragma Import (C, Intersect, "lv_area_intersect");
pragma Import (C, Join, "lv_area_join");
pragma Import (C, Is_Point_On, "lv_area_is_point_on");
pragma Import (C, Is_On, "lv_area_is_on");
pragma Import (C, Is_In, "lv_area_is_in");
end Lv.Area;
|
with AAA.Strings;
with CLIC.TTY;
with CLIC.User_Input;
with CLIC.Config.Load;
with CLIC_Ex.Commands.TTY;
with CLIC_Ex.Commands.User_Input;
with CLIC_Ex.Commands.Switches_And_Args;
with CLIC_Ex.Commands.Double_Dash;
with CLIC_Ex.Commands.Topics.Example;
with CLIC_Ex.Commands.Config;
with CLIC_Ex.Commands.Subsub;
package body CLIC_Ex.Commands is
Help_Switch : aliased Boolean := False;
No_Color : aliased Boolean := False;
-- Force-disable color output
No_TTY : aliased Boolean := False;
-- Used to disable control characters in output
-------------------------
-- Set_Global_Switches --
-------------------------
procedure Set_Global_Switches
(Config : in out CLIC.Subcommand.Switches_Configuration)
is
use CLIC.Subcommand;
begin
Define_Switch (Config,
Help_Switch'Access,
"-h", "--help",
"Display general or command-specific help");
Define_Switch (Config,
CLIC.User_Input.Not_Interactive'Access,
"-n", "--non-interactive",
"Assume default answers for all user prompts");
Define_Switch (Config,
No_Color'Access,
Long_Switch => "--no-color",
Help => "Disables colors in output");
Define_Switch (Config,
No_TTY'Access,
Long_Switch => "--no-tty",
Help => "Disables control characters in output");
end Set_Global_Switches;
-------------
-- Execute --
-------------
procedure Execute is
begin
Sub_Cmd.Parse_Global_Switches;
if No_TTY then
CLIC.TTY.Force_Disable_TTY;
end if;
if not No_Color and then not No_TTY then
CLIC.TTY.Enable_Color (Force => False);
-- This may still not enable color if TTY is detected to be incapable
end if;
CLIC.Config.Load.From_TOML (Config_DB, "global", "global_config.toml");
CLIC.Config.Load.From_TOML (Config_DB, "local", "local_config.toml");
Sub_Cmd.Load_Aliases (Config_DB);
Sub_Cmd.Execute;
end Execute;
begin
Sub_Cmd.Register (new Sub_Cmd.Builtin_Help);
Sub_Cmd.Register (new CLIC_Ex.Commands.Config.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.TTY.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.User_Input.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.Switches_And_Args.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.Double_Dash.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.Subsub.Instance);
Sub_Cmd.Register (new CLIC_Ex.Commands.Topics.Example.Instance);
Sub_Cmd.Set_Alias ("blink", AAA.Strings.Empty_Vector
.Append ("tty")
.Append ("--blink"));
Sub_Cmd.Set_Alias ("error_alias", AAA.Strings.Empty_Vector
.Append ("tty")
.Append ("--test"));
Sub_Cmd.Set_Alias ("alias_to_switch", AAA.Strings.Empty_Vector
.Append ("--plop"));
end CLIC_Ex.Commands;
|
with System.Pool_Local;
package body Actors is
-- Pool used to store/free components used for actors
component_pool : System.Pool_Local.Unbounded_Reclaim_Pool;
-- All orcs have same attack component, so we can share it between them
orc_attacker_comp : aliased Attacker := (power => 3);
troll_attacker_comp : aliased Attacker := (power => 4);
type Attacker_Ptr is access Attacker
with Storage_Pool => component_pool;
type Destructible_Ptr is access Destructible'Class
with Storage_Pool => component_pool;
type AI_Ptr is access AI'Class
with Storage_Pool => component_pool;
function make_player(x : Maps.X_Pos; y : Maps.Y_Pos;
name : String; defense_stat : Defense;
power, hp, max_hp : Health) return Actor is
attacker_comp : Attacker_Ptr := new Attacker'(power => power);
destructible_comp : Destructible_Ptr := new Player_Destructible'(max_hp => max_hp, hp => hp,
defense_stat => defense_stat);
ai_comp : AI_Ptr := new Player_AI;
begin
return result : Actor := (name => Actor_Names.To_Bounded_String(name),
x => x, y => y, ch => '@', color => Color.yellow, blocks => True,
attacker => attacker_comp,
destructible => destructible_comp,
ai => ai_comp);
end make_player;
function make_orc(x : Maps.X_Pos; y : Maps.Y_Pos) return Actor is
destructible_comp : Destructible_Ptr := new Monster_Destructible'(max_hp => 10, hp => 10,
defense_stat => 0);
ai_comp : AI_Ptr := new Monster_AI;
begin
return result : Actor := (name => Actor_Names.To_Bounded_String("Orc"),
x => x, y => y, ch => 'o', color => Color.desaturated_green,
blocks => True,
attacker => orc_attacker_comp'Unchecked_Access,
destructible => destructible_comp,
ai => ai_comp);
end make_orc;
function make_troll(x : Maps.X_Pos; y : Maps.Y_Pos) return Actor is
destructible_comp : Destructible_Ptr := new Monster_Destructible'(max_hp => 16, hp => 16,
defense_stat => 1);
ai_comp : AI_Ptr := new Monster_AI;
begin
return result : Actor := (name => Actor_Names.To_Bounded_String("Troll"),
x => x, y => y, ch => 'T', color => Color.darker_green,
blocks => True,
attacker => troll_attacker_comp'Unchecked_Access,
destructible => destructible_comp,
ai => ai_comp);
end make_troll;
function make_monster(x : Maps.X_Pos; y : Maps.Y_Pos; ch : Wide_Character;
name : String; color : RGB_Color;
defense_stat : Defense;
power, hp, max_hp : Health) return Actor is
attacker_comp : Attacker_Ptr := new Attacker'(power => power);
destructible_comp : Destructible_Ptr := new Monster_Destructible'(max_hp => max_hp, hp => hp,
defense_stat => defense_stat);
ai_comp : AI_Ptr := new Monster_AI;
begin
return result : Actor := (name => Actor_Names.To_Bounded_String(name),
x => x, y => y, ch => ch, color => color, blocks => True,
attacker => attacker_comp,
destructible => destructible_comp,
ai => ai_comp);
end make_monster;
function get_name(self : Actor) return String is (Actor_Names.To_String(self.name));
procedure render(self : Actor; screen : in out Console.Screen) is
begin
screen.put_char(Console.X_Pos(self.x), Console.Y_Pos(self.y), self.ch);
screen.set_char_fg(Console.X_Pos(self.x), Console.Y_Pos(self.y), self.color);
end render;
procedure update(self : in out Actor; engine : in out Engines.Engine) is
begin
if self.is_ai then
self.ai.update(self, engine);
end if;
end update;
end Actors;
|
package body Operation is
function Add (Left: NaturalDouble;
Right: NaturalDouble) return NaturalDouble is
begin
return Left + Right;
end Add;
function Multiple (Left: NaturalDouble;
Right: NaturalDouble) return NaturalDouble is
begin
return Left * Right;
end Multiple;
end Operation;
|
with Ada.Containers.Doubly_Linked_Lists;
with Interfaces;
with kv.Ref_Counting_Mixin;
with kv.avm.Control;
with kv.avm.Messages;
with kv.avm.Executables;
with kv.avm.Actor_References;
with kv.avm.Tuples;
with kv.avm.Actor_References.Sets;
with kv.avm.Affiliates;
package kv.avm.Routers is
type Router_Type is tagged private;
procedure Initialize
(Self : in out Router_Type;
Machine : in kv.avm.Control.Control_Access);
function Get_Queue_Size(Self : Router_Type) return Natural;
procedure Set_Queue_Limit(Self : in out Router_Type; Queue_Limit : in Natural);
procedure Post_Message
(Self : in out Router_Type;
Message : in kv.avm.Messages.Message_Type;
Status : out kv.avm.Control.Status_Type);
procedure Post_Response
(Self : in out Router_Type;
Reply_To : in kv.avm.Actor_References.Actor_Reference_Type;
Answer : in kv.avm.Tuples.Tuple_Type;
Future : in Interfaces.Unsigned_32);
procedure Deliver_Messages
(Self : in out Router_Type);
function Reachable_From_Messages(Self : Router_Type) return kv.avm.Actor_References.Sets.Set;
function Get_Affiliator(Self : Router_Type) return kv.avm.Affiliates.Affiliates_Type;
private
type Message_Control_Type is
record
Message : kv.avm.Messages.Message_Type;
Instance : kv.avm.Executables.Executable_Access;
end record;
package Message_Queue is new Ada.Containers.Doubly_Linked_Lists(Message_Control_Type);
type Router_Data_Type is
record
Machine : kv.avm.Control.Control_Access;
Queue : Message_Queue.List;
Queue_Limit : Natural := 200;
Affiliator : kv.avm.Affiliates.Affiliates_Type;
end record;
type Router_Data_Access is access Router_Data_Type;
package Ref_Count is new kv.Ref_Counting_Mixin(Router_Data_Type, Router_Data_Access);
type Router_Type is tagged
record
Ref : Ref_Count.Ref_Type;
end record;
end kv.avm.Routers;
|
--------------------------------------------------------------------------------
-- --
-- B B --
-- Ball on Beam Simulator --
-- --
-- Body --
-- --
-- This is the root package of a library implementing a ball on beam system --
-- simulator. It gives general definitions concerning this system, namely --
-- the types for representing the system variables (ball position and --
-- beam angle); and it implements general operations on the system, such --
-- as moving the system to a given solar system object or setting the --
-- simulator operating mode. --
-- --
-- The interfaces to obtain the ball position and set the beam angle from a --
-- client program are implemented by child packages of BB, which need to --
-- with'ed, together with package BB. These packages present different --
-- abstractions for the purpose, such as an ADC device to obtain the ball --
-- position. The same goes for the gnoga-based graphical user interface, --
-- which is implemented in child package BB.GUI and childs of it. --
-- --
-- Author: Jorge Real --
-- Universitat Politecnica de Valencia --
-- July, 2020 - Version 1 --
-- February, 2021 - Version 2 --
-- --
-- This is free software in the ample sense: you can use it freely, --
-- provided you preserve this comment at the header of source files and --
-- you clearly indicate the changes made to the original file, if any. --
-- --
--------------------------------------------------------------------------------
with System;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Real_Time.Timing_Events; use Ada.Real_Time.Timing_Events;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
package body BB is
-- Location related entities
Current_Location : Solar_System_Object := Earth
with Atomic;
type Gravities is array (Solar_System_Object) of Float;
Gravity_Of : constant Gravities :=
(Mercury => 3.7, Venus => 8.87, Earth => 9.80665,
Mars => 3.711, Jupiter => 24.79, Saturn => 10.4,
Uranus => 8.69, Neptune => 11.15, Pluto => 0.62,
Moon => 1.6249, Ceres => 0.27, Eris => 0.82,
Vesta => 0.22);
g : Float := Gravity_Of (Current_Location)
with Atomic;
procedure Move_BB_To (Where : in Solar_System_Object) is
begin
Current_Location := Where;
g := Gravity_Of (Current_Location);
end Move_BB_To;
function Current_Planet return Solar_System_Object is (Current_Location);
-- The BB.GUI obtains the current SSO name using this function
pi : constant := Ada.Numerics.Pi;
-- The default simulation mode is passive
Auto_Mode_On : Boolean := False;
-- Duration of a simulation step in auto mode
Auto_Period : Duration := 0.1;
pragma Atomic (Auto_Period);
-------------------
-- Sim (spec) --
-------------------
-- Protected object to simulate the ball & beam system.
-- The simulator can be used from concurrent tasks, but task dispatching
-- policy and locking policy are not enforced from this simulator.
-- There are only two significant events: calling Set_Angle and calling
-- Get_Pos. Either call recalculates the current position based on the
-- position, speed and acceleration of the ball at the previous event,
-- and the time elapsed since then. In addition, Set_Angle sets the Angle
-- to the given value, which determines the ball acceleration until the
-- next call to Set_Angle.
protected Sim
with Priority => System.Priority'Last
is
procedure Set_Angle (To : Angle);
procedure Get_Pos (Where : out Position);
-- These two procedures imply a state update in the simulator, i.e. the
-- calculation of a simulation step.
function Last_Pos return Position;
function Last_Angle return Angle;
-- These two functions simply return the most recently simulated position
-- and angle, without forcing the recalculation of a simulation step.
-- They are intended for GUI updates, for which a relatively recent value
-- is good enough. They do not update the simulation state, so they are
-- faster and less interferring. GUI updates are performed from a task
-- in child package BB.GUI.Controller.
procedure Set_Refresh_Mode (Mode : Simulation_Mode);
-- Set the auto-refresh mode, passive for Closed_Loop or 100 ms periodic
-- for Open_Loop mode. Auto-refresh is operated by a recurring TE
private
procedure Update_State (Last_Interval : in Time_Span);
Pos : Position := 0.0; -- Simulated ball position, in mm
Vel : Float := 0.0; -- Ball velocity, in mm/s
Acc : Float := 0.0; -- Ball acceleration, in mm/s^2
Ang : Angle := 0.0; -- Beam angle, in degrees
Last_Event : Time := Clock; -- Start time of simulation interval
Refresh_TE : Timing_Event;
Time_To_Refresh : Time;
procedure Auto_Refresh (TE : in out Timing_Event);
-- TE and support for Auto-refresh (Open_Loop) mode
end Sim;
------------------
-- Sim (body) --
------------------
Refresh_Period : constant Time_Span := Milliseconds (100);
-- Auto-refresh period in Open_Loop mode
protected body Sim is
procedure Update_State (Last_Interval : in Time_Span) is
-- Duration of last simulation interval, in seconds, as a Float
T : constant Float := Float (To_Duration (Last_Interval));
-- An estimated position could fall out of range, so we use this
-- Float for the calculated position, and then trim it to fall
-- within the bounds of type Position, imposed by the beam size.
Unbounded_Pos : Float;
begin
-- Update simulator state. Called whenever there is a simulator event.
-- The current ball position depends on the beam angle during the last
-- interval (which determines the acceleration), and the ball
-- velocity and position at the start of the simulation interval.
-- Since changing the beam angle causes a simulator event, the beam
-- angle remains constant during a simulator step.
-- Ball acceleration as a function of beam angle.
-- Since angle grows CCW and position decreases leftwards, a positive
-- angle causes a negative acceleration -- hence "-Ang" here.
Acc := (5.0 * g * Sin ((Float (-Ang) * pi) / 180.0)) / 7.0; -- m/s**2
-- Ball velocity acquired during last interval.
Vel := Vel + Acc * T; -- m/s
-- Calculated a ball position that is not constrained to the range
-- of type Position. If it was constrained, there would be a
-- Constraint_Error if T was large enough to let the ball continue
-- falling beyond either end of the beam.
-- The constant 1_000.0 scales meters to mm, since ball position is
-- given in mm.
Unbounded_Pos := Pos + (1_000.0 * Vel * T) +
((1_000.0 * Acc * T**2) / 2.0);
-- Adjust to position limits. Assume ball stoppers at both beam ends.
-- Assume also no bouncing when the ball hits a stopper.
if Unbounded_Pos > Position'Last then -- Ball hits right end
Unbounded_Pos := Position'Last;
Vel := 0.0; -- Rectify velocity: the ball hit the right stopper
elsif Unbounded_Pos < Position'First then -- Ball hits left end
Unbounded_Pos := Position'First;
Vel := 0.0; -- Rectify velocity: the ball hit the left stopper
end if;
Pos := Position (Unbounded_Pos); -- Safe conversion after adjustment
end Update_State;
procedure Set_Angle (To : Angle) is
Now : constant Time := Clock;
begin
Update_State (Now - Last_Event);
Last_Event := Now;
-- Set the beam inclination to the given angle
Ang := To;
end Set_Angle;
procedure Get_Pos (Where : out Position) is
Now : constant Time := Clock;
begin
Update_State (Now - Last_Event);
Last_Event := Now;
-- Return updated position
Where := Pos;
end Get_Pos;
function Last_Pos return Position is (Pos);
function Last_Angle return Angle is (Ang);
procedure Set_Refresh_Mode (Mode : Simulation_Mode) is
Cancelled : Boolean;
begin
case Mode is
when Open_Loop =>
Time_To_Refresh := Clock;
Set_Handler (Event => Refresh_TE,
At_Time => Time_To_Refresh,
Handler => Auto_Refresh'Access);
when Closed_Loop =>
Cancel_Handler (Refresh_TE, Cancelled);
end case;
end Set_Refresh_Mode;
procedure Auto_Refresh (TE : in out Timing_Event) is
begin
-- Update simulator state to make it simulate one more step so that
-- the GUI can show progress in open-loop uses
Update_State (Time_To_Refresh - Last_Event);
Last_Event := Time_To_Refresh;
Time_To_Refresh := Time_To_Refresh + Refresh_Period;
Set_Handler (Event => Refresh_TE,
At_Time => Time_To_Refresh,
Handler => Auto_Refresh'Access);
end Auto_Refresh;
end Sim;
--------------------
-- Set_Beam_Angle --
--------------------
procedure Set_Beam_Angle (Inclination : Angle) is
begin
Sim.Set_Angle (Inclination);
end Set_Beam_Angle;
-------------------
-- Ball_Position --
-------------------
function Ball_Position return Position is
Result : Position;
begin
Sim.Get_Pos (Result);
return Result;
end Ball_Position;
-------------------------
-- Set_Simulation_Mode --
-------------------------
procedure Set_Simulation_Mode (Mode : Simulation_Mode) is
begin
Sim.Set_Refresh_Mode (Mode);
end Set_Simulation_Mode;
-- Private subprograms
--------------
-- Last_Pos --
--------------
function Last_Pos return Position is (Sim.Last_Pos);
----------------
-- Last_Angle --
----------------
function Last_Angle return Angle is (Sim.Last_Angle);
end BB;
|
with Text_IO;
use Text_IO;
with Ada.Real_Time;
with Ada.Characters.Latin_1;
use Ada.Real_Time;
procedure Main is
update_display: Boolean := true;
task type display is
entry StartStop;
entry Lap;
end display;
task body display is
isStarted: Boolean := false;
isPaused: Boolean := false;
startTime: Time := Clock;
begin
loop
-- Ada RM 9.7.1: select contains at least one accept.
-- Optional: *either* one of 'terminate' or 'delay' or 'else'
select
accept StartStop do
if not isStarted then
startTime := Clock;
isStarted := true;
isPaused := false;
else
isStarted := false;
end if;
end StartStop;
or
when isStarted =>
accept Lap do
isPaused := not isPaused;
end Lap;
or
delay 0.1; -- unblock after 100ms
end select;
-- update display
if isStarted and then not isPaused then
Put_Line(Duration'Image(To_Duration(Clock-startTime)));
end if;
end loop;
end display;
char: Character;
disp1: display;
begin
Put_Line("Press q to quit, Space to Lap or any other key to start the stopwatch!");
loop
Get_Immediate(char);
if char = Ada.Characters.Latin_1.Space then
disp1.Lap;
elsif char = 'q' then
abort disp1; -- directly exit the display task.
exit;
else
disp1.StartStop;
end if;
end loop;
end Main;
|
-- Institution: Technische Universitaet Muenchen
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
-- Author: Martin Becker (becker@rcs.ei.tum.de)
with ULog;
with Interfaces;
-- @summary
-- implements ULOG GPS message
package ULog.GPS with SPARK_Mode is
type fixtype is (NOFIX, DEADR, FIX2D, FIX3D, FIX3DDEADR, FIXTIME);
-- extends base record, specific for GPS. Implicitely tagged (RM 3.9-2).
type Message is new ULog.Message with record
gps_week : Interfaces.Integer_16 := 0;
gps_msec : Interfaces.Unsigned_64 := 0;
fix : fixtype := NOFIX;
nsat : Interfaces.Unsigned_8 := 0;
lat : Interfaces.IEEE_Float_32 := 0.0;
lon : Interfaces.IEEE_Float_32 := 0.0;
alt : Interfaces.IEEE_Float_32 := 0.0;
end record;
function Copy (msg : in Message) return Message;
-- what happens if we have two class-wide types in the signature?
procedure Describe_Func (msg : in Message; namestring : out String);
private
overriding
function Self (msg : in Message) return ULog.Message'Class;
overriding
procedure Get_Serialization (msg : in Message; bytes : out HIL.Byte_Array);
overriding
function Get_Size (msg : in Message) return Interfaces.Unsigned_16;
overriding
procedure Get_Format (msg : in Message; bytes : out HIL.Byte_Array);
end ULog.GPS;
|
pragma License (Unrestricted);
with Ada.Text_IO;
package Ada.Short_Float_Text_IO is new Text_IO.Float_IO (Short_Float);
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Testsuite Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Fixed;
with Ada.Strings.Wide_Fixed;
with Ada.Strings.Wide_Wide_Fixed;
with Ada.Strings.Wide_Unbounded;
with Ada.Text_IO;
with League.Application;
with League.Characters;
with League.Strings;
procedure String_Performance is
use Ada.Calendar;
use Ada.Strings;
use Ada.Strings.Fixed;
use Ada.Strings.Wide_Fixed;
use Ada.Strings.Wide_Unbounded;
use Ada.Strings.Wide_Wide_Fixed;
use Ada.Text_IO;
use League.Characters;
use League.Strings;
procedure Test_Copy_Of_Empty_String;
procedure Test_Copy;
procedure Test_Compare;
procedure Test_Append;
procedure Test_Index;
procedure Test_Last_Index;
procedure Test_Initialization;
type Result_Type is record
Ada_Duration : Duration;
League_Duration : Duration;
Passes : Positive;
end record;
type Result_Type_Array is array (Positive range <>) of Result_Type;
procedure Results
(Name : String;
Result : Result_Type);
procedure Results
(Name : String;
Result : Result_Type_Array);
-------------
-- Results --
-------------
procedure Results
(Name : String;
Result : Result_Type)
is
type Speedup is delta 0.01 range 0.0 .. 100.0;
P : Speedup := Speedup (Result.Ada_Duration / Result.League_Duration);
begin
Put_Line (Name & " (" & Trim (Speedup'Image (P), Both) & ")");
Put_Line
(" AUS : "
& Duration'Image (Result.Ada_Duration)
& Duration'Image (Result.Ada_Duration / Result.Passes));
Put_Line
(" LUS : "
& Duration'Image (Result.League_Duration)
& Duration'Image (Result.League_Duration / Result.Passes));
end Results;
-------------
-- Results --
-------------
procedure Results
(Name : String;
Result : Result_Type_Array)
is
type Speedup is delta 0.01 range 0.0 .. 1000.0;
begin
Put (Name & " (");
for J in Result'Range loop
if J /= Result'First then
Put ('/');
end if;
Put
(Trim
(Speedup'Image
(Speedup (Result (J).Ada_Duration / Result (J).League_Duration)),
Both));
end loop;
Put_Line (")");
Put (" AUS :");
for J in Result'Range loop
if J /= Result'First then
Put (" /");
end if;
Put
(Duration'Image (Result (J).Ada_Duration)
& Duration'Image (Result (J).Ada_Duration / Result (J).Passes));
end loop;
New_Line;
Put (" LUS :");
for J in Result'Range loop
if J /= Result'First then
Put (" /");
end if;
Put
(Duration'Image (Result (J).League_Duration)
& Duration'Image
(Result (J).League_Duration / Result (J).Passes));
end loop;
New_Line;
end Results;
-----------------
-- Test_Append --
-----------------
procedure Test_Append is
Passes : constant := 5_000_000;
Ada_Duration : Duration;
League_Duration : Duration;
begin
declare
Start : Time;
S1 : Unbounded_Wide_String;
S2 : Unbounded_Wide_String :=
To_Unbounded_Wide_String ("123");
begin
Start := Clock;
for J in 1 .. Passes loop
Append (S1, S2);
end loop;
Ada_Duration := Clock - Start;
end;
declare
Start : Time;
S1 : Universal_String;
S2 : Universal_String :=
To_Universal_String ("123");
begin
Start := Clock;
for J in 1 .. Passes loop
Append (S1, S2);
end loop;
League_Duration := Clock - Start;
end;
Results
("Append string", Result_Type'(Ada_Duration, League_Duration, Passes));
end Test_Append;
------------------
-- Test_Compare --
------------------
procedure Test_Compare is
generic
with function Compare
(Left : Unbounded_Wide_String;
Right : Unbounded_Wide_String) return Boolean;
with function Compare
(Left : Universal_String; Right : Universal_String) return Boolean;
procedure Generic_Test
(Size : Positive;
Passes : Positive;
Result : out Result_Type);
------------------
-- Generic_Test --
------------------
procedure Generic_Test
(Size : Positive;
Passes : Positive;
Result : out Result_Type)
is
Start : Time;
Y : Boolean;
begin
declare
S1 : Unbounded_Wide_String :=
To_Unbounded_Wide_String (Size * ' ' & '1');
S2 : Unbounded_Wide_String :=
To_Unbounded_Wide_String (Size * ' ' & '2');
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Compare (S1, S2);
end loop;
Result.Ada_Duration := Clock - Start;
end;
declare
S1 : Universal_String :=
To_Universal_String (Size * ' ' & '1');
S2 : Universal_String :=
To_Universal_String (Size * ' ' & '2');
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Compare (S1, S2);
end loop;
Result.League_Duration := Clock - Start;
end;
Result.Passes := Passes;
end Generic_Test;
procedure Equal_Test is new Generic_Test ("=", "=");
procedure Less_Test is new Generic_Test ("<", "<");
Equal_Passes : constant := 10_000_000;
Less_Passes : constant := 12_000_000;
Size : constant := 100;
Result : Result_Type_Array (1 .. 5);
begin
Equal_Test (1, Equal_Passes, Result (1));
Equal_Test (10, Equal_Passes, Result (2));
Equal_Test (100, Equal_Passes / 2, Result (3));
Equal_Test (1000, Equal_Passes / 10, Result (4));
Equal_Test (10000, Equal_Passes / 50, Result (5));
Results ("Compare for equality", Result);
Less_Test (1, Less_Passes, Result (1));
Less_Test (10, Less_Passes, Result (2));
Less_Test (100, Less_Passes / 2, Result (3));
Less_Test (1000, Less_Passes / 10, Result (4));
Less_Test (10000, Less_Passes / 50, Result (5));
Results ("Compare for less", Result);
end Test_Compare;
-----------------
-- Test_Copy_2 --
-----------------
procedure Test_Copy_2 is
Passes : constant := 4_000_000;
Ada_Duration : Duration;
League_Duration : Duration;
begin
declare
Start : Time;
begin
Start := Clock;
for J in 1 .. Passes loop
declare
S1 : Unbounded_Wide_String :=
To_Unbounded_Wide_String (" ");
S2 : Unbounded_Wide_String;
begin
S2 := S1;
end;
end loop;
Ada_Duration := Clock - Start;
end;
declare
Start : Time;
begin
Start := Clock;
for J in 1 .. Passes loop
declare
S1 : Universal_String :=
To_Universal_String (" ");
S2 : Universal_String;
begin
S2 := S1;
end;
end loop;
League_Duration := Clock - Start;
end;
Results
("Create/copy of non-empty string",
Result_Type'(Ada_Duration, League_Duration, Passes));
end Test_Copy_2;
---------------
-- Test_Copy --
---------------
procedure Test_Copy is
Passes : constant := 20_000_000;
Ada_Duration : Duration;
League_Duration : Duration;
begin
declare
Start : Time;
S1 : Unbounded_Wide_String :=
To_Unbounded_Wide_String (" ");
S2 : Unbounded_Wide_String;
begin
Start := Clock;
for J in 1 .. Passes loop
S2 := S1;
end loop;
Ada_Duration := Clock - Start;
end;
declare
Start : Time;
S1 : Universal_String :=
To_Universal_String (" ");
S2 : Universal_String;
begin
Start := Clock;
for J in 1 .. Passes loop
S2 := S1;
end loop;
League_Duration := Clock - Start;
end;
Results
("Copy of non-empty string",
Result_Type'(Ada_Duration, League_Duration, Passes));
end Test_Copy;
-------------------------------
-- Test_Copy_Of_Empty_String --
-------------------------------
procedure Test_Copy_Of_Empty_String is
Passes : constant := 20_000_000;
Ada_Duration : Duration;
League_Duration : Duration;
begin
declare
Start : Time;
S1 : Unbounded_Wide_String;
S2 : Unbounded_Wide_String;
begin
Start := Clock;
for J in 1 .. Passes loop
S2 := S1;
end loop;
Ada_Duration := Clock - Start;
end;
declare
Start : Time;
S1 : Universal_String;
S2 : Universal_String;
begin
Start := Clock;
for J in 1 .. Passes loop
S2 := S1;
end loop;
League_Duration := Clock - Start;
end;
Results
("Copy of empty string",
Result_Type'(Ada_Duration, League_Duration, Passes));
end Test_Copy_Of_Empty_String;
----------------
-- Test_Index --
----------------
procedure Test_Index is
----------
-- Test --
----------
procedure Test
(Size : Positive;
Passes : Positive;
Result : out Result_Type)
is
Start : Time;
Y : Natural;
begin
declare
S : Unbounded_Wide_String :=
To_Unbounded_Wide_String (Size * ' ' & '1');
C : Wide_String := "1";
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Index (S, C);
end loop;
Result.Ada_Duration := Clock - Start;
end;
declare
S : Universal_String :=
To_Universal_String (Size * ' ' & '1');
C : Universal_Character := To_Universal_Character ('1');
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Index (S, C);
end loop;
Result.League_Duration := Clock - Start;
end;
Result.Passes := Passes;
end Test;
Index_Passes : constant := 1_000_000;
Result : Result_Type_Array (1 .. 5);
begin
Test (1, Index_Passes, Result (1));
Test (10, Index_Passes, Result (2));
Test (100, Index_Passes / 2, Result (3));
Test (1000, Index_Passes / 10, Result (4));
Test (10000, Index_Passes / 50, Result (5));
Results ("Index", Result);
end Test_Index;
-------------------------
-- Test_Initialization --
-------------------------
procedure Test_Initialization is
Passes : constant := 10_000_000;
Ada_Duration : Duration;
League_Duration : Duration;
begin
declare
Start : Time;
begin
Start := Clock;
for J in 1 .. Passes loop
declare
S1 : Unbounded_Wide_String;
S2 : Unbounded_Wide_String;
X : Boolean := S1 = S2;
begin
null;
end;
end loop;
Ada_Duration := Clock - Start;
end;
declare
Start : Time;
begin
Start := Clock;
for J in 1 .. Passes loop
declare
S1 : Universal_String;
S2 : Universal_String;
X : Boolean := S1 = S2;
begin
null;
end;
end loop;
League_Duration := Clock - Start;
end;
Results
("Initialization of default object",
Result_Type'(Ada_Duration, League_Duration, Passes));
end Test_Initialization;
---------------------
-- Test_Last_Index --
---------------------
procedure Test_Last_Index is
----------
-- Test --
----------
procedure Test
(Size : Positive;
Passes : Positive;
Result : out Result_Type)
is
Start : Time;
Y : Natural;
begin
declare
S : Unbounded_Wide_String :=
To_Unbounded_Wide_String ('1' & Size * ' ');
C : Wide_String := "1";
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Index (S, C, Ada.Strings.Backward);
end loop;
Result.Ada_Duration := Clock - Start;
end;
declare
S : Universal_String :=
To_Universal_String ('1' & Size * ' ');
C : Universal_Character := To_Universal_Character ('1');
begin
Start := Clock;
for J in 1 .. Passes loop
Y := Last_Index (S, C);
end loop;
Result.League_Duration := Clock - Start;
end;
Result.Passes := Passes;
end Test;
Index_Passes : constant := 1_000_000;
Result : Result_Type_Array (1 .. 5);
begin
Test (1, Index_Passes, Result (1));
Test (10, Index_Passes, Result (2));
Test (100, Index_Passes / 2, Result (3));
Test (1000, Index_Passes / 10, Result (4));
Test (10000, Index_Passes / 50, Result (5));
Results ("Last_Index", Result);
end Test_Last_Index;
begin
Test_Initialization;
Test_Copy_Of_Empty_String;
Test_Copy;
Test_Copy_2;
Test_Compare;
Test_Append;
Test_Index;
Test_Last_Index;
end String_Performance;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
package Program.Elements.Defining_Names is
pragma Pure (Program.Elements.Defining_Names);
type Defining_Name is limited interface and Program.Elements.Element;
type Defining_Name_Access is access all Defining_Name'Class
with Storage_Size => 0;
not overriding function Image (Self : Defining_Name) return Text
is abstract;
end Program.Elements.Defining_Names;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.