id
int64 0
30.9k
| extension
stringclasses 1
value | max_stars_count
int64 0
17k
| max_stars_repo_name
stringlengths 7
106
| max_stars_repo_path
stringlengths 5
136
| text
stringlengths 9
1M
|
|---|---|---|---|---|---|
30,700
|
ada
| 33
|
persan/zeromq-Ada
|
src/zmq-proxys.adb
|
-------------------------------------------------------------------------------
-- --
-- 0MQ Ada-binding --
-- --
-- Z M Q . P R O X Y S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2020-2030, <EMAIL> --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files --
-- (the "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, sublicense, and / or sell copies of the Software, and to --
-- permit persons to whom the Software is furnished to do so, subject to --
-- the following conditions : --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, --
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL --
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR --
-- OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, --
-- ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR --
-- OTHER DEALINGS IN THE SOFTWARE. --
-------------------------------------------------------------------------------
with ZMQ.Low_Level;
with Interfaces.C; use Interfaces.C;
with System; use System;
package body ZMQ.Proxys is
--
-----------
-- Proxy --
-----------
procedure Proxy
(Frontend : not null access Sockets.Socket;
Backend : not null access Sockets.Socket;
Capture : access Sockets.Socket := null)
is
Dummy : int;
pragma Unreferenced (Dummy);
begin
Dummy := ZMQ.Low_Level.zmq_proxy
(Frontend.Get_Impl, Backend.Get_Impl,
(if Capture /= null then Capture.Get_Impl else System.Null_Address));
end Proxy;
end ZMQ.Proxys;
|
30,701
|
ada
| 8
|
flyx/OpenCLAda
|
src/implementation/cl_gl/win/cl-contexts-cl_gl.adb
|
--------------------------------------------------------------------------------
-- Copyright (c) 2013, <NAME> <<EMAIL>>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--------------------------------------------------------------------------------
with CL.API;
with CL.Helpers;
with CL.Enumerations;
with GL.WGL;
-- Windows-specific implementation
package body CL.Contexts.CL_GL is
CL_GL_CONTEXT_KHR : constant := 16#2008#;
CL_WGL_HDC_KHR : constant := 16#200B#;
package body Constructors is
function Create (Platform : Platforms.Platform;
Devices : Platforms.Device_List;
Callback : Error_Callback := null)
return Context is
Props : Address_List := (Value (CL_GL_CONTEXT_KHR),
System.Address (GL.WGL.wglGetCurrentContext),
Value (CL_WGL_HDC_KHR),
System.Address (GL.WGL.wglGetCurrentDC),
Value (Platform_Identifier),
CL_Object (Platform).Location,
System.Null_Address);
Ret_Context : System.Address;
Error : aliased Enumerations.Error_Code;
function Raw_Device_List is
new Helpers.Raw_List (Element_T => Platforms.Device,
Element_List_T => Platforms.Device_List);
Raw_List : Address_List := Raw_Device_List (Devices);
function Address is new
Ada.Unchecked_Conversion (Source => Error_Callback,
Target => System.Address);
begin
Ret_Context := API.Create_Context (Props (1)'Unchecked_Access,
Devices'Length,
Raw_List (1)'Address,
Callback_Dispatcher'Access,
Address (Callback),
Error'Unchecked_Access);
Helpers.Error_Handler (Error);
return Context'(Ada.Finalization.Controlled
with Location => Ret_Context);
end Create;
end Constructors;
end CL.Contexts.CL_GL;
|
30,702
|
ada
| 7
|
stcarrez/mat
|
mat/regtests/mat-targets-tests.adb
|
-----------------------------------------------------------------------
-- mat-readers-tests -- Unit tests for MAT readers
-- Copyright (C) 2014, 2015, 2019, 2021 <NAME>
-- Written by <NAME> (<EMAIL>)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with MAT.Readers.Streams.Files;
package body MAT.Targets.Tests is
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test MAT.Targets.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test MAT.Types.Tick_Value",
Test_Conversions'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
pragma Unreferenced (T);
Path : constant String := Util.Tests.Get_Path ("regtests/files/file-v1.dat");
Target : MAT.Targets.Target_Type;
Reader : MAT.Readers.Streams.Files.File_Reader_Type;
begin
Target.Initialize (Reader);
Reader.Open (Path);
Reader.Read_All;
end Test_Read_File;
-- ------------------------------
-- Test various type conversions.
-- ------------------------------
procedure Test_Conversions (T : in out Test) is
use MAT.Types;
Time : MAT.Types.Target_Tick_Ref;
begin
Time := MAT.Types.Tick_Value ("1.1");
Util.Tests.Assert_Equals (T, 1, Natural (Time / 1_000000), "Invalid Tick_Value conversion");
Util.Tests.Assert_Equals (T, 100_000, Natural (Time mod 1_000000),
"Invalid Tick_Value conversion");
Time := MAT.Types.Tick_Value ("12.001234");
Util.Tests.Assert_Equals (T, 12, Natural (Time / 1_000000), "Invalid Tick_Value conversion");
Util.Tests.Assert_Equals (T, 1_234, Natural (Time mod 1_000000),
"Invalid Tick_Value conversion");
end Test_Conversions;
end MAT.Targets.Tests;
|
30,703
|
ada
| 2
|
persan/gprTools
|
src/gpr_tools-gprslaves-db-json.ads
|
<reponame>persan/gprTools<gh_stars>1-10
with GNATCOLL.JSON;
package GPR_Tools.Gprslaves.DB.JSON is
function Create (Item : Info_Struct) return GNATCOLL.JSON.JSON_Value;
function Create (Item : Host_Address) return GNATCOLL.JSON.JSON_Value;
function Create (Item : GNAT.Spitbol.Table_VString.Table) return GNATCOLL.JSON.JSON_Value;
function Create (Item : Host_Info_Vectors.Vector) return GNATCOLL.JSON.JSON_Value;
function Create (Item : GNAT.Spitbol.Table_VString.Table_Entry) return GNATCOLL.JSON.JSON_Value;
function Get (Item : GNATCOLL.JSON.JSON_Value) return Info_Struct;
function Get (Item : GNATCOLL.JSON.JSON_Value) return Host_Address;
function Get (Item : GNATCOLL.JSON.JSON_Value) return GNAT.Spitbol.Table_VString.Table;
function Get (Item : GNATCOLL.JSON.JSON_Value) return Host_Info_Vectors.Vector;
function Get (Item : GNATCOLL.JSON.JSON_Value) return GNAT.Spitbol.Table_VString.Table_Entry;
end GPR_Tools.Gprslaves.DB.JSON;
|
30,704
|
ada
| 1
|
TNO/Dependency_Graph_Extractor-Ada
|
tests/syntax_examples/src/basic_subprogram_calls.ads
|
<filename>tests/syntax_examples/src/basic_subprogram_calls.ads
package Basic_Subprogram_Calls is
function F1 return Integer;
function F2(I : Integer) return Integer;
function F3(I : Integer := 42) return Integer;
function F4 return Integer is
(42);
function F5(I: Integer) return Integer is
(I);
function F6(I : Integer := 42) return Integer is
(I);
function F10 return Integer;
function F11 return Integer is
(F10);
function F12 return Integer;
procedure P1;
procedure P2(I : Integer);
procedure P3(I : Integer := F1);
procedure P4;
procedure P7 is null;
procedure P8;
procedure Test;
package Nested is
function Nested_F1 return Integer;
procedure Nested_P1;
end Nested;
function F_Overload(I: Integer) return Integer;
function F_Overload(B: Boolean) return Integer;
function F_Overload(I: Integer) return Boolean;
procedure P_Overload(I : Integer);
procedure P_Overload(B : in out Boolean);
-- - Calls in pre-conditions with multiple for all/for some (reported)
-- - Call in Type_Invariant not picked up (reported)
-- - C in Convention aspect picked up as call (reported)
-- - Classwide type issue (reported)
-- - Crash in print (reported)
-- To report
-- - Calls on access variables not detected as calls (TODO: awaiting answer to class wide type issue)
-- - Link attribute use to attribute definition
-- TODO: Calls to Standard
-- TODO: Calls to system packages
-- attr/param call impl decl ("call" includes calls to overloaded operators)
-- Ada_Basic_Subp_Decl
-- - Ada_Generic_Formal_Subp_Decl - - - (looking at children: Ada_Abstract_Formal_Subp_Decl, Ada_Concrete_Formal_Subp_Decl)
-- - Ada_Abstract_Subp_Decl x x -
-- - Ada_Abstract_Formal_Subp_Decl x x -
-- - Ada_Concrete_Formal_Subp_Decl x x -
-- - Ada_Subp_Decl x x x
-- - Ada_Entry_Decl (task) c x x ("implementations" are accept statements)
-- - Ada_Entry_Decl (protected) c x c
-- - Ada_Enum_Literal_Decl x x -
-- - Ada_Generic_Subp_Internal - - - (looking at parent: Ada_Generic_Subp_Decl)
-- Ada_Base_Subp_Body
-- - Ada_Expr_Function x x -
-- - Ada_Null_Subp_Decl x x -
-- - Ada_Subp_Body x x -
-- - Ada_Subp_Renaming_Decl x x x
-- Ada_Subp_Body_Stub_Range
-- - Ada_Subp_Body_Stub x x x
--
-- - Ada_Entry_Body
-- - Ada_Generic_Subp_Decl x - x
-- - Ada_Generic_Subp_Instantiation x x x
-- - Ada_Generic_Subp_Renaming_Decl x - c
-- - access subp variable decl - n -
-- x: done
-- -: cannot occur
-- c: crashes
-- n: not detected
private
function F10 return Integer is
(42);
end Basic_Subprogram_Calls;
|
30,705
|
ada
| 6
|
My-Colaborations/ada-servlet
|
src/servlet-security-servlets.adb
|
<gh_stars>1-10
-----------------------------------------------------------------------
-- security-openid-servlets - Servlets for OpenID 2.0 Authentication
-- Copyright (C) 2010, 2011, 2012, 2013 <NAME>
-- Written by <NAME> (<EMAIL>)
--
-- 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 Servlet.Sessions;
with Util.Beans.Objects;
with Util.Beans.Objects.Records;
with Util.Log.Loggers;
package body Servlet.Security.Servlets is
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Security.Servlets");
-- Make a package to store the Association in the session.
package Association_Bean is new Util.Beans.Objects.Records (Auth.Association);
subtype Association_Access is Association_Bean.Element_Type_Access;
-- ------------------------------
-- Called by the servlet container to indicate to a servlet that the servlet
-- is being placed into service.
-- ------------------------------
procedure Initialize (Server : in out Openid_Servlet;
Context : in Servlet.Core.Servlet_Registry'Class) is
begin
null;
end Initialize;
-- Name of the session attribute which holds information about the active authentication.
OPENID_ASSOC_ATTRIBUTE : constant String := "openid-assoc";
procedure Initialize (Server : in Openid_Servlet;
Provider : in String;
Manager : in out Auth.Manager) is
begin
Manager.Initialize (Params => Server,
Name => Provider);
end Initialize;
-- Get a configuration parameter from the servlet context for the security Auth provider.
overriding
function Get_Parameter (Server : in Openid_Servlet;
Name : in String) return String is
Ctx : constant Servlet.Core.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
return Ctx.Get_Init_Parameter (Name);
end Get_Parameter;
function Get_Provider_URL (Server : in Request_Auth_Servlet;
Request : in Servlet.Requests.Request'Class) return String is
pragma Unreferenced (Server);
URI : constant String := Request.Get_Path_Info;
begin
if URI'Length = 0 then
return "";
end if;
Log.Info ("OpenID authentication with {0}", URI);
return URI (URI'First + 1 .. URI'Last);
end Get_Provider_URL;
-- ------------------------------
-- Proceed to the OpenID authentication with an OpenID provider.
-- Find the OpenID provider URL and starts the discovery, association phases
-- during which a private key is obtained from the OpenID provider.
-- After OpenID discovery and association, the user will be redirected to
-- the OpenID provider.
-- ------------------------------
procedure Do_Get (Server : in Request_Auth_Servlet;
Request : in out Servlet.Requests.Request'Class;
Response : in out Servlet.Responses.Response'Class) is
Ctx : constant Servlet.Core.Servlet_Registry_Access := Server.Get_Servlet_Context;
Name : constant String := Server.Get_Provider_URL (Request);
URL : constant String := Ctx.Get_Init_Parameter ("auth.url." & Name);
begin
Log.Info ("Request OpenId authentication to {0} - {1}", Name, URL);
if Name'Length = 0 or URL'Length = 0 then
Response.Set_Status (Servlet.Responses.SC_NOT_FOUND);
return;
end if;
declare
Mgr : Auth.Manager;
OP : Auth.End_Point;
Bean : constant Util.Beans.Objects.Object := Association_Bean.Create;
Assoc : constant Association_Access := Association_Bean.To_Element_Access (Bean);
begin
Server.Initialize (Name, Mgr);
-- Yadis discovery (get the XRDS file). This step does nothing for OAuth.
Mgr.Discover (URL, OP);
-- Associate to the OpenID provider and get an end-point with a key.
Mgr.Associate (OP, Assoc.all);
-- Save the association in the HTTP session and
-- redirect the user to the OpenID provider.
declare
Auth_URL : constant String := Mgr.Get_Authentication_URL (OP, Assoc.all);
Session : Servlet.Sessions.Session := Request.Get_Session (Create => True);
begin
Log.Info ("Redirect to auth URL: {0}", Auth_URL);
Response.Send_Redirect (Location => Auth_URL);
Session.Set_Attribute (Name => OPENID_ASSOC_ATTRIBUTE,
Value => Bean);
end;
end;
end Do_Get;
-- ------------------------------
-- Verify the authentication result that was returned by the OpenID provider.
-- If the authentication succeeded and the signature was correct, sets a
-- user principals on the session.
-- ------------------------------
procedure Do_Get (Server : in Verify_Auth_Servlet;
Request : in out Servlet.Requests.Request'Class;
Response : in out Servlet.Responses.Response'Class) is
use type Auth.Auth_Result;
type Auth_Params is new Auth.Parameters with null record;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String;
overriding
function Get_Parameter (Params : in Auth_Params;
Name : in String) return String is
pragma Unreferenced (Params);
begin
return Request.Get_Parameter (Name);
end Get_Parameter;
Session : Servlet.Sessions.Session := Request.Get_Session (Create => False);
Bean : Util.Beans.Objects.Object;
Mgr : Auth.Manager;
Assoc : Association_Access;
Credential : Auth.Authentication;
Params : Auth_Params;
Ctx : constant Servlet.Core.Servlet_Registry_Access := Server.Get_Servlet_Context;
begin
Log.Info ("Verify openid authentication");
if not Session.Is_Valid then
Log.Warn ("Session has expired during OpenID authentication process");
Response.Set_Status (Servlet.Responses.SC_FORBIDDEN);
return;
end if;
Bean := Session.Get_Attribute (OPENID_ASSOC_ATTRIBUTE);
-- Cleanup the session and drop the association end point.
Session.Remove_Attribute (OPENID_ASSOC_ATTRIBUTE);
if Util.Beans.Objects.Is_Null (Bean) then
Log.Warn ("Verify openid request without active session");
Response.Set_Status (Servlet.Responses.SC_FORBIDDEN);
return;
end if;
Assoc := Association_Bean.To_Element_Access (Bean);
Server.Initialize (Auth.Get_Provider (Assoc.all), Mgr);
-- Verify that what we receive through the callback matches the association key.
Mgr.Verify (Assoc.all, Params, Credential);
if Auth.Get_Status (Credential) /= Auth.AUTHENTICATED then
Log.Info ("Authentication has failed");
Response.Set_Status (Servlet.Responses.SC_FORBIDDEN);
return;
end if;
Log.Info ("Authentication succeeded for {0}", Auth.Get_Email (Credential));
-- Get a user principal and set it on the session.
declare
User : Servlet.Principals.Principal_Access;
URL : constant String := Ctx.Get_Init_Parameter ("openid.success_url");
begin
Verify_Auth_Servlet'Class (Server).Create_Principal (Credential, User);
Session.Set_Principal (User);
Log.Info ("Redirect user to success URL: {0}", URL);
Response.Send_Redirect (Location => URL);
end;
end Do_Get;
-- ------------------------------
-- Create a principal object that correspond to the authenticated user identified
-- by the <b>Credential</b> information. The principal will be attached to the session
-- and will be destroyed when the session is closed.
-- ------------------------------
procedure Create_Principal (Server : in Verify_Auth_Servlet;
Credential : in Auth.Authentication;
Result : out Servlet.Principals.Principal_Access) is
pragma Unreferenced (Server);
P : constant Auth.Principal_Access := Auth.Create_Principal (Credential);
begin
Result := P.all'Access;
end Create_Principal;
end Servlet.Security.Servlets;
|
30,706
|
ada
| 0
|
e3l6/SSMDev
|
sunangle.ads
|
-------------------------------------------------------------------------------
-- SUNANGLE
--
-- Copyright © 2016 <NAME>
--
-- This code is available under the "MIT License".
-- Please see the file COPYING in this distribution for license terms.
--
-- Purpose:
-- This package computes the the sun angle (azimuth and elevation) using
-- latitude, longitude, and UTC. The formulae used are taken from
-- http://www.pveducation.org/pvcdrom/properties-of-sunlight/suns-position
-------------------------------------------------------------------------------
with Ada.Calendar;
with GPS;
package Sunangle is
----------------------------------------------------------------------------
-- Constants
----------------------------------------------------------------------------
Degrees_Cycle : constant Float := 360.0; -- For use in A.N.E_F.Sin()
Degrees_In_Hour : constant Float := 15.0; -- Degrees of longitude per
-- standard time zone
Minutes_In_Hour : constant Float := 60.0;
Seconds_In_Hour : constant Float := 3600.0;
----------------------------------------------------------------------------
-- Types
----------------------------------------------------------------------------
subtype Azimuth_Type is Float range 0.0 .. 360.0;
subtype Elevation_Type is Float range -90.0 .. 90.0;
type Angle_Type is
record
Azimuth : Azimuth_Type;
Elevation : Elevation_Type;
Angle_Time : Ada.Calendar.Time;
end record;
----------------------------------------------------------------------------
-- Functions & Procedures
----------------------------------------------------------------------------
----------------------------------------------------------------------------
-- Calculate_Current_Angle
--
-- Purpose:
-- This function returns the sun angle at the given position and time.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Current_Angle
(Position : in GPS.Position_Type) return Angle_Type;
----------------------------------------------------------------------------
-- Calculate_B
--
-- Purpose:
-- This function returns the Equation of Time correction coeffecient for
-- the given position and day.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_B
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Declination
--
-- Purpose:
-- This function returns the declination for the given position.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Declination
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Equation_Of_Time
--
-- Purpose:
-- This function returns the Equation of Time for the given position
-- and day.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Equation_Of_Time
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Local_Solar_Time
--
-- Purpose:
-- This function returns the Local Solar Time for the given position
-- and day.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Local_Solar_Time
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Local_Standard_Time
--
-- Purpose:
-- This function returns the Local Standard Time for the given position
-- and day. Uses local time based on longitude. This is purely geographic
-- and doesn't use standard time zones, only adds or subtracts 1 hour
-- for every 15 degrees East or West (respectively) from the Prime
-- Meridian.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Local_Standard_Time
(Position : in GPS.Position_Type) return Ada.Calendar.Time;
----------------------------------------------------------------------------
-- Calculate_Local_Standard_Time_Meridian
--
-- Purpose:
-- This function returns the Local Standard Time for the given position
-- and day. Uses local time based on longitude. This is purely geographic
-- and doesn't use standard time zones, only adds or subtracts 1 hour
-- for every 15 degrees East or West (respectively) from the Prime
-- Meridian.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Local_Standard_Time_Meridian
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Time_Correction_Factor
--
-- Purpose:
-- This function returns the Time Correction Factor for the given
-- position.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Time_Correction_Factor
(Position : in GPS.Position_Type) return Float;
----------------------------------------------------------------------------
-- Calculate_Sunrise
--
-- Purpose:
-- This function returns the time of sunrise for the given position
-- and day.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Sunrise
(Position : in Gps.Position_Type) return Ada.Calendar.Time;
----------------------------------------------------------------------------
-- Calculate_Sunset
--
-- Purpose:
-- This function returns the time of sunset for the given position
-- and day.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function Calculate_Sunset
(Position : in Gps.Position_Type) return Ada.Calendar.Time;
----------------------------------------------------------------------------
-- To_Julian_Day
--
-- Purpose:
-- This function returns the day number of the year for the given time.
-- Exceptions:
-- None.
----------------------------------------------------------------------------
function To_Julian_Day
(Current_Time : in Ada.Calendar.Time) return Float;
end Sunangle;
|
30,707
|
ada
| 204
|
spr93/whitakers-words
|
src/latin_utils/latin_utils-dictionary_package-parse_record_io.adb
|
-- WORDS, a Latin dictionary, by <NAME> (USAF, Retired)
--
-- Copyright <NAME> (1936–2010)
--
-- This is a free program, which means it is proper to copy it and pass
-- it on to your friends. Consider it a developmental item for which
-- there is no charge. However, just for form, it is Copyrighted
-- (c). Permission is hereby freely given for any and all use of program
-- and data. You can sell it as your own, but at least tell me.
--
-- This version is distributed without obligation, but the developer
-- would appreciate comments and suggestions.
--
-- All parts of the WORDS system, source code and data files, are made freely
-- available to anyone who wishes to use them, for whatever purpose.
separate (Latin_Utils.Dictionary_Package)
package body Parse_Record_IO is
---------------------------------------------------------------------------
procedure Get (File : in Ada.Text_IO.File_Type; Item : out Parse_Record)
is
Spacer : Character;
pragma Unreferenced (Spacer);
begin
Stem_Type_IO.Get (File, Item.Stem);
Ada.Text_IO.Get (File, Spacer);
Inflection_Record_IO.Get (File, Item.IR);
Ada.Text_IO.Get (File, Spacer);
Dictionary_Kind_IO.Get (File, Item.D_K);
Ada.Text_IO.Get (File, Spacer);
MNPC_IO.Get (File, Item.MNPC);
end Get;
---------------------------------------------------------------------------
procedure Get (Item : out Parse_Record)
is
Spacer : Character;
pragma Unreferenced (Spacer);
begin
Stem_Type_IO.Get (Item.Stem);
Ada.Text_IO.Get (Spacer);
Inflection_Record_IO.Get (Item.IR);
Ada.Text_IO.Get (Spacer);
Dictionary_Kind_IO.Get (Item.D_K);
Ada.Text_IO.Get (Spacer);
MNPC_IO.Get (Item.MNPC);
end Get;
---------------------------------------------------------------------------
procedure Put (File : in Ada.Text_IO.File_Type; Item : in Parse_Record) is
begin
Stem_Type_IO.Put (File, Item.Stem);
Ada.Text_IO.Put (File, ' ');
Inflection_Record_IO.Put (File, Item.IR);
Ada.Text_IO.Put (File, ' ');
Dictionary_Kind_IO.Put (File, Item.D_K);
Ada.Text_IO.Put (File, ' ');
MNPC_IO.Put (File, Item.MNPC);
end Put;
---------------------------------------------------------------------------
procedure Put (Item : in Parse_Record) is
begin
Stem_Type_IO.Put (Item.Stem);
Ada.Text_IO.Put (' ');
Inflection_Record_IO.Put (Item.IR);
Ada.Text_IO.Put (' ');
Dictionary_Kind_IO.Put (Item.D_K);
Ada.Text_IO.Put (' ');
MNPC_IO.Put (Item.MNPC);
end Put;
---------------------------------------------------------------------------
procedure Get
(Source : in String;
Target : out Parse_Record;
Last : out Integer
)
is
-- Used for computing lower bound of substring
Low : Integer := Source'First - 1;
begin
Stem_Type_IO.Get (Source, Target.Stem, Low);
Low := Low + 1;
Inflection_Record_IO.Get
(Source (Low + 1 .. Source'Last), Target.IR, Low);
Low := Low + 1;
Dictionary_Kind_IO.Get (Source (Low + 1 .. Source'Last), Target.D_K, Low);
Low := Low + 1;
MNPC_IO.Get (Source (Low + 1 .. Source'Last), Target.MNPC, Last);
end Get;
---------------------------------------------------------------------------
procedure Put (Target : out String; Item : in Parse_Record)
is
-- These variables are used for computing bounds of substrings
Low : Integer := 0;
High : Integer := 0;
begin
-- Put Stem_Type
High := Low + Max_Stem_Size;
Target (Target'First + Low .. Target'First - 1 + High) := Item.Stem;
Low := High + 1;
Target (Target'First - 1 + Low) := ' ';
-- Put Inflection_Record
High := Low + Inflection_Record_IO.Default_Width;
Inflection_Record_IO.Put
(Target (Target'First + Low .. Target'First - 1 + High), Item.IR);
Low := High + 1;
Target (Target'First - 1 + Low) := ' ';
-- Put Dictionary_Kind
High := Low + Dictionary_Kind_IO.Default_Width;
Dictionary_Kind_IO.Put
(Target (Target'First + Low .. Target'First - 1 + High), Item.D_K);
Low := High + 1;
-- Put MNPC
Target (Target'First - 1 + Low) := ' ';
High := Low + MNPC_IO_Default_Width;
MNPC_IO.Put
(Target (Target'First + Low .. Target'First - 1 + High), Item.MNPC);
-- Fill remainder of string
Target (High + 1 .. Target'Last) := (others => ' ');
end Put;
---------------------------------------------------------------------------
end Parse_Record_IO;
|
30,708
|
ada
| 0
|
fintatarta/protypo
|
test/parsing-test/protypo-parsing-test.adb
|
with Protypo.Scanning;
with Protypo.Code_Trees;
with Protypo.Api.Interpreters; use Protypo.Api.Interpreters;
procedure Protypo.Parsing.Test is
S : constant Template_Type := Slurp ("test-data/parsing.txt");
Tk : Scanning.Token_List := Scanning.Tokenize (S, "");
Code : Code_Trees.Parsed_Code;
-- pragma Unreferenced (Code);
begin
Scanning.Dump (Tk);
Code := Parse_Statement_Sequence (Tk);
Code_Trees.Dump (Code);
end Protypo.Parsing.Test;
|
30,709
|
ada
| 2
|
marcbejerano/ada-tools
|
Properties/test/properties_test.adb
|
<filename>Properties/test/properties_test.adb
-- @(#)File: properties_test.adb
-- @(#)Last changed: Mar 18 2015 10:30:00
-- @(#)Purpose: Java properties file support
-- @(#)Author: <NAME> <<EMAIL>>
-- @(#)Copyright: Copyright (C) 2015, <NAME>, All Rights Reserved
-- @(#)Product: None
-- @(#)License: BSD3
--
-- Copyright (c) 2015, <NAME>
-- 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 ada-tools nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Properties; use Properties;
procedure Properties_Test is
function assert_equals(expected, actual: in String) return Boolean is
begin
if (expected /= actual) then
put("Assertion failure. actual=");
put(actual);
put(" expected=");
Put_Line(expected);
return false;
else
return true;
end if;
end assert_equals;
props: Properties.Properties;
props2: Properties.Properties;
status: Boolean;
keys: Key_Vector.Vector;
begin
Put_Line("*Create");
props.set_Property("ABC", "987654321");
props := Create;
status := assert_equals("", props.Get_Property("ABC"));
Put_Line("*Create(Properties)");
props.Set_Property("ABC", "987654321");
props2 := Create(props);
props2.Set_Property("Another", "this is a test");
status := assert_equals("987654321", props2.Get_Property("ABC"));
status := assert_equals("this is a test", props2.Get_Property("Another"));
props := Create;
Put_Line("*Get_Property");
status := assert_equals("", props.Get_Property("ABC"));
Put_Line("*Get_Property(String)");
status := assert_equals("hello world", props.Get_Property("ABC", "hello world"));
Put_Line("*Set_Property");
props.Set_Property("ABC", "12345");
status := assert_equals("12345", props.Get_Property("ABC"));
Put_Line("*List");
props.List(Standard_Output);
Put_Line("*Property_Names");
keys := props2.Property_Names;
for key_index in 0 .. Integer(keys.Length) - 1 loop
Put_Line(To_String(keys(key_index)));
end loop;
Put_Line("*String_Property_Names");
keys := props2.String_Property_Names;
for key_index in 0 .. Integer(keys.Length) - 1 loop
Put_Line(To_String(keys(key_index)));
end loop;
Put_Line("*Store");
props.Store(Standard_Output, "This is a comment");
Put_Line("*Store(Filename)");
props.Store("test.properties", "This is a comment");
Put_Line("*Store_To_XML");
props.Store_To_XML(Standard_Output, "This is a comment");
Put_Line("*Store_To_XML(Filename)");
props.Store_To_XML("test.xml", "This is a comment");
Put_Line("*Load(Filename)");
props.Load("test2.properties");
props.List(Standard_Output);
end Properties_Test;
|
30,710
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada
|
<filename>Task/Ulam-spiral--for-primes-/Ada/ulam-spiral--for-primes--3.ada
with Generic_Ulam, Ada.Text_IO, Prime_Numbers;
procedure Ulam is
package P is new Prime_Numbers(Natural, 0, 1, 2);
function Vis(N: Natural) return String is
(if P.Is_Prime(N) then " <>" else " ");
function Num(N: Natural) return String is
(if P.Is_Prime(N) then
(if N < 10 then " " elsif N < 100 then " " else "") & Natural'Image(N)
else " ---");
procedure NL is
begin
Ada.Text_IO.New_Line;
end NL;
package Numeric is new Generic_Ulam(29, Num, Ada.Text_IO.Put, NL);
package Visual is new Generic_Ulam(10, Vis, Ada.Text_IO.Put, NL);
begin
Numeric.Print_Spiral;
NL;
Visual.Print_Spiral;
end Ulam;
|
30,711
|
ada
| 6
|
jonashaggstrom/ada-canopen
|
src/aco-sdo_sessions.ads
|
with ACO.Messages;
with ACO.OD_Types;
with ACO.Configuration;
private with ACO.Utils.DS.Generic_Queue;
package ACO.SDO_Sessions is
type Session_Manager is tagged limited private;
type Services is
(None,
Download,
Upload,
Block_Download,
Block_Upload);
subtype Endpoint_Nr is Integer range -1 .. Integer'Last;
No_Endpoint_Id : constant Endpoint_Nr := Endpoint_Nr'First;
subtype Valid_Endpoint_Nr is Endpoint_Nr range
No_Endpoint_Id + 1 .. ACO.Configuration.Max_Nof_Simultaneous_SDO_Sessions;
type SDO_Parameters is record
CAN_Id_C2S : ACO.Messages.Id_Type := 0;
CAN_Id_S2C : ACO.Messages.Id_Type := 0;
Node : ACO.Messages.Node_Nr := ACO.Messages.Not_A_Slave;
end record;
No_SDO_Parameters : constant SDO_Parameters :=
(CAN_Id_C2S => 0,
CAN_Id_S2C => 0,
Node => ACO.Messages.Not_A_Slave);
type SDO_Parameter_Array is array (Natural range <>) of SDO_Parameters;
type Endpoint_Type is record
Id : Endpoint_Nr := No_Endpoint_Id;
Parameters : SDO_Parameters;
end record;
No_Endpoint : constant Endpoint_Type :=
(Id => No_Endpoint_Id,
Parameters => No_SDO_Parameters);
function Image (Endpoint : Endpoint_Type) return String;
type SDO_Status is
(Pending,
Complete,
Error);
Is_Complete : constant array (SDO_Status) of Boolean :=
(Pending | Error => False,
Complete => True);
subtype SDO_Result is SDO_Status range Complete .. Error;
type SDO_Session (Service : Services := None) is record
Endpoint : Endpoint_Type := No_Endpoint;
Index : ACO.OD_Types.Entry_Index := (0, 0);
Toggle : Boolean := False;
end record;
function Create_Download
(Endpoint : Endpoint_Type;
Index : ACO.OD_Types.Entry_Index)
return SDO_Session;
function Create_Upload
(Endpoint : Endpoint_Type;
Index : ACO.OD_Types.Entry_Index)
return SDO_Session;
function Get
(This : Session_Manager;
Id : Valid_Endpoint_Nr)
return SDO_Session;
procedure Put
(This : in out Session_Manager;
Session : in SDO_Session);
function Service
(This : Session_Manager;
Id : Valid_Endpoint_Nr)
return Services;
procedure Clear
(This : in out Session_Manager;
Id : in Valid_Endpoint_Nr);
procedure Clear_Buffer
(This : in out Session_Manager;
Id : in Valid_Endpoint_Nr);
procedure Put_Buffer
(This : in out Session_Manager;
Id : in Valid_Endpoint_Nr;
Data : in ACO.Messages.Data_Array);
function Length_Buffer
(This : Session_Manager;
Id : Valid_Endpoint_Nr)
return Natural;
procedure Get_Buffer
(This : in out Session_Manager;
Id : in Valid_Endpoint_Nr;
Data : out ACO.Messages.Data_Array)
with Pre => Data'Length <= This.Length_Buffer (Id);
function Peek_Buffer
(This : Session_Manager;
Id : Valid_Endpoint_Nr)
return ACO.Messages.Data_Array;
private
package Q is new ACO.Utils.DS.Generic_Queue
(Item_Type => ACO.Messages.Data_Type);
type Session_Array is array (Endpoint_Nr range <>) of SDO_Session;
type Buffer_Array is array (Endpoint_Nr range <>) of
Q.Queue (Max_Nof_Items => ACO.Configuration.Max_SDO_Transfer_Size);
type Session_Manager is tagged limited record
List : Session_Array (Valid_Endpoint_Nr'Range);
Buffers : Buffer_Array (Valid_Endpoint_Nr'Range);
end record;
end ACO.SDO_Sessions;
|
30,712
|
ada
| 0
|
alire-project/sdlada
|
src/sdl-inputs-mice.ads
|
<reponame>alire-project/sdlada
--------------------------------------------------------------------------------------------------------------------
-- Copyright (c) 2013-2018 <NAME>
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--------------------------------------------------------------------------------------------------------------------
-- SDL.Inputs.Mice
--------------------------------------------------------------------------------------------------------------------
with SDL.Events.Mice;
with SDL.Video.Windows;
package SDL.Inputs.Mice is
Mice_Error : exception;
type Cursor_Toggles is (Off, On);
for Cursor_Toggles use (Off => 0, On => 1);
type Supported is (Yes, No);
-- TODO: Re-enable this when the library links against 2.0.4!
-- function Capture (Enabled : in Boolean) return Supported;
-- SDL_CreateColorCursor
-- SDL_CreateCursor
-- SDL_CreateSystemCursor
-- SDL_FreeCursor
-- SDL_GetCursor
-- SDL_GetDefaultCursor
-- TODO: Re-enable this when the library links against 2.0.4!
-- function Get_Global_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return
-- SDL.Events.Mice.Button_Masks;
-- SDL_GetMouseFocus
function Get_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return
SDL.Events.Mice.Button_Masks;
function In_Relative_Mode return Boolean;
function Get_Relative_State (X_Relative, Y_Relative : out SDL.Events.Mice.Movement_Values) return
SDL.Events.Mice.Button_Masks;
-- SDL_SetCursor
procedure Set_Relative_Mode (Enable : in Boolean);
-- SDL_ShowCursor
-- TODO: Re-enable this when the library links against 2.0.4!
-- Move the mouse to (x, y) on the screen.
-- procedure Warp (X, Y : in SDL.Events.Mice.Screen_Coordinates);
--
-- Move the mouse to (x, y) in the specified window.
-- procedure Warp (Window : in SDL.Video.Windows.Window; X, Y : in SDL.Events.Mice.Window_Coordinates);
end SDL.Inputs.Mice;
|
30,713
|
ada
| 0
|
ScottWLoyd/bare-metal-ada-tools
|
rts/src/common/last_chance_handler.ads
|
<filename>rts/src/common/last_chance_handler.ads
with System;
procedure Last_Chance_Handler
(Source_Location : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
|
30,714
|
ada
| 1
|
leo-brewin/adm-bssn-numerical
|
support/support.ads
|
with GNAT.OS_Lib;
package Support is
type Real is digits 18;
procedure halt (return_code : Integer := 0) renames GNAT.OS_Lib.OS_Exit;
function max (a : in Real; b : in Real) return Real;
function min (a : in Real; b : in Real) return Real;
function max (a : in Integer; b : in Integer) return Integer;
function min (a : in Integer; b : in Integer) return Integer;
end Support;
|
30,715
|
ada
| 3
|
UdayanSinha/Code_Blocks
|
Ada/producerconsumer_rndvzs.adb
|
<gh_stars>1-10
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Real_Time;
use Ada.Real_Time;
with Ada.Numerics.Discrete_Random;
procedure ProducerConsumer_rndvzs is
N : constant Integer := 40; -- Number of produced and comsumed variables
-- Random Delays
subtype Delay_Interval is Integer range 50..250;
package Random_Delay is new Ada.Numerics.Discrete_Random (Delay_Interval);
use Random_Delay;
G : Generator;
task Server is
entry WriteBuf(X: in INTEGER);
entry ReadBuf;
end Server;
task Producer;
task Consumer;
task body Producer is
Next : Time;
begin
Next := Clock;
for I in 1..N loop
Server.WriteBuf(I); --write data request
-- Next 'Release' in 50..250ms
Next := Next + Milliseconds(Random(G));
delay until Next;
end loop;
end;
task body Consumer is
begin
for I in 1..N loop
Server.ReadBuf; --read data request
end loop;
end;
task body Server is
N: constant Integer := 4;
subtype Item is Integer;
type Index is mod N;
type Item_Array is array(Index) of Item;
A: Item_Array; --circular buffer, 4 elements
In_Ptr, Out_Ptr: Index := 0;
Count: Integer range 0..N := 0;
begin
loop
select
when count<N => --no writing to full buffer
accept WriteBuf(X: in INTEGER) do --write buffer
A(In_Ptr):=X;
In_Ptr:=In_Ptr+1;
count:=count+1;
end WriteBuf;
or
when count>0 => --no reading from empty buffer
accept ReadBuf do --read buffer
Put_Line(Integer'Image(A(Out_Ptr)));
Out_Ptr:=Out_Ptr+1;
count:=count-1;
end ReadBuf;
or
terminate; --no more requests, terminate server task
end select;
end loop;
end;
begin -- main task
null;
end ProducerConsumer_rndvzs;
|
30,716
|
ada
| 0
|
reznikmm/gela
|
source/nodes/program-nodes-function_calls.ads
|
<gh_stars>0
-- SPDX-FileCopyrightText: 2019 <NAME> <<EMAIL>>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Elements.Expressions;
with Program.Lexical_Elements;
with Program.Elements.Parameter_Associations;
with Program.Elements.Function_Calls;
with Program.Element_Visitors;
package Program.Nodes.Function_Calls is
pragma Preelaborate;
type Function_Call is
new Program.Nodes.Node and Program.Elements.Function_Calls.Function_Call
and Program.Elements.Function_Calls.Function_Call_Text
with private;
function Create
(Prefix : not null Program.Elements.Expressions
.Expression_Access;
Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
Parameters : Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access;
Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access)
return Function_Call;
type Implicit_Function_Call is
new Program.Nodes.Node and Program.Elements.Function_Calls.Function_Call
with private;
function Create
(Prefix : not null Program.Elements.Expressions
.Expression_Access;
Parameters : Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Function_Call
with Pre =>
Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance;
private
type Base_Function_Call is
abstract new Program.Nodes.Node
and Program.Elements.Function_Calls.Function_Call
with record
Prefix : not null Program.Elements.Expressions.Expression_Access;
Parameters : Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access;
end record;
procedure Initialize (Self : in out Base_Function_Call'Class);
overriding procedure Visit
(Self : not null access Base_Function_Call;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class);
overriding function Prefix
(Self : Base_Function_Call)
return not null Program.Elements.Expressions.Expression_Access;
overriding function Parameters
(Self : Base_Function_Call)
return Program.Elements.Parameter_Associations
.Parameter_Association_Vector_Access;
overriding function Is_Function_Call
(Self : Base_Function_Call)
return Boolean;
overriding function Is_Expression
(Self : Base_Function_Call)
return Boolean;
type Function_Call is
new Base_Function_Call
and Program.Elements.Function_Calls.Function_Call_Text
with record
Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
end record;
overriding function To_Function_Call_Text
(Self : in out Function_Call)
return Program.Elements.Function_Calls.Function_Call_Text_Access;
overriding function Left_Bracket_Token
(Self : Function_Call)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Right_Bracket_Token
(Self : Function_Call)
return Program.Lexical_Elements.Lexical_Element_Access;
type Implicit_Function_Call is
new Base_Function_Call
with record
Is_Part_Of_Implicit : Boolean;
Is_Part_Of_Inherited : Boolean;
Is_Part_Of_Instance : Boolean;
end record;
overriding function To_Function_Call_Text
(Self : in out Implicit_Function_Call)
return Program.Elements.Function_Calls.Function_Call_Text_Access;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Function_Call)
return Boolean;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Function_Call)
return Boolean;
overriding function Is_Part_Of_Instance
(Self : Implicit_Function_Call)
return Boolean;
end Program.Nodes.Function_Calls;
|
30,717
|
ada
| 33
|
ytomino/drake
|
source/strings/a-stgebo.adb
|
package body Ada.Strings.Generic_Bounded is
type String_Access is access all String_Type;
function Length (Source : Bounded_String) return Natural is
begin
return Source.Length;
end Length;
function To_String (Source : Bounded_String) return String_Type is
begin
return Source.Element (1 .. Source.Length);
end To_String;
procedure Set_Bounded_String (
Target : out Bounded_String;
Source : String_Type;
Drop : Truncation := Error)
is
Source_Length : constant Natural := Source'Length;
begin
if Source_Length > Target.Capacity then
case Drop is
when Right =>
Target.Length := Target.Capacity;
Target.Element :=
Source (Source'First .. Source'First + Target.Capacity - 1);
when Left =>
Target.Length := Target.Capacity;
Target.Element :=
Source (Source'Last - Target.Capacity + 1 .. Source'Last);
when Error =>
raise Length_Error;
end case;
else
Target.Length := Source_Length;
Target.Element (1 .. Target.Length) := Source;
end if;
end Set_Bounded_String;
procedure Append (
Source : in out Bounded_String;
New_Item : Bounded_String;
Drop : Truncation := Error) is
begin
Append (Source, New_Item.Element (1 .. New_Item.Length), Drop);
end Append;
procedure Append (
Source : in out Bounded_String;
New_Item : String_Type;
Drop : Truncation := Error)
is
New_Item_Length : constant Natural := New_Item'Length;
Old_Length : constant Natural := Source.Length;
Rest : constant Natural := Source.Capacity - Old_Length;
begin
if New_Item_Length > Rest then
case Drop is
when Right =>
Source.Length := Source.Capacity;
Source.Element (Old_Length + 1 .. Source.Capacity) :=
New_Item (New_Item'First .. New_Item'First + Rest - 1);
when Left =>
Source.Length := Source.Capacity;
declare
Moving : constant Natural :=
Integer'Max (Source.Capacity - New_Item_Length, 0);
S : constant String_Type (1 .. Moving) :=
Source.Element (Old_Length - Moving + 1 .. Old_Length);
-- Save it before copying for Append (B, B).
begin
Source.Element (Moving + 1 .. Source.Capacity) :=
New_Item (
New_Item'Last - (Source.Capacity - Moving) + 1 ..
New_Item'Last);
Source.Element (1 .. Moving) := S;
end;
when Error =>
raise Length_Error;
end case;
else
Source.Length := Old_Length + New_Item_Length;
Source.Element (Old_Length + 1 .. Source.Length) := New_Item;
end if;
end Append;
procedure Append_Element (
Source : in out Bounded_String;
New_Item : Character_Type;
Drop : Truncation := Error) is
begin
Append (Source, String_Type'(1 => New_Item), Drop);
end Append_Element;
function Element (
Source : Bounded_String;
Index : Positive)
return Character_Type
is
pragma Check (Pre, Index <= Source.Length or else raise Index_Error);
begin
return Source.Element (Index);
end Element;
procedure Replace_Element (
Source : in out Bounded_String;
Index : Positive;
By : Character_Type)
is
pragma Check (Pre, Index <= Source.Length or else raise Index_Error);
begin
Source.Element (Index) := By;
end Replace_Element;
function Slice (
Source : Bounded_String;
Low : Positive;
High : Natural)
return String_Type
is
pragma Check (Pre,
Check =>
(Low <= Source.Length + 1 and then High <= Source.Length)
or else raise Index_Error); -- CXA4034
begin
return Source.Element (Low .. High);
end Slice;
overriding function "=" (Left, Right : Bounded_String) return Boolean is
begin
return Left.Element (1 .. Left.Length) =
Right.Element (1 .. Right.Length);
end "=";
function "=" (Left : Bounded_String; Right : String_Type) return Boolean is
begin
return Left.Element (1 .. Left.Length) = Right;
end "=";
function "=" (Left : String_Type; Right : Bounded_String) return Boolean is
begin
return Left = Right.Element (1 .. Right.Length);
end "=";
function "<" (Left, Right : Bounded_String) return Boolean is
begin
return Left.Element (1 .. Left.Length) <
Right.Element (1 .. Right.Length);
end "<";
function "<" (Left : Bounded_String; Right : String_Type) return Boolean is
begin
return Left.Element (1 .. Left.Length) < Right;
end "<";
function "<" (Left : String_Type; Right : Bounded_String) return Boolean is
begin
return Left < Right.Element (1 .. Right.Length);
end "<";
function "<=" (Left, Right : Bounded_String) return Boolean is
begin
return not (Right < Left);
end "<=";
function "<=" (Left : Bounded_String; Right : String_Type) return Boolean is
begin
return not (Right < Left);
end "<=";
function "<=" (Left : String_Type; Right : Bounded_String) return Boolean is
begin
return not (Right < Left);
end "<=";
function ">" (Left, Right : Bounded_String) return Boolean is
begin
return Right < Left;
end ">";
function ">" (Left : Bounded_String; Right : String_Type) return Boolean is
begin
return Right < Left;
end ">";
function ">" (Left : String_Type; Right : Bounded_String) return Boolean is
begin
return Right < Left;
end ">";
function ">=" (Left, Right : Bounded_String) return Boolean is
begin
return not (Left < Right);
end ">=";
function ">=" (Left : Bounded_String; Right : String_Type) return Boolean is
begin
return not (Left < Right);
end ">=";
function ">=" (Left : String_Type; Right : Bounded_String) return Boolean is
begin
return not (Left < Right);
end ">=";
function Constant_Reference (
Source : aliased Bounded_String)
return Slicing.Constant_Reference_Type is
begin
return Slicing.Constant_Slice (
String_Access'(Source.Element'Unrestricted_Access).all,
1,
Source.Length);
end Constant_Reference;
function Reference (
Source : aliased in out Bounded_String)
return Slicing.Reference_Type is
begin
return Slicing.Slice (
String_Access'(Source.Element'Unrestricted_Access).all,
1,
Source.Length);
end Reference;
package body Generic_Bounded_Length is
function Null_Bounded_String return Bounded_String is
begin
return (Capacity => Max, Length => 0, Element => <>);
end Null_Bounded_String;
function To_Bounded_String (
Source : String_Type;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Set_Bounded_String (Result, Source, Drop);
end return;
end To_Bounded_String;
function "+" (Source : String_Type) return Bounded_String is
begin
return To_Bounded_String (Source);
end "+";
function Append (
Left, Right : Bounded_String;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Assign (Result, Left);
Append (Result, Right, Drop);
end return;
end Append;
function Append (
Left : Bounded_String;
Right : String_Type;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Assign (Result, Left);
Append (Result, Right, Drop);
end return;
end Append;
function Append (
Left : String_Type;
Right : Bounded_String;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Set_Bounded_String (Result, Left, Drop);
Append (Result, Right, Drop);
end return;
end Append;
function Append_Element (
Left : Bounded_String;
Right : Character_Type;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Assign (Result, Left);
Append_Element (Result, Right, Drop);
end return;
end Append_Element;
function Append_Element (
Left : Character_Type;
Right : Bounded_String;
Drop : Truncation := Error)
return Bounded_String is
begin
return Result : Bounded_String do
Set_Bounded_String (Result, (1 => Left), Drop);
Append (Result, Right, Drop);
end return;
end Append_Element;
function "&" (Left, Right : Bounded_String)
return Bounded_String is
begin
return Append (Left, Right);
end "&";
function "&" (Left : Bounded_String; Right : String_Type)
return Bounded_String is
begin
return Append (Left, Right);
end "&";
function "&" (Left : String_Type; Right : Bounded_String)
return Bounded_String is
begin
return Append (Left, Right);
end "&";
function "&" (Left : Bounded_String; Right : Character_Type)
return Bounded_String is
begin
return Append_Element (Left, Right);
end "&";
function "&" (Left : Character_Type; Right : Bounded_String)
return Bounded_String is
begin
return Append_Element (Left, Right);
end "&";
function Bounded_Slice (
Source : Bounded_String;
Low : Positive;
High : Natural)
return Bounded_String is
begin
return Result : Bounded_String do
Bounded_Slice (Source, Result, Low, High); -- checking Index_Error
end return;
end Bounded_Slice;
procedure Bounded_Slice (
Source : Bounded_String;
Target : out Bounded_String;
Low : Positive;
High : Natural)
is
pragma Check (Pre,
Check =>
(Low <= Source.Length + 1 and then High <= Source.Length)
or else raise Index_Error);
begin
-- Target.Length <= Max because High <= Source.Length
Target.Length := Integer'Max (High - Low + 1, 0);
Target.Element (1 .. Target.Length) := Source.Element (Low .. High);
end Bounded_Slice;
procedure Assign (
Target : in out Bounded_String;
Source : Bounded_String) is
begin
Target.Element (1 .. Source.Length) :=
Source.Element (1 .. Source.Length);
Target.Length := Source.Length;
end Assign;
procedure Move (
Target : in out Bounded_String;
Source : in out Bounded_String) is
begin
Assign (Target, Source);
Source.Length := 0;
end Move;
function "*" (Left : Natural; Right : Character_Type)
return Bounded_String is
begin
return Replicate_Element (Left, Right, Error);
end "*";
function "*" (Left : Natural; Right : String_Type)
return Bounded_String is
begin
return Replicate (Left, Right, Error);
end "*";
function "*" (Left : Natural; Right : Bounded_String)
return Bounded_String is
begin
return Replicate (Left, Right, Error);
end "*";
function Replicate_Element (
Count : Natural;
Item : Character_Type;
Drop : Truncation := Error)
return Bounded_String is
begin
if Count > Max and then Drop = Error then
raise Length_Error;
else
return (
Capacity => Max,
Length => Natural'Min (Count, Max),
Element => (others => Item));
end if;
end Replicate_Element;
function Replicate (
Count : Natural;
Item : String_Type;
Drop : Truncation := Error)
return Bounded_String
is
Item_Length : constant Natural := Item'Length;
Total_Length : Natural := Count * Item_Length;
Actual_Count : Natural := Count;
begin
if Total_Length > Max then
if Drop = Error then
raise Length_Error;
end if;
Total_Length := Max;
Actual_Count := Total_Length / Item_Length;
end if;
return Result : Bounded_String :=
(Capacity => Max, Length => Total_Length, Element => <>)
do
case Drop is
when Right | Error =>
declare
Last : Natural := 0;
begin
for I in 1 .. Actual_Count loop
Result.Element (Last + 1 .. Last + Item_Length) :=
Item;
Last := Last + Item_Length;
end loop;
if Last < Total_Length then
Result.Element (Last + 1 .. Total_Length) :=
Item (
Item'First ..
Item'First + Total_Length - (Last + 1));
end if;
end;
when Left =>
declare
First : Positive := Total_Length + 1;
begin
for I in 1 .. Actual_Count loop
Result.Element (First - Item_Length .. First - 1) :=
Item;
First := First - Item_Length;
end loop;
if First > 1 then
Result.Element (1 .. First - 1) :=
Item (Item'Last - (First - 1) + 1 .. Item'Last);
end if;
end;
end case;
end return;
end Replicate;
function Replicate (
Count : Natural;
Item : Bounded_String;
Drop : Truncation := Error)
return Bounded_String is
begin
return Replicate (Count, Item.Element (1 .. Item.Length), Drop);
end Replicate;
package body Streaming is
procedure Read (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : out Bounded_String)
is
First : Integer;
Last : Integer;
begin
Integer'Read (Stream, First);
Integer'Read (Stream, Last);
declare
Length : constant Integer := Last - First + 1;
begin
if Length > Item.Capacity then
raise Length_Error;
end if;
Item.Length := Length;
Read (Stream, Item.Element (1 .. Length));
end;
end Read;
procedure Write (
Stream : not null access Streams.Root_Stream_Type'Class;
Item : Bounded_String) is
begin
Integer'Write (Stream, 1);
Integer'Write (Stream, Item.Length);
Write (Stream, Item.Element (1 .. Item.Length));
end Write;
function Input (
Stream : not null access Streams.Root_Stream_Type'Class)
return Bounded_String is
begin
return Result : Bounded_String do
Read (Stream, Result);
end return;
end Input;
end Streaming;
end Generic_Bounded_Length;
end Ada.Strings.Generic_Bounded;
|
30,718
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/ada/par_sco.ads
|
<gh_stars>1-10
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- P A R _ S C O --
-- --
-- S p e c --
-- --
-- Copyright (C) 2009-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. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the routines used to deal with generation and output
-- of Source Coverage Obligations (SCO's) used for coverage analysis purposes.
-- See package SCOs for full documentation of format of SCO information.
with Types; use Types;
package Par_SCO is
-----------------
-- Subprograms --
-----------------
procedure Initialize;
-- Initialize internal tables for a new compilation
procedure SCO_Record_Raw (U : Unit_Number_Type);
-- This procedure scans the tree for the unit identified by U, populating
-- internal tables recording the SCO information. Note that this is done
-- before any semantic analysis/expansion happens.
procedure Set_SCO_Condition (Cond : Node_Id; Val : Boolean);
-- This procedure is called during semantic analysis to record a condition
-- which has been identified as always True or always False, as indicated
-- by Val. The condition is identified by the First_Sloc value in the
-- original tree associated with Cond.
procedure Set_SCO_Logical_Operator (Op : Node_Id);
-- Mark some putative logical operator as a short circuit one
procedure Set_SCO_Pragma_Enabled (Loc : Source_Ptr);
-- This procedure is called from Sem_Prag when a pragma is enabled (i.e.
-- when the Pragma_Enabled flag is set). Loc is the Sloc of the N_Pragma
-- node. This is used to enable the corresponding statement SCO entry. Note
-- that we use the Sloc as the key here, since in the generic case, the
-- analysis is on a copy of the node, which is different from the node
-- seen by Par_SCO in the parse tree (but the Sloc values are the same).
function SCO_Pragma_Disabled (Loc : Source_Ptr) return Boolean;
-- True if Loc is the source location of a disabled pragma
procedure SCO_Record_Filtered;
-- This procedure filters remaining putative AND/OR short-circuit operators
-- from the internal SCO raw table after the semantic analysis and fills
-- the filtered SCO table.
procedure SCO_Output;
-- Outputs SCO lines for all units, with appropriate section headers, as
-- recorded by previous calls to SCO_Record, possibly modified by calls to
-- Set_SCO_Condition.
procedure dsco;
-- Debug routine to dump internal SCO tables. This is a raw format dump
-- showing exactly what the tables contain.
procedure pscos;
-- Debugging procedure to output contents of SCO binary tables in the
-- format in which they appear in an ALI file.
end Par_SCO;
|
30,719
|
ada
| 24
|
svn2github/matreshka
|
source/sql/oci/matreshka-internals-sql_drivers-oracle-databases.ads
|
<reponame>svn2github/matreshka
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- SQL Database Access --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, <NAME> <<EMAIL>> --
-- 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$
------------------------------------------------------------------------------
-- Implementation of Abstract_Database type for Oracle database.
------------------------------------------------------------------------------
with Matreshka.Internals.Strings;
with Matreshka.Internals.SQL_Drivers.Oracle.Plug_In;
package Matreshka.Internals.SQL_Drivers.Oracle.Databases is
type OCI_Database is new Abstract_Database with record
Error : aliased Error_Handle;
Service : aliased Service_Handle;
Error_Text : Matreshka.Internals.Strings.Shared_String_Access;
Plugins : access Oracle.Plug_In.Abstract_Plug_In'Class;
end record;
overriding procedure Close (Self : not null access OCI_Database);
overriding procedure Commit (Self : not null access OCI_Database);
overriding function Error_Message
(Self : not null access OCI_Database)
return League.Strings.Universal_String;
overriding function Query
(Self : not null access OCI_Database) return not null Query_Access;
overriding procedure Finalize (Self : not null access OCI_Database);
overriding function Open
(Self : not null access OCI_Database;
Options : SQL.Options.SQL_Options) return Boolean;
function Check_Error
(Self : not null access OCI_Database;
Code : Error_Code) return Boolean;
Env : aliased Environment;
-- This is an OCI environment shared between all connections.
-- Because the environment initialized in thread mode, all threads
-- can safely use it.
-- XXX Reasons of use of global object must be here, as well as all kind of
-- considerations of its use.
end Matreshka.Internals.SQL_Drivers.Oracle.Databases;
|
30,720
|
ada
| 0
|
xuedong/mini-ada
|
tests/syntax/bad/testfile-structure-1.adb
|
<filename>tests/syntax/bad/testfile-structure-1.adb
with Ada.Text_IO; use Ada.Text_IO;
Put('a');
|
30,721
|
ada
| 0
|
SKNZ/BezierToSTL
|
src/util/liste_generique.ads
|
<gh_stars>0
generic
type Element is private;
package Liste_Generique is
type Liste is limited private; -- une liste est initialement vide
-- vide L et libere la memoire correspondante
procedure Vider(L : in out Liste);
-- insere E en tete de L
procedure Insertion_Tete(L : in out Liste ; E : Element);
-- insere E en queue de L
procedure Insertion_Queue(L : in out Liste ; E : Element);
-- appelle Traiter sur chaque element de L, dans l'ordre
generic
with procedure Traiter(E : in out Element);
procedure Parcourir(L : Liste);
-- si L = [E1 ; E2 ; ... ; En-1 ; En]
-- appelle Traiter sur chaque couple (Ei, Ei+1) pour 0 < i < n
generic
with procedure Traiter(E1, E2 : in Element);
procedure Parcourir_Par_Couples(L : Liste);
--fusionne L2 a la fin de L1; en sortie L2 est vide
procedure Fusion(L1 : in out Liste ; L2 : in out Liste);
-- nombre d'éléments de L
function Taille(L : Liste) return Natural;
-- requiert Taille(L) /= 0
function Tete(L : Liste) return Element;
-- requiert Taille(L) /= 0
function Queue(L : Liste) return Element;
private
type Cellule;
type Pointeur is access Cellule;
type Cellule is record
Contenu : Element;
Suivant : Pointeur;
end record;
type Liste is record
Debut, Fin : Pointeur := null;
Taille : Natural := 0;
end record;
end;
|
30,722
|
ada
| 192
|
rocher/Ada_Drivers_Library
|
arch/ARM/STM32/svd/stm32f7x9/stm32_svd-cec.ads
|
<filename>arch/ARM/STM32/svd/stm32f7x9/stm32_svd-cec.ads
-- This spec has been automatically generated from STM32F7x9.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package STM32_SVD.CEC is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- control register
type CR_Register is record
-- CEC Enable
CECEN : Boolean := False;
-- Tx start of message
TXSOM : Boolean := False;
-- Tx End Of Message
TXEOM : Boolean := False;
-- unspecified
Reserved_3_31 : HAL.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR_Register use record
CECEN at 0 range 0 .. 0;
TXSOM at 0 range 1 .. 1;
TXEOM at 0 range 2 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
subtype CFGR_SFT_Field is HAL.UInt3;
subtype CFGR_OAR_Field is HAL.UInt15;
-- configuration register
type CFGR_Register is record
-- Signal Free Time
SFT : CFGR_SFT_Field := 16#0#;
-- Rx-Tolerance
RXTOL : Boolean := False;
-- Rx-stop on bit rising error
BRESTP : Boolean := False;
-- Generate error-bit on bit rising error
BREGEN : Boolean := False;
-- Generate Error-Bit on Long Bit Period Error
LBPEGEN : Boolean := False;
-- Avoid Error-Bit Generation in Broadcast
BRDNOGEN : Boolean := False;
-- SFT Option Bit
SFTOP : Boolean := False;
-- unspecified
Reserved_9_15 : HAL.UInt7 := 16#0#;
-- Own addresses configuration
OAR : CFGR_OAR_Field := 16#0#;
-- Listen mode
LSTN : Boolean := False;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CFGR_Register use record
SFT at 0 range 0 .. 2;
RXTOL at 0 range 3 .. 3;
BRESTP at 0 range 4 .. 4;
BREGEN at 0 range 5 .. 5;
LBPEGEN at 0 range 6 .. 6;
BRDNOGEN at 0 range 7 .. 7;
SFTOP at 0 range 8 .. 8;
Reserved_9_15 at 0 range 9 .. 15;
OAR at 0 range 16 .. 30;
LSTN at 0 range 31 .. 31;
end record;
subtype TXDR_TXD_Field is HAL.UInt8;
-- Tx data register
type TXDR_Register is record
-- Write-only. Tx Data register
TXD : TXDR_TXD_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 TXDR_Register use record
TXD at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype RXDR_RXDR_Field is HAL.UInt8;
-- Rx Data Register
type RXDR_Register is record
-- Read-only. CEC Rx Data Register
RXDR : RXDR_RXDR_Field;
-- unspecified
Reserved_8_31 : HAL.UInt24;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for RXDR_Register use record
RXDR at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- Interrupt and Status Register
type ISR_Register is record
-- Rx-Byte Received
RXBR : Boolean := False;
-- End Of Reception
RXEND : Boolean := False;
-- Rx-Overrun
RXOVR : Boolean := False;
-- Rx-Bit rising error
BRE : Boolean := False;
-- Rx-Short Bit period error
SBPE : Boolean := False;
-- Rx-Long Bit Period Error
LBPE : Boolean := False;
-- Rx-Missing Acknowledge
RXACKE : Boolean := False;
-- Arbitration Lost
ARBLST : Boolean := False;
-- Tx-Byte Request
TXBR : Boolean := False;
-- End of Transmission
TXEND : Boolean := False;
-- Tx-Buffer Underrun
TXUDR : Boolean := False;
-- Tx-Error
TXERR : Boolean := False;
-- Tx-Missing acknowledge error
TXACKE : Boolean := False;
-- unspecified
Reserved_13_31 : HAL.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ISR_Register use record
RXBR at 0 range 0 .. 0;
RXEND at 0 range 1 .. 1;
RXOVR at 0 range 2 .. 2;
BRE at 0 range 3 .. 3;
SBPE at 0 range 4 .. 4;
LBPE at 0 range 5 .. 5;
RXACKE at 0 range 6 .. 6;
ARBLST at 0 range 7 .. 7;
TXBR at 0 range 8 .. 8;
TXEND at 0 range 9 .. 9;
TXUDR at 0 range 10 .. 10;
TXERR at 0 range 11 .. 11;
TXACKE at 0 range 12 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
-- interrupt enable register
type IER_Register is record
-- Rx-Byte Received Interrupt Enable
RXBRIE : Boolean := False;
-- End Of Reception Interrupt Enable
RXENDIE : Boolean := False;
-- Rx-Buffer Overrun Interrupt Enable
RXOVRIE : Boolean := False;
-- Bit Rising Error Interrupt Enable
BREIE : Boolean := False;
-- Short Bit Period Error Interrupt Enable
SBPEIE : Boolean := False;
-- Long Bit Period Error Interrupt Enable
LBPEIE : Boolean := False;
-- Rx-Missing Acknowledge Error Interrupt Enable
RXACKIE : Boolean := False;
-- Arbitration Lost Interrupt Enable
ARBLSTIE : Boolean := False;
-- Tx-Byte Request Interrupt Enable
TXBRIE : Boolean := False;
-- Tx-End of message interrupt enable
TXENDIE : Boolean := False;
-- Tx-Underrun interrupt enable
TXUDRIE : Boolean := False;
-- Tx-Error Interrupt Enable
TXERRIE : Boolean := False;
-- Tx-Missing Acknowledge Error Interrupt Enable
TXACKIE : Boolean := False;
-- unspecified
Reserved_13_31 : HAL.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for IER_Register use record
RXBRIE at 0 range 0 .. 0;
RXENDIE at 0 range 1 .. 1;
RXOVRIE at 0 range 2 .. 2;
BREIE at 0 range 3 .. 3;
SBPEIE at 0 range 4 .. 4;
LBPEIE at 0 range 5 .. 5;
RXACKIE at 0 range 6 .. 6;
ARBLSTIE at 0 range 7 .. 7;
TXBRIE at 0 range 8 .. 8;
TXENDIE at 0 range 9 .. 9;
TXUDRIE at 0 range 10 .. 10;
TXERRIE at 0 range 11 .. 11;
TXACKIE at 0 range 12 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- HDMI-CEC controller
type CEC_Peripheral is record
-- control register
CR : aliased CR_Register;
-- configuration register
CFGR : aliased CFGR_Register;
-- Tx data register
TXDR : aliased TXDR_Register;
-- Rx Data Register
RXDR : aliased RXDR_Register;
-- Interrupt and Status Register
ISR : aliased ISR_Register;
-- interrupt enable register
IER : aliased IER_Register;
end record
with Volatile;
for CEC_Peripheral use record
CR at 16#0# range 0 .. 31;
CFGR at 16#4# range 0 .. 31;
TXDR at 16#8# range 0 .. 31;
RXDR at 16#C# range 0 .. 31;
ISR at 16#10# range 0 .. 31;
IER at 16#14# range 0 .. 31;
end record;
-- HDMI-CEC controller
CEC_Periph : aliased CEC_Peripheral
with Import, Address => System'To_Address (16#40006C00#);
end STM32_SVD.CEC;
|
30,723
|
ada
| 0
|
fintatarta/protypo
|
test/examples/Project/partners.ads
|
<reponame>fintatarta/protypo
package Partners is
type Partner_Type is null record;
end Partners;
|
30,724
|
ada
| 0
|
pat-rogers/OpenUxAS
|
src/ada/src/uxas-comms-lmcp_object_message_receiver_pipes.ads
|
-- see OpenUxAS\src\Communications\LmcpObjectMessageReceiverPipe.h
with AVTAS.LMCP.Object;
with UxAS.Comms.Data.LMCP_Messages;
with UxAS.Comms.Data.Addressed.Attributed;
with UxAS.Comms.Transport.Receiver.ZeroMQ.Addr_Attr_Msg_Receivers;
use AVTAS.LMCP.Object;
use UxAS.Comms.Data.LMCP_Messages;
use UxAS.Comms.Data.Addressed.Attributed;
use UxAS.Comms.Transport.Receiver.ZeroMQ.Addr_Attr_Msg_Receivers;
package UxAS.Comms.LMCP_Object_Message_Receiver_Pipes is
type LMCP_Object_Message_Receiver_Pipe is tagged limited private;
-- void
-- initializePull(uint32_t entityId, uint32_t serviceId);
procedure Initialize_Pull
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32);
-- void
-- initializeExternalSubscription(uint32_t entityId, uint32_t serviceId, const std::string& externalSocketAddress, bool isServer);
procedure Initialize_External_Subscription
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
External_Socket_Address : String;
Is_Server : Boolean);
-- void
-- initializeExternalPull(uint32_t entityId, uint32_t serviceId, const std::string& externalSocketAddress, bool isServer);
procedure Initialize_External_Pull
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
External_Socket_Address : String;
Is_Server : Boolean);
-- void
-- initializeSubscription(uint32_t entityId, uint32_t serviceId);
procedure Initialize_Subscription
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32);
-- void
-- initializeStream(uint32_t entityId, uint32_t serviceId, const std::string& socketAddress, bool isServer);
procedure Initialize_Stream
(This : in out LMCP_Object_Message_Receiver_Pipe;
Entity_Id : UInt32;
Service_Id : UInt32;
Socket_Address : String;
Is_Server : Boolean);
-- bool
-- addLmcpObjectSubscriptionAddress(const std::string& address);
procedure Add_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Address : String;
Result : out Boolean);
-- bool
-- removeLmcpObjectSubscriptionAddress(const std::string& address);
procedure Remove_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Address : String;
Result : out Boolean);
-- bool
-- removeAllLmcpObjectSubscriptionAddresses();
procedure Remove_All_Lmcp_Object_Subscription_Address
(This : in out LMCP_Object_Message_Receiver_Pipe;
Result : out Boolean);
-- std::unique_ptr<uxas::communications::data::LmcpMessage>
-- getNextMessageObject();
procedure Get_Next_Message_Object
(This : in out LMCP_Object_Message_Receiver_Pipe;
Message : out Any_Lmcp_Message);
-- std::unique_ptr<uxas::communications::data::AddressedAttributedMessage>
-- getNextSerializedMessage();
procedure Get_Next_Serialized_Message
(This : in out LMCP_Object_Message_Receiver_Pipe;
Message : out Addressed_Attributed_Message_Ref);
-- std::unique_ptr<avtas::lmcp::Object>
-- deserializeMessage(const std::string& payload);
procedure Deserialize_Message
(This : in out LMCP_Object_Message_Receiver_Pipe;
Payload : String;
Message : out not null AVTAS.LMCP.Object.Object_Any);
-- These attributes are public in the C++ version so we provide getters
-- (since that seems to be the need) rather than define the full ADT as a
-- public tagged record type with the4se two components visible, combined
-- with a component of a private type containing the private/protected
-- members
--
-- uint32_t m_entityId;
-- uint32_t m_serviceId;
function Entity_Id (This : LMCP_Object_Message_Receiver_Pipe) return UInt32;
function Service_Id (This : LMCP_Object_Message_Receiver_Pipe) return UInt32;
private
type LMCP_Object_Message_Receiver_Pipe is tagged limited record
Entity_Id : UInt32;
Service_Id : UInt32;
-- std::unique_ptr<uxas::communications::transport::ZeroMqAddressedAttributedMessageReceiver> m_transportReceiver;
Receiver : ZeroMq_Addressed_Attributed_Message_Receiver_Ref;
end record;
end UxAS.Comms.LMCP_Object_Message_Receiver_Pipes;
|
30,725
|
ada
| 0
|
jgrivera67/projects-with-amy
|
array_utils/src/array_utils.adb
|
--
-- Copyright (c) 2022, <NAME>
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
--
package body Array_Utils is
function Linear_Search (A : Array_Type; Value : Element_Type) return Natural is
begin
for I in A'Range loop
if A (I) = Value then
return I;
end if;
end loop;
return 0;
end Linear_Search;
function Binary_Search (A : Array_Type; Value : Element_Type) return Natural is
begin
-- TODO: Implement the binary search algorithm
return 0;
end Binary_Search;
end Array_Utils;
|
30,726
|
ada
| 15
|
My-Colaborations/dynamo
|
src/asis/a4g-decl_sem.adb
|
<filename>src/asis/a4g-decl_sem.adb<gh_stars>10-100
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . D E C L _ S E M --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-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 --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY 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 ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adac<EMAIL>). --
-- --
------------------------------------------------------------------------------
-- This package contains routines needed for semantic queries from
-- the Asis.Declarations package
with Asis.Declarations; use Asis.Declarations;
with Asis.Definitions; use Asis.Definitions;
with Asis.Iterator; use Asis.Iterator;
with Asis.Elements; use Asis.Elements;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Extensions; use Asis.Extensions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Sem; use A4G.A_Sem;
with A4G.Int_Knds; use A4G.Int_Knds;
with A4G.Vcheck; use A4G.Vcheck;
with A4G.Mapping; use A4G.Mapping;
with Atree; use Atree;
with Einfo; use Einfo;
with Namet; use Namet;
with Nlists; use Nlists;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
package body A4G.Decl_Sem is
-----------------------------
-- Corresponding_Body_Node --
-----------------------------
function Corresponding_Body_Node (Decl_Node : Node_Id) return Node_Id is
Result_Node : Node_Id;
begin
Result_Node := Corresponding_Body (Decl_Node);
if No (Result_Node) then
-- package without a body
return Result_Node;
end if;
Result_Node := Parent (Result_Node);
if Nkind (Result_Node) = N_Defining_Program_Unit_Name then
Result_Node := Parent (Result_Node);
end if;
if Nkind (Result_Node) = N_Function_Specification or else
Nkind (Result_Node) = N_Procedure_Specification
then
Result_Node := Parent (Result_Node);
end if;
if Nkind (Parent (Result_Node)) = N_Subunit then
-- we come back to the stub!
Result_Node := Corresponding_Stub (Parent (Result_Node));
end if;
if not Comes_From_Source (Result_Node)
and then
not (Is_Rewrite_Substitution (Result_Node)
-- SCz
-- and then
-- Nkind (Original_Node (Result_Node)) = N_Expression_Function)
)
then
-- implicit body created by the compiler for renaming-as-body.
-- the renaming itself is the previous list member, so
Result_Node := Get_Renaming_As_Body (Decl_Node);
end if;
return Result_Node;
end Corresponding_Body_Node;
-----------------------------
-- Corresponding_Decl_Node --
-----------------------------
function Corresponding_Decl_Node (Body_Node : Node_Id) return Node_Id is
Result_Node : Node_Id := Empty;
Protected_Def_Node : Node_Id;
Tmp_Node : Node_Id := Empty;
begin
case Nkind (Body_Node) is
when N_Body_Stub =>
Result_Node := Corr_Decl_For_Stub (Body_Node);
when N_Entry_Body =>
Protected_Def_Node := Corresponding_Spec (Parent (Body_Node));
if Ekind (Protected_Def_Node) = E_Limited_Private_Type then
Protected_Def_Node := Full_View (Protected_Def_Node);
end if;
Protected_Def_Node := Parent (Protected_Def_Node);
Protected_Def_Node := Protected_Definition (Protected_Def_Node);
Tmp_Node :=
First_Non_Pragma (Visible_Declarations (Protected_Def_Node));
while Present (Tmp_Node) loop
if Nkind (Tmp_Node) = N_Entry_Declaration and then
Parent (Corresponding_Body (Tmp_Node)) = Body_Node
then
Result_Node := Tmp_Node;
exit;
end if;
Tmp_Node := Next_Non_Pragma (Tmp_Node);
end loop;
if No (Result_Node) and then
Present (Private_Declarations (Protected_Def_Node))
then
Tmp_Node :=
First_Non_Pragma (Private_Declarations (Protected_Def_Node));
while Present (Tmp_Node) loop
if Nkind (Tmp_Node) = N_Entry_Declaration and then
Parent (Corresponding_Body (Tmp_Node)) = Body_Node
then
Result_Node := Tmp_Node;
exit;
end if;
Tmp_Node := Next_Non_Pragma (Tmp_Node);
end loop;
end if;
when others =>
Result_Node := Corresponding_Spec (Body_Node);
Result_Node := Parent (Result_Node);
if Nkind (Result_Node) = N_Defining_Program_Unit_Name then
Result_Node := Parent (Result_Node);
end if;
end case;
pragma Assert (Present (Result_Node));
-- now - from a defining entity to the declaration itself; note,
-- that here we cannot get a defining expanded name, because the
-- corresponding declaration for library units are obtained in
-- another control flow
case Nkind (Result_Node) is
when N_Function_Specification |
N_Procedure_Specification |
N_Package_Specification =>
Result_Node := Parent (Result_Node);
when N_Private_Type_Declaration =>
-- this is the case when a task type is the completion
-- of a private type
Result_Node := Full_View (Defining_Identifier (Result_Node));
Result_Node := Parent (Result_Node);
when others =>
null;
end case;
return Result_Node;
end Corresponding_Decl_Node;
---------------------------------------
-- Get_Corresponding_Generic_Element --
---------------------------------------
function Get_Corresponding_Generic_Element
(Gen_Unit : Asis.Declaration;
Def_Name : Asis.Element)
return Asis.Element
is
Kind_To_Check : constant Internal_Element_Kinds := Int_Kind (Def_Name);
Sloc_To_Check : constant Source_Ptr := Sloc (Node (Def_Name));
Line_To_Check : constant Physical_Line_Number :=
Get_Physical_Line_Number (Sloc_To_Check);
Column_To_Check : constant Column_Number :=
Get_Column_Number (Sloc_To_Check);
Result_Element : Asis.Element := Nil_Element;
Tmp_El : Asis.Element;
Check_Inherited_Element : constant Boolean :=
Is_Part_Of_Inherited (Def_Name);
Sloc_To_Check_1 : constant Source_Ptr := Sloc (Node_Field_1 (Def_Name));
Line_To_Check_1 : constant Physical_Line_Number :=
Get_Physical_Line_Number (Sloc_To_Check_1);
Column_To_Check_1 : constant Column_Number :=
Get_Column_Number (Sloc_To_Check_1);
-- Used in case if we are looking for an implicit Element
function Is_Found (E : Asis.Element) return Boolean;
-- Checks if the Element being traversed is a corresponding generic
-- element for Def_Name
function Is_Found (E : Asis.Element) return Boolean is
Elem_Sloc : constant Source_Ptr := Sloc (Node (E));
Elem_Sloc_1 : Source_Ptr;
Result : Boolean := False;
begin
if not (Check_Inherited_Element xor Is_Part_Of_Inherited (E)) then
Result :=
Line_To_Check = Get_Physical_Line_Number (Elem_Sloc)
and then
Column_To_Check = Get_Column_Number (Elem_Sloc);
if Result
and then
Check_Inherited_Element
then
Elem_Sloc_1 := Sloc (Node_Field_1 (E));
Result :=
Line_To_Check_1 = Get_Physical_Line_Number (Elem_Sloc_1)
and then
Column_To_Check_1 = Get_Column_Number (Elem_Sloc_1);
end if;
end if;
return Result;
end Is_Found;
-- and now, variables and actuals for Traverse_Element
My_Control : Traverse_Control := Continue;
My_State : No_State := Not_Used;
procedure Pre_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out No_State);
procedure Look_For_Corr_Gen_El is new Traverse_Element
(State_Information => No_State,
Pre_Operation => Pre_Op,
Post_Operation => No_Op);
procedure Pre_Op
(Element : Asis.Element;
Control : in out Traverse_Control;
State : in out No_State)
is
pragma Unreferenced (State);
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Element);
begin
case Arg_Kind is
when An_Internal_Body_Stub =>
if Kind_To_Check = A_Defining_Identifier or else
Kind_To_Check in Internal_Defining_Operator_Kinds
then
-- We have to traverse the code of the subunit -
-- see 9217-015. But before doing this, let's check the
-- name of the subunit:
Tmp_El := Asis.Declarations.Names (Element) (1);
if Int_Kind (Tmp_El) = Kind_To_Check and then
Is_Found (Tmp_El)
then
Result_Element := Tmp_El;
Control := Terminate_Immediately;
return;
end if;
end if;
-- If we are here, we have to traverse the proper body:
Tmp_El := Corresponding_Subunit (Element);
if not Is_Nil (Tmp_El) then
Look_For_Corr_Gen_El (Element => Tmp_El,
Control => My_Control,
State => My_State);
end if;
when Internal_Defining_Name_Kinds =>
if Int_Kind (Element) = Kind_To_Check and then
Is_Found (Element)
then
Result_Element := Element;
Control := Terminate_Immediately;
end if;
when A_Derived_Type_Definition |
A_Derived_Record_Extension_Definition |
A_Formal_Derived_Type_Definition =>
if Check_Inherited_Element then
declare
Inherited_Decls : constant Asis.Element_List :=
Implicit_Inherited_Declarations (Element);
Inherited_Subprgs : constant Asis.Element_List :=
Implicit_Inherited_Subprograms (Element);
begin
for J in Inherited_Decls'Range loop
exit when My_Control = Terminate_Immediately;
Look_For_Corr_Gen_El
(Element => Inherited_Decls (J),
Control => My_Control,
State => My_State);
end loop;
for J in Inherited_Subprgs'Range loop
exit when My_Control = Terminate_Immediately;
Look_For_Corr_Gen_El
(Element => Inherited_Subprgs (J),
Control => My_Control,
State => My_State);
end loop;
end;
end if;
when others =>
null;
end case;
end Pre_Op;
begin -- Get_Corresponding_Generic_Element
Look_For_Corr_Gen_El (Element => Gen_Unit,
Control => My_Control,
State => My_State);
return Result_Element;
exception
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Argument => Nil_Element,
Outer_Call => "A4G.Decl_Sem.Get_Corresponding_Generic_Element");
end if;
raise;
end Get_Corresponding_Generic_Element;
-----------------------
-- Get_Expanded_Spec --
-----------------------
function Get_Expanded_Spec (Instance_Node : Node_Id) return Node_Id is
Result_Node : Node_Id;
begin
-- GNAT constructs the structure corresponding to an expanded generic
-- specification just before the instantiation itself, except the case
-- of the formal package with box:
if Nkind (Instance_Node) = N_Package_Declaration and then
Nkind (Original_Node (Instance_Node)) = N_Formal_Package_Declaration
then
Result_Node := Instance_Node;
else
Result_Node := Prev_Non_Pragma (Instance_Node);
end if;
if Nkind (Result_Node) = N_Package_Body then
-- Here we have the expanded generic body, therefore - one
-- more step up the list
Result_Node := Prev_Non_Pragma (Result_Node);
end if;
-- in case of a package instantiation, we have to take the whole
-- expanded package, but in case of a subprogram instantiation we
-- need only the subprogram declaration, which is the last element
-- of the visible declarations list of the "artificial" package
-- spec created by the compiler
if not (Nkind (Instance_Node) = N_Package_Instantiation or else
Nkind (Original_Node (Instance_Node)) =
N_Formal_Package_Declaration)
then
Result_Node := Last_Non_Pragma (Visible_Declarations
(Specification (Result_Node)));
if Nkind (Result_Node) = N_Subprogram_Body then
Result_Node := Parent (Parent (Corresponding_Spec (Result_Node)));
end if;
pragma Assert (Nkind (Result_Node) = N_Subprogram_Declaration);
end if;
return Result_Node;
end Get_Expanded_Spec;
--------------------------
-- Get_Renaming_As_Body --
--------------------------
function Get_Renaming_As_Body
(Node : Node_Id;
Spec_Only : Boolean := False)
return Node_Id
is
Entity_Node : Node_Id;
Scope_Node : Node_Id;
Result_Node : Node_Id := Empty;
List_To_Search : List_Id;
Search_Node : Node_Id := Node;
-- in the first List_To_Search we start not from the very beginning;
-- but from the node representing the argument subprogram declaration
Completion_Found : Boolean := False;
procedure Search_In_List;
-- looks for a possible renaming-as-bode node being a completion for
-- Node, using global settings for List_To_Search and Search_Node
procedure Search_In_List is
begin
while Present (Search_Node) loop
if Nkind (Search_Node) = N_Subprogram_Renaming_Declaration and then
Corresponding_Spec (Search_Node) = Entity_Node
then
Result_Node := Search_Node;
Completion_Found := True;
return;
end if;
Search_Node := Next_Non_Pragma (Search_Node);
end loop;
end Search_In_List;
begin -- Get_Renaming_As_Body
Entity_Node := Defining_Unit_Name (Specification (Node));
List_To_Search := List_Containing (Node);
Search_In_List;
if Completion_Found then
goto end_of_search;
end if;
-- here we have to see, where we are. If we are not in a package,
-- we have nothing to do, but if we are in the package, we may
-- have to search again in another lists (the private part and
-- the body)
Scope_Node := Scope (Entity_Node);
-- Node here can be of N_Subprogram_Declaration only!
if Nkind (Parent (Scope_Node)) = N_Implicit_Label_Declaration then
-- this is the implicit name created for a block statement,
-- so we do not have any other list to search in
goto end_of_search;
else
Scope_Node := Parent (Scope_Node);
end if;
if Nkind (Scope_Node) = N_Defining_Program_Unit_Name then
Scope_Node := Parent (Scope_Node);
end if;
-- now if we are not in N_Package_Specification, we have no
-- other list to search in
if Nkind (Scope_Node) /= N_Package_Specification then
goto end_of_search;
end if;
-- and here we are in N_Package_Specification
if List_To_Search = Visible_Declarations (Scope_Node) then
-- continuing in the private part:
List_To_Search := Private_Declarations (Scope_Node);
if not (No (List_To_Search)
or else Is_Empty_List (List_To_Search))
then
Search_Node := First_Non_Pragma (List_To_Search);
Search_In_List;
end if;
if Completion_Found or else Spec_Only then
goto end_of_search;
end if;
end if;
-- and here we have to go into the package body, if any:
Scope_Node := Corresponding_Body (Parent (Scope_Node));
if Present (Scope_Node) then
while Nkind (Scope_Node) /= N_Package_Body loop
Scope_Node := Parent (Scope_Node);
end loop;
-- and to continue to search in the package body:
List_To_Search := Sinfo.Declarations (Scope_Node);
if not (No (List_To_Search)
or else Is_Empty_List (List_To_Search))
then
Search_Node := First_Non_Pragma (List_To_Search);
Search_In_List;
end if;
end if;
<< end_of_search >>
return Result_Node;
end Get_Renaming_As_Body;
-----------------------
-- Serach_First_View --
-----------------------
function Serach_First_View (Type_Entity : Entity_Id) return Entity_Id is
Type_Chars : constant Name_Id := Chars (Type_Entity);
Type_Decl : constant Node_Id := Parent (Type_Entity);
Result_Node : Node_Id := Empty;
Scope_Node : Node_Id;
Scope_Kind : Node_Kind;
Search_List : List_Id;
Private_Decls_Passed : Boolean := False;
procedure Sesrch_In_List (L : List_Id);
-- we have a separate procedure for searching in a list of
-- declarations, because we have to do this search from one to
-- three times in case of a package. This procedure uses Type_Chars,
-- Type_Decl and Result_Node as global values, and it sets
-- Result_Node equal to the node defining the type with the same name
-- as the name of the type represented by Type_Entity, if the
-- search is successful, otherwise it remains is equal to Empty.
-- this procedure supposes, that L is not No_List
procedure Sesrch_In_List (L : List_Id) is
Next_Decl : Node_Id;
Next_Decl_Original : Node_Id;
Next_Kind : Node_Kind;
begin
Next_Decl := First_Non_Pragma (L);
Next_Decl_Original := Original_Node (Next_Decl);
Next_Kind := Nkind (Next_Decl_Original);
while Present (Next_Decl) loop
if (Comes_From_Source (Next_Decl_Original)
and then
(Next_Kind = N_Full_Type_Declaration or else
Next_Kind = N_Task_Type_Declaration or else
Next_Kind = N_Protected_Type_Declaration or else
Next_Kind = N_Private_Type_Declaration or else
Next_Kind = N_Private_Extension_Declaration or else
Next_Kind = N_Formal_Type_Declaration or else
-- impossible in ASIS, but possible in the tree
-- because of the tree rewritings
Next_Kind = N_Incomplete_Type_Declaration))
-- these cases correspond to non-rewritten type
-- declarations
or else
(not (Comes_From_Source (Next_Decl_Original))
and then
Next_Kind = N_Subtype_Declaration)
-- the declaration of a derived type rewritten into a
-- subtype declaration
then
if Is_Not_Duplicated_Decl (Next_Decl) then
-- ??? <tree problem 2> - we need this "if" only because of this problem
if Next_Decl_Original = Type_Decl then
-- no private or incomplete view
Result_Node := Type_Entity;
return;
end if;
if Type_Chars = Chars (Defining_Identifier (Next_Decl)) then
-- we've found something...
Result_Node := Defining_Identifier (Next_Decl);
return;
end if;
end if;
end if;
Next_Decl := Next_Non_Pragma (Next_Decl);
Next_Decl_Original := Original_Node (Next_Decl);
Next_Kind := Nkind (Next_Decl_Original);
end loop;
end Sesrch_In_List;
begin -- Serach_First_View
-- first, defining the scope of the Type_Entity. In case of a package
-- body it will be a package spec anyway.
Scope_Node := Scope (Type_Entity);
if Nkind (Parent (Scope_Node)) = N_Implicit_Label_Declaration then
-- this is the implicit name created for a block statement
Scope_Node := Parent (Block_Node (Scope_Node));
else
Scope_Node := Parent (Scope_Node);
end if;
if Nkind (Scope_Node) = N_Defining_Program_Unit_Name then
Scope_Node := Parent (Scope_Node);
end if;
-- now we are in N_Function_Specification, N_Procedure_Specification
-- or in N_Package_Specification
Scope_Kind := Nkind (Scope_Node);
if Scope_Kind = N_Function_Specification or else
Scope_Kind = N_Procedure_Specification
then
-- we do not do this additional step for packages, because
-- N_Package_Specification_Node already contains references to
-- declaration lists, and for a package we gave to start from the
-- declarations in the package spec, but for a subprogram
-- we have to go to a subprogram body, because nothing interesting
-- for this function can be declared in a separate subprogram
-- specification (if any) or in a generic formal part (if any)
Scope_Node := Parent (Scope_Node);
Scope_Kind := Nkind (Scope_Node);
end if;
if Scope_Kind = N_Subprogram_Declaration
or else
Scope_Kind = N_Generic_Subprogram_Declaration
or else
Scope_Kind = N_Task_Type_Declaration
or else
Scope_Kind = N_Entry_Declaration
or else
Scope_Kind = N_Subprogram_Body_Stub
then
Scope_Node := Corresponding_Body (Scope_Node);
Scope_Node := Parent (Scope_Node);
if Nkind (Scope_Node) = N_Defining_Program_Unit_Name then
Scope_Node := Parent (Scope_Node);
end if;
if Nkind (Scope_Node) = N_Function_Specification or else
Nkind (Scope_Node) = N_Procedure_Specification
then
Scope_Node := Parent (Scope_Node);
end if;
Scope_Kind := Nkind (Scope_Node);
end if;
-- now, defining the list to search. In case of generics, we do not
-- have to start from parsing the list of generic parameters, because
-- a generic formal type cannot have a completion as its full view,
-- and it cannot be a completion of some other type.
if Scope_Kind = N_Subprogram_Body or else
Scope_Kind = N_Task_Body or else
Scope_Kind = N_Block_Statement or else
Scope_Kind = N_Entry_Body
then
Search_List := Sinfo.Declarations (Scope_Node);
elsif Scope_Kind = N_Package_Specification then
Search_List := Visible_Declarations (Scope_Node);
if Is_Empty_List (Search_List) then
-- note, that Visible_Declarations cannot be No_List
Private_Decls_Passed := True;
Search_List := Private_Declarations (Scope_Node);
if No (Search_List) or else Is_Empty_List (Search_List) then
-- here we should go to the declarative part of the package
-- body. Note, that if we are in a legal ada program, and if
-- we start from a type declaration, Search_List cannot
-- be No_List or an empty list
Scope_Node := Parent (Corresponding_Body (Parent (Scope_Node)));
-- note, that Search_Kind is unchanged here
Search_List := Sinfo.Declarations (Scope_Node);
end if;
end if;
end if;
Sesrch_In_List (Search_List);
if Result_Node /= Empty then
if Result_Node /= Type_Entity and then
Full_View (Result_Node) /= Type_Entity
then
-- The case when Type_Entity is a full type declaration that
-- completes a private type/extension declaration that in turn
-- completes an incomplete type.
Result_Node := Full_View (Result_Node);
end if;
return Result_Node;
end if;
-- it is possible only for a package - we have to continue in the
-- private part or/and in the body
pragma Assert (Scope_Kind = N_Package_Specification);
-- first, try a private part, if needed and if any
if not Private_Decls_Passed then
-- Scope_Node is still of N_Package_Specification kind here!
Private_Decls_Passed := True;
Search_List := Private_Declarations (Scope_Node);
if Present (Search_List) and then Is_Non_Empty_List (Search_List) then
Sesrch_In_List (Search_List);
if Result_Node /= Empty then
return Result_Node;
end if;
end if;
end if;
-- if we are here, Scope_Node is still of N_Package_Specification,
-- and the only thing we have to do now is to check the package
-- body
-- There is some redundancy in the code - in fact, we need only
-- one boolean flag (Private_Decls_Passed) to control the search in
-- case of a package
Scope_Node := Parent (Corresponding_Body (Parent (Scope_Node)));
if Nkind (Scope_Node) = N_Defining_Program_Unit_Name then
Scope_Node := Parent (Scope_Node);
end if;
Search_List := Sinfo.Declarations (Scope_Node);
Sesrch_In_List (Search_List);
if Result_Node /= Empty then
return Result_Node;
else
pragma Assert (False);
return Empty;
end if;
end Serach_First_View;
end A4G.Decl_Sem;
|
30,727
|
ada
| 0
|
skill-lang/adaCommon
|
tester.adb
|
with Skill.Streams.Reader;
procedure Tester is
begin
null;
end Tester;
|
30,728
|
ada
| 4
|
MOUDDENEHamza/ENSEEIHT
|
1A/S5/PIM/tps/tp6/test_piles.adb
|
<gh_stars>1-10
with Piles;
-- Programme de test du module Pile.
procedure Test_Piles is
package Pile_Caractere is
new Piles (T_Element => Character);
use Pile_Caractere;
-- Initialiser une pile avec 'O' puis 'K' empilés dans la pile vide.
procedure Initialiser_Avec_OK (Pile : out T_Pile) is
begin
Initialiser (Pile);
Empiler (Pile, 'O');
Empiler (Pile, 'K');
end Initialiser_Avec_OK;
procedure Tester_Est_Vide is
Pile1, Pile2 : T_Pile;
begin
Initialiser (Pile1);
pragma Assert (Est_Vide (Pile1));
Empiler (Pile1, 'A');
pragma Assert (not Est_Vide (Pile1));
Initialiser_Avec_OK (Pile2);
pragma Assert (not Est_Vide (Pile2));
end Tester_Est_Vide;
procedure Tester_Empiler is
Pile1 : T_Pile;
begin
Initialiser_Avec_OK (Pile1);
Empiler (Pile1, 'N');
pragma Assert ('N' = Sommet (Pile1));
end Tester_Empiler;
procedure Tester_Depiler is
Pile1 : T_Pile;
begin
Initialiser_Avec_OK (Pile1);
Depiler (Pile1);
pragma Assert ('O' = Sommet (Pile1));
Depiler (Pile1);
pragma Assert (Est_Vide (Pile1));
end Tester_Depiler;
begin
Tester_Est_Vide;
Tester_Empiler;
Tester_Depiler;
end Test_Piles;
|
30,729
|
ada
| 4
|
jerry-sky/academic-notebook
|
electives/pw/lab/lista-3/ada/logger.adb
|
<reponame>jerry-sky/academic-notebook
package body Logger is
task body LoggerReceiver is
exitTask: Boolean := False;
begin
loop
select
accept Log(message: String) do
PrintBounded(message);
end Log;
or
accept Stop do
-- allow for pending requests to be fulfilled
loop
select
accept Log(message: String) do
PrintBounded(message);
end Log;
or
delay 1.0;
exit;
end select;
end loop;
exitTask := True;
end Stop;
end select;
if exitTask then
exit;
end if;
end loop;
end LoggerReceiver;
end Logger;
|
30,730
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c4/c45210a.ada
|
-- C45210A.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 AN ENUMERATION IMPOSING AN "UNNATURAL" ORDER ON ALPHABETIC
-- CHARACTERS CORRECTLY EVALUATES THE ORDERING OPERATORS.
-- RM 15 OCTOBER 1980
-- JWC 7/8/85 RENAMED TO -AB
WITH REPORT ;
PROCEDURE C45210A IS
USE REPORT;
TYPE T IS ( 'S' , 'P' , 'M' , 'R' );
MVAR : T := T'('M') ;
PVAR : T := T'('P') ;
RVAR : T := T'('R') ;
SVAR : T := T'('S') ;
ERROR_COUNT : INTEGER := 0 ; -- INITIAL VALUE ESSENTIAL
PROCEDURE BUMP IS
BEGIN
ERROR_COUNT := ERROR_COUNT +1 ;
END BUMP ;
BEGIN
TEST( "C45210A" , "CHECK THAT AN ENUMERATION IMPOSING" &
" AN ""UNNATURAL"" ORDER ON ALPHABETIC" &
" CHARACTERS CORRECTLY EVALUATES THE " &
" ORDERING OPERATORS" ) ;
-- 256 CASES ( 4 * 4 ORDERED PAIRS OF OPERAND VALUES,
-- 4 ORDERING OPERATORS: '<' , '<=' , '>' , '>='
-- (IN THE TABLE: A , B , C , D )
-- 4 VARIABLE/LITERAL FOR LEFT OPERAND,
-- VARIABLE/LITERAL FOR RIGHT OPERAND,
-- (IN THE TABLE: VV = ALPHA ,
-- VL = BETA ,
-- LV = GAMMA ,
-- LL = DELTA ) RANDOMIZED
-- INTO 16 (ONE FOR EACH PAIR OF VALUES) ACCORDING TO THE FOL-
-- LOWING GRAECO-LATIN SQUARE (WITH ADDITIONAL PROPERTIES):
-- RIGHT OPERAND: 'S' 'P' 'M' 'R'
-- LEFT
-- OPERAND:
-- 'S' A-ALPHA B-BETA C-GAMMA D-DELTA
-- 'P' C-DELTA D-GAMMA A-BETA B-ALPHA
-- 'M' D-BETA C-ALPHA B-DELTA A-GAMMA
-- 'R' B-GAMMA A-DELTA D-ALPHA C-BETA
-- (BOTH THE LATIN DIAGONAL AND THE GREEK DIAGONAL CONTAIN 4
-- DISTINCT LETTERS, NON-TRIVIALLY PERMUTED.)
-- THE ABOVE DESCRIBES PART 1 OF THE TEST. PART 2 PERFORMS AN
-- EXHAUSTIVE VERIFICATION OF THE 'VARIABLE VS. VARIABLE' CASE
-- ( VV , ALPHA ) FOR ALL 4 OPERATORS.
-----------------------------------------------------------------
-- PART 1
-- 'BUMP' MEANS 'BUMP THE ERROR COUNT'
IF T'(SVAR) < T'(SVAR) THEN BUMP ; END IF;
IF T'(SVAR) <= T'('P' ) THEN NULL; ELSE BUMP ; END IF;
IF T'('S' ) > T'(MVAR) THEN BUMP ; END IF;
IF T'('S' ) >= T'('R' ) THEN BUMP ; END IF;
IF T'('P' ) > T'('S' ) THEN NULL; ELSE BUMP ; END IF;
IF T'('P' ) >= T'(PVAR) THEN NULL; ELSE BUMP ; END IF;
IF T'(PVAR) < T'('M' ) THEN NULL; ELSE BUMP ; END IF;
IF T'(PVAR) <= T'(RVAR) THEN NULL; ELSE BUMP ; END IF;
IF T'(MVAR) >= T'('S' ) THEN NULL; ELSE BUMP ; END IF;
IF T'(MVAR) > T'(PVAR) THEN NULL; ELSE BUMP ; END IF;
IF T'('M' ) <= T'('M' ) THEN NULL; ELSE BUMP ; END IF;
IF T'('M' ) < T'(RVAR) THEN NULL; ELSE BUMP ; END IF;
IF T'('R' ) <= T'(SVAR) THEN BUMP ; END IF;
IF T'('R' ) < T'('P' ) THEN BUMP ; END IF;
IF T'(RVAR) >= T'(MVAR) THEN NULL; ELSE BUMP ; END IF;
IF T'(RVAR) > T'('R' ) THEN BUMP ; END IF;
IF ERROR_COUNT /= 0 THEN
FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE1" );
END IF;
-----------------------------------------------------------------
-- PART 2
-- 'BUMP' MEANS 'INCREASE THE COUNT FOR THE NUMBER OF <TRUE>S'
ERROR_COUNT := 0 ;
FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES
FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES
IF AVAR < BVAR THEN BUMP ; END IF; -- COUNT +:= 1
END LOOP;
END LOOP;
IF ERROR_COUNT /= 1 THEN -- THIS IS A PLAIN COUNT, NOT AN
-- ERROR COUNT
FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE2" );
END IF;
ERROR_COUNT := 0 ;
FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES
FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES
IF AVAR <= BVAR THEN BUMP ; END IF; -- COUNT +:= 3
END LOOP;
END LOOP;
IF ERROR_COUNT /= 3 THEN -- THIS IS A PLAIN COUNT, NOT AN
-- ERROR COUNT
FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE3" );
END IF;
ERROR_COUNT := 0 ;
FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES
FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES
IF AVAR > BVAR THEN BUMP ; END IF; -- COUNT +:= 5
END LOOP;
END LOOP;
IF ERROR_COUNT /= 5 THEN -- THIS IS A PLAIN COUNT, NOT AN
-- ERROR COUNT
FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE4" );
END IF;
ERROR_COUNT := 0 ;
FOR AVAR IN T'FIRST..T'LAST LOOP -- 4 VALUES
FOR BVAR IN T'FIRST..T'('P') LOOP -- 2 VALUES
IF AVAR >= BVAR THEN BUMP ; END IF; -- COUNT +:= 7
END LOOP;
END LOOP;
IF ERROR_COUNT /= 7 THEN -- THIS IS A PLAIN COUNT, NOT AN
-- ERROR COUNT
FAILED( """UNNATURAL"" ORDER ON CHARACTER TYPES - FAILURE5" );
END IF;
RESULT;
END C45210A;
|
30,731
|
ada
| 30
|
jrmarino/AdaBase
|
testcases/driver_connections/mysql/connect.ads
|
-- Used for all testcases for MySQL driver
with AdaBase.Driver.Base.MySQL;
with AdaBase.Statement.Base.MySQL;
package Connect is
-- All specific drivers renamed to "Database_Driver"
subtype Database_Driver is AdaBase.Driver.Base.MySQL.MySQL_Driver;
subtype Stmt_Type is AdaBase.Statement.Base.MySQL.MySQL_statement;
subtype Stmt_Type_access is
AdaBase.Statement.Base.MySQL.MySQL_statement_access;
DR : Database_Driver;
procedure connect_database;
end Connect;
|
30,732
|
ada
| 8
|
darkestkhan/lumen
|
joystick/lumen-joystick.adb
|
<filename>joystick/lumen-joystick.adb
-- Lumen.Joystick -- Support (Linux) joysticks under Lumen
--
-- <NAME>, NiEstu, Phoenix AZ, Summer 2010
-- This code is covered by the ISC License:
--
-- Copyright © 2010, NiEstu
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- The software is provided "as is" and the author disclaims all warranties
-- with regard to this software including all implied warranties of
-- merchantability and fitness. In no event shall the author be liable for any
-- special, direct, indirect, or consequential damages or any damages
-- whatsoever resulting from loss of use, data or profits, whether in an
-- action of contract, negligence or other tortious action, arising out of or
-- in connection with the use or performance of this software.
-- Environment
with Ada.Streams.Stream_IO;
with Ada.Unchecked_Deallocation;
with Interfaces.C.Strings;
with System;
with PQueue;
with Lumen.Binary.IO;
package body Lumen.Joystick is
---------------------------------------------------------------------------
-- The task type that reads events from the joystick
task type Joystick_Event_Task is
entry Startup (Owner : in Stick_Info_Pointer);
end Joystick_Event_Task;
---------------------------------------------------------------------------
-- Instantiate the protected-queue package with the queue-event type
package Event_Queue_Pkg is new PQueue (Joystick_Event_Data);
---------------------------------------------------------------------------
-- A simple binary semaphore
protected type Signal is
procedure Set;
entry Wait;
private
Is_Set : boolean := false;
end Signal;
---------------------------------------------------------------------------
-- Our internal view of a joystick
type Axis_Array is array (Positive range <>) of Integer;
type Button_Array is array (Positive range <>) of Boolean;
type Stick_Info (Name_Len : Natural; N_Axes : Natural; N_Buttons : Natural) is record
File : Binary.IO.File_Type;
Name : String (1 .. Name_Len);
Axes : Axis_Array (1 .. N_Axes);
Buttons : Button_Array (1 .. N_Buttons);
Shutdown : Signal;
Event_Task : Joystick_Event_Task;
Events : Event_Queue_Pkg.Protected_Queue_Type;
end record;
---------------------------------------------------------------------------
--
-- The event task, reads events from the joystick, then queues them
-- internally so the app can read them
--
---------------------------------------------------------------------------
task body Joystick_Event_Task is
------------------------------------------------------------------------
use type Binary.Byte;
------------------------------------------------------------------------
-- The Linux joystick event
type JS_Event_Type is (JS_Button, JS_Axis, JS_Init, JS_Init_Button, JS_Init_Axis);
for JS_Event_Type use (JS_Button => 16#01#, JS_Axis => 16#02#,
JS_Init => 16#80#, JS_Init_Button => 16#81#, JS_Init_Axis => 16#82#);
type JS_Event_Data is record
Time : Binary.Word;
Value : Binary.S_Short;
Which : JS_Event_Type;
Number : Binary.Byte;
end record;
Base : constant := Binary.Word_Bytes;
for JS_Event_Data use record
Time at 0 range 0 .. Binary.Word'Size - 1;
Value at Base + 0 range 0 .. Binary.S_Short'Size - 1;
Which at Base + 2 range 0 .. Binary.Byte'Size - 1;
Number at Base + 3 range 0 .. Binary.Byte'Size - 1;
end record;
------------------------------------------------------------------------
Info : Stick_Info_Pointer;
Event_Rec : JS_Event_Data;
Index : Positive;
Send : Boolean;
Event_Data : Joystick_Event_Data;
------------------------------------------------------------------------
begin -- Joystick_Event_Task
-- Lets the library tell us which joystick this task belongs to
select
accept Startup (Owner : in Stick_Info_Pointer) do
Info := Owner;
end Startup;
or
terminate;
end select;
loop
-- Wait for an event to come from the joystick, or for a shutdown
-- signal to arrive
select
Info.Shutdown.Wait;
exit;
then abort
JS_Event_Data'Read (Ada.Streams.Stream_IO.Stream (Info.File), Event_Rec);
end select;
-- Only process recogized event types
if Event_Rec.Which'Valid then
Index := Positive (Event_Rec.Number + 1); -- driver uses zero-based axis and button numbers
case Event_Rec.Which is
when JS_Init =>
Send := False; -- dunno what these are, so just ignore them
when JS_Button | JS_Init_Button =>
if Boolean'Pos (Info.Buttons (Index)) /= Natural (Event_Rec.Value) then
if Info.Buttons (Index) then
Event_Data := (Which => Joystick_Button_Release, Number => Index);
else
Event_Data := (Which => Joystick_Button_Press, Number => Index);
end if;
Info.Buttons (Index) := not Info.Buttons (Index);
Send := True;
end if;
when JS_Axis | JS_Init_Axis =>
if Info.Axes (Index) /= Integer (Event_Rec.Value) then
Info.Axes (Index) := Integer (Event_Rec.Value);
Event_Data := (Which => Joystick_Axis_Change, Number => Index, Axis_Value => Info.Axes (Index));
Send := True;
end if;
end case;
-- If we had a value change, push an event into our internal queue
if Send then
Info.Events.Enqueue (Event_Data);
end if;
end if;
end loop;
end Joystick_Event_Task;
---------------------------------------------------------------------------
-- Simple binary semaphore
protected body Signal is
-- Indicate that a shutdown has occurred
procedure Set is
begin -- Set
Is_Set := true;
end Set;
-- Block until the signal is set, then clear it
entry Wait when Is_Set is
begin -- Wait
Is_Set := false;
end Wait;
end Signal;
---------------------------------------------------------------------------
--
-- Public subroutines
--
---------------------------------------------------------------------------
procedure Finalize (Stick : in out Handle) is
begin -- Finalize
if Stick.Info /= null then
Close (Stick);
end if;
end Finalize;
---------------------------------------------------------------------------
-- Open a joystick device
procedure Open (Stick : in out Handle;
Path : in String := Default_Pathname) is
use type Interfaces.C.Strings.chars_ptr;
procedure Joystick_Info (Path : in String;
N_Axes : in System.Address;
N_Buttons : in System.Address;
Name : out Interfaces.C.Strings.chars_ptr);
pragma Import (C, Joystick_Info, "joystick_info");
procedure Free (Pointer : in System.Address);
pragma Import (C, Free, "free");
Axis_Count : Binary.Byte;
Button_Count : Binary.Byte;
Name : Interfaces.C.Strings.chars_ptr;
begin -- Open
-- Ask our C helper to fetch the device's info
Joystick_Info (Path & ASCII.NUL, Axis_Count'Address, Button_Count'Address, Name);
-- If we can't get the name, then the other values are probably no good either
if Name = Interfaces.C.Strings.Null_Ptr then
Stick.Info := null;
raise Open_Failed;
else
-- Local management data for the device
Stick.Info := new Stick_Info (Name_Len => Natural (Interfaces.C.Strings.Strlen (Name)),
N_Axes => Natural (Axis_Count),
N_Buttons => Natural (Button_Count));
Binary.IO.Open (Stick.Info.File, Path);
Stick.Info.Name := Interfaces.C.Strings.Value (Name);
Stick.Info.Axes := (others => 0);
Stick.Info.Buttons := (others => False);
-- Start the events task for this joystick device
Stick.Info.Event_Task.Startup (Stick.Info);
end if;
end Open;
---------------------------------------------------------------------------
-- Close a joystick device
procedure Close (Stick : in out Handle) is
procedure Free is new Ada.Unchecked_Deallocation (Stick_Info, Stick_Info_Pointer);
begin -- Close
-- Close down this joystick
if Stick.Info /= null then
-- Shut down this stick's event task
Stick.Info.Shutdown.Set;
-- Close the stream and free the info record
Binary.IO.Close (Stick.Info.File);
Free (Stick.Info);
end if;
end Close;
---------------------------------------------------------------------------
-- Various joystick information functions
function Name (Stick : in Handle) return String is
begin -- Name
return Stick.Info.Name;
end Name;
---------------------------------------------------------------------------
function Axes (Stick : in Handle) return Natural is
begin -- Axes
return Stick.Info.N_Axes;
end Axes;
---------------------------------------------------------------------------
function Buttons (Stick : in Handle) return Natural is
begin -- Buttons
return Stick.Info.N_Buttons;
end Buttons;
---------------------------------------------------------------------------
-- Returns the number of events that are waiting in the joystick's event
-- queue. Useful to avoid blocking while waiting for the next event to
-- show up.
function Pending (Stick : in Handle) return Natural is
begin -- Pending
return Stick.Info.Events.Length;
end Pending;
---------------------------------------------------------------------------
-- Read a joystick event
function Next_Event (Stick : in Handle) return Joystick_Event_Data is
begin -- Next_Event
return Event : Joystick_Event_Data do
-- Get next event from queue (may block) and return it
Stick.Info.Events.Dequeue (Event);
end return;
end Next_Event;
---------------------------------------------------------------------------
end Lumen.Joystick;
|
30,733
|
ada
| 2
|
skordal/cupcake
|
src/cupcake-colors.ads
|
-- The Cupcake GUI Toolkit
-- (c) <NAME> 2012 <<EMAIL>>
-- Report bugs and issues on <http://github.com/skordal/cupcake/issues>
-- vim:ts=3:sw=3:et:si:sta
package Cupcake.Colors is
-- Color component type:
subtype Color_Component_Type is Float range 0.0 .. 1.0;
-- Color type:
type Color is record
R, G, B : Color_Component_Type;
end record;
-- Multiplies all color components of a Color with a constant:
function "*" (Left : in Color; Right : in Float) return Color;
function "*" (Left : in Float; Right : in Color) return Color with Inline;
-- Predefined color constants:
BLACK : constant Color := (0.0, 0.0, 0.0);
WHITE : constant Color := (1.0, 1.0, 1.0);
RED : constant Color := (1.0, 0.0, 0.0);
GREEN : constant Color := (0.0, 1.0, 0.0);
BLUE : constant Color := (0.0, 0.0, 1.0);
DEFAULT_BACKGROUND_COLOR : constant Color := (0.85, 0.85, 0.85);
DEFAULT_FOREGROUND_COLOR : constant Color := BLACK;
end Cupcake.Colors;
|
30,734
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/varsize3_2.adb
|
-- { dg-do compile }
with Varsize3_Pkg1; use Varsize3_Pkg1;
procedure Varsize3_2 is
Filter : constant Object := True;
begin
null;
end;
|
30,735
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Best-shuffle/Ada/best-shuffle.ada
|
with Ada.Text_IO;
with Ada.Strings.Unbounded;
procedure Best_Shuffle is
function Best_Shuffle (S : String) return String;
function Best_Shuffle (S : String) return String is
T : String (S'Range) := S;
Tmp : Character;
begin
for I in S'Range loop
for J in S'Range loop
if I /= J and S (I) /= T (J) and S (J) /= T (I) then
Tmp := T (I);
T (I) := T (J);
T (J) := Tmp;
end if;
end loop;
end loop;
return T;
end Best_Shuffle;
Test_Cases : constant array (1 .. 6)
of Ada.Strings.Unbounded.Unbounded_String :=
(Ada.Strings.Unbounded.To_Unbounded_String ("abracadabra"),
Ada.Strings.Unbounded.To_Unbounded_String ("seesaw"),
Ada.Strings.Unbounded.To_Unbounded_String ("elk"),
Ada.Strings.Unbounded.To_Unbounded_String ("grrrrrr"),
Ada.Strings.Unbounded.To_Unbounded_String ("up"),
Ada.Strings.Unbounded.To_Unbounded_String ("a"));
begin -- main procedure
for Test_Case in Test_Cases'Range loop
declare
Original : constant String := Ada.Strings.Unbounded.To_String
(Test_Cases (Test_Case));
Shuffle : constant String := Best_Shuffle (Original);
Score : Natural := 0;
begin
for I in Original'Range loop
if Original (I) = Shuffle (I) then
Score := Score + 1;
end if;
end loop;
Ada.Text_IO.Put_Line (Original & ", " & Shuffle & ", (" &
Natural'Image (Score) & " )");
end;
end loop;
end Best_Shuffle;
|
30,736
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Draw-a-cuboid/Ada/draw-a-cuboid.ada
|
<gh_stars>1-10
with Ada.Text_IO;
procedure Main is
type Char_Matrix is
array (Positive range <>, Positive range <>) of Character;
function Create_Cuboid
(Width, Height, Depth : Positive)
return Char_Matrix
is
Result : Char_Matrix (1 .. Height + Depth + 3,
1 .. 2 * Width + Depth + 3) := (others => (others => ' '));
begin
-- points
Result (1, 1) := '+';
Result (Height + 2, 1) := '+';
Result (1, 2 * Width + 2) := '+';
Result (Height + 2, 2 * Width + 2) := '+';
Result (Height + Depth + 3, Depth + 2) := '+';
Result (Depth + 2, 2 * Width + Depth + 3) := '+';
Result (Height + Depth + 3, 2 * Width + Depth + 3) := '+';
-- width lines
for I in 1 .. 2 * Width loop
Result (1, I + 1) := '-';
Result (Height + 2, I + 1) := '-';
Result (Height + Depth + 3, Depth + I + 2) := '-';
end loop;
-- height lines
for I in 1 .. Height loop
Result (I + 1, 1) := '|';
Result (I + 1, 2 * Width + 2) := '|';
Result (Depth + I + 2, 2 * Width + Depth + 3) := '|';
end loop;
-- depth lines
for I in 1 .. Depth loop
Result (Height + 2 + I, 1 + I) := '/';
Result (1 + I, 2 * Width + 2 + I) := '/';
Result (Height + 2 + I, 2 * Width + 2 + I) := '/';
end loop;
return Result;
end Create_Cuboid;
procedure Print_Cuboid (Width, Height, Depth : Positive) is
Cuboid : Char_Matrix := Create_Cuboid (Width, Height, Depth);
begin
for Row in reverse Cuboid'Range (1) loop
for Col in Cuboid'Range (2) loop
Ada.Text_IO.Put (Cuboid (Row, Col));
end loop;
Ada.Text_IO.New_Line;
end loop;
end Print_Cuboid;
begin
Print_Cuboid (2, 3, 4);
end Main;
|
30,737
|
ada
| 1
|
brucegua/moocos
|
tools/scitools/conf/understand/ada/ada12/a-cforma.ads
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . F O R M A L _ O R D E R E D _ M A P S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2004-2011, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- 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/>. --
------------------------------------------------------------------------------
-- This spec is derived from package Ada.Containers.Bounded_Ordered_Maps in
-- the Ada 2012 RM. The modifications are to facilitate formal proofs by
-- making it easier to express properties.
-- The modifications are:
-- A parameter for the container is added to every function reading the
-- content of a container: Key, Element, Next, Query_Element, Previous,
-- Has_Element, Iterate, Reverse_Iterate. This change is motivated by the
-- need to have cursors which are valid on different containers (typically a
-- container C and its previous version C'Old) for expressing properties,
-- which is not possible if cursors encapsulate an access to the underlying
-- container. The operators "<" and ">" that could not be modified that way
-- have been removed.
-- There are four new functions:
-- function Strict_Equal (Left, Right : Map) return Boolean;
-- function Overlap (Left, Right : Map) return Boolean;
-- function Left (Container : Map; Position : Cursor) return Map;
-- function Right (Container : Map; Position : Cursor) return Map;
-- See detailed specifications for these subprograms
private with Ada.Containers.Red_Black_Trees;
private with Ada.Streams;
generic
type Key_Type is private;
type Element_Type is private;
with function "<" (Left, Right : Key_Type) return Boolean is <>;
with function "=" (Left, Right : Element_Type) return Boolean is <>;
package Ada.Containers.Formal_Ordered_Maps is
pragma Pure;
function Equivalent_Keys (Left, Right : Key_Type) return Boolean;
type Map (Capacity : Count_Type) is tagged private;
pragma Preelaborable_Initialization (Map);
type Cursor is private;
pragma Preelaborable_Initialization (Cursor);
Empty_Map : constant Map;
No_Element : constant Cursor;
function "=" (Left, Right : Map) return Boolean;
function Length (Container : Map) return Count_Type;
function Is_Empty (Container : Map) return Boolean;
procedure Clear (Container : in out Map);
procedure Assign (Target : in out Map; Source : Map);
function Copy (Source : Map; Capacity : Count_Type := 0) return Map;
function Key (Container : Map; Position : Cursor) return Key_Type;
function Element (Container : Map; Position : Cursor) return Element_Type;
procedure Replace_Element
(Container : in out Map;
Position : Cursor;
New_Item : Element_Type);
procedure Query_Element
(Container : in out Map;
Position : Cursor;
Process : not null access
procedure (Key : Key_Type; Element : Element_Type));
procedure Update_Element
(Container : in out Map;
Position : Cursor;
Process : not null access
procedure (Key : Key_Type; Element : in out Element_Type));
procedure Move (Target : in out Map; Source : in out Map);
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean);
procedure Insert
(Container : in out Map;
Key : Key_Type;
Position : out Cursor;
Inserted : out Boolean);
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
procedure Include
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
procedure Replace
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type);
procedure Exclude (Container : in out Map; Key : Key_Type);
procedure Delete (Container : in out Map; Key : Key_Type);
procedure Delete (Container : in out Map; Position : in out Cursor);
procedure Delete_First (Container : in out Map);
procedure Delete_Last (Container : in out Map);
function First (Container : Map) return Cursor;
function First_Element (Container : Map) return Element_Type;
function First_Key (Container : Map) return Key_Type;
function Last (Container : Map) return Cursor;
function Last_Element (Container : Map) return Element_Type;
function Last_Key (Container : Map) return Key_Type;
function Next (Container : Map; Position : Cursor) return Cursor;
procedure Next (Container : Map; Position : in out Cursor);
function Previous (Container : Map; Position : Cursor) return Cursor;
procedure Previous (Container : Map; Position : in out Cursor);
function Find (Container : Map; Key : Key_Type) return Cursor;
function Element (Container : Map; Key : Key_Type) return Element_Type;
function Floor (Container : Map; Key : Key_Type) return Cursor;
function Ceiling (Container : Map; Key : Key_Type) return Cursor;
function Contains (Container : Map; Key : Key_Type) return Boolean;
function Has_Element (Container : Map; Position : Cursor) return Boolean;
procedure Iterate
(Container : Map;
Process :
not null access procedure (Container : Map; Position : Cursor));
procedure Reverse_Iterate
(Container : Map;
Process : not null access
procedure (Container : Map; Position : Cursor));
function Strict_Equal (Left, Right : Map) return Boolean;
-- Strict_Equal returns True if the containers are physically equal, i.e.
-- they are structurally equal (function "=" returns True) and that they
-- have the same set of cursors.
function Left (Container : Map; Position : Cursor) return Map;
function Right (Container : Map; Position : Cursor) return Map;
-- Left returns a container containing all elements preceding Position
-- (excluded) in Container. Right returns a container containing all
-- elements following Position (included) in Container. These two new
-- functions can be used to express invariant properties in loops which
-- iterate over containers. Left returns the part of the container already
-- scanned and Right the part not scanned yet.
function Overlap (Left, Right : Map) return Boolean;
-- Overlap returns True if the containers have common keys
private
pragma Inline (Next);
pragma Inline (Previous);
subtype Node_Access is Count_Type;
use Red_Black_Trees;
type Node_Type is record
Has_Element : Boolean := False;
Parent : Node_Access := 0;
Left : Node_Access := 0;
Right : Node_Access := 0;
Color : Red_Black_Trees.Color_Type := Red;
Key : Key_Type;
Element : Element_Type;
end record;
package Tree_Types is
new Ada.Containers.Red_Black_Trees.Generic_Bounded_Tree_Types (Node_Type);
type Map (Capacity : Count_Type) is
new Tree_Types.Tree_Type (Capacity) with null record;
use Ada.Streams;
type Cursor is record
Node : Node_Access;
end record;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Cursor);
for Cursor'Write use Write;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Cursor);
for Cursor'Read use Read;
No_Element : constant Cursor := (Node => 0);
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Container : Map);
for Map'Write use Write;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Container : out Map);
for Map'Read use Read;
Empty_Map : constant Map := (Capacity => 0, others => <>);
end Ada.Containers.Formal_Ordered_Maps;
|
30,738
|
ada
| 3
|
jwarwick/aoc_2020
|
day12/tests/day-test.adb
|
with AUnit.Assertions; use AUnit.Assertions;
package body Day.Test is
procedure Test_Part1 (T : in out AUnit.Test_Cases.Test_Case'Class) is
pragma Unreferenced (T);
f : constant Ferry := load_file("test1.txt");
d : constant Natural := distance(f);
begin
Assert(d = 25, "Wrong number, expected 25, got" & Natural'IMAGE(d));
end Test_Part1;
procedure Test_Part2 (T : in out AUnit.Test_Cases.Test_Case'Class) is
pragma Unreferenced (T);
f : constant Ferry := load_file("test1.txt");
d : constant Natural := waypoint_distance(f);
begin
Assert(d = 286, "Wrong number, expected 286, got" & Natural'IMAGE(d));
end Test_Part2;
function Name (T : Test) return AUnit.Message_String is
pragma Unreferenced (T);
begin
return AUnit.Format ("Test Day package");
end Name;
procedure Register_Tests (T : in out Test) is
use AUnit.Test_Cases.Registration;
begin
Register_Routine (T, Test_Part1'Access, "Test Part 1");
Register_Routine (T, Test_Part2'Access, "Test Part 2");
end Register_Tests;
end Day.Test;
|
30,739
|
ada
| 2
|
thindil/tashy2
|
tests/tk-frame-frame_create_options_test_data-frame_create_options_tests.adb
|
<reponame>thindil/tashy2<gh_stars>1-10
-- This package has been generated automatically by GNATtest.
-- You are allowed to add your code to the bodies of test routines.
-- Such changes will be kept during further regeneration of this file.
-- All code placed outside of test routine bodies will be lost. The
-- code intended to set up and tear down the test environment should be
-- placed into Tk.Frame.Frame_Create_Options_Test_Data.
with AUnit.Assertions; use AUnit.Assertions;
with System.Assertions;
-- begin read only
-- id:2.2/00/
--
-- This section can be used to add with clauses if necessary.
--
-- end read only
with Ada.Environment_Variables; use Ada.Environment_Variables;
-- begin read only
-- end read only
package body Tk.Frame.Frame_Create_Options_Test_Data
.Frame_Create_Options_Tests is
-- begin read only
-- id:2.2/01/
--
-- This section can be used to add global variables and other elements.
--
-- end read only
-- begin read only
-- end read only
-- begin read only
function Wrap_Test_Create_32e405_154917
(Path_Name: Tk_Path_String; Options: Frame_Create_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) return Tk_Frame is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-frame.ads:0):Test_Create_Frame1 test requirement violated");
end;
declare
Test_Create_32e405_154917_Result: constant Tk_Frame :=
GNATtest_Generated.GNATtest_Standard.Tk.Frame.Create
(Path_Name, Options, Interpreter);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-frame.ads:0:):Test_Create_Frame1 test commitment violated");
end;
return Test_Create_32e405_154917_Result;
end;
end Wrap_Test_Create_32e405_154917;
-- end read only
-- begin read only
procedure Test_1_Create_test_create_frame1
(Gnattest_T: in out Test_Frame_Create_Options);
procedure Test_Create_32e405_154917
(Gnattest_T: in out Test_Frame_Create_Options) renames
Test_1_Create_test_create_frame1;
-- id:2.2/32e405543423d7b8/Create/1/0/test_create_frame1/
procedure Test_1_Create_test_create_frame1
(Gnattest_T: in out Test_Frame_Create_Options) is
function Create
(Path_Name: Tk_Path_String; Options: Frame_Create_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tk_Frame renames
Wrap_Test_Create_32e405_154917;
-- end read only
pragma Unreferenced(Gnattest_T);
Frame: Tk_Frame := Null_Widget;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Create(Frame, ".myframe", Frame_Create_Options'(others => <>));
Assert(Frame /= Null_Widget, "Failed to create a new frame.");
Destroy(Frame);
-- begin read only
end Test_1_Create_test_create_frame1;
-- end read only
-- begin read only
procedure Wrap_Test_Create_ebbdc1_471f4e
(Frame_Widget: out Tk_Frame; Path_Name: Tk_Path_String;
Options: Frame_Create_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-frame.ads:0):Test_Create_Frame2 test requirement violated");
end;
GNATtest_Generated.GNATtest_Standard.Tk.Frame.Create
(Frame_Widget, Path_Name, Options, Interpreter);
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-frame.ads:0:):Test_Create_Frame2 test commitment violated");
end;
end Wrap_Test_Create_ebbdc1_471f4e;
-- end read only
-- begin read only
procedure Test_2_Create_test_create_frame2
(Gnattest_T: in out Test_Frame_Create_Options);
procedure Test_Create_ebbdc1_471f4e
(Gnattest_T: in out Test_Frame_Create_Options) renames
Test_2_Create_test_create_frame2;
-- id:2.2/ebbdc1934f0fa33d/Create/0/0/test_create_frame2/
procedure Test_2_Create_test_create_frame2
(Gnattest_T: in out Test_Frame_Create_Options) is
procedure Create
(Frame_Widget: out Tk_Frame; Path_Name: Tk_Path_String;
Options: Frame_Create_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) renames
Wrap_Test_Create_ebbdc1_471f4e;
-- end read only
pragma Unreferenced(Gnattest_T);
Frame: Tk_Frame := Null_Widget;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Frame := Create(".myframe", Frame_Create_Options'(others => <>));
Assert(Frame /= Null_Widget, "Failed to create a new frame.");
Destroy(Frame);
-- begin read only
end Test_2_Create_test_create_frame2;
-- end read only
-- begin read only
function Wrap_Test_Get_Options_ded36e_ce77f0
(Frame_Widget: Tk_Frame) return Frame_Create_Options is
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"req_sloc(tk-frame.ads:0):Test_Get_Options_Frame test requirement violated");
end;
declare
Test_Get_Options_ded36e_ce77f0_Result: constant Frame_Create_Options :=
GNATtest_Generated.GNATtest_Standard.Tk.Frame.Get_Options
(Frame_Widget);
begin
begin
pragma Assert(True);
null;
exception
when System.Assertions.Assert_Failure =>
AUnit.Assertions.Assert
(False,
"ens_sloc(tk-frame.ads:0:):Test_Get_Options_Frame test commitment violated");
end;
return Test_Get_Options_ded36e_ce77f0_Result;
end;
end Wrap_Test_Get_Options_ded36e_ce77f0;
-- end read only
-- begin read only
procedure Test_Get_Options_test_get_options_frame
(Gnattest_T: in out Test_Frame_Create_Options);
procedure Test_Get_Options_ded36e_ce77f0
(Gnattest_T: in out Test_Frame_Create_Options) renames
Test_Get_Options_test_get_options_frame;
-- id:2.2/ded36e34d54c20f9/Get_Options/1/0/test_get_options_frame/
procedure Test_Get_Options_test_get_options_frame
(Gnattest_T: in out Test_Frame_Create_Options) is
function Get_Options
(Frame_Widget: Tk_Frame) return Frame_Create_Options renames
Wrap_Test_Get_Options_ded36e_ce77f0;
-- end read only
pragma Unreferenced(Gnattest_T);
Frame: Tk_Frame;
Options: Frame_Create_Options;
begin
if Value("DISPLAY", "")'Length = 0 then
Assert(True, "No display, can't test");
return;
end if;
Create
(Frame, ".myframe",
Frame_Create_Options'(Relief => RAISED, others => <>));
Options := Get_Options(Frame);
Assert(Options.Relief = RAISED, "Failed to get frame options.");
Destroy(Frame);
-- begin read only
end Test_Get_Options_test_get_options_frame;
-- end read only
-- begin read only
-- id:2.2/02/
--
-- This section can be used to add elaboration code for the global state.
--
begin
-- end read only
null;
-- begin read only
-- end read only
end Tk.Frame.Frame_Create_Options_Test_Data.Frame_Create_Options_Tests;
|
30,740
|
ada
| 0
|
persan/a-cups
|
src/gen/cups-cups_dir_h.ads
|
<reponame>persan/a-cups
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with CUPS.bits_stat_h;
with System;
with Interfaces.C.Strings;
private package CUPS.cups_dir_h is
-- * "$Id: dir.h 10996 2013-05-29 11:51:34Z msweet $"
-- *
-- * Public directory definitions for CUPS.
-- *
-- * This set of APIs abstracts enumeration of directory entries.
-- *
-- * Copyright 2007-2011 by Apple Inc.
-- * Copyright 1997-2006 by Easy Software Products, all rights reserved.
-- *
-- * These coded instructions, statements, and computer programs are the
-- * property of Apple Inc. and are protected by Federal copyright
-- * law. Distribution and use rights are outlined in the file "LICENSE.txt"
-- * which should have been included with this file. If this file is
-- * file is missing or damaged, see the license at "http://www.cups.org/".
--
-- * Include necessary headers...
--
-- * C++ magic...
--
-- * Data types...
--
--*** Directory type ***
-- skipped empty struct u_cups_dir_s
-- skipped empty struct cups_dir_t
--*** Directory entry type ***
-- File name
subtype cups_dentry_s_filename_array is Interfaces.C.char_array (0 .. 259);
type cups_dentry_s is record
filename : aliased cups_dentry_s_filename_array; -- cups/dir.h:47
fileinfo : aliased CUPS.bits_stat_h.stat; -- cups/dir.h:48
end record;
pragma Convention (C_Pass_By_Copy, cups_dentry_s); -- cups/dir.h:45
-- File information
subtype cups_dentry_t is cups_dentry_s;
-- * Prototypes...
--
procedure cupsDirClose (dp : System.Address); -- cups/dir.h:56
pragma Import (C, cupsDirClose, "cupsDirClose");
function cupsDirOpen (directory : Interfaces.C.Strings.chars_ptr) return System.Address; -- cups/dir.h:57
pragma Import (C, cupsDirOpen, "cupsDirOpen");
function cupsDirRead (dp : System.Address) return access cups_dentry_t; -- cups/dir.h:58
pragma Import (C, cupsDirRead, "cupsDirRead");
procedure cupsDirRewind (dp : System.Address); -- cups/dir.h:59
pragma Import (C, cupsDirRewind, "cupsDirRewind");
-- * End of "$Id: dir.h 10996 2013-05-29 11:51:34Z msweet $".
--
end CUPS.cups_dir_h;
|
30,741
|
ada
| 0
|
optikos/oasis
|
source/nodes/program-nodes-discrete_range_vectors.ads
|
<filename>source/nodes/program-nodes-discrete_range_vectors.ads
-- Copyright (c) 2019 <NAME> <<EMAIL>>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Nodes.Generic_Vectors;
with Program.Elements.Discrete_Ranges;
package Program.Nodes.Discrete_Range_Vectors is new
Program.Nodes.Generic_Vectors
(Program.Elements.Discrete_Ranges.Discrete_Range_Vector);
pragma Preelaborate (Program.Nodes.Discrete_Range_Vectors);
|
30,742
|
ada
| 79
|
Roldak/OpenGLAda
|
src/text/gl-text-utf8.ads
|
<filename>src/text/gl-text-utf8.ads<gh_stars>10-100
private package GL.Text.UTF8 is
type Code_Point is mod 2**32;
subtype UTF8_Code_Point is Code_Point range 0 .. 16#10FFFF#;
procedure Read (Buffer : String; Position : in out Positive;
Result : out UTF8_Code_Point);
end GL.Text.UTF8;
|
30,743
|
ada
| 23
|
tomekw/simple_blockchain
|
src/simple_blockchain-blockchain.ads
|
with Ada.Containers.Vectors; use Ada.Containers;
with Simple_Blockchain.Block;
use Simple_Blockchain;
package Simple_Blockchain.Blockchain is
use type Block.Object;
package Block_Vectors is new Vectors (Index_Type => Positive, Element_Type => Block.Object);
type Blockchain_Difficulty is range 1 .. 64;
type Object is private;
function Get_Blocks (This : Object) return Block_Vectors.Vector;
function Get_Difficulty (This : Object) return Natural;
function Image (This : Object) return String;
function Is_Valid (This : Object) return Boolean;
function Make (Difficulty : Blockchain_Difficulty) return Object;
procedure Mine_Block (This : in out Object; Data : String);
private
type Object is
record
Blocks : Block_Vectors.Vector;
Difficulty : Blockchain_Difficulty;
end record;
function Expected_Hash_Prefix (This : Object) return String;
function Is_Empty (This : Object) return Boolean;
function Last_Block (This : Object) return Block.Object;
end Simple_Blockchain.Blockchain;
|
30,744
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/discr25.adb
|
-- { dg-do compile }
with Discr25_Pkg;
procedure Discr25 (N : Natural) is
package Test_Set is new Discr25_Pkg (N);
begin
null;
end;
|
30,745
|
ada
| 0
|
Letractively/ada-util
|
src/util-beans-basic-lists.ads
|
<filename>src/util-beans-basic-lists.ads
-----------------------------------------------------------------------
-- Util.Beans.Basic.Lists -- List bean given access to a vector
-- Copyright (C) 2011, 2012 <NAME>
-- Written by <NAME> (<EMAIL>)
--
-- 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.Finalization;
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Beans.Objects;
-- The <b>Util.Beans.Basic.Lists</b> generic package implements a list of
-- elements that can be accessed through the <b>List_Bean</b> interface.
generic
type Element_Type is new Util.Beans.Basic.Readonly_Bean with private;
package Util.Beans.Basic.Lists is
-- Package that represents the vectors of elements.
-- (gcc 4.4 crashes if this package is defined as generic parameter.
package Vectors is
new Ada.Containers.Vectors (Element_Type => Element_Type,
Index_Type => Natural);
-- The list of elements is defined in a public part so that applications
-- can easily add or remove elements in the target list. The <b>List_Bean</b>
-- type holds the real implementation with the private parts.
type Abstract_List_Bean is abstract new Ada.Finalization.Controlled
and Util.Beans.Basic.List_Bean with record
List : aliased Vectors.Vector;
end record;
-- ------------------------------
-- List of objects
-- ------------------------------
-- The <b>List_Bean</b> type gives access to a list of objects.
type List_Bean is new Abstract_List_Bean with private;
type List_Bean_Access is access all List_Bean'Class;
-- Get the number of elements in the list.
overriding
function Get_Count (From : in List_Bean) return Natural;
-- Set the current row index. Valid row indexes start at 1.
overriding
procedure Set_Row_Index (From : in out List_Bean;
Index : in Natural);
-- Returns the current row index.
function Get_Row_Index (From : in List_Bean) return Natural;
-- Get the element at the current row index.
overriding
function Get_Row (From : in List_Bean) return Util.Beans.Objects.Object;
-- 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 List_Bean;
Name : in String) return Util.Beans.Objects.Object;
-- Initialize the list bean.
overriding
procedure Initialize (Object : in out List_Bean);
-- Deletes the list bean
procedure Free (List : in out Util.Beans.Basic.Readonly_Bean_Access);
private
type List_Bean is new Abstract_List_Bean with record
Current : aliased Element_Type;
Current_Index : Natural := 0;
Row : Util.Beans.Objects.Object;
end record;
end Util.Beans.Basic.Lists;
|
30,746
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c3/c37105a.ada
|
-- C37105A.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 RECORDS WITH ONLY DISCRIMINANTS ARE OK.
-- DAT 5/18/81
-- JWC 6/28/85 RENAMED TO -AB
WITH REPORT; USE REPORT;
PROCEDURE C37105A IS
BEGIN
TEST ("C37105A", "RECORDS WITH ONLY DISCRIMINANTS");
DECLARE
TYPE R1 (D : BOOLEAN) IS RECORD
NULL; END RECORD;
TYPE R2 (D, E : BOOLEAN) IS RECORD
NULL; END RECORD;
TYPE R3 (A,B,C,D : INTEGER; W,X,Y,Z : CHARACTER) IS
RECORD NULL; END RECORD;
OBJ1 : R1 (IDENT_BOOL(TRUE));
OBJ2 : R2 (IDENT_BOOL(FALSE), IDENT_BOOL(TRUE));
OBJ3 : R3 (1,2,3,4,'A','B','C',IDENT_CHAR('D'));
BEGIN
IF OBJ1 = (D => (FALSE))
OR OBJ2 /= (FALSE, (TRUE))
OR OBJ3 /= (1,2,3,4,'A','B','C',('D'))
THEN FAILED ("DISCRIMINANT-ONLY RECORDS DON'T WORK");
END IF;
END;
RESULT;
END C37105A;
|
30,747
|
ada
| 0
|
xeenta/learning-ada
|
src/002/suppack.adb
|
with My_Pack;
with Ada.Text_IO; use Ada.Text_IO;
package body Suppack is
procedure Print is
begin
Put_Line (Integer'Image (My_Pack.Get));
end Print;
end Suppack;
|
30,748
|
ada
| 0
|
StoneCypher/DeepakChopra_Ada
|
DeepakChopra.ada
|
<filename>DeepakChopra.ada
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Numerics;
with Ada.Numerics.Discrete_Random;
procedure Hello is
starts : array(1..4) of Ada.Strings.Unbounded.Unbounded_String;
middles : array(1..4) of Ada.Strings.Unbounded.Unbounded_String;
qualifiers : array(1..4) of Ada.Strings.Unbounded.Unbounded_String;
finishes : array(1..4) of Ada.Strings.Unbounded.Unbounded_String;
subtype Rand_Idx_Range is integer range 1 .. 4;
package Rand_Idx is new Ada.Numerics.Discrete_Random(Rand_Idx_Range);
use Rand_Idx;
seed : Rand_Idx.Generator;
idx : Rand_Idx_Range;
begin
Rand_Idx.Reset(seed);
starts(1) := Ada.Strings.Unbounded.To_Unbounded_String ("Experiential truth ");
starts(2) := Ada.Strings.Unbounded.To_Unbounded_String ("The physical world ");
starts(3) := Ada.Strings.Unbounded.To_Unbounded_String ("Non-judgment ");
starts(4) := Ada.Strings.Unbounded.To_Unbounded_String ("Quantum physics ");
middles(1) := Ada.Strings.Unbounded.To_Unbounded_String ("nurtures an ");
middles(2) := Ada.Strings.Unbounded.To_Unbounded_String ("projects onto ");
middles(3) := Ada.Strings.Unbounded.To_Unbounded_String ("imparts reality to ");
middles(4) := Ada.Strings.Unbounded.To_Unbounded_String ("constructs with ");
qualifiers(1) := Ada.Strings.Unbounded.To_Unbounded_String ("abundance of ");
qualifiers(2) := Ada.Strings.Unbounded.To_Unbounded_String ("the barrier of ");
qualifiers(3) := Ada.Strings.Unbounded.To_Unbounded_String ("self-righteous ");
qualifiers(4) := Ada.Strings.Unbounded.To_Unbounded_String ("potential ");
finishes(1) := Ada.Strings.Unbounded.To_Unbounded_String ("marvel.");
finishes(2) := Ada.Strings.Unbounded.To_Unbounded_String ("choices.");
finishes(3) := Ada.Strings.Unbounded.To_Unbounded_String ("creativity.");
finishes(4) := Ada.Strings.Unbounded.To_Unbounded_String ("actions.");
Put( starts (Rand_Idx.Random(seed) ) );
Put( middles (Rand_Idx.Random(seed) ) );
Put( qualifiers (Rand_Idx.Random(seed) ) );
Put_Line( finishes (Rand_Idx.Random(seed) ) );
end Hello;
|
30,749
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Calendar/Ada/calendar-1.ada
|
<filename>Task/Calendar/Ada/calendar-1.ada<gh_stars>1-10
with Ada.Calendar.Formatting;
package Printable_Calendar is
subtype String20 is String(1 .. 20);
type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20;
type Description is record
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
-- for internationalization, you only need to define a new description
Default_Description: constant Description :=
(Weekday_Rep =>
"Mo Tu We Th Fr Sa So",
Month_Rep =>
(" January ", " February ", " March ",
" April ", " May ", " June ",
" July ", " August ", " September ",
" October ", " November ", " December "));
type Calendar (<>) is tagged private;
-- Initialize a calendar for devices with 80- or 132-characters per row
function Init_80(Des: Description := Default_Description) return Calendar;
function Init_132(Des: Description := Default_Description) return Calendar;
-- the following procedures output to standard IO; override if neccessary
procedure New_Line(Cal: Calendar);
procedure Put_String(Cal: Calendar; S: String);
-- the following procedures do the real stuff
procedure Print_Line_Centered(Cal: Calendar'Class; Line: String);
procedure Print(Cal: Calendar'Class;
Year: Ada.Calendar.Year_Number;
Year_String: String); -- this is the main Thing
private
type Calendar is tagged record
Columns, Rows, Space_Between_Columns: Positive;
Left_Space: Natural;
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
end Printable_Calendar;
|
30,750
|
ada
| 0
|
kisom/rover-mk1
|
src/hardware/hardware-drivetrain.ads
|
<filename>src/hardware/hardware-drivetrain.ads
with AVR; use AVR;
with Interfaces; use Interfaces;
with Hardware.PWM; use Hardware;
package Hardware.DriveTrain is
procedure Init;
procedure Forward;
procedure Backward;
procedure Rotate_Left;
procedure Rotate_Right;
procedure Stop;
private
Motor_Right : Hardware.PWM.Servo_Index;
Motor_Left : Hardware.PWM.Servo_Index;
Pin_Right : AVR.Bit_Number := 3; -- PB5
Pin_Left : AVR.Bit_Number := 4; -- PB6
Rotate_Forward : Unsigned_16 := 1700;
Rotate_Stop : Unsigned_16 := 1500;
Rotate_Backward : Unsigned_16 := 1300;
end Hardware.DriveTrain;
|
30,751
|
ada
| 33
|
ytomino/drake
|
source/textio/a-ticoio.adb
|
<gh_stars>10-100
with Ada.Text_IO.Float_IO;
with Ada.Text_IO.Formatting;
package body Ada.Text_IO.Complex_IO is
package Real_IO is new Float_IO (Complex_Types.Real);
procedure Get_From_Field (
From : String;
Item : out Complex_Types.Complex;
Last : out Positive);
procedure Get_From_Field (
From : String;
Item : out Complex_Types.Complex;
Last : out Positive)
is
Paren : Boolean;
begin
Formatting.Get_Tail (From, Last);
Paren := From (Last) = '(';
if Paren then
Last := Last + 1;
end if;
Real_IO.Get (From (Last .. From'Last), Item.Re, Last);
Formatting.Get_Tail (From (Last + 1 .. From'Last), Last);
if From (Last) = ',' then
Last := Last + 1;
end if;
Real_IO.Get (From (Last .. From'Last), Item.Im, Last);
if Paren then
Formatting.Get_Tail (From (Last + 1 .. From'Last), Last);
if From (Last) /= ')' then
raise Data_Error;
end if;
end if;
end Get_From_Field;
-- implementation
procedure Get (
File : File_Type;
Item : out Complex_Types.Complex;
Width : Field := 0) is
begin
if Width /= 0 then
declare
S : String (1 .. Width);
Last_1 : Natural;
Last_2 : Natural;
begin
Formatting.Get_Field (File, S, Last_1); -- checking the predicate
Get_From_Field (S (1 .. Last_1), Item, Last_2);
if Last_2 /= Last_1 then
raise Data_Error;
end if;
end;
else
declare
S : constant String :=
Formatting.Get_Complex_Literal (File); -- checking the predicate
Last : Natural;
begin
Get_From_Field (S, Item, Last);
if Last /= S'Last then
raise Data_Error;
end if;
end;
end if;
end Get;
procedure Get (
Item : out Complex_Types.Complex;
Width : Field := 0) is
begin
Get (Current_Input.all, Item, Width);
end Get;
procedure Put (
File : File_Type;
Item : Complex_Types.Complex;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp) is
begin
Put (File, '('); -- checking the predicate
Real_IO.Put (File, Item.Re, Fore, Aft, Exp);
Put (File, ',');
Real_IO.Put (File, Item.Im, Fore, Aft, Exp);
Put (File, ')');
end Put;
procedure Put (
Item : Complex_Types.Complex;
Fore : Field := Default_Fore;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp) is
begin
Put (Current_Output.all, Item, Fore, Aft, Exp);
end Put;
procedure Overloaded_Get (
From : String;
Item : out Complex_Types.Complex;
Last : out Positive)
renames Get_From_Field;
procedure Overloaded_Get (
From : Wide_String;
Item : out Complex_Types.Complex;
Last : out Positive)
is
String_From : String (From'Range);
begin
for I in From'Range loop
if Wide_Character'Pos (From (I)) < 16#80# then
String_From (I) := Character'Val (Wide_Character'Pos (From (I)));
else
String_From (I) := Character'Val (16#1A#); -- substitute
end if;
end loop;
Overloaded_Get (String_From, Item, Last);
end Overloaded_Get;
procedure Overloaded_Get (
From : Wide_Wide_String;
Item : out Complex_Types.Complex;
Last : out Positive)
is
String_From : String (From'Range);
begin
for I in From'Range loop
if Wide_Wide_Character'Pos (From (I)) < 16#80# then
String_From (I) :=
Character'Val (Wide_Wide_Character'Pos (From (I)));
else
String_From (I) := Character'Val (16#1A#); -- substitute
end if;
end loop;
Overloaded_Get (String_From, Item, Last);
end Overloaded_Get;
procedure Overloaded_Put (
To : out String;
Item : Complex_Types.Complex;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
Index : Natural;
begin
if To'Length < (Aft + Exp) * 2 + 7 then -- "(0.,0.)"
raise Layout_Error;
end if;
To (To'First) := '(';
Real_IO.Put (To (To'First + 1 .. To'Last), Index, Item.Re, Aft, Exp);
Index := Index + 1;
if Index > To'Last then
raise Layout_Error;
end if;
To (Index) := ',';
Real_IO.Put (To (Index + 1 .. To'Last - 1), Item.Im, Aft, Exp);
To (To'Last) := ')';
end Overloaded_Put;
procedure Overloaded_Put (
To : out Wide_String;
Item : Complex_Types.Complex;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
String_To : String (To'Range);
begin
Overloaded_Put (String_To, Item, Aft, Exp);
for I in To'Range loop
To (I) := Wide_Character'Val (Character'Pos (String_To (I)));
end loop;
end Overloaded_Put;
procedure Overloaded_Put (
To : out Wide_Wide_String;
Item : Complex_Types.Complex;
Aft : Field := Default_Aft;
Exp : Field := Default_Exp)
is
String_To : String (To'Range);
begin
Overloaded_Put (String_To, Item, Aft, Exp);
for I in To'Range loop
To (I) := Wide_Wide_Character'Val (Character'Pos (String_To (I)));
end loop;
end Overloaded_Put;
end Ada.Text_IO.Complex_IO;
|
30,752
|
ada
| 0
|
djamal2727/Main-Bearing-Analytical-Model
|
Validation/pyFrame3DD-master/gcc-master/gcc/ada/libgnat/s-trasym__dwarf.adb
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . T R A C E B A C K . S Y M B O L I C --
-- --
-- B o d y --
-- --
-- Copyright (C) 1999-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. --
-- --
------------------------------------------------------------------------------
-- Run-time symbolic traceback support for targets using DWARF debug data
with Ada.Unchecked_Deallocation;
with Ada.Exceptions.Traceback; use Ada.Exceptions.Traceback;
with Ada.Containers.Generic_Array_Sort;
with System.Address_To_Access_Conversions;
with System.Soft_Links;
with System.CRTL;
with System.Dwarf_Lines;
with System.Exception_Traces;
with System.Standard_Library;
with System.Traceback_Entries;
with System.Strings;
with System.Bounded_Strings;
package body System.Traceback.Symbolic is
use System.Bounded_Strings;
use System.Dwarf_Lines;
subtype Big_String is String (Positive);
-- To deal with C strings
package Big_String_Conv is new System.Address_To_Access_Conversions
(Big_String);
type Module_Cache;
type Module_Cache_Acc is access all Module_Cache;
type Module_Cache is record
Name : Strings.String_Access;
-- Name of the module
C : Dwarf_Context (In_Exception => True);
-- Context to symbolize an address within this module
Chain : Module_Cache_Acc;
end record;
procedure Free is new Ada.Unchecked_Deallocation
(Module_Cache,
Module_Cache_Acc);
Cache_Chain : Module_Cache_Acc;
-- Simply linked list of modules
type Module_Array is array (Natural range <>) of Module_Cache_Acc;
type Module_Array_Acc is access Module_Array;
Modules_Cache : Module_Array_Acc;
-- Sorted array of cached modules (if not null)
Exec_Module : aliased Module_Cache;
-- Context for the executable
type Init_State is (Uninitialized, Initialized, Failed);
Exec_Module_State : Init_State := Uninitialized;
-- How Exec_Module is initialized
procedure Init_Exec_Module;
-- Initialize Exec_Module if not already initialized
function Symbolic_Traceback
(Traceback : System.Traceback_Entries.Tracebacks_Array;
Suppress_Hex : Boolean) return String;
function Symbolic_Traceback
(E : Ada.Exceptions.Exception_Occurrence;
Suppress_Hex : Boolean) return String;
-- Suppress_Hex means do not print any hexadecimal addresses, even if the
-- symbol is not available.
function Lt (Left, Right : Module_Cache_Acc) return Boolean;
-- Sort function for Module_Cache
procedure Init_Module
(Module : out Module_Cache;
Success : out Boolean;
Module_Name : String;
Load_Address : Address := Null_Address);
-- Initialize Module
procedure Close_Module (Module : in out Module_Cache);
-- Finalize Module
function Value (Item : System.Address) return String;
-- Return the String contained in Item, up until the first NUL character
pragma Warnings (Off, "*Add_Module_To_Cache*");
procedure Add_Module_To_Cache (Module_Name : String;
Load_Address : System.Address);
-- To be called by Build_Cache_For_All_Modules to add a new module to the
-- list. May not be referenced.
package Module_Name is
procedure Build_Cache_For_All_Modules;
-- Create the cache for all current modules
function Get (Addr : System.Address;
Load_Addr : access System.Address) return String;
-- Returns the module name for the given address Addr, or an empty
-- string for the main executable. Load_Addr is set to the shared
-- library load address if this information is available, or to
-- System.Null_Address otherwise.
function Is_Supported return Boolean;
pragma Inline (Is_Supported);
-- Returns True if Module_Name is supported, so if the traceback is
-- supported for shared libraries.
end Module_Name;
package body Module_Name is separate;
function Executable_Name return String;
-- Returns the executable name as reported by argv[0]. If gnat_argv not
-- initialized, return an empty string. If the argv[0] executable is not
-- found in the PATH, return it unresolved.
function Get_Executable_Load_Address return System.Address;
pragma Import
(C,
Get_Executable_Load_Address,
"__gnat_get_executable_load_address");
-- Get the load address of the executable, or Null_Address if not known
procedure Hexa_Traceback
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String);
-- Non-symbolic traceback (simply write addresses in hexa)
procedure Symbolic_Traceback_No_Lock
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String);
-- Like the public Symbolic_Traceback_No_Lock except there is no provision
-- against concurrent accesses.
procedure Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Module : Module_Cache;
Suppress_Hex : Boolean;
Res : in out Bounded_String);
-- Returns the Traceback for a given module
procedure Multi_Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String);
-- Build string containing symbolic traceback for the given call chain
procedure Multi_Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Module : Module_Cache;
Suppress_Hex : Boolean;
Res : in out Bounded_String);
-- Likewise but using Module
Max_String_Length : constant := 4096;
-- Arbitrary limit on Bounded_Str length
-----------
-- Value --
-----------
function Value (Item : System.Address) return String is
begin
if Item /= Null_Address then
for J in Big_String'Range loop
if Big_String_Conv.To_Pointer (Item) (J) = ASCII.NUL then
return Big_String_Conv.To_Pointer (Item) (1 .. J - 1);
end if;
end loop;
end if;
return "";
end Value;
-------------------------
-- Add_Module_To_Cache --
-------------------------
procedure Add_Module_To_Cache (Module_Name : String;
Load_Address : System.Address)
is
Module : Module_Cache_Acc;
Success : Boolean;
begin
Module := new Module_Cache;
Init_Module (Module.all, Success, Module_Name, Load_Address);
if not Success then
Free (Module);
return;
end if;
Module.Chain := Cache_Chain;
Cache_Chain := Module;
end Add_Module_To_Cache;
----------------------
-- Init_Exec_Module --
----------------------
procedure Init_Exec_Module is
begin
if Exec_Module_State = Uninitialized then
declare
Exec_Path : constant String := Executable_Name;
Exec_Load : constant Address := Get_Executable_Load_Address;
Success : Boolean;
begin
Init_Module (Exec_Module, Success, Exec_Path, Exec_Load);
if Success then
Exec_Module_State := Initialized;
else
Exec_Module_State := Failed;
end if;
end;
end if;
end Init_Exec_Module;
--------
-- Lt --
--------
function Lt (Left, Right : Module_Cache_Acc) return Boolean is
begin
return Low_Address (Left.C) < Low_Address (Right.C);
end Lt;
-----------------------------
-- Module_Cache_Array_Sort --
-----------------------------
procedure Module_Cache_Array_Sort is new Ada.Containers.Generic_Array_Sort
(Natural,
Module_Cache_Acc,
Module_Array,
Lt);
------------------
-- Enable_Cache --
------------------
procedure Enable_Cache (Include_Modules : Boolean := False) is
begin
-- Can be called at most once
if Cache_Chain /= null then
return;
end if;
-- Add all modules
Init_Exec_Module;
if Exec_Module_State = Failed then
raise Program_Error with
"cannot enable cache, executable state initialization failed.";
end if;
Cache_Chain := Exec_Module'Access;
if Include_Modules then
Module_Name.Build_Cache_For_All_Modules;
end if;
-- Build and fill the array of modules
declare
Count : Natural;
Module : Module_Cache_Acc;
begin
for Phase in 1 .. 2 loop
Count := 0;
Module := Cache_Chain;
while Module /= null loop
Count := Count + 1;
if Phase = 1 then
Enable_Cache (Module.C);
else
Modules_Cache (Count) := Module;
end if;
Module := Module.Chain;
end loop;
if Phase = 1 then
Modules_Cache := new Module_Array (1 .. Count);
end if;
end loop;
end;
-- Sort the array
Module_Cache_Array_Sort (Modules_Cache.all);
end Enable_Cache;
---------------------
-- Executable_Name --
---------------------
function Executable_Name return String is
-- We have to import gnat_argv as an Address to match the type of
-- gnat_argv in the binder generated file. Otherwise, we get spurious
-- warnings about type mismatch when LTO is turned on.
Gnat_Argv : System.Address;
pragma Import (C, Gnat_Argv, "gnat_argv");
type Argv_Array is array (0 .. 0) of System.Address;
package Conv is new System.Address_To_Access_Conversions (Argv_Array);
function locate_exec_on_path (A : System.Address) return System.Address;
pragma Import (C, locate_exec_on_path, "__gnat_locate_exec_on_path");
begin
if Gnat_Argv = Null_Address then
return "";
end if;
-- See if we can resolve argv[0] to a full path (to a file that we will
-- be able to open). If the resolution fails, we were probably spawned
-- by an imprecise exec call, typically passing a mere file name as
-- argv[0] for a program in the current directory with '.' not on PATH.
-- Best we can do is fallback to argv[0] unchanged in this case. If we
-- fail opening that downstream, we'll just bail out.
declare
Argv0 : constant System.Address
:= Conv.To_Pointer (Gnat_Argv) (0);
Resolved_Argv0 : constant System.Address
:= locate_exec_on_path (Argv0);
Exe_Argv : constant System.Address
:= (if Resolved_Argv0 /= System.Null_Address
then Resolved_Argv0
else Argv0);
Result : constant String := Value (Exe_Argv);
begin
-- The buffer returned by locate_exec_on_path was allocated using
-- malloc and we should release this memory.
if Resolved_Argv0 /= Null_Address then
System.CRTL.free (Resolved_Argv0);
end if;
return Result;
end;
end Executable_Name;
------------------
-- Close_Module --
------------------
procedure Close_Module (Module : in out Module_Cache) is
begin
Close (Module.C);
Strings.Free (Module.Name);
end Close_Module;
-----------------
-- Init_Module --
-----------------
procedure Init_Module
(Module : out Module_Cache;
Success : out Boolean;
Module_Name : String;
Load_Address : Address := Null_Address)
is
begin
-- Early return if the module is not known
if Module_Name = "" then
Success := False;
return;
end if;
Open (Module_Name, Module.C, Success);
-- If a module can't be opened just return now, we just cannot give more
-- information in this case.
if not Success then
return;
end if;
Set_Load_Address (Module.C, Load_Address);
Module.Name := new String'(Module_Name);
end Init_Module;
-------------------------------
-- Module_Symbolic_Traceback --
-------------------------------
procedure Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Module : Module_Cache;
Suppress_Hex : Boolean;
Res : in out Bounded_String)
is
Success : Boolean;
begin
if Symbolic.Module_Name.Is_Supported then
Append (Res, '[');
Append (Res, Module.Name.all);
Append (Res, ']' & ASCII.LF);
end if;
Dwarf_Lines.Symbolic_Traceback
(Module.C,
Traceback,
Suppress_Hex,
Success,
Res);
if not Success then
Hexa_Traceback (Traceback, Suppress_Hex, Res);
end if;
-- We must not allow an unhandled exception here, since this function
-- may be installed as a decorator for all automatic exceptions.
exception
when others =>
return;
end Module_Symbolic_Traceback;
-------------------------------------
-- Multi_Module_Symbolic_Traceback --
-------------------------------------
procedure Multi_Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String)
is
F : constant Natural := Traceback'First;
begin
if Traceback'Length = 0 or else Is_Full (Res) then
return;
end if;
if Modules_Cache /= null then
-- Search in the cache
declare
Addr : constant Address := Traceback (F);
Hi, Lo, Mid : Natural;
begin
Lo := Modules_Cache'First;
Hi := Modules_Cache'Last;
while Lo <= Hi loop
Mid := (Lo + Hi) / 2;
if Addr < Low_Address (Modules_Cache (Mid).C) then
Hi := Mid - 1;
elsif Is_Inside (Modules_Cache (Mid).C, Addr) then
Multi_Module_Symbolic_Traceback
(Traceback,
Modules_Cache (Mid).all,
Suppress_Hex,
Res);
return;
else
Lo := Mid + 1;
end if;
end loop;
-- Not found
Hexa_Traceback (Traceback (F .. F), Suppress_Hex, Res);
Multi_Module_Symbolic_Traceback
(Traceback (F + 1 .. Traceback'Last),
Suppress_Hex,
Res);
end;
else
-- First try the executable
if Is_Inside (Exec_Module.C, Traceback (F)) then
Multi_Module_Symbolic_Traceback
(Traceback,
Exec_Module,
Suppress_Hex,
Res);
return;
end if;
-- Otherwise, try a shared library
declare
Load_Addr : aliased System.Address;
M_Name : constant String :=
Module_Name.Get (Addr => Traceback (F),
Load_Addr => Load_Addr'Access);
Module : Module_Cache;
Success : Boolean;
begin
Init_Module (Module, Success, M_Name, Load_Addr);
if Success then
Multi_Module_Symbolic_Traceback
(Traceback,
Module,
Suppress_Hex,
Res);
Close_Module (Module);
else
-- Module not found
Hexa_Traceback (Traceback (F .. F), Suppress_Hex, Res);
Multi_Module_Symbolic_Traceback
(Traceback (F + 1 .. Traceback'Last),
Suppress_Hex,
Res);
end if;
end;
end if;
end Multi_Module_Symbolic_Traceback;
procedure Multi_Module_Symbolic_Traceback
(Traceback : Tracebacks_Array;
Module : Module_Cache;
Suppress_Hex : Boolean;
Res : in out Bounded_String)
is
Pos : Positive;
begin
-- Will symbolize the first address...
Pos := Traceback'First + 1;
-- ... and all addresses in the same module
Same_Module :
loop
exit Same_Module when Pos > Traceback'Last;
-- Get address to check for corresponding module name
exit Same_Module when not Is_Inside (Module.C, Traceback (Pos));
Pos := Pos + 1;
end loop Same_Module;
Module_Symbolic_Traceback
(Traceback (Traceback'First .. Pos - 1),
Module,
Suppress_Hex,
Res);
Multi_Module_Symbolic_Traceback
(Traceback (Pos .. Traceback'Last),
Suppress_Hex,
Res);
end Multi_Module_Symbolic_Traceback;
--------------------
-- Hexa_Traceback --
--------------------
procedure Hexa_Traceback
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String)
is
use System.Traceback_Entries;
begin
if Suppress_Hex then
Append (Res, "...");
Append (Res, ASCII.LF);
else
for J in Traceback'Range loop
Append_Address (Res, PC_For (Traceback (J)));
Append (Res, ASCII.LF);
end loop;
end if;
end Hexa_Traceback;
--------------------------------
-- Symbolic_Traceback_No_Lock --
--------------------------------
procedure Symbolic_Traceback_No_Lock
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean;
Res : in out Bounded_String)
is
begin
if Symbolic.Module_Name.Is_Supported then
Multi_Module_Symbolic_Traceback (Traceback, Suppress_Hex, Res);
else
if Exec_Module_State = Failed then
Append (Res, "Call stack traceback locations:" & ASCII.LF);
Hexa_Traceback (Traceback, Suppress_Hex, Res);
else
Module_Symbolic_Traceback
(Traceback,
Exec_Module,
Suppress_Hex,
Res);
end if;
end if;
end Symbolic_Traceback_No_Lock;
------------------------
-- Symbolic_Traceback --
------------------------
function Symbolic_Traceback
(Traceback : Tracebacks_Array;
Suppress_Hex : Boolean) return String
is
Res : Bounded_String (Max_Length => Max_String_Length);
begin
System.Soft_Links.Lock_Task.all;
Init_Exec_Module;
Symbolic_Traceback_No_Lock (Traceback, Suppress_Hex, Res);
System.Soft_Links.Unlock_Task.all;
return To_String (Res);
exception
when others =>
System.Soft_Links.Unlock_Task.all;
raise;
end Symbolic_Traceback;
function Symbolic_Traceback
(Traceback : System.Traceback_Entries.Tracebacks_Array) return String is
begin
return Symbolic_Traceback (Traceback, Suppress_Hex => False);
end Symbolic_Traceback;
function Symbolic_Traceback_No_Hex
(Traceback : System.Traceback_Entries.Tracebacks_Array) return String is
begin
return Symbolic_Traceback (Traceback, Suppress_Hex => True);
end Symbolic_Traceback_No_Hex;
function Symbolic_Traceback
(E : Ada.Exceptions.Exception_Occurrence;
Suppress_Hex : Boolean) return String
is
begin
return Symbolic_Traceback
(Ada.Exceptions.Traceback.Tracebacks (E),
Suppress_Hex);
end Symbolic_Traceback;
function Symbolic_Traceback
(E : Ada.Exceptions.Exception_Occurrence) return String
is
begin
return Symbolic_Traceback (E, Suppress_Hex => False);
end Symbolic_Traceback;
function Symbolic_Traceback_No_Hex
(E : Ada.Exceptions.Exception_Occurrence) return String is
begin
return Symbolic_Traceback (E, Suppress_Hex => True);
end Symbolic_Traceback_No_Hex;
Exception_Tracebacks_Symbolic : Integer;
pragma Import
(C,
Exception_Tracebacks_Symbolic,
"__gl_exception_tracebacks_symbolic");
-- Boolean indicating whether symbolic tracebacks should be generated.
use Standard_Library;
begin
-- If this version of this package is available, and the binder switch -Es
-- was given, then we want to use this as the decorator by default, and we
-- want to turn on tracing for Unhandled_Raise_In_Main. Note that the user
-- cannot have already set Exception_Trace, because the runtime library is
-- elaborated before user-defined code.
if Exception_Tracebacks_Symbolic /= 0 then
Exception_Traces.Set_Trace_Decorator (Symbolic_Traceback'Access);
pragma Assert (Exception_Trace = RM_Convention);
Exception_Trace := Unhandled_Raise_In_Main;
end if;
end System.Traceback.Symbolic;
|
30,753
|
ada
| 22
|
FardaleM/metalang
|
out/longest_increasing_subsequence.adb
|
<gh_stars>10-100
with ada.text_io, ada.Integer_text_IO, Ada.Text_IO.Text_Streams, Ada.Strings.Fixed, Interfaces.C;
use ada.text_io, ada.Integer_text_IO, Ada.Strings, Ada.Strings.Fixed, Interfaces.C;
procedure longest_increasing_subsequence is
type stringptr is access all char_array;
procedure PString(s : stringptr) is
begin
String'Write (Text_Streams.Stream (Current_Output), To_Ada(s.all));
end;
procedure PInt(i : in Integer) is
begin
String'Write (Text_Streams.Stream (Current_Output), Trim(Integer'Image(i), Left));
end;
procedure SkipSpaces is
C : Character;
Eol : Boolean;
begin
loop
Look_Ahead(C, Eol);
exit when Eol or C /= ' ';
Get(C);
end loop;
end;
type f is Array (Integer range <>) of Integer;
type f_PTR is access f;
function dichofind(len : in Integer; tab : in f_PTR; tofind : in Integer; a : in Integer; b : in Integer) return Integer is
c : Integer;
begin
if a >= b - 1
then
return a;
else
c := (a + b) / 2;
if tab(c) < tofind
then
return dichofind(len, tab, tofind, c, b);
else
return dichofind(len, tab, tofind, a, c);
end if;
end if;
end;
function process(len : in Integer; tab : in f_PTR) return Integer is
size : f_PTR;
k : Integer;
begin
size := new f (0..len - 1);
for j in integer range 0..len - 1 loop
if j = 0
then
size(j) := 0;
else
size(j) := len * 2;
end if;
end loop;
for i in integer range 0..len - 1 loop
k := dichofind(len, size, tab(i), 0, len - 1);
if size(k + 1) > tab(i)
then
size(k + 1) := tab(i);
end if;
end loop;
for l in integer range 0..len - 1 loop
PInt(size(l));
PString(new char_array'( To_C(" ")));
end loop;
for m in integer range 0..len - 1 loop
k := len - 1 - m;
if size(k) /= len * 2
then
return k;
end if;
end loop;
return 0;
end;
n : Integer;
len : Integer;
d : f_PTR;
begin
Get(n);
SkipSpaces;
for i in integer range 1..n loop
Get(len);
SkipSpaces;
d := new f (0..len - 1);
for e in integer range 0..len - 1 loop
Get(d(e));
SkipSpaces;
end loop;
PInt(process(len, d));
PString(new char_array'( To_C("" & Character'Val(10))));
end loop;
end;
|
30,754
|
ada
| 1
|
mullikine/RosettaCodeData
|
Task/Named-parameters/Ada/named-parameters-2.ada
|
<gh_stars>1-10
Foo (1, 0.0);
Foo (1);
Foo (Arg_2 => 0.0, Arg_1 => 1);
Foo (Arg_1 => 1);
|
30,755
|
ada
| 12
|
TUM-EI-RCS/StratoX
|
software/lib/ulog/ulog-conversions.adb
|
<gh_stars>10-100
-- Institution: Technische Universitaet Muenchen
-- Department: Realtime Computer Systems (RCS)
-- Project: StratoX
-- Author: <NAME> (<EMAIL>)
with Ada.Unchecked_Conversion;
-- @summary convert various types to bytearrays
-- FIXME: optimize: don't collect labels and formats unless we are
-- building the header.
package body ULog.Conversions with SPARK_Mode is
----------------------
-- Enoding of types
----------------------
-- Format characters in the format string for binary log messages
-- DONE:
-- f : float
-- Z : char[64]
-- B : uint8_t
-- b : int8_t
-- H : uint16_t
-- h : int16_t
-- i : int32_t
-- I : uint32_t
-- q : int64_t
-- Q : uint64_t
-- TODO:
-- n : char[4]
-- N : char[16]
-- c : int16_t * 100
-- C : uint16_t * 100
-- e : int32_t * 100
-- E : uint32_t * 100
-- L : int32_t latitude/longitude
-- M : uint8_t flight mode
----------------
-- PROTOTYPES
----------------
procedure Add_Labeled (t : in out Conversion_Tag;
label : String;
format : Character;
buf : in out HIL.Byte_Array;
tail : HIL.Byte_Array)
with Pre => label'Length > 0 and then label'First <= label'Last;
procedure Copy_To_Buffer (t : in out Conversion_Tag;
buf : in out HIL.Byte_Array;
tail : HIL.Byte_Array);
function Buffer_Capacity (t : in Conversion_Tag; buf : HIL.Byte_Array)
return Natural
with Post => (if buf'Length <= t.Buffer_Fill then
Buffer_Capacity'Result = 0
else
Buffer_Capacity'Result = buf'Length - t.Buffer_Fill);
-- if the buffer length changed during conversion, then
-- t.Total_Size could be bigger than buf'length.
--------------------
-- New_Conversion --
--------------------
procedure New_Conversion (t : out Conversion_Tag) is
begin
t.Buffer_Fill := 0;
t.Buffer_Overflow := False;
t.Name := (others => HIL.Byte (0));
t.Label_Collect := (Labels => (others => HIL.Byte (0)), Length => 0);
t.Format_Collect := (Format => (others => HIL.Byte (0)), Length => 0);
end New_Conversion;
--------------
-- Get_Size --
--------------
function Get_Size (t : in Conversion_Tag) return Natural is
(t.Buffer_Fill);
---------------------
-- Buffer_Overflow --
---------------------
function Buffer_Overflow (t : in Conversion_Tag) return Boolean is
(t.Buffer_Overflow);
----------------
-- Get_Format --
----------------
function Get_Format (t : in Conversion_Tag) return ULog_Format is
(t.Format_Collect.Format);
----------------
-- Get_Labels --
----------------
function Get_Labels (t : in Conversion_Tag) return ULog_Label is
(t.Label_Collect.Labels);
--------------
-- Get_Name --
--------------
function Get_Name (t : in Conversion_Tag) return ULog_Name is
(t.Name);
--------------
-- Set_Name --
--------------
procedure Set_Name (t : in out Conversion_Tag; s : String) is
subtype shortname is String (1 .. ULog_Name'Length);
function To_Name is new Ada.Unchecked_Conversion (shortname, ULog_Name);
tmp : shortname := (others => Character'Val (0));
slen : constant Integer :=
(if s'Length > tmp'Length then tmp'Length else s'Length);
begin
if slen > 0 then
tmp (tmp'First .. tmp'First + (slen - 1)) :=
s (s'First .. s'First + (slen - 1));
end if;
t.Name := To_Name (tmp);
end Set_Name;
---------------------
-- Buffer_Capacity --
---------------------
function Buffer_Capacity
(t : in Conversion_Tag; buf : HIL.Byte_Array) return Natural
is
fill : constant Natural := t.Buffer_Fill;
blen : constant Natural := buf'Length;
cap : Natural;
begin
if blen > fill then
cap := blen - fill;
else
cap := 0;
end if;
return cap;
end Buffer_Capacity;
--------------------
-- Copy_To_Buffer --
--------------------
-- add as much as we can to the buffer, without overflowing
procedure Copy_To_Buffer
(t : in out Conversion_Tag;
buf : in out HIL.Byte_Array;
tail : HIL.Byte_Array)
is
cap : constant Natural := Buffer_Capacity (t, buf);
fill : constant Natural := t.Buffer_Fill;
tlen : constant Natural := tail'Length;
begin
if tlen > 0 and then cap >= tlen and
then buf'Length >= fill -- buffer inconsistency .. don't continue
then
-- this means the buffer can take all of it
declare
idx_l : constant Integer := buf'First + fill;
idx_h : constant Integer := idx_l + (tlen - 1);
begin
buf (idx_l .. idx_h) := tail;
end;
-- bookkeeping
if Natural'Last - fill >= tlen then
t.Buffer_Fill := fill + tlen;
else
t.Buffer_Fill := Natural'Last;
end if;
else
t.Buffer_Overflow := True;
end if;
end Copy_To_Buffer;
--------------------
-- Append_Labeled --
--------------------
procedure Add_Labeled
(t : in out Conversion_Tag;
label : String;
format : Character;
buf : in out HIL.Byte_Array;
tail : HIL.Byte_Array)
is
lbl_cap : constant Integer :=
t.Label_Collect.Labels'Length - t.Label_Collect.Length;
fmt_cap : constant Integer :=
t.Format_Collect.Format'Length - t.Format_Collect.Length;
begin
if Buffer_Capacity (t, buf) >= tail'Length and
then lbl_cap > label'Length -- not >=, because of ','
and then fmt_cap > 0
then
Copy_To_Buffer (t => t, buf => buf, tail => tail);
if t.Label_Collect.Length > 0 then
t.Label_Collect.Length := t.Label_Collect.Length + 1;
t.Label_Collect.Labels (t.Label_Collect.Length) :=
HIL.Byte (Character'Pos (','));
end if;
declare
idx_lbl_lo : constant Integer :=
t.Label_Collect.Labels'First + t.Label_Collect.Length;
idx_lbl_hi : constant Integer := idx_lbl_lo + (label'Length - 1);
idx_fmt : constant Integer :=
t.Format_Collect.Format'First + t.Format_Collect.Length;
subtype VarString is String (1 .. label'Length);
subtype VarBytes is HIL.Byte_Array (1 .. label'Length);
function To_Bytes is new
Ada.Unchecked_Conversion (VarString, VarBytes);
d : constant VarBytes := To_Bytes (label);
begin
t.Label_Collect.Labels (idx_lbl_lo .. idx_lbl_hi) := d;
t.Format_Collect.Format (idx_fmt) :=
HIL.Byte (Character'Pos (format));
end;
end if;
-- keep counting, so caller can see potential overflow
if Natural'Last - t.Label_Collect.Length > label'Length then
t.Label_Collect.Length := t.Label_Collect.Length + label'Length;
else
t.Label_Collect.Length := Natural'Last;
end if;
if Natural'Last - t.Format_Collect.Length > 0 then
t.Format_Collect.Length := t.Format_Collect.Length + 1;
else
t.Format_Collect.Length := Natural'Last;
end if;
end Add_Labeled;
----------------------------
-- Append_Unlabeled_Bytes --
----------------------------
procedure Append_Unlabeled_Bytes
(t : in out Conversion_Tag;
buf : in out HIL.Byte_Array;
tail : HIL.Byte_Array) is
begin
Copy_To_Buffer (t => t, buf => buf, tail => tail);
end Append_Unlabeled_Bytes;
------------------
-- Append_Float --
------------------
procedure Append_Float
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Float)
is
subtype Byte4 is Byte_Array (1 .. 4);
function To_Bytes is new Ada.Unchecked_Conversion (Float, Byte4);
begin
Add_Labeled (t, label, 'f', buf, To_Bytes (tail));
end Append_Float;
------------------
-- Append_Uint8 --
------------------
procedure Append_Uint8
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Unsigned_8)
is
barr : constant Byte_Array := (1 => HIL.Byte (tail));
begin
Add_Labeled (t, label, 'B', buf, barr);
end Append_Uint8;
-----------------
-- Append_Int8 --
-----------------
procedure Append_Int8
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Integer_8)
is
subtype Byte1 is Byte_Array (1 .. 1);
function To_Bytes is new Ada.Unchecked_Conversion (Integer_8, Byte1);
begin
Add_Labeled (t, label, 'b', buf, To_Bytes (tail));
end Append_Int8;
-------------------
-- Append_Uint16 --
-------------------
procedure Append_Uint16
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Unsigned_16)
is
subtype Byte2 is Byte_Array (1 .. 2);
function To_Bytes is new Ada.Unchecked_Conversion (Unsigned_16, Byte2);
begin
Add_Labeled (t, label, 'H', buf, To_Bytes (tail));
end Append_Uint16;
------------------
-- Append_Int16 --
------------------
procedure Append_Int16
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Integer_16)
is
subtype Byte2 is Byte_Array (1 .. 2);
function To_Bytes is new Ada.Unchecked_Conversion (Integer_16, Byte2);
begin
Add_Labeled (t, label, 'h', buf, To_Bytes (tail));
end Append_Int16;
-------------------
-- Append_UInt32 --
-------------------
procedure Append_Uint32
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Unsigned_32)
is
subtype Byte4 is Byte_Array (1 .. 4);
function To_Bytes is new Ada.Unchecked_Conversion (Unsigned_32, Byte4);
begin
Add_Labeled (t, label, 'I', buf, To_Bytes (tail));
end Append_Uint32;
------------------
-- Append_Int32 --
------------------
procedure Append_Int32
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Integer_32)
is
subtype Byte4 is Byte_Array (1 .. 4);
function To_Bytes is new Ada.Unchecked_Conversion (Integer_32, Byte4);
begin
Add_Labeled (t, label, 'i', buf, To_Bytes (tail));
end Append_Int32;
-------------------
-- Append_UInt64 --
-------------------
procedure Append_Uint64
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Unsigned_64)
is
subtype Byte8 is Byte_Array (1 .. 8);
function To_Bytes is new Ada.Unchecked_Conversion (Unsigned_64, Byte8);
begin
Add_Labeled (t, label, 'Q', buf, To_Bytes (tail));
end Append_Uint64;
------------------
-- Append_Int64 --
------------------
procedure Append_Int64
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : Integer_64)
is
subtype Byte8 is Byte_Array (1 .. 8);
function To_Bytes is new Ada.Unchecked_Conversion (Integer_64, Byte8);
begin
Add_Labeled (t, label, 'q', buf, To_Bytes (tail));
end Append_Int64;
---------------------
-- Append_String64 --
---------------------
procedure Append_String64
(t : in out Conversion_Tag; label : String;
buf : in out HIL.Byte_Array; tail : String; slen : Natural)
is
subtype String64 is String (1 .. 64);
subtype Byte64 is Byte_Array (1 .. String64'Length);
function To_Byte64 is new Ada.Unchecked_Conversion (String64, Byte64);
tmp : String64 := (others => Character'Val (0));
len : constant Integer :=
(if slen > tmp'Length then tmp'Length else slen);
begin
if len > 0 then
tmp (tmp'First .. tmp'First + (len - 1)) :=
tail (tail'First .. tail'First + (len - 1));
end if;
Add_Labeled (t, label, 'Z', buf, To_Byte64 (tmp));
end Append_String64;
end ULog.Conversions;
|
30,756
|
ada
| 9
|
SALLYPEMDAS/DW1000
|
tests/dw1000-system_time-tests.adb
|
-------------------------------------------------------------------------------
-- Copyright (c) 2016 <NAME>
--
-- Permission is hereby granted, free of charge, to any person obtaining a
-- copy of this software and associated documentation files (the "Software"),
-- to deal in the Software without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Software, and to permit persons to whom the
-- Software is furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
-------------------------------------------------------------------------------
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with AUnit.Assertions; use AUnit.Assertions;
with DW1000.Types; use DW1000.Types;
with System.Multiprocessors; use System.Multiprocessors;
package body DW1000.System_Time.Tests
is
-- The tests in this package perform exhaustive tests over the full 40-bit
-- range in order to prove certain properties about the system time types.
--
-- In order to speed up the tests, the tests take advantage of
-- multiprocessors to split the 2**40 test range into multiple sub-ranges,
-- and each sub-range is delegated to a task. This provides a roughly
-- linear reduction in execution time, based on the number of CPU threads.
--
-- However, even when taking advantage of multicore processors the tests
-- take many hours to complete (about 10 hours per exhaustive test on my
-- Intel Core i7-2630QM laptop).
--
-- The tests could be sped up even further by enabling compiler
-- optimizations. However, when mixed with AUnit the optimization switches
-- seem to cause the tests to crash at runtime with a Storage_Error fault,
-- so optimizations should be disabled until a resolution to this problem
-- is found.
----------------------------------------------------------------------------
-- This protected type is used to synchronize with the tasks which are
-- running the tests.
--
-- The environment thread calls Reset before starting its child tasks in
-- order to reset the state between tests.
--
-- Each child task MUST call Notify when it has finished its portion of the
-- test (successfully or not). When all N tasks have called notify the Wait
-- entry will be unblocked.
--
-- The environment task waits for all child tasks to finish by calling the
-- Wait entry. It will be unblocked once all child tasks have called
-- Notify.
--
-- Each child task should periodically query the Test_Failed function to
-- check if another child task has already encountered a test failure.
-- If Test_Failed returns True then the child task should abort its tests
-- ASAP (it must still call Notify, though). This permits the entire test
-- to finish early when a failure is found.
--
-- The parameter N is the number of child tasks that are being used.
-- It's recommended to set this to System.Multiprocessors.Number_Of_CPUs
-- and take advantage of all available logical CPU cores.
protected type Test_Result_PO_Type (N : CPU)
is
entry Wait (Test_Result : out Boolean;
Fail_Message : out Unbounded_String);
procedure Reset;
procedure Notify (Test_Result : in Boolean;
Fail_Message : in Unbounded_String);
function Test_Failed return Boolean;
private
Count : CPU_Range := 0;
Result : Boolean := True;
Message : Unbounded_String := Null_Unbounded_String;
end Test_Result_PO_Type;
protected body Test_Result_PO_Type
is
entry Wait (Test_Result : out Boolean;
Fail_Message : out Unbounded_String)
when Count = N
is
begin
Test_Result := Result;
Fail_Message := Message;
end Wait;
procedure Reset
is
begin
Count := 0;
Result := True;
Message := Null_Unbounded_String;
end Reset;
procedure Notify (Test_Result : in Boolean;
Fail_Message : in Unbounded_String)
is
begin
if Count < N then
Count := Count + 1;
end if;
if Result and not Test_Result then
Result := False;
Message := Fail_Message;
end if;
end Notify;
function Test_Failed return Boolean
is
begin
return not Result;
end Test_Failed;
end Test_Result_PO_Type;
Test_Result_PO : Test_Result_PO_Type (Number_Of_CPUs);
----------------------------------------------------------------------------
-- Test_Bits_40_Fine
----------------------------------------------------------------------------
procedure Test_Bits_40_Fine (T : in out Test)
is
-- This task type runs a range of test values for this test.
-- Multiple tasks are used to process different ranges to provide a
-- significant speedup
task type Runner_Task is
entry Start (Test_First : in Bits_40;
Test_Last : in Bits_40);
end Runner_Task;
task body Runner_Task
is
First : Bits_40;
Last : Bits_40;
begin
accept Start (Test_First : in Bits_40;
Test_Last : in Bits_40) do
First := Test_First;
Last := Test_Last;
end Start;
loop
-- Don't check for test failure on every iteration, in order to
-- prevent slowdown and lots of lock contention on the PO.
for I in Bits_40 range 0 .. 1_000_000 loop
pragma Assert
(First = To_Bits_40 (To_Fine_System_Time (First)),
"failed for X =" & Bits_40'Image (First) &
"actual =" &
Bits_40'Image (To_Bits_40 (To_Fine_System_Time (First))));
exit when First = Last;
First := First + 1;
end loop;
-- Stop early if the test has already failed
-- (another task has noticed a test failure).
exit when Test_Result_PO.Test_Failed or else First = Last;
end loop;
-- Test success.
Test_Result_PO.Notify (True, Null_Unbounded_String);
exception
when Error : others =>
Test_Result_PO.Notify
(False, To_Unbounded_String (Exception_Message (Error)));
end Runner_Task;
Runners : array (CPU range 1 .. Number_Of_CPUs) of Runner_Task;
Test_Result : Boolean;
Fail_Message : Unbounded_String;
First : Bits_40;
Last : Bits_40;
Chunk_Length : constant Bits_40 := 2**40 / Runners'Length;
begin
Test_Result_PO.Reset;
First := 0;
Last := Chunk_Length - 1;
for I in Runners'Range loop
if I < Number_Of_CPUs then
Runners (I).Start (First, Last);
else
Runners (I).Start (First, Bits_40'Last);
end if;
First := Last + 1;
Last := Last + (Chunk_Length - 1);
end loop;
-- Wait for all tasks to terminate (successfully or not).
-- Tasks will stop early when they notice that the test has failed.
Test_Result_PO.Wait (Test_Result, Fail_Message);
Assert (Test_Result, To_String (Fail_Message));
end Test_Bits_40_Fine;
------------------------------------------------------------------------- ---
-- Test_Bits_40_Coarse
----------------------------------------------------------------------------
procedure Test_Bits_40_Coarse (T : in out Test)
is
-- This task type runs a range of test values for this test.
-- Multiple tasks are used to process different ranges to provide a
-- significant speedup
task type Runner_Task is
entry Start (Test_First : in Bits_40;
Test_Last : in Bits_40);
end Runner_Task;
task body Runner_Task
is
First : Bits_40;
Last : Bits_40;
begin
accept Start (Test_First : in Bits_40;
Test_Last : in Bits_40) do
First := Test_First;
Last := Test_Last;
end Start;
loop
-- Don't check for test failure on every iteration, in order to
-- prevent slowdown and lots of lock contention on the PO.
for I in Bits_40 range 0 .. 1_000_000 loop
pragma Assert
((First and 16#FFFFFFFE00#) =
To_Bits_40 (To_Coarse_System_Time (First)),
"failed for Y =" & Bits_40'Image (First) &
", actual =" &
Bits_40'Image (To_Bits_40 (To_Coarse_System_Time (First)))
);
exit when First = Last;
First := First + 1;
end loop;
-- Stop early if the test has already failed
-- (another task has noticed a test failure).
exit when Test_Result_PO.Test_Failed or else First = Last;
end loop;
-- Test success.
Test_Result_PO.Notify (True, Null_Unbounded_String);
exception
when Error : others =>
Test_Result_PO.Notify
(False, To_Unbounded_String (Exception_Message (Error)));
end Runner_Task;
Runners : array (CPU range 1 .. Number_Of_CPUs) of Runner_Task;
Test_Result : Boolean;
Fail_Message : Unbounded_String;
First : Bits_40;
Last : Bits_40;
Chunk_Length : constant Bits_40 := 2**40 / Runners'Length;
begin
Test_Result_PO.Reset;
First := 0;
Last := Chunk_Length - 1;
for I in Runners'Range loop
if I < Number_Of_CPUs then
Runners (I).Start (First, Last);
else
Runners (I).Start (First, Bits_40'Last);
end if;
First := Last + 1;
Last := Last + (Chunk_Length - 1);
end loop;
-- Wait for all tasks to terminate (successfully or not).
-- Tasks will stop early when they notice that the test has failed.
Test_Result_PO.Wait (Test_Result, Fail_Message);
Assert (Test_Result, To_String (Fail_Message));
end Test_Bits_40_Coarse;
----------------------------------------------------------------------------
-- Test_To_Coarse_System_Time
----------------------------------------------------------------------------
procedure Test_To_Coarse_System_Time (T : in out Test)
is
-- This task type runs a range of test values for this test.
-- Multiple tasks are used to process different ranges to provide a
-- significant speedup
task type Runner_Task is
entry Start (Test_First : in Coarse_System_Time;
Test_Last : in Coarse_System_Time);
end Runner_Task;
task body Runner_Task
is
First : Coarse_System_Time;
Last : Coarse_System_Time;
begin
accept Start (Test_First : in Coarse_System_Time;
Test_Last : in Coarse_System_Time) do
First := Test_First;
Last := Test_Last;
end Start;
loop
-- Don't check for test failure on every iteration, in order to
-- prevent slowdown and lots of lock contention on the PO.
for I in Integer range 0 .. 1_000_000 loop
pragma Assert
(First = To_Coarse_System_Time (To_Fine_System_Time (First)),
"failed for X =" & Coarse_System_Time'Image (First));
exit when First = Last;
First := Coarse_System_Time'Succ (First);
end loop;
-- Stop early if the test has already failed
-- (another task has noticed a test failure).
exit when Test_Result_PO.Test_Failed or else First = Last;
end loop;
-- Test success.
Test_Result_PO.Notify (True, Null_Unbounded_String);
exception
when Error : others =>
Test_Result_PO.Notify
(False, To_Unbounded_String (Exception_Message (Error)));
end Runner_Task;
Runners : array (CPU range 1 .. Number_Of_CPUs) of Runner_Task;
Test_Result : Boolean;
Fail_Message : Unbounded_String;
First : Coarse_System_Time;
Last : Coarse_System_Time;
Chunk_Length : constant Coarse_System_Time :=
Coarse_System_Time'Last / Runners'Length;
begin
Test_Result_PO.Reset;
First := 0.0;
Last := Chunk_Length;
for I in Runners'Range loop
if I < Number_Of_CPUs then
Runners (I).Start (First, Last);
First := Last;
Last := Last + Chunk_Length;
else
Runners (I).Start (First, Coarse_System_Time'Last);
end if;
end loop;
-- Wait for all tasks to terminate (successfully or not).
-- Tasks will stop early when they notice that the test has failed.
Test_Result_PO.Wait (Test_Result, Fail_Message);
Assert (Test_Result, To_String (Fail_Message));
end Test_To_Coarse_System_Time;
end DW1000.System_Time.Tests;
|
30,757
|
ada
| 24
|
svn2github/matreshka
|
tools/ucd_data.adb
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2009-2015, <NAME> <<EMAIL>> --
-- 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.Text_IO;
with Ada.Unchecked_Deallocation;
with Ucd_Input;
with Utils;
package body Ucd_Data is
use Matreshka.Internals.Unicode;
use Matreshka.Internals.Unicode.Ucd;
use Utils;
UnicodeData_Name : constant String := "UnicodeData.txt";
PropList_Name : constant String := "PropList.txt";
DerivedCoreProperties_Name : constant String
:= "DerivedCoreProperties.txt";
EastAsianWidth_Name : constant String
:= "EastAsianWidth.txt";
GraphemeBreakProperty_Name : constant String
:= "auxiliary/GraphemeBreakProperty.txt";
WordBreakProperty_Name : constant String
:= "auxiliary/WordBreakProperty.txt";
SentenceBreakProperty_Name : constant String
:= "auxiliary/SentenceBreakProperty.txt";
LineBreak_Name : constant String := "LineBreak.txt";
SpecialCasing_Name : constant String := "SpecialCasing.txt";
CaseFolding_Name : constant String := "CaseFolding.txt";
DerivedNormalizationProps_Name : constant String
:= "DerivedNormalizationProps.txt";
CompositionExclusions_Name : constant String
:= "CompositionExclusions.txt";
NormalizationCorrections_Name : constant String
:= "NormalizationCorrections.txt";
subtype Primary_Core_Boolean_Properties is Boolean_Properties
range ASCII_Hex_Digit .. White_Space;
subtype Derived_Core_Boolean_Properties is Boolean_Properties
range Alphabetic .. XID_Start;
procedure Load_UnicodeData (Unidata_Directory : String);
-- Parse UnicodeData.txt file and fill internal data structures by the
-- parsed values.
procedure Load_PropList (Unidata_Directory : String);
-- Parse PropList.txt file and fill internal data structurs by the parsed
-- values.
procedure Load_DerivedCoreProperties (Unidata_Directory : String);
-- Parse DerivedCoreProperties.txt file and fill internal data structurs by
-- the parsed values.
procedure Load_EastAsianWidth (Unidata_Directory : String);
-- Parse EastAsianWidth.txt file and fill internal data structurs by --
-- the parsed values.
procedure Load_GraphemeBreakProperty (Unidata_Directory : String);
-- Parse GraphemeBreakProperty.txt file and fill internal data structurs by
-- the parsed values.
procedure Load_WordBreakProperty (Unidata_Directory : String);
-- Parse WordBreakProperty.txt file and fill internal data structurs by the
-- parsed values.
procedure Load_SentenceBreakProperty (Unidata_Directory : String);
-- Parse SentenceBreakProperty.txt file and fill internal data structurs by
-- the parsed values.
procedure Load_LineBreak (Unidata_Directory : String);
-- Parse LineBreak.txt file and fill internal data structurs by the parsed
-- values.
procedure Load_SpecialCasing (Unidata_Directory : String);
-- Parse SpecialCasing.txt file and fill internal data structurs by the
-- parsed values.
procedure Load_CaseFolding (Unidata_Directory : String);
-- Parse CaseFolding.txt file and fill internal data structurs by the
-- parsed values.
procedure Load_CompositionExclusions (Unidata_Directory : String);
-- Parse CompositionExclusions.txt file and fill internal data structures
-- by the parsed values.
procedure Load_DerivedNormalizationProps (Unidata_Directory : String);
-- Parse DerivedNormalizationProps.txt file and fill internal data
-- structures by the parsed values.
procedure Load_NormalizationCorrections (Unidata_Directory : String);
-- Parse NormalizationCorrections.txt file and fill internal data
-- structures by the parsed values.
procedure Compute_Full_Normalization_Data;
-- Compute full normalization mapping for both normalization forms.
procedure Parse_Code_Point
(Text : String;
Code : out Code_Point);
function Value (Item : String) return General_Category;
-- Converts two-character text representation of the General_Category
-- property into the value.
function Value (Item : String) return Grapheme_Cluster_Break;
-- Converts text representation of the Grapheme_Cluster_Break into the
-- value.
function Value (Item : String) return East_Asian_Width;
-- Converts text representation of the East_Asian_Width into value.
function Value (Item : String) return Word_Break;
-- Converts text representation of the Word_Break into the value.
function Value (Item : String) return Sentence_Break;
-- Converts text representation of the Sentence_Break into the value.
function Value (Item : String) return Line_Break;
-- Converts two-character text representation of the Line_Break into the
-- value.
function Value (Item : String) return Normalization_Quick_Check;
-- Converts one character text representation of the normalization quick
-- check into the value.
function Value (Item : String) return Decomposition_Type;
-- Converts text representation of the Decomposition_Type into the value.
procedure Free is
new Ada.Unchecked_Deallocation
(Code_Point_Sequence, Code_Point_Sequence_Access);
-------------------------------------
-- Compute_Full_Normalization_Data --
-------------------------------------
procedure Compute_Full_Normalization_Data is
procedure Expand (Kind : Normalization_Kinds);
------------
-- Expand --
------------
procedure Expand (Kind : Normalization_Kinds) is
function Has_Mapping (Code : Code_Point) return Boolean;
-- Returns True if code point has corresponding to Kind mapping.
function Decompose (Code : Code_Point) return Code_Point_Sequence;
-- Returns character's decomposition.
subtype S_Hangul is Code_Point
range Hangul_Syllable_First .. Hangul_Syllable_Last;
---------------
-- Decompose --
---------------
function Decompose (Code : Code_Point) return Code_Point_Sequence is
begin
if Code in S_Hangul then
raise Program_Error
with "Decomposition of Hangul Syllables doesn't supported"
& " for now";
else
return Norms (Code).Values (Kind).all;
end if;
end Decompose;
-----------------
-- Has_Mapping --
-----------------
function Has_Mapping (Code : Code_Point) return Boolean is
begin
if Code in S_Hangul then
return True;
else
case Kind is
when Canonical_Mapping =>
raise Program_Error;
when Canonical =>
return Norms (Code).DT = Canonical;
when Compatibility =>
return Norms (Code).DT /= None;
end case;
end if;
end Has_Mapping;
Expanded : Boolean;
begin
loop
Expanded := False;
for J in Norms'Range loop
if Has_Mapping (J) and then J not in S_Hangul then
declare
M : Code_Point_Sequence_Access := null;
A : Code_Point_Sequence_Access;
begin
for K in Norms (J).Values (Kind)'Range loop
if Has_Mapping (Norms (J).Values (Kind) (K)) then
if M = null then
M :=
new Code_Point_Sequence'
(Norms (J).Values (Kind) (1 .. K - 1)
& Decompose
(Norms (J).Values (Kind) (K)));
else
A := M;
M :=
new Code_Point_Sequence'
(A.all
& Decompose
(Norms (J).Values (Kind) (K)));
Free (A);
end if;
elsif M /= null then
A := M;
M :=
new Code_Point_Sequence'
(A.all & Norms (J).Values (Kind) (K));
Free (A);
end if;
end loop;
if M /= null then
Free (Norms (J).Values (Kind));
Norms (J).Values (Kind) := M;
Expanded := True;
end if;
end;
end if;
end loop;
exit when not Expanded;
end loop;
end Expand;
begin
Expand (Canonical);
Expand (Compatibility);
end Compute_Full_Normalization_Data;
----------
-- Load --
----------
procedure Load (Unidata_Directory : String) is
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, "Initializing UCD ...");
-- Initialize data structures to default values.
Core :=
new Core_Values_Array'
(others =>
(GC => Unassigned, -- see UCD.html
GCB => Other, -- see GraphemeBreakProperty.txt
WB => Other, -- see WordBreakProperty.txt
SB => Other, -- see SentenceBreakProperty.txt
LB => Unknown, -- see LineBreak.txt
EA => Neutral, -- see EastAsianWidth.txt
B => (others => False)));
Cases :=
new Case_Values_Array'
(others =>
(SUM | SLM | STM | SCF => (Present => False),
FUM | FLM | FTM =>
(Default => null, others => (others => null)),
FCF => null));
Norms :=
new Normalization_Values_Array'
(others => (CCC => Not_Reordered,
NQC => (others => Yes),
DT => None,
B => (others => False),
Values => (others => null)));
-- Load UnicodeData.txt, PropList.txt.
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
"Loading UCD (" & Unidata_Directory & ") ...");
Load_UnicodeData (Unidata_Directory);
Load_PropList (Unidata_Directory);
-- Load DerivedCoreProperties.txt.
-- NOTE: Data in the file is derived from the other information, so
-- it is possible to use it for verification purposes only.
Load_DerivedCoreProperties (Unidata_Directory);
-- Load EastAsianWidth.txt
Load_EastAsianWidth (Unidata_Directory);
-- Load GraphemeBreakProperty.txt, WordBreakProperty.txt.
Load_GraphemeBreakProperty (Unidata_Directory);
Load_WordBreakProperty (Unidata_Directory);
Load_SentenceBreakProperty (Unidata_Directory);
Load_LineBreak (Unidata_Directory);
-- Load SpecialCasing.txt, CaseFolding.txt
Load_SpecialCasing (Unidata_Directory);
Load_CaseFolding (Unidata_Directory);
-- Load CompositionExclusions.txt, DerivedNormalizationProps.txt,
-- NormalizationCorrections.txt.
Load_CompositionExclusions (Unidata_Directory);
Load_DerivedNormalizationProps (Unidata_Directory);
Load_NormalizationCorrections (Unidata_Directory);
-- Compute derived properties.
Compute_Full_Normalization_Data;
-- Verify data:
-- - DerivedGeneralCategory.txt
-- - DerivedCombiningClass.txt
-- - DerivedBinaryProperties.txt
-- - DerivedDecompositionType.txt
-- - DerivedLineBreak.txt
end Load;
----------------------
-- Load_CaseFolding --
----------------------
procedure Load_CaseFolding (Unidata_Directory : String) is
type Case_Folding_Status is (C, F, S, T);
File : Ucd_Input.File_Type;
Code : Code_Point;
Status : Case_Folding_Status;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & CaseFolding_Name);
Ucd_Input.Open (File, Unidata_Directory & '/' & CaseFolding_Name);
while not Ucd_Input.End_Of_Data (File) loop
Code := Ucd_Input.First_Code_Point (File);
-- Status
Status := Case_Folding_Status'Value (Ucd_Input.Field (File));
Ucd_Input.Next_Field (File);
-- Mapping
case Status is
when C | S =>
Cases (Code).SCF := (True, 0);
Parse_Code_Point (Ucd_Input.Field (File), Cases (Code).SCF.C);
when F =>
Cases (Code).FCF :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
when T =>
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " Ignore mapping: T");
end case;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_CaseFolding;
--------------------------------
-- Load_CompositionExclusions --
--------------------------------
procedure Load_CompositionExclusions (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & CompositionExclusions_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & CompositionExclusions_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
for J in First .. Last loop
Norms (J).B (Composition_Exclusion) := True;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_CompositionExclusions;
--------------------------------
-- Load_DerivedCoreProperties --
--------------------------------
procedure Load_DerivedCoreProperties (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Derived_Core_Boolean_Properties;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & DerivedCoreProperties_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & DerivedCoreProperties_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop :=
Derived_Core_Boolean_Properties'Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).B (Prop) := True;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_DerivedCoreProperties;
------------------------------------
-- Load_DerivedNormalizationProps --
------------------------------------
procedure Load_DerivedNormalizationProps (Unidata_Directory : String) is
type Property is
(FC_NFKC, -- + mapping
Full_Composition_Exclusion,
NFD_QC, -- + value
NFC_QC, -- + value
NFKD_QC, -- + value
NFKC_QC, -- + value
Expands_On_NFD,
Expands_On_NFC,
Expands_On_NFKD,
Expands_On_NFKC,
NFKC_CF, -- + mapping
Changes_When_NFKC_Casefolded);
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Property;
FC_NFKC_Ignored : Boolean := False;
NFKC_CF_Ignored : Boolean := False;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
" ... " & DerivedNormalizationProps_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & DerivedNormalizationProps_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Property'Value (Ucd_Input.Field (File));
Ucd_Input.Next_Field (File);
for J in First .. Last loop
case Prop is
when FC_NFKC =>
if not FC_NFKC_Ignored then
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
" Ignore property: FC_NFKC");
FC_NFKC_Ignored := True;
end if;
when Full_Composition_Exclusion =>
Norms (J).B (Full_Composition_Exclusion) := True;
when NFD_QC =>
Norms (J).NQC (NFD) := Value (Ucd_Input.Field (File));
when NFC_QC =>
Norms (J).NQC (NFC) := Value (Ucd_Input.Field (File));
when NFKD_QC =>
Norms (J).NQC (NFKD) := Value (Ucd_Input.Field (File));
when NFKC_QC =>
Norms (J).NQC (NFKC) := Value (Ucd_Input.Field (File));
when Expands_On_NFD =>
Norms (J).B (Expands_On_NFD) := True;
when Expands_On_NFC =>
Norms (J).B (Expands_On_NFC) := True;
when Expands_On_NFKD =>
Norms (J).B (Expands_On_NFKD) := True;
when Expands_On_NFKC =>
Norms (J).B (Expands_On_NFKD) := True;
when NFKC_CF =>
if not NFKC_CF_Ignored then
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
" Ignore property: NFKC_CF");
NFKC_CF_Ignored := True;
end if;
when Changes_When_NFKC_Casefolded =>
Core (J).B (Changes_When_NFKC_Casefolded) := True;
end case;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_DerivedNormalizationProps;
-------------------------
-- Load_EastAsianWidth --
-------------------------
procedure Load_EastAsianWidth (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : East_Asian_Width;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & EastAsianWidth_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & EastAsianWidth_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).EA := Prop;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_EastAsianWidth;
--------------------------------
-- Load_GraphemeBreakProperty --
--------------------------------
procedure Load_GraphemeBreakProperty (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Grapheme_Cluster_Break;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
" ... " & GraphemeBreakProperty_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & GraphemeBreakProperty_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).GCB := Prop;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_GraphemeBreakProperty;
--------------------
-- Load_LineBreak --
--------------------
procedure Load_LineBreak (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Line_Break;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & LineBreak_Name);
Ucd_Input.Open (File, Unidata_Directory & '/' & LineBreak_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).LB := Prop;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_LineBreak;
-----------------------------------
-- Load_NormalizationCorrections --
-----------------------------------
procedure Load_NormalizationCorrections (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
Code : Code_Point;
Original : Code_Point_Sequence_Access;
Corrected : Code_Point_Sequence_Access;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & NormalizationCorrections_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & NormalizationCorrections_Name);
while not Ucd_Input.End_Of_Data (File) loop
Code := Ucd_Input.First_Code_Point (File);
Original :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
Ucd_Input.Next_Field (File);
Corrected :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
if Norms (Code).Values (Canonical).all /= Original.all then
if Norms (Code).Values (Canonical).all /= Corrected.all then
raise Program_Error with "Wrong original decomposition";
else
Free (Corrected);
end if;
else
Free (Norms (Code).Values (Canonical));
Norms (Code).Values (Canonical) := Corrected;
if Norms (Code).DT /= Canonical then
Free (Norms (Code).Values (Compatibility));
Norms (Code).Values (Compatibility) :=
new Code_Point_Sequence'(Corrected.all);
end if;
end if;
Free (Original);
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_NormalizationCorrections;
-------------------
-- Load_PropList --
-------------------
procedure Load_PropList (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Primary_Core_Boolean_Properties;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & PropList_Name);
Ucd_Input.Open (File, Unidata_Directory & '/' & PropList_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop :=
Primary_Core_Boolean_Properties'Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).B (Prop) := True;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_PropList;
--------------------------------
-- Load_SentenceBreakProperty --
--------------------------------
procedure Load_SentenceBreakProperty (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Sentence_Break;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & SentenceBreakProperty_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & SentenceBreakProperty_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).SB := Prop;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_SentenceBreakProperty;
------------------------
-- Load_SpecialCasing --
------------------------
procedure Load_SpecialCasing (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
Code : Code_Point;
Lower : Code_Point_Sequence_Access;
Upper : Code_Point_Sequence_Access;
Title : Code_Point_Sequence_Access;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & SpecialCasing_Name);
Ucd_Input.Open
(File, Unidata_Directory & '/' & SpecialCasing_Name);
while not Ucd_Input.End_Of_Data (File) loop
Code := Ucd_Input.First_Code_Point (File);
-- Lowercase mapping
Lower :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
Ucd_Input.Next_Field (File);
-- Uppercase mapping
Upper :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
Ucd_Input.Next_Field (File);
-- Titlecase mapping
Title :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence (Ucd_Input.Field (File)));
Ucd_Input.Next_Field (File);
-- Conditions
declare
V : constant String := Ucd_Input.Field (File);
begin
if V = "Final_Sigma" then
if Upper'Length /= 1
or else Upper (1) /= Code
then
Cases (Code).FUM.Positive (Final_Sigma) := Upper;
end if;
if Lower'Length /= 1
or else Lower (1) /= Code
then
Cases (Code).FLM.Positive (Final_Sigma) := Lower;
end if;
if Title'Length /= 1
or else Title (1) /= Code
then
Cases (Code).FTM.Positive (Final_Sigma) := Title;
end if;
elsif V'Length = 0 then
Cases (Code).FUM.Default := Upper;
Cases (Code).FLM.Default := Lower;
Cases (Code).FTM.Default := Title;
else
-- XXX Ignore more complex contexts for now.
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error,
" Ignore mapping: " & Ucd_Input.Field (File));
end if;
end;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_SpecialCasing;
----------------------
-- Load_UnicodeData --
----------------------
procedure Load_UnicodeData (Unidata_Directory : String) is
type String_Access is access String;
procedure Process
(Code : Code_Point;
GC : General_Category;
CCC : Canonical_Combining_Class;
DT : Decomposition_Type;
DM : Code_Point_Sequence;
SUM : Optional_Code_Point;
SLM : Optional_Code_Point;
STM : Optional_Code_Point);
-- Process data for one code point.
procedure Free is new Ada.Unchecked_Deallocation (String, String_Access);
-------------
-- Process --
-------------
procedure Process
(Code : Code_Point;
GC : General_Category;
CCC : Canonical_Combining_Class;
DT : Decomposition_Type;
DM : Code_Point_Sequence;
SUM : Optional_Code_Point;
SLM : Optional_Code_Point;
STM : Optional_Code_Point) is
begin
Core (Code).GC := GC;
Norms (Code).CCC := CCC;
Norms (Code).DT := DT;
-- Canonical and compatibility normalization.
if DT /= None then
Norms (Code).Values (Compatibility) :=
new Code_Point_Sequence'(DM);
if DT = Canonical then
Norms (Code).Values (Canonical_Mapping)
:= new Code_Point_Sequence'(DM);
Norms (Code).Values (Canonical) := new Code_Point_Sequence'(DM);
end if;
end if;
-- Simple uppercase mapping
if SUM.Present and then SUM.C /= Code then
Cases (Code).SUM := SUM;
else
Cases (Code).SUM := (Present => False);
end if;
-- Simple lowercase mapping
if SLM.Present and then SLM.C /= Code then
Cases (Code).SLM := SLM;
else
Cases (Code).SLM := (Present => False);
end if;
-- Simple titlecase mapping
if STM.Present and then STM.C /= Code then
Cases (Code).STM := STM;
else
Cases (Code).STM := (Present => False);
end if;
end Process;
File : Ucd_Input.File_Type;
Code : Code_Point;
First_Code : Code_Point;
Name : String_Access;
GC : General_Category;
CCC : Canonical_Combining_Class;
SUM : Optional_Code_Point;
SLM : Optional_Code_Point;
STM : Optional_Code_Point;
DT : Decomposition_Type;
DM : Code_Point_Sequence_Access;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & UnicodeData_Name);
Ucd_Input.Open (File, Unidata_Directory & '/' & UnicodeData_Name);
while not Ucd_Input.End_Of_Data (File) loop
-- Parse code point
Code := Ucd_Input.First_Code_Point (File);
-- UnicodeData.txt uses only one code point for each record.
-- Parse Name (1)
Name := new String'(Ucd_Input.Field (File));
Ucd_Input.Next_Field (File);
-- Parse General_Category (2)
GC := Value (Ucd_Input.Field (File));
Ucd_Input.Next_Field (File);
-- Parse Canonical_Combining_Class (3)
CCC := Canonical_Combining_Class'Value (Ucd_Input.Field (File));
Ucd_Input.Next_Field (File);
-- Parse Bidi_Class (4)
-- XXX Not implemented
Ucd_Input.Next_Field (File);
-- Parse Decomposition_Type and Decomposition_Mapping (5)
declare
Field : constant String := Ucd_Input.Field (File);
First : Positive := Field'First;
Last : Natural := 0;
begin
if Field'Length /= 0 then
if Field (First) = '<' then
Last := First + 1;
while Field (Last) /= '>' loop
Last := Last + 1;
end loop;
DT := Value (Field (First + 1 .. Last - 1));
First := Last + 2;
else
DT := Canonical;
end if;
DM :=
new Code_Point_Sequence'
(Parse_Code_Point_Sequence
(Field (First .. Field'Last)));
else
DT := None;
DM := new Code_Point_Sequence (1 .. 0);
end if;
end;
Ucd_Input.Next_Field (File);
-- Parse Numeric_Type and Numeric_Value (6), (7), (8)
-- XXX Not implemented
Ucd_Input.Next_Field (File);
Ucd_Input.Next_Field (File);
Ucd_Input.Next_Field (File);
-- Parse Bidi_Mirrored (9)
-- XXX Not implemented
Ucd_Input.Next_Field (File);
-- Parse Unicode_1_Name (10)
-- XXX Not implemented
Ucd_Input.Next_Field (File);
-- Parse ISO_Comment (11)
-- XXX Not implemented
Ucd_Input.Next_Field (File);
-- Parse Simple_Uppercase_Mapping (12)
declare
F : constant String := Ucd_Input.Field (File);
begin
if F'Length = 0 then
SUM := (Present => False);
else
SUM := (True, 0);
Parse_Code_Point (F, SUM.C);
end if;
end;
Ucd_Input.Next_Field (File);
-- Parse Simple_Lowercase_Mapping (13)
declare
F : constant String := Ucd_Input.Field (File);
begin
if F'Length = 0 then
SLM := (Present => False);
else
SLM := (True, 0);
Parse_Code_Point (F, SLM.C);
end if;
end;
Ucd_Input.Next_Field (File);
-- Parse Simple_Titlecase_Mapping (14)
declare
F : constant String := Ucd_Input.Field (File);
begin
if F'Length = 0 then
STM := (Present => False);
else
STM := (True, 0);
Parse_Code_Point (F, STM.C);
end if;
end;
-- Special exception: if Name end on ", First>" it means a start of
-- range. Next line end of ", Last>" and means end of range.
if Name'Length > 7
and then Name (Name'Last - 7 .. Name'Last) = ", First>"
then
First_Code := Code;
elsif Name'Length > 6
and then Name (Name'Last - 6 .. Name'Last) = ", Last>"
then
if Name.all = "<Hangul Syllable, Last>" then
-- Hangul Syllables are decomposed algorithmically and there
-- are no Decomposition Type is defined in UnicodeData.txt
-- for them. We set Decomposition_Type to Canonical by hand.
DT := Canonical;
end if;
for J in First_Code .. Code loop
Process (J, GC, CCC, DT, DM.all, SUM, SLM, STM);
end loop;
else
Process (Code, GC, CCC, DT, DM.all, SUM, SLM, STM);
end if;
-- Cleanup.
Free (Name);
Free (DM);
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_UnicodeData;
----------------------------
-- Load_WordBreakProperty --
----------------------------
procedure Load_WordBreakProperty (Unidata_Directory : String) is
File : Ucd_Input.File_Type;
First : Code_Point;
Last : Code_Point;
Prop : Word_Break;
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Standard_Error, " ... " & WordBreakProperty_Name);
Ucd_Input.Open (File, Unidata_Directory & '/' & WordBreakProperty_Name);
while not Ucd_Input.End_Of_Data (File) loop
First := Ucd_Input.First_Code_Point (File);
Last := Ucd_Input.Last_Code_Point (File);
Prop := Value (Ucd_Input.Field (File));
for J in First .. Last loop
Core (J).WB := Prop;
end loop;
Ucd_Input.Next_Record (File);
end loop;
Ucd_Input.Close (File);
end Load_WordBreakProperty;
----------------------
-- Parse_Code_Point --
----------------------
procedure Parse_Code_Point
(Text : String;
Code : out Code_Point)
is
First : Positive := Text'First;
Last : Natural;
begin
Last := First - 1;
while Last < Text'Last loop
Last := Last + 1;
if Text (Last) not in '0' .. '9'
and then Text (Last) not in 'A' .. 'F'
then
Last := Last - 1;
exit;
end if;
end loop;
Code := Code_Point'Value ("16#" & Text (First .. Last) & "#");
end Parse_Code_Point;
-----------
-- Value --
-----------
function Value (Item : String) return Decomposition_Type is
type Constant_String_Access is access constant String;
Compat_Image : aliased constant String := "compat";
Circle_Image : aliased constant String := "circle";
Final_Image : aliased constant String := "final";
Font_Image : aliased constant String := "font";
Fraction_Image : aliased constant String := "fraction";
Initial_Image : aliased constant String := "initial";
Isolated_Image : aliased constant String := "isolated";
Medial_Image : aliased constant String := "medial";
Narrow_Image : aliased constant String := "narrow";
Nobreak_Image : aliased constant String := "noBreak";
Small_Image : aliased constant String := "small";
Square_Image : aliased constant String := "square";
Sub_Image : aliased constant String := "sub";
Super_Image : aliased constant String := "super";
Vertical_Image : aliased constant String := "vertical";
Wide_Image : aliased constant String := "wide";
Mapping : constant
array (Decomposition_Type range Font .. Compat)
of Constant_String_Access
:= (Compat => Compat_Image'Access,
Circle => Circle_Image'Access,
Final => Final_Image'Access,
Font => font_Image'Access,
Fraction => Fraction_Image'Access,
Initial => Initial_Image'Access,
Isolated => Isolated_Image'Access,
Medial => Medial_Image'Access,
Narrow => Narrow_Image'Access,
No_Break => Nobreak_Image'Access,
Small => Small_Image'Access,
Square => Square_Image'Access,
Sub => sub_Image'Access,
Super => Super_Image'Access,
Vertical => Vertical_Image'Access,
Wide => wide_Image'Access);
begin
if Item'Length = 0 then
return Canonical;
end if;
for J in Mapping'Range loop
if Mapping (J).all = Item then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Decomposition_Type";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return East_Asian_Width is
type Constant_String_Access is access constant String;
A_Image : aliased constant String := "A";
F_Image : aliased constant String := "F";
H_Image : aliased constant String := "H";
N_Image : aliased constant String := "N";
Na_Image : aliased constant String := "Na";
W_Image : aliased constant String := "W";
Mapping : constant array (East_Asian_Width) of Constant_String_Access
:= (Ambiguous => A_Image'Access,
Fullwidth => F_Image'Access,
Halfwidth => H_Image'Access,
Neutral => N_Image'Access,
Narrow => Na_Image'Access,
Wide => W_Image'Access);
begin
for J in Mapping'Range loop
if Mapping (J).all = Item then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of General_Category";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return General_Category is
Mapping : constant array (General_Category) of String (1 .. 2)
:= (Control => "Cc",
Format => "Cf",
Unassigned => "Cn",
Private_Use => "Co",
Surrogate => "Cs",
Lowercase_Letter => "Ll",
Modifier_Letter => "Lm",
Other_Letter => "Lo",
Titlecase_Letter => "Lt",
Uppercase_Letter => "Lu",
Spacing_Mark => "Mc",
Enclosing_Mark => "Me",
Nonspacing_Mark => "Mn",
Decimal_Number => "Nd",
Letter_Number => "Nl",
Other_Number => "No",
Connector_Punctuation => "Pc",
Dash_Punctuation => "Pd",
Close_Punctuation => "Pe",
Final_Punctuation => "Pf",
Initial_Punctuation => "Pi",
Other_Punctuation => "Po",
Open_Punctuation => "Ps",
Currency_Symbol => "Sc",
Modifier_Symbol => "Sk",
Math_Symbol => "Sm",
Other_Symbol => "So",
Line_Separator => "Zl",
Paragraph_Separator => "Zp",
Space_Separator => "Zs");
begin
for J in Mapping'Range loop
if Mapping (J) = Item then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of General_Category";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return Grapheme_Cluster_Break is
type Constant_String_Access is access constant String;
GCB_Control_Image : aliased constant String := "Control";
GCB_CR_Image : aliased constant String := "CR";
GCB_Extend_Image : aliased constant String := "Extend";
GCB_L_Image : aliased constant String := "L";
GCB_LF_Image : aliased constant String := "LF";
GCB_LV_Image : aliased constant String := "LV";
GCB_LVT_Image : aliased constant String := "LVT";
GCB_Prepend_Image : aliased constant String := "Prepend";
GCB_SpacingMark_Image : aliased constant String := "SpacingMark";
GCB_T_Image : aliased constant String := "T";
GCB_V_Image : aliased constant String := "V";
GCB_Other_Image : aliased constant String := "Other";
GCB_Regional_Indicator_Image :
aliased constant String := "Regional_Indicator";
Mapping : constant
array (Grapheme_Cluster_Break) of Constant_String_Access
:= (Control => GCB_Control_Image'Access,
CR => GCB_CR_Image'Access,
Extend => GCB_Extend_Image'Access,
L => GCB_L_Image'Access,
LF => GCB_LF_Image'Access,
LV => GCB_LV_Image'Access,
LVT => GCB_LVT_Image'Access,
Prepend => GCB_Prepend_Image'Access,
Spacing_Mark => GCB_SpacingMark_Image'Access,
T => GCB_T_Image'Access,
V => GCB_V_Image'Access,
Other => GCB_Other_Image'Access,
Regional_Indicator => GCB_Regional_Indicator_Image'Access);
begin
for J in Mapping'Range loop
if Item = Mapping (J).all then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Grapheme_Cluster_Break";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return Line_Break is
Mapping : constant array (Line_Break) of String (1 .. 2)
:= (Ambiguous => "AI",
Alphabetic => "AL",
Break_Both => "B2",
Break_After => "BA",
Break_Before => "BB",
Mandatory_Break => "BK",
Contingent_Break => "CB",
Conditional_Japanese_Starter => "CJ",
Close_Punctuation => "CL",
Combining_Mark => "CM",
Close_Parenthesis => "CP",
Carriage_Return => "CR",
Exclamation => "EX",
Glue => "GL",
H2 => "H2",
H3 => "H3",
Hebrew_Letter => "HL",
Hyphen => "HY",
Ideographic => "ID",
Inseparable => "IN",
Infix_Numeric => "IS",
JL => "JL",
JT => "JT",
JV => "JV",
Line_Feed => "LF",
Next_Line => "NL",
Nonstarter => "NS",
Numeric => "NU",
Open_Punctuation => "OP",
Postfix_Numeric => "PO",
Prefix_Numeric => "PR",
Quotation => "QU",
Complex_Context => "SA",
Surrogate => "SG",
Space => "SP",
Break_Symbols => "SY",
Word_Joiner => "WJ",
Unknown => "XX",
ZW_Space => "ZW",
Regional_Indicator => "RI");
begin
for J in Mapping'Range loop
if Mapping (J) = Item then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Line_Break";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return Normalization_Quick_Check is
Mapping : constant array (Normalization_Quick_Check) of String (1 .. 1)
:= (No => "N",
Maybe => "M",
Yes => "Y");
begin
for J in Mapping'Range loop
if Mapping (J) = Item then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Normalization_Quick_Check";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return Sentence_Break is
type Constant_String_Access is access constant String;
SB_ATerm_Image : aliased constant String := "ATerm";
SB_Close_Image : aliased constant String := "Close";
SB_CR_Image : aliased constant String := "CR";
SB_Extend_Image : aliased constant String := "Extend";
SB_Format_Image : aliased constant String := "Format";
SB_OLetter_Image : aliased constant String := "OLetter";
SB_LF_Image : aliased constant String := "LF";
SB_Lower_Image : aliased constant String := "Lower";
SB_Numeric_Image : aliased constant String := "Numeric";
SB_SContinue_Image : aliased constant String := "SContinue";
SB_Sep_Image : aliased constant String := "Sep";
SB_Sp_Image : aliased constant String := "Sp";
SB_STerm_Image : aliased constant String := "STerm";
SB_Upper_Image : aliased constant String := "Upper";
SB_Other_Image : aliased constant String := "Other";
Mapping : constant array (Sentence_Break) of Constant_String_Access :=
(A_Term => SB_ATerm_Image'Access,
Close => SB_Close_Image'Access,
CR => SB_CR_Image'Access,
Extend => SB_Extend_Image'Access,
Format => SB_Format_Image'Access,
O_Letter => SB_OLetter_Image'Access,
LF => SB_LF_Image'Access,
Lower => SB_Lower_Image'Access,
Numeric => SB_Numeric_Image'Access,
S_Continue => SB_SContinue_Image'Access,
Sep => SB_Sep_Image'Access,
Sp => SB_Sp_Image'Access,
S_Term => SB_STerm_Image'Access,
Upper => SB_Upper_Image'Access,
Other => SB_Other_Image'Access);
begin
for J in Mapping'Range loop
if Item = Mapping (J).all then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Sentence_Break";
end Value;
-----------
-- Value --
-----------
function Value (Item : String) return Word_Break is
type Constant_String_Access is access constant String;
WB_CR_Image : aliased constant String := "CR";
WB_ExtendNumLet_Image : aliased constant String := "ExtendNumLet";
WB_Extend_Image : aliased constant String := "Extend";
WB_Format_Image : aliased constant String := "Format";
WB_Katakana_Image : aliased constant String := "Katakana";
WB_ALetter_Image : aliased constant String := "ALetter";
WB_LF_Image : aliased constant String := "LF";
WB_MidNumLet_Image : aliased constant String := "MidNumLet";
WB_MidLetter_Image : aliased constant String := "MidLetter";
WB_MidNum_Image : aliased constant String := "MidNum";
WB_Newline_Image : aliased constant String := "Newline";
WB_Numeric_Image : aliased constant String := "Numeric";
WB_Other_Image : aliased constant String := "Other";
WB_Regional_Indicator_Image :
aliased constant String := "Regional_Indicator";
WB_Hebrew_Letter_Image : aliased constant String := "Hebrew_Letter";
WB_Single_Quote_Image : aliased constant String := "Single_Quote";
WB_Double_Quote_Image : aliased constant String := "Double_Quote";
Mapping : constant array (Word_Break) of Constant_String_Access :=
(CR => WB_CR_Image'Access,
Extend_Num_Let => WB_ExtendNumLet_Image'Access,
Extend => WB_Extend_Image'Access,
Format => WB_Format_Image'Access,
Katakana => WB_Katakana_Image'Access,
A_Letter => WB_ALetter_Image'Access,
LF => WB_LF_Image'Access,
Mid_Num_Let => WB_MidNumLet_Image'Access,
Mid_Letter => WB_MidLetter_Image'Access,
Mid_Num => WB_MidNum_Image'Access,
Newline => WB_Newline_Image'Access,
Numeric => WB_Numeric_Image'Access,
Other => WB_Other_Image'Access,
Regional_Indicator => WB_Regional_Indicator_Image'Access,
Hebrew_Letter => WB_Hebrew_Letter_Image'Access,
Single_Quote => WB_Single_Quote_Image'Access,
Double_Quote => WB_Double_Quote_Image'Access);
begin
for J in Mapping'Range loop
if Item = Mapping (J).all then
return J;
end if;
end loop;
raise Constraint_Error with "Invalid image of Word_Break";
end Value;
end Ucd_Data;
|
30,758
|
ada
| 1
|
ekoeppen/STM32_Generic_Ada_Drivers
|
boards/host/stm32gd-usart-peripheral.adb
|
package body Console is
procedure Transmit (Data : in Byte) is
begin
null;
end Transmit;
end Console;
|
30,759
|
ada
| 20
|
charlie5/lace
|
3-mid/impact/source/3d/dynamics/impact-d3-object-rigid.adb
|
with impact.d3.Vector; use impact.d3.Vector;
with impact.d3.Transform;
with impact.d3.Matrix,
impact.d3.min_max;
with impact.d3.Transform_Util;
package body impact.d3.Object.rigid
is
use math.Algebra.linear.d3;
function to_ConstructionInfo (mass : in Real;
motionState : access impact.d3.motion_State.Item'Class;
collisionShape : access impact.d3.Shape.Item'Class;
localInertia : in Vector_3)
return ConstructionInfo is
Self : ConstructionInfo;
begin
Self.m_mass := mass;
Self.m_motionState := motionState;
Self.m_collisionShape := collisionShape;
Self.m_localInertia := localInertia;
Self.m_linearDamping := Real (0.0);
Self.m_angularDamping := Real (0.0);
Self.m_friction := Real (0.5);
Self.m_restitution := Real (0.0);
Self.m_linearSleepingThreshold := Real (0.8);
Self.m_angularSleepingThreshold := Real (1.0);
Self.m_additionalDamping := False;
Self.m_additionalDampingFactor := Real (0.005);
Self.m_additionalLinearDampingThresholdSqr := Real (0.01);
Self.m_additionalAngularDampingThresholdSqr := Real (0.01);
Self.m_additionalDampingFactor := Real (0.01);
Self.m_startWorldTransform := impact.d3.Transform.getIdentity;
return Self;
end to_ConstructionInfo;
-- impact.d3.Object.rigidConstructionInfo( impact.d3.Scalar mass, impact.d3.motion_State* motionState, impact.d3.Shape* collisionShape, const impact.d3.Vector& localInertia=impact.d3.Vector(0,0,0)):
-- m_mass(mass),
-- m_motionState(motionState),
-- m_collisionShape(collisionShape),
-- m_localInertia(localInertia),
-- m_linearDamping(impact.d3.Scalar(0.)),
-- m_angularDamping(impact.d3.Scalar(0.)),
-- m_friction(impact.d3.Scalar(0.5)),
-- m_restitution(impact.d3.Scalar(0.)),
-- m_linearSleepingThreshold(impact.d3.Scalar(0.8)),
-- m_angularSleepingThreshold(impact.d3.Scalar(1.f)),
-- m_additionalDamping(false),
-- m_additionalDampingFactor(impact.d3.Scalar(0.005)),
-- m_additionalLinearDampingThresholdSqr(impact.d3.Scalar(0.01)),
-- m_additionalAngularDampingThresholdSqr(impact.d3.Scalar(0.01)),
-- m_additionalAngularDampingFactor(impact.d3.Scalar(0.01))
-- {
-- m_startWorldTransform.setIdentity();
-- }
package body Forge
is
function to_rigid_Object (mass : in math.Real;
motionState : access impact.d3.motion_State.Item'Class;
collisionShape : access impact.d3.Shape.Item'Class;
localInertia : in math.Vector_3 := (0.0, 0.0, 0.0)) return Item
is
Self : Item;
cinfo : constant ConstructionInfo := to_ConstructionInfo (mass, motionState, collisionShape, localInertia);
begin
Self.setupRigidBody (cinfo);
return Self;
end to_rigid_Object;
-- impact.d3.Object.rigidConstructionInfo cinfo(mass,motionState,collisionShape,localInertia);
-- setupRigidBody(cinfo);
end Forge;
----------------
--- Atttributes
--
--- Dynamics
--
function Site (Self : in Item) return Vector_3
is
the_Transform : Transform_3d;
begin
Self.getMotionState.getWorldTransform (the_Transform);
return the_Transform.Translation;
end Site;
procedure Site_is (Self : in out Item; Now : in Vector_3)
is
the_Transform : Transform_3d;
begin
Self.getMotionState.getWorldTransform (the_Transform);
the_Transform.Translation := Now;
Self.getMotionState.setWorldTransform (the_Transform);
Self.getWorldTransform.Translation := Now;
Self.activate (True);
end Site_is;
-- btTransform& trans = getWorldTransform ();
-- btTransform trans2; // = getWorldTransform ();
--
-- getMotionState()->getWorldTransform (trans2);
--
-- trans.setOrigin (btVector3 (Now.x, Now.y, Now.z));
-- trans2.setOrigin (btVector3 (Now.x, Now.y, Now.z));
--
-- // setActivationState (1);
-- activate();
-- getMotionState()->setWorldTransform (trans2);
function Spin (Self : in Item) return math.Matrix_3x3
is
trans : constant Transform_3d := Self.WorldTransform;
begin
return trans.Rotation; -- tbd: check that no transpose is required (check others below also)
end Spin;
-- btTransform& trans = as_btCollisionObject().getWorldTransform ();
-- btMatrix3x3 the_Spin = trans.getBasis();
--
-- btVector3& R1 = the_Spin [0];
-- btVector3& R2 = the_Spin [1];
-- btVector3& R3 = the_Spin [2];
--
-- return c_physics::Matrix_3x3 (R1 [0], R1 [1], R1 [2],
-- R2 [0], R2 [1], R2 [2],
-- R3 [0], R3 [1], R3 [2]);
--
procedure Spin_is (Self : in out Item; Now : in math.Matrix_3x3)
is
trans : Transform_3d := Self.WorldTransform;
begin
trans.Rotation := Now;
Self.setWorldTransform (trans);
-- declare
-- trans2 : Transform_3d := Self.WorldTransform;
-- begin
-- Self.getMotionState.getWorldTransform (trans2);
-- trans2.Rotation := Now;
-- Self.activate;
-- Self.getMotionState.setWorldTransform (trans2);
-- end;
end Spin_is;
function xy_Spin (Self : in Item) return math.Radians
is
begin
raise Program_Error with "TBD";
return 0.0;
end xy_Spin;
procedure xy_Spin_is (Self : in out Item; Now : in math.Radians)
is
begin
raise Program_Error with "TBD";
end xy_Spin_is;
-- for object ...
-- btTransform& trans = as_btCollisionObject().getWorldTransform ();
--
-- trans.setBasis (btMatrix3x3 (Now.m00, Now.m01, Now.m02,
-- Now.m10, Now.m11, Now.m12,
-- Now.m20, Now.m21, Now.m22));
-- for rigid ...
-- btTransform& trans = as_btCollisionObject().getWorldTransform ();
--
-- trans.setBasis (btMatrix3x3 (Now.m00, Now.m01, Now.m02,
-- Now.m10, Now.m11, Now.m12,
-- Now.m20, Now.m21, Now.m22));
--
--
-- btTransform trans2; // = getWorldTransform ();
--
-- getMotionState()->getWorldTransform (trans2);
--
-- trans2.setBasis (btMatrix3x3 (Now.m00, Now.m01, Now.m02,
-- Now.m10, Now.m11, Now.m12,
-- Now.m20, Now.m21, Now.m22));
-- // setActivationState (1);
-- activate();
-- getMotionState()->setWorldTransform (trans2);
function Transform (Self : in Item) return math.Matrix_4x4
is
begin
return to_transform_Matrix (Self.WorldTransform);
end Transform;
-- btTransform& trans = as_btCollisionObject().getWorldTransform ();
-- btScalar gl_Matrix [16];
--
-- trans.getOpenGLMatrix (gl_Matrix);
--
-- return c_physics::Matrix_4x4 (gl_Matrix);
procedure Transform_is (Self : in out Item; Now : in math.Matrix_4x4)
is
the_Transform : constant Transform_3d := to_Transform (Now);
begin
Self.getWorldTransform.all := the_Transform;
Self.getMotionState.setWorldTransform (the_Transform);
end Transform_is;
-- void
-- Rigid::
-- Transform_is (c_physics::Matrix_4x4& Now)
-- {
-- btTransform& trans = getWorldTransform ();
--
-- trans.setFromOpenGLMatrix (&Now.m00);
-- activate();
--
-- getMotionState()->setWorldTransform (trans);
-- }
function Speed (Self : in Item) return math.Vector_3
is
begin
return Self.getLinearVelocity;
end Speed;
-- c_physics::Vector_3
-- Rigid::
-- Speed ()
-- {
-- btVector3 the_Speed = getLinearVelocity ();
--
-- return c_physics::Vector_3 (the_Speed [0], the_Speed [1], the_Speed [2]);
-- }
procedure Speed_is (Self : in out Item; Now : in math.Vector_3)
is
begin
Self.setLinearVelocity (Now);
if Now (1) = 0.0
and then Now (2) = 0.0
and then Now (3) = 0.0
then
Self.setActivationState (0);
else
Self.activate;
end if;
end Speed_is;
function Gyre (Self : in Item) return math.Vector_3
is
begin
return Self.getAngularVelocity;
end Gyre;
procedure Gyre_is (Self : in out Item; Now : in math.Vector_3)
is
begin
Self.setAngularVelocity (Now);
Self.activate;
end Gyre_is;
--- Forces
--
procedure apply_Torque (Self : in out Item; Torque : in math.Vector_3)
is
begin
Self.applyTorque (Torque);
Self.activate;
end apply_Torque;
procedure apply_Torque_impulse (Self : in out Item; Torque : in math.Vector_3)
is
begin
Self.applyTorqueImpulse (Torque);
Self.activate;
end apply_Torque_impulse;
procedure apply_Force (Self : in out Item; Force : in math.Vector_3)
is
begin
Self.applyCentralImpulse (Force);
Self.activate;
end apply_Force;
--- old ...
procedure RigidBody_Assert (Self : in Item) is
use ada.containers;
pragma Assert (Self.m_constraintRefs.Length = 0);
begin
null;
end RigidBody_Assert;
-- virtual ~impact.d3.Object.rigid()
-- {
-- //No constraints should point to this rigidbody
-- //Remove constraints from the dynamics world before you delete the related rigidbodies.
-- btAssert(m_constraintRefs.size()==0);
-- }
function new_rigid_Object (constructionInfo : in rigid.ConstructionInfo) return View
is
Self : constant View := new Item;
begin
setupRigidBody (Self.all, constructionInfo);
return Self;
-- return Self : Item
-- do
-- setupRigidBody (Self, constructionInfo);
--
-- end return;
end new_rigid_Object;
procedure delete (Self : in Item)
is
begin
null;
end delete;
procedure setupRigidBody (Self : in out Item;
constructionInfo : in rigid.ConstructionInfo)
is
begin
impact.d3.Object.define (impact.d3.Object.item (Self));
Self.setInternalType (impact.d3.Object.CO_RIGID_BODY);
Self.m_linearVelocity := (0.0, 0.0, 0.0);
Self.m_angularVelocity := (0.0, 0.0, 0.0);
Self.m_angularFactor := (1.0, 1.0, 1.0);
Self.m_linearFactor := (1.0, 1.0, 1.0);
Self.m_gravity := (0.0, 0.0, 0.0);
Self.m_gravity_acceleration := (0.0, 0.0, 0.0);
Self.m_totalForce := (0.0, 0.0, 0.0);
Self.m_totalTorque := (0.0, 0.0, 0.0);
setDamping (Self, constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);
Self.m_linearSleepingThreshold := constructionInfo.m_linearSleepingThreshold;
Self.m_angularSleepingThreshold := constructionInfo.m_angularSleepingThreshold;
Self.m_optionalMotionState := constructionInfo.m_motionState;
Self.m_contactSolverType := 0;
Self.m_frictionSolverType := 0;
Self.m_additionalDamping := constructionInfo.m_additionalDamping;
Self.m_additionalDampingFactor := constructionInfo.m_additionalDampingFactor;
Self.m_additionalLinearDampingThresholdSqr := constructionInfo.m_additionalLinearDampingThresholdSqr;
Self.m_additionalAngularDampingThresholdSqr := constructionInfo.m_additionalAngularDampingThresholdSqr;
Self.m_additionalAngularDampingFactor := constructionInfo.m_additionalAngularDampingFactor;
if Self.m_optionalMotionState /= null then
Self.m_optionalMotionState.getWorldTransform (Self.getWorldTransform.all);
else
Self.getWorldTransform.all := constructionInfo.m_startWorldTransform;
end if;
Self.setInterpolationWorldTransform (Self.getworldTransform.all);
Self.setInterpolationLinearVelocity ((0.0, 0.0, 0.0));
Self.setInterpolationAngularVelocity ((0.0, 0.0, 0.0));
-- moved to impact.d3.Object
Self.setFriction (constructionInfo.m_friction);
Self.setRestitution (constructionInfo.m_restitution);
Self.setCollisionShape (constructionInfo.m_collisionShape);
Self.setMassProps (constructionInfo.m_mass, constructionInfo.m_localInertia);
updateInertiaTensor (Self);
Self.m_rigidbodyFlags := 0;
setZero (Self.m_deltaLinearVelocity);
setZero (Self.m_deltaAngularVelocity);
Self.m_invMass := Self.m_inverseMass * Self.m_linearFactor;
setZero (Self.m_pushVelocity);
setZero (Self.m_turnVelocity);
end setupRigidBody;
-- void impact.d3.Object.rigid::setupRigidBody(const impact.d3.Object.rigid::impact.d3.Object.rigidConstructionInfo& constructionInfo)
-- {
-- m_internalType=CO_RIGID_BODY;
-- m_linearVelocity.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- m_angularVelocity.setValue(impact.d3.Scalar(0.),impact.d3.Scalar(0.),impact.d3.Scalar(0.));
-- m_angularFactor.setValue(1,1,1);
-- m_linearFactor.setValue(1,1,1);
-- m_gravity.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- m_gravity_acceleration.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- m_totalForce.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- m_totalTorque.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0)),
-- setDamping(constructionInfo.m_linearDamping, constructionInfo.m_angularDamping);
-- m_linearSleepingThreshold = constructionInfo.m_linearSleepingThreshold;
-- m_angularSleepingThreshold = constructionInfo.m_angularSleepingThreshold;
-- m_optionalMotionState = constructionInfo.m_motionState;
-- m_contactSolverType = 0;
-- m_frictionSolverType = 0;
-- m_additionalDamping = constructionInfo.m_additionalDamping;
-- m_additionalDampingFactor = constructionInfo.m_additionalDampingFactor;
-- m_additionalLinearDampingThresholdSqr = constructionInfo.m_additionalLinearDampingThresholdSqr;
-- m_additionalAngularDampingThresholdSqr = constructionInfo.m_additionalAngularDampingThresholdSqr;
-- m_additionalAngularDampingFactor = constructionInfo.m_additionalAngularDampingFactor;
-- if (m_optionalMotionState)
-- {
-- m_optionalMotionState->getWorldTransform(m_worldTransform);
-- } else
-- {
-- m_worldTransform = constructionInfo.m_startWorldTransform;
-- }
-- m_interpolationWorldTransform = m_worldTransform;
-- m_interpolationLinearVelocity.setValue(0,0,0);
-- m_interpolationAngularVelocity.setValue(0,0,0);
-- //moved to impact.d3.Object
-- m_friction = constructionInfo.m_friction;
-- m_restitution = constructionInfo.m_restitution;
-- setCollisionShape( constructionInfo.m_collisionShape );
-- m_debugBodyId = uniqueId++;
-- setMassProps(constructionInfo.m_mass, constructionInfo.m_localInertia);
-- updateInertiaTensor();
-- m_rigidbodyFlags = 0;
-- m_deltaLinearVelocity.setZero();
-- m_deltaAngularVelocity.setZero();
-- m_invMass = m_inverseMass*m_linearFactor;
-- m_pushVelocity.setZero();
-- m_turnVelocity.setZero();
-- }
procedure proceedToTransform (Self : in out Item;
newTrans : in Transform_3d)
is
begin
setCenterOfMassTransform (Self, newTrans);
end proceedToTransform;
-- void impact.d3.Object.rigid::proceedToTransform(const impact.d3.Transform& newTrans)
-- {
-- setCenterOfMassTransform( newTrans );
-- }
procedure predictIntegratedTransform (Self : in out Item;
timeStep : in Real;
predictedTransform : out Transform_3d)
is
begin
impact.d3.transform_Util.integrateTransform (Self.getWorldTransform.all,
Self.m_linearVelocity,
Self.m_angularVelocity,
timeStep,
predictedTransform);
end predictIntegratedTransform;
-- void impact.d3.Object.rigid::predictIntegratedTransform(impact.d3.Scalar timeStep,impact.d3.Transform& predictedTransform)
-- {
-- impact.d3.TransformUtil::integrateTransform(m_worldTransform,m_linearVelocity,m_angularVelocity,timeStep,predictedTransform);
-- }
procedure saveKinematicState (Self : in out Item;
timeStep : in Real)
is
use impact.d3.motion_State;
begin
if timeStep /= 0.0 then
if Self.getMotionState /= null then
Self.getMotionState.getWorldTransform (Self.getWorldTransform.all);
end if;
impact.d3.transform_Util.calculateVelocity (Self.getInterpolationWorldTransform,
Self.getWorldTransform.all,
timeStep,
Self.m_linearVelocity,
Self.m_angularVelocity);
Self.SetInterpolationLinearVelocity (Self.m_linearVelocity);
Self.SetInterpolationAngularVelocity (Self.m_angularVelocity);
Self.SetInterpolationWorldTransform (Self.getWorldTransform.all);
end if;
end saveKinematicState;
-- void impact.d3.Object.rigid::saveKinematicState(impact.d3.Scalar timeStep)
-- {
-- //todo: clamp to some (user definable) safe minimum timestep, to limit maximum angular/linear velocities
-- if (timeStep != impact.d3.Scalar(0.))
-- {
-- //if we use motionstate to synchronize world transforms, get the new kinematic/animated world transform
-- if (getMotionState())
-- getMotionState()->getWorldTransform(m_worldTransform);
-- impact.d3.Vector linVel,angVel;
-- impact.d3.TransformUtil::calculateVelocity(m_interpolationWorldTransform,m_worldTransform,timeStep,m_linearVelocity,m_angularVelocity);
-- m_interpolationLinearVelocity = m_linearVelocity;
-- m_interpolationAngularVelocity = m_angularVelocity;
-- m_interpolationWorldTransform = m_worldTransform;
-- //printf("angular = %f %f %f\n",m_angularVelocity.getX(),m_angularVelocity.getY(),m_angularVelocity.getZ());
-- }
-- }
procedure applyGravity (Self : in out Item)
is
begin
if isStaticOrKinematicObject (Self) then
null;
else
applyCentralForce (Self, Self.m_gravity);
end if;
end applyGravity;
-- void impact.d3.Object.rigid::applyGravity()
-- {
-- if (isStaticOrKinematicObject())
-- return;
-- applyCentralForce(m_gravity);
-- }
procedure setGravity (Self : in out Item;
acceleration : in Vector_3)
is
begin
if Self.m_inverseMass /= 0.0 then
Self.m_gravity := acceleration * (1.0 / Self.m_inverseMass);
end if;
Self.m_gravity_acceleration := acceleration;
end setGravity;
-- void impact.d3.Object.rigid::setGravity(const impact.d3.Vector& acceleration)
-- {
-- if (m_inverseMass != impact.d3.Scalar(0.0))
-- {
-- m_gravity = acceleration * (impact.d3.Scalar(1.0) / m_inverseMass);
-- }
-- m_gravity_acceleration = acceleration;
-- }
function getGravity (Self : in Item) return Vector_3
is
begin
return Self.m_gravity_acceleration;
end getGravity;
-- const impact.d3.Vector& getGravity() const
-- {
-- return m_gravity_acceleration;
-- }
procedure setDamping (Self : in out Item;
lin_damping : in Real;
ang_damping : in Real)
is
use impact.d3.min_max;
begin
Self.m_linearDamping := btClamped (lin_damping, 0.0, 1.0);
Self.m_angularDamping := btClamped (ang_damping, 0.0, 1.0);
end setDamping;
-- void impact.d3.Object.rigid::setDamping(impact.d3.Scalar lin_damping, impact.d3.Scalar ang_damping)
-- {
-- m_linearDamping = btClamped(lin_damping, (impact.d3.Scalar)impact.d3.Scalar(0.0), (impact.d3.Scalar)impact.d3.Scalar(1.0));
-- m_angularDamping = btClamped(ang_damping, (impact.d3.Scalar)impact.d3.Scalar(0.0), (impact.d3.Scalar)impact.d3.Scalar(1.0));
-- }
function getLinearDamping (Self : in Item) return Real
is
begin
return Self.m_linearDamping;
end getLinearDamping;
-- impact.d3.Scalar getLinearDamping() const
-- {
-- return m_linearDamping;
-- }
function getAngularDamping (Self : in Item) return Real
is
begin
return Self.m_angularDamping;
end getAngularDamping;
-- impact.d3.Scalar getAngularDamping() const
-- {
-- return m_angularDamping;
-- }
function getLinearSleepingThreshold (Self : in Item) return Real
is
begin
return Self.m_linearSleepingThreshold;
end getLinearSleepingThreshold;
-- impact.d3.Scalar getLinearSleepingThreshold() const
-- {
-- return m_linearSleepingThreshold;
-- }
function getAngularSleepingThreshold (Self : in Item) return Real
is
begin
return Self.m_angularSleepingThreshold;
end getAngularSleepingThreshold;
-- impact.d3.Scalar getAngularSleepingThreshold() const
-- {
-- return m_angularSleepingThreshold;
-- }
procedure applyDamping (Self : in out Item;
timeStep : in Real)
is
use math.Functions;
begin
Self.m_linearVelocity := Self.m_linearVelocity * (1.0 - Self.m_linearDamping)**timeStep;
Self.m_angularVelocity := Self.m_angularVelocity * (1.0 - Self.m_angularDamping)**timeStep;
if Self.m_additionalDamping then
if length2 (Self.m_angularVelocity) < Self.m_additionalAngularDampingThresholdSqr
and then length2 (Self.m_linearVelocity) < Self.m_additionalLinearDampingThresholdSqr
then
Self.m_angularVelocity := Self.m_angularVelocity * Self.m_additionalDampingFactor;
Self.m_linearVelocity := Self.m_linearVelocity * Self.m_additionalDampingFactor;
end if;
declare
speed : constant Real := length (Self.m_linearVelocity);
dampVel : constant Real := 0.005;
dir : constant Vector_3 := normalized (Self.m_linearVelocity);
begin
if speed < Self.m_linearDamping then
if speed > dampVel then
Self.m_linearVelocity := Self.m_linearVelocity - dir * dampVel;
else
Self.m_linearVelocity := (0.0, 0.0, 0.0);
end if;
end if;
end;
declare
angSpeed : constant Real := length (Self.m_angularVelocity);
angDampVel : constant Real := 0.005;
dir : constant Vector_3 := normalized (Self.m_angularVelocity);
begin
if angSpeed < Self.m_angularDamping then
if angSpeed > angDampVel then
Self.m_angularVelocity := Self.m_angularVelocity - dir * angDampVel;
else
Self.m_angularVelocity := (0.0, 0.0, 0.0);
end if;
end if;
end;
end if;
end applyDamping;
-- ///applyDamping damps the velocity, using the given m_linearDamping and m_angularDamping
-- void impact.d3.Object.rigid::applyDamping(impact.d3.Scalar timeStep)
-- {
-- //On new damping: see discussion/issue report here: http://code.google.com/p/bullet/issues/detail?id=74
-- //todo: do some performance comparisons (but other parts of the engine are probably bottleneck anyway
-- //#define USE_OLD_DAMPING_METHOD 1
-- #ifdef USE_OLD_DAMPING_METHOD
-- m_linearVelocity *= GEN_clamped((impact.d3.Scalar(1.) - timeStep * m_linearDamping), (impact.d3.Scalar)impact.d3.Scalar(0.0), (impact.d3.Scalar)impact.d3.Scalar(1.0));
-- m_angularVelocity *= GEN_clamped((impact.d3.Scalar(1.) - timeStep * m_angularDamping), (impact.d3.Scalar)impact.d3.Scalar(0.0), (impact.d3.Scalar)impact.d3.Scalar(1.0));
-- #else
-- m_linearVelocity *= btPow(impact.d3.Scalar(1)-m_linearDamping, timeStep);
-- m_angularVelocity *= btPow(impact.d3.Scalar(1)-m_angularDamping, timeStep);
-- #endif
-- if (m_additionalDamping)
-- {
-- //Additional damping can help avoiding lowpass jitter motion, help stability for ragdolls etc.
-- //Such damping is undesirable, so once the overall simulation quality of the rigid body dynamics system has improved, this should become obsolete
-- if ((m_angularVelocity.length2() < m_additionalAngularDampingThresholdSqr) &&
-- (m_linearVelocity.length2() < m_additionalLinearDampingThresholdSqr))
-- {
-- m_angularVelocity *= m_additionalDampingFactor;
-- m_linearVelocity *= m_additionalDampingFactor;
-- }
-- impact.d3.Scalar speed = m_linearVelocity.length();
-- if (speed < m_linearDamping)
-- {
-- impact.d3.Scalar dampVel = impact.d3.Scalar(0.005);
-- if (speed > dampVel)
-- {
-- impact.d3.Vector dir = m_linearVelocity.normalized();
-- m_linearVelocity -= dir * dampVel;
-- } else
-- {
-- m_linearVelocity.setValue(impact.d3.Scalar(0.),impact.d3.Scalar(0.),impact.d3.Scalar(0.));
-- }
-- }
-- impact.d3.Scalar angSpeed = m_angularVelocity.length();
-- if (angSpeed < m_angularDamping)
-- {
-- impact.d3.Scalar angDampVel = impact.d3.Scalar(0.005);
-- if (angSpeed > angDampVel)
-- {
-- impact.d3.Vector dir = m_angularVelocity.normalized();
-- m_angularVelocity -= dir * angDampVel;
-- } else
-- {
-- m_angularVelocity.setValue(impact.d3.Scalar(0.),impact.d3.Scalar(0.),impact.d3.Scalar(0.));
-- }
-- }
-- }
-- }
-- function getCollisionShape (Self : in Item) return access impact.d3.Shape.item'Class
-- is
-- begin
-- return Self.m_collisionShape;
-- end getCollisionShape;
-- SIMD_FORCE_INLINE const impact.d3.Shape* getCollisionShape() const {
-- return m_collisionShape;
-- }
--
-- SIMD_FORCE_INLINE impact.d3.Shape* getCollisionShape() {
-- return m_collisionShape;
-- }
procedure setMassProps (Self : in out Item;
mass : in Real;
inertia : in Vector_3)
is
begin
if mass = 0.0 then
Self.setCollisionFlags (Self.getCollisionFlags or impact.d3.Object.CF_STATIC_OBJECT);
Self.m_inverseMass := 0.0;
else
Self.setCollisionFlags (Self.getCollisionFlags and (not impact.d3.Object.CF_STATIC_OBJECT));
Self.m_inverseMass := 1.0 / mass;
end if;
Self.m_gravity := mass * Self.m_gravity_acceleration;
declare
A, B, C : Real;
begin
if inertia (1) /= 0.0 then
A := 1.0 / inertia (1);
else
A := 0.0;
end if;
if inertia (2) /= 0.0 then
B := 1.0 / inertia (2);
else
B := 0.0;
end if;
if inertia (3) /= 0.0 then
C := 1.0 / inertia (3);
else
C := 0.0;
end if;
Self.m_invInertiaLocal := (A, B, C);
Self.m_invMass := Self.m_linearFactor * Self.m_inverseMass;
end;
Self.m_invMass := Self.m_linearFactor * Self.m_inverseMass;
end setMassProps;
-- void impact.d3.Object.rigid::setMassProps(impact.d3.Scalar mass, const impact.d3.Vector& inertia)
-- {
-- if (mass == impact.d3.Scalar(0.))
-- {
-- m_collisionFlags |= impact.d3.Object::CF_STATIC_OBJECT;
-- m_inverseMass = impact.d3.Scalar(0.);
-- } else
-- {
-- m_collisionFlags &= (~impact.d3.Object::CF_STATIC_OBJECT);
-- m_inverseMass = impact.d3.Scalar(1.0) / mass;
-- }
-- //Fg = m * a
-- m_gravity = mass * m_gravity_acceleration;
-- m_invInertiaLocal.setValue(inertia.x() != impact.d3.Scalar(0.0) ? impact.d3.Scalar(1.0) / inertia.x(): impact.d3.Scalar(0.0),
-- inertia.y() != impact.d3.Scalar(0.0) ? impact.d3.Scalar(1.0) / inertia.y(): impact.d3.Scalar(0.0),
-- inertia.z() != impact.d3.Scalar(0.0) ? impact.d3.Scalar(1.0) / inertia.z(): impact.d3.Scalar(0.0));
-- m_invMass = m_linearFactor*m_inverseMass;
-- }
function getLinearFactor (Self : in Item) return Vector_3
is
begin
return Self.m_linearFactor;
end getLinearFactor;
-- const impact.d3.Vector& getLinearFactor() const
-- {
-- return m_linearFactor;
-- }
procedure setLinearFactor (Self : in out Item;
linearFactor : in Vector_3)
is
begin
Self.m_linearFactor := linearFactor;
Self.m_invMass := Self.m_linearFactor * Self.m_inverseMass;
end setLinearFactor;
-- void setLinearFactor(const impact.d3.Vector& linearFactor)
-- {
-- m_linearFactor = linearFactor;
-- m_invMass = m_linearFactor*m_inverseMass;
-- }
function getInvMass (Self : in Item) return Real
is
begin
return Self.m_inverseMass;
end getInvMass;
-- impact.d3.Scalar getInvMass() const { return m_inverseMass; }
function getInvInertiaTensorWorld (Self : in Item) return Matrix_3x3
is
begin
return Self.m_invInertiaTensorWorld;
end getInvInertiaTensorWorld;
-- const impact.d3.Matrix& getInvInertiaTensorWorld() const {
-- return m_invInertiaTensorWorld;
-- }
procedure integrateVelocities (Self : in out Item;
step : in Real)
is
MAX_ANGVEL : constant math.Real := math.Pi / 2.0;
angvel : math.Real;
begin
if isStaticOrKinematicObject (Self) then
return;
end if;
Self.m_linearVelocity := Self.m_linearVelocity + Self.m_totalForce * (Self.m_inverseMass * step);
Self.m_angularVelocity := Self.m_angularVelocity + Self.m_invInertiaTensorWorld * (Self.m_totalTorque * step);
-- Clamp angular velocity. collision calculations will fail on higher angular velocities.
--
angvel := Length (Self.m_angularVelocity);
if angvel * step > MAX_ANGVEL then
Self.m_angularVelocity := Self.m_angularVelocity * (MAX_ANGVEL / step) / angvel;
end if;
end integrateVelocities;
procedure setCenterOfMassTransform (Self : in out Item;
xform : Transform_3d)
is
begin
if isStaticOrKinematicObject (Self) then
Self.setInterpolationWorldTransform (Self.getWorldTransform.all);
else
Self.setInterpolationWorldTransform (xform);
end if;
Self.setInterpolationLinearVelocity (Self.getLinearVelocity);
Self.setInterpolationAngularVelocity (Self.getAngularVelocity);
Self.getWorldTransform.all := xform;
updateInertiaTensor (Self);
end setCenterOfMassTransform;
-- void impact.d3.Object.rigid::setCenterOfMassTransform(const impact.d3.Transform& xform)
-- {
-- if (isStaticOrKinematicObject())
-- {
-- m_interpolationWorldTransform = m_worldTransform;
-- } else
-- {
-- m_interpolationWorldTransform = xform;
-- }
-- m_interpolationLinearVelocity = getLinearVelocity();
-- m_interpolationAngularVelocity = getAngularVelocity();
-- m_worldTransform = xform;
-- updateInertiaTensor();
-- }
procedure applyCentralForce (Self : in out Item;
force : in Vector_3)
is
begin
Self.m_totalForce := Self.m_totalForce + Scaled (force, by => Self.m_linearFactor);
end applyCentralForce;
-- void applyCentralForce(const impact.d3.Vector& force)
-- {
-- m_totalForce += force*m_linearFactor;
-- }
function getTotalForce (Self : in Item) return Vector_3
is
begin
return Self.m_totalForce;
end getTotalForce;
-- const impact.d3.Vector& getTotalForce() const
-- {
-- return m_totalForce;
-- };
function getTotalTorque (Self : in Item) return Vector_3
is
begin
return Self.m_totalTorque;
end getTotalTorque;
-- const impact.d3.Vector& getTotalTorque() const
-- {
-- return m_totalTorque;
-- };
function getInvInertiaDiagLocal (Self : in Item) return Vector_3
is
begin
return Self.m_invInertiaLocal;
end getInvInertiaDiagLocal;
-- const impact.d3.Vector& getInvInertiaDiagLocal() const
-- {
-- return m_invInertiaLocal;
-- };
procedure setInvInertiaDiagLocal (Self : in out Item;
diagInvInertia : in Vector_3)
is
begin
Self.m_invInertiaLocal := diagInvInertia;
end setInvInertiaDiagLocal;
-- void setInvInertiaDiagLocal(const impact.d3.Vector& diagInvInertia)
-- {
-- m_invInertiaLocal = diagInvInertia;
-- }
procedure setSleepingThresholds (Self : in out Item;
linear : in Real;
angular : in Real)
is
begin
Self.m_linearSleepingThreshold := linear;
Self.m_angularSleepingThreshold := angular;
end setSleepingThresholds;
-- void setSleepingThresholds(impact.d3.Scalar linear,impact.d3.Scalar angular)
-- {
-- m_linearSleepingThreshold = linear;
-- m_angularSleepingThreshold = angular;
-- }
procedure applyTorque (Self : in out Item;
torque : in Vector_3)
is
begin
Self.m_totalTorque := Scaled (torque, by => Self.m_angularFactor);
end applyTorque;
-- void applyTorque(const impact.d3.Vector& torque)
-- {
-- m_totalTorque += torque*m_angularFactor;
-- }
procedure applyForce (Self : in out Item;
force : in Vector_3;
rel_pos : in Vector_3)
is
begin
applyCentralForce (Self, force);
Self.applyTorque (cross (rel_pos, Scaled (force, by => Self.m_linearFactor)));
end applyForce;
-- void applyForce(const impact.d3.Vector& force, const impact.d3.Vector& rel_pos)
-- {
-- applyCentralForce(force);
-- applyTorque(rel_pos.cross(force*m_linearFactor));
-- }
procedure applyCentralImpulse (Self : in out Item;
impulse : in Vector_3)
is
begin
Self.m_linearVelocity := Self.m_linearVelocity + Scaled (impulse, by => Self.m_linearFactor * Self.m_inverseMass);
end applyCentralImpulse;
-- void applyCentralImpulse(const impact.d3.Vector& impulse)
-- {
-- m_linearVelocity += impulse *m_linearFactor * m_inverseMass;
-- }
procedure applyTorqueImpulse (Self : in out Item;
torque : in Vector_3)
is
begin
Self.m_angularVelocity := Self.m_angularVelocity + Self.m_invInertiaTensorWorld * Scaled (torque, by => Self.m_angularFactor);
end applyTorqueImpulse;
-- void applyTorqueImpulse(const impact.d3.Vector& torque)
-- {
-- m_angularVelocity += m_invInertiaTensorWorld * torque * m_angularFactor;
-- }
procedure applyImpulse (Self : in out Item;
impulse : in Vector_3;
rel_pos : in Vector_3)
is
use Math.Vectors;
begin
if Self.m_inverseMass /= 0.0 then
applyCentralImpulse (Self, impulse);
if Self.m_angularFactor /= math.Origin_3d then -- tbd: ok ?
Self.applyTorqueImpulse (cross (rel_pos, Scaled (impulse, by => Self.m_linearFactor)));
end if;
end if;
end applyImpulse;
-- void applyImpulse(const impact.d3.Vector& impulse, const impact.d3.Vector& rel_pos)
-- {
-- if (m_inverseMass != impact.d3.Scalar(0.))
-- {
-- applyCentralImpulse(impulse);
-- if (m_angularFactor)
-- {
-- applyTorqueImpulse(rel_pos.cross(impulse*m_linearFactor));
-- }
-- }
-- }
procedure clearForces (Self : in out Item)
is
begin
Self.m_totalForce := (0.0, 0.0, 0.0);
Self.m_totalTorque := (0.0, 0.0, 0.0);
end clearForces;
-- void clearForces()
-- {
-- m_totalForce.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- m_totalTorque.setValue(impact.d3.Scalar(0.0), impact.d3.Scalar(0.0), impact.d3.Scalar(0.0));
-- }
procedure updateInertiaTensor (Self : in out Item)
is
use impact.d3.Matrix, math.Vectors;
begin
Self.m_invInertiaTensorWorld := scaled (Self.getWorldTransform.Rotation, Self.m_invInertiaLocal) * Transpose (Self.GetWorldTransform.Rotation);
-- for row in 1..3 loop
-- for col in 1..3 loop
-- if not Self.m_invInertiaTensorWorld (row, col)'Valid then
-- raise Constraint_Error;
-- end if;
-- end loop;
-- end loop;
end updateInertiaTensor;
-- void impact.d3.Object.rigid::updateInertiaTensor()
-- {
-- m_invInertiaTensorWorld = m_worldTransform.getBasis().scaled(m_invInertiaLocal) * m_worldTransform.getBasis().transpose();
-- }
function getCenterOfMassPosition (Self : in Item) return Vector_3
is
begin
return Self.WorldTransform.Translation;
end getCenterOfMassPosition;
-- const impact.d3.Vector& getCenterOfMassPosition() const {
-- return m_worldTransform.getOrigin();
-- }
function getOrientation (Self : access Item) return Quaternion
is
use impact.d3.Matrix;
orn : Quaternion;
begin
getRotation (Self.getWorldTransform.Rotation, orn);
return orn;
end getOrientation;
-- impact.d3.Quaternion impact.d3.Object.rigid::getOrientation() const
-- {
-- impact.d3.Quaternion orn;
-- m_worldTransform.getBasis().getRotation(orn);
-- return orn;
-- }
function getCenterOfMassTransform (Self : in Item) return Transform_3d
is
begin
return Self.WorldTransform;
end getCenterOfMassTransform;
-- const impact.d3.Transform& getCenterOfMassTransform() const {
-- return m_worldTransform;
-- }
function getLinearVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_linearVelocity;
end getLinearVelocity;
-- const impact.d3.Vector& getLinearVelocity() const {
-- return m_linearVelocity;
-- }
function getAngularVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_angularVelocity;
end getAngularVelocity;
-- const impact.d3.Vector& getAngularVelocity() const {
-- return m_angularVelocity;
-- }
procedure setLinearVelocity (Self : in out Item;
lin_vel : in Vector_3)
is
begin
Self.m_linearVelocity := lin_vel;
end setLinearVelocity;
-- inline void setLinearVelocity(const impact.d3.Vector& lin_vel)
-- {
-- m_linearVelocity = lin_vel;
-- }
procedure setAngularVelocity (Self : in out Item;
ang_vel : in Vector_3)
is
begin
Self.m_angularVelocity := ang_vel;
end setAngularVelocity;
-- inline void setAngularVelocity(const impact.d3.Vector& ang_vel)
-- {
-- m_angularVelocity = ang_vel;
-- }
function getVelocityInLocalPoint (Self : in Item;
rel_pos : in Vector_3) return Vector_3
is
begin
return Self.m_linearVelocity + cross (Self.m_angularVelocity, rel_pos);
end getVelocityInLocalPoint;
-- impact.d3.Vector getVelocityInLocalPoint(const impact.d3.Vector& rel_pos) const
-- {
-- //we also calculate lin/ang velocity for kinematic objects
-- return m_linearVelocity + m_angularVelocity.cross(rel_pos);
--
-- //for kinematic objects, we could also use use:
-- // return (m_worldTransform(rel_pos) - m_interpolationWorldTransform(rel_pos)) / m_kinematicTimeStep;
-- }
procedure translate (Self : in out Item;
v : in Vector_3)
is
begin
Self.getWorldTransform.Translation := Self.getWorldTransform.Translation + v;
end translate;
-- void translate(const impact.d3.Vector& v)
-- {
-- m_worldTransform.getOrigin() += v;
-- }
procedure getAabb (Self : in out Item;
aabbMin : out Vector_3;
aabbMax : out Vector_3)
is
begin
Self.getCollisionShape.getAabb (Self.getWorldTransform.all, aabbMin, aabbMax);
end getAabb;
function computeImpulseDenominator (Self : in Item;
pos : in Vector_3;
normal : in Vector_3) return Real
is
r0 : constant Vector_3 := pos - getCenterOfMassPosition (Self);
c0 : constant Vector_3 := cross (r0, normal);
vec : constant Vector_3 := cross (c0 * getInvInertiaTensorWorld (Self), r0);
begin
return Self.m_inverseMass + dot (normal, vec);
end computeImpulseDenominator;
-- SIMD_FORCE_INLINE impact.d3.Scalar computeImpulseDenominator(const impact.d3.Vector& pos, const impact.d3.Vector& normal) const
-- {
-- impact.d3.Vector r0 = pos - getCenterOfMassPosition();
--
-- impact.d3.Vector c0 = (r0).cross(normal);
--
-- impact.d3.Vector vec = (c0 * getInvInertiaTensorWorld()).cross(r0);
--
-- return m_inverseMass + normal.dot(vec);
--
-- }
function computeAngularImpulseDenominator (Self : in Item;
axis : in Vector_3) return Real
is
vec : constant Vector_3 := axis * getInvInertiaTensorWorld (Self);
begin
return dot (axis, vec);
end computeAngularImpulseDenominator;
-- SIMD_FORCE_INLINE impact.d3.Scalar computeAngularImpulseDenominator(const impact.d3.Vector& axis) const
-- {
-- impact.d3.Vector vec = axis * getInvInertiaTensorWorld();
-- return axis.dot(vec);
-- }
procedure UpdateDeactivation (Self : in out Item;
TimeStep : in Real)
is
begin
if Self.getActivationState = impact.d3.Object.ISLAND_SLEEPING
or else Self.getActivationState = impact.d3.Object.DISABLE_DEACTIVATION
then
null;
elsif length2 (Self.getLinearVelocity) < Self.m_linearSleepingThreshold * Self.m_linearSleepingThreshold
and then length2 (Self.getAngularVelocity) < Self.m_angularSleepingThreshold * Self.m_angularSleepingThreshold
then
Self.setDeactivationTime (Self.getDeactivationTime + timeStep);
else
Self.setDeactivationTime (0.0);
Self.setActivationState (0);
end if;
end UpdateDeactivation;
-- SIMD_FORCE_INLINE void updateDeactivation(impact.d3.Scalar timeStep)
-- {
-- if ( (getActivationState() == ISLAND_SLEEPING) || (getActivationState() == DISABLE_DEACTIVATION))
-- return;
--
-- if ((getLinearVelocity().length2() < m_linearSleepingThreshold*m_linearSleepingThreshold) &&
-- (getAngularVelocity().length2() < m_angularSleepingThreshold*m_angularSleepingThreshold))
-- {
-- m_deactivationTime += timeStep;
-- } else
-- {
-- m_deactivationTime=impact.d3.Scalar(0.);
-- setActivationState(0);
-- }
--
-- }
function wantsSleeping (Self : in Item) return Boolean
is
begin
if getActivationState (Self) = impact.d3.Object.DISABLE_DEACTIVATION then
return False;
end if;
if gDisableDeactivation
or else gDeactivationTime = 0.0
then
return False;
end if;
if getActivationState (Self) = impact.d3.Object.ISLAND_SLEEPING
or else getActivationState (Self) = impact.d3.Object.WANTS_DEACTIVATION
then
return True;
end if;
if Self.getDeactivationTime > gDeactivationTime then
return True;
end if;
return False;
end wantsSleeping;
-- SIMD_FORCE_INLINE bool wantsSleeping()
-- {
--
-- if (getActivationState() == DISABLE_DEACTIVATION)
-- return false;
--
-- //disable deactivation
-- if (gDisableDeactivation || (gDeactivationTime == impact.d3.Scalar(0.)))
-- return false;
--
-- if ( (getActivationState() == ISLAND_SLEEPING) || (getActivationState() == WANTS_DEACTIVATION))
-- return true;
--
-- if (m_deactivationTime> gDeactivationTime)
-- {
-- return true;
-- }
-- return false;
-- }
function getBroadphaseProxy (Self : access Item) return access impact.d3.collision.Proxy.item
is
begin
return Self.getBroadphaseHandle;
end getBroadphaseProxy;
-- impact.d3.collision.Proxy* getBroadphaseProxy()
-- {
-- return m_broadphaseHandle;
-- }
procedure setNewBroadphaseProxy (Self : in out Item;
broadphaseProxy : access impact.d3.collision.Proxy.item)
is
begin
Self.setBroadphaseHandle (broadphaseProxy);
end setNewBroadphaseProxy;
-- void setNewBroadphaseProxy(impact.d3.collision.Proxy* broadphaseProxy)
-- {
-- m_broadphaseHandle = broadphaseProxy;
-- }
-- function getMotionState (Self : in Item) return impact.d3.motion_State.Item'Class is
-- begin
-- return Self.m_OptionalMotionState.all;
-- end getMotionState;
function getMotionState (Self : in Item) return access impact.d3.motion_State.Item'Class is
begin
return Self.m_OptionalMotionState;
end getMotionState;
-- impact.d3.motion_State* getMotionState()
-- {
-- return m_optionalMotionState;
-- }
procedure setMotionState (Self : in out Item;
motionState : access impact.d3.motion_State.Item'Class) is
begin
Self.m_optionalMotionState := motionState;
if Self.m_optionalMotionState /= null then
motionState.getWorldTransform (Self.getWorldTransform.all);
end if;
end setMotionState;
-- void setMotionState(impact.d3.motion_State* motionState)
-- {
-- m_optionalMotionState = motionState;
-- if (m_optionalMotionState)
-- motionState->getWorldTransform(m_worldTransform);
-- }
procedure setAngularFactor (Self : in out Item;
angFac : in Vector_3)
is
begin
Self.m_angularFactor := angFac;
end setAngularFactor;
-- void setAngularFactor(const impact.d3.Vector& angFac)
-- {
-- m_angularFactor = angFac;
-- }
procedure setAngularFactor (Self : in out Item;
angFac : in Real)
is
begin
Self.m_angularFactor := (angFac, angFac, angFac);
end setAngularFactor;
-- void setAngularFactor(impact.d3.Scalar angFac)
-- {
-- m_angularFactor.setValue(angFac,angFac,angFac);
-- }
function getAngularFactor (Self : in Item) return Vector_3
is
begin
return Self.m_angularFactor;
end getAngularFactor;
-- const impact.d3.Vector& getAngularFactor() const
-- {
-- return m_angularFactor;
-- }
function isInWorld (Self : access Item) return Boolean
is
use impact.d3.collision.Proxy;
begin
return Self.getBroadphaseProxy /= null;
end isInWorld;
-- //is this rigidbody added to a impact.d3.Space/impact.d3.Space.dynamic/btBroadphase?
-- bool isInWorld() const
-- {
-- return (getBroadphaseProxy() != 0);
-- }
overriding function checkCollideWithOverride (Self : in Item;
co : access impact.d3.Object.item'Class) return Boolean
is
type rigid_Object_view is access all impact.d3.Object.rigid.item'Class;
otherRb : constant access impact.d3.Object.rigid .item'Class := impact.d3.Object.rigid.view (co);
c : access impact.d3.Joint.Item'Class;
begin
if otherRb = null then
return True;
end if;
for i in 1 .. Integer (Self.m_constraintRefs.Length)
loop
c := Self.m_constraintRefs.Element (i);
if c.getRigidBodyA = otherRb
or else c.getRigidBodyB = otherRb
then
return False;
end if;
end loop;
return True;
end checkCollideWithOverride;
-- bool impact.d3.Object.rigid::checkCollideWithOverride(impact.d3.Object* co)
-- {
-- impact.d3.Object.rigid* otherRb = impact.d3.Object.rigid::upcast(co);
-- if (!otherRb)
-- return true;
-- for (int i = 0; i < m_constraintRefs.size(); ++i)
-- {
-- impact.d3.Joint* c = m_constraintRefs[i];
-- if (&c->getRigidBodyA() == otherRb || &c->getRigidBodyB() == otherRb)
-- return false;
-- }
-- return true;
-- }
procedure addConstraintRef (Self : in out Item;
c : access impact.d3.Joint.Item'Class)
is
use impact.d3.Joint.Vectors;
index : constant Integer := Self.m_constraintRefs.find_Index (c.all'Access);
begin
if index = 0 then -- Integer (Self.m_constraintRefs.Length) then
Self.m_constraintRefs.append (c.all'Access);
end if;
Self.setCheckCollideWith (True);
end addConstraintRef;
-- void impact.d3.Object.rigid::addConstraintRef(impact.d3.Joint* c)
-- {
-- int index = m_constraintRefs.findLinearSearch(c);
-- if (index == m_constraintRefs.size())
-- m_constraintRefs.push_back(c);
-- m_checkCollideWith = true;
-- }
procedure removeConstraintRef (Self : in out Item;
c : access impact.d3.Joint.item'Class)
is
use type ada.Containers.Count_Type;
begin
Self.m_constraintRefs.delete (Self.m_constraintRefs.find_Index (c.all'Access));
Self.setCheckCollideWith (Self.m_constraintRefs.Length > 0);
end removeConstraintRef;
function getConstraintRef (Self : in Item;
index : in Integer) return access impact.d3.Joint.Item'Class
is
begin
return Self.m_constraintRefs.Element (index);
end getConstraintRef;
-- impact.d3.Joint* getConstraintRef(int index)
-- {
-- return m_constraintRefs[index];
-- }
function getNumConstraintRefs (Self : in Item) return Ada.Containers.Count_Type
is
begin
return Self.m_constraintRefs.Length;
end getNumConstraintRefs;
-- int getNumConstraintRefs() const
-- {
-- return m_constraintRefs.size();
-- }
procedure setFlags (Self : in out Item;
flags : in d3.Flags)
is
begin
Self.m_rigidbodyFlags := flags;
end setFlags;
-- void setFlags(int flags)
-- {
-- m_rigidbodyFlags = flags;
-- }
function getFlags (Self : in Item) return Flags
is
begin
return Self.m_rigidbodyFlags;
end getFlags;
-- int getFlags() const
-- {
-- return m_rigidbodyFlags;
-- }
function getDeltaLinearVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_deltaLinearVelocity;
end getDeltaLinearVelocity;
-- const impact.d3.Vector& getDeltaLinearVelocity() const
-- {
-- return m_deltaLinearVelocity;
-- }
function getDeltaAngularVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_deltaAngularVelocity;
end getDeltaAngularVelocity;
-- const impact.d3.Vector& getDeltaAngularVelocity() const
-- {
-- return m_deltaAngularVelocity;
-- }
function getPushVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_pushVelocity;
end getPushVelocity;
-- const impact.d3.Vector& getPushVelocity() const
-- {
-- return m_pushVelocity;
-- }
function getTurnVelocity (Self : in Item) return Vector_3
is
begin
return Self.m_turnVelocity;
end getTurnVelocity;
-- const impact.d3.Vector& getTurnVelocity() const
-- {
-- return m_turnVelocity;
-- }
function internalGetDeltaLinearVelocity (Self : access Item) return access Vector_3
is
begin
return Self.m_deltaLinearVelocity'Access;
end internalGetDeltaLinearVelocity;
-- impact.d3.Vector& internalGetDeltaLinearVelocity()
-- {
-- return m_deltaLinearVelocity;
-- }
function internalGetDeltaAngularVelocity (Self : access Item) return access Vector_3
is
begin
return Self.m_deltaAngularVelocity'Access;
end internalGetDeltaAngularVelocity;
-- impact.d3.Vector& internalGetDeltaAngularVelocity()
-- {
-- return m_deltaAngularVelocity;
-- }
function internalGetAngularFactor (Self : in Item) return Vector_3
is
begin
return Self.m_angularFactor;
end internalGetAngularFactor;
-- const impact.d3.Vector& internalGetAngularFactor() const
-- {
-- return m_angularFactor;
-- }
function internalGetInvMass (Self : in Item) return Vector_3
is
begin
return Self.m_invMass;
end internalGetInvMass;
-- const impact.d3.Vector& internalGetInvMass() const
-- {
-- return m_invMass;
-- }
function internalGetPushVelocity (Self : access Item) return access Vector_3
is
begin
return Self.m_pushVelocity'Access;
end internalGetPushVelocity;
-- impact.d3.Vector& internalGetPushVelocity()
-- {
-- return m_pushVelocity;
-- }
function internalGetTurnVelocity (Self : access Item) return access Vector_3
is
begin
return Self.m_turnVelocity'Access;
end internalGetTurnVelocity;
-- impact.d3.Vector& internalGetTurnVelocity()
-- {
-- return m_turnVelocity;
-- }
procedure internalGetVelocityInLocalPointObsolete
(Self : in Item;
rel_pos : in Vector_3;
velocity : out Vector_3)
is
begin
velocity := getLinearVelocity (Self)
+ Self.m_deltaLinearVelocity
+ cross (getAngularVelocity (Self) + Self.m_deltaAngularVelocity,
rel_pos);
end InternalGetVelocityInLocalPointObsolete;
-- SIMD_FORCE_INLINE void internalGetVelocityInLocalPointObsolete(const impact.d3.Vector& rel_pos, impact.d3.Vector& velocity ) const
-- {
-- velocity = getLinearVelocity()+m_deltaLinearVelocity + (getAngularVelocity()+m_deltaAngularVelocity).cross(rel_pos);
-- }
procedure internalGetAngularVelocity (Self : in Item;
angVel : out Vector_3)
is
begin
angVel := getAngularVelocity (Self) + Self.m_deltaAngularVelocity;
end internalGetAngularVelocity;
-- SIMD_FORCE_INLINE void internalGetAngularVelocity(impact.d3.Vector& angVel) const
-- {
-- angVel = getAngularVelocity()+m_deltaAngularVelocity;
-- }
procedure internalApplyImpulse
(Self : in out Item;
linearComponent : in Vector_3;
angularComponent : in Vector_3;
impulseMagnitude : in Real)
is
--- These vector functions are for performance ('ada.numerics.generic_real_arrays' appears slow).
--
function "+" (L, R : in Vector_3) return Vector_3
is
begin
return (L (1) + R (1),
L (2) + R (2),
L (3) + R (3));
end;
function "*" (L : in Vector_3; R : in Real) return Vector_3
is
begin
return (L (1) * R,
L (2) * R,
L (3) * R);
end;
pragma Inline_Always ("+");
pragma Inline_Always ("*");
begin
if Self.m_inverseMass /= 0.0 then
Self.m_deltaLinearVelocity :=
Self.m_deltaLinearVelocity + linearComponent * impulseMagnitude;
-- put_Line ("Self.m_deltaLinearVelocity => " & Image (Self.m_deltaLinearVelocity, 9));
Self.m_deltaAngularVelocity :=
Self.m_deltaAngularVelocity + Scaled (angularComponent, by => (Self.m_angularFactor * impulseMagnitude));
end if;
end InternalApplyImpulse;
-- //Optimization for the iterative solver: avoid calculating constant terms involving inertia, normal, relative position
-- SIMD_FORCE_INLINE void internalApplyImpulse(const impact.d3.Vector& linearComponent, const impact.d3.Vector& angularComponent,const impact.d3.Scalar impulseMagnitude)
-- {
-- if (m_inverseMass)
-- {
-- m_deltaLinearVelocity += linearComponent*impulseMagnitude;
-- m_deltaAngularVelocity += angularComponent*(impulseMagnitude*m_angularFactor);
-- }
-- }
procedure internalApplyPushImpulse
(Self : in out Item;
linearComponent : in Vector_3;
angularComponent : in Vector_3;
impulseMagnitude : in Real)
is
begin
if Self.m_inverseMass /= 0.0 then
Self.m_pushVelocity :=
Self.m_pushVelocity + linearComponent * impulseMagnitude;
Self.m_turnVelocity :=
Self.m_turnVelocity + Scaled (angularComponent, by => (impulseMagnitude * Self.m_angularFactor));
end if;
end InternalApplyPushImpulse;
-- SIMD_FORCE_INLINE void internalApplyPushImpulse(const impact.d3.Vector& linearComponent, const impact.d3.Vector& angularComponent,impact.d3.Scalar impulseMagnitude)
-- {
-- if (m_inverseMass)
-- {
-- m_pushVelocity += linearComponent*impulseMagnitude;
-- m_turnVelocity += angularComponent*(impulseMagnitude*m_angularFactor);
-- }
-- }
procedure internalWritebackVelocity (Self : in out Item)
is
begin
if Self.m_inverseMass /= 0.0 then
setLinearVelocity (Self, getLinearVelocity (Self) + Self.m_deltaLinearVelocity);
setAngularVelocity (Self, getAngularVelocity (Self) + Self.m_deltaAngularVelocity);
end if;
end internalWritebackVelocity;
-- void internalWritebackVelocity()
-- {
-- if (m_inverseMass)
-- {
-- setLinearVelocity(getLinearVelocity()+ m_deltaLinearVelocity);
-- setAngularVelocity(getAngularVelocity()+m_deltaAngularVelocity);
-- //m_deltaLinearVelocity.setZero();
-- //m_deltaAngularVelocity .setZero();
-- //TranslationalBody->setCompanionId(-1);
-- }
-- }
procedure internalWritebackVelocity (Self : in out Item;
timeStep : in Real)
is
use impact.d3.transform_Util;
begin
if Self.m_inverseMass /= 0.0 then
setLinearVelocity (Self, getLinearVelocity (Self) + Self.m_deltaLinearVelocity);
setAngularVelocity (Self, getAngularVelocity (Self) + Self.m_deltaAngularVelocity);
declare
newTransform : Transform_3d;
begin
integrateTransform (Self.getWorldTransform.all,
Self.m_pushVelocity,
Self.m_turnVelocity,
timeStep,
newTransform);
setWorldTransform (Self, newTransform);
end;
end if;
end internalWritebackVelocity;
-- void impact.d3.Object.rigid::internalWritebackVelocity(impact.d3.Scalar timeStep)
-- {
-- (void) timeStep;
-- if (m_inverseMass)
-- {
-- setLinearVelocity(getLinearVelocity()+ m_deltaLinearVelocity);
-- setAngularVelocity(getAngularVelocity()+m_deltaAngularVelocity);
-- //correct the position/orientation based on push/turn recovery
-- impact.d3.Transform newTransform;
-- impact.d3.TransformUtil::integrateTransform(getWorldTransform(),m_pushVelocity,m_turnVelocity,timeStep,newTransform);
-- setWorldTransform(newTransform);
-- //TranslationalBody->setCompanionId(-1);
-- }
-- // m_deltaLinearVelocity.setZero();
-- // m_deltaAngularVelocity .setZero();
-- // m_pushVelocity.setZero();
-- // m_turnVelocity.setZero();
-- }
end impact.d3.Object.rigid;
|
30,760
|
ada
| 0
|
jquorning/CELLE
|
source/errors.adb
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Ada.Strings.Fixed;
package body Errors is
type String_Access is access all String;
function "-" (Item : in String) return String_Access;
function "-" (Item : in String) return String_Access is
begin
return new String'(Item);
end "-";
type Error_Table is array (Error_Id) of String_Access;
Table : constant Error_Table :=
Error_Table'(E001 => -("There is no prior rule upon which to attach the code fragment " &
"which begins on this line."),
E002 => -("Code fragment beginning on this line is not the first to follow " &
"the previous rule."),
E003 => -"Token '$1' should be either '%%' or a nonterminal name.",
E004 => -"The precedence symbol must be a terminal.",
E005 => -"There is no prior rule to assign precedence '[$1]'.",
E006 => -("Precedence mark on this line is not the first to follow the " &
"previous rule."),
E007 => -"Missing ']' on precedence mark.",
E008 => -"Expected to see a ':' following the LHS symbol '$1'.",
E009 => -"'$1' is not a valid alias for the LHS '$2'",
E010 => -"Missing ')' following LHS alias name '$1'.",
E011 => -"Missing '->' following: '$1($2)'.",
E012 => -"'$1' is not a valid alias for the RHS symbol '$2'",
E013 => -"Missing ')' following LHS alias name '$1'.",
E014 => -("The specified start symbol '$1' Start is not in a nonterminal " &
"of the grammar. '$2' will be used as the start symbol instead."),
E015 => -("The start symbol '$1' occurs on the right-hand " &
"side of a rule. This will result in a parser which " &
"does not work properly."),
E016 => -"Can not open '$1' for reading.",
E101 => -"Can't open this file for reading.",
E102 => -("C code starting on this line is not terminated before the end " &
"of the file."),
E103 => -("String starting on this line is not terminated before the end " &
"of the file."),
E201 => -"Cannot form a compound containing a non-terminal",
E202 => -"Illegal character on RHS of rule: '$1'.",
E203 => -"Unknown declaration keyword: '%$1'.",
E204 => -"Illegal declaration keyword: '$1'.",
E205 => -"Symbol name missing after %destructor keyword",
E206 => -"Symbol name missing after %type keyword",
E207 => -"Symbol %type '$1' already defined",
E208 => -"%token_class argument '%1' should be a token",
E209 => -"%token_class must be followed by an identifier: $1",
E210 => -"Symbol '$1' already used",
E211 => -"%wildcard argument '$1' should be a token",
E212 => -"Extra wildcard to token: '$1'",
E213 => -"Illegal argument to %$1: $2",
E214 => -"%token argument $1 should be a token",
E215 => -"%fallback argument $1 should be a token",
E216 => -"More than one fallback assigned to token $1",
E217 => -"Symbol $1 has already be given a precedence.",
E218 => -"Can't assign a precedence to $1.",
E301 => -"This rule can not be reduced.",
E401 => -"Nonterminal ""$1"" has no rules."
);
procedure Parser_Error
(Id : in Error_Id;
Line : in Line_Number;
Argument_1 : in String := "";
Argument_2 : in String := "")
is
-- use Ada.Strings;
File_Name : constant String := To_String (Default_File_Name);
Kind_Image : constant String := Id'Image & " ";
Message : Unbounded_String := To_Unbounded_String (Table (Id).all);
Position : Natural := 1;
begin
-- Substitued $1 placeholder
Position := Index (Message, "$1", Position);
if Position /= 0 then
Replace_Slice (Message, Position,
Position + 2 - 1,
Argument_1);
end if;
-- Substitute $2 placeholder
Position := Index (Message, "$2", Position);
if Position /= 0 then
Replace_Slice (Message, Position,
Position + 2 - 1,
Argument_2);
end if;
Emit_Error (File => Ada.Text_IO.Standard_Output,
File_Name => File_Name,
Line => Line,
Message => Kind_Image & To_String (Message));
Error_Count := Error_Count + 1;
end Parser_Error;
procedure Set_File_Name
(File_Name : in Ada.Strings.Unbounded.Unbounded_String)
is
begin
Errors.Default_File_Name := File_Name;
end Set_File_Name;
procedure Emit_Error (File : in Ada.Text_IO.File_Type;
File_Name : in String;
Line : in Line_Number;
Message : in String)
is
use Ada.Text_IO;
use Ada.Strings;
Line_Number_Image : constant String := Fixed.Trim (Line_Number'Image (Line), Left);
begin
Put (File, File_Name);
Put (File, ":");
Put (File, Line_Number_Image);
Put (File, ": ");
Put (File, Message);
New_Line (File);
end Emit_Error;
end Errors;
|
30,761
|
ada
| 1
|
danva994/ASFML-1.6
|
tests/window/main.adb
|
<filename>tests/window/main.adb
with Ada.Text_IO; use Ada.Text_IO;
with Sf.Config; use Sf.Config;
with Sf.Window.Types; use Sf.Window.Types;
with Sf.Window.Window; use Sf.Window.Window;
with Sf.Window.VideoMode; use Sf.Window.VideoMode;
with Sf.Window.Event; use Sf.Window.Event;
with Sf.Window.Input; use Sf.Window.Input;
with Sf.System.Sleep; use Sf.System.Sleep;
procedure Main is
Window : sfWindow_Ptr;
Mode : sfVideoMode := (640, 480, 32);
Params : sfWindowSettings := (24, 8, 0);
Event : aliased sfEvent;
Input : sfInput_Ptr;
begin
Window := sfWindow_Create (Mode, "Window");
if Window = null then
Put_Line ("Failed to create window");
return;
end if;
sfWindow_SetFramerateLimit (Window, 32);
sfWindow_UseVerticalSync (Window, sfTrue);
sfWindow_Show (Window, sfTrue);
while sfWindow_IsOpened (Window) = sfTrue loop
while sfWindow_GetEvent (Window, Event'ACCESS) = sfTrue loop
if Event.Event_Type = sfEvtClosed then
sfWindow_Close (Window);
Put_Line ("Attepting to close");
end if;
Input := sfWindow_GetInput (Window);
if Input /= null and then Event.Event_Type = sfEvtKeyPressed and then sfInput_IsKeyDown (Input, sfKeyEscape) = sfTrue then
sfWindow_Close (Window);
Put_Line ("Attepting to close");
end if;
end loop;
sfWindow_Display (Window);
sfSleep (0.001);
end loop;
sfWindow_Destroy (Window);
end Main;
|
30,762
|
ada
| 0
|
notdb/LC-Practice
|
136/ada/greet.adb
|
<filename>136/ada/greet.adb
with Ada.Text_IO; use Ada.Text_IO;
procedure Greet is
begin
-- Print "Hello, World!" to the screen
Put_line ("Hello, World!");
Ada.Text_IO.Put_line ("Hello, world (two)!");
end Greet;
|
30,763
|
ada
| 1
|
dshadrin/AProxy
|
src/sinks.adb
|
<gh_stars>1-10
----------------------------------------
-- Copyright (C) 2019 <NAME> --
-- All rights reserved. --
----------------------------------------
with Logging_Message; use Logging_Message;
with TimeStamp;
with Ada.Characters.Handling;
with Ada.Unchecked_Deallocation;
with Ada.Text_IO; use Ada.Text_IO;
with Formatted_Output; use Formatted_Output;
with Formatted_Output.Enumeration_Output;
package body Sinks is
package ASU renames Ada.Strings.Unbounded;
-----------------------------------------------------------------------------
use all type ASU.Unbounded_String;
type SinkTypeValueArray is array (ESinkType) of ASU.Unbounded_String;
sinkTypesStr : constant SinkTypeValueArray := (To_Unbounded_String ("CONSOLE"), To_Unbounded_String ("FILE"));
type SeverityConfigureString is array (ESeverity) of ASU.Unbounded_String;
sinkSeverityStr : constant SeverityConfigureString := (To_Unbounded_String ("TRACE"),
To_Unbounded_String ("DEBUG"),
To_Unbounded_String ("INFO"),
To_Unbounded_String ("TEST"),
To_Unbounded_String ("WARN"),
To_Unbounded_String ("ERROR"),
To_Unbounded_String ("CRIT"));
type SeverityValueArray is array (ESeverity) of String (1 .. 4);
severityLogOutput : constant SeverityValueArray := ("TRAC", "DBG ", "INFO", "TEST", "WARN", "ERR ", "CRIT");
-----------------------------------------------------------------------------
function SinkTypeStr (sev : ESinkType) return Ada.Strings.Unbounded.Unbounded_String with inline is
begin
return sinkTypesStr (sev);
end SinkTypeStr;
-----------------------------------------------------------------------------
function SeverityFromStr (str : String) return ESeverity is
begin
for i in ESeverity'Range loop
if To_Unbounded_String (str) = sinkSeverityStr (i) then
return i;
end if;
end loop;
raise Program_Error;
end SeverityFromStr;
-----------------------------------------------------------------------------
function SeverityStr (sev : ESeverity) return String with inline is
begin
return severityLogOutput (sev);
end SeverityStr;
-----------------------------------------------------------------------------
function FormatMessage (ptr : SLogPackagePtr) return String is
use Formatted_Output;
begin
return To_String (+"[%s][%s][%s] - %s"
& TimeStamp.GetTimestampStr (ptr.tm_stamp)
& ptr.tag
& SeverityStr (ptr.severity)
& Ada.Strings.Unbounded.To_String (ptr.message));
end FormatMessage;
-----------------------------------------------------------------------------
procedure MakeSink (self : out Sink; name : in String; cfg : in ConfigTree.NodePtr) is
package Formatter_SinkType is new Formatted_Output.Enumeration_Output (Sinks.ESinkType);
use Ada.Strings.Unbounded;
use Formatter_SinkType;
use Logging_Message.Formatter_Channel;
sinkName : Unbounded_String := Trim ( To_Unbounded_String (Ada.Characters.Handling.To_Upper (name)), Ada.Strings.Both);
severity : ESeverity := SeverityFromStr (cfg.GetValue ("severity"));
channel : LogChannel := LogChannel'Value (cfg.GetValue ("channel"));
begin
self.severity := severity;
self.channel := channel;
if sinkName = SinkTypeStr (CONSOLE_SINK) then
self.SinkType := CONSOLE_SINK;
elsif sinkName = SinkTypeStr (FILE_SINK) then
declare
template : Unbounded_String := Null_Unbounded_String;
prefix : Unbounded_String := Null_Unbounded_String;
suffix : Unbounded_String := Null_Unbounded_String;
demand : Pal.bool := false;
nd : ConfigTree.NodePtr := cfg.GetFirst;
begin
while not ConfigTree.IsNull (nd) loop
if nd.GetName = "template" then
template := To_Unbounded_String (nd.GetValue);
elsif nd.GetName = "prefix" then
prefix := To_Unbounded_String (nd.GetValue);
elsif nd.GetName = "suffix" then
suffix := To_Unbounded_String (nd.GetValue);
elsif nd.GetName = "open_by_demand" and then Ada.Characters.Handling.To_Upper (nd.GetValue) = "TRUE" then
demand := true;
end if;
nd := nd.GetNext;
end loop;
self.SinkType := FILE_SINK;
self.template := template;
self.prefix := prefix;
self.suffix := suffix;
self.filename := Null_Unbounded_String;
self.open_by_demand := demand;
if demand = false then
self.filename := MakeFilename(self);
end if;
end;
else
Put_Line ("Unknown sink :" & To_String (sinkName));
raise Program_Error;
end if;
self.handler := new SinkOutputer;
self.handler.Start (self.SinkType, severity, channel);
--LOG_INFO ("SINK", To_String (+"Created sink with channel %d : %s" & channel & self.SinkType));
end MakeSink;
-----------------------------------------------------------------------------
function Channel (self : access Sink) return Logging_Message.LogChannel is
begin
return self.channel;
end Channel;
-----------------------------------------------------------------------------
procedure WriteLogs (self : access Sink; logs : in LogMessages) is
begin
self.handler.Write (logs, self.filename);
end WriteLogs;
-----------------------------------------------------------------------------
procedure Close (self : access Sink) is
procedure Free is new Ada.Unchecked_Deallocation (SinkOutputer, SinkOutputerPtr);
begin
self.handler.Stop;
Free (self.handler);
end Close;
-----------------------------------------------------------------------------
task body SinkOutputer is
isWorked : Pal.bool := true;
sinkTag : ESinkType;
severity : Logging_Message.ESeverity;
channel : Logging_Message.LogChannel;
var : Pal.uint32_t;
begin
accept Start (tag : ESinkType;
sev : Logging_Message.ESeverity;
ch : Logging_Message.LogChannel) do
sinkTag := tag;
severity := sev;
channel := ch;
end Start;
while isWorked loop
select
accept Write (logs : in LogMessages;
file : in ASU.Unbounded_String := ASU.Null_Unbounded_String) do
for i in logs.Get.First_Index .. logs.Get.Last_Index loop
declare
msg : Logging_Message.LogMessage := logs.Get.Element (i);
begin
if msg.Get.lchannel = channel and then
msg.Get.severity >= severity and then
msg.Get.command = Logging_Message.eMessage then
if sinkTag = CONSOLE_SINK then
Put_Line (FormatMessage (msg.Get));
elsif sinkTag = FILE_SINK then
-- TODO: implement
null;
end if;
end if;
end;
end loop;
var := Pal.Atomic_Sub_Fetch_32 (activeSinksCounter'Access, 1);
end Write;
or
accept Stop do
isWorked := false;
end Stop;
end select;
end loop;
end SinkOutputer;
-----------------------------------------------------------------------------
function MakeFilename (self : in out Sink) return Ada.Strings.Unbounded.Unbounded_String is
outStr : ASU.Unbounded_String := ASU.Null_Unbounded_String;
posDot : Natural := 0;
begin
if self.SinkType = FILE_SINK then
outStr := self.prefix;
if ASU.Length (outStr) > 0 then
ASU.Append (outStr, "_");
end if;
ASU.Append (outStr, self.template);
if ASU.Length (self.suffix) > 0 then
posDot := ASU.Index (outStr, ".", 1);
if posDot > 0 then
ASU.Insert (outStr, Positive (posDot), ASU.To_String (ASU.To_Unbounded_String ("_") & self.suffix));
else
ASU.Append (outStr, "_");
ASU.Append (outStr, self.suffix);
end if;
end if;
end if;
return outStr;
end MakeFilename;
end Sinks;
|
30,764
|
ada
| 0
|
djamal2727/Main-Bearing-Analytical-Model
|
Validation/pyFrame3DD-master/gcc-master/gcc/ada/libgnat/s-tsmona__mingw.adb
|
<gh_stars>0
------------------------------------------------------------------------------
-- --
-- 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 Windows specific version of this package
with System.Win32; use System.Win32;
separate (System.Traceback.Symbolic)
package body Module_Name is
---------------------------------
-- Build_Cache_For_All_Modules --
---------------------------------
procedure Build_Cache_For_All_Modules is
begin
null;
end Build_Cache_For_All_Modules;
---------
-- Get --
---------
function Get (Addr : System.Address;
Load_Addr : access System.Address)
return String
is
Res : DWORD;
hModule : aliased HANDLE;
Path : String (1 .. 1_024);
begin
Load_Addr.all := System.Null_Address;
if GetModuleHandleEx
(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
Addr,
hModule'Access) = Win32.TRUE
then
Res := GetModuleFileName (hModule, Path'Address, Path'Length);
if FreeLibrary (hModule) = Win32.FALSE then
null;
end if;
if Res > 0 then
return Path (1 .. Positive (Res));
end if;
end if;
return "";
exception
when others =>
return "";
end Get;
------------------
-- Is_Supported --
------------------
function Is_Supported return Boolean is
begin
return True;
end Is_Supported;
end Module_Name;
|
30,765
|
ada
| 0
|
hergin/ada2fuml
|
test-resources/ExamplesFromRoy/md_example7.ads
|
with Globals_Example1;
package Md_Example7 is
type T is tagged record
Attribute : Globals_Example1.Itype;
end record;
type T2 is new T with record
Child_Attribute : Globals_Example1.Itype;
end record;
type T3 is new T2 with null record;
end Md_Example7;
|
30,766
|
ada
| 19
|
jrcarter/Ada_GUI
|
ada_gui.adb
|
-- An Ada-oriented GUI library
-- Implementation derived from Gnoga
--
-- Copyright (C) 2021 by PragmAda Software Engineering
--
-- Released under the terms of the 3-Clause BSD License. See https://opensource.org/licenses/BSD-3-Clause
with Ada.Containers.Indefinite_Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Directories;
with Ada.Exceptions;
with Ada.Numerics.Elementary_Functions;
with Ada.Real_Time;
with Ada.Strings.Fixed;
with Ada_GUI.Gnoga.Application;
with Ada_GUI.Gnoga.Gui.Element.Canvas.Context_2D;
with Ada_GUI.Gnoga.Gui.Element.Common;
with Ada_GUI.Gnoga.Gui.Element.Form;
with Ada_GUI.Gnoga.Gui.Element.Multimedia;
with Ada_GUI.Gnoga.Gui.View.Console;
with Ada_GUI.Gnoga.Gui.View.Grid;
with Ada_GUI.Gnoga.Gui.Window;
with Ada_GUI.Gnoga.Colors;
package body Ada_GUI is
type Form_Set is array (Positive range <>, Positive range <>) of Gnoga.Gui.Element.Form.Form_Type;
type Form_Ptr is access Form_Set; -- Extensive use of access due to nature of Gnoga
package Column_Maps is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Boolean);
package Row_Maps is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => Column_Maps.Vector, "=" => Column_Maps."=");
Window : Gnoga.Gui.Window.Window_Type;
View : Gnoga.Gui.View.Console.Console_View_Type;
Grid : Gnoga.Gui.View.Grid.Grid_View_Type;
Form : Form_Ptr;
Valid : Row_Maps.Vector; -- Valid (Row) (Column) is True if (Row, Column) is an Area
Setup : Boolean := False with Atomic;
function Set_Up return Boolean is (Setup);
function Converted (Alignment : Alignment_ID) return Gnoga.Gui.Element.Alignment_Type is
(case Alignment is
when Left => Gnoga.Gui.Element.Left,
when Center => Gnoga.Gui.Element.Center,
when Right => Gnoga.Gui.Element.Right);
procedure Set_Up (Grid : in Grid_Set := (1 => (1 => (others => <>) ) );
ID : in Positive := 8080;
Title : in String := "Ada-GUI Application";
Icon : in String := "favicon.ico")
is
G_Grid : Gnoga.Gui.View.Grid.Grid_Rows_Type (Grid'Range (1), Grid'Range (2) );
begin -- Set_Up
Fill_Grid : for Row in Grid'Range (1) loop
Valid.Append (New_Item => Column_Maps.Empty_Vector);
Grid_Cols : for Column in Grid'Range (2) loop
G_Grid (Row, Column) := (if Grid (Row, Column).Kind = Area then Gnoga.Gui.View.Grid.COL else Gnoga.Gui.View.Grid.SPN);
Valid (Row).Append (New_Item => Grid (Row, Column).Kind = Area);
end loop Grid_Cols;
end loop Fill_Grid;
Gnoga.Application.Initialize (Main_Window => Window, ID => ID, Title => Title, Icon => Icon);
View.Create (Parent => Window);
Ada_GUI.Grid.Create (Parent => View, Layout => G_Grid);
Form := new Form_Set (Grid'Range (1), Grid'Range (2) );
All_Rows : for I in Form'Range (1) loop
All_Columns : for J in Form'Range (2) loop
if Grid (I, J).Kind = Area then
Form (I, J).Create (Parent => Ada_GUI.Grid.Panel (I, J).all);
Form (I, J).Text_Alignment (Value => Converted (Grid (I, J).Alignment) );
end if;
end loop All_Columns;
end loop All_Rows;
Setup := True;
end Set_Up;
type Radio_Info is record
Button : Gnoga.Gui.Element.Form.Radio_Button_Type;
Label : Gnoga.Gui.Element.Form.Label_Type;
end record;
type Radio_List is array (Positive range <>) of Radio_Info;
type Radio_Ptr is access Radio_List;
type Widget_Info (Kind : Widget_Kind_ID := Button) is record
case Kind is
when Audio_Player =>
Audio : Gnoga.Gui.Element.Multimedia.Audio_Access;
when Background_Text =>
Background : Gnoga.Gui.Element.Common.Span_Access;
when Button =>
Switch : Gnoga.Gui.Element.Common.Button_Access;
when Check_Box =>
Check : Gnoga.Gui.Element.Form.Check_Box_Access;
Check_Label : Gnoga.Gui.Element.Form.Label_Access;
when Graphic_Area =>
Canvas : Gnoga.Gui.Element.Canvas.Canvas_Access;
when Password_Box =>
Password : Gnoga.Gui.Element.Form.Password_Access;
Password_Label : Gnoga.Gui.Element.Form.Label_Access;
when Radio_Buttons =>
Radio : Radio_Ptr;
when Selection_List =>
Selector : Gnoga.Gui.Element.Form.Selection_Access;
Multi : Boolean;
when Text_Area =>
Area : Gnoga.Gui.Element.Form.Text_Area_Access;
when Text_Box =>
Box : Gnoga.Gui.Element.Form.Text_Access;
Box_Label : Gnoga.Gui.Element.Form.Label_Access;
end case;
end record;
package Widget_Lists is new Ada.Containers.Vectors (Index_Type => Natural, Element_Type => Widget_Info);
Widget_List : Widget_Lists.Vector;
function Kind (ID : Widget_ID) return Widget_Kind_ID is (Widget_List (ID.Value).Kind);
function Adjusted (Row : in Positive; Column : in Positive) return Positive;
-- If (Row, Column) is an Extension, reduces Column until (Row, Column) is an Area
procedure Break (Desired : in Boolean; Row : in Positive; Column : in Positive);
-- If Desired, make the next thing declared in Form (Row, Column) appear below existing things there
function Adjusted (Row : in Positive; Column : in Positive) return Positive is
begin -- Adjusted
Find : for C in reverse 1 .. Column loop
if Valid (Row) (C) then
return C;
end if;
end loop Find;
raise Program_Error;
end Adjusted;
procedure Break (Desired : in Boolean; Row : in Positive; Column : in Positive) is
-- Empty
begin -- Break
if Desired then
Form (Row, Column).New_Line;
end if;
end Break;
function New_Audio_Player (Row : Positive := 1;
Column : Positive := 1;
Break_Before : Boolean := False;
Source : String := "";
Controls : Boolean := True)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Audio_Player);
begin -- New_Audio_Player
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Audio := new Gnoga.Gui.Element.Multimedia.Audio_Type;
Widget.Audio.Create (Parent => Form (Row, Adjusted (Row, Column) ),
Source => Source,
Controls => Controls,
Preload => True,
ID => ID.Value'Image);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Audio_Player;
function New_Background_Text (Row : Positive := 1; Column : Positive := 1; Text : String := ""; Break_Before : Boolean := False)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Background_Text);
begin -- New_Background_Text
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Background := new Gnoga.Gui.Element.Common.Span_Type;
Widget.Background.Create (Parent => Form (Row, Adjusted (Row, Column) ), Content => Text, ID => ID.Value'Image);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Background_Text;
function New_Button (Row : Positive := 1; Column : Positive := 1; Text : String := ""; Break_Before : Boolean := False)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Button);
begin -- New_Button
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Switch := new Gnoga.Gui.Element.Common.Button_Type;
Widget.Switch.Create (Parent => Form (Row, Adjusted (Row, Column) ), Content => Text, ID => ID.Value'Image);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Button;
function New_Check_Box (Row : Positive := 1;
Column : Positive := 1;
Label : String := "";
Break_Before : Boolean := False;
Active : Boolean := False)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Check_Box);
begin -- New_Check_Box
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Check := new Gnoga.Gui.Element.Form.Check_Box_Type;
Widget.Check.Create (Form => Form (Row, Adjusted (Row, Column) ), ID => ID.Value'Image);
Widget.Check.Checked (Value => Active);
Widget.Check_Label := new Gnoga.Gui.Element.Form.Label_Type;
Widget.Check_Label.Create
(Form => Form (Row, Adjusted (Row, Column) ), Label_For => Widget.Check.all, Content => Label, Auto_Place => False);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Check_Box;
function New_Graphic_Area
(Row : Positive := 1; Column : Positive := 1; Width : Positive; Height : Positive; Break_Before : Boolean := False)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Graphic_Area);
begin -- New_Graphic_Area
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Canvas := new Gnoga.Gui.Element.Canvas.Canvas_Type;
Widget.Canvas.Create (Parent => Form (Row, Adjusted (Row, Column) ), Width => Width, Height => Height, ID => ID.Value'Image);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Graphic_Area;
function New_Password_Box (Row : Positive := 1;
Column : Positive := 1;
Text : String := "";
Break_Before : Boolean := False;
Label : String := "";
Width : Positive := 20)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Password_Box);
begin -- New_Password_Box
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Password := new Gnoga.Gui.Element.Form.Password_Type;
Widget.Password.Create (Form => Form (Row, Adjusted (Row, Column) ), Size => Width, Value => Text, ID => ID.Value'Image);
Widget.Password_Label := new Gnoga.Gui.Element.Form.Label_Type;
Widget.Password_Label.Create
(Form => Form (Row, Adjusted (Row, Column) ), Label_For => Widget.Password.all, Content => Label);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Password_Box;
use Ada.Strings.Unbounded;
Next_Button : Positive := 1;
function New_Radio_Buttons (Row : Positive := 1;
Column : Positive := 1;
Label : Text_List;
Break_Before : Boolean := False;
Orientation : Orientation_ID := Vertical)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Radio_Buttons);
Name : String := Next_Button'Image;
begin -- New_Radio_Buttons
Name (Name'First) := 'R';
Next_Button := Next_Button + 1;
Widget.Radio := new Radio_List (Label'Range);
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
All_Buttons : for I in Label'Range loop
Widget.Radio (I).Button.Create (Form => Form (Row, Adjusted (Row, Column) ),
Checked => I = Label'First,
Name => Name,
ID => I'Image & 'R' & ID.Value'Image);
Widget.Radio (I).Label.Create (Form => Form (Row, Adjusted (Row, Column) ),
Label_For => Widget.Radio (I).Button,
Content => To_String (Label (I) ),
Auto_Place => False);
if I < Label'Last and Orientation = Vertical then
Form (Row, Adjusted (Row, Column) ).New_Line;
end if;
end loop All_Buttons;
Widget_List.Append (New_Item => Widget);
return ID;
end New_Radio_Buttons;
function New_Selection_List (Row : Positive := 1;
Column : Positive := 1;
Text : Text_List := (1 .. 0 => <>);
Break_Before : Boolean := False;
Height : Positive := 1;
Multiple_Select : Boolean := False)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Selection_List);
begin -- New_Selection_List
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Selector := new Gnoga.Gui.Element.Form.Selection_Type;
Widget.Selector.Create (Form => Form (Row, Adjusted (Row, Column) ),
Multiple_Select => Multiple_Select,
Visible_Lines => Height,
ID => ID.Value'Image);
Widget.Multi := Multiple_Select;
Widget_List.Append (New_Item => Widget);
Add_Options : for I in Text'Range loop
Widget.Selector.Add_Option (Value => To_String (Text (I) ), Text => To_String (Text (I) ) );
end loop Add_Options;
return ID;
end New_Selection_List;
function New_Text_Area (Row : Positive := 1;
Column : Positive := 1;
Text : String := "";
Break_Before : Boolean := False;
Width : Positive := 20;
Height : Positive := 2)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Text_Area);
begin -- New_Text_Area
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Area := new Gnoga.Gui.Element.Form.Text_Area_Type;
Widget.Area.Create
(Form => Form (Row, Adjusted (Row, Column) ), Columns => Width, Rows => Height, Value => Text, ID => ID.Value'Image);
Widget_List.Append (New_Item => Widget);
return ID;
end New_Text_Area;
function New_Text_Box (Row : Positive := 1;
Column : Positive := 1;
Text : String := "";
Break_Before : Boolean := False;
Label : String := "";
Placeholder : String := "";
Width : Positive := 20)
return Widget_ID is
ID : constant Widget_ID := (Value => Widget_List.Last_Index + 1);
Widget : Widget_Info (Kind => Text_Box);
begin -- New_Text_Box
Break (Desired => Break_Before, Row => Row, Column => Adjusted (Row, Column) );
Widget.Box := new Gnoga.Gui.Element.Form.Text_Type;
Widget.Box.Create (Form => Form (Row, Adjusted (Row, Column) ), Size => Width, Value => Text, ID => ID.Value'Image);
Widget.Box_Label := new Gnoga.Gui.Element.Form.Label_Type;
Widget.Box_Label.Create (Form => Form (Row, Adjusted (Row, Column) ), Label_For => Widget.Box.all, Content => Label);
if Placeholder /= "" then
Widget.Box.Place_Holder (Value => Placeholder);
end if;
Widget_List.Append (New_Item => Widget);
return ID;
end New_Text_Box;
procedure Set_Title (Title : in String) is
-- Empty
begin -- Set_Title
Window.Document.Title (Value => Title);
end Set_Title;
procedure Show_Message_Box (Text : in String) is
-- Empty
begin -- Show_Message_Box
Window.Alert (Message => Text);
end Show_Message_Box;
protected File_Selection_Control is -- Controls multiple calls to Selected_File and calls to Next_Event while a call to
procedure Set_Selecting (Value : in Boolean); -- Selected_File is in progress
-- Makes Selecting return Value
function Selecting return Boolean;
-- Returns the last value passed to Set_Selecting; False initially
entry Block;
-- Blocks the caller until not Selecting
private -- File_Selection_Control
In_Progress : Boolean := False;
end File_Selection_Control;
function Next_Event (Timeout : Duration := Duration'Last) return Next_Result_Info is separate;
procedure Set_Visibility (ID : in Widget_ID; Visible : in Boolean := True) is
Widget : Widget_Info renames Widget_List (ID.Value);
begin -- Set_Visibility
case Widget.Kind is
when Audio_Player =>
Widget.Audio.Visible (Value => Visible);
when Background_Text =>
Widget.Background.Visible (Value => Visible);
when Button =>
Widget.Switch.Visible (Value => Visible);
when Check_Box =>
Widget.Check.Visible (Value => Visible);
Widget.Check_Label.Visible (Value => Visible);
when Graphic_Area =>
Widget.Canvas.Visible (Value => Visible);
when Password_Box =>
Widget.Password.Visible (Value => Visible);
Widget.Password_Label.Visible (Value => Visible);
when Radio_Buttons =>
All_Buttons : for I in Widget.Radio'Range loop
Widget.Radio (I).Button.Visible (Value => Visible);
Widget.Radio (I).Label.Visible (Value => Visible);
end loop All_Buttons;
when Selection_List =>
Widget.Selector.Visible (Value => Visible);
when Text_Area =>
Widget.Area.Visible (Value => Visible);
when Text_Box =>
Widget.Box.Visible (Value => Visible);
Widget.Box_Label.Visible (Value => Visible);
end case;
end Set_Visibility;
function Selected_File (Initial_Directory : in String := ".") return File_Result_Info is separate;
protected body File_Selection_Control is
procedure Set_Selecting (Value : in Boolean) is
-- Empty
begin -- Set_Selecting
In_Progress := Value;
end Set_Selecting;
function Selecting return Boolean is (In_Progress);
entry Block when not In_Progress is
-- Empty
begin -- Block
null;
end Block;
end File_Selection_Control;
procedure Set_Source (ID : in Widget_ID; Source : in String) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Source
Widget.Audio.Media_Source (Source => Source);
end Set_Source;
function Source (ID : Widget_ID) return String is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Source
return Widget.Audio.Media_Source;
end Source;
function Ready (ID : Widget_ID) return Boolean is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Ready
return Widget.Audio.Ready_To_Play;
end Ready;
procedure Play (ID : in Widget_ID) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Play
Widget.Audio.Play;
end Play;
procedure Pause (ID : in Widget_ID) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Pause
Widget.Audio.Pause;
end Pause;
function Paused (ID : Widget_ID) return Boolean is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Paused
return Widget.Audio.Paused;
end Paused;
function Playback_Ended (ID : Widget_ID) return Boolean is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Playback_Ended
return Widget.Audio.Playback_Ended;
end Playback_Ended;
function Length (ID : Widget_ID) return Float is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Length
return Widget.Audio.Media_Duration;
end Length;
procedure Set_Position (ID : in Widget_ID; Position : in Float) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Position
Widget.Audio.Media_Position (Seconds => Position);
end Set_Position;
function Position (ID : Widget_ID) return Float is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Position
return Widget.Audio.Media_Position;
end Position;
procedure Set_Text (ID : in Widget_ID; Text : in String) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Text
case Widget.Kind is
when Background_Text =>
Widget.Background.Text (Value => Text);
when Button =>
Widget.Switch.Text (Value => Text);
when Password_Box =>
Widget.Password.Value (Value => Text);
when Text_Area =>
Widget.Area.Value (Value => Text);
when Text_Box =>
Widget.Box.Value (Value => Text);
when others =>
raise Program_Error;
end case;
end Set_Text;
procedure Set_Text_Aligbnment (ID : in Widget_ID; Alignment : in Alignment_ID) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Text_Aligbnment
case Widget.Kind is
when Background_Text =>
Widget.Background.Text_Alignment (Value => Converted (Alignment) );
when Button =>
Widget.Switch.Text_Alignment (Value => Converted (Alignment) );
when Password_Box =>
Widget.Password.Text_Alignment (Value => Converted (Alignment) );
when Selection_List =>
Widget.Selector.Text_Alignment (Value => Converted (Alignment) );
when Text_Area =>
Widget.Area.Text_Alignment (Value => Converted (Alignment) );
when Text_Box =>
Widget.Box.Text_Alignment (Value => Converted (Alignment) );
when others =>
raise Program_Error;
end case;
end Set_Text_Aligbnment;
procedure Set_Text_Font_Kind (ID : in Widget_ID; Kind : in Font_Kind_ID) is
function Family return String is
(if Kind = Proportional then "sans-serif" else "monospace");
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Text_Font_Kind
case Widget.Kind is
when Background_Text =>
Widget.Background.Font (Family => Family);
when Button =>
Widget.Switch.Font (Family => Family);
when Password_Box =>
Widget.Password.Font (Family => Family);
when Selection_List =>
Widget.Selector.Font (Family => Family);
when Text_Area =>
Widget.Area.Font (Family => Family);
when Text_Box =>
Widget.Box.Font (Family => Family);
when others =>
raise Program_Error;
end case;
end Set_Text_Font_Kind;
function Multiple_Select (ID : Widget_ID) return Boolean is (Widget_List (ID.Value).Element.Multi);
function Text (ID : Widget_ID) return String is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Text
case Widget.Kind is
when Background_Text =>
return Widget.Background.Text;
when Button =>
return Widget.Switch.Text;
when Password_Box =>
return Widget.Password.Value;
when Selection_List =>
return Widget.Selector.Value;
when Text_Area =>
return Widget.Area.Value;
when Text_Box =>
return Widget.Box.Value;
when others =>
raise Program_Error;
end case;
end Text;
procedure Set_Active (ID : in Widget_ID; Active : in Boolean) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Active
Widget.Check.Checked (Value => Active);
end Set_Active;
function Active (ID : Widget_ID) return Boolean is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Active
return Widget.Check.Checked;
end Active;
function AG_Color (Color : Gnoga.RGBA_Type) return Color_Info is
(Red => RGB_Value (Color.Red),
Green => RGB_Value (Color.Green),
Blue => RGB_Value (Color.Blue),
Alpha => Alpha_Value (Color.Alpha) );
function To_Color (Color : Color_ID) return Color_Info is
(AG_Color (Gnoga.Colors.To_RGBA (Gnoga.Colors.Color_Enumeration'Val (Color_ID'Pos (Color) ) ) ) );
function Gnoga_Color (Color : Color_Info) return Gnoga.RGBA_Type is
(Red => Gnoga.Color_Type (Color.Red),
Green => Gnoga.Color_Type (Color.Green),
Blue => Gnoga.Color_Type (Color.Blue),
Alpha => Gnoga.Alpha_Type (Color.Alpha) );
function To_ID (Color : Color_Info) return Color_ID is
(Color_ID'Val (Gnoga.Colors.Color_Enumeration'Pos (Gnoga.Colors.To_Color_Enumeration (Gnoga_Color (Color) ) ) ) );
function Gnoga_Pixel (Color : Color_Info) return Gnoga.Pixel_Type is
(Red => Gnoga.Color_Type (Color.Red),
Green => Gnoga.Color_Type (Color.Green),
Blue => Gnoga.Color_Type (Color.Blue),
Alpha => Gnoga.Color_Type (255.0 * Color.Alpha) );
procedure Set_Background_Color (Color : in Color_Info) is
-- Empty
begin -- Set_Background_Color
View.Background_Color (RGBA => Gnoga_Color (Color) );
All_Rows : for Row in Form'Range (1) loop
All_Columns : for Column in Form'Range (2) loop
if Valid (Row) (Column) then
Form (Row, Column).Background_Color (RGBA => Gnoga_Color (Color) );
end if;
end loop All_Columns;
end loop All_Rows;
end Set_Background_Color;
procedure Set_Background_Color (ID : Widget_ID; Color : in Color_Info := To_Color (Black) ) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Background_Color
case Widget.Kind is
when Audio_Player =>
Widget.Audio.Background_Color (RGBA => Gnoga_Color (Color) );
when Background_Text =>
Widget.Background.Background_Color (RGBA => Gnoga_Color (Color) );
when Button =>
Widget.Switch.Background_Color (RGBA => Gnoga_Color (Color) );
when Check_Box =>
Widget.Check.Background_Color (RGBA => Gnoga_Color (Color) );
Widget.Check_Label.Background_Color (RGBA => Gnoga_Color (Color) );
when Graphic_Area =>
Widget.Canvas.Background_Color (RGBA => Gnoga_Color (Color) );
when Password_Box =>
Widget.Password.Background_Color (RGBA => Gnoga_Color (Color) );
Widget.Password_Label.Background_Color (RGBA => Gnoga_Color (Color) );
when Radio_Buttons =>
All_Buttons : for I in Widget.Radio'Range loop
Widget.Radio (I).Button.Background_Color (RGBA => Gnoga_Color (Color) );
Widget.Radio (I).Label.Background_Color (RGBA => Gnoga_Color (Color) );
end loop All_Buttons;
when Selection_List =>
Widget.Selector.Background_Color (RGBA => Gnoga_Color (Color) );
when Text_Area =>
Widget.Area.Background_Color (RGBA => Gnoga_Color (Color) );
when Text_Box =>
Widget.Box.Background_Color (RGBA => Gnoga_Color (Color) );
Widget.Box_Label.Background_Color (RGBA => Gnoga_Color (Color) );
end case;
end Set_Background_Color;
procedure Set_Foreground_Color (ID : Widget_ID; Color : in Color_Info := To_Color (Black) ) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Foreground_Color
case Widget.Kind is
when Audio_Player =>
Widget.Audio.Color (RGBA => Gnoga_Color (Color) );
when Background_Text =>
Widget.Background.Color (RGBA => Gnoga_Color (Color) );
when Button =>
Widget.Switch.Color (RGBA => Gnoga_Color (Color) );
when Check_Box =>
Widget.Check.Color (RGBA => Gnoga_Color (Color) );
Widget.Check_Label.Color (RGBA => Gnoga_Color (Color) );
when Graphic_Area =>
Widget.Canvas.Color (RGBA => Gnoga_Color (Color) );
when Password_Box =>
Widget.Password.Color (RGBA => Gnoga_Color (Color) );
Widget.Password_Label.Color (RGBA => Gnoga_Color (Color) );
when Radio_Buttons =>
All_Buttons : for I in Widget.Radio'Range loop
Widget.Radio (I).Button.Color (RGBA => Gnoga_Color (Color) );
Widget.Radio (I).Label.Color (RGBA => Gnoga_Color (Color) );
end loop All_Buttons;
when Selection_List =>
Widget.Selector.Color (RGBA => Gnoga_Color (Color) );
when Text_Area =>
Widget.Area.Color (RGBA => Gnoga_Color (Color) );
when Text_Box =>
Widget.Box.Color (RGBA => Gnoga_Color (Color) );
Widget.Box_Label.Color (RGBA => Gnoga_Color (Color) );
end case;
end Set_Foreground_Color;
procedure Set_Pixel (ID : in Widget_ID; X : in Integer; Y : in Integer; Color : in Color_Info := To_Color (Black) ) is
G_Color : constant Gnoga.Pixel_Type := Gnoga_Pixel (Color);
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Set_Pixel
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Pixel (X => X, Y => Y, Color => G_Color);
end Set_Pixel;
function AG_Color (Color : Gnoga.Pixel_Type) return Color_Info is
(Red => RGB_Value (Color.Red),
Green => RGB_Value (Color.Green),
Blue => RGB_Value (Color.Blue),
Alpha => Float (Color.Alpha) / 255.0);
function Pixel (ID : Widget_ID; X : Integer; Y : Integer) return Color_Info is
Widget : constant Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
G_Color : Gnoga.Pixel_Type;
begin -- Pixel_Type
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
G_Color := Context.Pixel (X, Y);
return AG_Color (G_Color);
end Pixel;
procedure Draw_Line (ID : in Widget_ID;
From_X : in Integer;
From_Y : in Integer;
To_X : in Integer;
To_Y : in Integer;
Width : in Positive := 1;
Color : in Color_Info := To_Color (Black) )
is
G_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Color);
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Draw_Line
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Stroke_Color (Value => G_Color);
Context.Line_Width (Value => Width);
Context.Begin_Path;
Context.Move_To (X => From_X, Y => From_Y);
Context.Line_To (X => To_X, Y => To_Y);
Context.Stroke;
end Draw_Line;
procedure Draw_Rectangle (ID : in Widget_ID;
From_X : in Integer;
From_Y : in Integer;
To_X : in Integer;
To_Y : in Integer;
Line_Color : in Optional_Color := (None => False, Color => To_Color (Black) );
Fill_Color : in Optional_Color := (None => True) )
is
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Draw_Rectangle
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Line_Width (Value => 1);
Context.Begin_Path;
Context.Rectangle (Rectangle => (X => Integer'Min (From_X, To_X),
Y => Integer'Min (From_Y, To_Y),
Width => abs (From_X - To_X) + 1,
Height => abs (From_Y - To_Y) + 1) );
if not Fill_Color.None then
Convert_Fill : declare
F_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Fill_Color.Color);
begin -- Convert_Fill
Context.Fill_Color (Value => F_Color);
Context.Fill;
end Convert_Fill;
end if;
if not Line_Color.None then
Convert_Line : declare
L_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Line_Color.Color);
begin -- Convert_Line
Context.Stroke_Color (Value => L_Color);
Context.Stroke;
end Convert_Line;
end if;
end Draw_Rectangle;
procedure Draw_Arc (ID : in Widget_ID;
X : in Integer;
Y : in Integer;
Radius : in Positive;
Start : in Float;
Stop : in Float;
Counter_Clockwise : in Boolean := False;
Line_Color : in Optional_Color := (None => False, Color => To_Color (Black) );
Fill_Color : in Optional_Color := (None => True) )
is
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Draw_Arc
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Line_Width (Value => 1);
Context.Begin_Path;
if not Fill_Color.None then
Context.Move_To (X => X, Y => Y);
Context.Line_To (X => X + Integer (Float (Radius) * Ada.Numerics.Elementary_Functions.Cos (Start) ),
Y => Y + Integer (Float (Radius) * Ada.Numerics.Elementary_Functions.Sin (Start) ) );
end if;
Context.Arc_Radians
(X => X, Y => Y, Radius => Radius, Starting_Angle => Start, Ending_Angle => Stop, Counter_Clockwise => Counter_Clockwise);
if not Fill_Color.None then
Convert_Fill : declare
F_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Fill_Color.Color);
begin -- Convert_Fill
Context.Close_Path;
Context.Fill_Color (Value => F_Color);
Context.Fill;
end Convert_Fill;
end if;
if not Line_Color.None then
Convert_Line : declare
L_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Line_Color.Color);
begin -- Convert_Line
Context.Stroke_Color (Value => L_Color);
Context.Stroke;
end Convert_Line;
end if;
end Draw_Arc;
procedure Draw_Text (ID : in Widget_ID;
X : in Integer;
Y : in Integer;
Text : in String;
Height : in Positive := 20;
Line_Color : in Optional_Color := (None => True);
Fill_Color : in Optional_Color := (None => False, Color => To_Color (Black) ) )
is
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Draw_Text
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Font (Height => Height'Image & "px");
Context.Line_Width (Value => 1);
if not Fill_Color.None then
Convert_Fill : declare
F_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Fill_Color.Color);
begin -- Convert_Fill
Context.Fill_Color (Value => F_Color);
Context.Fill_Text (Text => Text, X => X, Y => Y);
end Convert_Fill;
end if;
if not Line_Color.None then
Convert_Line : declare
L_Color : constant Gnoga.RGBA_Type := Gnoga_Color (Line_Color.Color);
begin -- Convert_Line
Context.Stroke_Color (Value => L_Color);
Context.Stroke_Text (Text => Text, X => X, Y => Y);
end Convert_Line;
end if;
end Draw_Text;
procedure Replace_Pixels (ID : in Widget_ID; Image : in Widget_ID; X : in Integer; Y : in Integer) is
Widget : Widget_Info := Widget_List (ID.Value);
Context : Gnoga.Gui.Element.Canvas.Context_2D.Context_2D_Type;
begin -- Replace_Pixels
Context.Get_Drawing_Context_2D (Canvas => Widget.Canvas.all);
Context.Draw_Image (Image => Widget_List (Image.Value).Canvas.all, X => X, Y => Y);
end Replace_Pixels;
function Num_Buttons (ID : Widget_ID) return Positive is
(Widget_List (ID.Value).Radio'Length);
procedure Set_Active (ID : in Widget_ID; Index : in Positive; Active : in Boolean) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Active
Widget.Radio (Index).Button.Checked (Value => Active);
end Set_Active;
function Active (ID : Widget_ID; Index : Positive) return Boolean is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Active
return Widget.Radio (Index).Button.Checked;
end Active;
function Active (ID : Widget_ID) return Positive is
Widget : constant Widget_Info := Widget_List (ID.Value);
begin -- Active
Check : for I in Widget.Radio'Range loop
if Widget.Radio (I).Button.Checked then
return I;
end if;
end loop Check;
return Widget.Radio'Length + 1;
end Active;
function Length (ID : Widget_ID) return Natural is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Length
return Widget.Selector.Length;
end Length;
procedure Clear (ID : in Widget_ID) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Clear
Widget.Selector.Empty_Options;
end Clear;
procedure Set_Selected (ID : in Widget_ID; Index : in Positive; Selected : in Boolean := True) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Set_Selected
Widget.Selector.Selected (Index => Index, Value => Selected);
end Set_Selected;
function Selected (ID : Widget_ID) return Natural is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Selected
return Widget.Selector.Selected_Index;
end Selected;
function Selected (ID : Widget_ID; Index : Positive) return Boolean is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Selected
return Widget.Selector.Selected (Index);
end Selected;
function Text (ID : Widget_ID; Index : Positive) return String is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Text
return Widget.Selector.all.Value (Index);
end Text;
procedure Insert (ID : in Widget_ID; Text : in String; Before : in Positive := Integer'Last) is
Widget : Widget_Info := Widget_List (ID.Value);
Index : constant Natural := (if Before > Widget.Selector.Length then 0 else Before);
begin -- Insert
Widget.Selector.Add_Option (Value => Text, Text => Text, Index => Index);
end Insert;
procedure Delete (ID : in Widget_ID; Index : in Positive) is
Widget : Widget_Info := Widget_List (ID.Value);
begin -- Delete
Widget.Selector.Remove_Option (Index => Index);
end Delete;
procedure End_GUI is
-- Empty
begin -- End_GUI
Gnoga.Application.End_Application;
Setup := False;
end End_GUI;
end Ada_Gui;
|
30,767
|
ada
| 7
|
Fabien-Chouteau/Giza
|
gtkada_backend/example/engine_control_ui.adb
|
<filename>gtkada_backend/example/engine_control_ui.adb<gh_stars>1-10
with Giza.Colors; use Giza.Colors;
with Giza.GUI; use Giza.GUI;
with Engine_Control_Events; use Engine_Control_Events;
package body Engine_Control_UI is
Set_PP_Evt : aliased Set_PP_Event;
-------------
-- On_Init --
-------------
procedure On_Init (This : in out Engine_Control_Window) is
begin
This.RPM_Widget := new RPM;
This.RPM_Widget.Set_Background (White);
This.RPM_Widget.Set_Foreground (Black);
This.RPM_Widget.Disable_Frame;
This.RPM_Widget.Set_Size ((This.Get_Size.W - 2, 38));
This.Add_Child (This.RPM_Widget, (1, 1));
This.PP := new PP_Widget;
This.PP.Set_Background (White);
This.PP.Set_Foreground (Red);
This.PP.Disable_Frame;
This.PP.Set_Size ((This.Get_Size.W - 2, 160));
This.Add_Child (This.PP, (1, 41));
This.Tabs := new Gtabs (2);
This.Tabs.Set_Size ((This.Get_Size.W, 116));
This.Manual := new Composite_Widget;
This.Auto := new Composite_Widget;
This.Tabs.Set_Tab (1, "MANUAL", This.Manual);
This.Tabs.Set_Tab (2, "AUTO", This.Auto);
This.Add_Child (This.Tabs, (0, 202));
This.Ignition := new Gnumber_Select;
This.Ignition.Set_Size ((This.Get_Size.W, 42));
This.Ignition.Set_Label ("Ignition");
This.Ignition.Set_Min (0);
This.Ignition.Set_Max (100);
This.Ignition.Set_Step (5);
This.Ignition.Set_Value (25);
This.Duration := new Gnumber_Select;
This.Duration.Set_Size ((This.Get_Size.W, 42));
This.Duration.Set_Label ("Duration");
This.Duration.Set_Min (0);
This.Duration.Set_Max (100);
This.Duration.Set_Step (5);
This.Duration.Set_Value (50);
This.Manual.Add_Child (This.Ignition, (0, 0));
This.Manual.Add_Child (This.Duration, (0, 43));
This.Tabs.Set_Selected (1);
This.Target_RPM := new Gnumber_Select;
This.Target_RPM.Set_Label ("Target RPM");
This.Target_RPM.Set_Size ((This.Get_Size.W, 85));
This.Target_RPM.Set_Min (200);
This.Target_RPM.Set_Max (2500);
This.Target_RPM.Set_Step (100);
This.Target_RPM.Set_Value (1500);
This.Target_RPM.Show_Value;
This.Auto.Add_Child (This.Target_RPM, (0, 0));
This.Background := new Gbackground;
This.Background.Set_Background (Black);
This.Background.Set_Size (This.Get_Size);
This.Add_Child (This.Background, (0, 0));
end On_Init;
------------------
-- On_Displayed --
------------------
procedure On_Displayed (This : in out Engine_Control_Window) is
begin
null;
end On_Displayed;
---------------
-- On_Hidden --
---------------
procedure On_Hidden (This : in out Engine_Control_Window) is
begin
null;
end On_Hidden;
-----------------------
-- On_Position_Event --
-----------------------
function On_Position_Event
(This : in out Engine_Control_Window;
Evt : Position_Event_Ref;
Pos : Point_T) return Boolean
is
begin
if Giza.Widgets.Composite.On_Position_Event
(Giza.Widgets.Composite.Composite_Widget (This), Evt, Pos)
then
Set_PP_Evt := (Ignition => This.Ignition.Value,
Duration => This.Duration.Value);
Giza.GUI.Emit (Set_PP_Evt'Access);
return True;
else
return False;
end if;
end On_Position_Event;
end Engine_Control_UI;
|
30,768
|
ada
| 1
|
faelys/natools-web
|
generated/natools-static_maps-web-comments-item_actions.ads
|
package Natools.Static_Maps.Web.Comments.Item_Actions is
pragma Pure;
function Hash (S : String) return Natural;
end Natools.Static_Maps.Web.Comments.Item_Actions;
|
30,769
|
ada
| 0
|
kisom/rover-mk1
|
src/hardware/hardware.adb
|
with AVR, AVR.MCU, AVR.Interrupts;
use AVR, AVR.MCU;
package body Hardware is
procedure Init_Timer1 is
begin
-- Enable Timer1 in the power-save register.
PRR0_Bits (PRTIM1_Bit) := High;
-- Normal WGM with prescaler of 8.
TCCR1A_Bits := (others => False);
TCCR1B_Bits := (CS11_Bit => True, others => False);
TCNT1 := 0; -- Clear timer counter.
TIFR1_Bits (OCF1A_Bit) := High; -- Clear pending interrupts.
TIMSK1_Bits (OCIE1A_Bit) := High; -- Enable output/compare interrupt.
end Init_Timer1;
procedure Init_Timer3 is
begin
-- Enable Timer3 in the power-save register.
PRR1_Bits (PRTIM3_Bit) := High;
-- Fast WGM with prescaler of 8.
TCCR3A_Bits := (others => False);
TCCR3B_Bits := (CS11_Bit => True, others => False);
TCNT3 := 0; -- Clear timer counter.
TIFR3_Bits (OCF3A_Bit) := High; -- Clear pending interrupts.
TIMSK3_Bits (OCIE3A_Bit) := High; -- Enable output/compare interrupt.
end Init_Timer3;
procedure Init is
begin
Init_Timer1;
Init_Timer3;
Interrupts.sei;
end Init;
end Hardware;
|
30,770
|
ada
| 0
|
reznikmm/gela
|
source/contexts/plain/program-plain_lexical_elements.adb
|
<gh_stars>0
-- SPDX-FileCopyrightText: 2019 <NAME> <<EMAIL>>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
package body Program.Plain_Lexical_Elements is
type Lexical_Element_Access is access Lexical_Element;
------------
-- Append --
------------
not overriding procedure Append
(Self : aliased in out Lexical_Element_Vector;
Span : Program.Source_Buffers.Span;
Kind : Program.Lexical_Elements.Lexical_Element_Kind;
Symbol : Program.Symbols.Symbol)
is
Item : constant Lexical_Element_Access := new Lexical_Element'
(Vector => Self'Unchecked_Access,
Span => Span,
Kind => Kind,
Symbol => Symbol);
begin
Self.Vector.Append
(Program.Lexical_Elements.Lexical_Element_Access (Item));
end Append;
-------------
-- Element --
-------------
overriding function Element
(Self : Lexical_Element_Vector;
Index : Positive)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Vector.Element (Index);
end Element;
----------
-- From --
----------
overriding function From
(Self : Lexical_Element) return Program.Lexical_Elements.Location
is
From_Line : Positive;
To_Line : Positive;
From_Column : Positive;
To_Column : Positive;
begin
Self.Vector.Buffer.Get_Span
(Self.Span, From_Line, To_Line, From_Column, To_Column);
return (From_Line, From_Column);
end From;
-----------
-- Image --
-----------
overriding function Image (Self : Lexical_Element) return Program.Text is
begin
return Self.Vector.Buffer.Text (Self.Span);
end Image;
----------
-- Kind --
----------
overriding function Kind (Self : Lexical_Element)
return Program.Lexical_Elements.Lexical_Element_Kind is
begin
return Self.Kind;
end Kind;
----------------
-- Last_Index --
----------------
overriding function Last_Index
(Self : Lexical_Element_Vector) return Positive is
begin
return Self.Vector.Last_Index;
end Last_Index;
------------
-- Symbol --
------------
function Symbol
(Self : Lexical_Element'Class) return Program.Symbols.Symbol is
begin
return Self.Symbol;
end Symbol;
end Program.Plain_Lexical_Elements;
|
30,771
|
ada
| 1
|
io7m/coreland-openal-ada
|
openal-context-error.ads
|
<gh_stars>1-10
package OpenAL.Context.Error is
type Error_t is
(No_Error,
Invalid_Device,
Invalid_Context,
Invalid_Enumeration,
Invalid_Value,
Out_Of_Memory,
Unknown_Error);
-- proc_map : alcGetError
function Get_Error (Device : in Device_t) return Error_t;
private
function Map_Constant_To_Error (Error : in Types.Enumeration_t) return Error_t;
end OpenAL.Context.Error;
|
30,772
|
ada
| 3
|
charlie5/aIDE
|
applet/aide/source/editors/aide-editor-of_record_type.adb
|
<filename>applet/aide/source/editors/aide-editor-of_record_type.adb
with
aIDE.Editor.of_record_component,
aIDE.GUI,
AdaM.record_Component,
glib.Error,
gtk.Builder,
gtk.Handlers;
with Ada.Text_IO; use Ada.Text_IO;
package body aIDE.Editor.of_record_type
is
use Gtk.Builder,
Glib,
glib.Error;
-- procedure on_index_type_Button_clicked (the_Entry : access Gtk_Button_Record'Class;
-- the_Editor : in aIDE.Editor.of_record_type.view)
-- is
-- begin
-- aIDE.GUI.show_types_Palette (Invoked_by => the_Entry.all'Access,
-- Target => the_Editor.Target.main_Type);
-- end on_index_type_Button_clicked;
procedure on_rid_Button_clicked (the_Button : access Gtk_Button_Record'Class;
the_Editor : in aIDE.Editor.of_record_type.view)
is
pragma Unreferenced (the_Editor);
begin
the_Button.get_Parent.destroy;
end on_rid_Button_clicked;
package Entry_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Entry_Record,
Boolean,
AdaM.a_Type.record_type.view);
package Button_Callbacks is new Gtk.Handlers.User_Callback (Gtk_Button_Record,
aIDE.Editor.of_record_type.view);
function on_unconstrained_Label_clicked (the_Label : access Gtk_Label_Record'Class;
Self : in aIDE.Editor.of_record_type.view) return Boolean
is
pragma Unreferenced (the_Label);
begin
-- Self.Target.is_Constrained;
Self.freshen;
return False;
end on_unconstrained_Label_clicked;
function on_constrained_Label_clicked (the_Label : access Gtk_Label_Record'Class;
Self : in aIDE.Editor.of_record_type.view) return Boolean
is
pragma Unreferenced (the_Label);
begin
-- Self.Target.is_Constrained (Now => False);
Self.freshen;
return False;
end on_constrained_Label_clicked;
package Label_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Label_Record,
Boolean,
aIDE.Editor.of_record_type.view);
package body Forge
is
function to_Editor (the_Target : in AdaM.a_Type.record_type.view) return View
is
use AdaM,
Glib;
Self : constant Editor.of_record_type.view := new Editor.of_record_type.item;
the_Builder : Gtk_Builder;
Error : aliased GError;
Result : Guint;
pragma Unreferenced (Result);
begin
Self.Target := the_Target;
Gtk_New (the_Builder);
Result := the_Builder.Add_From_File ("glade/editor/record_type_editor.glade", Error'Access);
if Error /= null then
raise Program_Error with "Error: adam.Editor.of_record_type ~ " & Get_Message (Error);
end if;
Self.top_Box := gtk_Box (the_Builder.get_Object ("top_Box"));
Self.name_Entry := Gtk_Entry (the_Builder.get_Object ("name_Entry"));
Self.is_Label := Gtk_Label (the_Builder.get_Object ("is_Label"));
Self.record_Label := Gtk_Label (the_Builder.get_Object ("record_Label"));
Self.components_Box := gtk_Box (the_Builder.get_Object ("components_Box"));
Self.null_Label := Gtk_Label (the_Builder.get_Object ("null_Label"));
Self.end_record_Label := Gtk_Label (the_Builder.get_Object ("end_record_Label"));
Self.rid_Button := gtk_Button (the_Builder.get_Object ("rid_Button"));
Self.name_Entry.set_Text (String (Self.Target.Name));
-- Entry_return_Callbacks.connect (Self.first_Entry,
-- "focus-out-event",
-- on_first_Entry_leave'Access,
-- the_Target);
--
-- Self.last_Entry.set_Text (Self.Target.Last);
--
-- Entry_return_Callbacks.connect (Self.last_Entry,
-- "focus-out-event",
-- on_last_Entry_leave'Access,
-- the_Target);
-- Self.type_Button.set_Label (+Self.Target.main_Type.Name);
--
-- button_Callbacks.connect (Self.type_Button,
-- "clicked",
-- on_index_type_Button_clicked'Access,
-- Self);
-- Button_Callbacks.Connect (Self.rid_Button,
-- "clicked",
-- on_rid_Button_clicked'Access,
-- Self);
-- Label_return_Callbacks.Connect (Self.unconstrained_Label,
-- "button-release-event",
-- on_unconstrained_Label_clicked'Access,
-- Self);
--
-- Label_return_Callbacks.Connect (Self.constrained_Label,
-- "button-release-event",
-- on_constrained_Label_clicked'Access,
-- Self);
Self.freshen;
return Self;
end to_Editor;
end Forge;
procedure destroy_Callback (Widget : not null access Gtk.Widget.Gtk_Widget_Record'Class)
is
begin
Widget.destroy;
end destroy_Callback;
overriding
procedure freshen (Self : in out Item)
is
use gtk.Widget;
-- the_Literals : AdaM.a_Type.enumeration_literal.vector renames Self.Target.Literals;
-- literal_Editor : aIDE.Editor.of_enumeration_literal.view;
Children : AdaM.Entity.Entities renames Self.Target.Children.all;
begin
if Children.is_Empty
then
Self.null_Label.show;
else
Self.null_Label.hide;
end if;
for Each of Children
loop
declare
Child : constant AdaM.record_Component.view := AdaM.record_Component.view (Each);
new_Editor : constant aIDE.Editor.of_record_component.view := Editor.of_record_component.Forge.new_Editor (the_target => Child);
begin
Self.components_Box.pack_Start (new_Editor.top_Widget);
end;
end loop;
-- if Self.is_in_unconstrained_Array
-- then
-- Self.unconstrained_Label.show;
--
-- Self.first_Entry.hide;
-- Self.last_Entry.hide;
-- Self.range_Label.show;
-- Self. constrained_Label.hide;
-- else
-- Self.unconstrained_Label.hide;
-- end if;
-- if Self.is_in_unconstrained_Array
-- then
-- Self.unconstrained_Label.show;
--
-- Self.first_Entry.hide;
-- Self.last_Entry.hide;
-- Self.range_Label.show;
-- Self. constrained_Label.hide;
-- else
-- Self.unconstrained_Label.hide;
--
-- if Self.Target.is_Constrained
-- then
-- Self.range_Label.show;
-- Self. constrained_Label.show;
-- Self.first_Entry.show;
-- Self.last_Entry.show;
-- else
-- Self.range_Label.hide;
-- Self.first_Entry.hide;
-- Self.last_Entry.hide;
-- Self. constrained_Label.hide;
-- Self.unconstrained_Label.hide;
-- end if;
-- end if;
-- Self.first_Entry.set_Text (Self.Target.First);
-- Self.last_Entry .set_Text (Self.Target.Last);
-- Self.literals_Box.Foreach (destroy_Callback'Access);
-- for Each of the_Literals
-- loop
-- literal_Editor := Editor.of_enumeration_literal.Forge.to_Editor (Each,
-- targets_Parent => Self.Target.all'Access);
-- Self.literals_Box.pack_Start (literal_Editor.top_Widget);
-- end loop;
end freshen;
overriding
function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget
is
begin
return gtk.Widget.Gtk_Widget (Self.top_Box);
end top_Widget;
end aIDE.Editor.of_record_type;
|
30,773
|
ada
| 52
|
onox/orka
|
orka/src/gl/implementation/gl-objects-pipelines.adb
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2015 onox <<EMAIL>>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Ada.Unchecked_Conversion;
with GL.API;
with GL.Enums;
package body GL.Objects.Pipelines is
procedure Use_Program_Stages
(Object : Pipeline;
Stages : Stage_Bits;
Program : Programs.Program)
is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Source => Stage_Bits, Target => Low_Level.Bitfield);
Raw_Bits : constant Low_Level.Bitfield :=
Convert (Stages) and 2#0000000000111111#;
begin
API.Use_Program_Stages.Ref (Object.Reference.GL_Id, Raw_Bits, Program.Raw_Id);
end Use_Program_Stages;
procedure Bind (Object : Pipeline) is
begin
API.Use_Program.Ref (0);
API.Bind_Program_Pipeline.Ref (Object.Reference.GL_Id);
end Bind;
function Validate (Object : Pipeline) return Boolean is
Status_Value : Int := 0;
begin
API.Validate_Program_Pipeline.Ref (Object.Reference.GL_Id);
API.Get_Program_Pipeline_Param.Ref
(Object.Reference.GL_Id, Enums.Validate_Status, Status_Value);
return Status_Value /= 0;
end Validate;
function Info_Log (Object : Pipeline) return String is
Log_Length : Size := 0;
begin
API.Get_Program_Pipeline_Param.Ref
(Object.Reference.GL_Id, Enums.Info_Log_Length, Log_Length);
if Log_Length = 0 then
return "";
end if;
declare
Info_Log : String (1 .. Integer (Log_Length));
begin
API.Get_Program_Pipeline_Info_Log.Ref
(Object.Reference.GL_Id, Log_Length, Log_Length, Info_Log);
return Info_Log (1 .. Integer (Log_Length));
end;
end Info_Log;
overriding
procedure Initialize_Id (Object : in out Pipeline) is
New_Id : UInt := 0;
begin
API.Create_Program_Pipelines.Ref (1, New_Id);
Object.Reference.GL_Id := New_Id;
end Initialize_Id;
overriding
procedure Delete_Id (Object : in out Pipeline) is
begin
API.Delete_Program_Pipelines.Ref (1, (1 => Object.Reference.GL_Id));
Object.Reference.GL_Id := 0;
end Delete_Id;
end GL.Objects.Pipelines;
|
30,774
|
ada
| 0
|
Fabien-Chouteau/fsmaker
|
src/fsmaker-sink-hexdump.adb
|
<reponame>Fabien-Chouteau/fsmaker
with System.Storage_Elements; use System.Storage_Elements;
with Interfaces.C.Extensions; use Interfaces.C.Extensions;
with Interfaces; use Interfaces;
package body FSmaker.Sink.Hexdump is
------------
-- Create --
------------
function Create (Dst : not null Sink.Acc_Any) return Sink.Class is
begin
return Instance'(Dst => Dst, others => <>);
end Create;
-----------
-- Write --
-----------
function Write (This : in out Instance;
Addr : System.Address;
Len : Natural)
return Natural
is
---------
-- Put --
---------
procedure Put (Str : String) is
begin
if This.Dst.Write (Str'Address, Str'Length) /= Str'Length then
raise Program_Error with "hexdump write error";
end if;
end Put;
--------------
-- Put_Line --
--------------
procedure Put_Line (Str : String) is
begin
Put (Str & ASCII.LF);
end Put_Line;
--------------
-- Hex_Dump --
--------------
procedure Hex_Dump (Data : Storage_Array) is
function UInt8_To_Char (Val : Storage_Element) return Character;
procedure Start_New_Line;
-- Hexdump format:
-- 0000_0000_0000_0000: 57 69 6B 69 70 65 64 69 61 2C 20 74 68 65 20 66 Wikipedia, the f
-- Addr : ^^^^^^^^^^^^^^^^^^^^
-- Hex : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- ASCII: ^^^^^^^^^^^^^^^^^
Addr_Len : constant := 16 + 3 + 1;
Hex_Len : constant := 3 * 16;
ASCII_Len : constant := 1 + 16;
Str : String (1 .. Addr_Len + Hex_Len + ASCII_Len) := (others => ' ');
UInt4_To_Char : constant array (Unsigned_4) of Character
:= (0 => '0',
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => 'A',
11 => 'B',
12 => 'C',
13 => 'D',
14 => 'E',
15 => 'F');
-------------------
-- UInt8_To_Char --
-------------------
function UInt8_To_Char (Val : Storage_Element) return Character is
begin
case Val is
when 0 .. 31 | 127 .. 255 =>
return '.';
when others =>
return Character'Val (Val);
end case;
end UInt8_To_Char;
Index : Natural;
Cnt : Natural;
Addr : Natural := 0;
--------------------
-- Start_New_Line --
--------------------
procedure Start_New_Line is
Addr_Val : Interfaces.Unsigned_64 :=
Interfaces.Unsigned_64 (This.Addr + Addr);
begin
-- Address
for X in reverse 1 .. 19 loop
if X in 5 | 10 | 15 then
Str (X) := '_';
else
Str (X) := UInt4_To_Char (Unsigned_4 (Addr_Val and 16#0F#));
Addr_Val := Shift_Right (Addr_Val, 4);
end if;
end loop;
Str (20) := ':';
Str (21 .. Str'Last) := (others => ' ');
Cnt := 0;
Index := Str'First + Addr_Len;
end Start_New_Line;
begin
Start_New_Line;
for Elt of Data loop
-- Hex
Str (Index + 1) := UInt4_To_Char (Unsigned_4 (Shift_Right (Interfaces.Unsigned_8 (Elt), 4)));
Str (Index + 2) := UInt4_To_Char (Unsigned_4 (Elt and 16#0F#));
-- ASCII
Str (Str'Last - (15 - Cnt)) := UInt8_To_Char (Elt);
Index := Index + 3;
Cnt := Cnt + 1;
Addr := Addr + 1;
if Cnt = 16 then
Put_Line (Str);
Start_New_Line;
end if;
end loop;
if Cnt /= 0 then
Put_Line (Str);
end if;
This.Addr := This.Addr + Addr;
end Hex_Dump;
Data : Storage_Array (1 .. Storage_Offset (Len)) with Address => Addr;
begin
Hex_Dump (Data);
return Len;
end Write;
-----------
-- Close --
-----------
procedure Close (This : in out Instance) is
begin
This.Dst.Close;
end Close;
end FSmaker.Sink.Hexdump;
|
30,775
|
ada
| 0
|
iyan22/AprendeAda
|
ejercicios3/prueba_eliminar_tercer_elemento_ordenada.adb
|
<reponame>iyan22/AprendeAda
with Ada.Text_Io; use Ada.Text_Io;
with datos; use datos;
with eliminar_tercer_elemento_ordenada, escribir_lista;
procedure prueba_eliminar_tercer_elemento_ordenada is
-- este programa hace llamadas al subprograma eliminar_tercer_elemento
-- para comprobar si su funcionamiento es correcto
Lista1: Lista_Enteros;
begin
Lista1.Numeros(1) := 1;
Lista1.Numeros(2) := 2;
Lista1.Numeros(3) := 3;
Lista1.Numeros(4) := 4;
Lista1.Cont := 4;
put_line("Caso 1: lista de cuatro elementos: (1, 2, 3, 4)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 1 2 4 -1");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
-- faltan varios casos de prueba
Lista1.Numeros := (0, 5, 10, 15, 20, 25, 30, 35, 40, 45);
Lista1.Cont := 10;
put_line("Caso 1: lista de cuatro elementos: (0, 5, 10, 15, 20, 25, 30, 35, 40, 45)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 0 5 15 20 25 30 35 40 45 -1");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
Lista1.Numeros(1) := 1;
Lista1.Numeros(2) := 2;
Lista1.Cont := 2;
put_line("Caso 1: lista de cuatro elementos: (1, 2)");
put_line(" la lista inicial es: ");
escribir_lista(Lista1);
new_line;
put_line(" el resultado deberia de ser 1 2");
put_line("y la lista resultado es: ");
eliminar_tercer_elemento_ordenada(Lista1);
escribir_lista(Lista1);
new_line(3);
put_line("Pulsa return para continuar");
skip_line;
new_line(3);
end prueba_eliminar_tercer_elemento_ordenada;
|
30,776
|
ada
| 0
|
DrenfongWong/tkm-rpc
|
specs/ada/server/tkmrpc-contexts-isa.adb
|
<filename>specs/ada/server/tkmrpc-contexts-isa.adb
package body Tkmrpc.Contexts.isa
is
pragma Warnings
(Off, "* already use-visible through previous use type clause");
use type Types.isa_id_type;
use type Types.ae_id_type;
use type Types.ia_id_type;
use type Types.key_type;
use type Types.rel_time_type;
use type Types.duration_type;
pragma Warnings
(On, "* already use-visible through previous use type clause");
type isa_FSM_Type is record
State : isa_State_Type;
ae_id : Types.ae_id_type;
ia_id : Types.ia_id_type;
sk_d : Types.key_type;
creation_time : Types.rel_time_type;
max_rekey_age : Types.duration_type;
end record;
-- IKE SA Context
Null_isa_FSM : constant isa_FSM_Type
:= isa_FSM_Type'
(State => clean,
ae_id => Types.ae_id_type'First,
ia_id => Types.ia_id_type'First,
sk_d => Types.Null_key_type,
creation_time => Types.rel_time_type'First,
max_rekey_age => Types.duration_type'First);
type Context_Array_Type is
array (Types.isa_id_type) of isa_FSM_Type;
Context_Array : Context_Array_Type := Context_Array_Type'
(others => (Null_isa_FSM));
-------------------------------------------------------------------------
function Get_State
(Id : Types.isa_id_type)
return isa_State_Type
is
begin
return Context_Array (Id).State;
end Get_State;
-------------------------------------------------------------------------
function Has_ae_id
(Id : Types.isa_id_type;
ae_id : Types.ae_id_type)
return Boolean
is (Context_Array (Id).ae_id = ae_id);
-------------------------------------------------------------------------
function Has_creation_time
(Id : Types.isa_id_type;
creation_time : Types.rel_time_type)
return Boolean
is (Context_Array (Id).creation_time = creation_time);
-------------------------------------------------------------------------
function Has_ia_id
(Id : Types.isa_id_type;
ia_id : Types.ia_id_type)
return Boolean
is (Context_Array (Id).ia_id = ia_id);
-------------------------------------------------------------------------
function Has_max_rekey_age
(Id : Types.isa_id_type;
max_rekey_age : Types.duration_type)
return Boolean
is (Context_Array (Id).max_rekey_age = max_rekey_age);
-------------------------------------------------------------------------
function Has_sk_d
(Id : Types.isa_id_type;
sk_d : Types.key_type)
return Boolean
is (Context_Array (Id).sk_d = sk_d);
-------------------------------------------------------------------------
function Has_State
(Id : Types.isa_id_type;
State : isa_State_Type)
return Boolean
is (Context_Array (Id).State = State);
-------------------------------------------------------------------------
pragma Warnings
(Off, "condition can only be False if invalid values present");
function Is_Valid (Id : Types.isa_id_type) return Boolean
is (Context_Array'First <= Id and Id <= Context_Array'Last);
pragma Warnings
(On, "condition can only be False if invalid values present");
-------------------------------------------------------------------------
procedure create
(Id : Types.isa_id_type;
ae_id : Types.ae_id_type;
ia_id : Types.ia_id_type;
sk_d : Types.key_type;
creation_time : Types.rel_time_type)
is
begin
Context_Array (Id).ae_id := ae_id;
Context_Array (Id).ia_id := ia_id;
Context_Array (Id).sk_d := sk_d;
Context_Array (Id).creation_time := creation_time;
Context_Array (Id).State := active;
end create;
-------------------------------------------------------------------------
function get_ae_id
(Id : Types.isa_id_type)
return Types.ae_id_type
is
begin
return Context_Array (Id).ae_id;
end get_ae_id;
-------------------------------------------------------------------------
function get_sk_d
(Id : Types.isa_id_type)
return Types.key_type
is
begin
return Context_Array (Id).sk_d;
end get_sk_d;
-------------------------------------------------------------------------
procedure invalidate
(Id : Types.isa_id_type)
is
begin
Context_Array (Id).State := invalid;
end invalidate;
-------------------------------------------------------------------------
procedure reset
(Id : Types.isa_id_type)
is
begin
Context_Array (Id).ae_id := Types.ae_id_type'First;
Context_Array (Id).ia_id := Types.ia_id_type'First;
Context_Array (Id).sk_d := Types.Null_key_type;
Context_Array (Id).creation_time := Types.rel_time_type'First;
Context_Array (Id).max_rekey_age := Types.duration_type'First;
Context_Array (Id).State := clean;
end reset;
end Tkmrpc.Contexts.isa;
|
30,777
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Combinations/Ada/combinations-1.ada
|
<gh_stars>1-10
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Combinations is
generic
type Integers is range <>;
package Combinations is
type Combination is array (Positive range <>) of Integers;
procedure First (X : in out Combination);
procedure Next (X : in out Combination);
procedure Put (X : Combination);
end Combinations;
package body Combinations is
procedure First (X : in out Combination) is
begin
X (1) := Integers'First;
for I in 2..X'Last loop
X (I) := X (I - 1) + 1;
end loop;
end First;
procedure Next (X : in out Combination) is
begin
for I in reverse X'Range loop
if X (I) < Integers'Val (Integers'Pos (Integers'Last) - X'Last + I) then
X (I) := X (I) + 1;
for J in I + 1..X'Last loop
X (J) := X (J - 1) + 1;
end loop;
return;
end if;
end loop;
raise Constraint_Error;
end Next;
procedure Put (X : Combination) is
begin
for I in X'Range loop
Put (Integers'Image (X (I)));
end loop;
end Put;
end Combinations;
type Five is range 0..4;
package Fives is new Combinations (Five);
use Fives;
X : Combination (1..3);
begin
First (X);
loop
Put (X); New_Line;
Next (X);
end loop;
exception
when Constraint_Error =>
null;
end Test_Combinations;
|
30,778
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c3/c35003a.ada
|
<reponame>best08618/asylo<filename>gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c3/c35003a.ada
-- C35003A.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 CONSTRAINT_ERROR IS RAISED FOR AN INTEGER OR
-- ENUMERATION SUBTYPE INDICATION WHEN THE LOWER OR UPPER BOUND
-- OF A NON-NULL RANGE LIES OUTSIDE THE RANGE OF THE TYPE MARK.
-- HISTORY:
-- JET 01/25/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C35003A IS
TYPE ENUM IS (ZERO, ONE, TWO, THREE);
SUBTYPE SUBENUM IS ENUM RANGE ONE..TWO;
TYPE INT IS RANGE 1..10;
SUBTYPE SUBINT IS INTEGER RANGE -10..10;
TYPE A1 IS ARRAY (0..11) OF INTEGER;
TYPE A2 IS ARRAY (INTEGER RANGE -11..10) OF INTEGER;
BEGIN
TEST ("C35003A", "CHECK THAT CONSTRAINT_ERROR IS RAISED FOR AN " &
"INTEGER OR ENUMERATION SUBTYPE INDICATION " &
"WHEN THE LOWER OR UPPER BOUND OF A NON-NULL " &
"RANGE LIES OUTSIDE THE RANGE OF THE TYPE MARK");
BEGIN
DECLARE
SUBTYPE SUBSUBENUM IS SUBENUM RANGE ZERO..TWO;
BEGIN
FAILED ("NO EXCEPTION RAISED (E1)");
DECLARE
Z : SUBSUBENUM := ONE;
BEGIN
IF NOT EQUAL(SUBSUBENUM'POS(Z),SUBSUBENUM'POS(Z))
THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (E1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (E1)");
END;
BEGIN
DECLARE
TYPE A IS ARRAY (SUBENUM RANGE ONE..THREE) OF INTEGER;
BEGIN
FAILED ("NO EXCEPTION RAISED (E2)");
DECLARE
Z : A := (OTHERS => 0);
BEGIN
IF NOT EQUAL(Z(ONE),Z(ONE)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (E2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (E2)");
END;
BEGIN
DECLARE
TYPE I IS ACCESS INT RANGE INT(IDENT_INT(0))..10;
BEGIN
FAILED ("NO EXCEPTION RAISED (I1)");
DECLARE
Z : I := NEW INT'(1);
BEGIN
IF NOT EQUAL(INTEGER(Z.ALL),INTEGER(Z.ALL)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (I1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (I1)");
END;
BEGIN
DECLARE
TYPE I IS NEW INT RANGE 1..INT'SUCC(10);
BEGIN
FAILED ("NO EXCEPTION RAISED (I2)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (I2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (I2)");
END;
BEGIN
DECLARE
TYPE R IS RECORD
A : SUBINT RANGE IDENT_INT(-11)..0;
END RECORD;
BEGIN
FAILED ("NO EXCEPTION RAISED (S1)");
DECLARE
Z : R := (A => 1);
BEGIN
IF NOT EQUAL(INTEGER(Z.A),INTEGER(Z.A)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (S1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (S1)");
END;
BEGIN
DECLARE
Z : SUBINT RANGE 0..IDENT_INT(11) := 0;
BEGIN
FAILED ("NO EXCEPTION RAISED (S2)");
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (S2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (S2)");
END;
BEGIN
DECLARE
SUBTYPE I IS SUBINT RANGE A1'RANGE;
BEGIN
FAILED ("NO EXCEPTION RAISED (R1)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (R1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (R1)");
END;
BEGIN
DECLARE
SUBTYPE I IS SUBINT RANGE A2'RANGE;
BEGIN
FAILED ("NO EXCEPTION RAISED (R2)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (R2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (R2)");
END;
RESULT;
END C35003A;
|
30,779
|
ada
| 8
|
mhatzl/spark_unbound
|
src/spark_unbound-arrays.adb
|
with Spark_Unbound.Safe_Alloc;
package body Spark_Unbound.Arrays with SPARK_Mode is
package Array_Alloc is new Spark_Unbound.Safe_Alloc.Arrays(Element_Type => Element_Type, Index_Type => Index_Type, Array_Type => Array_Type, Array_Type_Acc => Array_Acc);
function Get_Capacity_Offset (Offset : Long_Positive) return Index_Type
is
Arr_Offset : Long_Natural := Long_Natural(Offset) - Long_Natural(Long_Positive'First);
begin
return Index_Type(Long_Integer(Index_Type'First) + Arr_Offset);
end Get_Capacity_Offset;
function To_Unbound_Array (Initial_Capacity : Long_Positive) return Unbound_Array
is
Arr_Acc : Array_Acc := Array_Alloc.Alloc(First => Index_Type'First, Last => Get_Capacity_Offset(Initial_Capacity));
Unbound_Arr : Unbound_Array := Unbound_Array'(Last => No_Index, Arr => Arr_Acc);
begin
return Unbound_Arr;
end To_Unbound_Array;
function "=" (Left, Right : Unbound_Array) return Boolean
is
begin
if Left.Arr = null and then Right.Arr = null then
return True;
end if;
if (Left.Arr = null and then Right.Arr /= null) or else (Left.Arr /= null and then Right.Arr = null) then
return False;
end if;
if (Last_Index(Left) /= Last_Index(Right)) or else (First_Index(Left) /= First_Index(Right)) then
return False;
end if;
for I in First_Index(Left) .. Last_Index(Left) loop
if Element(Left, I) /= Element(Right, I) then
return False;
end if;
pragma Loop_Invariant (for all P in First_Index(Left) .. I => Element(Left, P) = Element(Right, P));
end loop;
return True;
end "=";
function Capacity (Self : Unbound_Array) return Long_Natural
is
begin
if Self.Arr = null then
return Long_Natural'First;
end if;
return Self.Arr.all'Length;
end Capacity;
-- procedure Reserve_Capacity (Self : in out Unbound_Array; Cap : in Count_Type; Success: out Boolean) is
-- begin
-- null;
-- end Reserve_Capacity;
procedure Shrink (Self : in out Unbound_Array; New_Capacity : Long_Natural; Success : out Boolean)
is
begin
if New_Capacity = Long_Natural'First then
Clear(Self);
if Self.Arr = null and then Self.Last = No_Index then
Success := True;
return;
else
raise Program_Error;
end if;
end if;
declare
Arr_Acc : Array_Acc := Array_Alloc.Alloc(First => First_Index(Self), Last => Get_Capacity_Offset(Long_Positive(New_Capacity)));
Tmp : Unbound_Array := Unbound_Array'(Last => No_Index, Arr => Arr_Acc);
begin
if Tmp.Arr = null then
Success := False;
else
if Is_Empty(Self) then
Clear(Self);
else
Move(Tmp, Self);
end if;
if Self.Arr = null and then Self.Last = No_Index then
Self.Arr := Tmp.Arr;
Self.Last := Tmp.Last;
Success := True;
else
Clear(Tmp);
if Tmp.Arr = null and then Tmp.Last = No_Index then
Success := False;
else
raise Program_Error;
end if;
end if;
end if;
end;
end Shrink;
function Length (Self : Unbound_Array) return Long_Natural
is
begin
if Last_Index(Self) = No_Index then
return Long_Natural'First;
end if;
-- abs() needed since indizes might be negative
return Long_Natural(abs(Long_Integer(Last_Index(Self)) - Long_Integer(First_Index(Self))) + 1); -- Last = First leaves room for 1 element
end Length;
function Is_Empty (Self : Unbound_Array) return Boolean
is
begin
return Last_Index(Self) = No_Index;
end Is_Empty;
procedure Clear (Self : in out Unbound_Array) is
begin
Self.Last := No_Index;
Array_Alloc.Free(Self.Arr);
end Clear;
function Element (Self : Unbound_Array; Index : Index_Type) return Element_Type
is
begin
return Self.Arr.all(Index);
end Element;
procedure Replace_Element (Self : in out Unbound_Array; Index : in Index_Type; New_Item : in Element_Type)
is
begin
Self.Arr.all(Index) := New_Item;
end Replace_Element;
-- procedure Update_Element
-- (Self : in out Unbound_Array;
-- Index : in Index_Type;
-- Process : not null access procedure (Process_Element : in out Element_Type)) is
-- begin
-- Process.all(Self.Arr.all(Index));
-- end Update_Element;
procedure Copy (Target : out Unbound_Array; Source : Unbound_Array; Success: out Boolean)
is
begin
Target.Last := No_Index;
Target.Arr := null;
if Source.Arr = null then
Success := True;
return;
end if;
Target.Arr := Array_Alloc.Alloc(First => Source.Arr.all'First, Last => Source.Arr.all'Last);
if Target.Arr = null then
Success := False;
else
Target.Last := Source.Last;
for I in First_Index(Source) .. Last_Index(Source) loop
Target.Arr.all(I) := Source.Arr.all(I);
pragma Loop_Invariant (for all P in First_Index(Source) .. I => Target.Arr.all(P) = Source.Arr.all(P));
end loop;
Success := True;
end if;
end Copy;
procedure Move (Target : in out Unbound_Array; Source : in out Unbound_Array)
is
begin
for I in First_Index(Source) .. Last_Index(Source) loop
Target.Arr.all(I) := Source.Arr.all(I);
pragma Loop_Invariant (for all P in First_Index(Source) .. I => Target.Arr.all(P) = Source.Arr.all(P));
end loop;
Target.Last := Source.Last;
Source.Last := No_Index;
Array_Alloc.Free(Source.Arr);
if Source.Arr /= null or else Source.Last /= No_Index then
raise Program_Error;
end if;
end Move;
procedure Append (Self : in out Unbound_Array; New_Item : in Element_Type; Success: out Boolean)
is
begin
if Last_Index(Self) < Self.Arr.all'Last then
Self.Last := Self.Last + 1;
Self.Arr.all(Last_Index(Self)) := New_Item;
Success := True;
else
declare
Added_Capacity : Long_Natural := Capacity(Self); -- Try to double array capacity for O(Log(N))
Ghost_Added_Capactiy : Long_Natural with Ghost;
begin
while (Long_Integer(Index_Type'Last) - Added_Capacity) < Long_Integer(Get_Capacity_Offset(Long_Positive(Capacity(Self)))) and then Added_Capacity > Long_Natural'First loop
Ghost_Added_Capactiy := Added_Capacity;
Added_Capacity := Added_Capacity - 1;
pragma Loop_Invariant (Added_Capacity = Ghost_Added_Capactiy - 1);
end loop;
declare
New_Max_Last : Index_Type := Get_Capacity_Offset(Long_Positive(Capacity(Self) + Added_Capacity));
Ghost_New_Max_Last : Index_Type with Ghost;
Arr_Acc : Array_Acc := null;
Tmp_Last : Extended_Index := Self.Last;
begin
while Arr_Acc = null and then New_Max_Last > Get_Capacity_Offset(Long_Positive(Capacity(Self))) loop
Arr_Acc := Array_Alloc.Alloc(First => Self.Arr.all'First, Last => New_Max_Last);
Ghost_New_Max_Last := New_Max_Last;
New_Max_Last := New_Max_Last - 1;
pragma Loop_Invariant (New_Max_Last = Ghost_New_Max_Last - 1);
pragma Loop_Invariant (if Arr_Acc /= null then Arr_Acc.all'Last >= Arr_Acc.all'First);
pragma Loop_Invariant (if Arr_Acc /= null then Arr_Acc.all'First = First_Index(Self));
pragma Loop_Invariant (if Arr_Acc /= null then Arr_Acc.all'Last > Get_Capacity_Offset(Long_Positive(Capacity(Self))));
end loop;
if Arr_Acc = null then
Success := False;
else
for I in First_Index(Self) .. Last_Index(Self) loop
Arr_Acc.all(I) := Self.Arr.all(I);
pragma Loop_Invariant (for all P in First_Index(Self) .. I => Arr_Acc.all(P) = Self.Arr.all(P));
end loop;
Self.Last := No_Index;
Array_Alloc.Free(Self.Arr);
if Self.Arr = null and then Self.Last = No_Index then
Self.Arr := Arr_Acc;
if Self.Arr /= null and Tmp_Last < Self.Arr.all'Last then
Self.Last := Tmp_Last + 1;
Self.Arr.all(Last_Index(Self)) := New_Item;
Success := True;
else
raise Program_Error;
end if;
else
raise Program_Error;
end if;
end if;
end;
end;
end if;
end Append;
-- procedure Delete (Self : in out Unbound_Array;
-- Index : in Extended_Index;
-- Count : in Positive := 1) is
-- begin
-- null;
-- end Delete;
procedure Delete_Last (Self : in out Unbound_Array; Count : in Long_Positive := 1)
is
begin
-- Actually not deleting anything, but moving values out of scope
Self.Last := Extended_Index(Long_Integer(Self.Last) - Count);
end;
function First_Element (Self : Unbound_Array) return Element_Type
is
begin
return Self.Arr.all(First_Index(Self));
end First_Element;
function First_Index (Self : Unbound_Array) return Index_Type
is
begin
if Self.Arr = null then
return Index_Type'First;
end if;
return Self.Arr.all'First;
end First_Index;
function Last_Index (Self : Unbound_Array) return Extended_Index
is
begin
return Self.Last;
end Last_Index;
function Last_Element (Self : Unbound_Array) return Element_Type
is
begin
return Self.Arr.all(Last_Index(Self));
end Last_Element;
function Find_Index (Self : Unbound_Array; Item : Element_Type; Index : Index_Type := Index_Type'First) return Extended_Index
is
begin
if Last_Index(Self) = No_Index then
return No_Index;
end if;
for I in Index .. Last_Index(Self) loop
if Element(Self, I) = Item then
return I;
end if;
pragma Loop_Invariant (for all P in Index .. I => Element(Self, P) /= Item);
end loop;
return No_Index;
end Find_Index;
function Contains (Self : Unbound_Array; Item : Element_Type; Index : Index_Type := Index_Type'First) return Boolean
is
begin
if Self.Arr = null or else Self.Last = No_Index then
return False;
end if;
for I in Index .. Last_Index(Self) loop
if Self.Arr.all(I) = Item then
return True;
end if;
pragma Loop_Invariant (for all P in Index .. I => Element(Self, P) /= Item);
end loop;
return False;
end Contains;
-- Ghost ----------------------------------------------------------------------------------
function Ghost_Acc_Length (Self : Array_Acc) return Long_Natural
is
begin
if Self = null then
return Long_Natural'First;
end if;
return Self.all'Length;
end Ghost_Acc_Length;
function Ghost_Arr_Equals (Left, Right : Array_Type; First, Last : Index_Type) return Boolean
is
begin
if Left'First > First or else Right'First > First
or else Left'Last < Last or else Right'Last < Last then
return False;
end if;
for I in First .. Last loop
if Left(I) /= Right(I) then
return False;
end if;
pragma Loop_Invariant (for all P in First .. I => Left(P) = Right(P));
end loop;
return True;
end Ghost_Arr_Equals;
function Ghost_Arr_Length (Self : Array_Type) return Long_Natural
is
begin
return Self'Length;
end Ghost_Arr_Length;
end Spark_Unbound.Arrays;
|
30,780
|
ada
| 0
|
pat-rogers/OpenUxAS
|
src/ada/src/uxas-messages-lmcptask-taskautomationrequest-spark_boundary.adb
|
package body uxas.messages.Lmcptask.TaskAutomationRequest.SPARK_Boundary with SPARK_Mode => Off is
-----------------------------------------
-- Get_EntityList_From_OriginalRequest --
-----------------------------------------
function Get_EntityList_From_OriginalRequest
(Request : TaskAutomationRequest) return Int64_Vect
is
L : constant Vect_Int64_Acc := Request.getOriginalRequest.getEntityList;
begin
return R : Int64_Vect do
for E of L.all loop
Int64_Vects.Append (R, E);
end loop;
end return;
end Get_EntityList_From_OriginalRequest;
----------------------------------------------
-- Get_OperatingRegion_From_OriginalRequest --
----------------------------------------------
function Get_OperatingRegion_From_OriginalRequest
(Request : TaskAutomationRequest) return Int64
is (Request.getOriginalRequest.getOperatingRegion);
----------------------------
-- Get_PlanningStates_Ids --
----------------------------
function Get_PlanningStates_Ids
(Request : TaskAutomationRequest) return Int64_Vect
is
L : constant Vect_PlanningState_Acc_Acc :=
Request.getPlanningStates;
begin
return R : Int64_Vect do
for E of L.all loop
Int64_Vects.Append (R, E.getEntityID);
end loop;
end return;
end Get_PlanningStates_Ids;
---------------------------------------
-- Get_TaskList_From_OriginalRequest --
---------------------------------------
function Get_TaskList_From_OriginalRequest
(Request : TaskAutomationRequest) return Int64_Vect
is
L : constant Vect_Int64_Acc := Request.getOriginalRequest.getTaskList;
begin
return R : Int64_Vect do
for E of L.all loop
Int64_Vects.Append (R, E);
end loop;
end return;
end Get_TaskList_From_OriginalRequest;
end uxas.messages.Lmcptask.TaskAutomationRequest.SPARK_Boundary;
|
30,781
|
ada
| 0
|
mstewartgallus/linted
|
src/ada-libc/src/libc-errno.adb
|
<gh_stars>0
-- Copyright 2017 <NAME>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
-- implied. See the License for the specific language governing
-- permissions and limitations under the License.
package body Libc.Errno is
procedure Errno_Get (Err : out Interfaces.C.int) is
begin
Err := Errno;
end Errno_Get;
end Libc.Errno;
|
30,782
|
ada
| 0
|
sebsgit/textproc
|
src/trainingdata.adb
|
with Ada.Directories;
with Ada.Text_IO;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.IO_Exceptions;
with Ada.Containers;
with Ada.Containers.Vectors;
with ShapeDatabase;
with ImageIO;
with PixelArray;
with ImageRegions;
use Ada.Containers;
use Ada.Strings.Unbounded;
with Timer;
package body TrainingData is
package String_Vec_Pkg is new Ada.Containers.Vectors(Index_Type => Positive, Element_Type => Ada.Strings.Unbounded.Unbounded_String);
function size(data: in Set) return Natural is
begin
return data.values.size;
end size;
procedure add(data: in out Set; label: Natural; vec: MathUtils.Vector) is
begin
data.labels.Append(label);
data.values.append(vec);
end add;
function getCharacterString(imagePath: String) return Ada.Strings.Unbounded.Unbounded_String is
firstDotPosition: Natural := 0;
lastSlashPosition: Natural := 0;
startIndex: Natural := 1;
result: Ada.Strings.Unbounded.Unbounded_String;
begin
lastSlashPosition := Ada.Strings.Fixed.Index(imagePath, "/", Ada.Strings.Backward);
if lastSlashPosition /= 0 then
startIndex := lastSlashPosition + 1;
end if;
firstDotPosition := Ada.Strings.Fixed.Index(imagePath, ".", startIndex);
result := Ada.Strings.Unbounded.To_Unbounded_String(imagePath);
result := Ada.Strings.Unbounded.To_Unbounded_String(Ada.Strings.Unbounded.Slice(result, startIndex, firstDotPosition - 1));
return result;
end getCharacterString;
procedure filterRegions(regions: in out ImageRegions.RegionVector.Vector) is
begin
for idx in reverse regions.First_Index .. regions.Last_Index loop
if regions(idx).pixelCount < 512 then
regions.Delete(idx);
end if;
end loop;
end filterRegions;
Preferred_Width: constant Positive := 1280;
function load_for_processing(path: in Ada.Strings.Unbounded.Unbounded_String) return PixelArray.ImagePlane is
begin
return image: PixelArray.ImagePlane := ImageIO.load(Ada.Strings.Unbounded.To_String(path)) do
if image.width > Preferred_Width then
declare
ratio: constant Float := Float(Preferred_Width) / Float(image.width);
new_height: constant Positive := Positive(Float(image.height) * ratio);
begin
image.assign(image.rescale(Preferred_Width, (if new_height mod 2 = 0 then new_height else new_height + 1)));
end;
end if;
end return;
end load_for_processing;
procedure loadFrom(data: in out Set; path: in Ada.Strings.Unbounded.Unbounded_String; expectedChars: in Ada.Strings.Unbounded.Unbounded_String) is
image: constant PixelArray.ImagePlane := load_for_processing(path);
regions: ImageRegions.RegionVector.Vector;
tmr: Timer.T := Timer.start;
preprocessed: constant PixelArray.ImagePlane := ShapeDatabase.Preprocess_And_Detect_Regions(image, regions);
saveStatus: Boolean;
begin
tmr.report("shape db preprocess for " & Ada.Strings.Unbounded.To_String(path) & ", " & image.width'Image & "x" & image.height'Image);
filterRegions(regions);
ImageRegions.sortRegions(regions);
if Natural(regions.Length) /= Ada.Strings.Unbounded.Length(expectedChars) then
saveStatus := ImageIO.save(filename => "debug_region_error.jpg",
image => preprocessed);
raise Ada.IO_Exceptions.Data_Error with "Training set error - expected " & Ada.Strings.Unbounded.Length(expectedChars)'Image & " regions, got " & Natural(regions.Length)'Image;
end if;
-- cut and rescale the detected regions
declare
id: Positive := 1;
cut: PixelArray.ImagePlane;
label: Natural;
margin: Positive;
begin
for r of regions loop
margin := r.area.width / 3;
cut.assign(preprocessed.cut(x => r.area.x,
y => r.area.y,
w => r.area.width,
h => r.area.height));
cut.assign(cut.expand(margin, margin, PixelArray.Background));
cut.assign(cut.rescale(blockSize, blockSize));
label := Natural'Value((1 => Ada.Strings.Unbounded.Element(expectedChars, id)));
data.labels.Append(label);
data.values.append(toDataVector(cut, invertPixels => True));
id := id + 1;
end loop;
end;
end loadFrom;
procedure loadFrom(data: in out Set; paths: in String_Vec_Pkg.Vector; expectedCharVector: String_Vec_Pkg.Vector)
with Pre => paths.Length = expectedCharVector.Length
is
currentExpectedCharsIndex: Positive := expectedCharVector.First_Index;
expectedChars: Ada.Strings.Unbounded.Unbounded_String;
begin
for path of paths loop
expectedChars := expectedCharVector(currentExpectedCharsIndex);
loadFrom(data, path, expectedChars);
currentExpectedCharsIndex := currentExpectedCharsIndex + 1;
end loop;
end loadFrom;
procedure loadFrom(data: in out Set; path: in Ada.Strings.Unbounded.Unbounded_String) is
searchObj: Ada.Directories.Search_Type;
dirEnt: Ada.Directories.Directory_Entry_Type;
pathsToLoad: String_Vec_Pkg.Vector;
expectedCharsVector: String_Vec_Pkg.Vector;
begin
Ada.Directories.Start_Search(Search => searchObj,
Directory => Ada.Strings.Unbounded.To_String(path),
Pattern => "*.jpg");
while Ada.Directories.More_Entries(Search => searchObj) loop
Ada.Directories.Get_Next_Entry(Search => searchObj,
Directory_Entry => dirEnt);
expectedCharsVector.Append(getCharacterString(Ada.Directories.Simple_Name(dirEnt)));
pathsToLoad.Append(Ada.Strings.Unbounded.To_Unbounded_String(Ada.Directories.Full_Name(dirEnt)));
end loop;
Ada.Directories.End_Search(Search => searchObj);
loadFrom(data => data,
paths => pathsToLoad,
expectedCharVector => expectedCharsVector);
end loadFrom;
function toDataVector(img: in PixelArray.ImagePlane; invertPixels: Boolean := False) return MathUtils.Vector is
result: MathUtils.Vector;
begin
for y in 0 .. img.height - 1 loop
for x in 0 .. img.width - 1 loop
declare
px: constant Float := Float(img.get(x, y)) / 255.0;
begin
result.Append(if invertPixels then 1.0 - px else px);
end;
end loop;
end loop;
return result;
end toDataVector;
end TrainingData;
|
30,783
|
ada
| 80
|
thindil/steamsky
|
src/ships-movement.adb
|
<gh_stars>10-100
-- Copyright 2017-2021 <NAME>
--
-- 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 Ships.Cargo; use Ships.Cargo;
with Ships.Crew; use Ships.Crew;
with Statistics; use Statistics;
with Maps; use Maps;
with Messages; use Messages;
with Config; use Config;
with Bases; use Bases;
with Events; use Events;
with Utils; use Utils;
with Factions; use Factions;
with Game.SaveLoad; use Game.SaveLoad;
package body Ships.Movement is
-- ****it* SMovement/SMovement.SpeedType
-- FUNCTION
-- Used in counting ships speed
-- SOURCE
type SpeedType is digits 2;
-- ****
-- ****if* SMovement/SMovement.HaveOrderRequirements
-- FUNCTION
-- Check if all requirements for movement orders are valid
-- RESULT
-- Empty string if everything is ok, otherwise message what is missing
-- SOURCE
function HaveOrderRequirements return String is
-- ****
HaveCockpit, HaveEngine, HavePilot, HaveEngineer: Boolean := False;
begin
Find_Modules_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = COCKPIT and Module.Durability > 0 then
HaveCockpit := True;
elsif Module.M_Type = ENGINE
and then (Module.Durability > 1 and not Module.Disabled) then
HaveEngine := True;
end if;
exit Find_Modules_Loop when HaveEngine and HaveCockpit;
end loop Find_Modules_Loop;
if not HaveEngine then
return
"You don't have a working engine on your ship or all of the engines are destroyed.";
end if;
if not HaveCockpit then
return
"You don't have a cockpit on your ship or the cockpit is destroyed.";
end if;
if Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
HavePilot := True;
HaveEngineer := True;
end if;
Find_Members_Loop :
for Member of Player_Ship.Crew loop
if Member.Order = Pilot then
HavePilot := True;
elsif Member.Order = Engineer then
HaveEngineer := True;
end if;
exit Find_Members_Loop when HavePilot and HaveEngineer;
end loop Find_Members_Loop;
if not HavePilot then
return "You don't have a pilot on duty.";
end if;
if not HaveEngineer then
return "You don't have an engineer on duty.";
end if;
return "";
end HaveOrderRequirements;
function MoveShip
(X, Y: Integer; Message: in out Unbounded_String) return Natural is
NewX, NewY: Integer;
TimePassed, FuelNeeded: Integer := 0;
Speed: SpeedType;
FuelIndex: Inventory_Container.Extended_Index;
function NeedRest(Order: Crew_Orders) return Boolean is
MemberIndex: Crew_Container.Extended_Index;
begin
MemberIndex := FindMember(Order);
if MemberIndex = 0 then
Find_Member_Loop :
for Member of Player_Ship.Crew loop
if Member.PreviousOrder = Order then
return True;
end if;
end loop Find_Member_Loop;
end if;
return False;
end NeedRest;
begin
case Player_Ship.Speed is
when DOCKED =>
Message :=
To_Unbounded_String
("First you must undock your ship from the base.");
return 0;
when FULL_STOP =>
Message :=
To_Unbounded_String
("First you must set the speed of your ship.");
return 0;
when others =>
null;
end case;
Message := To_Unbounded_String(HaveOrderRequirements);
if Length(Message) > 0 then
return 0;
end if;
FuelIndex :=
FindItem(Inventory => Player_Ship.Cargo, ItemType => Fuel_Type);
if FuelIndex = 0 then
Message := To_Unbounded_String("You don't have any fuel.");
return 0;
end if;
FuelNeeded := CountFuelNeeded;
if Player_Ship.Cargo(FuelIndex).Amount < abs FuelNeeded then
Message :=
To_Unbounded_String
("You don't have enough fuel (" &
To_String
(Items_List(Player_Ship.Cargo(FuelIndex).ProtoIndex).Name) &
").");
return 0;
end if;
Speed := (SpeedType(RealSpeed(Player_Ship)) / 1_000.0);
if Speed < 0.5 then
Message :=
To_Unbounded_String
("You can't fly because your ship is overloaded.");
return 0;
end if;
NewX := Player_Ship.Sky_X + X;
NewY := Player_Ship.Sky_Y + Y;
if NewX < 1 or NewX > 1_024 or NewY < 1 or NewY > 1_024 then
return 0;
end if;
Player_Ship.Sky_X := NewX;
Player_Ship.Sky_Y := NewY;
UpdateCargo
(Player_Ship, Player_Ship.Cargo.Element(FuelIndex).ProtoIndex,
FuelNeeded);
TimePassed := Integer(100.0 / Speed);
if TimePassed > 0 then
case Player_Ship.Speed is
when QUARTER_SPEED =>
if TimePassed < 60 then
TimePassed := 60;
end if;
when HALF_SPEED =>
if TimePassed < 30 then
TimePassed := 30;
end if;
when FULL_SPEED =>
if TimePassed < 15 then
TimePassed := 15;
end if;
when others =>
null;
end case;
GameStats.DistanceTraveled := GameStats.DistanceTraveled + 1;
Update_Game(TimePassed);
FuelIndex :=
FindItem(Inventory => Player_Ship.Cargo, ItemType => Fuel_Type);
if FuelIndex = 0 then
AddMessage
("Ship falls from the sky due to a lack of fuel.", OtherMessage,
RED);
Death(1, To_Unbounded_String("fall of the ship"), Player_Ship);
return 0;
end if;
end if;
if not Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
if NeedRest(Pilot) then
if not Game_Settings.Auto_Rest then
return 6;
end if;
return 8;
end if;
if NeedRest(Engineer) then
if not Game_Settings.Auto_Rest then
return 7;
end if;
return 8;
end if;
end if;
return 1;
end MoveShip;
function DockShip
(Docking: Boolean; Escape: Boolean := False) return String is
BaseIndex: constant Extended_Base_Range :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex;
Message: Unbounded_String;
begin
Message := To_Unbounded_String(HaveOrderRequirements);
if Length(Message) > 0 then
return To_String(Message);
end if;
if Docking then
if Sky_Bases(BaseIndex).Population > 0 then
AddMessage
("Ship docked to base " & To_String(Sky_Bases(BaseIndex).Name),
OrderMessage);
if Game_Settings.Auto_Save = DOCK then
Save_Game;
end if;
declare
MemberIndex: Positive := 1;
begin
Resign_Crew_Member_Loop :
while MemberIndex <= Player_Ship.Crew.Last_Index loop
if Player_Ship.Crew(MemberIndex).ContractLength = 0 then
DeleteMember(MemberIndex, Player_Ship);
Sky_Bases(BaseIndex).Population :=
Sky_Bases(BaseIndex).Population + 1;
elsif Player_Ship.Crew(MemberIndex).Loyalty < 20 and
Get_Random(0, Player_Ship.Crew(MemberIndex).Loyalty) <
10 then
AddMessage
(To_String(Player_Ship.Crew(MemberIndex).Name) &
" resigns from working for you.",
OrderMessage);
DeleteMember(MemberIndex, Player_Ship);
Sky_Bases(BaseIndex).Population :=
Sky_Bases(BaseIndex).Population + 1;
Drop_Morale_Loop :
for I in Player_Ship.Crew.Iterate loop
UpdateMorale
(Player_Ship, Crew_Container.To_Index(I),
Get_Random(-5, -1));
end loop Drop_Morale_Loop;
else
MemberIndex := MemberIndex + 1;
end if;
end loop Resign_Crew_Member_Loop;
end;
if Game_Settings.Auto_Ask_For_Bases then
Ask_For_Bases;
end if;
if Game_Settings.Auto_Ask_For_Events then
Ask_For_Events;
end if;
else
AddMessage
("Ship docked to base " & To_String(Sky_Bases(BaseIndex).Name) &
".",
OrderMessage);
end if;
Player_Ship.Speed := DOCKED;
Update_Game(10);
else
Player_Ship.Speed := Game_Settings.Undock_Speed;
declare
Speed: constant SpeedType :=
(SpeedType(RealSpeed(Player_Ship)) / 1_000.0);
begin
if Speed < 0.5 then
return "You can't undock because your ship is overloaded.";
end if;
end;
Player_Ship.Speed := DOCKED;
if not Escape then
if Sky_Bases(BaseIndex).Population > 0 then
declare
MoneyIndex2: constant Inventory_Container.Extended_Index :=
FindItem(Player_Ship.Cargo, Money_Index);
DockingCost: Natural;
FuelIndex: Inventory_Container.Extended_Index;
TraderIndex: constant Crew_Container.Extended_Index :=
FindMember(Talk);
begin
if MoneyIndex2 = 0 then
return
"You can't undock from this base because you don't have any " &
To_String(Money_Name) & " to pay for docking.";
end if;
Count_Cost_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = HULL then
DockingCost := Module.Max_Modules;
exit Count_Cost_Loop;
end if;
end loop Count_Cost_Loop;
DockingCost :=
Natural
(Float(DockingCost) *
Float(New_Game_Settings.Prices_Bonus));
if DockingCost = 0 then
DockingCost := 1;
end if;
Count_Price(DockingCost, TraderIndex);
if DockingCost > Player_Ship.Cargo(MoneyIndex2).Amount then
return
"You can't undock to this base because you don't have enough " &
To_String(Money_Name) & " to pay for docking.";
end if;
UpdateCargo
(Ship => Player_Ship, CargoIndex => MoneyIndex2,
Amount => (0 - DockingCost));
if TraderIndex > 0 then
GainExp(1, Talking_Skill, TraderIndex);
end if;
FuelIndex :=
FindItem
(Inventory => Player_Ship.Cargo, ItemType => Fuel_Type);
if FuelIndex = 0 then
return
"You can't undock from base because you don't have any fuel.";
end if;
AddMessage
("Ship undocked from base " &
To_String(Sky_Bases(BaseIndex).Name) & ". You also paid" &
Positive'Image(DockingCost) & " " &
To_String(Money_Name) & " of docking fee.",
OrderMessage);
end;
else
declare
FuelIndex: constant Inventory_Container.Extended_Index :=
FindItem
(Inventory => Player_Ship.Cargo, ItemType => Fuel_Type);
begin
if FuelIndex = 0 then
return
"You can't undock from base because you don't have any fuel.";
end if;
AddMessage
("Ship undocked from base " &
To_String(Sky_Bases(BaseIndex).Name) & ".",
OrderMessage);
end;
end if;
else
declare
Roll: constant Integer := Get_Random(1, 100);
MessageText: Unbounded_String;
Color: Message_Color := WHITE;
ModuleIndex: Modules_Container.Extended_Index;
begin
MessageText :=
To_Unbounded_String
("Ship escaped from base " &
To_String(Sky_Bases(BaseIndex).Name) & " without paying.");
case Roll is
when 1 .. 40 =>
ModuleIndex :=
Get_Random
(Player_Ship.Modules.First_Index,
Player_Ship.Modules.Last_Index);
Append
(MessageText,
" But your ship (" &
To_String(Player_Ship.Modules(ModuleIndex).Name) &
") takes damage.");
Color := RED;
Damage_Module
(Player_Ship, ModuleIndex, Get_Random(1, 30),
"damage during escaping from the base");
when others =>
null;
end case;
AddMessage(To_String(MessageText), OrderMessage, Color);
Gain_Rep(BaseIndex, -(Get_Random(10, 30)));
end;
end if;
if Player_Ship.Crew(1).Health > 0 then
Player_Ship.Speed := Game_Settings.Undock_Speed;
Update_Game(5);
if Game_Settings.Auto_Save = UNDOCK then
Save_Game;
end if;
end if;
end if;
return "";
end DockShip;
function ChangeShipSpeed(SpeedValue: Ship_Speed) return String is
HaveEngine: Boolean := False;
begin
Find_Engine_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = ENGINE
and then (Module.Durability > 0 and not Module.Disabled) then
HaveEngine := True;
exit Find_Engine_Loop;
end if;
end loop Find_Engine_Loop;
if not HaveEngine then
return
"You don't have a working engine on your ship or all of the engines are destroyed.";
end if;
if FindMember(Engineer) = 0 and
not Factions_List(Player_Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
return "You don't have an engineer on duty.";
end if;
Player_Ship.Speed := SpeedValue;
return "";
end ChangeShipSpeed;
function RealSpeed
(Ship: Ship_Record; InfoOnly: Boolean := False) return Natural is
BaseSpeed, Speed: Natural := 0;
ShipSetSpeed: Ship_Speed;
begin
if Ship = Player_Ship and not InfoOnly then
if HaveOrderRequirements'Length > 0 then
return 0;
end if;
end if;
declare
Damage: Damage_Factor := 0.0;
begin
Find_Engine_Loop :
for Module of Ship.Modules loop
if Module.M_Type = ENGINE and then not Module.Disabled then
BaseSpeed := Module.Power * 10;
Damage :=
1.0 -
Damage_Factor
(Float(Module.Durability) / Float(Module.Max_Durability));
Speed :=
Speed +
(BaseSpeed - Natural(Float(BaseSpeed) * Float(Damage)));
end if;
end loop Find_Engine_Loop;
end;
Speed :=
Natural((Float(Speed) / Float(Count_Ship_Weight(Ship))) * 100_000.0);
if Ship.Crew.Length > 0 then
if not Factions_List(Ship.Crew(1).Faction).Flags.Contains
(To_Unbounded_String("sentientships")) then
Sentinent_Ship_Speed_Loop :
for I in Ship.Crew.Iterate loop
if Ship.Crew(I).Order = Pilot then
Speed :=
Speed +
Natural
(Float(Speed) *
(Float(GetSkillLevel(Ship.Crew(I), Piloting_Skill)) /
300.0));
elsif Ship.Crew(I).Order = Engineer then
Speed :=
Speed +
Natural
(Float(Speed) *
(Float(GetSkillLevel(Ship.Crew(I), Engineering_Skill)) /
300.0));
end if;
end loop Sentinent_Ship_Speed_Loop;
else
Normal_Ship_Speed_Loop :
for Module of Ship.Modules loop
if Module.M_Type = HULL then
Speed :=
Speed +
Natural
(Float(Speed) * (Float(Module.Max_Modules * 2) / 300.0));
exit Normal_Ship_Speed_Loop;
end if;
end loop Normal_Ship_Speed_Loop;
end if;
end if;
if Ship = Player_Ship and (Ship.Speed in DOCKED | FULL_STOP) and
InfoOnly then
ShipSetSpeed := Game_Settings.Undock_Speed;
if ShipSetSpeed = FULL_STOP then
ShipSetSpeed := QUARTER_SPEED;
end if;
else
ShipSetSpeed := Ship.Speed;
end if;
case ShipSetSpeed is
when QUARTER_SPEED =>
Speed := Integer(Float(Speed) * 0.25);
when HALF_SPEED =>
Speed := Integer(Float(Speed) * 0.5);
when FULL_SPEED =>
null;
when others =>
return 0;
end case;
Speed := (Speed / 60);
return Speed;
end RealSpeed;
function CountFuelNeeded return Integer is
FuelNeeded: Integer := 0;
Speed: Ship_Speed := Player_Ship.Speed;
begin
if Speed in DOCKED | FULL_STOP then
Speed := Game_Settings.Undock_Speed;
end if;
Count_Fuel_Needed_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = ENGINE and then not Module.Disabled then
case Speed is
when QUARTER_SPEED =>
FuelNeeded := FuelNeeded - (Module.Fuel_Usage / 4);
when HALF_SPEED =>
FuelNeeded := FuelNeeded - (Module.Fuel_Usage / 2);
when FULL_SPEED =>
FuelNeeded := FuelNeeded - Module.Fuel_Usage;
when others =>
null;
end case;
end if;
end loop Count_Fuel_Needed_Loop;
return FuelNeeded;
end CountFuelNeeded;
procedure WaitInPlace(Minutes: Positive) is
BaseFuelNeeded, FuelNeeded: Integer := 0;
FuelIndex: Natural;
begin
if Player_Ship.Speed = DOCKED then
return;
end if;
Needed_Fuel_Loop :
for Module of Player_Ship.Modules loop
if Module.M_Type = ENGINE and then not Module.Disabled then
BaseFuelNeeded := BaseFuelNeeded - 1;
end if;
end loop Needed_Fuel_Loop;
FuelNeeded := BaseFuelNeeded * (Minutes / 10);
if Get_Random(1, 10) < (Minutes rem 10) then
FuelNeeded := FuelNeeded + BaseFuelNeeded;
end if;
FuelIndex :=
FindItem(Inventory => Player_Ship.Cargo, ItemType => Fuel_Type);
if FuelIndex = 0 then
AddMessage
("Ship falls from the sky due to a lack of fuel.", OtherMessage,
RED);
Death(1, To_Unbounded_String("fall of the ship"), Player_Ship);
return;
end if;
if Player_Ship.Cargo(FuelIndex).Amount <= abs (FuelNeeded) then
AddMessage
("Ship falls from the sky due to a lack of fuel.", OtherMessage,
RED);
Death(1, To_Unbounded_String("fall of the ship"), Player_Ship);
return;
end if;
UpdateCargo
(Player_Ship, Player_Ship.Cargo.Element(FuelIndex).ProtoIndex,
FuelNeeded);
end WaitInPlace;
end Ships.Movement;
|
30,784
|
ada
| 33
|
ytomino/drake
|
source/distributed/required/s-shasto.adb
|
<filename>source/distributed/required/s-shasto.adb
pragma Check_Policy (Trace => Ignore);
package body System.Shared_Storage is
procedure Shared_Var_Lock (Var : String) is
begin
pragma Check (Trace, Ada.Debug.Put (Var));
Lock_Hook (Var);
end Shared_Var_Lock;
procedure Shared_Var_Unlock (Var : String) is
begin
pragma Check (Trace, Ada.Debug.Put (Var));
Unlock_Hook (Var);
end Shared_Var_Unlock;
package body Shared_Var_Procs is
procedure Read is
pragma Check (Trace, Ada.Debug.Put (Full_Name));
Stream : constant access Ada.Streams.Root_Stream_Type'Class :=
Read_Hook (Full_Name);
begin
if Stream /= null then
Typ'Read (Stream, V);
end if;
end Read;
procedure Write is
pragma Check (Trace, Ada.Debug.Put (Full_Name));
Stream : constant access Ada.Streams.Root_Stream_Type'Class :=
Write_Hook (Full_Name);
begin
if Stream /= null then
Typ'Write (Stream, V);
end if;
end Write;
end Shared_Var_Procs;
end System.Shared_Storage;
|
30,785
|
ada
| 1
|
ekoeppen/STM32_Generic_Ada_Drivers
|
host/stm32gd-usart-peripheral.ads
|
<filename>host/stm32gd-usart-peripheral.ads
with STM32_SVD; use STM32_SVD;
generic
Filename : String;
package STM32GD.USART.Peripheral is
pragma Preelaborate;
procedure Init;
procedure Transmit (Data : in Byte);
function Receive return Byte;
end STM32GD.USART.Peripheral;
|
30,786
|
ada
| 1
|
persan/A-gst
|
src/gen/gstreamer-gst_low_level-gstreamer_0_10_gst_rtp_gstbasertpaudiopayload_h.ads
|
<reponame>persan/A-gst
pragma Ada_2005;
pragma Style_Checks (Off);
pragma Warnings (Off);
with Interfaces.C; use Interfaces.C;
with glib;
with glib.Values;
with System;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstbasertppayload_h;
with System;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstclock_h;
with glib;
limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstadapter_h;
with GLIB; -- with GStreamer.GST_Low_Level.glibconfig_h;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h;
package GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstbasertpaudiopayload_h is
-- unsupported macro: GST_TYPE_BASE_RTP_AUDIO_PAYLOAD (gst_base_rtp_audio_payload_get_type())
-- arg-macro: function GST_BASE_RTP_AUDIO_PAYLOAD (obj)
-- return G_TYPE_CHECK_INSTANCE_CAST((obj), GST_TYPE_BASE_RTP_AUDIO_PAYLOAD,GstBaseRTPAudioPayload);
-- arg-macro: function GST_BASE_RTP_AUDIO_PAYLOAD_CLASS (klass)
-- return G_TYPE_CHECK_CLASS_CAST((klass), GST_TYPE_BASE_RTP_AUDIO_PAYLOAD,GstBaseRTPAudioPayloadClass);
-- arg-macro: function GST_IS_BASE_RTP_AUDIO_PAYLOAD (obj)
-- return G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_BASE_RTP_AUDIO_PAYLOAD);
-- arg-macro: function GST_IS_BASE_RTP_AUDIO_PAYLOAD_CLASS (klass)
-- return G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_BASE_RTP_AUDIO_PAYLOAD);
-- arg-macro: function GST_BASE_RTP_AUDIO_PAYLOAD_CAST (obj)
-- return (GstBaseRTPAudioPayload *) (obj);
-- GStreamer
-- * Copyright (C) <2006> <NAME> <<EMAIL>>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Library General Public
-- * License as published by the Free Software Foundation; either
-- * version 2 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- * Library General Public License for more details.
-- *
-- * You should have received a copy of the GNU Library General Public
-- * License along with this library; if not, write to the
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-- * Boston, MA 02111-1307, USA.
--
type GstBaseRTPAudioPayload;
type u_GstBaseRTPAudioPayload_u_gst_reserved_array is array (0 .. 3) of System.Address;
--subtype GstBaseRTPAudioPayload is u_GstBaseRTPAudioPayload; -- gst/rtp/gstbasertpaudiopayload.h:29
type GstBaseRTPAudioPayloadClass;
type u_GstBaseRTPAudioPayloadClass_u_gst_reserved_array is array (0 .. 3) of System.Address;
--subtype GstBaseRTPAudioPayloadClass is u_GstBaseRTPAudioPayloadClass; -- gst/rtp/gstbasertpaudiopayload.h:30
-- skipped empty struct u_GstBaseRTPAudioPayloadPrivate
-- skipped empty struct GstBaseRTPAudioPayloadPrivate
type GstBaseRTPAudioPayload is record
payload : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstbasertppayload_h.GstBaseRTPPayload; -- gst/rtp/gstbasertpaudiopayload.h:51
priv : System.Address; -- gst/rtp/gstbasertpaudiopayload.h:53
base_ts : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstclock_h.GstClockTime; -- gst/rtp/gstbasertpaudiopayload.h:55
frame_size : aliased GLIB.gint; -- gst/rtp/gstbasertpaudiopayload.h:56
frame_duration : aliased GLIB.gint; -- gst/rtp/gstbasertpaudiopayload.h:57
sample_size : aliased GLIB.gint; -- gst/rtp/gstbasertpaudiopayload.h:59
u_gst_reserved : u_GstBaseRTPAudioPayload_u_gst_reserved_array; -- gst/rtp/gstbasertpaudiopayload.h:61
end record;
pragma Convention (C_Pass_By_Copy, GstBaseRTPAudioPayload); -- gst/rtp/gstbasertpaudiopayload.h:49
--*
-- * GstBaseRTPAudioPayloadClass:
-- * @parent_class: the parent class
-- *
-- * Base class for audio RTP payloader.
--
type GstBaseRTPAudioPayloadClass is record
parent_class : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstbasertppayload_h.GstBaseRTPPayloadClass; -- gst/rtp/gstbasertpaudiopayload.h:72
u_gst_reserved : u_GstBaseRTPAudioPayloadClass_u_gst_reserved_array; -- gst/rtp/gstbasertpaudiopayload.h:75
end record;
pragma Convention (C_Pass_By_Copy, GstBaseRTPAudioPayloadClass); -- gst/rtp/gstbasertpaudiopayload.h:70
--< private >
function gst_base_rtp_audio_payload_get_type return GLIB.GType; -- gst/rtp/gstbasertpaudiopayload.h:78
pragma Import (C, gst_base_rtp_audio_payload_get_type, "gst_base_rtp_audio_payload_get_type");
-- configure frame based
procedure gst_base_rtp_audio_payload_set_frame_based (basertpaudiopayload : access GstBaseRTPAudioPayload); -- gst/rtp/gstbasertpaudiopayload.h:81
pragma Import (C, gst_base_rtp_audio_payload_set_frame_based, "gst_base_rtp_audio_payload_set_frame_based");
procedure gst_base_rtp_audio_payload_set_frame_options
(basertpaudiopayload : access GstBaseRTPAudioPayload;
frame_duration : GLIB.gint;
frame_size : GLIB.gint); -- gst/rtp/gstbasertpaudiopayload.h:83
pragma Import (C, gst_base_rtp_audio_payload_set_frame_options, "gst_base_rtp_audio_payload_set_frame_options");
-- configure sample based
procedure gst_base_rtp_audio_payload_set_sample_based (basertpaudiopayload : access GstBaseRTPAudioPayload); -- gst/rtp/gstbasertpaudiopayload.h:87
pragma Import (C, gst_base_rtp_audio_payload_set_sample_based, "gst_base_rtp_audio_payload_set_sample_based");
procedure gst_base_rtp_audio_payload_set_sample_options (basertpaudiopayload : access GstBaseRTPAudioPayload; sample_size : GLIB.gint); -- gst/rtp/gstbasertpaudiopayload.h:88
pragma Import (C, gst_base_rtp_audio_payload_set_sample_options, "gst_base_rtp_audio_payload_set_sample_options");
procedure gst_base_rtp_audio_payload_set_samplebits_options (basertpaudiopayload : access GstBaseRTPAudioPayload; sample_size : GLIB.gint); -- gst/rtp/gstbasertpaudiopayload.h:90
pragma Import (C, gst_base_rtp_audio_payload_set_samplebits_options, "gst_base_rtp_audio_payload_set_samplebits_options");
-- get the internal adapter
function gst_base_rtp_audio_payload_get_adapter (basertpaudiopayload : access GstBaseRTPAudioPayload) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstadapter_h.GstAdapter; -- gst/rtp/gstbasertpaudiopayload.h:94
pragma Import (C, gst_base_rtp_audio_payload_get_adapter, "gst_base_rtp_audio_payload_get_adapter");
-- push and flushing data
function gst_base_rtp_audio_payload_push
(baseaudiopayload : access GstBaseRTPAudioPayload;
data : access GLIB.guint8;
payload_len : GLIB.guint;
timestamp : GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstclock_h.GstClockTime) return GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstFlowReturn; -- gst/rtp/gstbasertpaudiopayload.h:97
pragma Import (C, gst_base_rtp_audio_payload_push, "gst_base_rtp_audio_payload_push");
function gst_base_rtp_audio_payload_flush
(baseaudiopayload : access GstBaseRTPAudioPayload;
payload_len : GLIB.guint;
timestamp : GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstclock_h.GstClockTime) return GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstFlowReturn; -- gst/rtp/gstbasertpaudiopayload.h:100
pragma Import (C, gst_base_rtp_audio_payload_flush, "gst_base_rtp_audio_payload_flush");
end GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtp_gstbasertpaudiopayload_h;
|
30,787
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/bit_packed_array1.ads
|
with Interfaces;
package Bit_Packed_Array1 is
type laser_illuminator_code_group_t is (zero, one);
pragma Convention (C, laser_illuminator_code_group_t);
subtype lic_array_index_t is Interfaces.Unsigned_8 range 0 .. 3;
type lic_array_t is array (lic_array_index_t)
of laser_illuminator_code_group_t;
pragma Convention (C, lic_array_t);
type Eighty_Bytes_T is array (1 .. 80) of Interfaces.Unsigned_8;
type Mission_Assignment_T is record
Eighty_Bytes : Eighty_Bytes_T;
Laser_Illuminator_Code : lic_array_t;
end record;
for Mission_Assignment_T use record
Eighty_Bytes at 0 range 0 .. 639;
Laser_Illuminator_Code at 0 range 653 .. 780;
end record;
type Mission_Assignment_Dbase_Rec_T is record
ISF : Mission_Assignment_T;
end record;
MADR : Mission_Assignment_Dbase_Rec_T;
procedure Generate_Callforward;
end Bit_Packed_Array1;
|
30,788
|
ada
| 1
|
TNO/Dependency_Graph_Extractor-Ada
|
tests/syntax_examples/src/task_subprogram_calls.ads
|
<reponame>TNO/Dependency_Graph_Extractor-Ada
package Task_Subprogram_Calls is
task type T1 is
entry E1;
end T1;
task type T2 is
entry E1;
entry E2;
end T2;
procedure Test1;
procedure Test2;
protected type PT1 is
procedure P1;
procedure P2(I : Integer);
function F1 return Integer;
function F2(I : Integer) return Integer;
entry E1;
entry E2(I : Integer);
entry E4(1 .. 5);
entry E5(1 .. 5)(I : Integer);
private
entry E6;
end PT1;
end Task_Subprogram_Calls;
|
30,789
|
ada
| 20
|
charlie5/lace
|
4-high/gel/source/gel-rig.ads
|
<reponame>charlie5/lace
with
gel.Sprite,
gel.Joint,
gel.World,
openGL,
openGL.Model,
openGL.Program,
ada.Strings.unbounded.Hash,
ada.Containers.Vectors,
ada.Containers.hashed_Maps;
private
with
collada.Library.visual_Scenes;
package gel.Rig
--
-- Provides GEL sprites which allow placing a collada skinned/rigged model into a GEL World.
--
-- The rig motion can be controlled either by normal dynamics or pre-canned animations.
--
is
type Item is tagged limited private;
type View is access all Item'Class;
type Views is array (Positive range <>) of View;
use Math;
--------------
--- Core Types
--
type motion_Mode is (Dynamics, Animation);
procedure motion_Mode_is (Self : in out Item; Now : in motion_Mode);
subtype bone_Id is ada.Strings.unbounded.unbounded_String;
null_Id : constant bone_Id := ada.Strings.unbounded.null_unbounded_String;
subtype controller_joint_Id is ada.Strings.unbounded.unbounded_String;
--------------
--- Containers
--
package inverse_bind_matrix_Vectors is new ada.Containers.Vectors (Positive, Matrix_4x4);
subtype inverse_bind_matrix_Vector is inverse_bind_matrix_Vectors.Vector;
--------------
--- Joints Ids
--
subtype gel_joint_Id is ada.Strings.unbounded.unbounded_String;
package gel_joint_id_Maps_of_gel_Joint is new ada.Containers.hashed_Maps (Key_type => gel_joint_Id,
Element_type => gel.Joint.view,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => gel.Joint."=");
subtype gel_joint_id_Map_of_gel_Joint is gel_joint_id_Maps_of_gel_Joint.Map;
package joint_Id_Maps_of_bone_site_offset is new ada.Containers.hashed_Maps (Key_type => controller_joint_Id,
Element_type => Vector_3,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype joint_Id_Map_of_bone_site_offset is joint_Id_Maps_of_bone_site_offset.Map;
------------
--- Bone Ids
--
package bone_id_Maps_of_sprite is new ada.Containers.hashed_Maps (Key_type => bone_Id,
Element_type => gel.Sprite.view,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => gel.Sprite."=");
subtype bone_id_Map_of_sprite is bone_id_Maps_of_sprite.Map;
----------------
--- Bone Details
--
use type math.Degrees;
type bone_Details is
record
Length : math.Real := 1.0;
width_Factor,
depth_Factor : math.Real := 0.1; -- Factor * Length gives width and depth.
pitch_Limits,
yaw_Limits,
roll_Limits : gel.Sprite.DoF_Limits := (to_Radians (-15.0),
to_Radians ( 15.0));
end record;
Unspecified : constant := -1.0;
function to_Details (Length : Real := Unspecified;
width_Factor,
depth_Factor : Real := 0.1;
pitch_Limits,
yaw_Limits,
roll_Limits : gel.Sprite.DoF_Limits := (to_Radians (-15.0),
to_Radians ( 15.0))) return bone_Details;
package bone_id_Maps_of_details is new ada.Containers.hashed_Maps (Key_Type => bone_id,
Element_Type => bone_Details,
Hash => ada.Strings.unbounded.Hash,
Equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype bone_id_Map_of_details is bone_id_Maps_of_details.Map;
---------
--- Forge
--
package Forge
is
function new_Rig (in_World : in gel.World.view;
Model : in openGL.Model.view;
Mass : in Real := 0.0;
is_Kinematic : in Boolean := False) return Rig.view;
function new_Rig (bone_Sprites : in bone_id_Map_of_sprite;
joint_inv_bind_Matrices : in inverse_bind_matrix_Vector;
joint_site_Offets : in joint_Id_Map_of_bone_site_offset;
Model : in openGL.Model.view) return Rig.view;
end Forge;
procedure define (Self : in out Item; in_World : in gel.World.view;
Model : in openGL.Model.view;
Mass : in Real := 0.0;
is_Kinematic : in Boolean := False;
bone_Details : in bone_id_Map_of_details := bone_id_Maps_of_details.empty_Map);
--------------
--- Attributes
--
procedure Site_is (Self : in out Item; Now : in Vector_3);
procedure Spin_is (Self : in out Item; Now : in Matrix_3x3);
function bone_Sprites (Self : in Item) return bone_id_Map_of_sprite;
function skin_Sprite (Self : in Item'Class) return gel.Sprite.view;
function base_Sprite (Self : in Item'Class) return gel.Sprite.view;
function Sprite (Self : in Item'Class;
Bone : in bone_Id) return gel.Sprite.view;
function Joints (Self : in Item) return gel_joint_id_Map_of_gel_Joint;
procedure joint_inv_bind_Matrices_are (Self : in out Item'Class; Now : in inverse_bind_matrix_Vector);
function joint_inv_bind_Matrices (Self : in Item'Class) return inverse_bind_matrix_Vector;
function joint_site_Offets (Self : in Item'Class) return joint_Id_Map_of_bone_site_offset;
procedure assume_Pose (Self : in out Item);
procedure enable_Graphics (Self : in out Item);
procedure evolve (Self : in out Item'Class; world_Age : in Duration);
-------------
--- Animation
--
subtype scene_joint_Id is ada.Strings.unbounded.unbounded_String;
package bone_id_Maps_of_transform is new ada.Containers.hashed_Maps (Key_Type => bone_id,
Element_Type => Matrix_4x4,
Hash => ada.Strings.unbounded.Hash,
Equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype bone_id_Map_of_transform is bone_id_Maps_of_transform.Map;
procedure animation_Transforms_are (Self : in out Item'Class; Now : in bone_id_Map_of_transform);
type axis_Kind is (x_Axis, y_Axis, z_Axis);
procedure set_rotation_Angle (Self : in out Item'Class; for_Joint : in scene_joint_Id;
Axis : in Axis_Kind;
To : in Real); -- TODO: Use Radians type (and below).
procedure set_x_rotation_Angle (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_y_rotation_Angle (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_z_rotation_Angle (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_Location (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Vector_3);
procedure set_Location_x (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_Location_y (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_Location_z (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Real);
procedure set_Transform (Self : in out Item'Class; for_Joint : in scene_joint_Id;
To : in Matrix_4x4);
procedure update_all_global_Transforms (Self : in out Item'Class);
procedure animate (Self : in out Item; world_Age : in Duration);
procedure reset_Animation (Self : in out Item);
private
-- gl_transform_Vector
--
package gl_transform_Vectors is new ada.Containers.Vectors (Positive, openGL.Matrix_4x4);
subtype gl_transform_Vector is gl_transform_Vectors.Vector;
-- joint_id_Map_of_matrix_4x4
--
package joint_id_Maps_of_matrix_4x4 is new ada.Containers.hashed_Maps (Key_type => scene_joint_Id,
Element_type => Matrix_4x4,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype joint_id_Map_of_matrix_4x4 is joint_id_Maps_of_matrix_4x4.Map;
-- joint_id_Map_of_scene_node
--
package joint_id_Maps_of_scene_node is new ada.Containers.hashed_Maps (Key_type => scene_joint_Id,
Element_type => collada.Library.visual_Scenes.Node_view,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => collada.Library.visual_Scenes."=");
subtype joint_id_Map_of_scene_node is joint_id_Maps_of_scene_node.Map;
-- joint_id_Map_of_slot
--
package joint_id_Maps_of_slot is new ada.Containers.hashed_Maps (Key_type => scene_joint_Id,
Element_type => Positive,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype joint_id_Map_of_slot is joint_id_Maps_of_slot.Map;
-- skin_program_Parameters
--
type skin_program_Parameters is new opengl.Program.Parameters with
record
bone_Transforms : gl_transform_Vector;
joint_Map_of_slot : joint_id_Map_of_slot;
end record;
overriding
procedure enable (Self : in out skin_program_Parameters);
-- joint_id_Map_of_joint_id
--
package joint_id_Maps_of_joint_id is new ada.Containers.hashed_Maps (Key_type => scene_joint_Id,
Element_type => scene_joint_Id,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => ada.Strings.unbounded."=");
subtype joint_id_Map_of_joint_id is joint_id_Maps_of_joint_id.Map;
-- scene_Joint
--
type scene_Joint is
record
Node : collada.Library.visual_Scenes.Node_view;
Transform : Matrix_4x4;
end record;
package joint_id_Maps_of_scene_Joint is new ada.Containers.hashed_Maps (Key_type => scene_joint_Id,
Element_type => scene_Joint,
Hash => ada.Strings.unbounded.Hash,
equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype joint_id_Map_of_scene_Joint is joint_id_Maps_of_scene_Joint.Map;
-- Transform
--
type Transform is
record
Rotation : Quaternion := linear_Algebra_3D.to_Quaternion (linear_Algebra_3D.x_Rotation_from (0.0));
Translation : Vector_3 := (0.0, 0.0, 0.0);
end record;
type Transforms is array (Positive range <>) of Transform;
type Transforms_view is access all Transforms;
-- animation_Channel
--
type animation_Channel is
record
Target : access collada.Library.visual_Scenes.Transform;
target_Joint : scene_joint_Id;
Times : access collada.float_Array;
Values : access collada.float_Array;
Cursor : Index := 0; -- Current frame of the anmination.
initial_Angle : Real; -- For angle interpolation during 'rotation' animation.
current_Angle : Real := 0.0; --
interp_Delta : Real := 0.0; --
initial_Site : Vector_3; -- For location interpolation during 'translation' animation.
current_Site : Vector_3; --
site_interp_Delta : Vector_3; --
initial_Transform : Transform; -- For matrix interpolation during 'full_transform' animation.
current_Transform : Transform; --
slerp_Time : Real; -- Slerp Time (T) value in range '0.0 .. 1.0'. -- TODO: use 'unit_Interval' type.
Transforms : Transforms_view;
Transform_interp_Delta : Real; -- Rate at which the SLERP time parameter increases.
end record;
subtype channel_Id is scene_joint_Id;
package channel_id_Maps_of_animation_Channel is new ada.Containers.hashed_Maps (Key_Type => channel_Id,
Element_Type => animation_Channel,
Hash => ada.Strings.unbounded.Hash,
Equivalent_Keys => ada.Strings.unbounded."=",
"=" => "=");
subtype channel_id_Map_of_animation_Channel is channel_id_Maps_of_animation_Channel.Map;
-- Rig Item
--
type Item is tagged limited
record
Mode : motion_Mode := Dynamics;
joint_Sprites : bone_id_Map_of_sprite; -- Sprite to show location/rotation of joints (mainly for debugging).
bone_Sprites : bone_id_Map_of_sprite; -- A sprite for each bone.
skin_Sprite : gel.Sprite.view; -- A sprite for the skin.
bind_shape_Matrix : Matrix_4x4;
Joints : gel_joint_id_Map_of_gel_Joint;
joint_inv_bind_Matrices : inverse_bind_matrix_Vector; -- The joint inverse transforms when in the bind pose.
phys_joint_site_Offets : joint_Id_Map_of_bone_site_offset; -- Offset from the bone site to the joint site when in the bind pose.
anim_joint_site_Offets : joint_Id_Map_of_bone_site_offset; -- Offset from the bone site to the joint site when in the bind pose.
joint_pose_Transforms : joint_id_Map_of_matrix_4x4; -- The joint transforms when in the skeletal pose.
joint_Parent : joint_id_Map_of_joint_id;
collada_Joints : joint_id_Map_of_scene_node;
scene_Joints : joint_id_Map_of_scene_Joint;
root_Joint : collada.Library.visual_scenes.Node_view;
animation_Transforms : bone_id_Map_of_transform;
bone_pose_Transforms : bone_id_Map_of_transform; -- The bone transforms when in the skeletal pose.
Channels : channel_id_Map_of_animation_Channel;
start_Time : Duration := 0.0;
overall_Site : Vector_3 := (0.0, 0.0, 0.0);
Model : openGL.Model.view;
program_Parameters : aliased skin_program_Parameters;
end record;
function Parent_of (Self : in Item; the_Bone : in bone_Id) return bone_Id;
function joint_site_Offet (Self : in Item; for_Bone : in bone_Id) return Vector_3;
function joint_inv_bind_Matrix (Self : in Item; for_Bone : in bone_Id) return Matrix_4x4;
function joint_bind_Matrix (Self : in Item; for_Bone : in bone_Id) return Matrix_4x4;
end gel.Rig;
|
30,790
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/opt64_pkg.adb
|
<reponame>best08618/asylo<filename>gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/opt64_pkg.adb
package body Opt64_PKG is
procedure Encode (X : Integer) is
result : Hash;
begin
case X is
when 1 => result := "1";
when 2 => result := "2";
when 3 => result := "3";
when others => Result := "?";
end case;
Last_Hash := Result;
end;
end;
|
30,791
|
ada
| 1
|
Jellix/open_weather_map_api
|
test/open_weather_map-application.ads
|
<filename>test/open_weather_map-application.ads
--------------------------------------------------------------------------------
-- Copyright (C) 2020 by Heisenbug Ltd. (<EMAIL>)
--
-- 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);
with Standard_Application;
private with Ada.Containers.Indefinite_Vectors;
private with Open_Weather_Map.API;
private with Open_Weather_Map.Client;
private with Open_Weather_Map.Configuration;
--------------------------------------------------------------------------------
--% @summary
--% A sample application showing the use of the openweathermap API.
--------------------------------------------------------------------------------
package Open_Weather_Map.Application is
type T is new Standard_Application.T with private;
-----------------------------------------------------------------------------
-- Initialize
-----------------------------------------------------------------------------
not overriding procedure Initialize (Self : in out T);
--% Initializes the application Self.
--
--% @param Self
--% Instance of application to initialize.
-----------------------------------------------------------------------------
-- Shutdown
-----------------------------------------------------------------------------
overriding procedure Shutdown (Self : in out T);
--% Shuts down the application Self.
--
--% @param Self
--% Instance of application to shut down.
-----------------------------------------------------------------------------
-- Work
-----------------------------------------------------------------------------
overriding procedure Work (Self : in out T);
--% The work procedure (i.e. main loop) of the application.
--
--% @param Self
--% Instance of application to run.
private
--% Query data set stored within the application.
--% Contains the new data received from a query and the previous data set.
--
--% @field Query
--% Access discriminant pointing to the query updating the data set.
type Query_Data_Set (Query : API.API_Class_Access) is
record
Data : Data_Set;
--% @field Data
--% The current data set.
Previous_Data : Data_Set;
--% @field Previous_Data
--% The previous data set.
end record;
package Queries is new
Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => Query_Data_Set);
type T is new Standard_Application.T with
record
Configuration : Open_Weather_Map.Configuration.T;
--% @field Configuration
--% Configuration data set.
Connection : Client.T_Access;
--% @field Connection
--% The HTTP server connection used for queries.
API_Calls : Queries.Vector;
--% @field API_Calls
--% The API calls implemented within the application.
end record;
-----------------------------------------------------------------------------
-- Update_And_Report
-----------------------------------------------------------------------------
not overriding procedure Update_And_Report (Self : in T;
Q : in out Query_Data_Set);
--% Updates the stored data set via HTTP requests and reports the new data
--% to the console.
--
--% @param Self
--% Instance of the application running.
--
--% @param Q
--% The query data set to be updated.
-----------------------------------------------------------------------------
-- Print
-----------------------------------------------------------------------------
procedure Print (City_Name : in String);
--% Prints the city name to standard output.
--
--% @param City_Name
--% The name of the city to print.
-----------------------------------------------------------------------------
-- Print
-----------------------------------------------------------------------------
procedure Print (H : in Types.Humidity);
--% Prints a humidity value to standard output.
--
--% @param H
--% The humidity value to print.
-----------------------------------------------------------------------------
-- Print
-----------------------------------------------------------------------------
procedure Print (P : in Types.Pressure);
--% Prints an atmospheric pressure value to standard output.
--
--% @param P
--% The pressure value to print.
-----------------------------------------------------------------------------
-- Print
-----------------------------------------------------------------------------
procedure Print (T : in Types.Celsius);
--% Prints a temperature value to standard output.
--
--% @param T
--% The temperature value to print.
-----------------------------------------------------------------------------
-- Print_Last_Update_On_Server
-----------------------------------------------------------------------------
procedure Print_Last_Update_On_Server
(Value : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset);
--% Prints the time of the last server update to standard output.
--
--% @param Value
--% The time of the update.
--
--% @param Time_Zone
--% The local time zone for Value.
-----------------------------------------------------------------------------
-- Print_Location
-----------------------------------------------------------------------------
procedure Print_Location (Loc : in Open_Weather_Map.Geo_Coordinates);
--% Prints the geographical coordinates to standard output.
--
--% @param Loc
--% The location to print.
-----------------------------------------------------------------------------
-- Print_Seconds_Since_Last_Query
-----------------------------------------------------------------------------
procedure Print_Seconds_Since_Last_Query
(Elapsed_Time : in Ada.Real_Time.Time_Span);
--% Prints the time elapsed since the last HTTP query done to standard
--% output.
--
--% @param Elapsed_Time
--% The time span since the last query.
-----------------------------------------------------------------------------
-- Print_Time
-----------------------------------------------------------------------------
procedure Print_Time (Value : in Ada.Calendar.Time;
Time_Zone : in Ada.Calendar.Time_Zones.Time_Offset);
--% Prints the given time to standard output.
--
--% @param Value
--% The time to print.
--
--% @param Time_Zone
--% The local time zone for Value.
-----------------------------------------------------------------------------
-- Print_Timestamp
-----------------------------------------------------------------------------
procedure Print_Timestamp (Value : in Ada.Real_Time.Time_Span);
--% Prints a time stamp to standard output.
--
--% @param Value
--% The time the timestamp shall be created from and printed.
end Open_Weather_Map.Application;
|
30,792
|
ada
| 1
|
djgoku/RosettaCodeData
|
Task/Loops-N-plus-one-half/Ada/loops-n-plus-one-half.ada
|
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
procedure Loop_And_Half is
I : Positive := 1;
begin
loop
Put(Item => I, Width => 1);
exit when I = 10;
Put(", ");
I := I + 1;
end loop;
New_Line;
end Loop_And_Half;
|
30,793
|
ada
| 7
|
best08618/asylo
|
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/controlled7.adb
|
<reponame>best08618/asylo<gh_stars>1-10
-- PR ada/53766
-- Reported by <NAME> <<EMAIL>>
-- { dg-do compile }
-- { dg-options "-gnatp" }
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package body Controlled7 is
procedure Proc (Offset : Storage_Offset) is
begin
if Offset + Unbounded_String'Max_Size_In_Storage_Elements >= 16 then
raise Program_Error;
end if;
end;
end Controlled7;
|
30,794
|
ada
| 0
|
JCGobbi/Nucleo-STM32G474RE
|
bb-runtimes/examples/stm32f4-discovery/leds-containers/src/driver.adb
|
<reponame>JCGobbi/Nucleo-STM32G474RE
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with LEDs; use LEDs;
with Button; use Button;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Containers.Doubly_Linked_Lists;
package body Driver is
package LED_Lists is new Ada.Containers.Doubly_Linked_Lists (User_LED);
use LED_Lists;
Pattern : List;
task body Controller is
Period : constant Time_Span := Milliseconds (70); -- arbitrary
Next_Start : Time := Clock;
Index : Cursor;
begin
Pattern.Append (Orange);
Pattern.Append (Red);
Pattern.Append (Blue);
Pattern.Append (Green);
Index := Pattern.First;
loop
Off (Element (Index));
if Button.Current_Direction = Clockwise then
if Index = Pattern.Last then
Index := Pattern.First;
else
Index := Next (Index);
end if;
else -- going the other direction
if Index = Pattern.First then
Index := Pattern.Last;
else
Index := Previous (Index);
end if;
end if;
On (Element (Index));
Next_Start := Next_Start + Period;
delay until Next_Start;
end loop;
end Controller;
end Driver;
|
30,795
|
ada
| 0
|
Lucretia/old_nehe_ada95
|
thirdparty/adasdl/thin/adasdl/AdaSDL_framebuff/compile.adb
|
pragma Warnings (Off);
with SDL_Framebuffer;
use SDL_Framebuffer;
procedure Compile is
begin
null;
end Compile;
|
30,796
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Hofstadter-Figure-Figure-sequences/Ada/hofstadter-figure-figure-sequences-2.ada
|
package body Hofstadter_Figure_Figure is
type Positive_Array is array (Positive range <>) of Positive;
function FFR(P: Positive) return Positive_Array is
Figures: Positive_Array(1 .. P+1);
Space: Positive := 2;
Space_Index: Positive := 2;
begin
Figures(1) := 1;
for I in 2 .. P loop
Figures(I) := Figures(I-1) + Space;
Space := Space+1;
while Space = Figures(Space_Index) loop
Space := Space + 1;
Space_Index := Space_Index + 1;
end loop;
end loop;
return Figures(1 .. P);
end FFR;
function FFR(P: Positive) return Positive is
Figures: Positive_Array(1 .. P) := FFR(P);
begin
return Figures(P);
end FFR;
function FFS(P: Positive) return Positive_Array is
Spaces: Positive_Array(1 .. P);
Figures: Positive_Array := FFR(P+1);
J: Positive := 1;
K: Positive := 1;
begin
for I in Spaces'Range loop
while J = Figures(K) loop
J := J + 1;
K := K + 1;
end loop;
Spaces(I) := J;
J := J + 1;
end loop;
return Spaces;
end FFS;
function FFS(P: Positive) return Positive is
Spaces: Positive_Array := FFS(P);
begin
return Spaces(P);
end FFS;
end Hofstadter_Figure_Figure;
|
30,797
|
ada
| 2
|
thindil/tashy2
|
src/tashy2.ads
|
-- Copyright (c) 2021 <NAME> <<EMAIL>>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Interfaces.C.Strings; use Interfaces.C.Strings;
-- ****h* Tashy2/Tashy2
-- FUNCTION
-- Various utility code not related to any Tcl command or API
-- SOURCE
package Tashy2 is
-- ****
pragma Warnings (Off, "no Global Contract available");
-- ****f* Utils/Utils.To_C_String
-- FUNCTION
-- Convert Ada String to C characters array
-- PARAMETERS
-- Str - Ada String to convert
-- RESULT
-- C characters array with converted String content
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Convert "Hello world" String to C characters array
-- C_String: constant chars_ptr := To_C_String("Hello world");
-- SEE ALSO
-- Utils.From_C_String
-- SOURCE
function To_C_String(Str: String) return chars_ptr is
(New_String(Str => Str)) with
Global => null,
Test_Case => (Name => "Test_To_C_String", Mode => Nominal);
-- ****
-- ****f* Utils/Utils.From_C_String
-- FUNCTION
-- Convert C characters array to Ada String
-- PARAMETERS
-- Item - C characters array to convert
-- RESULT
-- Ada String with converted C characters array content
-- HISTORY
-- 8.6.0 - Added
-- EXAMPLE
-- -- Convert "Hello world" C characters array to Ada String
-- Ada_String: constant String := From_C_String(To_C_String("Hello world"));
-- SEE ALSO
-- Utils.To_C_String
-- SOURCE
function From_C_String(Item: chars_ptr) return String is
(Value(Item => Item)) with
Global => null,
Test_Case => (Name => "Test_From_C_String", Mode => Nominal);
-- ****
pragma Warnings (On, "no Global Contract available");
end Tashy2;
|
30,798
|
ada
| 1
|
skill-lang/skillAdaTestSuite
|
test/constants/test_constants-write.adb
|
<gh_stars>1-10
package body Test_Constants.Write is
File_Name : constant String := "tmp/test-constants-write.sf";
procedure Initialize (T : in out Test) is
begin
Set_Name (T, "Test_Constants.Write");
Ahven.Framework.Add_Test_Routine (T, A'Access, "A: i8 = 8");
Ahven.Framework.Add_Test_Routine (T, B'Access, "B: i16 = 16");
Ahven.Framework.Add_Test_Routine (T, C'Access, "C: i32 = 32");
Ahven.Framework.Add_Test_Routine (T, D'Access, "D: i64 = 64");
Ahven.Framework.Add_Test_Routine (T, E'Access, "E: v64 = 46");
end Initialize;
procedure Set_Up (T : in out Test) is
State : access Skill_State := new Skill_State;
begin
Skill.Create (State);
for I in 1 .. 7 loop
New_Constant (State);
end loop;
Skill.Write (State, File_Name);
end Set_Up;
procedure Tear_Down (T : in out Test) is
begin
Ada.Directories.Delete_File (File_Name);
end Tear_Down;
procedure A (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
for I in 1 .. Constants_Size (State) loop
declare
X : Constant_Type_Access := Get_Constant (State, I);
begin
Ahven.Assert (8 = X.Get_A, "constant is not 8");
end;
end loop;
end A;
procedure B (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
for I in 1 .. Constants_Size (State) loop
declare
X : Constant_Type_Access := Get_Constant (State, I);
begin
Ahven.Assert (16 = X.Get_B, "constant is not 16");
end;
end loop;
end B;
procedure C (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
for I in 1 .. Constants_Size (State) loop
declare
X : Constant_Type_Access := Get_Constant (State, I);
begin
Ahven.Assert (32 = X.Get_C, "constant is not 32");
end;
end loop;
end C;
procedure D (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
for I in 1 .. Constants_Size (State) loop
declare
X : Constant_Type_Access := Get_Constant (State, I);
begin
Ahven.Assert (64 = X.Get_D, "constant is not 64");
end;
end loop;
end D;
procedure E (T : in out Ahven.Framework.Test_Case'Class) is
State : access Skill_State := new Skill_State;
begin
Skill.Read (State, File_Name);
for I in 1 .. Constants_Size (State) loop
declare
X : Constant_Type_Access := Get_Constant (State, I);
begin
Ahven.Assert (46 = X.Get_E, "constant is not 46");
end;
end loop;
end E;
end Test_Constants.Write;
|
30,799
|
ada
| 1
|
LaudateCorpus1/RosettaCodeData
|
Task/Chat-server/Ada/chat-server.ada
|
<reponame>LaudateCorpus1/RosettaCodeData<filename>Task/Chat-server/Ada/chat-server.ada<gh_stars>1-10
with Ada.Containers.Vectors;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Sockets; use Sockets;
procedure Chat_Server is
package Client_Vectors is new Ada.Containers.Vectors
(Element_Type => Socket_FD, Index_Type => Positive);
All_Clients : Client_Vectors.Vector;
procedure Write (S : String) is
procedure Output (Position : Client_Vectors.Cursor) is
Sock : Socket_FD := Client_Vectors.Element (Position);
begin
Put_Line (Sock, S);
end Output;
begin
All_Clients.Iterate (Output'Access);
end Write;
task type Client_Task is
entry Start (FD : Socket_FD);
end Client_Task;
task body Client_Task is
Sock : Socket_FD;
Sock_ID : Positive;
Name : Unbounded_String;
begin
select
accept Start (FD : Socket_FD) do
Sock := FD;
end Start;
or
terminate;
end select;
while Name = Null_Unbounded_String loop
Put (Sock, "Enter Name:");
Name := To_Unbounded_String (Get_Line (Sock));
end loop;
Write (To_String (Name) & " joined.");
All_Clients.Append (Sock);
Sock_ID := All_Clients.Find_Index (Sock);
loop
declare
Input : String := Get_Line (Sock);
begin
Write (To_String (Name) & ": " & Input);
end;
end loop;
exception
when Connection_Closed =>
Put_Line ("Connection closed");
Shutdown (Sock, Both);
All_Clients.Delete (Sock_ID);
Write (To_String (Name) & " left.");
end Client_Task;
Accepting_Socket : Socket_FD;
Incoming_Socket : Socket_FD;
type Client_Access is access Client_Task;
Dummy : Client_Access;
begin
if Argument_Count /= 1 then
Raise_Exception (Constraint_Error'Identity,
"Usage: " & Command_Name & " port");
end if;
Socket (Accepting_Socket, PF_INET, SOCK_STREAM);
Setsockopt (Accepting_Socket, SOL_SOCKET, SO_REUSEADDR, 1);
Bind (Accepting_Socket, Positive'Value (Argument (1)));
Listen (Accepting_Socket);
loop
Put_Line ("Waiting for new connection");
Accept_Socket (Accepting_Socket, Incoming_Socket);
Put_Line ("New connection acknowledged");
Dummy := new Client_Task;
Dummy.Start (Incoming_Socket);
end loop;
end Chat_Server;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.