content stringlengths 23 1.05M |
|---|
-- Institution: Technische Universitaet Muenchen
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
--
-- Authors: Martin Becker (becker@rcs.ei.tum.de>
with HIL.Devices.Timers;
with Units; use Units;
with HAL; use HAL;
-- @summary
-- Target-independent specification for simple HIL of Hardware Timers
package HIL.Timers with SPARK_Mode => Off is
-- TODO: this package is unfinished business. It simply allows to set up
-- a very basic timer configuration w/o interrupts. This makes sense,
-- the alternative function of the respective timer is activated as pinout.
-- In that case, the timer's overflow etc. can be given to a device,
-- e.g., as square signal to a buzzer, or LED (dimming).
subtype HIL_Timer is HIL.Devices.Timers.HIL_Timer; -- expose type
subtype HIL_Timer_Channel is HIL.Devices.Timers.HIL_Timer_Channel;
procedure Initialize (t : in out HIL_Timer);
procedure Enable (t : in out HIL_Timer; ch : HIL.Timers.HIL_Timer_Channel);
procedure Disable (t : in out HIL_Timer; ch : HIL.Timers.HIL_Timer_Channel);
procedure Configure_OC_Toggle
(This : in out HIL_Timer;
Frequency : Frequency_Type;
Channel : HIL_Timer_Channel)
with Pre => Frequency in 1.0 .. 1_000_000.0;
-- configure output compare toggle on given timer and channel.
-- the channel is toggled every time the timer reaches zero.
-- i.e., the channel shows a 50% square waveform with given
-- frequency.
-- procedure Set_Autoreload (This : in out HIL_Timer; Value : Word);
-- procedure Set_Counter (This : in out HIL_Timer; Value : Word);
end HIL.Timers;
|
with Ada.Text_Io; use Ada.Text_Io;
with Iban_Code;
procedure Check_Iban is
procedure Check(Iban : String) is
begin
if Iban_Code.Is_Legal(Iban) then
Put_Line(Iban & " is valid.");
else
Put_Line(Iban & " is not valid.");
end if;
end Check;
begin
Check("GB82 WEST 1234 5698 7654 32");
Check("GB82WEST12345698765432");
Check("gb82 west 1234 5698 7654 32");
Check("GB82 TEST 1234 5698 7654 32");
Check("GB82 WEST 1243 5698 7654 32");
end Check_Iban;
|
with
box2d_c.Binding,
box2d_physics.Object,
c_math_c.Vector_3,
c_math_c.Matrix_4x4,
c_math_c.Conversion,
Swig,
interfaces.C,
ada.unchecked_Deallocation,
ada.unchecked_Conversion;
package body box2d_Physics.Joint
is
use c_math_c.Conversion,
box2d_c.Binding,
Interfaces;
type Any_limited_view is access all lace.Any.limited_item'Class;
function to_Any_view is new ada.unchecked_Conversion (Swig.void_ptr, Any_limited_view);
function to_Object_view is new ada.unchecked_Conversion (swig.void_ptr, physics.Object.view);
pragma Unreferenced (to_Object_view);
-- procedure set_b2d_user_Data (Self : in View)
-- is
-- function to_void_ptr is new ada.Unchecked_Conversion (Any_limited_view, Swig.void_ptr);
-- Self_as_any : constant Any_limited_view := Any_limited_view (Self);
-- begin
-- b2d_Joint_user_Data_is (Self.C, to_void_ptr (Self_as_any));
-- end set_b2d_user_Data;
overriding
function reaction_Force (Self : in Item) return Vector_3
is
begin
return +b2d_Joint_reaction_Force (Self.C);
end reaction_Force;
overriding
function reaction_Torque (Self : in Item) return Real
is
begin
return +b2d_Joint_reaction_Torque (Self.C);
end reaction_Torque;
overriding
procedure user_Data_is (Self : in out Item; Now : access lace.Any.limited_item'Class)
is
begin
Self.user_Data := Now;
end user_Data_is;
overriding
function user_Data (Self : in Item) return access lace.Any.limited_item'Class
is
begin
return Self.user_Data;
end user_Data;
--------
-- DoF6
--
function new_Dof6_Joint (Object_A, Object_B : in physics.Object.view;
Frame_A, Frame_B : in Matrix_4x4) return physics.Joint.DoF6.view
is
Self : constant access DoF6 := new DoF6;
pragma Unreferenced (Self);
c_Object_A : box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_A).C;
c_Object_B : box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_B).C;
c_Frame_A : aliased c_math_c.Matrix_4x4.item := +Frame_A;
c_Frame_B : aliased c_math_c.Matrix_4x4.item := +Frame_B;
begin
return null;
end new_Dof6_Joint;
overriding
procedure destruct (Self : in out DoF6)
is
begin
raise Program_Error with "TBD";
end destruct;
overriding
function Object_A (Self : in DoF6) return physics.Object.view
is
c_Object_A : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_A (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_A)));
end Object_A;
overriding
function Object_B (Self : in DoF6) return physics.Object.view
is
c_Object_B : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_B (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_B)));
end Object_B;
overriding
function Frame_A (Self : in DoF6) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_A (Self.C);
end Frame_A;
overriding
function Frame_B (Self : in DoF6) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_B (Self.C);
end Frame_B;
overriding
procedure Frame_A_is (Self : in out DoF6; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_A_is (Self.C, c_Now'unchecked_Access);
end Frame_A_is;
overriding
procedure Frame_B_is (Self : in out DoF6; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_B_is (Self.C, c_Now'unchecked_Access);
end Frame_B_is;
overriding
function is_Limited (Self : in DoF6; DoF : Degree_of_freedom) return Boolean
is
use type Swig.bool;
begin
return b2d_Joint_is_Limited (Self.C, Degree_of_freedom'Pos (DoF)) /= 0;
end is_Limited;
overriding
procedure Velocity_is (Self : in out DoF6; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
b2d_Joint_Velocity_is (Self.C, C.int (Now),
c_math_c.Real (DoF));
end Velocity_is;
overriding
function Extent (Self : in DoF6; DoF : Degree_of_freedom) return Real
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
return Real (b2d_Joint_Extent (Self.C, C.int (DoF)));
end Extent;
overriding
procedure desired_Extent_is (Self : in out DoF6; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end desired_Extent_is;
overriding
function lower_Limit (Self : in DoF6; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end lower_Limit;
overriding
function upper_Limit (Self : in DoF6; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end upper_Limit;
overriding
procedure lower_Limit_is (Self : in out DoF6; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end lower_Limit_is;
overriding
procedure upper_Limit_is (Self : in out DoF6; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end upper_Limit_is;
--------
-- Ball
--
function new_Ball_Joint (Object_A, Object_B : in physics.Object.view;
Pivot_in_A, Pivot_in_B : in Vector_3) return physics.Joint.ball.view
is
Self : constant access Ball := new Ball;
c_Object_A : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_A).C;
c_Object_B : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_B).C;
c_Pivot_in_A : aliased c_math_c.Vector_3.item := +Pivot_in_A;
c_Pivot_in_B : aliased c_math_c.Vector_3.item := +Pivot_in_B;
begin
Self.C := b2d_new_ball_Joint (c_Object_A,
c_Object_B,
c_Pivot_in_A'unchecked_Access,
c_Pivot_in_B'unchecked_Access);
return Self;
end new_Ball_Joint;
overriding
procedure destruct (Self : in out Ball)
is
begin
raise Error with "TODO";
end destruct;
overriding
function Object_A (Self : in Ball) return physics.Object.view
is
c_Object_A : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_A (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_A)));
end Object_A;
overriding
function Object_B (Self : in Ball) return physics.Object.view
is
c_Object_B : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_B (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_B)));
end Object_B;
overriding
function Frame_A (Self : in Ball) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_A (Self.C);
end Frame_A;
overriding
function Frame_B (Self : in Ball) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_B (Self.C);
end Frame_B;
overriding
procedure Frame_A_is (Self : in out Ball; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_A_is (Self.C, c_Now'unchecked_Access);
end Frame_A_is;
overriding
procedure Frame_B_is (Self : in out Ball; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_B_is (Self.C, c_Now'unchecked_Access);
end Frame_B_is;
overriding
function is_Limited (Self : in Ball; DoF : Degree_of_freedom) return Boolean
is
use type Swig.bool;
begin
return b2d_Joint_is_Limited (Self.C, Degree_of_freedom'Pos (DoF)) /= 0;
end is_Limited;
overriding
procedure Velocity_is (Self : in out Ball; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
b2d_Joint_Velocity_is (Self.C, C.int (Now),
c_math_c.Real (DoF));
end Velocity_is;
overriding
function Extent (Self : in Ball; DoF : Degree_of_freedom) return Real
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
return Real (b2d_Joint_Extent (Self.C, C.int (DoF)));
end Extent;
overriding
procedure desired_Extent_is (Self : in out Ball; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end desired_Extent_is;
overriding
function lower_Limit (Self : in Ball; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end lower_Limit;
overriding
function upper_Limit (Self : in Ball; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end upper_Limit;
overriding
procedure lower_Limit_is (Self : in out Ball; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end lower_Limit_is;
overriding
procedure upper_Limit_is (Self : in out Ball; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end upper_Limit_is;
----------
-- Slider
--
function new_Slider_Joint (Object_A, Object_B : in physics.Object.view;
Frame_A, Frame_B : in Matrix_4x4) return physics.Joint.slider.view
is
Self : constant access Slider := new Slider;
c_Object_A : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_A).C;
c_Object_B : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_B).C;
c_Frame_A : aliased c_math_c.Matrix_4x4.item := +Frame_A;
c_Frame_B : aliased c_math_c.Matrix_4x4.item := +Frame_B;
begin
Self.C := b2d_new_slider_Joint (c_Object_A,
c_Object_B,
c_Frame_A'unchecked_Access,
c_Frame_B'unchecked_Access);
return Self;
end new_Slider_Joint;
overriding
procedure destruct (Self : in out Slider)
is
begin
raise Error with "TODO";
end destruct;
overriding
function Object_A (Self : in Slider) return physics.Object.view
is
c_Object_A : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_A (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_A)));
end Object_A;
overriding
function Object_B (Self : in Slider) return physics.Object.view
is
c_Object_B : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_B (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_B)));
end Object_B;
overriding
function Frame_A (Self : in Slider) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_A (Self.C);
end Frame_A;
overriding
function Frame_B (Self : in Slider) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_B (Self.C);
end Frame_B;
overriding
procedure Frame_A_is (Self : in out Slider; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_A_is (Self.C, c_Now'unchecked_Access);
end Frame_A_is;
overriding
procedure Frame_B_is (Self : in out Slider; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_B_is (Self.C, c_Now'unchecked_Access);
end Frame_B_is;
overriding
function is_Limited (Self : in Slider; DoF : Degree_of_freedom) return Boolean
is
use type Swig.bool;
begin
return b2d_Joint_is_Limited (Self.C, Degree_of_freedom'Pos (DoF)) /= 0;
end is_Limited;
overriding
procedure Velocity_is (Self : in out Slider; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
b2d_Joint_Velocity_is (Self.C, C.int (Now),
c_math_c.Real (DoF));
end Velocity_is;
overriding
function Extent (Self : in Slider; DoF : Degree_of_freedom) return Real
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
return Real (b2d_Joint_Extent (Self.C, C.int (DoF)));
end Extent;
overriding
procedure desired_Extent_is (Self : in out Slider; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end desired_Extent_is;
overriding
function lower_Limit (Self : in Slider; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end lower_Limit;
overriding
function upper_Limit (Self : in Slider; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end upper_Limit;
overriding
procedure lower_Limit_is (Self : in out Slider; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end lower_Limit_is;
overriding
procedure upper_Limit_is (Self : in out Slider; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end upper_Limit_is;
--------------
-- cone_Twist
--
function new_cone_Twist_Joint (Object_A, Object_B : in physics.Object.view;
Frame_A, Frame_B : in Matrix_4x4) return physics.Joint.cone_twist.view
is
Self : constant access cone_Twist := new cone_Twist;
c_Object_A : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_A).C;
c_Object_B : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_B).C;
c_Frame_A : aliased c_math_c.Matrix_4x4.item := +Frame_A;
c_Frame_B : aliased c_math_c.Matrix_4x4.item := +Frame_B;
begin
Self.C := b2d_new_DoF6_Joint (c_Object_A,
c_Object_B,
c_Frame_A'unchecked_Access,
c_Frame_B'unchecked_Access);
return Self;
end new_cone_Twist_Joint;
overriding
procedure destruct (Self : in out cone_Twist)
is
begin
raise Error with "TODO";
end destruct;
overriding
function Object_A (Self : in cone_Twist) return physics.Object.view
is
c_Object_A : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_A (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_A)));
end Object_A;
overriding
function Object_B (Self : in cone_Twist) return physics.Object.view
is
c_Object_B : constant box2d_c.Pointers.Object_Pointer := b2d_Joint_Object_B (Self.C);
begin
return physics.Object.view (to_Any_view (b2d_Object_user_Data (c_Object_B)));
end Object_B;
overriding
function Frame_A (Self : in cone_Twist) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_A (Self.C);
end Frame_A;
overriding
function Frame_B (Self : in cone_Twist) return Matrix_4x4
is
begin
return +b2d_Joint_Frame_B (Self.C);
end Frame_B;
overriding
procedure Frame_A_is (Self : in out cone_Twist; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_A_is (Self.C, c_Now'unchecked_Access);
end Frame_A_is;
overriding
procedure Frame_B_is (Self : in out cone_Twist; Now : in Matrix_4x4)
is
c_Now : aliased c_math_c.Matrix_4x4.item := +Now;
begin
b2d_Joint_Frame_B_is (Self.C, c_Now'unchecked_Access);
end Frame_B_is;
overriding
function is_Limited (Self : in cone_Twist; DoF : Degree_of_freedom) return Boolean
is
use type Swig.bool;
begin
return b2d_Joint_is_Limited (Self.C, Degree_of_freedom'Pos (DoF)) /= 0;
end is_Limited;
overriding
procedure Velocity_is (Self : in out cone_Twist; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
b2d_Joint_Velocity_is (Self.C, C.int (Now),
c_math_c.Real (DoF));
end Velocity_is;
overriding
function Extent (Self : in cone_Twist; DoF : Degree_of_freedom) return Real
is
begin
if DoF < 4 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
return Real (b2d_Joint_Extent (Self.C, C.int (DoF)));
end Extent;
overriding
procedure desired_Extent_is (Self : in out cone_Twist; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end desired_Extent_is;
overriding
function lower_Limit (Self : in cone_Twist; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end lower_Limit;
overriding
function upper_Limit (Self : in cone_Twist; DoF : in Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
return 0.0;
end upper_Limit;
overriding
procedure lower_Limit_is (Self : in out cone_Twist; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end lower_Limit_is;
overriding
procedure upper_Limit_is (Self : in out cone_Twist; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end upper_Limit_is;
---------
-- Hinge
--
function new_hinge_Joint (in_Space : in box2d_c.Pointers.Space_Pointer;
Object_A, Object_B : in physics.Object.view;
Anchor_in_A, Anchor_in_B : in Vector_3;
low_Limit, high_Limit : in math.Real;
collide_Conected : in Boolean) return physics.Joint.hinge.view
is
use type box2d_physics.Object.view,
physics.Object.view;
Self : constant access Hinge := new Hinge;
c_Object_A : box2d_C.Pointers.Object_Pointer;
c_Object_B : box2d_C.Pointers.Object_Pointer;
c_Anchor_in_A : aliased c_math_c.Vector_3.item := +Anchor_in_A;
c_Anchor_in_B : aliased c_math_c.Vector_3.item := +Anchor_in_B;
begin
if Object_A = null
or Object_B = null
then
raise Error with "Null object detected.";
end if;
if box2d_physics.Object.view (Object_A) /= null
then
c_Object_A := box2d_physics.Object.view (Object_A).C;
end if;
if box2d_physics.Object.view (Object_B) /= null
then
c_Object_B := box2d_physics.Object.view (Object_B).C;
end if;
Self.C := b2d_new_hinge_Joint_with_local_anchors (in_Space,
c_Object_A,
c_Object_B,
c_Anchor_in_A'unchecked_Access,
c_Anchor_in_B'unchecked_Access,
c_math_c.Real (low_Limit),
c_math_c.Real (high_Limit),
Boolean'Pos (collide_Conected));
return Self;
end new_hinge_Joint;
function new_hinge_Joint (Object_A : in physics.Object.view;
Frame_A : in Matrix_4x4) return physics.Joint.hinge.view
is
use type box2d_physics.Object.view;
Self : constant access Hinge := new Hinge;
c_Object_A : constant box2d_C.Pointers.Object_Pointer := box2d_physics.Object.view (Object_A).C;
c_Frame_A : aliased c_math_c.Matrix_4x4.item := +Frame_A;
begin
Self.C := b2d_new_space_hinge_Joint (c_Object_A,
c_Frame_A'unchecked_Access);
return Self;
end new_hinge_Joint;
function new_hinge_Joint (in_Space : in box2d_c.Pointers.Space_Pointer;
Object_A, Object_B : in physics.Object.view;
Frame_A, Frame_B : in Matrix_4x4;
low_Limit, high_Limit : in math.Real;
collide_Conected : in Boolean) return physics.Joint.hinge.view
is
use type box2d_physics.Object.view,
physics.Object.view;
Self : constant access Hinge := new Hinge;
c_Object_A : box2d_C.Pointers.Object_Pointer;
c_Object_B : box2d_C.Pointers.Object_Pointer;
c_Frame_A : aliased c_math_c.Matrix_4x4.item := +Frame_A;
c_Frame_B : aliased c_math_c.Matrix_4x4.item := +Frame_B;
begin
if Object_A = null
or Object_B = null
then
raise Error with "Null object detected.";
end if;
if box2d_physics.Object.view (Object_A) /= null
then
c_Object_A := box2d_physics.Object.view (Object_A).C;
end if;
if box2d_physics.Object.view (Object_B) /= null
then
c_Object_B := box2d_physics.Object.view (Object_B).C;
end if;
Self.C := b2d_new_hinge_Joint (in_Space,
c_Object_A,
c_Object_B,
c_Frame_A'unchecked_Access,
c_Frame_B'unchecked_Access,
c_math_c.Real (low_Limit),
c_math_c.Real (high_Limit),
Boolean'Pos (collide_Conected));
return Self;
end new_hinge_Joint;
overriding
procedure destruct (Self : in out Hinge)
is
begin
b2d_free_hinge_Joint (Self.C);
Self.C := null;
end destruct;
overriding
procedure Limits_are (Self : in out Hinge; Low, High : in Real;
Softness : in Real := 0.9;
biasFactor : in Real := 0.3;
relaxationFactor : in Real := 1.0)
is
begin
b2d_Joint_hinge_Limits_are (Self.C, c_math_c.Real (Low),
c_math_c.Real (High));
end Limits_are;
overriding
function lower_Limit (Self : in Hinge) return Real
is
begin
raise Error with "TODO";
return 0.0;
end lower_Limit;
overriding
function upper_Limit (Self : in Hinge) return Real
is
begin
raise Error with "TODO";
return 0.0;
end upper_Limit;
overriding
function Angle (Self : in Hinge) return Real
is
begin
raise Error with "TODO";
return 0.0;
end Angle;
overriding
function Object_A (Self : in Hinge) return physics.Object.view
is
begin
raise Error with "TODO";
return null;
end Object_A;
overriding
function Object_B (Self : in Hinge) return physics.Object.view
is
begin
raise Error with "TODO";
return null;
end Object_B;
overriding
function Frame_A (Self : in Hinge) return Matrix_4x4
is
c_Frame : aliased c_math_c.Matrix_4x4.item;
begin
raise Error with "TODO";
return +c_Frame;
end Frame_A;
overriding
function Frame_B (Self : in Hinge) return Matrix_4x4
is
c_Frame : aliased c_math_c.Matrix_4x4.item;
begin
raise Error with "TODO";
return +c_Frame;
end Frame_B;
overriding
procedure Frame_A_is (Self : in out Hinge; Now : in Matrix_4x4)
is
c_Frame : aliased constant c_math_c.Matrix_4x4.item := +Now;
pragma Unreferenced (c_Frame);
begin
raise Error with "TODO";
end Frame_A_is;
overriding
procedure Frame_B_is (Self : in out Hinge; Now : in Matrix_4x4)
is
c_Frame : aliased constant c_math_c.Matrix_4x4.item := +Now;
pragma Unreferenced (c_Frame);
begin
raise Error with "TODO";
end Frame_B_is;
overriding
function is_Limited (Self : in Hinge; DoF : Degree_of_freedom) return Boolean
is
pragma unreferenced (Self);
begin
return DoF = 1;
end is_Limited;
overriding
procedure Velocity_is (Self : in out Hinge; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
if DoF /= 1 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
end Velocity_is;
overriding
function Extent (Self : in Hinge; DoF : Degree_of_freedom) return Real
is
begin
raise Error with "TODO";
if DoF /= 1 then
raise Error with "Illegal degree of freedom:" & Degree_of_freedom'Image (DoF);
end if;
return 0.0;
end Extent;
overriding
procedure desired_Extent_is (Self : in out Hinge; Now : in Real;
DoF : in Degree_of_freedom)
is
begin
raise Error with "TODO";
end desired_Extent_is;
--------
--- Free
--
procedure free (the_Joint : in out physics.Joint.view)
is
procedure deallocate is new ada.unchecked_Deallocation (physics.Joint.item'Class,
physics.Joint.view);
begin
deallocate (the_Joint);
end free;
end box2d_Physics.Joint;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . N U M E R I C S . A U X --
-- --
-- B o d y --
-- (Apple OS X Version) --
-- --
-- Copyright (C) 1998-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 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. --
-- --
------------------------------------------------------------------------------
-- File a-numaux.adb <- a-numaux-d arwin.adb
package body Ada.Numerics.Aux is
-----------------------
-- Local subprograms --
-----------------------
procedure Reduce (X : in out Double; Q : out Natural);
-- Implements reduction of X by Pi/2. Q is the quadrant of the final
-- result in the range 0 .. 3. The absolute value of X is at most Pi/4.
-- The following three functions implement Chebishev approximations
-- of the trigoniometric functions in their reduced domain.
-- These approximations have been computed using Maple.
function Sine_Approx (X : Double) return Double;
function Cosine_Approx (X : Double) return Double;
pragma Inline (Reduce);
pragma Inline (Sine_Approx);
pragma Inline (Cosine_Approx);
function Cosine_Approx (X : Double) return Double is
XX : constant Double := X * X;
begin
return (((((16#8.DC57FBD05F640#E-08 * XX
- 16#4.9F7D00BF25D80#E-06) * XX
+ 16#1.A019F7FDEFCC2#E-04) * XX
- 16#5.B05B058F18B20#E-03) * XX
+ 16#A.AAAAAAAA73FA8#E-02) * XX
- 16#7.FFFFFFFFFFDE4#E-01) * XX
- 16#3.655E64869ECCE#E-14 + 1.0;
end Cosine_Approx;
function Sine_Approx (X : Double) return Double is
XX : constant Double := X * X;
begin
return (((((16#A.EA2D4ABE41808#E-09 * XX
- 16#6.B974C10F9D078#E-07) * XX
+ 16#2.E3BC673425B0E#E-05) * XX
- 16#D.00D00CCA7AF00#E-04) * XX
+ 16#2.222222221B190#E-02) * XX
- 16#2.AAAAAAAAAAA44#E-01) * (XX * X) + X;
end Sine_Approx;
------------
-- Reduce --
------------
procedure Reduce (X : in out Double; Q : out Natural) is
Half_Pi : constant := Pi / 2.0;
Two_Over_Pi : constant := 2.0 / Pi;
HM : constant := Integer'Min (Double'Machine_Mantissa / 2, Natural'Size);
M : constant Double := 0.5 + 2.0**(1 - HM); -- Splitting constant
P1 : constant Double := Double'Leading_Part (Half_Pi, HM);
P2 : constant Double := Double'Leading_Part (Half_Pi - P1, HM);
P3 : constant Double := Double'Leading_Part (Half_Pi - P1 - P2, HM);
P4 : constant Double := Double'Leading_Part (Half_Pi - P1 - P2 - P3, HM);
P5 : constant Double := Double'Leading_Part (Half_Pi - P1 - P2 - P3
- P4, HM);
P6 : constant Double := Double'Model (Half_Pi - P1 - P2 - P3 - P4 - P5);
K : Double;
begin
-- For X < 2.0**HM, all products below are computed exactly.
-- Due to cancellation effects all subtractions are exact as well.
-- As no double extended floating-point number has more than 75
-- zeros after the binary point, the result will be the correctly
-- rounded result of X - K * (Pi / 2.0).
K := X * Two_Over_Pi;
while abs K >= 2.0 ** HM loop
K := K * M - (K * M - K);
X :=
(((((X - K * P1) - K * P2) - K * P3) - K * P4) - K * P5) - K * P6;
K := X * Two_Over_Pi;
end loop;
-- If K is not a number (because X was not finite) raise exception
if K /= K then
raise Constraint_Error;
end if;
K := Double'Rounding (K);
Q := Integer (K) mod 4;
X := (((((X - K * P1) - K * P2) - K * P3)
- K * P4) - K * P5) - K * P6;
end Reduce;
---------
-- Cos --
---------
function Cos (X : Double) return Double is
Reduced_X : Double := abs X;
Quadrant : Natural range 0 .. 3;
begin
if Reduced_X > Pi / 4.0 then
Reduce (Reduced_X, Quadrant);
case Quadrant is
when 0 =>
return Cosine_Approx (Reduced_X);
when 1 =>
return Sine_Approx (-Reduced_X);
when 2 =>
return -Cosine_Approx (Reduced_X);
when 3 =>
return Sine_Approx (Reduced_X);
end case;
end if;
return Cosine_Approx (Reduced_X);
end Cos;
---------
-- Sin --
---------
function Sin (X : Double) return Double is
Reduced_X : Double := X;
Quadrant : Natural range 0 .. 3;
begin
if abs X > Pi / 4.0 then
Reduce (Reduced_X, Quadrant);
case Quadrant is
when 0 =>
return Sine_Approx (Reduced_X);
when 1 =>
return Cosine_Approx (Reduced_X);
when 2 =>
return Sine_Approx (-Reduced_X);
when 3 =>
return -Cosine_Approx (Reduced_X);
end case;
end if;
return Sine_Approx (Reduced_X);
end Sin;
end Ada.Numerics.Aux;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
-- Style contains formatting properties that affect the appearance or style
-- of graphical elements.
------------------------------------------------------------------------------
limited with AMF.DC;
limited with AMF.DG.Fills;
with AMF.Real_Collections;
package AMF.DG.Styles is
pragma Preelaborate;
type DG_Style is limited interface;
type DG_Style_Access is
access all DG_Style'Class;
for DG_Style_Access'Storage_Size use 0;
not overriding function Get_Fill
(Self : not null access constant DG_Style)
return AMF.DG.Fills.DG_Fill_Access is abstract;
-- Getter of Style::fill.
--
-- a reference to a fill that is used to paint the enclosed regions of a
-- graphical element. A fill value is exclusive with a fillColor value. If
-- both are specified, the fill value is used. If none is specified, no
-- fill is applied (i.e. the element becomes see-through).
not overriding procedure Set_Fill
(Self : not null access DG_Style;
To : AMF.DG.Fills.DG_Fill_Access) is abstract;
-- Setter of Style::fill.
--
-- a reference to a fill that is used to paint the enclosed regions of a
-- graphical element. A fill value is exclusive with a fillColor value. If
-- both are specified, the fill value is used. If none is specified, no
-- fill is applied (i.e. the element becomes see-through).
not overriding function Get_Fill_Color
(Self : not null access constant DG_Style)
return AMF.DC.Optional_DC_Color is abstract;
-- Getter of Style::fillColor.
--
-- a color that is used to paint the enclosed regions of graphical
-- element. A fillColor value is exclusive with a fill value. If both are
-- specified, the fill value is used. If none is specified, no fill is
-- applied (i.e. the element becomes see-through).
not overriding procedure Set_Fill_Color
(Self : not null access DG_Style;
To : AMF.DC.Optional_DC_Color) is abstract;
-- Setter of Style::fillColor.
--
-- a color that is used to paint the enclosed regions of graphical
-- element. A fillColor value is exclusive with a fill value. If both are
-- specified, the fill value is used. If none is specified, no fill is
-- applied (i.e. the element becomes see-through).
not overriding function Get_Fill_Opacity
(Self : not null access constant DG_Style)
return AMF.Optional_Real is abstract;
-- Getter of Style::fillOpacity.
--
-- a real number (>=0 and <=1) representing the opacity of the fill or
-- fillColor used to paint a graphical element. A value of 0 means totally
-- transparent, while a value of 1 means totally opaque. The default is 1.
not overriding procedure Set_Fill_Opacity
(Self : not null access DG_Style;
To : AMF.Optional_Real) is abstract;
-- Setter of Style::fillOpacity.
--
-- a real number (>=0 and <=1) representing the opacity of the fill or
-- fillColor used to paint a graphical element. A value of 0 means totally
-- transparent, while a value of 1 means totally opaque. The default is 1.
not overriding function Get_Stroke_Width
(Self : not null access constant DG_Style)
return AMF.Optional_Real is abstract;
-- Getter of Style::strokeWidth.
--
-- a real number (>=0) representing the width of the stroke used to paint
-- the outline of a graphical element. A value of 0 specifies no stroke is
-- painted. The default is 1.
not overriding procedure Set_Stroke_Width
(Self : not null access DG_Style;
To : AMF.Optional_Real) is abstract;
-- Setter of Style::strokeWidth.
--
-- a real number (>=0) representing the width of the stroke used to paint
-- the outline of a graphical element. A value of 0 specifies no stroke is
-- painted. The default is 1.
not overriding function Get_Stroke_Opacity
(Self : not null access constant DG_Style)
return AMF.Optional_Real is abstract;
-- Getter of Style::strokeOpacity.
--
-- a real number (>=0 and <=1) representing the opacity of the stroke used
-- for a graphical element. A value of 0 means totally transparent, while
-- a value of 1 means totally opaque. The default is 1.
not overriding procedure Set_Stroke_Opacity
(Self : not null access DG_Style;
To : AMF.Optional_Real) is abstract;
-- Setter of Style::strokeOpacity.
--
-- a real number (>=0 and <=1) representing the opacity of the stroke used
-- for a graphical element. A value of 0 means totally transparent, while
-- a value of 1 means totally opaque. The default is 1.
not overriding function Get_Stroke_Color
(Self : not null access constant DG_Style)
return AMF.DC.Optional_DC_Color is abstract;
-- Getter of Style::strokeColor.
--
-- the color of the stroke used to paint the outline of a graphical
-- element. The default is black (red=0, green=0, blue=0).
not overriding procedure Set_Stroke_Color
(Self : not null access DG_Style;
To : AMF.DC.Optional_DC_Color) is abstract;
-- Setter of Style::strokeColor.
--
-- the color of the stroke used to paint the outline of a graphical
-- element. The default is black (red=0, green=0, blue=0).
not overriding function Get_Stroke_Dash_Length
(Self : not null access constant DG_Style)
return AMF.Real_Collections.Sequence_Of_Real is abstract;
-- Getter of Style::strokeDashLength.
--
-- a list of real numbers specifying a pattern of alternating dash and gap
-- lengths used in stroking the outline of a graphical element with the
-- first one specifying a dash length. The size of the list is expected to
-- be even. If the list is empty, the stroke is drawn solid. The default
-- is empty list.
not overriding function Get_Font_Size
(Self : not null access constant DG_Style)
return AMF.Optional_Real is abstract;
-- Getter of Style::fontSize.
--
-- a real number (>=0) representing the size (in unit of length) of the
-- font used to render a text element. The default is 10.
not overriding procedure Set_Font_Size
(Self : not null access DG_Style;
To : AMF.Optional_Real) is abstract;
-- Setter of Style::fontSize.
--
-- a real number (>=0) representing the size (in unit of length) of the
-- font used to render a text element. The default is 10.
not overriding function Get_Font_Name
(Self : not null access constant DG_Style)
return AMF.Optional_String is abstract;
-- Getter of Style::fontName.
--
-- the name of the font used to render a text element (e.g. "Times New
-- Roman", "Arial" or "Helvetica"). The default is "Arial".
not overriding procedure Set_Font_Name
(Self : not null access DG_Style;
To : AMF.Optional_String) is abstract;
-- Setter of Style::fontName.
--
-- the name of the font used to render a text element (e.g. "Times New
-- Roman", "Arial" or "Helvetica"). The default is "Arial".
not overriding function Get_Font_Color
(Self : not null access constant DG_Style)
return AMF.DC.Optional_DC_Color is abstract;
-- Getter of Style::fontColor.
--
-- the color of the font used to render a text element. The default is
-- black (red=0, green=0, blue=0).
not overriding procedure Set_Font_Color
(Self : not null access DG_Style;
To : AMF.DC.Optional_DC_Color) is abstract;
-- Setter of Style::fontColor.
--
-- the color of the font used to render a text element. The default is
-- black (red=0, green=0, blue=0).
not overriding function Get_Font_Italic
(Self : not null access constant DG_Style)
return AMF.Optional_Boolean is abstract;
-- Getter of Style::fontItalic.
--
-- whether the font used to render a text element has an <i>italic</i>
-- style. The default is false.
not overriding procedure Set_Font_Italic
(Self : not null access DG_Style;
To : AMF.Optional_Boolean) is abstract;
-- Setter of Style::fontItalic.
--
-- whether the font used to render a text element has an <i>italic</i>
-- style. The default is false.
not overriding function Get_Font_Bold
(Self : not null access constant DG_Style)
return AMF.Optional_Boolean is abstract;
-- Getter of Style::fontBold.
--
-- whether the font used to render a text element has a <b>bold</b> style.
-- The default is false.
not overriding procedure Set_Font_Bold
(Self : not null access DG_Style;
To : AMF.Optional_Boolean) is abstract;
-- Setter of Style::fontBold.
--
-- whether the font used to render a text element has a <b>bold</b> style.
-- The default is false.
not overriding function Get_Font_Underline
(Self : not null access constant DG_Style)
return AMF.Optional_Boolean is abstract;
-- Getter of Style::fontUnderline.
--
-- whether the font used to render a text element has an <b>underline</b>
-- style. The default is false.
not overriding procedure Set_Font_Underline
(Self : not null access DG_Style;
To : AMF.Optional_Boolean) is abstract;
-- Setter of Style::fontUnderline.
--
-- whether the font used to render a text element has an <b>underline</b>
-- style. The default is false.
not overriding function Get_Font_Strike_Through
(Self : not null access constant DG_Style)
return AMF.Optional_Boolean is abstract;
-- Getter of Style::fontStrikeThrough.
--
-- whether the font used to render a text element has a
-- <b>strike-through</b> style. The default is false.
not overriding procedure Set_Font_Strike_Through
(Self : not null access DG_Style;
To : AMF.Optional_Boolean) is abstract;
-- Setter of Style::fontStrikeThrough.
--
-- whether the font used to render a text element has a
-- <b>strike-through</b> style. The default is false.
end AMF.DG.Styles;
|
-- This package has been generated automatically by GNATtest.
-- You are allowed to add your code to the bodies of test routines.
-- Such changes will be kept during further regeneration of this file.
-- All code placed outside of test routine bodies will be lost. The
-- code intended to set up and tear down the test environment should be
-- placed into BasesTypes.Test_Data.
with AUnit.Assertions; use AUnit.Assertions;
with System.Assertions;
-- begin read only
-- id:2.2/00/
--
-- This section can be used to add with clauses if necessary.
--
-- end read only
-- begin read only
-- end read only
package body BasesTypes.Test_Data.Tests is
-- begin read only
-- id:2.2/01/
--
-- This section can be used to add global variables and other elements.
--
-- end read only
-- begin read only
-- end read only
-- begin read only
function Wrap_Test_Is_Buyable_e4fcaf_447d98
(Base_Type, Item_Index: Unbounded_String; Check_Flag: Boolean := True;
Base_Index: Extended_Base_Range := 0) return Boolean is
begin
begin
pragma Assert
(Bases_Types_List.Contains(Key => Base_Type) and
Items_List.Contains(Key => Item_Index));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(basestypes.ads:0):Test_Is_Buyable test requirement violated");
end;
declare
Test_Is_Buyable_e4fcaf_447d98_Result: constant Boolean :=
GNATtest_Generated.GNATtest_Standard.BasesTypes.Is_Buyable
(Base_Type, Item_Index, Check_Flag, Base_Index);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(basestypes.ads:0:):Test_Is_Buyable test commitment violated");
end;
return Test_Is_Buyable_e4fcaf_447d98_Result;
end;
end Wrap_Test_Is_Buyable_e4fcaf_447d98;
-- end read only
-- begin read only
procedure Test_Is_Buyable_test_is_buyable(Gnattest_T: in out Test);
procedure Test_Is_Buyable_e4fcaf_447d98(Gnattest_T: in out Test) renames
Test_Is_Buyable_test_is_buyable;
-- id:2.2/e4fcaf8408019fdf/Is_Buyable/1/0/test_is_buyable/
procedure Test_Is_Buyable_test_is_buyable(Gnattest_T: in out Test) is
function Is_Buyable
(Base_Type, Item_Index: Unbounded_String; Check_Flag: Boolean := True;
Base_Index: Extended_Base_Range := 0) return Boolean renames
Wrap_Test_Is_Buyable_e4fcaf_447d98;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
Assert
(Is_Buyable(To_Unbounded_String("0"), To_Unbounded_String("1")) =
False,
"Failed to check if item is not buyable in base.");
Assert
(Is_Buyable(To_Unbounded_String("1"), To_Unbounded_String("2")),
"Failed to check if item is buyable in base.");
-- begin read only
end Test_Is_Buyable_test_is_buyable;
-- end read only
-- begin read only
function Wrap_Test_Get_Price_58bb07_c6139c
(Base_Type, Item_Index: Unbounded_String) return Natural is
begin
begin
pragma Assert
(Bases_Types_List.Contains(Key => Base_Type) and
Items_List.Contains(Key => Item_Index));
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(basestypes.ads:0):Test_Get_Price test requirement violated");
end;
declare
Test_Get_Price_58bb07_c6139c_Result: constant Natural :=
GNATtest_Generated.GNATtest_Standard.BasesTypes.Get_Price
(Base_Type, Item_Index);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(basestypes.ads:0:):Test_Get_Price test commitment violated");
end;
return Test_Get_Price_58bb07_c6139c_Result;
end;
end Wrap_Test_Get_Price_58bb07_c6139c;
-- end read only
-- begin read only
procedure Test_Get_Price_test_get_price(Gnattest_T: in out Test);
procedure Test_Get_Price_58bb07_c6139c(Gnattest_T: in out Test) renames
Test_Get_Price_test_get_price;
-- id:2.2/58bb076ead9f93c1/Get_Price/1/0/test_get_price/
procedure Test_Get_Price_test_get_price(Gnattest_T: in out Test) is
function Get_Price
(Base_Type, Item_Index: Unbounded_String) return Natural renames
Wrap_Test_Get_Price_58bb07_c6139c;
-- end read only
pragma Unreferenced(Gnattest_T);
begin
Assert
(Get_Price(To_Unbounded_String("0"), To_Unbounded_String("1")) = 0,
"Failed to get price of not buyable item.");
Assert
(Get_Price(To_Unbounded_String("1"), To_Unbounded_String("2")) > 0,
"Failed to get price of buyable item.");
-- begin read only
end Test_Get_Price_test_get_price;
-- end read only
-- begin read only
-- id:2.2/02/
--
-- This section can be used to add elaboration code for the global state.
--
begin
-- end read only
null;
-- begin read only
-- end read only
end BasesTypes.Test_Data.Tests;
|
-- { dg-do compile }
procedure access_func is
type Abomination is access
function (X : Integer) return access
function (Y : Float) return access
function return Integer;
begin
null;
end;
|
-- {{Ada/Sourceforge|fibonacci_1.adb}}
pragma License (Gpl);
pragma Ada_95;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Fibonacci_1 is
type Integer_Type is range 0 .. 999_999_999_999_999_999;
package CL renames Ada.Command_Line;
package T_IO renames Ada.Text_IO;
package I_IO is new Ada.Text_IO.Integer_IO (Integer_Type);
function Fib (N : Integer_Type) return Integer_Type;
Last : Positive;
Value : Integer_Type;
function Fib (N : Integer_Type) return Integer_Type is
begin
if N = 0 then
return 0;
elsif N = 1 then
return 1;
else
return Fib (N - 1) + Fib (N - 2);
end if;
end Fib;
begin
I_IO.Get
(From => CL.Argument (1),
Item => Value,
Last => Last);
T_IO.Put ("The Fibonacci of ");
I_IO.Put
(Item => Value,
Width => 3,
Base => I_IO.Default_Base);
T_IO.Put (" is ");
I_IO.Put
(Item => Fib (Value),
Width => I_IO.Default_Width,
Base => I_IO.Default_Base);
return;
end Fibonacci_1;
----------------------------------------------------------------------------
-- $Author: krischik $
--
-- $Revision: 226 $
-- $Date: 2007-12-02 15:11:44 +0000 (Sun, 02 Dec 2007) $
--
-- $Id: fibonacci_1.adb 226 2007-12-02 15:11:44Z krischik $
-- $HeadURL: file:///svn/p/wikibook-ada/code/trunk/demos/Source/fibonacci_1.adb $
----------------------------------------------------------------------------
-- vim: textwidth=0 nowrap tabstop=8 shiftwidth=3 softtabstop=3 expandtab
-- vim: filetype=ada encoding=utf-8 fileformat=unix foldmethod=indent
|
--
-- Copyright (C) 2021, AdaCore
--
pragma Style_Checks (Off);
-- This spec has been automatically generated from STM32G474xx.svd
with System;
package Interfaces.STM32.Flash is
pragma Preelaborate;
pragma No_Elaboration_Code_All;
---------------
-- Registers --
---------------
subtype ACR_LATENCY_Field is Interfaces.STM32.UInt4;
subtype ACR_PRFTEN_Field is Interfaces.STM32.Bit;
subtype ACR_ICEN_Field is Interfaces.STM32.Bit;
subtype ACR_DCEN_Field is Interfaces.STM32.Bit;
subtype ACR_ICRST_Field is Interfaces.STM32.Bit;
subtype ACR_DCRST_Field is Interfaces.STM32.Bit;
subtype ACR_RUN_PD_Field is Interfaces.STM32.Bit;
subtype ACR_SLEEP_PD_Field is Interfaces.STM32.Bit;
subtype ACR_DBG_SWEN_Field is Interfaces.STM32.Bit;
-- Access control register
type ACR_Register is record
-- Latency
LATENCY : ACR_LATENCY_Field := 16#0#;
-- unspecified
Reserved_4_7 : Interfaces.STM32.UInt4 := 16#0#;
-- Prefetch enable
PRFTEN : ACR_PRFTEN_Field := 16#0#;
-- Instruction cache enable
ICEN : ACR_ICEN_Field := 16#1#;
-- Data cache enable
DCEN : ACR_DCEN_Field := 16#1#;
-- Instruction cache reset
ICRST : ACR_ICRST_Field := 16#0#;
-- Data cache reset
DCRST : ACR_DCRST_Field := 16#0#;
-- Flash Power-down mode during Low-power run mode
RUN_PD : ACR_RUN_PD_Field := 16#0#;
-- Flash Power-down mode during Low-power sleep mode
SLEEP_PD : ACR_SLEEP_PD_Field := 16#0#;
-- unspecified
Reserved_15_17 : Interfaces.STM32.UInt3 := 16#0#;
-- Debug software enable
DBG_SWEN : ACR_DBG_SWEN_Field := 16#0#;
-- unspecified
Reserved_19_31 : Interfaces.STM32.UInt13 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for ACR_Register use record
LATENCY at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
PRFTEN at 0 range 8 .. 8;
ICEN at 0 range 9 .. 9;
DCEN at 0 range 10 .. 10;
ICRST at 0 range 11 .. 11;
DCRST at 0 range 12 .. 12;
RUN_PD at 0 range 13 .. 13;
SLEEP_PD at 0 range 14 .. 14;
Reserved_15_17 at 0 range 15 .. 17;
DBG_SWEN at 0 range 18 .. 18;
Reserved_19_31 at 0 range 19 .. 31;
end record;
subtype SR_EOP_Field is Interfaces.STM32.Bit;
subtype SR_OPERR_Field is Interfaces.STM32.Bit;
subtype SR_PROGERR_Field is Interfaces.STM32.Bit;
subtype SR_WRPERR_Field is Interfaces.STM32.Bit;
subtype SR_PGAERR_Field is Interfaces.STM32.Bit;
subtype SR_SIZERR_Field is Interfaces.STM32.Bit;
subtype SR_PGSERR_Field is Interfaces.STM32.Bit;
subtype SR_MISERR_Field is Interfaces.STM32.Bit;
subtype SR_FASTERR_Field is Interfaces.STM32.Bit;
subtype SR_RDERR_Field is Interfaces.STM32.Bit;
subtype SR_OPTVERR_Field is Interfaces.STM32.Bit;
subtype SR_BSY_Field is Interfaces.STM32.Bit;
-- Status register
type SR_Register is record
-- End of operation
EOP : SR_EOP_Field := 16#0#;
-- Operation error
OPERR : SR_OPERR_Field := 16#0#;
-- unspecified
Reserved_2_2 : Interfaces.STM32.Bit := 16#0#;
-- Programming error
PROGERR : SR_PROGERR_Field := 16#0#;
-- Write protected error
WRPERR : SR_WRPERR_Field := 16#0#;
-- Programming alignment error
PGAERR : SR_PGAERR_Field := 16#0#;
-- Size error
SIZERR : SR_SIZERR_Field := 16#0#;
-- Programming sequence error
PGSERR : SR_PGSERR_Field := 16#0#;
-- Fast programming data miss error
MISERR : SR_MISERR_Field := 16#0#;
-- Fast programming error
FASTERR : SR_FASTERR_Field := 16#0#;
-- unspecified
Reserved_10_13 : Interfaces.STM32.UInt4 := 16#0#;
-- PCROP read error
RDERR : SR_RDERR_Field := 16#0#;
-- Option validity error
OPTVERR : SR_OPTVERR_Field := 16#0#;
-- Read-only. Busy
BSY : SR_BSY_Field := 16#0#;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SR_Register use record
EOP at 0 range 0 .. 0;
OPERR at 0 range 1 .. 1;
Reserved_2_2 at 0 range 2 .. 2;
PROGERR at 0 range 3 .. 3;
WRPERR at 0 range 4 .. 4;
PGAERR at 0 range 5 .. 5;
SIZERR at 0 range 6 .. 6;
PGSERR at 0 range 7 .. 7;
MISERR at 0 range 8 .. 8;
FASTERR at 0 range 9 .. 9;
Reserved_10_13 at 0 range 10 .. 13;
RDERR at 0 range 14 .. 14;
OPTVERR at 0 range 15 .. 15;
BSY at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype CR_PG_Field is Interfaces.STM32.Bit;
subtype CR_PER_Field is Interfaces.STM32.Bit;
subtype CR_MER1_Field is Interfaces.STM32.Bit;
subtype CR_PNB_Field is Interfaces.STM32.UInt7;
subtype CR_STRT_Field is Interfaces.STM32.Bit;
subtype CR_OPTSTRT_Field is Interfaces.STM32.Bit;
subtype CR_FSTPG_Field is Interfaces.STM32.Bit;
subtype CR_EOPIE_Field is Interfaces.STM32.Bit;
subtype CR_ERRIE_Field is Interfaces.STM32.Bit;
subtype CR_RDERRIE_Field is Interfaces.STM32.Bit;
subtype CR_OBL_LAUNCH_Field is Interfaces.STM32.Bit;
subtype CR_SEC_PROT1_Field is Interfaces.STM32.Bit;
subtype CR_OPTLOCK_Field is Interfaces.STM32.Bit;
subtype CR_LOCK_Field is Interfaces.STM32.Bit;
-- Flash control register
type CR_Register is record
-- Programming
PG : CR_PG_Field := 16#0#;
-- Page erase
PER : CR_PER_Field := 16#0#;
-- Bank 1 Mass erase
MER1 : CR_MER1_Field := 16#0#;
-- Page number
PNB : CR_PNB_Field := 16#0#;
-- unspecified
Reserved_10_15 : Interfaces.STM32.UInt6 := 16#0#;
-- Start
STRT : CR_STRT_Field := 16#0#;
-- Options modification start
OPTSTRT : CR_OPTSTRT_Field := 16#0#;
-- Fast programming
FSTPG : CR_FSTPG_Field := 16#0#;
-- unspecified
Reserved_19_23 : Interfaces.STM32.UInt5 := 16#0#;
-- End of operation interrupt enable
EOPIE : CR_EOPIE_Field := 16#0#;
-- Error interrupt enable
ERRIE : CR_ERRIE_Field := 16#0#;
-- PCROP read error interrupt enable
RDERRIE : CR_RDERRIE_Field := 16#0#;
-- Force the option byte loading
OBL_LAUNCH : CR_OBL_LAUNCH_Field := 16#0#;
-- SEC_PROT1
SEC_PROT1 : CR_SEC_PROT1_Field := 16#0#;
-- unspecified
Reserved_29_29 : Interfaces.STM32.Bit := 16#0#;
-- Options Lock
OPTLOCK : CR_OPTLOCK_Field := 16#1#;
-- FLASH_CR Lock
LOCK : CR_LOCK_Field := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CR_Register use record
PG at 0 range 0 .. 0;
PER at 0 range 1 .. 1;
MER1 at 0 range 2 .. 2;
PNB at 0 range 3 .. 9;
Reserved_10_15 at 0 range 10 .. 15;
STRT at 0 range 16 .. 16;
OPTSTRT at 0 range 17 .. 17;
FSTPG at 0 range 18 .. 18;
Reserved_19_23 at 0 range 19 .. 23;
EOPIE at 0 range 24 .. 24;
ERRIE at 0 range 25 .. 25;
RDERRIE at 0 range 26 .. 26;
OBL_LAUNCH at 0 range 27 .. 27;
SEC_PROT1 at 0 range 28 .. 28;
Reserved_29_29 at 0 range 29 .. 29;
OPTLOCK at 0 range 30 .. 30;
LOCK at 0 range 31 .. 31;
end record;
subtype ECCR_ADDR_ECC_Field is Interfaces.STM32.UInt19;
subtype ECCR_BK_ECC_Field is Interfaces.STM32.Bit;
subtype ECCR_SYSF_ECC_Field is Interfaces.STM32.Bit;
subtype ECCR_ECCIE_Field is Interfaces.STM32.Bit;
subtype ECCR_ECCC2_Field is Interfaces.STM32.Bit;
subtype ECCR_ECCD2_Field is Interfaces.STM32.Bit;
subtype ECCR_ECCC_Field is Interfaces.STM32.Bit;
subtype ECCR_ECCD_Field is Interfaces.STM32.Bit;
-- Flash ECC register
type ECCR_Register is record
-- Read-only. ECC fail address
ADDR_ECC : ECCR_ADDR_ECC_Field := 16#0#;
-- unspecified
Reserved_19_20 : Interfaces.STM32.UInt2 := 16#0#;
-- Read-only. BK_ECC
BK_ECC : ECCR_BK_ECC_Field := 16#0#;
-- Read-only. SYSF_ECC
SYSF_ECC : ECCR_SYSF_ECC_Field := 16#0#;
-- unspecified
Reserved_23_23 : Interfaces.STM32.Bit := 16#0#;
-- ECCIE
ECCIE : ECCR_ECCIE_Field := 16#0#;
-- unspecified
Reserved_25_27 : Interfaces.STM32.UInt3 := 16#0#;
-- ECC correction
ECCC2 : ECCR_ECCC2_Field := 16#0#;
-- ECC2 detection
ECCD2 : ECCR_ECCD2_Field := 16#0#;
-- ECC correction
ECCC : ECCR_ECCC_Field := 16#0#;
-- ECC detection
ECCD : ECCR_ECCD_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for ECCR_Register use record
ADDR_ECC at 0 range 0 .. 18;
Reserved_19_20 at 0 range 19 .. 20;
BK_ECC at 0 range 21 .. 21;
SYSF_ECC at 0 range 22 .. 22;
Reserved_23_23 at 0 range 23 .. 23;
ECCIE at 0 range 24 .. 24;
Reserved_25_27 at 0 range 25 .. 27;
ECCC2 at 0 range 28 .. 28;
ECCD2 at 0 range 29 .. 29;
ECCC at 0 range 30 .. 30;
ECCD at 0 range 31 .. 31;
end record;
subtype OPTR_RDP_Field is Interfaces.STM32.Byte;
subtype OPTR_BOR_LEV_Field is Interfaces.STM32.UInt3;
subtype OPTR_nRST_STOP_Field is Interfaces.STM32.Bit;
subtype OPTR_nRST_STDBY_Field is Interfaces.STM32.Bit;
subtype OPTR_nRST_SHDW_Field is Interfaces.STM32.Bit;
subtype OPTR_IDWG_SW_Field is Interfaces.STM32.Bit;
subtype OPTR_IWDG_STOP_Field is Interfaces.STM32.Bit;
subtype OPTR_IWDG_STDBY_Field is Interfaces.STM32.Bit;
subtype OPTR_WWDG_SW_Field is Interfaces.STM32.Bit;
subtype OPTR_nBOOT1_Field is Interfaces.STM32.Bit;
subtype OPTR_SRAM2_PE_Field is Interfaces.STM32.Bit;
subtype OPTR_SRAM2_RST_Field is Interfaces.STM32.Bit;
subtype OPTR_nSWBOOT0_Field is Interfaces.STM32.Bit;
subtype OPTR_nBOOT0_Field is Interfaces.STM32.Bit;
subtype OPTR_NRST_MODE_Field is Interfaces.STM32.UInt2;
subtype OPTR_IRHEN_Field is Interfaces.STM32.Bit;
-- Flash option register
type OPTR_Register is record
-- Read protection level
RDP : OPTR_RDP_Field := 16#0#;
-- BOR reset Level
BOR_LEV : OPTR_BOR_LEV_Field := 16#0#;
-- unspecified
Reserved_11_11 : Interfaces.STM32.Bit := 16#0#;
-- nRST_STOP
nRST_STOP : OPTR_nRST_STOP_Field := 16#0#;
-- nRST_STDBY
nRST_STDBY : OPTR_nRST_STDBY_Field := 16#0#;
-- nRST_SHDW
nRST_SHDW : OPTR_nRST_SHDW_Field := 16#0#;
-- unspecified
Reserved_15_15 : Interfaces.STM32.Bit := 16#0#;
-- Independent watchdog selection
IDWG_SW : OPTR_IDWG_SW_Field := 16#0#;
-- Independent watchdog counter freeze in Stop mode
IWDG_STOP : OPTR_IWDG_STOP_Field := 16#0#;
-- Independent watchdog counter freeze in Standby mode
IWDG_STDBY : OPTR_IWDG_STDBY_Field := 16#0#;
-- Window watchdog selection
WWDG_SW : OPTR_WWDG_SW_Field := 16#0#;
-- unspecified
Reserved_20_22 : Interfaces.STM32.UInt3 := 16#0#;
-- Boot configuration
nBOOT1 : OPTR_nBOOT1_Field := 16#0#;
-- SRAM2 parity check enable
SRAM2_PE : OPTR_SRAM2_PE_Field := 16#0#;
-- SRAM2 Erase when system reset
SRAM2_RST : OPTR_SRAM2_RST_Field := 16#0#;
-- nSWBOOT0
nSWBOOT0 : OPTR_nSWBOOT0_Field := 16#0#;
-- nBOOT0
nBOOT0 : OPTR_nBOOT0_Field := 16#0#;
-- NRST_MODE
NRST_MODE : OPTR_NRST_MODE_Field := 16#3#;
-- IRHEN
IRHEN : OPTR_IRHEN_Field := 16#1#;
-- unspecified
Reserved_31_31 : Interfaces.STM32.Bit := 16#1#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for OPTR_Register use record
RDP at 0 range 0 .. 7;
BOR_LEV at 0 range 8 .. 10;
Reserved_11_11 at 0 range 11 .. 11;
nRST_STOP at 0 range 12 .. 12;
nRST_STDBY at 0 range 13 .. 13;
nRST_SHDW at 0 range 14 .. 14;
Reserved_15_15 at 0 range 15 .. 15;
IDWG_SW at 0 range 16 .. 16;
IWDG_STOP at 0 range 17 .. 17;
IWDG_STDBY at 0 range 18 .. 18;
WWDG_SW at 0 range 19 .. 19;
Reserved_20_22 at 0 range 20 .. 22;
nBOOT1 at 0 range 23 .. 23;
SRAM2_PE at 0 range 24 .. 24;
SRAM2_RST at 0 range 25 .. 25;
nSWBOOT0 at 0 range 26 .. 26;
nBOOT0 at 0 range 27 .. 27;
NRST_MODE at 0 range 28 .. 29;
IRHEN at 0 range 30 .. 30;
Reserved_31_31 at 0 range 31 .. 31;
end record;
subtype PCROP1SR_PCROP1_STRT_Field is Interfaces.STM32.UInt15;
-- Flash Bank 1 PCROP Start address register
type PCROP1SR_Register is record
-- Bank 1 PCROP area start offset
PCROP1_STRT : PCROP1SR_PCROP1_STRT_Field := 16#0#;
-- unspecified
Reserved_15_31 : Interfaces.STM32.UInt17 := 16#1FFFE#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PCROP1SR_Register use record
PCROP1_STRT at 0 range 0 .. 14;
Reserved_15_31 at 0 range 15 .. 31;
end record;
subtype PCROP1ER_PCROP1_END_Field is Interfaces.STM32.UInt15;
subtype PCROP1ER_PCROP_RDP_Field is Interfaces.STM32.Bit;
-- Flash Bank 1 PCROP End address register
type PCROP1ER_Register is record
-- Bank 1 PCROP area end offset
PCROP1_END : PCROP1ER_PCROP1_END_Field := 16#0#;
-- unspecified
Reserved_15_30 : Interfaces.STM32.UInt16 := 16#1FFE#;
-- PCROP area preserved when RDP level decreased
PCROP_RDP : PCROP1ER_PCROP_RDP_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PCROP1ER_Register use record
PCROP1_END at 0 range 0 .. 14;
Reserved_15_30 at 0 range 15 .. 30;
PCROP_RDP at 0 range 31 .. 31;
end record;
subtype WRP1AR_WRP1A_STRT_Field is Interfaces.STM32.UInt7;
subtype WRP1AR_WRP1A_END_Field is Interfaces.STM32.UInt7;
-- Flash Bank 1 WRP area A address register
type WRP1AR_Register is record
-- Bank 1 WRP first area start offset
WRP1A_STRT : WRP1AR_WRP1A_STRT_Field := 16#0#;
-- unspecified
Reserved_7_15 : Interfaces.STM32.UInt9 := 16#0#;
-- Bank 1 WRP first area A end offset
WRP1A_END : WRP1AR_WRP1A_END_Field := 16#0#;
-- unspecified
Reserved_23_31 : Interfaces.STM32.UInt9 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for WRP1AR_Register use record
WRP1A_STRT at 0 range 0 .. 6;
Reserved_7_15 at 0 range 7 .. 15;
WRP1A_END at 0 range 16 .. 22;
Reserved_23_31 at 0 range 23 .. 31;
end record;
subtype WRP1BR_WRP1B_STRT_Field is Interfaces.STM32.UInt7;
subtype WRP1BR_WRP1B_END_Field is Interfaces.STM32.UInt7;
-- Flash Bank 1 WRP area B address register
type WRP1BR_Register is record
-- Bank 1 WRP second area B end offset
WRP1B_STRT : WRP1BR_WRP1B_STRT_Field := 16#0#;
-- unspecified
Reserved_7_15 : Interfaces.STM32.UInt9 := 16#0#;
-- Bank 1 WRP second area B start offset
WRP1B_END : WRP1BR_WRP1B_END_Field := 16#0#;
-- unspecified
Reserved_23_31 : Interfaces.STM32.UInt9 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for WRP1BR_Register use record
WRP1B_STRT at 0 range 0 .. 6;
Reserved_7_15 at 0 range 7 .. 15;
WRP1B_END at 0 range 16 .. 22;
Reserved_23_31 at 0 range 23 .. 31;
end record;
subtype SEC1R_SEC_SIZE1_Field is Interfaces.STM32.Byte;
subtype SEC1R_BOOT_LOCK_Field is Interfaces.STM32.Bit;
-- securable area bank1 register
type SEC1R_Register is record
-- SEC_SIZE1
SEC_SIZE1 : SEC1R_SEC_SIZE1_Field := 16#0#;
-- unspecified
Reserved_8_15 : Interfaces.STM32.Byte := 16#FF#;
-- BOOT_LOCK
BOOT_LOCK : SEC1R_BOOT_LOCK_Field := 16#0#;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15 := 16#7F80#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SEC1R_Register use record
SEC_SIZE1 at 0 range 0 .. 7;
Reserved_8_15 at 0 range 8 .. 15;
BOOT_LOCK at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Flash
type FLASH_Peripheral is record
-- Access control register
ACR : aliased ACR_Register;
-- Power down key register
PDKEYR : aliased Interfaces.STM32.UInt32;
-- Flash key register
KEYR : aliased Interfaces.STM32.UInt32;
-- Option byte key register
OPTKEYR : aliased Interfaces.STM32.UInt32;
-- Status register
SR : aliased SR_Register;
-- Flash control register
CR : aliased CR_Register;
-- Flash ECC register
ECCR : aliased ECCR_Register;
-- Flash option register
OPTR : aliased OPTR_Register;
-- Flash Bank 1 PCROP Start address register
PCROP1SR : aliased PCROP1SR_Register;
-- Flash Bank 1 PCROP End address register
PCROP1ER : aliased PCROP1ER_Register;
-- Flash Bank 1 WRP area A address register
WRP1AR : aliased WRP1AR_Register;
-- Flash Bank 1 WRP area B address register
WRP1BR : aliased WRP1BR_Register;
-- securable area bank1 register
SEC1R : aliased SEC1R_Register;
end record
with Volatile;
for FLASH_Peripheral use record
ACR at 16#0# range 0 .. 31;
PDKEYR at 16#4# range 0 .. 31;
KEYR at 16#8# range 0 .. 31;
OPTKEYR at 16#C# range 0 .. 31;
SR at 16#10# range 0 .. 31;
CR at 16#14# range 0 .. 31;
ECCR at 16#18# range 0 .. 31;
OPTR at 16#20# range 0 .. 31;
PCROP1SR at 16#24# range 0 .. 31;
PCROP1ER at 16#28# range 0 .. 31;
WRP1AR at 16#2C# range 0 .. 31;
WRP1BR at 16#30# range 0 .. 31;
SEC1R at 16#70# range 0 .. 31;
end record;
-- Flash
FLASH_Periph : aliased FLASH_Peripheral
with Import, Address => FLASH_Base;
end Interfaces.STM32.Flash;
|
------------------------------------------------------------------------------
-- G N A T C O L L --
-- --
-- Copyright (C) 2009-2019, AdaCore --
-- Copyright (C) 2020, Heisenbug Ltd. --
-- --
-- This library is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 3, or (at your option) any later --
-- version. This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- --
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling;
package body GNATCOLL.Opt_Parse.Extension is
function "+" (Self : in String) return XString renames To_XString;
function "+" (Self : in XString) return String renames To_String;
function Parse_One_Option
(Short, Long : in String;
Args : in XString_Array;
Pos : in Positive;
New_Pos : out Parser_Return) return XString;
---------------------------------------------------------------------------
-- Parse_One_Option
---------------------------------------------------------------------------
function Parse_One_Option (Short : in String;
Long : in String;
Args : in XString_Array;
Pos : in Positive;
New_Pos : out Parser_Return) return XString is
begin
if
Args (Pos) = Long
or else (Short /= "" and then Args (Pos) = Short)
then
if Pos + 1 > Args'Last or else Args (Pos + 1).Starts_With ("-") then
-- No more arguments or already next option.
New_Pos := Pos + 1;
return Null_XString;
end if;
New_Pos := Pos + 2;
return Args (Pos + 1);
elsif Args (Pos).Starts_With (Long & "=") then
New_Pos := Pos + 1;
return Args (Pos).Slice (Long'Last + 2, Args (Pos).Length);
elsif Short /= "" and then Args (Pos).Starts_With (Short) then
New_Pos := Pos + 1;
return Args (Pos).Slice (Short'Last + 1, Args (Pos).Length);
else
New_Pos := Error_Return;
return +"";
end if;
end Parse_One_Option;
package body Parse_Option_With_Default is
type Option_Parser is new GNATCOLL.Opt_Parse.Parser_Type with
null record;
overriding
function Usage (Self : Option_Parser) return String is
("[" & Long & (if Short = "" then "" else "|" & Short) & " "
& Ada.Characters.Handling.To_Upper (Long (3 .. Long'Last)) & "]");
overriding
function Help_Name (Dummy : Option_Parser) return String is
(Long & ", " & Short);
overriding
function Parse_Args
(Self : in out Option_Parser;
Args : in XString_Array;
Pos : in Positive;
Result : in out Parsed_Arguments) return Parser_Return;
type Internal_Result is new Parser_Result with
record
Result : Arg_Type;
end record;
type Internal_Result_Access is access all Internal_Result;
overriding
procedure Release (Self : in out Internal_Result) is null;
Self_Val : aliased Option_Parser :=
Option_Parser'(Name => +Long (3 .. Long'Last),
Help => +Help,
Parser => Parser.Data,
Opt => True,
Position => <>);
Self : constant Parser_Access := Self_Val'Unchecked_Access;
------------------------------------------------------------------------
-- Get
------------------------------------------------------------------------
function Get
(Args : Parsed_Arguments := No_Parsed_Arguments) return Arg_Type is
begin
if not Enabled then
return Default_Val;
end if;
declare
R : constant Parser_Result_Access := Self.Get_Result (Args);
begin
if R /= null then
return Internal_Result (R.all).Result;
else
return Default_Val;
end if;
end;
end Get;
------------------------------------------------------------------------
-- Parse_Args
------------------------------------------------------------------------
overriding
function Parse_Args
(Self : in out Option_Parser;
Args : in XString_Array;
Pos : in Positive;
Result : in out Parsed_Arguments) return Parser_Return
is
New_Pos : Parser_Return;
Raw : constant XString :=
Parse_One_Option (Short, Long, Args, Pos, New_Pos);
begin
if New_Pos /= Error_Return then
declare
Res : constant Internal_Result_Access :=
new Internal_Result'(Start_Pos => Pos,
End_Pos => Pos,
Result => Convert (+Raw));
begin
Result.Ref.Get.Results (Self.Position) :=
Res.all'Unchecked_Access;
end;
end if;
return New_Pos;
end Parse_Args;
begin
if Enabled then
Parser.Data.Opts_Parsers.Append (Self);
Parser.Data.All_Parsers.Append (Self);
Self.Position := Parser.Data.All_Parsers.Last_Index;
end if;
end Parse_Option_With_Default;
end GNATCOLL.Opt_Parse.Extension;
|
with GLOBE_3D;
package Box is
procedure Create (object : in out GLOBE_3D.p_Object_3D;
Sides : GLOBE_3D.Vector_3D := (1.0, 1.0, 1.0);
scale : GLOBE_3D.Real := 1.0;
centre : GLOBE_3D.Point_3D := (0.0, 0.0, 0.0));
end Box;
|
package body Server is
Count : Natural := 0;
procedure Foo is
begin
Count := Count + 1;
end Foo;
function Bar return Natural is
begin
return Count;
end Bar;
end Server;
|
-- kvflyweights-refcounted_lists.adb
-- A package of singly-linked reference-counting lists for the KVFlyweights
-- packages. Resources are associated with a key that can be used to create
-- them if they have not already been created.
-- Copyright (c) 2016, 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.
pragma Profile (No_Implementation_Extensions);
with Ada.Unchecked_Deallocation;
package body KVFlyweights.Refcounted_Lists is
procedure Deallocate_Key is new Ada.Unchecked_Deallocation(Object => Key,
Name => Key_Access);
procedure Deallocate_Value is new Ada.Unchecked_Deallocation(Object => Value,
Name => Value_Access);
procedure Deallocate_Node is new Ada.Unchecked_Deallocation(Object => Node,
Name => Node_Access);
procedure Insert (L : in out List;
K : in Key;
Key_Ptr : out Key_Access;
Value_Ptr : out Value_Access) is
Node_Ptr : Node_Access := L;
begin
if Node_Ptr = null then
-- List is empty:
-- Create a new node as the first list element
Key_Ptr := new Key'(K);
Value_Ptr := Factory(K);
L := new Node'(Next => null,
Key_Ptr => Key_Ptr,
Value_Ptr => Value_Ptr,
Use_Count => 1);
else
-- List is not empty
-- Loop over existing elements
loop
if K = Node_Ptr.Key_Ptr.all then
-- K's value is already in the KVFlyweight
Key_Ptr := Node_Ptr.Key_Ptr;
Value_Ptr := Node_Ptr.Value_Ptr;
Node_Ptr.Use_Count := Node_Ptr.Use_Count + 1;
exit;
elsif Node_Ptr.Next = null then
-- We have reached the end of the relevant bucket's list and K is
-- not already in the KVFlyweight, so add it.
Key_Ptr := new Key'(K);
Value_Ptr := Factory(K);
Node_Ptr.Next := new Node'(Next => null,
Key_Ptr => Key_Ptr,
Value_Ptr => Value_Ptr,
Use_Count => 1);
exit;
else
Node_Ptr := Node_Ptr.Next;
end if;
end loop;
end if;
end Insert;
procedure Increment (L : in out List;
Key_Ptr : in Key_Access) is
Node_Ptr : Node_Access := L;
begin
pragma Assert (Check => Node_Ptr /= null,
Message => "Attempting to increment reference counter " &
"but the element falls into an empty bucket");
-- Loop over existing elements, comparing keys by pointer rather than
-- by value as there should never be duplicate key values in a Flyweight
loop
if Key_Ptr = Node_Ptr.Key_Ptr then
Node_Ptr.Use_Count := Node_Ptr.Use_Count + 1;
exit;
elsif Node_Ptr.Next = null then
raise Program_Error with "Attempting to increment reference " &
"counter but the element is not in the relevant bucket's list";
else
Node_Ptr := Node_Ptr.Next;
end if;
end loop;
end Increment;
procedure Remove (L : in out List;
Key_Ptr : in Key_Access) is
Node_Ptr : Node_Access := L;
Last_Ptr : Node_Access;
begin
pragma Assert (Check => Node_Ptr /= null,
Message => "Attempting to remove an element from a null " &
"list.");
if Key_Ptr = Node_Ptr.Key_Ptr then
-- The element is the first in the list
Node_Ptr.Use_Count := Node_Ptr.Use_Count - 1;
if Node_Ptr.Use_Count = 0 then
Deallocate_Key(Node_Ptr.Key_Ptr);
Deallocate_Value(Node_Ptr.Value_Ptr);
L := Node_Ptr.Next; -- L might be set to null here - this is valid
Deallocate_Node(Node_Ptr);
end if;
elsif Node_Ptr.Next = null then
-- Element is not first in the list and there are no more elements
raise Program_Error with "Could not find element resource to " &
"decrement use count.";
else
-- Search remaining elements
Last_Ptr := Node_Ptr;
Node_Ptr := Node_Ptr.Next;
loop
if Key_Ptr = Node_Ptr.Key_Ptr then
Node_Ptr.Use_Count := Node_Ptr.Use_Count - 1;
if Node_Ptr.Use_Count = 0 then
Deallocate_Key(Node_Ptr.Key_Ptr);
Deallocate_Value(Node_Ptr.Value_Ptr);
Last_Ptr.Next := Node_Ptr.Next;
Deallocate_Node(Node_Ptr);
end if;
exit;
elsif Node_Ptr.Next = null then
raise Program_Error with "Could not find element resource to " &
"decrement use count.";
else
Last_Ptr := Node_Ptr;
Node_Ptr := Node_Ptr.Next;
end if;
end loop;
end if;
end Remove;
end KVFlyweights.Refcounted_Lists;
|
with Text_IO; use Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
with Spline;
procedure Spline_tst_1 is
type Real is digits 15;
package math is new Ada.Numerics.Generic_Elementary_Functions (Real);
use math;
package rio is new Float_IO (Real);
use rio;
type Index is range 1 .. 178;
type Data_Vector is array(Index) of Real;
package Sin_Spline is new Spline (Real, Index, Data_Vector);
use Sin_Spline;
X_Data, Y_Data : Data_Vector := (others => 0.0);
S : Spline_Coefficients;
Pii : constant Real := Ada.Numerics.Pi;
DeltaX : Real := Pii / (Real (Index'Last) - Real (Index'First));
X, Y : Real;
Y_true : Real;
dY, ddY : Real;
DeltaX1, DeltaX2, DeltaX3 : Real;
Integral_of_Sin, Err : Real;
Bound_First, Bound_Last : Boundary;
X_Stuff : X_Structure;
-- Requires Text_IO.
procedure Pause (s1,s2,s3,s4,s5,s6 : string := " ") is
Continuation : Character := ' ';
begin
Text_IO.New_Line;
if S1 /= " " then put_line (S1); end if;
if S2 /= " " then put_line (S2); end if;
if S3 /= " " then put_line (S3); end if;
if S4 /= " " then put_line (S4); end if;
if S5 /= " " then put_line (S5); end if;
if S6 /= " " then put_line (S6); end if;
Text_IO.New_Line;
begin
Text_IO.Put ("Type a character to continue: ");
Text_IO.Get_Immediate (Continuation);
exception
when others => null;
end;
Text_IO.New_Line;
end pause;
begin
-- Start by making natural splines
DeltaX := Pii / (Real (Index'Last) - Real (Index'First));
for I in Index loop
X := DeltaX * (Real (I) - Real(Index'First));
X_Data(I) := X;
Y_Data(I) := Sin (X);
end loop;
-- Natural boundary conditions:
Bound_First := (Alpha => 1.0, Beta => 0.0, Boundary_Val => 0.0);
Bound_Last := (Alpha => 1.0, Beta => 0.0, Boundary_Val => 0.0);
Prepare_X_Data (X_Stuff, X_Data, Index'First, Index'Last,
Bound_First, Bound_Last);
Get_Spline (S, X_Stuff, Y_Data);
-- Check that Spline is continuous
Pause
("Test 1: Verify that the Spline is continuous at the knots.",
"Recall that the spline equations were derived via this assumption",
"(along with the assumption that the first 2 derivatives of the curve",
"are also continuous at the knots.)");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
Y := Y_Data(I) + S.F(1)(I)*DeltaX1 + S.F(2)(I)*DeltaX2 + S.F(3)(I)*DeltaX3;
-- This is the Y at I+1 due to spline starting at point I.
-- Compare with Y at I+1 = Y_Data(I+1)
Put (Y - Y_Data(I+1)); New_Line;
end loop;
-- Check that derivative is continuous
Pause ("Verify that the derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
dY := S.F(1)(I) + 2.0*S.F(2)(I)*DeltaX1 + 3.0*S.F(3)(I)*DeltaX2;
-- This is the dY at I+1 due to spline starting at point I.
-- Compare with dY at I+1 = S.F(1)(I+1)
Put (dY - S.F(1)(I+1)); New_Line;
end loop;
-- Check that 2nd derivative is continuous
Pause ("Verify that the 2nd derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
ddY := 2.0*S.F(2)(I) + 6.0*S.F(3)(I)*DeltaX1;
-- This is the ddY at I+1 due to spline starting at point I.
-- Compare with ddY at I+1 = 2.0*S.F(2)(I+1)
Put (ddY - 2.0*S.F(2)(I+1)); New_Line;
end loop;
Pause ("Subtract Spline prediction from true value.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := Value_At (X, X_Data, Y_Data, S);
Y_true := Sin (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
Pause ("Subtract Spline prediction of 1st derivative from true value.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := First_Derivative_At (X, X_Data, S);
Y_true := Cos (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
Pause
("Subtract Spline prediction of 2nd derivative from true value.",
"You will notice that the error is much larger this time.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := Second_Derivative_At (X, X_Data, S);
Y_true := -Sin (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
-- Check quadrature:
Pause
("Test 1b: Calculate area under the curve.");
Integral_of_Sin := -(Cos (X_Data(Index'Last)) - Cos (X_Data(Index'First)));
Err := Abs (Integral_of_Sin - Integral (X_Data, Y_Data, S));
New_Line;
Put ("Error in numerical quadrature ="); Put (Err);
--Put (Integral_of_Sin); Put (Integral (X_Data, Y_Data, S));
New_Line;
-- make natural splines, test Cos.
DeltaX := Pii / (Real (Index'Last) - Real (Index'First));
for I in Index loop
X := DeltaX * (Real (I) - Real(Index'First));
X_Data(I) := X;
Y_Data(I) := Cos (X);
end loop;
-- Natural boundary conditions:
Bound_First := (Alpha => 1.0, Beta => 0.0, Boundary_Val => -1.0);
Bound_Last := (Alpha => 1.0, Beta => 0.0, Boundary_Val => 1.0);
Prepare_X_Data (X_Stuff, X_Data, Index'First, Index'Last,
Bound_First, Bound_Last);
Get_Spline (S, X_Stuff, Y_Data);
--Check that Spline is continuous
Pause
("Test 1c: Verify that the Spline is continuous at the knots.",
"In this test the boundary conditions are given by values of",
"the second derivative at the end points, but this second derivative",
"is not 0.0 as in the case of true natural splines.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
Y := Y_Data(I) + S.F(1)(I)*DeltaX1 + S.F(2)(I)*DeltaX2 + S.F(3)(I)*DeltaX3;
-- This is the Y at I+1 due to spline starting at point I.
-- Compare with Y at I+1 = Y_Data(I+1)
Put (Y - Y_Data(I+1)); New_Line;
end loop;
-- Check that derivative is continuous
Pause ("Verify that the derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
dY := S.F(1)(I) + 2.0*S.F(2)(I)*DeltaX1 + 3.0*S.F(3)(I)*DeltaX2;
-- This is the dY at I+1 due to spline starting at point I.
-- Compare with dY at I+1 = S.F(1)(I+1)
Put (dY - S.F(1)(I+1)); New_Line;
end loop;
-- Check that 2nd derivative is continuous
Pause ("Verify that the 2nd derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
ddY := 2.0*S.F(2)(I) + 6.0*S.F(3)(I)*DeltaX1;
-- This is the ddY at I+1 due to spline starting at point I.
-- Compare with ddY at I+1 = 2.0*S.F(2)(I+1)
Put (ddY - 2.0*S.F(2)(I+1)); New_Line;
end loop;
Pause ("Subtract Spline prediction from true value.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := Value_At (X, X_Data, Y_Data, S);
Y_true := Cos (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
-- Make mixed splines: natural at one end, clamped at the other.
DeltaX := 1.5 * Pii / (Real (Index'Last) - Real (Index'First));
for I in Index loop
X := DeltaX * (Real (I) - Real(Index'First));
X_Data(I) := X;
Y_Data(I) := Sin (X);
end loop;
-- Natural:
Bound_First := (Alpha => 1.0, Beta => 0.0, Boundary_Val => 0.0);
-- Clamped with derivative = 0.0:
Bound_Last := (Alpha => 0.0, Beta => 1.0, Boundary_Val => 0.0);
Prepare_X_Data (X_Stuff, X_Data, Index'First, Index'Last,
Bound_First, Bound_Last);
Get_Spline (S, X_Stuff, Y_Data);
-- Verify that Spline is continuous:
Pause
("Test 2: Verify that the mixed-boundary Spline is continuous at the knots.",
"Recall that the spline equations were derived via this assumption",
"(along with the assumption that the first 2 derivatives of the curve",
"are also continuous at the knots.)");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
Y := Y_Data(I) + S.F(1)(I)*DeltaX1 + S.F(2)(I)*DeltaX2 + S.F(3)(I)*DeltaX3;
-- This is the Y at I+1 due to spline starting at point I.
-- Compare with Y at I+1 = Y_Data(I+1)
Put (Y - Y_Data(I+1)); New_Line;
end loop;
-- Check that derivative is continuous:
Pause ("Verify that the derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
dY := S.F(1)(I) + 2.0*S.F(2)(I)*DeltaX1 + 3.0*S.F(3)(I)*DeltaX2;
-- This is the dY at I+1 due to spline starting at point I.
-- Compare with dY at I+1 = S.F(1)(I+1)
Put (dY - S.F(1)(I+1)); New_Line;
end loop;
-- Check that 2nd derivative is continuous:
Pause ("Verify that the 2nd derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
ddY := 2.0*S.F(2)(I) + 6.0*S.F(3)(I)*DeltaX1;
-- This is the ddY at I+1 due to spline starting at point I.
-- Compare with ddY at I+1 = 2.0*S.F(2)(I+1)
Put (ddY - 2.0*S.F(2)(I+1)); New_Line;
end loop;
Pause ("Subtract Spline prediction from true value.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := Value_At (X, X_Data, Y_Data, S);
Y_true := Sin (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
-- Make mixed splines: natural at one end, clamped at the other.
-- This time we get them wrong.
DeltaX := 1.5 * Pii / (Real (Index'Last) - Real (Index'First));
for I in Index loop
X := DeltaX * (Real (I) - Real(Index'First));
X_Data(I) := X;
Y_Data(I) := Sin (X);
end loop;
-- Now we have the boundary conditions wrong for the Sin curve:
-- Natural:
Bound_First := (Alpha => 0.0, Beta => 1.0, Boundary_Val => 0.0);
-- Clamped with derivative = 1.0:
Bound_Last := (Alpha => 1.0, Beta => 0.0, Boundary_Val => 0.0);
Prepare_X_Data (X_Stuff, X_Data, Index'First, Index'Last,
Bound_First, Bound_Last);
Get_Spline (S, X_Stuff, Y_Data);
--Check that Spline is continuous:
Pause
("Test 3: Make sure the mixed-boundary Spline is continuous at the knots.",
"Recall that the spline equations were derived via this assumption",
"(along with the assumption that the first 2 derivatives of the curve",
"are also continuous at the knots.)");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
Y := Y_Data(I) + S.F(1)(I)*DeltaX1 + S.F(2)(I)*DeltaX2 + S.F(3)(I)*DeltaX3;
-- This is the Y at I+1 due to spline starting at point I.
-- Compare with Y at I+1 = Y_Data(I+1)
Put (Y - Y_Data(I+1)); New_Line;
end loop;
-- Check that derivative is continuous:
Pause ("Verify that the derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
dY := S.F(1)(I) + 2.0*S.F(2)(I)*DeltaX1 + 3.0*S.F(3)(I)*DeltaX2;
-- This is the dY at I+1 due to spline starting at point I.
-- Compare with dY at I+1 = S.F(1)(I+1)
Put (dY - S.F(1)(I+1)); New_Line;
end loop;
-- Check that 2nd derivative is continuous:
Pause ("Verify that the 2nd derivative of the spline is continuous.");
for I in Index'First .. Index'Last-1 loop
DeltaX1 := X_Data(I+1) - X_Data(I);
DeltaX2 := DeltaX1*DeltaX1;
DeltaX3 := DeltaX1*DeltaX2;
ddY := 2.0*S.F(2)(I) + 6.0*S.F(3)(I)*DeltaX1;
-- This is the ddY at I+1 due to spline starting at point I.
-- Compare with ddY at I+1 = 2.0*S.F(2)(I+1)
Put (ddY - 2.0*S.F(2)(I+1)); New_Line;
end loop;
Pause
("Subtract Spline prediction from true value.",
"In this test we deliberately made the Boundary conditions",
"wrong, so the answers should be dreadful at the end points.");
for I in Index'first .. Index'last-1 loop
X := X_Data(I) + DeltaX/2.0;
Y := Value_At (X, X_Data, Y_Data, S);
Y_true := Sin (X);
Put (Y - Y_true); New_Line;
end loop;
New_line;
end;
|
pragma SPARK_Mode;
with Interfaces.C; use Interfaces.C;
with Types; use Types;
-- @summary
-- This package exposes many Arduino runtime routines to Ada
--
-- @description
-- This package imports all of the necessary Arduino runtime library calls
-- that are needed.
--
package Sparkduino is
-- Configures the specified pin to behave either as an input or an output
-- @param Pin the number of the pin whose mode you wish to set
-- @param Mode use PinMode'Pos (io_mode) where io_mode is of type PinMode
-- see Types package for more info
procedure SetPinMode (Pin : unsigned_char;
Mode : unsigned_char)
with Global => null;
pragma Import (C, SetPinMode, "pinMode");
-- Write a HIGH or a LOW value to a digital pin.
-- @param Pin the pin number
-- @param Val use DigPinValue'Pos (state) where state is of type
-- DigPinValue see Types package for more info
procedure DigitalWrite (Pin : unsigned_char;
Val : unsigned_char)
with Global => null;
pragma Import (C, DigitalWrite, "digitalWrite");
-- Reads the value from a specified digital pin, either HIGH or LOW.
-- @param Pin the number of the digital pin you want to read
-- @return an Integer that maps to HIGH or LOW with DigPinValue'Pos
function DigitalRead (Pin : unsigned_char) return Integer
with Global => null;
pragma Import (C, DigitalRead, "digitalRead");
-- Returns the number of milliseconds since the Arduino board began running
-- the current program. This number will overflow (go back to zero),
-- after approximately 50 days.
-- @return Number of milliseconds since the program started (unsigned long)
function Millis return unsigned_long
with Global => null;
pragma Import (C, Millis, "millis");
-- Returns the number of microseconds since the Arduino board began
-- running the current program. This number will overflow
-- (go back to zero), after approximately 70 minutes. On 16 MHz Arduino
-- boards (e.g. Duemilanove and Nano), this function has a resolution of
-- four microseconds (i.e. the value returned is always a multiple of
-- four). On 8 MHz Arduino boards (e.g. the LilyPad), this function has
-- a resolution of eight microseconds.
-- @return Returns the number of microseconds since the Arduino board began
-- running the current program. (unsigned long)
function Micros return unsigned_long
with Global => null;
pragma Import (C, Micros, "micros");
-- Pauses the program for the amount of time
-- @param Time the number of microseconds to pause
procedure DelayMicroseconds (Time : unsigned)
with Global => null;
pragma Import (C, DelayMicroseconds, "delayMicroseconds");
-- Pauses the program for the amount of time (in milliseconds)
-- @param Time the number of milliseconds to pause
procedure SysDelay (Time : unsigned_long)
with Global => null;
pragma Import (C, SysDelay, "delay");
-- AVR specific call which temporarily disables interrupts.
procedure SEI;
pragma Import (C, SEI, "sei_wrapper");
-- Print a string to the serial console
-- @param Msg the string to print
procedure Serial_Print (Msg : String)
with SPARK_Mode => Off;
-- Print a byte to the serial console
-- @param Msg the string to prepend
-- @param Val the byte to print
procedure Serial_Print_Byte (Msg : String;
Val : Byte)
with SPARK_Mode => Off;
-- Print a short to the serial console
-- @param Msg the string to prepend
-- @param Val the short to print
procedure Serial_Print_Short (Msg : String;
Val : short)
with SPARK_Mode => Off;
-- Print a float to the serial console
-- @param Msg the string to prepend
-- @param Val the float to print
procedure Serial_Print_Float (Msg : String;
Val : Float)
with SPARK_Mode => Off;
-- Print the format calibration data to the serial console
-- @param Index the specific sensor calibration data to print
-- @param Min the min sensor value in the calibration record
-- @param Max the max sensor value in the calibration record
procedure Serial_Print_Calibration (Index : Integer;
Min : Sensor_Value;
Max : Sensor_Value);
pragma Import (C, Serial_Print_Calibration, "Serial_Print_Calibration");
-- analog pin mappings
A0 : constant := 14;
A1 : constant := 15;
A2 : constant := 16;
A3 : constant := 17;
A4 : constant := 18;
A5 : constant := 19;
A6 : constant := 20;
A7 : constant := 21;
end Sparkduino;
|
--------------------------------------------------------------------------------
-- --
-- Copyright (C) 2004, RISC OS Ada Library (RASCAL) developers. --
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU Lesser General Public --
-- License as published by the Free Software Foundation; either --
-- version 2.1 of the License, or (at your option) any later version. --
-- --
-- This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU --
-- Lesser General Public License for more details. --
-- --
-- You should have received a copy of the GNU Lesser General Public --
-- License along with this library; if not, write to the Free Software --
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
--------------------------------------------------------------------------------
-- @brief Interface to host RISC OS
-- $Author$
-- $Date$
-- $Revision$
-- --------------------------------------------------------------------------
-- THIS FILE AND ANY ASSOCIATED DOCUMENTATION IS PROVIDED "AS IS" WITHOUT
-- WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-- TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
-- PARTICULAR PURPOSE. The user assumes the entire risk as to the accuracy
-- and the use of this file.
--
-- Ada version Copyright (c) P.J.Burwood, 1996
-- Royalty-free, unlimited, worldwide, non-exclusive use, modification,
-- reproduction and further distribution of this Ada file is permitted.
--
-- C version contains additional copyrights, see below
-- --------------------------------------------------------------------------
with Interfaces.C;
with System;
package Kernel is
subtype void is System.Address;
subtype void_ptr is System.Address;
subtype void_ptr_ptr is System.Address;
--
-- kernel.h:18
--
type vector_of_c_signed_int is
array (integer range <>) of Interfaces.C.int;
--
-- only r0 - r9 matter for swi's
-- kernel.h:19
--
type SWI_Regs is
record
R : vector_of_c_signed_int (0 .. 9);
end record;
pragma Convention (C, SWI_Regs);
--
-- error number
-- error message (zero terminated)
-- kernel.h:36
--
type oserror is
record
ErrNum : Interfaces.C.int;
ErrMess : Interfaces.C.char_array (0 .. 251);
end record;
pragma Convention (C, oserror);
type oserror_access is access all oserror;
-- kernel.h:83
kernel_NONX : constant Interfaces.C.unsigned := 16#80000000#;
--
-- Generic SWI interface. Returns NULL if there was no error.
-- The SWI called normally has the X bit set. To call a non-X bit set SWI,
-- kernel_NONX must be orred into no (in which case, if an error occurs,
-- swi does not return).
--
function swi (no : Interfaces.C.unsigned;
r_in : access SWI_Regs;
r_out : access SWI_Regs)
return oserror_access;
procedure swi (no : Interfaces.C.unsigned;
r_in : access SWI_Regs;
r_out : access SWI_Regs);
--
-- As swi, but for use with SWIs which return status in the C flag.
-- The int to which carry points is set
-- to reflect the state of the C flag on
-- exit from the SWI.
--
function swi_c (no : Interfaces.C.unsigned;
r_in : access SWI_Regs;
r_out : access SWI_Regs;
carry : access Interfaces.C.int)
return oserror_access;
procedure swi_c (no : Interfaces.C.unsigned;
r_in : access SWI_Regs;
r_out : access SWI_Regs;
carry : access Interfaces.C.int);
--
-- Returns a pointer to an error block describing the last os error since
-- last_oserror was last called (or since the program started if there has
-- been no such call). If there has been no os error, returns a null
-- pointer. Note that occurrence of a further error may overwrite the
-- contents of the block.
-- If swi caused the last os error, the error already returned by that call
-- gets returned by this too.
--
function last_oserror return oserror_access; -- kernel.h:199
private
-- kernel.h:84
pragma Import (C, swi, "_kernel_swi");
-- kernel.h:93
pragma Import (C, swi_c, "_kernel_swi_c");
-- kernel.h:199
pragma Import (C, last_oserror, "_kernel_last_oserror");
--
-- Interface to host OS.
-- Copyright (C) Acorn Computers Ltd., 1990
--
end Kernel;
|
pragma Warnings (Off);
pragma Style_Checks (Off);
with GL.Buffer.general;
with GL.Geometry;
package GL.Buffer.vertex is new GL.Buffer.general (base_object => GL.Buffer.array_Object,
index => GL.geometry.positive_vertex_Id,
element => GL.geometry.GL_Vertex,
element_array => GL.geometry.GL_vertex_Array);
|
-- Copyright (c) 2020-2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- 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.
-- ****h* Tcl/Variables
-- FUNCTION
-- Provides binding to manipulate Tcl variables (setting, getting, removing,
-- etc)
-- SOURCE
package Tcl.Variables is
-- ****
--## rule off REDUCEABLE_SCOPE
-- ****t* Variables/Variables.Variables_Flags
-- FUNCTION
-- Available flags for manipulation of Tcl variables
-- OPTIONS
-- NONE - No flags sets
-- TCL_GLOBAL_ONLY - Look only for global Tcl variables
-- TCL_NAMESPACE_ONLY - Look only for Tcl variables in current Tcl namespace
-- TCL_APPEND_VALUE - Append a new value to the current Tcl variable value
-- instead of replacing it
-- TCL_LIST_ELEMENT - The new value is a list element. Before adding it is
-- converted to the proper Tcl list value (added space
-- if needed, etc)
-- TCL_LEAVE_ERR_MSG - If error is returned, leave error message so it can
-- be retrieved with proper subprograms
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
type Variables_Flags is
(NONE, TCL_GLOBAL_ONLY, TCL_NAMESPACE_ONLY, TCL_APPEND_VALUE,
TCL_LIST_ELEMENT, TCL_LEAVE_ERR_MSG) with
Default_Value => NONE;
for Variables_Flags use
(NONE => 16#0000#, TCL_GLOBAL_ONLY => 16#0001#,
TCL_NAMESPACE_ONLY => 16#0002#, TCL_APPEND_VALUE => 16#0004#,
TCL_LIST_ELEMENT => 16#0008#, TCL_LEAVE_ERR_MSG => 16#0200#);
-- ****
-- ****d* Variables/Variables.Default_Flag
-- FUNCTION
-- Default flag for Tcl variables
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
Default_Flag: constant Variables_Flags := NONE;
-- ****
-- ****t* Variables/Variables.Flags_Array
-- FUNCTION
-- Used as to set flags for Tcl variables manipulation subprograms
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
type Flags_Array is array(Positive range <>) of Variables_Flags with
Default_Component_Value => Default_Flag;
-- ****
-- ****d* Variables/Variables.Default_Flags_Array
-- FUNCTION
-- Default flags array
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
Default_Flags_Array: constant Flags_Array(1 .. 1) := (1 => Default_Flag);
-- ****
-- ****f* Variables/Variables.Tcl_Set_Var
-- FUNCTION
-- Set value for the selected Tcl variable
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to set. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- New_Value - A new value for the selected Tcl variable to set. Cannot
-- empty.
-- Interpreter - Tcl interpreter on which the result will be set. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in setting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- True if variable was set or created, otherwise False
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Set the value of the Tcl variable $myvar to 2 on default Tcl interpreter
-- if not Tcl_Set_Var("myvar", "2") then
-- Ada.Text_IO.Put_Line("Can't set value for Tcl variable myvar.");
-- end if;
-- SOURCE
function Tcl_Set_Var
(Var_Name, New_Value: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Boolean with
Pre => Var_Name'Length > 0 and New_Value'Length > 0 and
Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_SetVar", Mode => Nominal);
-- ****
-- ****f* Variables/Variables.Tcl_Set_Var2
-- FUNCTION
-- Set value for the selected Tcl variable in the selected array
-- PARAMETERS
-- Array_Name - Name of the Tcl array in which the value will be set.
-- Cannot be empty.
-- Index_Name - Name of the index of element in the Tcl array which
-- the value will be set. Cannot be empty.
-- New_Value - A new value for the selected Tcl variable to set.
-- Cannot empty.
-- Interpreter - Tcl interpreter on which the result will be set. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in setting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- True if variable was set or created, otherwise False
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Set the value of the third element in Tcl array $myarray to 5 on default Tcl interpreter
-- if not Tcl_Set_Var2("myarray", "2", "5") then
-- Ada.Text_IO.Put_Line("Can't set third element in Tcl array $myarray.");
-- end if;
-- SOURCE
function Tcl_Set_Var2
(Array_Name, Index_Name, New_Value: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Boolean with
Pre => Array_Name'Length > 0 and Index_Name'Length > 0 and
New_Value'Length > 0 and Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_SetVar2", Mode => Nominal);
-- ****
-- ****f* Variables/Variables.Tcl_Get_Var_(String)
-- FUNCTION
-- Get the value for the selected Tcl variable as a String
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- String with the value of the selected Tcl variable. If there no
-- variable with that name, return empty String.
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the Tcl variable $myvar on default Tcl interpreter
-- Value: constant String := Tcl_Get_Var("myvar");
-- SOURCE
function Tcl_Get_Var
(Var_Name: String; Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return String with
Pre => Var_Name'Length > 0 and Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_GetVar", Mode => Nominal);
-- ****
-- ****g* Tcl/Tcl.Generic_Scalar_Tcl_Get_Var
-- FUNCTION
-- Generic function to get the value of Tcl variable as a scalar type
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- Scalar type result with the value of Tcl variable
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the variable $myvar the default Tcl interpreter as Integer
-- function Integer_Get_Var is new Generic_Scalar_Tcl_Get_Var(Integer);
-- Variable: constant Integer := Integer_Get_Var("myvar");
-- SEE ALSO
-- Tcl.Generic_Float_Tcl_Get_Var;
-- SOURCE
generic
type Result_Type is (<>);
function Generic_Scalar_Tcl_Get_Var
(Var_Name: String; Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Result_Type;
-- ****
-- ****g* Tcl/Tcl.Generic_Float_Tcl_Get_Var
-- FUNCTION
-- Generic function to get the value of Tcl variable as a float type
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- Float type result with the value of Tcl variable
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the variable $myvar the default Tcl interpreter as Float
-- function Float_Get_Var is new Generic_Float_Tcl_Get_Var(Float);
-- Variable: constant Float := Integer_Get_Var("myvar");
-- SEE ALSO
-- Tcl.Generic_Scalar_Tcl_Get_Var;
-- SOURCE
generic
type Result_Type is digits <>;
function Generic_Float_Tcl_Get_Var
(Var_Name: String; Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Result_Type;
-- ****
-- ****f* Variables/Variables.Tcl_Get_Var2_(String)
-- FUNCTION
-- Get the value for the selected Tcl variable in the selected array as String
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Index_Name - Name of the index of element in the Tcl array which
-- the value will be get. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- String with the value of the selected Tcl array element variable
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the third element in the Tcl array $myarray on default Tcl interpreter
-- Value: constant String := Tcl_GetVar2("myarray", "2");
-- SOURCE
function Tcl_Get_Var2
(Var_Name, Index_Name: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return String with
Pre => Var_Name'Length > 0 and Index_Name'Length > 0 and
Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_GetVar2", Mode => Nominal);
-- ****
-- ****g* Tcl/Tcl.Generic_Scalar_Tcl_Get_Var2
-- FUNCTION
-- Generic function to get the value of Tcl variable as a scalar type
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Index_Name - Name of the index of element in the Tcl array which
-- the value will be get. Cannot be empty.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- Scalar type result with the value of Tcl variable
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the variable $myvar the default Tcl interpreter as Integer
-- function Integer_Get_Var is new Generic_Scalar_Tcl_Get_Var2(Integer);
-- Variable: constant Integer := Integer_Get_Var("myvar");
-- SEE ALSO
-- Tcl.Generic_Float_Tcl_Get_Var2;
-- SOURCE
generic
type Result_Type is (<>);
function Generic_Scalar_Tcl_Get_Var2
(Var_Name, Index_Name: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Result_Type;
-- ****
-- ****g* Tcl/Tcl.Generic_Float_Tcl_Get_Var2
-- FUNCTION
-- Generic function to get the value of Tcl variable in the selected array as a float type
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to get. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Index_Name - Name of the index of element in the Tcl array which
-- the value will be get. Cannot be empty.
-- Interpreter - Tcl interpreter on which the result will be get. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in getting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- Float type result with the value of Tcl variable
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Get the value of the variable $myvar the default Tcl interpreter as Float
-- function Float_Get_Var is new Generic_Float_Tcl_Get_Var2(Float);
-- Variable: constant Float := Integer_Get_Var2("myvar");
-- SEE ALSO
-- Tcl.Generic_Scalar_Tcl_Get_Var2;
-- SOURCE
generic
type Result_Type is digits <>;
function Generic_Float_Tcl_Get_Var2
(Var_Name, Index_Name: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Result_Type;
-- ****
-- ****f* Variables/Variables.Tcl_Unset_Var
-- FUNCTION
-- Delete the selected Tcl variable
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to delete. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Interpreter - Tcl interpreter on which the variable will be deleted. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in deleting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- True if the selected Tcl variable was succesfully unset, otherwise
-- False
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Delete the Tcl variable $myvar on default Tcl interpreter
-- if not Tcl_Unset_Var("myvar") then
-- Ada.Text_IO.Put_Line("Can't delete Tcl variable $myvar");
-- end if;
-- SOURCE
function Tcl_Unset_Var
(Var_Name: String; Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Boolean with
Pre => Var_Name'Length > 0 and Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_UnsetVar", Mode => Nominal);
-- ****
-- ****f* Variables/Variables.Tcl_Unset_Var2
-- FUNCTION
-- Delete the selected Tcl variable in the selected Tcl array
-- PARAMETERS
-- Var_Name - Name of the Tcl variable to delete. If contains open and
-- close parenthesis it will be treated as index of the item
-- in the array. Cannot be empty.
-- Index_Name - Name of the index of element in the Tcl array which
-- will be deleted. Cannot be empty.
-- Interpreter - Tcl interpreter on which the variable will be deleted. By
-- default it is current default Tcl interpreter.
-- Flags - Array of flags used in deleting variable. Can be empty.
-- Default value is one element array NONE
-- RESULT
-- True if the selected Tcl variable was succesfully unset, otherwise
-- False
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Delete the third element in the Tcl array $myarray on default Tcl interpreter
-- if not Tcl_Unset_Var("myarray", "2") then
-- Ada.Text_IO.Put_Line("Can't unset the third element in Tcl array $myarray");
-- end if;
-- SOURCE
function Tcl_Unset_Var2
(Var_Name, Index_Name: String;
Interpreter: Tcl_Interpreter := Get_Interpreter;
Flags: Flags_Array := Default_Flags_Array) return Boolean with
Pre => Var_Name'Length > 0 and Index_Name'Length > 0 and
Interpreter /= Null_Interpreter,
Test_Case => (Name => "Test_Tcl_UnsetVar2", Mode => Nominal);
-- ****
--## rule on REDUCEABLE_SCOPE
end Tcl.Variables;
|
-- Ada regular expression library
-- (c) Kristian Klomsten Skordal 2020 <kristian.skordal@wafflemail.net>
-- Report bugs and issues on <https://github.com/skordal/ada-regex>
with Regex.State_Machines;
with Regex.Syntax_Trees;
package Regex.Debug is
-- Prints the parse tree for the regular expression:
procedure Print_Syntax_Tree (Root : in Regex.Syntax_Trees.Syntax_Tree_Node_Access);
-- Prints the state machine for the regular expression:
procedure Print_State_Machine (States : in Regex.State_Machines.State_Machine_State_Vectors.Vector);
private
-- Prints the contents of a state machine state:
procedure Print_State (State : in Regex.State_Machines.State_Machine_State);
end Regex.Debug;
|
package SDL is
pragma Linker_Options("-lSDL");
type Capabilities is mod 2 ** 31;
for Capabilities'Size use 32;
pragma Convention(C, Capabilities);
Timer : Capabilities := 16#0000_0001#;
Audio : Capabilities := 16#0000_0010#;
Video : Capabilities := 16#0000_0020#;
CDROM : Capabilities := 16#0000_0100#;
Joystick : Capabilities := 16#0000_0200#;
function Init(Flags : in Capabilities) return Boolean;
procedure Quit;
end SDL;
|
------------------------------------------------------------------------------
-- --
-- J E W L . W I N D O W S --
-- --
-- The body of the GUI package for use with Microsoft Windows. --
-- --
-- All window types contain a Controlled_Type object, which contains a --
-- pointer to a Reference_Counted_Type. The type Window_Internals is --
-- derived from Reference_Counted_Type to provide the internal data --
-- structures needed for all windows, and further derivations are made --
-- for specific types of window. Since Reference_Counted_Type is a --
-- controlled type, all derivations must occur at library level, so --
-- this is done in a separate non-generic private package which also --
-- contains other implementation details used by this package body. --
-- Even so, this is a large package! --
-- --
-- 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-windows.adb 1.7 2007/01/08 17:00:00 JE Exp $
------------------------------------------------------------------------------
--
-- $Log: jewl-windows.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 JEWL.Window_Implementation; use JEWL.Window_Implementation;
with JEWL.Message_Handling; use JEWL.Message_Handling;
with JEWL.Canvas_Implementation; use JEWL.Canvas_Implementation;
with JEWL.Win32_Interface; use JEWL.Win32_Interface;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Tags; use Ada.Tags;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with System;
package body JEWL.Windows is
use type System.Address;
use type Ada.Streams.Stream_Element_Offset;
use type Win32_BOOL, Win32_LONG, Win32_WORD,
Win32_UINT, Win32_SIZE, Win32_DWORD;
----------------------------------------------------------------------------
-- Win32 window class names
----------------------------------------------------------------------------
Frame_Class : constant Win32_String := To_Array("JEWL.Windows.Frame");
Dialog_Class : constant Win32_String := To_Array("JEWL.Windows.Dialog");
Canvas_Class : constant Win32_String := To_Array("JEWL.Windows.Canvas");
----------------------------------------------------------------------------
-- End-of-line string
----------------------------------------------------------------------------
EOL : constant String := ASCII.CR & ASCII.LF;
----------------------------------------------------------------------------
--
-- M I S C E L L A N E O U S R O U T I N E S
--
----------------------------------------------------------------------------
--
-- Show_Error: display a message box with an OK button and stop sign.
--
procedure Show_Error (Text : in String;
Title : in String := "Error") is
I : Integer;
begin
I := Message_Box (Text, Title, MB_OK+MB_ICONSTOP);
end Show_Error;
----------------------------------------------------------------------------
--
-- Show_Query: display a message box with Yes/No buttons and a question
-- mark.
--
function Show_Query (Text : in String;
Title : in String := "Query") return Boolean is
begin
return Message_Box (Text, Title, MB_YESNO+MB_ICONQUESTION) = IDYES;
end Show_Query;
----------------------------------------------------------------------------
--
-- Show_Message: display a message box with an OK button and an
-- information sign.
--
procedure Show_Message (Text : in String;
Title : in String := "Message") is
I : Integer;
begin
I := Message_Box (Text, Title, MB_OK+MB_ICONINFORMATION);
end Show_Message;
----------------------------------------------------------------------------
--
-- Play_Sound: play a sound held in a wave file.
--
procedure Play_Sound (Sound : in String) is
begin
Bool_Dummy := PlaySound (To_LPCSTR(To_Array(Sound)), System.Null_Address,
SND_FILENAME + SND_NODEFAULT + SND_ASYNC);
end Play_Sound;
----------------------------------------------------------------------------
--
-- Screen_Width: get width of display screen in pixels.
--
function Screen_Width return Natural is
begin
return Natural(GetSystemMetrics(SM_CXSCREEN));
end Screen_Width;
----------------------------------------------------------------------------
--
-- Screen_Height: get height of display screen in pixels.
--
function Screen_Height return Natural is
begin
return Natural(GetSystemMetrics(SM_CYSCREEN));
end Screen_Height;
----------------------------------------------------------------------------
--
-- I N T E R N A L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Get_Internals: check that a window has been initialised and return a
-- pointer to its Window_Internals structure, or raise an
-- Invalid_Window exception. Additional parameters are
-- used to generate a meaningful message to accompany
-- the exception.
--
function Get_Internals (Window : in Window_Type'Class;
Operation : in String) return Window_Ptr is
begin
if Window.Internals.Pointer = null then
Raise_Exception (Invalid_Window'Identity,
External_Tag(Window'Tag) &
": window not initialised in call to " & Operation);
end if;
return Window_Ptr(Window.Internals.Pointer);
end Get_Internals;
----------------------------------------------------------------------------
--
-- Get_Internals: check that a common dialog has been initialised and
-- return a pointer to its Common_Dialog_Internals, or
-- raise an Invalid_Window exception. Additional parameters
-- are used to generate a meaningful message to accompany
-- the exception.
--
function Get_Internals (Dialog : in Common_Dialog_Type'Class;
Operation : in String) return Common_Dialog_Ptr is
begin
if Dialog.Internals.Pointer = null then
Raise_Exception (Invalid_Window'Identity,
External_Tag(Dialog'Tag) &
": dialog not initialised in call to " & Operation);
end if;
return Common_Dialog_Ptr(Dialog.Internals.Pointer);
end Get_Internals;
----------------------------------------------------------------------------
--
-- Add: add an object to the end of a canvas drawing list and invalidate
-- the canvas window so it will be repainted. The second parameter
-- enables the actual operation name to be passed to Get_Internals.
--
procedure Add (Canvas : in Canvas_Type;
Operation : in String;
Object : in Canvas_Object_Ptr) is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, Operation));
begin
C.Monitor.Add (Object);
Bool_Dummy := InvalidateRect (C.Handle, null, 1);
end;
----------------------------------------------------------------------------
--
-- Create_Child: create a child window with specified characteristics.
-- The last parameter enables the actual operation name
-- to be passed to Get_Internals.
--
procedure Create_Child (Window : in out Window_Type'Class;
Parent : in Container_Type'Class;
Class : in String;
Title : in String;
XStyle : in Win32_DWORD;
Style : in Win32_DWORD;
Origin : in Point_Type;
Width : in Integer;
Height : in Integer;
Font : in Font_Type;
ID : in Integer;
Operation : in String) is
P : Container_Ptr := Container_Ptr (Get_Internals (Parent, Operation));
X : Window_Ptr := Get_Internals (Window, Operation);
T : Integer := Origin.Y;
L : Integer := Origin.X;
H : Integer := Height;
W : Integer := Width;
B : Boolean;
C : Win32_String := To_Array(Class);
N : Win32_String := To_Array(Title);
begin
-- Fill in links to parent and siblings
X.Parent := P;
if P.Last = null then
P.First := Window.Internals;
else
P.Last.Next := Window.Internals;
end if;
P.Last := X;
-- Fill in the command code associated with this window
X.Action := ID;
-- Fill in the window dimensions
X.Top := Origin.Y;
X.Left := Origin.X;
X.Height := Height;
X.Width := Width;
-- Calculate the actual window dimensions (the dimensions given may be
-- relative to the parent window)
Get_Actual_Bounds (P.Handle, T, L, W, H, B);
-- Ask the message loop task to create the child window
Message_Loop.Create_Child (X, P, C, N, XStyle, Style, T, L, W, H);
-- Create the font, or use the parent font if no font name is given
if Font.Length > 0 then
Set_Font (Window, Font);
else
X.Font := System.Null_Address;
end if;
end Create_Child;
----------------------------------------------------------------------------
--
-- I M A G E O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Image: load a bitmap image from a specified file.
--
function Image (Name : String) return Image_Type is
subtype Offset is Ada.Streams.Stream_Element_Offset;
subtype Elements is Ada.Streams.Stream_Element_Array;
Image : Image_Type;
File : Ada.Streams.Stream_IO.File_Type;
Stream : Ada.Streams.Stream_IO.Stream_Access;
Header : Win32_BITMAPFILEHEADER;
Info : aliased Win32_BITMAPINFOHEADER;
Colours : Offset;
Bytes : Offset;
Bitmap : Win32_HBITMAP;
Pointer : Image_Ptr;
begin
Image.Internals.Pointer := null;
-- Create a stream to read the bitmap file
Ada.Streams.Stream_IO.Open (File, Name => Name, Mode => In_File);
Stream := Ada.Streams.Stream_IO.Stream (File);
-- Read and check the file header
Win32_BITMAPFILEHEADER'Read (Stream, Header);
if Header.bfType /= BITMAP_MAGIC then
raise Data_Error;
end if;
-- Read and check the bitmap info header
Win32_BITMAPINFOHEADER'Read (Stream, Info);
if Info.biSize /= Info'Size/Win32_BYTE'Size or Info.biPlanes /= 1 then
raise Data_Error;
end if;
-- Calculate no. of colour table entries following the info header
if Info.biClrUsed /= 0 then
Colours := Offset(Info.biClrUsed);
elsif Info.biBitCount <= 8 then
Colours := Offset(2 ** Integer(Info.biBitCount));
elsif Info.biCompression = BI_BITFIELDS then
Colours := 3;
else
Colours := 0;
end if;
-- Calculate size of bitmap data
Bytes := Offset(Info.biSizeImage);
if Bytes = 0 then
Bytes := (Offset(Info.biWidth) * Offset(Info.biBitCount) + 31) / 32
* Offset(Info.biHeight);
end if;
-- Process the rest of the file
declare
C : Elements (1 .. Colours * 4 + Offset(Info.biSize));
D : Elements (1 .. Offset(Bytes));
E : Offset;
P : Win32_BITMAPINFOHEADER; for P'Address use C(1)'Address;
H : Win32_HDC;
begin
-- Copy the bitmap info header into the header block
P := Info;
-- Read the colour table into the header block
Ada.Streams.Read (Stream.all, C (Offset(Info.biSize)+1 .. C'Last), E);
if E /= C'Length then
raise Data_Error;
end if;
-- Read the rest of the file into the data block
Ada.Streams.Read (Stream.all, D, E);
if E /= D'Length then
raise Data_Error;
end if;
-- Get a device context for the display
H := CreateDC (To_LPCSTR(To_Array("DISPLAY")),
null, null, System.Null_Address);
if H = System.Null_Address then
raise Data_Error;
end if;
-- Create the bitmap using the display context
Bitmap := CreateDIBitmap (H, Info'Unchecked_Access, CBM_INIT,
D(1)'Address, C(1)'Address, DIB_RGB_COLORS);
if Bitmap = System.Null_Address then
raise Data_Error;
end if;
end;
-- Fill in image structure
Pointer := new Image_Internals;
Pointer.Image := Bitmap;
Pointer.Width := Natural(Info.biWidth);
Pointer.Height := Natural(Info.biHeight);
Image.Internals.Pointer := Reference_Counted_Ptr(Pointer);
Close (File);
return Image;
exception
when others =>
Close (File);
return Image;
end Image;
----------------------------------------------------------------------------
--
-- Valid: get the width of the specified image.
--
function Valid (Image : Image_Type) return Boolean is
begin
return Image.Internals.Pointer /= null;
end Valid;
----------------------------------------------------------------------------
--
-- Width: get the width of the specified image.
--
function Width (Image : Image_Type) return Natural is
begin
if Valid(Image) then
return Image_Internals(Image.Internals.Pointer.all).Width;
else
return 0;
end if;
end Width;
----------------------------------------------------------------------------
--
-- Height: get the height of the specified image.
--
function Height (Image : Image_Type) return Natural is
begin
if Valid(Image) then
return Image_Internals(Image.Internals.Pointer.all).Height;
else
return 0;
end if;
end Height;
----------------------------------------------------------------------------
--
-- W I N D O W O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Show: make a window visible or invisible, bringing visible windows to
-- the foreground.
--
procedure Show (Window : in Window_Type;
Visible : in Boolean := True) is
P : Window_Ptr := Get_Internals (Window, "Show");
begin
if Visible then
Bool_Dummy := ShowWindow(P.Handle,SW_SHOW);
Bool_Dummy := SetForegroundWindow (P.Handle);
else
Bool_Dummy := ShowWindow(P.Handle,SW_HIDE);
end if;
end Show;
----------------------------------------------------------------------------
--
-- Hide: use Show (above) to hide a window.
--
procedure Hide (Window : in Window_Type) is
P : Window_Ptr := Get_Internals (Window, "Hide");
begin
Show (Window, False);
end Hide;
----------------------------------------------------------------------------
--
-- Focus: give the input focus to the specified window.
--
procedure Focus (Window : in Window_Type) is
P : Window_Ptr := Get_Internals (Window, "Focus");
begin
Message_Loop.Set_Focus (P.Handle);
end Focus;
----------------------------------------------------------------------------
--
-- Visible: test if a window is visible.
--
function Visible (Window : Window_Type) return Boolean is
P : Window_Ptr := Get_Internals (Window, "Visible");
begin
return IsWindowVisible(P.Handle) /= 0;
end Visible;
----------------------------------------------------------------------------
--
-- Get_Origin: get the coordinates of a window's top left corner.
--
function Get_Origin (Window : Window_Type) return Point_Type is
P : Window_Ptr := Get_Internals (Window, "Visible");
R : aliased Win32_RECT;
begin
Bool_Dummy := GetWindowRect (P.Handle, R'Unchecked_Access);
return (Integer(R.Left),Integer(R.Top));
end Get_Origin;
----------------------------------------------------------------------------
--
-- Get_Width: get the width of a window.
--
function Get_Width (Window : Window_Type) return Natural is
P : Window_Ptr := Get_Internals (Window, "Get_Width");
R : aliased Win32_RECT;
begin
Bool_Dummy := GetWindowRect (P.Handle, R'Unchecked_Access);
return Natural (R.Right - R.Left);
end Get_Width;
----------------------------------------------------------------------------
--
-- Get_Height: get the height of a window.
--
function Get_Height (Window : Window_Type) return Natural is
P : Window_Ptr := Get_Internals (Window, "Get_Height");
R : aliased Win32_RECT;
begin
Bool_Dummy := GetWindowRect (P.Handle, R'Unchecked_Access);
return Natural (R.Bottom - R.Top);
end Get_Height;
----------------------------------------------------------------------------
--
-- Set_Origin: set the coordinates of a window's top left corner.
--
procedure Set_Origin (Window : in Window_Type;
Origin : in Point_Type) is
P : Window_Ptr := Get_Internals (Window, "Set_Origin");
begin
Bool_Dummy := SetWindowPos (P.Handle, System.Null_Address,
Win32_INT(Origin.X), Win32_INT(Origin.Y),
0, 0, SWP_NOZORDER + SWP_NOSIZE);
end Set_Origin;
----------------------------------------------------------------------------
--
-- Set_Size: set the width and height of a window.
--
procedure Set_Size (Window : in Window_Type;
Width : in Natural := 0;
Height : in Natural := 0) is
P : Window_Ptr := Get_Internals (Window, "Set_Size");
W : Natural := Width;
H : Natural := Height;
begin
if Width = 0 then
W := Get_Width (Window);
end if;
if Height = 0 then
H := Get_Height (Window);
end if;
Bool_Dummy := SetWindowPos (P.Handle, System.Null_Address, 0, 0,
Win32_INT(W), Win32_INT(H),
SWP_NOZORDER + SWP_NOMOVE);
end Set_Size;
----------------------------------------------------------------------------
--
-- Set_Font: change the font associated with a window and invalidate it
-- so that it will be repainted.
--
procedure Set_Font (Window : in Window_Type;
Font : in Font_Type) is
P : Window_Ptr := Get_Internals (Window, "Set_Font");
begin
if Font.Length > 0 then
if P.Font /= System.Null_Address then
Bool_Dummy := DeleteObject (P.Font);
end if;
P.Font := Create_Font (Font);
Long_Dummy := SendMessage (P.Handle, WM_SETFONT, To_WPARAM(P.Font), 0);
Bool_Dummy := InvalidateRect (P.Handle, null, 1);
end if;
end Set_Font;
----------------------------------------------------------------------------
--
-- Get_Font: build a Font_Type structure for a window's current font.
--
function Get_Font (Window : Window_Type) return Font_Type is
P : Window_Ptr := Get_Internals (Window, "Get_Font");
I : Win32_INT;
F : Win32_LOGFONT;
begin
while P.Font = System.Null_Address loop
P := Window_Ptr(P.Parent);
exit when P = null;
end loop;
if P = null or else P.Font = System.Null_Address then
return Default_Font;
else
I := GetObject (P.Font, Win32_LOGFONT'Size/Win32_BYTE'Size, F'Address);
return Get_Font (F);
end if;
end Get_Font;
----------------------------------------------------------------------------
--
-- F R A M E O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Frame: construct a frame with the specified characteristics.
--
function Frame (Origin : Point_Type;
Width : Positive;
Height : Positive;
Title : String;
Command : Command_Type;
Font : Font_Type := Default_Font) return Frame_Type is
W : Frame_Type;
M : Main_Window_Ptr := new Main_Window_Internals;
P : Window_Ptr := Window_Ptr(M);
T : Win32_String := To_Array(Title);
begin
-- Set up the Window_Internals structure for a window with default
-- placement
W.Internals.Pointer := Reference_Counted_Ptr(P);
P.Action := Command_Type'Pos(Command);
P.Top := Origin.Y;
P.Left := Origin.X;
P.Width := Width;
P.Height := Height;
-- Ask the message loop to create a top-level window
Message_Loop.Create_Window (M, Frame_Class, T,
WS_EX_CLIENTEDGE or WS_EX_APPWINDOW,
WS_OVERLAPPEDWINDOW,
True);
-- Set the font now that the frame exists
if Font.Length > 0 then
Set_Font (W, Font);
else
Set_Font (W, Default_Font);
end if;
-- Bring the window to the front and return the window object
Bool_Dummy := SetForegroundWindow(P.Handle);
return W;
end Frame;
----------------------------------------------------------------------------
--
-- Frame: construct a frame with the specified characteristics and
-- default placement.
--
function Frame (Width : Positive;
Height : Positive;
Title : String;
Command : Command_Type;
Font : Font_Type := Default_Font) return Frame_Type is
begin
return Frame ((Integer(CW_USEDEFAULT),Integer(CW_USEDEFAULT)),
Width, Height, Title, Command, Font);
end Frame;
----------------------------------------------------------------------------
--
-- Close: close and destroy a frame.
--
procedure Close (Frame : in Frame_Type) is
P : Window_Ptr := Get_Internals (Frame, "Close");
begin
if IsWindow(P.Handle) /= 0 then
Message_Loop.Destroy_Window (P.Handle);
end if;
end Close;
----------------------------------------------------------------------------
--
-- Valid: test if a frame is valid (i.e. if the window exists).
--
function Valid (Frame : Frame_Type) return Boolean is
P : Window_Ptr := Window_Ptr(Frame.Internals.Pointer);
begin
return P /= null and then
IsWindow(P.Handle) /= 0;
end Valid;
----------------------------------------------------------------------------
--
-- Frame_Width: return the width of a frame's border.
--
function Frame_Width return Natural is
begin
return Natural
((GetSystemMetrics(SM_CXFRAME) + GetSystemMetrics(SM_CXEDGE)) * 2);
end Frame_Width;
----------------------------------------------------------------------------
--
-- Frame_Height: return the height of a frame's border.
--
function Frame_Height return Natural is
begin
return Natural
((GetSystemMetrics(SM_CYFRAME) + GetSystemMetrics(SM_CYEDGE)) * 2 +
GetSystemMetrics(SM_CYCAPTION));
end Frame_Height;
----------------------------------------------------------------------------
--
-- Next_Command: ask the info monitor for the next command.
--
function Next_Command return Command_Type is
Cmd : Natural;
begin
Window_Info.Get_Command (Cmd);
return Command_Type'Val(Cmd);
end Next_Command;
----------------------------------------------------------------------------
--
-- Command_Ready: ask the info monitor if there is a command pending.
--
function Command_Ready return Boolean is
begin
return Window_Info.Test_Command;
end Command_Ready;
----------------------------------------------------------------------------
--
-- D I A L O G O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Dialog: create a top-level dialog window.
--
function Dialog (Width : Positive;
Height : Positive;
Title : String;
Command : Command_Type;
Font : Font_Type := Default_Font) return Dialog_Type is
W : Dialog_Type;
X : Integer := Integer(GetSystemMetrics(SM_CXSCREEN)) / 2;
Y : Integer := Integer(GetSystemMetrics(SM_CYSCREEN)) / 2;
M : Main_Window_Ptr := new Main_Window_Internals;
P : Window_Ptr := Window_Ptr(M);
T : Win32_String := To_Array(Title);
begin
-- Set up the Window_Internals structure for a centred window
W.Internals.Pointer := Reference_Counted_Ptr(P);
P.Action := Command_Type'Pos(Command);
P.Top := Y - Height/2;
P.Left := X - Width/2;
P.Width := Width;
P.Height := Height;
-- Ask the message loop to create a hidden top-level window
Message_Loop.Create_Window (M, Dialog_Class, T,
0, WS_DLGFRAME or WS_SYSMENU,
False);
-- Set the font now that the dialog exists
if Font.Length > 0 then
Set_Font (W, Font);
else
Set_Font (W, Default_Font);
end if;
-- Return the window object
return W;
end Dialog;
----------------------------------------------------------------------------
--
-- Execute: run a dialog until it issues a command. Note that dialogs
-- are hidden rather than destroyed so that closing a dialog
-- them won't make any attached controls disappear.
--
function Execute (Dialog : in Dialog_Type) return Command_Type is
D : Win32_HWND;
C : Natural;
P : Window_Ptr := Get_Internals (Dialog, "Execute");
begin
-- Record this window as the currently active dialog
D := P.Handle;
Window_Info.Get_Dialog (D);
-- Make the window visible and bring it to the foreground
Bool_Dummy := ShowWindow (P.Handle, SW_SHOW);
Bool_Dummy := SetForegroundWindow (P.Handle);
-- Wait for a command (which must be from this dialog, as dialog
-- windows disable all other windows belonging to the application)
Window_Info.Get_Command (C);
-- Restore the original active dialog setting
Window_Info.Get_Dialog (D);
-- Hide the dialog window and return the command code
Bool_Dummy := ShowWindow (P.Handle, SW_HIDE);
return Command_Type'Val(C);
end Execute;
----------------------------------------------------------------------------
--
-- Dialog_Width: return the width of a dialog's border.
--
function Dialog_Width return Natural is
begin
return Natural (GetSystemMetrics(SM_CXDLGFRAME) * 2);
end Dialog_Width;
----------------------------------------------------------------------------
--
-- Dialog_Height: return the height of a dialog's border.
--
function Dialog_Height return Natural is
begin
return Natural (GetSystemMetrics(SM_CYDLGFRAME) * 2 +
GetSystemMetrics(SM_CYCAPTION));
end Dialog_Height;
----------------------------------------------------------------------------
--
-- P A N E L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Panel: create a panel (which is actually a Windows groupbox if it has
-- a title, or a static control with an etched border if not).
--
function Panel (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Title : String := "";
Font : Font_Type := Parent_Font) return Panel_Type is
W : Panel_Type;
C : String(1..6);
S : Win32_DWORD := WS_GROUP;
P : Container_Ptr := new Container_Internals;
begin
-- Choose the actual window class and style
if Title = "" then
C := "static";
S := S or SS_ETCHEDFRAME;
else
C := "button";
S := S or BS_GROUPBOX;
end if;
-- Create the window and return it
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, C, Title, WS_EX_CONTROLPARENT, S,
Origin, Width, Height, Font, -1, "Panel");
P.WndProc := GetWindowLong (P.Handle, GWL_WNDPROC);
Long_Dummy := SetWindowLong (P.Handle, GWL_WNDPROC,
To_LONG(Panel_Proc'Access));
return W;
end Panel;
----------------------------------------------------------------------------
--
-- M E N U O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Menu: create a menu attached to a frame.
--
function Menu (Parent : Frame_Type'Class;
Text : String) return Menu_Type is
M : Menu_Type;
H : Win32_HMENU;
P : Window_Ptr := Get_Internals (Parent, "Menu");
W : Window_Ptr := new Window_Internals;
T : Win32_String := To_Array(Text);
begin
-- Get the frame's menu bar (and create it if it doesn't exist)
H := GetMenu (P.Handle);
if H = System.Null_Address then
H := CreateMenu;
Bool_Dummy := SetMenu (P.Handle, H);
end if;
-- Create a new menu and attach it to the menu bar
W.Handle := CreateMenu;
Bool_Dummy := AppendMenu(H, MF_POPUP, To_WPARAM(W.Handle), To_LPCSTR(T));
-- Redraw the menu bar and return the menu object
Bool_Dummy := DrawMenuBar (P.Handle);
M.Internals.Pointer := Reference_Counted_Ptr(W);
return M;
end Menu;
----------------------------------------------------------------------------
--
-- Menu: create a menu attached to another menu.
--
function Menu (Parent : Menu_Type'Class;
Text : String) return Menu_Type is
M : Menu_Type;
P : Window_Ptr := Get_Internals (Parent, "Menu");
W : Window_Ptr := new Window_Internals;
H : Win32_HWND := P.Handle;
T : Win32_String := To_Array(Text);
begin
-- Create a new submenu and attach it to the parent menu
W.Handle := CreateMenu;
Bool_Dummy := AppendMenu(H, MF_POPUP, To_WPARAM(W.Handle), To_LPCSTR(T));
-- Find the enclosing top-level window and redraw its menu bar
while GetParent(H) /= System.Null_Address loop
H := GetParent(H);
end loop;
Bool_Dummy := DrawMenuBar(H);
-- Return the menu object
M.Internals.Pointer := Reference_Counted_Ptr(W);
return M;
end Menu;
----------------------------------------------------------------------------
--
-- Menu_Height: return the height of a menubar.
--
function Menu_Height return Natural is
begin
return Natural (GetSystemMetrics(SM_CYMENU));
end Menu_Height;
----------------------------------------------------------------------------
--
-- C O N T R O L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Enable: enable or disable a control.
--
procedure Enable (Control : in Control_Type;
Enabled : in Boolean := True) is
P : Window_Ptr := Get_Internals (Control, "Enable");
begin
Bool_Dummy := EnableWindow (P.Handle, Win32_BOOL(Boolean'Pos(Enabled)));
end Enable;
----------------------------------------------------------------------------
--
-- Disable: use Enable (above) to disable a control.
--
procedure Disable (Control : in Control_Type) is
P : Window_Ptr := Get_Internals (Control, "Disable");
begin
Enable (Control_Type'Class(Control), False);
end Disable;
----------------------------------------------------------------------------
--
-- Enabled: test if a control is enabled.
--
function Enabled (Control : Control_Type) return Boolean is
P : Window_Ptr := Get_Internals (Control, "Enabled");
begin
return IsWindowEnabled(P.Handle) /= 0;
end Enabled;
----------------------------------------------------------------------------
--
-- T E X T C O N T R O L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Get_Length: get the length of the text in a text control.
--
function Get_Length (Control : Text_Control_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Length");
begin
return Natural(SendMessage(P.Handle, WM_GETTEXTLENGTH, 0, 0));
end Get_Length;
----------------------------------------------------------------------------
--
-- Get_Text: get the text from a text control.
--
function Get_Text (Control : Text_Control_Type) return String is
P : Window_Ptr := Get_Internals (Control, "Get_Text");
L : Natural;
begin
declare
A : Win32_String(1..Win32_SIZE(Get_Length(Control)+1)) := (others => ' ');
begin
L := Natural(SendMessage(P.Handle, WM_GETTEXT,
Win32_WPARAM(A'Length), To_LPARAM(A)));
return To_String(A);
end;
end Get_Text;
----------------------------------------------------------------------------
--
-- Get_Text: get the text from a text control into a fixed-length
-- string variable.
--
procedure Get_Text (Control : in Text_Control_Type;
Text : out String;
Length : out Natural) is
S : constant String := Get_Text (Control);
begin
if S'Length > Text'Length then
Text := S(S'First..S'First+Text'Length-1);
Length := Text'Length;
else
Text(Text'First..Text'First+S'Length-1) := S;
Length := S'Length;
end if;
end Get_Text;
----------------------------------------------------------------------------
--
-- Set_Text: store the specified text in a text control.
--
procedure Set_Text (Control : in Text_Control_Type;
Text : in String) is
P : Window_Ptr := Get_Internals (Control, "Set_Text");
T : Win32_String := To_Array(Text);
begin
Long_Dummy := SendMessage (P.Handle, WM_SETTEXT, 0, To_LPARAM(T));
end Set_Text;
----------------------------------------------------------------------------
--
-- B U T T O N O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Button: create a button as specified.
--
function Button (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Text : String;
Command : Command_Type;
Default : Boolean := False;
Font : Font_Type := Parent_Font) return Button_Type is
W : Button_Type;
P : Window_Ptr := new Window_Internals;
S : Win32_DWORD := WS_TABSTOP or WS_GROUP;
begin
if Default then
S := S or BS_DEFPUSHBUTTON;
else
S := S or BS_PUSHBUTTON;
end if;
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "button", Text,
0, S, Origin, Width, Height, Font,
Command_Type'Pos(Command)+WM_USER, "Button");
return W;
end Button;
----------------------------------------------------------------------------
--
-- L A B E L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Label: create a label as specified.
--
function Label (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Text : String;
Align : Alignment_Type := Left;
Font : Font_Type := Parent_Font) return Label_Type is
W : Label_Type;
P : Window_Ptr := new Window_Internals;
S : Win32_DWORD := WS_GROUP or SS_NOPREFIX;
begin
if Align = Right then
S := S or SS_RIGHT;
elsif Align = Centre then
S := S or SS_CENTER;
end if;
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "static", Text, 0, S,
Origin, Width, Height, Font, -1, "Label");
return W;
end Label;
----------------------------------------------------------------------------
--
-- E D I T B O X O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Editbox: create an editbox as specified.
--
function Editbox (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Text : String := "";
Password : Boolean := False;
Font : Font_Type := Parent_Font) return Editbox_Type is
W : Editbox_Type;
P : Window_Ptr := new Window_Internals;
E : Win32_DWORD := ES_AUTOHSCROLL or WS_BORDER or WS_TABSTOP or WS_GROUP;
begin
if Password then
E := E or ES_PASSWORD;
end if;
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "edit", Text, 0, E,
Origin, Width, Height, Font, -1, "Editbox");
return W;
end Editbox;
----------------------------------------------------------------------------
--
-- Modified: test if the user has modified the editbox since the last
-- time this function was called.
--
function Modified (Editbox : Editbox_Type) return Boolean is
P : Window_Ptr := Get_Internals(Editbox, "Modified");
B : Boolean;
begin
B := SendMessage(P.Handle,EM_GETMODIFY,0,0) /= 0;
Long_Dummy := SendMessage(P.Handle, EM_SETMODIFY, 0, 0);
return B;
end Modified;
----------------------------------------------------------------------------
--
-- B O O L E A N C O N T R O L O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Get_State: test if a Boolean control is checked.
--
function Get_State (Control : Boolean_Control_Type) return Boolean is
P : Window_Ptr := Get_Internals (Control, "Get_State");
begin
return SendMessage (P.Handle, BM_GETCHECK, 0, 0) = 1;
end Get_State;
----------------------------------------------------------------------------
--
-- Set_State: set the state of a Boolean control as specified.
--
procedure Set_State (Control : in Boolean_Control_Type;
State : in Boolean) is
P : Window_Ptr := Get_Internals (Control, "Set_State");
begin
Long_Dummy := SendMessage (P.Handle, BM_SETCHECK,
Boolean'Pos(State), 0);
end Set_State;
----------------------------------------------------------------------------
--
-- M E N U I T E M O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Menuitem: create a menuitem.
--
function Menuitem (Parent : Menu_Type'Class;
Text : String;
Command : Command_Type) return Menuitem_Type is
M : Menuitem_Type;
P : Window_Ptr := Get_Internals (Parent, "Menuitem");
W : Window_Ptr := new Window_Internals;
H : Win32_HWND := P.Handle;
T : Win32_String := To_Array(Text);
begin
-- Set the command code and set the internal handle to be the parent
-- handle (since Win32 menuitems are not real windows and do not have
-- handles of their own)
M.Internals.Pointer := Reference_Counted_Ptr(W);
W.Handle := P.Handle;
W.Action := Command_Type'Pos(Command);
-- Add the menuitem to the parent menu
Bool_Dummy := AppendMenu(P.Handle, MF_STRING,
Win32_UINT(W.Action+WM_USER),
To_LPCSTR(T));
-- Find the enclosing top-level window and redraw its menu bar
while GetParent(H) /= System.Null_Address loop
H := GetParent(H);
end loop;
Bool_Dummy := DrawMenuBar(H);
-- Return the menuitem object
return M;
end Menuitem;
----------------------------------------------------------------------------
--
-- Separator: create a separator for a menu.
--
function Separator (Parent : Menu_Type'Class) return Menuitem_Type is
M : Menuitem_Type;
P : Window_Ptr := Get_Internals (Parent, "Separator");
W : Window_Ptr := new Window_Internals;
H : Win32_HWND := P.Handle;
begin
-- Set the command code and set the internal handle to be the parent
-- handle (since Win32 menuitems are not real windows and do not have
-- handles of their own)
M.Internals.Pointer := Reference_Counted_Ptr(W);
W.Handle := P.Handle;
W.Action := -1;
-- Add the menuitem to the parent menu
Bool_Dummy := AppendMenu(P.Handle, MF_STRING or MF_SEPARATOR, 0, null);
-- Find the enclosing top-level window and redraw its menu bar
while GetParent(H) /= System.Null_Address loop
H := GetParent(H);
end loop;
Bool_Dummy := DrawMenuBar(H);
-- Return the menuitem object
return M;
end Separator;
----------------------------------------------------------------------------
--
-- Enable: enable or disable a menu item using its command code.
--
procedure Enable (Control : in Menuitem_Type;
Enabled : in Boolean := True) is
P : Window_Ptr := Get_Internals (Control, "Enable");
E : Win32_UINT;
begin
if P.Action >= 0 then
if Enabled then
E := MF_BYCOMMAND or MF_ENABLED;
else
E := MF_BYCOMMAND or MF_GRAYED;
end if;
Bool_Dummy := EnableMenuItem (P.Handle,
Win32_UINT(P.Action+WM_USER), E);
end if;
end Enable;
----------------------------------------------------------------------------
--
-- Enabled: test if a menu item is enabled using its command code.
--
function Enabled (Control : Menuitem_Type) return Boolean is
P : Window_Ptr := Get_Internals (Control, "Enabled");
S : Win32_UINT;
begin
if P.Action < 0 then
return False;
else
S := GetMenuState (P.Handle,
Win32_UINT(P.Action+WM_USER), MF_BYCOMMAND);
return (S and MF_DISABLED) = 0;
end if;
end Enabled;
----------------------------------------------------------------------------
--
-- Get_Length: get the length of the text in a menuitem.
--
function Get_Length (Control : Menuitem_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Length");
begin
if P.Action < 0 then
return 0;
else
return Natural(GetMenuString(P.Handle, Win32_UINT(P.Action+WM_USER),
null, 0, MF_BYCOMMAND));
end if;
end Get_Length;
----------------------------------------------------------------------------
--
-- Get_Text: get the text from a menuitem.
--
function Get_Text (Control : Menuitem_Type) return String is
P : Window_Ptr := Get_Internals (Control, "Get_Text");
L : Natural;
begin
if P.Action < 0 then
return "";
else
declare
A : Win32_String(1..Win32_SIZE(Get_Length(Control)+1)) :=
(others => ' ');
begin
L := Natural(GetMenuString(P.Handle, Win32_UINT(P.Action+WM_USER),
To_LPSTR(A), A'Length, MF_BYCOMMAND));
return To_String(A);
end;
end if;
end Get_Text;
----------------------------------------------------------------------------
--
-- Set_Text: store the specified text in a text control.
--
procedure Set_Text (Control : in Menuitem_Type;
Text : in String) is
P : Window_Ptr := Get_Internals (Control, "Set_Text");
T : Win32_String := To_Array(Text);
H : Win32_HWND;
begin
if P.Action >= 0 then -- ignore menu separators
Bool_Dummy := ModifyMenu (P.Handle, Win32_UINT(P.Action+WM_USER),
MF_BYCOMMAND or MF_STRING,
Win32_UINT(P.Action), To_LPCSTR(T));
H := P.Handle;
while GetParent(H) /= System.Null_Address loop
H := GetParent(H);
end loop;
Bool_Dummy := DrawMenuBar(H);
end if;
end Set_Text;
----------------------------------------------------------------------------
--
-- Get_State: test if a menuitem is checked.
--
function Get_State (Control : Menuitem_Type) return Boolean is
P : Window_Ptr := Get_Internals (Control, "Get_State");
begin
return (GetMenuState(P.Handle,Win32_UINT(P.Action+WM_USER),
MF_BYCOMMAND) and MF_CHECKED) /= 0;
end Get_State;
----------------------------------------------------------------------------
--
-- Set_State: set the state of a menuitem as specified.
--
procedure Set_State (Control : in Menuitem_Type;
State : in Boolean) is
P : Window_Ptr := Get_Internals (Control, "Set_State");
D : Win32_DWORD;
begin
if State then
D := CheckMenuItem (P.Handle, Win32_UINT(P.Action+WM_USER),
MF_BYCOMMAND or MF_CHECKED);
else
D := CheckMenuItem (P.Handle, Win32_UINT(P.Action+WM_USER),
MF_BYCOMMAND or MF_UNCHECKED);
end if;
end Set_State;
----------------------------------------------------------------------------
--
-- C H E C K B O X O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Checkbox: create a checkbox with the specified initial state.
--
function Checkbox (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Text : String;
Checked : Boolean := False;
Font : Font_Type := Parent_Font)
return Checkbox_Type is
W : Checkbox_Type;
P : Window_Ptr := new Window_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "button", Text, 0,
BS_AUTOCHECKBOX or WS_TABSTOP or WS_GROUP,
Origin, Width, Height, Font, -1, "Checkbox");
Set_State (W, Checked);
return W;
end Checkbox;
----------------------------------------------------------------------------
--
-- R A D I O B U T T O N O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Radiobutton: create a radiobutton with the specified initial state.
--
function Radiobutton (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Text : String;
Checked : Boolean := False;
Font : Font_Type := Parent_Font)
return Radiobutton_Type is
W : Radiobutton_Type;
P : Window_Ptr := new Window_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "button", Text, 0,
BS_AUTORADIOBUTTON or WS_TABSTOP,
Origin, Width, Height, Font, -1, "Radiobutton");
Set_State (W, Checked);
return W;
end Radiobutton;
----------------------------------------------------------------------------
--
-- M U L T I L I N E O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Get_Text: get the text of a specified line into a fixed-length
-- string variable by dispatching to the appropriate
-- Get_Text function.
--
procedure Get_Text (Control : in Multiline_Type;
Line : in Natural := 0;
Text : out String;
Length : out Natural) is
S : constant String := Get_Text (Multiline_Type'Class(Control), Line);
begin
if S'Length > Text'Length then
Text := S(S'First..S'First+Text'Length-1);
Length := Text'Length;
else
Text(Text'First..Text'First+S'Length-1) := S;
Length := S'Length;
end if;
end Get_Text;
----------------------------------------------------------------------------
--
-- Get_Actual_Line: convert a line number in a multiline control
-- (which may be zero or out-of-range) to an
-- absolute line number (internal use only).
--
function Get_Actual_Line (Control : in Multiline_Type'Class;
Line : in Natural;
Name : in String) return Natural is
L : Natural := Line;
begin
if L > Get_Count(Control) then
Raise_Exception (Constraint_Error'Identity,
External_Tag(Control'Tag) &
": Line number out of range in " & Name);
end if;
if L = 0 then
L := Get_Line(Control);
end if;
return L;
end Get_Actual_Line;
----------------------------------------------------------------------------
--
-- L I S T B O X O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Listbox: create a listbox.
--
function Listbox (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Font : Font_Type := Parent_Font) return Listbox_Type is
W : Listbox_Type;
P : Window_Ptr := new Window_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "listbox", "", 0,
WS_HSCROLL or WS_VSCROLL or WS_BORDER or
WS_TABSTOP or WS_GROUP,
Origin, Width, Height, Font, -1, "Listbox");
return W;
end Listbox;
----------------------------------------------------------------------------
--
-- Get_Count: get the number of lines in the listbox.
--
function Get_Count (Control : Listbox_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Count");
begin
return Natural(SendMessage(P.Handle,LB_GETCOUNT,0,0));
end Get_Count;
----------------------------------------------------------------------------
--
-- Get_Line: get the number of the current line (0 if no line is
-- selected).
--
function Get_Line (Control : Listbox_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Line");
begin
return Natural(SendMessage(P.Handle,LB_GETCURSEL,0,0) + 1);
end Get_Line;
----------------------------------------------------------------------------
--
-- Get_Length: get the length of the specified line (0 if no line
-- is selected).
--
function Get_Length (Control : Listbox_Type;
Line : Natural := 0) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Length");
L : Natural := Get_Actual_Line (Control, Line, "Get_Length");
begin
if L = 0 then
return 0;
else
return Natural(SendMessage(P.Handle, LB_GETTEXTLEN,
Win32_WPARAM(L)-1, 0));
end if;
end Get_Length;
----------------------------------------------------------------------------
--
-- Get_Text: get the text of the specified line (the empty string if
-- the current line is specified and no line is selected).
--
function Get_Text (Control : Listbox_Type;
Line : Natural := 0) return String is
P : Window_Ptr := Get_Internals (Control, "Get_Text");
L : Natural := Get_Actual_Line (Control, Line, "Get_Text");
begin
if L = 0 then
return "";
else
declare
A : Win32_String(1..Win32_SIZE(Get_Length(Control,L)+1)) :=
(others => ' ');
begin
L := Natural(SendMessage(P.Handle, LB_GETTEXT,
Win32_WPARAM(L)-1, To_LPARAM(A)));
return To_String(A);
end;
end if;
end Get_Text;
----------------------------------------------------------------------------
--
-- Set_Text: set the text of the specified line (delete the current
-- line and insert its replacement).
--
procedure Set_Text (Control : in Listbox_Type;
Text : in String;
Line : in Natural := 0) is
L : Natural := Get_Actual_Line (Control, Line, "Set_Text");
begin
Delete_Line (Control, L);
Insert_Line (Control, Text, L);
end Set_Text;
----------------------------------------------------------------------------
--
-- Select_Line: set the line number for the current selection (deselect
-- all lines if the line number is 0).
--
procedure Select_Line (Control : in Listbox_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Select_Line");
begin
if Line > Get_Count(Control) then
Raise_Exception (Constraint_Error'Identity,
External_Tag(Multiline_Type'Class(Control)'Tag) &
": Line number out of range in Select_Line");
end if;
Long_Dummy := SendMessage(P.Handle, LB_SETCURSEL,
Win32_WPARAM(Line)-1, 0);
end Select_Line;
----------------------------------------------------------------------------
--
-- Append_Line: add a line containing the specified line to the end
-- of the listbox.
--
procedure Append_Line (Control : in Listbox_Type;
Text : in String) is
P : Window_Ptr := Get_Internals (Control, "Append_Line");
T : Win32_String := To_Array(Text);
begin
Long_Dummy := SendMessage(P.Handle, LB_ADDSTRING, 0, To_LPARAM(T));
end Append_Line;
----------------------------------------------------------------------------
--
-- Insert_Line: insert a new line above the specified line. If the real
-- line number is zero (no current line), append the line
-- as above.
--
procedure Insert_Line (Control : in Listbox_Type;
Text : in String;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Insert_Line");
L : Natural := Get_Actual_Line (Control, Line, "Insert_Line");
T : Win32_String := To_Array(Text);
begin
if L = 0 then
Append_Line (Control, Text);
else
Long_Dummy := SendMessage(P.Handle, LB_INSERTSTRING,
Win32_WPARAM(L)-1, To_LPARAM(T));
end if;
end Insert_Line;
----------------------------------------------------------------------------
--
-- Delete_Line: delete the specified line.
--
procedure Delete_Line (Control : in Listbox_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Delete_Line");
L : Natural := Get_Actual_Line (Control, Line, "Delete_Line");
begin
Long_Dummy := SendMessage(P.Handle, LB_DELETESTRING,
Win32_WPARAM(L)-1, 0);
end Delete_Line;
----------------------------------------------------------------------------
--
-- Delete_All: delete all lines in the listbox.
--
procedure Delete_All (Control : in Listbox_Type) is
P : Window_Ptr := Get_Internals (Control, "Delete_All");
begin
Long_Dummy := SendMessage(P.Handle, LB_RESETCONTENT, 0, 0);
end Delete_All;
----------------------------------------------------------------------------
--
-- C O M B O B O X O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Combobox: create a combobox.
--
function Combobox (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Editable : Boolean := True;
Font : Font_Type := Parent_Font)
return Combobox_Type is
W : Combobox_Type;
P : Window_Ptr := new Window_Internals;
S : Win32_DWORD := CBS_AUTOHSCROLL or WS_GROUP;
begin
if Editable then
S := S or CBS_DROPDOWN;
else
S := S or CBS_DROPDOWNLIST;
end if;
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "combobox", "", 0,
S or WS_HSCROLL or WS_VSCROLL or WS_BORDER or WS_TABSTOP,
Origin, Width, 120, Font, -1, "Combobox");
return W;
end Combobox;
----------------------------------------------------------------------------
--
-- Get_Count: get the number of lines in the combobox.
--
function Get_Count (Control : Combobox_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Count");
begin
return Natural(SendMessage(P.Handle,CB_GETCOUNT,0,0));
end Get_Count;
----------------------------------------------------------------------------
--
-- Get_Line: get the number of the current line (0 if no line is
-- selected, or if the text in the editbox part of the
-- control is not a string selected from the listbox
-- part).
--
function Get_Line (Control : Combobox_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Line");
begin
return Natural(SendMessage(P.Handle,CB_GETCURSEL,0,0) + 1);
end Get_Line;
----------------------------------------------------------------------------
--
-- Get_Length: get the length of the specified line (0 if no line
-- is selected).
--
function Get_Length (Control : Combobox_Type;
Line : Natural := 0) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Length");
L : Natural := Get_Actual_Line (Control, Line, "Get_Length");
begin
if L = 0 then
return Natural(SendMessage(P.Handle, WM_GETTEXTLENGTH, 0, 0));
else
return Natural(SendMessage(P.Handle, CB_GETLBTEXTLEN,
Win32_WPARAM(L)-1, 0));
end if;
end Get_Length;
----------------------------------------------------------------------------
--
-- Get_Text: get the text of the specified line (the text of the editbox
-- part of the control if the line number is 0).
--
function Get_Text (Control : Combobox_Type;
Line : Natural := 0) return String is
P : Window_Ptr := Get_Internals (Control, "Get_Text");
L : Natural := Get_Actual_Line (Control, Line, "Get_Text");
begin
declare
A : Win32_String(1..Win32_SIZE(Get_Length(Control,L)+1)) :=
(others => ' ');
begin
if L = 0 then
Long_Dummy := SendMessage(P.Handle, WM_GETTEXT,
Win32_WPARAM(A'Length), To_LPARAM(A));
else
Long_Dummy := SendMessage(P.Handle, CB_GETLBTEXT,
Win32_WPARAM(L-1), To_LPARAM(A));
end if;
return To_String(A);
end;
end Get_Text;
----------------------------------------------------------------------------
--
-- Set_Text: set the text of the specified line (delete the current
-- line and insert its replacement).
--
procedure Set_Text (Control : in Combobox_Type;
Text : in String;
Line : in Natural := 0) is
L : Natural := Get_Actual_Line (Control, Line, "Set_Text");
begin
Delete_Line (Control, L);
if L > Get_Count(Control) then
L := 0;
end if;
Insert_Line (Control, Text, L);
end Set_Text;
----------------------------------------------------------------------------
--
-- Select_Line: set the line number for the current selection (deselect
-- all lines if the line number is 0).
--
procedure Select_Line (Control : in Combobox_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Select_Line");
L : Natural := Get_Actual_Line (Control, Line, "Select_Line");
begin
Long_Dummy := SendMessage(P.Handle, CB_SETCURSEL,
Win32_WPARAM(Line)-1, 0);
end Select_Line;
----------------------------------------------------------------------------
--
-- Append_Line: add a line containing the specified line to the end
-- of the listbox part of the combobox.
--
procedure Append_Line (Control : in Combobox_Type;
Text : in String) is
P : Window_Ptr := Get_Internals (Control, "Append_Line");
T : Win32_String := To_Array(Text);
begin
Long_Dummy := SendMessage(P.Handle, CB_ADDSTRING, 0, To_LPARAM(T));
end Append_Line;
----------------------------------------------------------------------------
--
-- Insert_Line: insert a new line above the specified line. If the real
--
procedure Insert_Line (Control : in Combobox_Type;
Text : in String;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Insert_Line");
L : Natural := Get_Actual_Line (Control, Line, "Insert_Line");
T : Win32_String := To_Array(Text);
begin
if L = 0 then
Append_Line (Control, Text);
else
Long_Dummy := SendMessage(P.Handle, CB_INSERTSTRING,
Win32_WPARAM(L)-1, To_LPARAM(T));
end if;
end Insert_Line;
----------------------------------------------------------------------------
--
-- Delete_Line: delete the specified line.
--
procedure Delete_Line (Control : in Combobox_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Delete_Line");
L : Natural := Get_Actual_Line (Control, Line, "Delete_Line");
begin
if L = 0 then
Select_Line (Control);
else
Long_Dummy := SendMessage(P.Handle, CB_DELETESTRING,
Win32_WPARAM(L)-1, 0);
end if;
end Delete_Line;
----------------------------------------------------------------------------
--
-- Delete_All: delete all lines in the combobox.
--
procedure Delete_All (Control : in Combobox_Type) is
P : Window_Ptr := Get_Internals (Control, "Delete_All");
begin
Long_Dummy := SendMessage(P.Handle, CB_RESETCONTENT, 0, 0);
end Delete_All;
----------------------------------------------------------------------------
--
-- M E M O O P E R A T I O N S
--
-- Memos are slightly peculiar because Windows always reports them as
-- having at least one line, even when they're completely empty. I've
-- decided that a blank last line won't count as a line -- a CR/LF at
-- the end of a line is part of the line it ends, and only lines with
-- characters in them should count. So there.
--
----------------------------------------------------------------------------
--
-- Last_Line: returns character index of start of last line (for internal
-- use only).
--
function Last_Line (Memo : in Win32_HWND) return Win32_LONG is
L : Win32_LONG;
begin
L := SendMessage (Memo, EM_GETLINECOUNT, 0, 0);
return SendMessage (Memo, EM_LINEINDEX, Win32_WPARAM(L-1), 0);
end Last_Line;
----------------------------------------------------------------------------
--
-- Length: returns length of memo text (for internal use only).
--
function Length (Memo : in Win32_HWND) return Win32_LONG is
begin
return SendMessage (Memo, WM_GETTEXTLENGTH, 0, 0);
end Length;
----------------------------------------------------------------------------
--
-- Memo: create a memo control as specified.
--
function Memo (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Font : Font_Type := Parent_Font) return Memo_Type is
W : Memo_Type;
P : Window_Ptr := new Window_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, "edit", "", WS_EX_CLIENTEDGE,
ES_MULTILINE or ES_WANTRETURN or ES_NOHIDESEL or
ES_AUTOHSCROLL or ES_AUTOVSCROLL or
WS_HSCROLL or WS_VSCROLL or
WS_TABSTOP or WS_GROUP,
Origin, Width, Height, Font, -1, "Memo");
P.WndProc := GetWindowLong (P.Handle, GWL_WNDPROC);
Long_Dummy := SetWindowLong (P.Handle, GWL_WNDPROC,
To_LONG(Memo_Proc'Access));
return W;
end Memo;
----------------------------------------------------------------------------
--
-- Get_Column: find the column number where the caret is positioned.
--
function Get_Column (Memo : Memo_Type) return Natural is
P : Window_Ptr := Get_Internals (Memo, "Get_Column");
S : Integer;
L : Win32_LONG;
begin
Long_Dummy := SendMessage (P.Handle, EM_GETSEL,
To_WPARAM(S'Address), 0);
L := SendMessage (P.Handle, EM_LINEFROMCHAR,
Win32_WPARAM(S), 0);
L := SendMessage(P.Handle, EM_LINEINDEX, Win32_WPARAM(L), 0);
return S - Integer(L) + 1;
end Get_Column;
----------------------------------------------------------------------------
--
-- Modified: test if the user has modified the memo since the last
-- time this function was called.
--
function Modified (Memo : Memo_Type) return Boolean is
P : Window_Ptr := Get_Internals(Memo, "Modified");
B : Boolean;
begin
B := SendMessage(P.Handle,EM_GETMODIFY,0,0) /= 0;
Long_Dummy := SendMessage(P.Handle, EM_SETMODIFY, 0, 0);
return B;
end Modified;
----------------------------------------------------------------------------
--
-- Cut_Selection: cut the current selection to the clipboard.
--
procedure Cut_Selection (Memo : in Memo_Type) is
P : Window_Ptr := Get_Internals (Memo, "Cut_Selection");
begin
Long_Dummy := SendMessage (P.Handle, WM_CUT, 0, 0);
end Cut_Selection;
----------------------------------------------------------------------------
--
-- Copy_Selection: copy the current selection to the clipboard.
--
procedure Copy_Selection (Memo : in Memo_Type) is
P : Window_Ptr := Get_Internals (Memo, "Copy_Selection");
begin
Long_Dummy := SendMessage (P.Handle, WM_COPY, 0, 0);
end Copy_Selection;
----------------------------------------------------------------------------
--
-- Paste_Selection: paste the clipboard over the current selection.
--
procedure Paste_Selection (Memo : in Memo_Type) is
P : Window_Ptr := Get_Internals (Memo, "Paste_Selection");
begin
Long_Dummy := SendMessage (P.Handle, WM_PASTE, 0, 0);
end Paste_Selection;
----------------------------------------------------------------------------
--
-- Undo_Change: undo the user's last change to the text of the memo.
--
procedure Undo_Change (Memo : in Memo_Type) is
P : Window_Ptr := Get_Internals (Memo, "Undo_Change");
begin
Long_Dummy := SendMessage (P.Handle, WM_UNDO, 0, 0);
end Undo_Change;
----------------------------------------------------------------------------
--
-- Show_Selection: scroll the memo so that the caret is in view.
--
procedure Show_Selection (Memo : in Memo_Type) is
P : Window_Ptr := Get_Internals(Memo, "Show_Selection");
begin
Long_Dummy := SendMessage (P.Handle, EM_SCROLLCARET, 0, 0);
end Show_Selection;
----------------------------------------------------------------------------
--
-- Get_Count: get the number of lines in the memo.
--
function Get_Count (Control : Memo_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Count");
begin
return Natural(SendMessage(P.Handle, EM_GETLINECOUNT, 0, 0)) -
Boolean'Pos(Last_Line(P.Handle) = Length(P.Handle));
end Get_Count;
----------------------------------------------------------------------------
--
-- Get_Line: get the number of the line where the caret is positioned.
-- Return zero if it's on a blank last line.
--
function Get_Line (Control : Memo_Type) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Line");
begin
if Last_Line(P.Handle) = Length(P.Handle) then
return 0;
else
return Natural(SendMessage(P.Handle,EM_LINEFROMCHAR,-1,0)) + 1;
end if;
end Get_Line;
----------------------------------------------------------------------------
--
-- Get_Length: get the length of the specified line.
--
function Get_Length (Control : Memo_Type;
Line : Natural := 0) return Natural is
P : Window_Ptr := Get_Internals (Control, "Get_Length");
L : Natural := Get_Actual_Line (Control, Line, "Get_Length");
R : Win32_LONG;
begin
if L = 0 then
return 0;
else
R := SendMessage (P.Handle, EM_LINEINDEX, Win32_WPARAM(L)-1, 0);
return Natural(SendMessage(P.Handle,EM_LINELENGTH,Win32_WPARAM(R),0));
end if;
end Get_Length;
----------------------------------------------------------------------------
--
-- Get_Text: get the text of the specified line. Note that the EM_GETLINE
-- message takes the line length in the first two bytes of the
-- destination string, and no terminating null is copied (so
-- the rest of the destination string must be initialised to
-- nulls).
--
function Get_Text (Control : Memo_Type;
Line : Natural := 0) return String is
P : Window_Ptr := Get_Internals(Control, "Get_Text");
L : Natural := Get_Actual_Line (Control, Line, "Get_Text");
W : Natural;
begin
W := Get_Length (Control, L);
if W = 0 then
return "";
else
declare
A : Win32_String(1..Win32_SIZE(W+1)) :=
(1 => Win32_CHAR'Val(W mod 16#100#),
2 => Win32_CHAR'Val(W / 16#100#),
others => Win32_Char'Val(0));
begin
Long_Dummy := SendMessage(P.Handle, EM_GETLINE,
Win32_WPARAM(L)-1, To_LPARAM(A));
return To_String(A);
end;
end if;
end Get_Text;
----------------------------------------------------------------------------
--
-- Set_Text: set the text of the specified line (select the line and
-- replace the selection).
--
procedure Set_Text (Control : in Memo_Type;
Text : in String;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Set_Text");
L : Natural := Get_Actual_Line (Control, Line, "Set_Text");
S : Win32_LONG; -- start position (start of line)
E : Win32_LONG; -- end position (start of next line)
T : Win32_String := To_Array(Text);
begin
if L = 0 then
Append_Line (Control, Text);
else
S := SendMessage(P.Handle, EM_LINEINDEX, Win32_WPARAM(L)-1, 0);
E := S + Win32_LONG(Get_Length(Control,L));
Long_Dummy := SendMessage (P.Handle, EM_SETSEL,
Win32_WPARAM(S), Win32_LPARAM(E));
Long_Dummy := SendMessage (P.Handle, EM_REPLACESEL, 0,
To_LPARAM(T));
end if;
end Set_Text;
----------------------------------------------------------------------------
--
-- Select_Line: set the line number for the caret position.
--
procedure Select_Line (Control : in Memo_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Select_Line");
L : Natural := Get_Actual_Line (Control, Line, "Select_Line");
R : Win32_LONG;
begin
if L = 0 then
R := Length(P.Handle);
else
R := SendMessage(P.Handle, EM_LINEINDEX, Win32_WPARAM(L)-1, 0);
end if;
Long_Dummy := SendMessage (P.Handle, EM_SETSEL,
Win32_WPARAM(R), Win32_LPARAM(R));
end Select_Line;
----------------------------------------------------------------------------
--
-- Append_Line: add a line containing the specified line to the end
-- of the memo. If the last line is not blank, add a
-- preceding EOL to start a new line
--
procedure Append_Line (Control : in Memo_Type;
Text : in String) is
P : Window_Ptr := Get_Internals (Control, "Append_Line");
C : Integer;
begin
C := Integer(Length(P.Handle));
Long_Dummy := SendMessage (P.Handle, EM_SETSEL,
Win32_WPARAM(C), Win32_LPARAM(C));
if Last_Line(P.Handle) = Length(P.Handle) then
declare
T : Win32_String := To_Array(Text);
begin
Long_Dummy := SendMessage (P.Handle, EM_REPLACESEL, 0, To_LPARAM(T));
end;
else
declare
T : Win32_String := To_Array(EOL & Text);
begin
Long_Dummy := SendMessage (P.Handle, EM_REPLACESEL, 0, To_LPARAM(T));
end;
end if;
end Append_Line;
----------------------------------------------------------------------------
--
-- Insert_Line: insert a new line above the specified line. If the line
-- number is zero, append the line as above.
--
procedure Insert_Line (Control : in Memo_Type;
Text : in String;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Insert_Line");
L : Natural := Get_Actual_Line (Control, Line, "Select_Line");
T : Win32_String := To_Array(Text & EOL);
begin
if L = 0 then
Append_Line (Control, Text);
else
Select_Line (Control, Line);
Long_Dummy := SendMessage (P.Handle, EM_REPLACESEL, 0, To_LPARAM(T));
end if;
end Insert_Line;
----------------------------------------------------------------------------
--
-- Delete_Line: delete the specified line.
--
procedure Delete_Line (Control : in Memo_Type;
Line : in Natural := 0) is
P : Window_Ptr := Get_Internals (Control, "Delete_Line");
L : Natural;
S : Win32_LONG;
E : Win32_LONG;
N : Win32_String := To_Array("");
begin
L := Get_Actual_Line (Control, Line, "Delete_Line");
if L > 0 then
S := SendMessage(P.Handle, EM_LINEINDEX, Win32_WPARAM(L)-1, 0);
E := SendMessage(P.Handle, EM_LINEINDEX, Win32_WPARAM(L), 0);
if E < 0 then
E := Length(P.Handle);
end if;
Long_Dummy := SendMessage (P.Handle, EM_SETSEL,
Win32_WPARAM(S), Win32_LPARAM(E));
Long_Dummy := SendMessage (P.Handle, EM_REPLACESEL, 0,
To_LPARAM(N));
end if;
end Delete_Line;
----------------------------------------------------------------------------
--
-- Delete_All: delete all lines in the memo.
--
procedure Delete_All (Control : in Memo_Type) is
P : Window_Ptr := Get_Internals (Control, "Delete_All");
N : Win32_String := To_Array("");
begin
Long_Dummy := SendMessage (P.Handle, WM_SETTEXT, 0,
To_LPARAM(N));
end Delete_All;
----------------------------------------------------------------------------
--
-- C A N V A S O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Canvas: create a canvas window which does not generate a command.
--
function Canvas (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Font : Font_Type := Parent_Font) return Canvas_Type is
W : Canvas_Type;
P : Canvas_Ptr := new Canvas_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, To_String(Canvas_Class), "",
0, WS_BORDER or WS_GROUP,
Origin, Width, Height, Font, -1, "Canvas");
Set_Fill (W);
return W;
end Canvas;
----------------------------------------------------------------------------
--
-- Canvas: create a canvas window which generates a command when the
-- mouse button is pressed within it.
--
function Canvas (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Command : Command_Type;
Font : Font_Type := Parent_Font) return Canvas_Type is
W : Canvas_Type;
P : Canvas_Ptr := new Canvas_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, To_String(Canvas_Class), "",
0, WS_BORDER or WS_GROUP,
Origin, Width, Height, Font,
Command_Type'Pos(Command), "Canvas");
Set_Fill (W);
return W;
end Canvas;
----------------------------------------------------------------------------
--
-- Canvas: create a canvas window which generates a command when the
-- mouse button or a key is pressed within it.
--
function Canvas (Parent : Container_Type'Class;
Origin : Point_Type;
Width : Integer;
Height : Integer;
Command : Command_Type;
Keypress : Command_Type;
Font : Font_Type := Parent_Font) return Canvas_Type is
W : Canvas_Type;
P : Canvas_Ptr := new Canvas_Internals;
begin
W.Internals.Pointer := Reference_Counted_Ptr(P);
Create_Child (W, Parent, To_String(Canvas_Class), "",
0, WS_BORDER or WS_GROUP,
Origin, Width, Height, Font,
Command_Type'Pos(Command), "Canvas");
P.Keypress := Command_Type'Pos(Keypress);
Focus (W);
Set_Fill (W);
return W;
end Canvas;
----------------------------------------------------------------------------
--
-- Set_Colour: ask the monitor to set the background colour.
--
procedure Set_Colour (Canvas : in Canvas_Type;
Colour : in Colour_Type := White) is
B : Win32_COLORREF := RGB(Colour);
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Set_Colour"));
begin
C.Monitor.Set_Brush (CreateSolidBrush(B));
Bool_Dummy := InvalidateRect (C.Handle, null, 1);
end Set_Colour;
----------------------------------------------------------------------------
--
-- Erase: ask the monitor to delete the drawing list and then redraw
-- the window.
--
procedure Erase (Canvas : in Canvas_Type) is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Erase"));
begin
C.Monitor.Clear;
Bool_Dummy := InvalidateRect (C.Handle, null, 1);
end Erase;
----------------------------------------------------------------------------
--
-- Save: ask the monitor to save the current position in the drawing list.
--
procedure Save (Canvas : in Canvas_Type) is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Save"));
begin
C.Monitor.Save;
end Save;
----------------------------------------------------------------------------
--
-- Restore: revert to a previously saved position in the drawing list
-- (ignored if there is no saved position). This is safe because
-- the list always grows unless it is erased, so the saved
-- position will be valid until Erase is called, at which point
-- the monitor will reset it to null.
--
procedure Restore (Canvas : in Canvas_Type) is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Restore"));
begin
C.Monitor.Restore;
Bool_Dummy := InvalidateRect (C.Handle, null, 1);
end Restore;
----------------------------------------------------------------------------
--
-- Set_Font: add a font handle to the drawing list.
--
procedure Set_Font (Canvas : in Canvas_Type;
Font : in Font_Type) is
P : Canvas_Object_Ptr := new Handle_Type;
H : Win32_HFONT := Create_Font (Font);
begin
Handle_Type(P.all).Handle := Handle(H);
Add (Canvas, "Set_Font", P);
end Set_Font;
----------------------------------------------------------------------------
--
-- Set_Pen: add a pen handle to the drawing list.
--
procedure Set_Pen (Canvas : in Canvas_Type;
Colour : in Colour_Type := Black;
Width : in Natural := 1) is
P : Canvas_Object_Ptr := new Handle_Type;
S : Win32_COLORREF := RGB(Colour);
begin
if Width > 0 then
Handle_Type(P.all).Handle := Handle (CreatePen(0,Win32_INT(Width),S));
else
Handle_Type(P.all).Handle := Handle (GetStockObject(NULL_PEN));
end if;
Add (Canvas, "Set_Pen", P);
end Set_Pen;
----------------------------------------------------------------------------
--
-- Set_Fill: add a solid brush handle to the drawing list.
--
procedure Set_Fill (Canvas : in Canvas_Type;
Colour : in Colour_Type) is
P : Canvas_Object_Ptr := new Handle_Type;
S : Win32_COLORREF := RGB(Colour);
begin
Handle_Type(P.all).Handle := Handle (CreateSolidBrush(S));
Add (Canvas, "Set_Fill", P);
end Set_Fill;
----------------------------------------------------------------------------
--
-- Set_Fill: add a transparent brush handle to the drawing list.
--
procedure Set_Fill (Canvas : in Canvas_Type) is
P : Canvas_Object_Ptr := new Handle_Type;
L : aliased Win32_LOGBRUSH;
begin
L.lbStyle := BS_HOLLOW;
Handle_Type(P.all).Handle :=
Handle (CreateBrushIndirect(L'Unchecked_Access));
Add (Canvas, "Set_Fill", P);
end Set_Fill;
----------------------------------------------------------------------------
--
-- Draw_Text: add a text string to the drawing with the top left
-- corner at the specified point.
--
procedure Draw_Text (Canvas : in Canvas_Type;
From : in Point_Type;
Text : in String) is
P : Canvas_Object_Ptr := new Text_Type (Text'Length);
begin
Text_Type(P.all).Text := Text;
Text_Type(P.all).From := From;
Text_Type(P.all).To := From;
Text_Type(P.all).Align := -1;
Add (Canvas, "Draw_Text", P);
end Draw_Text;
----------------------------------------------------------------------------
--
-- Draw_Text: add a text string to the drawing within a rectangle
-- specified by diagonally opposite corners.
--
procedure Draw_Text (Canvas : in Canvas_Type;
From : in Point_Type;
To : in Point_Type;
Text : in String;
Align : in Alignment_Type := Left) is
P : Canvas_Object_Ptr := new Text_Type (Text'Length);
begin
Text_Type(P.all).Text := Text;
Text_Type(P.all).From := From;
Text_Type(P.all).To := To;
Text_Type(P.all).Align := Alignment_Type'Pos(Align);
Add (Canvas, "Draw_Text", P);
end Draw_Text;
----------------------------------------------------------------------------
--
-- Draw_Text: calculate the text rectangle from a height and width.
--
procedure Draw_Text (Canvas : in Canvas_Type;
From : in Point_Type;
Width : in Integer;
Height : in Integer;
Text : in String;
Align : in Alignment_Type := Left) is
begin
Draw_Text (Canvas, From, (From.X+Width,From.Y+Height), Text, Align);
end Draw_Text;
----------------------------------------------------------------------------
--
-- Draw_Line: add a line to the drawing between two points.
--
procedure Draw_Line (Canvas : in Canvas_Type;
From : in Point_Type;
To : in Point_Type) is
P : Canvas_Object_Ptr := new Line_Type;
begin
Line_Type(P.all).From := From;
Line_Type(P.all).To := To;
Add (Canvas, "Draw_Line", P);
end Draw_Line;
----------------------------------------------------------------------------
--
-- Draw_Line: calculate the line endpoint from a length and angle.
--
procedure Draw_Line (Canvas : in Canvas_Type;
From : in Point_Type;
Length : in Positive;
Angle : in Angle_Type) is
To : Point_Type;
begin
To := Endpoint(From,Length,Angle);
Draw_Line (Canvas, From, To);
end Draw_Line;
----------------------------------------------------------------------------
--
-- Draw_Line_List: add a polyline to the drawing. Ignore polylines with
-- less than two points, and draw an ordinary line for a
-- polyline with only two points.
--
procedure Draw_Line_List (Canvas : in Canvas_Type;
Points : in Point_List) is
P : Window_Ptr := Get_Internals (Canvas, "Draw_Line_List");
begin
if Points'Length = 2 then
Draw_Line (Canvas, Points(Points'First), Points(Points'Last));
elsif Points'Length > 2 then
declare
P : Canvas_Object_Ptr := new Polyline_Type(Points'Length);
begin
P.Next := null;
for I in 1..Points'Length loop
Polyline_Type(P.all).Points(I) :=
(Win32_LONG(Points(Points'First+I-1).X),
Win32_LONG(Points(Points'First+I-1).Y));
end loop;
Add (Canvas, "Draw_Line_List", P);
end;
end if;
end Draw_Line_List;
----------------------------------------------------------------------------
--
-- Draw_Rectangle: add either a normal rectangle or a rounded rectangle
-- to the drawing, depending on whether the rounding is
-- zero or not.
--
procedure Draw_Rectangle (Canvas : in Canvas_Type;
From : in Point_Type;
To : in Point_Type;
Rounding : in Point_Type := (0,0)) is
P : Canvas_Object_Ptr;
begin
if Rounding = (0,0) then
P := new Rectangle_Type;
Rectangle_Type(P.all).From := From;
Rectangle_Type(P.all).To := To;
else
P := new Rounded_Rectangle_Type;
Rounded_Rectangle_Type(P.all).From := From;
Rounded_Rectangle_Type(P.all).To := To;
Rounded_Rectangle_Type(P.all).Corner := Rounding;
end if;
Add (Canvas, "Draw_Rectangle", P);
end Draw_Rectangle;
----------------------------------------------------------------------------
--
-- Draw_Rectangle: calculate the rectangle size from a height and width.
--
procedure Draw_Rectangle (Canvas : in Canvas_Type;
From : in Point_Type;
Width : in Positive;
Height : in Positive;
Rounding : in Point_Type := (0,0)) is
begin
Draw_Rectangle (Canvas, From, (From.X+Width, From.Y+Height), Rounding);
end Draw_Rectangle;
----------------------------------------------------------------------------
--
-- Draw_Ellipse: draw an ellipse whose size is specified by a bounding
-- rectangle.
--
procedure Draw_Ellipse (Canvas : in Canvas_Type;
From : in Point_Type;
To : in Point_Type) is
P : Canvas_Object_Ptr := new Ellipse_Type;
begin
Ellipse_Type(P.all).From := From;
Ellipse_Type(P.all).To := To;
Add (Canvas, "Draw_Ellipse", P);
end Draw_Ellipse;
----------------------------------------------------------------------------
--
-- Draw_Ellipse: calculate the bounding rectangle from a height and width.
--
procedure Draw_Ellipse (Canvas : in Canvas_Type;
From : in Point_Type;
Width : in Positive;
Height : in Positive) is
begin
Draw_Ellipse (Canvas, From, (From.X + Width, From.Y + Height));
end Draw_Ellipse;
----------------------------------------------------------------------------
--
-- Draw_Circle: draw an ellipse in a bounding square calculated from
-- the centre point and the radius.
--
procedure Draw_Circle (Canvas : in Canvas_Type;
Centre : in Point_Type;
Radius : in Positive) is
P : Window_Ptr := Get_Internals (Canvas, "Draw_Circle");
begin
Draw_Ellipse (Canvas, (Centre.X - Radius,Centre.Y - Radius),
(Centre.X + Radius,Centre.Y + Radius));
end Draw_Circle;
----------------------------------------------------------------------------
--
-- Draw_Polygon: create and fill a Windows-style array with the coordinates
-- of the vertices, then add the polygon to the drawing list.
-- Draw a line if there are only two vertices, and do nothing
-- if there are less than two vertices.
--
procedure Draw_Polygon (Canvas : in Canvas_Type;
Points : in Point_List) is
P : Window_Ptr := Get_Internals (Canvas, "Draw_Polygon");
begin
if Points'Length = 2 then
Draw_Line (Canvas, Points(Points'First), Points(Points'Last));
elsif Points'Length > 2 then
declare
P : Canvas_Object_Ptr := new Polygon_Type(Points'Length);
begin
P.Next := null;
for I in 1..Points'Length loop
Polygon_Type(P.all).Points(I) :=
(Win32_LONG(Points(Points'First+I-1).X),
Win32_LONG(Points(Points'First+I-1).Y));
end loop;
Add (Canvas, "Draw_Polygon", P);
end;
end if;
end Draw_Polygon;
----------------------------------------------------------------------------
--
-- Draw_Image: draw the specified image on the canvas starting at the
-- specified top-left corner point.
--
procedure Draw_Image (Canvas : in Canvas_Type;
From : in Point_Type;
Image : in Image_Type) is
I : Image_Ptr;
begin
if Valid(Image) then
I := Image_Ptr(Image.Internals.Pointer);
Draw_Image (Canvas, From, I.Width, I.Height, Image);
end if;
end Draw_Image;
----------------------------------------------------------------------------
--
-- Draw_Image: draw the specified image on the canvas starting at the
-- specified top-left corner point, stretching it to the
-- specified bottom-right corner point.
--
procedure Draw_Image (Canvas : in Canvas_Type;
From : in Point_Type;
To : in Point_Type;
Image : in Image_Type) is
L : Integer := Integer'Min(From.X,To.X);
T : Integer := Integer'Min(From.Y,To.Y);
R : Integer := Integer'Max(From.X,To.X);
B : Integer := Integer'Max(From.Y,To.Y);
begin
Draw_Image (Canvas, (L,T), R-L, B-T, Image);
end Draw_Image;
----------------------------------------------------------------------------
--
-- Draw_Image: draw the specified image on the canvas starting at the
-- specified top-left corner point, stretching it to the
-- specified width and height.
--
procedure Draw_Image (Canvas : in Canvas_Type;
From : in Point_Type;
Width : in Natural;
Height : in Natural;
Image : in Image_Type) is
P : Window_Ptr := Get_Internals (Canvas, "Draw_Image");
B : Canvas_Object_Ptr := new Bitmap_Type;
I : Image_Ptr;
begin
if Valid(Image) then
I := Image_Ptr(Image.Internals.Pointer);
Bitmap_Type(B.all).From := From;
Bitmap_Type(B.all).Width := Width;
Bitmap_Type(B.all).Height := Height;
Bitmap_Type(B.all).Bitmap := Image.Internals;
Add (Canvas, "Draw_Image", B);
end if;
end Draw_Image;
----------------------------------------------------------------------------
--
-- Mouse_Down: test whether the mouse was pressed within a specific
-- canvas.
--
function Mouse_Down (Canvas : Canvas_Type) return Boolean is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Mouse_Down"));
begin
return C.Monitor.Mouse_Down;
end Mouse_Down;
----------------------------------------------------------------------------
--
-- Mouse_Moved: test if the mouse has moved within a canvas, which
-- will only be true while the mouse is down after being
-- pressed inside this canvas.
--
function Mouse_Moved (Canvas : Canvas_Type) return Boolean is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Mouse_Moved"));
begin
return C.Monitor.Mouse_Moved;
end Mouse_Moved;
----------------------------------------------------------------------------
--
-- Start_Point: get the position where the mouse was pressed within the
-- specified canvas.
--
function Start_Point (Canvas : Canvas_Type) return Point_Type is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Start_Point"));
P : Point_Type;
begin
C.Monitor.Get_Start (P.X, P.Y);
return P;
end Start_Point;
----------------------------------------------------------------------------
--
-- End_Point: get the latest mouse position within the specified canvas.
--
function End_Point (Canvas : Canvas_Type) return Point_Type is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "End_Point"));
P : Point_Type;
begin
C.Monitor.Get_End (P.X, P.Y);
return P;
end End_Point;
----------------------------------------------------------------------------
--
-- Key_Code: get the latest key position within the specified canvas.
--
function Key_Code (Canvas : Canvas_Type) return Character is
C : Canvas_Ptr := Canvas_Ptr(Get_Internals(Canvas, "Key_Code"));
K : Character;
begin
C.Monitor.Get_Key (K);
return K;
end Key_Code;
----------------------------------------------------------------------------
--
-- C O M M O N D I A L O G O P E R A T I O N S
--
----------------------------------------------------------------------------
--
-- Execute: execute a common dialog by asking the message loop to call
-- its Show_Dialog primitive and return the result.
--
function Execute (Dialog : Common_Dialog_Type) return Boolean is
P : Common_Dialog_Ptr := Get_Internals (Dialog, "Execute");
B : Boolean;
begin
Message_Loop.Show_Dialog (P,B);
return B;
end Execute;
----------------------------------------------------------------------------
--
-- Colour_Dialog: construct a colour dialog.
--
function Colour_Dialog return Colour_Dialog_Type is
D : Colour_Dialog_Type;
P : Colour_Dialog_Ptr := new Colour_Dialog_Internals;
begin
D.Internals.Pointer := Reference_Counted_Ptr(P);
P.Struct.lStructSize := P.Struct'Size / Win32_BYTE'Size;
P.Struct.lpCustColors := P.Custom(P.Custom'First)'Access;
return D;
end Colour_Dialog;
----------------------------------------------------------------------------
--
-- Set_Colour: set the colour stored in a colour dialog.
--
procedure Set_Colour (Dialog : in Colour_Dialog_Type;
Colour : in Colour_Type) is
P : Colour_Dialog_Ptr := Colour_Dialog_Ptr(Get_Internals(Dialog,
"Set_Colour"));
begin
P.Colour := Colour;
end Set_Colour;
----------------------------------------------------------------------------
--
-- Get_Colour: get the colour stored in a colour dialog.
--
function Get_Colour (Dialog : in Colour_Dialog_Type) return Colour_Type is
P : Colour_Dialog_Ptr := Colour_Dialog_Ptr(Get_Internals(Dialog,
"Get_Colour"));
begin
return P.Colour;
end Get_Colour;
----------------------------------------------------------------------------
--
-- Font_Dialog: construct a font dialog.
--
function Font_Dialog return Font_Dialog_Type is
D : Font_Dialog_Type;
P : Font_Dialog_Ptr := new Font_Dialog_Internals;
begin
D.Internals.Pointer := Reference_Counted_Ptr(P);
P.Struct.lStructSize := P.Struct'Size / Win32_BYTE'Size;
P.Struct.lpLogFont := P.Font'Access;
P.Font := Set_Font(Font("Arial",9));
return D;
end Font_Dialog;
----------------------------------------------------------------------------
--
-- Set_Font: set the font stored in a font dialog.
--
procedure Set_Font (Dialog : in Font_Dialog_Type;
Font : in Font_Type) is
P : Font_Dialog_Ptr := Font_Dialog_Ptr(Get_Internals(Dialog,
"Set_Font"));
begin
P.Font := Set_Font(Font);
end Set_Font;
----------------------------------------------------------------------------
--
-- Get_Font: get the font stored in a font dialog.
--
function Get_Font (Dialog : in Font_Dialog_Type) return Font_Type is
P : Font_Dialog_Ptr := Font_Dialog_Ptr(Get_Internals(Dialog,
"Get_Font"));
begin
return Get_Font (P.Font);
end Get_Font;
----------------------------------------------------------------------------
--
-- Set_Name: set the filename stored in a file dialog.
--
procedure Set_Name (Dialog : in File_Dialog_Type;
Name : in String) is
P : File_Dialog_Ptr := File_Dialog_Ptr(Get_Internals(Dialog,
"Set_Name"));
begin
if P.Buffer'Length > Name'Length then
P.Buffer(P.Buffer'First..P.Buffer'First+Name'Length) := To_Array(Name);
else
P.Buffer := To_Array(Name(Name'First..Name'First+P.Buffer'Length-2));
end if;
end Set_Name;
----------------------------------------------------------------------------
--
-- Get_Name: get the filename stored in a file dialog.
--
function Get_Name (Dialog : in File_Dialog_Type) return String is
P : File_Dialog_Ptr := File_Dialog_Ptr(Get_Internals(Dialog,
"Get_Name"));
begin
return To_String(P.Buffer);
end Get_Name;
----------------------------------------------------------------------------
--
-- Add_Filter: add a filename filter to a file dialog.
--
procedure Add_Filter (Dialog : in File_Dialog_Type;
Text : in String;
Filter : in String) is
P : File_Dialog_Ptr := File_Dialog_Ptr(Get_Internals(Dialog,
"Add_Filter"));
begin
if P.Length + Text'Length + Filter'Length + 2 < P.Filter'Length then
P.Filter (P.Filter'First+P.Length ..
P.Filter'First+P.Length+Text'Length) := To_Array(Text);
P.Length := P.Length + Text'Length + 1;
P.Filter (P.Filter'First+P.Length ..
P.Filter'First+P.Length+Filter'Length) := To_Array(Filter);
P.Length := P.Length + Filter'Length + 1;
P.Filter (P.Filter'First+P.Length) := Win32_CHAR'First;
if P.Struct.lpstrFilter = null then
P.Struct.lpstrFilter := To_LPCSTR(P.Filter);
end if;
end if;
end Add_Filter;
----------------------------------------------------------------------------
--
-- Set_Directory: select the initial directory for a file dialog.
--
procedure Set_Directory (Dialog : in File_Dialog_Type;
Name : in String) is
P : File_Dialog_Ptr := File_Dialog_Ptr(Get_Internals(Dialog,
"Set_Directory"));
L : Win32_SIZE := Win32_SIZE'Min(Name'Length,P.Directory'Length-1);
begin
P.Directory (P.Directory'First .. P.Directory'First+L) :=
To_Array(Name(Name'First..Name'First+Integer(L)-1));
if P.Struct.lpstrInitialDir = null then
P.Struct.lpstrInitialDir := To_LPCSTR(P.Directory);
end if;
end Set_Directory;
----------------------------------------------------------------------------
--
-- Open_Dialog: construct a file open dialog.
--
function Open_Dialog (Title : String) return Open_Dialog_Type is
D : Open_Dialog_Type;
P : File_Dialog_Ptr := new Open_Dialog_Internals (Title'Length+1);
begin
D.Internals.Pointer := Reference_Counted_Ptr(P);
P.Struct.lStructSize := P.Struct'Size / Win32_BYTE'Size;
P.Struct.lpstrTitle := To_LPCSTR(P.Title);
P.Struct.lpstrFile := P.Buffer(P.Buffer'First)'Access;
P.Struct.nMaxFile := P.Buffer'Length;
P.Struct.Flags := OFN_HIDEREADONLY or OFN_FILEMUSTEXIST or
OFN_PATHMUSTEXIST;
P.Buffer(P.Buffer'First) := Win32_CHAR'Val(0);
P.Title := To_Array(Title);
return D;
end Open_Dialog;
----------------------------------------------------------------------------
--
-- Save_Dialog: construct a file save dialog.
--
function Save_Dialog (Title : String;
Create : Boolean := True) return Save_Dialog_Type is
D : Save_Dialog_Type;
P : File_Dialog_Ptr := new Save_Dialog_Internals (Title'Length+1);
begin
D.Internals.Pointer := Reference_Counted_Ptr(P);
P.Struct.lStructSize := P.Struct'Size / Win32_BYTE'Size;
P.Struct.lpstrTitle := To_LPCSTR(P.Title);
P.Struct.lpstrFile := P.Buffer(P.Buffer'First)'Access;
P.Struct.nMaxFile := P.Buffer'Length;
P.Struct.Flags := OFN_HIDEREADONLY or OFN_PATHMUSTEXIST;
if Create then
P.Struct.Flags := P.Struct.Flags or OFN_OVERWRITEPROMPT;
else
P.Struct.Flags := P.Struct.Flags or OFN_CREATEPROMPT;
end if;
P.Buffer(1) := Win32_CHAR'Val(0);
P.Title := To_Array(Title);
return D;
end Save_Dialog;
------------------------------------------------------------------------------
--
-- P A C K A G E I N I T I A L I S A T I O N
--
-- Register the window classes if there is no previous module instance.
--
------------------------------------------------------------------------------
begin
if Get_hPrevInstance = System.Null_Address then
declare
Class : aliased Win32_WNDCLASS;
Dummy : Win32_ATOM;
begin
-- Set up general window class information
Class.Style := CS_HREDRAW or CS_VREDRAW;
Class.cbClsExtra := 0;
Class.cbWndExtra := 0;
Class.hInstance := Get_hInstance;
Class.hIcon := LoadIcon(System.Null_Address,
To_LPCSTR(IDI_APPLICATION));
Class.hCursor := LoadCursor(System.Null_Address,
To_LPCSTR(IDC_ARROW));
Class.hbrBackground := To_Handle(COLOR_BTNFACE+1);
Class.lpszMenuName := null;
-- Set frame-specific information and register the frame class
Class.lpszClassName := To_LPCSTR(Frame_Class);
Class.lpfnWndProc := Frame_Proc'Access;
Dummy := RegisterClass(Class'Unchecked_Access);
-- Set dialog-specific information and register the dialog class
Class.lpszClassName := To_LPCSTR(Dialog_Class);
Class.lpfnWndProc := Dialog_Proc'Access;
Dummy := RegisterClass(Class'Unchecked_Access);
-- Set canvas-specific information and register the canvas class
Class.lpszClassName := To_LPCSTR(Canvas_Class);
Class.hbrBackground := System.Null_Address;
Class.lpfnWndProc := Canvas_Proc'Access;
Dummy := RegisterClass(Class'Unchecked_Access);
end;
end if;
end JEWL.Windows;
|
-------------------------------------------------------------------------------
-- Package : Cmd_Flags --
-- Description : Manage user provided CLI flags for the program. --
-- Author : Simon Rowe <simon@wiremoons.com> --
-- License : MIT Open Source. --
-------------------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Command_Line; use GNAT.Command_Line;
-- local packages
with Show_Version;
package body Cmd_Flags is
function Command_Line_Flags_Exist return Boolean is
----------------------------------------------
-- Parse and manage and command line flags --
----------------------------------------------
-- GNAT.Command_Line variables and config
Help_Option : aliased Boolean := False;
Version_Option : aliased Boolean := False;
Config : Command_Line_Configuration;
begin
-- define params for the 'help' option
Define_Switch
(Config,
Help_Option'Access,
Switch => "-h",
Long_Switch => "--help",
Help => "Show command line usage for application");
-- define params for the 'version' option
Define_Switch
(Config,
Version_Option'Access,
Switch => "-v",
Long_Switch => "--version",
Help => "Show version details");
-- Additional help message as first line of 'Display_Help()'
Set_Usage
(Config,
Usage => "[switches] [arguments]",
Help => "Program to generate passwords from random three letter words.");
-- cli flags parse using config and above defined switched
Getopt (Config);
-- show program 'version' if requested
if Version_Option then
Show_Version.Show;
return True;
end if;
-- show 'help' if requested
if Help_Option then
New_Line (1);
Display_Help (Config);
return True;
end if;
-- no cli params : so just return
--Try_Help; -- alternative one line response
return False;
exception
when Invalid_Switch =>
New_Line (1);
Put_Line (Standard_Error, "Exception caught: caused by the use of an invalid command line switch.");
New_Line (1);
Display_Help (Config);
return True;
when Invalid_Parameter =>
New_Line (1);
Put_Line
(Standard_Error,
"Exception caught: caused by the use of an invalid parameter to a command line switch.");
New_Line (1);
Display_Help (Config);
return True;
when Exit_From_Command_Line =>
New_Line (1);
Put_Line (Standard_Error, "Exit following display of help message.");
return True;
end Command_Line_Flags_Exist;
end Cmd_Flags;
|
--
-- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr>
-- - Ryad Benadjila
-- - Arnauld Michelizza
-- - Mathieu Renard
-- - Philippe Thierry
-- - Philippe Trebuchet
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
with ewok.debug;
with ewok.tasks; use ewok.tasks;
with ewok.tasks_shared; use ewok.tasks_shared;
with ewok.exported.devices; use ewok.exported.devices;
with ewok.devices_shared; use ewok.devices_shared;
with ewok.devices;
package body ewok.syscalls.cfg.dev
with spark_mode => off
is
--pragma debug_policy (IGNORE);
package TSK renames ewok.tasks;
procedure dev_map
(caller_id : in ewok.tasks_shared.t_task_id;
params : in out t_parameters;
mode : in ewok.tasks_shared.t_task_mode)
is
dev_descriptor : unsigned_8
with address => params(1)'address;
dev_id : ewok.devices_shared.t_device_id;
dev : ewok.devices.t_checked_user_device_access;
ok : boolean;
begin
--
-- Checking user inputs
--
-- Task must not be in ISR mode
-- NOTE
-- The reasons to forbid a task in ISR mode to map/unmap some devices
-- are not technical. An ISR *must* be a minimal piece of code that
-- manage only the interrupts provided by a specific hardware.
if mode = ewok.tasks_shared.TASK_MODE_ISRTHREAD then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): forbidden in ISR mode"));
goto ret_denied;
end if;
-- No map/unmap before end of initialization
if not is_init_done (caller_id) then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): forbidden during init sequence"));
goto ret_denied;
end if;
-- Valid device descriptor ?
if dev_descriptor not in TSK.tasks_list(caller_id).device_id'range
then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): invalid device descriptor"));
goto ret_inval;
end if;
dev_id := TSK.tasks_list(caller_id).device_id (dev_descriptor);
-- Used device descriptor ?
if dev_id = ID_DEV_UNUSED then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): unused device"));
goto ret_inval;
end if;
-- Defensive programming. Verifying that the device really belongs to the
-- task
if ewok.devices.get_task_from_id (dev_id) /= caller_id then
raise program_error;
end if;
-- Verifying that the device may be voluntary mapped by the task
dev := ewok.devices.get_user_device (dev_id);
if dev.map_mode /= ewok.exported.devices.DEV_MAP_VOLUNTARY then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): not a DEV_MAP_VOLUNTARY device"));
goto ret_denied;
end if;
-- Verifying that the device is not already mapped
if TSK.is_mounted (caller_id, dev_id) then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): the device is already mapped"));
goto ret_denied;
end if;
--
-- Mapping the device
--
TSK.mount_device (caller_id, dev_id, ok);
if not ok then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_map(): mount_device() failed (no free region?)"));
goto ret_busy;
end if;
-- We enable the device if its not already enabled
-- FIXME - That code should not be here.
-- Should create a special syscall for enabling/disabling
-- devices (cf. ewok-syscalls-init.adb)
ewok.devices.enable_device (dev_id, ok);
if not ok then
goto ret_denied;
end if;
set_return_value (caller_id, mode, SYS_E_DONE);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_inval>>
set_return_value (caller_id, mode, SYS_E_INVAL);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_denied>>
set_return_value (caller_id, mode, SYS_E_DENIED);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_busy>>
set_return_value (caller_id, mode, SYS_E_BUSY);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
end dev_map;
procedure dev_unmap
(caller_id : in ewok.tasks_shared.t_task_id;
params : in out t_parameters;
mode : in ewok.tasks_shared.t_task_mode)
is
dev_descriptor : unsigned_8
with address => params(1)'address;
dev_id : ewok.devices_shared.t_device_id;
dev : ewok.devices.t_checked_user_device_access;
ok : boolean;
begin
--
-- Checking user inputs
--
-- Task must not be in ISR mode
-- NOTE
-- The reasons to forbid a task in ISR mode to map/unmap some devices
-- are not technical. An ISR *must* be a minimal piece of code that
-- manage only the interrupts provided by a specific hardware.
if mode = ewok.tasks_shared.TASK_MODE_ISRTHREAD then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): forbidden in ISR mode"));
goto ret_denied;
end if;
-- No unmap before end of initialization
if not is_init_done (caller_id) then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): forbidden during init sequence"));
goto ret_denied;
end if;
-- Valid device descriptor ?
if dev_descriptor not in TSK.tasks_list(caller_id).device_id'range
then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): invalid device descriptor"));
goto ret_inval;
end if;
dev_id := TSK.tasks_list(caller_id).device_id (dev_descriptor);
-- Used device descriptor ?
if dev_id = ID_DEV_UNUSED then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): unused device"));
goto ret_inval;
end if;
-- Defensive programming. Verifying that the device really belongs to the
-- task
if ewok.devices.get_task_from_id (dev_id) /= caller_id then
raise program_error;
end if;
-- Verifying that the device may be voluntary unmapped by the task
dev := ewok.devices.get_user_device (dev_id);
if dev.map_mode /= ewok.exported.devices.DEV_MAP_VOLUNTARY then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): not a DEV_MAP_VOLUNTARY device"));
goto ret_denied;
end if;
--
-- Unmapping the device
--
TSK.unmount_device (caller_id, dev_id, ok);
if not ok then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_unmap(): device is not mapped"));
goto ret_denied;
end if;
set_return_value (caller_id, mode, SYS_E_DONE);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_inval>>
set_return_value (caller_id, mode, SYS_E_INVAL);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_denied>>
set_return_value (caller_id, mode, SYS_E_DENIED);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
end dev_unmap;
procedure dev_release
(caller_id : in ewok.tasks_shared.t_task_id;
params : in out t_parameters;
mode : in ewok.tasks_shared.t_task_mode)
is
dev_descriptor : unsigned_8
with address => params(1)'address;
dev_id : ewok.devices_shared.t_device_id;
ok : boolean;
begin
-- No release before end of initialization
if not is_init_done (caller_id) then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_release(): forbidden during init sequence"));
goto ret_denied;
end if;
-- Valid device descriptor ?
if dev_descriptor not in TSK.tasks_list(caller_id).device_id'range
then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_release(): invalid device descriptor"));
goto ret_inval;
end if;
dev_id := TSK.tasks_list(caller_id).device_id (dev_descriptor);
-- Used device descriptor ?
if dev_id = ID_DEV_UNUSED then
pragma DEBUG (debug.log (debug.ERROR,
ewok.tasks.tasks_list(caller_id).name
& ": dev_release(): unused device"));
goto ret_inval;
end if;
-- Defensive programming. Verifying that the device really belongs to the
-- task
if ewok.devices.get_task_from_id (dev_id) /= caller_id then
raise program_error;
end if;
--
-- Releasing the device
--
-- Unmounting the device
if TSK.is_mounted (caller_id, dev_id) then
TSK.unmount_device (caller_id, dev_id, ok);
if not ok then
raise program_error; -- Should never happen
end if;
end if;
-- Removing it from the task's list of used devices
TSK.remove_device (caller_id, dev_id, ok);
if not ok then
raise program_error; -- Should never happen
end if;
-- Release GPIOs, EXTIs and interrupts
ewok.devices.release_device (caller_id, dev_id, ok);
set_return_value (caller_id, mode, SYS_E_DONE);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_inval>>
set_return_value (caller_id, mode, SYS_E_INVAL);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
<<ret_denied>>
set_return_value (caller_id, mode, SYS_E_DENIED);
TSK.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
end dev_release;
end ewok.syscalls.cfg.dev;
|
-- SPDX-FileCopyrightText: 2022 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Bluetooth;
with Ada.Streams;
with Ada.Unchecked_Conversion;
package Locations is
-- Location and navigation profile allows these characteristics:
type Characteristic_Index is
(LN_Feature,
Location_and_Speed,
Battery_Level);
package Bluetooth is new Standard.Bluetooth
(Characteristic_Index => Characteristic_Index,
Byte => Ada.Streams.Stream_Element,
Byte_Index => Ada.Streams.Stream_Element_Offset,
Byte_Array => Ada.Streams.Stream_Element_Array);
Advertising : constant Bluetooth.Advertising_Data :=
Bluetooth.Raw_Data
((16#02#, 16#01#, 16#06#,
16#05#, 16#03#, 16#19#, 16#18#, 16#0F#, 16#18#,
16#07#, 16#09#, 16#4D#, 16#79#, 16#54#, 16#65#, 16#73#, 16#74#));
Read : constant Bluetooth.Characteristic_Property_Set :=
(Bluetooth.Read => True, others => False);
Notify : constant Bluetooth.Characteristic_Property_Set :=
(Bluetooth.Notify => True, others => False);
Location_Supported : constant := 2 ** 2;
Rolling_Time_Supported : constant := 2 ** 5;
UTC_Time_Supported : constant := 2 ** 6;
Location_Present : constant := 2 ** 2;
Rolling_Time_Present : constant := 2 ** 5;
UTC_Time_Present : constant := 2 ** 6;
use type Ada.Streams.Stream_Element_Offset;
-- Latitude sint32:4 Longitude sint32:4 /10**7
-- UTC: yyyy:2 mm:1 dd:1 hh:1 mm:1 ss:1 = 7 bytes
package Peripheral_Device is new Bluetooth.Peripheral_Device
(Advertising => Advertising,
Characteristic_Array =>
(LN_Feature => (16#2A6A#, Read, 4),
Location_and_Speed => (16#2A67#, Notify, 2 + 2 * 4 + 7),
Battery_Level => (16#2A19#, Read, 1)),
Service_Array =>
((16#1819#, LN_Feature, Location_and_Speed),
(16#180F#, Battery_Level, Battery_Level)),
Buffer_Size => 4 + 2 + 2 * 4 + 7 + 1);
subtype Byte_Array_4 is Ada.Streams.Stream_Element_Array (1 .. 4);
function Cast is new Ada.Unchecked_Conversion (Integer, Byte_Array_4);
task Bluetooth_Runner
with Storage_Size => 4096;
end Locations; |
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Matreshka.Internals.Stream_Element_Vectors is
Growth_Factor : constant := 32;
-- The growth factor controls how much extra space is allocated when we
-- have to increase the size of an allocated vector. By allocating extra
-- space, we avoid the need to reallocate on every append, particularly
-- important when a vector is built up by repeated append operations of
-- small pieces. This is expressed as a factor so 32 means add 1/32 of the
-- length of the vector as growth space.
Min_Mul_Alloc : constant
:= Standard'Maximum_Alignment * Standard'Storage_Unit
/ Ada.Streams.Stream_Element'Size;
-- Allocation will be done by a multiple of Min_Mul_Alloc. This causes
-- no memory loss as most (all?) malloc implementations are obliged to
-- align the returned memory on the maximum alignment as malloc does not
-- know the target alignment.
procedure Free is
new Ada.Unchecked_Deallocation
(Shared_Stream_Element_Vector, Shared_Stream_Element_Vector_Access);
function Aligned_Size
(Size : Ada.Streams.Stream_Element_Offset)
return Ada.Streams.Stream_Element_Offset;
pragma Inline (Aligned_Size);
-- Returns recommended size of the shared vector which is greater or equal
-- to specified. Calculation take in sense alignment of the allocated
-- memory segments to use memory effectively by Append/Insert/etc
-- operations.
------------------
-- Aligned_Size --
------------------
function Aligned_Size
(Size : Ada.Streams.Stream_Element_Offset)
return Ada.Streams.Stream_Element_Offset
is
Static_Size : constant Ada.Streams.Stream_Element_Offset
:= (Empty_Shared_Stream_Element_Vector'Size
- Ada.Streams.Stream_Element'Size
* (Empty_Shared_Stream_Element_Vector.Size + 1))
/ Ada.Streams.Stream_Element'Size;
-- Total size of all static components in Code_Unit_16 units.
pragma Assert
((Empty_Shared_Stream_Element_Vector'Size
- Ada.Streams.Stream_Element'Size
* (Empty_Shared_Stream_Element_Vector.Size + 1))
mod Ada.Streams.Stream_Element'Size = 0);
-- Reminder must be zero to compute value correctly.
begin
return
(((Static_Size + Size + Size / Growth_Factor)
/ Min_Mul_Alloc + 1) * Min_Mul_Alloc - Static_Size);
end Aligned_Size;
--------------
-- Allocate --
--------------
function Allocate
(Size : Ada.Streams.Stream_Element_Offset)
return not null Shared_Stream_Element_Vector_Access is
begin
if Size = 0 then
return Empty_Shared_Stream_Element_Vector'Access;
else
return new Shared_Stream_Element_Vector (Aligned_Size (Size) - 1);
end if;
end Allocate;
-------------------
-- Can_Be_Reused --
-------------------
function Can_Be_Reused
(Self : not null Shared_Stream_Element_Vector_Access;
Size : Ada.Streams.Stream_Element_Offset) return Boolean is
begin
return
Self /= Empty_Shared_Stream_Element_Vector'Access
and Self.Size >= Size
and Matreshka.Atomics.Counters.Is_One (Self.Counter);
end Can_Be_Reused;
-----------------
-- Dereference --
-----------------
procedure Dereference (Item : in out Shared_Stream_Element_Vector_Access) is
begin
if Item /= Empty_Shared_Stream_Element_Vector'Access
and then Matreshka.Atomics.Counters.Decrement (Item.Counter)
then
Free (Item);
else
Item := null;
end if;
end Dereference;
---------------
-- Fill_Tail --
---------------
procedure Fill_Tail (Item : not null Shared_Stream_Element_Vector_Access) is
pragma Assert (Ada.Streams.Stream_Element'Size = 8);
Index : Ada.Streams.Stream_Element_Offset := Item.Length;
begin
while Index mod 4 /= 0 loop
Item.Value (Index) := 0;
Index := Index + 1;
end loop;
end Fill_Tail;
----------
-- Hash --
----------
function Hash
(Item : not null Shared_Stream_Element_Vector_Access) return League.Hash_Type
is
use type League.Hash_Type;
M : constant League.Hash_Type := 16#5BD1E995#;
H : League.Hash_Type := League.Hash_Type (Item.Length);
K : League.Hash_Type;
Index : Ada.Streams.Stream_Element_Offset := 0;
Length : Ada.Streams.Stream_Element_Offset := (Item.Length + 3) / 4;
Data :
array (Ada.Streams.Stream_Element_Offset range 0 .. Length - 1)
of League.Hash_Type;
for Data'Address use Item.Value'Address;
pragma Import (Ada, Data);
begin
while Index < Length loop
K := League.Hash_Type (Data (Index)) * M;
K := K xor (K / 16#1000000#);
K := K * M;
H := H * M;
H := H xor K;
Index := Index + 1;
end loop;
H := H xor (H / 16#2000#);
H := H * M;
H := H xor (H / 16#8000#);
return H;
end Hash;
---------------
-- Reference --
---------------
procedure Reference (Item : Shared_Stream_Element_Vector_Access) is
begin
if Item /= Empty_Shared_Stream_Element_Vector'Access then
Matreshka.Atomics.Counters.Increment (Item.Counter);
end if;
end Reference;
end Matreshka.Internals.Stream_Element_Vectors;
|
--
-- Copyright (C) 2022 Jeremy Grosser <jeremy@synack.me>
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with HAL.Time; use HAL.Time;
with HAL.I2C; use HAL.I2C;
with HAL; use HAL;
package SGP30 is
Default_I2C_Address : constant I2C_Address := 16#B0#;
type SGP30_Status is (Ok, I2C_Error, Checksum_Error);
type Device
(Port : not null Any_I2C_Port;
Addr : I2C_Address;
Delays : not null Any_Delays)
is tagged record
Bus_Status : I2C_Status;
Status : SGP30_Status := Ok;
end record;
function Has_Error
(This : Device)
return Boolean;
procedure Clear_Error
(This : in out Device);
procedure Soft_Reset
(This : in out Device);
-- Soft_Reset is a broadcast and will reset all devices on the bus that
-- respond to General Call commands.
procedure Init_Air_Quality
(This : in out Device);
procedure Measure_Air_Quality
(This : in out Device;
eCO2 : out Natural;
TVOC : out Natural);
function Get_Baseline
(This : in out Device)
return UInt32;
procedure Set_Baseline
(This : in out Device;
Baseline : UInt32);
procedure Set_Humidity
(This : in out Device;
Humidity : UInt16);
function Measure_Test
(This : in out Device)
return UInt16;
function Get_Feature_Set_Version
(This : in out Device)
return UInt16;
function Measure_Raw_Signals
(This : in out Device)
return UInt32;
function Get_Serial_Id
(This : in out Device)
return UInt48;
private
function Verify_Checksum
(Data : UInt8_Array)
return Boolean;
function Read_48
(This : in out Device;
Reg : UInt16)
return UInt48;
function Read_32
(This : in out Device;
Reg : UInt16)
return UInt32;
function Read_16
(This : in out Device;
Reg : UInt16)
return UInt16;
procedure Write_32
(This : in out Device;
Reg : UInt16;
Value : UInt32);
procedure Write_16
(This : in out Device;
Reg : UInt16;
Value : UInt16);
procedure Write_Command
(This : in out Device;
Reg : UInt16);
function To_I2C_Data
(X : UInt16)
return I2C_Data;
end SGP30;
|
with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
with Ada.Real_Time; use Ada.Real_Time;
with STM32GD.GPIO;
with STM32GD.GPIO.Pin;
with STM32GD.EXTI;
with STM32GD.Timer;
with STM32GD.Timer.Peripheral;
with STM32GD.Board; use STM32GD.Board;
with Peripherals;
procedure Main is
package GPIO renames STM32GD.GPIO;
package EXTI renames STM32GD.EXTI;
Next_Release : Time := Clock;
Period : constant Time_Span := Milliseconds (50);
procedure Polling_Test is
begin
loop
if EXTI.IRQ_Handler.Status (EXTI.EXTI_Line_0) = True then
LED.Toggle;
EXTI.IRQ_Handler.Reset_Status (EXTI.EXTI_Line_0);
end if;
Next_Release := Next_Release + Period;
delay until Next_Release;
end loop;
end Polling_Test;
procedure Waiting_Test is
begin
loop
Button.Wait_For_Trigger;
LED.Toggle;
end loop;
end Waiting_Test;
procedure Cancel_Test is
begin
Peripherals.Timer.Init;
loop
Peripherals.Timer.After (Milliseconds (5000), Button.Cancel_Wait'Access);
Button.Wait_For_Trigger;
if Button.Triggered then
LED.Toggle;
else
LED.Toggle;
end if;
Button.Clear_Trigger;
end loop;
end Cancel_Test;
begin
Init;
TX.Init;
USART.Init;
Button.Configure_Trigger (EXTI.Interrupt_Falling_Edge);
LED.Set;
-- Polling_Test;
-- Waiting_Test;
Cancel_Test;
end Main;
|
with Config_String_Parsers;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Config_String_Parsers is
function Identity (X : String) return String
is (X);
package Test_Parsers is
new Config_String_Parsers (Name_Type => string,
Value_Type => String,
No_Value => "(null)",
To_Name => Identity,
To_Value => Identity);
procedure Dump (Y : Test_Parsers.Parsing_Result) is
use Test_Parsers.Parameter_Maps, Test_Parsers;
X : constant Test_Parsers.Parameter_Maps.Map := Parameters (Y);
begin
Put_Line ("##################");
Put_line ("header: '"
& (if Has_Header (Y) then Header (Y) else "")
& "'");
for Pos in X.Iterate loop
Put_Line ("'" & Key (Pos) & "' -> '" & Element (Pos) & "'");
end loop;
end Dump;
Params : Test_Parsers.Parsing_Result;
begin
Params := Test_Parsers.Parse (" ciao , pluto= 33 ,zimo-xamo={ 42,33 }");
Dump (Params);
Params := Test_Parsers.Parse
(Input => "zorro : ciao , pluto= 33 ,zimo-xamo={}",
Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe));
Dump (Params);
declare
use Test_Parsers;
Syntax : Syntax_Descriptor;
begin
Add_Parameter_Syntax (Syntax => Syntax,
Parameter_Name => "ciao",
If_Missing => die);
Add_Parameter_Syntax(Syntax => Syntax,
Parameter_Name => "pippo",
If_Missing => Use_Default,
Default => "minima veniali");
Params := Test_Parsers.Parse
(Input => "zorro : ciao , pluto=,zimo-xamo={ 42,33 }",
Syntax => Syntax,
Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe),
On_Unknown_Name => OK);
Dump (Params);
Params := Test_Parsers.Parse
(Input => "zorro : ciao , pippo= 37 ,zimo-xamo={ 42,33 }",
Syntax => Syntax,
Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe),
On_Unknown_Name => OK);
Dump (Params);
Params := Test_Parsers.Parse
(Input => "zorro : ciao=112, pippo={33,11},zimo--xamo={ 42,33 }",
Syntax => Syntax,
Options => Test_Parsers.Config (Expect_Header => Test_Parsers.Maybe),
On_Unknown_Name => OK);
Dump (Params);
end;
end Test_Config_String_Parsers;
|
-- SPDX-FileCopyrightText: 2020 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
----------------------------------------------------------------
with Markdown.List_Items;
with Markdown.Lists;
with Markdown.Visitors;
package body Markdown.Blocks is
type List_Access is access all Markdown.Lists.List'Class;
------------------
-- Append_Child --
------------------
not overriding procedure Append_Child
(Self : in out Container_Block;
Child : not null Block_Access) is
begin
if Self.Last_Child = null then
Child.Next := Child;
else
Child.Next := Self.Last_Child.Next;
Self.Last_Child.Next := Child;
end if;
Self.Last_Child := Child;
end Append_Child;
--------------------
-- Visit_Children --
--------------------
procedure Visit_Children
(Self : Container_Block'Class;
Visitor : in out Markdown.Visitors.Visitor'Class)
is
begin
if Self.Last_Child = null then
return;
end if;
declare
Item : not null Block_Access := Self.Last_Child.Next;
begin
loop
Item.Visit (Visitor);
exit when Item = Self.Last_Child;
Item := Item.Next;
end loop;
end;
end Visit_Children;
---------------------
-- Wrap_List_Items --
---------------------
procedure Wrap_List_Items (Self : in out Container_Block'Class) is
type Visitor is new Markdown.Visitors.Visitor with record
Is_List_Item : Boolean := False;
Is_Ordered : Boolean := False;
Marker : League.Strings.Universal_String;
end record;
overriding procedure List_Item
(Self : in out Visitor;
Value : in out Markdown.List_Items.List_Item);
overriding procedure List_Item
(Self : in out Visitor;
Value : in out Markdown.List_Items.List_Item) is
begin
Self.Is_List_Item := True;
Self.Is_Ordered := Value.Is_Ordered;
Self.Marker := Value.Marker;
end List_Item;
begin
if Self.Last_Child = null then
return;
end if;
declare
List : List_Access;
Last : constant not null Block_Access := Self.Last_Child;
Item : not null Block_Access := Last.Next;
Next : not null Block_Access := Item.Next;
begin
Self.Last_Child := null;
loop
declare
Checker : Visitor;
begin
Item.Visit (Checker);
if Checker.Is_List_Item then
if List = null or else not List.Match (Checker.Marker) then
List := new Markdown.Lists.List;
Self.Append_Child (Block_Access (List));
List.Append_Child (Item);
else
List.Append_Child (Item);
end if;
else
List := null;
Self.Append_Child (Item);
end if;
exit when Item = Last;
Item := Next;
Next := Item.Next;
end;
end loop;
end;
end Wrap_List_Items;
end Markdown.Blocks;
|
-------------------------------------------------------------------------------
-- Copyright 2021, The Trendy Terminal Developers (see AUTHORS file)
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
-- http://www.apache.org/licenses/LICENSE-2.0
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-------------------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.Text_IO;
with Ada.Unchecked_Conversion;
with Interfaces.C.Strings;
with Trendy_Terminal.VT100;
with Trendy_Terminal.Windows;
package body Trendy_Terminal.Platform is
package Win renames Trendy_Terminal.Windows;
use all type ASU.Unbounded_String;
use type Win.BOOL;
use type Win.HANDLE;
---------------------------------------------------------------------------
-- Original settings
---------------------------------------------------------------------------
Input_Settings, Output_Settings, Error_Settings : Win.DWORD;
Original_Input_CP, Original_Output_CP : Win.UINT;
type Input_Stream is record
Handle : Win.HANDLE := Win.INVALID_HANDLE_VALUE;
Settings : Win.Console_Input_Mode := Win.To_Console_Input_Mode (0);
end record;
type Output_Stream is record
Handle : Win.HANDLE := Win.INVALID_HANDLE_VALUE;
Settings : Win.Console_Output_Mode := Win.To_Console_Output_Mode (0);
end record;
---------------------------------------------------------------------------
-- The triad of I/O streams.
---------------------------------------------------------------------------
Std_Input : Input_Stream;
Std_Output, Std_Error : Output_Stream;
---------------------------------------------------------------------------
-- Output
---------------------------------------------------------------------------
procedure Put (H : Win.Handle; C : Character) is
S : constant String := (1 => C);
Native : aliased Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String(S);
Written : aliased Win.DWORD;
begin
if Win.WriteFile (H, Win.LPCVOID(Native), S'Length, Written'Unchecked_Access, 0) = 0 then
null;
end if;
Interfaces.C.Strings.Free(Native);
end Put;
procedure Put(C : Character) is
begin
Put (Std_Output.Handle, C);
end Put;
procedure Put(S : String) is
Native : aliased Interfaces.C.Strings.chars_ptr := Interfaces.C.Strings.New_String(S);
Written : aliased Win.DWORD;
begin
if Win.WriteFile (Std_Output.Handle, Win.LPCVOID(Native), S'Length, Written'Unchecked_Access, 0) = 0 then
null;
end if;
Interfaces.C.Strings.Free(Native);
end Put;
---------------------------------------------------------------------------
-- Start and Shutdown
---------------------------------------------------------------------------
function Load_Std_Settings return Boolean is
Input_DWORD, Output_DWORD, Error_DWORD : aliased Win.DWORD;
begin
if Win.GetConsoleMode (Std_Input.Handle, Input_DWORD'Unchecked_Access) = 0 then
return False;
end if;
if Win.GetConsoleMode (Std_Output.Handle, Output_DWORD'Unchecked_Access) = 0 then
return False;
end if;
if Win.GetConsoleMode (Std_Error.Handle, Error_DWORD'Unchecked_Access) = 0 then
return False;
end if;
Std_Input.Settings := Win.To_Console_Input_Mode (Input_DWORD);
Std_Output.Settings := Win.To_Console_Output_Mode (Output_DWORD);
Std_Error.Settings := Win.To_Console_Output_Mode (Error_DWORD);
return True;
end Load_Std_Settings;
function Enable_UTF8 return Boolean is
begin
return Win.SetConsoleCP (Win.CP_UTF8) /= 0 and then Win.SetConsoleOutputCP (Win.CP_UTF8) /= 0;
end Enable_UTF8;
function Init return Boolean is
begin
Std_Output.Handle := Win.GetStdHandle (Win.STD_OUTPUT_HANDLE);
Std_Input.Handle := Win.GetStdHandle (Win.STD_INPUT_HANDLE);
Std_Error.Handle := Win.GetStdHandle (Win.STD_ERROR_HANDLE);
if Std_Output.Handle = Win.INVALID_HANDLE_VALUE or else Std_Input.Handle = Win.INVALID_HANDLE_VALUE
or else Std_Error.Handle = Win.INVALID_HANDLE_VALUE then
Ada.Text_IO.Put_Line ("Unable to get one or more of in/out/err handles.");
return False;
end if;
if not Load_Std_Settings then
return False;
end if;
-- Save the initial settings to be restored later.
Input_Settings := Win.To_DWORD (Std_Input.Settings);
Output_Settings := Win.To_DWORD (Std_Output.Settings);
Error_Settings := Win.To_DWORD (Std_Error.Settings);
Original_Input_CP := Win.GetConsoleCP;
Original_Output_CP := Win.GetConsoleOutputCP;
if not Enable_UTF8 then
Ada.Text_IO.Put_Line ("Unable to set UTF8 code page.");
return False;
end if;
return True;
end Init;
procedure Shutdown is
begin
if Win.SetConsoleMode (Std_Input.Handle, Input_Settings) = 0
or else Win.SetConsoleMode (Std_Output.Handle, Output_Settings) = 0
or else Win.SetConsoleMode (Std_Error.Handle, Error_Settings) = 0 then
Ada.Text_IO.Put_Line ("Unable to restore all terminal settings to originals.");
end if;
if Win.SetConsoleCP (Original_Input_CP) = 0 or else Win.SetConsoleOutputCP (Original_Output_CP) = 0 then
Ada.Text_IO.Put_Line ("Unable to restore original terminal code page.");
end if;
end Shutdown;
procedure Apply (Input : Input_Stream) is
begin
if Win.SetConsoleMode(Input.Handle, Win.To_DWORD(Input.Settings)) = 0 then
Ada.Text_IO.Put_Line ("Unable to change console modes: ERROR#" & Win.GetLastError'Image);
end if;
end Apply;
procedure Apply (Output : Output_Stream) is
begin
if Win.SetConsoleMode(Output.Handle, Win.To_DWORD(Output.Settings)) = 0 then
Ada.Text_IO.Put_Line ("Unable to change console modes: ERROR# " & Win.GetLastError'Image);
end if;
end Apply;
procedure Set (Setting : Input_Setting; Enabled : Boolean) is
begin
case Setting is
when Echo =>
Std_Input.Settings (Win.ENABLE_ECHO_INPUT) := Enabled;
Apply(Std_Input);
when Line_Input =>
Std_Input.Settings (Win.ENABLE_LINE_INPUT) := Enabled;
Apply(Std_Input);
when Signals_As_Input =>
Std_Input.Settings (Win.ENABLE_PROCESSED_INPUT) := not Enabled;
Apply(Std_Input);
end case;
end Set;
procedure Set (Setting : Output_Setting; Enabled : Boolean) is
begin
case Setting is
when Escape_Sequences =>
Std_Output.Settings (Win.ENABLE_VIRTUAL_TERMINAL_PROCESSING) := Enabled;
Std_Output.Settings (Win.ENABLE_WRAP_AT_EOL_OUTPUT) := True;
Std_Output.Settings (Win.DISABLE_NEWLINE_AUTO_RETURN) := False;
Std_Output.Settings (Win.ENABLE_PROCESSED_OUTPUT) := True;
Std_Error.Settings (Win.ENABLE_VIRTUAL_TERMINAL_PROCESSING) := Enabled;
Std_Error.Settings (Win.ENABLE_WRAP_AT_EOL_OUTPUT) := True;
Std_Error.Settings (Win.DISABLE_NEWLINE_AUTO_RETURN) := False;
Std_Error.Settings (Win.ENABLE_PROCESSED_OUTPUT) := True;
Std_Input.Settings (Win.ENABLE_VIRTUAL_TERMINAL_INPUT) := Enabled;
Apply(Std_Input);
Apply(Std_Output);
Apply(Std_Error);
end case;
end Set;
---------------------------------------------------------------------------
-- Inputs
---------------------------------------------------------------------------
-- Gets an entire input line from one keypress. E.g. all the characters
-- received for a controlling keypress, such as an arrow key.
function Get_Input return String is
Buffer_Size : constant := 512;
Buffer : aliased Interfaces.C.char_array := (1 .. Interfaces.C.size_t(Buffer_Size) => Interfaces.C.nul);
Chars_Read : aliased Win.DWORD;
use all type Interfaces.C.size_t;
begin
if Win.ReadConsoleA (Std_Input.Handle, Win.LPVOID(Interfaces.C.Strings.To_Chars_Ptr(Buffer'Unchecked_Access)),
Buffer_Size, Chars_Read'Unchecked_Access, 0) /= 0 then
return Interfaces.C.To_Ada(Buffer(1 .. Interfaces.C.size_t(Chars_Read) + 1));
else
return "";
end if;
end Get_Input;
function End_Of_Line return String is
begin
return Ada.Characters.Latin_1.CR & Ada.Characters.Latin_1.LF;
end End_Of_Line;
procedure Print_Configuration is
begin
Ada.Text_IO.Put_Line ("Input Mode: " & Win.To_DWORD (Std_Input.Settings)'Image);
Ada.Text_IO.Put_Line ("Output Mode: " & Win.To_DWORD (Std_Output.Settings)'Image);
Ada.Text_IO.Put_Line ("Error Mode: " & Win.To_DWORD (Std_Error.Settings)'Image);
end Print_Configuration;
end Trendy_Terminal.Platform;
|
with STM32GD.Timer;
with STM32GD.Timer.Peripheral;
with STM32_SVD.Interrupts;
package Peripherals is
package Timer is new STM32GD.Timer.Peripheral;
end Peripherals;
|
-- This spec has been automatically generated from STM32WB55x.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package STM32_SVD.TIM16 is
pragma Preelaborate;
---------------
-- Registers --
---------------
subtype CR1_CKD_Field is HAL.UInt2;
type CR1_Register is record
CEN : Boolean := False;
UDIS : Boolean := False;
URS : Boolean := False;
OPM : Boolean := False;
-- unspecified
Reserved_4_6 : HAL.UInt3 := 16#0#;
ARPE : Boolean := False;
CKD : CR1_CKD_Field := 16#0#;
-- unspecified
Reserved_10_10 : HAL.Bit := 16#0#;
UIFREMAP : Boolean := False;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR1_Register use record
CEN at 0 range 0 .. 0;
UDIS at 0 range 1 .. 1;
URS at 0 range 2 .. 2;
OPM at 0 range 3 .. 3;
Reserved_4_6 at 0 range 4 .. 6;
ARPE at 0 range 7 .. 7;
CKD at 0 range 8 .. 9;
Reserved_10_10 at 0 range 10 .. 10;
UIFREMAP at 0 range 11 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
type CR2_Register is record
CCPC : Boolean := False;
-- unspecified
Reserved_1_1 : HAL.Bit := 16#0#;
CCUS : Boolean := False;
CCDS : Boolean := False;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
OIS1 : Boolean := False;
OIS1N : Boolean := False;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR2_Register use record
CCPC at 0 range 0 .. 0;
Reserved_1_1 at 0 range 1 .. 1;
CCUS at 0 range 2 .. 2;
CCDS at 0 range 3 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
OIS1 at 0 range 8 .. 8;
OIS1N at 0 range 9 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
type DIER_Register is record
UIE : Boolean := False;
CC1IE : Boolean := False;
-- unspecified
Reserved_2_4 : HAL.UInt3 := 16#0#;
COMIE : Boolean := False;
-- unspecified
Reserved_6_6 : HAL.Bit := 16#0#;
BIE : Boolean := False;
UDE : Boolean := False;
CC1DE : Boolean := False;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DIER_Register use record
UIE at 0 range 0 .. 0;
CC1IE at 0 range 1 .. 1;
Reserved_2_4 at 0 range 2 .. 4;
COMIE at 0 range 5 .. 5;
Reserved_6_6 at 0 range 6 .. 6;
BIE at 0 range 7 .. 7;
UDE at 0 range 8 .. 8;
CC1DE at 0 range 9 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
type SR_Register is record
UIF : Boolean := False;
CC1IF : Boolean := False;
-- unspecified
Reserved_2_4 : HAL.UInt3 := 16#0#;
COMIF : Boolean := False;
-- unspecified
Reserved_6_6 : HAL.Bit := 16#0#;
BIF : Boolean := False;
-- unspecified
Reserved_8_8 : HAL.Bit := 16#0#;
CC1OF : Boolean := False;
-- unspecified
Reserved_10_31 : HAL.UInt22 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR_Register use record
UIF at 0 range 0 .. 0;
CC1IF at 0 range 1 .. 1;
Reserved_2_4 at 0 range 2 .. 4;
COMIF at 0 range 5 .. 5;
Reserved_6_6 at 0 range 6 .. 6;
BIF at 0 range 7 .. 7;
Reserved_8_8 at 0 range 8 .. 8;
CC1OF at 0 range 9 .. 9;
Reserved_10_31 at 0 range 10 .. 31;
end record;
type EGR_Register is record
UG : Boolean := False;
CC1G : Boolean := False;
-- unspecified
Reserved_2_4 : HAL.UInt3 := 16#0#;
COMG : Boolean := False;
-- unspecified
Reserved_6_6 : HAL.Bit := 16#0#;
BG : Boolean := False;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EGR_Register use record
UG at 0 range 0 .. 0;
CC1G at 0 range 1 .. 1;
Reserved_2_4 at 0 range 2 .. 4;
COMG at 0 range 5 .. 5;
Reserved_6_6 at 0 range 6 .. 6;
BG at 0 range 7 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype CCMR1_Output_CC1S_Field is HAL.UInt2;
subtype CCMR1_Output_OC1M_Field is HAL.UInt3;
type CCMR1_Output_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
CC1S : CCMR1_Output_CC1S_Field := 16#0#;
OC1FE : Boolean := False;
OC1PE : Boolean := False;
OC1M : CCMR1_Output_OC1M_Field := 16#0#;
-- unspecified
Reserved_8_15 : HAL.UInt8 := 16#0#;
OC1M_1 : Boolean := False;
-- unspecified
Reserved_17_31 : HAL.UInt15 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCMR1_Output_Register use record
Reserved_0_0 at 0 range 0 .. 0;
CC1S at 0 range 1 .. 2;
OC1FE at 0 range 3 .. 3;
OC1PE at 0 range 4 .. 4;
OC1M at 0 range 5 .. 7;
Reserved_8_15 at 0 range 8 .. 15;
OC1M_1 at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype CCMR1_Input_CC1S_Field is HAL.UInt2;
subtype CCMR1_Input_IC1PSC_Field is HAL.UInt2;
subtype CCMR1_Input_IC1F_Field is HAL.UInt4;
type CCMR1_Input_Register is record
CC1S : CCMR1_Input_CC1S_Field := 16#0#;
IC1PSC : CCMR1_Input_IC1PSC_Field := 16#0#;
IC1F : CCMR1_Input_IC1F_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCMR1_Input_Register use record
CC1S at 0 range 0 .. 1;
IC1PSC at 0 range 2 .. 3;
IC1F at 0 range 4 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
type CCER_Register is record
CC1E : Boolean := False;
CC1P : Boolean := False;
CC1NE : Boolean := False;
CC1NP : Boolean := False;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCER_Register use record
CC1E at 0 range 0 .. 0;
CC1P at 0 range 1 .. 1;
CC1NE at 0 range 2 .. 2;
CC1NP at 0 range 3 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
subtype CNT_CNT_Field is HAL.UInt16;
type CNT_Register is record
CNT : CNT_CNT_Field := 16#0#;
-- unspecified
Reserved_16_30 : HAL.UInt15 := 16#0#;
UIFCPY : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CNT_Register use record
CNT at 0 range 0 .. 15;
Reserved_16_30 at 0 range 16 .. 30;
UIFCPY at 0 range 31 .. 31;
end record;
subtype PSC_PSC_Field is HAL.UInt16;
type PSC_Register is record
PSC : PSC_PSC_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for PSC_Register use record
PSC at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype ARR_ARR_Field is HAL.UInt16;
type ARR_Register is record
ARR : ARR_ARR_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ARR_Register use record
ARR at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype RCR_REP_Field is HAL.UInt8;
type RCR_Register is record
REP : RCR_REP_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for RCR_Register use record
REP at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype CCR1_CCR1_Field is HAL.UInt16;
type CCR1_Register is record
CCR1 : CCR1_CCR1_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CCR1_Register use record
CCR1 at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype BDTR_DT_Field is HAL.UInt8;
subtype BDTR_LOCK_Field is HAL.UInt2;
type BDTR_Register is record
DT : BDTR_DT_Field := 16#0#;
LOCK : BDTR_LOCK_Field := 16#0#;
OSSI : Boolean := False;
OSSR : Boolean := False;
BKE : Boolean := False;
BKP : Boolean := False;
AOE : Boolean := False;
MOE : Boolean := False;
-- unspecified
Reserved_16_25 : HAL.UInt10 := 16#0#;
BKDSRM : Boolean := False;
-- unspecified
Reserved_27_27 : HAL.Bit := 16#0#;
BKBID : Boolean := False;
-- unspecified
Reserved_29_31 : HAL.UInt3 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for BDTR_Register use record
DT at 0 range 0 .. 7;
LOCK at 0 range 8 .. 9;
OSSI at 0 range 10 .. 10;
OSSR at 0 range 11 .. 11;
BKE at 0 range 12 .. 12;
BKP at 0 range 13 .. 13;
AOE at 0 range 14 .. 14;
MOE at 0 range 15 .. 15;
Reserved_16_25 at 0 range 16 .. 25;
BKDSRM at 0 range 26 .. 26;
Reserved_27_27 at 0 range 27 .. 27;
BKBID at 0 range 28 .. 28;
Reserved_29_31 at 0 range 29 .. 31;
end record;
subtype DCR_DBA_Field is HAL.UInt5;
subtype DCR_DBL_Field is HAL.UInt5;
type DCR_Register is record
DBA : DCR_DBA_Field := 16#0#;
-- unspecified
Reserved_5_7 : HAL.UInt3 := 16#0#;
DBL : DCR_DBL_Field := 16#0#;
-- unspecified
Reserved_13_31 : HAL.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DCR_Register use record
DBA at 0 range 0 .. 4;
Reserved_5_7 at 0 range 5 .. 7;
DBL at 0 range 8 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
subtype DMAR_DMAB_Field is HAL.UInt16;
type DMAR_Register is record
DMAB : DMAR_DMAB_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for DMAR_Register use record
DMAB at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype TIM16_OR1_TI1_RMP_Field is HAL.UInt2;
type TIM16_OR1_Register is record
TI1_RMP : TIM16_OR1_TI1_RMP_Field := 16#0#;
-- unspecified
Reserved_2_31 : HAL.UInt30 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM16_OR1_Register use record
TI1_RMP at 0 range 0 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
subtype TIM17_OR1_TI1_RMP_Field is HAL.UInt2;
type TIM17_OR1_Register is record
TI1_RMP : TIM17_OR1_TI1_RMP_Field := 16#0#;
-- unspecified
Reserved_2_31 : HAL.UInt30 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM17_OR1_Register use record
TI1_RMP at 0 range 0 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
type TIM16_AF1_Register is record
BKINE : Boolean := False;
BKCMP1E : Boolean := False;
BKCMP2E : Boolean := False;
-- unspecified
Reserved_3_8 : HAL.UInt6 := 16#0#;
BKINP : Boolean := False;
BKCMP1P : Boolean := False;
BKCMP2P : Boolean := False;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM16_AF1_Register use record
BKINE at 0 range 0 .. 0;
BKCMP1E at 0 range 1 .. 1;
BKCMP2E at 0 range 2 .. 2;
Reserved_3_8 at 0 range 3 .. 8;
BKINP at 0 range 9 .. 9;
BKCMP1P at 0 range 10 .. 10;
BKCMP2P at 0 range 11 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
type TIM17_AF1_Register is record
BKINE : Boolean := False;
BKCMP1E : Boolean := False;
BKCMP2E : Boolean := False;
-- unspecified
Reserved_3_8 : HAL.UInt6 := 16#0#;
BKINP : Boolean := False;
BKCMP1P : Boolean := False;
BKCMP2P : Boolean := False;
-- unspecified
Reserved_12_31 : HAL.UInt20 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM17_AF1_Register use record
BKINE at 0 range 0 .. 0;
BKCMP1E at 0 range 1 .. 1;
BKCMP2E at 0 range 2 .. 2;
Reserved_3_8 at 0 range 3 .. 8;
BKINP at 0 range 9 .. 9;
BKCMP1P at 0 range 10 .. 10;
BKCMP2P at 0 range 11 .. 11;
Reserved_12_31 at 0 range 12 .. 31;
end record;
subtype TIM16_TISEL_TI1SEL_Field is HAL.UInt4;
type TIM16_TISEL_Register is record
TI1SEL : TIM16_TISEL_TI1SEL_Field := 16#0#;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM16_TISEL_Register use record
TI1SEL at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
subtype TIM17_TISEL_TI1SEL_Field is HAL.UInt4;
type TIM17_TISEL_Register is record
TI1SEL : TIM17_TISEL_TI1SEL_Field := 16#0#;
-- unspecified
Reserved_4_31 : HAL.UInt28 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for TIM17_TISEL_Register use record
TI1SEL at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
type TIM16_Disc is
(
Output,
Input,
TIM16_Disc_6_Or1,
TIM16_Disc_7_Or1,
TIM16_Disc_6_Af1,
TIM16_Disc_7_Af1,
TIM16_Disc_6_Tisel,
TIM16_Disc_7_Tisel);
type TIM16_Peripheral
(Discriminent : TIM16_Disc := Output)
is record
CR1 : aliased CR1_Register;
CR2 : aliased CR2_Register;
DIER : aliased DIER_Register;
SR : aliased SR_Register;
EGR : aliased EGR_Register;
CCER : aliased CCER_Register;
CNT : aliased CNT_Register;
PSC : aliased PSC_Register;
ARR : aliased ARR_Register;
RCR : aliased RCR_Register;
CCR1 : aliased CCR1_Register;
BDTR : aliased BDTR_Register;
DCR : aliased DCR_Register;
DMAR : aliased DMAR_Register;
case Discriminent is
when Output =>
CCMR1_Output : aliased CCMR1_Output_Register;
when Input =>
CCMR1_Input : aliased CCMR1_Input_Register;
when TIM16_Disc_6_Or1 =>
TIM16_OR1 : aliased TIM16_OR1_Register;
when TIM16_Disc_7_Or1 =>
TIM17_OR1 : aliased TIM17_OR1_Register;
when TIM16_Disc_6_Af1 =>
TIM16_AF1 : aliased TIM16_AF1_Register;
when TIM16_Disc_7_Af1 =>
TIM17_AF1 : aliased TIM17_AF1_Register;
when TIM16_Disc_6_Tisel =>
TIM16_TISEL : aliased TIM16_TISEL_Register;
when TIM16_Disc_7_Tisel =>
TIM17_TISEL : aliased TIM17_TISEL_Register;
end case;
end record
with Unchecked_Union, Volatile;
for TIM16_Peripheral use record
CR1 at 16#0# range 0 .. 31;
CR2 at 16#4# range 0 .. 31;
DIER at 16#C# range 0 .. 31;
SR at 16#10# range 0 .. 31;
EGR at 16#14# range 0 .. 31;
CCER at 16#20# range 0 .. 31;
CNT at 16#24# range 0 .. 31;
PSC at 16#28# range 0 .. 31;
ARR at 16#2C# range 0 .. 31;
RCR at 16#30# range 0 .. 31;
CCR1 at 16#34# range 0 .. 31;
BDTR at 16#44# range 0 .. 31;
DCR at 16#48# range 0 .. 31;
DMAR at 16#4C# range 0 .. 31;
CCMR1_Output at 16#18# range 0 .. 31;
CCMR1_Input at 16#18# range 0 .. 31;
TIM16_OR1 at 16#50# range 0 .. 31;
TIM17_OR1 at 16#50# range 0 .. 31;
TIM16_AF1 at 16#60# range 0 .. 31;
TIM17_AF1 at 16#60# range 0 .. 31;
TIM16_TISEL at 16#68# range 0 .. 31;
TIM17_TISEL at 16#68# range 0 .. 31;
end record;
TIM16_Periph : aliased TIM16_Peripheral
with Import, Address => System'To_Address (16#40014400#);
end STM32_SVD.TIM16;
|
-----------------------------------------------------------------------
-- util-listeners -- Listeners
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Concurrent.Arrays;
-- == Introduction ==
-- The `Listeners` package implements a simple observer/listener design pattern.
-- A subscriber registers to a list. When a change is made on an object, the
-- application can notify the subscribers which are then called with the object.
--
-- == Creating the listener list ==
-- The listeners list contains a list of listener interfaces.
--
-- L : Util.Listeners.List;
--
-- The list is heterogeneous meaning that several kinds of listeners could
-- be registered.
--
-- == Creating the observers ==
-- First the `Observers` package must be instantiated with the type being
-- observed. In the example below, we will observe a string:
--
-- package String_Observers is new Util.Listeners.Observers (String);
--
-- == Implementing the observer ==
-- Now we must implement the string observer:
--
-- type String_Observer is new String_Observer.Observer with null record;
-- procedure Update (List : in String_Observer; Item : in String);
--
-- == Registering the observer ==
-- An instance of the string observer must now be registered in the list.
--
-- O : aliased String_Observer;
-- L.Append (O'Access);
--
-- == Publishing ==
-- Notifying the listeners is done by invoking the `Notify` operation
-- provided by the `String_Observers` package:
--
-- String_Observer.Notify (L, "Hello");
--
package Util.Listeners is
-- The listener root interface.
type Listener is limited interface;
type Listener_Access is access all Listener'Class;
-- The multi-task safe list of listeners.
package Listener_Arrays is new Util.Concurrent.Arrays (Listener_Access);
-- ------------------------------
-- List of listeners
-- ------------------------------
-- The `List` type is a list of listeners that have been registered and must be
-- called when a notification is sent. The list uses the concurrent arrays thus
-- allowing tasks to add or remove listeners while dispatching is also running.
subtype List is Listener_Arrays.Vector;
procedure Add_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Append;
procedure Remove_Listener (Into : in out Listener_Arrays.Vector;
Item : in Listener_Access) renames Listener_Arrays.Remove;
end Util.Listeners;
|
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with STM32F4.Reset_Clock_Control; use STM32F4.Reset_Clock_Control;
package body STM32F4.I2C is
subtype I2C_SR1_Flag is I2C_Flag range SB .. SMBALERT;
subtype I2C_SR2_Flag is I2C_Flag range MSL .. DUALF;
SR1_Flag_Pos : constant array (I2C_SR1_Flag) of Natural :=
(0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12, 14, 15);
SR2_Flag_Pos : constant array (I2C_SR2_Flag) of Natural :=
(0, 1, 2, 4, 5, 6, 7);
---------------
-- Configure --
---------------
procedure Configure (Port : out I2C_Port; Conf : I2C_Config) is
CR2, CR1 : Half_Word;
CCR : Half_Word := 0;
Pclk1 : Word;
Freq_Range : Half_Word;
begin
-- Load CR2 and clear FREQ
-- the Reference Manual, RM0090, Doc ID 018909 Rev 6 843 specifies that the
-- reset value for Cr2 is zero so we just clear it
-- CR2 := Port.CR2 and (not 16#3F#);
CR2 := 0;
-- Compute frequency from pclk1
Pclk1 := Get_Clock_Frequency.Pclk1;
Freq_Range := Half_Word (Pclk1 / 1_000_000);
if Freq_Range < 2 or else Freq_Range > 42 then
raise Program_Error;
end if;
Port.CR2 := CR2 or Freq_Range;
Set_State (Port, Disabled);
if Conf.Clock_Speed <= 100_000 then
CCR := Half_Word (Pclk1 / (Conf.Clock_Speed * 2));
if CCR < 4 then
CCR := 4;
end if;
Port.TRISE := Freq_Range + 1;
else
-- Fast mode
if Conf.Duty_Cycle = I2C_DutyCycle_2 then
CCR := Half_Word (Pclk1 / (Conf.Clock_Speed * 3));
else
CCR := Half_Word (Pclk1 / (Conf.Clock_Speed * 25));
CCR := CCR or I2C_DutyCycle_16_9;
end if;
if (CCR and 16#0FFF#) = 0 then
CCR := 1;
end if;
CCR := CCR or 16#80#;
Port.TRISE := (Freq_Range * 300) / 1000 + 1;
end if;
Port.CCR := CCR;
Set_State (Port, Enabled);
CR1 := Port.CR1;
CR1 := CR1 and 16#FBF5#;
CR1 := CR1 or Conf.Mode or Conf.Ack;
Port.CR1 := CR1;
Port.OAR1 := Conf.Ack_Address or Conf.Own_Address;
end Configure;
---------------
-- Set_State --
---------------
procedure Set_State (Port : in out I2C_Port; State : I2C_State) is
begin
if State = Enabled then
Port.CR1 := Port.CR1 or CR1_PE;
else
Port.CR1 := Port.CR1 and (not CR1_PE);
end if;
end Set_State;
----------------
-- Is_Enabled --
----------------
function Is_Enabled (Port : I2C_Port) return Boolean is
begin
return (Port.CR1 and 16#01#) /= 0;
end Is_Enabled;
--------------------
-- Generate_Start --
--------------------
procedure Generate_Start (Port : in out I2C_Port; State : I2C_State) is
begin
if State = Enabled then
Port.CR1 := Port.CR1 or CR1_START;
else
Port.CR1 := Port.CR1 and (not CR1_START);
end if;
end Generate_Start;
-------------------
-- Generate_Stop --
-------------------
procedure Generate_Stop (Port : in out I2C_Port; State : I2C_State) is
begin
if State = Enabled then
Port.CR1 := Port.CR1 or CR1_STOP;
else
Port.CR1 := Port.CR1 and (not CR1_STOP);
end if;
end Generate_Stop;
--------------------
-- Send_7Bit_Addr --
--------------------
procedure Send_7Bit_Addr
(Port : in out I2C_Port;
Addr : Byte;
Dir : I2C_Direction)
is
Address : Half_Word := Half_Word (Addr);
begin
if Dir = Receiver then
Address := Address or I2C_OAR1_ADD0;
else
Address := Address and (not I2C_OAR1_ADD0);
end if;
Port.DR := Address;
end Send_7Bit_Addr;
--------------
-- Get_Flag --
--------------
function Get_Flag (Port : I2C_Port; Flag : I2C_Flag) return Boolean is
begin
if Flag in I2C_SR1_Flag then
return (Port.SR1 and (2**SR1_Flag_Pos (Flag))) /= 0;
else
return (Port.SR2 and (2**SR2_Flag_Pos (Flag))) /= 0;
end if;
end Get_Flag;
----------------
-- Clear_Flag --
----------------
procedure Clear_Flag (Port : in out I2C_Port; Flag : I2C_Flag) is
Unref : Half_Word with Unreferenced;
begin
if Flag = ADDR then
-- To clear the ADDR flag we have to read SR2 after reading SR1
Unref := Port.SR1;
Unref := Port.SR2;
else
if Flag in I2C_SR1_Flag then
Port.SR1 := Port.SR1 and (not (2**SR1_Flag_Pos (Flag)));
else
Port.SR2 := Port.SR2 and (not (2**SR2_Flag_Pos (Flag)));
end if;
end if;
end Clear_Flag;
-------------------
-- Wait_For_Flag --
-------------------
procedure Wait_For_Flag (Port : I2C_Port;
Flag : I2C_Flag;
State : I2C_State;
Time_Out : Natural := 1_000_000)
is
pragma Unreferenced (Time_Out);
Expected : constant Boolean := (if State = Enabled then True else False);
-- Cnt : Natural := Time_Out;
begin
while Get_Flag (Port, Flag) /= Expected loop
-- Cnt := Cnt - 1;
-- if Cnt = 0 then
-- raise Program_Error;
-- end if;
null;
end loop;
end Wait_For_Flag;
---------------
-- Send_Data --
---------------
procedure Send_Data (Port : in out I2C_Port; Data : Byte) is
begin
Port.DR := Half_Word (Data);
end Send_Data;
---------------
-- Read_Data --
---------------
function Read_Data (Port : I2C_Port) return Byte is
begin
return Byte (Port.DR);
end Read_Data;
--------------------
-- Set_Ack_Config --
--------------------
procedure Set_Ack_Config (Port : in out I2C_Port; State : I2C_State) is
begin
if State = Enabled then
Port.CR1 := Port.CR1 or CR1_ACK;
else
Port.CR1 := Port.CR1 and (not CR1_ACK);
end if;
end Set_Ack_Config;
---------------------
-- Set_Nack_Config --
---------------------
procedure Set_Nack_Config (Port : in out I2C_Port; Pos : I2C_Nack_Position) is
begin
if Pos = Next then
Port.CR1 := Port.CR1 or CR1_POS;
else
Port.CR1 := Port.CR1 and (not CR1_POS);
end if;
end Set_Nack_Config;
end STM32F4.I2C;
|
-- AOC 2020, Day 13
with Ada.Containers.Vectors;
package Day is
type Schedule is private;
function load_file(filename : in String) return Schedule;
function bus_mult(s : in Schedule) return Long_Long_Integer;
function earliest_matching(s : in Schedule) return Long_Long_Integer;
function earliest_matching_iterative(s : in Schedule) return Long_Long_Integer;
private
package Depart_Vectors is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Long_Long_Integer);
use Depart_Vectors;
type Schedule is record
earliest : Long_Long_Integer := 0;
departures : Depart_Vectors.Vector := Empty_Vector;
offsets : Depart_Vectors.Vector := Empty_Vector;
end record;
end Day;
|
-- Copyright 2017-2021 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
name = "ShadowServer"
type = "misc"
local shadowServerWhoisAddress = ""
-- shadowServerWhoisURL is the URL for the ShadowServer whois server.
local shadowServerWhoisURL = "asn.shadowserver.org"
function start()
set_rate_limit(2)
end
function asn(ctx, addr, asn)
if (shadowServerWhoisAddress == "") then
shadowServerWhoisAddress = get_whois_addr(ctx)
if (shadowServerWhoisAddress == "") then return end
end
local result
if (asn == 0) then
if (addr == "") then return end
result = origin(ctx, addr)
if (result == nil) then return end
check_rate_limit()
local cidrs = netblocks(ctx, result.asn)
if (cidrs == nil or #cidrs == 0) then return end
result['netblocks'] = cidrs
else
local cidrs = netblocks(ctx, asn)
if (cidrs == nil or #cidrs == 0) then return end
check_rate_limit()
if (addr == "") then
local parts = split(cidrs[1], "/")
if (#parts < 2) then return end
addr = parts[1]
end
result = origin(ctx, addr)
if (result == nil) then return end
result['netblocks'] = cidrs
end
new_asn(ctx, result)
check_rate_limit()
end
function origin(ctx, addr)
if not is_ipv4(addr) then return nil end
local name = reverse_ip(addr) .. ".origin.asn.shadowserver.org"
local resp, err = resolve(ctx, name, "TXT", false)
if ((err ~= nil and err ~= "") or #resp == 0) then return nil end
local fields = split(resp[1].rrdata, "|")
return {
['addr']=addr,
['asn']=tonumber(trim_space(fields[1])),
['prefix']=trim_space(fields[2]),
['cc']=trim_space(fields[4]),
['desc']=trim_space(fields[3]) .. " - " .. trim_space(fields[5]),
}
end
function netblocks(ctx, asn)
local conn, err = socket.connect(ctx, shadowServerWhoisAddress, 43, "tcp")
if (err ~= nil and err ~= "") then return nil end
_, err = conn:send("prefix " .. tostring(asn) .. "\n")
if (err ~= nil and err ~= "") then
conn:close()
return nil
end
local data
data, err = conn:recv_all()
if (err ~= nil and err ~= "") then
conn:close()
return nil
end
local netblocks = {}
for _, block in pairs(split(data, "\n")) do
table.insert(netblocks, trim_space(block))
end
conn:close()
return netblocks
end
function split(str, delim)
local result = {}
local pattern = "[^%" .. delim .. "]+"
local matches = find(str, pattern)
if (matches == nil or #matches == 0) then return result end
for _, match in pairs(matches) do
table.insert(result, match)
end
return result
end
function get_whois_addr(ctx)
local resp, err = resolve(ctx, shadowServerWhoisURL, "A", false)
if ((err ~= nil and err ~= "") or #resp == 0) then return "" end
return resp[1].rrdata
end
function is_ipv4(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
if (#octets == 4) then
for _, v in pairs(octets) do
if tonumber(v) > 255 then return false end
end
return true
end
return false
end
function reverse_ip(addr)
local octets = { addr:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$") }
local ip = ""
for i, o in pairs(octets) do
local n = o
if (i ~= 1) then n = n .. "." end
ip = n .. ip
end
return ip
end
function trim_space(s)
if (s == nil) then
return ""
end
return s:match( "^%s*(.-)%s*$" )
end
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- R E S T R I C T --
-- --
-- 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. 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 Casing; use Casing;
with Einfo; use Einfo;
with Errout; use Errout;
with Debug; use Debug;
with Fname; use Fname;
with Fname.UF; use Fname.UF;
with Lib; use Lib;
with Opt; use Opt;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Stand; use Stand;
with Uname; use Uname;
package body Restrict is
-------------------------------
-- SPARK Restriction Control --
-------------------------------
-- SPARK HIDE directives allow the effect of the SPARK_05 restriction to be
-- turned off for a specified region of code, and the following tables are
-- the data structures used to keep track of these regions.
-- The table contains pairs of source locations, the first being the start
-- location for hidden region, and the second being the end location.
-- Note that the start location is included in the hidden region, while
-- the end location is excluded from it. (It typically corresponds to the
-- next token during scanning.)
type SPARK_Hide_Entry is record
Start : Source_Ptr;
Stop : Source_Ptr;
end record;
package SPARK_Hides is new Table.Table (
Table_Component_Type => SPARK_Hide_Entry,
Table_Index_Type => Natural,
Table_Low_Bound => 1,
Table_Initial => 100,
Table_Increment => 200,
Table_Name => "SPARK Hides");
--------------------------------
-- Package Local Declarations --
--------------------------------
Config_Cunit_Boolean_Restrictions : Save_Cunit_Boolean_Restrictions;
-- Save compilation unit restrictions set by config pragma files
Restricted_Profile_Result : Boolean := False;
-- This switch memoizes the result of Restricted_Profile function calls for
-- improved efficiency. Valid only if Restricted_Profile_Cached is True.
-- Note: if this switch is ever set True, it is never turned off again.
Restricted_Profile_Cached : Boolean := False;
-- This flag is set to True if the Restricted_Profile_Result contains the
-- correct cached result of Restricted_Profile calls.
No_Specification_Of_Aspects : array (Aspect_Id) of Source_Ptr :=
(others => No_Location);
-- Entries in this array are set to point to a previously occuring pragma
-- that activates a No_Specification_Of_Aspect check.
No_Specification_Of_Aspect_Warning : array (Aspect_Id) of Boolean :=
(others => True);
-- An entry in this array is set False in reponse to a previous call to
-- Set_No_Speficiation_Of_Aspect for pragmas in the main unit that
-- specify Warning as False. Once set False, an entry is never reset.
No_Specification_Of_Aspect_Set : Boolean := False;
-- Set True if any entry of No_Specifcation_Of_Aspects has been set True.
-- Once set True, this is never turned off again.
No_Use_Of_Attribute : array (Attribute_Id) of Source_Ptr :=
(others => No_Location);
No_Use_Of_Attribute_Warning : array (Attribute_Id) of Boolean :=
(others => False);
No_Use_Of_Attribute_Set : Boolean := False;
-- Indicates that No_Use_Of_Attribute was set at least once
No_Use_Of_Pragma : array (Pragma_Id) of Source_Ptr :=
(others => No_Location);
-- Source location of pragma No_Use_Of_Pragma for given pragma, a value
-- of System_Location indicates occurrence in system.ads.
No_Use_Of_Pragma_Warning : array (Pragma_Id) of Boolean :=
(others => False);
No_Use_Of_Pragma_Set : Boolean := False;
-- Indicates that No_Use_Of_Pragma was set at least once
-----------------------
-- Local Subprograms --
-----------------------
procedure Restriction_Msg (R : Restriction_Id; N : Node_Id);
-- Called if a violation of restriction R at node N is found. This routine
-- outputs the appropriate message or messages taking care of warning vs
-- real violation, serious vs non-serious, implicit vs explicit, the second
-- message giving the profile name if needed, and the location information.
function Same_Entity (E1, E2 : Node_Id) return Boolean;
-- Returns True iff E1 and E2 represent the same entity. Used for handling
-- of No_Use_Of_Entity => fully_qualified_ENTITY restriction case.
function Same_Unit (U1, U2 : Node_Id) return Boolean;
-- Returns True iff U1 and U2 represent the same library unit. Used for
-- handling of No_Dependence => Unit restriction case.
function Suppress_Restriction_Message (N : Node_Id) return Boolean;
-- N is the node for a possible restriction violation message, but the
-- message is to be suppressed if this is an internal file and this file is
-- not the main unit. Returns True if message is to be suppressed.
-------------------
-- Abort_Allowed --
-------------------
function Abort_Allowed return Boolean is
begin
if Restrictions.Set (No_Abort_Statements)
and then Restrictions.Set (Max_Asynchronous_Select_Nesting)
and then Restrictions.Value (Max_Asynchronous_Select_Nesting) = 0
then
return False;
else
return True;
end if;
end Abort_Allowed;
----------------------------------------
-- Add_To_Config_Boolean_Restrictions --
----------------------------------------
procedure Add_To_Config_Boolean_Restrictions (R : Restriction_Id) is
begin
Config_Cunit_Boolean_Restrictions (R) := True;
end Add_To_Config_Boolean_Restrictions;
-- Add specified restriction to stored configuration boolean restrictions.
-- This is used for handling the special case of No_Elaboration_Code.
-------------------------
-- Check_Compiler_Unit --
-------------------------
procedure Check_Compiler_Unit (Feature : String; N : Node_Id) is
begin
if Compiler_Unit then
Error_Msg_N (Feature & " not allowed in compiler unit!!??", N);
end if;
end Check_Compiler_Unit;
procedure Check_Compiler_Unit (Feature : String; Loc : Source_Ptr) is
begin
if Compiler_Unit then
Error_Msg (Feature & " not allowed in compiler unit!!??", Loc);
end if;
end Check_Compiler_Unit;
------------------------------------
-- Check_Elaboration_Code_Allowed --
------------------------------------
procedure Check_Elaboration_Code_Allowed (N : Node_Id) is
begin
Check_Restriction (No_Elaboration_Code, N);
end Check_Elaboration_Code_Allowed;
-----------------------------------------
-- Check_Implicit_Dynamic_Code_Allowed --
-----------------------------------------
procedure Check_Implicit_Dynamic_Code_Allowed (N : Node_Id) is
begin
Check_Restriction (No_Implicit_Dynamic_Code, N);
end Check_Implicit_Dynamic_Code_Allowed;
--------------------------------
-- Check_No_Implicit_Aliasing --
--------------------------------
procedure Check_No_Implicit_Aliasing (Obj : Node_Id) is
E : Entity_Id;
begin
-- If restriction not active, nothing to check
if not Restriction_Active (No_Implicit_Aliasing) then
return;
end if;
-- If we have an entity name, check entity
if Is_Entity_Name (Obj) then
E := Entity (Obj);
-- Restriction applies to entities that are objects
if Is_Object (E) then
if Is_Aliased (E) then
return;
elsif Present (Renamed_Object (E)) then
Check_No_Implicit_Aliasing (Renamed_Object (E));
return;
end if;
-- If we don't have an object, then it's OK
else
return;
end if;
-- For selected component, check selector
elsif Nkind (Obj) = N_Selected_Component then
Check_No_Implicit_Aliasing (Selector_Name (Obj));
return;
-- Indexed component is OK if aliased components
elsif Nkind (Obj) = N_Indexed_Component then
if Has_Aliased_Components (Etype (Prefix (Obj)))
or else
(Is_Access_Type (Etype (Prefix (Obj)))
and then Has_Aliased_Components
(Designated_Type (Etype (Prefix (Obj)))))
then
return;
end if;
-- For type conversion, check converted expression
elsif Nkind_In (Obj, N_Unchecked_Type_Conversion, N_Type_Conversion) then
Check_No_Implicit_Aliasing (Expression (Obj));
return;
-- Explicit dereference is always OK
elsif Nkind (Obj) = N_Explicit_Dereference then
return;
end if;
-- If we fall through, then we have an aliased view that does not meet
-- the rules for being explicitly aliased, so issue restriction msg.
Check_Restriction (No_Implicit_Aliasing, Obj);
end Check_No_Implicit_Aliasing;
----------------------------------
-- Check_No_Implicit_Heap_Alloc --
----------------------------------
procedure Check_No_Implicit_Heap_Alloc (N : Node_Id) is
begin
Check_Restriction (No_Implicit_Heap_Allocations, N);
end Check_No_Implicit_Heap_Alloc;
----------------------------------
-- Check_No_Implicit_Task_Alloc --
----------------------------------
procedure Check_No_Implicit_Task_Alloc (N : Node_Id) is
begin
Check_Restriction (No_Implicit_Task_Allocations, N);
end Check_No_Implicit_Task_Alloc;
---------------------------------------
-- Check_No_Implicit_Protected_Alloc --
---------------------------------------
procedure Check_No_Implicit_Protected_Alloc (N : Node_Id) is
begin
Check_Restriction (No_Implicit_Protected_Object_Allocations, N);
end Check_No_Implicit_Protected_Alloc;
-----------------------------------
-- Check_Obsolescent_2005_Entity --
-----------------------------------
procedure Check_Obsolescent_2005_Entity (E : Entity_Id; N : Node_Id) is
function Chars_Is (E : Entity_Id; S : String) return Boolean;
-- Return True iff Chars (E) matches S (given in lower case)
--------------
-- Chars_Is --
--------------
function Chars_Is (E : Entity_Id; S : String) return Boolean is
Nam : constant Name_Id := Chars (E);
begin
if Length_Of_Name (Nam) /= S'Length then
return False;
else
return Get_Name_String (Nam) = S;
end if;
end Chars_Is;
-- Start of processing for Check_Obsolescent_2005_Entity
begin
if Restriction_Check_Required (No_Obsolescent_Features)
and then Ada_Version >= Ada_2005
and then Chars_Is (Scope (E), "handling")
and then Chars_Is (Scope (Scope (E)), "characters")
and then Chars_Is (Scope (Scope (Scope (E))), "ada")
and then Scope (Scope (Scope (Scope (E)))) = Standard_Standard
then
if Chars_Is (E, "is_character") or else
Chars_Is (E, "is_string") or else
Chars_Is (E, "to_character") or else
Chars_Is (E, "to_string") or else
Chars_Is (E, "to_wide_character") or else
Chars_Is (E, "to_wide_string")
then
Check_Restriction (No_Obsolescent_Features, N);
end if;
end if;
end Check_Obsolescent_2005_Entity;
---------------------------
-- Check_Restricted_Unit --
---------------------------
procedure Check_Restricted_Unit (U : Unit_Name_Type; N : Node_Id) is
begin
if Suppress_Restriction_Message (N) then
return;
elsif Is_Spec_Name (U) then
declare
Fnam : constant File_Name_Type :=
Get_File_Name (U, Subunit => False);
begin
-- Get file name
Get_Name_String (Fnam);
-- Nothing to do if name not at least 5 characters long ending
-- in .ads or .adb extension, which we strip.
if Name_Len < 5
or else (Name_Buffer (Name_Len - 3 .. Name_Len) /= ".ads"
and then
Name_Buffer (Name_Len - 3 .. Name_Len) /= ".adb")
then
return;
end if;
-- Strip extension and pad to eight characters
Name_Len := Name_Len - 4;
Add_Str_To_Name_Buffer ((Name_Len + 1 .. 8 => ' '));
-- If predefined unit, check the list of restricted units
if Is_Predefined_File_Name (Fnam) then
for J in Unit_Array'Range loop
if Name_Len = 8
and then Name_Buffer (1 .. 8) = Unit_Array (J).Filenm
then
Check_Restriction (Unit_Array (J).Res_Id, N);
end if;
end loop;
-- If not predefined unit, then one special check still
-- remains. GNAT.Current_Exception is not allowed if we have
-- restriction No_Exception_Propagation active.
else
if Name_Buffer (1 .. 8) = "g-curexc" then
Check_Restriction (No_Exception_Propagation, N);
end if;
end if;
end;
end if;
end Check_Restricted_Unit;
-----------------------
-- Check_Restriction --
-----------------------
procedure Check_Restriction
(R : Restriction_Id;
N : Node_Id;
V : Uint := Uint_Minus_1)
is
Msg_Issued : Boolean;
pragma Unreferenced (Msg_Issued);
begin
Check_Restriction (Msg_Issued, R, N, V);
end Check_Restriction;
procedure Check_Restriction
(Msg_Issued : out Boolean;
R : Restriction_Id;
N : Node_Id;
V : Uint := Uint_Minus_1)
is
VV : Integer;
-- V converted to integer form. If V is greater than Integer'Last,
-- it is reset to minus 1 (unknown value).
procedure Update_Restrictions (Info : in out Restrictions_Info);
-- Update violation information in Info.Violated and Info.Count
-------------------------
-- Update_Restrictions --
-------------------------
procedure Update_Restrictions (Info : in out Restrictions_Info) is
begin
-- If not violated, set as violated now
if not Info.Violated (R) then
Info.Violated (R) := True;
if R in All_Parameter_Restrictions then
if VV < 0 then
Info.Unknown (R) := True;
Info.Count (R) := 1;
else
Info.Count (R) := VV;
end if;
end if;
-- Otherwise if violated already and a parameter restriction,
-- update count by maximizing or summing depending on restriction.
elsif R in All_Parameter_Restrictions then
-- If new value is unknown, result is unknown
if VV < 0 then
Info.Unknown (R) := True;
-- If checked by maximization, nothing to do because the
-- check is per-object.
elsif R in Checked_Max_Parameter_Restrictions then
null;
-- If checked by adding, do add, checking for overflow
elsif R in Checked_Add_Parameter_Restrictions then
declare
pragma Unsuppress (Overflow_Check);
begin
Info.Count (R) := Info.Count (R) + VV;
exception
when Constraint_Error =>
Info.Count (R) := Integer'Last;
Info.Unknown (R) := True;
end;
-- Should not be able to come here, known counts should only
-- occur for restrictions that are Checked_max or Checked_Sum.
else
raise Program_Error;
end if;
end if;
end Update_Restrictions;
-- Start of processing for Check_Restriction
begin
Msg_Issued := False;
-- In CodePeer mode, we do not want to check for any restriction, or set
-- additional restrictions other than those already set in gnat1drv.adb
-- so that we have consistency between each compilation.
-- In GNATprove mode restrictions are checked, except for
-- No_Initialize_Scalars, which is implicitly set in gnat1drv.adb.
if CodePeer_Mode
or else (GNATprove_Mode and then R = No_Initialize_Scalars)
then
return;
end if;
-- In SPARK 05 mode, issue an error for any use of class-wide, even if
-- the No_Dispatch restriction is not set.
if R = No_Dispatch then
Check_SPARK_05_Restriction ("class-wide is not allowed", N);
end if;
if UI_Is_In_Int_Range (V) then
VV := Integer (UI_To_Int (V));
else
VV := -1;
end if;
-- Count can only be specified in the checked val parameter case
pragma Assert (VV < 0 or else R in Checked_Val_Parameter_Restrictions);
-- Nothing to do if value of zero specified for parameter restriction
if VV = 0 then
return;
end if;
-- Update current restrictions
Update_Restrictions (Restrictions);
-- If in main extended unit, update main restrictions as well. Note
-- that as usual we check for Main_Unit explicitly to deal with the
-- case of configuration pragma files.
if Current_Sem_Unit = Main_Unit
or else In_Extended_Main_Source_Unit (N)
then
Update_Restrictions (Main_Restrictions);
end if;
-- Nothing to do if restriction message suppressed
if Suppress_Restriction_Message (N) then
null;
-- If restriction not set, nothing to do
elsif not Restrictions.Set (R) then
null;
-- Don't complain about No_Obsolescent_Features in an instance, since we
-- will complain on the template, which is much better. Are there other
-- cases like this ??? Do we need a more general mechanism ???
elsif R = No_Obsolescent_Features
and then Instantiation_Location (Sloc (N)) /= No_Location
then
null;
-- Here if restriction set, check for violation (this is a Boolean
-- restriction, or a parameter restriction with a value of zero and an
-- unknown count, or a parameter restriction with a known value that
-- exceeds the restriction count).
elsif R in All_Boolean_Restrictions
or else (Restrictions.Unknown (R)
and then Restrictions.Value (R) = 0)
or else Restrictions.Count (R) > Restrictions.Value (R)
then
Msg_Issued := True;
Restriction_Msg (R, N);
end if;
-- For Max_Entries and the like, do not carry forward the violation
-- count because it does not affect later declarations.
if R in Checked_Max_Parameter_Restrictions then
Restrictions.Count (R) := 0;
Restrictions.Violated (R) := False;
end if;
end Check_Restriction;
-------------------------------------
-- Check_Restriction_No_Dependence --
-------------------------------------
procedure Check_Restriction_No_Dependence (U : Node_Id; Err : Node_Id) is
DU : Node_Id;
begin
-- Ignore call if node U is not in the main source unit. This avoids
-- cascaded errors, e.g. when Ada.Containers units with other units.
-- However, allow Standard_Location here, since this catches some cases
-- of constructs that get converted to run-time calls.
if not In_Extended_Main_Source_Unit (U)
and then Sloc (U) /= Standard_Location
then
return;
end if;
-- Loop through entries in No_Dependence table to check each one in turn
for J in No_Dependences.First .. No_Dependences.Last loop
DU := No_Dependences.Table (J).Unit;
if Same_Unit (U, DU) then
Error_Msg_Sloc := Sloc (DU);
Error_Msg_Node_1 := DU;
if No_Dependences.Table (J).Warn then
Error_Msg
("?*?violation of restriction `No_Dependence '='> &`#",
Sloc (Err));
else
Error_Msg
("|violation of restriction `No_Dependence '='> &`#",
Sloc (Err));
end if;
return;
end if;
end loop;
end Check_Restriction_No_Dependence;
--------------------------------------------------
-- Check_Restriction_No_Specification_Of_Aspect --
--------------------------------------------------
procedure Check_Restriction_No_Specification_Of_Aspect (N : Node_Id) is
A_Id : Aspect_Id;
Id : Node_Id;
begin
-- Ignore call if no instances of this restriction set
if not No_Specification_Of_Aspect_Set then
return;
end if;
-- Ignore call if node N is not in the main source unit, since we only
-- give messages for the main unit. This avoids giving messages for
-- aspects that are specified in withed units.
if not In_Extended_Main_Source_Unit (N) then
return;
end if;
Id := Identifier (N);
A_Id := Get_Aspect_Id (Chars (Id));
pragma Assert (A_Id /= No_Aspect);
Error_Msg_Sloc := No_Specification_Of_Aspects (A_Id);
if Error_Msg_Sloc /= No_Location then
Error_Msg_Node_1 := Id;
Error_Msg_Warn := No_Specification_Of_Aspect_Warning (A_Id);
Error_Msg_N
("<*<violation of restriction `No_Specification_Of_Aspect '='> &`#",
Id);
end if;
end Check_Restriction_No_Specification_Of_Aspect;
-------------------------------------------
-- Check_Restriction_No_Use_Of_Attribute --
--------------------------------------------
procedure Check_Restriction_No_Use_Of_Attribute (N : Node_Id) is
Attr_Id : Attribute_Id;
Attr_Nam : Name_Id;
begin
-- Nothing to do if the attribute is not in the main source unit, since
-- we only give messages for the main unit. This avoids giving messages
-- for attributes that are specified in withed units.
if not In_Extended_Main_Source_Unit (N) then
return;
-- Nothing to do if not checking No_Use_Of_Attribute
elsif not No_Use_Of_Attribute_Set then
return;
-- Do not consider internally generated attributes because this leads to
-- bizarre errors.
elsif not Comes_From_Source (N) then
return;
end if;
if Nkind (N) = N_Attribute_Definition_Clause then
Attr_Nam := Chars (N);
else
pragma Assert (Nkind (N) = N_Attribute_Reference);
Attr_Nam := Attribute_Name (N);
end if;
Attr_Id := Get_Attribute_Id (Attr_Nam);
Error_Msg_Sloc := No_Use_Of_Attribute (Attr_Id);
if Error_Msg_Sloc /= No_Location then
Error_Msg_Name_1 := Attr_Nam;
Error_Msg_Warn := No_Use_Of_Attribute_Warning (Attr_Id);
Error_Msg_N
("<*<violation of restriction `No_Use_Of_Attribute '='> %` #", N);
end if;
end Check_Restriction_No_Use_Of_Attribute;
----------------------------------------
-- Check_Restriction_No_Use_Of_Entity --
----------------------------------------
procedure Check_Restriction_No_Use_Of_Entity (N : Node_Id) is
begin
-- Error defence (not clearly necessary, but better safe)
if No (Entity (N)) then
return;
end if;
-- If simple name of entity not flagged with Boolean2 flag, then there
-- cannot be a matching entry in the table, so skip the search.
if Get_Name_Table_Boolean2 (Chars (Entity (N))) = False then
return;
end if;
-- Restriction is only recognized within a configuration pragma file,
-- or within a unit of the main extended program. Note: the test for
-- Main_Unit is needed to properly include the case of configuration
-- pragma files.
if Current_Sem_Unit /= Main_Unit
and then not In_Extended_Main_Source_Unit (N)
then
return;
end if;
-- Here we must search the table
for J in No_Use_Of_Entity.First .. No_Use_Of_Entity.Last loop
declare
NE_Ent : NE_Entry renames No_Use_Of_Entity.Table (J);
Ent : Entity_Id;
Expr : Node_Id;
begin
Ent := Entity (N);
Expr := NE_Ent.Entity;
loop
-- Here if at outer level of entity name in reference (handle
-- also the direct use of Text_IO in the pragma). For example:
-- pragma Restrictions (No_Use_Of_Entity => Text_IO.Put);
if Scope (Ent) = Standard_Standard
or else (Nkind (Expr) = N_Identifier
and then Chars (Ent) = Name_Text_IO
and then Chars (Scope (Ent)) = Name_Ada
and then Scope (Scope (Ent)) = Standard_Standard)
then
if Nkind_In (Expr, N_Identifier, N_Operator_Symbol)
and then Chars (Ent) = Chars (Expr)
then
Error_Msg_Node_1 := N;
Error_Msg_Warn := NE_Ent.Warn;
Error_Msg_Sloc := Sloc (NE_Ent.Entity);
Error_Msg_N
("<*<reference to & violates restriction "
& "No_Use_Of_Entity #", N);
return;
else
exit;
end if;
-- Here if at outer level of entity name in table
elsif Nkind_In (Expr, N_Identifier, N_Operator_Symbol) then
exit;
-- Here if neither at the outer level
else
pragma Assert (Nkind (Expr) = N_Selected_Component);
exit when Chars (Selector_Name (Expr)) /= Chars (Ent);
end if;
-- Move up a level
loop
Ent := Scope (Ent);
exit when not Is_Internal_Name (Chars (Ent));
end loop;
Expr := Prefix (Expr);
end loop;
end;
end loop;
end Check_Restriction_No_Use_Of_Entity;
----------------------------------------
-- Check_Restriction_No_Use_Of_Pragma --
----------------------------------------
procedure Check_Restriction_No_Use_Of_Pragma (N : Node_Id) is
Id : constant Node_Id := Pragma_Identifier (N);
P_Id : constant Pragma_Id := Get_Pragma_Id (Chars (Id));
begin
-- Nothing to do if the pragma is not in the main source unit, since we
-- only give messages for the main unit. This avoids giving messages for
-- pragmas that are specified in withed units.
if not In_Extended_Main_Source_Unit (N) then
return;
-- Nothing to do if not checking No_Use_Of_Pragma
elsif not No_Use_Of_Pragma_Set then
return;
-- Do not consider internally generated pragmas because this leads to
-- bizarre errors.
elsif not Comes_From_Source (N) then
return;
end if;
Error_Msg_Sloc := No_Use_Of_Pragma (P_Id);
if Error_Msg_Sloc /= No_Location then
Error_Msg_Warn := No_Use_Of_Pragma_Warning (P_Id);
Error_Msg_N
("<*<violation of restriction `No_Use_Of_Pragma '='> &` #", Id);
end if;
end Check_Restriction_No_Use_Of_Pragma;
--------------------------------
-- Check_SPARK_05_Restriction --
--------------------------------
procedure Check_SPARK_05_Restriction
(Msg : String;
N : Node_Id;
Force : Boolean := False)
is
Msg_Issued : Boolean;
Save_Error_Msg_Sloc : Source_Ptr;
Onode : constant Node_Id := Original_Node (N);
begin
-- Output message if Force set
if Force
-- Or if this node comes from source
or else Comes_From_Source (N)
-- Or if this is a range node which rewrites a range attribute and
-- the range attribute comes from source.
or else (Nkind (N) = N_Range
and then Nkind (Onode) = N_Attribute_Reference
and then Attribute_Name (Onode) = Name_Range
and then Comes_From_Source (Onode))
-- Or this is an expression that does not come from source, which is
-- a rewriting of an expression that does come from source.
or else (Nkind (N) in N_Subexpr and then Comes_From_Source (Onode))
then
if Restriction_Check_Required (SPARK_05)
and then Is_In_Hidden_Part_In_SPARK (Sloc (N))
then
return;
end if;
-- Since the call to Restriction_Msg from Check_Restriction may set
-- Error_Msg_Sloc to the location of the pragma restriction, save and
-- restore the previous value of the global variable around the call.
Save_Error_Msg_Sloc := Error_Msg_Sloc;
Check_Restriction (Msg_Issued, SPARK_05, First_Node (N));
Error_Msg_Sloc := Save_Error_Msg_Sloc;
if Msg_Issued then
Error_Msg_F ("\\| " & Msg, N);
end if;
end if;
end Check_SPARK_05_Restriction;
procedure Check_SPARK_05_Restriction
(Msg1 : String;
Msg2 : String;
N : Node_Id)
is
Msg_Issued : Boolean;
Save_Error_Msg_Sloc : Source_Ptr;
begin
pragma Assert (Msg2'Length /= 0 and then Msg2 (Msg2'First) = '\');
if Comes_From_Source (Original_Node (N)) then
if Restriction_Check_Required (SPARK_05)
and then Is_In_Hidden_Part_In_SPARK (Sloc (N))
then
return;
end if;
-- Since the call to Restriction_Msg from Check_Restriction may set
-- Error_Msg_Sloc to the location of the pragma restriction, save and
-- restore the previous value of the global variable around the call.
Save_Error_Msg_Sloc := Error_Msg_Sloc;
Check_Restriction (Msg_Issued, SPARK_05, First_Node (N));
Error_Msg_Sloc := Save_Error_Msg_Sloc;
if Msg_Issued then
Error_Msg_F ("\\| " & Msg1, N);
Error_Msg_F (Msg2, N);
end if;
end if;
end Check_SPARK_05_Restriction;
--------------------------------------
-- Check_Wide_Character_Restriction --
--------------------------------------
procedure Check_Wide_Character_Restriction (E : Entity_Id; N : Node_Id) is
begin
if Restriction_Check_Required (No_Wide_Characters)
and then Comes_From_Source (N)
then
declare
T : constant Entity_Id := Root_Type (E);
begin
if T = Standard_Wide_Character or else
T = Standard_Wide_String or else
T = Standard_Wide_Wide_Character or else
T = Standard_Wide_Wide_String
then
Check_Restriction (No_Wide_Characters, N);
end if;
end;
end if;
end Check_Wide_Character_Restriction;
----------------------------------------
-- Cunit_Boolean_Restrictions_Restore --
----------------------------------------
procedure Cunit_Boolean_Restrictions_Restore
(R : Save_Cunit_Boolean_Restrictions)
is
begin
for J in Cunit_Boolean_Restrictions loop
Restrictions.Set (J) := R (J);
end loop;
-- If No_Elaboration_Code set in configuration restrictions, and we
-- in the main extended source, then set it here now. This is part of
-- the special processing for No_Elaboration_Code.
if In_Extended_Main_Source_Unit (Cunit_Entity (Current_Sem_Unit))
and then Config_Cunit_Boolean_Restrictions (No_Elaboration_Code)
then
Restrictions.Set (No_Elaboration_Code) := True;
end if;
end Cunit_Boolean_Restrictions_Restore;
-------------------------------------
-- Cunit_Boolean_Restrictions_Save --
-------------------------------------
function Cunit_Boolean_Restrictions_Save
return Save_Cunit_Boolean_Restrictions
is
R : Save_Cunit_Boolean_Restrictions;
begin
for J in Cunit_Boolean_Restrictions loop
R (J) := Restrictions.Set (J);
end loop;
return R;
end Cunit_Boolean_Restrictions_Save;
------------------------
-- Get_Restriction_Id --
------------------------
function Get_Restriction_Id
(N : Name_Id) return Restriction_Id
is
begin
Get_Name_String (N);
Set_Casing (All_Upper_Case);
for J in All_Restrictions loop
declare
S : constant String := Restriction_Id'Image (J);
begin
if S = Name_Buffer (1 .. Name_Len) then
return J;
end if;
end;
end loop;
return Not_A_Restriction_Id;
end Get_Restriction_Id;
--------------------------------
-- Is_In_Hidden_Part_In_SPARK --
--------------------------------
function Is_In_Hidden_Part_In_SPARK (Loc : Source_Ptr) return Boolean is
begin
-- Loop through table of hidden ranges
for J in SPARK_Hides.First .. SPARK_Hides.Last loop
if SPARK_Hides.Table (J).Start <= Loc
and then Loc < SPARK_Hides.Table (J).Stop
then
return True;
end if;
end loop;
return False;
end Is_In_Hidden_Part_In_SPARK;
-------------------------------
-- No_Exception_Handlers_Set --
-------------------------------
function No_Exception_Handlers_Set return Boolean is
begin
return (No_Run_Time_Mode or else Configurable_Run_Time_Mode)
and then (Restrictions.Set (No_Exception_Handlers)
or else
Restrictions.Set (No_Exception_Propagation));
end No_Exception_Handlers_Set;
-------------------------------------
-- No_Exception_Propagation_Active --
-------------------------------------
function No_Exception_Propagation_Active return Boolean is
begin
return (No_Run_Time_Mode
or else Configurable_Run_Time_Mode
or else Debug_Flag_Dot_G)
and then Restriction_Active (No_Exception_Propagation);
end No_Exception_Propagation_Active;
--------------------------------
-- OK_No_Dependence_Unit_Name --
--------------------------------
function OK_No_Dependence_Unit_Name (N : Node_Id) return Boolean is
begin
if Nkind (N) = N_Selected_Component then
return
OK_No_Dependence_Unit_Name (Prefix (N))
and then
OK_No_Dependence_Unit_Name (Selector_Name (N));
elsif Nkind (N) = N_Identifier then
return True;
else
Error_Msg_N ("wrong form for unit name for No_Dependence", N);
return False;
end if;
end OK_No_Dependence_Unit_Name;
------------------------------
-- OK_No_Use_Of_Entity_Name --
------------------------------
function OK_No_Use_Of_Entity_Name (N : Node_Id) return Boolean is
begin
if Nkind (N) = N_Selected_Component then
return
OK_No_Use_Of_Entity_Name (Prefix (N))
and then
OK_No_Use_Of_Entity_Name (Selector_Name (N));
elsif Nkind_In (N, N_Identifier, N_Operator_Symbol) then
return True;
else
Error_Msg_N ("wrong form for entity name for No_Use_Of_Entity", N);
return False;
end if;
end OK_No_Use_Of_Entity_Name;
----------------------------------
-- Process_Restriction_Synonyms --
----------------------------------
-- Note: body of this function must be coordinated with list of renaming
-- declarations in System.Rident.
function Process_Restriction_Synonyms (N : Node_Id) return Name_Id is
Old_Name : constant Name_Id := Chars (N);
New_Name : Name_Id;
begin
case Old_Name is
when Name_Boolean_Entry_Barriers =>
New_Name := Name_Simple_Barriers;
when Name_Max_Entry_Queue_Depth =>
New_Name := Name_Max_Entry_Queue_Length;
when Name_No_Dynamic_Interrupts =>
New_Name := Name_No_Dynamic_Attachment;
when Name_No_Requeue =>
New_Name := Name_No_Requeue_Statements;
when Name_No_Task_Attributes =>
New_Name := Name_No_Task_Attributes_Package;
-- SPARK is special in that we unconditionally warn
when Name_SPARK =>
Error_Msg_Name_1 := Name_SPARK;
Error_Msg_N ("restriction identifier % is obsolescent??", N);
Error_Msg_Name_1 := Name_SPARK_05;
Error_Msg_N ("|use restriction identifier % instead??", N);
return Name_SPARK_05;
when others =>
return Old_Name;
end case;
-- Output warning if we are warning on obsolescent features for all
-- cases other than SPARK.
if Warn_On_Obsolescent_Feature then
Error_Msg_Name_1 := Old_Name;
Error_Msg_N ("restriction identifier % is obsolescent?j?", N);
Error_Msg_Name_1 := New_Name;
Error_Msg_N ("|use restriction identifier % instead?j?", N);
end if;
return New_Name;
end Process_Restriction_Synonyms;
--------------------------------------
-- Reset_Cunit_Boolean_Restrictions --
--------------------------------------
procedure Reset_Cunit_Boolean_Restrictions is
begin
for J in Cunit_Boolean_Restrictions loop
Restrictions.Set (J) := False;
end loop;
end Reset_Cunit_Boolean_Restrictions;
-----------------------------------------------
-- Restore_Config_Cunit_Boolean_Restrictions --
-----------------------------------------------
procedure Restore_Config_Cunit_Boolean_Restrictions is
begin
Cunit_Boolean_Restrictions_Restore (Config_Cunit_Boolean_Restrictions);
end Restore_Config_Cunit_Boolean_Restrictions;
------------------------
-- Restricted_Profile --
------------------------
function Restricted_Profile return Boolean is
begin
if Restricted_Profile_Cached then
return Restricted_Profile_Result;
else
Restricted_Profile_Result := True;
Restricted_Profile_Cached := True;
declare
R : Restriction_Flags renames
Profile_Info (Restricted_Tasking).Set;
V : Restriction_Values renames
Profile_Info (Restricted_Tasking).Value;
begin
for J in R'Range loop
if R (J)
and then (Restrictions.Set (J) = False
or else Restriction_Warnings (J)
or else
(J in All_Parameter_Restrictions
and then Restrictions.Value (J) > V (J)))
then
Restricted_Profile_Result := False;
exit;
end if;
end loop;
return Restricted_Profile_Result;
end;
end if;
end Restricted_Profile;
------------------------
-- Restriction_Active --
------------------------
function Restriction_Active (R : All_Restrictions) return Boolean is
begin
return Restrictions.Set (R) and then not Restriction_Warnings (R);
end Restriction_Active;
--------------------------------
-- Restriction_Check_Required --
--------------------------------
function Restriction_Check_Required (R : All_Restrictions) return Boolean is
begin
return Restrictions.Set (R);
end Restriction_Check_Required;
---------------------
-- Restriction_Msg --
---------------------
procedure Restriction_Msg (R : Restriction_Id; N : Node_Id) is
Msg : String (1 .. 100);
Len : Natural := 0;
procedure Add_Char (C : Character);
-- Append given character to Msg, bumping Len
procedure Add_Str (S : String);
-- Append given string to Msg, bumping Len appropriately
procedure Id_Case (S : String; Quotes : Boolean := True);
-- Given a string S, case it according to current identifier casing,
-- except for SPARK_05 (an acronym) which is set all upper case, and
-- store in Error_Msg_String. Then append `~` to the message buffer
-- to output the string unchanged surrounded in quotes. The quotes
-- are suppressed if Quotes = False.
--------------
-- Add_Char --
--------------
procedure Add_Char (C : Character) is
begin
Len := Len + 1;
Msg (Len) := C;
end Add_Char;
-------------
-- Add_Str --
-------------
procedure Add_Str (S : String) is
begin
Msg (Len + 1 .. Len + S'Length) := S;
Len := Len + S'Length;
end Add_Str;
-------------
-- Id_Case --
-------------
procedure Id_Case (S : String; Quotes : Boolean := True) is
begin
Name_Buffer (1 .. S'Last) := S;
Name_Len := S'Length;
if R = SPARK_05 then
Set_All_Upper_Case;
else
Set_Casing (Identifier_Casing (Get_Source_File_Index (Sloc (N))));
end if;
Error_Msg_Strlen := Name_Len;
Error_Msg_String (1 .. Name_Len) := Name_Buffer (1 .. Name_Len);
if Quotes then
Add_Str ("`~`");
else
Add_Char ('~');
end if;
end Id_Case;
-- Start of processing for Restriction_Msg
begin
-- Set warning message if warning
if Restriction_Warnings (R) then
Add_Str ("?*?");
-- If real violation (not warning), then mark it as non-serious unless
-- it is a violation of No_Finalization in which case we leave it as a
-- serious message, since otherwise we get crashes during attempts to
-- expand stuff that is not properly formed due to assumptions made
-- about no finalization being present.
elsif R /= No_Finalization then
Add_Char ('|');
end if;
Error_Msg_Sloc := Restrictions_Loc (R);
-- Set main message, adding implicit if no source location
if Error_Msg_Sloc > No_Location
or else Error_Msg_Sloc = System_Location
then
Add_Str ("violation of restriction ");
else
Add_Str ("violation of implicit restriction ");
Error_Msg_Sloc := No_Location;
end if;
-- Case of parameterized restriction
if R in All_Parameter_Restrictions then
Add_Char ('`');
Id_Case (Restriction_Id'Image (R), Quotes => False);
Add_Str (" = ^`");
Error_Msg_Uint_1 := UI_From_Int (Int (Restrictions.Value (R)));
-- Case of boolean restriction
else
Id_Case (Restriction_Id'Image (R));
end if;
-- Case of no secondary profile continuation message
if Restriction_Profile_Name (R) = No_Profile then
if Error_Msg_Sloc /= No_Location then
Add_Char ('#');
end if;
Add_Char ('!');
Error_Msg_N (Msg (1 .. Len), N);
-- Case of secondary profile continuation message present
else
Add_Char ('!');
Error_Msg_N (Msg (1 .. Len), N);
Len := 0;
Add_Char ('\');
-- Set as warning if warning case
if Restriction_Warnings (R) then
Add_Str ("??");
end if;
-- Set main message
Add_Str ("from profile ");
Id_Case (Profile_Name'Image (Restriction_Profile_Name (R)));
-- Add location if we have one
if Error_Msg_Sloc /= No_Location then
Add_Char ('#');
end if;
-- Output unconditional message and we are done
Add_Char ('!');
Error_Msg_N (Msg (1 .. Len), N);
end if;
end Restriction_Msg;
-----------------
-- Same_Entity --
-----------------
function Same_Entity (E1, E2 : Node_Id) return Boolean is
begin
if Nkind_In (E1, N_Identifier, N_Operator_Symbol)
and then
Nkind_In (E2, N_Identifier, N_Operator_Symbol)
then
return Chars (E1) = Chars (E2);
elsif Nkind_In (E1, N_Selected_Component, N_Expanded_Name)
and then
Nkind_In (E2, N_Selected_Component, N_Expanded_Name)
then
return Same_Unit (Prefix (E1), Prefix (E2))
and then
Same_Unit (Selector_Name (E1), Selector_Name (E2));
else
return False;
end if;
end Same_Entity;
---------------
-- Same_Unit --
---------------
function Same_Unit (U1, U2 : Node_Id) return Boolean is
begin
if Nkind (U1) = N_Identifier and then Nkind (U2) = N_Identifier then
return Chars (U1) = Chars (U2);
elsif Nkind_In (U1, N_Selected_Component, N_Expanded_Name)
and then
Nkind_In (U2, N_Selected_Component, N_Expanded_Name)
then
return Same_Unit (Prefix (U1), Prefix (U2))
and then
Same_Unit (Selector_Name (U1), Selector_Name (U2));
else
return False;
end if;
end Same_Unit;
--------------------------------------------
-- Save_Config_Cunit_Boolean_Restrictions --
--------------------------------------------
procedure Save_Config_Cunit_Boolean_Restrictions is
begin
Config_Cunit_Boolean_Restrictions := Cunit_Boolean_Restrictions_Save;
end Save_Config_Cunit_Boolean_Restrictions;
------------------------------
-- Set_Hidden_Part_In_SPARK --
------------------------------
procedure Set_Hidden_Part_In_SPARK (Loc1, Loc2 : Source_Ptr) is
begin
SPARK_Hides.Increment_Last;
SPARK_Hides.Table (SPARK_Hides.Last).Start := Loc1;
SPARK_Hides.Table (SPARK_Hides.Last).Stop := Loc2;
end Set_Hidden_Part_In_SPARK;
------------------------------
-- Set_Profile_Restrictions --
------------------------------
procedure Set_Profile_Restrictions
(P : Profile_Name;
N : Node_Id;
Warn : Boolean)
is
R : Restriction_Flags renames Profile_Info (P).Set;
V : Restriction_Values renames Profile_Info (P).Value;
begin
for J in R'Range loop
if R (J) then
declare
Already_Restricted : constant Boolean := Restriction_Active (J);
begin
-- Set the restriction
if J in All_Boolean_Restrictions then
Set_Restriction (J, N);
else
Set_Restriction (J, N, V (J));
end if;
-- Record that this came from a Profile[_Warnings] restriction
Restriction_Profile_Name (J) := P;
-- Set warning flag, except that we do not set the warning
-- flag if the restriction was already active and this is
-- the warning case. That avoids a warning overriding a real
-- restriction, which should never happen.
if not (Warn and Already_Restricted) then
Restriction_Warnings (J) := Warn;
end if;
end;
end if;
end loop;
end Set_Profile_Restrictions;
---------------------
-- Set_Restriction --
---------------------
-- Case of Boolean restriction
procedure Set_Restriction
(R : All_Boolean_Restrictions;
N : Node_Id)
is
begin
Restrictions.Set (R) := True;
if Restricted_Profile_Cached and Restricted_Profile_Result then
null;
else
Restricted_Profile_Cached := False;
end if;
-- Set location, but preserve location of system restriction for nice
-- error msg with run time name.
if Restrictions_Loc (R) /= System_Location then
Restrictions_Loc (R) := Sloc (N);
end if;
-- Note restriction came from restriction pragma, not profile
Restriction_Profile_Name (R) := No_Profile;
-- Record the restriction if we are in the main unit, or in the extended
-- main unit. The reason that we test separately for Main_Unit is that
-- gnat.adc is processed with Current_Sem_Unit = Main_Unit, but nodes in
-- gnat.adc do not appear to be in the extended main source unit (they
-- probably should do ???)
if Current_Sem_Unit = Main_Unit
or else In_Extended_Main_Source_Unit (N)
then
if not Restriction_Warnings (R) then
Main_Restrictions.Set (R) := True;
end if;
end if;
end Set_Restriction;
-- Case of parameter restriction
procedure Set_Restriction
(R : All_Parameter_Restrictions;
N : Node_Id;
V : Integer)
is
begin
if Restricted_Profile_Cached and Restricted_Profile_Result then
null;
else
Restricted_Profile_Cached := False;
end if;
if Restrictions.Set (R) then
if V < Restrictions.Value (R) then
Restrictions.Value (R) := V;
Restrictions_Loc (R) := Sloc (N);
end if;
else
Restrictions.Set (R) := True;
Restrictions.Value (R) := V;
Restrictions_Loc (R) := Sloc (N);
end if;
-- Record the restriction if we are in the main unit, or in the extended
-- main unit. The reason that we test separately for Main_Unit is that
-- gnat.adc is processed with Current_Sem_Unit = Main_Unit, but nodes in
-- gnat.adc do not appear to be the extended main source unit (they
-- probably should do ???)
if Current_Sem_Unit = Main_Unit
or else In_Extended_Main_Source_Unit (N)
then
if Main_Restrictions.Set (R) then
if V < Main_Restrictions.Value (R) then
Main_Restrictions.Value (R) := V;
end if;
elsif not Restriction_Warnings (R) then
Main_Restrictions.Set (R) := True;
Main_Restrictions.Value (R) := V;
end if;
end if;
-- Note restriction came from restriction pragma, not profile
Restriction_Profile_Name (R) := No_Profile;
end Set_Restriction;
-----------------------------------
-- Set_Restriction_No_Dependence --
-----------------------------------
procedure Set_Restriction_No_Dependence
(Unit : Node_Id;
Warn : Boolean;
Profile : Profile_Name := No_Profile)
is
begin
-- Loop to check for duplicate entry
for J in No_Dependences.First .. No_Dependences.Last loop
-- Case of entry already in table
if Same_Unit (Unit, No_Dependences.Table (J).Unit) then
-- Error has precedence over warning
if not Warn then
No_Dependences.Table (J).Warn := False;
end if;
return;
end if;
end loop;
-- Entry is not currently in table
No_Dependences.Append ((Unit, Warn, Profile));
end Set_Restriction_No_Dependence;
--------------------------------------
-- Set_Restriction_No_Use_Of_Entity --
--------------------------------------
procedure Set_Restriction_No_Use_Of_Entity
(Entity : Node_Id;
Warning : Boolean;
Profile : Profile_Name := No_Profile)
is
Nam : Node_Id;
begin
-- Loop to check for duplicate entry
for J in No_Use_Of_Entity.First .. No_Use_Of_Entity.Last loop
-- Case of entry already in table
if Same_Entity (Entity, No_Use_Of_Entity.Table (J).Entity) then
-- Error has precedence over warning
if not Warning then
No_Use_Of_Entity.Table (J).Warn := False;
end if;
return;
end if;
end loop;
-- Entry is not currently in table
No_Use_Of_Entity.Append ((Entity, Warning, Profile));
-- Now we need to find the direct name and set Boolean2 flag
if Nkind_In (Entity, N_Identifier, N_Operator_Symbol) then
Nam := Entity;
else
pragma Assert (Nkind (Entity) = N_Selected_Component);
Nam := Selector_Name (Entity);
pragma Assert (Nkind_In (Nam, N_Identifier, N_Operator_Symbol));
end if;
Set_Name_Table_Boolean2 (Chars (Nam), True);
end Set_Restriction_No_Use_Of_Entity;
------------------------------------------------
-- Set_Restriction_No_Specification_Of_Aspect --
------------------------------------------------
procedure Set_Restriction_No_Specification_Of_Aspect
(N : Node_Id;
Warning : Boolean)
is
A_Id : constant Aspect_Id_Exclude_No_Aspect := Get_Aspect_Id (Chars (N));
begin
No_Specification_Of_Aspect_Set := True;
No_Specification_Of_Aspects (A_Id) := Sloc (N);
No_Specification_Of_Aspect_Warning (A_Id) := Warning;
end Set_Restriction_No_Specification_Of_Aspect;
procedure Set_Restriction_No_Specification_Of_Aspect (A_Id : Aspect_Id) is
begin
No_Specification_Of_Aspect_Set := True;
No_Specification_Of_Aspects (A_Id) := System_Location;
No_Specification_Of_Aspect_Warning (A_Id) := False;
end Set_Restriction_No_Specification_Of_Aspect;
-----------------------------------------
-- Set_Restriction_No_Use_Of_Attribute --
-----------------------------------------
procedure Set_Restriction_No_Use_Of_Attribute
(N : Node_Id;
Warning : Boolean)
is
A_Id : constant Attribute_Id := Get_Attribute_Id (Chars (N));
begin
No_Use_Of_Attribute_Set := True;
No_Use_Of_Attribute (A_Id) := Sloc (N);
No_Use_Of_Attribute_Warning (A_Id) := Warning;
end Set_Restriction_No_Use_Of_Attribute;
procedure Set_Restriction_No_Use_Of_Attribute (A_Id : Attribute_Id) is
begin
No_Use_Of_Attribute_Set := True;
No_Use_Of_Attribute (A_Id) := System_Location;
No_Use_Of_Attribute_Warning (A_Id) := False;
end Set_Restriction_No_Use_Of_Attribute;
--------------------------------------
-- Set_Restriction_No_Use_Of_Pragma --
--------------------------------------
procedure Set_Restriction_No_Use_Of_Pragma
(N : Node_Id;
Warning : Boolean)
is
A_Id : constant Pragma_Id := Get_Pragma_Id (Chars (N));
begin
No_Use_Of_Pragma_Set := True;
No_Use_Of_Pragma (A_Id) := Sloc (N);
No_Use_Of_Pragma_Warning (A_Id) := Warning;
end Set_Restriction_No_Use_Of_Pragma;
procedure Set_Restriction_No_Use_Of_Pragma (A_Id : Pragma_Id) is
begin
No_Use_Of_Pragma_Set := True;
No_Use_Of_Pragma (A_Id) := System_Location;
No_Use_Of_Pragma_Warning (A_Id) := False;
end Set_Restriction_No_Use_Of_Pragma;
----------------------------------
-- Suppress_Restriction_Message --
----------------------------------
function Suppress_Restriction_Message (N : Node_Id) return Boolean is
begin
-- We only output messages for the extended main source unit
if In_Extended_Main_Source_Unit (N) then
return False;
-- If loaded by rtsfind, then suppress message
elsif Sloc (N) <= No_Location then
return True;
-- Otherwise suppress message if internal file
else
return Is_Internal_File_Name (Unit_File_Name (Get_Source_Unit (N)));
end if;
end Suppress_Restriction_Message;
---------------------
-- Tasking_Allowed --
---------------------
function Tasking_Allowed return Boolean is
begin
return not Restrictions.Set (No_Tasking)
and then (not Restrictions.Set (Max_Tasks)
or else Restrictions.Value (Max_Tasks) > 0)
and then not No_Run_Time_Mode;
end Tasking_Allowed;
end Restrict;
|
with PixelArray;
with Ada.Containers.Vectors;
package ImageRegions is
-- 0 and 255 are reserved to represent 0 / 1 in "binary" images
type RegionLabel is new Integer range 1 .. 254;
New_Region_Pixel_Threshold: constant Positive := 10;
type Rect is tagged record
x, y, width, height: Natural;
end record;
function toString(r: Rect) return String;
type Centroid is tagged record
x, y: Float;
end record;
type Region is tagged record
label: RegionLabel;
area: Rect;
center: Centroid;
pixelCount: Natural;
end record;
package RegionVector is new Ada.Containers.Vectors(Index_Type => Natural, Element_Type => Region);
function detectRegions(image: in out PixelArray.ImagePlane) return RegionVector.Vector;
procedure markRegions(image: in out PixelArray.ImagePlane; color: PixelArray.Pixel);
procedure sortRegions(input: in out RegionVector.Vector);
end ImageRegions;
|
--//////////////////////////////////////////////////////////
-- SFML - Simple and Fast Multimedia Library
-- Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
-- This software is provided 'as-is', without any express or implied warranty.
-- In no event will the authors be held liable for any damages arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it freely,
-- subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented;
-- you must not claim that you wrote the original software.
-- If you use this software in a product, an acknowledgment
-- in the product documentation would be appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such,
-- and must not be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
with Sf.Network.IpAddress;
with Sf.Network.SocketStatus;
package Sf.Network.TcpListener is
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--/ @brief Create a new TCP listener
--/
--/ @return A new sfTcpListener object
--/
--//////////////////////////////////////////////////////////
function create return sfTcpListener_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Destroy a TCP listener
--/
--/ @param listener TCP listener to destroy
--/
--//////////////////////////////////////////////////////////
procedure destroy (listener : sfTcpListener_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Set the blocking state of a TCP listener
--/
--/ In blocking mode, calls will not return until they have
--/ completed their task. For example, a call to
--/ sfTcpListener_accept in blocking mode won't return until
--/ a new connection was actually received.
--/ In non-blocking mode, calls will always return immediately,
--/ using the return code to signal whether there was data
--/ available or not.
--/ By default, all sockets are blocking.
--/
--/ @param listener TCP listener object
--/ @param blocking sfTrue to set the socket as blocking, sfFalse for non-blocking
--/
--//////////////////////////////////////////////////////////
procedure setBlocking (listener : sfTcpListener_Ptr;
blocking : sfBool);
--//////////////////////////////////////////////////////////
--/ @brief Tell whether a TCP listener is in blocking or non-blocking mode
--/
--/ @param listener TCP listener object
--/
--/ @return sfTrue if the socket is blocking, sfFalse otherwise
--/
--//////////////////////////////////////////////////////////
function isBlocking (listener : sfTcpListener_Ptr)
return sfBool;
--//////////////////////////////////////////////////////////
--/ @brief Get the port to which a TCP listener is bound locally
--/
--/ If the socket is not listening to a port, this function
--/ returns 0.
--/
--/ @param listener TCP listener object
--/
--/ @return Port to which the TCP listener is bound
--/
--//////////////////////////////////////////////////////////
function getLocalPort (listener : sfTcpListener_Ptr)
return sfUint16;
--//////////////////////////////////////////////////////////
--/ @brief Start listening for connections
--/
--/ This functions makes the socket listen to the specified
--/ port, waiting for new connections.
--/ If the socket was previously listening to another port,
--/ it will be stopped first and bound to the new port.
--/
--/ If there is no specific address to listen to, pass sfIpAddress_Any
--/
--/ @param listener TCP listener object
--/ @param port Port to listen for new connections
--/ @param address Address of the interface to listen on
--/
--/ @return Status code
--/
--//////////////////////////////////////////////////////////
function listen
(listener : sfTcpListener_Ptr;
port : sfUint16;
address : Sf.Network.IpAddress.sfIpAddress)
return Sf.Network.SocketStatus.sfSocketStatus;
--//////////////////////////////////////////////////////////
--/ @brief Accept a new connection
--/
--/ If the socket is in blocking mode, this function will
--/ not return until a connection is actually received.
--/
--/ The @a connected argument points to a valid sfTcpSocket pointer
--/ in case of success (the function returns sfSocketDone), it points
--/ to a NULL pointer otherwise.
--/
--/ @param listener TCP listener object
--/ @param connected Socket that will hold the new connection
--/
--/ @return Status code
--/
--//////////////////////////////////////////////////////////
function tcpAccept (listener : sfTcpListener_Ptr;
connected : in out sfTcpSocket_Ptr)
return Sf.Network.SocketStatus.sfSocketStatus;
private
pragma Import (C, create, "sfTcpListener_create");
pragma Import (C, destroy, "sfTcpListener_destroy");
pragma Import (C, setBlocking, "sfTcpListener_setBlocking");
pragma Import (C, isBlocking, "sfTcpListener_isBlocking");
pragma Import (C, getLocalPort, "sfTcpListener_getLocalPort");
pragma Import (C, listen, "sfTcpListener_listen");
pragma Import (C, tcpAccept, "sfTcpListener_accept");
end Sf.Network.TcpListener;
|
-- Demonstrates use of package: Disorderly.Random
with Disorderly.Random; use Disorderly.Random;
with Disorderly.Random.Clock_Entropy;
with Text_io; use text_io;
procedure Random_demo_1 is
X : Random_Int;
Stream_1 : State;
-- Must declare one of these for each desired independent stream of rands.
-- To get successive random nums X from stream_k,
-- you then call Get_Random(X, stream_k);
procedure Pause is
Continue : Character;
begin
new_line; put ("Enter a character to continue: ");
get_immediate (Continue);
new_line;
exception
when others => null;
end Pause;
begin
new_line;
put_line ("The generator needs an initial state before it can create streams");
put_line ("of random numbers. We usually call the state Stream_1. You can");
put_line ("create lots of independent Streams by calling Reset with different");
put_line ("values of the seeds, which are called Initiator1, Initiator2 ... Below");
put_line ("is a series of 12 states created by procedure Reset. The 12 states are");
put_line ("created by setting Initiator1 to 1, 2, 3 ... 12, while keeping ");
put_line ("the other 2 Initiators constant. In fact we only needed to change");
put_line ("Initiator1 by just 1 bit to get a complete change in all four of the");
put_line ("64-bit Integers comprising the state. Each line below shows the four 64 bit");
put_line ("integers of a state. Twelve independent states are printed on 12 lines.");
Pause;
for k in Seed_Random_Int range 1..12 loop
Reset (Stream_1, k, 4444, 55555, 666666);
new_line; put (Formatted_Image (Stream_1));
end loop;
new_line(2);
put_line ("Test functions Image and Value.");
put_line ("Function Image translates the State (an array of 4 Integers) into a String.");
put_line ("Function Value translates the string back to array of 4 Integers.");
put_line ("Do this back and forth, and print the results below. Each string");
put_line ("of 4 numbers (representing a State) should appear twice.");
Pause;
for k in Seed_Random_Int range 1..4 loop
Reset (Stream_1, k, 1, 1, 1);
new_line; put (Formatted_Image (Stream_1));
new_line; put (Formatted_Image (Value (Image (Stream_1))));
new_line;
end loop;
new_line(2);
put_line ("Test of procedure: Clock_Entropy.Reset (Stream_1)");
put_line ("Procedure Clock_Entropy.Reset calls Calendar in an attempt to create");
put_line ("a new and unique initial state each time Clock_Entropy.Reset is called.");
put_line ("Below we call Clock_Entropy.Reset 12 times, in order to get 12 unique");
put_line ("initial states. The 12 initial states (strings of 4 numbers) are printed");
put_line ("on the 12 lines below. If you get the same State twice in a row then the");
put_line ("procedure failed to find a new and unique initial state.");
Pause;
-- up top we wrote: use Disorderly.Random;
-- so we can just call Clock_Entropy.Reset instead of
-- Disorderly.Random.Clock_Entropy.Reset:
new_line;
for k in Seed_Random_Int range 1..12 loop
--Disorderly.Random.Clock_Entropy.Reset (Stream_1);
Clock_Entropy.Reset (Stream_1);
new_line; put (Formatted_Image (Stream_1));
end loop;
new_line(2);
put_line ("Print 8 random nums from Stream_1, the state just initialized.");
Pause;
new_line;
for k in 1..8 loop
Get_Random (X, Stream_1);
new_line; put (Random_Int'Image (X));
end loop;
new_line(2);
put_line ("Final Test");
put_line ("Translate state Integers to a string, and then back to Integer. Do this");
put_line ("back and forth for a long time. If error detected, then report failure.");
Pause;
Clock_Entropy.Reset (Stream_1);
for k in Seed_Random_Int range 1 .. 2**26 loop
Get_Random (X, Stream_1);
if not Are_Equal (Stream_1, Value (Image (Stream_1))) then
raise Program_Error with "FAILURE in Image/Value routines";
end if;
end loop;
new_line; put ("Finished part 1 of the final test.");
for k in Seed_Random_Int range 1 .. 2**22 loop
Reset (Stream_1, k, 1, 1, 1);
if not Are_Equal (Stream_1, Value (Image (Stream_1))) then
raise Program_Error with "FAILURE in Image/Value routines";
end if;
end loop;
new_line; put ("Finished part 2 of the final test.");
for k in Seed_Random_Int range 1 .. 2**20 loop
Clock_Entropy.Reset (Stream_1);
if not Are_Equal (Stream_1, Value (Image (Stream_1))) then
raise Program_Error with "FAILURE in Image/Value routines";
end if;
end loop;
new_line; put ("Finished part 3 of the final test.");
end Random_Demo_1;
|
function Product(Item : Int_Array) return Integer is
Prod : Integer := 1;
begin
for I in Item'range loop
Prod := Prod * Item(I);
end loop;
return Prod;
end Product;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with GL.Types;
package Silo is
type Label_Data is private;
Empty_Stack : Exception;
procedure Get_Data (Label_String : out Unbounded_String;
Label_Position : out GL.Types.Singles.Vector2);
procedure Push (Data : Label_Data);
function Pull return Label_Data;
function Set_Data (Label_String : Unbounded_String;
Label_Position : GL.Types.Singles.Vector2)
return Label_Data;
function Size return Integer;
private
type Label_Data is record
Label_String : Unbounded_String;
Label_Position : GL.Types.Singles.Vector2;
end record;
end Silo;
|
-- Copyright (c) 2013, Nordic Semiconductor ASA
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * 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 Nordic Semiconductor ASA nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
-- This spec has been automatically generated from nrf51.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package NRF_SVD.UICR is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Readback protect region 0. Will be ignored if pre-programmed factory
-- code is present on the chip.
type RBPCONF_PR0_Field is
(-- Enabled.
Enabled,
-- Disabled.
Disabled)
with Size => 8;
for RBPCONF_PR0_Field use
(Enabled => 0,
Disabled => 255);
-- Readback protect all code in the device.
type RBPCONF_PALL_Field is
(-- Enabled.
Enabled,
-- Disabled.
Disabled)
with Size => 8;
for RBPCONF_PALL_Field use
(Enabled => 0,
Disabled => 255);
-- Readback protection configuration.
type RBPCONF_Register is record
-- Readback protect region 0. Will be ignored if pre-programmed factory
-- code is present on the chip.
PR0 : RBPCONF_PR0_Field := NRF_SVD.UICR.Disabled;
-- Readback protect all code in the device.
PALL : RBPCONF_PALL_Field := NRF_SVD.UICR.Disabled;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#FFFF#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for RBPCONF_Register use record
PR0 at 0 range 0 .. 7;
PALL at 0 range 8 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- Reset value for CLOCK XTALFREQ register.
type XTALFREQ_XTALFREQ_Field is
(-- 32MHz Xtal is used.
Val_32Mhz,
-- 16MHz Xtal is used.
Val_16Mhz)
with Size => 8;
for XTALFREQ_XTALFREQ_Field use
(Val_32Mhz => 0,
Val_16Mhz => 255);
-- Reset value for CLOCK XTALFREQ register.
type XTALFREQ_Register is record
-- Reset value for CLOCK XTALFREQ register.
XTALFREQ : XTALFREQ_XTALFREQ_Field := NRF_SVD.UICR.Val_16Mhz;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#FFFFFF#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for XTALFREQ_Register use record
XTALFREQ at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype FWID_FWID_Field is HAL.UInt16;
-- Firmware ID.
type FWID_Register is record
-- Read-only. Identification number for the firmware loaded into the
-- chip.
FWID : FWID_FWID_Field;
-- unspecified
Reserved_16_31 : HAL.UInt16;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FWID_Register use record
FWID at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- Reserved for Nordic firmware design.
-- Reserved for Nordic firmware design.
type NRFFW_Registers is array (0 .. 14) of HAL.UInt32;
-- Reserved for Nordic hardware design.
-- Reserved for Nordic hardware design.
type NRFHW_Registers is array (0 .. 11) of HAL.UInt32;
-- Reserved for customer.
-- Reserved for customer.
type CUSTOMER_Registers is array (0 .. 31) of HAL.UInt32;
-----------------
-- Peripherals --
-----------------
type UICR_Disc is
(Mode_1,
Mode_2);
-- User Information Configuration.
type UICR_Peripheral
(Discriminent : UICR_Disc := Mode_1)
is record
-- Length of code region 0.
CLENR0 : aliased HAL.UInt32;
-- Readback protection configuration.
RBPCONF : aliased RBPCONF_Register;
-- Reset value for CLOCK XTALFREQ register.
XTALFREQ : aliased XTALFREQ_Register;
-- Firmware ID.
FWID : aliased FWID_Register;
-- Reserved for Nordic hardware design.
NRFHW : aliased NRFHW_Registers;
-- Reserved for customer.
CUSTOMER : aliased CUSTOMER_Registers;
case Discriminent is
when Mode_1 =>
-- Bootloader start address.
BOOTLOADERADDR : aliased HAL.UInt32;
when Mode_2 =>
-- Reserved for Nordic firmware design.
NRFFW : aliased NRFFW_Registers;
end case;
end record
with Unchecked_Union, Volatile;
for UICR_Peripheral use record
CLENR0 at 16#0# range 0 .. 31;
RBPCONF at 16#4# range 0 .. 31;
XTALFREQ at 16#8# range 0 .. 31;
FWID at 16#10# range 0 .. 31;
NRFHW at 16#50# range 0 .. 383;
CUSTOMER at 16#80# range 0 .. 1023;
BOOTLOADERADDR at 16#14# range 0 .. 31;
NRFFW at 16#14# range 0 .. 479;
end record;
-- User Information Configuration.
UICR_Periph : aliased UICR_Peripheral
with Import, Address => UICR_Base;
end NRF_SVD.UICR;
|
with Ada.Text_IO;
procedure Program is
Comment_Characters : String := "#;";
begin
loop
declare
Line : String := Ada.Text_IO.Get_Line;
begin
exit when Line'Length = 0;
Outer_Loop : for I in Line'Range loop
for J in Comment_Characters'Range loop
if Comment_Characters(J) = Line(I) then
Ada.Text_IO.Put_Line(Line(Line'First .. I - 1));
exit Outer_Loop;
end if;
end loop;
end loop Outer_Loop;
end;
end loop;
end Program;
|
package Separated is
procedure Watch_Me;
function Look_Out return Float;
end Separated;
|
-- { dg-do compile }
procedure aggr7 is
package P is
type T is limited private;
type TT is limited private;
type TTT is tagged limited private;
private
type T is limited
record
Self : access T := T'Unchecked_Access;
end record;
type TT is tagged limited
record
Self : access TT := TT'Unchecked_Access;
end record;
type TTT is tagged limited
record
Self : access TTT := TTT'Unchecked_Access;
end record;
end P;
package body P is
X : T := (Self => <>);
XX : TT := (Self => <>);
XXX : TTT := (Self => <>);
Y : T := (others => <>);
YY : TT := (others => <>);
YYY : TTT := (others => <>);
end P;
begin
null;
end aggr7;
|
-- RUN: %llvmgcc -S %s -I%p/Support
package body Var_Offset is
function F (X : T) return Character is
begin
return X.Bad_Field;
end;
end;
|
-- 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.Strings.Unbounded; use Ada.Strings.Unbounded;
with Bases; use Bases;
with Items; use Items;
with Ships; use Ships;
-- ****h* Trades/Trades
-- FUNCTION
-- Provides code for trading with ships and bases
-- SOURCE
package Trades is
-- ****
-- ****v* Trades/Trades.TraderCargo
-- FUNCTION
-- List of all cargo in trader ship
-- SOURCE
TraderCargo: BaseCargo_Container.Vector;
-- ****
-- ****e* Trades/Trades.Trade_Cant_Buy
-- FUNCTION
-- Raised when items is not available to buy
-- SOURCE
Trade_Cant_Buy: exception;
-- ****
-- ****e* Trades/Trades.Trade_Not_For_Sale_Now
-- FUNCTION
-- Raised when no items available at this time for sale
-- SOURCE
Trade_Not_For_Sale_Now: exception;
-- ****
-- ****e* Trades/Trades.Trade_Buying_Too_Much
-- FUNCTION
-- Raised when player trying buy more than can
-- SOURCE
Trade_Buying_Too_Much: exception;
-- ****
-- ****e* Trades/Trades.Trade_No_Free_Cargo
-- FUNCTION
-- Raised when no enough free cargo in ship
-- SOURCE
Trade_No_Free_Cargo: exception;
-- ****
-- ****e* Trades/Trades.Trade_No_Money
-- FUNCTION
-- Raised when player don't have money
-- SOURCE
Trade_No_Money: exception;
-- ****
-- ****e* Trades/Trades.Trade_Not_Enough_Money
-- FUNCTION
-- Raised when player don't have enough money
-- SOURCE
Trade_Not_Enough_Money: exception;
-- ****
-- ****e* Trades/Trades.Trade_Invalid_Amount
-- FUNCTION
-- Raised when player enter invalid amount
-- SOURCE
Trade_Invalid_Amount: exception;
-- ****
-- ****e* Trades/Trades.Trade_Too_Much_For_Sale
-- FUNCTION
-- Raised when player try sell more than have
-- SOURCE
Trade_Too_Much_For_Sale: exception;
-- ****
-- ****e* Trades/Trades.Trade_No_Money_In_Base
-- FUNCTION
-- Raised when base don't have enough money for buy item
-- SOURCE
Trade_No_Money_In_Base: exception;
-- ****
-- ****e* Trades/Trades.Trade_No_Trader
-- FUNCTION
-- Raised when no one is assigned to talk in bases duty
-- SOURCE
Trade_No_Trader: exception;
-- ****
-- ****f* Trades/Trades.BuyItems
-- FUNCTION
-- Buy items from bases or trader
-- PARAMETERS
-- BaseItemIndex - Base or ship cargo index of item to buy
-- Amount - Amount of items to buy
-- SOURCE
procedure BuyItems
(BaseItemIndex: BaseCargo_Container.Extended_Index; Amount: String) with
Pre => Amount'Length > 0,
Test_Case => (Name => "Test_BuyItems", Mode => Nominal);
-- ****
-- ****f* Trades/Trades.SellItems
-- FUNCTION
-- Sell items from bases or trader
-- PARAMETERS
-- ItemIndex - Player ship cargo index of item to sell
-- Amount - Amount of items to sell
-- SOURCE
procedure SellItems
(ItemIndex: Inventory_Container.Extended_Index; Amount: String) with
Pre => ItemIndex in
Player_Ship.Cargo.First_Index .. Player_Ship.Cargo.Last_Index and
Amount'Length > 0,
Test_Case => (Name => "Test_SellItems", Mode => Nominal);
-- ****
-- ****f* Trades/Trades.GenerateTraderCargo
-- FUNCTION
-- Generate list of cargo to trade
-- PARAMETERS
-- ProtoIndex - Index of prototype ship which will be used to generate
-- cargo
-- SOURCE
procedure GenerateTraderCargo(ProtoIndex: Unbounded_String) with
Pre => Proto_Ships_Container.Contains(Proto_Ships_List, ProtoIndex),
Test_Case => (Name => "Test_GenerateTraderCargo", Mode => Nominal);
-- ****
end Trades;
|
package openGL.remote_Model
--
-- Provides a DSA friendly base class for 3D models.
--
is
pragma remote_Types;
type Item is abstract tagged
record
Id : model_Id := null_model_Id;
Scale : Vector_3 := (1.0, 1.0, 1.0);
Shine : openGL.Shine := 200.0;
end record;
end openGL.remote_Model;
|
-- 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.TtkLabelFrame.Ttk_Label_Frame_Options_Test_Data
.Ttk_Label_Frame_Options_Tests
is
type Test_Ttk_Label_Frame_Options is new GNATtest_Generated
.GNATtest_Standard
.Tk
.TtkLabelFrame
.Ttk_Label_Frame_Options_Test_Data
.Test_Ttk_Label_Frame_Options with
null record;
procedure Test_Configure_0076be_459bf9
(Gnattest_T: in out Test_Ttk_Label_Frame_Options);
-- tk-ttklabelframe.ads:88:4:Configure:Test_Configure_TtkLabelFrame
procedure Test_Create_32e405_465c74
(Gnattest_T: in out Test_Ttk_Label_Frame_Options);
-- tk-ttklabelframe.ads:115:4:Create:Test_Create_TtkLabelFrame1
procedure Test_Create_ebbdc1_d1ec6f
(Gnattest_T: in out Test_Ttk_Label_Frame_Options);
-- tk-ttklabelframe.ads:149:4:Create:Test_Create_TtkLabelFrame2
procedure Test_Get_Options_ded36e_39fa14
(Gnattest_T: in out Test_Ttk_Label_Frame_Options);
-- tk-ttklabelframe.ads:174:4:Get_Options:Test_Get_Options_TtkLabelFrame
end Tk.TtkLabelFrame.Ttk_Label_Frame_Options_Test_Data
.Ttk_Label_Frame_Options_Tests;
-- end read only
|
-----------------------------------------------------------------------
-- asf-applications-tests - ASF Application tests using ASFUnit
-- Copyright (C) 2011, 2012, 2015, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log;
with Util.Test_Caller;
with ASF.Tests;
with ASF.Events.Faces.Actions;
with ASF.Requests.Mockup;
with ASF.Responses.Mockup;
with ASF.Applications.Main;
with ASF.Applications.Main.Configs;
with ASF.Models.Selects;
with ASF.Contexts.Faces;
pragma Warnings (Off); -- gcc complains that the package is not referenced but it is!
with ASF.Contexts.Flash;
pragma Warnings (On);
package body ASF.Applications.Tests is
use ASF.Tests;
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Applications");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test service HTTP invalid method",
Test_Invalid_Request'Access);
Caller.Add_Test (Suite, "Test service HTTP GET (File_Servlet)",
Test_Get_File'Access);
Caller.Add_Test (Suite, "Test service HTTP GET 404",
Test_Get_404'Access);
Caller.Add_Test (Suite, "Test service HTTP GET (Measure_Servlet)",
Test_Get_Measures'Access);
Caller.Add_Test (Suite, "Test service HTTP POST+INVOKE_APPLICATION (inputText)",
Test_Form_Post'Access);
Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION (inputText)",
Test_Form_Post_Validation_Error'Access);
Caller.Add_Test (Suite, "Test service HTTP POST+PROCESS_VALIDATION (selectOneMenu)",
Test_Form_Post_Select'Access);
Caller.Add_Test (Suite, "Test AJAX bean method invocation",
Test_Ajax_Action'Access);
Caller.Add_Test (Suite, "Test AJAX invalid requests",
Test_Ajax_Action_Error'Access);
Caller.Add_Test (Suite, "Test POST/REDIRECT/GET with flash object",
Test_Flash_Object'Access);
Caller.Add_Test (Suite, "Test GET+POST request with the default navigation",
Test_Default_Navigation_Rule'Access);
Caller.Add_Test (Suite, "Test GET with view parameters",
Test_View_Params'Access);
Caller.Add_Test (Suite, "Test GET with view action",
Test_View_Action'Access);
Caller.Add_Test (Suite, "Test GET with request parameter injection from URI",
Test_View_Inject_Parameter'Access);
end Add_Tests;
package Save_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Form_Bean,
Method => Save,
Name => "save");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (Save_Binding.Proxy'Access,
Save_Binding.Proxy'Access);
-- ------------------------------
-- Get the value identified by the name.
-- ------------------------------
overriding
function Get_Value (From : in Form_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "email" then
return Util.Beans.Objects.To_Object (From.Email);
elsif Name = "password" then
return Util.Beans.Objects.To_Object (From.Password);
elsif Name = "name" then
return Util.Beans.Objects.To_Object (From.Name);
elsif Name = "gender" then
return Util.Beans.Objects.To_Object (From.Gender);
elsif Name = "genderList" then
declare
List : ASF.Models.Selects.Select_Item_List;
begin
ASF.Models.Selects.Append (List, ASF.Models.Selects.Create_Select_Item ("None", "0"));
ASF.Models.Selects.Append (List, ASF.Models.Selects.Create_Select_Item ("Mrs", "1"));
ASF.Models.Selects.Append (List, ASF.Models.Selects.Create_Select_Item ("Mr", "2"));
ASF.Models.Selects.Append (List, ASF.Models.Selects.Create_Select_Item ("Mss", "3"));
return ASF.Models.Selects.To_Object (List);
end;
elsif Name = "called" then
return Util.Beans.Objects.To_Object (From.Called);
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- ------------------------------
overriding
procedure Set_Value (From : in out Form_Bean;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
-- Simulate a Set_Value that raises some exception during the Update_Values phase.
if Util.Beans.Objects.To_String (Value) = "error" then
From.Perm_Error := True;
raise Constraint_Error;
end if;
if Name = "email" then
From.Email := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "password" then
From.Password := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "name" then
From.Name := Util.Beans.Objects.To_Unbounded_String (Value);
elsif Name = "gender" then
From.Gender := Util.Beans.Objects.To_Unbounded_String (Value);
end if;
end Set_Value;
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Form_Bean)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
-- ------------------------------
-- Create a form bean.
-- ------------------------------
function Create_Form_Bean return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Form_Bean_Access := new Form_Bean;
begin
return Result.all'Access;
end Create_Form_Bean;
-- ------------------------------
-- Create a list of forms.
-- ------------------------------
function Create_Form_List return Util.Beans.Basic.Readonly_Bean_Access is
Result : constant Form_Lists.List_Bean_Access := new Form_Lists.List_Bean;
Form : Form_Bean;
begin
for I in 1 .. 100 loop
Form.Name := To_Unbounded_String ("Name" & Integer'Image (I));
Form.Email := To_Unbounded_String ("Joe" & Integer'Image (I) & "@gmail.com");
Result.List.Append (Form);
end loop;
return Result.all'Access;
end Create_Form_List;
-- ------------------------------
-- Initialize the ASF application for the unit test.
-- ------------------------------
procedure Initialize_Test_Application is
use type ASF.Applications.Main.Application_Access;
Fact : ASF.Applications.Main.Application_Factory;
Config : constant String := Util.Tests.Get_Path ("regtests/config/test-config.xml");
begin
if ASF.Tests.Get_Application = null then
ASF.Tests.Initialize (Util.Tests.Get_Properties, Factory => Fact);
end if;
ASF.Applications.Main.Configs.Read_Configuration (App => ASF.Tests.Get_Application.all,
File => Config);
ASF.Tests.Get_Application.Start;
end Initialize_Test_Application;
-- ------------------------------
-- Initialize the test application
-- ------------------------------
overriding
procedure Set_Up (T : in out Test) is
pragma Unreferenced (T);
begin
Initialize_Test_Application;
end Set_Up;
-- ------------------------------
-- Action to authenticate a user (password authentication).
-- ------------------------------
procedure Save (Data : in out Form_Bean;
Outcome : in out Unbounded_String) is
use Util.Beans.Objects;
begin
if Data.Def_Nav then
Outcome := To_Unbounded_String ("form-default-result");
else
Outcome := To_Unbounded_String ("success");
end if;
Data.Called := Data.Called + 1;
if Data.Use_Flash then
declare
Ctx : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
Ctx.Get_Flash.Set_Attribute ("name", To_Object (Data.Name));
Ctx.Get_Flash.Set_Attribute ("email", To_Object (Data.Email));
Ctx.Get_Flash.Set_Keep_Messages (True);
Ctx.Add_Message (Client_Id => "",
Message => "Message saved in the flash context");
end;
end if;
if Data.Perm_Error then
raise Test_Exception;
end if;
end Save;
-- ------------------------------
-- Test an invalid HTTP request.
-- ------------------------------
procedure Test_Invalid_Request (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
-- Unknown method
Request.Set_Method ("BLAB");
Request.Set_Request_URI ("/asfunit/views/set.xhtml");
Do_Req (Request, Reply);
Assert_Equals (T, ASF.Responses.SC_NOT_IMPLEMENTED, Reply.Get_Status, "Invalid response");
-- PUT on a file is not allowed
Request.Set_Method ("PUT");
Request.Set_Request_URI ("/asfunit/views/set.xhtml");
Do_Req (Request, Reply);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response");
-- POST on a file is not allowed
Request.Set_Method ("POST");
Request.Set_Request_URI ("/asfunit/views/set.xhtml");
Do_Req (Request, Reply);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response");
-- DELETE on a file is not allowed
Request.Set_Method ("DELETE");
Request.Set_Request_URI ("/asfunit/views/set.xhtml");
Do_Req (Request, Reply);
Assert_Equals (T, ASF.Responses.SC_METHOD_NOT_ALLOWED, Reply.Get_Status, "Invalid response");
end Test_Invalid_Request;
-- ------------------------------
-- Test a GET request on a static file served by the File_Servlet.
-- ------------------------------
procedure Test_Get_404 (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/file-does-not-exist.txt", "test-404.html");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response");
Assert_Matches (T, ".*This is a 404 error page.*", Reply, "Invalid 404 page returned",
Status => ASF.Responses.SC_NOT_FOUND);
Do_Get (Request, Reply, "/file-does-not-exist.js", "test-404.html");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid response");
Assert_Matches (T, ".*This is a 404 error page.*", Reply, "Invalid 404 page returned",
Status => ASF.Responses.SC_NOT_FOUND);
end Test_Get_404;
-- ------------------------------
-- Test a GET request on a static file served by the File_Servlet.
-- ------------------------------
procedure Test_Get_File (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/views/set.xhtml", "get-file-set.txt");
Assert_Contains (T, "<c:set var=""user"" value=""John Smith""/>", Reply, "Wrong content");
Assert_Header (T, "Content-Type", "text/plain", Reply, "Content-Type");
Do_Get (Request, Reply, "/views/set.html", "get-file-set.html");
Assert_Matches (T, "^\s*John Smith\s?$", Reply, "Wrong content");
Assert_Header (T, "Content-Type", "text/html", Reply, "Content-Type");
Do_Get (Request, Reply, "/js/asf.js", "get-file-asf.js");
Assert_Matches (T, "^\s*var ASF = {};\s?$", Reply, "Wrong content");
Assert_Header (T, "Content-Type", "text/javascript", Reply, "Content-Type");
Do_Get (Request, Reply, "/css/asf.css", "get-file-asf.css");
Assert_Matches (T, "^.*asf.css.*$", Reply, "Wrong content");
Assert_Header (T, "Content-Type", "text/css", Reply, "Content-Type");
end Test_Get_File;
-- ------------------------------
-- Test a GET request on the measure servlet
-- ------------------------------
procedure Test_Get_Measures (T : in out Test) is
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
begin
Do_Get (Request, Reply, "/stats.xml", "stats.xml");
-- We must get at least one measure value (assuming the Test_Get_File test
-- was executed).
Assert_Matches (T, "<time count=""\d+"" time=""\d+.\d+ [um]s"" title="".*""/>",
Reply, "Wrong content");
end Test_Get_Measures;
-- ------------------------------
-- Test a GET+POST request with submitted values and an action method called on the bean.
-- ------------------------------
procedure Test_Form_Post (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/form-text.html", "form-text.txt");
Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content");
Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*",
Reply, "Wrong form content");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "john@gmail.com");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt");
Assert_Matches (T, ".*success exact.*",
Reply, "Wrong form content");
Assert_Equals (T, "John", Form.Name, "Form name not saved in the bean");
Assert_Equals (T, "12345", Form.Password, "Form password not saved in the bean");
Assert_Equals (T, "john@gmail.com", Form.Email, "Form email not saved in the bean");
Assert_Equals (T, 1, Form.Called, "save action was not called");
end Test_Form_Post;
-- ------------------------------
-- Test a POST request with an invalid submitted value
-- ------------------------------
procedure Test_Form_Post_Validation_Error (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
-- Post with password too short and empty email
Request.Set_Parameter ("ok", "1");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12");
Request.Set_Parameter ("email", "");
Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-1.txt");
Assert_Matches (T, ".*<input type=.text. name=.name. value=.John. id=.name.*",
Reply, "Wrong form content");
Assert_Matches (T, ".*Validation Error: Length is less than "
& "allowable minimum of '4'.*",
Reply, "Missing error message");
-- No field should be modified.
Assert_Equals (T, "", Form.Name, "Form name was saved in the bean");
Assert_Equals (T, "", Form.Password, "Form password was saved in the bean");
Assert_Equals (T, "", Form.Email, "Form email was saved in the bean");
Request.Set_Parameter ("ok", "1");
Request.Set_Parameter ("email", "1");
Request.Set_Parameter ("password", "12333");
Request.Set_Parameter ("name", "122222222222222222222222222222222222222222");
Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-2.txt");
Assert_Matches (T, ".*<span class=.error.>Invalid email address</span>.*",
Reply, "Invalid error message for email");
Assert_Matches (T, ".*<span class=.error.>Invalid name</span>.*",
Reply, "Invalid error message for name");
Request.Set_Parameter ("ok", "1");
Request.Set_Parameter ("email", "1dddddd");
Request.Set_Parameter ("password", "12333ddddddddddddddd");
Request.Set_Parameter ("name", "1222222222");
Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-3.txt");
Assert_Matches (T, ".*Validation Error: Length is greater than "
& "allowable maximum of '10'.*",
Reply, "Invalid error message for password");
Request.Set_Parameter ("ok", "1");
Request.Set_Parameter ("email", "error");
Request.Set_Parameter ("password", "12333");
Request.Set_Parameter ("name", "1222222222");
Do_Post (Request, Reply, "/tests/form-text.html", "form-text-post-4.txt");
Assert_Matches (T, ".*<span class=.error.>Validation Error: Value is not correct.*",
Reply, "Invalid error message for name");
Assert_Equals (T, 0, Form.Called, "Save method should not be called");
end Test_Form_Post_Validation_Error;
-- ------------------------------
-- Test a GET+POST request with form having <h:selectOneMenu> element.
-- ------------------------------
procedure Test_Form_Post_Select (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/form-select.html", "form-select.txt");
Assert_Matches (T, ".*<label for=.gender.>Gender</label>.*", Reply, "Wrong form content");
Assert_Matches (T, ".*<select name=.gender.*",
Reply, "Wrong form content");
Request.Set_Parameter ("formSelect", "1");
Request.Set_Parameter ("gender", "2");
Do_Post (Request, Reply, "/tests/form-select.html", "form-select-post.txt");
Assert_Matches (T, ".*<option value=.2. selected=.selected.*",
Reply, "Wrong form content");
Request.Set_Parameter ("formSelect", "1");
Request.Set_Parameter ("gender", "3");
Do_Post (Request, Reply, "/tests/form-select.html", "form-select-post2.txt");
Assert_Matches (T, ".*<option value=.3. selected=.selected.*",
Reply, "Wrong form content");
end Test_Form_Post_Select;
-- ------------------------------
-- Test a POST request to invoke a bean method.
-- ------------------------------
procedure Test_Ajax_Action (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Post (Request, Reply, "/ajax/form/save", "ajax-action-1.txt");
Assert_Equals (T, 1, Form.Called, "Save method was not called");
end Test_Ajax_Action;
-- ------------------------------
-- Test a POST request to invoke a bean method.
-- Verify that invalid requests raise an error.
-- ------------------------------
procedure Test_Ajax_Action_Error (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Post (Request, Reply, "/ajax/", "ajax-error-1.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 1");
Do_Post (Request, Reply, "/ajax/a", "ajax-error-2.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 2");
Do_Post (Request, Reply, "/ajax/a/", "ajax-error-3.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 3");
Do_Post (Request, Reply, "/ajax//c", "ajax-error-4.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 4");
Do_Post (Request, Reply, "/ajax/form/savex", "ajax-error-5.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 5");
Do_Post (Request, Reply, "/ajax/formx/save", "ajax-error-6.txt");
Assert_Equals (T, ASF.Responses.SC_NOT_FOUND, Reply.Get_Status, "Invalid error response 6");
end Test_Ajax_Action_Error;
-- ------------------------------
-- Test a POST/REDIRECT/GET request with a flash information passed in between.
-- ------------------------------
procedure Test_Flash_Object (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
Path : constant String := Util.Tests.Get_Path ("regtests/config/test-config.xml");
App : constant ASF.Applications.Main.Application_Access := ASF.Tests.Get_Application;
begin
ASF.Applications.Main.Configs.Read_Configuration (App.all, Path);
Form.Use_Flash := True;
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/form-text-redirect.html", "form-text-flash.txt");
Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content");
Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*",
Reply, "Wrong form content");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "john@gmail.com");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/form-text-redirect.html", "form-text-post-flash.txt");
-- The navigation rule should redirect to the GET page.
Assert_Redirect (T, "/asfunit/tests/flash-data.html", Reply, "Invalid response");
Request.Set_Cookie (Reply);
Do_Get (Request, Reply, "/tests/flash-data.html", "flash-data.txt");
Assert_Matches (T, ".*Name: John.*",
Reply, "Wrong form content");
Assert_Matches (T, ".*Email: john@gmail.com",
Reply, "Wrong form content");
Assert_Matches (T, ".*Message saved in the flash context.*",
Reply, "Message was not restored");
Request.Set_Cookie (Reply);
Do_Get (Request, Reply, "/tests/flash-data.html", "flash-data-2.txt");
Assert_Matches (T, ".*Name: Email:",
Reply, "Wrong form content");
end Test_Flash_Object;
-- ------------------------------
-- Test a GET+POST request with the default navigation rule based on the outcome.
-- ------------------------------
procedure Test_Default_Navigation_Rule (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
begin
Form.Def_Nav := True;
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/form-text-default.html", "form-text-default.txt");
Assert_Matches (T, ".*<label for=.name.>Name</label>.*", Reply, "Wrong form content");
Assert_Matches (T, ".*<input type=.text. name=.name. value=.. id=.name.*",
Reply, "Wrong form content");
Request.Set_Parameter ("formText", "1");
Request.Set_Parameter ("name", "John");
Request.Set_Parameter ("password", "12345");
Request.Set_Parameter ("email", "john@gmail.com");
Request.Set_Parameter ("ok", "1");
Do_Post (Request, Reply, "/tests/form-text-default.html", "form-text-post-default.txt");
Assert_Matches (T, ".*Email: john@gmail.com Name: John.*",
Reply, "Wrong form content");
end Test_Default_Navigation_Rule;
-- ------------------------------
-- Test a GET request with meta data and view parameters.
-- ------------------------------
procedure Test_View_Params (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
Path : constant String := Util.Tests.Get_Path ("regtests/config/test-config.xml");
App : constant ASF.Applications.Main.Application_Access := ASF.Tests.Get_Application;
begin
ASF.Applications.Main.Configs.Read_Configuration (App.all, Path);
Form.Use_Flash := True;
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/view-params.html?name=John&email=john@gmail.com&is_a=male",
"view-params.txt");
Assert_Equals (T, "John", Form.Name, "View parameter for name was not set");
Assert_Equals (T, "john@gmail.com", Form.Email, "View parameter for email was not set");
Assert_Equals (T, "male", Form.Gender, "View parameter for gender was not set");
Assert_Matches (T, ".*Name: John Email: john@gmail.com Gender: male",
Reply, "Wrong generated content");
end Test_View_Params;
-- ------------------------------
-- Test a GET request with meta data and view action.
-- ------------------------------
procedure Test_View_Action (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
Path : constant String := Util.Tests.Get_Path ("regtests/config/test-config.xml");
App : constant ASF.Applications.Main.Application_Access := ASF.Tests.Get_Application;
begin
ASF.Applications.Main.Configs.Read_Configuration (App.all, Path);
Form.Use_Flash := True;
Request.Set_Attribute ("form", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/tests/view-action.html?name=John&email=john@gmail.com&is_a=male",
"view-action.txt");
Assert_Equals (T, 1, Form.Called, "View action was not called");
Assert_Equals (T, "John", Form.Name, "View parameter for name was not set");
Assert_Equals (T, "john@gmail.com", Form.Email, "View parameter for email was not set");
Assert_Equals (T, "male", Form.Gender, "View parameter for gender was not set");
Assert_Matches (T, ".*Name: John Email: john@gmail.com Gender: male",
Reply, "Wrong generated content");
end Test_View_Action;
-- ------------------------------
-- Test a GET request with pretty URL and request parameter injection.
-- ------------------------------
procedure Test_View_Inject_Parameter (T : in out Test) is
use Util.Beans.Objects;
Request : ASF.Requests.Mockup.Request;
Reply : ASF.Responses.Mockup.Response;
Form : aliased Form_Bean;
Path : constant String := Util.Tests.Get_Path ("regtests/config/test-inject.xml");
App : constant ASF.Applications.Main.Application_Access := ASF.Tests.Get_Application;
begin
ASF.Applications.Main.Configs.Read_Configuration (App.all, Path);
App.Dump_Routes (Util.Log.INFO_LEVEL);
Form.Use_Flash := True;
Request.Set_Attribute ("user", To_Object (Value => Form'Unchecked_Access,
Storage => STATIC));
Do_Get (Request, Reply, "/users/john/view", "view-user.txt");
Assert_Equals (T, 0, Form.Called, "View action must not be called");
Assert_Equals (T, "john", Form.Name, "View parameter for name was not set");
Assert_Matches (T, ".*Name: john Email: Gender: ",
Reply, "Wrong generated content");
Do_Get (Request, Reply, "/users/harry/potter/view", "view-user2.txt");
Assert_Equals (T, "harry", Form.Name, "View parameter for name was not set");
Assert_Equals (T, "potter", Form.Email, "View parameter for email was not set");
Assert_Matches (T, ".*Name: harry Email: potter Gender: ",
Reply, "Wrong generated content");
Do_Get (Request, Reply, "/users/Gandalf/Mithrandir/view/wizard", "view-user3.txt");
Assert_Equals (T, "Gandalf", Form.Name, "View parameter for name was not set");
Assert_Equals (T, "Mithrandir", Form.Email, "View parameter for email was not set");
Assert_Equals (T, "wizard", Form.Gender, "View parameter for gender was not set");
Assert_Matches (T, ".*Name: Gandalf Email: Mithrandir Gender: wizard",
Reply, "Wrong generated content");
end Test_View_Inject_Parameter;
end ASF.Applications.Tests;
|
with Ada.Text_Io;
procedure Main is
begin
Ada.Text_Io.Put_Line(Item=>'Hello World');
end Main;
|
package body Word_Wrap is
procedure Push_Word(State: in out Basic; Word: String) is
begin
if Word'Length + State.Size >= State.Length_Of_Output_Line then
Put_Line(State.Line(1 .. State.Size));
State.Line(1 .. Word'Length) := Word; -- may raise CE if Word too long
State.Size := Word'Length;
elsif State.Size > 0 then
State.Line(State.Size+1 .. State.Size+1+Word'Length) := ' ' & Word;
State.Size := State.Size + 1 + Word'Length;
else
State.Line(1 .. Word'Length) := Word;
State.Size := Word'Length;
end if;
State.Top_Of_Paragraph := False;
end Push_Word;
procedure New_Paragraph(State: in out Basic) is
begin
Finish(State);
if not State.Top_Of_Paragraph then
Put_Line("");
State.Top_Of_Paragraph := True;
end if;
end New_Paragraph;
procedure Finish(State: in out Basic) is
begin
if State.Size > 0 then
Put_Line(State.Line(1 .. State.Size));
State.Size := 0;
end if;
end Finish;
end Word_Wrap;
|
-----------------------------------------------------------------------
-- gen-artifacts-mappings -- Type mapping artifact for Code Generator
-- Copyright (C) 2011, 2012, 2015, 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 Util.Log.Loggers;
with Gen.Utils;
with Gen.Model;
with Gen.Model.Mappings;
-- The <b>Gen.Artifacts.Mappings</b> package is an artifact to map XML-based types
-- into Ada types.
package body Gen.Artifacts.Mappings is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
-- ------------------------------
-- Register a new type mapping.
-- ------------------------------
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
N : constant DOM.Core.Node := Gen.Utils.Get_Child (Node, "to");
To : constant String := Gen.Utils.Get_Data_Content (N);
Kind : constant String := To_String (Gen.Utils.Get_Attribute (Node, "type"));
Allow_Null : constant Boolean := Gen.Utils.Get_Attribute (Node, "allow-null", False);
Kind_Type : Gen.Model.Mappings.Basic_Type;
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
pragma Unreferenced (O);
From : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Gen.Model.Mappings.Register_Type (Target => To,
From => From,
Kind => Kind_Type,
Allow_Null => Allow_Null);
end Register_Type;
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Type);
begin
if Kind = "date" or To = "Ada.Calendar.Time" then
Kind_Type := Gen.Model.Mappings.T_DATE;
elsif Kind = "identifier" or To = "ADO.Identifier" then
Kind_Type := Gen.Model.Mappings.T_IDENTIFIER;
elsif Kind = "boolean" then
Kind_Type := Gen.Model.Mappings.T_BOOLEAN;
elsif Kind = "float" then
Kind_Type := Gen.Model.Mappings.T_FLOAT;
elsif Kind = "string" or To = "Ada.Strings.Unbounded.Unbounded_String" then
Kind_Type := Gen.Model.Mappings.T_STRING;
elsif Kind = "blob" or To = "ADO.Blob_Ref" then
Kind_Type := Gen.Model.Mappings.T_BLOB;
elsif Kind = "entity_type" or To = "ADO.Entity_Type" then
Kind_Type := Gen.Model.Mappings.T_ENTITY_TYPE;
else
Kind_Type := Gen.Model.Mappings.T_INTEGER;
end if;
Iterate (O, Node, "from");
end Register_Mapping;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
begin
Gen.Model.Mappings.Set_Mapping_Name (Name);
Iterate (Model, Node, "mapping");
end Register_Mappings;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mappings);
begin
Log.Debug ("Initializing mapping artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "mappings");
end Initialize;
end Gen.Artifacts.Mappings;
|
pragma License (Unrestricted);
private with System.UTF_Conversions.From_8_To_16;
private with System.UTF_Conversions.From_8_To_32;
private with System.UTF_Conversions.From_16_To_32;
private with System.UTF_Conversions.From_16_To_8;
private with System.UTF_Conversions.From_32_To_8;
private with System.UTF_Conversions.From_32_To_16;
package Ada.Characters.Conversions is
pragma Pure;
-- extended
-- Use Is_Wide_String instead of Is_Wide_Character for multi-byte sequence.
-- Is_Wide_String checks if all code-points of Item can be converted to
-- UTF-16 Wide_String (each code-point is in BMP or surrogate pair).
-- These functions Is_XXX_String assume Item contains a legal sequence.
function Is_Wide_Character (Item : Character) return Boolean;
function Is_Wide_String (Item : String) return Boolean;
-- extended
-- Use Is_Wide_Wide_String instead of Is_Wide_Wide_Character for multi-byte
-- sequence.
-- UTF-8 String can always be converted to UTF-32 Wide_Wide_String.
function Is_Wide_Wide_Character (Item : Character) return Boolean
renames Is_Wide_Character;
-- function Is_Wide_Wide_String (Item : String) return Boolean; -- True
-- Do not use Is_Character for Item that is greater than 16#7F#.
-- UTF-16 Wide_String can always be converted to UTF-8 String.
function Is_Character (Item : Wide_Character) return Boolean;
function Is_String (Item : Wide_String) return Boolean; -- True
-- extended
-- Do not use Is_Wide_Wide_Character for surrogate pair.
-- UTF-16 Wide_String can always be converted to UTF-32 Wide_Wide_String.
function Is_Wide_Wide_Character (Item : Wide_Character) return Boolean;
-- function Is_Wide_Wide_String (Item : Wide_String) return Boolean; -- True
-- Do not use Is_Character for Item that is greater than 16#7F#.
-- UTF-32 Wide_Wide_String can always be converted to UTF-8 String.
function Is_Character (Item : Wide_Wide_Character) return Boolean;
function Is_String (Item : Wide_Wide_String) return Boolean; -- True
-- Use Is_Wide_String instead of Is_Wide_Character for Item that is greater
-- than 16#FFFF#.
function Is_Wide_Character (Item : Wide_Wide_Character) return Boolean;
function Is_Wide_String (Item : Wide_Wide_String) return Boolean;
pragma Inline (Is_Character);
pragma Inline (Is_Wide_Character);
pragma Inline (Is_Wide_Wide_Character);
pragma Inline (Is_String);
-- modified
-- These functions use Substitute if Item contains illegal byte sequence.
function To_Wide_Character (
Item : Character;
Substitute : Wide_Character := ' ') -- additional
return Wide_Character;
function To_Wide_String (
Item : String;
Substitute : Wide_String := " ") -- additional
return Wide_String;
-- modified
function To_Wide_Wide_Character (
Item : Character;
Substitute : Wide_Wide_Character := ' ') -- additional
return Wide_Wide_Character;
function To_Wide_Wide_String (
Item : String;
Substitute : Wide_Wide_String := " ") -- additional
return Wide_Wide_String;
-- modified
function To_Wide_Wide_Character (
Item : Wide_Character;
Substitute : Wide_Wide_Character := ' ') -- additional
return Wide_Wide_Character;
function To_Wide_Wide_String (
Item : Wide_String;
Substitute : Wide_Wide_String := " ") -- additional
return Wide_Wide_String;
function To_Character (
Item : Wide_Character;
Substitute : Character := ' ')
return Character;
function To_String (
Item : Wide_String;
Substitute : Character := ' ')
return String;
-- extended
function To_String (
Item : Wide_String;
Substitute : String)
return String;
function To_Character (
Item : Wide_Wide_Character;
Substitute : Character := ' ')
return Character;
function To_String (
Item : Wide_Wide_String;
Substitute : Character := ' ')
return String;
-- extended
function To_String (
Item : Wide_Wide_String;
Substitute : String)
return String;
function To_Wide_Character (
Item : Wide_Wide_Character;
Substitute : Wide_Character := ' ')
return Wide_Character;
function To_Wide_String (
Item : Wide_Wide_String;
Substitute : Wide_Character := ' ')
return Wide_String;
-- extended
function To_Wide_String (
Item : Wide_Wide_String;
Substitute : Wide_String)
return Wide_String;
pragma Inline (To_String); -- renamed, or normal inline
pragma Inline (To_Wide_String); -- renamed, or normal inline
pragma Inline (To_Wide_Wide_String); -- renamed, or normal inline
-- extended
-- There are subprograms for code-point based decoding iteration.
procedure Get (
Item : String;
Last : out Natural;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get (
Item : String;
Last : out Natural;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
procedure Get_Reverse (
Item : String;
First : out Positive;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get_Reverse (
Item : String;
First : out Positive;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
procedure Get (
Item : Wide_String;
Last : out Natural;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get (
Item : Wide_String;
Last : out Natural;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
procedure Get_Reverse (
Item : Wide_String;
First : out Positive;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get_Reverse (
Item : Wide_String;
First : out Positive;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
procedure Get (
Item : Wide_Wide_String;
Last : out Natural;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get (
Item : Wide_Wide_String;
Last : out Natural;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
procedure Get_Reverse (
Item : Wide_Wide_String;
First : out Positive;
Value : out Wide_Wide_Character;
Substitute : Wide_Wide_Character := ' ');
procedure Get_Reverse (
Item : Wide_Wide_String;
First : out Positive;
Value : out Wide_Wide_Character;
Is_Illegal_Sequence : out Boolean);
-- extended
-- Encoding subprograms:
procedure Put (
Value : Wide_Wide_Character;
Item : out String;
Last : out Natural);
procedure Put (
Value : Wide_Wide_Character;
Item : out Wide_String;
Last : out Natural);
procedure Put (
Value : Wide_Wide_Character;
Item : out Wide_Wide_String;
Last : out Natural);
-- extended
-- Max lengths of each one multi-byte character,
-- and the rates of expansion:
Max_Length_In_String : constant := 6;
Max_Length_In_Wide_String : constant := 2;
Max_Length_In_Wide_Wide_String : constant := 1;
Expanding_From_String_To_Wide_String : constant := 1;
Expanding_From_String_To_Wide_Wide_String : constant := 1;
Expanding_From_Wide_String_To_String : constant := 3;
Expanding_From_Wide_String_To_Wide_Wide_String : constant := 1;
Expanding_From_Wide_Wide_String_To_String : constant := 6;
Expanding_From_Wide_Wide_String_To_Wide_String : constant := 2;
Expanding_From_String_To_UTF_8 : constant := 1;
Expanding_From_String_To_UTF_16 : constant := 1;
Expanding_From_String_To_UTF_32 : constant := 1;
Expanding_From_Wide_String_To_UTF_8 : constant := 3;
Expanding_From_Wide_String_To_UTF_16 : constant := 1;
Expanding_From_Wide_String_To_UTF_32 : constant := 1;
Expanding_From_Wide_Wide_String_To_UTF_8 : constant := 6;
Expanding_From_Wide_Wide_String_To_UTF_16 : constant := 2;
Expanding_From_Wide_Wide_String_To_UTF_32 : constant := 1;
Expanding_From_UTF_8_To_String : constant := 1;
Expanding_From_UTF_8_To_Wide_String : constant := 1;
Expanding_From_UTF_8_To_Wide_Wide_String : constant := 1;
Expanding_From_UTF_16_To_String : constant := 3;
Expanding_From_UTF_16_To_Wide_String : constant := 1;
Expanding_From_UTF_16_To_Wide_Wide_String : constant := 1;
Expanding_From_UTF_32_To_String : constant := 6;
Expanding_From_UTF_32_To_Wide_String : constant := 2;
Expanding_From_UTF_32_To_Wide_Wide_String : constant := 1;
private
function To_Wide_String (
Item : String;
Substitute : Wide_String := " ")
return Wide_String
renames System.UTF_Conversions.From_8_To_16.Convert;
function To_Wide_Wide_String (
Item : String;
Substitute : Wide_Wide_String := " ")
return Wide_Wide_String
renames System.UTF_Conversions.From_8_To_32.Convert;
function To_Wide_Wide_String (
Item : Wide_String;
Substitute : Wide_Wide_String := " ")
return Wide_Wide_String
renames System.UTF_Conversions.From_16_To_32.Convert;
function To_String (
Item : Wide_String;
Substitute : String)
return String
renames System.UTF_Conversions.From_16_To_8.Convert;
function To_String (
Item : Wide_Wide_String;
Substitute : String)
return String
renames System.UTF_Conversions.From_32_To_8.Convert;
function To_Wide_String (
Item : Wide_Wide_String;
Substitute : Wide_String)
return Wide_String
renames System.UTF_Conversions.From_32_To_16.Convert;
end Ada.Characters.Conversions;
|
pragma License (Unrestricted);
-- implementation unit required by compiler
with System.Packed_Arrays;
package System.Compare_Array_Unsigned_8 is
pragma Preelaborate;
-- It can not be Pure, subprograms would become __attribute__((const)).
type Unsigned_8 is mod 2 ** 8;
for Unsigned_8'Size use 8;
package Ordering is new Packed_Arrays.Ordering (Unsigned_8);
-- required to compare arrays by compiler (s-carun8.ads)
function Compare_Array_U8_Unaligned (
Left : Address;
Right : Address;
Left_Len : Natural;
Right_Len : Natural)
return Integer
renames Ordering.Compare;
-- required to compare arrays by compiler (s-carun8.ads)
function Compare_Array_U8 (
Left : Address;
Right : Address;
Left_Len : Natural;
Right_Len : Natural)
return Integer
renames Ordering.Compare;
end System.Compare_Array_Unsigned_8;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
-- Autogenerated by Generate, do not edit
package GL.API.UInts is
pragma Preelaborate;
Uniform1 : T51;
Uniform1v : T52;
Uniform2 : T53;
Uniform2v : T54;
Uniform3 : T55;
Uniform3v : T56;
Uniform4 : T57;
Uniform4v : T58;
Uniform_Matrix2 : T59;
Uniform_Matrix3 : T60;
Uniform_Matrix4 : T61;
Vertex_Attrib1 : T62;
Vertex_Attrib2 : T63;
Vertex_Attrib2v : T64;
Vertex_Attrib3 : T65;
Vertex_Attrib3v : T66;
Vertex_Attrib4 : T67;
Vertex_Attrib4v : T68;
end GL.API.UInts;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . S T A N D A R D _ L I B R A R Y --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2013, 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. --
-- --
------------------------------------------------------------------------------
pragma Compiler_Unit_Warning;
-- The purpose of this body is simply to ensure that the two with'ed units
-- are properly included in the link. They are not with'ed from the spec
-- of System.Standard_Library, since this would cause order of elaboration
-- problems (Elaborate_Body would have the same problem).
pragma Polling (Off);
-- We must turn polling off for this unit, because otherwise we get
-- elaboration circularities with Ada.Exceptions if polling is on.
pragma Warnings (Off);
-- Kill warnings from unused withs. These unused with's are here to make
-- sure the relevant units are loaded and properly elaborated.
with System.Soft_Links;
-- Referenced directly from generated code using external symbols so it
-- must always be present in a build, even if no unit has a direct with
-- of this unit. Also referenced from exception handling routines.
-- This is needed for programs that don't use exceptions explicitly but
-- direct calls to Ada.Exceptions are generated by gigi (for example,
-- by calling __gnat_raise_constraint_error directly).
with System.Memory;
-- Referenced directly from generated code using external symbols, so it
-- must always be present in a build, even if no unit has a direct with
-- of this unit.
pragma Warnings (On);
package body System.Standard_Library is
Runtime_Finalized : Boolean := False;
-- Set to True when adafinal is called. Used to ensure that subsequent
-- calls to adafinal after the first have no effect.
--------------------------
-- Abort_Undefer_Direct --
--------------------------
procedure Abort_Undefer_Direct is
begin
System.Soft_Links.Abort_Undefer.all;
end Abort_Undefer_Direct;
--------------
-- Adafinal --
--------------
procedure Adafinal is
begin
if not Runtime_Finalized then
Runtime_Finalized := True;
System.Soft_Links.Adafinal.all;
end if;
end Adafinal;
-----------------
-- Break_Start --
-----------------
procedure Break_Start;
pragma Export (C, Break_Start, "__gnat_break_start");
-- This is a dummy procedure that is called at the start of execution.
-- Its sole purpose is to provide a well defined point for the placement
-- of a main program breakpoint. This is not used anymore but kept for
-- bootstrapping issues (still referenced by old gnatbind generated files).
procedure Break_Start is
begin
null;
end Break_Start;
end System.Standard_Library;
|
with Ada.Text_Io, Datos;
with Crear_Lista_Vacia, Esc, Ins, Interseccion;
use Datos;
use Ada.Text_Io;
procedure Prueba_Interseccion is
Lis1, Lis2 : Lista; -- variables del programa principal
procedure Pedir_Return is
begin
Put_Line("pulsa return para continuar ");
Skip_Line;
end Pedir_Return;
begin -- programa principal
-- Casos de prueba:
-- 1. Dos listas vacias.
-- 2. Una lista vacia y la otra no.
-- 3. Listas de un solo elemento que es comun.
-- 4. Listas de un solo elemento que es distinto.
-- 5. Listas de varios elementos.
-- 5.1. Listas de varios elementos. Elementos comunes
-- 5.2. Listas de varios elementos. Elementos disjuntos
Put_Line("Programa de prueba: ");
Put_Line("*********");
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Put_Line("Caso de prueba 1: Listas vacias ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista vacia: ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Ins(Lis1, 3);
Ins(Lis1, 5);
Put_Line("Caso de prueba 2: Una lista vacia y la otra no. ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista vacia: ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Ins(Lis1, 3);
Ins(Lis2, 3);
Put_Line("Caso de prueba 3: Listas de un solo elemento que es comun. ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista <3> ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Ins(Lis1, 3);
Ins(Lis2, 5);
Put_Line("Caso de prueba 4: Listas de un solo elemento que es distinto. ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista <> ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Ins(Lis1, 3);
Ins(Lis1, 5);
Ins(Lis1, 7);
Ins(Lis1, 9);
Ins(Lis2, 5);
Ins(Lis2, 9);
Put_Line("Caso de prueba 5.1: Listas de varios elementos. Elementos comunes. ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista <9, 5> ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Crear_Lista_Vacia(Lis1);
Crear_Lista_Vacia(Lis2);
Ins(Lis1, 3);
Ins(Lis1, 5);
Ins(Lis1, 7);
Ins(Lis1, 9);
Ins(Lis2, 11);
Ins(Lis2, 13);
Put_Line("Caso de prueba 5.2: Listas de varios elementos. Elementos disjuntos. ");
Put_Line("Las listas iniciales contienen ");
Esc(Lis1);
Esc(Lis2);
Put_Line("Ahora deberia escribir la lista <> ");
Esc(Interseccion(Lis1, Lis2));
New_Line;
New_Line;
Pedir_Return;
Put_Line("Se acabo la prueba. Agur ");
end Prueba_Interseccion;
|
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO;
procedure Scaffolding is
package Try is new Ada.Numerics.Discrete_Random (Boolean);
use Try;
Dice : Generator;
Level : Integer := 0;
function Step return Boolean is
begin
if Random (Dice) then
Level := Level + 1;
Ada.Text_IO.Put_Line ("Climbed up to" & Integer'Image (Level));
return True;
else
Level := Level - 1;
Ada.Text_IO.Put_Line ("Fell down to" & Integer'Image (Level));
return False;
end if;
end Step;
procedure Step_Up is
begin
while not Step loop
Step_Up;
end loop;
end Step_Up;
begin
Reset (Dice);
Step_Up;
end Scaffolding;
|
with Ada.Exception_Identification.From_Here;
with System.Debug; -- assertions
with C.winbase;
with C.windef;
with C.winerror;
package body System.Synchronous_Objects is
use Ada.Exception_Identification.From_Here;
use type C.windef.DWORD;
use type C.windef.WINBOOL;
function atomic_load (
ptr : not null access constant Counter;
memorder : Integer := C.ATOMIC_ACQUIRE)
return Counter
with Import, Convention => Intrinsic, External_Name => "__atomic_load_4";
procedure atomic_store (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_RELEASE)
with Import,
Convention => Intrinsic, External_Name => "__atomic_store_4";
procedure atomic_add_fetch (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_ACQ_REL)
with Import,
Convention => Intrinsic, External_Name => "__atomic_add_fetch_4";
function atomic_sub_fetch (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_ACQ_REL)
return Counter
with Import,
Convention => Intrinsic, External_Name => "__atomic_sub_fetch_4";
function atomic_compare_exchange (
ptr : not null access Counter;
expected : not null access Counter;
desired : Counter;
weak : Boolean := False;
success_memorder : Integer := C.ATOMIC_ACQ_REL;
failure_memorder : Integer := C.ATOMIC_ACQUIRE)
return Boolean
with Import,
Convention => Intrinsic,
External_Name => "__atomic_compare_exchange_4";
-- mutex
procedure Initialize (Object : in out Mutex) is
begin
Object.Handle := C.winbase.CreateMutex (null, 0, null);
pragma Check (Debug,
Check =>
Address (Object.Handle) /= Null_Address
or else Debug.Runtime_Error ("CreateMutex failed"));
end Initialize;
procedure Finalize (Object : in out Mutex) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.CloseHandle (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("CloseHandle failed"));
end Finalize;
procedure Enter (Object : in out Mutex) is
begin
if C.winbase.WaitForSingleObject (Object.Handle, C.winbase.INFINITE) /=
C.winbase.WAIT_OBJECT_0
then
Raise_Exception (Tasking_Error'Identity);
end if;
end Enter;
procedure Leave (Object : in out Mutex) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.ReleaseMutex (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("ReleaseMutex failed"));
end Leave;
-- condition variable
procedure Initialize (Object : in out Condition_Variable) is
begin
atomic_store (Object.Waiters'Access, 0);
Initialize (Object.Event, Manual => True);
Initialize (Object.Reset_Barrier, Manual => True);
end Initialize;
procedure Finalize (Object : in out Condition_Variable) is
begin
Finalize (Object.Event);
Finalize (Object.Reset_Barrier);
end Finalize;
procedure Notify_All (Object : in out Condition_Variable) is
begin
Reset (Object.Reset_Barrier);
Set (Object.Event);
end Notify_All;
procedure Wait (
Object : in out Condition_Variable;
Mutex : in out Synchronous_Objects.Mutex)
is
Signaled : C.windef.DWORD;
begin
atomic_add_fetch (Object.Waiters'Access, 1);
Signaled :=
C.winbase.SignalObjectAndWait (
hObjectToSignal => Mutex.Handle,
hObjectToWaitOn => Object.Event.Handle,
dwMilliseconds => C.winbase.INFINITE,
bAlertable => 0);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Debug.Runtime_Error ("SignalObjectAndWait failed"));
if atomic_sub_fetch (Object.Waiters'Access, 1) = 0 then
Reset (Object.Event);
Set (Object.Reset_Barrier);
else
Wait (Object.Reset_Barrier);
end if;
Enter (Mutex);
end Wait;
-- queue
procedure Initialize (
Object : in out Queue;
Mutex : not null Mutex_Access) is
begin
Object.Mutex := Mutex;
Initialize (Object.Event, Manual => False);
Object.Head := null;
Object.Tail := null;
Object.Filter := null;
Object.Waiting := False;
Object.Canceled := False;
end Initialize;
procedure Finalize (Object : in out Queue) is
begin
Finalize (Object.Event);
end Finalize;
function Count (
Object : Queue;
Params : Address;
Filter : Queue_Filter)
return Natural
is
Result : Natural;
begin
Enter (Object.Mutex.all);
Result := Unsynchronized_Count (Object, Params, Filter);
Leave (Object.Mutex.all);
return Result;
end Count;
function Unsynchronized_Count (
Object : Queue;
Params : Address;
Filter : Queue_Filter)
return Natural
is
Result : Natural := 0;
I : Queue_Node_Access := Object.Head;
begin
while I /= null loop
if Filter = null or else Filter (I, Params) then
Result := Result + 1;
end if;
I := I.Next;
end loop;
return Result;
end Unsynchronized_Count;
function Canceled (Object : Queue) return Boolean is
begin
return Object.Canceled;
end Canceled;
procedure Cancel (
Object : in out Queue;
Cancel_Node : access procedure (X : in out Queue_Node_Access)) is
begin
Enter (Object.Mutex.all);
Object.Canceled := True;
if Cancel_Node /= null then
while Object.Head /= null loop
declare
Next : constant Queue_Node_Access := Object.Head.Next;
begin
Cancel_Node (Object.Head);
Object.Head := Next;
end;
end loop;
end if;
Leave (Object.Mutex.all);
end Cancel;
procedure Unsynchronized_Prepend (
Object : in out Queue;
Item : not null Queue_Node_Access;
Canceled : out Boolean) is
begin
Canceled := Object.Canceled;
if not Canceled then
Item.Next := Object.Head;
Object.Head := Item;
if Object.Tail = null then
Object.Tail := Item;
end if;
Notify_All (Object, Item);
end if;
end Unsynchronized_Prepend;
procedure Add (
Object : in out Queue;
Item : not null Queue_Node_Access;
Canceled : out Boolean) is
begin
Enter (Object.Mutex.all);
Canceled := Object.Canceled;
if not Canceled then
if Object.Head = null then
Object.Head := Item;
else
Object.Tail.Next := Item;
end if;
Object.Tail := Item;
Item.Next := null;
Notify_All (Object, Item);
end if;
Leave (Object.Mutex.all);
end Add;
procedure Take (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter) is
begin
Enter (Object.Mutex.all);
Unsynchronized_Take (Object, Item, Params, Filter);
Leave (Object.Mutex.all);
end Take;
procedure Unsynchronized_Take (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter)
is
Previous : Queue_Node_Access := null;
I : Queue_Node_Access := Object.Head;
begin
Take_No_Sync (Object, Item, Params, Filter, Previous, I);
end Unsynchronized_Take;
procedure Take_No_Sync (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter;
Previous : in out Queue_Node_Access;
Current : in out Queue_Node_Access) is
begin
Item := null;
Search : while Current /= null loop
if Filter = null or else Filter (Current, Params) then
if Previous /= null then
Previous.Next := Current.Next;
else
Object.Head := Current.Next;
end if;
if Current = Object.Tail then
Object.Tail := Previous;
end if;
Item := Current;
exit Search;
end if;
Previous := Current;
Current := Current.Next;
end loop Search;
end Take_No_Sync;
procedure Notify_All (
Object : in out Queue;
Item : not null Queue_Node_Access) is
begin
if Object.Waiting
and then (
Object.Filter = null or else Object.Filter (Item, Object.Params))
then
Set (Object.Event);
end if;
end Notify_All;
-- event
procedure Initialize (Object : in out Event; Manual : Boolean := True) is
begin
Object.Handle :=
C.winbase.CreateEvent (null, Boolean'Pos (Manual), 0, null);
end Initialize;
procedure Finalize (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.CloseHandle (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("CloseHandle failed"));
end Finalize;
function Get (Object : Event) return Boolean is
Signaled : C.windef.DWORD;
begin
Signaled := C.winbase.WaitForSingleObject (Object.Handle, 0);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Signaled = C.winerror.WAIT_TIMEOUT
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
return Signaled = C.winbase.WAIT_OBJECT_0;
end Get;
procedure Set (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.SetEvent (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("SetEvent failed"));
end Set;
procedure Reset (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.ResetEvent (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("ResetEvent failed"));
end Reset;
procedure Wait (
Object : in out Event)
is
Signaled : C.windef.DWORD;
begin
Signaled :=
C.winbase.WaitForSingleObject (Object.Handle, C.winbase.INFINITE);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
end Wait;
procedure Wait (
Object : in out Event;
Timeout : Duration;
Value : out Boolean)
is
Milliseconds : constant C.windef.DWORD :=
C.windef.DWORD (Duration'Max (0.0, Timeout) * 1_000);
Signaled : C.windef.DWORD;
begin
Signaled := C.winbase.WaitForSingleObject (Object.Handle, Milliseconds);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Signaled = C.winerror.WAIT_TIMEOUT
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
Value := Signaled = C.winbase.WAIT_OBJECT_0;
end Wait;
function Handle (Object : Event) return C.winnt.HANDLE is
begin
return Object.Handle;
end Handle;
-- multi-read/exclusive-write lock for protected
procedure Initialize (Object : in out RW_Lock) is
begin
atomic_store (Object.State'Access, 0);
Initialize (Object.Reader_Barrier, Manual => True);
Initialize (Object.Writer_Barrier, Manual => False);
end Initialize;
procedure Finalize (Object : in out RW_Lock) is
begin
Finalize (Object.Reader_Barrier);
Finalize (Object.Writer_Barrier);
end Finalize;
procedure Enter_Reading (Object : in out RW_Lock) is
begin
loop
declare
Current : constant Counter := atomic_load (Object.State'Access);
begin
if Current >= 0 then
declare
Expected : aliased Counter := Current;
begin
exit when atomic_compare_exchange (
Object.State'Access,
Expected'Access,
Current + 1);
end;
else
Wait (Object.Reader_Barrier);
end if;
end;
end loop;
end Enter_Reading;
procedure Enter_Writing (Object : in out RW_Lock) is
begin
loop
declare
Expected : aliased Counter := 0;
begin
exit when atomic_compare_exchange (
Object.State'Access,
Expected'Access,
-999);
end;
Wait (Object.Writer_Barrier);
end loop;
Reset (Object.Reader_Barrier);
end Enter_Writing;
procedure Leave (Object : in out RW_Lock) is
Expected : aliased Counter := -999;
begin
if atomic_compare_exchange (Object.State'Access, Expected'Access, 0) then
-- writer
Set (Object.Reader_Barrier);
Set (Object.Writer_Barrier);
else
-- reader
if atomic_sub_fetch (Object.State'Access, 1) = 0 then
Reset (Object.Reader_Barrier);
Set (Object.Writer_Barrier);
end if;
end if;
end Leave;
end System.Synchronous_Objects;
|
--
-- Copyright (C) 2015-2016 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; version 2 of the License.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with System;
with Musinfo;
with Muschedinfo;
package body HW.Time.Timer
with Refined_State => (Timer_State => null,
Abstract_Time => (Sinfo, Sched_Info))
is
Sinfo_Base_Address : constant := 16#000e_0000_0000#;
Sinfo_Page_Size : constant
:= ((Musinfo.Subject_Info_Type_Size + (16#1000# - 1))
/ 16#1000#) * 16#1000#;
Sinfo : Musinfo.Subject_Info_Type
with
Address => System'To_Address (Sinfo_Base_Address);
Sched_Info : Muschedinfo.Scheduling_Info_Type
with
Volatile,
Async_Writers,
Address => System'To_Address (Sinfo_Base_Address + Sinfo_Page_Size);
function Raw_Value_Min return T
is
TSC_Schedule_Start : constant Interfaces.Unsigned_64
:= Sched_Info.TSC_Schedule_Start;
begin
return T (TSC_Schedule_Start);
end Raw_Value_Min;
function Raw_Value_Max return T
is
TSC_Schedule_End : constant Interfaces.Unsigned_64
:= Sched_Info.TSC_Schedule_End;
begin
return T (TSC_Schedule_End);
end Raw_Value_Max;
function Hz return T is
begin
return T (Sinfo.TSC_Khz) * 1000;
end Hz;
end HW.Time.Timer;
|
with Vect9_Pkg; use Vect9_Pkg;
package Vect9 is
type Rec is record
Data : Vector_Access;
end record;
procedure Proc
(This : in Rec;
CV : in Unit_Vector;
Data : in out Unit_Vector);
end Vect9;
|
------------------------------------------------------------------------------
-- --
-- Ada User Repository Annex (AURA) --
-- ANNEXI-STRAYLINE Reference Implementation --
-- --
-- Command Line Interface --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2020-2021, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Richard Wai (ANNEXI-STRAYLINE) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- --
-- * Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A --
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with Ada.Assertions;
with Ada.Streams.Stream_IO;
with Registrar.Registration;
with Stream_Hashing.Collective;
separate (Build)
package body Hash_Compilation_Orders is
use Registrar.Library_Units;
-----------
-- Image --
-----------
function Image (Order: Hash_Compilation_Order) return String is
("[Hash_Compilation_Order] (Build)" & New_Line
& " Target unit: " & Order.Target.Name.To_UTF8_String);
-------------
-- Execute --
-------------
procedure Execute (Order: in out Hash_Compilation_Order) is
use Stream_Hashing.Collective;
Collection: Hash_Collections.Set;
procedure Include_Hash (Path: in String) is
use Ada.Streams.Stream_IO;
File: File_Type;
begin
Open (File => File,
Mode => In_File,
Name => Path);
Collection.Include (Stream_Hashing.Digest_Stream (Stream (File)));
Close (File);
end Include_Hash;
Object_Path: constant String := Object_File_Name (Order.Target);
ALI_Path : constant String := ALI_File_Name (Order.Target);
Have_Object: constant Boolean := Ada.Directories.Exists (Object_Path);
Have_ALI : constant Boolean := Ada.Directories.Exists (ALI_Path);
begin
pragma Assert (Order.Target.Kind not in Unknown | Subunit
and then Order.Target.State in Available | Compiled);
-- Don't waste time if we have no object or ALI!
if (not Have_Object) and (not Have_ALI) then return; end if;
-- For units that are not External_Units, we expect to have an ".ali".
-- file as well as .o file. It is all or nothing. If we don't find both,
-- then we want to delete the ones we do have.
--
-- For subsystems checked-out from "System" repository, Object_Path will
-- return a path to the library shared object.
--
-- Otherwise, we expect that an External Unit will not have an ALI file
if Order.Target.Kind = External_Unit then
Ada.Assertions.Assert
(Check => not Have_ALI,
Message => "External_Units should not have .ali files.");
elsif Have_Object xor Have_ALI then
if Have_Object then
Ada.Directories.Delete_File (Object_Path);
else
Ada.Directories.Delete_File (ALI_Path);
end if;
return;
end if;
if Have_Object then Include_Hash (Object_Path); end if;
if Have_ALI then Include_Hash (ALI_Path); end if;
Compute_Collective_Hash
(Collection => Collection,
Collective_Hash => Order.Target.Compilation_Hash);
Order.Target.State := Compiled;
-- If we got this far, it definately means the unit was compiled, so
-- we can promote that unit to being such
Registrar.Registration.Update_Library_Unit (Order.Target);
end Execute;
end Hash_Compilation_Orders;
|
with Numerics, Numerics.Sparse_Matrices, Numerics.Sparse_Matrices.CSparse;
use Numerics, Numerics.Sparse_Matrices, Numerics.Sparse_Matrices.CSparse;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Containers; use Ada.Containers;
procedure Linear_Solver_Test is
use Real_IO, Int_IO, Real_Functions;
Mat : Sparse_Matrix;
LU : LU_Type;
SX : Sparse_Vector;
SB : Sparse_Vector;
SY : Sparse_Vector;
Y : Sparse_Vector;
Dir : String := "matrices/sparse-triplet/zero-based/";
Res : Real;
begin
Put ("Read Matrix . . .");
------ Rectangular Matrices -----------------
-- Mat := Read_Sparse_Triplet (Dir & "ash219_st.txt"); -- 3.6K
-- Mat := Transpose (Mat) * Mat;
------ Square Matrices ----------------------
-- Mat := Read_Sparse_Triplet (Dir & "a5by5_st.txt"); -- 611
-- Mat := Read_Sparse_Triplet (Dir & "bcsstk01_st.txt"); -- 4.9K
Mat := Read_Sparse_Triplet (Dir & "bcsstk16_st.txt"); -- 3.7M
-- Mat := Read_Sparse_Triplet (Dir & "fs_183_1_st.txt"); -- 24K
-- Mat := Read_Sparse_Triplet (Dir & "kershaw_st.txt"); -- 564
-- Mat := Read_Sparse_Triplet (Dir & "t1_st.txt"); -- 80
-- Mat := Read_Sparse_Triplet (Dir & "west0067_st.txt"); -- 3.9K
Put_Line ("finished");
----- Print matrix' info --------------
Put ("Size of matrix: ");
Put (N_Row (Mat), 0); Put (" x "); Put (N_Col (Mat), 0); New_Line;
Put ("Number of entries: "); Put (Number_Of_Elements (Mat), 0); New_Line;
----- Set size of vectors X and B ----
Set_Length (SB, N_Col (Mat)); Set_Length (SX, N_Col (Mat));
----- Begin LU Decomposition ---------
Put ("LU Decomposition . . .");
LU := LU_Decomposition (Mat);
Put_Line ("finished");
------ Begin tests ------------------------
Put_Line ("Begin testing . . .");
for K in 1 .. 10 loop
Put ("Trial "); Put (K, Width => 2); Put (": ");
for I in 1 .. N_Col (Mat) loop
Set (SB, I, (10.0 * Rand) ** 10 * Sin (10.0 * Rand));
end loop;
SX := Solve (LU, SB);
SY := SB - Mat * SX;
Y := SB - Mat * Solve (Mat, SB);
-- Res := Norm (SY - Y);
-- Res := Norm (Y) / Real'Max (1.0, Norm (SB));
-- Put (" Norm (Res) = "); Put (Res, Fore => 1, Aft => 1, Exp => 3);
-- Put_Line (if Res > 1.0e-10 then " ***" else "");
end loop;
Put_Line ("tests completed");
end loop;
---- Free memory allocated by LU : LU_Type -------
Free (LU);
end Linear_Solver_Test;
|
with Ada.Containers.Indefinite_Ordered_Maps;
with kv.avm.Capabilities;
with kv.avm.Control;
with kv.avm.Registers;
with kv.avm.Actor_References;
package kv.avm.Brokers is
type Broker_Type is new kv.avm.Capabilities.Capability_Interface with private;
overriding procedure Execute
(Self : in out Broker_Type;
Machine : in out kv.avm.Control.Control_Interface'CLASS;
Input : in kv.avm.Registers.Register_Type;
Output : out kv.avm.Registers.Register_Type;
Status : out kv.avm.Control.Status_Type);
procedure Add
(Self : in out Broker_Type;
Actor_Reference : in kv.avm.Actor_References.Actor_Reference_Type;
Name : in String);
procedure Delete
(Self : in out Broker_Type;
Name : in String);
function Is_Available
(Self : in Broker_Type;
Name : in String) return Boolean;
function Get
(Self : in Broker_Type;
Name : in String) return kv.avm.Actor_References.Actor_Reference_Type;
private
use kv.avm.Actor_References;
package Actor_Maps is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String,
Element_Type => kv.avm.Actor_References.Actor_Reference_Type);
type Broker_Type is new kv.avm.Capabilities.Capability_Interface with
record
Registrar : Actor_Maps.Map;
end record;
end kv.avm.Brokers;
|
-----------------------------------------------------------------------
-- util-commands-consoles -- Console interface
-- Copyright (C) 2014, 2015, 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 Ada.Strings.Unbounded;
generic
type Field_Type is (<>);
type Notice_Type is (<>);
package Util.Commands.Consoles is
type Justify_Type is (J_LEFT, -- Justify left |item |
J_RIGHT, -- Justify right | item|
J_CENTER, -- Justify center | item |
J_RIGHT_NO_FILL -- Justify right |item|
);
type Console_Type is abstract tagged limited private;
type Console_Access is access all Console_Type'Class;
-- Report an error message.
procedure Error (Console : in out Console_Type;
Message : in String) is abstract;
-- Report a notice message.
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String) is abstract;
-- Print the field value for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT) is abstract;
-- Print the title for the given field.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String) is abstract;
-- Start a new title in a report.
procedure Start_Title (Console : in out Console_Type) is abstract;
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type) is abstract;
-- Start a new row in a report.
procedure Start_Row (Console : in out Console_Type) is abstract;
-- Finish a new row in a report.
procedure End_Row (Console : in out Console_Type) is abstract;
-- Print the title for the given field and setup the associated field size.
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String;
Length : in Positive);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Integer;
Justify : in Justify_Type := J_LEFT);
-- Format the integer and print it for the given field.
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in Ada.Strings.Unbounded.Unbounded_String;
Justify : in Justify_Type := J_LEFT);
-- Get the field count that was setup through the Print_Title calls.
function Get_Field_Count (Console : in Console_Type) return Natural;
-- Reset the field count.
procedure Clear_Fields (Console : in out Console_Type);
private
type Field_Size_Array is array (Field_Type) of Natural;
type Field_List_Array is array (1 .. Field_Size_Array'Length) of Field_Type;
type Console_Type is abstract tagged limited record
Sizes : Field_Size_Array := (others => 0);
Cols : Field_Size_Array := (others => 1);
Fields : Field_List_Array;
Field_Count : Natural := 0;
end record;
end Util.Commands.Consoles;
|
with Es_Divisor;
function Suma_Divisores_Propios (N: Integer) return Integer is
Cont: Integer;
begin
Cont := 0;
for I in 1..N-1 loop
if Es_Divisor(I, N) then
Cont := Cont + I;
end if;
end loop;
return Cont;
end Suma_Divisores_Propios; |
with Ada.Directories; use Ada.Directories;
package body platform is
function get_ui_specification_filepath return string is
begin
return Current_Directory & "/../../../../../src/form/covidsim_form.ui";
end;
function get_covid_raw_data_filepath return string is
begin
return Current_Directory & "/../../../../../deps/xph_covid19/data/covid19.csv";
end;
end;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Buffers;
with GL.Types;
with Orka.Rendering.Drawing;
with Orka.Rendering.Programs.Modules;
package body Orka.Rendering.Debug.Coordinate_Axes is
function Create_Coordinate_Axes
(Location : Resources.Locations.Location_Ptr) return Coordinate_Axes
is
use Rendering.Programs;
begin
return Result : Coordinate_Axes :=
(Program => Create_Program (Modules.Create_Module
(Location, VS => "debug/axes.vert", FS => "debug/line.frag")),
others => <>)
do
Result.Uniform_Visible := Result.Program.Uniform ("visible");
Result.Uniform_View := Result.Program.Uniform ("view");
Result.Uniform_Proj := Result.Program.Uniform ("proj");
end return;
end Create_Coordinate_Axes;
procedure Render
(Object : in out Coordinate_Axes;
View, Proj : Transforms.Matrix4;
Transforms, Sizes : Rendering.Buffers.Bindable_Buffer'Class)
is
use all type GL.Types.Compare_Function;
use all type Rendering.Buffers.Indexed_Buffer_Target;
Reverse_Function : constant array (GL.Types.Compare_Function) of GL.Types.Compare_Function :=
(Never => Always,
Always => Never,
Less => GEqual,
Greater => LEqual,
LEqual => Greater,
GEqual => Less,
Equal => Not_Equal,
Not_Equal => Equal);
Original_Function : constant GL.Types.Compare_Function := GL.Buffers.Depth_Function;
Original_Mask : constant Boolean := GL.Buffers.Depth_Mask;
begin
Object.Uniform_View.Set_Matrix (View);
Object.Uniform_Proj.Set_Matrix (Proj);
Object.Program.Use_Program;
Transforms.Bind (Shader_Storage, 0);
Sizes.Bind (Shader_Storage, 1);
-- Visible part of axes
Object.Uniform_Visible.Set_Boolean (True);
Orka.Rendering.Drawing.Draw (GL.Types.Lines, 0, 6, Instances => Transforms.Length);
-- Hidden part of axes
GL.Buffers.Set_Depth_Function (Reverse_Function (Original_Function));
GL.Buffers.Set_Depth_Mask (Enabled => False);
Object.Uniform_Visible.Set_Boolean (False);
Orka.Rendering.Drawing.Draw (GL.Types.Lines, 0, 6, Instances => Transforms.Length);
GL.Buffers.Set_Depth_Function (Original_Function);
GL.Buffers.Set_Depth_Mask (Enabled => Original_Mask);
end Render;
end Orka.Rendering.Debug.Coordinate_Axes;
|
with System;
package Thin_Pointer1 is
type Stream is array (Integer range <>) of Character;
type Stream_Ptr is access Stream;
for Stream_Ptr'Size use Standard'Address_Size;
type Buf is record
A : System.Address;
end record;
type Buf_Wrapper is record
B : Buf;
end record;
type Buf_Ptr is access Buf_Wrapper;
procedure Set_Buffer (AD : Buf_Ptr; Buffer : Stream_ptr);
end Thin_Pointer1;
|
with
glx.Pointers;
package body openGL.Context -- TODO: Finish this package.
is
procedure define (Self : in out Item; Profile : in openGL.surface_Profile.item'Class)
is
pragma Unreferenced (Profile);
use GlX,
glx.Pointers;
begin
if Self.glx_Context = null
then
raise Program_Error with "No openGL context";
end if;
end define;
procedure make_Current (Self : in Item; read_Surface : in Surface.item;
write_Surface : in Surface.item)
is
pragma Unreferenced (write_Surface);
Success : glx.Bool with Unreferenced;
begin
null;
end make_Current;
function glx_Context_debug (Self : in Item'Class) return glx.Context.item
is
begin
return Self.glx_Context;
end glx_Context_debug;
end openGL.Context;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T V S N --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2006 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package spec exports version information for GNAT, GNATBIND and
-- GNATMAKE.
package Gnatvsn is
function Gnat_Version_String return String;
-- Version output when GNAT (compiler), or its related tools, including
-- GNATBIND, GNATCHOP, GNATFIND, GNATLINK, GNATMAKE, GNATXREF, are run
-- (with appropriate verbose option switch set).
Gnat_Static_Version_String : constant String := "GNU Ada";
-- Static string identifying this version, that can be used as an argument
-- to e.g. pragma Ident.
type Gnat_Build_Type is (FSF, Public, GAP);
-- See Get_Gnat_Build_Type below for the meaning of these values.
function Get_Gnat_Build_Type return Gnat_Build_Type;
-- This function returns one of the following values of Gnat_Build_Type:
--
-- FSF
-- GNAT FSF version. This version of GNAT is part of a Free Software
-- Foundation release of the GNU Compiler Collection (GCC). The binder
-- will not output informational messages regarding intended use,
-- and the bug box generated by Comperr will give information on
-- how to report bugs and list the "no warranty" information.
--
-- Public
-- GNAT Public version.
-- The binder will output informational messages, and the bug box
-- generated by the package Comperr will give appropriate bug
-- submission instructions.
--
-- GAP
-- GNAT Academic Program, similar to Public.
Ver_Len_Max : constant := 32;
-- Longest possible length for Gnat_Version_String in this or any
-- other version of GNAT. This is used by the binder to establish
-- space to store any possible version string value for checks. This
-- value should never be decreased in the future, but it would be
-- OK to increase it if absolutely necessary.
Library_Version : constant String := "4.2";
-- Library version. This value must be updated whenever any change to the
-- compiler affects the library formats in such a way as to obsolete
-- previously compiled library modules.
--
-- Note: Makefile.in relies on the precise format of the library version
-- string in order to correctly construct the soname value.
Verbose_Library_Version : constant String := "GNAT Lib v" & Library_Version;
-- Version string stored in e.g. ALI files.
ASIS_Version_Number : constant := 5;
-- ASIS Version. This is used to check for consistency between the compiler
-- used to generate trees, and an ASIS application that is reading the
-- trees. It must be updated (incremented) whenever a change is made to
-- the tree format that would result in a compiler being incompatible with
-- an older version of ASIS, or vice versa.
Current_Year : constant String := "2006";
-- Used in printing copyright messages
end Gnatvsn;
|
with OpenGL.Types;
with OpenGL.Thin;
package OpenGL.Matrix is
type Matrix_4x4f_t is new Types.Float_Arrays.Real_Matrix (1 .. 4, 1 .. 4);
type Matrix_4x4d_t is new Types.Double_Arrays.Real_Matrix (1 .. 4, 1 .. 4);
type Mode_t is (Texture, Modelview, Color, Projection);
-- proc_map : glMatrixMode
procedure Mode (Mode : in OpenGL.Matrix.Mode_t);
--
-- Load
--
-- proc_map : glLoadMatrixf
procedure Load (Matrix : in Matrix_4x4f_t);
-- proc_map : glLoadMatrixd
procedure Load (Matrix : in Matrix_4x4d_t);
--
-- Load_Identity
--
-- proc_map : glLoadIdentity
procedure Load_Identity
renames Thin.Load_Identity;
--
-- Multiply
--
-- proc_map : glMultMatrixf
procedure Multiply (Matrix : in Matrix_4x4f_t);
-- proc_map : glMultMatrixd
procedure Multiply (Matrix : in Matrix_4x4d_t);
--
-- Load_Transpose
--
-- proc_map : glLoadTransposeMatrixf
procedure Load_Transpose (Matrix : in Matrix_4x4f_t);
-- proc_map : glLoadTransposeMatrixd
procedure Load_Transpose (Matrix : in Matrix_4x4d_t);
--
-- Multiply_Transpose
--
-- proc_map : glMultTransposeMatrixf
procedure Multiply_Transpose (Matrix : in Matrix_4x4f_t);
-- proc_map : glMultTransposeMatrixd
procedure Multiply_Transpose (Matrix : in Matrix_4x4d_t);
--
-- Rotate
--
-- proc_map : glRotatef
procedure Rotate
(Angle : in OpenGL.Types.Float_t;
X : in OpenGL.Types.Float_t;
Y : in OpenGL.Types.Float_t;
Z : in OpenGL.Types.Float_t);
-- proc_map : glRotated
procedure Rotate
(Angle : in OpenGL.Types.Double_t;
X : in OpenGL.Types.Double_t;
Y : in OpenGL.Types.Double_t;
Z : in OpenGL.Types.Double_t);
--
-- Translate
--
-- proc_map : glTranslatef
procedure Translate
(X : in OpenGL.Types.Float_t;
Y : in OpenGL.Types.Float_t;
Z : in OpenGL.Types.Float_t);
-- proc_map : glTranslated
procedure Translate
(X : in OpenGL.Types.Double_t;
Y : in OpenGL.Types.Double_t;
Z : in OpenGL.Types.Double_t);
--
-- Scale
--
-- proc_map : glScalef
procedure Scale
(X : in OpenGL.Types.Float_t;
Y : in OpenGL.Types.Float_t;
Z : in OpenGL.Types.Float_t);
-- proc_map : glScaled
procedure Scale
(X : in OpenGL.Types.Double_t;
Y : in OpenGL.Types.Double_t;
Z : in OpenGL.Types.Double_t);
--
-- Frustum
--
subtype Near_Double_t is OpenGL.Types.Double_t
range 0.0 .. OpenGL.Types.Double_t'Last;
-- proc_map : glFrustum
procedure Frustum
(Left : in OpenGL.Types.Double_t;
Right : in OpenGL.Types.Double_t;
Bottom : in OpenGL.Types.Double_t;
Top : in OpenGL.Types.Double_t;
Near : in Near_Double_t;
Far : in OpenGL.Types.Double_t);
--
-- Ortho
--
-- proc_map : glOrtho
procedure Ortho
(Left : in OpenGL.Types.Double_t;
Right : in OpenGL.Types.Double_t;
Bottom : in OpenGL.Types.Double_t;
Top : in OpenGL.Types.Double_t;
Near : in OpenGL.Types.Double_t;
Far : in OpenGL.Types.Double_t);
--
-- Push
--
-- proc_map : glPushMatrix
procedure Push
renames Thin.Push_Matrix;
-- proc_map : glPopMatrix
procedure Pop
renames Thin.Pop_Matrix;
end OpenGL.Matrix;
|
with Bitmaps.RGB;
package ImageOps is
function Manhattan_Distance (A, B : in Bitmaps.RGB.Pixel) return Natural;
function Adj_Distance_Sum
(Source : in Bitmaps.RGB.Image) return Long_Integer;
procedure Noise (Target : in out Bitmaps.RGB.Image);
end ImageOps;
|
-- C85005E.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 A VARIABLE CREATED BY AN ALLOCATOR CAN BE RENAMED AND
-- HAS THE CORRECT VALUE, AND THAT THE NEW NAME CAN BE USED IN AN
-- ASSIGNMENT STATEMENT AND PASSED ON AS AN ACTUAL SUBPROGRAM OR
-- ENTRY 'IN OUT' OR 'OUT' PARAMETER, AND AS AN ACTUAL GENERIC
-- 'IN OUT' PARAMETER, AND THAT WHEN THE VALUE OF THE RENAMED
-- VARIABLE IS CHANGED, THE NEW VALUE IS REFLECTED BY THE VALUE OF
-- THE NEW NAME.
-- HISTORY:
-- JET 03/15/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C85005E IS
TYPE ARRAY1 IS ARRAY (POSITIVE RANGE <>) OF INTEGER;
TYPE RECORD1 (D : INTEGER) IS
RECORD
FIELD1 : INTEGER := 1;
END RECORD;
TYPE POINTER1 IS ACCESS INTEGER;
PACKAGE PACK1 IS
TYPE PACKACC IS ACCESS INTEGER;
AK1 : PACKACC := NEW INTEGER'(0);
TYPE PRIVY IS PRIVATE;
ZERO : CONSTANT PRIVY;
ONE : CONSTANT PRIVY;
TWO : CONSTANT PRIVY;
THREE : CONSTANT PRIVY;
FOUR : CONSTANT PRIVY;
FIVE : CONSTANT PRIVY;
FUNCTION IDENT (I : PRIVY) RETURN PRIVY;
FUNCTION NEXT (I : PRIVY) RETURN PRIVY;
PRIVATE
TYPE PRIVY IS RANGE 0..127;
ZERO : CONSTANT PRIVY := 0;
ONE : CONSTANT PRIVY := 1;
TWO : CONSTANT PRIVY := 2;
THREE : CONSTANT PRIVY := 3;
FOUR : CONSTANT PRIVY := 4;
FIVE : CONSTANT PRIVY := 5;
END PACK1;
TASK TYPE TASK1 IS
ENTRY ASSIGN (J : IN INTEGER);
ENTRY VALU (J : OUT INTEGER);
ENTRY NEXT;
ENTRY STOP;
END TASK1;
GENERIC
GI1 : IN OUT INTEGER;
GA1 : IN OUT ARRAY1;
GR1 : IN OUT RECORD1;
GP1 : IN OUT POINTER1;
GV1 : IN OUT PACK1.PRIVY;
GT1 : IN OUT TASK1;
GK1 : IN OUT INTEGER;
PACKAGE GENERIC1 IS
END GENERIC1;
FUNCTION IDENT (P : POINTER1) RETURN POINTER1 IS
BEGIN
IF EQUAL (3,3) THEN
RETURN P;
ELSE
RETURN NULL;
END IF;
END IDENT;
PACKAGE BODY PACK1 IS
FUNCTION IDENT (I : PRIVY) RETURN PRIVY IS
BEGIN
IF EQUAL(3,3) THEN
RETURN I;
ELSE
RETURN PRIVY'(0);
END IF;
END IDENT;
FUNCTION NEXT (I : PRIVY) RETURN PRIVY IS
BEGIN
RETURN I+1;
END NEXT;
END PACK1;
PACKAGE BODY GENERIC1 IS
BEGIN
GI1 := GI1 + 1;
GA1 := (GA1(1)+1, GA1(2)+1, GA1(3)+1);
GR1 := (D => 1, FIELD1 => GR1.FIELD1 + 1);
GP1 := NEW INTEGER'(GP1.ALL + 1);
GV1 := PACK1.NEXT(GV1);
GT1.NEXT;
GK1 := GK1 + 1;
END GENERIC1;
TASK BODY TASK1 IS
TASK_VALUE : INTEGER := 0;
ACCEPTING_ENTRIES : BOOLEAN := TRUE;
BEGIN
WHILE ACCEPTING_ENTRIES LOOP
SELECT
ACCEPT ASSIGN (J : IN INTEGER) DO
TASK_VALUE := J;
END ASSIGN;
OR
ACCEPT VALU (J : OUT INTEGER) DO
J := TASK_VALUE;
END VALU;
OR
ACCEPT NEXT DO
TASK_VALUE := TASK_VALUE + 1;
END NEXT;
OR
ACCEPT STOP DO
ACCEPTING_ENTRIES := FALSE;
END STOP;
END SELECT;
END LOOP;
END TASK1;
BEGIN
TEST ("C85005E", "CHECK THAT A VARIABLE CREATED BY AN ALLOCATOR " &
"CAN BE RENAMED AND HAS THE CORRECT VALUE, AND " &
"THAT THE NEW NAME CAN BE USED IN AN ASSIGNMENT" &
" STATEMENT AND PASSED ON AS AN ACTUAL " &
"SUBPROGRAM OR ENTRY 'IN OUT' OR 'OUT' " &
"PARAMETER, AND AS AN ACTUAL GENERIC 'IN OUT' " &
"PARAMETER, AND THAT WHEN THE VALUE OF THE " &
"RENAMED VARIABLE IS CHANGED, THE NEW VALUE " &
"IS REFLECTED BY THE VALUE OF THE NEW NAME");
DECLARE
TYPE ACCINT IS ACCESS INTEGER;
TYPE ACCARR IS ACCESS ARRAY1;
TYPE ACCREC IS ACCESS RECORD1;
TYPE ACCPTR IS ACCESS POINTER1;
TYPE ACCPVT IS ACCESS PACK1.PRIVY;
TYPE ACCTSK IS ACCESS TASK1;
AI1 : ACCINT := NEW INTEGER'(0);
AA1 : ACCARR := NEW ARRAY1'(0, 0, 0);
AR1 : ACCREC := NEW RECORD1'(D => 1, FIELD1 => 0);
AP1 : ACCPTR := NEW POINTER1'(NEW INTEGER'(0));
AV1 : ACCPVT := NEW PACK1.PRIVY'(PACK1.ZERO);
AT1 : ACCTSK := NEW TASK1;
XAI1 : INTEGER RENAMES AI1.ALL;
XAA1 : ARRAY1 RENAMES AA1.ALL;
XAR1 : RECORD1 RENAMES AR1.ALL;
XAP1 : POINTER1 RENAMES AP1.ALL;
XAV1 : PACK1.PRIVY RENAMES AV1.ALL;
XAK1 : INTEGER RENAMES PACK1.AK1.ALL;
XAT1 : TASK1 RENAMES AT1.ALL;
TASK TYPE TASK2 IS
ENTRY ENTRY1 (TI1 : OUT INTEGER; TA1 : OUT ARRAY1;
TR1 : OUT RECORD1; TP1 : IN OUT POINTER1;
TV1 : IN OUT PACK1.PRIVY;
TT1 : IN OUT TASK1; TK1 : IN OUT INTEGER);
END TASK2;
I : INTEGER;
A_CHK_TASK : TASK2;
PROCEDURE PROC1 (PI1 : IN OUT INTEGER; PA1 : IN OUT ARRAY1;
PR1 : IN OUT RECORD1; PP1 : OUT POINTER1;
PV1 : OUT PACK1.PRIVY; PT1 : IN OUT TASK1;
PK1 : OUT INTEGER) IS
BEGIN
PI1 := PI1 + 1;
PA1 := (PA1(1)+1, PA1(2)+1, PA1(3)+1);
PR1 := (D => 1, FIELD1 => PR1.FIELD1 + 1);
PP1 := NEW INTEGER'(AP1.ALL.ALL + 1);
PV1 := PACK1.NEXT(AV1.ALL);
PT1.NEXT;
PK1 := PACK1.AK1.ALL + 1;
END PROC1;
TASK BODY TASK2 IS
BEGIN
ACCEPT ENTRY1 (TI1 : OUT INTEGER; TA1 : OUT ARRAY1;
TR1 : OUT RECORD1; TP1 : IN OUT POINTER1;
TV1 : IN OUT PACK1.PRIVY;
TT1 : IN OUT TASK1;
TK1 : IN OUT INTEGER) DO
TI1 := AI1.ALL + 1;
TA1 := (AA1.ALL(1)+1, AA1.ALL(2)+1, AA1.ALL(3)+1);
TR1 := (D => 1, FIELD1 => AR1.ALL.FIELD1 + 1);
TP1 := NEW INTEGER'(TP1.ALL + 1);
TV1 := PACK1.NEXT(TV1);
TT1.NEXT;
TK1 := TK1 + 1;
END ENTRY1;
END TASK2;
PACKAGE GENPACK2 IS NEW
GENERIC1 (XAI1, XAA1, XAR1, XAP1, XAV1, XAT1, XAK1);
BEGIN
IF XAI1 /= IDENT_INT(1) THEN
FAILED ("INCORRECT VALUE OF XAI1 (1)");
END IF;
IF XAA1 /= (IDENT_INT(1),IDENT_INT(1),IDENT_INT(1)) THEN
FAILED ("INCORRECT VALUE OF XAA1 (1)");
END IF;
IF XAR1 /= (D => 1, FIELD1 => IDENT_INT(1)) THEN
FAILED ("INCORRECT VALUE OF XAR1 (1)");
END IF;
IF XAP1 /= IDENT(AP1.ALL) OR XAP1.ALL /= IDENT_INT(1) THEN
FAILED ("INCORRECT VALUE OF XAP1 (1)");
END IF;
IF PACK1."/=" (XAV1, PACK1.IDENT(PACK1.ONE)) THEN
FAILED ("INCORRECT VALUE OF XAV1 (1)");
END IF;
XAT1.VALU(I);
IF I /= IDENT_INT(1) THEN
FAILED ("INCORRECT RETURN VALUE OF XAT1.VALU (1)");
END IF;
IF XAK1 /= IDENT_INT(1) THEN
FAILED ("INCORRECT VALUE OF XAK1 (1)");
END IF;
PROC1(XAI1, XAA1, XAR1, XAP1, XAV1, XAT1, XAK1);
IF XAI1 /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE OF XAI1 (2)");
END IF;
IF XAA1 /= (IDENT_INT(2),IDENT_INT(2),IDENT_INT(2)) THEN
FAILED ("INCORRECT VALUE OF XAA1 (2)");
END IF;
IF XAR1 /= (D => 1, FIELD1 => IDENT_INT(2)) THEN
FAILED ("INCORRECT VALUE OF XAR1 (2)");
END IF;
IF XAP1 /= IDENT(AP1.ALL) OR XAP1.ALL /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE OF XAP1 (2)");
END IF;
IF PACK1."/=" (XAV1, PACK1.IDENT(PACK1.TWO)) THEN
FAILED ("INCORRECT VALUE OF XAV1 (2)");
END IF;
XAT1.VALU(I);
IF I /= IDENT_INT(2) THEN
FAILED ("INCORRECT RETURN VALUE OF XAT1.VALU (2)");
END IF;
IF XAK1 /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE OF XAK1 (2)");
END IF;
A_CHK_TASK.ENTRY1(XAI1, XAA1, XAR1, XAP1, XAV1, XAT1, XAK1);
IF XAI1 /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE OF XAI1 (3)");
END IF;
IF XAA1 /= (IDENT_INT(3),IDENT_INT(3),IDENT_INT(3)) THEN
FAILED ("INCORRECT VALUE OF XAA1 (3)");
END IF;
IF XAR1 /= (D => 1, FIELD1 => IDENT_INT(3)) THEN
FAILED ("INCORRECT VALUE OF XAR1 (3)");
END IF;
IF XAP1 /= IDENT(AP1.ALL) OR XAP1.ALL /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE OF XAP1 (3)");
END IF;
IF PACK1."/=" (XAV1, PACK1.IDENT(PACK1.THREE)) THEN
FAILED ("INCORRECT VALUE OF XAV1 (3)");
END IF;
XAT1.VALU(I);
IF I /= IDENT_INT(3) THEN
FAILED ("INCORRECT RETURN VALUE OF XAT1.VALU (3)");
END IF;
IF XAK1 /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE OF XAK1 (3)");
END IF;
XAI1 := XAI1 + 1;
XAA1 := (XAA1(1)+1, XAA1(2)+1, XAA1(3)+1);
XAR1 := (D => 1, FIELD1 => XAR1.FIELD1 + 1);
XAP1 := NEW INTEGER'(XAP1.ALL + 1);
XAV1 := PACK1.NEXT(XAV1);
XAT1.NEXT;
XAK1 := XAK1 + 1;
IF XAI1 /= IDENT_INT(4) THEN
FAILED ("INCORRECT VALUE OF XAI1 (4)");
END IF;
IF XAA1 /= (IDENT_INT(4),IDENT_INT(4),IDENT_INT(4)) THEN
FAILED ("INCORRECT VALUE OF XAA1 (4)");
END IF;
IF XAR1 /= (D => 1, FIELD1 => IDENT_INT(4)) THEN
FAILED ("INCORRECT VALUE OF XAR1 (4)");
END IF;
IF XAP1 /= IDENT(AP1.ALL) OR XAP1.ALL /= IDENT_INT(4) THEN
FAILED ("INCORRECT VALUE OF XAP1 (4)");
END IF;
IF PACK1."/=" (XAV1, PACK1.IDENT(PACK1.FOUR)) THEN
FAILED ("INCORRECT VALUE OF XAV1 (4)");
END IF;
XAT1.VALU(I);
IF I /= IDENT_INT(4) THEN
FAILED ("INCORRECT RETURN VALUE OF XAT1.VALU (4)");
END IF;
IF XAK1 /= IDENT_INT(4) THEN
FAILED ("INCORRECT VALUE OF XAK1 (4)");
END IF;
AI1.ALL := AI1.ALL + 1;
AA1.ALL := (AA1.ALL(1)+1, AA1.ALL(2)+1, AA1.ALL(3)+1);
AR1.ALL := (D => 1, FIELD1 => AR1.ALL.FIELD1 + 1);
AP1.ALL := NEW INTEGER'(AP1.ALL.ALL + 1);
AV1.ALL := PACK1.NEXT(AV1.ALL);
AT1.NEXT;
PACK1.AK1.ALL := PACK1.AK1.ALL + 1;
IF XAI1 /= IDENT_INT(5) THEN
FAILED ("INCORRECT VALUE OF XAI1 (5)");
END IF;
IF XAA1 /= (IDENT_INT(5),IDENT_INT(5),IDENT_INT(5)) THEN
FAILED ("INCORRECT VALUE OF XAA1 (5)");
END IF;
IF XAR1 /= (D => 1, FIELD1 => IDENT_INT(5)) THEN
FAILED ("INCORRECT VALUE OF XAR1 (5)");
END IF;
IF XAP1 /= IDENT(AP1.ALL) OR XAP1.ALL /= IDENT_INT(5) THEN
FAILED ("INCORRECT VALUE OF XAP1 (5)");
END IF;
IF PACK1."/=" (XAV1, PACK1.IDENT(PACK1.FIVE)) THEN
FAILED ("INCORRECT VALUE OF XAV1 (5)");
END IF;
XAT1.VALU(I);
IF I /= IDENT_INT(5) THEN
FAILED ("INCORRECT RETURN VALUE OF XAT1.VALU (5)");
END IF;
IF XAK1 /= IDENT_INT(5) THEN
FAILED ("INCORRECT VALUE OF XAK1 (5)");
END IF;
AT1.STOP;
END;
RESULT;
END C85005E;
|
-- Miscellaneous types and functions.
package Util is
-- Type to represent a memory address.
type Address_Type is mod 2 ** 64;
-- Type to represent access time in cycles.
type Time_Type is new Long_Integer range 0 .. Long_Integer'Last;
-- Type to represent the cost of a memory subsystem.
type Cost_Type is new Long_Integer range 0 .. Long_Integer'Last;
-- Add two cost types (saturating addition).
function "+"(a, b : Cost_Type) return Cost_Type;
-- Compute the log base 2 of a Natural.
function Log2(n : Natural) return Natural;
-- Compute the log base 2 of a Long_Integer.
function Log2(n : Long_Integer) return Natural;
-- Round n to the next highest power of 2.
function Round_Power2(n : Natural) return Natural;
-- Convert an Integer to a string (without spaces).
function To_String(i : Integer) return String;
-- Convert a Long_Integer to a string (without spaces).
function To_String(i : Long_Integer) return String;
-- Convert a Long_Float to a string (without spaces).
function To_String(f : Long_Float) return String;
end Util;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- G N A T . T R A C E B A C K . S Y M B O L I C . M O D U L E _ N A M E --
-- --
-- B o d y --
-- --
-- Copyright (C) 2012-2020, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This is the GNU/Linux specific version of this package
with Interfaces.C; use Interfaces.C;
separate (System.Traceback.Symbolic)
package body Module_Name is
pragma Linker_Options ("-ldl");
function Is_Shared_Lib (Base : Address) return Boolean;
-- Returns True if a shared library
-- The principle is:
-- 1. We get information about the module containing the address.
-- 2. We check that the full pathname is pointing to a shared library.
-- 3. for shared libraries, we return the non relocated address (so
-- the absolute address in the shared library).
-- 4. we also return the full pathname of the module containing this
-- address.
-------------------
-- Is_Shared_Lib --
-------------------
function Is_Shared_Lib (Base : Address) return Boolean is
EI_NIDENT : constant := 16;
type u16 is mod 2 ** 16;
-- Just declare the needed header information, we just need to read the
-- type encoded in the second field.
type Elf32_Ehdr is record
e_ident : char_array (1 .. EI_NIDENT);
e_type : u16;
end record;
ET_DYN : constant := 3; -- A shared lib if e_type = ET_DYN
Header : Elf32_Ehdr;
pragma Import (Ada, Header);
-- Suppress initialization in Normalized_Scalars mode
for Header'Address use Base;
begin
return Header.e_type = ET_DYN;
exception
when others =>
return False;
end Is_Shared_Lib;
---------------------------------
-- Build_Cache_For_All_Modules --
---------------------------------
procedure Build_Cache_For_All_Modules is
type link_map;
type link_map_acc is access all link_map;
pragma Convention (C, link_map_acc);
type link_map is record
l_addr : Address;
-- Base address of the shared object
l_name : Address;
-- Null-terminated absolute file name
l_ld : Address;
-- Dynamic section
l_next, l_prev : link_map_acc;
-- Chain
end record;
pragma Convention (C, link_map);
type r_debug_type is record
r_version : Integer;
r_map : link_map_acc;
end record;
pragma Convention (C, r_debug_type);
r_debug : r_debug_type;
pragma Import (C, r_debug, "_r_debug");
lm : link_map_acc;
begin
lm := r_debug.r_map;
while lm /= null loop
if Big_String_Conv.To_Pointer (lm.l_name) (1) /= ASCII.NUL then
-- Discard non-file (like the executable itself or the gate).
Add_Module_To_Cache (Value (lm.l_name), lm.l_addr);
end if;
lm := lm.l_next;
end loop;
end Build_Cache_For_All_Modules;
---------
-- Get --
---------
function Get (Addr : System.Address;
Load_Addr : access System.Address)
return String
is
-- Dl_info record for Linux, used to get sym reloc offset
type Dl_info is record
dli_fname : System.Address;
dli_fbase : System.Address;
dli_sname : System.Address;
dli_saddr : System.Address;
end record;
function dladdr
(addr : System.Address;
info : not null access Dl_info) return int;
pragma Import (C, dladdr, "dladdr");
-- This is a Linux extension and not POSIX
info : aliased Dl_info;
begin
Load_Addr.all := System.Null_Address;
if dladdr (Addr, info'Access) /= 0 then
-- If we have a shared library we need to adjust the address to
-- be relative to the base address of the library.
if Is_Shared_Lib (info.dli_fbase) then
Load_Addr.all := info.dli_fbase;
end if;
return Value (info.dli_fname);
-- Not found, fallback to executable name
else
return "";
end if;
exception
when others =>
return "";
end Get;
------------------
-- Is_Supported --
------------------
function Is_Supported return Boolean is
begin
return True;
end Is_Supported;
end Module_Name;
|
------------------------------------------------------------------------------
-- Copyright (C) 2017-2020 by Heisenbug Ltd. (gh+saatana@heisenbug.eu)
--
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
------------------------------------------------------------------------------
pragma License (Unrestricted);
package body Saatana.Crypto is
--
-- "+"
--
function "+" (Left : in Nonce_Stream;
Right : in Nonce_Stream) return Nonce_Stream
is
procedure Add_Carry (Left : in out Byte;
Right : in Byte;
Carry : in out Boolean) with
Inline => True,
Depends => (Left => (Left,
Right,
Carry),
Carry => (Left,
Right)),
Post => (Left = Left'Old + Right + Boolean'Pos (Carry'Old) and then
Carry = (Left'Old + Right < Left'Old));
procedure Add_Carry (Left : in out Byte;
Right : in Byte;
Carry : in out Boolean)
is
Old_Carry : constant Boolean := Carry;
begin
Left := Left + Right;
Carry := Left < Right;
Left := Left + Boolean'Pos (Old_Carry);
end Add_Carry;
Result : Nonce_Stream := Left;
Carry : Boolean := False;
begin
for Result_Idx in Result'Range loop
Add_Byte_With_Carry :
declare
Operand_Idx : constant Stream_Index := Result_Idx - Result'First + Right'First;
begin
Add_Carry (Left => Result (Result_Idx),
Right => Right (Operand_Idx),
Carry => Carry);
end Add_Byte_With_Carry;
end loop;
return Result;
end "+";
end Saatana.Crypto;
|
-- PR ada/42253
-- Testcase by Duncan Sands <baldrick@gcc.gnu.org>
-- { dg-do run }
with Thin_Pointer2_Pkg; use Thin_Pointer2_Pkg;
procedure Thin_Pointer2 is
begin
if F /= '*' then
raise Program_Error;
end if;
end;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2014, 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 League.Strings.Hash;
package body League.Environment_Variables is
function To_Key (Item : League.Strings.Universal_String) return Key_Type;
-- Converts name of environment variable into key of hash table. Where
-- environment variables is case sensitive, it converts name into upper
-- case; otherwise do nothing.
---------
-- "=" --
---------
overriding function "="
(Left : Environment_Variable_Set;
Right : Environment_Variable_Set) return Boolean
is
use type Universal_String_Maps.Map;
begin
return Left.Data = Right.Data;
end "=";
-----------
-- Clear --
-----------
procedure Clear (Self : in out Environment_Variable_Set'Class) is
begin
Self.Data.Clear;
end Clear;
--------------
-- Contains --
--------------
function Contains
(Self : Environment_Variable_Set'Class;
Name : League.Strings.Universal_String) return Boolean
is
Key : constant Key_Type := To_Key (Name);
Position : constant Universal_String_Maps.Cursor := Self.Data.Find (Key);
begin
return Universal_String_Maps.Has_Element (Position);
end Contains;
----------
-- Hash --
----------
function Hash (Item : Key_Type) return Ada.Containers.Hash_Type is
begin
return League.Strings.Hash (League.Strings.Universal_String (Item));
end Hash;
------------
-- Insert --
------------
procedure Insert
(Self : in out Environment_Variable_Set'Class;
Name : League.Strings.Universal_String;
Value : League.Strings.Universal_String)
is
Key : constant Key_Type := To_Key (Name);
Position : constant Universal_String_Maps.Cursor := Self.Data.Find (Key);
begin
if Universal_String_Maps.Has_Element (Position) then
Self.Data.Replace_Element (Position, Value);
else
Self.Data.Insert (Key, Value);
end if;
end Insert;
------------
-- Remove --
------------
procedure Remove
(Self : in out Environment_Variable_Set'Class;
Name : League.Strings.Universal_String)
is
Key : constant Key_Type := To_Key (Name);
Position : Universal_String_Maps.Cursor := Self.Data.Find (Key);
begin
if Universal_String_Maps.Has_Element (Position) then
Self.Data.Delete (Position);
end if;
end Remove;
------------
-- To_Key --
------------
function To_Key
(Item : League.Strings.Universal_String) return Key_Type is separate;
-----------
-- Value --
-----------
function Value
(Self : Environment_Variable_Set'Class;
Name : League.Strings.Universal_String;
Default_Value : League.Strings.Universal_String
:= League.Strings.Empty_Universal_String)
return League.Strings.Universal_String
is
Key : constant Key_Type := To_Key (Name);
Position : constant Universal_String_Maps.Cursor := Self.Data.Find (Key);
begin
if Universal_String_Maps.Has_Element (Position) then
return Universal_String_Maps.Element (Position);
else
return Default_Value;
end if;
end Value;
end League.Environment_Variables;
|
with
gel.Sprite,
openGL.Visual,
ada.unchecked_Deallocation;
package body gel.Camera
is
--------
-- Forge
--
procedure free (Self : in out View)
is
procedure deallocate is new ada.unchecked_Deallocation (Item'Class, View);
begin
Self.destroy;
deallocate (Self);
end free;
--------------
-- Operations
--
procedure render (Self : in out Item; the_World : in gel.World.view;
To : in openGL.Surface.view)
is
all_Sprites : gel.World.sprite_transform_Pairs renames the_World.sprite_Transforms;
the_Visuals : openGL.Visual.views (1 .. all_Sprites'Length);
Count : Natural := 0;
the_Sprite : gel.Sprite.view;
begin
for i in all_Sprites'Range
loop
the_Sprite := all_Sprites (i).Sprite;
if not the_Sprite.is_Destroyed
and then the_Sprite.is_Visible
then
Count := Count + 1;
the_Visuals (Count) := the_Sprite.Visual;
the_Visuals (Count).Transform_is (all_Sprites (i).Transform);
the_Visuals (Count).Scale_is ((1.0, 1.0, 1.0));
the_Visuals (Count).program_Parameters_are (the_Sprite.program_Parameters);
end if;
end loop;
Self.render (the_Visuals (1 .. Count));
end render;
end gel.Camera;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ I M G V --
-- --
-- B o d y --
-- --
-- Copyright (C) 2001-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. 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 Casing; use Casing;
with Checks; use Checks;
with Einfo; use Einfo;
with Exp_Util; use Exp_Util;
with Lib; use Lib;
with Namet; use Namet;
with Nmake; use Nmake;
with Nlists; use Nlists;
with Opt; use Opt;
with Rtsfind; use Rtsfind;
with Sem_Aux; use Sem_Aux;
with Sem_Res; use Sem_Res;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Stand; use Stand;
with Stringt; use Stringt;
with Tbuild; use Tbuild;
with Ttypes; use Ttypes;
with Uintp; use Uintp;
with Urealp; use Urealp;
package body Exp_Imgv is
function Has_Decimal_Small (E : Entity_Id) return Boolean;
-- Applies to all entities. True for a Decimal_Fixed_Point_Type, or an
-- Ordinary_Fixed_Point_Type with a small that is a negative power of ten.
-- Shouldn't this be in einfo.adb or sem_aux.adb???
------------------------------------
-- Build_Enumeration_Image_Tables --
------------------------------------
procedure Build_Enumeration_Image_Tables (E : Entity_Id; N : Node_Id) is
Loc : constant Source_Ptr := Sloc (E);
Str : String_Id;
Ind : List_Id;
Lit : Entity_Id;
Nlit : Nat;
Len : Nat;
Estr : Entity_Id;
Eind : Entity_Id;
Ityp : Node_Id;
begin
-- Nothing to do for other than a root enumeration type
if E /= Root_Type (E) then
return;
-- Nothing to do if pragma Discard_Names applies
elsif Discard_Names (E) then
return;
end if;
-- Otherwise tables need constructing
Start_String;
Ind := New_List;
Lit := First_Literal (E);
Len := 1;
Nlit := 0;
loop
Append_To (Ind,
Make_Integer_Literal (Loc, UI_From_Int (Len)));
exit when No (Lit);
Nlit := Nlit + 1;
Get_Unqualified_Decoded_Name_String (Chars (Lit));
if Name_Buffer (1) /= ''' then
Set_Casing (All_Upper_Case);
end if;
Store_String_Chars (Name_Buffer (1 .. Name_Len));
Len := Len + Int (Name_Len);
Next_Literal (Lit);
end loop;
if Len < Int (2 ** (8 - 1)) then
Ityp := Standard_Integer_8;
elsif Len < Int (2 ** (16 - 1)) then
Ityp := Standard_Integer_16;
else
Ityp := Standard_Integer_32;
end if;
Str := End_String;
Estr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (E), 'S'));
Eind :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (E), 'N'));
Set_Lit_Strings (E, Estr);
Set_Lit_Indexes (E, Eind);
Insert_Actions (N,
New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Estr,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (Standard_String, Loc),
Expression =>
Make_String_Literal (Loc,
Strval => Str)),
Make_Object_Declaration (Loc,
Defining_Identifier => Eind,
Constant_Present => True,
Object_Definition =>
Make_Constrained_Array_Definition (Loc,
Discrete_Subtype_Definitions => New_List (
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 0),
High_Bound => Make_Integer_Literal (Loc, Nlit))),
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication => New_Occurrence_Of (Ityp, Loc))),
Expression =>
Make_Aggregate (Loc,
Expressions => Ind))),
Suppress => All_Checks);
end Build_Enumeration_Image_Tables;
----------------------------
-- Expand_Image_Attribute --
----------------------------
-- For all cases other than user defined enumeration types, the scheme
-- is as follows. First we insert the following code:
-- Snn : String (1 .. rt'Width);
-- Pnn : Natural;
-- Image_xx (tv, Snn, Pnn [,pm]);
--
-- and then Expr is replaced by Snn (1 .. Pnn)
-- In the above expansion:
-- rt is the root type of the expression
-- tv is the expression with the value, usually a type conversion
-- pm is an extra parameter present in some cases
-- The following table shows tv, xx, and (if used) pm for the various
-- possible types of the argument:
-- For types whose root type is Character
-- xx = Character
-- tv = Character (Expr)
-- For types whose root type is Boolean
-- xx = Boolean
-- tv = Boolean (Expr)
-- For signed integer types with size <= Integer'Size
-- xx = Integer
-- tv = Integer (Expr)
-- For other signed integer types
-- xx = Long_Long_Integer
-- tv = Long_Long_Integer (Expr)
-- For modular types with modulus <= System.Unsigned_Types.Unsigned
-- xx = Unsigned
-- tv = System.Unsigned_Types.Unsigned (Expr)
-- For other modular integer types
-- xx = Long_Long_Unsigned
-- tv = System.Unsigned_Types.Long_Long_Unsigned (Expr)
-- For types whose root type is Wide_Character
-- xx = Wide_Character
-- tv = Wide_Character (Expr)
-- pm = Boolean, true if Ada 2005 mode, False otherwise
-- For types whose root type is Wide_Wide_Character
-- xx = Wide_Wide_Character
-- tv = Wide_Wide_Character (Expr)
-- For floating-point types
-- xx = Floating_Point
-- tv = Long_Long_Float (Expr)
-- pm = typ'Digits (typ = subtype of expression)
-- For ordinary fixed-point types
-- xx = Ordinary_Fixed_Point
-- tv = Long_Long_Float (Expr)
-- pm = typ'Aft (typ = subtype of expression)
-- For decimal fixed-point types with size = Integer'Size
-- xx = Decimal
-- tv = Integer (Expr)
-- pm = typ'Scale (typ = subtype of expression)
-- For decimal fixed-point types with size > Integer'Size
-- xx = Long_Long_Decimal
-- tv = Long_Long_Integer?(Expr) [convert with no scaling]
-- pm = typ'Scale (typ = subtype of expression)
-- For enumeration types other than those declared packages Standard
-- or System, Snn, Pnn, are expanded as above, but the call looks like:
-- Image_Enumeration_NN (rt'Pos (X), Snn, Pnn, typS, typI'Address)
-- where rt is the root type of the expression, and typS and typI are
-- the entities constructed as described in the spec for the procedure
-- Build_Enumeration_Image_Tables and NN is 32/16/8 depending on the
-- element type of Lit_Indexes. The rewriting of the expression to
-- Snn (1 .. Pnn) then occurs as in the other cases. A special case is
-- when pragma Discard_Names applies, in which case we replace expr by:
-- (rt'Pos (expr))'Img
-- So that the result is a space followed by the decimal value for the
-- position of the enumeration value in the enumeration type.
procedure Expand_Image_Attribute (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Exprs : constant List_Id := Expressions (N);
Pref : constant Node_Id := Prefix (N);
Ptyp : constant Entity_Id := Entity (Pref);
Rtyp : constant Entity_Id := Root_Type (Ptyp);
Expr : constant Node_Id := Relocate_Node (First (Exprs));
Imid : RE_Id;
Tent : Entity_Id;
Ttyp : Entity_Id;
Proc_Ent : Entity_Id;
Enum_Case : Boolean;
Arg_List : List_Id;
-- List of arguments for run-time procedure call
Ins_List : List_Id;
-- List of actions to be inserted
Snn : constant Entity_Id := Make_Temporary (Loc, 'S');
Pnn : constant Entity_Id := Make_Temporary (Loc, 'P');
begin
-- Build declarations of Snn and Pnn to be inserted
Ins_List := New_List (
-- Snn : String (1 .. typ'Width);
Make_Object_Declaration (Loc,
Defining_Identifier => Snn,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (Standard_String, Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Width)))))),
-- Pnn : Natural;
Make_Object_Declaration (Loc,
Defining_Identifier => Pnn,
Object_Definition => New_Occurrence_Of (Standard_Natural, Loc)));
-- Set Imid (RE_Id of procedure to call), and Tent, target for the
-- type conversion of the first argument for all possibilities.
Enum_Case := False;
if Rtyp = Standard_Boolean then
Imid := RE_Image_Boolean;
Tent := Rtyp;
-- For standard character, we have to select the version which handles
-- soft hyphen correctly, based on the version of Ada in use (this is
-- ugly, but we have no choice).
elsif Rtyp = Standard_Character then
if Ada_Version < Ada_2005 then
Imid := RE_Image_Character;
else
Imid := RE_Image_Character_05;
end if;
Tent := Rtyp;
elsif Rtyp = Standard_Wide_Character then
Imid := RE_Image_Wide_Character;
Tent := Rtyp;
elsif Rtyp = Standard_Wide_Wide_Character then
Imid := RE_Image_Wide_Wide_Character;
Tent := Rtyp;
elsif Is_Signed_Integer_Type (Rtyp) then
if Esize (Rtyp) <= Esize (Standard_Integer) then
Imid := RE_Image_Integer;
Tent := Standard_Integer;
else
Imid := RE_Image_Long_Long_Integer;
Tent := Standard_Long_Long_Integer;
end if;
elsif Is_Modular_Integer_Type (Rtyp) then
if Modulus (Rtyp) <= Modulus (RTE (RE_Unsigned)) then
Imid := RE_Image_Unsigned;
Tent := RTE (RE_Unsigned);
else
Imid := RE_Image_Long_Long_Unsigned;
Tent := RTE (RE_Long_Long_Unsigned);
end if;
elsif Is_Fixed_Point_Type (Rtyp) and then Has_Decimal_Small (Rtyp) then
if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
Imid := RE_Image_Decimal;
Tent := Standard_Integer;
else
Imid := RE_Image_Long_Long_Decimal;
Tent := Standard_Long_Long_Integer;
end if;
elsif Is_Ordinary_Fixed_Point_Type (Rtyp) then
Imid := RE_Image_Ordinary_Fixed_Point;
Tent := Standard_Long_Long_Float;
elsif Is_Floating_Point_Type (Rtyp) then
Imid := RE_Image_Floating_Point;
Tent := Standard_Long_Long_Float;
-- Only other possibility is user defined enumeration type
else
if Discard_Names (First_Subtype (Ptyp))
or else No (Lit_Strings (Root_Type (Ptyp)))
then
-- When pragma Discard_Names applies to the first subtype, build
-- (Pref'Pos (Expr))'Img.
Rewrite (N,
Make_Attribute_Reference (Loc,
Prefix =>
Make_Attribute_Reference (Loc,
Prefix => Pref,
Attribute_Name => Name_Pos,
Expressions => New_List (Expr)),
Attribute_Name =>
Name_Img));
Analyze_And_Resolve (N, Standard_String);
return;
else
-- Here for enumeration type case
Ttyp := Component_Type (Etype (Lit_Indexes (Rtyp)));
if Ttyp = Standard_Integer_8 then
Imid := RE_Image_Enumeration_8;
elsif Ttyp = Standard_Integer_16 then
Imid := RE_Image_Enumeration_16;
else
Imid := RE_Image_Enumeration_32;
end if;
-- Apply a validity check, since it is a bit drastic to get a
-- completely junk image value for an invalid value.
if not Expr_Known_Valid (Expr) then
Insert_Valid_Check (Expr);
end if;
Enum_Case := True;
end if;
end if;
-- Build first argument for call
if Enum_Case then
Arg_List := New_List (
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Pos,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Expressions => New_List (Expr)));
else
Arg_List := New_List (Convert_To (Tent, Expr));
end if;
-- Append Snn, Pnn arguments
Append_To (Arg_List, New_Occurrence_Of (Snn, Loc));
Append_To (Arg_List, New_Occurrence_Of (Pnn, Loc));
-- Get entity of procedure to call
Proc_Ent := RTE (Imid);
-- If the procedure entity is empty, that means we have a case in
-- no run time mode where the operation is not allowed, and an
-- appropriate diagnostic has already been issued.
if No (Proc_Ent) then
return;
end if;
-- Otherwise complete preparation of arguments for run-time call
-- Add extra arguments for Enumeration case
if Enum_Case then
Append_To (Arg_List, New_Occurrence_Of (Lit_Strings (Rtyp), Loc));
Append_To (Arg_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Lit_Indexes (Rtyp), Loc),
Attribute_Name => Name_Address));
-- For floating-point types, append Digits argument
elsif Is_Floating_Point_Type (Rtyp) then
Append_To (Arg_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Digits));
-- For ordinary fixed-point types, append Aft parameter
elsif Is_Ordinary_Fixed_Point_Type (Rtyp) then
Append_To (Arg_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Aft));
if Has_Decimal_Small (Rtyp) then
Set_Conversion_OK (First (Arg_List));
Set_Etype (First (Arg_List), Tent);
end if;
-- For decimal, append Scale and also set to do literal conversion
elsif Is_Decimal_Fixed_Point_Type (Rtyp) then
Append_To (Arg_List,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Scale));
Set_Conversion_OK (First (Arg_List));
Set_Etype (First (Arg_List), Tent);
-- For Wide_Character, append Ada 2005 indication
elsif Rtyp = Standard_Wide_Character then
Append_To (Arg_List,
New_Occurrence_Of
(Boolean_Literals (Ada_Version >= Ada_2005), Loc));
end if;
-- Now append the procedure call to the insert list
Append_To (Ins_List,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Proc_Ent, Loc),
Parameter_Associations => Arg_List));
-- Insert declarations of Snn, Pnn, and the procedure call. We suppress
-- checks because we are sure that everything is in range at this stage.
Insert_Actions (N, Ins_List, Suppress => All_Checks);
-- Final step is to rewrite the expression as a slice and analyze,
-- again with no checks, since we are sure that everything is OK.
Rewrite (N,
Make_Slice (Loc,
Prefix => New_Occurrence_Of (Snn, Loc),
Discrete_Range =>
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound => New_Occurrence_Of (Pnn, Loc))));
Analyze_And_Resolve (N, Standard_String, Suppress => All_Checks);
end Expand_Image_Attribute;
----------------------------
-- Expand_Value_Attribute --
----------------------------
-- For scalar types derived from Boolean, Character and integer types
-- in package Standard, typ'Value (X) expands into:
-- btyp (Value_xx (X))
-- where btyp is he base type of the prefix
-- For types whose root type is Character
-- xx = Character
-- For types whose root type is Wide_Character
-- xx = Wide_Character
-- For types whose root type is Wide_Wide_Character
-- xx = Wide_Wide_Character
-- For types whose root type is Boolean
-- xx = Boolean
-- For signed integer types with size <= Integer'Size
-- xx = Integer
-- For other signed integer types
-- xx = Long_Long_Integer
-- For modular types with modulus <= System.Unsigned_Types.Unsigned
-- xx = Unsigned
-- For other modular integer types
-- xx = Long_Long_Unsigned
-- For floating-point types and ordinary fixed-point types
-- xx = Real
-- For Wide_[Wide_]Character types, typ'Value (X) expands into:
-- btyp (Value_xx (X, EM))
-- where btyp is the base type of the prefix, and EM is the encoding method
-- For decimal types with size <= Integer'Size, typ'Value (X)
-- expands into
-- btyp?(Value_Decimal (X, typ'Scale));
-- For all other decimal types, typ'Value (X) expands into
-- btyp?(Value_Long_Long_Decimal (X, typ'Scale))
-- For enumeration types other than those derived from types Boolean,
-- Character, Wide_[Wide_]Character in Standard, typ'Value (X) expands to:
-- Enum'Val (Value_Enumeration_NN (typS, typI'Address, Num, X))
-- where typS and typI and the Lit_Strings and Lit_Indexes entities
-- from T's root type entity, and Num is Enum'Pos (Enum'Last). The
-- Value_Enumeration_NN function will search the tables looking for
-- X and return the position number in the table if found which is
-- used to provide the result of 'Value (using Enum'Val). If the
-- value is not found Constraint_Error is raised. The suffix _NN
-- depends on the element type of typI.
procedure Expand_Value_Attribute (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
Btyp : constant Entity_Id := Base_Type (Typ);
Rtyp : constant Entity_Id := Root_Type (Typ);
Exprs : constant List_Id := Expressions (N);
Vid : RE_Id;
Args : List_Id;
Func : RE_Id;
Ttyp : Entity_Id;
begin
Args := Exprs;
if Rtyp = Standard_Character then
Vid := RE_Value_Character;
elsif Rtyp = Standard_Boolean then
Vid := RE_Value_Boolean;
elsif Rtyp = Standard_Wide_Character then
Vid := RE_Value_Wide_Character;
Append_To (Args,
Make_Integer_Literal (Loc,
Intval => Int (Wide_Character_Encoding_Method)));
elsif Rtyp = Standard_Wide_Wide_Character then
Vid := RE_Value_Wide_Wide_Character;
Append_To (Args,
Make_Integer_Literal (Loc,
Intval => Int (Wide_Character_Encoding_Method)));
elsif Rtyp = Base_Type (Standard_Short_Short_Integer)
or else Rtyp = Base_Type (Standard_Short_Integer)
or else Rtyp = Base_Type (Standard_Integer)
then
Vid := RE_Value_Integer;
elsif Is_Signed_Integer_Type (Rtyp) then
Vid := RE_Value_Long_Long_Integer;
elsif Is_Modular_Integer_Type (Rtyp) then
if Modulus (Rtyp) <= Modulus (RTE (RE_Unsigned)) then
Vid := RE_Value_Unsigned;
else
Vid := RE_Value_Long_Long_Unsigned;
end if;
elsif Is_Decimal_Fixed_Point_Type (Rtyp) then
if UI_To_Int (Esize (Rtyp)) <= Standard_Integer_Size then
Vid := RE_Value_Decimal;
else
Vid := RE_Value_Long_Long_Decimal;
end if;
Append_To (Args,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Scale));
Rewrite (N,
OK_Convert_To (Btyp,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (Vid), Loc),
Parameter_Associations => Args)));
Set_Etype (N, Btyp);
Analyze_And_Resolve (N, Btyp);
return;
elsif Is_Real_Type (Rtyp) then
Vid := RE_Value_Real;
-- Only other possibility is user defined enumeration type
else
pragma Assert (Is_Enumeration_Type (Rtyp));
-- Case of pragma Discard_Names, transform the Value
-- attribute to Btyp'Val (Long_Long_Integer'Value (Args))
if Discard_Names (First_Subtype (Typ))
or else No (Lit_Strings (Rtyp))
then
Rewrite (N,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Btyp, Loc),
Attribute_Name => Name_Val,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Standard_Long_Long_Integer, Loc),
Attribute_Name => Name_Value,
Expressions => Args))));
Analyze_And_Resolve (N, Btyp);
-- Here for normal case where we have enumeration tables, this
-- is where we build
-- T'Val (Value_Enumeration_NN (typS, typI'Address, Num, X))
else
Ttyp := Component_Type (Etype (Lit_Indexes (Rtyp)));
if Ttyp = Standard_Integer_8 then
Func := RE_Value_Enumeration_8;
elsif Ttyp = Standard_Integer_16 then
Func := RE_Value_Enumeration_16;
else
Func := RE_Value_Enumeration_32;
end if;
Prepend_To (Args,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Last))));
Prepend_To (Args,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Lit_Indexes (Rtyp), Loc),
Attribute_Name => Name_Address));
Prepend_To (Args,
New_Occurrence_Of (Lit_Strings (Rtyp), Loc));
Rewrite (N,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Val,
Expressions => New_List (
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (Func), Loc),
Parameter_Associations => Args))));
Analyze_And_Resolve (N, Btyp);
end if;
return;
end if;
-- Fall through for all cases except user defined enumeration type
-- and decimal types, with Vid set to the Id of the entity for the
-- Value routine and Args set to the list of parameters for the call.
-- Compiling package Ada.Tags under No_Run_Time_Mode we disable the
-- expansion of the attribute into the function call statement to avoid
-- generating spurious errors caused by the use of Integer_Address'Value
-- in our implementation of Ada.Tags.Internal_Tag
-- Seems like a bit of a odd approach, there should be a better way ???
-- There is a better way, test RTE_Available ???
if No_Run_Time_Mode
and then Rtyp = RTE (RE_Integer_Address)
and then RTU_Loaded (Ada_Tags)
and then Cunit_Entity (Current_Sem_Unit)
= Body_Entity (RTU_Entity (Ada_Tags))
then
Rewrite (N,
Unchecked_Convert_To (Rtyp,
Make_Integer_Literal (Loc, Uint_0)));
else
Rewrite (N,
Convert_To (Btyp,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (Vid), Loc),
Parameter_Associations => Args)));
end if;
Analyze_And_Resolve (N, Btyp);
end Expand_Value_Attribute;
---------------------------------
-- Expand_Wide_Image_Attribute --
---------------------------------
-- We expand typ'Wide_Image (X) as follows. First we insert this code:
-- Rnn : Wide_String (1 .. rt'Wide_Width);
-- Lnn : Natural;
-- String_To_Wide_String
-- (typ'Image (Expr), Rnn, Lnn, Wide_Character_Encoding_Method);
-- where rt is the root type of the prefix type
-- Now we replace the Wide_Image reference by
-- Rnn (1 .. Lnn)
-- This works in all cases because String_To_Wide_String converts any
-- wide character escape sequences resulting from the Image call to the
-- proper Wide_Character equivalent
-- not quite right for typ = Wide_Character ???
procedure Expand_Wide_Image_Attribute (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Rtyp : constant Entity_Id := Root_Type (Entity (Prefix (N)));
Rnn : constant Entity_Id := Make_Temporary (Loc, 'S');
Lnn : constant Entity_Id := Make_Temporary (Loc, 'P');
begin
Insert_Actions (N, New_List (
-- Rnn : Wide_String (1 .. base_typ'Width);
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (Standard_Wide_String, Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Wide_Width)))))),
-- Lnn : Natural;
Make_Object_Declaration (Loc,
Defining_Identifier => Lnn,
Object_Definition => New_Occurrence_Of (Standard_Natural, Loc)),
-- String_To_Wide_String
-- (typ'Image (X), Rnn, Lnn, Wide_Character_Encoding_Method);
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_String_To_Wide_String), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Prefix (N),
Attribute_Name => Name_Image,
Expressions => Expressions (N)),
New_Occurrence_Of (Rnn, Loc),
New_Occurrence_Of (Lnn, Loc),
Make_Integer_Literal (Loc,
Intval => Int (Wide_Character_Encoding_Method))))),
-- Suppress checks because we know everything is properly in range
Suppress => All_Checks);
-- Final step is to rewrite the expression as a slice and analyze,
-- again with no checks, since we are sure that everything is OK.
Rewrite (N,
Make_Slice (Loc,
Prefix => New_Occurrence_Of (Rnn, Loc),
Discrete_Range =>
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound => New_Occurrence_Of (Lnn, Loc))));
Analyze_And_Resolve (N, Standard_Wide_String, Suppress => All_Checks);
end Expand_Wide_Image_Attribute;
--------------------------------------
-- Expand_Wide_Wide_Image_Attribute --
--------------------------------------
-- We expand typ'Wide_Wide_Image (X) as follows. First we insert this code:
-- Rnn : Wide_Wide_String (1 .. rt'Wide_Wide_Width);
-- Lnn : Natural;
-- String_To_Wide_Wide_String
-- (typ'Image (Expr), Rnn, Lnn, Wide_Character_Encoding_Method);
-- where rt is the root type of the prefix type
-- Now we replace the Wide_Wide_Image reference by
-- Rnn (1 .. Lnn)
-- This works in all cases because String_To_Wide_Wide_String converts any
-- wide character escape sequences resulting from the Image call to the
-- proper Wide_Wide_Character equivalent
-- not quite right for typ = Wide_Wide_Character ???
procedure Expand_Wide_Wide_Image_Attribute (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Rtyp : constant Entity_Id := Root_Type (Entity (Prefix (N)));
Rnn : constant Entity_Id := Make_Temporary (Loc, 'S');
Lnn : constant Entity_Id := Make_Temporary (Loc, 'P');
begin
Insert_Actions (N, New_List (
-- Rnn : Wide_Wide_String (1 .. rt'Wide_Wide_Width);
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Occurrence_Of (Standard_Wide_Wide_String, Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Wide_Wide_Width)))))),
-- Lnn : Natural;
Make_Object_Declaration (Loc,
Defining_Identifier => Lnn,
Object_Definition => New_Occurrence_Of (Standard_Natural, Loc)),
-- String_To_Wide_Wide_String
-- (typ'Image (X), Rnn, Lnn, Wide_Character_Encoding_Method);
Make_Procedure_Call_Statement (Loc,
Name =>
New_Occurrence_Of (RTE (RE_String_To_Wide_Wide_String), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Prefix (N),
Attribute_Name => Name_Image,
Expressions => Expressions (N)),
New_Occurrence_Of (Rnn, Loc),
New_Occurrence_Of (Lnn, Loc),
Make_Integer_Literal (Loc,
Intval => Int (Wide_Character_Encoding_Method))))),
-- Suppress checks because we know everything is properly in range
Suppress => All_Checks);
-- Final step is to rewrite the expression as a slice and analyze,
-- again with no checks, since we are sure that everything is OK.
Rewrite (N,
Make_Slice (Loc,
Prefix => New_Occurrence_Of (Rnn, Loc),
Discrete_Range =>
Make_Range (Loc,
Low_Bound => Make_Integer_Literal (Loc, 1),
High_Bound => New_Occurrence_Of (Lnn, Loc))));
Analyze_And_Resolve
(N, Standard_Wide_Wide_String, Suppress => All_Checks);
end Expand_Wide_Wide_Image_Attribute;
----------------------------
-- Expand_Width_Attribute --
----------------------------
-- The processing here also handles the case of Wide_[Wide_]Width. With the
-- exceptions noted, the processing is identical
-- For scalar types derived from Boolean, character and integer types
-- in package Standard. Note that the Width attribute is computed at
-- compile time for all cases except those involving non-static sub-
-- types. For such subtypes, typ'[Wide_[Wide_]]Width expands into:
-- Result_Type (xx (yy (Ptyp'First), yy (Ptyp'Last)))
-- where
-- For types whose root type is Character
-- xx = Width_Character
-- yy = Character
-- For types whose root type is Wide_Character
-- xx = Wide_Width_Character
-- yy = Character
-- For types whose root type is Wide_Wide_Character
-- xx = Wide_Wide_Width_Character
-- yy = Character
-- For types whose root type is Boolean
-- xx = Width_Boolean
-- yy = Boolean
-- For signed integer types
-- xx = Width_Long_Long_Integer
-- yy = Long_Long_Integer
-- For modular integer types
-- xx = Width_Long_Long_Unsigned
-- yy = Long_Long_Unsigned
-- For types derived from Wide_Character, typ'Width expands into
-- Result_Type (Width_Wide_Character (
-- Wide_Character (typ'First),
-- Wide_Character (typ'Last),
-- and typ'Wide_Width expands into:
-- Result_Type (Wide_Width_Wide_Character (
-- Wide_Character (typ'First),
-- Wide_Character (typ'Last));
-- and typ'Wide_Wide_Width expands into
-- Result_Type (Wide_Wide_Width_Wide_Character (
-- Wide_Character (typ'First),
-- Wide_Character (typ'Last));
-- For types derived from Wide_Wide_Character, typ'Width expands into
-- Result_Type (Width_Wide_Wide_Character (
-- Wide_Wide_Character (typ'First),
-- Wide_Wide_Character (typ'Last),
-- and typ'Wide_Width expands into:
-- Result_Type (Wide_Width_Wide_Wide_Character (
-- Wide_Wide_Character (typ'First),
-- Wide_Wide_Character (typ'Last));
-- and typ'Wide_Wide_Width expands into
-- Result_Type (Wide_Wide_Width_Wide_Wide_Char (
-- Wide_Wide_Character (typ'First),
-- Wide_Wide_Character (typ'Last));
-- For real types, typ'Width and typ'Wide_[Wide_]Width expand into
-- if Ptyp'First > Ptyp'Last then 0 else btyp'Width end if
-- where btyp is the base type. This looks recursive but it isn't
-- because the base type is always static, and hence the expression
-- in the else is reduced to an integer literal.
-- For user defined enumeration types, typ'Width expands into
-- Result_Type (Width_Enumeration_NN
-- (typS,
-- typI'Address,
-- typ'Pos (typ'First),
-- typ'Pos (Typ'Last)));
-- and typ'Wide_Width expands into:
-- Result_Type (Wide_Width_Enumeration_NN
-- (typS,
-- typI,
-- typ'Pos (typ'First),
-- typ'Pos (Typ'Last))
-- Wide_Character_Encoding_Method);
-- and typ'Wide_Wide_Width expands into:
-- Result_Type (Wide_Wide_Width_Enumeration_NN
-- (typS,
-- typI,
-- typ'Pos (typ'First),
-- typ'Pos (Typ'Last))
-- Wide_Character_Encoding_Method);
-- where typS and typI are the enumeration image strings and indexes
-- table, as described in Build_Enumeration_Image_Tables. NN is 8/16/32
-- for depending on the element type for typI.
-- Finally if Discard_Names is in effect for an enumeration type, then
-- a special if expression is built that yields the space needed for the
-- decimal representation of the largest pos value in the subtype. See
-- code below for details.
procedure Expand_Width_Attribute (N : Node_Id; Attr : Atype := Normal) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
Pref : constant Node_Id := Prefix (N);
Ptyp : constant Entity_Id := Etype (Pref);
Rtyp : constant Entity_Id := Root_Type (Ptyp);
Arglist : List_Id;
Ttyp : Entity_Id;
XX : RE_Id;
YY : Entity_Id;
begin
-- Types derived from Standard.Boolean
if Rtyp = Standard_Boolean then
XX := RE_Width_Boolean;
YY := Rtyp;
-- Types derived from Standard.Character
elsif Rtyp = Standard_Character then
case Attr is
when Normal => XX := RE_Width_Character;
when Wide => XX := RE_Wide_Width_Character;
when Wide_Wide => XX := RE_Wide_Wide_Width_Character;
end case;
YY := Rtyp;
-- Types derived from Standard.Wide_Character
elsif Rtyp = Standard_Wide_Character then
case Attr is
when Normal => XX := RE_Width_Wide_Character;
when Wide => XX := RE_Wide_Width_Wide_Character;
when Wide_Wide => XX := RE_Wide_Wide_Width_Wide_Character;
end case;
YY := Rtyp;
-- Types derived from Standard.Wide_Wide_Character
elsif Rtyp = Standard_Wide_Wide_Character then
case Attr is
when Normal => XX := RE_Width_Wide_Wide_Character;
when Wide => XX := RE_Wide_Width_Wide_Wide_Character;
when Wide_Wide => XX := RE_Wide_Wide_Width_Wide_Wide_Char;
end case;
YY := Rtyp;
-- Signed integer types
elsif Is_Signed_Integer_Type (Rtyp) then
XX := RE_Width_Long_Long_Integer;
YY := Standard_Long_Long_Integer;
-- Modular integer types
elsif Is_Modular_Integer_Type (Rtyp) then
XX := RE_Width_Long_Long_Unsigned;
YY := RTE (RE_Long_Long_Unsigned);
-- Real types
elsif Is_Real_Type (Rtyp) then
Rewrite (N,
Make_If_Expression (Loc,
Expressions => New_List (
Make_Op_Gt (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_First),
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Last)),
Make_Integer_Literal (Loc, 0),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Base_Type (Ptyp), Loc),
Attribute_Name => Name_Width))));
Analyze_And_Resolve (N, Typ);
return;
-- User defined enumeration types
else
pragma Assert (Is_Enumeration_Type (Rtyp));
-- Whenever pragma Discard_Names is in effect, the value we need
-- is the value needed to accomodate the largest integer pos value
-- in the range of the subtype + 1 for the space at the start. We
-- build:
-- Tnn : constant Integer := Rtyp'Pos (Ptyp'Last)
-- and replace the expression by
-- (if Ptyp'Range_Length = 0 then 0
-- else (if Tnn < 10 then 2
-- else (if Tnn < 100 then 3
-- ...
-- else n)))...
-- where n is equal to Rtyp'Pos (Ptyp'Last) + 1
-- Note: The above processing is in accordance with the intent of
-- the RM, which is that Width should be related to the impl-defined
-- behavior of Image. It is not clear what this means if Image is
-- not defined (as in the configurable run-time case for GNAT) and
-- gives an error at compile time.
-- We choose in this case to just go ahead and implement Width the
-- same way, returning what Image would have returned if it has been
-- available in the configurable run-time library.
if Discard_Names (Rtyp) then
declare
Tnn : constant Entity_Id := Make_Temporary (Loc, 'T');
Cexpr : Node_Id;
P : Int;
M : Int;
K : Int;
begin
Insert_Action (N,
Make_Object_Declaration (Loc,
Defining_Identifier => Tnn,
Constant_Present => True,
Object_Definition =>
New_Occurrence_Of (Standard_Integer, Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Rtyp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Convert_To (Rtyp,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Last))))));
-- OK, now we need to build the if expression. First get the
-- value of M, the largest possible value needed.
P := UI_To_Int
(Enumeration_Pos (Entity (Type_High_Bound (Rtyp))));
K := 1;
M := 1;
while M < P loop
M := M * 10;
K := K + 1;
end loop;
-- Build inner else
Cexpr := Make_Integer_Literal (Loc, K);
-- Wrap in inner if's until counted down to 2
while K > 2 loop
M := M / 10;
K := K - 1;
Cexpr :=
Make_If_Expression (Loc,
Expressions => New_List (
Make_Op_Lt (Loc,
Left_Opnd => New_Occurrence_Of (Tnn, Loc),
Right_Opnd => Make_Integer_Literal (Loc, M)),
Make_Integer_Literal (Loc, K),
Cexpr));
end loop;
-- Add initial comparison for null range and we are done, so
-- rewrite the attribute occurrence with this expression.
Rewrite (N,
Convert_To (Typ,
Make_If_Expression (Loc,
Expressions => New_List (
Make_Op_Eq (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Range_Length),
Right_Opnd => Make_Integer_Literal (Loc, 0)),
Make_Integer_Literal (Loc, 0),
Cexpr))));
Analyze_And_Resolve (N, Typ);
return;
end;
end if;
-- Normal case, not Discard_Names
Ttyp := Component_Type (Etype (Lit_Indexes (Rtyp)));
case Attr is
when Normal =>
if Ttyp = Standard_Integer_8 then
XX := RE_Width_Enumeration_8;
elsif Ttyp = Standard_Integer_16 then
XX := RE_Width_Enumeration_16;
else
XX := RE_Width_Enumeration_32;
end if;
when Wide =>
if Ttyp = Standard_Integer_8 then
XX := RE_Wide_Width_Enumeration_8;
elsif Ttyp = Standard_Integer_16 then
XX := RE_Wide_Width_Enumeration_16;
else
XX := RE_Wide_Width_Enumeration_32;
end if;
when Wide_Wide =>
if Ttyp = Standard_Integer_8 then
XX := RE_Wide_Wide_Width_Enumeration_8;
elsif Ttyp = Standard_Integer_16 then
XX := RE_Wide_Wide_Width_Enumeration_16;
else
XX := RE_Wide_Wide_Width_Enumeration_32;
end if;
end case;
Arglist :=
New_List (
New_Occurrence_Of (Lit_Strings (Rtyp), Loc),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Lit_Indexes (Rtyp), Loc),
Attribute_Name => Name_Address),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_First))),
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Pos,
Expressions => New_List (
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Last))));
Rewrite (N,
Convert_To (Typ,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (XX), Loc),
Parameter_Associations => Arglist)));
Analyze_And_Resolve (N, Typ);
return;
end if;
-- If we fall through XX and YY are set
Arglist := New_List (
Convert_To (YY,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_First)),
Convert_To (YY,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ptyp, Loc),
Attribute_Name => Name_Last)));
Rewrite (N,
Convert_To (Typ,
Make_Function_Call (Loc,
Name => New_Occurrence_Of (RTE (XX), Loc),
Parameter_Associations => Arglist)));
Analyze_And_Resolve (N, Typ);
end Expand_Width_Attribute;
-----------------------
-- Has_Decimal_Small --
-----------------------
function Has_Decimal_Small (E : Entity_Id) return Boolean is
begin
return Is_Decimal_Fixed_Point_Type (E)
or else
(Is_Ordinary_Fixed_Point_Type (E)
and then Ureal_10**Aft_Value (E) * Small_Value (E) = Ureal_1);
end Has_Decimal_Small;
end Exp_Imgv;
|
with Ada.Containers.Doubly_Linked_Lists;
limited with Rules;
package Rule_Lists is
type Rule_Access is access all Rules.Rule_Record;
package Lists is
new Ada.Containers.Doubly_Linked_Lists (Element_Type => Rule_Access);
-- function Element (List : Lists.List) return Natural;
end Rule_Lists;
|
with
cached_Rotation;
package body any_Math.any_fast_Rotation
is
function to_Matrix_2x2 (m11, m12,
m21, m22 : Real) return Matrix_2x2
is
begin
return (1 => (m11, m12),
2 => (m21, m22));
end to_Matrix_2x2;
package the_Cache is new cached_Rotation (Float_type => any_Math.Real,
Matrix_2x2_type => any_Math.Matrix_2x2,
float_elementary_Functions => any_math.Functions,
to_Matrix_2x2 => to_Matrix_2x2,
slot_Count => 10_000);
function to_Rotation (Angle : in Real) return access constant Matrix_2x2
is
begin
return the_Cache.to_Rotation (Angle);
end to_Rotation;
end any_Math.any_fast_Rotation;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- P R J . E R R --
-- --
-- S p e c --
-- --
-- Copyright (C) 2002-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the routines to output error messages and the scanner
-- for the project files. It replaces Errout and Scn. It is not dependent on
-- the GNAT tree packages (Atree, Sinfo, ...). It uses exactly the same global
-- variables as Errout, located in package Err_Vars. Like Errout, it also uses
-- the common variables and routines in package Erroutc.
with Scng;
with Errutil;
package Prj.Err is
---------------------------------------------------------
-- Error Message Text and Message Insertion Characters --
---------------------------------------------------------
-- See errutil.ads
-----------------------------------------------------
-- Format of Messages and Manual Quotation Control --
-----------------------------------------------------
-- See errutil.ads
------------------------------
-- Error Output Subprograms --
------------------------------
procedure Initialize renames Errutil.Initialize;
-- Initializes for output of error messages. Must be called for each
-- file before using any of the other routines in the package.
procedure Finalize (Source_Type : String := "project")
renames Errutil.Finalize;
-- Finalize processing of error messages for one file and output message
-- indicating the number of detected errors.
procedure Error_Msg (Msg : String; Flag_Location : Source_Ptr)
renames Errutil.Error_Msg;
-- Output a message at specified location
procedure Error_Msg_S (Msg : String) renames Errutil.Error_Msg_S;
-- Output a message at current scan pointer location
procedure Error_Msg_SC (Msg : String) renames Errutil.Error_Msg_SC;
-- Output a message at the start of the current token, unless we are at
-- the end of file, in which case we always output the message after the
-- last real token in the file.
procedure Error_Msg_SP (Msg : String) renames Errutil.Error_Msg_SP;
-- Output a message at the start of the previous token
-------------
-- Scanner --
-------------
package Style renames Errutil.Style;
-- Instantiation of the generic style package, needed for the instantiation
-- of the generic scanner below.
procedure Obsolescent_Check (S : Source_Ptr);
-- Dummy null procedure for Scng instantiation
procedure Post_Scan;
-- Convert an Ada operator symbol into a standard string
package Scanner is new Scng
(Post_Scan => Post_Scan,
Error_Msg => Error_Msg,
Error_Msg_S => Error_Msg_S,
Error_Msg_SC => Error_Msg_SC,
Error_Msg_SP => Error_Msg_SP,
Obsolescent_Check => Obsolescent_Check,
Style => Style);
-- Instantiation of the generic scanner
end Prj.Err;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Non_Determinism is
Some_Condition : Boolean := True;
-- select else
task Task1 is
entry Send_Message (Message : String);
end Task1;
task body Task1 is
begin
Put_Line ("Start of Task 1");
select
accept Send_Message (Message : String) do
Put_Line ("Task 1 - got message: " & Message);
end Send_Message;
else
Put_Line ("Task 1 does not have its entry called");
end select;
Put_Line ("End of Task 1");
end Task1;
-- select delay
task Task2 is
entry Send_Message (Message : String);
end Task2;
task body Task2 is
begin
Put_Line ("Start of Task 2");
select
accept Send_Message (Message : String) do
Put_Line ("Task 2 - got message: " & Message);
end Send_Message;
or
delay 1.0;
end select;
Put_Line ("End of Task 2");
end Task2;
-- select else with loop
task Task3 is
entry Send_Message (Message : String);
end Task3;
task body Task3 is
begin
Put_Line ("Start of Task 3");
loop
select
accept Send_Message (Message : String) do
Put_Line ("Task 3 - got message: " & Message);
end Send_Message;
else
null; -- do something while waiting
end select;
end loop;
Put_Line ("End of Task 3");
end Task3;
-- select terminate with condition
task Task4 is
entry Send_Message (Message : String);
end Task4;
task body Task4 is
begin
Put_Line ("Start of Task 4");
select
accept Send_Message (Message : String) do
Put_Line ("Task 4 - got message: " & Message);
end Send_Message;
or
when Some_Condition => terminate;
end select;
Put_Line ("End of Task 4");
end Task4;
begin
Put_Line ("Start of Main");
delay 0.5;
Task2.Send_Message ("Hi!"); -- call entry
delay 0.5;
Task3.Send_Message ("Hello!"); -- call entry
abort Task3; -- kill task
Put_Line ("End of Main");
end Non_Determinism;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016-2017, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of STMicroelectronics nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This demonstration illustrates the use of PWM to control the brightness of
-- an LED. The effect is to make the LED increase and decrease in brightness,
-- iteratively, for as long as the application runs. In effect the LED light
-- waxes and wanes. See http://visualgdb.com/tutorials/arm/stm32/fpu/ for the
-- inspiration.
--
-- The demo uses an abstract data type PWM_Modulator to control the power to
-- the LED via pulse-width-modulation. A timer is still used underneath, but
-- the details are hidden. For direct use of the timer see the other demo.
--
-- The demo is currently intended for the STM32F4 Discovery board for the sake
-- of the convenience of the four LEDs and their association with Timer_4, but
-- other boards could be used.
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
with STM32.Board; use STM32.Board;
with STM32.Device; use STM32.Device;
with STM32.PWM; use STM32.PWM;
with STM32.Timers; use STM32.Timers;
procedure Demo_PWM_ADT is -- demo the higher-level PWM abstract data type
Selected_Timer : STM32.Timers.Timer renames Timer_4;
-- NOT arbitrary! We drive the on-board LEDs that are tied to the channels
-- of Timer_4 on some boards. Not all boards have this association. If you
-- use a difference board, select a GPIO point connected to your selected
-- timer and drive that instead.
Timer_AF : constant STM32.GPIO_Alternate_Function := GPIO_AF_TIM4_2;
-- Note that this value MUST match the corresponding timer selected!
Output_Channel : constant Timer_Channel := Channel_2; -- arbitrary
-- The LED driven by this example is determined by the channel selected.
-- That is so because each channel of Timer_4 is connected to a specific
-- LED in the alternate function configuration on this board. We will
-- initialize all of the LEDs to be in the AF mode. The
-- particular channel selected is completely arbitrary, as long as the
-- selected GPIO port/pin for the LED matches the selected channel.
--
-- Channel_1 is connected to the green LED.
-- Channel_2 is connected to the orange LED.
-- Channel_3 is connected to the red LED.
-- Channel_4 is connected to the blue LED.
LED_For : constant array (Timer_Channel) of User_LED :=
(Channel_1 => Green_LED,
Channel_2 => Orange_LED,
Channel_3 => Red_LED,
Channel_4 => Blue_LED);
Requested_Frequency : constant Hertz := 30_000; -- arbitrary
Power_Control : PWM_Modulator;
-- The SFP run-time library for these boards is intended for certified
-- environments and so does not contain the full set of facilities defined
-- by the Ada language. The elementary functions are not included, for
-- example. In contrast, the Ravenscar "full" run-times do have these
-- functions.
function Sine (Input : Long_Float) return Long_Float;
-- Therefore there are four choices: 1) use the "ravescar-full-stm32f4"
-- runtime library, 2) pull the sources for the language-defined elementary
-- function package into the board's run-time library and rebuild the
-- run-time, 3) pull the sources for those packages into the source
-- directory of your application and rebuild your application, or 4) roll
-- your own approximation to the functions required by your application.
-- In this demonstration we roll our own approximation to the sine function
-- so that it doesn't matter which runtime library is used.
function Sine (Input : Long_Float) return Long_Float is
Pi : constant Long_Float := 3.14159_26535_89793_23846;
X : constant Long_Float := Long_Float'Remainder (Input, Pi * 2.0);
B : constant Long_Float := 4.0 / Pi;
C : constant Long_Float := (-4.0) / (Pi * Pi);
Y : constant Long_Float := B * X + C * X * abs (X);
P : constant Long_Float := 0.225;
begin
return P * (Y * abs (Y) - Y) + Y;
end Sine;
-- We use the sine function to drive the power applied to the LED, thereby
-- making the LED increase and decrease in brightness. We attach the timer
-- to the LED and then control how much power is supplied by changing the
-- value of the timer's output compare register. The sine function drives
-- that value, thus the waxing/waning effect.
begin
Configure_PWM_Timer (Selected_Timer'Access, Requested_Frequency);
Power_Control.Attach_PWM_Channel
(Selected_Timer'Access,
Output_Channel,
LED_For (Output_Channel),
Timer_AF);
Power_Control.Enable_Output;
declare
Arg : Long_Float := 0.0;
Value : Percentage;
Increment : constant Long_Float := 0.00003;
-- The Increment value controls the rate at which the brightness
-- increases and decreases. The value is more or less arbitrary, but
-- note that the effect of optimization is observable.
begin
loop
Value := Percentage (50.0 * (1.0 + Sine (Arg)));
Set_Duty_Cycle (Power_Control, Value);
Arg := Arg + Increment;
end loop;
end;
end Demo_PWM_ADT;
|
package body getter.file is
procedure close is
begin
ada.text_io.close(current_ptr.all);
free(current_ptr);
files_stack.delete_last;
if not files_stack_t.is_empty(files_stack) then
current_ptr := files_stack_t.last_element(files_stack).descriptor;
current_line := files_stack_t.last_element(files_stack).line;
set_line(current_line);
end if;
end close;
function get return character is
use type pos_count;
c : character;
begin
if ada.text_io.end_of_file(current_ptr.all) then
if not sended_last_lf then
sended_last_lf := true;
-- return ' ';
return ascii.lf;
end if;
sended_last_lf := false;
close;
return ascii.nul;
end if;
ada.text_io.get_immediate(current_ptr.all, c);
if c = ';' then
ada.text_io.get_immediate(current_ptr.all, c);
while c /= ascii.lf loop
if ada.text_io.end_of_file(current_ptr.all) then
c := ' ';
exit;
end if;
ada.text_io.get_immediate(current_ptr.all, c);
end loop;
end if;
if c = ascii.lf then
current_line := current_line + 1;
set_line(current_line);
-- return ' ';
elsif c = ascii.nul then
return ' ';
end if;
return c;
end get;
procedure open (path : string) is
begin
if not files_stack_t.is_empty(files_stack) then
files_stack.replace_element(files_stack_t.last(files_stack), (current_ptr, current_line));
end if;
current_ptr := new ada.text_io.file_type;
ada.text_io.open(current_ptr.all, ada.text_io.in_file, path);
files_stack.append((current_ptr, 1));
getter.push(get'access);
end open;
end getter.file; |
--
-- 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.Containers.Doubly_Linked_Lists;
with Ada.Strings.Unbounded;
package Files is
use Ada.Strings.Unbounded;
package Collection_Lists is
new Ada.Containers.Doubly_Linked_Lists
(Ada.Strings.Unbounded.Unbounded_String);
subtype Collection_List is Collection_Lists.List;
procedure Append_Collections (Collection : in out Collection_List;
Directory : in String);
-- Scan Directory adding valid databases to Collection.
end Files;
|
with Ada.text_IO;
-- testing attributes 'Value and 'Image as applied to Integer
procedure HelloEx1 is
A,B,C : Integer;
begin
A := Integer'Value ( Ada.text_IO.Get_Line);
B := Integer'Value ( Ada.text_IO.Get_Line);
C := A + B ;
if c = 0 then
Ada.text_IO.Put_Line ("Result is 0 ");
elsif C > 0 then
Ada.text_IO.Put_Line ("Positive Result : " & Integer'Image(C));
else
Ada.text_IO.Put_Line ("negative Result : " & Integer'Image(C));
end if;
end HelloEx1;
|
--
-- \brief Simple ada test program
-- \author Alexander Senier
-- \date 2019-01-03
--
with GNAT.IO;
with Except;
with Ada.Command_Line;
procedure Main is
use GNAT.IO;
begin
declare
begin
Put_Line ("Hello World!");
Except.Do_Sth_2;
Put_Line ("Bye World!");
Except.Do_Something;
exception
when Except.Test_Exception => Put_Line ("Exception caught (outer)");
end;
Put_Line ("Program terminated");
Ada.Command_Line.Set_Exit_Status (42);
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ S P A R K --
-- --
-- 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 Checks; use Checks;
with Einfo; use Einfo;
with Exp_Attr;
with Exp_Ch4;
with Exp_Ch5; use Exp_Ch5;
with Exp_Dbug; use Exp_Dbug;
with Exp_Util; use Exp_Util;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Prag; use Sem_Prag;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Stand; use Stand;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
package body Exp_SPARK is
-----------------------
-- Local Subprograms --
-----------------------
procedure Expand_SPARK_N_Attribute_Reference (N : Node_Id);
-- Perform attribute-reference-specific expansion
procedure Expand_SPARK_N_Delta_Aggregate (N : Node_Id);
-- Perform delta-aggregate-specific expansion
procedure Expand_SPARK_N_Freeze_Type (E : Entity_Id);
-- Build the DIC procedure of a type when needed, if not already done
procedure Expand_SPARK_N_Loop_Statement (N : Node_Id);
-- Perform loop-statement-specific expansion
procedure Expand_SPARK_N_Object_Declaration (N : Node_Id);
-- Perform object-declaration-specific expansion
procedure Expand_SPARK_N_Object_Renaming_Declaration (N : Node_Id);
-- Perform name evaluation for a renamed object
procedure Expand_SPARK_N_Op_Ne (N : Node_Id);
-- Rewrite operator /= based on operator = when defined explicitly
procedure Expand_SPARK_Delta_Or_Update (Typ : Entity_Id; Aggr : Node_Id);
-- Common expansion for attribute Update and delta aggregates
------------------
-- Expand_SPARK --
------------------
procedure Expand_SPARK (N : Node_Id) is
begin
case Nkind (N) is
-- Qualification of entity names in formal verification mode
-- is limited to the addition of a suffix for homonyms (see
-- Exp_Dbug.Qualify_Entity_Name). We used to qualify entity names
-- as full expansion does, but this was removed as this prevents the
-- verification back-end from using a short name for debugging and
-- user interaction. The verification back-end already takes care
-- of qualifying names when needed.
when N_Block_Statement
| N_Entry_Declaration
| N_Package_Body
| N_Package_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Body
| N_Task_Type_Declaration
=>
Qualify_Entity_Names (N);
-- Replace occurrences of System'To_Address by calls to
-- System.Storage_Elements.To_Address.
when N_Attribute_Reference =>
Expand_SPARK_N_Attribute_Reference (N);
when N_Delta_Aggregate =>
Expand_SPARK_N_Delta_Aggregate (N);
when N_Expanded_Name
| N_Identifier
=>
Expand_SPARK_Potential_Renaming (N);
-- Loop iterations over arrays need to be expanded, to avoid getting
-- two names referring to the same object in memory (the array and
-- the iterator) in GNATprove, especially since both can be written
-- (thus possibly leading to interferences due to aliasing). No such
-- problem arises with quantified expressions over arrays, which are
-- dealt with specially in GNATprove.
when N_Loop_Statement =>
Expand_SPARK_N_Loop_Statement (N);
when N_Object_Declaration =>
Expand_SPARK_N_Object_Declaration (N);
when N_Object_Renaming_Declaration =>
Expand_SPARK_N_Object_Renaming_Declaration (N);
when N_Op_Ne =>
Expand_SPARK_N_Op_Ne (N);
when N_Freeze_Entity =>
if Is_Type (Entity (N)) then
Expand_SPARK_N_Freeze_Type (Entity (N));
end if;
-- In SPARK mode, no other constructs require expansion
when others =>
null;
end case;
end Expand_SPARK;
----------------------------------
-- Expand_SPARK_Delta_Or_Update --
----------------------------------
procedure Expand_SPARK_Delta_Or_Update
(Typ : Entity_Id;
Aggr : Node_Id)
is
Assoc : Node_Id;
Comp : Node_Id;
Comp_Id : Entity_Id;
Comp_Type : Entity_Id;
Expr : Node_Id;
Index : Node_Id;
Index_Typ : Entity_Id;
New_Assoc : Node_Id;
begin
-- Apply scalar range checks on the updated components, if needed
if Is_Array_Type (Typ) then
-- Multidimensional arrays
if Present (Next_Index (First_Index (Typ))) then
Assoc := First (Component_Associations (Aggr));
while Present (Assoc) loop
Expr := Expression (Assoc);
Comp_Type := Component_Type (Typ);
if Is_Scalar_Type (Comp_Type) then
Apply_Scalar_Range_Check (Expr, Comp_Type);
end if;
-- The current association contains a sequence of indexes
-- denoting an element of a multidimensional array:
--
-- (Index_1, ..., Index_N)
Expr := First (Choices (Assoc));
pragma Assert (Nkind (Aggr) = N_Aggregate);
while Present (Expr) loop
Index := First (Expressions (Expr));
Index_Typ := First_Index (Typ);
while Present (Index_Typ) loop
Apply_Scalar_Range_Check (Index, Etype (Index_Typ));
Next (Index);
Next_Index (Index_Typ);
end loop;
Next (Expr);
end loop;
Next (Assoc);
end loop;
-- One-dimensional arrays
else
Assoc := First (Component_Associations (Aggr));
while Present (Assoc) loop
Expr := Expression (Assoc);
Comp_Type := Component_Type (Typ);
if Is_Scalar_Type (Comp_Type) then
Apply_Scalar_Range_Check (Expr, Comp_Type);
end if;
Index := First (Choices (Assoc));
Index_Typ := First_Index (Typ);
while Present (Index) loop
-- The index denotes a range of elements
if Nkind (Index) = N_Range then
Apply_Scalar_Range_Check
(Low_Bound (Index), Base_Type (Etype (Index_Typ)));
Apply_Scalar_Range_Check
(High_Bound (Index), Base_Type (Etype (Index_Typ)));
-- Otherwise the index denotes a single element
else
Apply_Scalar_Range_Check (Index, Etype (Index_Typ));
end if;
Next (Index);
end loop;
Next (Assoc);
end loop;
end if;
else pragma Assert (Is_Record_Type (Typ));
-- If the aggregate has multiple component choices, e.g.:
--
-- X'Update (A | B | C => 123)
--
-- then each component might be of a different type and might or
-- might not require a range check. We first rewrite associations
-- into single-component choices, e.g.:
--
-- X'Update (A => 123, B => 123, C => 123)
--
-- and then apply range checks to individual copies of the
-- expressions. We do the same for delta aggregates, accordingly.
-- Iterate over associations of the original aggregate
Assoc := First (Component_Associations (Aggr));
-- Rewrite into a new aggregate and decorate
case Nkind (Aggr) is
when N_Aggregate =>
Rewrite
(Aggr,
Make_Aggregate
(Sloc => Sloc (Aggr),
Component_Associations => New_List));
when N_Delta_Aggregate =>
Rewrite
(Aggr,
Make_Delta_Aggregate
(Sloc => Sloc (Aggr),
Expression => Expression (Aggr),
Component_Associations => New_List));
when others =>
raise Program_Error;
end case;
Set_Etype (Aggr, Typ);
-- Populate the new aggregate with component associations
while Present (Assoc) loop
Expr := Expression (Assoc);
Comp := First (Choices (Assoc));
while Present (Comp) loop
Comp_Id := Entity (Comp);
Comp_Type := Etype (Comp_Id);
New_Assoc :=
Make_Component_Association
(Sloc => Sloc (Assoc),
Choices =>
New_List
(New_Occurrence_Of (Comp_Id, Sloc (Comp))),
Expression => New_Copy_Tree (Expr));
-- New association must be attached to the aggregate before we
-- analyze it.
Append (New_Assoc, Component_Associations (Aggr));
Analyze_And_Resolve (Expression (New_Assoc), Comp_Type);
if Is_Scalar_Type (Comp_Type) then
Apply_Scalar_Range_Check
(Expression (New_Assoc), Comp_Type);
end if;
Next (Comp);
end loop;
Next (Assoc);
end loop;
end if;
end Expand_SPARK_Delta_Or_Update;
--------------------------------
-- Expand_SPARK_N_Freeze_Type --
--------------------------------
procedure Expand_SPARK_N_Freeze_Type (E : Entity_Id) is
begin
-- When a DIC is inherited by a tagged type, it may need to be
-- specialized to the descendant type, hence build a separate DIC
-- procedure for it as done during regular expansion for compilation.
if Has_DIC (E) and then Is_Tagged_Type (E) then
Build_DIC_Procedure_Body (E, For_Freeze => True);
end if;
end Expand_SPARK_N_Freeze_Type;
----------------------------------------
-- Expand_SPARK_N_Attribute_Reference --
----------------------------------------
procedure Expand_SPARK_N_Attribute_Reference (N : Node_Id) is
Aname : constant Name_Id := Attribute_Name (N);
Attr_Id : constant Attribute_Id := Get_Attribute_Id (Aname);
Loc : constant Source_Ptr := Sloc (N);
Pref : constant Node_Id := Prefix (N);
Typ : constant Entity_Id := Etype (N);
Expr : Node_Id;
begin
if Attr_Id = Attribute_To_Address then
-- Extract and convert argument to expected type for call
Expr :=
Make_Type_Conversion (Loc,
Subtype_Mark =>
New_Occurrence_Of (RTE (RE_Integer_Address), Loc),
Expression => Relocate_Node (First (Expressions (N))));
-- Replace attribute reference with call
Rewrite (N,
Make_Function_Call (Loc,
Name =>
New_Occurrence_Of (RTE (RE_To_Address), Loc),
Parameter_Associations => New_List (Expr)));
Analyze_And_Resolve (N, Typ);
elsif Attr_Id = Attribute_Object_Size
or else Attr_Id = Attribute_Size
or else Attr_Id = Attribute_Value_Size
or else Attr_Id = Attribute_VADS_Size
then
Exp_Attr.Expand_Size_Attribute (N);
-- For attributes which return Universal_Integer, introduce a conversion
-- to the expected type with the appropriate check flags set.
elsif Attr_Id = Attribute_Alignment
or else Attr_Id = Attribute_Bit
or else Attr_Id = Attribute_Bit_Position
or else Attr_Id = Attribute_Descriptor_Size
or else Attr_Id = Attribute_First_Bit
or else Attr_Id = Attribute_Last_Bit
or else Attr_Id = Attribute_Length
or else Attr_Id = Attribute_Max_Size_In_Storage_Elements
or else Attr_Id = Attribute_Pos
or else Attr_Id = Attribute_Position
or else Attr_Id = Attribute_Range_Length
or else Attr_Id = Attribute_Aft
or else Attr_Id = Attribute_Max_Alignment_For_Allocation
then
-- If the expected type is Long_Long_Integer, there will be no check
-- flag as the compiler assumes attributes always fit in this type.
-- Since in SPARK_Mode we do not take Storage_Error into account, we
-- cannot make this assumption and need to produce a check.
-- ??? It should be enough to add this check for attributes
-- 'Length, 'Range_Length and 'Pos when the type is as big
-- as Long_Long_Integer.
declare
Typ : Entity_Id;
begin
if Attr_Id = Attribute_Range_Length
or else Attr_Id = Attribute_Pos
then
Typ := Etype (Prefix (N));
elsif Attr_Id = Attribute_Length then
Typ := Get_Index_Subtype (N);
else
Typ := Empty;
end if;
Apply_Universal_Integer_Attribute_Checks (N);
if Present (Typ)
and then RM_Size (Typ) = RM_Size (Standard_Long_Long_Integer)
then
-- ??? This should rather be a range check, but this would
-- crash GNATprove which somehow recovers the proper kind
-- of check anyway.
Set_Do_Overflow_Check (N);
end if;
end;
elsif Attr_Id = Attribute_Constrained then
-- If the prefix is an access to object, the attribute applies to
-- the designated object, so rewrite with an explicit dereference.
if Is_Access_Type (Etype (Pref))
and then
(not Is_Entity_Name (Pref) or else Is_Object (Entity (Pref)))
then
Rewrite (Pref,
Make_Explicit_Dereference (Loc, Relocate_Node (Pref)));
Analyze_And_Resolve (N, Standard_Boolean);
end if;
elsif Attr_Id = Attribute_Update then
Expand_SPARK_Delta_Or_Update (Typ, First (Expressions (N)));
end if;
end Expand_SPARK_N_Attribute_Reference;
------------------------------------
-- Expand_SPARK_N_Delta_Aggregate --
------------------------------------
procedure Expand_SPARK_N_Delta_Aggregate (N : Node_Id) is
begin
Expand_SPARK_Delta_Or_Update (Etype (N), N);
end Expand_SPARK_N_Delta_Aggregate;
-----------------------------------
-- Expand_SPARK_N_Loop_Statement --
-----------------------------------
procedure Expand_SPARK_N_Loop_Statement (N : Node_Id) is
Scheme : constant Node_Id := Iteration_Scheme (N);
begin
-- Loop iterations over arrays need to be expanded, to avoid getting
-- two names referring to the same object in memory (the array and the
-- iterator) in GNATprove, especially since both can be written (thus
-- possibly leading to interferences due to aliasing). No such problem
-- arises with quantified expressions over arrays, which are dealt with
-- specially in GNATprove.
if Present (Scheme)
and then Present (Iterator_Specification (Scheme))
and then Is_Iterator_Over_Array (Iterator_Specification (Scheme))
then
Expand_Iterator_Loop_Over_Array (N);
end if;
end Expand_SPARK_N_Loop_Statement;
---------------------------------------
-- Expand_SPARK_N_Object_Declaration --
---------------------------------------
procedure Expand_SPARK_N_Object_Declaration (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Obj_Id : constant Entity_Id := Defining_Identifier (N);
Typ : constant Entity_Id := Etype (Obj_Id);
Call : Node_Id;
begin
-- If the object declaration denotes a variable without initialization
-- whose type is subject to pragma Default_Initial_Condition, create
-- and analyze a dummy call to the DIC procedure of the type in order
-- to detect potential elaboration issues.
if Comes_From_Source (Obj_Id)
and then Ekind (Obj_Id) = E_Variable
and then Has_DIC (Typ)
and then Present (DIC_Procedure (Typ))
and then not Has_Init_Expression (N)
then
Call := Build_DIC_Call (Loc, Obj_Id, Typ);
-- Partially insert the call into the tree by setting its parent
-- pointer.
Set_Parent (Call, N);
Analyze (Call);
end if;
end Expand_SPARK_N_Object_Declaration;
------------------------------------------------
-- Expand_SPARK_N_Object_Renaming_Declaration --
------------------------------------------------
procedure Expand_SPARK_N_Object_Renaming_Declaration (N : Node_Id) is
CFS : constant Boolean := Comes_From_Source (N);
Loc : constant Source_Ptr := Sloc (N);
Obj_Id : constant Entity_Id := Defining_Entity (N);
Nam : constant Node_Id := Name (N);
Typ : constant Entity_Id := Etype (Obj_Id);
begin
-- Transform a renaming of the form
-- Obj_Id : <subtype mark> renames <function call>;
-- into
-- Obj_Id : constant <subtype mark> := <function call>;
-- Invoking Evaluate_Name and ultimately Remove_Side_Effects introduces
-- a temporary to capture the function result. Once potential renamings
-- are rewritten for SPARK, the temporary may be leaked out into source
-- constructs and lead to confusing error diagnostics. Using an object
-- declaration prevents this unwanted side effect.
if Nkind (Nam) = N_Function_Call then
Rewrite (N,
Make_Object_Declaration (Loc,
Defining_Identifier => Obj_Id,
Constant_Present => True,
Object_Definition => New_Occurrence_Of (Typ, Loc),
Expression => Nam));
-- Inherit the original Comes_From_Source status of the renaming
Set_Comes_From_Source (N, CFS);
-- Sever the link to the renamed function result because the entity
-- will no longer alias anything.
Set_Renamed_Object (Obj_Id, Empty);
-- Remove the entity of the renaming declaration from visibility as
-- the analysis of the object declaration will reintroduce it again.
Remove_Entity_And_Homonym (Obj_Id);
Analyze (N);
-- Otherwise unconditionally remove all side effects from the name
else
Evaluate_Name (Nam);
end if;
end Expand_SPARK_N_Object_Renaming_Declaration;
--------------------------
-- Expand_SPARK_N_Op_Ne --
--------------------------
procedure Expand_SPARK_N_Op_Ne (N : Node_Id) is
Typ : constant Entity_Id := Etype (Left_Opnd (N));
begin
-- Case of elementary type with standard operator
if Is_Elementary_Type (Typ)
and then Sloc (Entity (N)) = Standard_Location
then
null;
else
Exp_Ch4.Expand_N_Op_Ne (N);
end if;
end Expand_SPARK_N_Op_Ne;
-------------------------------------
-- Expand_SPARK_Potential_Renaming --
-------------------------------------
procedure Expand_SPARK_Potential_Renaming (N : Node_Id) is
function In_Insignificant_Pragma (Nod : Node_Id) return Boolean;
-- Determine whether arbitrary node Nod appears within a significant
-- pragma for SPARK.
-----------------------------
-- In_Insignificant_Pragma --
-----------------------------
function In_Insignificant_Pragma (Nod : Node_Id) return Boolean is
Par : Node_Id;
begin
-- Climb the parent chain looking for an enclosing pragma
Par := Nod;
while Present (Par) loop
if Nkind (Par) = N_Pragma then
return not Pragma_Significant_In_SPARK (Get_Pragma_Id (Par));
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Par) then
exit;
end if;
Par := Parent (Par);
end loop;
return False;
end In_Insignificant_Pragma;
-- Local variables
Loc : constant Source_Ptr := Sloc (N);
Obj_Id : constant Entity_Id := Entity (N);
Typ : constant Entity_Id := Etype (N);
Ren : Node_Id;
-- Start of processing for Expand_SPARK_Potential_Renaming
begin
-- Replace a reference to a renaming with the actual renamed object
if Is_Object (Obj_Id) then
Ren := Renamed_Object (Obj_Id);
if Present (Ren) then
-- Do not process a reference when it appears within a pragma of
-- no significance to SPARK. It is assumed that the replacement
-- will violate the semantics of the pragma and cause a spurious
-- error.
if In_Insignificant_Pragma (N) then
return;
-- Instantiations and inlining of subprograms employ "prologues"
-- which map actual to formal parameters by means of renamings.
-- Replace a reference to a formal by the corresponding actual
-- parameter.
elsif Nkind (Ren) in N_Entity then
Rewrite (N, New_Occurrence_Of (Ren, Loc));
-- Otherwise the renamed object denotes a name
else
Rewrite (N, New_Copy_Tree (Ren, New_Sloc => Loc));
Reset_Analyzed_Flags (N);
end if;
Analyze_And_Resolve (N, Typ);
end if;
end if;
end Expand_SPARK_Potential_Renaming;
end Exp_SPARK;
|
-----------------------------------------------------------------------
-- facebook - Use Facebook Graph API
-- Copyright (C) 2012, 2013, 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.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Http.Rest.Rest_Get_Vector;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.Mappers.Vector_Mapper;
with ASF.Sessions;
with ASF.Contexts.Faces;
with ASF.Events.Faces.Actions;
package body Facebook is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Facebook");
type Friend_Field_Type is (FIELD_NAME, FIELD_ID);
type Feed_Field_Type is (FIELD_ID, FIELD_NAME, FIELD_FROM, FIELD_MESSAGE,
FIELD_PICTURE, FIELD_LINK, FIELD_DESCRIPTION, FIELD_ICON);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object);
procedure Set_Member (Into : in out Friend_Info;
Field : in Friend_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
end case;
end Set_Member;
procedure Set_Member (Into : in out Feed_Info;
Field : in Feed_Field_Type;
Value : in Util.Beans.Objects.Object) is
begin
Log.Info ("Set field {0} to {1}", Feed_Field_Type'Image (Field),
Util.Beans.Objects.To_String (Value));
case Field is
when FIELD_ID =>
Into.Id := Value;
when FIELD_NAME =>
Into.Name := Value;
when FIELD_FROM =>
Into.From := Value;
when FIELD_MESSAGE =>
Into.Message := Value;
when FIELD_LINK =>
Into.Link := Value;
when FIELD_PICTURE =>
Into.Picture := Value;
when FIELD_ICON =>
Into.Icon := Value;
when FIELD_DESCRIPTION =>
Into.Description := Value;
end case;
end Set_Member;
package Friend_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Friend_Info,
Element_Type_Access => Friend_Info_Access,
Fields => Friend_Field_Type,
Set_Member => Set_Member);
package Friend_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Friend_List.Vectors,
Element_Mapper => Friend_Mapper);
package Feed_Mapper is
new Util.Serialize.Mappers.Record_Mapper (Element_Type => Feed_Info,
Element_Type_Access => Feed_Info_Access,
Fields => Feed_Field_Type,
Set_Member => Set_Member);
package Feed_Vector_Mapper is
new Util.Serialize.Mappers.Vector_Mapper (Vectors => Feed_List.Vectors,
Element_Mapper => Feed_Mapper);
Friend_Map : aliased Friend_Mapper.Mapper;
Friend_Vector_Map : aliased Friend_Vector_Mapper.Mapper;
Feed_Map : aliased Feed_Mapper.Mapper;
Feed_Vector_Map : aliased Feed_Vector_Mapper.Mapper;
procedure Get_Friends is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Friend_Vector_Mapper);
procedure Get_Feeds is
new Util.Http.Rest.Rest_Get_Vector (Vector_Mapper => Feed_Vector_Mapper);
-- ------------------------------
-- Get the access token from the user session.
-- ------------------------------
function Get_Access_Token return String is
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if Context = null then
return "";
end if;
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
begin
if not S.Is_Valid then
return "";
end if;
declare
Token : constant Util.Beans.Objects.Object := S.Get_Attribute ("access_token");
begin
if Util.Beans.Objects.Is_Null (Token) then
return "";
else
return Util.Beans.Objects.To_String (Token);
end if;
end;
end;
end Get_Access_Token;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "name" then
return From.Name;
elsif Name = "id" then
return From.Id;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Feed_Info;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "id" then
return From.Id;
elsif Name = "name" then
return From.Name;
elsif Name = "from" then
return From.From;
elsif Name = "message" then
return From.Message;
elsif Name = "picture" then
return From.Picture;
elsif Name = "link" then
return From.Link;
elsif Name = "description" then
return From.Description;
elsif Name = "icon" then
return From.Icon;
else
return Util.Beans.Objects.Null_Object;
end if;
end Get_Value;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Friend_List_Bean;
Name : in String) return Util.Beans.Objects.Object is
begin
if Name = "hasAccessToken" then
return Util.Beans.Objects.To_Object (False);
end if;
return Friend_List.List_Bean (From).Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Create a Friend_List bean instance.
-- ------------------------------
function Create_Friends_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Friend_List_Bean_Access := new Friend_List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook friends");
Get_Friends ("https://graph.facebook.com/me/friends?access_token="
& Token,
Friend_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Friends_Bean;
-- ------------------------------
-- Build and return a Facebook feed list.
-- ------------------------------
function Create_Feed_List_Bean return Util.Beans.Basic.Readonly_Bean_Access is
List : Feed_List.List_Bean_Access := new Feed_List.List_Bean;
Token : constant String := Get_Access_Token;
begin
if Token'Length > 0 then
Log.Info ("Getting the Facebook feeds");
Get_Feeds ("https://graph.facebook.com/me/home?access_token="
& Token,
Feed_Vector_Map'Access,
"/data",
List.List'Access);
end if;
return List.all'Access;
end Create_Feed_List_Bean;
-- ------------------------------
-- Get the user information identified by the given name.
-- ------------------------------
overriding
function Get_Value (From : in Facebook_Auth;
Name : in String) return Util.Beans.Objects.Object is
use type ASF.Contexts.Faces.Faces_Context_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
begin
if F /= null and Name = "authenticate_url" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (True);
Id : constant String := S.Get_Id;
State : constant String := From.Get_State (Id);
Params : constant String := From.Get_Auth_Params (State, "read_stream");
begin
Log.Info ("OAuth params: {0}", Params);
return Util.Beans.Objects.To_Object ("https://www.facebook.com/dialog/oauth?"
& Params);
end;
elsif F /= null and Name = "isAuthenticated" then
declare
S : constant ASF.Sessions.Session := F.Get_Session (False);
begin
if S.Is_Valid and
then not Util.Beans.Objects.Is_Null (S.Get_Attribute ("access_token")) then
return Util.Beans.Objects.To_Object (True);
else
return Util.Beans.Objects.To_Object (False);
end if;
end;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Authenticate result from Facebook.
-- ------------------------------
procedure Authenticate (From : in out Facebook_Auth;
Outcome : in out Ada.Strings.Unbounded.Unbounded_String) is
pragma Unreferenced (Outcome);
use type Security.OAuth.Clients.Access_Token_Access;
F : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
Session : ASF.Sessions.Session := F.Get_Session;
State : constant String := F.Get_Parameter (Security.OAuth.State);
Code : constant String := F.Get_Parameter (Security.OAuth.Code);
begin
Log.Info ("Auth code {0} for state {1}", Code, State);
if Session.Is_Valid then
if From.Is_Valid_State (Session.Get_Id, State) then
declare
Acc : constant Security.OAuth.Clients.Access_Token_Access
:= From.Request_Access_Token (Code);
begin
if Acc /= null then
Log.Info ("Access token is {0}", Acc.Get_Name);
Session.Set_Attribute ("access_token",
Util.Beans.Objects.To_Object (Acc.Get_Name));
end if;
end;
end if;
end if;
end Authenticate;
package Authenticate_Binding is
new ASF.Events.Faces.Actions.Action_Method.Bind (Bean => Facebook_Auth,
Method => Authenticate,
Name => "authenticate");
Binding_Array : aliased constant Util.Beans.Methods.Method_Binding_Array
:= (1 => Authenticate_Binding.Proxy'Unchecked_Access);
-- ------------------------------
-- This bean provides some methods that can be used in a Method_Expression
-- ------------------------------
overriding
function Get_Method_Bindings (From : in Facebook_Auth)
return Util.Beans.Methods.Method_Binding_Array_Access is
pragma Unreferenced (From);
begin
return Binding_Array'Access;
end Get_Method_Bindings;
begin
Friend_Map.Add_Default_Mapping;
Friend_Vector_Map.Set_Mapping (Friend_Map'Access);
Feed_Map.Add_Mapping ("id", FIELD_ID);
Feed_Map.Add_Mapping ("name", FIELD_NAME);
Feed_Map.Add_Mapping ("message", FIELD_MESSAGE);
Feed_Map.Add_Mapping ("description", FIELD_DESCRIPTION);
Feed_Map.Add_Mapping ("from/name", FIELD_FROM);
Feed_Map.Add_Mapping ("picture", FIELD_PICTURE);
Feed_Map.Add_Mapping ("link", FIELD_LINK);
Feed_Map.Add_Mapping ("icon", FIELD_ICON);
Feed_Vector_Map.Set_Mapping (Feed_Map'Access);
end Facebook;
|
pragma Warnings (Off);
pragma Style_Checks (Off);
package GLOBE_3D.Wire_frame is
type Segment is record
P1, P2 : Positive; -- Indices to o.Point
colour : GL.RGBA_Color;
end record;
type Segment_array is array (Positive range <>) of Segment;
type p_Segment_array is access Segment_array;
type Wired_3D is new Object_3D with record
wire : p_Segment_array := null;
end record;
type p_Wired_3D is access Wired_3D;
type Wired_3D_array is array (Positive range <>) of p_Wired_3D;
type p_Wired_3D_array is access Wired_3D_array;
procedure Display_one (o : in out Wired_3D);
end GLOBE_3D.Wire_frame;
|
------------------------------------------------------------------------------
-- --
-- GNAT SYSTEM UTILITIES --
-- --
-- X T R E E P R S --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc.
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Program to construct the spec of the Treeprs package
-- Input files:
-- sinfo.ads Spec of Sinfo package
-- treeprs.adt Template for Treeprs package
-- Output files:
-- treeprs.ads Spec of Treeprs package
-- Note: this program assumes that sinfo.ads has passed the error checks which
-- are carried out by the CSinfo utility so it does not duplicate these checks
-- An optional argument allows the specification of an output file name to
-- override the default treeprs.ads file name for the generated output file.
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO; use Ada.Strings.Unbounded.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Spitbol; use GNAT.Spitbol;
with GNAT.Spitbol.Patterns; use GNAT.Spitbol.Patterns;
with GNAT.Spitbol.Table_Boolean; use GNAT.Spitbol.Table_Boolean;
with GNAT.Spitbol.Table_VString; use GNAT.Spitbol.Table_VString;
procedure XTreeprs is
package TB renames GNAT.Spitbol.Table_Boolean;
package TV renames GNAT.Spitbol.Table_VString;
Err : exception;
-- Raised on fatal error
A : VString := Nul;
Ffield : VString := Nul;
Field : VString := Nul;
Fieldno : VString := Nul;
Flagno : VString := Nul;
Line : VString := Nul;
Name : VString := Nul;
Node : VString := Nul;
Outstring : VString := Nul;
Prefix : VString := Nul;
S : VString := Nul;
S1 : VString := Nul;
Sinforev : VString := Nul;
Syn : VString := Nul;
Synonym : VString := Nul;
Temprev : VString := Nul;
Term : VString := Nul;
Treeprsrev : VString := Nul;
OutS : File_Type;
-- Output file
InS : File_Type;
-- Read sinfo.ads
InT : File_Type;
-- Read treeprs.adt
Special : TB.Table (20);
-- Table of special fields. These fields are not included in the table
-- constructed by Xtreeprs, since they are specially handled in treeprs.
-- This means these field definitions are completely ignored.
Names : array (1 .. 500) of VString;
-- Table of names of synonyms
Positions : array (1 .. 500) of Natural;
-- Table of starting positions in Pchars string for synonyms
Strings : TV.Table (300);
-- Contribution of each synonym to Pchars string, indexed by name
Count : Natural := 0;
-- Number of synonyms processed so far
Curpos : Natural := 1;
-- Number of characters generated in Pchars string so far
Lineno : Natural := 0;
-- Line number in sinfo.ads
Field_Base : constant := Character'Pos ('#');
-- Fields 1-5 are represented by the characters #$%&' (i.e. by five
-- contiguous characters starting at # (16#23#)).
Flag_Base : constant := Character'Pos ('(');
-- Flags 1-18 are represented by the characters ()*+,-./0123456789
-- (i.e. by 18 contiguous characters starting at (16#28#)).
Fieldch : Character;
-- Field character, as per above tables
Sp : aliased Natural;
-- Space left on line for Pchars output
wsp : Pattern := Span (' ' & ASCII.HT);
Get_SRev : Pattern := BreakX ('$') & "$Rev" & "ision: "
& Break (' ') * Sinforev;
Get_TRev : Pattern := BreakX ('$') & "$Rev" & "ision: "
& Break (' ') * Temprev;
Is_Temp : Pattern := BreakX ('T') * A & "T e m p l a t e";
Get_Node : Pattern := wsp & "-- N_" & Rest * Node;
Tst_Punc : Pattern := Break (" ,.");
Get_Syn : Pattern := Span (' ') & "-- " & Break (' ') * Synonym
& " (" & Break (')') * Field;
Brk_Min : Pattern := Break ('-') * Ffield;
Is_Flag : Pattern := "Flag" & Rest * Flagno;
Is_Field : Pattern := Rtab (1) & Len (1) * Fieldno;
Is_Syn : Pattern := wsp & "N_" & Break (",)") * Syn & Len (1) * Term;
Brk_Node : Pattern := Break (' ') * Node & ' ';
Chop_SP : Pattern := Len (Sp'Unrestricted_Access) * S1;
M : Match_Result;
begin
Anchored_Mode := True;
Match ("$Revision$",
"$Rev" & "ision: " & Break (' ') * Treeprsrev);
if Argument_Count > 0 then
Create (OutS, Out_File, Argument (1));
else
Create (OutS, Out_File, "treeprs.ads");
end if;
Open (InS, In_File, "sinfo.ads");
Open (InT, In_File, "treeprs.adt");
-- Initialize special fields table
Set (Special, "Analyzed", True);
Set (Special, "Cannot_Be_Constant", True);
Set (Special, "Chars", True);
Set (Special, "Comes_From_Source", True);
Set (Special, "Error_Posted", True);
Set (Special, "Etype", True);
Set (Special, "Has_No_Side_Effects", True);
Set (Special, "Is_Controlling_Actual", True);
Set (Special, "Is_Overloaded", True);
Set (Special, "Is_Static_Expression", True);
Set (Special, "Left_Opnd", True);
Set (Special, "Must_Check_Expr", True);
Set (Special, "No_Overflow_Expr", True);
Set (Special, "Paren_Count", True);
Set (Special, "Raises_Constraint_Error", True);
Set (Special, "Right_Opnd", True);
-- Get sinfo revs and write header to output file
loop
Line := Get_Line (InS);
Lineno := Lineno + 1;
if Line = "" then
raise Err;
end if;
exit when Match (Line, Get_SRev);
end loop;
-- Read template header and generate new header
loop
Line := Get_Line (InT);
if Match (Line, Get_TRev) then
Put_Line
(OutS,
"-- Generated by xtreeprs revision " &
Treeprsrev & " using");
Put_Line
(OutS,
"-- sinfo.ads revision " &
Sinforev);
Put_Line
(OutS,
"-- treeprs.adt revision "
& Temprev);
else
-- Skip lines describing the template
if Match (Line, "-- This file is a template") then
loop
Line := Get_Line (InT);
exit when Line = "";
end loop;
end if;
exit when Match (Line, "package");
if Match (Line, Is_Temp, M) then
Replace (M, A & " S p e c ");
end if;
Put_Line (OutS, Line);
end if;
end loop;
Put_Line (OutS, Line);
-- Copy rest of comments up to template insert point to spec
loop
Line := Get_Line (InT);
exit when Match (Line, "!!TEMPLATE INSERTION POINT");
Put_Line (OutS, Line);
end loop;
-- Here we are doing the actual insertions
Put_Line (OutS, " Pchars : constant String :=");
-- Loop through comments describing nodes, picking up fields
loop
Line := Get_Line (InS);
Lineno := Lineno + 1;
exit when Match (Line, " type Node_Kind");
if Match (Line, Get_Node)
and then not Match (Node, Tst_Punc)
then
Outstring := Node & ' ';
loop
Line := Get_Line (InS);
exit when Line = "";
if Match (Line, Get_Syn)
and then not Match (Synonym, "plus")
and then not Present (Special, Synonym)
then
-- Convert this field into the character used to
-- represent the field according to the table:
-- Field1 '#'
-- Field2 '$'
-- Field3 '%'
-- Field4 '&'
-- Field5 "'"
-- Flag1 "("
-- Flag2 ")"
-- Flag3 '*'
-- Flag4 '+'
-- Flag5 ','
-- Flag6 '-'
-- Flag7 '.'
-- Flag8 '/'
-- Flag9 '0'
-- Flag10 '1'
-- Flag11 '2'
-- Flag12 '3'
-- Flag13 '4'
-- Flag14 '5'
-- Flag15 '6'
-- Flag16 '7'
-- Flag17 '8'
-- Flag18 '9'
if Match (Field, Brk_Min) then
Field := Ffield;
end if;
if Match (Field, Is_Flag) then
Fieldch := Char (Flag_Base - 1 + N (Flagno));
elsif Match (Field, Is_Field) then
Fieldch := Char (Field_Base - 1 + N (Fieldno));
else
Put_Line
(Standard_Error,
"*** Line " &
Lineno &
" has unrecognized field name " &
Field);
raise Err;
end if;
Append (Outstring, Fieldch & Synonym);
end if;
end loop;
Set (Strings, Node, Outstring);
end if;
end loop;
-- Loop through actual definitions of node kind enumeration literals
loop
loop
Line := Get_Line (InS);
Lineno := Lineno + 1;
exit when Match (Line, Is_Syn);
end loop;
S := Get (Strings, Syn);
Match (S, Brk_Node, "");
Count := Count + 1;
Names (Count) := Syn;
Positions (Count) := Curpos;
Curpos := Curpos + Length (S);
Put_Line (OutS, " -- " & Node);
Prefix := V (" ");
exit when Term = ")";
-- Loop to output the string literal for Pchars
loop
Sp := 79 - 4 - Length (Prefix);
exit when (Size (S) <= Sp);
Match (S, Chop_SP, "");
Put_Line (OutS, Prefix & '"' & S1 & """ &");
Prefix := V (" ");
end loop;
Put_Line (OutS, Prefix & '"' & S & """ &");
end loop;
Put_Line (OutS, " """";");
Put_Line (OutS, "");
Put_Line
(OutS, " type Pchar_Pos_Array is array (Node_Kind) of Positive;");
Put_Line
(OutS,
" Pchar_Pos : constant Pchar_Pos_Array := Pchar_Pos_Array'(");
-- Output lines for Pchar_Pos_Array values
for M in 1 .. Count - 1 loop
Name := Rpad ("N_" & Names (M), 40);
Put_Line (OutS, " " & Name & " => " & Positions (M) & ',');
end loop;
Name := Rpad ("N_" & Names (Count), 40);
Put_Line (OutS, " " & Name & " => " & Positions (Count) & ");");
Put_Line (OutS, "");
Put_Line (OutS, "end Treeprs;");
exception
when Err =>
Put_Line (Standard_Error, "*** fatal error");
Set_Exit_Status (1);
end XTreeprs;
|
-- CC3004A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK THAT ACTUAL PARAMETERS IN A NAMED GENERIC ACTUAL PARAMETER
-- ASSOCIATION MAY BE OUT OF ORDER, AND ARE ASSOCIATED WITH THE
-- CORRECT FORMALS.
-- DAT 9/16/81
-- SPS 10/26/82
WITH REPORT; USE REPORT;
PROCEDURE CC3004A IS
BEGIN
TEST ("CC3004A", "ORDER OF NAMED GENERIC ACTUAL PARAMETERS");
DECLARE
GENERIC
A,B : INTEGER;
C : INTEGER;
D : INTEGER;
PACKAGE P1 IS END P1;
TYPE AI IS ACCESS INTEGER;
GENERIC
TYPE D IS ( <> );
VD : D;
TYPE AD IS ACCESS D;
VA : AD;
PACKAGE P2 IS END P2;
X : AI := NEW INTEGER '(IDENT_INT(23));
Y : AI := NEW INTEGER '(IDENT_INT(77));
PACKAGE BODY P1 IS
BEGIN
IF A /= IDENT_INT(4) OR
B /= IDENT_INT(12) OR
C /= IDENT_INT(11) OR
D /= IDENT_INT(-33)
THEN
FAILED ("WRONG GENERIC PARAMETER ASSOCIATIONS");
END IF;
END P1;
PACKAGE BODY P2 IS
BEGIN
IF VA.ALL /= VD THEN
FAILED ("WRONG GENERIC PARM ASSOCIATIONS 2");
END IF;
END P2;
PACKAGE N1 IS NEW P1 (C => 11, A => 4, D => -33, B => 12);
PACKAGE N2 IS NEW P2 (VA => X, AD => AI, D => INTEGER,
VD => 23);
PACKAGE N3 IS NEW P2 (INTEGER, 77, VA => Y, AD => AI);
BEGIN
NULL;
END;
RESULT;
END CC3004A;
|
-- Generated by Snowball 2.2.0 - https://snowballstem.org/
package body Stemmer.Danish is
pragma Style_Checks ("-mr");
pragma Warnings (Off, "*variable*is never read and never assigned*");
pragma Warnings (Off, "*mode could be*instead of*");
pragma Warnings (Off, "*formal parameter.*is not modified*");
pragma Warnings (Off, "*this line is too long*");
pragma Warnings (Off, "*is not referenced*");
procedure R_Undouble (Z : in out Context_Type; Result : out Boolean);
procedure R_Other_suffix (Z : in out Context_Type; Result : out Boolean);
procedure R_Consonant_pair (Z : in out Context_Type; Result : out Boolean);
procedure R_Main_suffix (Z : in out Context_Type; Result : out Boolean);
procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean);
G_C : constant Grouping_Array (0 .. 31) := (
True, True, True, False, True, True, True, False,
True, True, True, True, True, False, True, True,
True, True, True, False, True, True, True, False,
True, False, False, False, False, False, False, False
);
G_V : constant Grouping_Array (0 .. 151) := (
True, False, False, False, True, False, False, False,
True, False, False, False, False, False, True, False,
False, False, False, False, True, False, False, False,
True, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, True, True, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, True
);
G_S_ending : constant Grouping_Array (0 .. 135) := (
True, True, True, True, False, True, True, True,
False, True, True, True, True, True, True, True,
False, True, False, True, False, True, False, False,
True, True, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False,
False, False, False, False, True, False, False, False
);
Among_String : constant String := "hed" & "ethed" & "ered" & "e" & "erede"
& "ende" & "erende" & "ene" & "erne" & "ere" & "en" & "heden" & "eren" & "er"
& "heder" & "erer" & "s" & "heds" & "es" & "endes" & "erendes" & "enes" & "ernes"
& "eres" & "ens" & "hedens" & "erens" & "ers" & "ets" & "erets" & "et" & "eret"
& "gd" & "dt" & "gt" & "kt" & "ig" & "lig" & "elig" & "els" & "løst";
A_0 : constant Among_Array_Type (0 .. 31) := (
(1, 3, -1, 1, 0),
(4, 8, 0, 1, 0),
(9, 12, -1, 1, 0),
(13, 13, -1, 1, 0),
(14, 18, 3, 1, 0),
(19, 22, 3, 1, 0),
(23, 28, 5, 1, 0),
(29, 31, 3, 1, 0),
(32, 35, 3, 1, 0),
(36, 38, 3, 1, 0),
(39, 40, -1, 1, 0),
(41, 45, 10, 1, 0),
(46, 49, 10, 1, 0),
(50, 51, -1, 1, 0),
(52, 56, 13, 1, 0),
(57, 60, 13, 1, 0),
(61, 61, -1, 2, 0),
(62, 65, 16, 1, 0),
(66, 67, 16, 1, 0),
(68, 72, 18, 1, 0),
(73, 79, 19, 1, 0),
(80, 83, 18, 1, 0),
(84, 88, 18, 1, 0),
(89, 92, 18, 1, 0),
(93, 95, 16, 1, 0),
(96, 101, 24, 1, 0),
(102, 106, 24, 1, 0),
(107, 109, 16, 1, 0),
(110, 112, 16, 1, 0),
(113, 117, 28, 1, 0),
(118, 119, -1, 1, 0),
(120, 123, 30, 1, 0));
A_1 : constant Among_Array_Type (0 .. 3) := (
(124, 125, -1, -1, 0),
(126, 127, -1, -1, 0),
(128, 129, -1, -1, 0),
(130, 131, -1, -1, 0));
A_2 : constant Among_Array_Type (0 .. 4) := (
(132, 133, -1, 1, 0),
(134, 136, 0, 1, 0),
(137, 140, 1, 1, 0),
(141, 143, -1, 1, 0),
(144, 148, -1, 2, 0));
procedure R_Mark_regions (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
begin
-- (, line 31
Z.I_P1 := Z.L;
-- test, line 35
v_1 := Z.C;
-- (, line 35
C := Skip_Utf8 (Z, 3); -- hop, line 35
if C < 0 then
Result := False;
return;
end if;
Z.C := C;
-- setmark x, line 35
Z.I_X := Z.C;
Z.C := v_1;
-- goto, line 36
Out_Grouping (Z, G_V, 97, 248, True, C); if C < 0 then
Result := False;
return;
end if;
-- gopast, line 36
-- non v, line 36
In_Grouping (Z, G_V, 97, 248, True, C);
if C < 0 then
Result := False;
return;
end if;
Z.C := Z.C + C;
-- setmark p1, line 36
Z.I_P1 := Z.C;
-- try, line 37
-- (, line 37
if not (Z.I_P1 < Z.I_X) then
goto lab2;
end if;
Z.I_P1 := Z.I_X;
<<lab2>>
Result := True;
end R_Mark_regions;
procedure R_Main_suffix (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_2 : Integer;
begin
-- (, line 42
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_2 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 43
Z.Ket := Z.C; -- [, line 43
-- substring, line 43
if Z.C <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#1c4030#) then
Z.Lb := v_2;
Result := False;
return;
-- substring, line 43
end if;
Find_Among_Backward (Z, A_0, Among_String, null, A);
if A = 0 then
Z.Lb := v_2;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 43
Z.Lb := v_2;
-- among, line 44
case A is
when 1 =>
-- (, line 50
-- delete, line 50
Slice_Del (Z);
when 2 =>
-- (, line 52
In_Grouping_Backward (Z, G_S_ending, 97, 229, False, C);
if C /= 0 then
Result := False;
return;
end if;
-- delete, line 52
Slice_Del (Z);
when others =>
null;
end case;
Result := True;
end R_Main_suffix;
procedure R_Consonant_pair (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
v_3 : Integer;
begin
-- (, line 56
-- test, line 57
v_1 := Z.L - Z.C;
-- (, line 57
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_3 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 58
Z.Ket := Z.C; -- [, line 58
-- substring, line 58
if Z.C - 1 <= Z.Lb or else (Character'Pos (Z.P (Z.C)) /= 100 and then Character'Pos (Z.P (Z.C)) /= 116) then
Z.Lb := v_3;
Result := False;
return;
-- substring, line 58
end if;
Find_Among_Backward (Z, A_1, Among_String, null, A);
if A = 0 then
Z.Lb := v_3;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 58
Z.Lb := v_3;
Z.C := Z.L - v_1;
-- next, line 64
C := Skip_Utf8_Backward (Z);
if C < 0 then
Result := False;
return;
end if;
Z.C := C;
Z.Bra := Z.C; -- ], line 64
-- delete, line 64
Slice_Del (Z);
Result := True;
end R_Consonant_pair;
procedure R_Other_suffix (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
v_3 : Integer;
v_4 : Char_Index;
begin
-- (, line 67
-- do, line 68
v_1 := Z.L - Z.C;
-- (, line 68
Z.Ket := Z.C; -- [, line 68
-- literal, line 68
C := Eq_S_Backward (Z, "st");
if C = 0 then
goto lab0;
end if;
Z.C := Z.C - C;
Z.Bra := Z.C; -- ], line 68
-- literal, line 68
C := Eq_S_Backward (Z, "ig");
if C = 0 then
goto lab0;
end if;
Z.C := Z.C - C;
-- delete, line 68
Slice_Del (Z);
<<lab0>>
Z.C := Z.L - v_1;
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_3 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 69
Z.Ket := Z.C; -- [, line 69
-- substring, line 69
if Z.C - 1 <= Z.Lb or else Check_Among (Z, Z.C - 1, 3, 16#180080#) then
Z.Lb := v_3;
Result := False;
return;
-- substring, line 69
end if;
Find_Among_Backward (Z, A_2, Among_String, null, A);
if A = 0 then
Z.Lb := v_3;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 69
Z.Lb := v_3;
-- among, line 70
case A is
when 1 =>
-- (, line 72
-- delete, line 72
Slice_Del (Z);
-- do, line 72
v_4 := Z.L - Z.C;
-- call consonant_pair, line 72
R_Consonant_pair (Z, Result);
Z.C := Z.L - v_4;
when 2 =>
-- (, line 74
-- <-, line 74
Slice_From (Z, "løs");
when others =>
null;
end case;
Result := True;
end R_Other_suffix;
procedure R_Undouble (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_2 : Integer;
begin
-- (, line 77
if Z.C < Z.I_P1 then
Result := False;
return;
end if;
v_2 := Z.Lb; Z.Lb := Z.I_P1;
-- (, line 78
Z.Ket := Z.C; -- [, line 78
In_Grouping_Backward (Z, G_C, 98, 122, False, C);
if C /= 0 then
Z.Lb := v_2;
Result := False;
return;
end if;
Z.Bra := Z.C; -- ], line 78
-- -> ch, line 78
Z.S_Ch := Ada.Strings.Unbounded.To_Unbounded_String (Slice_To (Z));
Z.Lb := v_2;
-- name ch, line 79
C := Eq_S_Backward (Z, Ada.Strings.Unbounded.To_String (Z.S_Ch)); if C = 0 then
Result := False;
return;
end if;
-- delete, line 80
Slice_Del (Z);
Result := True;
end R_Undouble;
procedure Stem (Z : in out Context_Type; Result : out Boolean) is
C : Result_Index;
A : Integer;
v_1 : Char_Index;
v_2 : Char_Index;
v_3 : Char_Index;
v_4 : Char_Index;
v_5 : Char_Index;
begin
-- (, line 84
-- do, line 86
v_1 := Z.C;
-- call mark_regions, line 86
R_Mark_regions (Z, Result);
Z.C := v_1;
Z.Lb := Z.C; Z.C := Z.L; -- backwards, line 87
-- (, line 87
-- do, line 88
v_2 := Z.L - Z.C;
-- call main_suffix, line 88
R_Main_suffix (Z, Result);
Z.C := Z.L - v_2;
-- do, line 89
v_3 := Z.L - Z.C;
-- call consonant_pair, line 89
R_Consonant_pair (Z, Result);
Z.C := Z.L - v_3;
-- do, line 90
v_4 := Z.L - Z.C;
-- call other_suffix, line 90
R_Other_suffix (Z, Result);
Z.C := Z.L - v_4;
-- do, line 91
v_5 := Z.L - Z.C;
-- call undouble, line 91
R_Undouble (Z, Result);
Z.C := Z.L - v_5;
Z.C := Z.Lb;
Result := True;
end Stem;
end Stemmer.Danish;
|
-----------------------------------------------------------------------
-- util-processes-tests - Test for processes
-- Copyright (C) 2011, 2012, 2016, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Test_Caller;
with Util.Files;
with Util.Strings.Vectors;
with Util.Streams.Pipes;
with Util.Streams.Buffered;
with Util.Streams.Texts;
with Util.Processes.Tools;
package body Util.Processes.Tests is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Tests");
package Caller is new Util.Test_Caller (Test, "Processes");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Processes.Is_Running",
Test_No_Process'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Wait/Get_Exit_Status",
Test_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(READ pipe)",
Test_Output_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(WRITE pipe)",
Test_Input_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn/Shell(WRITE pipe)",
Test_Shell_Splitting_Pipe'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(OUTPUT redirect)",
Test_Output_Redirect'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Spawn(INPUT redirect)",
Test_Input_Redirect'Access);
Caller.Add_Test (Suite, "Test Util.Streams.Pipes.Open/Read/Close (Multi spawn)",
Test_Multi_Spawn'Access);
Caller.Add_Test (Suite, "Test Util.Processes.Tools.Execute",
Test_Tools_Execute'Access);
end Add_Tests;
-- ------------------------------
-- Tests when the process is not launched
-- ------------------------------
procedure Test_No_Process (T : in out Test) is
P : Process;
begin
T.Assert (not P.Is_Running, "Process should not be running");
T.Assert (P.Get_Pid < 0, "Invalid process id");
end Test_No_Process;
-- ------------------------------
-- Test executing a process
-- ------------------------------
procedure Test_Spawn (T : in out Test) is
P : Process;
begin
-- Launch the test process => exit code 2
P.Spawn ("bin/util_test_process");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 2, P.Get_Exit_Status, "Invalid exit status");
-- Launch the test process => exit code 0
P.Spawn ("bin/util_test_process 0 write b c d e f");
T.Assert (P.Is_Running, "Process is running");
P.Wait;
T.Assert (not P.Is_Running, "Process has stopped");
T.Assert (P.Get_Pid > 0, "Invalid process id");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Spawn;
-- ------------------------------
-- Test output pipe redirection: read the process standard output
-- ------------------------------
procedure Test_Output_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write b c d e f test_marker");
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b\s+c\s+d\s+e\s+f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Output_Pipe;
-- ------------------------------
-- Test shell splitting.
-- ------------------------------
procedure Test_Shell_Splitting_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 write ""b c d e f"" test_marker");
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
P.Close;
Util.Tests.Assert_Matches (T, "b c d e f\s+test_marker\s+", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Shell_Splitting_Pipe;
-- ------------------------------
-- Test input pipe redirection: write the process standard input
-- At the same time, read the process standard output.
-- ------------------------------
procedure Test_Input_Pipe (T : in out Test) is
P : aliased Util.Streams.Pipes.Pipe_Stream;
begin
P.Open ("bin/util_test_process 0 read -", READ_WRITE);
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
Print : Util.Streams.Texts.Print_Stream;
begin
-- Write on the process input stream.
Print.Initialize (P'Unchecked_Access);
Print.Write ("Write test on the input pipe");
Print.Close;
-- Read the output.
Buffer.Initialize (P'Unchecked_Access, 19);
Buffer.Read (Content);
-- Wait for the process to finish.
P.Close;
Util.Tests.Assert_Matches (T, "Write test on the input pipe-\s", Content,
"Invalid content");
end;
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Invalid exit status");
end Test_Input_Pipe;
-- ------------------------------
-- Test launching several processes through pipes in several threads.
-- ------------------------------
procedure Test_Multi_Spawn (T : in out Test) is
Task_Count : constant Natural := 8;
Count_By_Task : constant Natural := 10;
type State_Array is array (1 .. Task_Count) of Boolean;
States : State_Array;
begin
declare
task type Worker is
entry Start (Count : in Natural);
entry Result (Status : out Boolean);
end Worker;
task body Worker is
Cnt : Natural;
State : Boolean := True;
begin
accept Start (Count : in Natural) do
Cnt := Count;
end Start;
declare
type Pipe_Array is array (1 .. Cnt) of aliased Util.Streams.Pipes.Pipe_Stream;
Pipes : Pipe_Array;
begin
-- Launch the processes.
-- They will print their arguments on stdout, one by one on each line.
-- The expected exit status is the first argument.
for I in 1 .. Cnt loop
Pipes (I).Open ("bin/util_test_process 0 write b c d e f test_marker");
end loop;
-- Read their output
for I in 1 .. Cnt loop
declare
Buffer : Util.Streams.Buffered.Input_Buffer_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Buffer.Initialize (Pipes (I)'Unchecked_Access, 19);
Buffer.Read (Content);
Pipes (I).Close;
-- Check status and output.
State := State and Pipes (I).Get_Exit_Status = 0;
State := State and Ada.Strings.Unbounded.Index (Content, "test_marker") > 0;
end;
end loop;
exception
when E : others =>
Log.Error ("Exception raised", E);
State := False;
end;
accept Result (Status : out Boolean) do
Status := State;
end Result;
end Worker;
type Worker_Array is array (1 .. Task_Count) of Worker;
Tasks : Worker_Array;
begin
for I in Tasks'Range loop
Tasks (I).Start (Count_By_Task);
end loop;
-- Get the results (do not raise any assertion here because we have to call
-- 'Result' to ensure the thread terminates.
for I in Tasks'Range loop
Tasks (I).Result (States (I));
end loop;
-- Leaving the Worker task scope means we are waiting for our tasks to finish.
end;
for I in States'Range loop
T.Assert (States (I), "Task " & Natural'Image (I) & " failed");
end loop;
end Test_Multi_Spawn;
-- ------------------------------
-- Test output file redirection.
-- ------------------------------
procedure Test_Output_Redirect (T : in out Test) is
P : Process;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/proc-output.txt");
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Util.Processes.Set_Output_Stream (P, Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 write b c d e f test_marker");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*test_marker", Content,
"Invalid content");
Util.Processes.Set_Output_Stream (P, Path, True);
Util.Processes.Spawn (P, "bin/util_test_process 0 write appended_text");
Util.Processes.Wait (P);
Content := Ada.Strings.Unbounded.Null_Unbounded_String;
Util.Files.Read_File (Path, Content);
Util.Tests.Assert_Matches (T, ".*appended_text", Content,
"Invalid content");
Util.Tests.Assert_Matches (T, ".*test_marker.*", Content,
"Invalid content");
end Test_Output_Redirect;
-- ------------------------------
-- Test input file redirection.
-- ------------------------------
procedure Test_Input_Redirect (T : in out Test) is
P : Process;
In_Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/proc-input.txt");
Out_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/proc-inres.txt");
Exp_Path : constant String := Util.Tests.Get_Test_Path ("regtests/expect/proc-inres.txt");
begin
Util.Processes.Set_Input_Stream (P, In_Path);
Util.Processes.Set_Output_Stream (P, Out_Path);
Util.Processes.Spawn (P, "bin/util_test_process 0 read -");
Util.Processes.Wait (P);
T.Assert (not P.Is_Running, "Process has stopped");
Util.Tests.Assert_Equals (T, 0, P.Get_Exit_Status, "Process failed");
Util.Tests.Assert_Equal_Files (T => T,
Expect => Exp_Path,
Test => Out_Path,
Message => "Process input/output redirection");
end Test_Input_Redirect;
-- ------------------------------
-- Test the Tools.Execute operation.
-- ------------------------------
procedure Test_Tools_Execute (T : in out Test) is
List : Util.Strings.Vectors.Vector;
Status : Integer;
begin
Tools.Execute (Command => "bin/util_test_process 23 write ""b c d e f"" test_marker",
Output => List,
Status => Status);
Util.Tests.Assert_Equals (T, 23, Status, "Invalid exit status");
Util.Tests.Assert_Equals (T, 2, Integer (List.Length),
"Invalid output collected by Execute");
Util.Tests.Assert_Equals (T, "b c d e f", List.Element (1), "");
Util.Tests.Assert_Equals (T, "test_marker", List.Element (2), "");
end Test_Tools_Execute;
end Util.Processes.Tests;
|
with Test_Directories; use Test_Directories;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Bitmap; use Bitmap;
with Bitmap.Buffer; use Bitmap.Buffer;
with Bitmap.File_IO; use Bitmap.File_IO;
with Bitmap.Memory_Mapped; use Bitmap.Memory_Mapped;
procedure TC_BMP_File_Input is
function Bitmaps_Equal return Boolean;
function Allocate_Bitmap return not null Any_Bitmap_Buffer;
BM_Width : constant := 100;
BM_Height : constant := 100;
---------------------
-- Allocate_Bitmap --
---------------------
function Allocate_Bitmap return not null Any_Bitmap_Buffer is
type Pixel_Data is new Bitmap.UInt16_Array (1 .. BM_Height * BM_Height) with Pack;
type Pixel_Data_Access is access Pixel_Data;
BM : constant Any_Memory_Mapped_Bitmap_Buffer := new Memory_Mapped_Bitmap_Buffer;
Data : constant Pixel_Data_Access := new Pixel_Data;
begin
BM.Actual_Width := BM_Width;
BM.Actual_Height := BM_Height;
BM.Actual_Color_Mode := RGB_565;
BM.Currently_Swapped := False;
BM.Addr := Data.all'Address;
return Any_Bitmap_Buffer (BM);
end Allocate_Bitmap;
BMP_File : Ada.Streams.Stream_IO.File_Type;
BM1 : constant not null Any_Bitmap_Buffer := Allocate_Bitmap;
BM2 : Any_Bitmap_Buffer;
-------------------
-- Bitmaps_Equal --
-------------------
function Bitmaps_Equal return Boolean is
RGB_Pix1, RGB_Pix2 : Bitmap_Color;
begin
if BM1.Width /= BM2.Width then return False; end if;
if BM1.Height /= BM2.Height then return False; end if;
for Y in 0 .. BM1.Height - 1 loop
for X in 0 .. BM1.Width - 1 loop
RGB_Pix1 := BM1.Pixel ((X, Y));
RGB_Pix2 := BM2.Pixel ((X, Y));
if RGB_Pix1.Red /= RGB_Pix2.Red then return False; end if;
if RGB_Pix1.Green /= RGB_Pix2.Green then return False; end if;
if RGB_Pix1.Blue /= RGB_Pix2.Blue then return False; end if;
end loop;
end loop;
return True;
end Bitmaps_Equal;
begin
BM1.Fill (Black);
BM1.Fill_Rounded_Rect (Color => Green,
Area => ((5, 5), BM_Width / 2, BM_Height / 2),
Radius => 10);
BM1.Draw_Rounded_Rect (Color => Red,
Area => ((5, 5), BM_Width / 2, BM_Height / 2),
Radius => 10,
Thickness => 3);
BM1.Fill_Circle (Color => Yellow,
Center => (BM_Width / 2, BM_Height / 2),
Radius => BM_Width / 4);
BM1.Draw_Circle (Color => Blue,
Center => (BM_Width / 2, BM_Height / 2),
Radius => BM_Width / 4);
BM1.Cubic_Bezier (Color => Violet,
P1 => (5, 5),
P2 => (0, BM_Height / 2),
P3 => (BM_Width / 2, BM_Height / 2),
P4 => (BM_Width - 5, BM_Height - 5),
N => 100,
Thickness => 3);
BM1.Draw_Line (Color => White,
Start => (0, 0),
Stop => (BM_Width - 1, BM_Height / 2),
Thickness => 1,
Fast => True);
BM1.Set_Pixel ((0, 0), Red);
BM1.Set_Pixel ((0, 1), Green);
BM1.Set_Pixel ((0, 2), Blue);
Copy_Rect (Src_Buffer => BM1.all,
Src_Pt => (0, 0),
Dst_Buffer => BM1.all,
Dst_Pt => (0, BM_Height / 2 + 10),
Width => BM_Width / 4,
Height => BM_Height / 4,
Synchronous => True);
Open (File => BMP_File, Mode => In_File, Name => Test_Dir & "/ref.bmp");
BM2 := Read_BMP_File (BMP_File);
Close (BMP_File);
if not Bitmaps_Equal
then
Put_Line ("BMP file reading test FAILED.");
Put_Line ("Input BMP content is different than generated drawing.");
Put_Line ("This could mean that:");
Put_Line (" 1 - Bitmap drawing is broken");
Put_Line (" 2 - Bitmap file input is broken");
Put_Line (" 3 - You changed/improved bitmap drawing");
New_Line;
Put_Line ("When 1 or 2, please fix the problem,");
Put_Line ("When 3 please update the reference bitmap and exaplaining" &
" the changes you made.");
else
Put_Line ("BMP file reading test OK");
end if;
end TC_BMP_File_Input;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.