text
stringlengths 437
491k
| meta
dict |
---|---|
with Ada.Text_IO; use Ada.Text_IO;
with Datastore; use Datastore;
procedure Main is
function Get
(Prompt : String)
return String is
begin
Put (" " & Prompt & "> ");
return Get_Line;
end Get;
Index : Integer;
begin
loop
Index := Integer'value (Get ("Enter index"));
exit when Index not in Datastore.Index_T'range;
-- Add a user-supplied string to the array at the specified index
end loop;
for I in Index_T'range loop
-- If the object pointed to by index is not empty,
-- Print each item in the list
null;
end loop;
end Main;
--Main
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
with HAL.SPI; use HAL.SPI;
package MicroBit.SPI is
type Speed is (S125kbps, S250kbps, S500kbps, S1Mbps, S2Mbps, S4Mbps, S8Mbps);
type SPI_Mode is (Mode_0, Mode_1, Mode_2, Mode_3);
function Initialized return Boolean;
-- Return True if the SPI controller is initialized and ready to use
procedure Initialize (S : Speed := S1Mbps;
Mode : SPI_Mode := Mode_0)
with Post => Initialized;
-- Initialize the SPI controller at given speed, using the micro:bit SPI
-- pins:
-- - P15 -> MOSI
-- - P14 -> MISO
-- - P13 -> Clock
function Controller return not null Any_SPI_Port;
-- Return the HAL.SPI controller implementation
end MicroBit.SPI;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
--------------------------------------------------------------------------------
-- $Author$
-- $Date$
-- $Revision$
with Kernel; use Kernel;
with System.Storage_Elements; use System.Storage_Elements;
with System.Unsigned_Types; use System.Unsigned_Types;
with System.Address_To_Access_Conversions;
with Unchecked_Deallocation;
with Reporter;
with RASCAL.Utility; use RASCAL.Utility;
with RASCAL.OS;
package body RASCAL.Memory is
type MemoryBlock;
type Ptr_MemoryBlock is access MemoryBlock;
type MemoryBlock is array (Integer range <>) of Integer;
type bytearray is array(0..3) of Short_Short_Unsigned;
type halfwordarray is array(0..1) of Short_Short_Unsigned;
type lonely_byte is array(0..0) of Short_Short_Unsigned;
type PString is new String(1..1024);
--
package AddressToStrAccess is new System.Address_To_Access_Conversions
(object => PString);
--
package AddressToIntAccess is new System.Address_To_Access_Conversions
(object => bytearray);
--
package AddressToHWAccess is new System.Address_To_Access_Conversions
(object => halfwordarray);
--
package AddressToByteAccess is new System.Address_To_Access_Conversions
(object => lonely_byte);
type MemoryBlockStructure;
type MemoryBlockStructurePtr is access MemoryBlockStructure;
type MemoryBlockStructure is
record
object_ptr : Ptr_MemoryBlock;
object_adr : mem_adr_type;
next : MemoryBlockStructurePtr := null;
end record;
Anker,ptr : MemoryBlockStructurePtr;
firsttime : Boolean := true;
times : Integer := 0;
times2: Integer := 0;
--procedure FreeMemoryBlock is new Unchecked_Deallocation
-- (MemoryBlock, Ptr_MemoryBlock);
-- now a hack to address bug in GNAT 3.03
procedure FreeMemoryBlock (Mem : in out Ptr_MemoryBlock) is
procedure free (Addr: in System.Address);
pragma Import (C,free);
use type System.Storage_Elements.Storage_Offset;
begin
if Mem /= null then
free (Mem.all'Address - 8);
Mem := null;
end if;
end FreeMemoryBlock;
--end hack
procedure FreeListElement is new Unchecked_Deallocation
(MemoryBlockStructure, MemoryBlockStructurePtr);
function Allocate (amount : in Integer) return mem_adr_type is
pointer : Ptr_MemoryBlock;
returnintptr : mem_adr_type;
iteration : Integer := 0;
byte_amount : Integer;
begin
times := times + 1;
-- Debug.ErrorLog("Allocate Aufruf Nr. "&intstr(times));
if (amount rem 4) = 0 then
byte_amount := amount / 4;
else
byte_amount := (amount / 4) + 1;
end if;
pointer := new MemoryBlock (0..byte_amount-1);
pointer := new MemoryBlock (0..byte_amount-1);
returnintptr := pointer(0)'Address;
if firsttime then
Anker := new MemoryBlockStructure;
firsttime := false;
end if;
ptr := Anker;
while ptr.next /= null loop
ptr := ptr.next;
iteration := iteration + 1;
-- Debug.ErrorLog("Iteration: "&intstr(iteration));
end loop;
ptr.next := new MemoryBlockStructure;
ptr := ptr.next;
ptr.object_ptr := pointer;
ptr.object_adr := returnintptr;
return returnintptr;
end Allocate;
function AllocateFixed (amount : in Integer) return mem_adr_type is
pointer : Ptr_MemoryBlock;
byte_amount : Integer;
begin
if (amount rem 4) = 0 then
byte_amount := amount / 4;
else
byte_amount := (amount / 4) + 1;
end if;
pointer := new MemoryBlock (0..byte_amount-1);
return pointer(0)'Address;
end AllocateFixed;
procedure Deallocate (pointer : in mem_adr_type) is
found : Boolean := false;
index : Integer := 1;
prev : MemoryBlockStructurePtr;
iteration : Integer := 0;
begin
times2 := times2 + 1;
-- Debug.ErrorLog("Deallocate Aufruf Nr. "&intstr(times2));
ptr := Anker;
while not found and ptr.next /= null loop
prev := ptr;
ptr := ptr.next;
iteration := iteration + 1;
-- Debug.ErrorLog("Iteration: "&intstr(iteration));
if ptr.object_adr = pointer then
found := true;
end if;
end loop;
if found then
prev.next := ptr.next;
-- Debug.ErrorLog("Freeing memory...");
-- Debug.ErrorLog("Ptr is: " & intstr(Integer(ptr.object_adr)));
FreeMemoryBlock(ptr.object_ptr);
-- Debug.ErrorLog("Freeing structure...");
FreeListElement(ptr);
end if;
end Deallocate;
--
function GetByte (Adr : in Address;
Offset : in Integer := 0) return Integer is
Ptr : AddressToByteAccess.Object_Pointer;
realword : System.Unsigned_Types.Unsigned := 0;
begin
Ptr := AddressToByteAccess.To_Pointer(Adr+Storage_Offset(Offset));
realword := System.Unsigned_Types.Unsigned(Ptr(0));
return Unsigned_To_Int(realword);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.GetByte"));
raise;
end GetByte;
--
function GetWordBig (Adr : in Address;
Offset : in Integer := 0) return Integer is
Ptr : AddressToIntAccess.Object_Pointer;
realword : System.Unsigned_Types.Unsigned := 0;
begin
Ptr := AddressToIntAccess.To_Pointer(Adr+Storage_Offset(Offset));
realword := System.Unsigned_Types.Unsigned(Ptr(3)) + Shift_Left(System.Unsigned_Types.Unsigned(Ptr(2)),8)
+ Shift_Left(System.Unsigned_Types.Unsigned(Ptr(1)),16)
+ Shift_Left(System.Unsigned_Types.Unsigned(Ptr(0)),24);
return Unsigned_To_Int(realword);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.GetWordBig"));
raise;
end GetWordBig;
--
function GetWord (Adr : in Address;
Offset : in Integer := 0) return Integer is
Ptr : AddressToIntAccess.Object_Pointer;
realword : Unsigned := 0;
begin
Ptr := AddressToIntAccess.To_Pointer(Adr+Storage_Offset(Offset));
realword := Unsigned(Ptr(0)) + Shift_Left(Unsigned(Ptr(1)),8)
+ Shift_Left(Unsigned(Ptr(2)),16)
+ Shift_Left(Unsigned(Ptr(3)),24);
return Unsigned_To_Int(realword);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.GetWord"));
raise;
end GetWord;
--
procedure PutByte (Byte : in Integer;
Adr : in Address;
Offset : in Integer := 0) is
Ptr : AddressToByteAccess.Object_Pointer;
realword : Unsigned;
begin
Ptr := AddressToByteAccess.To_Pointer(Adr+Storage_Offset(Offset));
realword := Int_To_Unsigned (Byte);
Ptr(0) := Short_Short_Unsigned(realword and 16#000000FF#);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.PutByte!"));
raise;
end PutByte;
--
procedure PutWord (Word : in Integer;
Adr : in Address;
Offset : in Integer := 0) is
Ptr : AddressToIntAccess.Object_Pointer;
realword : Unsigned;
begin
Ptr := AddressToIntAccess.To_Pointer(Adr+Storage_Offset(Offset));
realword := Int_To_Unsigned (Word);
Ptr(0) := Short_Short_Unsigned(realword and 16#000000FF#);
Ptr(1) := Short_Short_Unsigned(Shift_Right(realword and 16#0000FF00#,8));
Ptr(2) := Short_Short_Unsigned(Shift_Right(realword and 16#00FF0000#,16));
Ptr(3) := Short_Short_Unsigned(Shift_Right(realword and 16#FF000000#,24));
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.PutWord!"));
raise;
end PutWord;
--
function MemoryToString (Adr : in Address;
Offset : in Integer := 0;
Amount : in Integer) return String is
Str : String(1..1024);
i : Integer := 1;
j : Integer := 1;
Ptr : AddressToStrAccess.Object_Pointer;
Chr : Character;
begin
Ptr := AddressToStrAccess.To_Pointer(Adr+Storage_Offset(Offset));
i := Ptr'First;
Chr := Ptr(i);
while j <= Amount loop
Str(j) := Chr;
j := j + 1;
i := i + 1;
Chr := Ptr(i);
end loop;
return Str(1..j-1);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.MemoryToString!"));
raise;
end MemoryToString;
--
function MemoryToString (Adr : in Address;
Offset : in Integer := 0;
Terminator : in Character := Character'Val(31))
return String is
Str : String(1..1024);
i : Integer := 1;
j : Integer := 1;
Ptr : AddressToStrAccess.Object_Pointer;
Chr : Character;
begin
Ptr := AddressToStrAccess.To_Pointer(Adr+Storage_Offset(Offset));
i := Ptr'First;
Chr := Ptr(i);
while Chr > Terminator loop
Str(j) := Chr;
j := j + 1;
i := i + 1;
Chr := Ptr(i);
end loop;
return Str(1..j-1);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.MemoryToString!"));
raise;
end MemoryToString;
--
function Read_String (Adr : in Address;
Offset : in Integer := 0;
Terminator : in Character := Character'Val(31))
return String is
Str : String(1..1024);
i : Integer := 1;
j : Integer := 1;
Ptr : AddressToStrAccess.Object_Pointer;
Chr : Character;
begin
Ptr := AddressToStrAccess.To_Pointer(Adr+Storage_Offset(Offset));
i := Ptr'First;
Chr := Ptr(i);
while Chr /= Terminator loop
Str(j) := Chr;
j := j + 1;
i := i + 1;
Chr := Ptr(i);
end loop;
return Str(1..j-1);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.MemoryToString!"));
raise;
end Read_String;
--
function Get_Line (Adr : in Address;
Offset : in Integer := 0) return String is
Str : String(1..1024);
i : Integer := 1;
j : Integer := 1;
Ptr : AddressToStrAccess.Object_Pointer;
Chr : Character;
begin
Ptr := AddressToStrAccess.To_Pointer(Adr+Storage_Offset(Offset));
i := Ptr'First;
Chr := Ptr(i);
while Chr /= ASCII.LF loop
Str(j) := Chr;
j := j + 1;
i := i + 1;
Chr := Ptr(i);
end loop;
return Str(1..j-1);
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.Get_line"));
raise;
end Get_Line;
--
procedure StringToMemory (Str : in String;
Adr : in Address;
Offset : in Integer := 0;
padlength : in Integer := 0;
Terminator : in Character := Character'Val(0)) is
Ptr : AddressToStrAccess.Object_Pointer;
i,j : Integer;
begin
Ptr := AddressToStrAccess.To_Pointer(Adr+Storage_Offset(Offset));
i := Str'First;
j := 1;
while i <= Str'Last loop
Ptr(j) := Str(i);
i := i + 1;
j := j + 1;
end loop;
Ptr(j) := Terminator;
for j in Str'Length+1..padlength loop
Ptr(j) := Terminator;
end loop;
exception
when others => pragma Debug(Reporter.Report("Exception raised in Memory.StringToMemory!"));
raise;
end StringToMemory;
--
procedure MemCopy (Sourceadr : in Address;
Destadr : in Address;
Dest_offset : in Integer := 0;
Length : in Integer) is
begin
for i in 0..Length-1 loop
PutByte (GetByte(Sourceadr,i),Destadr,i+Dest_offset);
end loop;
end MemCopy;
--
end RASCAL.Memory;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with System.Storage_Barriers;
with System.Synchronous_Control;
package body System.Once is
pragma Suppress (All_Checks);
Yet : constant := 0;
Start : constant := 1;
Done : constant := 2;
function atomic_load (
ptr : not null access constant Flag;
memorder : Integer := Storage_Barriers.ATOMIC_ACQUIRE)
return Flag
with Import, Convention => Intrinsic, External_Name => "__atomic_load_1";
procedure atomic_store (
ptr : not null access Flag;
val : Flag;
memorder : Integer := Storage_Barriers.ATOMIC_RELEASE)
with Import,
Convention => Intrinsic, External_Name => "__atomic_store_1";
function atomic_compare_exchange (
ptr : not null access Flag;
expected : not null access Flag;
desired : Flag;
weak : Boolean := False;
success_memorder : Integer := Storage_Barriers.ATOMIC_ACQ_REL;
failure_memorder : Integer := Storage_Barriers.ATOMIC_ACQUIRE)
return Boolean
with Import,
Convention => Intrinsic,
External_Name => "__atomic_compare_exchange_1";
-- implementation
procedure Initialize (
Flag : not null access Once.Flag;
Process : not null access procedure)
is
Expected : aliased Once.Flag := Yet;
begin
if atomic_compare_exchange (Flag, Expected'Access, Start) then
-- succeeded to swap
Process.all;
atomic_store (Flag, Done);
elsif Expected = Start then
-- wait until Flag = Done
loop
Synchronous_Control.Yield;
exit when atomic_load (Flag) = Done;
end loop;
end if;
-- Flag = Done
end Initialize;
end System.Once;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Tags.Generic_Dispatching_Constructor;
with League.Strings.Hash;
with Matreshka.DOM_Attributes;
with Matreshka.DOM_Elements;
with Matreshka.DOM_Texts;
package body Matreshka.DOM_Documents is
procedure Split_Qualified_Name
(Qualified_Name : League.Strings.Universal_String;
Prefix : out League.Strings.Universal_String;
Local_Name : out League.Strings.Universal_String);
-- Splits qualified name into prefix and local name parts.
type Qualified_Name is record
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
end record;
function Hash (Item : Qualified_Name) return Ada.Containers.Hash_Type;
-- Hash function to be used with standard containers.
package Qualified_Name_Maps is
new Ada.Containers.Hashed_Maps
(Qualified_Name, Ada.Tags.Tag, Hash, "=", Ada.Tags."=");
Attribute_Registry : Qualified_Name_Maps.Map;
Element_Registry : Qualified_Name_Maps.Map;
------------------
-- Constructors --
------------------
package body Constructors is
----------------
-- Initialize --
----------------
procedure Initialize (Self : not null access Document_Node'Class) is
begin
Matreshka.DOM_Nodes.Constructors.Initialize (Self, Self);
end Initialize;
end Constructors;
----------------------
-- Create_Attribute --
----------------------
function Create_Attribute
(Self : not null access Document_Node'Class;
Namespace_URI : League.Strings.Universal_String;
Prefix : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String)
return not null XML.DOM.Attributes.DOM_Attribute_Access
is
function Constructor is
new Ada.Tags.Generic_Dispatching_Constructor
(Matreshka.DOM_Attributes.Abstract_Attribute_L2_Node,
Matreshka.DOM_Attributes.Attribute_L2_Parameters,
Matreshka.DOM_Attributes.Create);
Parameters : aliased Matreshka.DOM_Attributes.Attribute_L2_Parameters
:= (Document => Self,
Namespace_URI => Namespace_URI,
Prefix => Prefix,
Local_Name => Local_Name);
Position : Qualified_Name_Maps.Cursor;
Tag : Ada.Tags.Tag;
Node : Matreshka.DOM_Nodes.Node_Access;
begin
Position :=
Attribute_Registry.Find
((Parameters.Namespace_URI, Parameters.Local_Name));
if Qualified_Name_Maps.Has_Element (Position) then
Tag := Qualified_Name_Maps.Element (Position);
else
Tag := Matreshka.DOM_Attributes.Attribute_L2_Node'Tag;
end if;
Node :=
new Matreshka.DOM_Attributes.Abstract_Attribute_L2_Node'Class'
(Constructor (Tag, Parameters'Access));
return XML.DOM.Attributes.DOM_Attribute_Access (Node);
end Create_Attribute;
-------------------------
-- Create_Attribute_NS --
-------------------------
overriding function Create_Attribute_NS
(Self : not null access Document_Node;
Namespace_URI : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String)
return not null XML.DOM.Attributes.DOM_Attribute_Access
is
Prefix : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Node : constant not null Matreshka.DOM_Nodes.Node_Access
:= new Matreshka.DOM_Attributes.Attribute_L2_Node;
begin
Split_Qualified_Name (Qualified_Name, Prefix, Local_Name);
return Self.Create_Attribute (Namespace_URI, Prefix, Local_Name);
end Create_Attribute_NS;
--------------------
-- Create_Element --
--------------------
function Create_Element
(Self : not null access Document_Node'Class;
Namespace_URI : League.Strings.Universal_String;
Prefix : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String)
return not null XML.DOM.Elements.DOM_Element_Access
is
function Constructor is
new Ada.Tags.Generic_Dispatching_Constructor
(Matreshka.DOM_Elements.Abstract_Element_Node,
Matreshka.DOM_Elements.Element_L2_Parameters,
Matreshka.DOM_Elements.Create);
Parameters : aliased Matreshka.DOM_Elements.Element_L2_Parameters
:= (Document => Self,
Namespace_URI => Namespace_URI,
Prefix => Prefix,
Local_Name => Local_Name);
Position : Qualified_Name_Maps.Cursor;
Tag : Ada.Tags.Tag;
Node : Matreshka.DOM_Nodes.Node_Access;
begin
Position :=
Element_Registry.Find
((Parameters.Namespace_URI, Parameters.Local_Name));
if Qualified_Name_Maps.Has_Element (Position) then
Tag := Qualified_Name_Maps.Element (Position);
else
Tag := Matreshka.DOM_Elements.Element_Node'Tag;
end if;
Node :=
new Matreshka.DOM_Elements.Abstract_Element_Node'Class'
(Constructor (Tag, Parameters'Access));
return XML.DOM.Elements.DOM_Element_Access (Node);
end Create_Element;
-----------------------
-- Create_Element_NS --
-----------------------
overriding function Create_Element_NS
(Self : not null access Document_Node;
Namespace_URI : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String)
return not null XML.DOM.Elements.DOM_Element_Access
is
Prefix : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
begin
Split_Qualified_Name (Qualified_Name, Prefix, Local_Name);
return Self.Create_Element (Namespace_URI, Prefix, Local_Name);
end Create_Element_NS;
----------------------
-- Create_Text_Node --
----------------------
overriding function Create_Text_Node
(Self : not null access Document_Node;
Data : League.Strings.Universal_String)
return not null XML.DOM.Texts.DOM_Text_Access
is
Node : constant not null Matreshka.DOM_Nodes.Node_Access
:= new Matreshka.DOM_Texts.Text_Node;
begin
Matreshka.DOM_Texts.Constructors.Initialize
(Matreshka.DOM_Texts.Text_Node'Class (Node.all)'Access, Self, Data);
return XML.DOM.Texts.DOM_Text_Access (Node);
end Create_Text_Node;
----------------
-- Enter_Node --
----------------
overriding procedure Enter_Node
(Self : not null access Document_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
Visitor.Enter_Document
(XML.DOM.Documents.DOM_Document_Access (Self), Control);
end Enter_Node;
----------------
-- Error_Code --
----------------
overriding function Error_Code
(Self : not null access constant Document_Node)
return XML.DOM.Error_Code is
begin
return Self.Diagnosis;
end Error_Code;
------------------
-- Error_String --
------------------
overriding function Error_String
(Self : not null access constant Document_Node)
return League.Strings.Universal_String is
begin
return League.Strings.Empty_Universal_String;
end Error_String;
-------------------
-- Get_Node_Name --
-------------------
overriding function Get_Node_Name
(Self : not null access constant Document_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return League.Strings.To_Universal_String ("#document");
end Get_Node_Name;
-------------------
-- Get_Node_Type --
-------------------
overriding function Get_Node_Type
(Self : not null access constant Document_Node)
return XML.DOM.Node_Type
is
pragma Unreferenced (Self);
begin
return XML.DOM.Document_Node;
end Get_Node_Type;
------------------------
-- Get_Owner_Document --
------------------------
overriding function Get_Owner_Document
(Self : not null access constant Document_Node)
return XML.DOM.Documents.DOM_Document_Access
is
pragma Unreferenced (Self);
begin
return null;
end Get_Owner_Document;
----------
-- Hash --
----------
function Hash (Item : Qualified_Name) return Ada.Containers.Hash_Type is
use type Ada.Containers.Hash_Type;
begin
return
League.Strings.Hash (Item.Namespace_URI)
+ League.Strings.Hash (Item.Local_Name);
end Hash;
----------------
-- Leave_Node --
----------------
overriding procedure Leave_Node
(Self : not null access Document_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
Visitor.Leave_Document
(XML.DOM.Documents.DOM_Document_Access (Self), Control);
end Leave_Node;
------------------------
-- Register_Attribute --
------------------------
procedure Register_Attribute
(Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Tag : Ada.Tags.Tag) is
begin
Attribute_Registry.Insert ((Namespace_URI, Local_Name), Tag);
end Register_Attribute;
----------------------
-- Register_Element --
----------------------
procedure Register_Element
(Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Tag : Ada.Tags.Tag) is
begin
Element_Registry.Insert ((Namespace_URI, Local_Name), Tag);
end Register_Element;
--------------------------
-- Split_Qualified_Name --
--------------------------
procedure Split_Qualified_Name
(Qualified_Name : League.Strings.Universal_String;
Prefix : out League.Strings.Universal_String;
Local_Name : out League.Strings.Universal_String)
is
Delimiter : constant Natural := Qualified_Name.Index (':');
begin
if Delimiter = 0 then
Prefix := League.Strings.Empty_Universal_String;
Local_Name := Qualified_Name;
else
Prefix := Qualified_Name.Head (Delimiter - 1);
Local_Name := Qualified_Name.Tail_From (Delimiter + 1);
end if;
end Split_Qualified_Name;
----------------
-- Visit_Node --
----------------
overriding procedure Visit_Node
(Self : not null access Document_Node;
Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control) is
begin
Iterator.Visit_Document
(Visitor, XML.DOM.Documents.DOM_Document_Access (Self), Control);
end Visit_Node;
end Matreshka.DOM_Documents;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- see C:\AFRL_mentorship\OpenUxAS\src\Utilities\UxAS_ConfigurationManager.cpp
with String_Utils; use String_Utils;
with Ada.Strings.Fixed;
with Input_Sources.Strings;
with Input_Sources.File;
with DOM.Readers;
with DOM.Core.Documents;
with DOM.Core.Nodes;
with Sax.Encodings;
with DOM.Core.Elements;
with UxAS.Common.String_Constant;
package body UxAS.Common.Configuration_Manager is
--------------
-- Instance --
--------------
function Instance return not null Manager_Reference is
begin
if The_Instance = null then
The_Instance := new Manager;
end if;
return The_Instance;
end Instance;
-------------------
-- Get_Entity_Id --
-------------------
function Get_Entity_Id (This : not null access Manager) return UInt32 is
(This.Entity_Id);
---------------------
-- Get_Entity_Type --
---------------------
function Get_Entity_Type (This : not null access Manager) return String is
(Value (This.Entity_Type));
--------------------------
-- Get_Enabled_Services --
--------------------------
procedure Get_Enabled_Services
(This : not null access Manager;
Services : out DOM.Core.Element;
Result : out Boolean)
is
begin
if This.Base_XML_Doc_Loaded and not This.Enabled_Services_XML_Doc_Built then
Reset (This.Enabled_Services_XML_Doc);
This.Populate_Enabled_Components (This.Enabled_Services_XML_Doc, Node_Name => String_Constant.Service);
This.Enabled_Services_XML_Doc_Built := True;
end if;
Services := DOM.Core.Documents.Get_Element (This.Enabled_Services_XML_Doc);
Result := True;
exception
when others =>
Result := False;
end Get_Enabled_Services;
-------------------------
-- Get_Enabled_Bridges --
-------------------------
procedure Get_Enabled_Bridges
(This : not null access Manager;
Bridges : out DOM.Core.Element;
Result : out Boolean)
is
begin
if This.Base_XML_Doc_Loaded and not This.Enabled_Bridges_XML_Doc_Built then
Reset (This.Enabled_Bridges_XML_Doc);
This.Populate_Enabled_Components (This.Enabled_Bridges_XML_Doc, Node_Name => String_Constant.Bridge);
This.Enabled_Bridges_XML_Doc_Built := True;
end if;
Bridges := DOM.Core.Documents.Get_Element (This.Enabled_Bridges_XML_Doc);
Result := True;
exception
when others =>
Result := False;
end Get_Enabled_Bridges;
---------------------------------
-- Populate_Enabled_Components --
---------------------------------
procedure Populate_Enabled_Components
(This : not null access Manager;
Doc : in out DOM.Core.Document;
Node_Name : String)
is
use DOM.Core;
use DOM.Core.Nodes;
Unused : DOM.Core.Element;
Matching_Children : Node_List := DOM.Core.Documents.Get_Elements_By_Tag_Name (This.Base_XML_Doc, Node_Name);
UxAS_Node : DOM.Core.Element;
begin
UxAS_Node := DOM.Core.Documents.Create_Element (Doc, Tag_Name => String_Constant.UxAS);
UxAS_Node := DOM.Core.Nodes.Append_Child (Doc, New_Child => UxAS_Node);
DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => "FormatVersion", Value => "1.0");
DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => String_Constant.EntityId, Value => To_String (This.Get_Entity_Id));
DOM.Core.Elements.Set_Attribute (UxAS_Node, Name => String_Constant.EntityType, Value => This.Get_Entity_Type);
for K in Natural range 1 .. DOM.Core.Nodes.Length (Matching_Children) loop
Unused := Append_Child
(UXAS_Node,
New_Child => DOM.Core.Documents.Import_Node (Doc, Item (Matching_Children, K-1), Deep => True));
end loop;
DOM.Core.Free (Matching_Children);
end Populate_Enabled_Components;
------------------------
-- Load_Base_XML_File --
------------------------
procedure Load_Base_XML_File
(This : not null access Manager;
XML_File_Path : String;
Result : out Boolean)
is
begin
This.Load_XML
(XML_Input => XML_File_Path,
XML_Is_File => True,
Is_Base_XML => True,
Result => Result);
end Load_Base_XML_File;
--------------------------
-- Load_Base_XML_String --
--------------------------
procedure Load_Base_XML_String
(This : not null access Manager;
XML_Content : String;
Result : out Boolean)
is
begin
This.Load_XML
(XML_Input => XML_Content,
XML_Is_File => False,
Is_Base_XML => True,
Result => Result);
end Load_Base_XML_String;
--------------
-- Load_XML --
--------------
procedure Load_XML
(This : not null access Manager;
XML_Input : String;
XML_Is_File : Boolean;
Is_Base_XML : Boolean;
Result : out Boolean)
is
XML_Parse_Success : Boolean;
Reader : DOM.Readers.Tree_Reader;
begin
if Is_Base_XML then
if This.Base_XML_Doc_Loaded then
Reset (This.Base_XML_Doc);
This.Base_XML_Doc_Loaded := False;
This.Enabled_Bridges_XML_Doc_Built := False;
This.Enabled_Services_XML_Doc_Built := False;
end if;
if XML_Is_File then
declare
Input : Input_Sources.File.File_Input;
begin
Input_Sources.File.Open (XML_Input, Input);
Reader.Parse (Input);
Input_Sources.File.Close (Input);
This.Base_XML_Doc := DOM.Readers.Get_Tree (Reader);
XML_Parse_Success := True;
exception
when others =>
XML_Parse_Success := False;
end;
else -- input is not a file
declare
Input : Input_Sources.Strings.String_Input;
begin
Input_Sources.Strings.Open (XML_Input, Sax.Encodings.Encoding, Input);
Reader.Parse (Input);
Input_Sources.Strings.Close (Input);
This.Base_XML_Doc := DOM.Readers.Get_Tree (Reader);
XML_Parse_Success := True;
exception
when others =>
XML_Parse_Success := False;
end;
end if;
This.Base_XML_Doc_Loaded := True;
end if;
if XML_Parse_Success then
This.Set_Entity_Values_From_XML_Node
(Root => This.Base_XML_Doc,
Result => Result);
end if;
if not Result then
if Is_Base_XML then
This.Base_XML_Doc_Loaded := False;
end if;
end if;
end Load_XML;
----------------
-- Unload_XML --
----------------
procedure Unload_XML (This : not null access Manager) is
begin
Reset (This.Base_XML_Doc);
This.Base_XML_Doc_Loaded := False;
Reset (This.Enabled_Bridges_XML_Doc);
This.Enabled_Bridges_XML_Doc_Built := False;
Reset (This.Enabled_Services_XML_Doc);
This.Enabled_Services_XML_Doc_Built := False;
end Unload_XML;
-------------------------------------
-- Set_Entity_Values_From_XML_Node --
-------------------------------------
procedure Set_Entity_Values_From_XML_Node
(This : not null access Manager;
Root : DOM.Core.Document;
Result : out Boolean)
is
Success : Boolean := False;
use DOM.Core;
use DOM.Core.Elements;
Children : constant Node_List := DOM.Core.Documents.Get_Elements_By_Tag_Name (Root, String_Constant.UxAS);
EntityInfoXmlNode : constant Node := DOM.Core.Nodes.Item (Children, Index => 0);
begin
if EntityInfoXmlNode /= null then
declare
Str : constant DOM_String := Get_Attribute (EntityInfoXmlNode, Name => String_Constant.EntityID);
begin
if Str /= "" then
This.Entity_Id := UInt32'Value (Str);
Success := True;
end if;
end;
if Success then
declare
Str : constant DOM_String := Get_Attribute (EntityInfoXmlNode, Name => String_Constant.EntityType);
begin
if Str /= "" then
Copy (Str, To => This.Entity_Type);
else
Success := False;
end if;
end;
end if;
-- and so on, for ConsoleLoggerSeverityLevel, MainFileLoggerSeverityLevel, etc.
pragma Compile_Time_Warning (True, "Set_Entity_Values_From_XML_Node is incomplete");
end if;
Result := Success;
end Set_Entity_Values_From_XML_Node;
-----------
-- Reset --
-----------
procedure Reset (This : in out DOM.Core.Document) is
Impl : DOM.Core.DOM_Implementation;
begin
-- the Pugi version first does a destroy() call but that doesn't seem to
-- exist in the XMLAda version
This := DOM.Core.Create_Document (Impl);
end Reset;
------------------------------
-- Root_Data_Work_Directory --
------------------------------
function Root_Data_Work_Directory return String is
(Value (Root_Data_Work_Dir));
----------------------------------
-- Set_Root_Data_Work_Directory --
----------------------------------
procedure Set_Root_Data_Work_Directory (Value : String) is
begin
Copy (Value, To => Root_Data_Work_Dir);
end Set_Root_Data_Work_Directory;
------------------------------
-- Component_Data_Directory --
------------------------------
function Component_Data_Directory (Directory_Name : String) return String is
use Ada.Strings.Fixed;
use Ada.Strings;
Trimmed_Dir : constant String := Trim (Directory_Name, Both);
Suffix : constant String := (if Index (Trimmed_Dir, "/", Going => Backward) = 1 then "" else "/");
begin
-- return (s_rootDataInDirectory + directoryName + ((*(directoryName.rbegin()) == '/') ? "" : "/"));
return Root_DataIn_Directory & Trimmed_Dir & Suffix;
end Component_Data_Directory;
end UxAS.Common.Configuration_Manager;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
with Ada.Finalization;
with System; use type System.Address;
package body Ada.Containers.Bounded_Multiway_Trees is
pragma Warnings (Off, "variable ""Busy*"" is not referenced");
pragma Warnings (Off, "variable ""Lock*"" is not referenced");
-- See comment in Ada.Containers.Helpers
use Finalization;
--------------------
-- Root_Iterator --
--------------------
type Root_Iterator is abstract new Limited_Controlled and
Tree_Iterator_Interfaces.Forward_Iterator with
record
Container : Tree_Access;
Subtree : Count_Type;
end record;
overriding procedure Finalize (Object : in out Root_Iterator);
-----------------------
-- Subtree_Iterator --
-----------------------
type Subtree_Iterator is new Root_Iterator with null record;
overriding function First (Object : Subtree_Iterator) return Cursor;
overriding function Next
(Object : Subtree_Iterator;
Position : Cursor) return Cursor;
---------------------
-- Child_Iterator --
---------------------
type Child_Iterator is new Root_Iterator and
Tree_Iterator_Interfaces.Reversible_Iterator with null record;
overriding function First (Object : Child_Iterator) return Cursor;
overriding function Next
(Object : Child_Iterator;
Position : Cursor) return Cursor;
overriding function Last (Object : Child_Iterator) return Cursor;
overriding function Previous
(Object : Child_Iterator;
Position : Cursor) return Cursor;
-----------------------
-- Local Subprograms --
-----------------------
procedure Initialize_Node (Container : in out Tree; Index : Count_Type);
procedure Initialize_Root (Container : in out Tree);
procedure Allocate_Node
(Container : in out Tree;
Initialize_Element : not null access procedure (Index : Count_Type);
New_Node : out Count_Type);
procedure Allocate_Node
(Container : in out Tree;
New_Item : Element_Type;
New_Node : out Count_Type);
procedure Allocate_Node
(Container : in out Tree;
Stream : not null access Root_Stream_Type'Class;
New_Node : out Count_Type);
procedure Deallocate_Node
(Container : in out Tree;
X : Count_Type);
procedure Deallocate_Children
(Container : in out Tree;
Subtree : Count_Type;
Count : in out Count_Type);
procedure Deallocate_Subtree
(Container : in out Tree;
Subtree : Count_Type;
Count : in out Count_Type);
function Equal_Children
(Left_Tree : Tree;
Left_Subtree : Count_Type;
Right_Tree : Tree;
Right_Subtree : Count_Type) return Boolean;
function Equal_Subtree
(Left_Tree : Tree;
Left_Subtree : Count_Type;
Right_Tree : Tree;
Right_Subtree : Count_Type) return Boolean;
procedure Iterate_Children
(Container : Tree;
Subtree : Count_Type;
Process : not null access procedure (Position : Cursor));
procedure Iterate_Subtree
(Container : Tree;
Subtree : Count_Type;
Process : not null access procedure (Position : Cursor));
procedure Copy_Children
(Source : Tree;
Source_Parent : Count_Type;
Target : in out Tree;
Target_Parent : Count_Type;
Count : in out Count_Type);
procedure Copy_Subtree
(Source : Tree;
Source_Subtree : Count_Type;
Target : in out Tree;
Target_Parent : Count_Type;
Target_Subtree : out Count_Type;
Count : in out Count_Type);
function Find_In_Children
(Container : Tree;
Subtree : Count_Type;
Item : Element_Type) return Count_Type;
function Find_In_Subtree
(Container : Tree;
Subtree : Count_Type;
Item : Element_Type) return Count_Type;
function Child_Count
(Container : Tree;
Parent : Count_Type) return Count_Type;
function Subtree_Node_Count
(Container : Tree;
Subtree : Count_Type) return Count_Type;
function Is_Reachable
(Container : Tree;
From, To : Count_Type) return Boolean;
function Root_Node (Container : Tree) return Count_Type;
procedure Remove_Subtree
(Container : in out Tree;
Subtree : Count_Type);
procedure Insert_Subtree_Node
(Container : in out Tree;
Subtree : Count_Type'Base;
Parent : Count_Type;
Before : Count_Type'Base);
procedure Insert_Subtree_List
(Container : in out Tree;
First : Count_Type'Base;
Last : Count_Type'Base;
Parent : Count_Type;
Before : Count_Type'Base);
procedure Splice_Children
(Container : in out Tree;
Target_Parent : Count_Type;
Before : Count_Type'Base;
Source_Parent : Count_Type);
procedure Splice_Children
(Target : in out Tree;
Target_Parent : Count_Type;
Before : Count_Type'Base;
Source : in out Tree;
Source_Parent : Count_Type);
procedure Splice_Subtree
(Target : in out Tree;
Parent : Count_Type;
Before : Count_Type'Base;
Source : in out Tree;
Position : in out Count_Type); -- source on input, target on output
---------
-- "=" --
---------
function "=" (Left, Right : Tree) return Boolean is
begin
if Left.Count /= Right.Count then
return False;
end if;
if Left.Count = 0 then
return True;
end if;
return Equal_Children
(Left_Tree => Left,
Left_Subtree => Root_Node (Left),
Right_Tree => Right,
Right_Subtree => Root_Node (Right));
end "=";
-------------------
-- Allocate_Node --
-------------------
procedure Allocate_Node
(Container : in out Tree;
Initialize_Element : not null access procedure (Index : Count_Type);
New_Node : out Count_Type)
is
begin
if Container.Free >= 0 then
New_Node := Container.Free;
pragma Assert (New_Node in Container.Elements'Range);
-- We always perform the assignment first, before we change container
-- state, in order to defend against exceptions duration assignment.
Initialize_Element (New_Node);
Container.Free := Container.Nodes (New_Node).Next;
else
-- A negative free store value means that the links of the nodes in
-- the free store have not been initialized. In this case, the nodes
-- are physically contiguous in the array, starting at the index that
-- is the absolute value of the Container.Free, and continuing until
-- the end of the array (Nodes'Last).
New_Node := abs Container.Free;
pragma Assert (New_Node in Container.Elements'Range);
-- As above, we perform this assignment first, before modifying any
-- container state.
Initialize_Element (New_Node);
Container.Free := Container.Free - 1;
if abs Container.Free > Container.Capacity then
Container.Free := 0;
end if;
end if;
Initialize_Node (Container, New_Node);
end Allocate_Node;
procedure Allocate_Node
(Container : in out Tree;
New_Item : Element_Type;
New_Node : out Count_Type)
is
procedure Initialize_Element (Index : Count_Type);
procedure Initialize_Element (Index : Count_Type) is
begin
Container.Elements (Index) := New_Item;
end Initialize_Element;
begin
Allocate_Node (Container, Initialize_Element'Access, New_Node);
end Allocate_Node;
procedure Allocate_Node
(Container : in out Tree;
Stream : not null access Root_Stream_Type'Class;
New_Node : out Count_Type)
is
procedure Initialize_Element (Index : Count_Type);
procedure Initialize_Element (Index : Count_Type) is
begin
Element_Type'Read (Stream, Container.Elements (Index));
end Initialize_Element;
begin
Allocate_Node (Container, Initialize_Element'Access, New_Node);
end Allocate_Node;
-------------------
-- Ancestor_Find --
-------------------
function Ancestor_Find
(Position : Cursor;
Item : Element_Type) return Cursor
is
R, N : Count_Type;
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
-- AI-0136 says to raise PE if Position equals the root node. This does
-- not seem correct, as this value is just the limiting condition of the
-- search. For now we omit this check, pending a ruling from the ARG.
-- ???
--
-- if Checks and then Is_Root (Position) then
-- raise Program_Error with "Position cursor designates root";
-- end if;
R := Root_Node (Position.Container.all);
N := Position.Node;
while N /= R loop
if Position.Container.Elements (N) = Item then
return Cursor'(Position.Container, N);
end if;
N := Position.Container.Nodes (N).Parent;
end loop;
return No_Element;
end Ancestor_Find;
------------------
-- Append_Child --
------------------
procedure Append_Child
(Container : in out Tree;
Parent : Cursor;
New_Item : Element_Type;
Count : Count_Type := 1)
is
Nodes : Tree_Node_Array renames Container.Nodes;
First, Last : Count_Type;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Count = 0 then
return;
end if;
if Checks and then Container.Count > Container.Capacity - Count then
raise Capacity_Error
with "requested count exceeds available storage";
end if;
TC_Check (Container.TC);
if Container.Count = 0 then
Initialize_Root (Container);
end if;
Allocate_Node (Container, New_Item, First);
Nodes (First).Parent := Parent.Node;
Last := First;
for J in Count_Type'(2) .. Count loop
Allocate_Node (Container, New_Item, Nodes (Last).Next);
Nodes (Nodes (Last).Next).Parent := Parent.Node;
Nodes (Nodes (Last).Next).Prev := Last;
Last := Nodes (Last).Next;
end loop;
Insert_Subtree_List
(Container => Container,
First => First,
Last => Last,
Parent => Parent.Node,
Before => No_Node); -- means "insert at end of list"
Container.Count := Container.Count + Count;
end Append_Child;
------------
-- Assign --
------------
procedure Assign (Target : in out Tree; Source : Tree) is
Target_Count : Count_Type;
begin
if Target'Address = Source'Address then
return;
end if;
if Checks and then Target.Capacity < Source.Count then
raise Capacity_Error -- ???
with "Target capacity is less than Source count";
end if;
Target.Clear; -- Checks busy bit
if Source.Count = 0 then
return;
end if;
Initialize_Root (Target);
-- Copy_Children returns the number of nodes that it allocates, but it
-- does this by incrementing the count value passed in, so we must
-- initialize the count before calling Copy_Children.
Target_Count := 0;
Copy_Children
(Source => Source,
Source_Parent => Root_Node (Source),
Target => Target,
Target_Parent => Root_Node (Target),
Count => Target_Count);
pragma Assert (Target_Count = Source.Count);
Target.Count := Source.Count;
end Assign;
-----------------
-- Child_Count --
-----------------
function Child_Count (Parent : Cursor) return Count_Type is
begin
if Parent = No_Element then
return 0;
elsif Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return 0;
else
return Child_Count (Parent.Container.all, Parent.Node);
end if;
end Child_Count;
function Child_Count
(Container : Tree;
Parent : Count_Type) return Count_Type
is
NN : Tree_Node_Array renames Container.Nodes;
CC : Children_Type renames NN (Parent).Children;
Result : Count_Type;
Node : Count_Type'Base;
begin
Result := 0;
Node := CC.First;
while Node > 0 loop
Result := Result + 1;
Node := NN (Node).Next;
end loop;
return Result;
end Child_Count;
-----------------
-- Child_Depth --
-----------------
function Child_Depth (Parent, Child : Cursor) return Count_Type is
Result : Count_Type;
N : Count_Type'Base;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Child = No_Element then
raise Constraint_Error with "Child cursor has no element";
end if;
if Checks and then Parent.Container /= Child.Container then
raise Program_Error with "Parent and Child in different containers";
end if;
if Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
pragma Assert (Child = Parent);
return 0;
end if;
Result := 0;
N := Child.Node;
while N /= Parent.Node loop
Result := Result + 1;
N := Parent.Container.Nodes (N).Parent;
if Checks and then N < 0 then
raise Program_Error with "Parent is not ancestor of Child";
end if;
end loop;
return Result;
end Child_Depth;
-----------
-- Clear --
-----------
procedure Clear (Container : in out Tree) is
Container_Count : constant Count_Type := Container.Count;
Count : Count_Type;
begin
TC_Check (Container.TC);
if Container_Count = 0 then
return;
end if;
Container.Count := 0;
-- Deallocate_Children returns the number of nodes that it deallocates,
-- but it does this by incrementing the count value that is passed in,
-- so we must first initialize the count return value before calling it.
Count := 0;
Deallocate_Children
(Container => Container,
Subtree => Root_Node (Container),
Count => Count);
pragma Assert (Count = Container_Count);
end Clear;
------------------------
-- Constant_Reference --
------------------------
function Constant_Reference
(Container : aliased Tree;
Position : Cursor) return Constant_Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with
"Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong container";
end if;
if Checks and then Position.Node = Root_Node (Container) then
raise Program_Error with "Position cursor designates root";
end if;
-- Implement Vet for multiway tree???
-- pragma Assert (Vet (Position),
-- "Position cursor in Constant_Reference is bad");
declare
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Constant_Reference_Type :=
(Element => Container.Elements (Position.Node)'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Constant_Reference;
--------------
-- Contains --
--------------
function Contains
(Container : Tree;
Item : Element_Type) return Boolean
is
begin
return Find (Container, Item) /= No_Element;
end Contains;
----------
-- Copy --
----------
function Copy
(Source : Tree;
Capacity : Count_Type := 0) return Tree
is
C : Count_Type;
begin
if Capacity = 0 then
C := Source.Count;
elsif Capacity >= Source.Count then
C := Capacity;
elsif Checks then
raise Capacity_Error with "Capacity value too small";
end if;
return Target : Tree (Capacity => C) do
Initialize_Root (Target);
if Source.Count = 0 then
return;
end if;
Copy_Children
(Source => Source,
Source_Parent => Root_Node (Source),
Target => Target,
Target_Parent => Root_Node (Target),
Count => Target.Count);
pragma Assert (Target.Count = Source.Count);
end return;
end Copy;
-------------------
-- Copy_Children --
-------------------
procedure Copy_Children
(Source : Tree;
Source_Parent : Count_Type;
Target : in out Tree;
Target_Parent : Count_Type;
Count : in out Count_Type)
is
S_Nodes : Tree_Node_Array renames Source.Nodes;
S_Node : Tree_Node_Type renames S_Nodes (Source_Parent);
T_Nodes : Tree_Node_Array renames Target.Nodes;
T_Node : Tree_Node_Type renames T_Nodes (Target_Parent);
pragma Assert (T_Node.Children.First <= 0);
pragma Assert (T_Node.Children.Last <= 0);
T_CC : Children_Type;
C : Count_Type'Base;
begin
-- We special-case the first allocation, in order to establish the
-- representation invariants for type Children_Type.
C := S_Node.Children.First;
if C <= 0 then -- source parent has no children
return;
end if;
Copy_Subtree
(Source => Source,
Source_Subtree => C,
Target => Target,
Target_Parent => Target_Parent,
Target_Subtree => T_CC.First,
Count => Count);
T_CC.Last := T_CC.First;
-- The representation invariants for the Children_Type list have been
-- established, so we can now copy the remaining children of Source.
C := S_Nodes (C).Next;
while C > 0 loop
Copy_Subtree
(Source => Source,
Source_Subtree => C,
Target => Target,
Target_Parent => Target_Parent,
Target_Subtree => T_Nodes (T_CC.Last).Next,
Count => Count);
T_Nodes (T_Nodes (T_CC.Last).Next).Prev := T_CC.Last;
T_CC.Last := T_Nodes (T_CC.Last).Next;
C := S_Nodes (C).Next;
end loop;
-- We add the newly-allocated children to their parent list only after
-- the allocation has succeeded, in order to preserve invariants of the
-- parent.
T_Node.Children := T_CC;
end Copy_Children;
------------------
-- Copy_Subtree --
------------------
procedure Copy_Subtree
(Target : in out Tree;
Parent : Cursor;
Before : Cursor;
Source : Cursor)
is
Target_Subtree : Count_Type;
Target_Count : Count_Type;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Target'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Target'Unrestricted_Access then
raise Program_Error with "Before cursor not in container";
end if;
if Checks and then
Before.Container.Nodes (Before.Node).Parent /= Parent.Node
then
raise Constraint_Error with "Before cursor not child of Parent";
end if;
end if;
if Source = No_Element then
return;
end if;
if Checks and then Is_Root (Source) then
raise Constraint_Error with "Source cursor designates root";
end if;
if Target.Count = 0 then
Initialize_Root (Target);
end if;
-- Copy_Subtree returns a count of the number of nodes that it
-- allocates, but it works by incrementing the value that is passed
-- in. We must therefore initialize the count value before calling
-- Copy_Subtree.
Target_Count := 0;
Copy_Subtree
(Source => Source.Container.all,
Source_Subtree => Source.Node,
Target => Target,
Target_Parent => Parent.Node,
Target_Subtree => Target_Subtree,
Count => Target_Count);
Insert_Subtree_Node
(Container => Target,
Subtree => Target_Subtree,
Parent => Parent.Node,
Before => Before.Node);
Target.Count := Target.Count + Target_Count;
end Copy_Subtree;
procedure Copy_Subtree
(Source : Tree;
Source_Subtree : Count_Type;
Target : in out Tree;
Target_Parent : Count_Type;
Target_Subtree : out Count_Type;
Count : in out Count_Type)
is
T_Nodes : Tree_Node_Array renames Target.Nodes;
begin
-- First we allocate the root of the target subtree.
Allocate_Node
(Container => Target,
New_Item => Source.Elements (Source_Subtree),
New_Node => Target_Subtree);
T_Nodes (Target_Subtree).Parent := Target_Parent;
Count := Count + 1;
-- We now have a new subtree (for the Target tree), containing only a
-- copy of the corresponding element in the Source subtree. Next we copy
-- the children of the Source subtree as children of the new Target
-- subtree.
Copy_Children
(Source => Source,
Source_Parent => Source_Subtree,
Target => Target,
Target_Parent => Target_Subtree,
Count => Count);
end Copy_Subtree;
-------------------------
-- Deallocate_Children --
-------------------------
procedure Deallocate_Children
(Container : in out Tree;
Subtree : Count_Type;
Count : in out Count_Type)
is
Nodes : Tree_Node_Array renames Container.Nodes;
Node : Tree_Node_Type renames Nodes (Subtree); -- parent
CC : Children_Type renames Node.Children;
C : Count_Type'Base;
begin
while CC.First > 0 loop
C := CC.First;
CC.First := Nodes (C).Next;
Deallocate_Subtree (Container, C, Count);
end loop;
CC.Last := 0;
end Deallocate_Children;
---------------------
-- Deallocate_Node --
---------------------
procedure Deallocate_Node
(Container : in out Tree;
X : Count_Type)
is
NN : Tree_Node_Array renames Container.Nodes;
pragma Assert (X > 0);
pragma Assert (X <= NN'Last);
N : Tree_Node_Type renames NN (X);
pragma Assert (N.Parent /= X); -- node is active
begin
-- The tree container actually contains two lists: one for the "active"
-- nodes that contain elements that have been inserted onto the tree,
-- and another for the "inactive" nodes of the free store, from which
-- nodes are allocated when a new child is inserted in the tree.
-- We desire that merely declaring a tree object should have only
-- minimal cost; specially, we want to avoid having to initialize the
-- free store (to fill in the links), especially if the capacity of the
-- tree object is large.
-- The head of the free list is indicated by Container.Free. If its
-- value is non-negative, then the free store has been initialized in
-- the "normal" way: Container.Free points to the head of the list of
-- free (inactive) nodes, and the value 0 means the free list is
-- empty. Each node on the free list has been initialized to point to
-- the next free node (via its Next component), and the value 0 means
-- that this is the last node of the free list.
-- If Container.Free is negative, then the links on the free store have
-- not been initialized. In this case the link values are implied: the
-- free store comprises the components of the node array started with
-- the absolute value of Container.Free, and continuing until the end of
-- the array (Nodes'Last).
-- We prefer to lazy-init the free store (in fact, we would prefer to
-- not initialize it at all, because such initialization is an O(n)
-- operation). The time when we need to actually initialize the nodes in
-- the free store is when the node that becomes inactive is not at the
-- end of the active list. The free store would then be discontigous and
-- so its nodes would need to be linked in the traditional way.
-- It might be possible to perform an optimization here. Suppose that
-- the free store can be represented as having two parts: one comprising
-- the non-contiguous inactive nodes linked together in the normal way,
-- and the other comprising the contiguous inactive nodes (that are not
-- linked together, at the end of the nodes array). This would allow us
-- to never have to initialize the free store, except in a lazy way as
-- nodes become inactive. ???
-- When an element is deleted from the list container, its node becomes
-- inactive, and so we set its Parent and Prev components to an
-- impossible value (the index of the node itself), to indicate that it
-- is now inactive. This provides a useful way to detect a dangling
-- cursor reference.
N.Parent := X; -- Node is deallocated (not on active list)
N.Prev := X;
if Container.Free >= 0 then
-- The free store has previously been initialized. All we need to do
-- here is link the newly-free'd node onto the free list.
N.Next := Container.Free;
Container.Free := X;
elsif X + 1 = abs Container.Free then
-- The free store has not been initialized, and the node becoming
-- inactive immediately precedes the start of the free store. All
-- we need to do is move the start of the free store back by one.
N.Next := X; -- Not strictly necessary, but marginally safer
Container.Free := Container.Free + 1;
else
-- The free store has not been initialized, and the node becoming
-- inactive does not immediately precede the free store. Here we
-- first initialize the free store (meaning the links are given
-- values in the traditional way), and then link the newly-free'd
-- node onto the head of the free store.
-- See the comments above for an optimization opportunity. If the
-- next link for a node on the free store is negative, then this
-- means the remaining nodes on the free store are physically
-- contiguous, starting at the absolute value of that index value.
-- ???
Container.Free := abs Container.Free;
if Container.Free > Container.Capacity then
Container.Free := 0;
else
for J in Container.Free .. Container.Capacity - 1 loop
NN (J).Next := J + 1;
end loop;
NN (Container.Capacity).Next := 0;
end if;
NN (X).Next := Container.Free;
Container.Free := X;
end if;
end Deallocate_Node;
------------------------
-- Deallocate_Subtree --
------------------------
procedure Deallocate_Subtree
(Container : in out Tree;
Subtree : Count_Type;
Count : in out Count_Type)
is
begin
Deallocate_Children (Container, Subtree, Count);
Deallocate_Node (Container, Subtree);
Count := Count + 1;
end Deallocate_Subtree;
---------------------
-- Delete_Children --
---------------------
procedure Delete_Children
(Container : in out Tree;
Parent : Cursor)
is
Count : Count_Type;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
TC_Check (Container.TC);
if Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return;
end if;
-- Deallocate_Children returns a count of the number of nodes that it
-- deallocates, but it works by incrementing the value that is passed
-- in. We must therefore initialize the count value before calling
-- Deallocate_Children.
Count := 0;
Deallocate_Children (Container, Parent.Node, Count);
pragma Assert (Count <= Container.Count);
Container.Count := Container.Count - Count;
end Delete_Children;
-----------------
-- Delete_Leaf --
-----------------
procedure Delete_Leaf
(Container : in out Tree;
Position : in out Cursor)
is
X : Count_Type;
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor not in container";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
if Checks and then not Is_Leaf (Position) then
raise Constraint_Error with "Position cursor does not designate leaf";
end if;
TC_Check (Container.TC);
X := Position.Node;
Position := No_Element;
Remove_Subtree (Container, X);
Container.Count := Container.Count - 1;
Deallocate_Node (Container, X);
end Delete_Leaf;
--------------------
-- Delete_Subtree --
--------------------
procedure Delete_Subtree
(Container : in out Tree;
Position : in out Cursor)
is
X : Count_Type;
Count : Count_Type;
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor not in container";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
TC_Check (Container.TC);
X := Position.Node;
Position := No_Element;
Remove_Subtree (Container, X);
-- Deallocate_Subtree returns a count of the number of nodes that it
-- deallocates, but it works by incrementing the value that is passed
-- in. We must therefore initialize the count value before calling
-- Deallocate_Subtree.
Count := 0;
Deallocate_Subtree (Container, X, Count);
pragma Assert (Count <= Container.Count);
Container.Count := Container.Count - Count;
end Delete_Subtree;
-----------
-- Depth --
-----------
function Depth (Position : Cursor) return Count_Type is
Result : Count_Type;
N : Count_Type'Base;
begin
if Position = No_Element then
return 0;
end if;
if Is_Root (Position) then
return 1;
end if;
Result := 0;
N := Position.Node;
while N >= 0 loop
N := Position.Container.Nodes (N).Parent;
Result := Result + 1;
end loop;
return Result;
end Depth;
-------------
-- Element --
-------------
function Element (Position : Cursor) return Element_Type is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Node = Root_Node (Position.Container.all)
then
raise Program_Error with "Position cursor designates root";
end if;
return Position.Container.Elements (Position.Node);
end Element;
--------------------
-- Equal_Children --
--------------------
function Equal_Children
(Left_Tree : Tree;
Left_Subtree : Count_Type;
Right_Tree : Tree;
Right_Subtree : Count_Type) return Boolean
is
L_NN : Tree_Node_Array renames Left_Tree.Nodes;
R_NN : Tree_Node_Array renames Right_Tree.Nodes;
Left_Children : Children_Type renames L_NN (Left_Subtree).Children;
Right_Children : Children_Type renames R_NN (Right_Subtree).Children;
L, R : Count_Type'Base;
begin
if Child_Count (Left_Tree, Left_Subtree)
/= Child_Count (Right_Tree, Right_Subtree)
then
return False;
end if;
L := Left_Children.First;
R := Right_Children.First;
while L > 0 loop
if not Equal_Subtree (Left_Tree, L, Right_Tree, R) then
return False;
end if;
L := L_NN (L).Next;
R := R_NN (R).Next;
end loop;
return True;
end Equal_Children;
-------------------
-- Equal_Subtree --
-------------------
function Equal_Subtree
(Left_Position : Cursor;
Right_Position : Cursor) return Boolean
is
begin
if Checks and then Left_Position = No_Element then
raise Constraint_Error with "Left cursor has no element";
end if;
if Checks and then Right_Position = No_Element then
raise Constraint_Error with "Right cursor has no element";
end if;
if Left_Position = Right_Position then
return True;
end if;
if Is_Root (Left_Position) then
if not Is_Root (Right_Position) then
return False;
end if;
if Left_Position.Container.Count = 0 then
return Right_Position.Container.Count = 0;
end if;
if Right_Position.Container.Count = 0 then
return False;
end if;
return Equal_Children
(Left_Tree => Left_Position.Container.all,
Left_Subtree => Left_Position.Node,
Right_Tree => Right_Position.Container.all,
Right_Subtree => Right_Position.Node);
end if;
if Is_Root (Right_Position) then
return False;
end if;
return Equal_Subtree
(Left_Tree => Left_Position.Container.all,
Left_Subtree => Left_Position.Node,
Right_Tree => Right_Position.Container.all,
Right_Subtree => Right_Position.Node);
end Equal_Subtree;
function Equal_Subtree
(Left_Tree : Tree;
Left_Subtree : Count_Type;
Right_Tree : Tree;
Right_Subtree : Count_Type) return Boolean
is
begin
if Left_Tree.Elements (Left_Subtree) /=
Right_Tree.Elements (Right_Subtree)
then
return False;
end if;
return Equal_Children
(Left_Tree => Left_Tree,
Left_Subtree => Left_Subtree,
Right_Tree => Right_Tree,
Right_Subtree => Right_Subtree);
end Equal_Subtree;
--------------
-- Finalize --
--------------
procedure Finalize (Object : in out Root_Iterator) is
begin
Unbusy (Object.Container.TC);
end Finalize;
----------
-- Find --
----------
function Find
(Container : Tree;
Item : Element_Type) return Cursor
is
Node : Count_Type;
begin
if Container.Count = 0 then
return No_Element;
end if;
Node := Find_In_Children (Container, Root_Node (Container), Item);
if Node = 0 then
return No_Element;
end if;
return Cursor'(Container'Unrestricted_Access, Node);
end Find;
-----------
-- First --
-----------
overriding function First (Object : Subtree_Iterator) return Cursor is
begin
if Object.Subtree = Root_Node (Object.Container.all) then
return First_Child (Root (Object.Container.all));
else
return Cursor'(Object.Container, Object.Subtree);
end if;
end First;
overriding function First (Object : Child_Iterator) return Cursor is
begin
return First_Child (Cursor'(Object.Container, Object.Subtree));
end First;
-----------------
-- First_Child --
-----------------
function First_Child (Parent : Cursor) return Cursor is
Node : Count_Type'Base;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return No_Element;
end if;
Node := Parent.Container.Nodes (Parent.Node).Children.First;
if Node <= 0 then
return No_Element;
end if;
return Cursor'(Parent.Container, Node);
end First_Child;
-------------------------
-- First_Child_Element --
-------------------------
function First_Child_Element (Parent : Cursor) return Element_Type is
begin
return Element (First_Child (Parent));
end First_Child_Element;
----------------------
-- Find_In_Children --
----------------------
function Find_In_Children
(Container : Tree;
Subtree : Count_Type;
Item : Element_Type) return Count_Type
is
N : Count_Type'Base;
Result : Count_Type;
begin
N := Container.Nodes (Subtree).Children.First;
while N > 0 loop
Result := Find_In_Subtree (Container, N, Item);
if Result > 0 then
return Result;
end if;
N := Container.Nodes (N).Next;
end loop;
return 0;
end Find_In_Children;
---------------------
-- Find_In_Subtree --
---------------------
function Find_In_Subtree
(Position : Cursor;
Item : Element_Type) return Cursor
is
Result : Count_Type;
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
-- Commented-out pending ruling by ARG. ???
-- if Checks and then
-- Position.Container /= Container'Unrestricted_Access
-- then
-- raise Program_Error with "Position cursor not in container";
-- end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return No_Element;
end if;
if Is_Root (Position) then
Result := Find_In_Children
(Container => Position.Container.all,
Subtree => Position.Node,
Item => Item);
else
Result := Find_In_Subtree
(Container => Position.Container.all,
Subtree => Position.Node,
Item => Item);
end if;
if Result = 0 then
return No_Element;
end if;
return Cursor'(Position.Container, Result);
end Find_In_Subtree;
function Find_In_Subtree
(Container : Tree;
Subtree : Count_Type;
Item : Element_Type) return Count_Type
is
begin
if Container.Elements (Subtree) = Item then
return Subtree;
end if;
return Find_In_Children (Container, Subtree, Item);
end Find_In_Subtree;
------------------------
-- Get_Element_Access --
------------------------
function Get_Element_Access
(Position : Cursor) return not null Element_Access is
begin
return Position.Container.Elements (Position.Node)'Access;
end Get_Element_Access;
-----------------
-- Has_Element --
-----------------
function Has_Element (Position : Cursor) return Boolean is
begin
if Position = No_Element then
return False;
end if;
return Position.Node /= Root_Node (Position.Container.all);
end Has_Element;
---------------------
-- Initialize_Node --
---------------------
procedure Initialize_Node
(Container : in out Tree;
Index : Count_Type)
is
begin
Container.Nodes (Index) :=
(Parent => No_Node,
Prev => 0,
Next => 0,
Children => (others => 0));
end Initialize_Node;
---------------------
-- Initialize_Root --
---------------------
procedure Initialize_Root (Container : in out Tree) is
begin
Initialize_Node (Container, Root_Node (Container));
end Initialize_Root;
------------------
-- Insert_Child --
------------------
procedure Insert_Child
(Container : in out Tree;
Parent : Cursor;
Before : Cursor;
New_Item : Element_Type;
Count : Count_Type := 1)
is
Position : Cursor;
pragma Unreferenced (Position);
begin
Insert_Child (Container, Parent, Before, New_Item, Position, Count);
end Insert_Child;
procedure Insert_Child
(Container : in out Tree;
Parent : Cursor;
Before : Cursor;
New_Item : Element_Type;
Position : out Cursor;
Count : Count_Type := 1)
is
Nodes : Tree_Node_Array renames Container.Nodes;
First : Count_Type;
Last : Count_Type;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Before cursor not in container";
end if;
if Checks and then
Before.Container.Nodes (Before.Node).Parent /= Parent.Node
then
raise Constraint_Error with "Parent cursor not parent of Before";
end if;
end if;
if Count = 0 then
Position := No_Element; -- Need ruling from ARG ???
return;
end if;
if Checks and then Container.Count > Container.Capacity - Count then
raise Capacity_Error
with "requested count exceeds available storage";
end if;
TC_Check (Container.TC);
if Container.Count = 0 then
Initialize_Root (Container);
end if;
Allocate_Node (Container, New_Item, First);
Nodes (First).Parent := Parent.Node;
Last := First;
for J in Count_Type'(2) .. Count loop
Allocate_Node (Container, New_Item, Nodes (Last).Next);
Nodes (Nodes (Last).Next).Parent := Parent.Node;
Nodes (Nodes (Last).Next).Prev := Last;
Last := Nodes (Last).Next;
end loop;
Insert_Subtree_List
(Container => Container,
First => First,
Last => Last,
Parent => Parent.Node,
Before => Before.Node);
Container.Count := Container.Count + Count;
Position := Cursor'(Parent.Container, First);
end Insert_Child;
procedure Insert_Child
(Container : in out Tree;
Parent : Cursor;
Before : Cursor;
Position : out Cursor;
Count : Count_Type := 1)
is
Nodes : Tree_Node_Array renames Container.Nodes;
First : Count_Type;
Last : Count_Type;
pragma Warnings (Off);
Default_Initialized_Item : Element_Type;
pragma Unmodified (Default_Initialized_Item);
-- OK to reference, see below
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Before cursor not in container";
end if;
if Checks and then
Before.Container.Nodes (Before.Node).Parent /= Parent.Node
then
raise Constraint_Error with "Parent cursor not parent of Before";
end if;
end if;
if Count = 0 then
Position := No_Element; -- Need ruling from ARG ???
return;
end if;
if Checks and then Container.Count > Container.Capacity - Count then
raise Capacity_Error
with "requested count exceeds available storage";
end if;
TC_Check (Container.TC);
if Container.Count = 0 then
Initialize_Root (Container);
end if;
-- There is no explicit element provided, but in an instance the element
-- type may be a scalar with a Default_Value aspect, or a composite
-- type with such a scalar component, or components with default
-- initialization, so insert the specified number of possibly
-- initialized elements at the given position.
Allocate_Node (Container, Default_Initialized_Item, First);
Nodes (First).Parent := Parent.Node;
Last := First;
for J in Count_Type'(2) .. Count loop
Allocate_Node
(Container, Default_Initialized_Item, Nodes (Last).Next);
Nodes (Nodes (Last).Next).Parent := Parent.Node;
Nodes (Nodes (Last).Next).Prev := Last;
Last := Nodes (Last).Next;
end loop;
Insert_Subtree_List
(Container => Container,
First => First,
Last => Last,
Parent => Parent.Node,
Before => Before.Node);
Container.Count := Container.Count + Count;
Position := Cursor'(Parent.Container, First);
pragma Warnings (On);
end Insert_Child;
-------------------------
-- Insert_Subtree_List --
-------------------------
procedure Insert_Subtree_List
(Container : in out Tree;
First : Count_Type'Base;
Last : Count_Type'Base;
Parent : Count_Type;
Before : Count_Type'Base)
is
NN : Tree_Node_Array renames Container.Nodes;
N : Tree_Node_Type renames NN (Parent);
CC : Children_Type renames N.Children;
begin
-- This is a simple utility operation to insert a list of nodes
-- (First..Last) as children of Parent. The Before node specifies where
-- the new children should be inserted relative to existing children.
if First <= 0 then
pragma Assert (Last <= 0);
return;
end if;
pragma Assert (Last > 0);
pragma Assert (Before <= 0 or else NN (Before).Parent = Parent);
if CC.First <= 0 then -- no existing children
CC.First := First;
NN (CC.First).Prev := 0;
CC.Last := Last;
NN (CC.Last).Next := 0;
elsif Before <= 0 then -- means "insert after existing nodes"
NN (CC.Last).Next := First;
NN (First).Prev := CC.Last;
CC.Last := Last;
NN (CC.Last).Next := 0;
elsif Before = CC.First then
NN (Last).Next := CC.First;
NN (CC.First).Prev := Last;
CC.First := First;
NN (CC.First).Prev := 0;
else
NN (NN (Before).Prev).Next := First;
NN (First).Prev := NN (Before).Prev;
NN (Last).Next := Before;
NN (Before).Prev := Last;
end if;
end Insert_Subtree_List;
-------------------------
-- Insert_Subtree_Node --
-------------------------
procedure Insert_Subtree_Node
(Container : in out Tree;
Subtree : Count_Type'Base;
Parent : Count_Type;
Before : Count_Type'Base)
is
begin
-- This is a simple wrapper operation to insert a single child into the
-- Parent's children list.
Insert_Subtree_List
(Container => Container,
First => Subtree,
Last => Subtree,
Parent => Parent,
Before => Before);
end Insert_Subtree_Node;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Tree) return Boolean is
begin
return Container.Count = 0;
end Is_Empty;
-------------
-- Is_Leaf --
-------------
function Is_Leaf (Position : Cursor) return Boolean is
begin
if Position = No_Element then
return False;
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return True;
end if;
return Position.Container.Nodes (Position.Node).Children.First <= 0;
end Is_Leaf;
------------------
-- Is_Reachable --
------------------
function Is_Reachable
(Container : Tree;
From, To : Count_Type) return Boolean
is
Idx : Count_Type;
begin
Idx := From;
while Idx >= 0 loop
if Idx = To then
return True;
end if;
Idx := Container.Nodes (Idx).Parent;
end loop;
return False;
end Is_Reachable;
-------------
-- Is_Root --
-------------
function Is_Root (Position : Cursor) return Boolean is
begin
return
(if Position.Container = null then False
else Position.Node = Root_Node (Position.Container.all));
end Is_Root;
-------------
-- Iterate --
-------------
procedure Iterate
(Container : Tree;
Process : not null access procedure (Position : Cursor))
is
Busy : With_Busy (Container.TC'Unrestricted_Access);
begin
if Container.Count = 0 then
return;
end if;
Iterate_Children
(Container => Container,
Subtree => Root_Node (Container),
Process => Process);
end Iterate;
function Iterate (Container : Tree)
return Tree_Iterator_Interfaces.Forward_Iterator'Class
is
begin
return Iterate_Subtree (Root (Container));
end Iterate;
----------------------
-- Iterate_Children --
----------------------
procedure Iterate_Children
(Parent : Cursor;
Process : not null access procedure (Position : Cursor))
is
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return;
end if;
declare
C : Count_Type;
NN : Tree_Node_Array renames Parent.Container.Nodes;
Busy : With_Busy (Parent.Container.TC'Unrestricted_Access);
begin
C := NN (Parent.Node).Children.First;
while C > 0 loop
Process (Cursor'(Parent.Container, Node => C));
C := NN (C).Next;
end loop;
end;
end Iterate_Children;
procedure Iterate_Children
(Container : Tree;
Subtree : Count_Type;
Process : not null access procedure (Position : Cursor))
is
NN : Tree_Node_Array renames Container.Nodes;
N : Tree_Node_Type renames NN (Subtree);
C : Count_Type;
begin
-- This is a helper function to recursively iterate over all the nodes
-- in a subtree, in depth-first fashion. This particular helper just
-- visits the children of this subtree, not the root of the subtree
-- itself. This is useful when starting from the ultimate root of the
-- entire tree (see Iterate), as that root does not have an element.
C := N.Children.First;
while C > 0 loop
Iterate_Subtree (Container, C, Process);
C := NN (C).Next;
end loop;
end Iterate_Children;
function Iterate_Children
(Container : Tree;
Parent : Cursor)
return Tree_Iterator_Interfaces.Reversible_Iterator'Class
is
C : constant Tree_Access := Container'Unrestricted_Access;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= C then
raise Program_Error with "Parent cursor not in container";
end if;
return It : constant Child_Iterator :=
Child_Iterator'(Limited_Controlled with
Container => C,
Subtree => Parent.Node)
do
Busy (C.TC);
end return;
end Iterate_Children;
---------------------
-- Iterate_Subtree --
---------------------
function Iterate_Subtree
(Position : Cursor)
return Tree_Iterator_Interfaces.Forward_Iterator'Class
is
C : constant Tree_Access := Position.Container;
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
-- Implement Vet for multiway trees???
-- pragma Assert (Vet (Position), "bad subtree cursor");
return It : constant Subtree_Iterator :=
(Limited_Controlled with
Container => C,
Subtree => Position.Node)
do
Busy (C.TC);
end return;
end Iterate_Subtree;
procedure Iterate_Subtree
(Position : Cursor;
Process : not null access procedure (Position : Cursor))
is
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return;
end if;
declare
T : Tree renames Position.Container.all;
Busy : With_Busy (T.TC'Unrestricted_Access);
begin
if Is_Root (Position) then
Iterate_Children (T, Position.Node, Process);
else
Iterate_Subtree (T, Position.Node, Process);
end if;
end;
end Iterate_Subtree;
procedure Iterate_Subtree
(Container : Tree;
Subtree : Count_Type;
Process : not null access procedure (Position : Cursor))
is
begin
-- This is a helper function to recursively iterate over all the nodes
-- in a subtree, in depth-first fashion. It first visits the root of the
-- subtree, then visits its children.
Process (Cursor'(Container'Unrestricted_Access, Subtree));
Iterate_Children (Container, Subtree, Process);
end Iterate_Subtree;
----------
-- Last --
----------
overriding function Last (Object : Child_Iterator) return Cursor is
begin
return Last_Child (Cursor'(Object.Container, Object.Subtree));
end Last;
----------------
-- Last_Child --
----------------
function Last_Child (Parent : Cursor) return Cursor is
Node : Count_Type'Base;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return No_Element;
end if;
Node := Parent.Container.Nodes (Parent.Node).Children.Last;
if Node <= 0 then
return No_Element;
end if;
return Cursor'(Parent.Container, Node);
end Last_Child;
------------------------
-- Last_Child_Element --
------------------------
function Last_Child_Element (Parent : Cursor) return Element_Type is
begin
return Element (Last_Child (Parent));
end Last_Child_Element;
----------
-- Move --
----------
procedure Move (Target : in out Tree; Source : in out Tree) is
begin
if Target'Address = Source'Address then
return;
end if;
TC_Check (Source.TC);
Target.Assign (Source);
Source.Clear;
end Move;
----------
-- Next --
----------
overriding function Next
(Object : Subtree_Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Next designates wrong tree";
end if;
pragma Assert (Object.Container.Count > 0);
pragma Assert (Position.Node /= Root_Node (Object.Container.all));
declare
Nodes : Tree_Node_Array renames Object.Container.Nodes;
Node : Count_Type;
begin
Node := Position.Node;
if Nodes (Node).Children.First > 0 then
return Cursor'(Object.Container, Nodes (Node).Children.First);
end if;
while Node /= Object.Subtree loop
if Nodes (Node).Next > 0 then
return Cursor'(Object.Container, Nodes (Node).Next);
end if;
Node := Nodes (Node).Parent;
end loop;
return No_Element;
end;
end Next;
overriding function Next
(Object : Child_Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Next designates wrong tree";
end if;
pragma Assert (Object.Container.Count > 0);
pragma Assert (Position.Node /= Root_Node (Object.Container.all));
return Next_Sibling (Position);
end Next;
------------------
-- Next_Sibling --
------------------
function Next_Sibling (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return No_Element;
end if;
declare
T : Tree renames Position.Container.all;
NN : Tree_Node_Array renames T.Nodes;
N : Tree_Node_Type renames NN (Position.Node);
begin
if N.Next <= 0 then
return No_Element;
end if;
return Cursor'(Position.Container, N.Next);
end;
end Next_Sibling;
procedure Next_Sibling (Position : in out Cursor) is
begin
Position := Next_Sibling (Position);
end Next_Sibling;
----------------
-- Node_Count --
----------------
function Node_Count (Container : Tree) return Count_Type is
begin
-- Container.Count is the number of nodes we have actually allocated. We
-- cache the value specifically so this Node_Count operation can execute
-- in O(1) time, which makes it behave similarly to how the Length
-- selector function behaves for other containers.
--
-- The cached node count value only describes the nodes we have
-- allocated; the root node itself is not included in that count. The
-- Node_Count operation returns a value that includes the root node
-- (because the RM says so), so we must add 1 to our cached value.
return 1 + Container.Count;
end Node_Count;
------------
-- Parent --
------------
function Parent (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return No_Element;
end if;
declare
T : Tree renames Position.Container.all;
NN : Tree_Node_Array renames T.Nodes;
N : Tree_Node_Type renames NN (Position.Node);
begin
if N.Parent < 0 then
pragma Assert (Position.Node = Root_Node (T));
return No_Element;
end if;
return Cursor'(Position.Container, N.Parent);
end;
end Parent;
-------------------
-- Prepend_Child --
-------------------
procedure Prepend_Child
(Container : in out Tree;
Parent : Cursor;
New_Item : Element_Type;
Count : Count_Type := 1)
is
Nodes : Tree_Node_Array renames Container.Nodes;
First, Last : Count_Type;
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Count = 0 then
return;
end if;
if Checks and then Container.Count > Container.Capacity - Count then
raise Capacity_Error
with "requested count exceeds available storage";
end if;
TC_Check (Container.TC);
if Container.Count = 0 then
Initialize_Root (Container);
end if;
Allocate_Node (Container, New_Item, First);
Nodes (First).Parent := Parent.Node;
Last := First;
for J in Count_Type'(2) .. Count loop
Allocate_Node (Container, New_Item, Nodes (Last).Next);
Nodes (Nodes (Last).Next).Parent := Parent.Node;
Nodes (Nodes (Last).Next).Prev := Last;
Last := Nodes (Last).Next;
end loop;
Insert_Subtree_List
(Container => Container,
First => First,
Last => Last,
Parent => Parent.Node,
Before => Nodes (Parent.Node).Children.First);
Container.Count := Container.Count + Count;
end Prepend_Child;
--------------
-- Previous --
--------------
overriding function Previous
(Object : Child_Iterator;
Position : Cursor) return Cursor
is
begin
if Position.Container = null then
return No_Element;
end if;
if Checks and then Position.Container /= Object.Container then
raise Program_Error with
"Position cursor of Previous designates wrong tree";
end if;
return Previous_Sibling (Position);
end Previous;
----------------------
-- Previous_Sibling --
----------------------
function Previous_Sibling (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return No_Element;
end if;
declare
T : Tree renames Position.Container.all;
NN : Tree_Node_Array renames T.Nodes;
N : Tree_Node_Type renames NN (Position.Node);
begin
if N.Prev <= 0 then
return No_Element;
end if;
return Cursor'(Position.Container, N.Prev);
end;
end Previous_Sibling;
procedure Previous_Sibling (Position : in out Cursor) is
begin
Position := Previous_Sibling (Position);
end Previous_Sibling;
----------------------
-- Pseudo_Reference --
----------------------
function Pseudo_Reference
(Container : aliased Tree'Class) return Reference_Control_Type
is
TC : constant Tamper_Counts_Access := Container.TC'Unrestricted_Access;
begin
return R : constant Reference_Control_Type := (Controlled with TC) do
Lock (TC.all);
end return;
end Pseudo_Reference;
-------------------
-- Query_Element --
-------------------
procedure Query_Element
(Position : Cursor;
Process : not null access procedure (Element : Element_Type))
is
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
declare
T : Tree renames Position.Container.all'Unrestricted_Access.all;
Lock : With_Lock (T.TC'Unrestricted_Access);
begin
Process (Element => T.Elements (Position.Node));
end;
end Query_Element;
----------
-- Read --
----------
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Container : out Tree)
is
procedure Read_Children (Subtree : Count_Type);
function Read_Subtree
(Parent : Count_Type) return Count_Type;
NN : Tree_Node_Array renames Container.Nodes;
Total_Count : Count_Type'Base;
-- Value read from the stream that says how many elements follow
Read_Count : Count_Type'Base;
-- Actual number of elements read from the stream
-------------------
-- Read_Children --
-------------------
procedure Read_Children (Subtree : Count_Type) is
Count : Count_Type'Base;
-- number of child subtrees
CC : Children_Type;
begin
Count_Type'Read (Stream, Count);
if Checks and then Count < 0 then
raise Program_Error with "attempt to read from corrupt stream";
end if;
if Count = 0 then
return;
end if;
CC.First := Read_Subtree (Parent => Subtree);
CC.Last := CC.First;
for J in Count_Type'(2) .. Count loop
NN (CC.Last).Next := Read_Subtree (Parent => Subtree);
NN (NN (CC.Last).Next).Prev := CC.Last;
CC.Last := NN (CC.Last).Next;
end loop;
-- Now that the allocation and reads have completed successfully, it
-- is safe to link the children to their parent.
NN (Subtree).Children := CC;
end Read_Children;
------------------
-- Read_Subtree --
------------------
function Read_Subtree
(Parent : Count_Type) return Count_Type
is
Subtree : Count_Type;
begin
Allocate_Node (Container, Stream, Subtree);
Container.Nodes (Subtree).Parent := Parent;
Read_Count := Read_Count + 1;
Read_Children (Subtree);
return Subtree;
end Read_Subtree;
-- Start of processing for Read
begin
Container.Clear; -- checks busy bit
Count_Type'Read (Stream, Total_Count);
if Checks and then Total_Count < 0 then
raise Program_Error with "attempt to read from corrupt stream";
end if;
if Total_Count = 0 then
return;
end if;
if Checks and then Total_Count > Container.Capacity then
raise Capacity_Error -- ???
with "node count in stream exceeds container capacity";
end if;
Initialize_Root (Container);
Read_Count := 0;
Read_Children (Root_Node (Container));
if Checks and then Read_Count /= Total_Count then
raise Program_Error with "attempt to read from corrupt stream";
end if;
Container.Count := Total_Count;
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Position : out Cursor)
is
begin
raise Program_Error with "attempt to read tree cursor from stream";
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
procedure Read
(Stream : not null access Root_Stream_Type'Class;
Item : out Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Read;
---------------
-- Reference --
---------------
function Reference
(Container : aliased in out Tree;
Position : Cursor) return Reference_Type
is
begin
if Checks and then Position.Container = null then
raise Constraint_Error with
"Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with
"Position cursor designates wrong container";
end if;
if Checks and then Position.Node = Root_Node (Container) then
raise Program_Error with "Position cursor designates root";
end if;
-- Implement Vet for multiway tree???
-- pragma Assert (Vet (Position),
-- "Position cursor in Constant_Reference is bad");
declare
TC : constant Tamper_Counts_Access :=
Container.TC'Unrestricted_Access;
begin
return R : constant Reference_Type :=
(Element => Container.Elements (Position.Node)'Access,
Control => (Controlled with TC))
do
Lock (TC.all);
end return;
end;
end Reference;
--------------------
-- Remove_Subtree --
--------------------
procedure Remove_Subtree
(Container : in out Tree;
Subtree : Count_Type)
is
NN : Tree_Node_Array renames Container.Nodes;
N : Tree_Node_Type renames NN (Subtree);
CC : Children_Type renames NN (N.Parent).Children;
begin
-- This is a utility operation to remove a subtree node from its
-- parent's list of children.
if CC.First = Subtree then
pragma Assert (N.Prev <= 0);
if CC.Last = Subtree then
pragma Assert (N.Next <= 0);
CC.First := 0;
CC.Last := 0;
else
CC.First := N.Next;
NN (CC.First).Prev := 0;
end if;
elsif CC.Last = Subtree then
pragma Assert (N.Next <= 0);
CC.Last := N.Prev;
NN (CC.Last).Next := 0;
else
NN (N.Prev).Next := N.Next;
NN (N.Next).Prev := N.Prev;
end if;
end Remove_Subtree;
----------------------
-- Replace_Element --
----------------------
procedure Replace_Element
(Container : in out Tree;
Position : Cursor;
New_Item : Element_Type)
is
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor not in container";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
TE_Check (Container.TC);
Container.Elements (Position.Node) := New_Item;
end Replace_Element;
------------------------------
-- Reverse_Iterate_Children --
------------------------------
procedure Reverse_Iterate_Children
(Parent : Cursor;
Process : not null access procedure (Position : Cursor))
is
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Parent.Container.Count = 0 then
pragma Assert (Is_Root (Parent));
return;
end if;
declare
NN : Tree_Node_Array renames Parent.Container.Nodes;
Busy : With_Busy (Parent.Container.TC'Unrestricted_Access);
C : Count_Type;
begin
C := NN (Parent.Node).Children.Last;
while C > 0 loop
Process (Cursor'(Parent.Container, Node => C));
C := NN (C).Prev;
end loop;
end;
end Reverse_Iterate_Children;
----------
-- Root --
----------
function Root (Container : Tree) return Cursor is
begin
return (Container'Unrestricted_Access, Root_Node (Container));
end Root;
---------------
-- Root_Node --
---------------
function Root_Node (Container : Tree) return Count_Type is
pragma Unreferenced (Container);
begin
return 0;
end Root_Node;
---------------------
-- Splice_Children --
---------------------
procedure Splice_Children
(Target : in out Tree;
Target_Parent : Cursor;
Before : Cursor;
Source : in out Tree;
Source_Parent : Cursor)
is
begin
if Checks and then Target_Parent = No_Element then
raise Constraint_Error with "Target_Parent cursor has no element";
end if;
if Checks and then Target_Parent.Container /= Target'Unrestricted_Access
then
raise Program_Error
with "Target_Parent cursor not in Target container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Target'Unrestricted_Access then
raise Program_Error
with "Before cursor not in Target container";
end if;
if Checks and then
Target.Nodes (Before.Node).Parent /= Target_Parent.Node
then
raise Constraint_Error
with "Before cursor not child of Target_Parent";
end if;
end if;
if Checks and then Source_Parent = No_Element then
raise Constraint_Error with "Source_Parent cursor has no element";
end if;
if Checks and then Source_Parent.Container /= Source'Unrestricted_Access
then
raise Program_Error
with "Source_Parent cursor not in Source container";
end if;
if Source.Count = 0 then
pragma Assert (Is_Root (Source_Parent));
return;
end if;
if Target'Address = Source'Address then
if Target_Parent = Source_Parent then
return;
end if;
TC_Check (Target.TC);
if Checks and then Is_Reachable (Container => Target,
From => Target_Parent.Node,
To => Source_Parent.Node)
then
raise Constraint_Error
with "Source_Parent is ancestor of Target_Parent";
end if;
Splice_Children
(Container => Target,
Target_Parent => Target_Parent.Node,
Before => Before.Node,
Source_Parent => Source_Parent.Node);
return;
end if;
TC_Check (Target.TC);
TC_Check (Source.TC);
if Target.Count = 0 then
Initialize_Root (Target);
end if;
Splice_Children
(Target => Target,
Target_Parent => Target_Parent.Node,
Before => Before.Node,
Source => Source,
Source_Parent => Source_Parent.Node);
end Splice_Children;
procedure Splice_Children
(Container : in out Tree;
Target_Parent : Cursor;
Before : Cursor;
Source_Parent : Cursor)
is
begin
if Checks and then Target_Parent = No_Element then
raise Constraint_Error with "Target_Parent cursor has no element";
end if;
if Checks and then
Target_Parent.Container /= Container'Unrestricted_Access
then
raise Program_Error
with "Target_Parent cursor not in container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Container'Unrestricted_Access
then
raise Program_Error
with "Before cursor not in container";
end if;
if Checks and then
Container.Nodes (Before.Node).Parent /= Target_Parent.Node
then
raise Constraint_Error
with "Before cursor not child of Target_Parent";
end if;
end if;
if Checks and then Source_Parent = No_Element then
raise Constraint_Error with "Source_Parent cursor has no element";
end if;
if Checks and then
Source_Parent.Container /= Container'Unrestricted_Access
then
raise Program_Error
with "Source_Parent cursor not in container";
end if;
if Target_Parent = Source_Parent then
return;
end if;
pragma Assert (Container.Count > 0);
TC_Check (Container.TC);
if Checks and then Is_Reachable (Container => Container,
From => Target_Parent.Node,
To => Source_Parent.Node)
then
raise Constraint_Error
with "Source_Parent is ancestor of Target_Parent";
end if;
Splice_Children
(Container => Container,
Target_Parent => Target_Parent.Node,
Before => Before.Node,
Source_Parent => Source_Parent.Node);
end Splice_Children;
procedure Splice_Children
(Container : in out Tree;
Target_Parent : Count_Type;
Before : Count_Type'Base;
Source_Parent : Count_Type)
is
NN : Tree_Node_Array renames Container.Nodes;
CC : constant Children_Type := NN (Source_Parent).Children;
C : Count_Type'Base;
begin
-- This is a utility operation to remove the children from Source parent
-- and insert them into Target parent.
NN (Source_Parent).Children := Children_Type'(others => 0);
-- Fix up the Parent pointers of each child to designate its new Target
-- parent.
C := CC.First;
while C > 0 loop
NN (C).Parent := Target_Parent;
C := NN (C).Next;
end loop;
Insert_Subtree_List
(Container => Container,
First => CC.First,
Last => CC.Last,
Parent => Target_Parent,
Before => Before);
end Splice_Children;
procedure Splice_Children
(Target : in out Tree;
Target_Parent : Count_Type;
Before : Count_Type'Base;
Source : in out Tree;
Source_Parent : Count_Type)
is
S_NN : Tree_Node_Array renames Source.Nodes;
S_CC : Children_Type renames S_NN (Source_Parent).Children;
Target_Count, Source_Count : Count_Type;
T, S : Count_Type'Base;
begin
-- This is a utility operation to copy the children from the Source
-- parent and insert them as children of the Target parent, and then
-- delete them from the Source. (This is not a true splice operation,
-- but it is the best we can do in a bounded form.) The Before position
-- specifies where among the Target parent's exising children the new
-- children are inserted.
-- Before we attempt the insertion, we must count the sources nodes in
-- order to determine whether the target have enough storage
-- available. Note that calculating this value is an O(n) operation.
-- Here is an optimization opportunity: iterate of each children the
-- source explicitly, and keep a running count of the total number of
-- nodes. Compare the running total to the capacity of the target each
-- pass through the loop. This is more efficient than summing the counts
-- of child subtree (which is what Subtree_Node_Count does) and then
-- comparing that total sum to the target's capacity. ???
-- Here is another possibility. We currently treat the splice as an
-- all-or-nothing proposition: either we can insert all of children of
-- the source, or we raise exception with modifying the target. The
-- price for not causing side-effect is an O(n) determination of the
-- source count. If we are willing to tolerate side-effect, then we
-- could loop over the children of the source, counting that subtree and
-- then immediately inserting it in the target. The issue here is that
-- the test for available storage could fail during some later pass,
-- after children have already been inserted into target. ???
Source_Count := Subtree_Node_Count (Source, Source_Parent) - 1;
if Source_Count = 0 then
return;
end if;
if Checks and then Target.Count > Target.Capacity - Source_Count then
raise Capacity_Error -- ???
with "Source count exceeds available storage on Target";
end if;
-- Copy_Subtree returns a count of the number of nodes it inserts, but
-- it does this by incrementing the value passed in. Therefore we must
-- initialize the count before calling Copy_Subtree.
Target_Count := 0;
S := S_CC.First;
while S > 0 loop
Copy_Subtree
(Source => Source,
Source_Subtree => S,
Target => Target,
Target_Parent => Target_Parent,
Target_Subtree => T,
Count => Target_Count);
Insert_Subtree_Node
(Container => Target,
Subtree => T,
Parent => Target_Parent,
Before => Before);
S := S_NN (S).Next;
end loop;
pragma Assert (Target_Count = Source_Count);
Target.Count := Target.Count + Target_Count;
-- As with Copy_Subtree, operation Deallocate_Children returns a count
-- of the number of nodes it deallocates, but it works by incrementing
-- the value passed in. We must therefore initialize the count before
-- calling it.
Source_Count := 0;
Deallocate_Children (Source, Source_Parent, Source_Count);
pragma Assert (Source_Count = Target_Count);
Source.Count := Source.Count - Source_Count;
end Splice_Children;
--------------------
-- Splice_Subtree --
--------------------
procedure Splice_Subtree
(Target : in out Tree;
Parent : Cursor;
Before : Cursor;
Source : in out Tree;
Position : in out Cursor)
is
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Target'Unrestricted_Access then
raise Program_Error with "Parent cursor not in Target container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Target'Unrestricted_Access then
raise Program_Error with "Before cursor not in Target container";
end if;
if Checks and then Target.Nodes (Before.Node).Parent /= Parent.Node
then
raise Constraint_Error with "Before cursor not child of Parent";
end if;
end if;
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Source'Unrestricted_Access then
raise Program_Error with "Position cursor not in Source container";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
if Target'Address = Source'Address then
if Target.Nodes (Position.Node).Parent = Parent.Node then
if Before = No_Element then
if Target.Nodes (Position.Node).Next <= 0 then -- last child
return;
end if;
elsif Position.Node = Before.Node then
return;
elsif Target.Nodes (Position.Node).Next = Before.Node then
return;
end if;
end if;
TC_Check (Target.TC);
if Checks and then Is_Reachable (Container => Target,
From => Parent.Node,
To => Position.Node)
then
raise Constraint_Error with "Position is ancestor of Parent";
end if;
Remove_Subtree (Target, Position.Node);
Target.Nodes (Position.Node).Parent := Parent.Node;
Insert_Subtree_Node (Target, Position.Node, Parent.Node, Before.Node);
return;
end if;
TC_Check (Target.TC);
TC_Check (Source.TC);
if Target.Count = 0 then
Initialize_Root (Target);
end if;
Splice_Subtree
(Target => Target,
Parent => Parent.Node,
Before => Before.Node,
Source => Source,
Position => Position.Node); -- modified during call
Position.Container := Target'Unrestricted_Access;
end Splice_Subtree;
procedure Splice_Subtree
(Container : in out Tree;
Parent : Cursor;
Before : Cursor;
Position : Cursor)
is
begin
if Checks and then Parent = No_Element then
raise Constraint_Error with "Parent cursor has no element";
end if;
if Checks and then Parent.Container /= Container'Unrestricted_Access then
raise Program_Error with "Parent cursor not in container";
end if;
if Before /= No_Element then
if Checks and then Before.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Before cursor not in container";
end if;
if Checks and then Container.Nodes (Before.Node).Parent /= Parent.Node
then
raise Constraint_Error with "Before cursor not child of Parent";
end if;
end if;
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor not in container";
end if;
if Checks and then Is_Root (Position) then
-- Should this be PE instead? Need ARG confirmation. ???
raise Constraint_Error with "Position cursor designates root";
end if;
if Container.Nodes (Position.Node).Parent = Parent.Node then
if Before = No_Element then
if Container.Nodes (Position.Node).Next <= 0 then -- last child
return;
end if;
elsif Position.Node = Before.Node then
return;
elsif Container.Nodes (Position.Node).Next = Before.Node then
return;
end if;
end if;
TC_Check (Container.TC);
if Checks and then Is_Reachable (Container => Container,
From => Parent.Node,
To => Position.Node)
then
raise Constraint_Error with "Position is ancestor of Parent";
end if;
Remove_Subtree (Container, Position.Node);
Container.Nodes (Position.Node).Parent := Parent.Node;
Insert_Subtree_Node (Container, Position.Node, Parent.Node, Before.Node);
end Splice_Subtree;
procedure Splice_Subtree
(Target : in out Tree;
Parent : Count_Type;
Before : Count_Type'Base;
Source : in out Tree;
Position : in out Count_Type) -- Source on input, Target on output
is
Source_Count : Count_Type := Subtree_Node_Count (Source, Position);
pragma Assert (Source_Count >= 1);
Target_Subtree : Count_Type;
Target_Count : Count_Type;
begin
-- This is a utility operation to do the heavy lifting associated with
-- splicing a subtree from one tree to another. Note that "splicing"
-- is a bit of a misnomer here in the case of a bounded tree, because
-- the elements must be copied from the source to the target.
if Checks and then Target.Count > Target.Capacity - Source_Count then
raise Capacity_Error -- ???
with "Source count exceeds available storage on Target";
end if;
-- Copy_Subtree returns a count of the number of nodes it inserts, but
-- it does this by incrementing the value passed in. Therefore we must
-- initialize the count before calling Copy_Subtree.
Target_Count := 0;
Copy_Subtree
(Source => Source,
Source_Subtree => Position,
Target => Target,
Target_Parent => Parent,
Target_Subtree => Target_Subtree,
Count => Target_Count);
pragma Assert (Target_Count = Source_Count);
-- Now link the newly-allocated subtree into the target.
Insert_Subtree_Node
(Container => Target,
Subtree => Target_Subtree,
Parent => Parent,
Before => Before);
Target.Count := Target.Count + Target_Count;
-- The manipulation of the Target container is complete. Now we remove
-- the subtree from the Source container.
Remove_Subtree (Source, Position); -- unlink the subtree
-- As with Copy_Subtree, operation Deallocate_Subtree returns a count of
-- the number of nodes it deallocates, but it works by incrementing the
-- value passed in. We must therefore initialize the count before
-- calling it.
Source_Count := 0;
Deallocate_Subtree (Source, Position, Source_Count);
pragma Assert (Source_Count = Target_Count);
Source.Count := Source.Count - Source_Count;
Position := Target_Subtree;
end Splice_Subtree;
------------------------
-- Subtree_Node_Count --
------------------------
function Subtree_Node_Count (Position : Cursor) return Count_Type is
begin
if Position = No_Element then
return 0;
end if;
if Position.Container.Count = 0 then
pragma Assert (Is_Root (Position));
return 1;
end if;
return Subtree_Node_Count (Position.Container.all, Position.Node);
end Subtree_Node_Count;
function Subtree_Node_Count
(Container : Tree;
Subtree : Count_Type) return Count_Type
is
Result : Count_Type;
Node : Count_Type'Base;
begin
Result := 1;
Node := Container.Nodes (Subtree).Children.First;
while Node > 0 loop
Result := Result + Subtree_Node_Count (Container, Node);
Node := Container.Nodes (Node).Next;
end loop;
return Result;
end Subtree_Node_Count;
----------
-- Swap --
----------
procedure Swap
(Container : in out Tree;
I, J : Cursor)
is
begin
if Checks and then I = No_Element then
raise Constraint_Error with "I cursor has no element";
end if;
if Checks and then I.Container /= Container'Unrestricted_Access then
raise Program_Error with "I cursor not in container";
end if;
if Checks and then Is_Root (I) then
raise Program_Error with "I cursor designates root";
end if;
if I = J then -- make this test sooner???
return;
end if;
if Checks and then J = No_Element then
raise Constraint_Error with "J cursor has no element";
end if;
if Checks and then J.Container /= Container'Unrestricted_Access then
raise Program_Error with "J cursor not in container";
end if;
if Checks and then Is_Root (J) then
raise Program_Error with "J cursor designates root";
end if;
TE_Check (Container.TC);
declare
EE : Element_Array renames Container.Elements;
EI : constant Element_Type := EE (I.Node);
begin
EE (I.Node) := EE (J.Node);
EE (J.Node) := EI;
end;
end Swap;
--------------------
-- Update_Element --
--------------------
procedure Update_Element
(Container : in out Tree;
Position : Cursor;
Process : not null access procedure (Element : in out Element_Type))
is
begin
if Checks and then Position = No_Element then
raise Constraint_Error with "Position cursor has no element";
end if;
if Checks and then Position.Container /= Container'Unrestricted_Access
then
raise Program_Error with "Position cursor not in container";
end if;
if Checks and then Is_Root (Position) then
raise Program_Error with "Position cursor designates root";
end if;
declare
T : Tree renames Position.Container.all'Unrestricted_Access.all;
Lock : With_Lock (T.TC'Unrestricted_Access);
begin
Process (Element => T.Elements (Position.Node));
end;
end Update_Element;
-----------
-- Write --
-----------
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Container : Tree)
is
procedure Write_Children (Subtree : Count_Type);
procedure Write_Subtree (Subtree : Count_Type);
--------------------
-- Write_Children --
--------------------
procedure Write_Children (Subtree : Count_Type) is
CC : Children_Type renames Container.Nodes (Subtree).Children;
C : Count_Type'Base;
begin
Count_Type'Write (Stream, Child_Count (Container, Subtree));
C := CC.First;
while C > 0 loop
Write_Subtree (C);
C := Container.Nodes (C).Next;
end loop;
end Write_Children;
-------------------
-- Write_Subtree --
-------------------
procedure Write_Subtree (Subtree : Count_Type) is
begin
Element_Type'Write (Stream, Container.Elements (Subtree));
Write_Children (Subtree);
end Write_Subtree;
-- Start of processing for Write
begin
Count_Type'Write (Stream, Container.Count);
if Container.Count = 0 then
return;
end if;
Write_Children (Root_Node (Container));
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Position : Cursor)
is
begin
raise Program_Error with "attempt to write tree cursor to stream";
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
procedure Write
(Stream : not null access Root_Stream_Type'Class;
Item : Constant_Reference_Type)
is
begin
raise Program_Error with "attempt to stream reference";
end Write;
end Ada.Containers.Bounded_Multiway_Trees;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body System.Startup is
pragma Suppress (All_Checks);
-- weak reference for System.Unwind.Mapping
procedure Install_Exception_Handler (SEH : Address)
with Import, -- weak linking
Convention => Ada,
External_Name => "__drake_install_exception_handler";
pragma Weak_External (Install_Exception_Handler);
-- implementation
procedure Initialize (SEH : Address) is
begin
if Install_Exception_Handler'Address /= Null_Address then
Install_Exception_Handler (SEH);
end if;
end Initialize;
end System.Startup;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Long_Float_Text_IO; use Ada.Long_Float_Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure Haversine_Formula is
package Math is new Ada.Numerics.Generic_Elementary_Functions (Long_Float); use Math;
-- Compute great circle distance, given latitude and longitude of two points, in radians
function Great_Circle_Distance (lat1, long1, lat2, long2 : Long_Float) return Long_Float is
Earth_Radius : constant := 6371.0; -- in kilometers
a : Long_Float := Sin (0.5 * (lat2 - lat1));
b : Long_Float := Sin (0.5 * (long2 - long1));
begin
return 2.0 * Earth_Radius * ArcSin (Sqrt (a * a + Cos (lat1) * Cos (lat2) * b * b));
end Great_Circle_Distance;
-- convert degrees, minutes and seconds to radians
function DMS_To_Radians (Deg, Min, Sec : Long_Float := 0.0) return Long_Float is
Pi_Over_180 : constant := 0.017453_292519_943295_769236_907684_886127;
begin
return (Deg + Min/60.0 + Sec/3600.0) * Pi_Over_180;
end DMS_To_Radians;
begin
Put_Line("Distance in kilometers between BNA and LAX");
Put (Great_Circle_Distance (
DMS_To_Radians (36.0, 7.2), DMS_To_Radians (86.0, 40.2), -- Nashville International Airport (BNA)
DMS_To_Radians (33.0, 56.4), DMS_To_Radians (118.0, 24.0)), -- Los Angeles International Airport (LAX)
Aft=>3, Exp=>0);
end Haversine_Formula;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- Created On : Thu Jun 14 12:06:48 2012
-- Licence : See LICENCE in the root directory.
-- with Console; use Console;
procedure Last_Chance_Handler
(Source_Location : System.Address; Line : Integer) is
procedure Crash (Source_Location : System.Address; Line : Integer) with
Import => True,
Convention => Ada;
begin
-- TODO: Add in code to dump the info to serial/screen which
-- is obviously board specific.
-- Put ("Exception raised",
-- Screen_Width_Range'First,
-- Screen_Height_Range'Last);
Crash (Source_Location => Source_Location, Line => Line);
end Last_Chance_Handler;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces;
package Bit_Types is
pragma Preelaborate;
type Word is new Interfaces.Unsigned_32; -- for shift/rotate
type Half_Word is new Interfaces.Unsigned_16; -- for shift/rotate
type Byte is new Interfaces.Unsigned_8; -- for shift/rotate
type Unsigned_8 is mod 2**8 with Size => 8;
type Bits_1 is mod 2**1 with Size => 1;
type Bits_2 is mod 2**2 with Size => 2;
type Bits_3 is mod 2**3 with Size => 3;
type Bits_4 is mod 2**4 with Size => 4;
type Bits_5 is mod 2**5 with Size => 5;
type Bits_6 is mod 2**6 with Size => 6;
type Bits_7 is mod 2**7 with Size => 7;
type Bits_8 is mod 2**8 with Size => 8;
type Bits_9 is mod 2**9 with Size => 9;
type Bits_10 is mod 2**10 with Size => 10;
type Bits_11 is mod 2**11 with Size => 11;
type Bits_12 is mod 2**12 with Size => 12;
type Bits_13 is mod 2**13 with Size => 13;
type Bits_14 is mod 2**14 with Size => 14;
type Bits_15 is mod 2**15 with Size => 15;
type Bits_16 is mod 2**16 with Size => 16;
type Bits_17 is mod 2**17 with Size => 17;
type Bits_18 is mod 2**18 with Size => 18;
type Bits_19 is mod 2**19 with Size => 19;
type Bits_20 is mod 2**20 with Size => 20;
type Bits_21 is mod 2**21 with Size => 21;
type Bits_22 is mod 2**22 with Size => 22;
type Bits_23 is mod 2**23 with Size => 23;
type Bits_24 is mod 2**24 with Size => 24;
type Bits_25 is mod 2**25 with Size => 25;
type Bits_26 is mod 2**26 with Size => 26;
type Bits_27 is mod 2**27 with Size => 27;
type Bits_28 is mod 2**28 with Size => 28;
type Bits_29 is mod 2**29 with Size => 29;
type Bits_30 is mod 2**30 with Size => 30;
type Bits_31 is mod 2**31 with Size => 31;
type Bits_32x1 is array (0 .. 31) of Bits_1 with Pack, Size => 32;
type Bits_16x2 is array (0 .. 15) of Bits_2 with Pack, Size => 32;
type Bits_8x4 is array (0 .. 7) of Bits_4 with Pack, Size => 32;
end Bit_Types;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces.C, Interfaces.C.Pointers;
package Numerics.Sparse_Matrices.CSparse is
------- Define Matrix --------------------------------------------
type LU_Type is private;
------ Basic Getter function ------------------------------------
function N_Col (LU : in LU_Type) return Pos;
------ LU Decomposition -----------------------------------------
function LU_Decomposition (Mat : in Sparse_Matrix;
Tol : in Real := 1.0e-20) return LU_Type
with Pre => Is_Valid (Mat) and Is_Square_Matrix (Mat);
function Solve (LU : in LU_Type;
B : in Sparse_Vector;
Tol : in Real := 1.0e-20) return Sparse_Vector
with Pre => N_Col (LU) = Length (B);
function Solve (A : in Sparse_Matrix;
B : in Sparse_Vector;
Tol : in Real := 1.0e-20) return Sparse_Vector;
procedure Free (LU : in out LU_Type);
private
package C renames Interfaces.C;
type Creal is new C.double range C.double'First .. C.double'Last;
type Cint is new C.long range C.long'First .. C.long'Last;
subtype Cpos is Cint range 0 .. Cint'Last;
subtype Cnat is Cint range 1 .. Cint'Last;
type Creal_Array is array (Cnat range <>) of aliased Creal with Convention => C;
type Cint_Array is array (Cnat range <>) of aliased Cint with Convention => C;
------- Define pointer packages ----------------------------------
package Creal_Ptrs is new C.Pointers (Index => Cnat,
Element => Creal,
Element_Array => Creal_Array,
Default_Terminator => 0.0);
package Cint_Ptrs is new C.Pointers (Index => Cnat,
Element => Cint,
Element_Array => Cint_Array,
Default_Terminator => 0);
---- Define CS type -----------------------------------------
type Sparse_Type is
record
Nzmax : Cpos := 0;
M : Cpos := 0;
N : Cpos := 0;
I : Cint_Ptrs.Pointer;
P : Cint_Ptrs.Pointer;
X : Creal_Ptrs.Pointer;
Nz : Cpos := 0;
end record with Convention => C;
type Sparse_Ptr is access Sparse_Type with Convention => C;
type Symbolic_Type is
record
Pinv : Cint_Ptrs.Pointer;
Q : Cint_Ptrs.Pointer;
Parent : Cint_Ptrs.Pointer;
Cp : Cint_Ptrs.Pointer;
Leftmost : Cint_Ptrs.Pointer;
M2 : Cint;
Lnz : Creal;
Unz : Creal;
end record with Convention => C;
type Symbolic_Ptr is access Symbolic_Type with Convention => C;
type Numeric_Type is
record
L : Sparse_Ptr;
U : Sparse_Ptr;
Pinv : Cint_Ptrs.Pointer;
B : Creal_Ptrs.Pointer;
end record with Convention => C;
type Numeric_Ptr is access Numeric_Type with Convention => C;
type LU_Type is
record
Symbolic : Symbolic_Ptr;
Numeric : Numeric_Ptr;
NCol : Cpos := 0;
end record;
----------- Testing functions -------------------------------------------
function Is_Valid (P : in Creal_Ptrs.Pointer;
N : in Cpos) return Boolean;
------------ C functions -------------------------------------------------
function From_Arrays (M : in Cint;
N : in Cint;
Nz : in Cint;
I : in Cint_Array;
J : in Cint_Array;
X : in Creal_Array) return Sparse_Ptr
with Import => True, Convention => C, External_Name => "from_arrays";
function To_CS (M : in Cint;
N : in Cint;
Nzmax : in Cint;
I : in Cint_Array;
P : in Cint_Array;
X : in Creal_Array) return Sparse_Ptr
with Import => True, Convention => C, External_Name => "to_cs";
function CS_Sqr (A : in Cint := 0;
Prob : in Sparse_Ptr;
B : in Cint := 0) return Symbolic_Ptr
with Import => True, Convention => C, External_Name => "cs_dl_sqr";
function CS_LU (Prob : in Sparse_Ptr;
S : in Symbolic_Ptr;
Tol : in Creal := 1.0e-15) return Numeric_Ptr
with Import => True, Convention => C, External_Name => "cs_dl_lu";
function Solve_CS (N_Col : in Cint;
S : in Symbolic_Ptr;
N : in Numeric_Ptr;
B : in Creal_Array;
Err : out C.int) return Creal_Ptrs.Pointer
with Import => True, Convention => C, External_Name => "solve_cs";
function Free (Sparse : in Sparse_Ptr) return Sparse_Ptr
with Import => True, Convention => C, External_Name => "cs_dl_spfree";
function Free (Symbolic : in Symbolic_Ptr) return Symbolic_Ptr
with Import => True, Convention => C, External_Name => "cs_dl_sfree";
function Free (Numeric : in Numeric_Ptr) return Numeric_Ptr
with Import => True, Convention => C, External_Name => "cs_dl_nfree";
procedure Print_Sparse (Sparse : in Sparse_Ptr)
with Import => True, Convention => C, External_Name => "print_cs";
function To_Sparse (Mat : in Sparse_Matrix) return Sparse_Ptr;
function Solve (LU : in LU_Type;
B : in Creal_Array) return Creal_Ptrs.Pointer
with Post => Is_Valid (Solve'Result, B'Length);
function Solve (LU : in LU_Type;
B : in Creal_Array) return Creal_Array
with Pre => N_Col (LU) = B'Length;
function To_Array (X : in RVector) return Creal_Array;
function To_Array (X : in IVector) return Cint_Array;
end Numerics.Sparse_Matrices.CSparse;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
--*
-- * \enum TCOD_bkgnd_flag_t
-- *
-- * Background color blend modes.
--
type TCOD_bkgnd_flag_t is
(TCOD_BKGND_NONE,
TCOD_BKGND_SET,
TCOD_BKGND_MULTIPLY,
TCOD_BKGND_LIGHTEN,
TCOD_BKGND_DARKEN,
TCOD_BKGND_SCREEN,
TCOD_BKGND_COLOR_DODGE,
TCOD_BKGND_COLOR_BURN,
TCOD_BKGND_ADD,
TCOD_BKGND_ADDA,
TCOD_BKGND_BURN,
TCOD_BKGND_OVERLAY,
TCOD_BKGND_ALPH,
TCOD_BKGND_DEFAULT)
with Convention => C; -- console.h:66
--*
-- * \enum TCOD_alignment_t
-- *
-- * Print justification options.
--
type TCOD_alignment_t is
(TCOD_LEFT,
TCOD_RIGHT,
TCOD_CENTER)
with Convention => C; -- console.h:72
--*
-- A console tile.
--
--*
-- The Unicode codepoint for this tile.
--
type TCOD_ConsoleTile is record
ch : aliased int; -- console.h:84
fg : aliased color_h.TCOD_ColorRGBA; -- console.h:88
bg : aliased color_h.TCOD_ColorRGBA; -- console.h:92
end record
with Convention => C_Pass_By_Copy; -- console.h:76
--*
-- The tile glyph color, rendered on top of the background.
--
--*
-- The tile background color, rendered behind the glyph.
--
--*
-- The libtcod console struct.
-- All attributes should be considered private.
-- All C++ methods should be considered provisional, and are subject to
-- change.
--
--*
-- Return a reference to the tile at `xy`.
--
--*
-- Return a constant reference to the tile at `xy`.
--
--*
-- Return a reference to the tile at `x`,`y`.
-- Throws if the index is out-of-bounds.
--
--*
-- Return a constant reference to the tile at `x`,`y`.
-- Throws if the index is out-of-bounds.
--
--*
-- Return the total number of tiles in this console.
--
--*
-- Internal function. Throws `std::out_of_range` if `x` or `y` is out-of-bounds.
--
--*
-- Return true if `x`,`y` are within the bounds of this console.
--
--* Console width and height (in characters, not pixels.)
type TCOD_Console;
type TCOD_Console is record
w : aliased int; -- console.h:156
h : aliased int; -- console.h:156
tiles : access TCOD_ConsoleTile; -- console.h:158
bkgnd_flag : aliased TCOD_bkgnd_flag_t; -- console.h:160
alignment : aliased TCOD_alignment_t; -- console.h:162
fore : aliased color_h.TCOD_color_t; -- console.h:164
back : aliased color_h.TCOD_color_t; -- console.h:164
has_key_color : aliased Extensions.bool; -- console.h:166
key_color : aliased color_h.TCOD_color_t; -- console.h:168
elements : aliased int; -- console.h:176
userdata : System.Address; -- console.h:182
on_delete : access procedure (arg1 : access TCOD_Console); -- console.h:184
end record
with Convention => C_Pass_By_Copy; -- console.h:102
--* A contiguous array of console tiles.
--* Default background operator for print & print_rect functions.
--* Default alignment for print & print_rect functions.
--* Foreground (text) and background colors.
--* True if a key color is being used.
--* The current key color for this console.
--*
-- The total length of the tiles array. Same as `w * h`.
-- \rst
-- .. versionadded:: 1.16
-- \endrst
--
--*
-- \rst
-- .. versionadded:: 1.16
-- \endrst
--
--* Internal use.
type TCOD_console_t is access all TCOD_Console; -- console.h:187
--*
-- * Return a new console with a specific number of columns and rows.
-- *
-- * \param w Number of columns.
-- * \param h Number of columns.
-- * \return A pointer to the new console, or NULL on error.
--
function TCOD_console_new (arg1 : int; arg2 : int) return access TCOD_Console -- console.h:198
with Import => True,
Convention => C,
External_Name => "TCOD_console_new";
--*
-- * Return the width of a console.
--
function TCOD_console_get_width (con : access constant TCOD_Console) return int -- console.h:202
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_width";
--*
-- * Return the height of a console.
--
function TCOD_console_get_height (con : access constant TCOD_Console) return int -- console.h:206
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_height";
procedure TCOD_console_set_key_color (con : access TCOD_Console; col : color_h.TCOD_color_t) -- console.h:207
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_key_color";
--*
-- * Blit from one console to another.
-- *
-- * \param srcCon Pointer to the source console.
-- * \param xSrc The left region of the source console to blit from.
-- * \param ySrc The top region of the source console to blit from.
-- * \param wSrc The width of the region to blit from.
-- * If 0 then it will fill to the maximum width.
-- * \param hSrc The height of the region to blit from.
-- * If 0 then it will fill to the maximum height.
-- * \param dstCon Pointer to the destination console.
-- * \param xDst The left corner to blit onto the destination console.
-- * \param yDst The top corner to blit onto the destination console.
-- * \param foreground_alpha Foreground blending alpha.
-- * \param background_alpha Background blending alpha.
-- *
-- * If the source console has a key color, this function will use it.
-- * \rst
-- * .. versionchanged:: 1.16
-- * Blits can now handle per-cell alpha transparency.
-- * \endrst
--
procedure TCOD_console_blit
(src : access constant TCOD_Console;
xSrc : int;
ySrc : int;
wSrc : int;
hSrc : int;
dst : access TCOD_Console;
xDst : int;
yDst : int;
foreground_alpha : float;
background_alpha : float) -- console.h:230
with Import => True,
Convention => C,
External_Name => "TCOD_console_blit";
procedure TCOD_console_blit_key_color
(src : access constant TCOD_Console;
xSrc : int;
ySrc : int;
wSrc : int;
hSrc : int;
dst : access TCOD_Console;
xDst : int;
yDst : int;
foreground_alpha : float;
background_alpha : float;
key_color : access constant color_h.TCOD_color_t) -- console.h:241
with Import => True,
Convention => C,
External_Name => "TCOD_console_blit_key_color";
--*
-- * Delete a console.
-- *
-- * \param con A console pointer.
-- *
-- * If the console being deleted is the root console, then the display will be
-- * uninitialized.
--
procedure TCOD_console_delete (console : access TCOD_Console) -- console.h:261
with Import => True,
Convention => C,
External_Name => "TCOD_console_delete";
procedure TCOD_console_set_default_background (con : access TCOD_Console; col : color_h.TCOD_color_t) -- console.h:263
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_default_background";
procedure TCOD_console_set_default_foreground (con : access TCOD_Console; col : color_h.TCOD_color_t) -- console.h:264
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_default_foreground";
--*
-- * Clear a console to its default colors and the space character code.
--
procedure TCOD_console_clear (con : access TCOD_Console) -- console.h:268
with Import => True,
Convention => C,
External_Name => "TCOD_console_clear";
--*
-- * Blend a background color onto a console tile.
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \param col The background color to blend.
-- * \param flag The blend mode to use.
--
procedure TCOD_console_set_char_background
(con : access TCOD_Console;
x : int;
y : int;
col : color_h.TCOD_color_t;
flag : TCOD_bkgnd_flag_t) -- console.h:278
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_char_background";
--*
-- * Change the foreground color of a console tile.
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \param col The foreground color to set.
--
procedure TCOD_console_set_char_foreground
(con : access TCOD_Console;
x : int;
y : int;
col : color_h.TCOD_color_t) -- console.h:288
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_char_foreground";
--*
-- * Change a character on a console tile, without changing its colors.
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \param c The character code to set.
--
procedure TCOD_console_set_char
(con : access TCOD_Console;
x : int;
y : int;
c : int) -- console.h:297
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_char";
--*
-- * Draw a character on a console using the default colors.
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \param c The character code to place.
-- * \param flag A TCOD_bkgnd_flag_t flag.
--
procedure TCOD_console_put_char
(con : access TCOD_Console;
x : int;
y : int;
c : int;
flag : TCOD_bkgnd_flag_t) -- console.h:307
with Import => True,
Convention => C,
External_Name => "TCOD_console_put_char";
--*
-- * Draw a character on the console with the given colors.
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \param c The character code to place.
-- * \param fore The foreground color.
-- * \param back The background color. This color will not be blended.
--
procedure TCOD_console_put_char_ex
(con : access TCOD_Console;
x : int;
y : int;
c : int;
fore : color_h.TCOD_color_t;
back : color_h.TCOD_color_t) -- console.h:318
with Import => True,
Convention => C,
External_Name => "TCOD_console_put_char_ex";
--*
-- * Set a consoles default background flag.
-- *
-- * \param con A console pointer.
-- * \param flag One of `TCOD_bkgnd_flag_t`.
--
procedure TCOD_console_set_background_flag (con : access TCOD_Console; flag : TCOD_bkgnd_flag_t) -- console.h:325
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_background_flag";
--*
-- * Return a consoles default background flag.
--
function TCOD_console_get_background_flag (con : access TCOD_Console) return TCOD_bkgnd_flag_t -- console.h:329
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_background_flag";
--*
-- * Set a consoles default alignment.
-- *
-- * \param con A console pointer.
-- * \param alignment One of TCOD_alignment_t
--
procedure TCOD_console_set_alignment (con : access TCOD_Console; alignment : TCOD_alignment_t) -- console.h:336
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_alignment";
--*
-- * Return a consoles default alignment.
--
function TCOD_console_get_alignment (con : access TCOD_Console) return TCOD_alignment_t -- console.h:340
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_alignment";
function TCOD_console_get_default_background (con : access TCOD_Console) return color_h.TCOD_color_t -- console.h:342
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_default_background";
function TCOD_console_get_default_foreground (con : access TCOD_Console) return color_h.TCOD_color_t -- console.h:343
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_default_foreground";
--*
-- * Return the background color of a console at x,y
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \return A TCOD_color_t struct with a copy of the background color.
--
function TCOD_console_get_char_background
(con : access constant TCOD_Console;
x : int;
y : int) return color_h.TCOD_color_t -- console.h:352
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_char_background";
--*
-- * Return the foreground color of a console at x,y
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \return A TCOD_color_t struct with a copy of the foreground color.
--
function TCOD_console_get_char_foreground
(con : access constant TCOD_Console;
x : int;
y : int) return color_h.TCOD_color_t -- console.h:361
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_char_foreground";
--*
-- * Return a character code of a console at x,y
-- *
-- * \param con A console pointer.
-- * \param x The X coordinate, the left-most position being 0.
-- * \param y The Y coordinate, the top-most position being 0.
-- * \return The character code.
--
function TCOD_console_get_char
(con : access constant TCOD_Console;
x : int;
y : int) return int -- console.h:370
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_char";
--*
-- * Fade the color of the display.
-- *
-- * \param val Where at 255 colors are normal and at 0 colors are completely
-- * faded.
-- * \param fadecol Color to fade towards.
--
procedure TCOD_console_set_fade (val : unsigned_char; fade : color_h.TCOD_color_t) -- console.h:379
with Import => True,
Convention => C,
External_Name => "TCOD_console_set_fade";
--*
-- * Return the fade value.
-- *
-- * \return At 255 colors are normal and at 0 colors are completely faded.
--
function TCOD_console_get_fade return unsigned_char -- console.h:385
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_fade";
--*
-- * Return the fade color.
-- *
-- * \return The current fading color.
--
function TCOD_console_get_fading_color return color_h.TCOD_color_t -- console.h:391
with Import => True,
Convention => C,
External_Name => "TCOD_console_get_fading_color";
procedure TCOD_console_resize_u
(console : access TCOD_Console;
width : int;
height : int) -- console.h:392
with Import => True,
Convention => C,
External_Name => "TCOD_console_resize_";
-- extern "C"
-- namespace tcod
end console_h;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Calendar.Time_Zones;
with Ada.Environment_Variables;
with Ada.Strings.Fixed;
package body Web is
Month_T : constant String := "JanFebMarAprMayJunJulAugSepOctNovDec";
Day_T : constant String := "MonTueWedThuFriSatSun";
function Environment_Variables_Value (Name : String) return String is
begin
if Ada.Environment_Variables.Exists (Name) then
return Ada.Environment_Variables.Value (Name);
else
return "";
end if;
end Environment_Variables_Value;
procedure Header_Cookie_Internal (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Cookie : in Web.Cookie;
Expires : access constant Ada.Calendar.Time) is
begin
if not Cookie.Is_Empty then
declare
Position : String_Maps.Cursor := String_Maps.First (Cookie);
begin
while String_Maps.Has_Element (Position) loop
String'Write (
Stream,
"set-cookie: " & String_Maps.Key (Position) & "="
& Encode_URI (String_Maps.Element (Position)) & ";");
if Expires /= null then
String'Write (Stream, " expires=" & Image (Expires.all) & ";");
end if;
String'Write (Stream, Line_Break);
Position := String_Maps.Next (Position);
end loop;
end;
end if;
end Header_Cookie_Internal;
-- implementation of string map
function Element (
Map : String_Maps.Map;
Key : String;
Default : String := "")
return String
is
Position : constant String_Maps.Cursor := String_Maps.Find (Map, Key);
begin
if not String_Maps.Has_Element (Position) then
return Default;
else
return String_Maps.Element (Position);
end if;
end Element;
function Element (
Map : String_Maps.Map;
Key : String;
Default : Ada.Streams.Stream_Element_Array := (-1 .. 0 => <>))
return Ada.Streams.Stream_Element_Array
is
Position : constant String_Maps.Cursor := String_Maps.Find (Map, Key);
begin
if not String_Maps.Has_Element (Position) then
return Default;
else
declare
Result_String : String_Maps.Constant_Reference_Type
renames String_Maps.Constant_Reference (Map, Position);
Result_SEA :
Ada.Streams.Stream_Element_Array (0 .. Result_String.Element.all'Length - 1);
for Result_SEA'Address use Result_String.Element.all'Address;
begin
return Result_SEA;
end;
end if;
end Element;
procedure Include (
Map : in out String_Maps.Map;
Key : in String;
Item : in Ada.Streams.Stream_Element_Array)
is
Item_String : String (1 .. Item'Length);
for Item_String'Address use Item'Address;
begin
String_Maps.Include (Map, Key, Item_String);
end Include;
-- implementation of time
function Image (Time : Ada.Calendar.Time) return Time_Name is
Year : Ada.Calendar.Year_Number;
Month : Ada.Calendar.Month_Number;
Day : Ada.Calendar.Day_Number;
Hou : Ada.Calendar.Formatting.Hour_Number;
Min : Ada.Calendar.Formatting.Minute_Number;
Sec : Ada.Calendar.Formatting.Second_Number;
Sub_Seconds : Ada.Calendar.Day_Duration;
begin
Ada.Calendar.Formatting.Split (
Time,
Year, Month, Day,
Hou, Min, Sec, Sub_Seconds);
return Day_Image (
Ada.Calendar.Formatting.Day_Of_Week (Time)) & ", " & Z2_Image (Day) & " "
& Month_Image (Month) & " " & Year_Image (Year) & " " & Z2_Image (Hou) & ":"
& Z2_Image (Min) & ":" & Z2_Image (Sec) & " GMT";
end Image;
function Value (Image : String) return Ada.Calendar.Time is
begin
if Image'Length /= Time_Name'Length
and then Image'Length /= Time_Name'Length + 2 -- +XXXX form
then
raise Constraint_Error;
else
declare
F : constant Positive := Image'First;
Dummy_Day_Of_Week : Ada.Calendar.Formatting.Day_Name;
Year : Ada.Calendar.Year_Number;
Month : Ada.Calendar.Month_Number;
Day : Ada.Calendar.Day_Number;
Hou : Ada.Calendar.Formatting.Hour_Number;
Min : Ada.Calendar.Formatting.Minute_Number;
Sec : Ada.Calendar.Formatting.Second_Number;
Offset : Ada.Calendar.Time_Zones.Time_Offset;
begin
Dummy_Day_Of_Week := Day_Value (Image (F .. F + 2));
if Image (F + 3 .. F + 4) /= ", " then
raise Constraint_Error;
end if;
Day := Natural'Value (Image (F + 5 .. F + 6));
if Image (F + 7) /= ' ' then
raise Constraint_Error;
end if;
Month := Month_Value (Image (F + 8 .. F + 10));
if Image (F + 11) /= ' ' then
raise Constraint_Error;
end if;
Year := Natural'Value (Image (F + 12 .. F + 15));
if Image (F + 16) /= ' ' then
raise Constraint_Error;
end if;
Hou := Natural'Value (Image (F + 17 .. F + 18));
if Image (F + 19) /= ':' then
raise Constraint_Error;
end if;
Min := Natural'Value (Image (F + 20 .. F + 21));
if Image (F + 22) /= ':' then
raise Constraint_Error;
end if;
Sec := Natural'Value (Image (F + 23 .. F + 24));
if Image'Length = Time_Name'Length + 2 then
pragma Assert (F + 30 = Image'Last);
if Image (F + 25) /= ' ' or else Image (F + 26) /= '+' then
raise Constraint_Error;
end if;
Offset :=
Ada.Calendar.Time_Zones.Time_Offset (
Natural'Value (Image (F + 27 .. F + 28)) * 60
+ Natural'Value (Image (F + 29 .. F + 30)));
else
pragma Assert (Image'Length = Time_Name'Length);
pragma Assert (F + 28 = Image'Last);
if Image (F + 25 .. F + 28) /= " GMT" then
raise Constraint_Error;
end if;
Offset := 0;
end if;
return Ada.Calendar.Formatting.Time_Of (
Year, Month, Day,
Hou, Min, Sec,
Time_Zone => Offset);
end;
end if;
end Value;
function Year_Image (Year : Natural) return Year_Name is
S : constant String := Natural'Image (Year);
begin
pragma Assert (S (S'First) = ' ');
return Result : Year_Name := (others => '0') do
Result (Year_Name'Last + 1 - (S'Last - S'First) .. Year_Name'Last) :=
S (S'First + 1 .. S'Last);
end return;
end Year_Image;
function Month_Image (Month : Ada.Calendar.Month_Number) return Month_Name is
begin
return Month_T (Month * 3 - 2 .. Month * 3);
end Month_Image;
function Month_Value (S : String) return Ada.Calendar.Month_Number is
begin
for Month in Ada.Calendar.Month_Number loop
if S = Month_T (Month * 3 - 2 .. Month * 3) then
return Month;
end if;
end loop;
raise Constraint_Error;
end Month_Value;
function Day_Image (Day : Ada.Calendar.Formatting.Day_Name) return Day_Name is
I : constant Natural := Ada.Calendar.Formatting.Day_Name'Pos (Day);
begin
return Day_T (I * 3 + 1 .. I * 3 + 3);
end Day_Image;
function Day_Value (S : String) return Ada.Calendar.Formatting.Day_Name is
begin
for Day in Ada.Calendar.Formatting.Day_Name loop
declare
I : constant Natural := Ada.Calendar.Formatting.Day_Name'Pos (Day);
begin
if S = Day_T (I * 3 + 1 .. I * 3 + 3) then
return Day;
end if;
end;
end loop;
raise Constraint_Error;
end Day_Value;
function Z2_Image (Value : Natural) return String_2 is
S : String := Natural'Image (Value);
begin
if S'Length > 2 then
return S (S'Last - 1 .. S'Last);
else
pragma Assert (S'Length = 2);
S (S'First) := '0';
return S;
end if;
end Z2_Image;
-- implementation of host
function Host return String is
begin
if Ada.Environment_Variables.Exists (HTTP_Host_Variable) then
return Environment_Variables_Value (HTTP_Host_Variable);
else
return Environment_Variables_Value (Server_Name_Variable);
end if;
end Host;
function Compose (Protocol : Web.Protocol; Host, Path : String)
return String
is
Path_First : Positive := Path'First;
begin
if Path_First <= Path'Last
and then Path (Path_First) = '/'
and then Host'First <= Host'Last
and then Host (Host'Last) = '/'
then
Path_First := Path_First + 1;
end if;
return String (Protocol) & Host & Path (Path_First .. Path'Last);
end Compose;
-- implementation of input
function Request_URI return String is
Request_URI_Value : constant String :=
Environment_Variables_Value (Request_URI_Variable);
Query_String_Value : constant String :=
Environment_Variables_Value (Query_String_Variable);
begin
if Query_String_Value'Length = 0
or else Ada.Strings.Fixed.Index (Request_URI_Value, "?") > 0
then
return Request_URI_Value;
else
return Request_URI_Value & "?" & Query_String_Value;
end if;
end Request_URI;
function Request_Path return String is
Request_URI_Value : constant String :=
Environment_Variables_Value (Request_URI_Variable);
Query_Index : constant Integer :=
Ada.Strings.Fixed.Index (Request_URI_Value, "?");
begin
if Query_Index > 0 then
return Request_URI_Value (Request_URI_Value'First .. Query_Index - 1);
else
return Request_URI_Value;
end if;
end Request_Path;
function Remote_Addr return String is
begin
return Environment_Variables_Value (Remote_Addr_Variable);
end Remote_Addr;
function Remote_Host return String is
begin
return Environment_Variables_Value (Remote_Host_Variable);
end Remote_Host;
function User_Agent return String is
begin
return Environment_Variables_Value (HTTP_User_Agent_Variable);
end User_Agent;
function Post return Boolean is
begin
return Equal_Case_Insensitive (
Environment_Variables_Value (Request_Method_Variable),
L => "post");
end Post;
function Get_Post_Length return Natural is
begin
return Natural'Value (
Ada.Environment_Variables.Value (Content_Length_Variable));
exception
when Constraint_Error => return 0;
end Get_Post_Length;
function Get_Post_Encoded_Kind return Post_Encoded_Kind is
Content_Type_Value : constant String :=
Ada.Environment_Variables.Value (Content_Type_Variable);
begin
if Prefixed_Case_Insensitive (
Content_Type_Value,
L_Prefix => String (Content_URL_Encoded))
then
return URL_Encoded;
elsif Prefixed_Case_Insensitive (
Content_Type_Value,
L_Prefix => String (Content_Multipart_Form_Data))
then
return Multipart_Form_Data;
else
return Miscellany;
end if;
end Get_Post_Encoded_Kind;
function Encode_URI (S : String) return String is
Integer_To_Hex : constant array (0 .. 15) of Character := "0123456789abcdef";
Result : String (1 .. S'Length * 3);
Length : Natural := 0;
begin
for I in S'Range loop
declare
C : constant Character := S (I);
begin
if (C >= 'A' and then C <= 'Z')
or else (C >= 'a' and then C <= 'z')
or else (C >= '0' and then C <= '9')
then
Length := Length + 1;
Result (Length) := C;
elsif C = ' ' then
Length := Length + 1;
Result (Length) := '+';
else
Length := Length + 1;
Result (Length) := '%';
Length := Length + 1;
Result (Length) := Integer_To_Hex (Character'Pos (C) / 16);
Length := Length + 1;
Result (Length) := Integer_To_Hex (Character'Pos (C) rem 16);
end if;
end;
end loop;
return Result (1 .. Length);
end Encode_URI;
function Decode_URI (S : String) return String is
Hex_To_Integer : constant array (Character) of Natural := (
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9,
'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13, 'E' => 14, 'F' => 15,
'a' => 10, 'b' => 11, 'c' => 12, 'd' => 13, 'e' => 14, 'f' => 15,
others => 0);
Result : String (1 .. S'Length);
I : Positive;
Length : Natural := 0;
begin
I := S'First;
while I <= S'Last loop
declare
C : constant Character := S (I);
begin
if C = '+' then
Length := Length + 1;
Result (Length) := ' ';
I := I + 1;
elsif C /= '%' then
Length := Length + 1;
Result (Length) := C;
I := I + 1;
else
I := I + 1;
declare
L, H : Natural := 0;
begin
if I <= S'Last then
H := Hex_To_Integer (S (I));
I := I + 1;
if I <= S'Last then
L := Hex_To_Integer (S (I));
I := I + 1;
end if;
end if;
Length := Length + 1;
Result (Length) := Character'Val (L + H * 16);
end;
end if;
end;
end loop;
return Result (1 .. Length);
end Decode_URI;
function Decode_Query_String (S : String) return Query_Strings is
Result : Query_Strings;
procedure Process (S : String) is
Sep_Pos : constant Natural := Ada.Strings.Fixed.Index (S, "=");
begin
if Sep_Pos >= S'First then
String_Maps.Include (
Result,
S (S'First .. Sep_Pos - 1),
Decode_URI (S (Sep_Pos + 1 .. S'Last)));
else
String_Maps.Include (Result, S, "");
end if;
end Process;
Pos : Natural := S'First;
Next : Natural;
begin
Parsing : loop
Next := Ada.Strings.Fixed.Index (S (Pos .. S'Last), "&");
if Next = 0 then
Next := S'Last + 1;
end if;
if Pos < Next then
Process (S (Pos .. Next - 1));
end if;
Pos := Next + 1;
if Pos > S'Last then
exit Parsing;
end if;
end loop Parsing;
return Result;
end Decode_Query_String;
function Get_Query_Strings return Query_Strings is
URI : constant String := Request_URI;
Arg_Pos : constant Natural := Ada.Strings.Fixed.Index (URI, "?");
begin
if Arg_Pos = 0 then
return String_Maps.Empty_Map;
else
return Decode_Query_String (URI (Arg_Pos + 1 .. URI'Last));
end if;
end Get_Query_Strings;
function Decode_Multipart_Form_Data (S : String) return Query_Strings is
function New_Line (Position : aliased in out Positive) return Natural is
begin
if S (Position) = Character'Val (13) then
if Position < S'Last and then S (Position + 1) = Character'Val (10) then
Position := Position + 2;
return 2;
else
Position := Position + 1;
return 1;
end if;
elsif S (Position) = Character'Val (10) then
Position := Position + 1;
return 1;
else
return 0;
end if;
end New_Line;
function Get_String (Position : aliased in out Positive) return String is
First, Last : Positive;
begin
if S (Position) = '"' then
Position := Position + 1;
First := Position;
while S (Position) /= '"' loop
Position := Position + 1;
end loop;
Last := Position - 1;
Position := Position + 1;
return S (First .. Last);
end if;
return "";
end Get_String;
procedure Skip_Spaces (Position : aliased in out Positive) is
begin
while S (Position) = ' ' loop
Position := Position + 1;
end loop;
end Skip_Spaces;
procedure Process_Item (
Position : aliased in out Positive;
Last : Natural;
Result : in out Query_Strings)
is
Content_Disposition : constant String := "content-disposition:";
Form_Data : constant String := "form-data;";
Name : constant String := "name=";
File_Name : constant String := "filename=";
Content_Type : constant String := "content-type:";
begin
if Position + Content_Disposition'Length - 1 <= S'Last
and then Equal_Case_Insensitive (
S (Position .. Position + Content_Disposition'Length - 1),
L => Content_Disposition)
then
Position := Position + Content_Disposition'Length;
Skip_Spaces (Position);
if S (Position .. Position + Form_Data'Length - 1) = Form_Data then
Position := Position + Form_Data'Length;
Skip_Spaces (Position);
if S (Position .. Position + Name'Length - 1) = Name then
Position := Position + Name'Length;
declare
Item_Name : constant String := Get_String (Position);
begin
if New_Line (Position) > 0 then
while New_Line (Position) > 0 loop
null;
end loop;
String_Maps.Include (Result, Item_Name, S (Position .. Last));
elsif S (Position) = ';' then
Position := Position + 1;
Skip_Spaces (Position);
if Equal_Case_Insensitive (
S (Position .. Position + File_Name'Length - 1),
L => File_Name)
then
Position := Position + File_Name'Length;
declare
Item_File_Name : constant String := Get_String (Position);
Content_Type_First, Content_Type_Last : Positive;
begin
if New_Line (Position) > 0 then
if Equal_Case_Insensitive (
S (Position .. Position + Content_Type'Length - 1),
L => Content_Type)
then
Position := Position + Content_Type'Length;
Skip_Spaces (Position);
Content_Type_First := Position;
while S (Position) > Character'Val (32) loop
Position := Position + 1;
end loop;
Content_Type_Last := Position - 1;
while New_Line (Position) > 0 loop
null;
end loop;
String_Maps.Include (Result, Item_Name, S (Position .. Last));
String_Maps.Include (Result, Item_Name & ":filename", Item_File_Name);
String_Maps.Include (
Result,
Item_Name & ":content-type",
S (Content_Type_First .. Content_Type_Last));
end if;
end if;
end;
end if;
end if;
end;
end if;
end if;
end if;
end Process_Item;
Result : Query_Strings;
Position : aliased Positive;
begin
if S (S'First) = '-' then
Get_First_Line : for I in S'Range loop
Position := I;
if New_Line (Position) > 0 then
declare
Boundary : constant String := S (S'First .. I - 1);
begin
Separating : loop
declare
Next : constant Natural :=
Ada.Strings.Fixed.Index (S (Position .. S'Last), Boundary);
Last : Natural;
begin
if Next = 0 then
Last := S'Last;
else
Last := Next - 1;
end if;
if S (Last) = Character'Val (10) then
Last := Last - 1;
end if;
if S (Last) = Character'Val (13) then
Last := Last - 1;
end if;
Process_Item (Position, Last, Result);
exit Separating when Next = 0;
Position := Next + Boundary'Length;
if New_Line (Position) = 0 then
exit Separating;
end if;
end;
end loop Separating;
end;
exit Get_First_Line;
end if;
end loop Get_First_Line;
end if;
return Result;
end Decode_Multipart_Form_Data;
function Get (Stream : not null access Ada.Streams.Root_Stream_Type'Class)
return Query_Strings is
begin
if Post then
declare
Input : String (1 .. Get_Post_Length);
begin
String'Read (Stream, Input);
case Get_Post_Encoded_Kind is
when URL_Encoded =>
return Decode_Query_String (Input);
when Multipart_Form_Data =>
return Decode_Multipart_Form_Data (Input);
when Miscellany =>
return String_Maps.Empty_Map;
end case;
end;
else
return String_Maps.Empty_Map;
end if;
end Get;
function Get_Cookie return Cookie is
S : constant String := Environment_Variables_Value (HTTP_Cookie_Variable);
Result : Cookie;
procedure Process (S : in String) is
Sep_Pos : constant Natural := Ada.Strings.Fixed.Index (S, "=");
First : Natural := S'First;
begin
while S (First) = ' ' loop
First := First + 1;
if First > S'Last then
return;
end if;
end loop;
if Sep_Pos > First then
String_Maps.Include (
Result,
S (First .. Sep_Pos - 1),
Decode_URI (S (Sep_Pos + 1 .. S'Last)));
else
String_Maps.Include (Result, S (First .. S'Last), "");
end if;
end Process;
Pos : Natural := S'First;
Next : Natural;
begin
Parsing : loop
Next := Ada.Strings.Fixed.Index (S (Pos .. S'Last), ";");
if Next = 0 then
Next := S'Last + 1;
end if;
if Pos < Next then
Process (S (Pos .. Next - 1));
end if;
Pos := Next + 1;
if Pos > S'Last then
exit Parsing;
end if;
end loop Parsing;
return Result;
end Get_Cookie;
function Equal_Case_Insensitive (S, L : String) return Boolean is
S_Length : constant Natural := S'Length;
L_Length : constant Natural := L'Length;
begin
if S_Length /= L_Length then
return False;
else
for I in 0 .. S_Length - 1 loop
declare
S_Item : Character := S (S'First + I);
begin
if S_Item in 'A' .. 'Z' then
S_Item :=
Character'Val (
Character'Pos (S_Item) + (Character'Pos ('a') - Character'Pos ('A')));
end if;
pragma Assert (L (L'First + I) not in 'A' .. 'Z');
if S_Item /= L (L'First + I) then
return False;
end if;
end;
end loop;
return True;
end if;
end Equal_Case_Insensitive;
function Prefixed_Case_Insensitive (S, L_Prefix : String) return Boolean is
begin
return S'Length >= L_Prefix'Length
and then Equal_Case_Insensitive (
S (S'First .. S'First + L_Prefix'Length - 1),
L_Prefix);
end Prefixed_Case_Insensitive;
-- implementation of output
procedure Header_303 (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Location : in String) is
begin
String'Write (Stream, "status: 303 See Other" & Line_Break & "location: ");
String'Write (Stream, Location);
String'Write (Stream, Line_Break);
end Header_303;
procedure Header_503 (
Stream : not null access Ada.Streams.Root_Stream_Type'Class) is
begin
String'Write (Stream, "status: 503 Service Unavailable" & Line_Break);
end Header_503;
procedure Header_Content_Type (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Content : in Mime_Type) is
begin
String'Write (Stream, "content-type: ");
String'Write (Stream, String (Content));
String'Write (Stream, Line_Break);
end Header_Content_Type;
procedure Header_Cookie (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Cookie : in Web.Cookie;
Expires : in Ada.Calendar.Time)
is
Aliased_Expires : aliased Ada.Calendar.Time := Expires;
begin
Header_Cookie_Internal (Stream, Cookie, Aliased_Expires'Access);
end Header_Cookie;
procedure Header_Cookie (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Cookie : in Web.Cookie) is
begin
Header_Cookie_Internal (Stream, Cookie, null);
end Header_Cookie;
procedure Header_X_Robots_Tag (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Options : in Robots_Options)
is
procedure Write (
Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Item : in String;
Continuing : in out Boolean) is
begin
if not Continuing then
String'Write (Stream, ", ");
Continuing := True;
end if;
String'Write (Stream, Item);
end Write;
begin
String'Write (Stream, "X-Robots-Tag: ");
declare
Continuing : Boolean := False;
begin
if Options.No_Index then
Write (Stream, "noindex", Continuing);
end if;
if Options.No_Follow then
Write (Stream, "nofollow", Continuing);
end if;
if Options.No_Archive then
Write (Stream, "noarchive", Continuing);
end if;
if Options.No_Snippet then
Write (Stream, "nosnippet", Continuing);
end if;
if Options.No_Translate then
Write (Stream, "notranslate", Continuing);
end if;
if Options.No_Image_Index then
Write (Stream, "noimageindex", Continuing);
end if;
if not Continuing then
String'Write (Stream, "all");
end if;
end;
String'Write (Stream, Line_Break);
end Header_X_Robots_Tag;
procedure Header_Break (
Stream : not null access Ada.Streams.Root_Stream_Type'Class) is
begin
String'Write (Stream, Line_Break);
end Header_Break;
procedure Generic_Write (Item : in String) is
begin
String'Write (Stream, Item);
end Generic_Write;
end Web;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Ada_2012;
package body EU_Projects.Times.Time_Expressions.Solving is
------------------
-- Add_Equation --
------------------
procedure Add_Equation (Equations : in out Time_Equation_System;
Left : Dotted_Identifier;
Right : Symbolic_Duration)
is
begin
if Contains_Left_Term (Equations, Left) then
raise Constraint_Error;
end if;
Equations.M.Insert (Key => Left,
New_Item => (Duration_Value, Right.D));
end Add_Equation;
------------------
-- Add_Equation --
------------------
procedure Add_Equation (Equations : in out Time_Equation_System;
Left : Dotted_Identifier;
Right : Symbolic_Instant)
is
begin
if Contains_Left_Term (Equations, Left) then
raise Constraint_Error;
end if;
-- Put_Line ("ADD(" & To_String (Left) & "," & Time_Expr.Dump (Right.T) & ")");
Equations.M.Insert (Key => Left,
New_Item => (Instant_value, Right.T));
end Add_Equation;
-----------
-- Solve --
-----------
function Solve (Equations : Time_Equation_System) return Variable_Map
is
Eq : Time_Equations.Equation_Tables.Map;
R : Time_Expr.Variable_Tables.Map;
Success : Boolean;
begin
for C in Equations.M.Iterate loop
Eq.Insert (Key => Equation_Maps.Key (C),
New_Item => Equation_Maps.Element (C).Val);
end loop;
Time_Equations.Triangular_Solve (What => Eq,
Result => R,
Success => Success);
if not Success then
raise Unsolvable;
end if;
declare
Result : Variable_Map;
begin
for C in R.Iterate loop
declare
use Time_Expr.Variable_Tables;
ID : constant Dotted_Identifier := Key (C);
Val : constant Scalar_Type := Element (C);
begin
case Equations.M.Element (ID).Class is
when Instant_Value =>
Result.M.Insert (Key => ID,
New_Item => (Class => Instant_Value,
I => Instant (Val)));
when Duration_Value =>
Result.M.Insert (Key => ID,
New_Item => (Class => Duration_Value,
D => Duration (Val)));
end case;
end;
end loop;
return Result;
end;
end Solve;
end EU_Projects.Times.Time_Expressions.Solving;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body openGL.Model.billboard
is
--------------
--- Attributes
--
function Width (Self : in Item) return Real
is
begin
case Self.Plane
is
when xy =>
return Self.Scale (1); -- TODO: Use own width and height dimensions record field instead of model 'Scale'.
when xz =>
return Self.Scale (1);
when yz =>
return Self.Scale (3);
end case;
end Width;
function Height (Self : in Item) return Real
is
begin
case Self.Plane
is
when xy =>
return Self.Scale (2); -- TODO: Use own width and height dimensions record field instead of model 'Scale'.
when xz =>
return Self.Scale (3);
when yz =>
return Self.Scale (2);
end case;
end height;
function vertex_Sites (for_Plane : in Plane;
Width, Height : in Real) return Sites
is
half_Width : constant openGL.Real := Width / 2.0;
half_Height : constant openGL.Real := Height / 2.0;
the_Sites : constant array (Plane) of Sites := (xy => ((-half_Width, -half_Height, 0.0),
( half_Width, -half_Height, 0.0),
( half_Width, half_Height, 0.0),
(-half_Width, half_Height, 0.0)),
xz => ((-half_Width, 0.0, 1.0),
( half_Width, 0.0, 1.0),
( half_Width, 0.0, -1.0),
(-half_Width, 0.0, -1.0)),
yz => (( 0.0, -half_Height, half_Width),
( 0.0, -half_Height, -half_Width),
( 0.0, half_Height, -half_Width),
( 0.0, half_Height, half_Width)));
begin
return the_Sites (for_Plane);
end vertex_Sites;
end openGL.Model.billboard;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Support.CmdLine; use Support.CmdLine;
with Support.Strings; use Support.Strings;
with Ada.Streams.Stream_IO;
with Ada.Directories;
package body ADMBase.Data_IO is
data_directory : String := read_command_arg ('D',"data/");
results_directory : String := read_command_arg ('O',"results/");
procedure read_data (file_name : String := "data.txt") is
use Ada.Directories;
use Ada.Streams.Stream_IO;
txt : Ada.Streams.Stream_IO.File_Type;
txt_access : Ada.Streams.Stream_IO.Stream_Access;
begin
Open (txt, In_File, data_directory & "/" & file_name);
txt_access := Stream (txt);
Real'Read (txt_access, the_time);
for i in 1..num_x loop
for j in 1..num_y loop
for k in 1..num_z loop
MetricPointArray'Read (txt_access, gab (i,j,k));
ExtcurvPointArray'Read (txt_access, Kab (i,j,k));
Real'Read (txt_access, N (i,j,k));
end loop;
end loop;
end loop;
Close (txt);
end read_data;
procedure read_grid (file_name : String := "grid.txt") is
use Ada.Directories;
use Ada.Streams.Stream_IO;
txt : Ada.Streams.Stream_IO.File_Type;
txt_access : Ada.Streams.Stream_IO.Stream_Access;
begin
Open (txt, In_File, data_directory & "/" & file_name);
txt_access := Stream (txt);
Integer'Read (txt_access, num_x); -- number of grid points along x-axis
Integer'Read (txt_access, num_y); -- number of grid points along y-axis
Integer'Read (txt_access, num_z); -- number of grid points along z-axis
Real'Read (txt_access, dx); -- grid spacing along x-axis
Real'Read (txt_access, dy); -- grid spacing along y-axis
Real'Read (txt_access, dz); -- grid spacing along z-axis
Integer'Read (txt_access, grid_point_num);
Integer'Read (txt_access, interior_num);
Integer'Read (txt_access, boundary_num);
Integer'Read (txt_access, north_bndry_num);
Integer'Read (txt_access, south_bndry_num);
Integer'Read (txt_access, east_bndry_num);
Integer'Read (txt_access, west_bndry_num);
Integer'Read (txt_access, front_bndry_num);
Integer'Read (txt_access, back_bndry_num);
for i in 1..grid_point_num loop
GridPoint'Read (txt_access, grid_point_list (i));
end loop;
for i in 1..interior_num loop
Integer'Read (txt_access, interior (i));
end loop;
for i in 1..boundary_num loop
Integer'Read (txt_access, boundary (i));
end loop;
for i in 1..north_bndry_num loop
Integer'Read (txt_access, north_bndry (i));
end loop;
for i in 1..south_bndry_num loop
Integer'Read (txt_access, south_bndry (i));
end loop;
for i in 1..east_bndry_num loop
Integer'Read (txt_access, east_bndry (i));
end loop;
for i in 1..west_bndry_num loop
Integer'Read (txt_access, west_bndry (i));
end loop;
for i in 1..front_bndry_num loop
Integer'Read (txt_access, front_bndry (i));
end loop;
for i in 1..back_bndry_num loop
Integer'Read (txt_access, back_bndry (i));
end loop;
Close (txt);
end read_grid;
procedure write_data (file_name : String := "data.txt") is
use Ada.Directories;
use Ada.Streams.Stream_IO;
txt : Ada.Streams.Stream_IO.File_Type;
txt_access : Ada.Streams.Stream_IO.Stream_Access;
begin
Create_Path (Containing_Directory(data_directory & "/" & file_name));
Create (txt, Out_File, data_directory & "/" & file_name);
txt_access := Stream (txt);
Real'Write (txt_access, the_time);
for i in 1..num_x loop
for j in 1..num_y loop
for k in 1..num_z loop
MetricPointArray'Write (txt_access, gab (i,j,k));
ExtcurvPointArray'Write (txt_access, Kab (i,j,k));
Real'Write (txt_access, N (i,j,k));
end loop;
end loop;
end loop;
Close (txt);
end write_data;
procedure write_grid (file_name : String := "grid.txt") is
use Ada.Directories;
use Ada.Streams.Stream_IO;
txt : Ada.Streams.Stream_IO.File_Type;
txt_access : Ada.Streams.Stream_IO.Stream_Access;
begin
Create_Path (Containing_Directory(data_directory & "/" & file_name));
Create (txt, Out_File, data_directory & "/" & file_name);
txt_access := Stream (txt);
Integer'Write (txt_access, num_x); -- number of grid points along x-axis
Integer'Write (txt_access, num_y); -- number of grid points along y-axis
Integer'Write (txt_access, num_z); -- number of grid points along z-axis
Real'Write (txt_access, dx); -- grid spacing along x-axis
Real'Write (txt_access, dy); -- grid spacing along y-axis
Real'Write (txt_access, dz); -- grid spacing along z-axis
Integer'write (txt_access, grid_point_num);
Integer'Write (txt_access, interior_num);
Integer'Write (txt_access, boundary_num);
Integer'Write (txt_access, north_bndry_num);
Integer'Write (txt_access, south_bndry_num);
Integer'Write (txt_access, east_bndry_num);
Integer'Write (txt_access, west_bndry_num);
Integer'Write (txt_access, front_bndry_num);
Integer'Write (txt_access, back_bndry_num);
for i in 1..grid_point_num loop
GridPoint'Write (txt_access, grid_point_list (i));
end loop;
for i in 1..interior_num loop
Integer'Write (txt_access, interior (i));
end loop;
for i in 1..boundary_num loop
Integer'Write (txt_access, boundary (i));
end loop;
for i in 1..north_bndry_num loop
Integer'Write (txt_access, north_bndry (i));
end loop;
for i in 1..south_bndry_num loop
Integer'Write (txt_access, south_bndry (i));
end loop;
for i in 1..east_bndry_num loop
Integer'Write (txt_access, east_bndry (i));
end loop;
for i in 1..west_bndry_num loop
Integer'Write (txt_access, west_bndry (i));
end loop;
for i in 1..front_bndry_num loop
Integer'Write (txt_access, front_bndry (i));
end loop;
for i in 1..back_bndry_num loop
Integer'Write (txt_access, back_bndry (i));
end loop;
Close (txt);
end write_grid;
procedure read_data_fmt (file_name : String := "data.txt") is
txt : File_Type;
begin
Open (txt, In_File, data_directory & "/" & file_name);
Get (txt, the_time); Skip_Line (txt);
for i in 1..num_x loop
for j in 1..num_y loop
for k in 1..num_z loop
for a in MetricPointArray'Range loop
Get (txt, gab (i,j,k)(a));
end loop;
Skip_line (txt);
for a in ExtcurvPointArray'Range loop
Get (txt, Kab (i,j,k)(a));
end loop;
Skip_line (txt);
Get (txt, N (i,j,k));
Skip_Line (txt);
end loop;
end loop;
end loop;
Close (txt);
end read_data_fmt;
procedure read_grid_fmt (file_name : String := "grid.txt") is
txt : File_Type;
begin
Open (txt, In_File, data_directory & "/" & file_name);
Get (txt, num_x); -- number of grid points along x-axis
Get (txt, num_y); -- number of grid points along y-axis
Get (txt, num_z); -- number of grid points along z-axis
Skip_Line (txt);
Get (txt, dx); -- grid spacing along x-axis
Get (txt, dy); -- grid spacing along y-axis
Get (txt, dz); -- grid spacing along z-axis
Skip_Line (txt);
Get (txt, grid_point_num);
Get (txt, interior_num);
Get (txt, boundary_num);
Skip_Line (txt);
Get (txt, north_bndry_num);
Get (txt, south_bndry_num);
Get (txt, east_bndry_num);
Get (txt, west_bndry_num);
Get (txt, front_bndry_num);
Get (txt, back_bndry_num);
Skip_Line (txt);
for i in 1..grid_point_num loop
Get (txt, grid_point_list (i).i);
Get (txt, grid_point_list (i).j);
Get (txt, grid_point_list (i).k);
Skip_Line (txt);
Get (txt, grid_point_list (i).x);
Get (txt, grid_point_list (i).y);
Get (txt, grid_point_list (i).z);
Skip_Line (txt);
end loop;
for i in 1..interior_num loop
Get (txt, interior (i));
Skip_Line (txt);
end loop;
for i in 1..boundary_num loop
Get (txt, boundary (i));
Skip_Line (txt);
end loop;
for i in 1..north_bndry_num loop
Get (txt, north_bndry (i));
Skip_Line (txt);
end loop;
for i in 1..south_bndry_num loop
Get (txt, south_bndry (i));
Skip_Line (txt);
end loop;
for i in 1..east_bndry_num loop
Get (txt, east_bndry (i));
Skip_Line (txt);
end loop;
for i in 1..west_bndry_num loop
Get (txt, west_bndry (i));
Skip_Line (txt);
end loop;
for i in 1..front_bndry_num loop
Get (txt, front_bndry (i));
Skip_Line (txt);
end loop;
for i in 1..back_bndry_num loop
Get (txt, back_bndry (i));
Skip_Line (txt);
end loop;
Close (txt);
end read_grid_fmt;
procedure write_data_fmt (file_name : String := "data.txt") is
txt : File_Type;
use Ada.Directories;
begin
Create_Path (Containing_Directory(data_directory & "/" & file_name));
Create (txt, Out_File, data_directory & "/" & file_name);
Put_Line (txt, str(the_time,25));
for i in 1..num_x loop
for j in 1..num_y loop
for k in 1..num_z loop
for a in MetricPointArray'Range loop
Put (txt, str (gab (i,j,k)(a),25) & spc (1));
end loop;
New_line (txt);
for a in ExtcurvPointArray'Range loop
Put (txt, str (Kab (i,j,k)(a),25) & spc (1));
end loop;
New_line (txt);
Put_Line (txt, str (N (i,j,k),25));
end loop;
end loop;
end loop;
Close (txt);
end write_data_fmt;
procedure write_grid_fmt (file_name : String := "grid.txt") is
txt : File_Type;
use Ada.Directories;
begin
Create_Path (Containing_Directory(data_directory & "/" & file_name));
Create (txt, Out_File, data_directory & "/" & file_name);
Put (txt, str (num_x) & spc (1)); -- number of grid points along x-axis
Put (txt, str (num_y) & spc (1)); -- number of grid points along y-axis
Put (txt, str (num_z)); -- number of grid points along z-axis
New_Line (txt);
Put (txt, str (dx,25) & spc (1)); -- grid spacing along x-axis
Put (txt, str (dy,25) & spc (1)); -- grid spacing along y-axis
Put (txt, str (dz,25)); -- grid spacing along z-axis
New_Line (txt);
Put (txt, str (grid_point_num) & spc (1));
Put (txt, str (interior_num) & spc (1));
Put (txt, str (boundary_num));
New_Line (txt);
Put (txt, str (north_bndry_num) & spc (1));
Put (txt, str (south_bndry_num) & spc (1));
Put (txt, str (east_bndry_num) & spc (1));
Put (txt, str (west_bndry_num) & spc (1));
Put (txt, str (front_bndry_num) & spc (1));
Put (txt, str (back_bndry_num));
New_Line (txt);
for i in 1..grid_point_num loop
Put (txt, str (grid_point_list (i).i) & spc (1));
Put (txt, str (grid_point_list (i).j) & spc (1));
Put (txt, str (grid_point_list (i).k) & spc (1));
New_Line (txt);
Put (txt, str (grid_point_list (i).x,25) & spc (1));
Put (txt, str (grid_point_list (i).y,25) & spc (1));
Put (txt, str (grid_point_list (i).z,25));
New_Line (txt);
end loop;
for i in 1..interior_num loop
Put (txt, str (interior (i)));
New_Line (txt);
end loop;
for i in 1..boundary_num loop
Put (txt, str (boundary (i)));
New_Line (txt);
end loop;
for i in 1..north_bndry_num loop
Put (txt, str (north_bndry (i)));
New_Line (txt);
end loop;
for i in 1..south_bndry_num loop
Put (txt, str (south_bndry (i)));
New_Line (txt);
end loop;
for i in 1..east_bndry_num loop
Put (txt, str (east_bndry (i)));
New_Line (txt);
end loop;
for i in 1..west_bndry_num loop
Put (txt, str (west_bndry (i)));
New_Line (txt);
end loop;
for i in 1..front_bndry_num loop
Put (txt, str (front_bndry (i)));
New_Line (txt);
end loop;
for i in 1..back_bndry_num loop
Put (txt, str (back_bndry (i)));
New_Line (txt);
end loop;
Close (txt);
end write_grid_fmt;
end ADMBase.Data_IO;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
-- At the moment there is only one version of this source package available.
-- It assumes integer sizes of 8, 16, 32 and 64 are available, and that the
-- floating-point formats are IEEE compatible. Specialization of this file
-- may be required later if these assumptions are not correct for some target.
package Interfaces is
pragma Pure (Interfaces);
type Integer_8 is range -2 ** 7 .. 2 ** 7 - 1;
for Integer_8'Size use 8;
type Integer_16 is range -2 ** 15 .. 2 ** 15 - 1;
for Integer_16'Size use 16;
type Integer_32 is range -2 ** 31 .. 2 ** 31 - 1;
for Integer_32'Size use 32;
type Integer_64 is range -2 ** 63 .. 2 ** 63 - 1;
for Integer_64'Size use 64;
type Unsigned_8 is mod 2 ** 8;
for Unsigned_8'SIze use 8;
type Unsigned_16 is mod 2 ** 16;
for Unsigned_16'SIze use 16;
type Unsigned_32 is mod 2 ** 32;
for Unsigned_32'SIze use 32;
type Unsigned_64 is mod 2 ** 64;
for Unsigned_64'Size use 64;
function Shift_Left
(Value : Unsigned_8;
Amount : Natural)
return Unsigned_8;
function Shift_Right
(Value : Unsigned_8;
Amount : Natural)
return Unsigned_8;
function Shift_Right_Arithmetic
(Value : Unsigned_8;
Amount : Natural)
return Unsigned_8;
function Rotate_Left
(Value : Unsigned_8;
Amount : Natural)
return Unsigned_8;
function Rotate_Right
(Value : Unsigned_8;
Amount : Natural)
return Unsigned_8;
function Shift_Left
(Value : Unsigned_16;
Amount : Natural)
return Unsigned_16;
function Shift_Right
(Value : Unsigned_16;
Amount : Natural)
return Unsigned_16;
function Shift_Right_Arithmetic
(Value : Unsigned_16;
Amount : Natural)
return Unsigned_16;
function Rotate_Left
(Value : Unsigned_16;
Amount : Natural)
return Unsigned_16;
function Rotate_Right
(Value : Unsigned_16;
Amount : Natural)
return Unsigned_16;
function Shift_Left
(Value : Unsigned_32;
Amount : Natural)
return Unsigned_32;
function Shift_Right
(Value : Unsigned_32;
Amount : Natural)
return Unsigned_32;
function Shift_Right_Arithmetic
(Value : Unsigned_32;
Amount : Natural)
return Unsigned_32;
function Rotate_Left
(Value : Unsigned_32;
Amount : Natural)
return Unsigned_32;
function Rotate_Right
(Value : Unsigned_32;
Amount : Natural)
return Unsigned_32;
function Shift_Left
(Value : Unsigned_64;
Amount : Natural)
return Unsigned_64;
function Shift_Right
(Value : Unsigned_64;
Amount : Natural)
return Unsigned_64;
function Shift_Right_Arithmetic
(Value : Unsigned_64;
Amount : Natural)
return Unsigned_64;
function Rotate_Left
(Value : Unsigned_64;
Amount : Natural)
return Unsigned_64;
function Rotate_Right
(Value : Unsigned_64;
Amount : Natural)
return Unsigned_64;
pragma Convention (Intrinsic, Shift_Left);
pragma Convention (Intrinsic, Shift_Right);
pragma Convention (Intrinsic, Shift_Right_Arithmetic);
pragma Convention (Intrinsic, Rotate_Left);
pragma Convention (Intrinsic, Rotate_Right);
pragma Import (Intrinsic, Shift_Left);
pragma Import (Intrinsic, Shift_Right);
pragma Import (Intrinsic, Shift_Right_Arithmetic);
pragma Import (Intrinsic, Rotate_Left);
pragma Import (Intrinsic, Rotate_Right);
-- Floating point types. We assume that we are on an IEEE machine, and
-- that the types Short_Float and Long_Float in Standard refer to the
-- 32-bit short and 64-bit long IEEE forms. Furthermore, if there is
-- an extended float, we assume that it is available as Long_Long_Float.
-- Note: it is harmless, and explicitly permitted, to include additional
-- types in interfaces, so it is not wrong to have IEEE_Extended_Float
-- defined even if the extended format is not available.
type IEEE_Float_32 is new Short_Float;
type IEEE_Float_64 is new Long_Float;
type IEEE_Extended_Float is new Long_Long_Float;
end Interfaces;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Binde;
with Opt; use Opt;
with Bindo.Elaborators;
use Bindo.Elaborators;
package body Bindo is
---------------------------------
-- Elaboration-order mechanism --
---------------------------------
-- The elaboration-order (EO) mechanism implemented in this unit and its
-- children has the following objectives:
--
-- * Find an ordering of all library items (historically referred to as
-- "units") in the bind which require elaboration, taking into account:
--
-- - The dependencies between units expressed in the form of with
-- clauses.
--
-- - Pragmas Elaborate, Elaborate_All, Elaborate_Body, Preelaborable,
-- and Pure.
--
-- - The flow of execution at elaboration time.
--
-- - Additional dependencies between units supplied to the binder by
-- means of a forced-elaboration-order file.
--
-- The high-level idea empoyed by the EO mechanism is to construct two
-- graphs and use the information they represent to find an ordering of
-- all units.
--
-- The invocation graph represents the flow of execution at elaboration
-- time.
--
-- The library graph captures the dependencies between units expressed
-- by with clause and elaboration-related pragmas. The library graph is
-- further augmented with additional information from the invocation
-- graph by exploring the execution paths from a unit with elaboration
-- code to other external units.
--
-- The strongly connected components of the library graph are computed.
--
-- The order is obtained using a topological sort-like algorithm which
-- traverses the library graph and its strongly connected components in
-- an attempt to order available units while enabling other units to be
-- ordered.
--
-- * Diagnose elaboration circularities between units
--
-- An elaboration circularity arises when either
--
-- - At least one unit cannot be ordered, or
--
-- - All units can be ordered, but an edge with an Elaborate_All
-- pragma links two vertices within the same component of the
-- library graph.
--
-- The library graph is traversed to discover, collect, and sort all
-- cycles that hinder the elaboration order.
--
-- The most important cycle is diagnosed by describing its effects on
-- the elaboration order and listing all units comprising the circuit.
-- Various suggestions on how to break the cycle are offered.
-----------------
-- Terminology --
-----------------
-- * Component - A strongly connected component of a graph.
--
-- * Elaborable component - A component that is not waiting on other
-- components to be elaborated.
--
-- * Elaborable vertex - A vertex that is not waiting on strong and weak
-- predecessors, and whose component is elaborable.
--
-- * Elaboration circularity - A cycle involving units from the bind.
--
-- * Elaboration root - A special invocation construct which denotes the
-- elaboration procedure of a unit.
--
-- * Invocation - The act of activating a task, calling a subprogram, or
-- instantiating a generic.
--
-- * Invocation construct - An entry declaration, [single] protected type,
-- subprogram declaration, subprogram instantiation, or a [single] task
-- type declared in the visible, private, or body declarations of some
-- unit. The construct is encoded in the ALI file of the related unit.
--
-- * Invocation graph - A directed graph which models the flow of execution
-- at elaboration time.
--
-- - Vertices - Invocation constructs plus extra information. Certain
-- vertices act as elaboration roots.
--
-- - Edges - Invocation relations plus extra information.
--
-- * Invocation relation - A flow link between two invocation constructs.
-- This link is encoded in the ALI file of unit that houses the invoker.
--
-- * Invocation signature - A set of attributes that uniquely identify an
-- invocation construct within the namespace of all ALI files.
--
-- * Invoker - The source construct of an invocation relation (the caller,
-- instantiator, or task activator).
--
-- * Library graph - A directed graph which captures with clause and pragma
-- dependencies between units.
--
-- - Vertices - Units plus extra information.
--
-- - Edges - With clause, pragma, and additional dependencies between
-- units.
--
-- * Pending predecessor - A vertex that must be elaborated before another
-- vertex can be elaborated.
--
-- * Strong edge - A non-invocation library graph edge. Strong edges
-- represent the language-defined relations between units.
--
-- * Strong predecessor - A library graph vertex reachable via a strong
-- edge.
--
-- * Target - The destination construct of an invocation relation (the
-- generic, subprogram, or task type).
--
-- * Weak edge - An invocation library graph edge. Weak edges represent
-- the speculative flow of execution at elaboration time, which may or
-- may not take place.
--
-- * Weak predecessor - A library graph vertex reachable via a weak edge.
--
-- * Weakly elaborable vertex - A vertex that is waiting solely on weak
-- predecessors to be elaborated, and whose component is elaborable.
------------------
-- Architecture --
------------------
-- Find_Elaboration_Order
-- |
-- +--> Collect_Elaborable_Units
-- +--> Write_ALI_Tables
-- +--> Elaborate_Units
-- |
-- +------ | -------------- Construction phase ------------------------+
-- | | |
-- | +--> Build_Library_Graph |
-- | +--> Validate_Library_Graph |
-- | +--> Write_Library_Graph |
-- | | |
-- | +--> Build_Invocation_Graph |
-- | +--> Validate_Invocation_Graph |
-- | +--> Write_Invocation_Graph |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Augmentation phase ------------------------+
-- | | |
-- | +--> Augment_Library_Graph |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Ordering phase ----------------------------+
-- | | |
-- | +--> Find_Components |
-- | | |
-- | +--> Elaborate_Library_Graph |
-- | +--> Validate_Elaboration_Order |
-- | +--> Write_Elaboration_Order |
-- | | |
-- | +--> Write_Unit_Closure |
-- | | |
-- +------ | ----------------------------------------------------------+
-- |
-- +------ | -------------- Diagnostics phase -------------------------+
-- | | |
-- | +--> Find_Cycles |
-- | +--> Validate_Cycles |
-- | +--> Write_Cycles |
-- | | |
-- | +--> Diagnose_Cycle / Diagnose_All_Cycles |
-- | |
-- +-------------------------------------------------------------------+
------------------------
-- Construction phase --
------------------------
-- The Construction phase has the following objectives:
--
-- * Build the library graph by inspecting the ALI file of each unit that
-- requires elaboration.
--
-- * Validate the consistency of the library graph, only when switch -d_V
-- is in effect.
--
-- * Write the contents of the invocation graph in human-readable form to
-- standard output when switch -d_L is in effect.
--
-- * Build the invocation graph by inspecting invocation constructs and
-- relations in the ALI file of each unit that requires elaboration.
--
-- * Validate the consistency of the invocation graph, only when switch
-- -d_V is in effect.
--
-- * Write the contents of the invocation graph in human-readable form to
-- standard output when switch -d_I is in effect.
------------------------
-- Augmentation phase --
------------------------
-- The Augmentation phase has the following objectives:
--
-- * Discover transitions of the elaboration flow from a unit with an
-- elaboration root to other units. Augment the library graph with
-- extra edges for each such transition.
--------------------
-- Ordering phase --
--------------------
-- The Ordering phase has the following objectives:
--
-- * Discover all components of the library graph by treating specs and
-- bodies as single vertices.
--
-- * Try to order as many vertices of the library graph as possible by
-- performing a topological sort based on the pending predecessors of
-- vertices across all components and within a single component.
--
-- * Validate the consistency of the order, only when switch -d_V is in
-- effect.
--
-- * Write the contents of the order in human-readable form to standard
-- output when switch -d_O is in effect.
--
-- * Write the sources of the order closure when switch -R is in effect.
-----------------------
-- Diagnostics phase --
-----------------------
-- The Diagnostics phase has the following objectives:
--
-- * Discover, save, and sort all cycles in the library graph. The cycles
-- are sorted based on the following heuristics:
--
-- - A cycle with higher precedence is preferred.
--
-- - A cycle with fewer invocation edges is preferred.
--
-- - A cycle with a shorter length is preferred.
--
-- * Validate the consistency of cycles, only when switch -d_V is in
-- effect.
--
-- * Write the contents of all cycles in human-readable form to standard
-- output when switch -d_O is in effect.
--
-- * Diagnose the most important cycle, or all cycles when switch -d_C is
-- in effect. The diagnostic consists of:
--
-- - The reason for the existence of the cycle, along with the unit
-- whose elaboration cannot be guaranteed.
--
-- - A detailed traceback of the cycle, showcasing the transition
-- between units, along with any other elaboration-order-related
-- information.
--
-- - A set of suggestions on how to break the cycle considering the
-- the edges comprising the circuit, the elaboration model used to
-- compile the units, the availability of invocation information,
-- and the state of various relevant switches.
--------------
-- Switches --
--------------
-- -d_a Ignore the effects of pragma Elaborate_All
--
-- GNATbind creates a regular with edge instead of an Elaborate_All
-- edge in the library graph, thus eliminating the effects of the
-- pragma.
--
-- -d_b Ignore the effects of pragma Elaborate_Body
--
-- GNATbind treats a spec and body pair as decoupled.
--
-- -d_e Ignore the effects of pragma Elaborate
--
-- GNATbind creates a regular with edge instead of an Elaborate edge
-- in the library graph, thus eliminating the effects of the pragma.
-- In addition, GNATbind does not create an edge to the body of the
-- pragma argument.
--
-- -d_t Output cycle-detection trace information
--
-- GNATbind outputs trace information on cycle-detection activities
-- to standard output.
--
-- -d_A Output ALI invocation tables
--
-- GNATbind outputs the contents of ALI table Invocation_Constructs
-- and Invocation_Edges in textual format to standard output.
--
-- -d_C Diagnose all cycles
--
-- GNATbind outputs diagnostics for all unique cycles in the bind,
-- rather than just the most important one.
--
-- -d_I Output invocation graph
--
-- GNATbind outputs the invocation graph in text format to standard
-- output.
--
-- -d_L Output library graph
--
-- GNATbind outputs the library graph in textual format to standard
-- output.
--
-- -d_P Output cycle paths
--
-- GNATbind outputs the cycle paths in text format to standard output
--
-- -d_S Output elaboration-order status information
--
-- GNATbind outputs trace information concerning the status of its
-- various phases to standard output.
--
-- -d_T Output elaboration-order trace information
--
-- GNATbind outputs trace information on elaboration-order detection
-- activities to standard output.
--
-- -d_V Validate bindo cycles, graphs, and order
--
-- GNATbind validates the invocation graph, library graph along with
-- its cycles, and elaboration order by detecting inconsistencies and
-- producing error reports.
--
-- -e Output complete list of elaboration-order dependencies
--
-- GNATbind outputs the dependencies between units to standard
-- output.
--
-- -f Force elaboration order from given file
--
-- GNATbind applies an additional set of edges to the library graph.
-- The edges are read from a file specified by the argument of the
-- flag.
--
-- -H Legacy elaboration-order model enabled
--
-- GNATbind uses the library-graph and heuristics-based elaboration-
-- order model.
--
-- -l Output chosen elaboration order
--
-- GNATbind outputs the elaboration order in text format to standard
-- output.
--
-- -p Pessimistic (worst-case) elaboration order
--
-- This switch is not used in Bindo and its children.
----------------------------------------
-- Debugging elaboration-order issues --
----------------------------------------
-- Prior to debugging elaboration-order-related issues, enable all relevant
-- debug flags to collect as much information as possible. Depending on the
-- number of files in the bind, Bindo may emit anywhere between several MBs
-- to several hundred MBs of data to standard output. The switches are:
--
-- -d_A -d_C -d_I -d_L -d_P -d_t -d_T -d_V
--
-- Bindo offers several debugging routines that can be invoked from gdb.
-- Those are defined in the body of Bindo.Writers, in sections denoted by
-- header Debug. For quick reference, the routines are:
--
-- palgc -- print all library-graph cycles
-- pau -- print all units
-- pc -- print component
-- pige -- print invocation-graph edge
-- pigv -- print invocation-graph vertex
-- plgc -- print library-graph cycle
-- plge -- print library-graph edge
-- plgv -- print library-graph vertex
-- pu -- print units
--
-- * Apparent infinite loop
--
-- The elaboration order mechanism appears to be stuck in an infinite
-- loop. Use switch -d_S to output the status of each elaboration phase.
--
-- * Invalid elaboration order
--
-- The elaboration order is invalid when:
--
-- - A unit that requires elaboration is missing from the order
-- - A unit that does not require elaboration is present in the order
--
-- Examine the output of the elaboration algorithm available via switch
-- -d_T to determine how the related units were included in or excluded
-- from the order. Determine whether the library graph contains all the
-- relevant edges for those units.
--
-- Units and routines of interest:
-- Bindo.Elaborators
-- Elaborate_Library_Graph
-- Elaborate_Units
--
-- * Invalid invocation graph
--
-- The invocation graph is invalid when:
--
-- - An edge lacks an attribute
-- - A vertex lacks an attribute
--
-- Find the malformed edge or vertex and determine which attribute is
-- missing. Examine the contents of the invocation-related ALI tables
-- available via switch -d_A. If the invocation construct or relation
-- is missing, verify the ALI file. If the ALI lacks all the relevant
-- information, then Sem_Elab most likely failed to discover a valid
-- elaboration path.
--
-- Units and routines of interest:
-- Bindo.Builders
-- Bindo.Graphs
-- Add_Edge
-- Add_Vertex
-- Build_Invocation_Graph
--
-- * Invalid library graph
--
-- The library graph is invalid when:
--
-- - An edge lacks an attribute
-- - A vertex lacks an attribute
--
-- Find the malformed edge or vertex and determine which attribute is
-- missing.
--
-- Units and routines of interest:
-- Bindo.Builders
-- Bindo.Graphs
-- Add_Edge
-- Add_Vertex
-- Build_Library_Graph
--
-- * Invalid library-graph cycle
--
-- A library-graph cycle is invalid when:
--
-- - It lacks enough edges to form a circuit
-- - At least one edge in the circuit is repeated
--
-- Find the malformed cycle and determine which attribute is missing.
--
-- Units and routines of interest:
-- Bindo.Graphs
-- Find_Cycles
----------------------------
-- Find_Elaboration_Order --
----------------------------
procedure Find_Elaboration_Order
(Order : out Unit_Id_Table;
Main_Lib_File : File_Name_Type)
is
begin
-- Use the library graph and heuristic-based elaboration order when
-- switch -H (legacy elaboration-order mode enabled).
if Legacy_Elaboration_Order then
Binde.Find_Elab_Order (Order, Main_Lib_File);
-- Otherwise use the invocation and library-graph-based elaboration
-- order.
else
Invocation_And_Library_Graph_Elaborators.Elaborate_Units
(Order => Order,
Main_Lib_File => Main_Lib_File);
end if;
end Find_Elaboration_Order;
end Bindo;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with SPARKNaCl; use SPARKNaCl;
with SPARKNaCl.Cryptobox; use SPARKNaCl.Cryptobox;
with SPARKNaCl.Stream;
with Random; use Random;
with Ada.Numerics.Discrete_Random;
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
procedure Box8
is
Raw_SK : Bytes_32;
AliceSK, BobSK : Secret_Key;
AlicePK, BobPK : Public_Key;
N : Stream.HSalsa20_Nonce;
S, S2 : Boolean;
begin
-- for MLen in N32 range 0 .. 999 loop
for MLen in N32 range 0 .. 99 loop
Random.Random_Bytes (Raw_SK);
Keypair (Raw_SK, AlicePK, AliceSK);
Random.Random_Bytes (Raw_SK);
Keypair (Raw_SK, BobPK, BobSK);
Random.Random_Bytes (Bytes_24 (N));
Put ("Box8 - iteration" & MLen'Img);
declare
subtype Index is
N32 range 0 .. Plaintext_Zero_Bytes + MLen - 1;
subtype CIndex is
N32 range Ciphertext_Zero_Bytes .. Index'Last;
subtype Text is
Byte_Seq (Index);
package RI is new Ada.Numerics.Discrete_Random (CIndex);
G : RI.Generator;
M, C, M2 : Text := (others => 0);
begin
RI.Reset (G);
Random.Random_Bytes (M (Plaintext_Zero_Bytes .. M'Last));
Create (C, S, M, N, BobPK, AliceSK);
if S then
C (RI.Random (G)) := Random_Byte;
Open (M2, S2, C, N, AlicePK, BobSK);
if S2 then
if not Equal (M, M2) then
Put_Line (" forgery!");
exit;
else
Put_Line (" OK");
end if;
else
Put_Line (" OK"); -- data corruption spotted OK
end if;
else
Put_Line ("bad encryption");
end if;
end;
end loop;
end Box8;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
package body Search.Tokens.Factories.Default is
overriding
procedure Create (Factory : in out Token_Factory;
Value : in String;
Token : out Token_Type) is
R : Token_Refs.Ref;
Item : Search.Tokens.Sets.Cursor;
begin
R := Token_Refs.Create (new Token_Content_Type '(Util.Refs.Ref_Entity with
Length => Value'Length,
Value => Value));
Token := Token_Type '(R with others => <>);
Item := Factory.Tokens.Find (Token);
if Search.Tokens.Sets.Has_Element (Item) then
Token := Search.Tokens.Sets.Element (Item);
else
Factory.Tokens.Insert (Token);
end if;
end Create;
end Search.Tokens.Factories.Default;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- Objectif : Implantation du module Arbre_Binaire.
-- Créé : <NAME> 25 2019
--------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Arbre_Binaire is
----------------------------------Constuctor--------------------------------
-- Initialiser Tree. Tree est vide.
procedure Initialize (Tree: out T_BT) is
begin
Tree := Null;
end Initialize;
-----------------------------------Getters----------------------------------
-- Obtenir à l'DATA de la racine de Tree.
function Get_Data (Tree : in T_BT) return T_DATA is
begin
return Tree.all.Data;
end Get_DATA;
-- Obtenir à le sous arbre gauche de Tree.
function Get_Left (Tree : in T_BT) return T_BT is
begin
return Tree.all.Left;
end Get_Left;
-- Obtenir à le sous arbre droit de Tree.
function Get_Right (Tree : in T_BT) return T_BT is
begin
return Tree.all.Right;
end Get_Right;
-----------------------------------Setters----------------------------------
-- Modifier l'DATA de la racine de Tree.
procedure Set_Data (Tree : in T_BT; Data : in T_DATA) is
begin
Tree.all.Data := Data;
end Set_DATA;
-- Modifier le sous arbre gauche de Tree.
procedure Set_Left (Tree, Left : in T_BT) is
begin
Tree.all.Left := Left;
end Set_Left;
-- Modifier le sous arbre droit de Tree.
procedure Set_Right (Tree, Right : in T_BT) is
begin
Tree.all.Right := Right;
end Set_Right;
----------------------------------------------------------------------------
-- Libérer la mémoire.
procedure Free is
new Ada.Unchecked_Deallocation (Object => T_Node, Name => T_BT);
-- Est-ce qu'un Tree est vDATAe ?
function Is_Empty (Tree : T_BT) return Boolean is
begin
return (Tree = Null);
end Is_Empty;
-- Obtenir le nombre d'éléments d'un Tree.
function Height (Tree : in T_BT) return Integer is
begin
if Is_Empty (Tree) then
return 0;
else
return 1 + Height (Tree.all.Left) + Height (Tree.all.Right);
end if;
end Height;
-- Vérifier qu'un DATA passé en paramètre est dans l'arbre.
function Is_Present (Tree : in T_BT; DATA : in T_DATA) return Boolean is
begin
if (Is_Empty (Tree)) then
return False;
elsif (Get_DATA (Tree) = DATA) then
return True;
else
return Is_Present (Get_Left (Tree), DATA) or Is_Present (Get_Right (Tree), DATA);
end if;
end Is_Present;
-- Obtenir la profondeur d'un Tree.
function Depth (Tree : in T_BT) return Integer is
-- Nom : max
-- Sémantique : Obtenir le max de deux entiers.
-- Paramètres :
-- a -- L'élement qu'on va comparer avec b.
-- b -- L'élement qu'on va comparer avec a.
function max (a, b : in Integer) return Integer is
begin
if (a > b) then
return a;
else
return b;
end if;
end max;
begin
if (Is_Empty (Tree)) then
return 0;
else
return 1 + max (depth (Get_Left (Tree)), depth (Get_Right (Tree)));
end if;
end Depth;
-- Créer un arbre avec un seul noeud.
procedure Create_Node (Node : out T_BT; DATA : T_DATA) is
begin
Node := New T_Node'(DATA, Null, Null);
end Create_Node;
-- Insérer un DATA associé à un nouveau noeud dans Tree.
procedure Insert (Tree : in out T_BT ; DATA : T_DATA) is
begin
if (Is_Empty(Tree)) then
Create_Node (Tree, DATA);
elsif (Tree.all.DATA = DATA) then
raise PRESENT_DATA_EXCEPTION;
elsif (gt (Tree.all.DATA, DATA)) then -- Tree.all. DATA > DATA
Insert(Tree.all.Left, DATA);
elsif (gt (DATA, Tree.all.DATA)) then
Insert(Tree.all.Right, DATA);
end if;
end Insert;
-- Supprimer tous les éléments d'un Tree.
procedure Destruct (Tree : in out T_BT) is
begin
if Is_Empty (Tree) then
Null;
else
Destruct (Tree.all.Left);
Destruct (Tree.all.Right);
Free (Tree);
end if;
end Destruct;
-- Afficher un Tree dans l'ordre croissant des DATAs.
procedure Display (Tree : in T_BT) is
begin
if (not Is_Empty (Tree)) then
Display (Tree.all.Left);
Display_DATA (Tree.all.DATA);
Display (Tree.all.Right);
end if;
end Display;
end Arbre_Binaire;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--*
-- CHECK THAT THE BOUNDS OF A POSITIONAL AGGREGATE ARE DETERMINED
-- CORRECTLY. IN PARTICULAR, CHECK THAT THE LOWER BOUND IS GIVEN BY
-- THE LOWER BOUND OF THE APPLICABLE INDEX CONSTRAINT WHEN THE
-- POSITIONAL AGGREGATE IS USED AS:
-- AN ACTUAL PARAMETER IN A SUBPROGRAM, AND THE
-- FORMAL PARAMETER IS CONSTRAINED.
-- EG 01/27/84
WITH REPORT;
PROCEDURE C43205G IS
USE REPORT;
BEGIN
TEST("C43205G", "SUBPROGRAM WITH CONSTRAINED " &
"ONE-DIMENSIONAL ARRAY FORMAL PARAMETER");
BEGIN
CASE_G : BEGIN
CASE_G1 : DECLARE
TYPE TA IS ARRAY (IDENT_INT(11) .. 15) OF INTEGER;
PROCEDURE PROC1 (A : TA) IS
BEGIN
IF A'FIRST /= 11 THEN
FAILED ("CASE A1 : LOWER BOUND " &
"INCORRECT");
ELSIF A'LAST /= 15 THEN
FAILED ("CASE A1 : UPPER BOUND " &
"INCORRECT");
ELSIF A /= (6, 7, 8, 9, 10) THEN
FAILED ("CASE A1 : ARRAY DOES NOT " &
"CONTAIN THE CORRECT VALUES");
END IF;
END;
BEGIN
PROC1 ((6, 7, 8, IDENT_INT(9), 10));
END CASE_G1;
CASE_G2 : DECLARE
TYPE TA IS ARRAY (11 .. 12,
IDENT_INT(10) .. 11) OF INTEGER;
PROCEDURE PROC1 (A : TA) IS
BEGIN
IF A'FIRST(1) /= 11 OR A'FIRST(2) /= 10 THEN
FAILED ("CASE A2 : LOWER BOUND " &
"INCORRECT");
ELSIF A'LAST(1) /= 12 OR A'LAST(2) /= 11 THEN
FAILED ("CASE A2 : UPPER BOUND " &
"INCORRECT");
ELSIF A /= ((1, 2), (3, 4)) THEN
FAILED ("CASE A2 : ARRAY DOES NOT " &
"CONTAIN THE CORRECT VALUES");
END IF;
END;
BEGIN
PROC1 (((1, 2), (3, 4)));
END CASE_G2;
END CASE_G;
END;
RESULT;
END C43205G;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Apsepp.Test_Event_Class.Generic_Timestamp_Mixin is
----------------------------------------------------------------------------
overriding
procedure Set (Obj : in out Child_W_Timestamp; Data : Test_Event_Data) is
begin
Parent (Obj).Set (Data); -- Inherited procedure call.
Obj.Date := Data.Date;
end Set;
----------------------------------------------------------------------------
overriding
function Timestamp (Obj : Child_W_Timestamp) return Time
is (Obj.Date);
----------------------------------------------------------------------------
overriding
procedure Set_Timestamp (Obj : in out Child_W_Timestamp;
Date : Time := Clock) is
begin
Obj.Date := Date;
end Set_Timestamp;
----------------------------------------------------------------------------
end Apsepp.Test_Event_Class.Generic_Timestamp_Mixin;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.IO_Exceptions;
with Ada.IO_Modes;
private with Ada.Streams; -- [gcc-5] can not find it by below "with Stream_IO"
private with Ada.Streams.Stream_IO;
generic
type Element_Type (<>) is private;
package Ada.Sequential_IO is
type File_Type is limited private;
-- Similar to Text_IO in AI12-0054-2:
-- subtype Open_File_Type is File_Type
-- with
-- Dynamic_Predicate => Is_Open (Open_File_Type),
-- Predicate_Failure => raise Status_Error with "File not open";
-- subtype Input_File_Type is Open_File_Type
-- with
-- Dynamic_Predicate => Mode (Input_File_Type) = In_File,
-- Predicate_Failure =>
-- raise Mode_Error with
-- "Cannot read file: " & Name (Input_File_Type);
-- subtype Output_File_Type is Open_File_Type
-- with
-- Dynamic_Predicate => Mode (Output_File_Type) /= In_File,
-- Predicate_Failure =>
-- raise Mode_Error with
-- "Cannot write file: " & Name (Output_File_Type);
-- type File_Mode is (In_File, Out_File, Append_File);
type File_Mode is new IO_Modes.File_Mode; -- for conversion
-- File management
procedure Create (
File : in out File_Type;
Mode : File_Mode := Out_File;
Name : String := "";
Form : String := "");
procedure Open (
File : in out File_Type;
Mode : File_Mode;
Name : String;
Form : String := "");
procedure Close (File : in out File_Type);
procedure Delete (File : in out File_Type);
procedure Reset (File : in out File_Type; Mode : File_Mode);
procedure Reset (File : in out File_Type);
function Mode (
File : File_Type) -- Open_File_Type
return File_Mode;
function Name (
File : File_Type) -- Open_File_Type
return String;
function Form (
File : File_Type) -- Open_File_Type
return String;
pragma Inline (Mode);
pragma Inline (Name);
pragma Inline (Form);
function Is_Open (File : File_Type) return Boolean;
pragma Inline (Is_Open);
procedure Flush (
File : File_Type); -- Output_File_Type
-- AI12-0130-1
-- Input and output operations
procedure Read (
File : File_Type; -- Input_File_Type
Item : out Element_Type);
procedure Write (
File : File_Type; -- Output_File_Type
Item : Element_Type);
function End_Of_File (
File : File_Type) -- Input_File_Type
return Boolean;
pragma Inline (End_Of_File);
-- Exceptions
Status_Error : exception
renames IO_Exceptions.Status_Error;
Mode_Error : exception
renames IO_Exceptions.Mode_Error;
Name_Error : exception
renames IO_Exceptions.Name_Error;
Use_Error : exception
renames IO_Exceptions.Use_Error;
Device_Error : exception
renames IO_Exceptions.Device_Error;
End_Error : exception
renames IO_Exceptions.End_Error;
Data_Error : exception
renames IO_Exceptions.Data_Error;
private
type File_Type is new Streams.Stream_IO.File_Type;
end Ada.Sequential_IO;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body WisiToken.Generate.Packrat is
function Potential_Direct_Right_Recursive
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Empty : in Token_ID_Set)
return Token_ID_Set
is
subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index;
begin
return Result : Token_ID_Set (Nonterminal) := (others => False) do
for Prod of Grammar loop
RHS_Loop :
for RHS of Prod.RHSs loop
ID_Loop :
for I in reverse RHS.Tokens.First_Index + 1 .. RHS.Tokens.Last_Index loop
declare
ID : constant Token_ID := RHS.Tokens (I);
begin
if ID = Prod.LHS then
Result (ID) := True;
exit RHS_Loop;
elsif not (ID in Nonterminal) then
exit ID_Loop;
elsif not Empty (ID) then
exit ID_Loop;
end if;
end;
end loop ID_Loop;
end loop RHS_Loop;
end loop;
end return;
end Potential_Direct_Right_Recursive;
procedure Indirect_Left_Recursive (Data : in out Packrat.Data)
is
begin
for Prod_I of Data.Grammar loop
for Prod_J of Data.Grammar loop
Data.Involved (Prod_I.LHS, Prod_J.LHS) :=
Data.First (Prod_I.LHS, Prod_J.LHS) and
Data.First (Prod_J.LHS, Prod_I.LHS);
end loop;
end loop;
end Indirect_Left_Recursive;
----------
-- Public subprograms
function Initialize
(Source_File_Name : in String;
Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Source_Line_Map : in Productions.Source_Line_Maps.Vector;
First_Terminal : in Token_ID)
return Packrat.Data
is
Empty : constant Token_ID_Set := WisiToken.Generate.Has_Empty_Production (Grammar);
begin
return Result : Packrat.Data :=
(First_Terminal => First_Terminal,
First_Nonterminal => Grammar.First_Index,
Last_Nonterminal => Grammar.Last_Index,
Source_File_Name => +Source_File_Name,
Grammar => Grammar,
Source_Line_Map => Source_Line_Map,
Empty => Empty,
Direct_Left_Recursive => Potential_Direct_Left_Recursive (Grammar, Empty),
First => WisiToken.Generate.First (Grammar, Empty, First_Terminal => First_Terminal),
Involved => (others => (others => False)))
do
Indirect_Left_Recursive (Result);
end return;
end Initialize;
procedure Check_Recursion (Data : in Packrat.Data; Descriptor : in WisiToken.Descriptor)
is
Right_Recursive : constant Token_ID_Set := Potential_Direct_Right_Recursive (Data.Grammar, Data.Empty);
begin
for Prod of Data.Grammar loop
if Data.Direct_Left_Recursive (Prod.LHS) and Right_Recursive (Prod.LHS) then
-- We only implement the simplest left recursion solution ([warth
-- 2008] figure 3); [tratt 2010] section 6.3 gives this condition for
-- that to be valid.
-- FIXME: not quite? definite direct right recursive ok?
-- FIXME: for indirect left recursion, need potential indirect right recursive check?
Put_Error
(Error_Message
(-Data.Source_File_Name, Data.Source_Line_Map (Prod.LHS).Line, "'" & Image (Prod.LHS, Descriptor) &
"' is both left and right recursive; not supported."));
end if;
for I in Data.Involved'Range (2) loop
if Prod.LHS /= I and then Data.Involved (Prod.LHS, I) then
Put_Error
(Error_Message
(-Data.Source_File_Name, Data.Source_Line_Map (Prod.LHS).Line, "'" & Image (Prod.LHS, Descriptor) &
"' is indirect recursive with " & Image (I, Descriptor) & ", not supported"));
end if;
end loop;
end loop;
end Check_Recursion;
procedure Check_RHS_Order (Data : in Packrat.Data; Descriptor : in WisiToken.Descriptor)
is
use all type Ada.Containers.Count_Type;
begin
for Prod of Data.Grammar loop
-- Empty must be last
for I in Prod.RHSs.First_Index .. Prod.RHSs.Last_Index - 1 loop
if Prod.RHSs (I).Tokens.Length = 0 then
Put_Error
(Error_Message
(-Data.Source_File_Name, Data.Source_Line_Map (Prod.LHS).RHS_Map (I),
"right hand side" & Integer'Image (I) & " in " & Image (Prod.LHS, Descriptor) &
" is empty, but not last; no later right hand side will match."));
WisiToken.Generate.Error := True;
end if;
end loop;
for I in Prod.RHSs.First_Index + 1 .. Prod.RHSs.Last_Index loop
declare
Cur : Token_ID_Arrays.Vector renames Prod.RHSs (I).Tokens;
begin
-- Shared prefix; longer must be first
for J in Prod.RHSs.First_Index .. I - 1 loop
declare
Prev : Token_ID_Arrays.Vector renames Prod.RHSs (J).Tokens;
K : constant Natural := Shared_Prefix (Prev, Cur);
begin
if K > 0 and Prev.Length < Cur.Length then
Put_Error
(Error_Message
(-Data.Source_File_Name, Data.Source_Line_Map (Prod.LHS).RHS_Map (I),
"right hand side" & Integer'Image (I) & " in " & Image (Prod.LHS, Descriptor) &
" may never match; it shares a prefix with a shorter previous rhs" &
Integer'Image (J) & "."));
end if;
end;
end loop;
-- recursion; typical LALR list is written:
--
-- statement_list
-- : statement
-- | statement_list statement
-- ;
-- association_list
-- : association
-- | association_list COMMA association
-- ;
--
-- a different recursive definition:
--
-- name
-- : IDENTIFIER
-- | name LEFT_PAREN range_list RIGHT_PAREN
-- | name actual_parameter_part
-- ...
-- ;
--
-- For packrat, the recursive RHSs must come before others:
--
-- statement_list
-- : statement_list statement
-- | statement
-- ;
-- association_list
-- : association_list COMMA association
-- | association
-- ;
-- name
-- : name LEFT_PAREN range_list RIGHT_PAREN
-- | name actual_parameter_part
-- | IDENTIFIER
-- ...
-- ;
declare
Prev : Token_ID_Arrays.Vector renames Prod.RHSs (I - 1).Tokens;
begin
if Cur.Length > 0 and then Prev.Length > 0 and then
Cur (1) = Prod.LHS and then Prev (1) /= Prod.LHS
then
Put_Error
(Error_Message
(-Data.Source_File_Name, Data.Source_Line_Map (Prod.LHS).Line,
"recursive right hand sides must be before others."));
end if;
end;
end;
end loop;
end loop;
end Check_RHS_Order;
procedure Check_All (Data : in Packrat.Data; Descriptor : in WisiToken.Descriptor)
is begin
Check_Recursion (Data, Descriptor);
Check_RHS_Order (Data, Descriptor);
end Check_All;
function Potential_Direct_Left_Recursive
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Empty : in Token_ID_Set)
return Token_ID_Set
is
subtype Nonterminal is Token_ID range Grammar.First_Index .. Grammar.Last_Index;
begin
-- FIXME: this duplicates the computation of First; if keep First,
-- change this to use it.
return Result : Token_ID_Set (Nonterminal) := (others => False) do
for Prod of Grammar loop
RHS_Loop :
for RHS of Prod.RHSs loop
ID_Loop :
for ID of RHS.Tokens loop
if ID = Prod.LHS then
Result (ID) := True;
exit RHS_Loop;
elsif not (ID in Nonterminal) then
exit ID_Loop;
elsif not Empty (ID) then
exit ID_Loop;
end if;
end loop ID_Loop;
end loop RHS_Loop;
end loop;
end return;
end Potential_Direct_Left_Recursive;
end WisiToken.Generate.Packrat;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with
ada.unchecked_Deallocation;
package body openGL.Glyph
is
---------
-- Forge
--
procedure define (Self : in out Item; glyth_Slot : in freetype_c.FT_GlyphSlot.item)
is
begin
Self.Impl := new GlyphImpl.item;
Self.Impl.define (glyth_Slot);
end define;
procedure define (Self : in out Item; pImpl : in GlyphImpl.view)
is
begin
Self.Impl := pImpl;
end define;
procedure destruct (Self : in out Item)
is
procedure deallocate is new ada.unchecked_Deallocation (GlyphImpl.item'Class,
GlyphImpl.view);
begin
deallocate (Self.Impl);
end destruct;
--------------
-- Attributes
--
function Advance (Self : in Item) return Real
is
begin
return Self.Impl.Advance;
end Advance;
function BBox (Self : in Item) return Bounds
is
begin
return Self.Impl.BBox;
end BBox;
function Error (Self : in Item) return GlyphImpl.Error_Kind
is
begin
return Self.Impl.Error;
end Error;
end openGL.Glyph;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------------------------
with Text_IO; use Text_IO;
package body Orthogonal_Polys is
-- Global range for operations on data vectors:
Data_First : Points_Index := Points_index'First;
Data_Last : Points_Index := Points_index'Last;
-------------
-- Make_Re --
-------------
-- Converts Coeff_Index to Real in a way that simplifies things
-- when Real is a private extended precision floating point type.
-- It's slow, but it doesn't slow down any critical inner loops.
function Make_Re (N : Coeff_Index) return Real is
Result : Real := Zero;
begin
for i in 1 .. N loop
Result := Result + One;
end loop;
return Result;
end Make_Re;
------------------------------
-- Set_Limits_On_Vector_Ops --
------------------------------
procedure Set_Limits_On_Vector_Ops (First, Last : Points_Index) is
begin
Data_First := First;
Data_Last := Last;
end;
--------------------------------
-- Max_Permissable_Degree_Of --
--------------------------------
function Max_Permissable_Degree_Of (P : Polynomials) return Coeff_Index is
begin
return P.Max_Permissable_Degree_Of_Poly;
end Max_Permissable_Degree_Of;
-------------------
-- Inner product --
-------------------
function Inner_Product
(X, Y : in Data;
First, Last : in Points_Index;
Weights : in Data)
return Real
is
Sum : Real := Zero;
begin
for i in First .. Last loop
Sum := Sum + Weights(i) * Y(i) * X(i);
end loop;
return Sum;
end Inner_Product;
---------
-- "-" --
---------
function "-"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) - Right(i);
end loop;
return Result;
end "-";
---------
-- "+" --
---------
function "+"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) + Right(i);
end loop;
return Result;
end "+";
---------
-- "-" --
---------
function "-"
(Left : in Data;
Right : in Real)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) - Right;
end loop;
return Result;
end "-";
---------
-- "*" --
---------
function "*"
(Left : in Real;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left * Right(i);
end loop;
return Result;
end "*";
---------
-- "*" --
---------
-- fortran 90 Array * Array multiplication.
function "*"
(Left : in Data;
Right : in Data)
return Data
is
Result : Data;
begin
for i in Data_First .. Data_Last loop
Result(i) := Left(i) * Right(i);
end loop;
return Result;
end "*";
----------------------------------------
-- Start_Gram_Schmidt_Poly_Recursion --
----------------------------------------
-- Given a set of discrete points X
-- X = (X1, X2, ...)
-- and the weights
-- W = (W1, W2, ...)
-- the Gram-Schmidt recurrance method yield a unique set of
-- orthogonal polynomials (functions defined at the grid points Xj).
-- It is assumed that the the zeroth order poly is constant 1,
-- and the 1st order poly is X. (Both have normalization factors
-- that are not applied to the polys here...instead the norm factor
-- is calculated and returned as field in the poly data structure.)
procedure Start_Gram_Schmidt_Poly_Recursion
(X_axis, Weights : in Data;
First, Last : in Points_Index;
Poly_0, Poly_1 : in out Poly_Data;
Poly_Set : out Polynomials)
is
X_max, X_min, Max_Delta_X : Real;
Slope, Const : Real;
X_Poly_0 : Data;
Alpha, Beta : Real;
X_Scaled : Data;
type Local_Float is digits 9;
Data_Length, No_Of_Weightless_Data_Points : Local_Float := 0.0;
begin
Set_Limits_On_Vector_Ops (First, Last);
-- Step 0. Make sure we have enough data points to calculate
-- a polynomial of the desired degree. For example we don't want
-- to try to fit a parabola to just two data points. So we start by
-- calculating the number of data points to be used. if Weight(i) is
-- less than Smallest_Weight then don't count this as a data
-- point. (However the data point will be used
-- in the calculation below.) We require a minimum of 2 data points.
No_Of_Weightless_Data_Points := 0.0;
for i in First .. Last loop
if Weights(i) < Smallest_Weight then
No_Of_Weightless_Data_Points := No_Of_Weightless_Data_Points - 1.0;
end if;
end loop;
Data_Length := Local_Float (Last) - Local_Float (First) + 1.0;
Data_length := Data_Length - No_Of_Weightless_Data_Points;
if Data_Length < 2.0 then
put_line ("Need at last 2 data points with positive weight.");
raise Constraint_Error;
end if;
-- Because we make a first order poly in this procedure.
if Data_Length - 1.0 <= Local_Float (Max_Order_Of_Poly) then
Poly_Set.Max_Permissable_Degree_Of_Poly := Coeff_Index(Data_Length-1.0);
else
Poly_Set.Max_Permissable_Degree_Of_Poly := Max_Order_Of_Poly;
end if;
Poly_Set.Degree_Of_Poly := 1; -- Below we make 0 and 1.
-- Step 1. Make sure that the DeltaX is > Smallest_Delta_X for all
-- all X. So no two points can have the same X, and we can't
-- have Data_X(i+1) < Data_X(i) for any i.
for i in First+1 .. Last loop
if X_axis (i) - X_axis (i-1) < Smallest_Delta_X then
put_line("Data Points Must Be Ordered In X and Distinct.");
raise Constraint_Error;
end if;
end loop;
-- Step 2. Accuracy can be much improved if X is in the interval
-- [-2,2], so the X axis is scaled such that the X values lie in
-- the interval [-2,2]. We
-- scale X with the following equation: X_new = X * Slope + Const,
-- where
-- Slope = 4.0 / (X_max - X_min)
-- and
-- Const = -2.0 * (X_max + X_min) / (X_max - X_min).
--
-- The final poly for Y will be correct, but the coefficients
-- of powers of X in the power form of Poly calculated below
-- must be scaled.
--
-- The results will be stored in Poly_Set, for subsequent use in
-- generating polynomials, and unscaling the calculations done on
-- these polynomials.
X_max := X_axis (First);
X_min := X_axis (First);
for i in First+1 .. Last loop
if not (X_axis (i) < X_max) then
X_max := X_axis (i);
end if;
if X_axis(i) < X_min then
X_min := X_axis (i);
end if;
end loop;
Max_Delta_X := (X_max - X_min);
if Max_Delta_X < Smallest_Delta_X then
put_line ("Data Points Too Close Together In X");
raise Constraint_Error;
end if;
Slope := Four / Max_Delta_X;
Const := -Two * ((X_max + X_min) / Max_Delta_X);
X_scaled := Slope * X_axis - (-Const); -- Vector operations.
-- Store the results in Poly_Set:
Poly_Set.X_scaled := X_scaled;
Poly_Set.Scale_Factors := X_Axis_Scale'(Slope, Const);
-- Step 3. Get the Polynomials. Vector op limits have been set above.
-- The zeroth order poly (unnormalized) is just 1.0:
Poly_Set.Alpha(0) := Zero;
Poly_Set.Beta(0) := Zero;
Poly_0.Points := (others => One);
Poly_0.First := First;
Poly_0.Last := Last;
Poly_0.Squared :=
Inner_Product (Poly_0.Points, Poly_0.Points, First, Last, Weights);
Poly_0.Degree := 0;
-- Get the 1st order Polynomial. Unnormalized, it's just X - alpha;
X_Poly_0 := X_Scaled * Poly_0.Points;
Alpha :=
Inner_Product(X_Poly_0, Poly_0.Points, First, Last, Weights) / Poly_0.Squared;
Beta := Zero;
Poly_Set.Alpha(1) := Alpha;
Poly_Set.Beta(1) := Beta;
Poly_1.Points := X_scaled - Alpha;
Poly_1.Squared :=
Inner_Product (Poly_1.Points, Poly_1.Points, First, Last, Weights);
Poly_1.First := First;
Poly_1.Last := Last;
Poly_1.Degree := 1;
end Start_Gram_Schmidt_Poly_Recursion;
-------------------
-- Get_Next_Poly --
-------------------
-- We want Q_m, Alpha_m, and Beta_m, given the previous values.
--
-- Q_0 = 1
-- Q_1 = (X - Alpha_1)
-- Q_m = (X - Alpha_m) * Q_m-1 - Beta_m*Q_m-2
-- where
-- Alpha_m = (X*Q_m-1, Q_m-1) / (Q_m-1, Q_m-1)
-- Beta_m = (X*Q_m-1, Q_m-2) / (Q_m-2, Q_m-2)
--
-- Can be shown: Beta_m = (Q_m-1, Q_m-1) / (Q_m-2, Q_m-2) which is
-- the form used below.
procedure Get_Next_Poly
(Poly_0, Poly_1 : in Poly_Data;
Weights : in Data;
Poly_2 : in out Poly_Data;
Poly_Set : in out Polynomials)
is
X_Poly_1 : Data;
Alpha, Beta : Real;
X_scaled : Data renames Poly_Set.X_scaled;
Degree_2 : Coeff_Index;
First : Points_Index renames Poly_1.First;
Last : Points_Index renames Poly_1.Last;
begin
Set_Limits_On_Vector_Ops (First, Last);
-- Have to tell the vector ops that the data goes from First..Last.
-- Not really necessary, because Start_Gram_.. has already done this.
-- But we do it anyway. Next some checks:
if Poly_0.First /= Poly_1.First or Poly_0.Last /= Poly_1.Last then
put_line ("Some error in input polys for Get_Next_Poly.");
raise Constraint_Error;
end if;
-- Must have Poly_Set.Degree_Of_Poly = Poly_1.Degree = Poly_0.Degree+1
if Poly_Set.Degree_Of_Poly /= Poly_0.Degree + 1 or
Poly_Set.Degree_Of_Poly /= Poly_1.Degree then
put_line ("Some error in input polys for Get_Next_Poly.");
raise Constraint_Error;
end if;
-- The purpose of this is to raise the degree of poly_set by one.
-- Can we do that?
if Poly_Set.Degree_Of_Poly >= Poly_Set.Max_Permissable_Degree_Of_Poly then
put_line ("Cannot make a poly of that order with so few points.");
raise Constraint_Error;
end if;
-- Now we can construct the next higher order polynomial: Poly_2
X_Poly_1 := X_Scaled * Poly_1.Points;
Alpha := Inner_Product(X_Poly_1, Poly_1.Points,
First, Last, Weights) / Poly_1.Squared;
Beta := Poly_1.Squared / Poly_0.Squared;
Degree_2 := Poly_Set.Degree_Of_Poly + 1;
Poly_Set.Degree_Of_Poly := Degree_2;
Poly_Set.Beta (Degree_2) := Beta;
Poly_Set.Alpha (Degree_2) := Alpha;
Poly_2.Points := (X_scaled - Alpha) * Poly_1.Points
- Beta * Poly_0.Points;
Poly_2.Squared := Inner_Product (Poly_2.Points, Poly_2.Points,
First, Last, Weights);
Poly_2.First := Poly_1.First;
Poly_2.Last := Poly_1.Last;
Poly_2.Degree := Poly_1.Degree + 1;
end Get_Next_Poly;
-------------------------------
-- Get_Coeffs_Of_Powers_Of_X --
-------------------------------
-- Calculate the Coefficients of powers of X in the best fit poly, using
-- Alpha, Beta, C as calculated above and the following formula for
-- the orthogonal polynomials:
-- Q_0 = 1
-- Q_1 = (X - Alpha_1)
-- Q_k = (X - Alpha_k) * Q_k-1 - Beta_k*Q_k-2
-- and the best fit poly is SUM {C_k * Q_k}. The Coefficients of X**k
-- are put in array Poly_Coefficients(k), which is set to 0.0 initially,
-- since the formula may assign values to only a small subset of it.
-- the E_k's in SUM {E_k * X**k} go into Poly_Coefficients(k).
-- Clenshaw's formula is used to get Poly_Coefficients. The
-- coefficients of the following D polynomials are put into arrays
-- D_0, D_1, and D_2, and advanced recursively until the final
-- D_0 = SUM {C_k * Q_k} is found. This will be named Poly_Coefficients.
-- The recursion formula for the Coefficients follows from the formula for D(X):
--
-- D_n+2(X) = 0
-- D_n+1(X) = 0
-- D_m(X) = C_m + (X - Alpha_m+1)*D_m+1(X) - Beta_m+2*D_m+2(X)
--
-- where n = Desired_Poly_Degree and m is in 0..n.
--
-- Now suppose we want the coefficients of powers of X for the above D polys.
-- (In the end that will give us the coeffs of the actual poly, D_0.)
-- Well, the first poly D_n is 0-th order and equals C(n). The second poly, D_n-1,
-- gets a contribution to its coefficient of X**1 from the X*D_n term. That
-- contribution is the coefficient of X**0 in D_n. Its X**0 coeff gets a
-- contribution from C(n-1) and one from -Alpha(n)*D_n at X**0, or -Alpha(n)*D_n(0).
-- Now we re-use the D
-- polynomial arrays to store these coefficients in the obvious place.
-- The arrays D_0, D_1, and D_2 are initialized to 0.0.
-- D_0, D_1, and D_2 contain be the coeff's of powers of X in the orthogonal
-- polynomials D_m, D_m+1, D_m+2, respectively. The formulas above
-- imply: for m in Desired_Poly_Degree .. 0:
--
-- D_0(0) := C(m);
-- for k in 1 .. Desired_Poly_Degree loop
-- D_0(k) := D_1(k-1);
-- end loop;
-- -- The above initalizes D_0.
--
-- for k in 0 .. Desired_Poly_Degree loop
-- D_0(k) := D_0(k) - Alpha(m+1)*D_1(k) - Beta(m+2)*D_2(k);
-- end loop;
--
-- So if we define shl_1 = Shift_Array_Left_by_1_and_Put_0_at_Index_0, the
-- formula in vector notation is:
--
-- D_0 = Y(m) + shl_1 (D_1) - Alpha(m+1)*D_1 - Beta(m+2)*D_2
--
-- where Y(m) = (C(m),0,0,....).
-- the above step is repeated recursivly using D_2 = D_1, and D_1 = D_0.
-- Notice that the above formula must be modified at m = n and m = n-1.
-- In matrix notation, using vector D, and vector Y this becomes:
--
--
-- | 1 0 0 0 | |D(n) | | Y(n) |
-- | A_n 1 0 0 | |D(n-1)| = | Y(n-1) |
-- | B_n A_n-1 1 0 | |D(n-2)| | Y(n-2) |
-- | 0 B_n-1 A_n-2 1 | |D(n-3)| | Y(n-3) |
--
-- where A_m = -(shl_1 - Alpha_m), B_m = Beta_m, and Y(m) = (C(m),0,0,....).
-- In the end, D(0) should be an array that contains the Coefficients of Powers
-- of X. The operator is not a standard matrix operator, but it's linear and we
-- know its inverse and forward operation, so Newton's method gives the
-- iterative refinement. The array D(k)(m) is possibly very large!
procedure Get_Coeffs_Of_Powers_Of_X
(Coeffs : out Powers_Of_X_Coeffs;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
is
D_1, D_2 : Recursion_Coeffs := (others => Zero);
D_0 : Recursion_Coeffs := (others => Zero);
m : Coeff_Index;
Const2 : Real := Zero;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
Coeffs := (others => Zero);
-- Special Case. Calculate D_2 (i.e. the D_m+2 poly):
m := Poly_Degree;
D_2(0) := C(m);
if Poly_Degree = 0 then
D_0 := D_2;
end if;
-- Special Case. Calculate D_1 (i.e. the D_m+1 poly):
if Poly_Degree > 0 then
m := Poly_Degree - 1;
D_1(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_1(k) := D_2(k-1);
end loop;
-- The previous 2 assigments have initialized D_1. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_1(k) := D_1(k) - A(m+1) * D_2(k);
end loop;
end if;
if Poly_Degree = 1 then
D_0 := D_1;
end if;
-- Calculate D's for D_n-2 and lower:
if Poly_Degree > 1 then
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D_0(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_0(k) := D_1(k-1);
end loop;
-- The previous 2 assigments have initialized D_0. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_0(k) := D_0(k) - A(m+1) * D_1(k);
end loop;
for k in Coeff_Index'First .. Poly_Degree-m-2 loop
D_0(k) := D_0(k) - B(m+2) * D_2(k);
end loop;
D_2 := D_1;
D_1 := D_0;
end loop;
end if;
-- Now we have the coefficients of powers of X for the poly P1 (Z(X))
-- whose Z is in the range [-2,2]. How do we get the coeffs of
-- poly P2 (X) = P1 (Z(X)) whose X is in the range [a, b]. The
-- relation between Z and X is Z = 2*(2*X - (a + b)) / (a - b).
-- or Z = Slope * (X - Const2) where Slope = 4 / (a - b) and
-- Const2 = (a + b) / 2. We have P1 (Z). The first step in getting
-- P2 (X) is to get P1 (X - Const2) by multiplying the Coeffs of
-- of P1 by powers of Slope.
-- This is a common source of overflow.
-- The following method is slower but slightly more overflow resistant
-- than the more obvious method.
for j in 1 .. Poly_Degree loop
for k in Coeff_Index'First+j .. Poly_Degree loop
D_0(k) := D_0(k) * Scale_Factors.Slope;
end loop;
end loop;
-- Next we want coefficients of powers of X in P2 where P2 (X) is
-- defined P2 (X) = P1 (X - Const2). In other words we want the
-- coefficients E_n in
--
-- P2 (X) = E_n*X**n + E_n-1*X**n-1 .. + E_1*X + E_0.
--
-- We know that
--
-- P1 (X) = F_n*X**n + F_n-1*X**n-1 .. + F_1*X + F_0,
--
-- where the F's are given by Coeff_0 above,
-- and P2 (X + Const2) = P1 (X). Use synthetic division to
-- shift P1 in X as follows. (See Mathew and Walker).
-- P2 (X + Const2) = E_n*(X + Const2)**n + .. + E_0.
-- So if we divide P2 (X + Const2) by (X + Const2) the remainder
-- is E_0. if we repeat the division, the remainder is E_1.
-- So we use synthetic division to divide P1 (X) by (X + Const2).
-- Synthetic division: multiply (X + Const2) by
-- F_n*X**(n-1) = D_0(n)*X**(n-1) and subtract from P1.
-- Repeat as required.
-- What is Const2?
-- Slope := 4.0 / Max_Delta_X;
-- Const := -2.0 * (X_max + X_min) / Max_Delta_X; -- 2 (a + b)/(b - a)
-- X_scaled = Z = X * Slope + Const.
-- Want Z = Slope * (X - Const2). Therefore Const2 = - Const/Slope
Const2 := -Scale_Factors.Const / Scale_Factors.Slope;
for m in Coeff_Index range 1 .. Poly_Degree loop
for k in reverse Coeff_Index range m .. Poly_Degree loop
D_0 (k-1) := D_0 (k-1) - D_0 (k) * Const2;
end loop;
Coeffs (m-1) := D_0 (m-1);
end loop;
Coeffs (Poly_Degree) := D_0 (Poly_Degree);
end Get_Coeffs_Of_Powers_Of_X;
----------------
-- Horner_Sum --
----------------
-- Want Sum = a_0 + a_1*X + a_2*X**2 + ... + a_n*X**n.
-- or in Horner's form: Sum = a_0 + X*(a_1 + ... + X*(a_n-1 + X*a_n)))))).
-- This is easily written as matrix equation, with Sum = S_0:
--
-- S_n = a_n; S_n-1 = a_n-1 + X*S_n; S_1 = a_1 + X*S_2; S_0 = a_0 + X*S_1;
--
-- In matrix form, vector S is the solution to matrix equation M*S = A,
-- where A = (a_0,...,a_n), S = (S_0,...,S_n) and matrix M is equal to
-- the unit matrix i minus X*O1, where O1 is all 1's on the 1st lower off-
-- diagonal. The reason this form is chosen is that the solution vector
-- S can be improved numerically by iterative refinement with Newton's
-- method:
-- S(k+1) = S(k) + M_inverse * (A - M*S(k))
--
-- where S = M_inverse * A is the calculation of S given above. if the
-- said calculation of S is numerically imperfect, then the iteration above
-- will produce improved values of S. Of course, if the Coefficients of
-- the polynomial A are numerically poor, then this effort may be wasted.
--
function Horner_Sum
(A : in Recursion_Coeffs;
Coeff_Last : in Coeff_Index;
X : in Real;
No_Of_Iterations : in Natural)
return Real
is
S : Recursion_Coeffs := (others => Zero);
Del, Product : Recursion_Coeffs;
begin
if Coeff_Last = Coeff_Index'First then
return A(Coeff_Index'First);
end if;
-- Poly is zeroth order = A(Index'First). No work to do. Go home.
-- Now solve for S in the matrix equation M*S = A. first iteration:
S(Coeff_Last) := A(Coeff_Last);
for n in reverse Coeff_Index'First .. Coeff_Last-1 loop
S(n) := A(n) + X * S(n+1);
end loop;
-- Now iterate as required. We have the first S, S(1), now get S(2) from
-- S(k+1) = S(k) + M_inverse * (A - M*S(k))
Iterate: for k in 1..No_Of_Iterations loop
-- Get Product = M*S(k):
Product(Coeff_Last) := S(Coeff_Last);
for n in reverse Coeff_Index'First..Coeff_Last-1 loop
Product(n) := S(n) - X * S(n+1);
end loop;
-- Get Product = Residual = A - M*S(k):
for n in Coeff_Index'First .. Coeff_Last loop
Product(n) := A(n) - Product(n);
end loop;
-- Get Del = M_inverse * (A - M*S(k)) = M_inverse * Product:
Del(Coeff_Last) := Product(Coeff_Last);
for n in reverse Coeff_Index'First .. Coeff_Last-1 loop
Del(n) := Product(n) + X * Del(n+1);
end loop;
-- Get S(k+1) = S(k) + Del;
for n in Coeff_Index'First .. Coeff_Last loop
S(n) := S(n) + Del(n);
end loop;
end loop Iterate;
return S(Coeff_Index'First);
end Horner_Sum;
-------------------
-- Poly_Integral --
-------------------
-- Use Clenshaw summation to get coefficients of powers of X,
-- then sum analytically integrated polynomial using Horner's rule.
-- Poly_Integral returns the indefinite integral. Integral on an
-- interval [A, B] is Poly_Integral(B) - Poly_Integral(A).
--
function Poly_Integral
(X : in Real;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials;
Order_Of_Integration : in Coeff_Index := 1)
return Real
is
D_1, D_2 : Recursion_Coeffs := (others => Zero);
D_0 : Recursion_Coeffs := (others => Zero);
m : Coeff_Index;
Result : Real := Zero;
Denom, X_scaled : Real := Zero;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
-- Special Case. Calculate D_2 (i.e. the D_m+2 poly):
m := Poly_Degree;
D_2(0) := C(m);
if Poly_Degree = 0 then
D_0 := D_2;
end if;
-- Special Case. Calculate D_1 (i.e. the D_m+1 poly):
if Poly_Degree > 0 then
m := Poly_Degree - 1;
D_1(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_1(k) := D_2(k-1);
end loop;
-- The previous 2 assigments have initialized D_1. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_1(k) := D_1(k) - A(m+1) * D_2(k);
end loop;
end if;
if Poly_Degree = 1 then
D_0 := D_1;
end if;
-- Calculate D's for D_n-2 and lower:
if Poly_Degree > 1 then
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D_0(0) := C(m);
for k in Coeff_Index range 1 .. Poly_Degree-m loop
D_0(k) := D_1(k-1);
end loop;
-- The previous 2 assigments have initialized D_0. Now:
for k in Coeff_Index'First .. Poly_Degree-m-1 loop
D_0(k) := D_0(k) - A(m+1) * D_1(k);
end loop;
for k in Coeff_Index'First .. Poly_Degree-m-2 loop
D_0(k) := D_0(k) - B(m+2) * D_2(k);
end loop;
D_2 := D_1;
D_1 := D_0;
end loop;
end if;
-- The unscaled Coeffs of X**m are D_0(m). Integrate once,
-- (brings a 1/(m+1) down) then use Horner's rule for poly sum:
-- First scale X from [a, b] to [-2, 2]:
X_Scaled := X * Poly_Set.Scale_Factors.Slope + Poly_Set.Scale_Factors.Const;
for m in reverse Coeff_Index'First .. Poly_Degree loop
Denom := One;
for i in 1 .. Order_Of_Integration loop
Denom := Denom * (Make_Re (m + i));
end loop;
D_0(m) := D_0(m) / Denom;
end loop;
Result :=
Horner_Sum
(A => D_0,
Coeff_Last => Poly_Degree,
X => X_scaled,
No_Of_Iterations => 1);
Result := Result * X_scaled ** Integer(Order_Of_Integration);
-- This X was neglected above in Horner_Sum.
-- The integral was on a scaled interval [-2, X]. Unscale the result:
Result :=
Result / Poly_Set.Scale_Factors.Slope ** Integer(Order_Of_Integration);
return Result;
end Poly_Integral;
----------------------
-- Poly_Derivatives --
----------------------
-- How do we get the derivatives of the best-fit polynomial? Just
-- take the derivative of the Clenshaw recurrence formula given above.
-- In the special case of orthogonal polynomials it is particularly
-- easy. By differentiating the formula given above p times it's easy
-- to see that the p-th derivative of the D_m functions of X satisfy:
--
-- p = order of derivative = 0:
--
-- D_n+2(0,X) = 0
-- D_n+1(0,X) = 0
-- D_m(0,X) = C_m + (X - Alpha(m+1)) * D_m+1(0,X) + Beta(m+2) * D_m+2(0,X)
--
-- p = order of derivative > 0:
--
-- D_n+2(p,X) = 0
-- D_n+1(p,X) = 0
-- D_m(p,X)
-- = p*D_m+1(p-1,X) + (X - Alpha(m+1))*D_m+1(p,X) - Beta(m+2)*D_m+2(p,X)
--
-- for m in 0..n,
-- where D(p,X) is the pth derivative of D(X). It follows that the
-- p-th derivative of the sum over m of C_m*Q_m(X) equals D_0(p,X).
--
-- We still aren't finished. What we really want is the derivative
-- respect the UNSCALED variable, Y. Here X = X_Scaled is in the range
-- [-2,2] and X_scaled = Slope * Y + Constant. So d/dY = Slope * d/dX.
-- Usually Y is in (say) 1..100, and X is in -2..2, so Slope is << 1.
-- It follows that the recurrence relation for the p-th derivative
-- of the D polynomials respect Y is
--
-- D_n+2(p,X) = 0
-- D_n+1(p,X) = 0
-- D_m(p,X) = p * Slope * D_m+1(p-1,X)
-- + (X - Alpha(m+1))*D_m+1(p,X) - Beta(m+2)*D_m+2(p,X)
--
-- for m in 0..n,
-- where D(p,X) is the p-th derivative of D(X). It follows that the
-- p-th derivative the sum over m of C_m*Q_m(X) equals D_0(p,X).
--
-- To perform the calculation, the 0th derivative (p=0) D is calculated
-- first, then used as a constant in the recursion relation to get the
-- p=1 D. These steps are repeated recursively.
--
-- In the code that follows D is an array only in "m". X is a constant,
-- input by the user of the procedure, and p is reduced to 2 values,
-- "Hi" and "Low". So we calculate D_low(m) where derivative order
-- p = Low, which starts at 0, and use D_low(m) to get D_hi(m), where
-- Hi = Low + 1.
--
-- p = order of derivative == Low = 0:
--
-- D_low(n+2) = 0
-- D_low(n+1) = 0
-- D_low(m) = C_m + (X - Alpha(m+1)) * D_low(m+1) + Beta(m+2) * D_low(m+2)
--
-- p = order of derivative == hi > 0
--
-- D_hi(n+2) = 0
-- D_hi(n+1) = 0
-- D_hi(m) = p * Slope * D_low(m+1)
-- + (X - Alpha(m+1))*D_hi(m+1) - Beta(m+2)*D_hi(m+2)
--
-- Next iterative refinement is optionally performed. For each value of
-- of p, the following matrix equation represents the recursive equations
-- above. Remember, in the following, D_low is a previously calculated
-- constant:
--
-- | 1 0 0 0 | |D_hi(n) | | Y(n) |
-- | A_n 1 0 0 | |D_hi(n-1)| = | Y(n-1) |
-- | B_n A_n-1 1 0 | |D_hi(n-2)| | Y(n-2) |
-- | 0 B_n-1 A_n-2 1 | |D_hi(n-3)| | Y(n-3) |
--
-- where A_m = -(X - Alpha_m), B_m = Beta_m, and Y(m) = C(m) if p=0, and
-- Y(m) = p * Slope * D_low(m+1) if p > 0. (Remember, D_any(n+1) = 0.0).
-- So the refinement is in the m iteration not the p iteration.
-- The iteration can actually be done in both p and m, but in that case D
-- must be stored as a 2-d array. In that case the matrix equation
-- is a block Lower triangular matrix. We do it the less sophisticated way
-- here.
procedure Poly_Derivatives
(Derivatives : in out Derivative_List;
X : in Real;
Order_Of_Deriv : in Derivatives_Index;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
is
Order : Real;
Order_times_Slope : Real;
X_Scaled : Real;
D_Hi, D_Low : Recursion_Coeffs;
-- D_Hi is the higher deriv. in the recurrence relation.
Local_Order_Of_Deriv : Derivatives_Index;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
begin
-- The derivatives of a polynomial are zero if their order is
-- greater than the degree of the polynomial, so in that case
-- don't bother to get them:
Derivatives := (others => Zero);
if Order_Of_Deriv > Poly_Degree then
Local_Order_Of_Deriv := Poly_Degree;
else
Local_Order_Of_Deriv := Order_Of_Deriv;
end if;
-- Scale X to the interval [-2,2].
X_Scaled := X * Scale_Factors.Slope + Scale_Factors.Const;
-- Step 1. We need a 0th order poly to start off the recurrence
-- relation. Start by getting undifferentiated D's (p=0).
-- Store them in array D_Low. The Low is for "Lower Order".
-- Use recurrence relation to get Poly at X.
-- Start with special formulas for the 1st 2 D-Polys:
D_Low(Poly_Degree) := C(Poly_Degree);
if Poly_Degree > Coeff_Index'First then
D_low(Poly_Degree-1) := C(Poly_Degree-1) +
(X_Scaled - A(Poly_Degree)) * D_low(Poly_Degree);
end if;
for m in reverse Coeff_Index'First+2 .. Poly_Degree loop
D_Low(m-2) := C(m-2) +
(X_Scaled - A(m-1))*D_Low(m-1) - B(m)*D_low(m);
end loop;
Derivatives (Derivatives_Index'First) := D_Low(Coeff_Index'First);
-- Step 2. Use the recurrence relation to get next higher
-- higher derivative. Store it in array D_Hi.
for p in Derivatives_Index'First+1 .. Local_Order_Of_Deriv loop
Order := Make_Re (p);
D_Hi(Poly_Degree) := Zero;
Order_times_Slope := Order * Scale_Factors.Slope;
if Poly_Degree > Coeff_Index'First then
D_Hi(Poly_Degree-1) := Order_times_Slope * D_Low(Poly_Degree) +
(X_Scaled - A(Poly_Degree)) * D_Hi(Poly_Degree);
end if;
for m in reverse Coeff_Index'First+2 .. Poly_Degree loop
D_Hi(m-2) := Order_times_Slope * D_low(m-1) +
(X_Scaled - A(m-1))*D_Hi(m-1) - B(m)*D_Hi(m);
end loop;
Derivatives (p) := D_Hi(Coeff_Index'First);
D_Low := D_Hi;
end loop;
end Poly_Derivatives;
----------------
-- Poly_Value --
----------------
-- This is easily written as matrix equation, with Sum = S_0:
--
-- D_n = C_n;
-- D_n-1 = C_n-1 + (X - A_n)*D_n;
-- D_n-2 = C_n-2 + (X - A_n-1)*D_n-1 - B_n-2*D_n-2;
-- ...
-- D_0 = C_0 + (X - A_1)*D_1 - B_2*D_2
--
-- In matrix form, M*D = C, this becomes:
--
-- | 1 0 0 0 | |D(n) | | C(n) |
-- | E_n 1 0 0 | |D(n-1)| = | C(n-1) |
-- | B_n E_n-1 1 0 | |D(n-2)| | C(n-2) |
-- | 0 B_n-1 E_n-2 1 | |D(n-3)| | C(n-3) |
--
-- where E_m = (A_m - X), B_m = B_m.
--
-- D can be improved numerically by iterative refinement with Newton's
-- method:
-- D_new = D_old + M_inverse * (C - M*D_old)
--
-- where D = M_inverse * C is the calculation of D given at the top. if the
-- said calculation of D is numerically imperfect, then the iteration above
-- will produce improved values of D. Of course, if the Coefficients of
-- the polynomials C are numerically poor, then this effort may be wasted.
function Poly_Value
(X : in Real;
C : in Poly_Sum_Coeffs;
Poly_Set : in Polynomials)
return Real
is
D, Product, Del : Recursion_Coeffs := (others => Zero);
X_Scaled : Real;
m : Coeff_Index;
A : Recursion_Coeffs renames Poly_Set.Alpha;
B : Recursion_Coeffs renames Poly_Set.Beta;
Scale_Factors : X_Axis_Scale renames Poly_Set.Scale_Factors;
Poly_Degree : Coeff_Index renames Poly_Set.Degree_Of_Poly;
No_Of_Iterations : constant Natural := 0;
begin
-- Scale X to the interval [-2,2].
X_Scaled := X * Scale_Factors.Slope + Scale_Factors.Const;
-- Step 0. Poly is zeroth order = C(Index'First). No work to do.
if Poly_Degree = Coeff_Index'First then
m := Poly_Degree;
D(m) := C(m);
return D(Coeff_Index'First);
end if;
-- Step 0b. Poly is 1st order. Almost no work to do.
-- Don't do any iteration.
if Poly_Degree = Coeff_Index'First + 1 then
m := Poly_Degree;
D(m) := C(m);
m := Poly_Degree - 1;
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1);
return D(Coeff_Index'First);
end if;
-- Step 1. We now know henceforth that Poly_Degree > 1.
-- Start by getting starting value of D by solving M*D = C.
-- Use recurrence relation to get Poly at X.
-- Start with special formulas for the 1st two Polys:
m := Poly_Degree;
D(m) := C(m);
m := Poly_Degree - 1;
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
D(m) := C(m) - (A(m+1) - X_Scaled)*D(m+1) - B(m+2)*D(m+2);
end loop;
-- Step 2. Improve D numerically through Newton iteration.
-- D_new = D_old + M_inverse * (C - M*D_old)
Iterate: for k in 1 .. No_Of_Iterations loop
-- Get Product = M*D(k):
m := Poly_Degree;
Product(m) := D(m);
m := Poly_Degree - 1;
Product(m) := D(m) + (A(m+1) - X_Scaled)*D(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
Product(m) := D(m) + (A(m+1) - X_Scaled)*D(m+1) + B(m+2)*D(m+2);
end loop;
-- Get Residual = C - M*D(k) and set it equal to Product:
for m in Coeff_Index'First .. Poly_Degree loop
Product(m) := C(m) - Product(m);
end loop;
-- Get Del = M_inverse * (A - M*S(k)) = M_inverse * Product:
m := Poly_Degree;
Del(m) := Product(m);
m := Poly_Degree - 1;
Del(m) := Product(m) - (A(m+1) - X_Scaled)*Del(m+1);
for m in reverse Coeff_Index'First .. Poly_Degree-2 loop
Del(m) := Product(m) - (A(m+1) - X_Scaled)*Del(m+1) - B(m+2)*Del(m+2);
end loop;
-- Get D(k+1) = D(k) + Del;
for m in Coeff_Index'First .. Poly_Degree loop
D(m) := D(m) + Del(m);
end loop;
end loop Iterate;
return D(Coeff_Index'First);
end Poly_Value;
--------------
-- Poly_Fit --
--------------
-- Generate orthogonal polys and project them onto the data
-- with the Inner_Product function in order to calculate
-- C_k, the Best_Fit_Coefficients.
procedure Poly_Fit
(Data_To_Fit : in Data;
X_axis, Weights : in Data;
First, Last : in Points_Index;
Desired_Poly_Degree : in Coeff_Index;
Best_Fit_Poly : in out Poly_Data;
Best_Fit_Coeffs : in out Poly_Sum_Coeffs;
Poly_Set : in out Polynomials;
Mean_Square_Error : out Real)
is
Poly_0, Poly_1, Poly_2 : Poly_Data;
Local_Poly_Degree : Coeff_Index := Desired_Poly_Degree;
Data_Length : Real;
C : Poly_Sum_Coeffs renames Best_Fit_Coeffs;
Dat : Data renames Data_To_Fit;
Best_Fit : Data renames Best_Fit_Poly.Points;
begin
Start_Gram_Schmidt_Poly_Recursion
(X_axis, Weights, First, Last, Poly_0, Poly_1, Poly_Set);
-- Get Degree of poly: may be less than the desired degree
-- if too few points exist in the subset defined by X.
if Local_Poly_Degree > Poly_Set.Max_Permissable_Degree_Of_Poly then
Local_Poly_Degree := Poly_Set.Max_Permissable_Degree_Of_Poly;
end if;
Data_Length := Make_Re (Local_Poly_Degree) + (One);
-- By definition of Local_Poly_Degree.
Set_Limits_On_Vector_Ops (First, Last);
-- Get C(0) = Coefficient of 0th orthog. poly.
C(0) :=
Inner_Product (Poly_0.Points, Dat, First, Last, Weights) / Poly_0.Squared;
Best_Fit := C(0) * Poly_0.Points;
-- Get C(1) = Coefficient of 1st orthog. poly.
if Local_Poly_Degree > 0 then
C(1) := Inner_Product (Poly_1.Points, Dat - Best_Fit,
First, Last, Weights) / Poly_1.Squared;
Best_Fit := Best_Fit + C(1) * Poly_1.Points;
end if;
-- Get C(2) = Coefficient of 2nd orthog. poly.
if Local_Poly_Degree > 1 then
Get_Next_Poly (Poly_0, Poly_1, Weights, Poly_2, Poly_Set);
C(2) :=
Inner_Product
(Poly_2.Points, Dat - Best_Fit, First, Last, Weights) / Poly_2.Squared;
Best_Fit := Best_Fit + C(2) * Poly_2.Points;
end if;
-- Higher order Polynomials: get C(i) which is the coefficient of
-- the Ith orthogonal polynomial. Also get the Best_Fit_Polynomial.
-- Notice that the formula used to get C(i) is a little more complicated
-- than the the one written in the prologue above. The formula used
-- below gives substantially better numerical results, and is
-- mathematically identical to formula given in the prologue.
for N in Coeff_Index range 3 .. Local_Poly_Degree loop
Poly_0 := Poly_1;
Poly_1 := Poly_2;
Get_Next_Poly (Poly_0, Poly_1, Weights, Poly_2, Poly_Set);
C(N) :=
Inner_Product
(Poly_2.Points, Dat - Best_Fit, First, Last, Weights) / Poly_2.Squared;
Best_Fit := Best_Fit + C(N) * Poly_2.Points;
end loop;
-- Reuse Poly_0 to calculate Error**2 per Point = Mean_Square_Error:
Poly_0.Points := Dat - Best_Fit;
Mean_Square_Error := Inner_Product (Poly_0.Points, Poly_0.Points,
First, Last, Weights) / Data_Length;
-- Finish filling Best_Fit_Poly and Poly_Set:
Poly_Set.Degree_Of_Poly := Local_Poly_Degree;
--Best_Fit_Poly.Points := Best_Fit; -- through renaming.
Best_Fit_Poly.First := First;
Best_Fit_Poly.Last := Last;
Best_Fit_Poly.Degree := Local_Poly_Degree;
Best_Fit_Poly.Squared :=
Inner_Product (Best_Fit, Best_Fit, First, Last, Weights);
end Poly_Fit;
begin
if Max_Order_Of_Poly > Max_No_Of_Data_Points - 1 then
put_line("Max poly order must be less than max number of data points.");
raise Constraint_Error;
end if;
end Orthogonal_Polys;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
-- The <b>Gen.Artifacts.Mappings</b> package is an artifact to map XML-based types
-- into Ada types.
package Gen.Artifacts.Mappings is
-- ------------------------------
-- Mappings artifact
-- ------------------------------
type Artifact is new Gen.Artifacts.Artifact with null record;
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class);
end Gen.Artifacts.Mappings;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
-- Cannibalized from Game_Driving (see Engine_3D)
-- To do : programmable behaviour
with GL, GLUT.Devices;
package Game_Control is
type Command is (
go_forward,
go_backwards,
go_graduated,
slide_left,
slide_right,
slide_lateral_graduated,
turn_left,
turn_right,
turn_lateral_graduated,
slide_up,
slide_down,
slide_vertical_graduated,
turn_up,
turn_down,
turn_vertical_graduated,
run_mode,
ctrl_mode, -- "shoot", but useless with GLUT
slide_mode,
swing_plus,
swing_minus,
jump,
special_plus,
special_minus,
photo, video,
toggle_10,
interrupt_game,
n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, -- numeric keys
bogus_command -- a control can be directed on this
);
pragma Ordered (Command);
type Command_set is array (Command) of Boolean;
-- The empty command set:
no_command : constant Command_set := (others => False);
-- Function Set_ .. .
-- keyboard_command_mapping : array (Multi_keys.key_value) of Command :=
-- (others => bogus_command); -- for later !!
-- mouse_command_mapping : array (PC_Mouse.Mouse_button) of Command :=
-- (others => bogus_command); -- for later !!
-- Record game commands from peripherals (keyboard, mouse) --
procedure Append_Commands (size_x,
size_y : Integer; -- screen dimensions for mouse
warp_mouse : Boolean; -- recenter mouse cursor
c : in out Game_Control.Command_set; -- commands are added to c
gx, gy : out GL.Double; -- mouse movement since last call
Keyboard : access GLUT.Devices.Keyboard := GLUT.Devices.default_Keyboard'Access;
Mouse : access GLUT.Devices.Mouse := GLUT.Devices.default_Mouse'Access);
end Game_Control;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Ada.Exceptions;
with Ada.Unchecked_Conversion;
with Interfaces;
with GNAT.SHA1;
with Torrent.Downloaders;
with Torrent.Handshakes; use Torrent.Handshakes;
with Torrent.Logs;
package body Torrent.Connections is
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
subtype Int_Buffer is Ada.Streams.Stream_Element_Array (1 .. 4);
function To_Int (Value : Natural) return Int_Buffer;
Expire_Loops : constant := 3;
-- Protection from lost of requests
function Get_Handshake (Self : Connection'Class) return Handshake_Image;
function Get_Int
(Data : Ada.Streams.Stream_Element_Array;
From : Ada.Streams.Stream_Element_Count := 0) return Natural;
function Is_Valid_Piece
(Self : Connection'Class;
Piece : Piece_Index) return Boolean;
procedure Send_Message
(Self : in out Connection'Class;
Data : Ada.Streams.Stream_Element_Array);
procedure Send_Have
(Self : in out Connection'Class;
Piece : Piece_Index);
procedure Send_Bitfield
(Self : in out Connection'Class;
Completed : Piece_Index_Array);
procedure Send_Pieces
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time);
procedure Unreserve_Intervals (Self : in out Connection'Class);
procedure Close_Connection (Self : in out Connection'Class);
----------------------
-- Close_Connection --
----------------------
procedure Close_Connection (Self : in out Connection'Class) is
begin
GNAT.Sockets.Close_Socket (Self.Socket);
Self.Closed := True;
Self.Unreserve_Intervals;
end Close_Connection;
---------------
-- Connected --
---------------
function Connected (Self : Connection'Class) return Boolean is
begin
return not Self.Closed;
end Connected;
------------------
-- Do_Handshake --
------------------
procedure Do_Handshake
(Self : in out Connection'Class;
Socket : GNAT.Sockets.Socket_Type;
Completed : Piece_Index_Array;
Inbound : Boolean)
is
Last : Ada.Streams.Stream_Element_Count;
begin
Self.Socket := Socket;
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Self.Get_Handshake,
Last => Last);
pragma Assert (Last = Handshake_Image'Last);
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout, 0.0));
Self.Initialize (Self.My_Peer_Id, Self.Peer, Self.Listener);
Self.Sent_Handshake := True;
Self.Got_Handshake := Inbound;
Self.Send_Bitfield (Completed);
Self.Last_Completed := Completed'Last;
exception
when E : others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Do_Handshake:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end Do_Handshake;
----------------
-- Downloaded --
----------------
function Downloaded (Self : in out Connection'Class) return Piece_Offset is
begin
return Result : constant Piece_Offset := Self.Downloaded do
Self.Downloaded := Self.Downloaded / 3;
end return;
end Downloaded;
-------------------
-- Get_Handshake --
-------------------
function Get_Handshake (Self : Connection'Class) return Handshake_Image is
Result : Handshake_Type;
begin
Result.Info_Hash := Self.Meta.Info_Hash;
Result.Peer_Id := Self.My_Peer_Id;
return +Result;
end Get_Handshake;
-------------
-- Get_Int --
-------------
function Get_Int
(Data : Ada.Streams.Stream_Element_Array;
From : Ada.Streams.Stream_Element_Count := 0) return Natural
is
subtype X is Natural;
begin
return
((X (Data (Data'First + From)) * 256
+ X (Data (Data'First + From + 1))) * 256
+ X (Data (Data'First + From + 2))) * 256
+ X (Data (Data'First + From + 3));
end Get_Int;
----------------
-- Initialize --
----------------
procedure Initialize
(Self : in out Connection'Class;
My_Id : SHA1;
Peer : GNAT.Sockets.Sock_Addr_Type;
Listener : Connection_State_Listener_Access)
is
begin
Self.Peer := Peer;
Self.Sent_Handshake := False;
Self.Got_Handshake := False;
Self.Closed := False;
Self.We_Choked := True;
Self.He_Choked := True;
Self.Choked_Sent := True;
Self.We_Intrested := False;
Self.He_Intrested := False;
Self.My_Peer_Id := My_Id;
Self.Last_Request := 0;
Self.Last_Completed := 0;
Self.Listener := Listener;
Self.Downloaded := 0;
Self.Current_Piece := (0, Intervals => <>);
Self.Piece_Map := (others => False);
end Initialize;
------------
-- Insert --
------------
procedure Insert
(List : in out Interval_Vectors.Vector;
Value : Interval)
is
M, N : Natural := 0;
Next : Interval := Value;
begin
if (for some X of List => X.From <= Next.From and X.To >= Next.To) then
return;
end if;
loop
M := 0;
N := 0;
for J in 1 .. List.Last_Index loop
if List (J).To + 1 = Next.From then
M := J;
exit;
elsif Next.To + 1 = List (J).From then
N := J;
exit;
end if;
end loop;
if M > 0 then
Next := (List (M).From, Next.To);
List.Swap (M, List.Last_Index);
List.Delete_Last;
elsif N > 0 then
Next := (Next.From, List (N).To);
List.Swap (N, List.Last_Index);
List.Delete_Last;
else
List.Append (Next);
exit;
end if;
end loop;
end Insert;
---------------
-- Intrested --
---------------
function Intrested (Self : Connection'Class) return Boolean is
begin
return not Self.Closed and Self.He_Intrested;
end Intrested;
--------------------
-- Is_Valid_Piece --
--------------------
function Is_Valid_Piece
(Self : Connection'Class;
Piece : Piece_Index) return Boolean is
begin
return Is_Valid_Piece (Self.Meta, Self.Storage.all, Piece);
end Is_Valid_Piece;
--------------------
-- Is_Valid_Piece --
--------------------
function Is_Valid_Piece
(Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access;
Storage : in out Torrent.Storages.Storage;
Piece : Piece_Index) return Boolean
is
Context : GNAT.SHA1.Context;
From : Ada.Streams.Stream_Element_Offset :=
Piece_Offset (Piece - 1) * Meta.Piece_Length;
Left : Ada.Streams.Stream_Element_Offset;
Data : Ada.Streams.Stream_Element_Array (1 .. Max_Interval_Size);
Value : SHA1;
begin
Storage.Start_Reading; -- Block storage
if Piece = Meta.Piece_Count then
Left := Meta.Last_Piece_Length;
else
Left := Meta.Piece_Length;
end if;
while Left > Data'Length loop
Storage.Read (From, Data);
From := From + Data'Length;
Left := Left - Data'Length;
GNAT.SHA1.Update (Context, Data);
end loop;
if Left > 0 then
Storage.Read (From, Data (1 .. Left));
GNAT.SHA1.Update (Context, Data (1 .. Left));
end if;
Value := GNAT.SHA1.Digest (Context);
Storage.Stop_Reading; -- Unblock storage
return Meta.Piece_SHA1 (Piece) = Value;
end Is_Valid_Piece;
----------
-- Peer --
----------
function Peer
(Self : Connection'Class) return GNAT.Sockets.Sock_Addr_Type is
begin
return Self.Peer;
end Peer;
-------------------
-- Send_Bitfield --
-------------------
procedure Send_Bitfield
(Self : in out Connection'Class;
Completed : Piece_Index_Array)
is
Length : constant Piece_Offset :=
Piece_Offset (Self.Piece_Count + 7) / 8;
Data : Ada.Streams.Stream_Element_Array (0 .. Length - 1) :=
(others => 0); -- Zero based
Mask : Interfaces.Unsigned_8;
begin
for X of Completed loop
Mask := Interfaces.Shift_Right (128, Natural ((X - 1) mod 8));
Data (Piece_Offset (X - 1) / 8) := Data (Piece_Offset (X - 1) / 8)
or Ada.Streams.Stream_Element (Mask);
end loop;
Self.Send_Message (To_Int (Positive (Length) + 1) & 05 & Data);
end Send_Bitfield;
---------------
-- Send_Have --
---------------
procedure Send_Have
(Self : in out Connection'Class;
Piece : Piece_Index) is
begin
Self.Send_Message
((00, 00, 00, 05, 04) & -- have
To_Int (Natural (Piece - 1)));
end Send_Have;
------------------
-- Send_Message --
------------------
procedure Send_Message
(Self : in out Connection'Class;
Data : Ada.Streams.Stream_Element_Array)
is
Last : Ada.Streams.Stream_Element_Offset;
begin
if Self.Closed then
return;
end if;
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Data,
Last => Last);
pragma Assert (Last = Data'Last);
if Data'Length <= 4 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send keepalive " & GNAT.Sockets.Image (Self.Peer)));
elsif Data (Data'First + 4) = 6 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send request "
& GNAT.Sockets.Image (Self.Peer)
& Integer'Image (Get_Int (Data, 5) + 1)
& Integer'Image (Get_Int (Data, 9))
& Integer'Image (Get_Int (Data, 13))));
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send "
& GNAT.Sockets.Image (Self.Peer)
& (Data (Data'First + 4)'Img)));
end if;
exception
when E : GNAT.Sockets.Socket_Error =>
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout,
GNAT.Sockets.Forever));
Self.Send_Message (Data);
return;
end if;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send_Message:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
end Send_Message;
-----------------
-- Send_Pieces --
-----------------
procedure Send_Pieces
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
Total_Sent : Ada.Streams.Stream_Element_Count := 0;
begin -- FIXME check if unchoked
while not Self.Requests.Is_Empty loop
declare
Last : Ada.Streams.Stream_Element_Count;
Item : constant Piece_Interval := Self.Requests.Last_Element;
Data : Ada.Streams.Stream_Element_Array
(Item.Span.From - 4 - 1 - 4 - 4 .. Item.Span.To);
begin
Self.Storage.Start_Reading;
Self.Storage.Read
(Offset => Ada.Streams.Stream_Element_Count (Item.Piece - 1)
* Self.Meta.Piece_Length
+ Ada.Streams.Stream_Element_Count (Item.Span.From),
Data => Data (Item.Span.From .. Item.Span.To));
Self.Storage.Stop_Reading;
Data (Data'First .. Data'First + 3) := -- Message length
To_Int (Data'Length - 4);
Data (Data'First + 4) := 7; -- piece
Data (Data'First + 5 .. Data'First + 8) :=
To_Int (Positive (Item.Piece) - 1);
Data (Data'First + 9 .. Data'First + 12) :=
To_Int (Natural (Item.Span.From));
exit when Self.Closed;
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout,
Limit - Ada.Calendar.Clock));
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Data,
Last => Last);
pragma Assert (Last = Data'Last);
Total_Sent := Total_Sent + Data'Length;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send piece "
& GNAT.Sockets.Image (Self.Peer)
& Piece_Count'Image (Item.Piece)
& Piece_Offset'Image (Item.Span.From)));
Self.Requests.Delete_Last;
-- FIXME Increment send statistic.
end;
end loop;
Self.Listener.Interval_Sent (Total_Sent);
exception
when E : GNAT.Sockets.Socket_Error =>
Self.Listener.Interval_Sent (Total_Sent);
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
return;
end if;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send_Pieces:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
end Send_Pieces;
-----------
-- Serve --
-----------
procedure Serve
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
procedure Check_Intrested;
procedure Send_Initial_Requests;
function Get_Handshake
(Data : Ada.Streams.Stream_Element_Array) return Boolean;
function Get_Length
(Data : Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Offset;
procedure Read_Messages
(Data : in out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Count);
procedure On_Message (Data : Ada.Streams.Stream_Element_Array);
procedure Save_Piece
(Index : Piece_Index;
Offset : Natural;
Data : Ada.Streams.Stream_Element_Array);
---------------------
-- Check_Intrested --
---------------------
procedure Check_Intrested is
begin
if not Self.We_Intrested
and then Self.Listener.We_Are_Intrested (Self.Piece_Map)
then
Self.Send_Message ((00, 00, 00, 01, 02)); -- interested
Self.We_Intrested := True;
end if;
end Check_Intrested;
-------------------
-- Get_Handshake --
-------------------
function Get_Handshake
(Data : Ada.Streams.Stream_Element_Array) return Boolean
is
function "+" is new Ada.Unchecked_Conversion
(Handshake_Image, Handshake_Type);
HS : constant Handshake_Type := +Data (1 .. Handshake_Image'Length);
begin
if HS.Length = Header'Length
and then HS.Head = Header
and then HS.Info_Hash = Self.Meta.Info_Hash
then
Self.Got_Handshake := True;
Self.Unparsed.Clear;
Self.Unparsed.Append
(Data (Handshake_Image'Length + 1 .. Data'Last));
return True;
else
return False;
end if;
end Get_Handshake;
----------------
-- Get_Length --
----------------
function Get_Length
(Data : Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Offset
is
subtype X is Ada.Streams.Stream_Element_Offset;
begin
return ((X (Data (Data'First)) * 256
+ X (Data (Data'First + 1))) * 256
+ X (Data (Data'First + 2))) * 256
+ X (Data (Data'First + 3));
end Get_Length;
----------------
-- On_Message --
----------------
procedure On_Message (Data : Ada.Streams.Stream_Element_Array) is
function Get_Int
(From : Ada.Streams.Stream_Element_Count := 0) return Natural
is (Get_Int (Data, From));
Index : Piece_Index;
begin
case Data (Data'First) is
when 0 => -- choke
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " choke"));
Self.We_Choked := True;
Self.Unreserve_Intervals;
when 1 => -- unchoke
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " unchoke"));
Self.We_Choked := False;
Send_Initial_Requests;
when 2 => -- interested
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " interested"));
Self.He_Intrested := True;
when 3 => -- not interested
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " not interested"));
Self.He_Intrested := False;
when 4 => -- have
declare
Index : constant Piece_Index :=
Piece_Index (Get_Int (1) + 1);
begin
if Index in Self.Piece_Map'Range then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer)
& " have" & (Index'Img)));
Self.Piece_Map (Index) := True;
Check_Intrested;
end if;
end;
when 5 => -- bitfield
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " bitfield"));
Index := 1;
Each_Byte :
for X of Data (Data'First + 1 .. Data'Last) loop
declare
use type Interfaces.Unsigned_8;
Byte : Interfaces.Unsigned_8 := Interfaces.Unsigned_8 (X);
begin
for J in 1 .. 8 loop
if (Byte and 16#80#) /= 0 then
Self.Piece_Map (Index) := True;
end if;
Byte := Interfaces.Shift_Left (Byte, 1);
Index := Index + 1;
exit Each_Byte when Index > Self.Piece_Count;
end loop;
end;
end loop Each_Byte;
Check_Intrested;
when 6 => -- request
declare
Next : Piece_Interval :=
(Piece => Piece_Count (Get_Int (1) + 1),
Span => (From => Piece_Offset (Get_Int (5)),
To => Piece_Offset (Get_Int (9))));
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " request"
& (Next.Piece'Img) & (Next.Span.From'Img)));
if Next.Span.To > Max_Interval_Size then
return;
else
Next.Span.To := Next.Span.From + Next.Span.To - 1;
end if;
if Next.Piece in Self.Piece_Map'Range
and then not Self.He_Choked
then
Self.Requests.Append (Next);
end if;
end;
when 7 => -- piece
declare
Index : constant Piece_Index :=
Piece_Index (Get_Int (1) + 1);
Offset : constant Natural := Get_Int (5);
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " piece"
& (Index'Img) & (Offset'Img)));
if Index in Self.Piece_Map'Range
and then Data'Length > 9
then
Save_Piece
(Index, Offset, Data (Data'First + 9 .. Data'Last));
end if;
end;
when 8 => -- cancel
declare
Next : Piece_Interval :=
(Piece => Piece_Count (Get_Int (1) + 1),
Span => (From => Piece_Offset (Get_Int (5)),
To => Piece_Offset (Get_Int (9))));
Cursor : Natural;
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " cancel"
& (Next.Piece'Img) & (Next.Span.From'Img)));
Next.Span.To := Next.Span.From + Next.Span.To - 1;
Cursor := Self.Requests.Find_Index (Next);
if Cursor /= 0 then
Self.Requests.Swap (Cursor, Self.Requests.Last_Index);
Self.Requests.Delete_Last;
end if;
end;
when others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " unkown"
& (Data (Data'First)'Img)));
end case;
end On_Message;
-------------------
-- Read_Messages --
-------------------
procedure Read_Messages
(Data : in out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Count)
is
From : Ada.Streams.Stream_Element_Count := Data'First;
Length : Ada.Streams.Stream_Element_Count;
begin
loop
exit when Data'Length - From + 1 < 4;
Length := Get_Length (Data (From .. Data'Last));
exit when Data'Length - From + 1 < 4 + Length;
From := From + 4;
if Length > 0 then
On_Message (Data (From .. From + Length - 1));
From := From + Length;
else
Self.Send_Message ((00, 00, 00, 00)); -- keepalive
end if;
end loop;
if From > Data'First then
Last := Data'Length - From + 1;
Data (1 .. Last) := Data (From .. Data'Last);
else
Last := Data'Last;
end if;
end Read_Messages;
----------------
-- Save_Piece --
----------------
procedure Save_Piece
(Index : Piece_Index;
Offset : Natural;
Data : Ada.Streams.Stream_Element_Array)
is
procedure Swap (Left, Right : Piece_Interval_Count);
----------
-- Swap --
----------
procedure Swap (Left, Right : Piece_Interval_Count) is
Request : constant Piece_Interval :=
Self.Pipelined.Request.List (Left);
Expire : constant Natural := Self.Pipelined.Expire (Left);
begin
Self.Pipelined.Request.List (Left) :=
Self.Pipelined.Request.List (Right);
Self.Pipelined.Request.List (Right) := Request;
Self.Pipelined.Expire (Left) := Self.Pipelined.Expire (Right);
Self.Pipelined.Expire (Right) := Expire;
end Swap;
Last : Boolean;
From : constant Piece_Offset := Piece_Offset (Offset);
J : Natural := 1;
begin
Self.Downloaded := Self.Downloaded + Data'Length;
Self.Storage.Write
(Offset => Ada.Streams.Stream_Element_Count (Index - 1)
* Self.Meta.Piece_Length
+ Ada.Streams.Stream_Element_Count (Offset),
Data => Data);
Self.Listener.Interval_Saved
(Index, (From, From + Data'Length - 1), Last);
if Last then
if Self.Is_Valid_Piece (Index) then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Piece completed" & (Index'Img)));
Self.Listener.Piece_Completed (Index, True);
Self.Send_Have (Index);
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Piece FAILED!" & (Index'Img)));
Self.Listener.Piece_Completed (Index, False);
end if;
end if;
if Self.Current_Piece.Intervals.Is_Empty then
Self.Listener.Reserve_Intervals
(Map => Self.Piece_Map,
Value => Self.Current_Piece);
end if;
while J <= Self.Pipelined.Length loop
if Self.Pipelined.Request.List (J).Piece = Index
and Self.Pipelined.Request.List (J).Span.From = From
then
if Self.Current_Piece.Intervals.Is_Empty then
Swap (J, Self.Pipelined.Length);
Self.Pipelined :=
(Self.Pipelined.Length - 1,
Request =>
(Self.Pipelined.Length - 1,
Self.Pipelined.Request.List
(1 .. Self.Pipelined.Length - 1)),
Expire => Self.Pipelined.Expire
(1 .. Self.Pipelined.Length - 1));
else
declare
Last : constant Interval :=
Self.Current_Piece.Intervals.Last_Element;
begin
Self.Current_Piece.Intervals.Delete_Last;
Self.Pipelined.Request.List (J) :=
(Self.Current_Piece.Piece, Last);
Self.Pipelined.Expire (J) :=
Self.Pipelined.Length * Expire_Loops;
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural (Self.Current_Piece.Piece - 1)) &
To_Int (Natural (Last.From)) &
To_Int (Natural (Last.To - Last.From + 1)));
J := J + 1;
end;
end if;
else -- Check if some request was lost
Self.Pipelined.Expire (J) := Self.Pipelined.Expire (J) - 1;
if Self.Pipelined.Expire (J) = 0 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Re-send lost request:"));
Self.Pipelined.Expire (J) :=
Self.Pipelined.Length * Expire_Loops;
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural
(Self.Pipelined.Request.List (J).Piece - 1)) &
To_Int (Natural (Self.Pipelined.Request.List (J)
.Span.From)) &
To_Int (Natural (Self.Pipelined.Request.List (J)
.Span.To
- Self.Pipelined.Request.List (J)
.Span.From + 1)));
end if;
J := J + 1;
end if;
end loop;
end Save_Piece;
---------------------------
-- Send_Initial_Requests --
---------------------------
procedure Send_Initial_Requests is
Length : Piece_Interval_Count;
begin
if Self.Current_Piece.Intervals.Is_Empty then
Self.Listener.Reserve_Intervals
(Map => Self.Piece_Map,
Value => Self.Current_Piece);
end if;
Length := Piece_Interval_Count'Min
(Piece_Interval_Count'Last,
Self.Current_Piece.Intervals.Last_Index);
Self.Pipelined :=
(Length => Length,
Expire => (1 .. Length => Length * Expire_Loops),
Request => (Length, others => <>));
for J in 1 .. Length loop
declare
Last : constant Interval :=
Self.Current_Piece.Intervals.Last_Element;
Index : constant Piece_Index := Self.Current_Piece.Piece;
Offset : constant Piece_Offset := Last.From;
Length : constant Piece_Offset := Last.To - Offset + 1;
begin
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural (Index - 1)) &
To_Int (Natural (Offset)) &
To_Int (Natural (Length)));
Self.Pipelined.Request.List (J) :=
(Piece => Self.Current_Piece.Piece,
Span => (Offset, Last.To));
Self.Current_Piece.Intervals.Delete_Last;
end;
end loop;
end Send_Initial_Requests;
Completed : constant Piece_Index_Array := Self.Downloader.Completed;
Last : Ada.Streams.Stream_Element_Count := Self.Unparsed.Length;
Data : Ada.Streams.Stream_Element_Array (1 .. Max_Interval_Size + 20);
begin
if Self.Closed then
return;
end if;
if not Self.Choked_Sent then
Self.Choked_Sent := True;
if Self.He_Choked then
Self.Send_Message ((00, 00, 00, 01, 00)); -- choke
Self.Requests.Clear;
else
Self.Send_Message ((00, 00, 00, 01, 01)); -- unchoke
end if;
end if;
for J in Self.Last_Completed + 1 .. Completed'Last loop
Self.Send_Have (Completed (J));
end loop;
Self.Last_Completed := Completed'Last;
Data (1 .. Last) := Self.Unparsed.To_Stream_Element_Array;
Self.Unparsed.Clear;
loop
declare
Read : Ada.Streams.Stream_Element_Count;
begin
if Self.Closed then
return;
end if;
GNAT.Sockets.Receive_Socket
(Socket => Self.Socket,
Item => Data (Last + 1 .. Data'Last),
Last => Read);
if Read = Last then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Closed on Read:" & GNAT.Sockets.Image (Self.Peer)));
Self.Close_Connection;
return;
else
Last := Read;
end if;
exception
when E : GNAT.Sockets.Socket_Error =>
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
null; -- Timeout on Read
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Read:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end if;
end;
if Self.Got_Handshake then
Read_Messages (Data (1 .. Last), Last);
elsif Last >= Handshake_Image'Length
and then Get_Handshake (Data (1 .. Last))
then
Data (1 .. Last - Handshake_Image'Length) :=
Data (Handshake_Image'Last + 1 .. Last);
Last := Last - Handshake_Image'Length;
Read_Messages (Data (1 .. Last), Last);
end if;
Self.Send_Pieces (Limit);
exit when Ada.Calendar.Clock > Limit;
end loop;
if Last > 0 then
Self.Unparsed.Append (Data (1 .. Last));
end if;
exception
when E : others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Serve:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end Serve;
---------------
-- Serve_All --
---------------
procedure Serve_All
(Selector : GNAT.Sockets.Selector_Type;
Vector : in out Connection_Vectors.Vector;
Except : Connection_Access_Array;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
Now : Ada.Calendar.Time;
Status : GNAT.Sockets.Selector_Status;
R_Set : GNAT.Sockets.Socket_Set_Type;
W_Set : GNAT.Sockets.Socket_Set_Type;
begin
loop
for C of Vector loop
if C.Connected
and then not (for some X of Except => X = C)
then
GNAT.Sockets.Set (R_Set, C.Socket);
end if;
end loop;
Now := Ada.Calendar.Clock;
if GNAT.Sockets.Is_Empty (R_Set) or Now >= Limit then
return;
end if;
GNAT.Sockets.Check_Selector
(Selector => Selector,
R_Socket_Set => R_Set,
W_Socket_Set => W_Set,
Status => Status,
Timeout => Limit - Now);
if Status in GNAT.Sockets.Completed then
for C of Vector loop
if C.Connected
and then GNAT.Sockets.Is_Set (R_Set, C.Socket)
then
GNAT.Sockets.Clear (R_Set, C.Socket);
C.Serve (Now);
end if;
end loop;
end if;
GNAT.Sockets.Empty (R_Set);
end loop;
end Serve_All;
------------------
-- Serve_Needed --
------------------
function Serve_Needed (Self : Connection'Class) return Boolean is
begin
return not Self.Choked_Sent;
end Serve_Needed;
----------------
-- Set_Choked --
----------------
procedure Set_Choked (Self : in out Connection'Class; Value : Boolean) is
begin
if Self.He_Choked /= Value then
Self.He_Choked := Value;
Self.Choked_Sent := not Self.Choked_Sent;
end if;
end Set_Choked;
-------------
-- To_Int --
-------------
function To_Int (Value : Natural) return Int_Buffer is
use type Interfaces.Unsigned_32;
Result : Int_Buffer;
Next : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Value);
begin
for X of reverse Result loop
X := Ada.Streams.Stream_Element (Next mod 256);
Next := Interfaces.Shift_Right (Next, 8);
end loop;
return Result;
end To_Int;
-------------------------
-- Unreserve_Intervals --
-------------------------
procedure Unreserve_Intervals (Self : in out Connection'Class) is
Back : Piece_Interval_Array
(1 .. Self.Current_Piece.Intervals.Last_Index);
begin
for J in Back'Range loop
Back (J).Piece := Self.Current_Piece.Piece;
Back (J).Span := Self.Current_Piece.Intervals (J);
end loop;
Self.Listener.Unreserve_Intervals (Self.Pipelined.Request.List & Back);
Self.Current_Piece := (0, Interval_Vectors.Empty_Vector);
Self.Pipelined := (0, Request => (0, others => <>), Expire => <>);
end Unreserve_Intervals;
end Torrent.Connections;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- You can use, modify, distribute this table freely.
------------------------------------------------------------------------------
with Matreshka.Internals.Strings.Configuration;
with Matreshka.Internals.Text_Codecs.SHIFTJIS.Tables;
with Matreshka.Internals.Utf16;
package body Matreshka.Internals.Text_Codecs.SHIFTJIS is
use Matreshka.Internals.Strings.Configuration;
Accept_Single_State : constant SHIFTJIS_DFA_State := 0;
Accept_Double_State : constant SHIFTJIS_DFA_State := 1;
Reject_State : constant SHIFTJIS_DFA_State := 2;
Transition : constant
array (SHIFTJIS_DFA_State range 0 .. 31) of SHIFTJIS_DFA_State
:= (0, 0, 3, 3, 2, 2, 2, 2,
0, 0, 3, 3, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2,
1, 2, 1, 2, 1, 2, 2, 2);
-------------------
-- Decode_Append --
-------------------
overriding procedure Decode_Append
(Self : in out SHIFTJIS_Decoder;
Data : Ada.Streams.Stream_Element_Array;
String : in out Matreshka.Internals.Strings.Shared_String_Access)
is
use type Matreshka.Internals.Unicode.Code_Point;
use type Matreshka.Internals.Utf16.Utf16_String_Index;
Current_State : SHIFTJIS_DFA_State := Self.State;
Current_First : Ada.Streams.Stream_Element := Self.First;
Current_Code : Matreshka.Internals.Unicode.Code_Unit_32;
begin
Matreshka.Internals.Strings.Mutate (String, String.Unused + Data'Length);
for J in Data'Range loop
declare
M : constant SHIFTJIS_Meta_Class := Tables.Meta_Class (Data (J));
begin
Current_State :=
Transition (Current_State * 8 + SHIFTJIS_DFA_State (M));
if Current_State = Accept_Single_State then
Self.Unchecked_Append
(Self, String, Tables.Decode_Single (Data (J)));
elsif Current_State = Accept_Double_State then
Current_Code := Tables.Decode_Double (Current_First) (Data (J));
if Current_Code = 16#0000# then
Current_State := Reject_State;
elsif Current_Code in Tables.Expansion'Range then
Self.Unchecked_Append
(Self, String, Tables.Expansion (Current_Code).First);
Self.Unchecked_Append
(Self, String, Tables.Expansion (Current_Code).Second);
else
Self.Unchecked_Append (Self, String, Current_Code);
end if;
else
Current_First := Data (J);
end if;
end;
end loop;
Self.State := Current_State;
Self.First := Current_First;
String_Handler.Fill_Null_Terminator (String);
end Decode_Append;
-------------
-- Decoder --
-------------
function Decoder (Mode : Decoder_Mode) return Abstract_Decoder'Class is
begin
case Mode is
when Raw =>
return
SHIFTJIS_Decoder'
(Skip_LF => False,
Unchecked_Append => Unchecked_Append_Raw'Access,
State => Accept_Single_State,
First => 0);
when XML_1_0 =>
return
SHIFTJIS_Decoder'
(Skip_LF => False,
Unchecked_Append => Unchecked_Append_XML10'Access,
State => Accept_Single_State,
First => 0);
when XML_1_1 =>
return
SHIFTJIS_Decoder'
(Skip_LF => False,
Unchecked_Append => Unchecked_Append_XML11'Access,
State => Accept_Single_State,
First => 0);
end case;
end Decoder;
--------------
-- Is_Error --
--------------
overriding function Is_Error (Self : SHIFTJIS_Decoder) return Boolean is
begin
return Self.State = Reject_State;
end Is_Error;
-------------------
-- Is_Mailformed --
-------------------
overriding function Is_Mailformed
(Self : SHIFTJIS_Decoder) return Boolean is
begin
return Self.State not in Accept_Single_State .. Accept_Double_State;
end Is_Mailformed;
end Matreshka.Internals.Text_Codecs.SHIFTJIS;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
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 euler33 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;
function max2_0(a : in Integer; b : in Integer) return Integer is
begin
if a > b
then
return a;
else
return b;
end if;
end;
function min2_0(a : in Integer; b : in Integer) return Integer is
begin
if a < b
then
return a;
else
return b;
end if;
end;
function pgcd(a : in Integer; b : in Integer) return Integer is
reste : Integer;
d : Integer;
c : Integer;
begin
c := min2_0(a, b);
d := max2_0(a, b);
reste := d rem c;
if reste = 0
then
return c;
else
return pgcd(c, reste);
end if;
end;
top : Integer;
p : Integer;
bottom : Integer;
b : Integer;
a : Integer;
begin
top := 1;
bottom := 1;
for i in integer range 1..9 loop
for j in integer range 1..9 loop
for k in integer range 1..9 loop
if i /= j and then j /= k
then
a := i * 10 + j;
b := j * 10 + k;
if a * k = i * b
then
PInt(a);
PString(new char_array'( To_C("/")));
PInt(b);
PString(new char_array'( To_C("" & Character'Val(10))));
top := top * a;
bottom := bottom * b;
end if;
end if;
end loop;
end loop;
end loop;
PInt(top);
PString(new char_array'( To_C("/")));
PInt(bottom);
PString(new char_array'( To_C("" & Character'Val(10))));
p := pgcd(top, bottom);
PString(new char_array'( To_C("pgcd=")));
PInt(p);
PString(new char_array'( To_C("" & Character'Val(10))));
PInt(bottom / p);
PString(new char_array'( To_C("" & Character'Val(10))));
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Web_Services.SOAP.Constants;
with Web_Services.SOAP.Headers.Decoders.Registry;
with Web_Services.SOAP.Payloads.Decoders.Registry;
with Web_Services.SOAP.Payloads.Faults.Simple;
package body Web_Services.SOAP.Message_Decoders is
use Web_Services.SOAP.Constants;
use type League.Strings.Universal_String;
procedure Free is
new Ada.Unchecked_Deallocation
(Web_Services.SOAP.Payloads.Decoders.SOAP_Payload_Decoder'Class,
Web_Services.SOAP.Payloads.Decoders.SOAP_Payload_Decoder_Access);
procedure Free is
new Ada.Unchecked_Deallocation
(Web_Services.SOAP.Headers.Decoders.SOAP_Header_Decoder'Class,
Web_Services.SOAP.Headers.Decoders.SOAP_Header_Decoder_Access);
procedure Set_Sender_Fault
(Self : in out SOAP_Message_Decoder'Class;
Text : League.Strings.Universal_String;
Detail : League.Strings.Universal_String
:= League.Strings.Empty_Universal_String);
-- Sets error state with specified diagnosis and creates env:Sender fault
-- message.
procedure Set_Must_Understand_Error
(Self : in out SOAP_Message_Decoder'Class;
Diagnosis : League.Strings.Universal_String);
-- Sets error state with specified diagnosis and creates env:MustUnderstand
-- fault message.
procedure Set_Version_Mismatch_Fault
(Self : in out SOAP_Message_Decoder'Class;
Diagnosis : League.Strings.Universal_String);
-- Sets error state with specified diagnosis and creates
-- env:VersionMismatch fault message.
procedure Check_No_SOAP_Encoding_Style_Attribute
(Self : in out SOAP_Message_Decoder'Class;
Local_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean);
-- Checks that encodingStyle attribute is not present in the given set of
-- attributes.
----------------
-- Characters --
----------------
overriding procedure Characters
(Self : in out SOAP_Message_Decoder;
Text : League.Strings.Universal_String;
Success : in out Boolean) is
begin
if Self.State = Header_Element and then Self.Depth /= 0 then
Self.Header_Decoder.Characters (Text, Success);
if not Success then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Message header decoder reports error"));
return;
end if;
elsif Self.State = Body_Element and then Self.Depth /= 0 then
Self.Payload_Decoder.Characters (Text, Success);
if not Success then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Message body decoder reports error"));
return;
end if;
end if;
end Characters;
--------------------------------------------
-- Check_No_SOAP_Encoding_Style_Attribute --
--------------------------------------------
procedure Check_No_SOAP_Encoding_Style_Attribute
(Self : in out SOAP_Message_Decoder'Class;
Local_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean) is
begin
for J in 1 .. Attributes.Length loop
if Attributes.Namespace_URI (J) = SOAP_Envelope_URI
and Attributes.Local_Name (J) = SOAP_Encoding_Style_Name
then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Incorrect SOAP Body element serialization"),
"SOAP "
& Local_Name
& " must not have encodingStyle attribute information item.");
Success := False;
return;
end if;
end loop;
end Check_No_SOAP_Encoding_Style_Attribute;
-----------------
-- End_Element --
-----------------
overriding procedure End_Element
(Self : in out SOAP_Message_Decoder;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Success : in out Boolean) is
begin
case Self.State is
when Initial =>
-- Must never be happen.
raise Program_Error;
when Header_Ignore | Body_Ignore =>
-- Decrement depth of ignore element counter.
Self.Depth := Self.Depth - 1;
if Self.Depth = 0 then
-- Change state of decoder on leave of root element.
if Self.State = Header_Ignore then
Self.State := SOAP_Header;
elsif Self.State = Body_Ignore then
Self.State := SOAP_Body;
end if;
end if;
when SOAP_Envelope =>
Self.State := Initial;
when SOAP_Header =>
Self.State := SOAP_Envelope;
when SOAP_Body =>
Self.State := SOAP_Envelope;
when Header_Element =>
-- Decrement depth of nesting XML elements in Header element.
Self.Depth := Self.Depth - 1;
-- Redirect processing to decoder.
Self.Header_Decoder.End_Element
(Namespace_URI, Local_Name, Success);
-- Obtain decoded data.
if Self.Depth = 0 then
declare
Header : constant
Web_Services.SOAP.Headers.SOAP_Header_Access
:= Self.Header_Decoder.Header;
begin
Self.Message.Headers.Insert (Header);
Free (Self.Header_Decoder);
Self.State := SOAP_Header;
end;
end if;
when Body_Element =>
-- Decrement depth of nesting XML elements in Body element.
Self.Depth := Self.Depth - 1;
-- Redirect processing to decoder.
Self.Payload_Decoder.End_Element
(Namespace_URI, Local_Name, Success);
if not Success then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Message body decoder reports error"));
return;
end if;
-- Obtain decoded data.
if Self.Depth = 0 then
Self.Message.Payload := Self.Payload_Decoder.Payload;
Self.Message.Namespace_URI := Namespace_URI;
Self.Message.Local_Name := Local_Name;
Free (Self.Payload_Decoder);
Self.State := SOAP_Body;
end if;
end case;
end End_Element;
-----------
-- Error --
-----------
overriding procedure Error
(Self : in out SOAP_Message_Decoder;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception;
Success : in out Boolean) is
begin
Self.Fatal_Error (Occurrence);
Success := False;
end Error;
------------------
-- Error_String --
------------------
overriding function Error_String
(Self : SOAP_Message_Decoder) return League.Strings.Universal_String
is
pragma Unreferenced (Self);
-- This parameter is not used, but defined by profile of overloaded
-- subprogram.
begin
return
League.Strings.To_Universal_String
("Unknown error in SOAP message decoder");
end Error_String;
-----------------
-- Fatal_Error --
-----------------
overriding procedure Fatal_Error
(Self : in out SOAP_Message_Decoder;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception) is
begin
-- Set error message only when there is no previous error message was
-- set.
if Self.Success then
Self.Set_Sender_Fault ("XML error: " & Occurrence.Message);
end if;
end Fatal_Error;
-------------
-- Message --
-------------
function Message
(Self : SOAP_Message_Decoder'Class)
return Web_Services.SOAP.Messages.SOAP_Message_Access is
begin
return Self.Message;
end Message;
----------------------------
-- Processing_Instruction --
----------------------------
overriding procedure Processing_Instruction
(Self : in out SOAP_Message_Decoder;
Target : League.Strings.Universal_String;
Data : League.Strings.Universal_String;
Success : in out Boolean)
is
pragma Unreferenced (Target);
pragma Unreferenced (Data);
-- These parameters is not used, but defined by profile of overloaded
-- subprogram.
begin
-- [SOAP12] 5. SOAP Message Construct
--
-- "SOAP messages sent by initial SOAP senders MUST NOT contain
-- processing instruction information items. SOAP intermediaries MUST
-- NOT insert processing instruction information items in SOAP messages
-- they relay. SOAP receivers receiving a SOAP message containing a
-- processing instruction information item SHOULD generate a SOAP fault
-- with the Value of Code set to "env:Sender"."
if Self.Mode = Strict then
-- This assertion is checked in strict mode only; otherwise Test:T26
-- testcase of SOAP Conformance Testsuite is failed.
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("SOAP message must not contain processing instruction"));
Success := False;
end if;
end Processing_Instruction;
-------------------------------
-- Set_Must_Understand_Error --
-------------------------------
procedure Set_Must_Understand_Error
(Self : in out SOAP_Message_Decoder'Class;
Diagnosis : League.Strings.Universal_String) is
begin
-- Deallocate decoded SOAP message if any.
Web_Services.SOAP.Messages.Free (Self.Message);
Free (Self.Payload_Decoder);
-- Set error state.
Self.Success := False;
-- Create env:MustUnderstand fault reply.
Self.Message :=
new Web_Services.SOAP.Messages.SOAP_Message'
(Action => <>,
Namespace_URI => <>,
Local_Name => <>,
Output => null,
Headers => <>,
Payload =>
Web_Services.SOAP.Payloads.Faults.Simple
.Create_Must_Understand_Fault (XML_EN_US_Code, Diagnosis));
end Set_Must_Understand_Error;
----------------------
-- Set_Sender_Fault --
----------------------
procedure Set_Sender_Fault
(Self : in out SOAP_Message_Decoder'Class;
Text : League.Strings.Universal_String;
Detail : League.Strings.Universal_String
:= League.Strings.Empty_Universal_String) is
begin
-- Deallocate decoded SOAP message if any.
Web_Services.SOAP.Messages.Free (Self.Message);
Free (Self.Payload_Decoder);
-- Set error state and diagnosis.
Self.Success := False;
-- Create env:Sender fault reply.
Self.Message :=
new Web_Services.SOAP.Messages.SOAP_Message'
(Action => <>,
Namespace_URI => <>,
Local_Name => <>,
Output => null,
Headers => <>,
Payload =>
Web_Services.SOAP.Payloads.Faults.Simple.Create_Sender_Fault
(XML_EN_US_Code, Text, Detail));
end Set_Sender_Fault;
--------------------------------
-- Set_Version_Mismatch_Fault --
--------------------------------
procedure Set_Version_Mismatch_Fault
(Self : in out SOAP_Message_Decoder'Class;
Diagnosis : League.Strings.Universal_String) is
begin
-- Deallocate decoded SOAP message if any.
Web_Services.SOAP.Messages.Free (Self.Message);
Free (Self.Payload_Decoder);
-- Set error state and diagnosis.
Self.Success := False;
-- Create env:VersionMismatch fault reply.
Self.Message :=
new Web_Services.SOAP.Messages.SOAP_Message'
(Action => <>,
Namespace_URI => <>,
Local_Name => <>,
Output => null,
Headers => <>,
Payload =>
Web_Services.SOAP.Payloads.Faults.Simple
.Create_Version_Mismatch_Fault (XML_EN_US_Code, Diagnosis));
end Set_Version_Mismatch_Fault;
--------------------
-- Start_Document --
--------------------
overriding procedure Start_Document
(Self : in out SOAP_Message_Decoder;
Success : in out Boolean)
is
pragma Unreferenced (Success);
-- This parameter is not used, but defined by profile of overloaded
-- subprogram.
begin
Self.Message := new Web_Services.SOAP.Messages.SOAP_Message;
end Start_Document;
---------------
-- Start_DTD --
---------------
overriding procedure Start_DTD
(Self : in out SOAP_Message_Decoder;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Success : in out Boolean)
is
pragma Unreferenced (Name);
pragma Unreferenced (Public_Id);
pragma Unreferenced (System_Id);
-- These parameters are not used but defined by profile of overrided
-- subprogram.
begin
-- [SOAP12P1] 5. SOAP Message Construct
--
-- "The XML infoset of a SOAP message MUST NOT contain a document type
-- declaration information item."
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("DTD are not supported by SOAP 1.2"));
Success := False;
end Start_DTD;
-------------------
-- Start_Element --
-------------------
overriding procedure Start_Element
(Self : in out SOAP_Message_Decoder;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean)
is
use type Web_Services.SOAP.Payloads.Decoders.SOAP_Payload_Decoder_Access;
use type Web_Services.SOAP.Headers.Decoders.SOAP_Header_Decoder_Access;
begin
case Self.State is
when Initial =>
if Namespace_URI = SOAP_Envelope_URI then
if Local_Name = SOAP_Envelope_Name then
-- The encodingStyle attribute MUST NOT appear in SOAP
-- Envelope element.
Self.Check_No_SOAP_Encoding_Style_Attribute
(Local_Name, Attributes, Success);
if not Success then
return;
end if;
end if;
elsif Local_Name = SOAP_Envelope_Name then
-- Root element has correct name, but unknown namespace; report
-- env:VersionMismatch fault.
Self.Set_Version_Mismatch_Fault
(League.Strings.To_Universal_String ("Wrong Version"));
Success := False;
return;
end if;
Self.State := SOAP_Envelope;
when Header_Ignore | Body_Ignore =>
-- Each children element of unknown element increments element
-- ignore counter to proper handling of arbitrary depth of
-- elements.
Self.Depth := Self.Depth + 1;
when SOAP_Envelope =>
if Namespace_URI = SOAP_Envelope_URI then
if Local_Name = SOAP_Header_Name then
-- "Header" element is processed now.
Self.State := SOAP_Header;
elsif Local_Name = SOAP_Body_Name then
-- The encodingStyle attribute MUST NOT appear in SOAP Body
-- element.
Self.Check_No_SOAP_Encoding_Style_Attribute
(Local_Name, Attributes, Success);
if not Success then
return;
end if;
-- Switch state to process content of SOAP Body element.
Self.State := SOAP_Body;
else
Self.Set_Sender_Fault
("Unexpected element {" & Namespace_URI & "}" & Local_Name);
end if;
else
Self.Set_Sender_Fault
("Unexpected element {" & Namespace_URI & "}" & Local_Name);
end if;
when SOAP_Header =>
-- SOAP Header element has been processed, currect element is its
-- child. Appropriate decoder must be created to continue
-- processing.
Self.Header_Decoder :=
Web_Services.SOAP.Headers.Decoders.Registry.Resolve
(Namespace_URI);
-- [SOAP1.2] 5.2.3 SOAP mustUnderstand Attribute
--
-- "Omitting this attribute information item is defined as being
-- semantically equivalent to including it with a value of
-- "false".
--
-- SOAP senders SHOULD NOT generate, but SOAP receivers MUST
-- accept, the SOAP mustUnderstand attribute information item with
-- a value of "false" or "0".
--
-- If generating a SOAP mustUnderstand attribute information item,
-- a SOAP sender SHOULD use the canonical representation "true" of
-- the attribute value (see XML Schema [XML Schema Part 2]). A
-- SOAP receiver MUST accept any valid lexical representation of
-- the attribute value.
--
-- If relaying the message, a SOAP intermediary MAY substitute
-- "true" for the value "1", or "false" for "0". In addition, a
-- SOAP intermediary MAY omit a SOAP mustUnderstand attribute
-- information item if its value is "false" (see 2.7 Relaying SOAP
-- Messages).
--
-- A SOAP sender generating a SOAP message SHOULD use the
-- mustUnderstand attribute information item only on SOAP header
-- blocks. A SOAP receiver MUST ignore this attribute information
-- item if it appears on descendants of a SOAP header block or on
-- a SOAP body child element information item (or its
-- descendents)."
-- XXX Correct processing of literal value of env:mustUnderstand
-- attribute must be implemented.
if Self.Header_Decoder = null
and then Attributes.Is_Specified
(SOAP_Envelope_URI, SOAP_Must_Understand_Name)
and then Attributes.Value
(SOAP_Envelope_URI, SOAP_Must_Understand_Name)
= SOAP_True_Literal
then
-- [SOAP1.2] 5.4.8 SOAP mustUnderstand Faults
--
-- "When a SOAP node generates a fault with a Value of Code set
-- to "env:MustUnderstand", it SHOULD provide NotUnderstood
-- SOAP header blocks in the generated fault message. The
-- NotUnderstood SOAP header blocks, as described below, detail
-- the XML qualified names (per XML Schema [XML Schema Part 2])
-- of the particular SOAP header block(s) which were not
-- understood."
-- XXX Generation of NotUnderstood SOAP header blocks is not
-- implemented yet.
Self.Set_Must_Understand_Error
(League.Strings.To_Universal_String
("One or more mandatory SOAP header blocks not"
& " understood"));
Success := False;
elsif Self.Header_Decoder /= null then
-- Decoder has been found, use it to decode header.
Self.State := Header_Element;
Self.Depth := 1;
-- Redirect handling of current XML element to decoder.
Self.Header_Decoder.Start_Element
(Namespace_URI, Local_Name, Attributes, Success);
else
Self.State := Header_Ignore;
Self.Depth := 1;
end if;
when Header_Element =>
-- Redirect handling of current XML element to decoder.
Self.Header_Decoder.Start_Element
(Namespace_URI, Local_Name, Attributes, Success);
-- Increment depth of nested XML elements in Body element.
Self.Depth := Self.Depth + 1;
when SOAP_Body =>
-- SOAP Body element has been processed, current element is its
-- child. Appropriate decoder must be created to continue
-- processing.
Self.Payload_Decoder :=
Web_Services.SOAP.Payloads.Decoders.Registry.Resolve
(Namespace_URI);
if Self.Payload_Decoder = null then
Self.Set_Sender_Fault
("Unknown namespace URI '"
& Namespace_URI
& "' of the child element of SOAP:Body");
Success := False;
return;
end if;
-- [SOAP1.2P1] 5.1.1 SOAP encodingStyle Attribute
--
-- "The encodingStyle attribute information item MAY appear on the
-- following:"
--
-- ...
--
-- "A child element information item of the SOAP Body element
-- information item (see 5.3.1 SOAP Body child Element) if that
-- child is not a SOAP Fault element information item (see 5.4
-- SOAP Fault)."
-- XXX This check is not implemented yet.
-- Self.Check_No_SOAP_Encoding_Style_Attribute
-- (Local_Name, Attributes, Success);
--
-- if not Success then
-- return;
-- end if;
Self.State := Body_Element;
Self.Depth := 1;
-- Redirect handling of current XML element to decoder.
Self.Payload_Decoder.Start_Element
(Namespace_URI, Local_Name, Attributes, Success);
if not Success then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Message body decoder reports error"));
return;
end if;
when Body_Element =>
-- Redirect handling of current XML element to decoder.
Self.Payload_Decoder.Start_Element
(Namespace_URI, Local_Name, Attributes, Success);
if not Success then
Self.Set_Sender_Fault
(League.Strings.To_Universal_String
("Message body decoder reports error"));
return;
end if;
-- Increment depth of nested XML elements in Body element.
Self.Depth := Self.Depth + 1;
end case;
end Start_Element;
-------------
-- Success --
-------------
function Success (Self : SOAP_Message_Decoder'Class) return Boolean is
begin
return Self.Success;
end Success;
end Web_Services.SOAP.Message_Decoders;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package implements PowerPC architecture specific support for the GNAT
-- Ravenscar run time.
with System.Machine_Code;
package body System.BB.CPU_Specific is
type Exception_Handler_Array is array (Vector_Id) of Address;
procedure GNAT_Error_Handler (Trap : Vector_Id);
Exception_Handlers : Exception_Handler_Array :=
(others => GNAT_Error_Handler'Address);
pragma Export (C, Exception_Handlers, "__gnat_powerpc_exception_handlers");
-------------------------------
-- Finish_Initialize_Context --
-------------------------------
procedure Finish_Initialize_Context
(Buffer : not null access Context_Buffer)
is
use System.Machine_Code;
use Interfaces;
Spefpscr : Unsigned_32;
begin
-- Copy the current value of SPEFPSCR
Asm ("mfspr %0, 512",
Outputs => Unsigned_32'Asm_Output ("=r", Spefpscr),
Volatile => True);
Buffer.SPEFPSCR := Spefpscr;
end Finish_Initialize_Context;
--------------------
-- Initialize_CPU --
--------------------
procedure Initialize_CPU is
use System.Machine_Code;
use Interfaces;
Addr : Address;
-- Interrupt vector table prefix
DIE : constant Unsigned_32 := 16#0400_0000#;
-- Decrementer interrupt enable
begin
-- Set TCR
Asm ("mtspr 340, %0",
Inputs => Unsigned_32'Asm_Input ("r", DIE),
Volatile => True);
-- Set IVPR
Asm ("lis %0,handler_0@h",
Outputs => Address'Asm_Output ("=r", Addr),
Volatile => True);
Asm ("mtspr 63, %0",
Inputs => Address'Asm_Input ("r", Addr),
Volatile => True);
-- Set IVOR10 (decrementer)
Asm ("li %0,handler_10@l",
Outputs => Address'Asm_Output ("=r", Addr),
Volatile => True);
Asm ("mtspr 410, %0",
Inputs => Address'Asm_Input ("r", Addr),
Volatile => True);
-- Set IVOR4 (External interrupt)
Asm ("li %0,handler_4@l",
Outputs => Address'Asm_Output ("=r", Addr),
Volatile => True);
Asm ("mtspr 404, %0",
Inputs => Address'Asm_Input ("r", Addr),
Volatile => True);
-- Set IVOR33 (spe data interrupt)
Asm ("li %0,handler_33@l",
Outputs => Address'Asm_Output ("=r", Addr),
Volatile => True);
Asm ("mtspr 529, %0",
Inputs => Address'Asm_Input ("r", Addr),
Volatile => True);
end Initialize_CPU;
---------------------
-- Install_Handler --
---------------------
procedure Install_Exception_Handler
(Service_Routine : System.Address;
Vector : Vector_Id)
is
begin
Exception_Handlers (Vector) := Service_Routine;
end Install_Exception_Handler;
------------------------
-- GNAT_Error_Handler --
------------------------
procedure GNAT_Error_Handler (Trap : Vector_Id) is
begin
case Trap is
when Floatting_Point_Data_Excp =>
raise Constraint_Error with "floating point exception";
when others =>
raise Program_Error with "unhandled trap";
end case;
end GNAT_Error_Handler;
----------------------------
-- Install_Error_Handlers --
----------------------------
procedure Install_Error_Handlers is
begin
Install_Exception_Handler (GNAT_Error_Handler'Address,
Floatting_Point_Data_Excp);
end Install_Error_Handlers;
end System.BB.CPU_Specific;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Finalization;
private with Linted.GCC_Atomics;
private with Linted.Tagged_Accessors;
package Linted.Wait_Lists with
Spark_Mode,
Abstract_State => (State with External) is
pragma Elaborate_Body;
type Wait_List is limited private;
procedure Wait (W : in out Wait_List) with
Global => (In_Out => State),
Depends => ((State, W) => (State, W));
procedure Signal (W : in out Wait_List) with
Global => (In_Out => State),
Depends => ((State, W) => (State, W));
private
pragma SPARK_Mode (Off);
type Node;
-- Should be 64 but we can only speciy up to 7
Cache_Line_Size : constant := 64;
type Waiter_Count is range -2**31 .. 1 with
Default_Value => 0;
type Node_Access is access all Node;
package Tags is new Tagged_Accessors (Node, Node_Access);
package Node_Access_Atomics is new GCC_Atomics.Atomic_Ts
(Tags.Tagged_Access);
package Waiter_Atomics is new GCC_Atomics.Atomic_Ts (Waiter_Count);
type Atomic_Node_Access is record
Value : Node_Access_Atomics.Atomic;
end record;
for Atomic_Node_Access'Alignment use Cache_Line_Size;
type Atomic_Waiter_Count is record
Value : Waiter_Atomics.Atomic;
end record;
for Atomic_Waiter_Count'Alignment use Cache_Line_Size;
type Queue is new Ada.Finalization.Limited_Controlled with record
Head : Atomic_Node_Access;
Tail : Atomic_Node_Access;
end record;
overriding procedure Initialize (Q : in out Queue) with
Global => null,
Depends => (Q => Q);
type Wait_List is record
Q : Queue;
Waiter_Count : Atomic_Waiter_Count;
end record;
for Wait_List'Alignment use Cache_Line_Size;
end Linted.Wait_Lists;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package Port_Specification.Buildsheet is
-- This generates the port buildsheet from the specification based on given parameters
-- The output_file must be blank (stdout) or a file to (over)write a file with output.
procedure generator
(specs : Portspecs;
ravensrcdir : String;
output_file : String);
-- This produces a skeleton of the mandatory specification elements.
procedure print_specification_template (dump_to_file : Boolean);
private
-- Takes a string and appends enough tabs to align to column 24
-- If payload is empty, it returns 3 tabs
-- If payload > 24 columns, return payload without modification
function align24 (payload : String) return String;
-- Takes a string and appends enough tabs to align to column 40
-- If payload is empty, it returns 5 tabs
-- If payload > 40 columns, return payload without modification
function align40 (payload : String) return String;
end Port_Specification.Buildsheet;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Ada_2012;
package body Adventofcode.File_Line_Readers is
use Ada.Text_IO;
----------------
-- Read_Lines --
----------------
function Read_Lines (From_Path : String) return File_Reader is
begin
return Ret : File_Reader do
Ada.Text_IO.Open (Ret.F, In_File, From_Path);
end return;
end Read_Lines;
------------------
-- First_Cursor --
------------------
function First_Cursor (Cont : File_Reader) return Cursor is
begin
return Cursor'(0);
end First_Cursor;
-------------
-- Advance --
-------------
function Advance (Cont : File_Reader; Position : Cursor) return Cursor is
begin
return Cursor'(0);
end Advance;
------------------------
-- Cursor_Has_Element --
------------------------
function Cursor_Has_Element
(Cont : File_Reader; Position : Cursor) return Boolean
is
begin
return not End_Of_File (Cont.F);
end Cursor_Has_Element;
-----------------
-- Get_Element --
-----------------
function Get_Element (Cont : File_Reader; Position : Cursor) return String
is
begin
return Get_Line (Cont.F);
end Get_Element;
overriding procedure Finalize (Object : in out File_Reader) is
begin
Close (Object.F);
end;
end Adventofcode.File_Line_Readers;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Sodium.Functions; use Sodium.Functions;
with Ada.Text_IO; use Ada.Text_IO;
procedure Demo_Ada
is
FF : constant Character := Character'Val (255);
n1 : String (1 .. 3) := (others => ASCII.NUL);
n2 : String (1 .. 3) := (others => FF);
n3 : String (1 .. 3) := (3 => Character'Val (254), others => ASCII.NUL);
n4 : String (1 .. 3) := (3 => FF, others => ASCII.NUL);
n5 : String (1 .. 3) := (1 => Character'Val (5), 2 => FF, 3 => FF);
n6 : Box_Nonce;
n7 : Symmetric_Nonce;
begin
if not initialize_sodium_library then
Put_Line ("Initialization failed");
return;
end if;
n6 := Random_Nonce;
n7 := Random_Symmetric_Nonce;
Put_Line ("N1: " & As_Hexidecimal (n1));
increment_nonce (n1);
Put_Line ("+1: " & As_Hexidecimal (n1));
Put_Line ("");
Put_Line ("N2: " & As_Hexidecimal (n2));
increment_nonce (n2);
Put_Line ("+1: " & As_Hexidecimal (n2));
Put_Line ("");
Put_Line ("N3: " & As_Hexidecimal (n3));
increment_nonce (n3);
Put_Line ("+1: " & As_Hexidecimal (n3));
Put_Line ("");
Put_Line ("N4: " & As_Hexidecimal (n4));
increment_nonce (n4);
Put_Line ("+1: " & As_Hexidecimal (n4));
Put_Line ("");
Put_Line ("N5: " & As_Hexidecimal (n5));
increment_nonce (n5);
Put_Line ("+1: " & As_Hexidecimal (n5));
Put_Line ("");
Put_Line ("N6: " & As_Hexidecimal (n6));
increment_nonce (n6);
Put_Line ("+1: " & As_Hexidecimal (n6));
Put_Line ("");
Put_Line ("N7: " & As_Hexidecimal (n7));
increment_nonce (n7);
Put_Line ("+1: " & As_Hexidecimal (n7));
end Demo_Ada;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- (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.
with Ada.Text_IO; use Ada.Text_IO;
with Latin_Utils.Strings_Package; use Latin_Utils.Strings_Package;
with Latin_Utils.Config;
with Support_Utils.Word_Parameters; use Support_Utils.Word_Parameters;
with Latin_Utils.Inflections_Package; use Latin_Utils.Inflections_Package;
with Latin_Utils.Dictionary_Package; use Latin_Utils.Dictionary_Package;
with Support_Utils.Developer_Parameters; use Support_Utils.Developer_Parameters;
with Words_Engine.Word_Package; use Words_Engine.Word_Package;
with Words_Engine.English_Support_Package;
use Words_Engine.English_Support_Package;
with Support_Utils.Dictionary_Form;
use Latin_Utils;
procedure Words_Engine.Search_English
(Input_English_Word : String;
Pofs : Part_Of_Speech_Type := X)
is
use Ewds_Direct_Io;
Input_Word : Eword := Lower_Case (Head (Input_English_Word, Eword_Size));
Input_Pofs : constant Part_Of_Speech_Type := Pofs;
Output_Array : Ewds_Array (1 .. 500) := (others => Null_Ewds_Record);
Number_Of_Hits : Integer := 0;
J1, J2, J : Ewds_Direct_Io.Count := 0;
D_K : constant Dictionary_Kind := General; -- For the moment
Ewds : Ewds_Record := Null_Ewds_Record;
First_Try, Second_Try : Boolean := True;
procedure Load_Output_Array (Ewds : in Ewds_Record) is
begin
if Ewds.Pofs <= Input_Pofs then
Number_Of_Hits := Number_Of_Hits + 1;
Output_Array (Number_Of_Hits) := Ewds;
end if;
end Load_Output_Array;
--procedure TRIM_OUTPUT_ARRAY is
procedure Sort_Output_Array is
Hits : Integer := 0;
begin
-- Bubble sort
Hit_Loop :
loop
Hits := 0;
Switch :
declare
Dw : Ewds_Record := Null_Ewds_Record;
begin
Inner_Loop : -- Order by RANK, FREQ, SEMI
for I in 1 .. Number_Of_Hits - 1 loop
if Output_Array (I + 1).Rank > Output_Array (I).Rank or else
(Output_Array (I + 1).Rank = Output_Array (I).Rank and then
Output_Array (I + 1).Freq < Output_Array (I).Freq) or else
(Output_Array (I + 1).Rank = Output_Array (I).Rank and then
Output_Array (I + 1).Freq = Output_Array (I).Freq and then
Output_Array (I + 1).Semi < Output_Array (I).Semi)
then
Dw := Output_Array (I);
Output_Array (I) := Output_Array (I + 1);
Output_Array (I + 1) := Dw;
Hits := Hits + 1;
--PUT_LINE ("HITS " & INTEGER'IMAGE (HITS));
end if;
end loop Inner_Loop;
end Switch;
exit Hit_Loop when Hits = 0;
end loop Hit_Loop;
end Sort_Output_Array;
procedure Dump_Output_Array (Output : in Ada.Text_IO.File_Type) is
De : Dictionary_Entry := Null_Dictionary_Entry;
Number_To_Show : Integer := Number_Of_Hits;
One_Screen : constant Integer := 6;
begin
--TEXT_IO.PUT_LINE ("DUMP_OUTPUT");
if Number_Of_Hits = 0 then
Ada.Text_IO.Put_Line (Output, "No Match");
else
Sort_Output_Array;
--TEXT_IO.PUT_LINE ("DUMP_OUTPUT SORTED");
Trimmed := False;
if Words_Mode (Trim_Output) then
if Number_Of_Hits > One_Screen then
Number_To_Show := One_Screen;
Trimmed := True;
else
Number_To_Show := Number_Of_Hits;
end if;
end if;
for I in 1 .. Number_To_Show loop
Ada.Text_IO.New_Line (Output);
Do_Pause :
begin
if Integer (Ada.Text_IO.Line (Output)) >
Scroll_Line_Number + Config.Output_Screen_Size
then
Pause (Output);
Scroll_Line_Number := Integer (Ada.Text_IO.Line (Output));
end if;
end Do_Pause;
Dict_IO.Read (Dict_File (General),
De, Dict_IO.Count (Output_Array (I).N));
Put (Output, Support_Utils.Dictionary_Form (De));
Ada.Text_IO.Put (Output, " ");
if De.Part.Pofs = N then
Ada.Text_IO.Put (Output, " ");
Decn_Record_IO.Put (Output, De.Part.N.Decl);
Ada.Text_IO.Put (Output, " " &
Gender_Type'Image (De.Part.N.Gender) & " ");
end if;
if De.Part.Pofs = V then
Ada.Text_IO.Put (Output, " ");
Decn_Record_IO.Put (Output, De.Part.V.Con);
end if;
if (De.Part.Pofs = V) and then
(De.Part.V.Kind in Gen .. Perfdef)
then
Ada.Text_IO.Put (Output, " " &
Verb_Kind_Type'Image (De.Part.V.Kind) & " ");
end if;
if Words_Mdev (Show_Dictionary_Codes) then
Ada.Text_IO.Put (Output, " [");
-- FIXME: Why noy Translation_Record_IO.Put ?
Age_Type_IO.Put (Output, De.Tran.Age);
Area_Type_IO.Put (Output, De.Tran.Area);
Geo_Type_IO.Put (Output, De.Tran.Geo);
Frequency_Type_IO.Put (Output, De.Tran.Freq);
Source_Type_IO.Put (Output, De.Tran.Source);
Ada.Text_IO.Put (Output, "] ");
end if;
if Words_Mdev (Show_Dictionary) then
Ada.Text_IO.Put (Output, Ext (D_K) & ">");
end if;
--TEXT_IO.PUT_LINE ("DUMP_OUTPUT SHOW");
if Words_Mdev (Show_Dictionary_Line) then
Ada.Text_IO.Put (Output, "("
& Trim (Integer'Image (Output_Array (I).N)) & ")");
end if;
Ada.Text_IO.New_Line (Output);
--TEXT_IO.PUT_LINE ("DUMP_OUTPUT MEAN");
Ada.Text_IO.Put (Output, Trim (De.Mean));
Ada.Text_IO.New_Line (Output);
end loop;
--TEXT_IO.PUT_LINE ("DUMP_OUTPUT TRIMMED");
if Trimmed then
Put_Line (Output, "*");
end if;
end if; -- On HITS = 0
exception
when others =>
null; -- If N not in DICT_FILE
end Dump_Output_Array;
begin
J1 := 1;
J2 := Size (Ewds_File);
First_Try := True;
Second_Try := True;
J := (J1 + J2) / 2;
Binary_Search :
loop
-- TEXT_IO.PUT_LINE ("J = " & INTEGER'IMAGE (INTEGER (J)));
if (J1 = J2 - 1) or (J1 = J2) then
if First_Try then
J := J1;
First_Try := False;
elsif Second_Try then
J := J2;
Second_Try := False;
else
exit Binary_Search;
end if;
end if;
-- Should D_K
Set_Index (Ewds_File, J);
Read (Ewds_File, Ewds);
if "<"(Lower_Case (Ewds.W), Input_Word) then -- Not LTU, not u=v
J1 := J;
J := (J1 + J2) / 2;
elsif ">"(Lower_Case (Ewds.W), Input_Word) then
J2 := J;
J := (J1 + J2) / 2;
else
for I in reverse J1 .. J loop
Set_Index (Ewds_File, Ewds_Direct_Io.Count (I));
Read (Ewds_File, Ewds); -- Reads and advances index!!
if "="(Lower_Case (Ewds.W), Input_Word) then
Load_Output_Array (Ewds);
else
exit;
end if;
end loop;
for I in J + 1 .. J2 loop
Set_Index (Ewds_File, Ewds_Direct_Io.Count (I));
Read (Ewds_File, Ewds);
if "="(Lower_Case (Ewds.W), Input_Word) then
Load_Output_Array (Ewds);
else
exit Binary_Search;
end if;
end loop;
exit Binary_Search;
end if;
end loop Binary_Search;
if Words_Mode (Write_Output_To_File) then
Dump_Output_Array (Output);
else
Dump_Output_Array (Current_Output);
end if;
exception
when others =>
Ada.Text_IO.Put_Line ("exception SEARCH NUMBER_OF_HITS = " &
Integer'Image (Number_Of_Hits));
raise;
end Words_Engine.Search_English;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
private with GL.Low_Level;
with GL.Types;
package GL.Toggles is
pragma Preelaborate;
type Toggle_State is (Disabled, Enabled);
type Toggle is (Cull_Face, Depth_Test,
Stencil_Test, Dither, Blend, Color_Logic_Op, Scissor_Test,
Polygon_Offset_Point, Polygon_Offset_Line,
Clip_Distance_0, Clip_Distance_1, Clip_Distance_2, Clip_Distance_3,
Clip_Distance_4, Clip_Distance_5, Clip_Distance_6, Clip_Distance_7,
Polygon_Offset_Fill, Multisample,
Sample_Alpha_To_Coverage, Sample_Alpha_To_One, Sample_Coverage,
Debug_Output_Synchronous,
Program_Point_Size, Depth_Clamp,
Texture_Cube_Map_Seamless, Sample_Shading,
Rasterizer_Discard, Primitive_Restart_Fixed_Index,
Framebuffer_SRGB, Sample_Mask, Primitive_Restart,
Debug_Output);
procedure Enable (Subject : Toggle);
procedure Disable (Subject : Toggle);
procedure Set (Subject : Toggle; Value : Toggle_State);
function State (Subject : Toggle) return Toggle_State;
type Toggle_Indexed is (Blend, Scissor_Test);
procedure Enable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Disable (Subject : Toggle_Indexed; Index : Types.UInt);
procedure Set (Subject : Toggle_Indexed; Index : Types.UInt; Value : Toggle_State);
function State (Subject : Toggle_Indexed; Index : Types.UInt) return Toggle_State;
private
for Toggle use (Cull_Face => 16#0B44#,
Depth_Test => 16#0B71#,
Stencil_Test => 16#0B90#,
Dither => 16#0BD0#,
Blend => 16#0BE2#,
Color_Logic_Op => 16#0BF2#,
Scissor_Test => 16#0C11#,
Polygon_Offset_Point => 16#2A01#,
Polygon_Offset_Line => 16#2A02#,
Clip_Distance_0 => 16#3000#,
Clip_Distance_1 => 16#3001#,
Clip_Distance_2 => 16#3002#,
Clip_Distance_3 => 16#3003#,
Clip_Distance_4 => 16#3004#,
Clip_Distance_5 => 16#3005#,
Clip_Distance_6 => 16#3006#,
Clip_Distance_7 => 16#3007#,
Polygon_Offset_Fill => 16#8037#,
Multisample => 16#809D#,
Sample_Alpha_To_Coverage => 16#809E#,
Sample_Alpha_To_One => 16#809F#,
Sample_Coverage => 16#80A0#,
Debug_Output_Synchronous => 16#8242#,
Program_Point_Size => 16#8642#,
Depth_Clamp => 16#864F#,
Texture_Cube_Map_Seamless => 16#884F#,
Sample_Shading => 16#8C36#,
Rasterizer_Discard => 16#8C89#,
Primitive_Restart_Fixed_Index => 16#8D69#,
Framebuffer_SRGB => 16#8DB9#,
Sample_Mask => 16#8E51#,
Primitive_Restart => 16#8F9D#,
Debug_Output => 16#92E0#);
for Toggle'Size use Low_Level.Enum'Size;
for Toggle_Indexed use
(Blend => 16#0BE2#,
Scissor_Test => 16#0C11#);
for Toggle_Indexed'Size use Low_Level.Enum'Size;
end GL.Toggles;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Internals.Elements;
with AMF.Internals.Extents;
with AMF.Internals.Helpers;
with AMF.Internals.Links;
with AMF.Internals.Listener_Registry;
with AMF.Internals.Tables.UTP_Constructors;
with AMF.Internals.Tables.Utp_Metamodel;
with AMF.Utp.Holders.Verdicts;
package body AMF.Internals.Factories.Utp_Factories is
None_Img : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("none");
Pass_Img : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("pass");
Inconclusive_Img : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("inconclusive");
Fail_Img : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("fail");
Error_Img : constant League.Strings.Universal_String
:= League.Strings.To_Universal_String ("error");
function Convert_Duration_To_String
(Value : League.Holders.Holder) return League.Strings.Universal_String
is separate;
function Create_Duration_From_String
(Image : League.Strings.Universal_String) return League.Holders.Holder
is separate;
function Convert_Time_To_String
(Value : League.Holders.Holder) return League.Strings.Universal_String
is separate;
function Create_Time_From_String
(Image : League.Strings.Universal_String) return League.Holders.Holder
is separate;
function Convert_Timezone_To_String
(Value : League.Holders.Holder) return League.Strings.Universal_String
is separate;
function Create_Timezone_From_String
(Image : League.Strings.Universal_String) return League.Holders.Holder
is separate;
-----------------
-- Constructor --
-----------------
function Constructor
(Extent : AMF.Internals.AMF_Extent)
return not null AMF.Factories.Factory_Access is
begin
return new Utp_Factory'(Extent => Extent);
end Constructor;
-----------------------
-- Convert_To_String --
-----------------------
overriding function Convert_To_String
(Self : not null access Utp_Factory;
Data_Type : not null access AMF.CMOF.Data_Types.CMOF_Data_Type'Class;
Value : League.Holders.Holder) return League.Strings.Universal_String
is
pragma Unreferenced (Self);
DT : constant AMF.Internals.CMOF_Element
:= AMF.Internals.Elements.Element_Base'Class (Data_Type.all).Element;
begin
if DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Duration then
return Convert_Duration_To_String (Value);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time then
return Convert_Time_To_String (Value);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Timezone then
return Convert_Timezone_To_String (Value);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Verdict then
declare
Item : constant AMF.Utp.Utp_Verdict
:= AMF.Utp.Holders.Verdicts.Element (Value);
begin
case Item is
when AMF.Utp.None =>
return None_Img;
when AMF.Utp.Pass =>
return Pass_Img;
when AMF.Utp.Inconclusive =>
return Inconclusive_Img;
when AMF.Utp.Fail =>
return Fail_Img;
when AMF.Utp.Error =>
return Error_Img;
end case;
end;
else
raise Program_Error;
end if;
end Convert_To_String;
------------
-- Create --
------------
overriding function Create
(Self : not null access Utp_Factory;
Meta_Class : not null access AMF.CMOF.Classes.CMOF_Class'Class)
return not null AMF.Elements.Element_Access
is
MC : constant AMF.Internals.CMOF_Element
:= AMF.Internals.Elements.Element_Base'Class (Meta_Class.all).Element;
Element : AMF.Internals.AMF_Element;
begin
if MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Coding_Rule then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Coding_Rule;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Partition then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Data_Partition;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Pool then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Data_Pool;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Selector then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Data_Selector;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Default then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Default;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Default_Application then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Default_Application;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Determ_Alt then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Determ_Alt;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Finish_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Finish_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Get_Timezone_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Get_Timezone_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Literal_Any then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Literal_Any;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Literal_Any_Or_Null then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Literal_Any_Or_Null;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Log_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Log_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Managed_Element then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Managed_Element;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Read_Timer_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Read_Timer_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_SUT then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_SUT;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Set_Timezone_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Set_Timezone_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Start_Timer_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Start_Timer_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Stop_Timer_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Stop_Timer_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Case then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Case;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Component then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Component;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Context then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Context;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Log then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Log;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Log_Application then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Log_Application;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Objective then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Objective;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Suite then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Test_Suite;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Time_Out;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Time_Out_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out_Message then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Time_Out_Message;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Timer_Running_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Timer_Running_Action;
elsif MC = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Validation_Action then
Element := AMF.Internals.Tables.UTP_Constructors.Create_Utp_Validation_Action;
else
raise Program_Error;
end if;
AMF.Internals.Extents.Internal_Append (Self.Extent, Element);
AMF.Internals.Listener_Registry.Notify_Instance_Create
(AMF.Internals.Helpers.To_Element (Element));
return AMF.Internals.Helpers.To_Element (Element);
end Create;
------------------------
-- Create_From_String --
------------------------
overriding function Create_From_String
(Self : not null access Utp_Factory;
Data_Type : not null access AMF.CMOF.Data_Types.CMOF_Data_Type'Class;
Image : League.Strings.Universal_String) return League.Holders.Holder
is
pragma Unreferenced (Self);
use type League.Strings.Universal_String;
DT : constant AMF.Internals.CMOF_Element
:= AMF.Internals.Elements.Element_Base'Class (Data_Type.all).Element;
begin
if DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Duration then
return Create_Duration_From_String (Image);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time then
return Create_Time_From_String (Image);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Timezone then
return Create_Timezone_From_String (Image);
elsif DT = AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Verdict then
if Image = None_Img then
return
AMF.Utp.Holders.Verdicts.To_Holder
(AMF.Utp.None);
elsif Image = Pass_Img then
return
AMF.Utp.Holders.Verdicts.To_Holder
(AMF.Utp.Pass);
elsif Image = Inconclusive_Img then
return
AMF.Utp.Holders.Verdicts.To_Holder
(AMF.Utp.Inconclusive);
elsif Image = Fail_Img then
return
AMF.Utp.Holders.Verdicts.To_Holder
(AMF.Utp.Fail);
elsif Image = Error_Img then
return
AMF.Utp.Holders.Verdicts.To_Holder
(AMF.Utp.Error);
else
raise Constraint_Error;
end if;
else
raise Program_Error;
end if;
end Create_From_String;
-----------------
-- Create_Link --
-----------------
overriding function Create_Link
(Self : not null access Utp_Factory;
Association :
not null access AMF.CMOF.Associations.CMOF_Association'Class;
First_Element : not null AMF.Elements.Element_Access;
Second_Element : not null AMF.Elements.Element_Access)
return not null AMF.Links.Link_Access
is
pragma Unreferenced (Self);
begin
return
AMF.Internals.Links.Proxy
(AMF.Internals.Links.Create_Link
(AMF.Internals.Elements.Element_Base'Class
(Association.all).Element,
AMF.Internals.Helpers.To_Element (First_Element),
AMF.Internals.Helpers.To_Element (Second_Element)));
end Create_Link;
-----------------
-- Get_Package --
-----------------
overriding function Get_Package
(Self : not null access constant Utp_Factory)
return AMF.CMOF.Packages.Collections.Set_Of_CMOF_Package
is
pragma Unreferenced (Self);
begin
return Result : AMF.CMOF.Packages.Collections.Set_Of_CMOF_Package do
Result.Add (Get_Package);
end return;
end Get_Package;
-----------------
-- Get_Package --
-----------------
function Get_Package return not null AMF.CMOF.Packages.CMOF_Package_Access is
begin
return
AMF.CMOF.Packages.CMOF_Package_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MM_Utp_Utp));
end Get_Package;
------------------------
-- Create_Coding_Rule --
------------------------
overriding function Create_Coding_Rule
(Self : not null access Utp_Factory)
return AMF.Utp.Coding_Rules.Utp_Coding_Rule_Access is
begin
return
AMF.Utp.Coding_Rules.Utp_Coding_Rule_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Coding_Rule))));
end Create_Coding_Rule;
---------------------------
-- Create_Data_Partition --
---------------------------
overriding function Create_Data_Partition
(Self : not null access Utp_Factory)
return AMF.Utp.Data_Partitions.Utp_Data_Partition_Access is
begin
return
AMF.Utp.Data_Partitions.Utp_Data_Partition_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Partition))));
end Create_Data_Partition;
----------------------
-- Create_Data_Pool --
----------------------
overriding function Create_Data_Pool
(Self : not null access Utp_Factory)
return AMF.Utp.Data_Pools.Utp_Data_Pool_Access is
begin
return
AMF.Utp.Data_Pools.Utp_Data_Pool_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Pool))));
end Create_Data_Pool;
--------------------------
-- Create_Data_Selector --
--------------------------
overriding function Create_Data_Selector
(Self : not null access Utp_Factory)
return AMF.Utp.Data_Selectors.Utp_Data_Selector_Access is
begin
return
AMF.Utp.Data_Selectors.Utp_Data_Selector_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Data_Selector))));
end Create_Data_Selector;
--------------------
-- Create_Default --
--------------------
overriding function Create_Default
(Self : not null access Utp_Factory)
return AMF.Utp.Defaults.Utp_Default_Access is
begin
return
AMF.Utp.Defaults.Utp_Default_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Default))));
end Create_Default;
--------------------------------
-- Create_Default_Application --
--------------------------------
overriding function Create_Default_Application
(Self : not null access Utp_Factory)
return AMF.Utp.Default_Applications.Utp_Default_Application_Access is
begin
return
AMF.Utp.Default_Applications.Utp_Default_Application_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Default_Application))));
end Create_Default_Application;
-----------------------
-- Create_Determ_Alt --
-----------------------
overriding function Create_Determ_Alt
(Self : not null access Utp_Factory)
return AMF.Utp.Determ_Alts.Utp_Determ_Alt_Access is
begin
return
AMF.Utp.Determ_Alts.Utp_Determ_Alt_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Determ_Alt))));
end Create_Determ_Alt;
--------------------------
-- Create_Finish_Action --
--------------------------
overriding function Create_Finish_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Finish_Actions.Utp_Finish_Action_Access is
begin
return
AMF.Utp.Finish_Actions.Utp_Finish_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Finish_Action))));
end Create_Finish_Action;
--------------------------------
-- Create_Get_Timezone_Action --
--------------------------------
overriding function Create_Get_Timezone_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Get_Timezone_Actions.Utp_Get_Timezone_Action_Access is
begin
return
AMF.Utp.Get_Timezone_Actions.Utp_Get_Timezone_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Get_Timezone_Action))));
end Create_Get_Timezone_Action;
------------------------
-- Create_Literal_Any --
------------------------
overriding function Create_Literal_Any
(Self : not null access Utp_Factory)
return AMF.Utp.Literal_Anies.Utp_Literal_Any_Access is
begin
return
AMF.Utp.Literal_Anies.Utp_Literal_Any_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Literal_Any))));
end Create_Literal_Any;
--------------------------------
-- Create_Literal_Any_Or_Null --
--------------------------------
overriding function Create_Literal_Any_Or_Null
(Self : not null access Utp_Factory)
return AMF.Utp.Literal_Any_Or_Nulls.Utp_Literal_Any_Or_Null_Access is
begin
return
AMF.Utp.Literal_Any_Or_Nulls.Utp_Literal_Any_Or_Null_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Literal_Any_Or_Null))));
end Create_Literal_Any_Or_Null;
-----------------------
-- Create_Log_Action --
-----------------------
overriding function Create_Log_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Log_Actions.Utp_Log_Action_Access is
begin
return
AMF.Utp.Log_Actions.Utp_Log_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Log_Action))));
end Create_Log_Action;
----------------------------
-- Create_Managed_Element --
----------------------------
overriding function Create_Managed_Element
(Self : not null access Utp_Factory)
return AMF.Utp.Managed_Elements.Utp_Managed_Element_Access is
begin
return
AMF.Utp.Managed_Elements.Utp_Managed_Element_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Managed_Element))));
end Create_Managed_Element;
------------------------------
-- Create_Read_Timer_Action --
------------------------------
overriding function Create_Read_Timer_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Read_Timer_Actions.Utp_Read_Timer_Action_Access is
begin
return
AMF.Utp.Read_Timer_Actions.Utp_Read_Timer_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Read_Timer_Action))));
end Create_Read_Timer_Action;
----------------
-- Create_SUT --
----------------
overriding function Create_SUT
(Self : not null access Utp_Factory)
return AMF.Utp.SUTs.Utp_SUT_Access is
begin
return
AMF.Utp.SUTs.Utp_SUT_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_SUT))));
end Create_SUT;
--------------------------------
-- Create_Set_Timezone_Action --
--------------------------------
overriding function Create_Set_Timezone_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Set_Timezone_Actions.Utp_Set_Timezone_Action_Access is
begin
return
AMF.Utp.Set_Timezone_Actions.Utp_Set_Timezone_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Set_Timezone_Action))));
end Create_Set_Timezone_Action;
-------------------------------
-- Create_Start_Timer_Action --
-------------------------------
overriding function Create_Start_Timer_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Start_Timer_Actions.Utp_Start_Timer_Action_Access is
begin
return
AMF.Utp.Start_Timer_Actions.Utp_Start_Timer_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Start_Timer_Action))));
end Create_Start_Timer_Action;
------------------------------
-- Create_Stop_Timer_Action --
------------------------------
overriding function Create_Stop_Timer_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Stop_Timer_Actions.Utp_Stop_Timer_Action_Access is
begin
return
AMF.Utp.Stop_Timer_Actions.Utp_Stop_Timer_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Stop_Timer_Action))));
end Create_Stop_Timer_Action;
----------------------
-- Create_Test_Case --
----------------------
overriding function Create_Test_Case
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Cases.Utp_Test_Case_Access is
begin
return
AMF.Utp.Test_Cases.Utp_Test_Case_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Case))));
end Create_Test_Case;
---------------------------
-- Create_Test_Component --
---------------------------
overriding function Create_Test_Component
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Components.Utp_Test_Component_Access is
begin
return
AMF.Utp.Test_Components.Utp_Test_Component_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Component))));
end Create_Test_Component;
-------------------------
-- Create_Test_Context --
-------------------------
overriding function Create_Test_Context
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Contexts.Utp_Test_Context_Access is
begin
return
AMF.Utp.Test_Contexts.Utp_Test_Context_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Context))));
end Create_Test_Context;
---------------------
-- Create_Test_Log --
---------------------
overriding function Create_Test_Log
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Logs.Utp_Test_Log_Access is
begin
return
AMF.Utp.Test_Logs.Utp_Test_Log_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Log))));
end Create_Test_Log;
---------------------------------
-- Create_Test_Log_Application --
---------------------------------
overriding function Create_Test_Log_Application
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Log_Applications.Utp_Test_Log_Application_Access is
begin
return
AMF.Utp.Test_Log_Applications.Utp_Test_Log_Application_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Log_Application))));
end Create_Test_Log_Application;
---------------------------
-- Create_Test_Objective --
---------------------------
overriding function Create_Test_Objective
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Objectives.Utp_Test_Objective_Access is
begin
return
AMF.Utp.Test_Objectives.Utp_Test_Objective_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Objective))));
end Create_Test_Objective;
-----------------------
-- Create_Test_Suite --
-----------------------
overriding function Create_Test_Suite
(Self : not null access Utp_Factory)
return AMF.Utp.Test_Suites.Utp_Test_Suite_Access is
begin
return
AMF.Utp.Test_Suites.Utp_Test_Suite_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Test_Suite))));
end Create_Test_Suite;
---------------------
-- Create_Time_Out --
---------------------
overriding function Create_Time_Out
(Self : not null access Utp_Factory)
return AMF.Utp.Time_Outs.Utp_Time_Out_Access is
begin
return
AMF.Utp.Time_Outs.Utp_Time_Out_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out))));
end Create_Time_Out;
----------------------------
-- Create_Time_Out_Action --
----------------------------
overriding function Create_Time_Out_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Time_Out_Actions.Utp_Time_Out_Action_Access is
begin
return
AMF.Utp.Time_Out_Actions.Utp_Time_Out_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out_Action))));
end Create_Time_Out_Action;
-----------------------------
-- Create_Time_Out_Message --
-----------------------------
overriding function Create_Time_Out_Message
(Self : not null access Utp_Factory)
return AMF.Utp.Time_Out_Messages.Utp_Time_Out_Message_Access is
begin
return
AMF.Utp.Time_Out_Messages.Utp_Time_Out_Message_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Time_Out_Message))));
end Create_Time_Out_Message;
---------------------------------
-- Create_Timer_Running_Action --
---------------------------------
overriding function Create_Timer_Running_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Timer_Running_Actions.Utp_Timer_Running_Action_Access is
begin
return
AMF.Utp.Timer_Running_Actions.Utp_Timer_Running_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Timer_Running_Action))));
end Create_Timer_Running_Action;
------------------------------
-- Create_Validation_Action --
------------------------------
overriding function Create_Validation_Action
(Self : not null access Utp_Factory)
return AMF.Utp.Validation_Actions.Utp_Validation_Action_Access is
begin
return
AMF.Utp.Validation_Actions.Utp_Validation_Action_Access
(Self.Create
(AMF.CMOF.Classes.CMOF_Class_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.Utp_Metamodel.MC_Utp_Validation_Action))));
end Create_Validation_Action;
end AMF.Internals.Factories.Utp_Factories;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Streams.Buffered;
-- Implements a <b>ResponseWriter</b> that puts the result in a string.
-- The response content can be retrieved after the response is rendered.
package body ASF.Contexts.Writer.String is
procedure Initialize (Stream : in out String_Writer) is
Output : ASF.Streams.Print_Stream;
begin
Stream.Content.Initialize (Size => 256 * 1024);
Output.Initialize (Stream.Content'Unchecked_Access);
Stream.Initialize ("text/xml", "utf-8", Output);
end Initialize;
-- ------------------------------
-- Get the response
-- ------------------------------
function Get_Response (Stream : in String_Writer) return Unbounded_String is
use Util.Streams;
begin
return To_Unbounded_String (Texts.To_String (Buffered.Buffered_Stream (Stream.Content)));
end Get_Response;
end ASF.Contexts.Writer.String;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Calendar;
with Ada.Real_Time;
procedure delays is
use type Ada.Calendar.Time;
use type Ada.Real_Time.Time;
use type Ada.Real_Time.Time_Span;
begin
declare
Start : Ada.Calendar.Time := Ada.Calendar.Clock;
begin
delay 1.0;
delay until Ada.Calendar.Clock + 1.0;
pragma Assert (Ada.Calendar.Clock - Start >= 2.0);
pragma Assert (Ada.Calendar.Clock - Start < 3.0); -- ??
end;
declare
Start : Ada.Real_Time.Time := Ada.Real_Time.Clock;
begin
delay 1.0;
delay until Ada.Real_Time.Clock + Ada.Real_Time.To_Time_Span (1.0);
pragma Assert (Ada.Real_Time.Clock - Start >= Ada.Real_Time.To_Time_Span (2.0));
pragma Assert (Ada.Real_Time.Clock - Start < Ada.Real_Time.To_Time_Span (3.0)); -- ??
end;
pragma Debug (Ada.Debug.Put ("OK"));
end delays;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma SPARK_Mode;
with Ada.Numerics.Long_Elementary_Functions;
use Ada.Numerics.Long_Elementary_Functions;
with Wire;
package body Zumo_Motion is
Pi : constant := 3.1415926;
function Get_Heading return Degrees
is
Mag : Axis_Data;
Heading : Degrees;
begin
Zumo_LSM303.Read_Mag (Data => Mag);
Heading := Degrees (
Arctan (
Long_Float (Mag (Y)) / Long_Float (Mag (X))
) * (180.0 / Pi));
if Heading > 360.0 then
Heading := Heading - 360.0;
elsif Heading < 0.0 then
Heading := 360.0 + Heading;
end if;
return Heading;
end Get_Heading;
procedure Init
is
begin
Wire.Init_Master;
Zumo_LSM303.Init;
Zumo_L3gd20h.Init;
Initd := True;
end Init;
end Zumo_Motion;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Amb is
type Alternatives is array (Positive range <>) of Unbounded_String;
type Amb (Count : Positive) is record
This : Positive := 1;
Left : access Amb;
List : Alternatives (1..Count);
end record;
function Image (L : Amb) return String is
begin
return To_String (L.List (L.This));
end Image;
function "/" (L, R : String) return Amb is
Result : Amb (2);
begin
Append (Result.List (1), L);
Append (Result.List (2), R);
return Result;
end "/";
function "/" (L : Amb; R : String) return Amb is
Result : Amb (L.Count + 1);
begin
Result.List (1..L.Count) := L.List ;
Append (Result.List (Result.Count), R);
return Result;
end "/";
function "=" (L, R : Amb) return Boolean is
Left : Unbounded_String renames L.List (L.This);
begin
return Element (Left, Length (Left)) = Element (R.List (R.This), 1);
end "=";
procedure Failure (L : in out Amb) is
begin
loop
if L.This < L.Count then
L.This := L.This + 1;
else
L.This := 1;
Failure (L.Left.all);
end if;
exit when L.Left = null or else L.Left.all = L;
end loop;
end Failure;
procedure Join (L : access Amb; R : in out Amb) is
begin
R.Left := L;
while L.all /= R loop
Failure (R);
end loop;
end Join;
W_1 : aliased Amb := "the" / "that" / "a";
W_2 : aliased Amb := "frog" / "elephant" / "thing";
W_3 : aliased Amb := "walked" / "treaded" / "grows";
W_4 : aliased Amb := "slowly" / "quickly";
begin
Join (W_1'Access, W_2);
Join (W_2'Access, W_3);
Join (W_3'Access, W_4);
Put_Line (Image (W_1) & ' ' & Image (W_2) & ' ' & Image (W_3) & ' ' & Image (W_4));
end Test_Amb;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with EL.Contexts.Default;
with Util.Serialize.Mappers;
with Keystore.Properties;
-- The <b>AWA.Applications.Configs</b> package reads the application configuration files.
package AWA.Applications.Configs is
MAX_PREFIX_LENGTH : constant := 64;
-- Merge the configuration content and the keystore to a final configuration object.
-- The keystore can be used to store sensitive information such as database connection,
-- secret keys while the rest of the configuration remains in clear property files.
-- The keystore must be unlocked to have access to its content.
-- The prefix parameter is used to prefix names from the keystore so that the same
-- keystore could be used by several applications.
procedure Merge (Into : in out ASF.Applications.Config;
Config : in out ASF.Applications.Config;
Wallet : in out Keystore.Properties.Manager;
Prefix : in String) with Pre => Prefix'Length <= MAX_PREFIX_LENGTH;
-- XML reader configuration. By instantiating this generic package, the XML parser
-- gets initialized to read the configuration for servlets, filters, managed beans,
-- permissions, events and other configuration elements.
generic
Mapper : in out Util.Serialize.Mappers.Processing;
App : in Application_Access;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean;
package Reader_Config is
end Reader_Config;
-- Read the application configuration file and configure the application
procedure Read_Configuration (App : in out Application'Class;
File : in String;
Context : in EL.Contexts.Default.Default_Context_Access;
Override_Context : in Boolean);
-- Get the configuration path for the application name.
-- The configuration path is search from:
-- o the current directory,
-- o the 'config' directory,
-- o the Dynamo installation directory in share/dynamo
function Get_Config_Path (Name : in String) return String;
end AWA.Applications.Configs;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Files;
with Util.Test_Caller;
package body Are.Generator.Go.Tests is
Expect_Dir : constant String := "regtests/expect/go/";
function Tool return String;
package Caller is new Util.Test_Caller (Test, "Are.Generator.Go");
function Tool return String is
begin
return "bin/are" & Are.Testsuite.EXE;
end Tool;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Are.Generate_Go1",
Test_Generate_Go1'Access);
Caller.Add_Test (Suite, "Test Are.Generate_Go2",
Test_Generate_Go2'Access);
Caller.Add_Test (Suite, "Test Are.Generate_Go3",
Test_Generate_Go3'Access);
end Add_Tests;
procedure Test_Generate_Go1 (T : in out Test) is
Dir : constant String := Util.Tests.Get_Test_Path ("");
Target : constant String := Util.Files.Compose (Dir, "resources1/resources1.go");
Web : constant String := "regtests/files/test-c-1/web";
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Generate the resources1.go file
T.Execute (Tool & " --lang=go -o " & Dir
& " --name-access --resource=Resources1 --fileset '**/*' "
& Web, Result);
T.Assert (Ada.Directories.Exists (Target),
"Resource file 'resources1/resources1.go' not generated");
Are.Testsuite.Assert_Equal_Files
(T => T,
Expect => Util.Tests.Get_Path (Expect_Dir & "resources1.go"),
Test => Target,
Message => "Invalid Go generation");
end Test_Generate_Go1;
procedure Test_Generate_Go2 (T : in out Test) is
Dir : constant String := Util.Tests.Get_Test_Path ("");
Target : constant String := Util.Files.Compose (Dir, "resources2/resources2.go");
Web : constant String := "regtests/files/test-ada-2";
Rule : constant String := "regtests/files/test-ada-2/package.xml";
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Generate the resources1.go file
T.Execute (Tool & " --lang=go -o " & Dir & " --name-access --rule=" & Rule
& " " & Web, Result);
T.Assert (Ada.Directories.Exists (Target),
"Resource file 'resources2/resources2.go' not generated");
Are.Testsuite.Assert_Equal_Files
(T => T,
Expect => Util.Tests.Get_Path (Expect_Dir & "resources2.go"),
Test => Target,
Message => "Invalid Go generation");
end Test_Generate_Go2;
procedure Test_Generate_Go3 (T : in out Test) is
Dir : constant String := Util.Tests.Get_Test_Path ("");
Target : constant String := Util.Files.Compose (Dir, "resource4/resource4.go");
Web : constant String := "regtests/files/test-ada-4";
Rule : constant String := "regtests/files/test-ada-4/package.xml";
Result : Ada.Strings.Unbounded.Unbounded_String;
begin
-- Generate the resources1.go file
T.Execute (Tool & " --lang=go -o " & Dir & " --name-access --rule=" & Rule
& " " & Web, Result);
T.Assert (Ada.Directories.Exists (Target),
"Resource file 'resource4/resource4.go' not generated");
Are.Testsuite.Assert_Equal_Files
(T => T,
Expect => Util.Tests.Get_Path (Expect_Dir & "resource4.go"),
Test => Target,
Message => "Invalid Go generation");
end Test_Generate_Go3;
end Are.Generator.Go.Tests;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body PIN with SPARK_Mode is
function From_String(S : in String) return PIN is
Result : Natural := 0;
Count : Natural := 0;
begin
for I in S'Range loop
declare
Ch : Character := S(I);
begin
--pragma Assert (Character'Pos(Ch) - Character'Pos('0') <= 9);
pragma Loop_Invariant (Ch >= '0' and Ch <= '9' and Count = I-S'First and Count <= 4 and Result < 10 ** Count);
Count := Count + 1;
Result := Result * 10;
Result := Result + (Character'Pos(Ch) - Character'Pos('0'));
end;
end loop;
return PIN(Result);
end From_String;
end PIN;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Program.Lexical_Elements;
with Program.Elements.Parameter_Specifications;
with Program.Elements.Procedure_Access_Types;
with Program.Element_Visitors;
package Program.Nodes.Procedure_Access_Types is
pragma Preelaborate;
type Procedure_Access_Type is
new Program.Nodes.Node
and Program.Elements.Procedure_Access_Types.Procedure_Access_Type
and Program.Elements.Procedure_Access_Types.Procedure_Access_Type_Text
with private;
function Create
(Not_Token : Program.Lexical_Elements.Lexical_Element_Access;
Null_Token : Program.Lexical_Elements.Lexical_Element_Access;
Access_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Protected_Token : Program.Lexical_Elements.Lexical_Element_Access;
Procedure_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
Parameters : Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access;
Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access)
return Procedure_Access_Type;
type Implicit_Procedure_Access_Type is
new Program.Nodes.Node
and Program.Elements.Procedure_Access_Types.Procedure_Access_Type
with private;
function Create
(Parameters : Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False;
Has_Not_Null : Boolean := False;
Has_Protected : Boolean := False)
return Implicit_Procedure_Access_Type
with Pre =>
Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance;
private
type Base_Procedure_Access_Type is
abstract new Program.Nodes.Node
and Program.Elements.Procedure_Access_Types.Procedure_Access_Type
with record
Parameters : Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access;
end record;
procedure Initialize
(Self : aliased in out Base_Procedure_Access_Type'Class);
overriding procedure Visit
(Self : not null access Base_Procedure_Access_Type;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class);
overriding function Parameters
(Self : Base_Procedure_Access_Type)
return Program.Elements.Parameter_Specifications
.Parameter_Specification_Vector_Access;
overriding function Is_Procedure_Access_Type_Element
(Self : Base_Procedure_Access_Type)
return Boolean;
overriding function Is_Access_Type_Element
(Self : Base_Procedure_Access_Type)
return Boolean;
overriding function Is_Type_Definition_Element
(Self : Base_Procedure_Access_Type)
return Boolean;
overriding function Is_Definition_Element
(Self : Base_Procedure_Access_Type)
return Boolean;
type Procedure_Access_Type is
new Base_Procedure_Access_Type
and Program.Elements.Procedure_Access_Types.Procedure_Access_Type_Text
with record
Not_Token : Program.Lexical_Elements.Lexical_Element_Access;
Null_Token : Program.Lexical_Elements.Lexical_Element_Access;
Access_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Protected_Token : Program.Lexical_Elements.Lexical_Element_Access;
Procedure_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Left_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
Right_Bracket_Token : Program.Lexical_Elements.Lexical_Element_Access;
end record;
overriding function To_Procedure_Access_Type_Text
(Self : aliased in out Procedure_Access_Type)
return Program.Elements.Procedure_Access_Types
.Procedure_Access_Type_Text_Access;
overriding function Not_Token
(Self : Procedure_Access_Type)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Null_Token
(Self : Procedure_Access_Type)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Access_Token
(Self : Procedure_Access_Type)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Protected_Token
(Self : Procedure_Access_Type)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Procedure_Token
(Self : Procedure_Access_Type)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Left_Bracket_Token
(Self : Procedure_Access_Type)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Right_Bracket_Token
(Self : Procedure_Access_Type)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Has_Not_Null
(Self : Procedure_Access_Type)
return Boolean;
overriding function Has_Protected
(Self : Procedure_Access_Type)
return Boolean;
type Implicit_Procedure_Access_Type is
new Base_Procedure_Access_Type
with record
Is_Part_Of_Implicit : Boolean;
Is_Part_Of_Inherited : Boolean;
Is_Part_Of_Instance : Boolean;
Has_Not_Null : Boolean;
Has_Protected : Boolean;
end record;
overriding function To_Procedure_Access_Type_Text
(Self : aliased in out Implicit_Procedure_Access_Type)
return Program.Elements.Procedure_Access_Types
.Procedure_Access_Type_Text_Access;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Procedure_Access_Type)
return Boolean;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Procedure_Access_Type)
return Boolean;
overriding function Is_Part_Of_Instance
(Self : Implicit_Procedure_Access_Type)
return Boolean;
overriding function Has_Not_Null
(Self : Implicit_Procedure_Access_Type)
return Boolean;
overriding function Has_Protected
(Self : Implicit_Procedure_Access_Type)
return Boolean;
end Program.Nodes.Procedure_Access_Types;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- -----------------------------------------------------------------------------
with Ada.Directories;
separate (Smk.Main)
-- --------------------------------------------------------------------------
function Must_Be_Run (Command : Run_Files.Command_Lines;
Previous_Run : in out Run_Files.Run_Lists.Map)
return Boolean
is
-- -----------------------------------------------------------------------
procedure Put_Explanation (Text : in String) is
use Smk.Run_Files;
begin
if Explain then
IO.Put_Line ("run " & (+Command) & " " & Text);
end if;
end Put_Explanation;
use Run_Files;
-- -----------------------------------------------------------------------
function A_Target_Is_Missing (Targets : in Run_Files.File_Lists.Map)
return Boolean is
use Ada.Directories;
use Run_Files.File_Lists;
begin
for T in Targets.Iterate loop
declare
Name : constant String := (+Key (T));
begin
if not Exists (+(Key (T))) then
Put_Explanation ("because " & Name & " is missing");
return True;
end if;
end;
end loop;
return False;
end A_Target_Is_Missing;
-- --------------------------------------------------------------------------
function A_Source_Is_Updated (Sources : in File_Lists.Map) return Boolean is
use Ada.Directories;
use Run_Files.File_Lists;
begin
for S in Sources.Iterate loop
declare
use Ada.Calendar;
Name : constant String := Full_Name (+Key (S));
File_TT : constant Time := Modification_Time (Name);
Last_Run_TT : constant Time := Element (S);
begin
if File_TT /= Last_Run_TT then
Put_Explanation ("because " & Name & " (" & IO.Image (File_TT)
& ") has been updated since last run ("
& IO.Image (Last_Run_TT) & ")");
return True;
end if;
end;
end loop;
return False;
end A_Source_Is_Updated;
use Run_Files.Run_Lists;
C : Run_Files.Run_Lists.Cursor;
begin
-- -----------------------------------------------------------------------
if Always_Make then
-- don't even ask, run it!
Put_Explanation ("because -a option is set");
return True;
end if;
C := Previous_Run.Find (Command);
if C = No_Element then
-- never run command
Put_Explanation ("because it was not run before");
return True;
else
return
A_Target_Is_Missing (Run_Files.Run_Lists.Element (C).Targets) or else
A_Source_Is_Updated (Run_Files.Run_Lists.Element (C).Sources);
end if;
end Must_Be_Run;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
--------------------------------------------------------------------------------
-- @brief Toolbox related types and methods.
-- $Author$
-- $Date$
-- $Revision$
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with System.Unsigned_Types; use System.Unsigned_Types;
with System; use System;
with Interfaces.C; use Interfaces.C;
with Ada.Unchecked_Conversion;
with System.Address_To_Access_Conversions;
with RASCAL.Memory; use RASCAL.Memory;
with RASCAL.OS; use RASCAL.OS;
package RASCAL.Toolbox is
type Object_Class is new Integer;
Max_Object_Name : Integer := 12;
type Descriptor_Block_Type is new Address;
type Object_State is (Hidden, Showing);
type Toolbox_SysInfo_Type is (Task_Name,
Messages_File_Descriptor,
Ressource_Directory,
Wimp_Task_Handle,
Sprite_Area);
type Object_ShowType is (Default,
FullSpec,
TopLeft,
Centre,
AtPointer);
type Creation_Type is (From_Template,
From_Memory);
type Top_Left_Type is
record
X : Integer;
Y : Integer;
end record;
pragma Convention (C, Top_Left_Type);
type Template_Header is
record
Class : Object_Class;
Flags : Integer;
Version : Integer;
Name : Char_Array (1..12);
Total_Size : Integer;
Body_Ptr : System.Address;
Body_Size : Integer;
end record;
pragma Convention (C, Template_Header);
--
-- Type used by Window class for window sizing.
--
type Toolbox_BBox_Type is
record
xmin : Integer;
ymin : Integer;
xmax : Integer;
ymax : Integer;
end record;
pragma Convention (C, Toolbox_BBox_Type);
type Toolbox_EventObject_Type is
record
Header : Toolbox_Event_Header;
end record;
pragma Convention (C, Toolbox_EventObject_Type);
type Toolbox_MessageEvent_Type is
record
Self : Object_ID;
Component : Component_ID;
Event : Toolbox_EventObject_Type;
end record;
pragma Convention (C, Toolbox_MessageEvent_Type);
type ResourceFile_Header_Type is
record
File_ID : Integer;
Version_Number : Integer;
Object_Offset : Integer;
end record;
pragma Convention (C, ResourceFile_Header_Type);
type RelocationTable_Type is
record
Num_Relocations : Integer;
Relocations : Integer;
end record;
pragma Convention (C, RelocationTable_Type);
type Relocation_Type is
record
Word_To_Relocate : Integer;
Directive : Integer;
end record;
pragma Convention (C, Relocation_Type);
type Event_Interest_Type is
record
Code : Integer;
Class : Object_Class;
end record;
pragma Convention (C, Event_Interest_Type);
type ResourceFileObject_TemplateHeader_Type is
record
String_Table_Offset : Integer;
Message_Table_Offset : Integer;
Relocation_Table_Offset : Integer;
Header : Template_Header;
end record;
pragma Convention (C, ResourceFileObject_TemplateHeader_Type);
--
-- A Toolbox Event.
--
type Reason_ToolboxEvent is null record;
pragma Convention (C, Reason_ToolboxEvent);
type Reason_ToolboxEvent_Pointer is access Reason_ToolboxEvent;
type AWEL_Reason_ToolboxEvent is abstract new
Wimp_EventListener(Reason_Event_ToolboxEvent,-1,-1) with
record
Event : Reason_ToolboxEvent_Pointer;
end record;
--
-- Raised if the Toolbox detects an error when it is not processing a Toolbox SWI.
--
type Toolbox_Error is
record
Header : Toolbox_Event_Header;
Number : Integer;
Message : Char_Array (1 .. 256 - 20 -
(Toolbox_Event_Header'Size/CHAR_BIT) -
(Object_ID'Size/CHAR_BIT) -
(Component_ID'Size/CHAR_BIT) -
(Integer'Size/CHAR_BIT));
end record;
pragma Convention (C, Toolbox_Error);
type Toolbox_Error_Pointer is access Toolbox_Error;
type ATEL_Toolbox_Error is abstract new Toolbox_EventListener(Toolbox_Event_Error,-1,-1) with
record
Event : Toolbox_Error_Pointer;
end record;
--
-- Raised after the Toolbox creates objects that have their auto-created attribute set.
--
type Toolbox_ObjectAutoCreated is
record
Header : Toolbox_Event_Header;
Template_Name : Char_Array (1 .. 256 - 20 -
(Toolbox_Event_Header'Size/CHAR_BIT) -
(Object_ID'Size/CHAR_BIT) -
(Component_ID'Size/CHAR_BIT));
end record;
pragma Convention (C, Toolbox_ObjectAutoCreated);
type Toolbox_ObjectAutoCreated_Pointer is access Toolbox_ObjectAutoCreated;
type ATEL_Toolbox_ObjectAutoCreated is abstract new
Toolbox_EventListener(Toolbox_Event_ObjectAutoCreated,-1,-1) with
record
Event : Toolbox_ObjectAutoCreated_Pointer;
end record;
--
-- Raised after the Toolbox deletes an object.
--
type Toolbox_ObjectDeleted is
record
Header : Toolbox_Event_Header;
end record;
pragma Convention (C, Toolbox_ObjectDeleted);
type Toolbox_ObjectDeleted_Pointer is access Toolbox_ObjectDeleted;
type ATEL_Toolbox_ObjectDeleted is abstract new
Toolbox_EventListener(Toolbox_Event_ObjectDeleted,-1,-1) with
record
Event : Toolbox_ObjectDeleted_Pointer;
end record;
--
-- Creates an object, either from a named template in a res file, or from a template description block in memory.
--
function Create_Object (Template : in string;
Flags : in Creation_Type := From_Template) return Object_ID;
--
-- Deletes a given object. By default objects attached to this object are also deleted.
--
procedure Delete_Object (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Returns the id of the Ancestor of the given object.
--
procedure Get_Ancestor (Object : in Object_ID;
Ancestor : out Object_ID;
Component : out Component_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Returns the value of the client handle for this object.
--
function Get_Client (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0) return Object_ID;
--
-- Returns the class of the object.
--
function Get_Class (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0) return Object_Class;
--
-- Returns information regarding the state of an object.
--
function Get_State (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0) return Object_State;
--
-- Returns the parent of the object.
--
procedure Get_Parent (Object : in Object_ID;
Parent : out Object_ID;
Component : out Component_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Returns the name of the template used to create the object.
--
function Get_Template_Name (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0)
return string;
--
-- Hides the object.
--
procedure Hide_Object (Object : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Loads the given resource file, and creates any objects which have the auto-create flag set.
--
procedure Load_Resources (Filename : in string;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Sets the value of the client handle for this object.
--
procedure Set_Client_Handle
(Object : in Object_ID;
Client : in Object_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Shows the given object on screen at specific coordinates.
--
procedure Show_Object_At (Object : in Object_ID;
X : Integer;
Y : Integer;
Parent_Object : in Object_ID;
Parent_Component : in Component_ID;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Shows the given object on screen.
--
procedure Show_Object (Object : in Object_ID;
Parent_Object : in Object_ID := 0;
Parent_Component : in Component_ID := 0;
Show : in Object_ShowType := Default;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Returns a pointer to a block suitable to pass to Create_Object.
--
function Template_Lookup (Template_Name : in string;
Flags : in System.Unsigned_Types.Unsigned := 0)
return Address;
--
-- Raises toolbox event.
--
procedure Raise_Event (Object : in Object_ID;
Component : in Component_ID;
Event : in Address;
Flags : in System.Unsigned_Types.Unsigned := 0);
--
-- Abstract event handler for AWEL_Reason_ToolboxEvent event.
--
procedure Handle (The : in AWEL_Reason_ToolboxEvent) is abstract;
--
-- Abstract event handler for the ATEL_Toolbox_Error event.
--
procedure Handle (The : in ATEL_Toolbox_Error) is abstract;
--
-- Abstract event handler for the ATEL_Toolbox_ObjectAutoCreated event.
--
procedure Handle (The : in ATEL_Toolbox_ObjectAutoCreated) is abstract;
--
-- Abstract event handler for the ATEL_Toolbox_ObjectDeleted event.
--
procedure Handle (The : in ATEL_Toolbox_ObjectDeleted) is abstract;
end RASCAL.Toolbox;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package System.Bitfield_Utils is
-- This package provides a procedure for copying arbitrarily large and
-- arbitrarily bit-aligned bit fields.
-- Type Val is used to represent small bit fields. Val_2 represents a
-- contiguous pair of Vals. Val_2'Alignment is half of its size in bytes,
-- which is likely not the natural alignment. This is done to ensure that
-- any bit field that fits in a Val can fit in an aligned Val_2, starting
-- somewhere in the first half, and possibly crossing over into the second
-- half. This allows us to isolate a Val value by shifting and masking the
-- Val_2.
--
-- Val can be 8, 16, or 32 bits; larger values are more efficient. It can't
-- be 64 bits, because we need Val_2 to be a double-wide shiftable type,
-- and 128 bits is not supported. Instantiating with an 8-bit Val is useful
-- for testing and debugging; 32 bits should be used for production.
--
-- We use modular types here, not because we want modular arithmetic, but
-- so we can do shifting and masking. The actual for Val_2 should have
-- pragma Provide_Shift_Operators, so that the Shift_Left and Shift_Right
-- intrinsics can be passed in. It is impossible to put that pragma on a
-- generic formal, or on a type derived from a generic formal, so they have
-- to be passed in.
--
-- Endian indicates whether we're on little-endian or big-endian machine.
pragma Elaborate_Body;
Little : constant Bit_Order := Low_Order_First;
Big : constant Bit_Order := High_Order_First;
generic
type Val is mod <>;
type Val_2 is mod <>;
with function Shift_Left
(Value : Val_2;
Amount : Natural) return Val_2 is <>;
with function Shift_Right
(Value : Val_2;
Amount : Natural) return Val_2 is <>;
Endian : Bit_Order := Default_Bit_Order;
package G is
-- Assert that Val has one of the allowed sizes, and that Val_2 is twice
-- that.
pragma Assert (Val'Size in 8 | 16 | 32);
pragma Assert (Val_2'Size = Val'Size * 2);
-- Assert that both are aligned the same, to the size in bytes of Val
-- (not Val_2).
pragma Assert (Val'Alignment = Val'Size / Storage_Unit);
pragma Assert (Val_2'Alignment = Val'Alignment);
type Val_Array is array (Positive range <>) of Val;
-- It might make more sense to have:
-- subtype Val is Val_2 range 0 .. 2**Val'Size - 1;
-- But then GNAT gets the component size of Val_Array wrong.
pragma Assert (Val_Array'Alignment = Val'Alignment);
pragma Assert (Val_Array'Component_Size = Val'Size);
subtype Bit_Size is Natural; -- Size in bits of a bit field
subtype Small_Size is Bit_Size range 0 .. Val'Size;
-- Size of a small one
subtype Bit_Offset is Small_Size range 0 .. Val'Size - 1;
-- Starting offset
subtype Bit_Offset_In_Byte is Bit_Offset range 0 .. Storage_Unit - 1;
procedure Copy_Bitfield
(Src_Address : Address;
Src_Offset : Bit_Offset_In_Byte;
Dest_Address : Address;
Dest_Offset : Bit_Offset_In_Byte;
Size : Bit_Size);
-- An Address and a Bit_Offset together form a "bit address". This
-- copies the source bit field to the destination. Size is the size in
-- bits of the bit field. The bit fields can be arbitrarily large, but
-- the starting offsets must be within the first byte that the Addresses
-- point to. The Address values need not be aligned.
--
-- For example, a slice assignment of a packed bit field:
--
-- D (D_First .. D_Last) := S (S_First .. S_Last);
--
-- can be implemented using:
--
-- Copy_Bitfield
-- (S (S_First)'Address, S (S_First)'Bit,
-- D (D_First)'Address, D (D_First)'Bit,
-- Size);
end G;
end System.Bitfield_Utils;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with STM32_SVD; use STM32_SVD;
with STM32_SVD.GPIO;
with STM32_SVD.USB;
with System;
package STM32GD.USB is
-----------------------------------------------------------------------------
-- Endpoint register and associated types and operations
-----------------------------------------------------------------------------
subtype EPxR_EA_Field is STM32_SVD.UInt4;
subtype EPxR_STAT_TX_Field is STM32_SVD.UInt2;
subtype EPxR_DTOG_TX_Field is STM32_SVD.Bit;
subtype EPxR_CTR_TX_Field is STM32_SVD.Bit;
subtype EPxR_EP_KIND_Field is STM32_SVD.Bit;
subtype EPxR_EP_TYPE_Field is STM32_SVD.UInt2;
subtype EPxR_SETUP_Field is STM32_SVD.Bit;
subtype EPxR_STAT_RX_Field is STM32_SVD.UInt2;
subtype EPxR_DTOG_RX_Field is STM32_SVD.Bit;
subtype EPxR_CTR_RX_Field is STM32_SVD.Bit;
type EPxR_Register is record
-- Endpoint address
EA : EPxR_EA_Field := 16#0#;
-- Status bits, for transmission transfers
STAT_TX : EPxR_STAT_TX_Field := 16#0#;
-- Data Toggle, for transmission transfers
DTOG_TX : EPxR_DTOG_TX_Field := 16#0#;
-- Correct Transfer for transmission
CTR_TX : EPxR_CTR_TX_Field := 16#0#;
-- Endpoint kind
EP_KIND : EPxR_EP_KIND_Field := 16#0#;
-- Endpoint type
EP_TYPE : EPxR_EP_TYPE_Field := 16#0#;
-- Setup transaction completed
SETUP : EPxR_SETUP_Field := 16#0#;
-- Status bits, for reception transfers
STAT_RX : EPxR_STAT_RX_Field := 16#0#;
-- Data Toggle, for reception transfers
DTOG_RX : EPxR_DTOG_RX_Field := 16#0#;
-- Correct transfer for reception
CTR_RX : EPxR_CTR_RX_Field := 16#0#;
-- unspecified
Reserved_16_31 : STM32_SVD.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for EPxR_Register use record
EA at 0 range 0 .. 3;
STAT_TX at 0 range 4 .. 5;
DTOG_TX at 0 range 6 .. 6;
CTR_TX at 0 range 7 .. 7;
EP_KIND at 0 range 8 .. 8;
EP_TYPE at 0 range 9 .. 10;
SETUP at 0 range 11 .. 11;
STAT_RX at 0 range 12 .. 13;
DTOG_RX at 0 range 14 .. 14;
CTR_RX at 0 range 15 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
type EP_Status is (Disabled, Stall, NAK, Valid);
for EP_Status use (Disabled => 0, Stall => 1, NAK => 2, Valid => 3);
type EP_Type is (Bulk, Control, Iso, Interrupt);
for EP_Type use (Bulk => 0, Control => 1, Iso => 2, Interrupt => 3);
type Endpoint_Range is range 0 .. 7;
type Endpoint_Array_Type is array (Endpoint_Range) of EPxR_Register;
USB_Endpoints : aliased Endpoint_Array_Type
with Import, Address => System'To_Address (16#40005C00#);
function EP_Unused_Reset (BTable_Offset : Integer) return Integer;
procedure EP_Unused_Handler (Out_Transaction : Boolean);
procedure Set_TX_Status (EP : Endpoint_Range; Status : EP_Status);
procedure Set_RX_Status (EP : Endpoint_Range; Status : EP_Status);
procedure Set_TX_RX_Status (EP : Endpoint_Range; TX_Status : EP_Status; RX_Status : EP_Status);
-----------------------------------------------------------------------------
-- Buffer table types and operations
-----------------------------------------------------------------------------
subtype USB_ADDRx_TX is STM32_SVD.UInt16
with Dynamic_Predicate => USB_ADDRx_TX mod 2 = 0;
subtype USB_ADDRx_RX is STM32_SVD.UInt16
with Dynamic_Predicate => USB_ADDRx_RX mod 2 = 0;
subtype USB_COUNTx_TX is STM32_SVD.UInt10;
type USB_COUNTx_RX is record
BL_SIZE : STM32_SVD.Bit := 16#0#;
NUM_BLOCKS : STM32_SVD.UInt5 := 16#0#;
COUNTx_RX : STM32_SVD.UInt10 := 16#0#;
end record;
for USB_COUNTx_RX use record
BL_SIZE at 0 range 15 .. 15;
NUM_BLOCKS at 0 range 10 .. 14;
COUNTx_RX at 0 range 0 .. 9;
end record;
type USB_BTABLE_Descriptor is record
Addr_TX : USB_ADDRx_TX := 16#0#;
Count_TX : USB_COUNTx_TX := 16#0#;
Addr_RX : USB_ADDRx_RX := 16#0#;
Count_RX : USB_COUNTx_RX;
end record;
for USB_BTABLE_Descriptor use record
Addr_TX at 0 range 0 .. 15;
Count_TX at 2 range 0 .. 15;
Addr_RX at 4 range 0 .. 15;
Count_RX at 6 range 0 .. 15;
end record;
pragma Warnings (Off, "bits of*unused");
for USB_BTABLE_Descriptor'Size use (4 * 2 + 4 * 2) * 8;
pragma Warnings (On, "bits of*unused");
type USB_BTABLE_Descriptor_Array is array (Endpoint_Range) of USB_BTABLE_Descriptor;
USB_BTABLE_Descriptors : aliased USB_BTABLE_Descriptor_Array
with Import, Address => System'To_Address (16#40006000#);
type USB_BTABLE_Type is array (0 .. 1023) of UInt16;
USB_BTABLE : aliased USB_BTABLE_Type
with Import, Address => System'To_Address (16#40006000#);
end STM32GD.USB;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Ada_2012;
with GNAT.Calendar;
package body USB is
package Libusb_1_0_Libusb_H is
function Libusb_Init (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1306
pragma Import (C, Libusb_Init, "libusb_init");
procedure Libusb_Exit (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1307
pragma Import (C, Libusb_Exit, "libusb_exit");
procedure Libusb_Set_Debug (Ctx : System.Address; Level : Int); -- /usr/include/libusb-1.0/libusb.h:1308
pragma Import (C, Libusb_Set_Debug, "libusb_set_debug");
function Libusb_Get_Version return access constant Version; -- /usr/include/libusb-1.0/libusb.h:1309
pragma Import (C, Libusb_Get_Version, "libusb_get_version");
function Libusb_Has_Capability (Capability : Interfaces.Unsigned_32) return Int; -- /usr/include/libusb-1.0/libusb.h:1310
pragma Import (C, Libusb_Has_Capability, "libusb_has_capability");
function Libusb_Error_Name (Errcode : Int) return Interfaces.C.Strings.Chars_Ptr; -- /usr/include/libusb-1.0/libusb.h:1311
pragma Import (C, Libusb_Error_Name, "libusb_error_name");
function Libusb_Setlocale (Locale : Interfaces.C.Strings.Chars_Ptr) return Int; -- /usr/include/libusb-1.0/libusb.h:1312
pragma Import (C, Libusb_Setlocale, "libusb_setlocale");
function Libusb_Strerror (Errcode : Error) return Interfaces.C.Strings.Chars_Ptr; -- /usr/include/libusb-1.0/libusb.h:1313
pragma Import (C, Libusb_Strerror, "libusb_strerror");
function Libusb_Get_Device_List (Ctx : System.Address; List : System.Address) return Size_T; -- /usr/include/libusb-1.0/libusb.h:1315
pragma Import (C, Libusb_Get_Device_List, "libusb_get_device_list");
procedure Libusb_Free_Device_List (List : System.Address; Unref_Devices : Int); -- /usr/include/libusb-1.0/libusb.h:1317
pragma Import (C, Libusb_Free_Device_List, "libusb_free_device_list");
function Libusb_Ref_Device (Dev : System.Address) return System.Address; -- /usr/include/libusb-1.0/libusb.h:1319
pragma Import (C, Libusb_Ref_Device, "libusb_ref_device");
procedure Libusb_Unref_Device (Dev : System.Address); -- /usr/include/libusb-1.0/libusb.h:1320
pragma Import (C, Libusb_Unref_Device, "libusb_unref_device");
function Libusb_Get_Configuration (Dev : System.Address; Config : access Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1322
pragma Import (C, Libusb_Get_Configuration, "libusb_get_configuration");
function Libusb_Get_Device_Descriptor (Dev : System.Address; Desc : access Device_Descriptor) return Int; -- /usr/include/libusb-1.0/libusb.h:1324
pragma Import (C, Libusb_Get_Device_Descriptor, "libusb_get_device_descriptor");
function Libusb_Get_Active_Config_Descriptor (Dev : System.Address; Config : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1326
pragma Import (C, Libusb_Get_Active_Config_Descriptor, "libusb_get_active_config_descriptor");
function Libusb_Get_Config_Descriptor
(Dev : System.Address;
Config_Index : Interfaces.Unsigned_8;
Config : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1328
pragma Import (C, Libusb_Get_Config_Descriptor, "libusb_get_config_descriptor");
function Libusb_Get_Config_Descriptor_By_Value
(Dev : System.Address;
BConfigurationValue : Interfaces.Unsigned_8;
Config : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1330
pragma Import (C, Libusb_Get_Config_Descriptor_By_Value, "libusb_get_config_descriptor_by_value");
procedure Libusb_Free_Config_Descriptor (Config : access Config_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1332
pragma Import (C, Libusb_Free_Config_Descriptor, "libusb_free_config_descriptor");
function Libusb_Get_Ss_Endpoint_Companion_Descriptor
(Ctx : System.Address;
Endpoint : access constant Endpoint_Descriptor;
Ep_Comp : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1334
pragma Import (C, Libusb_Get_Ss_Endpoint_Companion_Descriptor, "libusb_get_ss_endpoint_companion_descriptor");
procedure Libusb_Free_Ss_Endpoint_Companion_Descriptor (Ep_Comp : access Ss_Endpoint_Companion_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1338
pragma Import (C, Libusb_Free_Ss_Endpoint_Companion_Descriptor, "libusb_free_ss_endpoint_companion_descriptor");
function Libusb_Get_Bos_Descriptor (Dev_Handle : System.Address; Bos : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1340
pragma Import (C, Libusb_Get_Bos_Descriptor, "libusb_get_bos_descriptor");
procedure Libusb_Free_Bos_Descriptor (Bos : access Bos_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1342
pragma Import (C, Libusb_Free_Bos_Descriptor, "libusb_free_bos_descriptor");
function Libusb_Get_Usb_2_0_Extension_Descriptor
(Ctx : System.Address;
Dev_Cap : access Bos_Dev_Capability_Descriptor;
Usb_2_0_Extension : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1343
pragma Import (C, Libusb_Get_Usb_2_0_Extension_Descriptor, "libusb_get_usb_2_0_extension_descriptor");
procedure Libusb_Free_Usb_2_0_Extension_Descriptor (Usb_2_0_Extension : access Usb_2_0_Extension_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1347
pragma Import (C, Libusb_Free_Usb_2_0_Extension_Descriptor, "libusb_free_usb_2_0_extension_descriptor");
function Libusb_Get_Ss_Usb_Device_Capability_Descriptor
(Ctx : System.Address;
Dev_Cap : access Bos_Dev_Capability_Descriptor;
Ss_Usb_Device_Cap : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1349
pragma Import (C, Libusb_Get_Ss_Usb_Device_Capability_Descriptor, "libusb_get_ss_usb_device_capability_descriptor");
procedure Libusb_Free_Ss_Usb_Device_Capability_Descriptor (Ss_Usb_Device_Cap : access Ss_Usb_Device_Capability_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1353
pragma Import (C, Libusb_Free_Ss_Usb_Device_Capability_Descriptor, "libusb_free_ss_usb_device_capability_descriptor");
function Libusb_Get_Container_Id_Descriptor
(Ctx : System.Address;
Dev_Cap : access Bos_Dev_Capability_Descriptor;
Container_Id : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1355
pragma Import (C, Libusb_Get_Container_Id_Descriptor, "libusb_get_container_id_descriptor");
procedure Libusb_Free_Container_Id_Descriptor (Container_Id : access Container_Id_Descriptor); -- /usr/include/libusb-1.0/libusb.h:1358
pragma Import (C, Libusb_Free_Container_Id_Descriptor, "libusb_free_container_id_descriptor");
function Libusb_Get_Bus_Number (Dev : System.Address) return Interfaces.Unsigned_8; -- /usr/include/libusb-1.0/libusb.h:1360
pragma Import (C, Libusb_Get_Bus_Number, "libusb_get_bus_number");
function Libusb_Get_Port_Number (Dev : System.Address) return Interfaces.Unsigned_8; -- /usr/include/libusb-1.0/libusb.h:1361
pragma Import (C, Libusb_Get_Port_Number, "libusb_get_port_number");
function Libusb_Get_Port_Numbers
(Dev : System.Address;
Port_Numbers : access Interfaces.Unsigned_8;
Port_Numbers_Len : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1362
pragma Import (C, Libusb_Get_Port_Numbers, "libusb_get_port_numbers");
function Libusb_Get_Port_Path
(Ctx : System.Address;
Dev : System.Address;
Path : access Interfaces.Unsigned_8;
Path_Length : Interfaces.Unsigned_8) return Int; -- /usr/include/libusb-1.0/libusb.h:1364
pragma Import (C, Libusb_Get_Port_Path, "libusb_get_port_path");
function Libusb_Get_Parent (Dev : System.Address) return System.Address; -- /usr/include/libusb-1.0/libusb.h:1365
pragma Import (C, Libusb_Get_Parent, "libusb_get_parent");
function Libusb_Get_Device_Address (Dev : System.Address) return Interfaces.Unsigned_8; -- /usr/include/libusb-1.0/libusb.h:1366
pragma Import (C, Libusb_Get_Device_Address, "libusb_get_device_address");
function Libusb_Get_Device_Speed (Dev : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1367
pragma Import (C, Libusb_Get_Device_Speed, "libusb_get_device_speed");
function Libusb_Get_Max_Packet_Size (Dev : System.Address; Endpoint : Unsigned_Char) return Int; -- /usr/include/libusb-1.0/libusb.h:1368
pragma Import (C, Libusb_Get_Max_Packet_Size, "libusb_get_max_packet_size");
function Libusb_Get_Max_Iso_Packet_Size (Dev : System.Address; Endpoint : Unsigned_Char) return Int; -- /usr/include/libusb-1.0/libusb.h:1370
pragma Import (C, Libusb_Get_Max_Iso_Packet_Size, "libusb_get_max_iso_packet_size");
function Libusb_Open (Dev : System.Address; Dev_Handle : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1373
pragma Import (C, Libusb_Open, "libusb_open");
procedure Libusb_Close (Dev_Handle : System.Address); -- /usr/include/libusb-1.0/libusb.h:1374
pragma Import (C, Libusb_Close, "libusb_close");
function Libusb_Get_Device (Dev_Handle : System.Address) return System.Address; -- /usr/include/libusb-1.0/libusb.h:1375
pragma Import (C, Libusb_Get_Device, "libusb_get_device");
function Libusb_Set_Configuration (Dev_Handle : System.Address; Configuration : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1377
pragma Import (C, Libusb_Set_Configuration, "libusb_set_configuration");
function Libusb_Claim_Interface (Dev_Handle : System.Address; Interface_Number : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1379
pragma Import (C, Libusb_Claim_Interface, "libusb_claim_interface");
function Libusb_Release_Interface (Dev_Handle : System.Address; Interface_Number : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1381
pragma Import (C, Libusb_Release_Interface, "libusb_release_interface");
function Libusb_Open_Device_With_Vid_Pid
(Ctx : System.Address;
Vendor_Id : Interfaces.Unsigned_16;
Product_Id : Interfaces.Unsigned_16) return System.Address; -- /usr/include/libusb-1.0/libusb.h:1384
pragma Import (C, Libusb_Open_Device_With_Vid_Pid, "libusb_open_device_with_vid_pid");
function Libusb_Set_Interface_Alt_Setting
(Dev_Handle : System.Address;
Interface_Number : Int;
Alternate_Setting : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1387
pragma Import (C, Libusb_Set_Interface_Alt_Setting, "libusb_set_interface_alt_setting");
function Libusb_Clear_Halt (Dev_Handle : System.Address; Endpoint : Unsigned_Char) return Int; -- /usr/include/libusb-1.0/libusb.h:1389
pragma Import (C, Libusb_Clear_Halt, "libusb_clear_halt");
function Libusb_Reset_Device (Dev_Handle : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1391
pragma Import (C, Libusb_Reset_Device, "libusb_reset_device");
function Libusb_Alloc_Streams
(Dev_Handle : System.Address;
Num_Streams : Interfaces.Unsigned_32;
Endpoints : access Unsigned_Char;
Num_Endpoints : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1393
pragma Import (C, Libusb_Alloc_Streams, "libusb_alloc_streams");
function Libusb_Free_Streams
(Dev_Handle : System.Address;
Endpoints : access Unsigned_Char;
Num_Endpoints : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1395
pragma Import (C, Libusb_Free_Streams, "libusb_free_streams");
function Libusb_Dev_Mem_Alloc (Dev_Handle : System.Address; Length : Size_T) return access Unsigned_Char; -- /usr/include/libusb-1.0/libusb.h:1398
pragma Import (C, Libusb_Dev_Mem_Alloc, "libusb_dev_mem_alloc");
function Libusb_Dev_Mem_Free
(Dev_Handle : System.Address;
Buffer : access Unsigned_Char;
Length : Size_T) return Int; -- /usr/include/libusb-1.0/libusb.h:1400
pragma Import (C, Libusb_Dev_Mem_Free, "libusb_dev_mem_free");
function Libusb_Kernel_Driver_Active (Dev_Handle : System.Address; Interface_Number : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1403
pragma Import (C, Libusb_Kernel_Driver_Active, "libusb_kernel_driver_active");
function Libusb_Detach_Kernel_Driver (Dev_Handle : System.Address; Interface_Number : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1405
pragma Import (C, Libusb_Detach_Kernel_Driver, "libusb_detach_kernel_driver");
function Libusb_Attach_Kernel_Driver (Dev_Handle : System.Address; Interface_Number : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1407
pragma Import (C, Libusb_Attach_Kernel_Driver, "libusb_attach_kernel_driver");
function Libusb_Set_Auto_Detach_Kernel_Driver (Dev_Handle : System.Address; Enable : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1409
pragma Import (C, Libusb_Set_Auto_Detach_Kernel_Driver, "libusb_set_auto_detach_kernel_driver");
function Libusb_Control_Transfer_Get_Data (T : access Transfer) return access Unsigned_Char; -- /usr/include/libusb-1.0/libusb.h:1426
pragma Import (C, Libusb_Control_Transfer_Get_Data, "libusb_control_transfer_get_data");
function Libusb_Control_Transfer_Get_Setup (T : access Transfer) return access Control_Setup; -- /usr/include/libusb-1.0/libusb.h:1444
pragma Import (C, Libusb_Control_Transfer_Get_Setup, "libusb_control_transfer_get_setup");
procedure Libusb_Fill_Control_Setup
(Buffer : access Unsigned_Char;
BmRequestType : Interfaces.Unsigned_8;
BRequest : Interfaces.Unsigned_8;
WValue : Interfaces.Unsigned_16;
WIndex : Interfaces.Unsigned_16;
WLength : Interfaces.Unsigned_16); -- /usr/include/libusb-1.0/libusb.h:1473
pragma Import (C, Libusb_Fill_Control_Setup, "libusb_fill_control_setup");
function Libusb_Alloc_Transfer (Iso_Packets : Int) return access Transfer; -- /usr/include/libusb-1.0/libusb.h:1485
pragma Import (C, Libusb_Alloc_Transfer, "libusb_alloc_transfer");
function Libusb_Submit_Transfer (T : access Transfer) return Int; -- /usr/include/libusb-1.0/libusb.h:1486
pragma Import (C, Libusb_Submit_Transfer, "libusb_submit_transfer");
function Libusb_Cancel_Transfer (T : access Transfer) return Int; -- /usr/include/libusb-1.0/libusb.h:1487
pragma Import (C, Libusb_Cancel_Transfer, "libusb_cancel_transfer");
procedure Libusb_Free_Transfer (T : access Transfer); -- /usr/include/libusb-1.0/libusb.h:1488
pragma Import (C, Libusb_Free_Transfer, "libusb_free_transfer");
procedure Libusb_Transfer_Set_Stream_Id (T : access Transfer; Stream_Id : Interfaces.Unsigned_32); -- /usr/include/libusb-1.0/libusb.h:1489
pragma Import (C, Libusb_Transfer_Set_Stream_Id, "libusb_transfer_set_stream_id");
function Libusb_Transfer_Get_Stream_Id (T : access Transfer) return Interfaces.Unsigned_32; -- /usr/include/libusb-1.0/libusb.h:1491
pragma Import (C, Libusb_Transfer_Get_Stream_Id, "libusb_transfer_get_stream_id");
procedure Libusb_Fill_Control_Transfer
(T : access Transfer;
Dev_Handle : System.Address;
Buffer : access Unsigned_Char;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1522
pragma Import (C, Libusb_Fill_Control_Transfer, "libusb_fill_control_transfer");
procedure Libusb_Fill_Bulk_Transfer
(T : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1553
pragma Import (C, Libusb_Fill_Bulk_Transfer, "libusb_fill_bulk_transfer");
procedure Libusb_Fill_Bulk_Stream_Transfer
(T : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Stream_Id : Interfaces.Unsigned_32;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1584
pragma Import (C, Libusb_Fill_Bulk_Stream_Transfer, "libusb_fill_bulk_stream_transfer");
procedure Libusb_Fill_Interrupt_Transfer
(T : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1609
pragma Import (C, Libusb_Fill_Interrupt_Transfer, "libusb_fill_interrupt_transfer");
procedure Libusb_Fill_Iso_Transfer
(T : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Num_Iso_Packets : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1638
pragma Import (C, Libusb_Fill_Iso_Transfer, "libusb_fill_iso_transfer");
procedure Libusb_Set_Iso_Packet_Lengths (T : access Transfer; Length : Unsigned); -- /usr/include/libusb-1.0/libusb.h:1662
pragma Import (C, Libusb_Set_Iso_Packet_Lengths, "libusb_set_iso_packet_lengths");
function Libusb_Get_Iso_Packet_Buffer (T : access Transfer; Packet : Unsigned) return access Unsigned_Char; -- /usr/include/libusb-1.0/libusb.h:1686
pragma Import (C, Libusb_Get_Iso_Packet_Buffer, "libusb_get_iso_packet_buffer");
function Libusb_Get_Iso_Packet_Buffer_Simple (T : access Transfer; Packet : Unsigned) return access Unsigned_Char; -- /usr/include/libusb-1.0/libusb.h:1728
pragma Import (C, Libusb_Get_Iso_Packet_Buffer_Simple, "libusb_get_iso_packet_buffer_simple");
function Libusb_Control_Transfer
(Dev_Handle : System.Address;
Request_Type : Interfaces.Unsigned_8;
BRequest : Interfaces.Unsigned_8;
WValue : Interfaces.Unsigned_16;
WIndex : Interfaces.Unsigned_16;
Data : access Unsigned_Char;
WLength : Interfaces.Unsigned_16;
Timeout : Unsigned) return Int; -- /usr/include/libusb-1.0/libusb.h:1748
pragma Import (C, Libusb_Control_Transfer, "libusb_control_transfer");
function Libusb_Bulk_Transfer
(Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Data : access Unsigned_Char;
Length : Int;
Actual_Length : access Int;
Timeout : Unsigned) return Int; -- /usr/include/libusb-1.0/libusb.h:1752
pragma Import (C, Libusb_Bulk_Transfer, "libusb_bulk_transfer");
function Libusb_Interrupt_Transfer
(Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Data : access Unsigned_Char;
Length : Int;
Actual_Length : access Int;
Timeout : Unsigned) return Int; -- /usr/include/libusb-1.0/libusb.h:1756
pragma Import (C, Libusb_Interrupt_Transfer, "libusb_interrupt_transfer");
function Libusb_Get_Descriptor
(Dev_Handle : System.Address;
Desc_Type : Interfaces.Unsigned_8;
Desc_Index : Interfaces.Unsigned_8;
Data : access Unsigned_Char;
Length : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1772
pragma Import (C, Libusb_Get_Descriptor, "libusb_get_descriptor");
function Libusb_Get_String_Descriptor
(Dev_Handle : System.Address;
Desc_Index : Interfaces.Unsigned_8;
Langid : Interfaces.Unsigned_16;
Data : access Unsigned_Char;
Length : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1794
pragma Import (C, Libusb_Get_String_Descriptor, "libusb_get_string_descriptor");
function Libusb_Get_String_Descriptor_Ascii
(Dev_Handle : System.Address;
Desc_Index : Interfaces.Unsigned_8;
Data : access Unsigned_Char;
Length : Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1802
pragma Import (C, Libusb_Get_String_Descriptor_Ascii, "libusb_get_string_descriptor_ascii");
function Libusb_Try_Lock_Events (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1807
pragma Import (C, Libusb_Try_Lock_Events, "libusb_try_lock_events");
procedure Libusb_Lock_Events (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1808
pragma Import (C, Libusb_Lock_Events, "libusb_lock_events");
procedure Libusb_Unlock_Events (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1809
pragma Import (C, Libusb_Unlock_Events, "libusb_unlock_events");
function Libusb_Event_Handling_Ok (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1810
pragma Import (C, Libusb_Event_Handling_Ok, "libusb_event_handling_ok");
function Libusb_Event_Handler_Active (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1811
pragma Import (C, Libusb_Event_Handler_Active, "libusb_event_handler_active");
procedure Libusb_Interrupt_Event_Handler (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1812
pragma Import (C, Libusb_Interrupt_Event_Handler, "libusb_interrupt_event_handler");
procedure Libusb_Lock_Event_Waiters (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1813
pragma Import (C, Libusb_Lock_Event_Waiters, "libusb_lock_event_waiters");
procedure Libusb_Unlock_Event_Waiters (Ctx : System.Address); -- /usr/include/libusb-1.0/libusb.h:1814
pragma Import (C, Libusb_Unlock_Event_Waiters, "libusb_unlock_event_waiters");
function Libusb_Wait_For_Event (Ctx : System.Address; Tv : access GNAT.Calendar.Timeval) return Int; -- /usr/include/libusb-1.0/libusb.h:1815
pragma Import (C, Libusb_Wait_For_Event, "libusb_wait_for_event");
function Libusb_Handle_Events_Timeout (Ctx : System.Address; Tv : access GNAT.Calendar.Timeval) return Int; -- /usr/include/libusb-1.0/libusb.h:1817
pragma Import (C, Libusb_Handle_Events_Timeout, "libusb_handle_events_timeout");
function Libusb_Handle_Events_Timeout_Completed
(Ctx : System.Address;
Tv : access GNAT.Calendar.Timeval;
Completed : access Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1819
pragma Import (C, Libusb_Handle_Events_Timeout_Completed, "libusb_handle_events_timeout_completed");
function Libusb_Handle_Events (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1821
pragma Import (C, Libusb_Handle_Events, "libusb_handle_events");
function Libusb_Handle_Events_Completed (Ctx : System.Address; Completed : access Int) return Int; -- /usr/include/libusb-1.0/libusb.h:1822
pragma Import (C, Libusb_Handle_Events_Completed, "libusb_handle_events_completed");
function Libusb_Handle_Events_Locked (Ctx : System.Address; Tv : access GNAT.Calendar.Timeval) return Int; -- /usr/include/libusb-1.0/libusb.h:1823
pragma Import (C, Libusb_Handle_Events_Locked, "libusb_handle_events_locked");
function Libusb_Pollfds_Handle_Timeouts (Ctx : System.Address) return Int; -- /usr/include/libusb-1.0/libusb.h:1825
pragma Import (C, Libusb_Pollfds_Handle_Timeouts, "libusb_pollfds_handle_timeouts");
function Libusb_Get_Next_Timeout (Ctx : System.Address; Tv : access GNAT.Calendar.Timeval) return Int; -- /usr/include/libusb-1.0/libusb.h:1826
pragma Import (C, Libusb_Get_Next_Timeout, "libusb_get_next_timeout");
type Libusb_Pollfd is record
Fd : aliased Int; -- /usr/include/libusb-1.0/libusb.h:1834
Events : aliased Short; -- /usr/include/libusb-1.0/libusb.h:1840
end record;
pragma Convention (C_Pass_By_Copy, Libusb_Pollfd); -- /usr/include/libusb-1.0/libusb.h:1832
type Libusb_Pollfd_Added_Cb is access procedure
(Arg1 : Int;
Arg2 : Short;
Arg3 : System.Address);
pragma Convention (C, Libusb_Pollfd_Added_Cb); -- /usr/include/libusb-1.0/libusb.h:1853
type Libusb_Pollfd_Removed_Cb is access procedure (Arg1 : Int; Arg2 : System.Address);
pragma Convention (C, Libusb_Pollfd_Removed_Cb); -- /usr/include/libusb-1.0/libusb.h:1865
function Libusb_Get_Pollfds (Ctx : System.Address) return System.Address; -- /usr/include/libusb-1.0/libusb.h:1867
pragma Import (C, Libusb_Get_Pollfds, "libusb_get_pollfds");
procedure Libusb_Free_Pollfds (Pollfds : System.Address); -- /usr/include/libusb-1.0/libusb.h:1869
pragma Import (C, Libusb_Free_Pollfds, "libusb_free_pollfds");
procedure Libusb_Set_Pollfd_Notifiers
(Ctx : System.Address;
Added_Cb : Libusb_Pollfd_Added_Cb;
Removed_Cb : Libusb_Pollfd_Removed_Cb;
User_Data : System.Address); -- /usr/include/libusb-1.0/libusb.h:1870
pragma Import (C, Libusb_Set_Pollfd_Notifiers, "libusb_set_pollfd_notifiers");
subtype Libusb_Hotplug_Callback_Handle is Int; -- /usr/include/libusb-1.0/libusb.h:1886
type Libusb_Hotplug_Flag is
(LIBUSB_HOTPLUG_NO_FLAGS,
LIBUSB_HOTPLUG_ENUMERATE);
pragma Convention (C, Libusb_Hotplug_Flag); -- /usr/include/libusb-1.0/libusb.h:1899
subtype Libusb_Hotplug_Event is Unsigned;
LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED : constant Libusb_Hotplug_Event := 1;
LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT : constant Libusb_Hotplug_Event := 2; -- /usr/include/libusb-1.0/libusb.h:1914
type Libusb_Hotplug_Callback_Fn is access function
(Arg1 : System.Address;
Arg2 : System.Address;
Arg3 : Libusb_Hotplug_Event;
Arg4 : System.Address) return Int;
pragma Convention (C, Libusb_Hotplug_Callback_Fn); -- /usr/include/libusb-1.0/libusb.h:1942
function Libusb_Hotplug_Register_Callback
(Ctx : System.Address;
Events : Libusb_Hotplug_Event;
Flags : Libusb_Hotplug_Flag;
Vendor_Id : Int;
Product_Id : Int;
Dev_Class : Int;
Cb_Fn : Libusb_Hotplug_Callback_Fn;
User_Data : System.Address;
Callback_Handle : access Hotplug_Callback_Handle) return Int; -- /usr/include/libusb-1.0/libusb.h:1981
pragma Import (C, Libusb_Hotplug_Register_Callback, "libusb_hotplug_register_callback");
procedure Libusb_Hotplug_Deregister_Callback (Ctx : System.Address; Callback_Handle : Libusb_Hotplug_Callback_Handle); -- /usr/include/libusb-1.0/libusb.h:2001
pragma Import (C, Libusb_Hotplug_Deregister_Callback, "libusb_hotplug_deregister_callback");
end Libusb_1_0_Libusb_H;
-----------------
-- cpu_to_le16 --
-----------------
use Libusb_1_0_Libusb_H;
function Cpu_To_Le16
(X : Interfaces.Unsigned_16)
return Interfaces.Unsigned_16
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Libusb_1_0_Libusb_H unimplemented");
return raise Program_Error with "Unimplemented procedure Libusb_1_0_Libusb_H";
end Cpu_To_Le16;
procedure Initialize (Ctx : in out Context) is
begin
Ret2exception (Libusb_Init (Ctx.Ctx'Address));
end;
procedure Finalize (Ctx : in out Context) is
begin
Libusb_Exit (Ctx.Ctx);
end;
---------------
-- set_debug --
---------------
procedure Set_Debug (Ctx : Context; Level : Int) is
begin
Libusb_Set_Debug (Ctx.Ctx, Level);
end Set_Debug;
-----------------
-- get_version --
-----------------
function Get_Version return access constant Version is
begin
return Libusb_Get_Version;
end Get_Version;
--------------------
-- has_capability --
--------------------
function Has_Capability (Capability : Interfaces.Unsigned_32) return Int is
begin
return Libusb_Has_Capability(Capability);
end Has_Capability;
----------------
-- error_name --
----------------
function Error_Name
(Errcode : Int)
return Interfaces.C.Strings.Chars_Ptr
is
begin
return Libusb_Error_Name (Errcode);
end Error_Name;
---------------
-- setlocale --
---------------
procedure Setlocale (Locale : Interfaces.C.Strings.Chars_Ptr) is
begin
Ret2exception (Libusb_Setlocale (Locale));
end Setlocale;
--------------
-- strerror --
--------------
function Strerror
(Errcode : Error)
return Interfaces.C.Strings.Chars_Ptr
is
begin
return Libusb_Strerror (Errcode);
end Strerror;
---------------------
-- get_device_list --
---------------------
function Get_Device_List
(Ctx : Context'Class) return Device_List
is
begin
return ret : Device_List do
Ret.Len := Libusb_Get_Device_List (Ctx.Ctx, Ret.List'Address);
end return;
end Get_Device_List;
----------------------
-- free_device_list --
----------------------
procedure Free_Device_List (list : Device_Access; unref_devices : int) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_device_list unimplemented");
raise Program_Error with "Unimplemented procedure free_device_list";
end Free_Device_List;
----------------
-- ref_device --
----------------
function Ref_Device (dev : Device_Access) return Device_Access is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "ref_device unimplemented");
return raise Program_Error with "Unimplemented function ref_device";
end Ref_Device;
------------------
-- unref_device --
------------------
procedure Unref_Device (Dev : System.Address) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "unref_device unimplemented");
raise Program_Error with "Unimplemented procedure unref_device";
end Unref_Device;
-----------------------
-- get_configuration --
-----------------------
function Get_Configuration
(Dev : System.Address;
Config : access Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_configuration unimplemented");
return raise Program_Error with "Unimplemented function get_configuration";
end Get_Configuration;
---------------------------
-- get_device_descriptor --
---------------------------
function Get_Device_Descriptor
(Dev : System.Address;
Desc : access Device_Descriptor)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_device_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_device_descriptor";
end Get_Device_Descriptor;
----------------------------------
-- get_active_config_descriptor --
----------------------------------
function Get_Active_Config_Descriptor
(Dev : System.Address;
Config : System.Address)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_active_config_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_active_config_descriptor";
end Get_Active_Config_Descriptor;
---------------------------
-- get_config_descriptor --
---------------------------
function Get_Config_Descriptor
(Dev : System.Address;
Config_Index : Interfaces.Unsigned_8;
Config : System.Address)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_config_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_config_descriptor";
end Get_Config_Descriptor;
------------------------------------
-- get_config_descriptor_by_value --
------------------------------------
function Get_Config_Descriptor_By_Value
(Dev : System.Address;
BConfigurationValue : Interfaces.Unsigned_8;
Config : System.Address)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_config_descriptor_by_value unimplemented");
return raise Program_Error with "Unimplemented function get_config_descriptor_by_value";
end Get_Config_Descriptor_By_Value;
----------------------------
-- free_config_descriptor --
----------------------------
procedure Free_Config_Descriptor (Config : access Config_Descriptor) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_config_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_config_descriptor";
end Free_Config_Descriptor;
------------------------------------------
-- get_ss_endpoint_companion_descriptor --
------------------------------------------
function Get_Ss_Endpoint_Companion_Descriptor
(ctx : context;
endpoint : access constant endpoint_descriptor;
ep_comp : System.Address) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_ss_endpoint_companion_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_ss_endpoint_companion_descriptor";
end Get_Ss_Endpoint_Companion_Descriptor;
-------------------------------------------
-- free_ss_endpoint_companion_descriptor --
-------------------------------------------
procedure Free_Ss_Endpoint_Companion_Descriptor
(Ep_Comp : access Ss_Endpoint_Companion_Descriptor)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_ss_endpoint_companion_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_ss_endpoint_companion_descriptor";
end Free_Ss_Endpoint_Companion_Descriptor;
------------------------
-- get_bos_descriptor --
------------------------
function Get_Bos_Descriptor
(Dev_Handle : System.Address;
Bos : System.Address)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_bos_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_bos_descriptor";
end Get_Bos_Descriptor;
-------------------------
-- free_bos_descriptor --
-------------------------
procedure Free_Bos_Descriptor (Bos : access Bos_Descriptor) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_bos_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_bos_descriptor";
end Free_Bos_Descriptor;
--------------------------------------
-- get_usb_2_0_extension_descriptor --
--------------------------------------
function Get_Usb_2_0_Extension_Descriptor
(ctx : context;
dev_cap : access bos_dev_capability_descriptor;
usb_2_0_extension : System.Address) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_usb_2_0_extension_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_usb_2_0_extension_descriptor";
end Get_Usb_2_0_Extension_Descriptor;
---------------------------------------
-- free_usb_2_0_extension_descriptor --
---------------------------------------
procedure Free_Usb_2_0_Extension_Descriptor
(Usb_2_0_Extension : access Usb_2_0_Extension_Descriptor)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_usb_2_0_extension_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_usb_2_0_extension_descriptor";
end Free_Usb_2_0_Extension_Descriptor;
---------------------------------------------
-- get_ss_usb_device_capability_descriptor --
---------------------------------------------
function Get_Ss_Usb_Device_Capability_Descriptor
(ctx : context;
dev_cap : access bos_dev_capability_descriptor;
ss_usb_device_cap : System.Address) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_ss_usb_device_capability_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_ss_usb_device_capability_descriptor";
end Get_Ss_Usb_Device_Capability_Descriptor;
----------------------------------------------
-- free_ss_usb_device_capability_descriptor --
----------------------------------------------
procedure Free_Ss_Usb_Device_Capability_Descriptor
(Ss_Usb_Device_Cap : access Ss_Usb_Device_Capability_Descriptor)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_ss_usb_device_capability_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_ss_usb_device_capability_descriptor";
end Free_Ss_Usb_Device_Capability_Descriptor;
---------------------------------
-- get_container_id_descriptor --
---------------------------------
function Get_Container_Id_Descriptor
(ctx : context;
dev_cap : access bos_dev_capability_descriptor;
container_id : System.Address) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_container_id_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_container_id_descriptor";
end Get_Container_Id_Descriptor;
----------------------------------
-- free_container_id_descriptor --
----------------------------------
procedure Free_Container_Id_Descriptor
(Container_Id : access Container_Id_Descriptor)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_container_id_descriptor unimplemented");
raise Program_Error with "Unimplemented procedure free_container_id_descriptor";
end Free_Container_Id_Descriptor;
--------------------
-- get_bus_number --
--------------------
function Get_Bus_Number
(Dev : System.Address)
return Interfaces.Unsigned_8
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_bus_number unimplemented");
return raise Program_Error with "Unimplemented function get_bus_number";
end Get_Bus_Number;
---------------------
-- get_port_number --
---------------------
function Get_Port_Number
(Dev : System.Address)
return Interfaces.Unsigned_8
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_port_number unimplemented");
return raise Program_Error with "Unimplemented function get_port_number";
end Get_Port_Number;
----------------------
-- get_port_numbers --
----------------------
function Get_Port_Numbers
(Dev : System.Address;
Port_Numbers : access Interfaces.Unsigned_8;
Port_Numbers_Len : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_port_numbers unimplemented");
return raise Program_Error with "Unimplemented function get_port_numbers";
end Get_Port_Numbers;
-------------------
-- get_port_path --
-------------------
function Get_Port_Path
(ctx : context;
dev : System.Address;
path : access Interfaces.Unsigned_8;
path_length : Interfaces.Unsigned_8) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_port_path unimplemented");
return raise Program_Error with "Unimplemented function get_port_path";
end Get_Port_Path;
----------------
-- get_parent --
----------------
function Get_Parent (Dev : System.Address) return System.Address is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_parent unimplemented");
return raise Program_Error with "Unimplemented function get_parent";
end Get_Parent;
------------------------
-- get_device_address --
------------------------
function Get_Device_Address
(Dev : System.Address)
return Interfaces.Unsigned_8
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_device_address unimplemented");
return raise Program_Error with "Unimplemented function get_device_address";
end Get_Device_Address;
----------------------
-- get_device_speed --
----------------------
function Get_Device_Speed (Dev : System.Address) return Int is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_device_speed unimplemented");
return raise Program_Error with "Unimplemented function get_device_speed";
end Get_Device_Speed;
-------------------------
-- get_max_packet_size --
-------------------------
function Get_Max_Packet_Size
(Dev : System.Address;
Endpoint : Unsigned_Char)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_max_packet_size unimplemented");
return raise Program_Error with "Unimplemented function get_max_packet_size";
end Get_Max_Packet_Size;
-----------------------------
-- get_max_iso_packet_size --
-----------------------------
function Get_Max_Iso_Packet_Size
(Dev : System.Address;
Endpoint : Unsigned_Char)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_max_iso_packet_size unimplemented");
return raise Program_Error with "Unimplemented function get_max_iso_packet_size";
end Get_Max_Iso_Packet_Size;
----------
-- open --
----------
function Open
(Dev : System.Address;
Dev_Handle : System.Address)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "open unimplemented");
return raise Program_Error with "Unimplemented function open";
end Open;
-----------
-- close --
-----------
procedure Close (Dev_Handle : System.Address) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "close unimplemented");
raise Program_Error with "Unimplemented procedure close";
end Close;
----------------
-- get_device --
----------------
function Get_Device (Dev_Handle : System.Address) return System.Address is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_device unimplemented");
return raise Program_Error with "Unimplemented function get_device";
end Get_Device;
-----------------------
-- set_configuration --
-----------------------
function Set_Configuration
(Dev_Handle : System.Address;
Configuration : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "set_configuration unimplemented");
return raise Program_Error with "Unimplemented function set_configuration";
end Set_Configuration;
---------------------
-- claim_interface --
---------------------
function Claim_Interface
(Dev_Handle : System.Address;
Interface_Number : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "claim_interface unimplemented");
return raise Program_Error with "Unimplemented function claim_interface";
end Claim_Interface;
-----------------------
-- release_interface --
-----------------------
function Release_Interface
(Dev_Handle : System.Address;
Interface_Number : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "release_interface unimplemented");
return raise Program_Error with "Unimplemented function release_interface";
end Release_Interface;
------------------------------
-- open_device_with_vid_pid --
------------------------------
function Open_Device_With_Vid_Pid
(ctx : context;
vendor_id : Interfaces.Unsigned_16;
product_id : Interfaces.Unsigned_16) return System.Address
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "open_device_with_vid_pid unimplemented");
return raise Program_Error with "Unimplemented function open_device_with_vid_pid";
end Open_Device_With_Vid_Pid;
-------------------------------
-- set_interface_alt_setting --
-------------------------------
function Set_Interface_Alt_Setting
(Dev_Handle : System.Address;
Interface_Number : Int;
Alternate_Setting : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "set_interface_alt_setting unimplemented");
return raise Program_Error with "Unimplemented function set_interface_alt_setting";
end Set_Interface_Alt_Setting;
----------------
-- clear_halt --
----------------
function Clear_Halt
(Dev_Handle : System.Address;
Endpoint : Unsigned_Char)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "clear_halt unimplemented");
return raise Program_Error with "Unimplemented function clear_halt";
end Clear_Halt;
------------------
-- reset_device --
------------------
function Reset_Device (Dev_Handle : System.Address) return Int is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "reset_device unimplemented");
return raise Program_Error with "Unimplemented function reset_device";
end Reset_Device;
-------------------
-- alloc_streams --
-------------------
function Alloc_Streams
(Dev_Handle : System.Address;
Num_Streams : Interfaces.Unsigned_32;
Endpoints : access Unsigned_Char;
Num_Endpoints : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "alloc_streams unimplemented");
return raise Program_Error with "Unimplemented function alloc_streams";
end Alloc_Streams;
------------------
-- free_streams --
------------------
function Free_Streams
(Dev_Handle : System.Address;
Endpoints : access Unsigned_Char;
Num_Endpoints : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_streams unimplemented");
return raise Program_Error with "Unimplemented function free_streams";
end Free_Streams;
-------------------
-- dev_mem_alloc --
-------------------
function Dev_Mem_Alloc
(Dev_Handle : System.Address;
Length : Size_T)
return access Unsigned_Char
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "dev_mem_alloc unimplemented");
return raise Program_Error with "Unimplemented function dev_mem_alloc";
end Dev_Mem_Alloc;
------------------
-- dev_mem_free --
------------------
function Dev_Mem_Free
(Dev_Handle : System.Address;
Buffer : access Unsigned_Char;
Length : Size_T)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "dev_mem_free unimplemented");
return raise Program_Error with "Unimplemented function dev_mem_free";
end Dev_Mem_Free;
--------------------------
-- kernel_driver_active --
--------------------------
function Kernel_Driver_Active
(Dev_Handle : System.Address;
Interface_Number : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "kernel_driver_active unimplemented");
return raise Program_Error with "Unimplemented function kernel_driver_active";
end Kernel_Driver_Active;
--------------------------
-- detach_kernel_driver --
--------------------------
function Detach_Kernel_Driver
(Dev_Handle : System.Address;
Interface_Number : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "detach_kernel_driver unimplemented");
return raise Program_Error with "Unimplemented function detach_kernel_driver";
end Detach_Kernel_Driver;
--------------------------
-- attach_kernel_driver --
--------------------------
function Attach_Kernel_Driver
(Dev_Handle : System.Address;
Interface_Number : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "attach_kernel_driver unimplemented");
return raise Program_Error with "Unimplemented function attach_kernel_driver";
end Attach_Kernel_Driver;
-----------------------------------
-- set_auto_detach_kernel_driver --
-----------------------------------
function Set_Auto_Detach_Kernel_Driver
(Dev_Handle : System.Address;
Enable : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "set_auto_detach_kernel_driver unimplemented");
return raise Program_Error with "Unimplemented function set_auto_detach_kernel_driver";
end Set_Auto_Detach_Kernel_Driver;
-------------------------------
-- control_transfer_get_data --
-------------------------------
function Control_Transfer_Get_Data
(Transfe : access Transfer)
return access Unsigned_Char
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "control_transfer_get_data unimplemented");
return raise Program_Error with "Unimplemented function control_transfer_get_data";
end Control_Transfer_Get_Data;
--------------------------------
-- control_transfer_get_setup --
--------------------------------
function Control_Transfer_Get_Setup
(Transfe : access Transfer)
return access Control_Setup
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "control_transfer_get_setup unimplemented");
return raise Program_Error with "Unimplemented function control_transfer_get_setup";
end Control_Transfer_Get_Setup;
------------------------
-- fill_control_setup --
------------------------
procedure Fill_Control_Setup
(Buffer : access Unsigned_Char;
BmRequestType : Interfaces.Unsigned_8;
BRequest : Interfaces.Unsigned_8;
WValue : Interfaces.Unsigned_16;
WIndex : Interfaces.Unsigned_16;
WLength : Interfaces.Unsigned_16)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_control_setup unimplemented");
raise Program_Error with "Unimplemented procedure fill_control_setup";
end Fill_Control_Setup;
--------------------
-- alloc_transfer --
--------------------
function Alloc_Transfer (Iso_Packets : Int) return access Transfer is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "alloc_transfer unimplemented");
return raise Program_Error with "Unimplemented function alloc_transfer";
end Alloc_Transfer;
---------------------
-- submit_transfer --
---------------------
function Submit_Transfer (Transfe : access Transfer) return Int is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "submit_transfer unimplemented");
return raise Program_Error with "Unimplemented function submit_transfer";
end Submit_Transfer;
---------------------
-- cancel_transfer --
---------------------
function Cancel_Transfer (Transfe : access Transfer) return Int is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "cancel_transfer unimplemented");
return raise Program_Error with "Unimplemented function cancel_transfer";
end Cancel_Transfer;
-------------------
-- free_transfer --
-------------------
procedure Free_Transfer (Transfe : access Transfer) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "free_transfer unimplemented");
raise Program_Error with "Unimplemented procedure free_transfer";
end Free_Transfer;
----------------------------
-- transfer_set_stream_id --
----------------------------
procedure Transfer_Set_Stream_Id
(Transfe : access Transfer;
Stream_Id : Interfaces.Unsigned_32)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "transfer_set_stream_id unimplemented");
raise Program_Error with "Unimplemented procedure transfer_set_stream_id";
end Transfer_Set_Stream_Id;
----------------------------
-- transfer_get_stream_id --
----------------------------
function Transfer_Get_Stream_Id
(Transfe : access Transfer)
return Interfaces.Unsigned_32
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "transfer_get_stream_id unimplemented");
return raise Program_Error with "Unimplemented function transfer_get_stream_id";
end Transfer_Get_Stream_Id;
---------------------------
-- fill_control_transfer --
---------------------------
procedure Fill_Control_Transfer
(Transfe : access Transfer;
Dev_Handle : System.Address;
Buffer : access Unsigned_Char;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_control_transfer unimplemented");
raise Program_Error with "Unimplemented procedure fill_control_transfer";
end Fill_Control_Transfer;
------------------------
-- fill_bulk_transfer --
------------------------
procedure Fill_Bulk_Transfer
(Transfe : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_bulk_transfer unimplemented");
raise Program_Error with "Unimplemented procedure fill_bulk_transfer";
end Fill_Bulk_Transfer;
-------------------------------
-- fill_bulk_stream_transfer --
-------------------------------
procedure Fill_Bulk_Stream_Transfer
(Transfe : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Stream_Id : Interfaces.Unsigned_32;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_bulk_stream_transfer unimplemented");
raise Program_Error with "Unimplemented procedure fill_bulk_stream_transfer";
end Fill_Bulk_Stream_Transfer;
-----------------------------
-- fill_interrupt_transfer --
-----------------------------
procedure Fill_Interrupt_Transfer
(Transfe : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_interrupt_transfer unimplemented");
raise Program_Error with "Unimplemented procedure fill_interrupt_transfer";
end Fill_Interrupt_Transfer;
-----------------------
-- fill_iso_transfer --
-----------------------
procedure Fill_Iso_Transfer
(Transfe : access Transfer;
Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Buffer : access Unsigned_Char;
Length : Int;
Num_Iso_Packets : Int;
Callback : Transfer_Cb_Fn;
User_Data : System.Address;
Timeout : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "fill_iso_transfer unimplemented");
raise Program_Error with "Unimplemented procedure fill_iso_transfer";
end Fill_Iso_Transfer;
----------------------------
-- set_iso_packet_lengths --
----------------------------
procedure Set_Iso_Packet_Lengths
(Transfe : access Transfer;
Length : Unsigned)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "set_iso_packet_lengths unimplemented");
raise Program_Error with "Unimplemented procedure set_iso_packet_lengths";
end Set_Iso_Packet_Lengths;
---------------------------
-- get_iso_packet_buffer --
---------------------------
function Get_Iso_Packet_Buffer
(Transfe : access Transfer;
Packet : Unsigned)
return access Unsigned_Char
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_iso_packet_buffer unimplemented");
return raise Program_Error with "Unimplemented function get_iso_packet_buffer";
end Get_Iso_Packet_Buffer;
----------------------------------
-- get_iso_packet_buffer_simple --
----------------------------------
function Get_Iso_Packet_Buffer_Simple
(Transfe : access Transfer;
Packet : Unsigned)
return access Unsigned_Char
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_iso_packet_buffer_simple unimplemented");
return raise Program_Error with "Unimplemented function get_iso_packet_buffer_simple";
end Get_Iso_Packet_Buffer_Simple;
----------------------
-- control_transfer --
----------------------
function Control_Transfer
(Dev_Handle : System.Address;
Request_Type : Interfaces.Unsigned_8;
BRequest : Interfaces.Unsigned_8;
WValue : Interfaces.Unsigned_16;
WIndex : Interfaces.Unsigned_16;
Data : access Unsigned_Char;
WLength : Interfaces.Unsigned_16;
Timeout : Unsigned)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "control_transfer unimplemented");
return raise Program_Error with "Unimplemented function control_transfer";
end Control_Transfer;
-------------------
-- bulk_transfer --
-------------------
function Bulk_Transfer
(Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Data : access Unsigned_Char;
Length : Int;
Actual_Length : access Int;
Timeout : Unsigned)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "bulk_transfer unimplemented");
return raise Program_Error with "Unimplemented function bulk_transfer";
end Bulk_Transfer;
------------------------
-- interrupt_transfer --
------------------------
function Interrupt_Transfer
(Dev_Handle : System.Address;
Endpoint : Unsigned_Char;
Data : access Unsigned_Char;
Length : Int;
Actual_Length : access Int;
Timeout : Unsigned)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "interrupt_transfer unimplemented");
return raise Program_Error with "Unimplemented function interrupt_transfer";
end Interrupt_Transfer;
--------------------
-- get_descriptor --
--------------------
function Get_Descriptor
(Dev_Handle : System.Address;
Desc_Type : Interfaces.Unsigned_8;
Desc_Index : Interfaces.Unsigned_8;
Data : access Unsigned_Char;
Length : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_descriptor";
end Get_Descriptor;
---------------------------
-- get_string_descriptor --
---------------------------
function Get_String_Descriptor
(Dev_Handle : System.Address;
Desc_Index : Interfaces.Unsigned_8;
Langid : Interfaces.Unsigned_16;
Data : access Unsigned_Char;
Length : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_string_descriptor unimplemented");
return raise Program_Error with "Unimplemented function get_string_descriptor";
end Get_String_Descriptor;
---------------------------------
-- get_string_descriptor_ascii --
---------------------------------
function Get_String_Descriptor_Ascii
(Dev_Handle : System.Address;
Desc_Index : Interfaces.Unsigned_8;
Data : access Unsigned_Char;
Length : Int)
return Int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "get_string_descriptor_ascii unimplemented");
return raise Program_Error with "Unimplemented function get_string_descriptor_ascii";
end Get_String_Descriptor_Ascii;
---------------------
-- try_lock_events --
---------------------
function Try_Lock_Events (ctx : context) return int is
begin
return Libusb_Try_Lock_Events(Ctx.Ctx);
end Try_Lock_Events;
-----------------
-- lock_events --
-----------------
procedure Lock_Events (ctx : context) is
begin
Libusb_Lock_Events(Ctx.Ctx);
end Lock_Events;
-------------------
-- unlock_events --
-------------------
procedure Unlock_Events (ctx : context) is
begin
Libusb_unLock_Events(Ctx.Ctx);
end Unlock_Events;
-----------------------
-- event_handling_ok --
-----------------------
function Event_Handling_Ok (ctx : context) return int is
begin
return Libusb_Event_Handling_Ok(Ctx.Ctx);
end Event_Handling_Ok;
--------------------------
-- event_handler_active --
--------------------------
function Event_Handler_Active (ctx : context) return int is
begin
return Libusb_Event_Handler_Active(Ctx.Ctx);
end Event_Handler_Active;
-----------------------------
-- interrupt_event_handler --
-----------------------------
procedure Interrupt_Event_Handler (ctx : context) is
begin
Libusb_Interrupt_Event_Handler(Ctx.Ctx);
end Interrupt_Event_Handler;
------------------------
-- lock_event_waiters --
------------------------
procedure Lock_Event_Waiters (ctx : context) is
begin
Libusb_Lock_Event_Waiters(Ctx.Ctx);
end Lock_Event_Waiters;
--------------------------
-- unlock_event_waiters --
--------------------------
procedure Unlock_Event_Waiters (ctx : context) is
begin
Libusb_Unlock_Event_Waiters(Ctx.Ctx);
end Unlock_Event_Waiters;
--------------------
-- wait_for_event --
--------------------
function Wait_For_Event (Ctx : Context; Tv : Duration) return Int is
L_tv : aliased GNAT.Calendar.Timeval := GNAT.Calendar.To_Timeval (Tv);
begin
return Libusb_Wait_For_Event (Ctx.Ctx, L_Tv'Access);
end Wait_For_Event;
---------------------------
-- handle_events_timeout --
---------------------------
function Handle_Events_Timeout
(ctx : context; tv : Duration) return int
is
L_tv : aliased GNAT.Calendar.Timeval := GNAT.Calendar.To_Timeval (Tv);
begin
return Libusb_Handle_Events_Timeout (Ctx.Ctx, L_Tv'Access);
end Handle_Events_Timeout;
-------------------------------------
-- handle_events_timeout_completed --
-------------------------------------
function Handle_Events_Timeout_Completed
(ctx : context;
completed : access int) return int
is
begin
return Libusb_Handle_Events_Completed (Ctx.Ctx, Completed);
end Handle_Events_Timeout_Completed;
-------------------
-- handle_events --
-------------------
function Handle_Events (ctx : context) return int is
begin
return Libusb_Handle_Events (Ctx.Ctx);
end Handle_Events;
-----------------------------
-- handle_events_completed --
-----------------------------
function Handle_Events_Completed
(ctx : context; completed : access int) return int
is
begin
return Libusb_Handle_Events_Completed (Ctx.Ctx,Completed);
end Handle_Events_Completed;
--------------------------
-- handle_events_locked --
--------------------------
function Handle_Events_Locked
(ctx : context; tv : Duration) return int
is
L_tv : aliased GNAT.Calendar.Timeval := GNAT.Calendar.To_Timeval (Tv);
begin
return Libusb_Handle_Events_Locked (Ctx.Ctx, L_Tv'Access);
end Handle_Events_Locked;
-----------------------------
-- pollfds_handle_timeouts --
-----------------------------
function Pollfds_Handle_Timeouts (ctx : context) return int is
begin
return Libusb_Pollfds_Handle_Timeouts (Ctx.Ctx);
end Pollfds_Handle_Timeouts;
----------------------
-- get_next_timeout --
----------------------
function Get_Next_Timeout
(Ctx : Context;
Tv : Duration)
return Int
is
L_tv : aliased GNAT.Calendar.Timeval := GNAT.Calendar.To_Timeval (Tv);
begin
return Libusb_Get_Next_Timeout (Ctx.Ctx, L_Tv'Access);
end Get_Next_Timeout;
-----------------
-- get_pollfds --
-----------------
function Get_Pollfds (ctx : context) return System.Address is
begin
return Libusb_Get_Pollfds (Ctx.Ctx);
end Get_Pollfds;
------------------
-- free_pollfds --
------------------
procedure Free_Pollfds (Pollfds : System.Address) is
begin
Libusb_Free_Pollfds (Pollfds);
end Free_Pollfds;
--------------------------
-- set_pollfd_notifiers --
--------------------------
procedure Set_Pollfd_Notifiers
(ctx : context;
added_cb : pollfd_added_cb;
removed_cb : pollfd_removed_cb;
user_data : System.Address)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "set_pollfd_notifiers unimplemented");
raise Program_Error with "Unimplemented procedure set_pollfd_notifiers";
end Set_Pollfd_Notifiers;
-------------------------------
-- hotplug_register_callback --
-------------------------------
function Hotplug_Register_Callback
(ctx : context;
events : hotplug_event;
flags : hotplug_flag;
vendor_id : int;
product_id : int;
dev_class : int;
cb_fn : hotplug_callback_fn;
user_data : System.Address;
callback_handle : access hotplug_callback_handle) return int
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "hotplug_register_callback unimplemented");
return raise Program_Error with "Unimplemented function hotplug_register_callback";
end Hotplug_Register_Callback;
---------------------------------
-- hotplug_deregister_callback --
---------------------------------
procedure Hotplug_Deregister_Callback
(ctx : context; callback_handle : hotplug_callback_handle)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "hotplug_deregister_callback unimplemented");
raise Program_Error with "Unimplemented procedure hotplug_deregister_callback";
end Hotplug_Deregister_Callback;
end USB;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Unchecked_Deallocation;
with Ada.Containers.Indefinite_Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Text_IO; --use Ada.Text_IO;
with Ada.Strings.Maps;
with Ada.Strings.Fixed;
with Ada.Characters.Latin_1;
with Interfaces;
with String_Ops;
with kv.avm.Assemblers;
with kv.avm.File_Reader;
with kv.avm.Memories;
with kv.avm.Registers;
with kv.avm.Log; use kv.avm.Log;
package body kv.avm.Ini is
package String_Lists is new Ada.Containers.Indefinite_Vectors
(Index_Type => Positive,
Element_Type => String);
package Configurations is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String,
Element_Type => String_Lists.Vector,
"=" => String_Lists."=");
use Configurations;
type Configuration_Access is access Configurations.Map;
type Settings_Reference_Counter_Type is
record
Count : Natural := 0;
Data : Configuration_Access;
end record;
-----------------------------------------------------------------------------
procedure Free is new Ada.Unchecked_Deallocation(Settings_Reference_Counter_Type, Settings_Reference_Counter_Access);
-----------------------------------------------------------------------------
procedure Free is new Ada.Unchecked_Deallocation(Configurations.Map, Configuration_Access);
-----------------------------------------------------------------------------
procedure Initialize (Self : in out Settings_Type) is
begin
Self.Ref := new Settings_Reference_Counter_Type;
Self.Ref.Count := 1;
Self.Ref.Data := new Configurations.Map;
end Initialize;
-----------------------------------------------------------------------------
procedure Adjust (Self : in out Settings_Type) is
Ref : Settings_Reference_Counter_Access := Self.Ref;
begin
if Ref /= null then
Ref.Count := Ref.Count + 1;
end if;
end Adjust;
-----------------------------------------------------------------------------
procedure Finalize (Self : in out Settings_Type) is
Ref : Settings_Reference_Counter_Access := Self.Ref;
begin
Self.Ref := null;
if Ref /= null then
Ref.Count := Ref.Count - 1;
if Ref.Count = 0 then
Free(Ref.Data);
Free(Ref);
end if;
end if;
end Finalize;
-----------------------------------------------------------------------------
function Split_Index(The_String : String) return Natural is
begin
return Ada.Strings.Fixed.Index(The_String, "=");
end Split_Index;
-----------------------------------------------------------------------------
procedure Parse_Line
(Self : in out Settings_Type;
Line : in String) is
Split_Point : Natural;
Key_And_Value : constant String := String_Ops.Drop_Vole_Comments(Line);
begin
--Put_Line("Parse_Line = <"&Key_And_Value&">");
Split_Point := Split_Index(Key_And_Value);
--Put_Line("Split_Point =" & Natural'IMAGE(Split_Point));
if Split_Point /= 0 then
declare
Key : constant String := String_Ops.Trim_Blanks(Key_And_Value(Key_And_Value'FIRST .. Split_Point-1));
Value : constant String := String_Ops.Trim_Blanks(Key_And_Value(Split_Point+1 .. Key_And_Value'LAST));
begin
--Put_Line("Key = <"& Key &">");
--Put_Line("Value = <"& Value &">");
if Self.Has(Key) then
Self.Add_Value_To_Existing_Key(Key, Value);
else
Self.Insert(Key, Value);
end if;
--Self.Ref.Data.Insert(Key, Value);
end;
end if;
end Parse_Line;
-----------------------------------------------------------------------------
procedure Add_Value_To_Existing_Key
(Self : in out Settings_Type;
Key : in String;
Value : in String) is
Value_List : String_Lists.Vector;
Location : Cursor;
begin
--Put_Line("Adding <" & Value & "> to existing key <" & Key & ">");
Location := Self.Ref.Data.Find(Key);
if Location /= No_Element then
Value_List := Element(Location);
String_Lists.Append(Value_List, Value);
Self.Ref.Data.Replace_Element(Location, Value_List);
else
--raise Constraint_Error; --TODO: define an exception and raise it with a message
Raise_Exception(Constraint_Error'IDENTITY, "Error: key <" & Key & "> not found.");
end if;
end Add_Value_To_Existing_Key;
-----------------------------------------------------------------------------
procedure Insert
(Self : in out Settings_Type;
Key : in String;
Value : in String) is
Value_List : String_Lists.Vector;
begin
--Put_Line("Inserting <" & Value & "> at key <" & Key & ">");
String_Lists.Append(Value_List, Value);
Self.Ref.Data.Insert(Key, Value_List);
end Insert;
-----------------------------------------------------------------------------
function Has(Self : Settings_Type; Key : String) return Boolean is
begin
return Self.Ref.Data.Contains(Key);
end Has;
-----------------------------------------------------------------------------
function Lookup_As_String(Self : Settings_Type; Key : String; Index : Positive := 1) return String is
Location : Cursor;
Value_List : String_Lists.Vector;
begin
Location := Self.Ref.Data.Find(Key);
if Location /= No_Element then
Value_List := Element(Location);
return String_Lists.Element(Value_List, Index);
end if;
return "";
end Lookup_As_String;
-----------------------------------------------------------------------------
function Lookup_As_Integer(Self : Settings_Type; Key : String; Index : Positive := 1) return Integer is
Image : constant String := Self.Lookup_As_String(Key, Index);
begin
return Integer'VALUE(Image);
end Lookup_As_Integer;
----------------------------------------------------------------------------
function Tuple_String_Count_Elements(Tuple_String : String) return Positive is
begin
return Ada.Strings.Fixed.Count(Tuple_String, ",") + 1; -- The number of delimiters plus one
end Tuple_String_Count_Elements;
----------------------------------------------------------------------------
function Tuple_String_Get(Tuple_String : String; Index : Positive) return String is
begin
return String_Ops.Nth(Tuple_String, Index, Ada.Strings.Maps.To_Set(','));
end Tuple_String_Get;
----------------------------------------------------------------------------
function Make_String_Register(Value : String) return kv.avm.Registers.Register_Type is
Clean : constant String := String_Ops.Trim_One_From_Both_Ends(Value);
use kv.avm.Registers;
begin
return (Format => Immutable_String, The_String => +Clean);
end Make_String_Register;
----------------------------------------------------------------------------
function Make_Intger_Value(Value : String) return kv.avm.Registers.Register_Type is
begin
return kv.avm.Registers.Make_S(Interfaces.Integer_64'VALUE(Value));
end Make_Intger_Value;
----------------------------------------------------------------------------
function Make_Register(Value : String) return kv.avm.Registers.Register_Type is
begin
if Value(Value'FIRST) = Ada.Characters.Latin_1.Quotation then
return Make_String_Register(Value);
else
return Make_Intger_Value(Value);
end if;
end Make_Register;
----------------------------------------------------------------------------
function String_To_Registers(Tuple_String : String) return kv.avm.Memories.Register_Set_Type is
Clean : constant String := String_Ops.Trim_One_From_Both_Ends(Tuple_String); -- drop []
Count : constant Positive := Tuple_String_Count_Elements(Clean);
Answer : kv.avm.Memories.Register_Set_Type(0 .. Interfaces.Unsigned_32(Count - 1));
use Interfaces;
begin
--Put_Line("String_To_Registers processing <" & Clean & "> (count =" & Positive'IMAGE(Count) & ")");
for Index in Answer'RANGE loop
Answer(Index) := Make_Register(Tuple_String_Get(Clean, Positive(Index + 1)));
end loop;
return Answer;
end String_To_Registers;
----------------------------------------------------------------------------
function Lookup_As_Tuple(Self : Settings_Type; Key : String; Index : Positive := 1) return kv.avm.Tuples.Tuple_Type is
Answer : kv.avm.Tuples.Tuple_Type;
Contents : kv.avm.Memories.Register_Array_Type;
begin
Contents.Initialize(String_To_Registers(Self.Lookup_As_String(Key, Index)));
Answer.Fold(Contents);
return Answer;
end Lookup_As_Tuple;
----------------------------------------------------------------------------
function Value_Count_For_Key(Self : Settings_Type; Key : String) return Natural is
Location : Cursor;
Value_List : String_Lists.Vector;
begin
Location := Self.Ref.Data.Find(Key);
if Location /= No_Element then
Value_List := Element(Location);
return Natural(String_Lists.Length(Value_List));
end if;
return 0;
end Value_Count_For_Key;
----------------------------------------------------------------------------
package Settings_Reader is new kv.avm.File_Reader(Settings_Type);
----------------------------------------------------------------------------
procedure Parse_Input_File
(Self : in out Settings_Type;
File_In : in String) renames Settings_Reader.Parse_Input_File;
end kv.avm.Ini;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
with Ada.Numerics.Big_Numbers.Big_Integers;
with Ada.Strings.Text_Output; use Ada.Strings.Text_Output;
package Ada.Numerics.Big_Numbers.Big_Reals
with Preelaborate
is
type Big_Real is private with
Real_Literal => From_String,
Put_Image => Put_Image;
function Is_Valid (Arg : Big_Real) return Boolean
with
Convention => Intrinsic,
Global => null;
subtype Valid_Big_Real is Big_Real
with Dynamic_Predicate => Is_Valid (Valid_Big_Real),
Predicate_Failure => raise Program_Error;
function "/"
(Num, Den : Big_Integers.Valid_Big_Integer) return Valid_Big_Real
with Global => null;
-- with Pre => (Big_Integers."/=" (Den, Big_Integers.To_Big_Integer (0))
-- or else Constraint_Error);
function Numerator
(Arg : Valid_Big_Real) return Big_Integers.Valid_Big_Integer
with Global => null;
function Denominator (Arg : Valid_Big_Real) return Big_Integers.Big_Positive
with
Post =>
(if Arg = To_Real (0)
then Big_Integers."=" (Denominator'Result,
Big_Integers.To_Big_Integer (1))
else Big_Integers."="
(Big_Integers.Greatest_Common_Divisor
(Numerator (Arg), Denominator'Result),
Big_Integers.To_Big_Integer (1))),
Global => null;
function To_Big_Real
(Arg : Big_Integers.Big_Integer)
return Valid_Big_Real is (Arg / Big_Integers.To_Big_Integer (1))
with Global => null;
function To_Real (Arg : Integer) return Valid_Big_Real is
(Big_Integers.To_Big_Integer (Arg) / Big_Integers.To_Big_Integer (1))
with Global => null;
function "=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function "<" (L, R : Valid_Big_Real) return Boolean with Global => null;
function "<=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function ">" (L, R : Valid_Big_Real) return Boolean with Global => null;
function ">=" (L, R : Valid_Big_Real) return Boolean with Global => null;
function In_Range (Arg, Low, High : Big_Real) return Boolean is
(Low <= Arg and then Arg <= High)
with Global => null;
generic
type Num is digits <>;
package Float_Conversions is
function To_Big_Real (Arg : Num) return Valid_Big_Real
with Global => null;
function From_Big_Real (Arg : Big_Real) return Num
with
Pre => In_Range (Arg,
Low => To_Big_Real (Num'First),
High => To_Big_Real (Num'Last))
or else (raise Constraint_Error),
Global => null;
end Float_Conversions;
generic
type Num is delta <>;
package Fixed_Conversions is
function To_Big_Real (Arg : Num) return Valid_Big_Real
with Global => null;
function From_Big_Real (Arg : Big_Real) return Num
with
Pre => In_Range (Arg,
Low => To_Big_Real (Num'First),
High => To_Big_Real (Num'Last))
or else (raise Constraint_Error),
Global => null;
end Fixed_Conversions;
function To_String (Arg : Valid_Big_Real;
Fore : Field := 2;
Aft : Field := 3;
Exp : Field := 0) return String
with
Post => To_String'Result'First = 1,
Global => null;
function From_String (Arg : String) return Big_Real
with Global => null;
function To_Quotient_String (Arg : Big_Real) return String is
(Big_Integers.To_String (Numerator (Arg)) & " / "
& Big_Integers.To_String (Denominator (Arg)))
with Global => null;
function From_Quotient_String (Arg : String) return Valid_Big_Real
with Global => null;
procedure Put_Image (S : in out Sink'Class; V : Big_Real);
function "+" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "-" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "abs" (L : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "+" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "-" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "*" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "/" (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function "**" (L : Valid_Big_Real; R : Integer) return Valid_Big_Real
with Global => null;
function Min (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
function Max (L, R : Valid_Big_Real) return Valid_Big_Real
with Global => null;
private
type Big_Real is record
Num, Den : Big_Integers.Big_Integer;
end record;
end Ada.Numerics.Big_Numbers.Big_Reals;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
generic
type Float is digits <>;
n_simp1_max : Integer := 64; -- max. number of legs in the lattice
n_simp2_max : Integer := 1; -- max. number of bones in the lattice
n_loop02_max : Integer := 10; -- max. number of vertices in the loop around a bone
package regge is
subtype Real is Float;
type bone_type is (timelike, spacelike);
type Array1dReal is array (Integer range <>) of Real;
type Array2dReal is array (Integer range <>, Integer range <>) of Real;
type Array1dIntg is array (Integer range <>) of Integer;
function "*" (Left : Integer; Right : Real) return Real;
function "*" (Left : Real; Right : Integer) return Real;
function get_signature
(bone : Integer) return bone_type;
procedure set_metric
(metric : out Array2dReal;
bone : Integer;
index : Integer);
procedure get_defect
(defect : out Real; -- the defect
bone : Integer; -- the bone
n_vertex : Integer); -- the number of vertices that enclose the bone
procedure get_defect_deriv
(deriv : out Real; -- the derivative of the defect
bone : Integer; -- the bone
n_vertex : Integer; -- the number of vertices that enclose the bone
leg_pq : Integer); -- use this leg to compute the derivative
procedure get_defect_and_deriv
(defect : out Real; -- the defect
deriv : out Real; -- the derivative of the defect
bone : Integer; -- the bone
n_vertex : Integer; -- the number of vertices that enclose the bone
leg_pq : Integer); -- use this leg to compute the derivative
bone_signature : bone_type;
n_simp12_max : Integer := 3 + 4*n_loop02_max; -- max. number of legs in the loop around a bone
n_lsq_max : Integer := n_simp1_max; -- max. number of legs in the lattice
n_simp1 : Integer := 0; -- number of legs in the lattice
n_simp2 : Integer := 0; -- number of bones in the lattice
n_loop02 : Array1dIntg (1 .. n_simp2_max); -- number of vertices in the loop around a bone
n_simp12 : Array1dIntg (1 .. n_simp2_max); -- number of legs in the loop around a bone
lsq : Array1dReal (1..n_lsq_max); -- the lsq's of the lattice
simp12 : Array (1 .. n_simp2_max) of Array1dIntg (1 .. n_simp12_max); -- all legs for each bone
end regge;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Command_Line;
with Ada.Streams.Stream_IO;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with GMP.Z;
procedure test_streams is
use Ada.Streams.Stream_IO;
use Ada.Strings;
use Ada.Strings.Fixed;
use Ada.Text_IO;
use GMP.Z;
Verbose : Boolean := False;
package Binary_IO is new Ada.Text_IO.Modular_IO (Ada.Streams.Stream_Element);
use Binary_IO;
procedure test (X : Long_Long_Integer) is
Z1 : constant MP_Integer := To_MP_Integer (X);
Z2 : MP_Integer;
F : Ada.Streams.Stream_IO.File_Type;
B : Ada.Streams.Stream_Element;
begin
if Verbose then
Put (Trim (Long_Long_Integer'Image (X), Both)); New_Line;
Put (Image (Z1)); New_Line;
end if;
Create (F);
MP_Integer'Write (Stream (F), Z1);
Reset (F, In_File);
Set_Index (F, 1);
MP_Integer'Read (Stream (F), Z2);
if Verbose then
Put (Image (Z2)); New_Line;
end if;
Set_Index (F, 1);
while not End_Of_File (F) loop
Ada.Streams.Stream_Element'Read (Stream (F), B);
if Verbose then
Put (B, Base => 16);
Put (" ");
end if;
end loop;
if Verbose then
New_Line;
end if;
Close (F);
end test;
begin
for I in 1 .. Ada.Command_Line.Argument_Count loop
if Ada.Command_Line.Argument (I) = "-v" then
Verbose := True;
end if;
end loop;
test (0);
test (1);
test (2);
test (3);
test (256);
test (65535);
test (-1);
test (-2);
test (-3);
test (-256);
test (-65535);
test (Long_Long_Integer'First);
test (Long_Long_Integer'Last);
-- finish
Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error.all, "ok");
end test_streams;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides the low level interface to the C runtime library
-- (additional declarations for use in the Ada runtime only, not in the
-- compiler itself).
with Interfaces.C.Strings;
package System.CRTL.Runtime is
pragma Preelaborate;
subtype chars_ptr is Interfaces.C.Strings.chars_ptr;
function strerror (errno : int) return chars_ptr;
pragma Import (C, strerror, "strerror");
end System.CRTL.Runtime;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Numerics.Generic_Real_Arrays;
with Ada.Numerics.Generic_Elementary_Functions;
generic
type Real_Type is digits <>;
package Math_2D.Types is
package Functions is new Ada.Numerics.Generic_Elementary_Functions (Real_Type);
package Arrays is new Ada.Numerics.Generic_Real_Arrays (Real_Type);
type Point_t is new Arrays.Real_Vector (1 .. 2);
type Vector_t is new Arrays.Real_Vector (1 .. 2);
type Triangle_Point_Index_t is range 1 .. 3;
type Triangle_t is array (Triangle_Point_Index_t) of Point_t;
type Line_Segment_Point_Index_t is range 1 .. 2;
type Line_Segment_t is array (Line_Segment_Point_Index_t) of Point_t;
end Math_2D.Types;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $
generic
type Element_Type (<>) is private;
with function "<" (Left : in Element_Type;
Right : in Element_Type)
return Boolean is <>;
with function "=" (Left : in Element_Type;
Right : in Element_Type)
return Boolean is <>;
package Ada.Containers.Indefinite_Ordered_Sets is
pragma Preelaborate (Indefinite_Ordered_Sets);
function Equivalent_Elements (Left : in Element_Type;
Right : in Element_Type)
return Boolean;
type Set is tagged private;
pragma Preelaborable_Initialization (Set);
type Cursor is private;
pragma Preelaborable_Initialization (Cursor);
Empty_Set : constant Set;
No_Element : constant Cursor;
function "=" (Left : in Set;
Right : in Set)
return Boolean;
function Equivalent_Sets (Left : in Set;
Right : in Set)
return Boolean;
function To_Set (New_Item : in Element_Type) return Set;
function Length (Container : in Set) return Count_Type;
function Is_Empty (Container : in Set) return Boolean;
procedure Clear (Container : in out Set);
function Element (Position : in Cursor) return Element_Type;
procedure Replace_Element (Container : in out Set;
Position : in Cursor;
New_Item : in Element_Type);
procedure Query_Element
(Position : in Cursor;
Process : not null access procedure (Element : in Element_Type));
procedure Move (Target : in out Set;
Source : in out Set);
procedure Insert (Container : in out Set;
New_Item : in Element_Type;
Position : out Cursor;
Inserted : out Boolean);
procedure Insert (Container : in out Set;
New_Item : in Element_Type);
procedure Include (Container : in out Set;
New_Item : in Element_Type);
procedure Replace (Container : in out Set;
New_Item : in Element_Type);
procedure Exclude (Container : in out Set;
Item : in Element_Type);
procedure Delete (Container : in out Set;
Item : in Element_Type);
procedure Delete (Container : in out Set;
Position : in out Cursor);
procedure Delete_First (Container : in out Set);
procedure Delete_Last (Container : in out Set);
procedure Union (Target : in out Set;
Source : in Set);
function Union (Left : in Set;
Right : in Set)
return Set;
function "or" (Left : in Set;
Right : in Set)
return Set renames Union;
procedure Intersection (Target : in out Set;
Source : in Set);
function Intersection (Left : in Set;
Right : in Set)
return Set;
function "and" (Left : in Set;
Right : in Set)
return Set renames Intersection;
procedure Difference (Target : in out Set;
Source : in Set);
function Difference (Left : in Set;
Right : in Set)
return Set;
function "-" (Left : in Set;
Right : in Set)
return Set renames Difference;
procedure Symmetric_Difference (Target : in out Set;
Source : in Set);
function Symmetric_Difference (Left : in Set;
Right : in Set)
return Set;
function "xor" (Left : in Set;
Right : in Set)
return Set renames Symmetric_Difference;
function Overlap (Left : in Set;
Right : in Set)
return Boolean;
function Is_Subset (Subset : in Set;
Of_Set : in Set)
return Boolean;
function First (Container : in Set) return Cursor;
function First_Element (Container : in Set) return Element_Type;
function Last (Container : in Set) return Cursor;
function Last_Element (Container : in Set) return Element_Type;
function Next (Position : in Cursor) return Cursor;
procedure Next (Position : in out Cursor);
function Previous (Position : in Cursor) return Cursor;
procedure Previous (Position : in out Cursor);
function Find (Container : in Set;
Item : in Element_Type)
return Cursor;
function Floor (Container : in Set;
Item : in Element_Type)
return Cursor;
function Ceiling (Container : in Set;
Item : in Element_Type)
return Cursor;
function Contains (Container : in Set;
Item : in Element_Type)
return Boolean;
function Has_Element (Position : in Cursor) return Boolean;
function "<" (Left : in Cursor;
Right : in Cursor)
return Boolean;
function ">" (Left : in Cursor;
Right : in Cursor)
return Boolean;
function "<" (Left : in Cursor;
Right : in Element_Type)
return Boolean;
function ">" (Left : in Cursor;
Right : in Element_Type)
return Boolean;
function "<" (Left : in Element_Type;
Right : in Cursor)
return Boolean;
function ">" (Left : in Element_Type;
Right : in Cursor)
return Boolean;
procedure Iterate
(Container : in Set;
Process : not null access procedure (Position : in Cursor));
procedure Reverse_Iterate
(Container : in Set;
Process : not null access procedure (Position : in Cursor));
generic
type Key_Type (<>) is private;
with function Key (Element : in Element_Type) return Key_Type;
with function "<" (Left : in Key_Type;
Right : in Key_Type)
return Boolean is <>;
package Generic_Keys is
function Equivalent_Keys (Left : in Key_Type;
Right : in Key_Type)
return Boolean;
function Key (Position : in Cursor) return Key_Type;
function Element (Container : in Set;
Key : in Key_Type)
return Element_Type;
procedure Replace (Container : in out Set;
Key : in Key_Type;
New_Item : in Element_Type);
procedure Exclude (Container : in out Set;
Key : in Key_Type);
procedure Delete (Container : in out Set;
Key : in Key_Type);
function Find (Container : in Set;
Key : in Key_Type)
return Cursor;
function Floor (Container : in Set;
Key : in Key_Type)
return Cursor;
function Ceiling (Container : in Set;
Key : in Key_Type)
return Cursor;
function Contains (Container : in Set;
Key : in Key_Type)
return Boolean;
procedure Update_Element_Preserving_Key
(Container : in out Set;
Position : in Cursor;
Process : not null access procedure (Element : in out Element_Type));
end Generic_Keys;
private
type Set is tagged null record;
Empty_Set : constant Set := (null record);
type Cursor is null record;
No_Element : constant Cursor := (null record);
end Ada.Containers.Indefinite_Ordered_Sets;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains a set of subprogram access variables that access
-- some low-level primitives that are different depending whether tasking is
-- involved or not (e.g. the Get/Set_Jmpbuf_Address that needs to provide a
-- different value for each task). To avoid dragging in the tasking runtimes
-- all the time, we use a system of soft links where the links are
-- initialized to non-tasking versions, and then if the tasking support is
-- initialized, they are set to the real tasking versions.
pragma Compiler_Unit_Warning;
with Ada.Exceptions;
with System.Parameters;
with System.Secondary_Stack;
with System.Stack_Checking;
package System.Soft_Links is
pragma Preelaborate;
package SST renames System.Secondary_Stack;
subtype EOA is Ada.Exceptions.Exception_Occurrence_Access;
subtype EO is Ada.Exceptions.Exception_Occurrence;
function Current_Target_Exception return EO;
pragma Import
(Ada, Current_Target_Exception, "__gnat_current_target_exception");
-- Import this subprogram from the private part of Ada.Exceptions
-- First we have the access subprogram types used to establish the links.
-- The approach is to establish variables containing access subprogram
-- values, which by default point to dummy no tasking versions of routines.
type No_Param_Proc is access procedure;
pragma Favor_Top_Level (No_Param_Proc);
pragma Suppress_Initialization (No_Param_Proc);
-- Some uninitialized objects of that type are initialized by the Binder
-- so it is important that such objects are not reset to null during
-- elaboration.
type Addr_Param_Proc is access procedure (Addr : Address);
pragma Favor_Top_Level (Addr_Param_Proc);
type EO_Param_Proc is access procedure (Excep : EO);
pragma Favor_Top_Level (EO_Param_Proc);
type Get_Address_Call is access function return Address;
pragma Favor_Top_Level (Get_Address_Call);
type Set_Address_Call is access procedure (Addr : Address);
pragma Favor_Top_Level (Set_Address_Call);
type Set_Address_Call2 is access procedure
(Self_ID : Address; Addr : Address);
pragma Favor_Top_Level (Set_Address_Call2);
type Get_Integer_Call is access function return Integer;
pragma Favor_Top_Level (Get_Integer_Call);
type Set_Integer_Call is access procedure (Len : Integer);
pragma Favor_Top_Level (Set_Integer_Call);
type Get_EOA_Call is access function return EOA;
pragma Favor_Top_Level (Get_EOA_Call);
type Set_EOA_Call is access procedure (Excep : EOA);
pragma Favor_Top_Level (Set_EOA_Call);
type Set_EO_Call is access procedure (Excep : EO);
pragma Favor_Top_Level (Set_EO_Call);
type Get_Stack_Call is access function return SST.SS_Stack_Ptr;
pragma Favor_Top_Level (Get_Stack_Call);
type Set_Stack_Call is access procedure (Stack : SST.SS_Stack_Ptr);
pragma Favor_Top_Level (Set_Stack_Call);
type Special_EO_Call is access
procedure (Excep : EO := Current_Target_Exception);
pragma Favor_Top_Level (Special_EO_Call);
type Timed_Delay_Call is access
procedure (Time : Duration; Mode : Integer);
pragma Favor_Top_Level (Timed_Delay_Call);
type Get_Stack_Access_Call is access
function return Stack_Checking.Stack_Access;
pragma Favor_Top_Level (Get_Stack_Access_Call);
type Task_Name_Call is access
function return String;
pragma Favor_Top_Level (Task_Name_Call);
-- Suppress checks on all these types, since we know the corresponding
-- values can never be null (the soft links are always initialized).
pragma Suppress (Access_Check, No_Param_Proc);
pragma Suppress (Access_Check, Addr_Param_Proc);
pragma Suppress (Access_Check, EO_Param_Proc);
pragma Suppress (Access_Check, Get_Address_Call);
pragma Suppress (Access_Check, Set_Address_Call);
pragma Suppress (Access_Check, Set_Address_Call2);
pragma Suppress (Access_Check, Get_Integer_Call);
pragma Suppress (Access_Check, Set_Integer_Call);
pragma Suppress (Access_Check, Get_EOA_Call);
pragma Suppress (Access_Check, Set_EOA_Call);
pragma Suppress (Access_Check, Get_Stack_Call);
pragma Suppress (Access_Check, Set_Stack_Call);
pragma Suppress (Access_Check, Timed_Delay_Call);
pragma Suppress (Access_Check, Get_Stack_Access_Call);
pragma Suppress (Access_Check, Task_Name_Call);
-- The following one is not related to tasking/no-tasking but to the
-- traceback decorators for exceptions.
type Traceback_Decorator_Wrapper_Call is access
function (Traceback : System.Address;
Len : Natural)
return String;
pragma Favor_Top_Level (Traceback_Decorator_Wrapper_Call);
-- Declarations for the no tasking versions of the required routines
procedure Abort_Defer_NT;
-- Defer task abort (non-tasking case, does nothing)
procedure Abort_Undefer_NT;
-- Undefer task abort (non-tasking case, does nothing)
procedure Abort_Handler_NT;
-- Handle task abort (non-tasking case, does nothing). Currently, no port
-- makes use of this, but we retain the interface for possible future use.
function Check_Abort_Status_NT return Integer;
-- Returns Boolean'Pos (True) iff abort signal should raise
-- Standard'Abort_Signal.
procedure Task_Lock_NT;
-- Lock out other tasks (non-tasking case, does nothing)
procedure Task_Unlock_NT;
-- Release lock set by Task_Lock (non-tasking case, does nothing)
procedure Task_Termination_NT (Excep : EO);
-- Handle task termination routines for the environment task (non-tasking
-- case, does nothing).
procedure Adafinal_NT;
-- Shuts down the runtime system (non-tasking case)
Abort_Defer : No_Param_Proc := Abort_Defer_NT'Access;
pragma Suppress (Access_Check, Abort_Defer);
-- Defer task abort (task/non-task case as appropriate)
Abort_Undefer : No_Param_Proc := Abort_Undefer_NT'Access;
pragma Suppress (Access_Check, Abort_Undefer);
-- Undefer task abort (task/non-task case as appropriate)
Abort_Handler : No_Param_Proc := Abort_Handler_NT'Access;
-- Handle task abort (task/non-task case as appropriate)
Check_Abort_Status : Get_Integer_Call := Check_Abort_Status_NT'Access;
-- Called when Abort_Signal is delivered to the process. Checks to
-- see if signal should result in raising Standard'Abort_Signal.
Lock_Task : No_Param_Proc := Task_Lock_NT'Access;
-- Locks out other tasks. Preceding a section of code by Task_Lock and
-- following it by Task_Unlock creates a critical region. This is used
-- for ensuring that a region of non-tasking code (such as code used to
-- allocate memory) is tasking safe. Note that it is valid for calls to
-- Task_Lock/Task_Unlock to be nested, and this must work properly, i.e.
-- only the corresponding outer level Task_Unlock will actually unlock.
-- This routine also prevents against asynchronous aborts (abort is
-- deferred).
Unlock_Task : No_Param_Proc := Task_Unlock_NT'Access;
-- Releases lock previously set by call to Lock_Task. In the nested case,
-- all nested locks must be released before other tasks competing for the
-- tasking lock are released.
--
-- In the non nested case, this routine terminates the protection against
-- asynchronous aborts introduced by Lock_Task (unless abort was already
-- deferred before the call to Lock_Task (e.g in a protected procedures).
--
-- Note: the recommended protocol for using Lock_Task and Unlock_Task
-- is as follows:
--
-- Locked_Processing : begin
-- System.Soft_Links.Lock_Task.all;
-- ...
-- System.Soft_Links.Unlock_Task.all;
--
-- exception
-- when others =>
-- System.Soft_Links.Unlock_Task.all;
-- raise;
-- end Locked_Processing;
--
-- This ensures that the lock is not left set if an exception is raised
-- explicitly or implicitly during the critical locked region.
Task_Termination_Handler : EO_Param_Proc := Task_Termination_NT'Access;
-- Handle task termination routines (task/non-task case as appropriate)
Finalize_Library_Objects : No_Param_Proc;
pragma Export (C, Finalize_Library_Objects,
"__gnat_finalize_library_objects");
-- Will be initialized by the binder
Adafinal : No_Param_Proc := Adafinal_NT'Access;
-- Performs the finalization of the Ada Runtime
function Get_Jmpbuf_Address_NT return Address;
procedure Set_Jmpbuf_Address_NT (Addr : Address);
Get_Jmpbuf_Address : Get_Address_Call := Get_Jmpbuf_Address_NT'Access;
Set_Jmpbuf_Address : Set_Address_Call := Set_Jmpbuf_Address_NT'Access;
function Get_Sec_Stack_NT return SST.SS_Stack_Ptr;
procedure Set_Sec_Stack_NT (Stack : SST.SS_Stack_Ptr);
Get_Sec_Stack : Get_Stack_Call := Get_Sec_Stack_NT'Access;
Set_Sec_Stack : Set_Stack_Call := Set_Sec_Stack_NT'Access;
function Get_Current_Excep_NT return EOA;
Get_Current_Excep : Get_EOA_Call := Get_Current_Excep_NT'Access;
function Get_Stack_Info_NT return Stack_Checking.Stack_Access;
Get_Stack_Info : Get_Stack_Access_Call := Get_Stack_Info_NT'Access;
--------------------------
-- Master_Id Soft-Links --
--------------------------
-- Soft-Links are used for procedures that manipulate Master_Ids because
-- a Master_Id must be generated for access to limited class-wide types,
-- whose root may be extended with task components.
function Current_Master_NT return Integer;
procedure Enter_Master_NT;
procedure Complete_Master_NT;
Current_Master : Get_Integer_Call := Current_Master_NT'Access;
Enter_Master : No_Param_Proc := Enter_Master_NT'Access;
Complete_Master : No_Param_Proc := Complete_Master_NT'Access;
----------------------
-- Delay Soft-Links --
----------------------
-- Soft-Links are used for procedures that manipulate time to avoid
-- dragging the tasking run time when using delay statements.
Timed_Delay : Timed_Delay_Call;
--------------------------
-- Task Name Soft-Links --
--------------------------
function Task_Name_NT return String;
Task_Name : Task_Name_Call := Task_Name_NT'Access;
-------------------------------------
-- Exception Tracebacks Soft-Links --
-------------------------------------
Library_Exception : EO;
-- Library-level finalization routines use this common reference to store
-- the first library-level exception which occurs during finalization.
Library_Exception_Set : Boolean := False;
-- Used in conjunction with Library_Exception, set when an exception has
-- been stored.
Traceback_Decorator_Wrapper : Traceback_Decorator_Wrapper_Call;
-- Wrapper to the possible user specified traceback decorator to be
-- called during automatic output of exception data.
-- The null value of this wrapper correspond sto the null value of the
-- current actual decorator. This is ensured first by the null initial
-- value of the corresponding variables, and then by Set_Trace_Decorator
-- in g-exctra.adb.
pragma Atomic (Traceback_Decorator_Wrapper);
-- Since concurrent read/write operations may occur on this variable.
-- See the body of Tailored_Exception_Traceback in Ada.Exceptions for
-- a more detailed description of the potential problems.
procedure Save_Library_Occurrence (E : EOA);
-- When invoked, this routine saves an exception occurrence into a hidden
-- reference. Subsequent calls will have no effect.
------------------------
-- Task Specific Data --
------------------------
-- Here we define a single type that encapsulates the various task
-- specific data. This type is used to store the necessary data into the
-- Task_Control_Block or into a global variable in the non tasking case.
type TSD is record
Pri_Stack_Info : aliased Stack_Checking.Stack_Info;
-- Information on stack (Base/Limit/Size) used by System.Stack_Checking.
-- If this TSD does not belong to the environment task, the Size field
-- must be initialized to the tasks requested stack size before the task
-- can do its first stack check.
Jmpbuf_Address : System.Address;
-- Address of jump buffer used to store the address of the current
-- longjmp/setjmp buffer for exception management. These buffers are
-- threaded into a stack, and the address here is the top of the stack.
-- A null address means that no exception handler is currently active.
Sec_Stack_Ptr : SST.SS_Stack_Ptr;
-- Pointer of the allocated secondary stack
Current_Excep : aliased EO;
-- Exception occurrence that contains the information for the current
-- exception. Note that any exception in the same task destroys this
-- information, so the data in this variable must be copied out before
-- another exception can occur.
--
-- Also act as a list of the active exceptions in the case of the GCC
-- exception mechanism, organized as a stack with the most recent first.
end record;
procedure Create_TSD
(New_TSD : in out TSD;
Sec_Stack : SST.SS_Stack_Ptr;
Sec_Stack_Size : System.Parameters.Size_Type);
pragma Inline (Create_TSD);
-- Called from s-tassta when a new thread is created to perform
-- any required initialization of the TSD.
procedure Destroy_TSD (Old_TSD : in out TSD);
pragma Inline (Destroy_TSD);
-- Called from s-tassta just before a thread is destroyed to perform
-- any required finalization.
function Get_GNAT_Exception return Ada.Exceptions.Exception_Id;
pragma Inline (Get_GNAT_Exception);
-- This function obtains the Exception_Id from the Exception_Occurrence
-- referenced by the Current_Excep field of the task specific data, i.e.
-- the call is equivalent to
-- Exception_Identity (Get_Current_Exception.all)
-- Export the Get/Set routines for the various Task Specific Data (TSD)
-- elements as callable subprograms instead of objects of access to
-- subprogram types.
function Get_Jmpbuf_Address_Soft return Address;
procedure Set_Jmpbuf_Address_Soft (Addr : Address);
pragma Inline (Get_Jmpbuf_Address_Soft);
pragma Inline (Set_Jmpbuf_Address_Soft);
function Get_Sec_Stack_Soft return SST.SS_Stack_Ptr;
procedure Set_Sec_Stack_Soft (Stack : SST.SS_Stack_Ptr);
pragma Inline (Get_Sec_Stack_Soft);
pragma Inline (Set_Sec_Stack_Soft);
-- The following is a dummy record designed to mimic Communication_Block as
-- defined in s-tpobop.ads:
-- type Communication_Block is record
-- Self : Task_Id; -- An access type
-- Enqueued : Boolean := True;
-- Cancelled : Boolean := False;
-- end record;
-- The record is used in the construction of the predefined dispatching
-- primitive _disp_asynchronous_select in order to avoid the import of
-- System.Tasking.Protected_Objects.Operations. Note that this package
-- is always imported in the presence of interfaces since the dispatch
-- table uses entities from here.
type Dummy_Communication_Block is record
Comp_1 : Address; -- Address and access have the same size
Comp_2 : Boolean;
Comp_3 : Boolean;
end record;
private
NT_TSD : TSD;
-- The task specific data for the main task when the Ada tasking run-time
-- is not used. It relies on the default initialization of NT_TSD. It is
-- placed here and not the body to ensure the default initialization does
-- not clobber the secondary stack initialization that occurs as part of
-- System.Soft_Links.Initialization.
end System.Soft_Links;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--------------------------------------------------------------------------------------------------------------------
with Interfaces.C;
with Interfaces.C.Strings;
with SDL.Error;
package body SDL.Video is
use type C.int;
function Is_Screen_Saver_Enabled return Boolean is
function SDL_Is_Screen_Saver_Enabled return C.int with
Import => True,
Convention => C,
External_Name => "SDL_IsScreenSaverEnabled";
begin
return (if SDL_Is_Screen_Saver_Enabled = 1 then True else False);
end Is_Screen_Saver_Enabled;
function Initialise (Name : in String) return Boolean is
function SDL_Video_Init (C_Name : in C.Strings.chars_ptr) return C.int with
Import => True,
Convention => C,
External_Name => "SDL_VideoInit";
C_Str : C.Strings.chars_ptr := C.Strings.Null_Ptr;
Result : C.int;
begin
if Name /= "" then
C_Str := C.Strings.New_String (Name);
Result := SDL_Video_Init (C_Name => C_Str);
C.Strings.Free (C_Str);
else
Result := SDL_Video_Init (C_Name => C.Strings.Null_Ptr);
end if;
return (Result = Success);
end Initialise;
function Total_Drivers return Positive is
function SDL_Get_Num_Video_Drivers return C.int with
Import => True,
Convention => C,
External_Name => "SDL_GetNumVideoDrivers";
Num : constant C.int := SDL_Get_Num_Video_Drivers;
begin
if Num < 0 then
raise Video_Error with SDL.Error.Get;
end if;
return Positive (Num);
end Total_Drivers;
function Driver_Name (Index : in Positive) return String is
function SDL_Get_Video_Driver (I : in C.int) return C.Strings.chars_ptr with
Import => True,
Convention => C,
External_Name => "SDL_GetVideoDriver";
-- Index is zero based, so need to subtract 1 to correct it.
C_Str : C.Strings.chars_ptr := SDL_Get_Video_Driver (C.int (Index) - 1);
begin
return C.Strings.Value (C_Str);
end Driver_Name;
function Current_Driver_Name return String is
function SDL_Get_Current_Video_Driver return C.Strings.chars_ptr with
Import => True,
Convention => C,
External_Name => "SDL_GetCurrentVideoDriver";
C_Str : constant C.Strings.chars_ptr := SDL_Get_Current_Video_Driver;
use type C.Strings.chars_ptr;
begin
if C_Str = C.Strings.Null_Ptr then
raise Video_Error with SDL.Error.Get;
end if;
return C.Strings.Value (C_Str);
end Current_Driver_Name;
function Total_Displays return Positive is
function SDL_Get_Num_Video_Displays return C.int with
Import => True,
Convention => C,
External_Name => "SDL_GetNumVideoDisplays";
Num : constant C.int := SDL_Get_Num_Video_Displays;
begin
if Num <= 0 then
raise Video_Error with SDL.Error.Get;
end if;
return Positive (Num);
end Total_Displays;
end SDL.Video;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Panel;
with HW.GFX.GMA.DP_Info;
with HW.Debug;
with GNAT.Source_Info;
package body HW.GFX.GMA.Connector_Info is
procedure Preferred_Link_Setting
(Port_Cfg : in out Port_Config;
Success : out Boolean)
is
DP_Port : constant GMA.DP_Port :=
(if Port_Cfg.Port = DIGI_A then
DP_A
else
(case Port_Cfg.PCH_Port is
when PCH_DP_B => DP_B,
when PCH_DP_C => DP_C,
when PCH_DP_D => DP_D,
when others => GMA.DP_Port'First));
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Display = DP then
if Port_Cfg.Port = DIGI_A then
if GMA.Config.Use_PP_VDD_Override then
Panel.VDD_Override;
else
Panel.On;
end if;
end if;
DP_Info.Read_Caps
(Link => Port_Cfg.DP,
Port => DP_Port,
Success => Success);
if Success then
DP_Info.Preferred_Link_Setting
(Link => Port_Cfg.DP,
Mode => Port_Cfg.Mode,
Success => Success);
pragma Debug (Success, DP_Info.Dump_Link_Setting (Port_Cfg.DP));
end if;
else
Success := True;
end if;
end Preferred_Link_Setting;
procedure Next_Link_Setting
(Port_Cfg : in out Port_Config;
Success : out Boolean)
is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Port_Cfg.Display = DP then
DP_Info.Next_Link_Setting
(Link => Port_Cfg.DP,
Mode => Port_Cfg.Mode,
Success => Success);
pragma Debug (Success, DP_Info.Dump_Link_Setting (Port_Cfg.DP));
else
Success := False;
end if;
end Next_Link_Setting;
----------------------------------------------------------------------------
function Default_BPC (Port_Cfg : Port_Config) return HW.GFX.BPC_Type
is
begin
return
(if Port_Cfg.Port = DIGI_A or
(Port_Cfg.Is_FDI and Port_Cfg.PCH_Port = PCH_LVDS) or
Port_Cfg.Port = LVDS
then 6
else 8);
end Default_BPC;
end HW.GFX.GMA.Connector_Info;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package FLTK.Images.Pixmaps.XPM is
type XPM_Image is new Pixmap with private;
type XPM_Image_Reference (Data : not null access XPM_Image'Class) is
limited null record with Implicit_Dereference => Data;
package Forge is
function Create
(Filename : in String)
return XPM_Image;
end Forge;
private
type XPM_Image is new Pixmap with null record;
overriding procedure Finalize
(This : in out XPM_Image);
end FLTK.Images.Pixmaps.XPM;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Program.Lexical_Elements;
with Program.Elements.Expressions;
with Program.Elements.Use_Clauses;
with Program.Element_Visitors;
package Program.Nodes.Use_Clauses is
pragma Preelaborate;
type Use_Clause is
new Program.Nodes.Node and Program.Elements.Use_Clauses.Use_Clause
and Program.Elements.Use_Clauses.Use_Clause_Text
with private;
function Create
(Use_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
All_Token : Program.Lexical_Elements.Lexical_Element_Access;
Type_Token : Program.Lexical_Elements.Lexical_Element_Access;
Clause_Names : not null Program.Elements.Expressions
.Expression_Vector_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Use_Clause;
type Implicit_Use_Clause is
new Program.Nodes.Node and Program.Elements.Use_Clauses.Use_Clause
with private;
function Create
(Clause_Names : not null Program.Elements.Expressions
.Expression_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False;
Has_All : Boolean := False;
Has_Type : Boolean := False)
return Implicit_Use_Clause
with Pre =>
Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance;
private
type Base_Use_Clause is
abstract new Program.Nodes.Node
and Program.Elements.Use_Clauses.Use_Clause
with record
Clause_Names : not null Program.Elements.Expressions
.Expression_Vector_Access;
end record;
procedure Initialize (Self : in out Base_Use_Clause'Class);
overriding procedure Visit
(Self : not null access Base_Use_Clause;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class);
overriding function Clause_Names
(Self : Base_Use_Clause)
return not null Program.Elements.Expressions.Expression_Vector_Access;
overriding function Is_Use_Clause (Self : Base_Use_Clause) return Boolean;
overriding function Is_Clause (Self : Base_Use_Clause) return Boolean;
type Use_Clause is
new Base_Use_Clause and Program.Elements.Use_Clauses.Use_Clause_Text
with record
Use_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
All_Token : Program.Lexical_Elements.Lexical_Element_Access;
Type_Token : Program.Lexical_Elements.Lexical_Element_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
end record;
overriding function To_Use_Clause_Text
(Self : in out Use_Clause)
return Program.Elements.Use_Clauses.Use_Clause_Text_Access;
overriding function Use_Token
(Self : Use_Clause)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function All_Token
(Self : Use_Clause)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Type_Token
(Self : Use_Clause)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Semicolon_Token
(Self : Use_Clause)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Has_All (Self : Use_Clause) return Boolean;
overriding function Has_Type (Self : Use_Clause) return Boolean;
type Implicit_Use_Clause is
new Base_Use_Clause
with record
Is_Part_Of_Implicit : Boolean;
Is_Part_Of_Inherited : Boolean;
Is_Part_Of_Instance : Boolean;
Has_All : Boolean;
Has_Type : Boolean;
end record;
overriding function To_Use_Clause_Text
(Self : in out Implicit_Use_Clause)
return Program.Elements.Use_Clauses.Use_Clause_Text_Access;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Use_Clause)
return Boolean;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Use_Clause)
return Boolean;
overriding function Is_Part_Of_Instance
(Self : Implicit_Use_Clause)
return Boolean;
overriding function Has_All (Self : Implicit_Use_Clause) return Boolean;
overriding function Has_Type (Self : Implicit_Use_Clause) return Boolean;
end Program.Nodes.Use_Clauses;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
private with Ada.Finalization;
with League.Strings;
with XML.SAX.Attributes;
with XML.SAX.Content_Handlers;
with XML.SAX.DTD_Handlers;
with XML.SAX.Entity_Resolvers;
with XML.SAX.Error_Handlers;
with XML.SAX.Input_Sources;
with XML.SAX.Locators;
with XML.SAX.Lexical_Handlers;
with XML.SAX.Parse_Exceptions;
package SAX_Events_Writers is
type SAX_Events_Writer is
limited new XML.SAX.Content_Handlers.SAX_Content_Handler
and XML.SAX.DTD_Handlers.SAX_DTD_Handler
and XML.SAX.Entity_Resolvers.SAX_Entity_Resolver
and XML.SAX.Error_Handlers.SAX_Error_Handler
and XML.SAX.Lexical_Handlers.SAX_Lexical_Handler with private;
not overriding procedure Set_Testsuite_URI
(Self : in out SAX_Events_Writer;
URI : League.Strings.Universal_String);
not overriding procedure Done (Self : in out SAX_Events_Writer);
not overriding function Has_Fatal_Errors
(Self : SAX_Events_Writer) return Boolean;
not overriding function Has_Errors
(Self : SAX_Events_Writer) return Boolean;
not overriding function Text
(Self : SAX_Events_Writer) return League.Strings.Universal_String;
overriding procedure Characters
(Self : in out SAX_Events_Writer;
Text : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure End_CDATA
(Self : in out SAX_Events_Writer;
Success : in out Boolean);
overriding procedure End_Document
(Self : in out SAX_Events_Writer;
Success : in out Boolean);
overriding procedure End_Element
(Self : in out SAX_Events_Writer;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure End_Prefix_Mapping
(Self : in out SAX_Events_Writer;
Prefix : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Error
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception;
Success : in out Boolean);
overriding function Error_String
(Self : SAX_Events_Writer)
return League.Strings.Universal_String;
overriding procedure Fatal_Error
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception);
overriding procedure Ignorable_Whitespace
(Self : in out SAX_Events_Writer;
Text : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Notation_Declaration
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Processing_Instruction
(Self : in out SAX_Events_Writer;
Target : League.Strings.Universal_String;
Data : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Resolve_Entity
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
Base_URI : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Source : out XML.SAX.Input_Sources.SAX_Input_Source_Access;
Success : in out Boolean);
overriding procedure Set_Document_Locator
(Self : in out SAX_Events_Writer;
Locator : XML.SAX.Locators.SAX_Locator);
overriding procedure Skipped_Entity
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Start_CDATA
(Self : in out SAX_Events_Writer;
Success : in out Boolean);
overriding procedure Start_Document
(Self : in out SAX_Events_Writer;
Success : in out Boolean);
overriding procedure Start_Element
(Self : in out SAX_Events_Writer;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean);
overriding procedure Start_Prefix_Mapping
(Self : in out SAX_Events_Writer;
Prefix : League.Strings.Universal_String;
URI : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Unparsed_Entity_Declaration
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Notation_Name : League.Strings.Universal_String;
Success : in out Boolean);
overriding procedure Warning
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception;
Success : in out Boolean);
private
type SAX_Events_Writer is
limited new Ada.Finalization.Limited_Controlled
and XML.SAX.Content_Handlers.SAX_Content_Handler
and XML.SAX.DTD_Handlers.SAX_DTD_Handler
and XML.SAX.Entity_Resolvers.SAX_Entity_Resolver
and XML.SAX.Error_Handlers.SAX_Error_Handler
and XML.SAX.Lexical_Handlers.SAX_Lexical_Handler with
record
Fatal_Errors : Boolean := False;
Errors : Boolean := False;
Result : League.Strings.Universal_String;
URI : League.Strings.Universal_String;
end record;
not overriding procedure Add_Line
(Self : in out SAX_Events_Writer;
Item : League.Strings.Universal_String);
-- Adds line to result.
overriding procedure Initialize (Self : in out SAX_Events_Writer);
end SAX_Events_Writers;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
--
-- SPARK Proof Analysis Tool
--
-- S.P.A.T. - GNAT project file (.gpr) support.
--
------------------------------------------------------------------------------
limited with SPAT.Strings;
limited with GNATCOLL.VFS;
package SPAT.GPR_Support is
---------------------------------------------------------------------------
-- Get_SPARK_Files
--
-- Retrieve all (existing) .spark files from the project.
---------------------------------------------------------------------------
function Get_SPARK_Files
(GPR_File : GNATCOLL.VFS.Filesystem_String) return Strings.File_Names;
end SPAT.GPR_Support;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with
openGL.Font,
openGL.Geometry;
package openGL.Model.sphere.lit_colored_textured
--
-- Models a lit, colored, textured sphere.
--
is
type Item is new Model.sphere.item with
record
Image : asset_Name := null_Asset; -- Usually a mercator projection to be mapped onto the sphere.
end record;
type View is access all Item'Class;
function new_Sphere (Radius : in Real;
Image : in asset_Name := null_Asset) return View;
overriding
function to_GL_Geometries (Self : access Item; Textures : access Texture.name_Map_of_texture'Class;
Fonts : in Font.font_id_Map_of_font) return Geometry.views;
end openGL.Model.sphere.lit_colored_textured;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- This program demonstrates the on-board gyro provided by the L3GD20 chip
-- on the STM32F429 Discovery boards. The pitch, roll, and yaw values are
-- continuously displayed on the LCD, as are the adjusted raw values. Move
-- the board to see them change. The values will be positive or negative,
-- depending on the direction of movement. Note that the values are not
-- constant, even when the board is not moving, due to noise.
-- This program demonstrates use of interrupts rather than polling.
-- NB: You may need to reset the board after downloading.
with Last_Chance_Handler; pragma Unreferenced (Last_Chance_Handler);
with Gyro_Interrupts;
with Output_Utils; use Output_Utils;
with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
with STM32.Device; use STM32.Device;
with STM32.Board; use STM32.Board;
with LCD_Std_Out;
with L3GD20; use L3GD20;
with STM32; use STM32;
with STM32.GPIO; use STM32.GPIO;
with STM32.EXTI; use STM32.EXTI;
procedure Demo_L3GD20 is
Axes : L3GD20.Angle_Rates;
Stable : L3GD20.Angle_Rates; -- the values when the board is motionless
Sensitivity : Float;
Scaled_X : Float;
Scaled_Y : Float;
Scaled_Z : Float;
procedure Get_Gyro_Offsets
(Offsets : out Angle_Rates;
Sample_Count : in Long_Integer);
-- Computes the averages for the gyro values returned when the board is
-- motionless
procedure Configure_Gyro;
-- Configures the on-board gyro chip
procedure Await_Raw_Angle_Rates (Rates : out Angle_Rates);
-- Returns the next angle rates available from the gyro, for all three
-- axes. Suspends until the gyro generates an interrupt indicating data
-- available. The interrupt handler sets a Suspension_Object to allow
-- the caller to resume, at which point it gets the raw data from the gyro.
procedure Configure_Gyro_Interrupt;
-- Configures the gyro's "data ready" interrupt (interrupt #2) on the
-- required port/pin for the F429 Discovery board. Enables the interrupt.
-- See the F429 Disco User Manual, Table 6, pg 19, for the port/pin.
---------------------------
-- Await_Raw_Angle_Rates --
---------------------------
procedure Await_Raw_Angle_Rates (Rates : out Angle_Rates) is
begin
Suspend_Until_True (Gyro_Interrupts.Data_Available);
Get_Raw_Angle_Rates (Gyro, Rates);
end Await_Raw_Angle_Rates;
--------------------
-- Configure_Gyro --
--------------------
procedure Configure_Gyro is
begin
-- Init the on-board gyro SPI and GPIO. This is board-specific, not
-- every board has a gyro. The F429 Discovery does, for example, but
-- the F4 Discovery does not.
STM32.Board.Initialize_Gyro_IO;
Gyro.Reset;
Gyro.Configure
(Power_Mode => L3GD20_Mode_Active,
Output_Data_Rate => L3GD20_Output_Data_Rate_95Hz,
Axes_Enable => L3GD20_Axes_Enable,
Bandwidth => L3GD20_Bandwidth_1,
BlockData_Update => L3GD20_BlockDataUpdate_Continous,
Endianness => L3GD20_Little_Endian,
Full_Scale => L3GD20_Fullscale_250);
Gyro.Enable_Low_Pass_Filter;
end Configure_Gyro;
------------------------------
-- Configure_Gyro_Interrupt --
------------------------------
procedure Configure_Gyro_Interrupt is
Config : GPIO_Port_Configuration;
-- This is the required port/pin configuration on STM32F429 Disco
-- boards for interrupt 2 on the L3GD20 gyro. See the F429 Disco
-- User Manual, Table 6, pg 19.
begin
Enable_Clock (MEMS_INT2);
Config.Mode := Mode_In;
Config.Resistors := Floating;
Config.Speed := Speed_50MHz;
Configure_IO (MEMS_INT2, Config);
Configure_Trigger (MEMS_INT2, Interrupt_Rising_Edge);
Gyro.Enable_Data_Ready_Interrupt; -- L3GD20 gyro interrupt 2
end Configure_Gyro_Interrupt;
----------------------
-- Get_Gyro_Offsets --
----------------------
procedure Get_Gyro_Offsets
(Offsets : out Angle_Rates;
Sample_Count : in Long_Integer)
is
Sample : Angle_Rates;
Total_X : Long_Integer := 0;
Total_Y : Long_Integer := 0;
Total_Z : Long_Integer := 0;
begin
for K in 1 .. Sample_Count loop
Await_Raw_Angle_Rates (Sample);
Total_X := Total_X + Long_Integer (Sample.X);
Total_Y := Total_Y + Long_Integer (Sample.Y);
Total_Z := Total_Z + Long_Integer (Sample.Z);
end loop;
Offsets.X := Angle_Rate (Total_X / Sample_Count);
Offsets.Y := Angle_Rate (Total_Y / Sample_Count);
Offsets.Z := Angle_Rate (Total_Z / Sample_Count);
end Get_Gyro_Offsets;
begin
LCD_Std_Out.Set_Font (Output_Utils.Selected_Font);
Configure_Gyro;
Configure_Gyro_Interrupt;
Sensitivity := Full_Scale_Sensitivity (Gyro);
Print (0, 0, "Calibrating");
Get_Gyro_Offsets (Stable, Sample_Count => 100); -- arbitrary count
Print_Static_Content (Stable);
loop
Await_Raw_Angle_Rates (Axes);
-- remove the computed stable offsets from the raw values
Axes.X := Axes.X - Stable.X;
Axes.Y := Axes.Y - Stable.Y;
Axes.Z := Axes.Z - Stable.Z;
-- print the values after the stable offset is removed
Print (Col_Adjusted, Line1_Adjusted, Axes.X'Img & " ");
Print (Col_Adjusted, Line2_Adjusted, Axes.Y'Img & " ");
Print (Col_Adjusted, Line3_Adjusted, Axes.Z'Img & " ");
-- scale the adjusted values
Scaled_X := Float (Axes.X) * Sensitivity;
Scaled_Y := Float (Axes.Y) * Sensitivity;
Scaled_Z := Float (Axes.Z) * Sensitivity;
-- print the final values
Print (Final_Column, Line1_Final, Scaled_X'Img & " ");
Print (Final_Column, Line2_Final, Scaled_Y'Img & " ");
Print (Final_Column, Line3_Final, Scaled_Z'Img & " ");
end loop;
end Demo_L3GD20;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Unchecked_Conversion;
with Ada.Directories;
with Ada.Containers.Vectors;
with Ada.Strings.Fixed;
with Util.Log.Loggers;
with Util.Files;
with Util.Concurrent.Counters;
package body Util.Properties.Bundles is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Properties.Bundles");
use Implementation;
procedure Free is
new Ada.Unchecked_Deallocation (Manager'Class,
Bundle_Manager_Access);
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package Interface_P is
package PropertyList is new Ada.Containers.Vectors
(Element_Type => Util.Properties.Manager_Access,
Index_Type => Natural,
"=" => "=");
type Manager is limited new Util.Properties.Implementation.Manager with record
List : PropertyList.Vector;
Props : aliased Util.Properties.Manager;
Count : Util.Concurrent.Counters.Counter := Util.Concurrent.Counters.ONE;
Shared : Boolean := False;
end record;
-- 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 Manager;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Manager;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Manager;
Name : in String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
procedure Load_Properties (Self : in out Manager;
File : in String);
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Manager)
return Util.Properties.Implementation.Manager_Access;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access);
package Shared_Implementation is
new Implementation.Shared_Implementation (Manager);
subtype Shared_Manager is Shared_Implementation.Manager;
function Allocate_Property return Implementation.Shared_Manager_Access is
(new Shared_Manager);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl is
new Implementation.Create (Allocator => Allocate_Property);
end Interface_P;
procedure Add_Bundle (Self : in out Manager;
Props : in Manager_Access) is
begin
Interface_P.Manager'Class (Self.Impl.all).Add_Bundle (Props);
end Add_Bundle;
procedure Initialize (Object : in out Manager) is
begin
Interface_P.Check_And_Create_Impl (Object);
end Initialize;
procedure Adjust (Object : in out Manager) is
begin
Interface_P.Check_And_Create_Impl (Object);
Object.Impl.Adjust;
end Adjust;
-- ------------------------------
-- Initialize the bundle factory and specify where the property files are stored.
-- ------------------------------
procedure Initialize (Factory : in out Loader;
Path : in String) is
begin
Log.Info ("Initialize bundle factory to load from {0}", Path);
Factory.Path := To_Unbounded_String (Path);
end Initialize;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class) is
Found : Boolean := False;
begin
Log.Info ("Load bundle {0} for language {1}", Name, Locale);
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Load_Bundle (Factory, Name, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
Find_Bundle (Factory, Name, Locale, Bundle, Found);
if not Found then
Log.Error ("Bundle {0} not found", Name);
raise NO_BUNDLE with "No bundle '" & Name & "'";
end if;
end if;
end Load_Bundle;
-- ------------------------------
-- Find the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Find_Bundle (Factory : in out Loader;
Name : in String;
Locale : in String;
Bundle : out Manager'Class;
Found : out Boolean) is
use Ada.Strings;
Loc_Name : constant String := '_' & Locale;
Last_Pos : Integer := Loc_Name'Last;
begin
Log.Debug ("Looking for bundle {0} and language {1}", Name, Locale);
Found := False;
Factory.Lock.Read;
declare
Pos : Bundle_Map.Cursor;
begin
while Last_Pos + 1 >= Loc_Name'First loop
declare
Bundle_Name : aliased constant String
:= Name & Loc_Name (Loc_Name'First .. Last_Pos);
begin
Log.Debug ("Searching for {0}", Bundle_Name);
Pos := Factory.Bundles.Find (Bundle_Name'Unrestricted_Access);
if Bundle_Map.Has_Element (Pos) then
Bundle.Finalize;
Bundle.Impl := Bundle_Map.Element (Pos).Impl;
Bundle.Impl.Adjust;
Found := True;
exit;
end if;
end;
if Last_Pos > Loc_Name'First then
Last_Pos := Fixed.Index (Loc_Name, "_", Last_Pos - 1, Backward) - 1;
else
Last_Pos := Last_Pos - 1;
end if;
end loop;
exception
when others =>
Factory.Lock.Release_Read;
raise;
end;
Factory.Lock.Release_Read;
end Find_Bundle;
-- ------------------------------
-- Load the bundle with the given name and for the given locale name.
-- ------------------------------
procedure Load_Bundle (Factory : in out Loader;
Name : in String;
Found : out Boolean) is
use Ada.Directories;
use Ada.Strings;
use Util.Strings;
use Ada.Containers;
use Util.Strings.String_Set;
use Bundle_Map;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean);
Path : constant String := To_String (Factory.Path);
Pattern : constant String := Name & "*.properties";
Names : Util.Strings.String_Set.Set;
procedure Process_File (Name : in String;
File_Path : in String;
Done : out Boolean) is
subtype Cursor is Bundle_Map.Cursor;
Base_Name : aliased constant String := Name (Name'First .. Name'Last - 11);
Pos : constant Cursor := Factory.Bundles.Find (Base_Name'Unchecked_Access);
Bundle_Name : Name_Access;
Bundle : Bundle_Manager_Access;
begin
Log.Info ("Loading file {0}", File_Path);
if Bundle_Map.Has_Element (Pos) then
Bundle := Bundle_Map.Element (Pos);
else
Bundle := new Manager;
Bundle_Name := new String '(Base_Name);
Factory.Bundles.Include (Key => Bundle_Name, New_Item => Bundle);
Names.Insert (Bundle_Name);
end if;
Interface_P.Manager'Class (Bundle.Impl.all).Load_Properties (File_Path);
Found := True;
Done := False;
end Process_File;
begin
Log.Info ("Reading bundle {1} in directory {0}", Path, Name);
Found := False;
Factory.Lock.Write;
begin
Util.Files.Iterate_Files_Path (Pattern => Pattern,
Path => Path,
Process => Process_File'Access,
Going => Ada.Strings.Backward);
-- Link the property files to implement the localization default rules.
while Names.Length > 0 loop
declare
Name_Pos : String_Set.Cursor := Names.First;
Bundle_Name : constant Name_Access := String_Set.Element (Name_Pos);
Idx : Natural := Fixed.Index (Bundle_Name.all, "_", Backward);
Bundle_Pos : constant Bundle_Map.Cursor := Factory.Bundles.Find (Bundle_Name);
Bundle : constant Bundle_Manager_Access := Element (Bundle_Pos);
begin
Names.Delete (Name_Pos);
-- Associate the property bundle to the first existing parent
-- Ex: message_fr_CA -> message_fr
-- message_fr_CA -> message
while Idx > 0 loop
declare
Name : aliased constant String
:= Bundle_Name (Bundle_Name'First .. Idx - 1);
Pos : constant Bundle_Map.Cursor
:= Factory.Bundles.Find (Name'Unchecked_Access);
begin
if Bundle_Map.Has_Element (Pos) then
Bundle.Add_Bundle (Bundle_Map.Element (Pos).all'Access);
Idx := 0;
else
Idx := Fixed.Index (Bundle_Name.all, "_", Idx - 1, Backward);
end if;
end;
end loop;
end;
end loop;
exception
when others =>
Factory.Lock.Release_Write;
raise;
end;
Factory.Lock.Release_Write;
exception
when Name_Error =>
Log.Error ("Cannot read directory: {0}", Path);
end Load_Bundle;
-- Implementation of the Bundle
-- (this allows to decouples the implementation from the API)
package body Interface_P is
use PropertyList;
-- 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 Manager;
Name : in String) return Util.Beans.Objects.Object is
Result : Util.Beans.Objects.Object := From.Props.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Result) then
declare
Iter : Cursor := From.List.First;
begin
while Has_Element (Iter) loop
Result := Element (Iter).all.Get_Value (Name);
exit when not Util.Beans.Objects.Is_Null (Result);
Iter := Next (Iter);
end loop;
end;
end if;
return Result;
end Get_Value;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
function Exists (Self : in Manager; Name : in String)
return Boolean is
Iter : Cursor := Self.List.First;
begin
if Self.Props.Exists (Name) then
return True;
end if;
while Has_Element (Iter) loop
if Element (Iter).Exists (Name) then
return True;
end if;
Iter := Next (Iter);
end loop;
return False;
end Exists;
procedure Load_Properties (Self : in out Manager;
File : in String) is
begin
Self.Props.Load_Properties (File);
end Load_Properties;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager;
Name : in String) is
begin
raise NOT_WRITEABLE with "Bundle is readonly";
end Remove;
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object)) is
begin
raise Program_Error with "Iterate is not implemented on Bundle";
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
overriding
function Create_Copy (Self : in Manager)
return Util.Properties.Implementation.Manager_Access is
pragma Unreferenced (Self);
begin
return null;
end Create_Copy;
procedure Add_Bundle (Self : in out Manager;
Props : in Util.Properties.Manager_Access) is
begin
Self.List.Append (Props);
end Add_Bundle;
end Interface_P;
-- ------------------------------
-- Clear the bundle cache
-- ------------------------------
procedure Clear_Cache (Factory : in out Loader) is
use Util.Strings;
use Bundle_Map;
function To_String_Access is
new Ada.Unchecked_Conversion (Source => Util.Strings.Name_Access,
Target => Ada.Strings.Unbounded.String_Access);
begin
Log.Info ("Clearing bundle cache");
Factory.Lock.Write;
loop
declare
Pos : Bundle_Map.Cursor := Factory.Bundles.First;
Name : Ada.Strings.Unbounded.String_Access;
Node : Bundle_Manager_Access;
begin
exit when not Has_Element (Pos);
Node := Element (Pos);
Name := To_String_Access (Key (Pos));
Factory.Bundles.Delete (Pos);
Free (Node);
Free (Name);
end;
end loop;
Factory.Lock.Release_Write;
end Clear_Cache;
-- ------------------------------
-- Finalize the bundle loader and clear the cache
-- ------------------------------
procedure Finalize (Factory : in out Loader) is
begin
Clear_Cache (Factory);
end Finalize;
end Util.Properties.Bundles;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package is an internal package that provides basic character
-- classification capabilities needed by the compiler for handling full
-- 32-bit wide wide characters. We avoid the use of the actual type
-- Wide_Wide_Character, since we want to use these routines in the compiler
-- itself, and we want to be able to compile the compiler with old versions
-- of GNAT that did not implement Wide_Wide_Character.
-- System.UTF_32 should not be directly used from an application program, but
-- an equivalent package GNAT.UTF_32 can be used directly and provides exactly
-- the same services. The reason this package is in System is so that it can
-- with'ed by other packages in the Ada and System hierarchies.
pragma Compiler_Unit_Warning;
package System.UTF_32 is
pragma Pure;
type UTF_32 is range 0 .. 16#7FFF_FFFF#;
-- So far, the only defined character codes are in 0 .. 16#01_FFFF#
-- The following type defines the categories from the unicode definitions.
-- The one addition we make is Fe, which represents the characters FFFE
-- and FFFF in any of the planes.
type Category is (
Cc, -- Other, Control
Cf, -- Other, Format
Cn, -- Other, Not Assigned
Co, -- Other, Private Use
Cs, -- Other, Surrogate
Ll, -- Letter, Lowercase
Lm, -- Letter, Modifier
Lo, -- Letter, Other
Lt, -- Letter, Titlecase
Lu, -- Letter, Uppercase
Mc, -- Mark, Spacing Combining
Me, -- Mark, Enclosing
Mn, -- Mark, Nonspacing
Nd, -- Number, Decimal Digit
Nl, -- Number, Letter
No, -- Number, Other
Pc, -- Punctuation, Connector
Pd, -- Punctuation, Dash
Pe, -- Punctuation, Close
Pf, -- Punctuation, Final quote
Pi, -- Punctuation, Initial quote
Po, -- Punctuation, Other
Ps, -- Punctuation, Open
Sc, -- Symbol, Currency
Sk, -- Symbol, Modifier
Sm, -- Symbol, Math
So, -- Symbol, Other
Zl, -- Separator, Line
Zp, -- Separator, Paragraph
Zs, -- Separator, Space
Fe); -- relative position FFFE/FFFF in any plane
function Get_Category (U : UTF_32) return Category;
-- Given a UTF32 code, returns corresponding Category, or Cn if
-- the code does not have an assigned unicode category.
-- The following functions perform category tests corresponding to lexical
-- classes defined in the Ada standard. There are two interfaces for each
-- function. The second takes a Category (e.g. returned by Get_Category).
-- The first takes a UTF_32 code. The form taking the UTF_32 code is
-- typically more efficient than calling Get_Category, but if several
-- different tests are to be performed on the same code, it is more
-- efficient to use Get_Category to get the category, then test the
-- resulting category.
function Is_UTF_32_Letter (U : UTF_32) return Boolean;
function Is_UTF_32_Letter (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Letter);
-- Returns true iff U is a letter that can be used to start an identifier,
-- or if C is one of the corresponding categories, which are the following:
-- Letter, Uppercase (Lu)
-- Letter, Lowercase (Ll)
-- Letter, Titlecase (Lt)
-- Letter, Modifier (Lm)
-- Letter, Other (Lo)
-- Number, Letter (Nl)
function Is_UTF_32_Digit (U : UTF_32) return Boolean;
function Is_UTF_32_Digit (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Digit);
-- Returns true iff U is a digit that can be used to extend an identifier,
-- or if C is one of the corresponding categories, which are the following:
-- Number, Decimal_Digit (Nd)
function Is_UTF_32_Line_Terminator (U : UTF_32) return Boolean;
pragma Inline (Is_UTF_32_Line_Terminator);
-- Returns true iff U is an allowed line terminator for source programs,
-- if U is in the category Zp (Separator, Paragraph), or Zl (Separator,
-- Line), or if U is a conventional line terminator (CR, LF, VT, FF).
-- There is no category version for this function, since the set of
-- characters does not correspond to a set of Unicode categories.
function Is_UTF_32_Mark (U : UTF_32) return Boolean;
function Is_UTF_32_Mark (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Mark);
-- Returns true iff U is a mark character which can be used to extend an
-- identifier, or if C is one of the corresponding categories, which are
-- the following:
-- Mark, Non-Spacing (Mn)
-- Mark, Spacing Combining (Mc)
function Is_UTF_32_Other (U : UTF_32) return Boolean;
function Is_UTF_32_Other (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Other);
-- Returns true iff U is an other format character, which means that it
-- can be used to extend an identifier, but is ignored for the purposes of
-- matching of identifiers, or if C is one of the corresponding categories,
-- which are the following:
-- Other, Format (Cf)
function Is_UTF_32_Punctuation (U : UTF_32) return Boolean;
function Is_UTF_32_Punctuation (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Punctuation);
-- Returns true iff U is a punctuation character that can be used to
-- separate pieces of an identifier, or if C is one of the corresponding
-- categories, which are the following:
-- Punctuation, Connector (Pc)
function Is_UTF_32_Space (U : UTF_32) return Boolean;
function Is_UTF_32_Space (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Space);
-- Returns true iff U is considered a space to be ignored, or if C is one
-- of the corresponding categories, which are the following:
-- Separator, Space (Zs)
function Is_UTF_32_Non_Graphic (U : UTF_32) return Boolean;
function Is_UTF_32_Non_Graphic (C : Category) return Boolean;
pragma Inline (Is_UTF_32_Non_Graphic);
-- Returns true iff U is considered to be a non-graphic character, or if C
-- is one of the corresponding categories, which are the following:
-- Other, Control (Cc)
-- Other, Private Use (Co)
-- Other, Surrogate (Cs)
-- Separator, Line (Zl)
-- Separator, Paragraph (Zp)
-- FFFE or FFFF positions in any plane (Fe)
--
-- Note that the Ada category format effector is subsumed by the above
-- list of Unicode categories.
--
-- Note that Other, Unassigned (Cn) is quite deliberately not included
-- in the list of categories above. This means that should any of these
-- code positions be defined in future with graphic characters they will
-- be allowed without a need to change implementations or the standard.
--
-- Note that Other, Format (Cf) is also quite deliberately not included
-- in the list of categories above. This means that these characters can
-- be included in character and string literals.
-- The following function is used to fold to upper case, as required by
-- the Ada 2005 standard rules for identifier case folding. Two
-- identifiers are equivalent if they are identical after folding all
-- letters to upper case using this routine. A corresponding routine to
-- fold to lower case is also provided.
function UTF_32_To_Lower_Case (U : UTF_32) return UTF_32;
pragma Inline (UTF_32_To_Lower_Case);
-- If U represents an upper case letter, returns the corresponding lower
-- case letter, otherwise U is returned unchanged. The folding rule is
-- simply that if the code corresponds to a 10646 entry whose name contains
-- the string CAPITAL LETTER, and there is a corresponding entry whose name
-- is the same but with CAPITAL LETTER replaced by SMALL LETTER, then the
-- code is folded to this SMALL LETTER code. Otherwise the input code is
-- returned unchanged.
function UTF_32_To_Upper_Case (U : UTF_32) return UTF_32;
pragma Inline (UTF_32_To_Upper_Case);
-- If U represents a lower case letter, returns the corresponding lower
-- case letter, otherwise U is returned unchanged. The folding rule is
-- simply that if the code corresponds to a 10646 entry whose name contains
-- the string SMALL LETTER, and there is a corresponding entry whose name
-- is the same but with SMALL LETTER replaced by CAPITAL LETTER, then the
-- code is folded to this CAPITAL LETTER code. Otherwise the input code is
-- returned unchanged.
end System.UTF_32;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with
freetype_C.FT_GlyphSlot;
package openGL.GlyphImpl
--
-- Implements an openGL glyph.
--
is
type Item is tagged private;
type View is access all Item'Class;
---------
-- Types
--
subtype error_Kind is freetype_C.FT_Error;
no_Error : constant error_Kind;
---------
-- Forge
--
procedure define (Self : in out Item; glyth_Slot : in freetype_c.FT_GlyphSlot.item);
--
-- glyth_Slot: The Freetype glyph to be processed.
--------------
-- Attributes
--
function Advance (Self : in Item) return Real; -- The advance distance for this glyph.
function BBox (Self : in Item) return Bounds; -- Return the bounding box for this glyph.
function Error (Self : in Item) return error_Kind; -- Return the current error code.
private
type Item is tagged
record
Advance : Vector_3;
bBox : Bounds;
Err : error_Kind;
end record;
procedure destruct (Self : in out Item);
no_Error : constant error_Kind := 0;
end openGL.GlyphImpl;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- 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 generic functions which are instantiated with
-- predefined integer and real types to generate the runtime exponentiation
-- functions called by expanded code generated by Expand_Op_Expon. This
-- version of the package contains routines that are compiled with overflow
-- checks suppressed, so they are called for exponentiation operations which
-- do not require overflow checking
package System.Exn_Gen is
pragma Pure (System.Exn_Gen);
-- Exponentiation for float types (checks off)
generic
type Type_Of_Base is digits <>;
function Exn_Float_Type
(Left : Type_Of_Base;
Right : Integer)
return Type_Of_Base;
-- Exponentiation for signed integer base
generic
type Type_Of_Base is range <>;
function Exn_Integer_Type
(Left : Type_Of_Base;
Right : Natural)
return Type_Of_Base;
end System.Exn_Gen;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Ada.Containers;
with Ada.Containers.Vectors;
with Util.Serialize.Contexts;
with Util.Serialize.Mappers.Record_Mapper;
with Util.Serialize.IO;
generic
-- Package that represents the vectors of elements.
with package Vectors is
new Ada.Containers.Vectors (<>);
-- Package that maps the element into a record.
with package Element_Mapper is
new Record_Mapper (Element_Type => Vectors.Element_Type,
others => <>);
package Util.Serialize.Mappers.Vector_Mapper is
subtype Element_Type is Vectors.Element_Type;
subtype Vector is Vectors.Vector;
subtype Index_Type is Vectors.Index_Type;
type Vector_Type_Access is access all Vector;
-- Procedure to give access to the <b>Vector</b> object from the context.
type Process_Object is not null
access procedure (Ctx : in out Util.Serialize.Contexts.Context'Class;
Process : not null access procedure (Item : in out Vector));
-- -----------------------
-- Data context
-- -----------------------
-- Data context to get access to the target element.
type Vector_Data is new Util.Serialize.Contexts.Data with private;
type Vector_Data_Access is access all Vector_Data'Class;
-- Get the vector object.
function Get_Vector (Data : in Vector_Data) return Vector_Type_Access;
-- Set the vector object.
procedure Set_Vector (Data : in out Vector_Data;
Vector : in Vector_Type_Access);
-- -----------------------
-- Record mapper
-- -----------------------
type Mapper is new Util.Serialize.Mappers.Mapper with private;
type Mapper_Access is access all Mapper'Class;
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object);
-- Set the <b>Data</b> vector in the context.
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Data : in Vector_Type_Access);
procedure Set_Mapping (Into : in out Mapper;
Inner : in Element_Mapper.Mapper_Access);
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
function Find_Mapper (Controller : in Mapper;
Name : in String) return Util.Serialize.Mappers.Mapper_Access;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String);
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String);
-- Write the element on the stream using the mapper description.
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Vectors.Vector);
private
type Vector_Data is new Util.Serialize.Contexts.Data with record
Vector : Vector_Type_Access;
Position : Index_Type;
end record;
type Mapper is new Util.Serialize.Mappers.Mapper with record
Map : aliased Element_Mapper.Mapper;
end record;
overriding
procedure Initialize (Controller : in out Mapper);
end Util.Serialize.Mappers.Vector_Mapper;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with GNAT.Regpat;
with Ada.Strings.Unbounded;
with Util.Files;
with ASF.Streams;
with ASF.Servlets.Faces;
with ASF.Servlets.Files;
with ASF.Servlets.Ajax;
with ASF.Servlets.Measures;
with ASF.Responses;
with ASF.Responses.Tools;
with ASF.Filters.Dump;
package body ASF.Tests is
use Ada.Strings.Unbounded;
use Util.Tests;
CONTEXT_PATH : constant String := "/asfunit";
Server : access ASF.Server.Container;
App : ASF.Applications.Main.Application_Access := null;
Faces : aliased ASF.Servlets.Faces.Faces_Servlet;
Files : aliased ASF.Servlets.Files.File_Servlet;
Ajax : aliased ASF.Servlets.Ajax.Ajax_Servlet;
Dump : aliased ASF.Filters.Dump.Dump_Filter;
Measures : aliased ASF.Servlets.Measures.Measure_Servlet;
-- Save the response headers and content in a file
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response);
-- ------------------------------
-- Initialize the awa test framework mockup.
-- ------------------------------
procedure Initialize (Props : in Util.Properties.Manager;
Application : in ASF.Applications.Main.Application_Access := null;
Factory : in out ASF.Applications.Main.Application_Factory'Class) is
use type ASF.Applications.Main.Application_Access;
C : ASF.Applications.Config;
begin
if Application /= null then
App := Application;
else
App := new ASF.Applications.Main.Application;
end if;
Server := new ASF.Server.Container;
Server.Register_Application (CONTEXT_PATH, App.all'Access);
C.Copy (Props);
App.Initialize (C, Factory);
App.Register ("layoutMsg", "layout");
App.Set_Global ("contextPath", CONTEXT_PATH);
-- Register the servlets and filters
App.Add_Servlet (Name => "faces", Server => Faces'Access);
App.Add_Servlet (Name => "files", Server => Files'Access);
App.Add_Servlet (Name => "ajax", Server => Ajax'Access);
App.Add_Servlet (Name => "measures", Server => Measures'Access);
App.Add_Filter (Name => "dump", Filter => Dump'Access);
App.Add_Filter (Name => "measures", Filter => Measures'Access);
-- Define servlet mappings
App.Add_Mapping (Name => "faces", Pattern => "*.html");
App.Add_Mapping (Name => "files", Pattern => "*.css");
App.Add_Mapping (Name => "files", Pattern => "*.js");
App.Add_Mapping (Name => "files", Pattern => "*.properties");
App.Add_Mapping (Name => "files", Pattern => "*.xhtml");
App.Add_Mapping (Name => "ajax", Pattern => "/ajax/*");
App.Add_Mapping (Name => "measures", Pattern => "stats.xml");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "/ajax/*");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "measures", Pattern => "*.xhtml");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.html");
App.Add_Filter_Mapping (Name => "dump", Pattern => "*.css");
App.Add_Filter_Mapping (Name => "dump", Pattern => "/ajax/*");
end Initialize;
-- ------------------------------
-- Get the server
-- ------------------------------
function Get_Server return access ASF.Server.Container is
begin
return Server;
end Get_Server;
-- ------------------------------
-- Get the test application.
-- ------------------------------
function Get_Application return ASF.Applications.Main.Application_Access is
begin
return App;
end Get_Application;
-- ------------------------------
-- Save the response headers and content in a file
-- ------------------------------
procedure Save_Response (Name : in String;
Response : in out ASF.Responses.Mockup.Response) is
use ASF.Responses;
Info : constant String := Tools.To_String (Reply => Response,
Html => False,
Print_Headers => True);
Result_Path : constant String := Util.Tests.Get_Test_Path ("regtests/result");
Content : Unbounded_String;
Stream : ASF.Streams.Print_Stream := Response.Get_Output_Stream;
begin
Response.Read_Content (Content);
Stream.Write (Content);
Insert (Content, 1, Info);
Util.Files.Write_File (Result_Path & "/" & Name, Content);
end Save_Response;
-- ------------------------------
-- Simulate a raw request. The URI and method must have been set on the Request object.
-- ------------------------------
procedure Do_Req (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response) is
begin
-- For the purpose of writing tests, clear the buffer before invoking the service.
Response.Clear;
Server.Service (Request => Request,
Response => Response);
end Do_Req;
-- ------------------------------
-- Simulate a GET request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Get (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "GET");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Get;
-- ------------------------------
-- Simulate a POST request on the given URI with the request parameters.
-- Get the result in the response object.
-- ------------------------------
procedure Do_Post (Request : in out ASF.Requests.Mockup.Request;
Response : in out ASF.Responses.Mockup.Response;
URI : in String;
Save : in String := "") is
begin
Request.Set_Method (Method => "POST");
Request.Set_Request_URI (URI => CONTEXT_PATH & URI);
Request.Set_Protocol (Protocol => "HTTP/1.1");
Do_Req (Request, Response);
if Save'Length > 0 then
Save_Response (Save, Response);
end if;
end Do_Post;
-- ------------------------------
-- Check that the response body contains the string
-- ------------------------------
procedure Assert_Contains (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, ASF.Responses.SC_OK, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Index (Content, Value) > 0,
Message => Message & ": value '" & Value & "' not found",
Source => Source,
Line => Line);
end Assert_Contains;
-- ------------------------------
-- Check that the response body matches the regular expression
-- ------------------------------
procedure Assert_Matches (T : in Util.Tests.Test'Class;
Pattern : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Status : in Natural := ASF.Responses.SC_OK;
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
use GNAT.Regpat;
Stream : ASF.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Unbounded_String;
Regexp : constant Pattern_Matcher := Compile (Expression => Pattern,
Flags => Multiple_Lines);
begin
Reply.Read_Content (Content);
Stream.Write (Content);
Assert_Equals (T, Status, Reply.Get_Status, "Invalid response", Source, Line);
T.Assert (Condition => Match (Regexp, To_String (Content)),
Message => Message & ": does not match '" & Pattern & "'",
Source => Source,
Line => Line);
end Assert_Matches;
-- ------------------------------
-- Check that the response body is a redirect to the given URI.
-- ------------------------------
procedure Assert_Redirect (T : in Util.Tests.Test'Class;
Value : in String;
Reply : in out ASF.Responses.Mockup.Response;
Message : in String := "Test failed";
Source : String := GNAT.Source_Info.File;
Line : Natural := GNAT.Source_Info.Line) is
begin
Assert_Equals (T, ASF.Responses.SC_MOVED_TEMPORARILY, Reply.Get_Status,
"Invalid response", Source, Line);
Util.Tests.Assert_Equals (T, Value, Reply.Get_Header ("Location"),
Message & ": missing Location",
Source, Line);
end Assert_Redirect;
end ASF.Tests;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Program.Elements.Discrete_Ranges;
with Program.Elements.Attribute_References;
package Program.Elements.Discrete_Range_Attribute_References is
pragma Pure (Program.Elements.Discrete_Range_Attribute_References);
type Discrete_Range_Attribute_Reference is
limited interface and Program.Elements.Discrete_Ranges.Discrete_Range;
type Discrete_Range_Attribute_Reference_Access is
access all Discrete_Range_Attribute_Reference'Class
with Storage_Size => 0;
not overriding function Range_Attribute
(Self : Discrete_Range_Attribute_Reference)
return not null Program.Elements.Attribute_References
.Attribute_Reference_Access is abstract;
type Discrete_Range_Attribute_Reference_Text is limited interface;
type Discrete_Range_Attribute_Reference_Text_Access is
access all Discrete_Range_Attribute_Reference_Text'Class
with Storage_Size => 0;
not overriding function To_Discrete_Range_Attribute_Reference_Text
(Self : aliased in out Discrete_Range_Attribute_Reference)
return Discrete_Range_Attribute_Reference_Text_Access is abstract;
end Program.Elements.Discrete_Range_Attribute_References;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Gen.Utils;
with Gen.Model;
with Gen.Model.Mappings;
-- The <b>Gen.Artifacts.Mappings</b> package is an artifact to map XML-based types
-- into Ada types.
package body Gen.Artifacts.Mappings is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Artifacts.Query");
-- ------------------------------
-- After the configuration file is read, processes the node whose root
-- is passed in <b>Node</b> and initializes the <b>Model</b> with the information.
-- ------------------------------
overriding
procedure Initialize (Handler : in out Artifact;
Path : in String;
Node : in DOM.Core.Node;
Model : in out Gen.Model.Packages.Model_Definition'Class;
Context : in out Generator'Class) is
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
-- ------------------------------
-- Register a new type mapping.
-- ------------------------------
procedure Register_Mapping (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node);
N : constant DOM.Core.Node := Gen.Utils.Get_Child (Node, "to");
To : constant String := Gen.Utils.Get_Data_Content (N);
Kind : constant String := To_String (Gen.Utils.Get_Attribute (Node, "type"));
Allow_Null : constant Boolean := Gen.Utils.Get_Attribute (Node, "allow-null", False);
Kind_Type : Gen.Model.Mappings.Basic_Type;
procedure Register_Type (O : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
pragma Unreferenced (O);
From : constant String := Gen.Utils.Get_Data_Content (Node);
begin
Gen.Model.Mappings.Register_Type (Target => To,
From => From,
Kind => Kind_Type,
Allow_Null => Allow_Null);
end Register_Type;
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Type);
begin
if Kind = "date" or To = "Ada.Calendar.Time" then
Kind_Type := Gen.Model.Mappings.T_DATE;
elsif Kind = "identifier" or To = "ADO.Identifier" then
Kind_Type := Gen.Model.Mappings.T_IDENTIFIER;
elsif Kind = "boolean" then
Kind_Type := Gen.Model.Mappings.T_BOOLEAN;
elsif Kind = "float" then
Kind_Type := Gen.Model.Mappings.T_FLOAT;
elsif Kind = "string" or To = "Ada.Strings.Unbounded.Unbounded_String" then
Kind_Type := Gen.Model.Mappings.T_STRING;
elsif Kind = "blob" or To = "ADO.Blob_Ref" then
Kind_Type := Gen.Model.Mappings.T_BLOB;
elsif Kind = "entity_type" or To = "ADO.Entity_Type" then
Kind_Type := Gen.Model.Mappings.T_ENTITY_TYPE;
else
Kind_Type := Gen.Model.Mappings.T_INTEGER;
end if;
Iterate (O, Node, "from");
end Register_Mapping;
-- ------------------------------
-- Register a model mapping
-- ------------------------------
procedure Register_Mappings (Model : in out Gen.Model.Packages.Model_Definition;
Node : in DOM.Core.Node) is
procedure Iterate is
new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mapping);
Name : constant String := Gen.Utils.Get_Attribute (Node, "name");
begin
Gen.Model.Mappings.Set_Mapping_Name (Name);
Iterate (Model, Node, "mapping");
end Register_Mappings;
procedure Iterate is new Gen.Utils.Iterate_Nodes (T => Gen.Model.Packages.Model_Definition,
Process => Register_Mappings);
begin
Log.Debug ("Initializing mapping artifact for the configuration");
Gen.Artifacts.Artifact (Handler).Initialize (Path, Node, Model, Context);
Iterate (Gen.Model.Packages.Model_Definition (Model), Node, "mappings");
end Initialize;
end Gen.Artifacts.Mappings;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces.C, Interfaces.C.Extensions, Ada.Unchecked_Conversion;
package body Libtcod.Maps.Lines is
use bresenham_h, Interfaces.C, Interfaces.C.Extensions;
type Int_Ptr is access all int;
type X_Pos_Ptr is access all X_Pos;
type Y_Pos_Ptr is access all Y_Pos;
function X_Ptr_To_Int_Ptr is new Ada.Unchecked_Conversion
(Source => X_Pos_Ptr, Target => Int_Ptr);
function Y_Ptr_To_Int_Ptr is new Ada.Unchecked_Conversion
(Source => Y_Pos_Ptr, Target => Int_Ptr);
function Line_Cb_To_TCOD_Cb is new Ada.Unchecked_Conversion
(Source => Line_Callback, Target => TCOD_line_listener_t);
---------------
-- make_line --
---------------
function make_line(start_x : X_Pos; start_y : Y_Pos;
end_x : X_Pos; end_y : Y_Pos) return Line is
begin
return l : Line do
TCOD_line_init_mt(int(start_x), int(start_y),
int(end_x), int(end_y), l.data'Access);
end return;
end make_line;
---------------
-- copy_line --
---------------
procedure copy_line(a : Line; b : out Line) is
begin
b.data := a.data;
end copy_line;
----------
-- step --
----------
function step(l : aliased in out Line;
x : aliased in out X_Pos; y : aliased in out Y_Pos) return Boolean is
(Boolean(TCOD_line_step_mt(X_Ptr_To_Int_Ptr(x'Unchecked_Access),
Y_Ptr_To_Int_Ptr(y'Unchecked_Access),
l.data'Access)));
----------------
-- visit_line --
----------------
function visit_line(start_x : X_Pos; start_y : Y_Pos;
end_x : X_Pos; end_y : Y_Pos; cb : Line_Callback) return Boolean is
(Boolean(TCOD_line(int(start_x), int(start_y), int(end_x), int(end_y),
Line_Cb_To_TCOD_Cb(cb))));
end Libtcod.Maps.Lines;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with TEXT_IO;
with DIRECT_IO;
with STRINGS_PACKAGE; use STRINGS_PACKAGE;
with INFLECTIONS_PACKAGE; use INFLECTIONS_PACKAGE;
with DICTIONARY_PACKAGE; use DICTIONARY_PACKAGE;
procedure SORTER is
-- This program sorts a file of lines (strings) on 5 substrings Mx..Nx
-- Sort by stringwise (different cases), numeric, or POS enumeration
package BOOLEAN_IO is new TEXT_IO.ENUMERATION_IO(BOOLEAN);
use BOOLEAN_IO;
package INTEGER_IO is new TEXT_IO.INTEGER_IO(INTEGER);
use INTEGER_IO;
package FLOAT_IO is new TEXT_IO.FLOAT_IO(FLOAT);
use FLOAT_IO;
use TEXT_IO;
NAME_LENGTH : constant := 80;
ST, ENTER_LINE : STRING(1..NAME_LENGTH) := (others => ' ');
LS, LAST : INTEGER := 0;
INPUT_NAME : STRING(1..80) := (others => ' ');
LINE_LENGTH : constant := 300; -- ##################################
-- Max line length on input file
-- Shorter => less disk space to sort
CURRENT_LENGTH : INTEGER := 0;
subtype TEXT_TYPE is STRING(1..LINE_LENGTH);
--type LINE_TYPE is
-- record
-- CURRENT_LENGTH : CURRENT_LINE_LENGTH_TYPE := 0;
-- TEXT : TEXT_TYPE;
-- end record;
package LINE_IO is new DIRECT_IO(TEXT_TYPE);
use LINE_IO;
BLANK_TEXT : TEXT_TYPE := (others => ' ');
LINE_TEXT : TEXT_TYPE := BLANK_TEXT;
OLD_LINE : TEXT_TYPE := BLANK_TEXT;
P_LINE : TEXT_TYPE := BLANK_TEXT;
type SORT_TYPE is (A, C, G, U, N, F, P, R, S);
package SORT_TYPE_IO is new TEXT_IO.ENUMERATION_IO(SORT_TYPE);
use SORT_TYPE_IO;
type WAY_TYPE is (I, D);
package WAY_TYPE_IO is new TEXT_IO.ENUMERATION_IO(WAY_TYPE);
use WAY_TYPE_IO;
INPUT : TEXT_IO.FILE_TYPE;
OUTPUT : TEXT_IO.FILE_TYPE;
WORK : LINE_IO.FILE_TYPE;
M1, M2, M3, M4, M5 : NATURAL := 1;
N1, N2, N3, N4, N5 : NATURAL := LINE_LENGTH;
Z1, Z2, Z3, Z4, Z5 : NATURAL := 0;
S1, S2, S3, S4, S5 : SORT_TYPE := A;
W1, W2, W3, W4, W5 : WAY_TYPE := I;
ENTRY_FINISHED : exception;
-- For section numbering of large documents and standards
type SECTION_TYPE is
record
FIRST_LEVEL : INTEGER := 0;
SECOND_LEVEL : INTEGER := 0;
THIRD_LEVEL : INTEGER := 0;
FOURTH_LEVEL : INTEGER := 0;
FIFTH_LEVEL : INTEGER := 0;
end record;
NO_SECTION : constant SECTION_TYPE := (0, 0, 0, 0, 0);
type APPENDIX_TYPE is (NONE, A, B, C, D, E, F, G, H, I, J, K, L, M,
N, O, P, Q, R, S, T, U, V, W, X, Y, Z);
package APPENDIX_IO is new TEXT_IO.ENUMERATION_IO(APPENDIX_TYPE);
type APPENDIX_SECTION_TYPE is record
APPENDIX : APPENDIX_TYPE := NONE;
SECTION : SECTION_TYPE := NO_SECTION;
end record;
NO_APPENDIX_SECTION : constant APPENDIX_SECTION_TYPE :=
(NONE, (0, 0, 0, 0, 0));
-- procedure PUT(OUTPUT : TEXT_IO.FILE_TYPE; S : SECTION_TYPE);
-- procedure PUT(S : SECTION_TYPE);
-- procedure GET(FROM : in STRING;
-- S : out SECTION_TYPE; LAST : out POSITIVE);
-- function "<"(A, B : SECTION_TYPE) return BOOLEAN;
--
-- procedure PUT(OUTPUT : TEXT_IO.FILE_TYPE; S : APPENDIX_SECTION_TYPE);
-- procedure PUT(S : APPENDIX_SECTION_TYPE);
-- procedure GET(FROM : in STRING;
-- S : out APPENDIX_SECTION_TYPE; LAST : out POSITIVE);
-- function "<"(A, B : APPENDIX_SECTION_TYPE) return BOOLEAN;
--
procedure PUT(OUTPUT : TEXT_IO.FILE_TYPE; S : SECTION_TYPE) is
LEVEL : INTEGER := 0;
procedure PUT_LEVEL(OUTPUT : TEXT_IO.FILE_TYPE; L : INTEGER) is
begin
if L > 9999 then
PUT(OUTPUT, "****");
elsif L > 999 then
PUT(OUTPUT, L, 4);
elsif L > 99 then
PUT(OUTPUT, L, 3);
elsif L > 9 then
PUT(OUTPUT, L, 2);
elsif L >= 0 then
PUT(OUTPUT, L, 1);
else
PUT(OUTPUT, "**");
end if;
end PUT_LEVEL;
begin
if S.FIFTH_LEVEL <= 0 then
if S.FOURTH_LEVEL <= 0 then
if S.THIRD_LEVEL <= 0 then
if S.SECOND_LEVEL <= 0 then
LEVEL := 1;
else
LEVEL := 2;
end if;
else
LEVEL := 3;
end if;
else
LEVEL := 4;
end if;
else
LEVEL := 5;
end if;
if S.FIRST_LEVEL <= 9 then
PUT(OUTPUT, ' ');
end if;
PUT_LEVEL(OUTPUT, S.FIRST_LEVEL);
if LEVEL = 1 then
PUT(OUTPUT, '.');
PUT(OUTPUT, '0'); -- To match the ATLAS index convention
end if;
if LEVEL >= 2 then
PUT(OUTPUT, '.');
PUT_LEVEL(OUTPUT, S.SECOND_LEVEL);
end if;
if LEVEL >= 3 then
PUT(OUTPUT, '.');
PUT_LEVEL(OUTPUT, S.THIRD_LEVEL);
end if;
if LEVEL >= 4 then
PUT(OUTPUT, '.');
PUT_LEVEL(OUTPUT, S.FOURTH_LEVEL);
end if;
if LEVEL >= 5 then
PUT(OUTPUT, '.');
PUT_LEVEL(OUTPUT, S.FIFTH_LEVEL);
end if;
end PUT;
procedure PUT(S : SECTION_TYPE) is
LEVEL : INTEGER := 0;
procedure PUT_LEVEL(L : INTEGER) is
begin
if L > 9999 then
PUT("****");
elsif L > 999 then
PUT(L, 4);
elsif L > 99 then
PUT(L, 3);
elsif L > 9 then
PUT(L, 2);
elsif L >= 0 then
PUT(L, 1);
else
PUT("**");
end if;
end PUT_LEVEL;
begin
if S.FIFTH_LEVEL = 0 then
if S.FOURTH_LEVEL = 0 then
if S.THIRD_LEVEL = 0 then
if S.SECOND_LEVEL = 0 then
LEVEL := 1;
else
LEVEL := 2;
end if;
else
LEVEL := 3;
end if;
else
LEVEL := 4;
end if;
else
LEVEL := 5;
end if;
if S.FIRST_LEVEL <= 9 then
PUT(' ');
end if;
PUT_LEVEL(S.FIRST_LEVEL);
PUT('.');
if LEVEL = 1 then
PUT('0'); -- To match the ATLAS index convention
end if;
if LEVEL >= 2 then
PUT_LEVEL(S.SECOND_LEVEL);
end if;
if LEVEL >= 3 then
PUT('.');
PUT_LEVEL(S.THIRD_LEVEL);
end if;
if LEVEL >= 4 then
PUT('.');
PUT_LEVEL(S.FOURTH_LEVEL);
end if;
if LEVEL >= 5 then
PUT('.');
PUT_LEVEL(S.FIFTH_LEVEL);
end if;
end PUT;
procedure GET(FROM : in STRING;
S : out SECTION_TYPE; LAST : out INTEGER) is
L : INTEGER := 0;
FT : INTEGER := FROM'FIRST;
LT : INTEGER := FROM'LAST;
begin
S := NO_SECTION;
if TRIM(FROM)'LAST < FROM'FIRST then
return; -- Empty string, no data -- Return default
end if;
GET(FROM, S.FIRST_LEVEL, L);
if L+1 >= LT then
LAST := L;
return;
end if;
GET(FROM(L+2..LT), S.SECOND_LEVEL, L);
if L+1 >= LT then
LAST := L;
return;
end if;
GET(FROM(L+2..LT), S.THIRD_LEVEL, L);
if L+1 >= LT then
LAST := L;
return;
end if;
GET(FROM(L+2..LT), S.FOURTH_LEVEL, L);
if L+1 >= LT then
LAST := L;
return;
end if;
GET(FROM(L+2..LT), S.FIFTH_LEVEL, L);
LAST := L;
return;
exception
when TEXT_IO.END_ERROR =>
LAST := L;
return;
when TEXT_IO.DATA_ERROR =>
LAST := L;
return;
when others =>
PUT(" Unexpected exception in GET(FROM; SECTION_TYPE) with input =>");
PUT(FROM);
NEW_LINE;
LAST := L;
raise;
end GET;
function "<"(A, B : SECTION_TYPE) return BOOLEAN is
begin
if A.FIRST_LEVEL > B.FIRST_LEVEL then
return FALSE;
elsif A.FIRST_LEVEL < B.FIRST_LEVEL then
return TRUE;
else
if A.SECOND_LEVEL > B.SECOND_LEVEL then
return FALSE;
elsif A.SECOND_LEVEL < B.SECOND_LEVEL then
return TRUE;
else
if A.THIRD_LEVEL > B.THIRD_LEVEL then
return FALSE;
elsif A.THIRD_LEVEL < B.THIRD_LEVEL then
return TRUE;
else
if A.FOURTH_LEVEL > B.FOURTH_LEVEL then
return FALSE;
elsif A.FOURTH_LEVEL < B.FOURTH_LEVEL then
return TRUE;
else
if A.FIFTH_LEVEL > B.FIFTH_LEVEL then
return FALSE;
elsif A.FIFTH_LEVEL < B.FIFTH_LEVEL then
return TRUE;
else
return FALSE;
end if;
end if;
end if;
end if;
end if;
return FALSE;
end "<";
procedure PUT(OUTPUT : TEXT_IO.FILE_TYPE; S : APPENDIX_SECTION_TYPE) is
use APPENDIX_IO;
begin
PUT(OUTPUT, S.APPENDIX);
PUT(OUTPUT, ' ');
PUT(OUTPUT, S.SECTION);
end PUT;
procedure PUT(S : APPENDIX_SECTION_TYPE) is
use APPENDIX_IO;
begin
PUT(S.APPENDIX);
PUT(' ');
PUT(S.SECTION);
end PUT;
procedure GET(FROM : in STRING;
S : out APPENDIX_SECTION_TYPE; LAST : out INTEGER) is
use APPENDIX_IO;
L : INTEGER := 0;
FT : INTEGER := FROM'FIRST;
LT : INTEGER := FROM'LAST;
begin
S := NO_APPENDIX_SECTION;
if (FT = LT) or else
(TRIM(FROM)'LENGTH = 0) then -- Empty/blank string, no data
PUT("@");
return; -- Return default
end if;
--PUT_LINE("In GET =>" & FROM & '|');
begin
GET(FROM, S.APPENDIX, L);
--PUT("A");
if L+1 >= LT then
LAST := L;
return;
end if;
exception
when others =>
S.APPENDIX := NONE;
L := FT - 2;
end;
-- PUT("B");
-- GET(FROM(L+2..LT), S.SECTION.FIRST_LEVEL, L);
-- if L+1 >= LT then
-- LAST := L;
-- return;
-- end if;
--PUT("C");
-- GET(FROM(L+2..LT), S.SECTION.SECOND_LEVEL, L);
-- if L+1 >= LT then
-- LAST := L;
-- return;
-- end if;
--PUT("D");
-- GET(FROM(L+2..LT), S.SECTION.THIRD_LEVEL, L);
-- if L+1 >= LT then
-- LAST := L;
-- return;
-- end if;
--PUT("E");
-- GET(FROM(L+2..LT), S.SECTION.FOURTH_LEVEL, L);
-- if L+1 >= LT then
-- LAST := L;
-- return;
-- end if;
--PUT("F");
-- GET(FROM(L+2..LT), S.SECTION.FIFTH_LEVEL, L);
-- LAST := L;
--PUT("G");
GET(FROM(L+2..LT), S.SECTION, L);
--PUT("F");
return;
exception
when TEXT_IO.END_ERROR =>
LAST := L;
return;
when TEXT_IO.DATA_ERROR =>
LAST := L;
return;
when others =>
PUT
(" Unexpected exception in GET(FROM; APPENDIX_SECTION_TYPE) with input =>");
PUT(FROM);
NEW_LINE;
LAST := L;
return;
end GET;
function "<"(A, B : APPENDIX_SECTION_TYPE) return BOOLEAN is
begin
if A.APPENDIX > B.APPENDIX then
return FALSE;
elsif A.APPENDIX < B.APPENDIX then
return TRUE;
else
if A.SECTION.FIRST_LEVEL > B.SECTION.FIRST_LEVEL then
return FALSE;
elsif A.SECTION.FIRST_LEVEL < B.SECTION.FIRST_LEVEL then
return TRUE;
else
if A.SECTION.SECOND_LEVEL > B.SECTION.SECOND_LEVEL then
return FALSE;
elsif A.SECTION.SECOND_LEVEL < B.SECTION.SECOND_LEVEL then
return TRUE;
else
if A.SECTION.THIRD_LEVEL > B.SECTION.THIRD_LEVEL then
return FALSE;
elsif A.SECTION.THIRD_LEVEL < B.SECTION.THIRD_LEVEL then
return TRUE;
else
if A.SECTION.FOURTH_LEVEL > B.SECTION.FOURTH_LEVEL then
return FALSE;
elsif A.SECTION.FOURTH_LEVEL < B.SECTION.FOURTH_LEVEL then
return TRUE;
else
if A.SECTION.FIFTH_LEVEL > B.SECTION.FIFTH_LEVEL then
return FALSE;
elsif A.SECTION.FIFTH_LEVEL < B.SECTION.FIFTH_LEVEL then
return TRUE;
else
return FALSE;
end if;
end if;
end if;
end if;
end if;
end if;
end "<";
procedure PROMPT_FOR_ENTRY(ENTRY_NUMBER : STRING) is
begin
PUT("Give starting column and size of ");
PUT(ENTRY_NUMBER);
PUT_LINE(" significant sort field ");
PUT(" with optional sort type and way => ");
end PROMPT_FOR_ENTRY;
procedure GET_ENTRY (MX, NX : out NATURAL;
SX : out SORT_TYPE;
WX : out WAY_TYPE ) is
M : NATURAL := 1;
N : NATURAL := LINE_LENGTH;
S : SORT_TYPE := A;
W : WAY_TYPE := I;
Z : NATURAL := 0;
procedure ECHO_ENTRY is
begin
PUT(" Sorting on LINE("); PUT(M,3);
PUT(".."); PUT(N, 3); PUT(")");
PUT(" with S = "); PUT(S); PUT(" and W = "); PUT(W);
NEW_LINE(2);
end ECHO_ENTRY;
begin
M := 0;
N := LINE_LENGTH;
S := A;
W := I;
GET_LINE(ENTER_LINE, LS);
if LS = 0 then
raise ENTRY_FINISHED;
end if;
INTEGER_IO.GET(ENTER_LINE(1..LS), M, LAST);
begin
INTEGER_IO.GET(ENTER_LINE(LAST+1..LS), Z, LAST);
if M = 0 or Z = 0 then
PUT_LINE("Start or size of zero, you must be kidding, aborting");
raise PROGRAM_ERROR;
elsif M + Z > LINE_LENGTH then
PUT_LINE("Size too large, going to end of line");
N := LINE_LENGTH;
else
N := M + Z - 1;
end if;
SORT_TYPE_IO.GET(ENTER_LINE(LAST+1..LS), S, LAST);
WAY_TYPE_IO.GET(ENTER_LINE(LAST+1..LS), W, LAST);
MX := M; NX := N; SX := S; WX := W;
ECHO_ENTRY;
return;
exception
when PROGRAM_ERROR =>
PUT_LINE("PROGRAM_ERROR raised in GET_ENTRY");
raise;
when others =>
MX := M; NX := N; SX := S; WX := W;
ECHO_ENTRY;
return;
end;
end GET_ENTRY;
function IGNORE_SEPARATORS(S : STRING) return STRING is
T : STRING(S'FIRST..S'LAST) := LOWER_CASE(S);
begin
for I in S'FIRST+1..S'LAST-1 loop
if (S(I-1) /= '-' and then S(I-1) /= '_') and then
(S(I) = '-' or else S(I) = '_') and then
(S(I+1) /= '-' and then S(I+1) /= '_') then
T(I) := ' ';
end if;
end loop;
return T;
end IGNORE_SEPARATORS;
function LTU(C, D : CHARACTER) return BOOLEAN is
begin
if (D = 'v') then
if (C < 'u') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'j') then
if (C < 'i') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'V') then
if (C < 'U') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'J') then
if (C < 'I') then
return TRUE;
else
return FALSE;
end if;
else
return C < D;
end if;
end LTU;
function EQU(C, D : CHARACTER) return BOOLEAN is
begin
if (D = 'u') or (D = 'v') then
if (C = 'u') or (C = 'v') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'i') or (D = 'j') then
if (C = 'i') or (C = 'j') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'U') or (D = 'V') then
if (C = 'U') or (C = 'V') then
return TRUE;
else
return FALSE;
end if;
elsif (D = 'I') or (D = 'J') then
if (C = 'I') or (C = 'J') then
return TRUE;
else
return FALSE;
end if;
else
return C = D;
end if;
end EQU;
function GTU(C, D : CHARACTER) return BOOLEAN is
begin
if D = 'u' then
if (C > 'v') then
return TRUE;
else
return FALSE;
end if;
elsif D = 'i' then
if (C > 'j') then
return TRUE;
else
return FALSE;
end if;
elsif D = 'U' then
if (C > 'V') then
return TRUE;
else
return FALSE;
end if;
elsif D = 'I' then
if (C > 'J') then
return TRUE;
else
return FALSE;
end if;
else
return C > D;
end if;
end GTU;
function LTU(S, T : STRING) return BOOLEAN is
begin
for I in 1..S'LENGTH loop -- Not TRIMed, so same length
if EQU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
null;
elsif GTU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
return FALSE;
elsif LTU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
return TRUE;
end if;
end loop;
return FALSE;
end LTU;
function GTU(S, T : STRING) return BOOLEAN is
begin
for I in 1..S'LENGTH loop
if EQU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
null;
elsif LTU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
return FALSE;
elsif GTU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
return TRUE;
end if;
end loop;
return FALSE;
end GTU;
function EQU(S, T : STRING) return BOOLEAN is
begin
if S'LENGTH /= T'LENGTH then
return FALSE;
end if;
for I in 1..S'LENGTH loop
if not EQU(S(S'FIRST+I-1), T(T'FIRST+I-1)) then
return FALSE;
end if;
end loop;
return TRUE;
end EQU;
function SLT (X, Y : STRING; -- Make LEFT and RIGHT
ST : SORT_TYPE := A;
WT : WAY_TYPE := I) return BOOLEAN is
AS : STRING(X'RANGE) := X;
BS : STRING(Y'RANGE) := Y;
MN, NN : INTEGER := 0;
FN, GN : FLOAT := 0.0;
--FS, GS : SECTION_TYPE := NO_SECTION;
FS, GS : APPENDIX_SECTION_TYPE := NO_APPENDIX_SECTION;
PX, PY : PART_ENTRY; -- So I can X here
RX, RY : PART_OF_SPEECH_TYPE; -- So I can X here
begin
if ST = A then
AS := LOWER_CASE(AS);
BS := LOWER_CASE(BS);
if WT = I then
return AS < BS;
else
return AS > BS;
end if;
elsif ST = C then
if WT = I then
return AS < BS;
else
return AS > BS;
end if;
elsif ST = G then
AS := IGNORE_SEPARATORS(AS);
BS := IGNORE_SEPARATORS(BS);
if WT = I then
return AS < BS;
else
return AS > BS;
end if;
elsif ST = U then
AS := LOWER_CASE(AS);
BS := LOWER_CASE(BS);
if WT = I then
return LTU(AS, BS);
else
return GTU(AS, BS);
end if;
elsif ST = N then
INTEGER_IO.GET(AS, MN, LAST);
INTEGER_IO.GET(BS, NN, LAST);
if WT = I then
return MN < NN;
else
return MN > NN;
end if;
elsif ST = F then
FLOAT_IO.GET(AS, FN, LAST);
FLOAT_IO.GET(BS, GN, LAST);
if WT = I then
return FN < GN;
else
return FN > GN;
end if;
elsif ST = P then
PART_ENTRY_IO.GET(AS, PX, LAST);
PART_ENTRY_IO.GET(BS, PY, LAST);
if WT = I then
return PX < PY;
else
return (not (PX < PY)) and (not (PX = PY));
end if;
elsif ST = R then
PART_OF_SPEECH_TYPE_IO.GET(AS, RX, LAST);
PART_OF_SPEECH_TYPE_IO.GET(BS, RY, LAST);
if WT = I then
return RX < RY;
else
return (not (RX < RY)) and (not (RX = RY));
end if;
elsif ST = S then
--PUT_LINE("AS =>" & AS & '|');
GET(AS, FS, LAST);
--PUT_LINE("BS =>" & BS & '|');
GET(BS, GS, LAST);
--PUT_LINE("GOT AS & BS");
if WT = I then
return FS < GS;
else
return (not (FS < GS)) and (not (FS = GS));
end if;
else
return FALSE;
end if;
exception
when others =>
TEXT_IO.PUT_LINE("exception in SLT showing LEFT and RIGHT");
TEXT_IO.PUT_LINE(X & "&");
TEXT_IO.PUT_LINE(Y & "|");
raise;
end SLT;
function SORT_EQUAL (X, Y : STRING;
ST : SORT_TYPE := A;
WT : WAY_TYPE := I) return BOOLEAN is
AS : STRING(X'RANGE) := X;
BS : STRING(Y'RANGE) := Y;
MN, NN : INTEGER := 0;
FN, GN : FLOAT := 0.0;
FS, GS : APPENDIX_SECTION_TYPE := NO_APPENDIX_SECTION;
PX, PY : PART_ENTRY;
RX, RY : PART_OF_SPEECH_TYPE;
begin
if ST = A then
AS := LOWER_CASE(AS);
BS := LOWER_CASE(BS);
return AS = BS;
elsif ST = C then
return AS = BS;
elsif ST = G then
AS := IGNORE_SEPARATORS(AS);
BS := IGNORE_SEPARATORS(BS);
return AS = BS;
elsif ST = U then
AS := LOWER_CASE(AS);
BS := LOWER_CASE(BS);
return EQU(AS, BS);
elsif ST = N then
INTEGER_IO.GET(AS, MN, LAST);
INTEGER_IO.GET(BS, NN, LAST);
return MN = NN;
elsif ST = F then
FLOAT_IO.GET(AS, FN, LAST);
FLOAT_IO.GET(BS, GN, LAST);
return FN = GN;
elsif ST = P then
PART_ENTRY_IO.GET(AS, PX, LAST);
PART_ENTRY_IO.GET(BS, PY, LAST);
return PX = PY;
elsif ST = R then
PART_OF_SPEECH_TYPE_IO.GET(AS, RX, LAST);
PART_OF_SPEECH_TYPE_IO.GET(BS, RY, LAST);
return RX = RY;
elsif ST = S then
GET(AS, FS, LAST);
GET(BS, GS, LAST);
return FS = GS;
else
return FALSE;
end if;
exception
when others =>
TEXT_IO.PUT_LINE("exception in LT showing LEFT and RIGHT");
TEXT_IO.PUT_LINE(X & "|");
TEXT_IO.PUT_LINE(Y & "|");
raise;
end SORT_EQUAL;
function LT (LEFT, RIGHT : TEXT_TYPE) return BOOLEAN is
begin
if SLT(LEFT(M1..N1), RIGHT(M1..N1), S1, W1) then
return TRUE;
elsif SORT_EQUAL(LEFT(M1..N1), RIGHT(M1..N1), S1, W1) then
if ((N2 > 0) and then
SLT(LEFT(M2..N2), RIGHT(M2..N2), S2, W2) ) then
return TRUE;
elsif ((N2 > 0) and then
SORT_EQUAL(LEFT(M2..N2), RIGHT(M2..N2), S2, W2)) then
if ((N3 > 0) and then
SLT(LEFT(M3..N3), RIGHT(M3..N3), S3, W3 )) then
return TRUE;
elsif ((N3 > 0) and then
SORT_EQUAL(LEFT(M3..N3), RIGHT(M3..N3), S3, W3)) then
if ((N4 > 0) and then
SLT(LEFT(M4..N4), RIGHT(M4..N4), S4, W4) ) then
return TRUE;
elsif ((N4 > 0) and then
SORT_EQUAL(LEFT(M4..N4), RIGHT(M4..N4), S4, W4)) then
if ((N5 > 0) and then
SLT(LEFT(M5..N5), RIGHT(M5..N5), S5, W5) ) then
return TRUE;
end if;
end if;
end if;
end if;
end if;
return FALSE;
exception
when others =>
TEXT_IO.PUT_LINE("exception in LT showing LEFT and RIGHT");
TEXT_IO.PUT_LINE(LEFT & "|");
TEXT_IO.PUT_LINE(RIGHT & "|");
raise;
end LT;
procedure OPEN_FILE_FOR_INPUT(INPUT : in out TEXT_IO.FILE_TYPE;
PROMPT : STRING := "File for input => ") is
LAST : NATURAL := 0;
begin
GET_INPUT_FILE:
loop
CHECK_INPUT:
begin
NEW_LINE;
PUT(PROMPT);
GET_LINE(INPUT_NAME, LAST);
OPEN(INPUT, IN_FILE, INPUT_NAME(1..LAST));
exit;
exception
when others =>
PUT_LINE(" !!!!!!!!! Try Again !!!!!!!!");
end CHECK_INPUT;
end loop GET_INPUT_FILE;
end OPEN_FILE_FOR_INPUT;
procedure CREATE_FILE_FOR_OUTPUT(OUTPUT : in out TEXT_IO.FILE_TYPE;
PROMPT : STRING := "File for output => ") is
NAME : STRING(1..80) := (others => ' ');
LAST : NATURAL := 0;
begin
GET_OUTPUT_FILE:
loop
CHECK_OUTPUT:
begin
NEW_LINE;
PUT(PROMPT);
GET_LINE(NAME, LAST);
if TRIM(NAME(1..LAST))'LENGTH /= 0 then
CREATE(OUTPUT, OUT_FILE, NAME(1..LAST));
else
CREATE(OUTPUT, OUT_FILE, TRIM(INPUT_NAME));
end if;
exit;
exception
when others =>
PUT_LINE(" !!!!!!!!! Try Again !!!!!!!!");
end CHECK_OUTPUT;
end loop GET_OUTPUT_FILE;
end CREATE_FILE_FOR_OUTPUT;
function GRAPHIC(S : STRING) return STRING is
T : STRING(1..S'LENGTH) := S;
begin
for I in S'RANGE loop
if CHARACTER'POS(S(I)) < 32 then
T(I) := ' ';
end if;
end loop;
return T;
end GRAPHIC;
begin
NEW_LINE;
PUT_LINE("Sorts a text file of lines four times on substrings M..N");
PUT_LINE("A)lphabetic (all case) C)ase sensitive, iG)nore seperators, U)i_is_vj,");
PUT_LINE(" iN)teger, F)loating point, S)ection, P)art entry, or paR)t of speech");
PUT_LINE(" I)ncreasing or D)ecreasing");
NEW_LINE;
OPEN_FILE_FOR_INPUT(INPUT, "What file to sort from => ");
NEW_LINE;
PROMPT_FOR_ENTRY("first");
begin
GET_ENTRY(M1, N1, S1, W1);
exception
when PROGRAM_ERROR =>
raise;
when others =>
null;
end;
begin
PROMPT_FOR_ENTRY("second");
GET_ENTRY(M2, N2, S2, W2);
PROMPT_FOR_ENTRY("third");
GET_ENTRY(M3, N3, S3, W3);
PROMPT_FOR_ENTRY("fourth");
GET_ENTRY(M4, N4, S4, W4);
PROMPT_FOR_ENTRY("fifth");
GET_ENTRY(M5, N5, S5, W5);
exception
when PROGRAM_ERROR =>
raise;
when ENTRY_FINISHED =>
null;
when TEXT_IO.DATA_ERROR | TEXT_IO.END_ERROR =>
null;
end;
--PUT_LINE("CREATING WORK FILE");
NEW_LINE;
CREATE (WORK, INOUT_FILE, "WORK.");
PUT_LINE("CREATED WORK FILE");
while not END_OF_FILE(INPUT) loop
--begin
GET_LINE(INPUT, LINE_TEXT, CURRENT_LENGTH);
--exception when others =>
--TEXT_IO.PUT_LINE("INPUT GET exception");
--TEXT_IO.PUT_LINE(LINE_TEXT(1..CURRENT_LENGTH) & "|");
--end;
--PUT_LINE(LINE_TEXT(1..CURRENT_LENGTH));
--PUT_LINE("=>" & HEAD(LINE_TEXT(1..CURRENT_LENGTH), LINE_LENGTH) & "|");
if TRIM(LINE_TEXT(1..CURRENT_LENGTH)) /= "" then
--begin
WRITE(WORK, HEAD(LINE_TEXT(1..CURRENT_LENGTH), LINE_LENGTH) );
--exception when others =>
--TEXT_IO.PUT_LINE("WORK WRITE exception");
--TEXT_IO.PUT_LINE(LINE_TEXT(1..CURRENT_LENGTH) & "|");
--end;
end if;
end loop;
CLOSE(INPUT);
PUT_LINE("Begin sorting");
LINE_HEAPSORT:
declare
L : LINE_IO.POSITIVE_COUNT := SIZE(WORK) / 2 + 1;
IR : LINE_IO.POSITIVE_COUNT := SIZE(WORK);
I, J : LINE_IO.POSITIVE_COUNT;
begin
TEXT_IO.PUT_LINE("SIZE OF WORK = " & INTEGER'IMAGE(INTEGER(SIZE(WORK))));
MAIN:
loop
if L > 1 then
L := L - 1;
READ(WORK, LINE_TEXT, L);
OLD_LINE := LINE_TEXT;
else
READ(WORK, LINE_TEXT, IR);
OLD_LINE := LINE_TEXT;
READ(WORK, LINE_TEXT, 1);
WRITE(WORK, LINE_TEXT, IR);
IR := IR - 1;
if IR = 1 THEN
WRITE(WORK, OLD_LINE, 1);
exit MAIN;
end if;
end if;
I := L;
J := L + L;
while J <= IR loop
if J < IR then
READ(WORK, LINE_TEXT, J);
READ(WORK, P_LINE, J+1);
--if LT (LINE.TEXT, P_LINE.TEXT) then
if LT (LINE_TEXT, P_LINE) then
J := J + 1;
end if;
end if;
READ(WORK, LINE_TEXT, J);
--if OLD_LINE.TEXT < LINE.TEXT then
if LT (OLD_LINE , LINE_TEXT) then
WRITE(WORK, LINE_TEXT, I);
I := J;
J := J + J;
else
J := IR + 1;
end if;
end loop;
WRITE(WORK, OLD_LINE, I);
end loop MAIN;
exception
when CONSTRAINT_ERROR => PUT_LINE("HEAP CONSTRAINT_ERROR");
when others => PUT_LINE("HEAP other_ERROR");
end LINE_HEAPSORT;
PUT_LINE("Finished sorting in WORK");
CREATE_FILE_FOR_OUTPUT(OUTPUT, "Where to put the output => ");
--RESET(WORK);
Set_Index(WORK, 1);
while not END_OF_FILE(WORK) loop
READ(WORK, LINE_TEXT);
if TRIM(GRAPHIC(LINE_TEXT))'LENGTH > 0 then
--PUT_LINE(TRIM(LINE_TEXT, RIGHT));
PUT_LINE(OUTPUT, TRIM(LINE_TEXT, RIGHT));
end if;
end loop;
CLOSE(WORK);
CLOSE(OUTPUT);
PUT_LINE("Done!");
NEW_LINE;
exception
when PROGRAM_ERROR =>
PUT_LINE("SORT terminated on a PROGRAM_ERROR");
CLOSE(OUTPUT);
when TEXT_IO.DATA_ERROR => --Terminate on primary start or size = 0
PUT_LINE("SORT terminated on a DATA_ERROR");
PUT_LINE(LINE_TEXT);
CLOSE(OUTPUT);
when CONSTRAINT_ERROR => --Terminate on blank line for file name
PUT_LINE("SORT terminated on a CONSTRAINT_ERROR");
CLOSE(OUTPUT);
when TEXT_IO.DEVICE_ERROR => --Ran out of space to write output file
PUT_LINE("SORT terminated on a DEVICE_ERROR");
DELETE(OUTPUT);
CREATE_FILE_FOR_OUTPUT(OUTPUT, "Wherelse to put the output => ");
RESET(WORK);
while not END_OF_FILE(WORK) loop
READ(WORK, LINE_TEXT);
PUT_LINE(OUTPUT, LINE_TEXT); --(1..LINE.CURRENT_LENGTH));
end loop;
CLOSE(OUTPUT);
end SORTER;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-------------------------------------------------------------------------------
with LCD_Graphic_Backend;
with Giza.GUI;
with Giza.Context;
with Giza.Bitmap_Fonts.FreeSerifItalic18pt7b;
with Ada.Synchronous_Task_Control;
with STM32.RNG.Polling;
with System;
with Giza.Events; use Giza.Events;
with Ada.Real_Time; use Ada.Real_Time;
with STM32.Board;
with HAL.Touch_Panel; use HAL.Touch_Panel;
with Clock_Window;
package body GUI is
Backend : aliased LCD_Graphic_Backend.Instance;
Context : aliased Giza.Context.Instance;
Main_W : aliased Clock_Window.Instance;
Sync : Ada.Synchronous_Task_Control.Suspension_Object;
type Touch_State is record
Touch_Detected : Boolean;
X : Natural;
Y : Natural;
end record;
function Current_Touch_State return Touch_State;
-------------------------
-- Current_Touch_State --
-------------------------
function Current_Touch_State return Touch_State is
TS : Touch_State;
ST_TS : constant HAL.Touch_Panel.TP_State :=
STM32.Board.Touch_Panel.Get_All_Touch_Points;
begin
TS.Touch_Detected := ST_TS'Length > 0;
if TS.Touch_Detected then
TS.X := ST_TS (1).X;
TS.Y := ST_TS (1).Y;
else
TS.X := 0;
TS.Y := 0;
end if;
return TS;
end Current_Touch_State;
task Touch_Screen is
pragma Priority (System.Default_Priority - 1);
end Touch_Screen;
task body Touch_Screen is
TS, Prev : Touch_State;
Click_Evt : constant Click_Event_Ref := new Click_Event;
Release_Evt : constant Click_Released_Event_Ref
:= new Click_Released_Event;
begin
Ada.Synchronous_Task_Control.Suspend_Until_True (Sync);
Prev.Touch_Detected := False;
loop
-- STM32F4.Touch_Panel.Wait_For_Touch_Detected;
TS := Current_Touch_State;
if TS.Touch_Detected /= Prev.Touch_Detected then
if TS.Touch_Detected then
Click_Evt.Pos.X := TS.X;
Click_Evt.Pos.Y := TS.Y;
Giza.GUI.Emit (Event_Not_Null_Ref (Click_Evt));
else
Giza.GUI.Emit (Event_Not_Null_Ref (Release_Evt));
end if;
end if;
Prev := TS;
delay until Clock + Milliseconds (10);
end loop;
end Touch_Screen;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
LCD_Graphic_Backend.Initialize;
Giza.GUI.Set_Backend (Backend'Access);
STM32.Board.Touch_Panel.Initialize;
Context.Set_Font (Giza.Bitmap_Fonts.FreeSerifItalic18pt7b.Font);
Giza.GUI.Set_Context (Context'Access);
end Initialize;
-----------
-- Start --
-----------
procedure Start is
begin
STM32.Board.Configure_User_Button_GPIO;
Giza.GUI.Push (Main_W'Access);
Ada.Synchronous_Task_Control.Set_True (Sync);
Giza.GUI.Event_Loop;
end Start;
------------
-- Random --
------------
function Random (Modulo : Unsigned_32) return Unsigned_32 is
Rand_Exess : constant Unsigned_32 := (Unsigned_32'Last mod Modulo) + 1;
Rand_Linit : constant Unsigned_32 := Unsigned_32'Last - Rand_Exess;
Ret : Unsigned_32;
begin
loop
Ret := STM32.RNG.Polling.Random;
exit when Ret <= Rand_Linit;
end loop;
return Ret mod Modulo;
end Random;
end GUI;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- GNAT: enforce generation of preinitialized data section instead of
-- generation of elaboration code.
package Matreshka.Internals.Unicode.Ucd.Core_0007 is
pragma Preelaborate;
Group_0007 : aliased constant Core_Second_Stage
:= (16#00# .. 16#02# => -- 0700 .. 0702
(Other_Punctuation, Neutral,
Other, Other, S_Term, Alphabetic,
(STerm
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#03# .. 16#0A# => -- 0703 .. 070A
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#0B# => -- 070B
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Grapheme_Base => True,
others => False)),
16#0C# => -- 070C
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#0D# => -- 070D
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Grapheme_Base => True,
others => False)),
16#0E# => -- 070E
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#0F# => -- 070F
(Format, Neutral,
Control, Format, Format, Alphabetic,
(Case_Ignorable => True,
others => False)),
16#11# => -- 0711
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#30# .. 16#3F# => -- 0730 .. 073F
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#40# .. 16#4A# => -- 0740 .. 074A
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#4B# .. 16#4C# => -- 074B .. 074C
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#A6# .. 16#B0# => -- 07A6 .. 07B0
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Other_Alphabetic
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#B2# .. 16#BF# => -- 07B2 .. 07BF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#C0# .. 16#C9# => -- 07C0 .. 07C9
(Decimal_Number, Neutral,
Other, Numeric, Numeric, Numeric,
(Grapheme_Base
| ID_Continue
| XID_Continue => True,
others => False)),
16#EB# .. 16#F3# => -- 07EB .. 07F3
(Nonspacing_Mark, Neutral,
Extend, Extend, Extend, Combining_Mark,
(Diacritic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| XID_Continue => True,
others => False)),
16#F4# .. 16#F5# => -- 07F4 .. 07F5
(Modifier_Letter, Neutral,
Other, A_Letter, O_Letter, Alphabetic,
(Diacritic
| Alphabetic
| Case_Ignorable
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)),
16#F6# => -- 07F6
(Other_Symbol, Neutral,
Other, Other, Other, Alphabetic,
(Grapheme_Base => True,
others => False)),
16#F7# => -- 07F7
(Other_Punctuation, Neutral,
Other, Other, Other, Alphabetic,
(Grapheme_Base => True,
others => False)),
16#F8# => -- 07F8
(Other_Punctuation, Neutral,
Other, Mid_Num, S_Continue, Infix_Numeric,
(Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#F9# => -- 07F9
(Other_Punctuation, Neutral,
Other, Other, S_Term, Exclamation,
(STerm
| Terminal_Punctuation
| Grapheme_Base => True,
others => False)),
16#FA# => -- 07FA
(Modifier_Letter, Neutral,
Other, A_Letter, O_Letter, Alphabetic,
(Extender
| Alphabetic
| Case_Ignorable
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)),
16#FB# .. 16#FF# => -- 07FB .. 07FF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
others =>
(Other_Letter, Neutral,
Other, A_Letter, O_Letter, Alphabetic,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start => True,
others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_0007;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with EL.Expressions;
with EL.Objects;
with EL.Contexts.Default;
with EL.Functions.Default;
with Ada.Text_IO;
with Bean;
procedure Functions is
use Bean;
use Ada.Text_IO;
use EL.Expressions;
use EL.Objects;
E : Expression;
Fn : constant EL.Functions.Function_Mapper_Access
:= new EL.Functions.Default.Default_Function_Mapper;
Ctx : EL.Contexts.Default.Default_Context;
Joe : constant Person_Access := Create_Person ("Joe", "Smith", 12);
Bill : constant Person_Access := Create_Person ("Bill", "Johnson", 42);
Result : Object;
begin
-- Register the 'format' function.
Fn.Set_Function (Namespace => "",
Name => "format",
Func => Bean.Format'Access);
Ctx.Set_Function_Mapper (Fn);
-- Create the expression
E := Create_Expression ("#{format(user.firstName)} #{user.lastName}", Ctx);
-- Bind the context to 'Joe' and evaluate
Ctx.Set_Variable ("user", Joe);
Result := E.Get_Value (Ctx);
Put_Line ("Joe's name is " & To_String (Result));
-- Bind the context to 'Bill' and evaluate
Ctx.Set_Variable ("user", Bill);
Result := E.Get_Value (Ctx);
Put_Line ("Bill's name is " & To_String (Result));
end Functions;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
with CRC;
package body SGP30 is
package CRC_8 is new CRC
(Word => HAL.UInt8,
Word_Array => HAL.UInt8_Array);
function Verify_Checksum
(Data : UInt8_Array)
return Boolean
is
-- Every third byte is the CRC-8 of the preceding two bytes.
I : Positive := Data'First;
begin
while I <= Data'Last loop
if CRC_8.Calculate (Data (I .. I + 1), Initial => 16#FF#) /= Data (I + 2) then
return False;
end if;
I := I + 3;
end loop;
return True;
end Verify_Checksum;
function To_I2C_Data
(X : UInt16)
return I2C_Data
is (I2C_Data'(UInt8 (Shift_Right (X, 8)), UInt8 (X and 16#FF#)));
procedure Soft_Reset
(This : in out Device)
is
begin
This.Port.Master_Transmit
(Addr => 16#00#,
Data => I2C_Data'(1 => 16#06#),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
This.Delays.Delay_Milliseconds (10);
end Soft_Reset;
function Read_48
(This : in out Device;
Reg : UInt16)
return UInt48
is
Data : I2C_Data (1 .. 9);
begin
This.Port.Master_Transmit
(Addr => This.Addr,
Data => To_I2C_Data (Reg),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
This.Port.Master_Receive
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
if Verify_Checksum (Data) then
return UInt48
(Shift_Left (UInt64 (Data (1)), 40) or
Shift_Left (UInt64 (Data (2)), 32) or
Shift_Left (UInt64 (Data (4)), 24) or
Shift_Left (UInt64 (Data (5)), 16) or
Shift_Left (UInt64 (Data (7)), 8) or
Shift_Left (UInt64 (Data (8)), 0));
else
This.Status := Checksum_Error;
return 0;
end if;
end Read_48;
function Read_32
(This : in out Device;
Reg : UInt16)
return UInt32
is
Data : I2C_Data (1 .. 6);
begin
This.Port.Master_Transmit
(Addr => This.Addr,
Data => To_I2C_Data (Reg),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
This.Delays.Delay_Milliseconds (12);
This.Port.Master_Receive
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
if Verify_Checksum (Data) then
return Shift_Left (UInt32 (Data (1)), 24) or
Shift_Left (UInt32 (Data (2)), 16) or
Shift_Left (UInt32 (Data (4)), 8) or
Shift_Left (UInt32 (Data (5)), 0);
else
This.Status := Checksum_Error;
return 0;
end if;
end Read_32;
function Read_16
(This : in out Device;
Reg : UInt16)
return UInt16
is
Data : I2C_Data (1 .. 3);
begin
This.Port.Master_Transmit
(Addr => This.Addr,
Data => To_I2C_Data (Reg),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
This.Delays.Delay_Milliseconds (10);
This.Port.Master_Receive
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
return 0;
end if;
if Verify_Checksum (Data) then
return Shift_Left (UInt16 (Data (1)), 8) or
Shift_Left (UInt16 (Data (2)), 0);
else
This.Status := Checksum_Error;
return 0;
end if;
end Read_16;
procedure Write_32
(This : in out Device;
Reg : UInt16;
Value : UInt32)
is
Data : I2C_Data (1 .. 6);
begin
Data (1) := UInt8 (Shift_Right (Value, 24) and 16#FF#);
Data (2) := UInt8 (Shift_Right (Value, 16) and 16#FF#);
Data (3) := CRC_8.Calculate (Data (1 .. 2), Initial => 16#FF#);
Data (4) := UInt8 (Shift_Right (Value, 8) and 16#FF#);
Data (5) := UInt8 (Shift_Right (Value, 0) and 16#FF#);
Data (6) := CRC_8.Calculate (Data (4 .. 5), Initial => 16#FF#);
This.Port.Master_Transmit
(Addr => This.Addr,
Data => To_I2C_Data (Reg),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
This.Delays.Delay_Milliseconds (10);
This.Port.Master_Transmit
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
end Write_32;
procedure Write_16
(This : in out Device;
Reg : UInt16;
Value : UInt16)
is
Data : I2C_Data (1 .. 3);
begin
Data (1) := UInt8 (Shift_Right (Value, 8) and 16#FF#);
Data (2) := UInt8 (Shift_Right (Value, 0) and 16#FF#);
Data (3) := CRC_8.Calculate (Data (1 .. 2), Initial => 16#FF#);
This.Port.Master_Transmit
(Addr => This.Addr,
Data => To_I2C_Data (Reg),
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
This.Delays.Delay_Milliseconds (10);
This.Port.Master_Transmit
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
end Write_16;
procedure Write_Command
(This : in out Device;
Reg : UInt16)
is
Data : I2C_Data (1 .. 2);
begin
Data (1) := UInt8 (Shift_Right (Reg, 8));
Data (2) := UInt8 (Reg and 16#FF#);
This.Port.Master_Transmit
(Addr => This.Addr,
Data => Data,
Status => This.Bus_Status);
if This.Bus_Status /= Ok then
This.Status := I2C_Error;
end if;
This.Delays.Delay_Milliseconds (10);
end Write_Command;
procedure Init_Air_Quality
(This : in out Device)
is
begin
This.Write_Command (16#2003#);
end Init_Air_Quality;
procedure Measure_Air_Quality
(This : in out Device;
eCO2 : out Natural;
TVOC : out Natural)
is
X : UInt32;
begin
X := This.Read_32 (16#2008#);
eCO2 := Natural (Shift_Right (X, 16));
TVOC := Natural (X and 16#FFFF#);
end Measure_Air_Quality;
function Get_Baseline
(This : in out Device)
return UInt32
is (This.Read_32 (16#2015#));
procedure Set_Baseline
(This : in out Device;
Baseline : UInt32)
is
begin
This.Write_32 (16#201E#, Baseline);
end Set_Baseline;
procedure Set_Humidity
(This : in out Device;
Humidity : UInt16)
is
begin
This.Write_16 (16#2061#, Humidity);
end Set_Humidity;
function Measure_Test
(This : in out Device)
return UInt16
is (This.Read_16 (16#2032#));
function Get_Feature_Set_Version
(This : in out Device)
return UInt16
is (This.Read_16 (16#202F#));
function Measure_Raw_Signals
(This : in out Device)
return UInt32
is (This.Read_32 (16#2050#));
function Get_Serial_Id
(This : in out Device)
return UInt48
is (This.Read_48 (16#3682#));
function Has_Error
(This : Device)
return Boolean
is (This.Status /= Ok);
procedure Clear_Error
(This : in out Device)
is
begin
This.Bus_Status := Ok;
This.Status := Ok;
end Clear_Error;
begin
CRC_8.Poly := 16#31#;
end SGP30;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
-- Convert any image or animation file to BMP file(s).
--
-- Middle-size test/demo for the GID (Generic Image Decoder) package.
--
-- Supports:
-- - Transparency (blends transparent or partially opaque areas with a
-- background image, gid.gif, or a fixed, predefined colour)
-- - Display orientation (JPEG EXIF informations from digital cameras)
--
-- For a smaller and simpler example, look for mini.adb .
--
with GID;
with Ada.Calendar;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with Interfaces;
procedure To_BMP is
default_bkg_name: constant String:= "gid.gif";
procedure Blurb is
begin
Put_Line(Standard_Error, "To_BMP * Converts any image file to a BMP file");
Put_Line(Standard_Error, "Simple test for the GID (Generic Image Decoder) package");
Put_Line(Standard_Error, "Package version " & GID.version & " dated " & GID.reference);
Put_Line(Standard_Error, "URL: " & GID.web);
New_Line(Standard_Error);
Put_Line(Standard_Error, "Syntax:");
Put_Line(Standard_Error, "to_bmp [-] [-<background_image_name>] <image_1> [<image_2>...]");
New_Line(Standard_Error);
Put_Line(Standard_Error, "Options:");
Put_Line(Standard_Error, " '-': don't output image (testing only)");
Put_Line(Standard_Error, " '-<background_image_name>':");
Put_Line(Standard_Error, " use specifed background to mix with transparent images");
Put_Line(Standard_Error, " (otherwise, trying with '"& default_bkg_name &"' or single color)");
New_Line(Standard_Error);
Put_Line(Standard_Error, "Output: "".dib"" is added the full input name(s)");
Put_Line(Standard_Error, " Reason of "".dib"": unknown synonym of "".bmp"";");
Put_Line(Standard_Error, " just do ""del *.dib"" for cleanup");
New_Line(Standard_Error);
end Blurb;
-- Image used as background for displaying images having transparency
background_image_name: Unbounded_String:= Null_Unbounded_String;
use Interfaces;
type Byte_Array is array(Integer range <>) of Unsigned_8;
type p_Byte_Array is access Byte_Array;
procedure Dispose is new Ada.Unchecked_Deallocation(Byte_Array, p_Byte_Array);
forgive_errors: constant Boolean:= False;
error: Boolean;
img_buf, bkg_buf: p_Byte_Array:= null;
bkg: GID.Image_descriptor;
generic
correct_orientation: GID.Orientation;
-- Load image into a 24-bit truecolor BGR raw bitmap (for a BMP output)
procedure Load_raw_image(
image : in out GID.Image_descriptor;
buffer: in out p_Byte_Array;
next_frame: out Ada.Calendar.Day_Duration
);
--
procedure Load_raw_image(
image : in out GID.Image_descriptor;
buffer: in out p_Byte_Array;
next_frame: out Ada.Calendar.Day_Duration
)
is
subtype Primary_color_range is Unsigned_8;
subtype U16 is Unsigned_16;
image_width: constant Positive:= GID.Pixel_width(image);
image_height: constant Positive:= GID.Pixel_height(image);
padded_line_size_x: constant Positive:=
4 * Integer(Float'Ceiling(Float(image_width) * 3.0 / 4.0));
padded_line_size_y: constant Positive:=
4 * Integer(Float'Ceiling(Float(image_height) * 3.0 / 4.0));
-- (in bytes)
idx: Integer;
mem_x, mem_y: Natural;
bkg_padded_line_size: Positive;
bkg_width, bkg_height: Natural;
--
procedure Set_X_Y (x, y: Natural) is
pragma Inline(Set_X_Y);
use GID;
rev_x: constant Natural:= image_width - (x+1);
rev_y: constant Natural:= image_height - (y+1);
begin
case correct_orientation is
when Unchanged =>
idx:= 3 * x + padded_line_size_x * y;
when Rotation_90 =>
idx:= 3 * rev_y + padded_line_size_y * x;
when Rotation_180 =>
idx:= 3 * rev_x + padded_line_size_x * rev_y;
when Rotation_270 =>
idx:= 3 * y + padded_line_size_y * rev_x;
end case;
mem_x:= x;
mem_y:= y;
end Set_X_Y;
--
-- No background version of Put_Pixel
--
procedure Put_Pixel_without_bkg (
red, green, blue : Primary_color_range;
alpha : Primary_color_range
)
is
pragma Inline(Put_Pixel_without_bkg);
pragma Warnings(off, alpha); -- alpha is just ignored
use GID;
begin
buffer(idx..idx+2):= (blue, green, red);
-- GID requires us to look to next pixel for next time:
case correct_orientation is
when Unchanged =>
idx:= idx + 3;
when Rotation_90 =>
idx:= idx + padded_line_size_y;
when Rotation_180 =>
idx:= idx - 3;
when Rotation_270 =>
idx:= idx - padded_line_size_y;
end case;
end Put_Pixel_without_bkg;
--
-- Unicolor background version of Put_Pixel
--
procedure Put_Pixel_with_unicolor_bkg (
red, green, blue : Primary_color_range;
alpha : Primary_color_range
)
is
pragma Inline(Put_Pixel_with_unicolor_bkg);
u_red : constant:= 200;
u_green: constant:= 133;
u_blue : constant:= 32;
begin
if alpha = 255 then
buffer(idx..idx+2):= (blue, green, red);
else -- blend with bckground color
buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * u_blue )/255);
buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * u_green)/255);
buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * u_red )/255);
end if;
idx:= idx + 3;
-- ^ GID requires us to look to next pixel on the right for next time.
end Put_Pixel_with_unicolor_bkg;
--
-- Background image version of Put_Pixel
--
procedure Put_Pixel_with_image_bkg (
red, green, blue : Primary_color_range;
alpha : Primary_color_range
)
is
pragma Inline(Put_Pixel_with_image_bkg);
b_red,
b_green,
b_blue : Primary_color_range;
bkg_idx: Natural;
begin
if alpha = 255 then
buffer(idx..idx+2):= (blue, green, red);
else -- blend with background image
bkg_idx:= 3 * (mem_x mod bkg_width) + bkg_padded_line_size * (mem_y mod bkg_height);
b_blue := bkg_buf(bkg_idx);
b_green:= bkg_buf(bkg_idx+1);
b_red := bkg_buf(bkg_idx+2);
buffer(idx) := Primary_color_range((U16(alpha) * U16(blue) + U16(255-alpha) * U16(b_blue) )/255);
buffer(idx+1):= Primary_color_range((U16(alpha) * U16(green) + U16(255-alpha) * U16(b_green))/255);
buffer(idx+2):= Primary_color_range((U16(alpha) * U16(red) + U16(255-alpha) * U16(b_red) )/255);
end if;
idx:= idx + 3;
-- ^ GID requires us to look to next pixel on the right for next time.
mem_x:= mem_x + 1;
end Put_Pixel_with_image_bkg;
stars: Natural:= 0;
procedure Feedback(percents: Natural) is
so_far: constant Natural:= percents / 5;
begin
for i in stars+1..so_far loop
Put( Standard_Error, '*');
end loop;
stars:= so_far;
end Feedback;
-- Here, the exciting thing: the instanciation of
-- GID.Load_image_contents. In our case, we load the image
-- into a 24-bit bitmap (because we provide a Put_Pixel
-- that does that with the pixels), but we could do plenty
-- of other things instead, like display the image live on a GUI.
-- More exciting: for tuning performance, we have 3 different
-- instances of GID.Load_image_contents (each of them with the full
-- decoders for all formats, own specialized generic instances, inlines,
-- etc.) depending on the transparency features.
procedure BMP24_Load_without_bkg is
new GID.Load_image_contents(
Primary_color_range,
Set_X_Y,
Put_Pixel_without_bkg,
Feedback,
GID.fast
);
procedure BMP24_Load_with_unicolor_bkg is
new GID.Load_image_contents(
Primary_color_range,
Set_X_Y,
Put_Pixel_with_unicolor_bkg,
Feedback,
GID.fast
);
procedure BMP24_Load_with_image_bkg is
new GID.Load_image_contents(
Primary_color_range,
Set_X_Y,
Put_Pixel_with_image_bkg,
Feedback,
GID.fast
);
begin
error:= False;
Dispose(buffer);
case correct_orientation is
when GID.Unchanged | GID.Rotation_180 =>
buffer:= new Byte_Array(0..padded_line_size_x * GID.Pixel_height(image) - 1);
when GID.Rotation_90 | GID.Rotation_270 =>
buffer:= new Byte_Array(0..padded_line_size_y * GID.Pixel_width(image) - 1);
end case;
if GID.Expect_transparency(image) then
if background_image_name = Null_Unbounded_String then
BMP24_Load_with_unicolor_bkg(image, next_frame);
else
bkg_width:= GID.Pixel_width(bkg);
bkg_height:= GID.Pixel_height(bkg);
bkg_padded_line_size:=
4 * Integer(Float'Ceiling(Float(bkg_width) * 3.0 / 4.0));
BMP24_Load_with_image_bkg(image, next_frame);
end if;
else
BMP24_Load_without_bkg(image, next_frame);
end if;
-- -- For testing: white rectangle with a red half-frame.
-- buffer.all:= (others => 255);
-- for x in 0..GID.Pixel_width(image)-1 loop
-- Put_Pixel_with_unicolor_bkg(x,0,255,0,0,255);
-- end loop;
-- for y in 0..GID.Pixel_height(image)-1 loop
-- Put_Pixel_with_unicolor_bkg(0,y,255,0,0,255);
-- end loop;
exception
when others =>
if forgive_errors then
error:= True;
next_frame:= 0.0;
else
raise;
end if;
end Load_raw_image;
procedure Load_raw_image_0 is new Load_raw_image(GID.Unchanged);
procedure Load_raw_image_90 is new Load_raw_image(GID.Rotation_90);
procedure Load_raw_image_180 is new Load_raw_image(GID.Rotation_180);
procedure Load_raw_image_270 is new Load_raw_image(GID.Rotation_270);
procedure Dump_BMP_24(name: String; i: GID.Image_descriptor) is
f: Ada.Streams.Stream_IO.File_Type;
type BITMAPFILEHEADER is record
bfType : Unsigned_16;
bfSize : Unsigned_32;
bfReserved1: Unsigned_16:= 0;
bfReserved2: Unsigned_16:= 0;
bfOffBits : Unsigned_32;
end record;
-- ^ No packing needed
BITMAPFILEHEADER_Bytes: constant:= 14;
type BITMAPINFOHEADER is record
biSize : Unsigned_32;
biWidth : Unsigned_32;
biHeight : Unsigned_32;
biPlanes : Unsigned_16:= 1;
biBitCount : Unsigned_16;
biCompression : Unsigned_32:= 0;
biSizeImage : Unsigned_32;
biXPelsPerMeter: Unsigned_32:= 0;
biYPelsPerMeter: Unsigned_32:= 0;
biClrUsed : Unsigned_32:= 0;
biClrImportant : Unsigned_32:= 0;
end record;
-- ^ No packing needed
BITMAPINFOHEADER_Bytes: constant:= 40;
FileInfo : BITMAPINFOHEADER;
FileHeader: BITMAPFILEHEADER;
--
generic
type Number is mod <>;
procedure Write_Intel_x86_number(n: in Number);
procedure Write_Intel_x86_number(n: in Number) is
m: Number:= n;
bytes: constant Integer:= Number'Size/8;
begin
for i in 1..bytes loop
Unsigned_8'Write(Stream(f), Unsigned_8(m and 255));
m:= m / 256;
end loop;
end Write_Intel_x86_number;
procedure Write_Intel is new Write_Intel_x86_number( Unsigned_16 );
procedure Write_Intel is new Write_Intel_x86_number( Unsigned_32 );
begin
FileHeader.bfType := 16#4D42#; -- 'BM'
FileHeader.bfOffBits := BITMAPINFOHEADER_Bytes + BITMAPFILEHEADER_Bytes;
FileInfo.biSize := BITMAPINFOHEADER_Bytes;
case GID.Display_orientation(i) is
when GID.Unchanged | GID.Rotation_180 =>
FileInfo.biWidth := Unsigned_32(GID.Pixel_width(i));
FileInfo.biHeight := Unsigned_32(GID.Pixel_height(i));
when GID.Rotation_90 | GID.Rotation_270 =>
FileInfo.biWidth := Unsigned_32(GID.Pixel_height(i));
FileInfo.biHeight := Unsigned_32(GID.Pixel_width(i));
end case;
FileInfo.biBitCount := 24;
FileInfo.biSizeImage := Unsigned_32(img_buf.all'Length);
FileHeader.bfSize := FileHeader.bfOffBits + FileInfo.biSizeImage;
Create(f, Out_File, name & ".dib");
-- BMP Header, endian-safe:
Write_Intel(FileHeader.bfType);
Write_Intel(FileHeader.bfSize);
Write_Intel(FileHeader.bfReserved1);
Write_Intel(FileHeader.bfReserved2);
Write_Intel(FileHeader.bfOffBits);
--
Write_Intel(FileInfo.biSize);
Write_Intel(FileInfo.biWidth);
Write_Intel(FileInfo.biHeight);
Write_Intel(FileInfo.biPlanes);
Write_Intel(FileInfo.biBitCount);
Write_Intel(FileInfo.biCompression);
Write_Intel(FileInfo.biSizeImage);
Write_Intel(FileInfo.biXPelsPerMeter);
Write_Intel(FileInfo.biYPelsPerMeter);
Write_Intel(FileInfo.biClrUsed);
Write_Intel(FileInfo.biClrImportant);
-- BMP raw BGR image:
declare
-- Workaround for the severe xxx'Read xxx'Write performance
-- problems in the GNAT and ObjectAda compilers (as in 2009)
-- This is possible if and only if Byte = Stream_Element and
-- arrays types are both packed the same way.
--
subtype Size_test_a is Byte_Array(1..19);
subtype Size_test_b is Ada.Streams.Stream_Element_Array(1..19);
workaround_possible: constant Boolean:=
Size_test_a'Size = Size_test_b'Size and then
Size_test_a'Alignment = Size_test_b'Alignment;
--
begin
if workaround_possible then
declare
use Ada.Streams;
SE_Buffer : Stream_Element_Array (0..Stream_Element_Offset(img_buf'Length-1));
for SE_Buffer'Address use img_buf.all'Address;
pragma Import (Ada, SE_Buffer);
begin
Ada.Streams.Write(Stream(f).all, SE_Buffer(0..Stream_Element_Offset(img_buf'Length-1)));
end;
else
Byte_Array'Write(Stream(f), img_buf.all); -- the workaround is about this line...
end if;
end;
Close(f);
end Dump_BMP_24;
procedure Process(name: String; as_background, test_only: Boolean) is
f: Ada.Streams.Stream_IO.File_Type;
i: GID.Image_descriptor;
up_name: constant String:= To_Upper(name);
--
next_frame, current_frame: Ada.Calendar.Day_Duration:= 0.0;
begin
--
-- Load the image in its original format
--
Open(f, In_File, name);
Put_Line(Standard_Error, "Processing " & name & "...");
--
GID.Load_image_header(
i,
Stream(f).all,
try_tga =>
name'Length >= 4 and then
up_name(up_name'Last-3..up_name'Last) = ".TGA"
);
Put_Line(Standard_Error,
" Image format: " & GID.Image_format_type'Image(GID.Format(i))
);
Put_Line(Standard_Error,
" Image detailed format: " & GID.Detailed_format(i)
);
Put_Line(Standard_Error,
" Image sub-format ID (if any): " & Integer'Image(GID.Subformat(i))
);
Put_Line(Standard_Error,
" Dimensions in pixels: " &
Integer'Image(GID.Pixel_width(i)) & " x" &
Integer'Image(GID.Pixel_height(i))
);
Put_Line(Standard_Error,
" Display orientation: " &
GID.Orientation'Image(GID.Display_orientation(i))
);
Put(Standard_Error,
" Color depth: " &
Integer'Image(GID.Bits_per_pixel(i)) & " bits"
);
if GID.Bits_per_pixel(i) <= 24 then
Put_Line(Standard_Error,
',' &
Integer'Image(2**GID.Bits_per_pixel(i)) & " colors"
);
else
New_Line(Standard_Error);
end if;
Put_Line(Standard_Error,
" Palette: " & Boolean'Image(GID.Has_palette(i))
);
Put_Line(Standard_Error,
" Greyscale: " & Boolean'Image(GID.Greyscale(i))
);
Put_Line(Standard_Error,
" RLE encoding (if any): " & Boolean'Image(GID.RLE_encoded(i))
);
Put_Line(Standard_Error,
" Interlaced (GIF: each frame's choice): " & Boolean'Image(GID.Interlaced(i))
);
Put_Line(Standard_Error,
" Expect transparency: " & Boolean'Image(GID.Expect_transparency(i))
);
Put_Line(Standard_Error, "1........10........20");
Put_Line(Standard_Error, " | | ");
--
if as_background then
case GID.Display_orientation(i) is
when GID.Unchanged =>
Load_raw_image_0(i, bkg_buf, next_frame);
when GID.Rotation_90 =>
Load_raw_image_90(i, bkg_buf, next_frame);
when GID.Rotation_180 =>
Load_raw_image_180(i, bkg_buf, next_frame);
when GID.Rotation_270 =>
Load_raw_image_270(i, bkg_buf, next_frame);
end case;
bkg:= i;
New_Line(Standard_Error);
Close(f);
return;
end if;
loop
case GID.Display_orientation(i) is
when GID.Unchanged =>
Load_raw_image_0(i, img_buf, next_frame);
when GID.Rotation_90 =>
Load_raw_image_90(i, img_buf, next_frame);
when GID.Rotation_180 =>
Load_raw_image_180(i, img_buf, next_frame);
when GID.Rotation_270 =>
Load_raw_image_270(i, img_buf, next_frame);
end case;
if not test_only then
Dump_BMP_24(name & Duration'Image(current_frame), i);
end if;
New_Line(Standard_Error);
if error then
Put_Line(Standard_Error, "Error!");
end if;
exit when next_frame = 0.0;
current_frame:= next_frame;
end loop;
Close(f);
exception
when GID.unknown_image_format =>
Put_Line(Standard_Error, " Image format is unknown!");
if Is_Open(f) then
Close(f);
end if;
end Process;
test_only: Boolean:= False;
begin
if Argument_Count=0 then
Blurb;
return;
end if;
Put_Line(Standard_Error, "To_BMP, using GID version " & GID.version & " dated " & GID.reference);
begin
Process(default_bkg_name, True, False);
-- if success:
background_image_name:= To_Unbounded_String(default_bkg_name);
exception
when Ada.Text_IO.Name_Error =>
null; -- nothing bad, just couldn't find default background
end;
for i in 1..Argument_Count loop
declare
arg: constant String:= Argument(i);
begin
if arg /= "" and then arg(arg'First)='-' then
declare
opt: constant String:= arg(arg'First+1..arg'Last);
begin
if opt = "" then
test_only:= True;
else
Put_Line(Standard_Error, "Background image is " & opt);
Process(opt, True, False);
-- define this only after processing, otherwise
-- a transparent background will try to use
-- an undefined background
background_image_name:= To_Unbounded_String(opt);
end if;
end;
else
Process(arg, False, test_only);
end if;
end;
end loop;
end To_BMP;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Agen; use Agen;
with Argument_Stack;
package body Actions.Init is
procedure Help is
begin
Put_Line(" (new|init)");
Put_Line(" project <name> - create a project from a basic template");
Put_Line(" gpr <name> - create a GPR from a basic template");
end Help;
function Try_Act return Boolean is
begin
if Argument_Stack.Is_Empty then goto Fail; end if;
declare
Action : constant String := Argument_Stack.Pop;
begin
if To_Upper(Action) /= "NEW" and To_Upper(Action) /= "INIT" then
goto Fail;
end if;
end;
if Argument_Stack.Is_Empty then
Put_Line(Standard_Error, "Error: No target was specified");
goto Fail;
end if;
declare
Target : constant String := Argument_Stack.Pop;
begin
if To_Upper(Target) = "PROJECT" then
if Argument_Stack.Is_Empty then
Put_Line(Standard_Error, "Error: No name was specifed");
goto Fail;
end if;
Agen.Create_Project(Argument_Stack.Pop);
return True;
elsif To_Upper(Target) = "GPR" then
if Argument_Stack.Is_Empty then
Put_Line(Standard_Error, "Error: No name was specified");
goto Fail;
end if;
Agen.Create_GPR(Argument_Stack.Pop);
return True;
else
Put_Line(Standard_Error, "Error: """ & Target & """ was not an understood target");
goto Fail;
end if;
end;
<<Fail>>
Argument_Stack.Reset;
return False;
end Try_Act;
end Actions.Init;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- (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.
with Ada.Integer_Text_IO;
separate (Latin_Utils.Inflections_Package)
package body Decn_Record_IO is
---------------------------------------------------------------------------
procedure Get (File : in File_Type; Item : out Decn_Record)
is
Spacer : Character := ' ';
pragma Unreferenced (Spacer);
begin
Ada.Integer_Text_IO.Get (File, Item.Which);
Get (File, Spacer);
Ada.Integer_Text_IO.Get (File, Item.Var);
end Get;
---------------------------------------------------------------------------
procedure Get (Item : out Decn_Record)
is
Spacer : Character := ' ';
pragma Unreferenced (Spacer);
begin
Ada.Integer_Text_IO.Get (Item.Which);
Get (Spacer);
Ada.Integer_Text_IO.Get (Item.Var);
end Get;
---------------------------------------------------------------------------
procedure Put (File : in File_Type; Item : in Decn_Record) is
begin
Ada.Integer_Text_IO.Put (File, Item.Which, 1);
Put (File, ' ');
Ada.Integer_Text_IO.Put (File, Item.Var, 1);
end Put;
---------------------------------------------------------------------------
procedure Put (Item : in Decn_Record) is
begin
Ada.Integer_Text_IO.Put (Item.Which, 1);
Put (' ');
Ada.Integer_Text_IO.Put (Item.Var, 1);
end Put;
---------------------------------------------------------------------------
procedure Get
(Source : in String;
Target : out Decn_Record;
Last : out Integer
)
is
-- This variable are used for computing lower bound of substrings
Low : Integer := Source'First - 1;
begin
Ada.Integer_Text_IO.Get
(Source (Low + 1 .. Source'Last), Target.Which, Low);
Low := Low + 1;
Ada.Integer_Text_IO.Get
(Source (Low + 1 .. Source'Last), Target.Var, Last);
end Get;
---------------------------------------------------------------------------
procedure Put (Target : out String; Item : in Decn_Record)
is
-- These variables are used for computing bounds of substrings
Low : Integer := Target'First - 1;
High : Integer := 0;
begin
-- Put Which_Type
High := Low + 1;
Ada.Integer_Text_IO.Put (Target (Low + 1 .. High), Item.Which);
Low := High + 1;
-- Put Variant_Type
Target (Low) := ' ';
High := Low + 1;
Ada.Integer_Text_IO.Put (Target (Low + 1 .. High), Item.Var);
-- Fill remainder of String
Target (High + 1 .. Target'Last) := (others => ' ');
end Put;
---------------------------------------------------------------------------
end Decn_Record_IO;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- if not, write to the Free Software Foundation, Inc., 59 Temple --
-- Place - Suite 330, Boston, MA 02111-1307, USA. --
-----------------------------------------------------------------------
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Real_Time; use Ada.Real_Time;
with Display; use Display;
with Display.Basic; use Display.Basic;
with Libm_Single; use Libm_Single;
procedure Main is
-- QUESTION 1 - Part 1
-- define type Bodies_Enum_T as an enumeration of Sun, Earth, Moon, Satellite
-- define type Parameters_Enum_T as an enumeration of parameter X, Y,
-- Radius, Speed, Distance, Angle
-- define type Bodies_Array_T as an array of float indexed by bodies and
-- parameters
-- define type Colors_Array_T as an array of color (RGBA_T) indexed by bodies
-- declare variable Bodies which is an instance of Bodies_Array_T
-- declare variable Colors which is an instance of Colors_Array_T
-- declare a variable Next of type Time to store the Next step time
Next : Time;
-- declare a constant Period of 40 milliseconds of type Time_Span defining
-- the loop period
Period : constant Time_Span := Milliseconds (40);
-- reference to the application window
Window : Window_ID;
-- reference to the graphical canvas associated with the application window
Canvas : Canvas_ID;
begin
-- Create a window 240x320
Window :=
Create_Window (Width => 240, Height => 320, Name => "Solar System");
-- Retrieve the graphical canvas from the window
Canvas := Get_Canvas (Window);
-- QUESTION 1 - Part 2
-- initialize Bodies variable with parameters for each body using an aggregate
-- Sun Distance = 0.0, Angle = 0.0, Speed = 0.0, Radius = 20.0;
-- Earth Distance = 50.0, Angle = 0.0, Speed = 0.02, Radius = 5.0;
-- Moon Distance = 15.0, Angle = 0.0, Speed = 0.04, Radius = 2.0;
-- Satellite Distance = 8.0, Angle = 0.0, Speed = 0.1, Radius = 1.0;
-- QUESTION 1 - Part 3
-- initialize Colors variable with Sun is Yellow, Earth is Blue, Moon is
-- White, Satellite is Red
-- initialize the Next step time begin the current time (Clock) + the period
Next := Clock + Period;
while not Is_Killed loop
-- QUESTION 2 - part 1
-- create a loop to update each body position and angles
-- the position of an object around (0,0) at distance d with an angle a
-- is (d*cos(a), d*sin(a))
-- update angle parameter of each body adding speed to the previous angle
-- QUESTION 2 - part 2
-- create a loop to draw every objects
-- use the Draw_Sphere procedure to do it
-- update the screen using procedure Swap_Buffers
Swap_Buffers (Window);
-- wait until Next
delay until Next;
-- update the Next time adding the period for the next step
Next := Next + Period;
end loop;
end Main;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with numbers; use numbers;
with strings; use strings;
package address is
type pos_addr_t is tagged private;
null_pos_addr : constant pos_addr_t;
error_address_odd : exception;
function create (value : word) return pos_addr_t;
procedure set (pos_addr : in out pos_addr_t; value : word);
function get (pos_addr : pos_addr_t) return word;
function valid_value_for_pos_addr (value : word) return boolean;
procedure inc (pos_addr : in out pos_addr_t);
function inc (pos_addr : pos_addr_t) return pos_addr_t;
procedure dec (pos_addr : in out pos_addr_t);
function "<" (a, b : pos_addr_t) return boolean;
function "<=" (a, b : pos_addr_t) return boolean;
function ">" (a, b : pos_addr_t) return boolean;
function ">=" (a, b : pos_addr_t) return boolean;
function "-" (a, b : pos_addr_t) return pos_addr_t;
function "+" (a, b : pos_addr_t) return pos_addr_t;
function "*" (a, b : pos_addr_t) return pos_addr_t;
function "/" (a, b : pos_addr_t) return pos_addr_t;
function "+" (a: pos_addr_t; b : natural) return pos_addr_t;
function "+" (a: pos_addr_t; b : word) return pos_addr_t;
private
use type word;
type pos_addr_t is tagged record
addr : word;
end record;
null_pos_addr : constant pos_addr_t := (addr => 16#ffff#);
end address;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- { dg-do run }
with GNAT.Time_Stamp;
use GNAT.Time_Stamp;
procedure test_time_stamp is
S : constant String := Current_Time;
function NN (S : String) return Boolean is
begin
for J in S'Range loop
if S (J) not in '0' .. '9' then
return True;
end if;
end loop;
return False;
end NN;
begin
if S'Length /= 22
or else S (5) /= '-'
or else S (8) /= '-'
or else S (11) /= ' '
or else S (14) /= ':'
or else S (17) /= ':'
or else S (20) /= '.'
or else NN (S (1 .. 4))
or else NN (S (6 .. 7))
or else NN (S (9 .. 10))
or else NN (S (12 .. 13))
or else NN (S (15 .. 16))
or else NN (S (18 .. 19))
or else NN (S (21 .. 22))
then
raise Program_Error;
end if;
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
with Ada.Strings.Wide_Maps;
package Ada.Strings.Wide_Fixed is
pragma Preelaborate;
-------------------------------------------------------------------
-- Copy Procedure for Wide_Strings of Possibly Different Lengths --
-------------------------------------------------------------------
procedure Move
(Source : Wide_String;
Target : out Wide_String;
Drop : Truncation := Error;
Justify : Alignment := Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
------------------------
-- Search Subprograms --
------------------------
function Index
(Source : Wide_String;
Pattern : Wide_String;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
function Index
(Source : Wide_String;
Pattern : Wide_String;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
function Index
(Source : Wide_String;
Set : Wide_Maps.Wide_Character_Set;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
function Index
(Source : Wide_String;
Pattern : Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
pragma Ada_05 (Index);
function Index
(Source : Wide_String;
Pattern : Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
pragma Ada_05 (Index);
function Index
(Source : Wide_String;
Set : Wide_Maps.Wide_Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
pragma Ada_05 (Index);
function Index_Non_Blank
(Source : Wide_String;
Going : Direction := Forward) return Natural;
function Index_Non_Blank
(Source : Wide_String;
From : Positive;
Going : Direction := Forward) return Natural;
pragma Ada_05 (Index_Non_Blank);
function Count
(Source : Wide_String;
Pattern : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping := Wide_Maps.Identity)
return Natural;
function Count
(Source : Wide_String;
Pattern : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Natural;
function Count
(Source : Wide_String;
Set : Wide_Maps.Wide_Character_Set) return Natural;
procedure Find_Token
(Source : Wide_String;
Set : Wide_Maps.Wide_Character_Set;
From : Positive;
Test : Membership;
First : out Positive;
Last : out Natural);
pragma Ada_2012 (Find_Token);
procedure Find_Token
(Source : Wide_String;
Set : Wide_Maps.Wide_Character_Set;
Test : Membership;
First : out Positive;
Last : out Natural);
-----------------------------------------
-- Wide_String Translation Subprograms --
-----------------------------------------
function Translate
(Source : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping) return Wide_String;
procedure Translate
(Source : in out Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping);
function Translate
(Source : Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function) return Wide_String;
procedure Translate
(Source : in out Wide_String;
Mapping : Wide_Maps.Wide_Character_Mapping_Function);
--------------------------------------------
-- Wide_String Transformation Subprograms --
--------------------------------------------
function Replace_Slice
(Source : Wide_String;
Low : Positive;
High : Natural;
By : Wide_String) return Wide_String;
procedure Replace_Slice
(Source : in out Wide_String;
Low : Positive;
High : Natural;
By : Wide_String;
Drop : Truncation := Error;
Justify : Alignment := Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
function Insert
(Source : Wide_String;
Before : Positive;
New_Item : Wide_String) return Wide_String;
procedure Insert
(Source : in out Wide_String;
Before : Positive;
New_Item : Wide_String;
Drop : Truncation := Error);
function Overwrite
(Source : Wide_String;
Position : Positive;
New_Item : Wide_String) return Wide_String;
procedure Overwrite
(Source : in out Wide_String;
Position : Positive;
New_Item : Wide_String;
Drop : Truncation := Right);
function Delete
(Source : Wide_String;
From : Positive;
Through : Natural) return Wide_String;
procedure Delete
(Source : in out Wide_String;
From : Positive;
Through : Natural;
Justify : Alignment := Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
--------------------------------------
-- Wide_String Selector Subprograms --
--------------------------------------
function Trim
(Source : Wide_String;
Side : Trim_End) return Wide_String;
procedure Trim
(Source : in out Wide_String;
Side : Trim_End;
Justify : Alignment := Left;
Pad : Wide_Character := Wide_Space);
function Trim
(Source : Wide_String;
Left : Wide_Maps.Wide_Character_Set;
Right : Wide_Maps.Wide_Character_Set) return Wide_String;
procedure Trim
(Source : in out Wide_String;
Left : Wide_Maps.Wide_Character_Set;
Right : Wide_Maps.Wide_Character_Set;
Justify : Alignment := Ada.Strings.Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
function Head
(Source : Wide_String;
Count : Natural;
Pad : Wide_Character := Ada.Strings.Wide_Space) return Wide_String;
procedure Head
(Source : in out Wide_String;
Count : Natural;
Justify : Alignment := Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
function Tail
(Source : Wide_String;
Count : Natural;
Pad : Wide_Character := Ada.Strings.Wide_Space) return Wide_String;
procedure Tail
(Source : in out Wide_String;
Count : Natural;
Justify : Alignment := Left;
Pad : Wide_Character := Ada.Strings.Wide_Space);
---------------------------------------
-- Wide_String Constructor Functions --
---------------------------------------
function "*"
(Left : Natural;
Right : Wide_Character) return Wide_String;
function "*"
(Left : Natural;
Right : Wide_String) return Wide_String;
end Ada.Strings.Wide_Fixed;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
-- @summary
-- Version Trees
--
-- @description
-- The package provides Version and Version_Tree types.
-- Nested generic package Versioned_Values provides Container type.
--
package Incr.Version_Trees is
type Version is private;
-- Version identificator
type Version_Tree is tagged limited private;
-- Version_Tree keeps history of a document as sequence (actually tree) of
-- Versions as they are created. One version (changing) is different, this
-- is a version where current chages are performed.
-- Only read-write version of the document is its changing version.
type Version_Tree_Access is access all Version_Tree'Class;
not overriding function Changing (Self : Version_Tree) return Version;
-- Version where current chages are performed
not overriding function Is_Changing
(Self : Version_Tree; Value : Version) return Boolean;
-- Check if given Value is changing version of a document.
-- @param Value version under test
not overriding function Parent
(Self : Version_Tree; Value : Version) return Version;
-- Provide origin of given Version.
-- @param Value version under query
not overriding procedure Start_Change
(Self : in out Version_Tree;
Parent : Version;
Changing : out Version);
-- Create new changing version by branching it from given Parent version.
-- @param Parent version to branch new one from
-- @param Changing return new version. It becames changing version of
-- a document
generic
type Element is private;
-- @private Disable indexing this type in gnatdoc
package Versioned_Values is
-- @summary
-- Versioned Values
--
-- @description
-- The package provides Container to keep history of value changes
-- over the time.
type Container is private;
-- Container to store history of value changes.
procedure Initialize
(Self : in out Container;
Initial_Value : Element);
-- Initialize container and place Initial_Value as current.
-- @param Initial_Value value at the initial version of a document
function Get
(Self : Container;
Time : Version) return Element;
-- Retrieve a value from container corresponding to given version.
-- @param Time provides requested version
-- @return Value at given time/version
procedure Set
(Self : in out Container;
Value : Element;
Time : Version;
Changes : in out Integer);
-- Update container by given value. Version should be Is_Changing in
-- the corresponding Version_Tree. The call returns Changes counter:
-- * as +1 if Value becomes new value of the property
-- * as -1 if Value is revereted to old value of the property
-- * and 0 if Value has been changed already or match old value
procedure Discard
(Self : in out Container;
Time : Version;
Changes : out Integer);
-- Update container by reverting its value. Version should be
-- Is_Changing as in Set. See Set for description of Changes.
private
type Circle_Index is mod 8;
type Element_Array is array (Circle_Index) of Element;
type Version_Array is array (Circle_Index) of Version;
type Container is record
Elements : Element_Array;
Versions : Version_Array;
Index : Circle_Index := 0;
end record;
end Versioned_Values;
private
-- This is prototype implementation. It doesn't support branching
-- and keeps history as linear sequence of versions. Only a few versions
-- are kept and any older versions are dropped.
type Version is mod 256;
function "<" (Left, Right : Version) return Boolean;
function ">=" (Left, Right : Version) return Boolean is
(not (Left < Right));
function ">" (Left, Right : Version) return Boolean is (Right < Left);
type Version_Tree is tagged limited record
Changing : Version := 1;
end record;
end Incr.Version_Trees;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Checks; use Checks;
with Einfo; use Einfo;
with Exp_Util; use Exp_Util;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Eval; use Sem_Eval;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Snames; use Snames;
with Stand; use Stand;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
with Urealp; use Urealp;
package body Exp_Fixd is
-----------------------
-- Local Subprograms --
-----------------------
-- General note; in this unit, a number of routines are driven by the
-- types (Etype) of their operands. Since we are dealing with unanalyzed
-- expressions as they are constructed, the Etypes would not normally be
-- set, but the construction routines that we use in this unit do in fact
-- set the Etype values correctly. In addition, setting the Etype ensures
-- that the analyzer does not try to redetermine the type when the node
-- is analyzed (which would be wrong, since in the case where we set the
-- Conversion_OK flag, it would think it was still dealing with a normal
-- fixed-point operation and mess it up).
function Build_Conversion
(N : Node_Id;
Typ : Entity_Id;
Expr : Node_Id;
Rchk : Boolean := False;
Trunc : Boolean := False) return Node_Id;
-- Build an expression that converts the expression Expr to type Typ,
-- taking the source location from Sloc (N). If the conversions involve
-- fixed-point types, then the Conversion_OK flag will be set so that the
-- resulting conversions do not get re-expanded. On return the resulting
-- node has its Etype set. If Rchk is set, then Do_Range_Check is set
-- in the resulting conversion node. If Trunc is set, then the
-- Float_Truncate flag is set on the conversion, which must be from
-- a floating-point type to an integer type.
function Build_Divide (N : Node_Id; L, R : Node_Id) return Node_Id;
-- Builds an N_Op_Divide node from the given left and right operand
-- expressions, using the source location from Sloc (N). The operands are
-- either both Universal_Real, in which case Build_Divide differs from
-- Make_Op_Divide only in that the Etype of the resulting node is set (to
-- Universal_Real), or they can be integer or fixed-point types. In this
-- case the types need not be the same, and Build_Divide chooses a type
-- long enough to hold both operands (i.e. the size of the longer of the
-- two operand types), and both operands are converted to this type. The
-- Etype of the result is also set to this value. The Rounded_Result flag
-- of the result in this case is set from the Rounded_Result flag of node
-- N. On return, the resulting node is analyzed and has its Etype set.
function Build_Double_Divide
(N : Node_Id;
X, Y, Z : Node_Id) return Node_Id;
-- Returns a node corresponding to the value X/(Y*Z) using the source
-- location from Sloc (N). The division is rounded if the Rounded_Result
-- flag of N is set. The integer types of X, Y, Z may be different. On
-- return the resulting node is analyzed, and has its Etype set.
procedure Build_Double_Divide_Code
(N : Node_Id;
X, Y, Z : Node_Id;
Qnn, Rnn : out Entity_Id;
Code : out List_Id);
-- Generates a sequence of code for determining the quotient and remainder
-- of the division X/(Y*Z), using the source location from Sloc (N).
-- Entities of appropriate types are allocated for the quotient and
-- remainder and returned in Qnn and Rnn. The result is rounded if the
-- Rounded_Result flag of N is set. The Etype fields of Qnn and Rnn are
-- appropriately set on return.
function Build_Multiply (N : Node_Id; L, R : Node_Id) return Node_Id;
-- Builds an N_Op_Multiply node from the given left and right operand
-- expressions, using the source location from Sloc (N). The operands are
-- either both Universal_Real, in which case Build_Multiply differs from
-- Make_Op_Multiply only in that the Etype of the resulting node is set (to
-- Universal_Real), or they can be integer or fixed-point types. In this
-- case the types need not be the same, and Build_Multiply chooses a type
-- long enough to hold the product (i.e. twice the size of the longer of
-- the two operand types), and both operands are converted to this type.
-- The Etype of the result is also set to this value. However, the result
-- can never overflow Integer_64, so this is the largest type that is ever
-- generated. On return, the resulting node is analyzed and has Etype set.
function Build_Rem (N : Node_Id; L, R : Node_Id) return Node_Id;
-- Builds an N_Op_Rem node from the given left and right operand
-- expressions, using the source location from Sloc (N). The operands are
-- both integer types, which need not be the same. Build_Rem converts the
-- operand with the smaller sized type to match the type of the other
-- operand and sets this as the result type. The result is never rounded
-- (rem operations cannot be rounded in any case). On return, the resulting
-- node is analyzed and has its Etype set.
function Build_Scaled_Divide
(N : Node_Id;
X, Y, Z : Node_Id) return Node_Id;
-- Returns a node corresponding to the value X*Y/Z using the source
-- location from Sloc (N). The division is rounded if the Rounded_Result
-- flag of N is set. The integer types of X, Y, Z may be different. On
-- return the resulting node is analyzed and has is Etype set.
procedure Build_Scaled_Divide_Code
(N : Node_Id;
X, Y, Z : Node_Id;
Qnn, Rnn : out Entity_Id;
Code : out List_Id);
-- Generates a sequence of code for determining the quotient and remainder
-- of the division X*Y/Z, using the source location from Sloc (N). Entities
-- of appropriate types are allocated for the quotient and remainder and
-- returned in Qnn and Rrr. The integer types for X, Y, Z may be different.
-- The division is rounded if the Rounded_Result flag of N is set. The
-- Etype fields of Qnn and Rnn are appropriately set on return.
procedure Do_Divide_Fixed_Fixed (N : Node_Id);
-- Handles expansion of divide for case of two fixed-point operands
-- (neither of them universal), with an integer or fixed-point result.
-- N is the N_Op_Divide node to be expanded.
procedure Do_Divide_Fixed_Universal (N : Node_Id);
-- Handles expansion of divide for case of a fixed-point operand divided
-- by a universal real operand, with an integer or fixed-point result. N
-- is the N_Op_Divide node to be expanded.
procedure Do_Divide_Universal_Fixed (N : Node_Id);
-- Handles expansion of divide for case of a universal real operand
-- divided by a fixed-point operand, with an integer or fixed-point
-- result. N is the N_Op_Divide node to be expanded.
procedure Do_Multiply_Fixed_Fixed (N : Node_Id);
-- Handles expansion of multiply for case of two fixed-point operands
-- (neither of them universal), with an integer or fixed-point result.
-- N is the N_Op_Multiply node to be expanded.
procedure Do_Multiply_Fixed_Universal (N : Node_Id; Left, Right : Node_Id);
-- Handles expansion of multiply for case of a fixed-point operand
-- multiplied by a universal real operand, with an integer or fixed-
-- point result. N is the N_Op_Multiply node to be expanded, and
-- Left, Right are the operands (which may have been switched).
procedure Expand_Convert_Fixed_Static (N : Node_Id);
-- This routine is called where the node N is a conversion of a literal
-- or other static expression of a fixed-point type to some other type.
-- In such cases, we simply rewrite the operand as a real literal and
-- reanalyze. This avoids problems which would otherwise result from
-- attempting to build and fold expressions involving constants.
function Fpt_Value (N : Node_Id) return Node_Id;
-- Given an operand of fixed-point operation, return an expression that
-- represents the corresponding Universal_Real value. The expression
-- can be of integer type, floating-point type, or fixed-point type.
-- The expression returned is neither analyzed and resolved. The Etype
-- of the result is properly set (to Universal_Real).
function Integer_Literal
(N : Node_Id;
V : Uint;
Negative : Boolean := False) return Node_Id;
-- Given a non-negative universal integer value, build a typed integer
-- literal node, using the smallest applicable standard integer type. If
-- and only if Negative is true a negative literal is built. If V exceeds
-- 2**63-1, the largest value allowed for perfect result set scaling
-- factors (see RM G.2.3(22)), then Empty is returned. The node N provides
-- the Sloc value for the constructed literal. The Etype of the resulting
-- literal is correctly set, and it is marked as analyzed.
function Real_Literal (N : Node_Id; V : Ureal) return Node_Id;
-- Build a real literal node from the given value, the Etype of the
-- returned node is set to Universal_Real, since all floating-point
-- arithmetic operations that we construct use Universal_Real
function Rounded_Result_Set (N : Node_Id) return Boolean;
-- Returns True if N is a node that contains the Rounded_Result flag
-- and if the flag is true or the target type is an integer type.
procedure Set_Result
(N : Node_Id;
Expr : Node_Id;
Rchk : Boolean := False;
Trunc : Boolean := False);
-- N is the node for the current conversion, division or multiplication
-- operation, and Expr is an expression representing the result. Expr may
-- be of floating-point or integer type. If the operation result is fixed-
-- point, then the value of Expr is in units of small of the result type
-- (i.e. small's have already been dealt with). The result of the call is
-- to replace N by an appropriate conversion to the result type, dealing
-- with rounding for the decimal types case. The node is then analyzed and
-- resolved using the result type. If Rchk or Trunc are True, then
-- respectively Do_Range_Check and Float_Truncate are set in the
-- resulting conversion.
----------------------
-- Build_Conversion --
----------------------
function Build_Conversion
(N : Node_Id;
Typ : Entity_Id;
Expr : Node_Id;
Rchk : Boolean := False;
Trunc : Boolean := False) return Node_Id
is
Loc : constant Source_Ptr := Sloc (N);
Result : Node_Id;
Rcheck : Boolean := Rchk;
begin
-- A special case, if the expression is an integer literal and the
-- target type is an integer type, then just retype the integer
-- literal to the desired target type. Don't do this if we need
-- a range check.
if Nkind (Expr) = N_Integer_Literal
and then Is_Integer_Type (Typ)
and then not Rchk
then
Result := Expr;
-- Cases where we end up with a conversion. Note that we do not use the
-- Convert_To abstraction here, since we may be decorating the resulting
-- conversion with Rounded_Result and/or Conversion_OK, so we want the
-- conversion node present, even if it appears to be redundant.
else
-- Remove inner conversion if both inner and outer conversions are
-- to integer types, since the inner one serves no purpose (except
-- perhaps to set rounding, so we preserve the Rounded_Result flag)
-- and also preserve the Conversion_OK and Do_Range_Check flags of
-- the inner conversion.
if Is_Integer_Type (Typ)
and then Is_Integer_Type (Etype (Expr))
and then Nkind (Expr) = N_Type_Conversion
then
Result :=
Make_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Expression => Expression (Expr));
Set_Rounded_Result (Result, Rounded_Result_Set (Expr));
Set_Conversion_OK (Result, Conversion_OK (Expr));
Rcheck := Rcheck or Do_Range_Check (Expr);
-- For all other cases, a simple type conversion will work
else
Result :=
Make_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Expression => Expr);
Set_Float_Truncate (Result, Trunc);
end if;
-- Set Conversion_OK if either result or expression type is a
-- fixed-point type, since from a semantic point of view, we are
-- treating fixed-point values as integers at this stage.
if Is_Fixed_Point_Type (Typ)
or else Is_Fixed_Point_Type (Etype (Expression (Result)))
then
Set_Conversion_OK (Result);
end if;
-- Set Do_Range_Check if either it was requested by the caller,
-- or if an eliminated inner conversion had a range check.
if Rcheck then
Enable_Range_Check (Result);
else
Set_Do_Range_Check (Result, False);
end if;
end if;
Set_Etype (Result, Typ);
return Result;
end Build_Conversion;
------------------
-- Build_Divide --
------------------
function Build_Divide (N : Node_Id; L, R : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (N);
Left_Type : constant Entity_Id := Base_Type (Etype (L));
Right_Type : constant Entity_Id := Base_Type (Etype (R));
Left_Size : Int;
Right_Size : Int;
Rsize : Int;
Result_Type : Entity_Id;
Rnode : Node_Id;
begin
-- Deal with floating-point case first
if Is_Floating_Point_Type (Left_Type) then
pragma Assert (Left_Type = Universal_Real);
pragma Assert (Right_Type = Universal_Real);
Rnode := Make_Op_Divide (Loc, L, R);
Result_Type := Universal_Real;
-- Integer and fixed-point cases
else
-- An optimization. If the right operand is the literal 1, then we
-- can just return the left hand operand. Putting the optimization
-- here allows us to omit the check at the call site.
if Nkind (R) = N_Integer_Literal and then Intval (R) = 1 then
return L;
end if;
-- First figure out the effective sizes of the operands. Normally
-- the effective size of an operand is the RM_Size of the operand.
-- But a special case arises with operands whose size is known at
-- compile time. In this case, we can use the actual value of the
-- operand to get its size if it would fit signed in 8 or 16 bits.
Left_Size := UI_To_Int (RM_Size (Left_Type));
if Compile_Time_Known_Value (L) then
declare
Val : constant Uint := Expr_Value (L);
begin
if Val < Int'(2 ** 7) then
Left_Size := 8;
elsif Val < Int'(2 ** 15) then
Left_Size := 16;
end if;
end;
end if;
Right_Size := UI_To_Int (RM_Size (Right_Type));
if Compile_Time_Known_Value (R) then
declare
Val : constant Uint := Expr_Value (R);
begin
if Val <= Int'(2 ** 7) then
Right_Size := 8;
elsif Val <= Int'(2 ** 15) then
Right_Size := 16;
end if;
end;
end if;
-- Do the operation using the longer of the two sizes
Rsize := Int'Max (Left_Size, Right_Size);
if Rsize <= 8 then
Result_Type := Standard_Integer_8;
elsif Rsize <= 16 then
Result_Type := Standard_Integer_16;
elsif Rsize <= 32 then
Result_Type := Standard_Integer_32;
else
Result_Type := Standard_Integer_64;
end if;
Rnode :=
Make_Op_Divide (Loc,
Left_Opnd => Build_Conversion (N, Result_Type, L),
Right_Opnd => Build_Conversion (N, Result_Type, R));
end if;
-- We now have a divide node built with Result_Type set. First
-- set Etype of result, as required for all Build_xxx routines
Set_Etype (Rnode, Base_Type (Result_Type));
-- The result is rounded if the target of the operation is decimal
-- and Rounded_Result is set, or if the target of the operation
-- is an integer type.
if Is_Integer_Type (Etype (N))
or else Rounded_Result_Set (N)
then
Set_Rounded_Result (Rnode);
end if;
-- One more check. We did the divide operation using the longer of
-- the two sizes, which is reasonable. However, in the case where the
-- two types have unequal sizes, it is impossible for the result of
-- a divide operation to be larger than the dividend, so we can put
-- a conversion round the result to keep the evolving operation size
-- as small as possible.
if not Is_Floating_Point_Type (Left_Type) then
Rnode := Build_Conversion (N, Left_Type, Rnode);
end if;
return Rnode;
end Build_Divide;
-------------------------
-- Build_Double_Divide --
-------------------------
function Build_Double_Divide
(N : Node_Id;
X, Y, Z : Node_Id) return Node_Id
is
Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y)));
Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z)));
Expr : Node_Id;
begin
-- If denominator fits in 64 bits, we can build the operations directly
-- without causing any intermediate overflow, so that's what we do.
if Nat'Max (Y_Size, Z_Size) <= 32 then
return
Build_Divide (N, X, Build_Multiply (N, Y, Z));
-- Otherwise we use the runtime routine
-- [Qnn : Interfaces.Integer_64,
-- Rnn : Interfaces.Integer_64;
-- Double_Divide (X, Y, Z, Qnn, Rnn, Round);
-- Qnn]
else
declare
Loc : constant Source_Ptr := Sloc (N);
Qnn : Entity_Id;
Rnn : Entity_Id;
Code : List_Id;
pragma Warnings (Off, Rnn);
begin
Build_Double_Divide_Code (N, X, Y, Z, Qnn, Rnn, Code);
Insert_Actions (N, Code);
Expr := New_Occurrence_Of (Qnn, Loc);
-- Set type of result in case used elsewhere (see note at start)
Set_Etype (Expr, Etype (Qnn));
-- Set result as analyzed (see note at start on build routines)
return Expr;
end;
end if;
end Build_Double_Divide;
------------------------------
-- Build_Double_Divide_Code --
------------------------------
-- If the denominator can be computed in 64-bits, we build
-- [Nnn : constant typ := typ (X);
-- Dnn : constant typ := typ (Y) * typ (Z)
-- Qnn : constant typ := Nnn / Dnn;
-- Rnn : constant typ := Nnn / Dnn;
-- If the numerator cannot be computed in 64 bits, we build
-- [Qnn : typ;
-- Rnn : typ;
-- Double_Divide (X, Y, Z, Qnn, Rnn, Round);]
procedure Build_Double_Divide_Code
(N : Node_Id;
X, Y, Z : Node_Id;
Qnn, Rnn : out Entity_Id;
Code : out List_Id)
is
Loc : constant Source_Ptr := Sloc (N);
X_Size : constant Nat := UI_To_Int (Esize (Etype (X)));
Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y)));
Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z)));
QR_Siz : Nat;
QR_Typ : Entity_Id;
Nnn : Entity_Id;
Dnn : Entity_Id;
Quo : Node_Id;
Rnd : Entity_Id;
begin
-- Find type that will allow computation of numerator
QR_Siz := Nat'Max (X_Size, 2 * Nat'Max (Y_Size, Z_Size));
if QR_Siz <= 16 then
QR_Typ := Standard_Integer_16;
elsif QR_Siz <= 32 then
QR_Typ := Standard_Integer_32;
elsif QR_Siz <= 64 then
QR_Typ := Standard_Integer_64;
-- For more than 64, bits, we use the 64-bit integer defined in
-- Interfaces, so that it can be handled by the runtime routine.
else
QR_Typ := RTE (RE_Integer_64);
end if;
-- Define quotient and remainder, and set their Etypes, so
-- that they can be picked up by Build_xxx routines.
Qnn := Make_Temporary (Loc, 'S');
Rnn := Make_Temporary (Loc, 'R');
Set_Etype (Qnn, QR_Typ);
Set_Etype (Rnn, QR_Typ);
-- Case that we can compute the denominator in 64 bits
if QR_Siz <= 64 then
-- Create temporaries for numerator and denominator and set Etypes,
-- so that New_Occurrence_Of picks them up for Build_xxx calls.
Nnn := Make_Temporary (Loc, 'N');
Dnn := Make_Temporary (Loc, 'D');
Set_Etype (Nnn, QR_Typ);
Set_Etype (Dnn, QR_Typ);
Code := New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Nnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression => Build_Conversion (N, QR_Typ, X)),
Make_Object_Declaration (Loc,
Defining_Identifier => Dnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression =>
Build_Multiply (N,
Build_Conversion (N, QR_Typ, Y),
Build_Conversion (N, QR_Typ, Z))));
Quo :=
Build_Divide (N,
New_Occurrence_Of (Nnn, Loc),
New_Occurrence_Of (Dnn, Loc));
Set_Rounded_Result (Quo, Rounded_Result_Set (N));
Append_To (Code,
Make_Object_Declaration (Loc,
Defining_Identifier => Qnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression => Quo));
Append_To (Code,
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression =>
Build_Rem (N,
New_Occurrence_Of (Nnn, Loc),
New_Occurrence_Of (Dnn, Loc))));
-- Case where denominator does not fit in 64 bits, so we have to
-- call the runtime routine to compute the quotient and remainder
else
Rnd := Boolean_Literals (Rounded_Result_Set (N));
Code := New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Qnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc)),
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc)),
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Double_Divide), Loc),
Parameter_Associations => New_List (
Build_Conversion (N, QR_Typ, X),
Build_Conversion (N, QR_Typ, Y),
Build_Conversion (N, QR_Typ, Z),
New_Occurrence_Of (Qnn, Loc),
New_Occurrence_Of (Rnn, Loc),
New_Occurrence_Of (Rnd, Loc))));
end if;
end Build_Double_Divide_Code;
--------------------
-- Build_Multiply --
--------------------
function Build_Multiply (N : Node_Id; L, R : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (N);
Left_Type : constant Entity_Id := Etype (L);
Right_Type : constant Entity_Id := Etype (R);
Left_Size : Int;
Right_Size : Int;
Rsize : Int;
Result_Type : Entity_Id;
Rnode : Node_Id;
begin
-- Deal with floating-point case first
if Is_Floating_Point_Type (Left_Type) then
pragma Assert (Left_Type = Universal_Real);
pragma Assert (Right_Type = Universal_Real);
Result_Type := Universal_Real;
Rnode := Make_Op_Multiply (Loc, L, R);
-- Integer and fixed-point cases
else
-- An optimization. If the right operand is the literal 1, then we
-- can just return the left hand operand. Putting the optimization
-- here allows us to omit the check at the call site. Similarly, if
-- the left operand is the integer 1 we can return the right operand.
if Nkind (R) = N_Integer_Literal and then Intval (R) = 1 then
return L;
elsif Nkind (L) = N_Integer_Literal and then Intval (L) = 1 then
return R;
end if;
-- Otherwise we need to figure out the correct result type size
-- First figure out the effective sizes of the operands. Normally
-- the effective size of an operand is the RM_Size of the operand.
-- But a special case arises with operands whose size is known at
-- compile time. In this case, we can use the actual value of the
-- operand to get its size if it would fit signed in 8 or 16 bits.
Left_Size := UI_To_Int (RM_Size (Left_Type));
if Compile_Time_Known_Value (L) then
declare
Val : constant Uint := Expr_Value (L);
begin
if Val < Int'(2 ** 7) then
Left_Size := 8;
elsif Val < Int'(2 ** 15) then
Left_Size := 16;
end if;
end;
end if;
Right_Size := UI_To_Int (RM_Size (Right_Type));
if Compile_Time_Known_Value (R) then
declare
Val : constant Uint := Expr_Value (R);
begin
if Val <= Int'(2 ** 7) then
Right_Size := 8;
elsif Val <= Int'(2 ** 15) then
Right_Size := 16;
end if;
end;
end if;
-- Now the result size must be at least twice the longer of
-- the two sizes, to accommodate all possible results.
Rsize := 2 * Int'Max (Left_Size, Right_Size);
if Rsize <= 8 then
Result_Type := Standard_Integer_8;
elsif Rsize <= 16 then
Result_Type := Standard_Integer_16;
elsif Rsize <= 32 then
Result_Type := Standard_Integer_32;
else
Result_Type := Standard_Integer_64;
end if;
Rnode :=
Make_Op_Multiply (Loc,
Left_Opnd => Build_Conversion (N, Result_Type, L),
Right_Opnd => Build_Conversion (N, Result_Type, R));
end if;
-- We now have a multiply node built with Result_Type set. First
-- set Etype of result, as required for all Build_xxx routines
Set_Etype (Rnode, Base_Type (Result_Type));
return Rnode;
end Build_Multiply;
---------------
-- Build_Rem --
---------------
function Build_Rem (N : Node_Id; L, R : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (N);
Left_Type : constant Entity_Id := Etype (L);
Right_Type : constant Entity_Id := Etype (R);
Result_Type : Entity_Id;
Rnode : Node_Id;
begin
if Left_Type = Right_Type then
Result_Type := Left_Type;
Rnode :=
Make_Op_Rem (Loc,
Left_Opnd => L,
Right_Opnd => R);
-- If left size is larger, we do the remainder operation using the
-- size of the left type (i.e. the larger of the two integer types).
elsif Esize (Left_Type) >= Esize (Right_Type) then
Result_Type := Left_Type;
Rnode :=
Make_Op_Rem (Loc,
Left_Opnd => L,
Right_Opnd => Build_Conversion (N, Left_Type, R));
-- Similarly, if the right size is larger, we do the remainder
-- operation using the right type.
else
Result_Type := Right_Type;
Rnode :=
Make_Op_Rem (Loc,
Left_Opnd => Build_Conversion (N, Right_Type, L),
Right_Opnd => R);
end if;
-- We now have an N_Op_Rem node built with Result_Type set. First
-- set Etype of result, as required for all Build_xxx routines
Set_Etype (Rnode, Base_Type (Result_Type));
-- One more check. We did the rem operation using the larger of the
-- two types, which is reasonable. However, in the case where the
-- two types have unequal sizes, it is impossible for the result of
-- a remainder operation to be larger than the smaller of the two
-- types, so we can put a conversion round the result to keep the
-- evolving operation size as small as possible.
if Esize (Left_Type) >= Esize (Right_Type) then
Rnode := Build_Conversion (N, Right_Type, Rnode);
elsif Esize (Right_Type) >= Esize (Left_Type) then
Rnode := Build_Conversion (N, Left_Type, Rnode);
end if;
return Rnode;
end Build_Rem;
-------------------------
-- Build_Scaled_Divide --
-------------------------
function Build_Scaled_Divide
(N : Node_Id;
X, Y, Z : Node_Id) return Node_Id
is
X_Size : constant Nat := UI_To_Int (Esize (Etype (X)));
Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y)));
Expr : Node_Id;
begin
-- If numerator fits in 64 bits, we can build the operations directly
-- without causing any intermediate overflow, so that's what we do.
if Nat'Max (X_Size, Y_Size) <= 32 then
return
Build_Divide (N, Build_Multiply (N, X, Y), Z);
-- Otherwise we use the runtime routine
-- [Qnn : Integer_64,
-- Rnn : Integer_64;
-- Scaled_Divide (X, Y, Z, Qnn, Rnn, Round);
-- Qnn]
else
declare
Loc : constant Source_Ptr := Sloc (N);
Qnn : Entity_Id;
Rnn : Entity_Id;
Code : List_Id;
pragma Warnings (Off, Rnn);
begin
Build_Scaled_Divide_Code (N, X, Y, Z, Qnn, Rnn, Code);
Insert_Actions (N, Code);
Expr := New_Occurrence_Of (Qnn, Loc);
-- Set type of result in case used elsewhere (see note at start)
Set_Etype (Expr, Etype (Qnn));
return Expr;
end;
end if;
end Build_Scaled_Divide;
------------------------------
-- Build_Scaled_Divide_Code --
------------------------------
-- If the numerator can be computed in 64-bits, we build
-- [Nnn : constant typ := typ (X) * typ (Y);
-- Dnn : constant typ := typ (Z)
-- Qnn : constant typ := Nnn / Dnn;
-- Rnn : constant typ := Nnn / Dnn;
-- If the numerator cannot be computed in 64 bits, we build
-- [Qnn : Interfaces.Integer_64;
-- Rnn : Interfaces.Integer_64;
-- Scaled_Divide (X, Y, Z, Qnn, Rnn, Round);]
procedure Build_Scaled_Divide_Code
(N : Node_Id;
X, Y, Z : Node_Id;
Qnn, Rnn : out Entity_Id;
Code : out List_Id)
is
Loc : constant Source_Ptr := Sloc (N);
X_Size : constant Nat := UI_To_Int (Esize (Etype (X)));
Y_Size : constant Nat := UI_To_Int (Esize (Etype (Y)));
Z_Size : constant Nat := UI_To_Int (Esize (Etype (Z)));
QR_Siz : Nat;
QR_Typ : Entity_Id;
Nnn : Entity_Id;
Dnn : Entity_Id;
Quo : Node_Id;
Rnd : Entity_Id;
begin
-- Find type that will allow computation of numerator
QR_Siz := Nat'Max (X_Size, 2 * Nat'Max (Y_Size, Z_Size));
if QR_Siz <= 16 then
QR_Typ := Standard_Integer_16;
elsif QR_Siz <= 32 then
QR_Typ := Standard_Integer_32;
elsif QR_Siz <= 64 then
QR_Typ := Standard_Integer_64;
-- For more than 64, bits, we use the 64-bit integer defined in
-- Interfaces, so that it can be handled by the runtime routine.
else
QR_Typ := RTE (RE_Integer_64);
end if;
-- Define quotient and remainder, and set their Etypes, so
-- that they can be picked up by Build_xxx routines.
Qnn := Make_Temporary (Loc, 'S');
Rnn := Make_Temporary (Loc, 'R');
Set_Etype (Qnn, QR_Typ);
Set_Etype (Rnn, QR_Typ);
-- Case that we can compute the numerator in 64 bits
if QR_Siz <= 64 then
Nnn := Make_Temporary (Loc, 'N');
Dnn := Make_Temporary (Loc, 'D');
-- Set Etypes, so that they can be picked up by New_Occurrence_Of
Set_Etype (Nnn, QR_Typ);
Set_Etype (Dnn, QR_Typ);
Code := New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Nnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression =>
Build_Multiply (N,
Build_Conversion (N, QR_Typ, X),
Build_Conversion (N, QR_Typ, Y))),
Make_Object_Declaration (Loc,
Defining_Identifier => Dnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression => Build_Conversion (N, QR_Typ, Z)));
Quo :=
Build_Divide (N,
New_Occurrence_Of (Nnn, Loc),
New_Occurrence_Of (Dnn, Loc));
Append_To (Code,
Make_Object_Declaration (Loc,
Defining_Identifier => Qnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression => Quo));
Append_To (Code,
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc),
Constant_Present => True,
Expression =>
Build_Rem (N,
New_Occurrence_Of (Nnn, Loc),
New_Occurrence_Of (Dnn, Loc))));
-- Case where numerator does not fit in 64 bits, so we have to
-- call the runtime routine to compute the quotient and remainder
else
Rnd := Boolean_Literals (Rounded_Result_Set (N));
Code := New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Qnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc)),
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition => New_Occurrence_Of (QR_Typ, Loc)),
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (RTE (RE_Scaled_Divide), Loc),
Parameter_Associations => New_List (
Build_Conversion (N, QR_Typ, X),
Build_Conversion (N, QR_Typ, Y),
Build_Conversion (N, QR_Typ, Z),
New_Occurrence_Of (Qnn, Loc),
New_Occurrence_Of (Rnn, Loc),
New_Occurrence_Of (Rnd, Loc))));
end if;
-- Set type of result, for use in caller
Set_Etype (Qnn, QR_Typ);
end Build_Scaled_Divide_Code;
---------------------------
-- Do_Divide_Fixed_Fixed --
---------------------------
-- We have:
-- (Result_Value * Result_Small) =
-- (Left_Value * Left_Small) / (Right_Value * Right_Small)
-- Result_Value = (Left_Value / Right_Value) *
-- (Left_Small / (Right_Small * Result_Small));
-- we can do the operation in integer arithmetic if this fraction is an
-- integer or the reciprocal of an integer, as detailed in (RM G.2.3(21)).
-- Otherwise the result is in the close result set and our approach is to
-- use floating-point to compute this close result.
procedure Do_Divide_Fixed_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Left_Type : constant Entity_Id := Etype (Left);
Right_Type : constant Entity_Id := Etype (Right);
Result_Type : constant Entity_Id := Etype (N);
Right_Small : constant Ureal := Small_Value (Right_Type);
Left_Small : constant Ureal := Small_Value (Left_Type);
Result_Small : Ureal;
Frac : Ureal;
Frac_Num : Uint;
Frac_Den : Uint;
Lit_Int : Node_Id;
begin
-- Rounding is required if the result is integral
if Is_Integer_Type (Result_Type) then
Set_Rounded_Result (N);
end if;
-- Get result small. If the result is an integer, treat it as though
-- it had a small of 1.0, all other processing is identical.
if Is_Integer_Type (Result_Type) then
Result_Small := Ureal_1;
else
Result_Small := Small_Value (Result_Type);
end if;
-- Get small ratio
Frac := Left_Small / (Right_Small * Result_Small);
Frac_Num := Norm_Num (Frac);
Frac_Den := Norm_Den (Frac);
-- If the fraction is an integer, then we get the result by multiplying
-- the left operand by the integer, and then dividing by the right
-- operand (the order is important, if we did the divide first, we
-- would lose precision).
if Frac_Den = 1 then
Lit_Int := Integer_Literal (N, Frac_Num); -- always positive
if Present (Lit_Int) then
Set_Result (N, Build_Scaled_Divide (N, Left, Lit_Int, Right));
return;
end if;
-- If the fraction is the reciprocal of an integer, then we get the
-- result by first multiplying the divisor by the integer, and then
-- doing the division with the adjusted divisor.
-- Note: this is much better than doing two divisions: multiplications
-- are much faster than divisions (and certainly faster than rounded
-- divisions), and we don't get inaccuracies from double rounding.
elsif Frac_Num = 1 then
Lit_Int := Integer_Literal (N, Frac_Den); -- always positive
if Present (Lit_Int) then
Set_Result (N, Build_Double_Divide (N, Left, Right, Lit_Int));
return;
end if;
end if;
-- If we fall through, we use floating-point to compute the result
Set_Result (N,
Build_Multiply (N,
Build_Divide (N, Fpt_Value (Left), Fpt_Value (Right)),
Real_Literal (N, Frac)));
end Do_Divide_Fixed_Fixed;
-------------------------------
-- Do_Divide_Fixed_Universal --
-------------------------------
-- We have:
-- (Result_Value * Result_Small) = (Left_Value * Left_Small) / Lit_Value;
-- Result_Value = Left_Value * Left_Small /(Lit_Value * Result_Small);
-- The result is required to be in the perfect result set if the literal
-- can be factored so that the resulting small ratio is an integer or the
-- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed
-- analysis of these RM requirements:
-- We must factor the literal, finding an integer K:
-- Lit_Value = K * Right_Small
-- Right_Small = Lit_Value / K
-- such that the small ratio:
-- Left_Small
-- ------------------------------
-- (Lit_Value / K) * Result_Small
-- Left_Small
-- = ------------------------ * K
-- Lit_Value * Result_Small
-- is an integer or the reciprocal of an integer, and for
-- implementation efficiency we need the smallest such K.
-- First we reduce the left fraction to lowest terms
-- If numerator = 1, then for K = 1, the small ratio is the reciprocal
-- of an integer, and this is clearly the minimum K case, so set K = 1,
-- Right_Small = Lit_Value.
-- If numerator > 1, then set K to the denominator of the fraction so
-- that the resulting small ratio is an integer (the numerator value).
procedure Do_Divide_Fixed_Universal (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Left_Type : constant Entity_Id := Etype (Left);
Result_Type : constant Entity_Id := Etype (N);
Left_Small : constant Ureal := Small_Value (Left_Type);
Lit_Value : constant Ureal := Realval (Right);
Result_Small : Ureal;
Frac : Ureal;
Frac_Num : Uint;
Frac_Den : Uint;
Lit_K : Node_Id;
Lit_Int : Node_Id;
begin
-- Get result small. If the result is an integer, treat it as though
-- it had a small of 1.0, all other processing is identical.
if Is_Integer_Type (Result_Type) then
Result_Small := Ureal_1;
else
Result_Small := Small_Value (Result_Type);
end if;
-- Determine if literal can be rewritten successfully
Frac := Left_Small / (Lit_Value * Result_Small);
Frac_Num := Norm_Num (Frac);
Frac_Den := Norm_Den (Frac);
-- Case where fraction is the reciprocal of an integer (K = 1, integer
-- = denominator). If this integer is not too large, this is the case
-- where the result can be obtained by dividing by this integer value.
if Frac_Num = 1 then
Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac));
if Present (Lit_Int) then
Set_Result (N, Build_Divide (N, Left, Lit_Int));
return;
end if;
-- Case where we choose K to make fraction an integer (K = denominator
-- of fraction, integer = numerator of fraction). If both K and the
-- numerator are small enough, this is the case where the result can
-- be obtained by first multiplying by the integer value and then
-- dividing by K (the order is important, if we divided first, we
-- would lose precision).
else
Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac));
Lit_K := Integer_Literal (N, Frac_Den, False);
if Present (Lit_Int) and then Present (Lit_K) then
Set_Result (N, Build_Scaled_Divide (N, Left, Lit_Int, Lit_K));
return;
end if;
end if;
-- Fall through if the literal cannot be successfully rewritten, or if
-- the small ratio is out of range of integer arithmetic. In the former
-- case it is fine to use floating-point to get the close result set,
-- and in the latter case, it means that the result is zero or raises
-- constraint error, and we can do that accurately in floating-point.
-- If we end up using floating-point, then we take the right integer
-- to be one, and its small to be the value of the original right real
-- literal. That way, we need only one floating-point multiplication.
Set_Result (N,
Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Frac)));
end Do_Divide_Fixed_Universal;
-------------------------------
-- Do_Divide_Universal_Fixed --
-------------------------------
-- We have:
-- (Result_Value * Result_Small) =
-- Lit_Value / (Right_Value * Right_Small)
-- Result_Value =
-- (Lit_Value / (Right_Small * Result_Small)) / Right_Value
-- The result is required to be in the perfect result set if the literal
-- can be factored so that the resulting small ratio is an integer or the
-- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed
-- analysis of these RM requirements:
-- We must factor the literal, finding an integer K:
-- Lit_Value = K * Left_Small
-- Left_Small = Lit_Value / K
-- such that the small ratio:
-- (Lit_Value / K)
-- --------------------------
-- Right_Small * Result_Small
-- Lit_Value 1
-- = -------------------------- * -
-- Right_Small * Result_Small K
-- is an integer or the reciprocal of an integer, and for
-- implementation efficiency we need the smallest such K.
-- First we reduce the left fraction to lowest terms
-- If denominator = 1, then for K = 1, the small ratio is an integer
-- (the numerator) and this is clearly the minimum K case, so set K = 1,
-- and Left_Small = Lit_Value.
-- If denominator > 1, then set K to the numerator of the fraction so
-- that the resulting small ratio is the reciprocal of an integer (the
-- numerator value).
procedure Do_Divide_Universal_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Right_Type : constant Entity_Id := Etype (Right);
Result_Type : constant Entity_Id := Etype (N);
Right_Small : constant Ureal := Small_Value (Right_Type);
Lit_Value : constant Ureal := Realval (Left);
Result_Small : Ureal;
Frac : Ureal;
Frac_Num : Uint;
Frac_Den : Uint;
Lit_K : Node_Id;
Lit_Int : Node_Id;
begin
-- Get result small. If the result is an integer, treat it as though
-- it had a small of 1.0, all other processing is identical.
if Is_Integer_Type (Result_Type) then
Result_Small := Ureal_1;
else
Result_Small := Small_Value (Result_Type);
end if;
-- Determine if literal can be rewritten successfully
Frac := Lit_Value / (Right_Small * Result_Small);
Frac_Num := Norm_Num (Frac);
Frac_Den := Norm_Den (Frac);
-- Case where fraction is an integer (K = 1, integer = numerator). If
-- this integer is not too large, this is the case where the result
-- can be obtained by dividing this integer by the right operand.
if Frac_Den = 1 then
Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac));
if Present (Lit_Int) then
Set_Result (N, Build_Divide (N, Lit_Int, Right));
return;
end if;
-- Case where we choose K to make the fraction the reciprocal of an
-- integer (K = numerator of fraction, integer = numerator of fraction).
-- If both K and the integer are small enough, this is the case where
-- the result can be obtained by multiplying the right operand by K
-- and then dividing by the integer value. The order of the operations
-- is important (if we divided first, we would lose precision).
else
Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac));
Lit_K := Integer_Literal (N, Frac_Num, False);
if Present (Lit_Int) and then Present (Lit_K) then
Set_Result (N, Build_Double_Divide (N, Lit_K, Right, Lit_Int));
return;
end if;
end if;
-- Fall through if the literal cannot be successfully rewritten, or if
-- the small ratio is out of range of integer arithmetic. In the former
-- case it is fine to use floating-point to get the close result set,
-- and in the latter case, it means that the result is zero or raises
-- constraint error, and we can do that accurately in floating-point.
-- If we end up using floating-point, then we take the right integer
-- to be one, and its small to be the value of the original right real
-- literal. That way, we need only one floating-point division.
Set_Result (N,
Build_Divide (N, Real_Literal (N, Frac), Fpt_Value (Right)));
end Do_Divide_Universal_Fixed;
-----------------------------
-- Do_Multiply_Fixed_Fixed --
-----------------------------
-- We have:
-- (Result_Value * Result_Small) =
-- (Left_Value * Left_Small) * (Right_Value * Right_Small)
-- Result_Value = (Left_Value * Right_Value) *
-- (Left_Small * Right_Small) / Result_Small;
-- we can do the operation in integer arithmetic if this fraction is an
-- integer or the reciprocal of an integer, as detailed in (RM G.2.3(21)).
-- Otherwise the result is in the close result set and our approach is to
-- use floating-point to compute this close result.
procedure Do_Multiply_Fixed_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Left_Type : constant Entity_Id := Etype (Left);
Right_Type : constant Entity_Id := Etype (Right);
Result_Type : constant Entity_Id := Etype (N);
Right_Small : constant Ureal := Small_Value (Right_Type);
Left_Small : constant Ureal := Small_Value (Left_Type);
Result_Small : Ureal;
Frac : Ureal;
Frac_Num : Uint;
Frac_Den : Uint;
Lit_Int : Node_Id;
begin
-- Get result small. If the result is an integer, treat it as though
-- it had a small of 1.0, all other processing is identical.
if Is_Integer_Type (Result_Type) then
Result_Small := Ureal_1;
else
Result_Small := Small_Value (Result_Type);
end if;
-- Get small ratio
Frac := (Left_Small * Right_Small) / Result_Small;
Frac_Num := Norm_Num (Frac);
Frac_Den := Norm_Den (Frac);
-- If the fraction is an integer, then we get the result by multiplying
-- the operands, and then multiplying the result by the integer value.
if Frac_Den = 1 then
Lit_Int := Integer_Literal (N, Frac_Num); -- always positive
if Present (Lit_Int) then
Set_Result (N,
Build_Multiply (N, Build_Multiply (N, Left, Right),
Lit_Int));
return;
end if;
-- If the fraction is the reciprocal of an integer, then we get the
-- result by multiplying the operands, and then dividing the result by
-- the integer value. The order of the operations is important, if we
-- divided first, we would lose precision.
elsif Frac_Num = 1 then
Lit_Int := Integer_Literal (N, Frac_Den); -- always positive
if Present (Lit_Int) then
Set_Result (N, Build_Scaled_Divide (N, Left, Right, Lit_Int));
return;
end if;
end if;
-- If we fall through, we use floating-point to compute the result
Set_Result (N,
Build_Multiply (N,
Build_Multiply (N, Fpt_Value (Left), Fpt_Value (Right)),
Real_Literal (N, Frac)));
end Do_Multiply_Fixed_Fixed;
---------------------------------
-- Do_Multiply_Fixed_Universal --
---------------------------------
-- We have:
-- (Result_Value * Result_Small) = (Left_Value * Left_Small) * Lit_Value;
-- Result_Value = Left_Value * (Left_Small * Lit_Value) / Result_Small;
-- The result is required to be in the perfect result set if the literal
-- can be factored so that the resulting small ratio is an integer or the
-- reciprocal of an integer (RM G.2.3(21-22)). We now give a detailed
-- analysis of these RM requirements:
-- We must factor the literal, finding an integer K:
-- Lit_Value = K * Right_Small
-- Right_Small = Lit_Value / K
-- such that the small ratio:
-- Left_Small * (Lit_Value / K)
-- ----------------------------
-- Result_Small
-- Left_Small * Lit_Value 1
-- = ---------------------- * -
-- Result_Small K
-- is an integer or the reciprocal of an integer, and for
-- implementation efficiency we need the smallest such K.
-- First we reduce the left fraction to lowest terms
-- If denominator = 1, then for K = 1, the small ratio is an integer, and
-- this is clearly the minimum K case, so set
-- K = 1, Right_Small = Lit_Value
-- If denominator > 1, then set K to the numerator of the fraction, so
-- that the resulting small ratio is the reciprocal of the integer (the
-- denominator value).
procedure Do_Multiply_Fixed_Universal
(N : Node_Id;
Left, Right : Node_Id)
is
Left_Type : constant Entity_Id := Etype (Left);
Result_Type : constant Entity_Id := Etype (N);
Left_Small : constant Ureal := Small_Value (Left_Type);
Lit_Value : constant Ureal := Realval (Right);
Result_Small : Ureal;
Frac : Ureal;
Frac_Num : Uint;
Frac_Den : Uint;
Lit_K : Node_Id;
Lit_Int : Node_Id;
begin
-- Get result small. If the result is an integer, treat it as though
-- it had a small of 1.0, all other processing is identical.
if Is_Integer_Type (Result_Type) then
Result_Small := Ureal_1;
else
Result_Small := Small_Value (Result_Type);
end if;
-- Determine if literal can be rewritten successfully
Frac := (Left_Small * Lit_Value) / Result_Small;
Frac_Num := Norm_Num (Frac);
Frac_Den := Norm_Den (Frac);
-- Case where fraction is an integer (K = 1, integer = numerator). If
-- this integer is not too large, this is the case where the result can
-- be obtained by multiplying by this integer value.
if Frac_Den = 1 then
Lit_Int := Integer_Literal (N, Frac_Num, UR_Is_Negative (Frac));
if Present (Lit_Int) then
Set_Result (N, Build_Multiply (N, Left, Lit_Int));
return;
end if;
-- Case where we choose K to make fraction the reciprocal of an integer
-- (K = numerator of fraction, integer = denominator of fraction). If
-- both K and the denominator are small enough, this is the case where
-- the result can be obtained by first multiplying by K, and then
-- dividing by the integer value.
else
Lit_Int := Integer_Literal (N, Frac_Den, UR_Is_Negative (Frac));
Lit_K := Integer_Literal (N, Frac_Num);
if Present (Lit_Int) and then Present (Lit_K) then
Set_Result (N, Build_Scaled_Divide (N, Left, Lit_K, Lit_Int));
return;
end if;
end if;
-- Fall through if the literal cannot be successfully rewritten, or if
-- the small ratio is out of range of integer arithmetic. In the former
-- case it is fine to use floating-point to get the close result set,
-- and in the latter case, it means that the result is zero or raises
-- constraint error, and we can do that accurately in floating-point.
-- If we end up using floating-point, then we take the right integer
-- to be one, and its small to be the value of the original right real
-- literal. That way, we need only one floating-point multiplication.
Set_Result (N,
Build_Multiply (N, Fpt_Value (Left), Real_Literal (N, Frac)));
end Do_Multiply_Fixed_Universal;
---------------------------------
-- Expand_Convert_Fixed_Static --
---------------------------------
procedure Expand_Convert_Fixed_Static (N : Node_Id) is
begin
Rewrite (N,
Convert_To (Etype (N),
Make_Real_Literal (Sloc (N), Expr_Value_R (Expression (N)))));
Analyze_And_Resolve (N);
end Expand_Convert_Fixed_Static;
-----------------------------------
-- Expand_Convert_Fixed_To_Fixed --
-----------------------------------
-- We have:
-- Result_Value * Result_Small = Source_Value * Source_Small
-- Result_Value = Source_Value * (Source_Small / Result_Small)
-- If the small ratio (Source_Small / Result_Small) is a sufficiently small
-- integer, then the perfect result set is obtained by a single integer
-- multiplication.
-- If the small ratio is the reciprocal of a sufficiently small integer,
-- then the perfect result set is obtained by a single integer division.
-- In other cases, we obtain the close result set by calculating the
-- result in floating-point.
procedure Expand_Convert_Fixed_To_Fixed (N : Node_Id) is
Rng_Check : constant Boolean := Do_Range_Check (N);
Expr : constant Node_Id := Expression (N);
Result_Type : constant Entity_Id := Etype (N);
Source_Type : constant Entity_Id := Etype (Expr);
Small_Ratio : Ureal;
Ratio_Num : Uint;
Ratio_Den : Uint;
Lit : Node_Id;
begin
if Is_OK_Static_Expression (Expr) then
Expand_Convert_Fixed_Static (N);
return;
end if;
Small_Ratio := Small_Value (Source_Type) / Small_Value (Result_Type);
Ratio_Num := Norm_Num (Small_Ratio);
Ratio_Den := Norm_Den (Small_Ratio);
if Ratio_Den = 1 then
if Ratio_Num = 1 then
Set_Result (N, Expr);
return;
else
Lit := Integer_Literal (N, Ratio_Num);
if Present (Lit) then
Set_Result (N, Build_Multiply (N, Expr, Lit));
return;
end if;
end if;
elsif Ratio_Num = 1 then
Lit := Integer_Literal (N, Ratio_Den);
if Present (Lit) then
Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check);
return;
end if;
end if;
-- Fall through to use floating-point for the close result set case
-- either as a result of the small ratio not being an integer or the
-- reciprocal of an integer, or if the integer is out of range.
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Expr),
Real_Literal (N, Small_Ratio)),
Rng_Check);
end Expand_Convert_Fixed_To_Fixed;
-----------------------------------
-- Expand_Convert_Fixed_To_Float --
-----------------------------------
-- If the small of the fixed type is 1.0, then we simply convert the
-- integer value directly to the target floating-point type, otherwise
-- we first have to multiply by the small, in Universal_Real, and then
-- convert the result to the target floating-point type.
procedure Expand_Convert_Fixed_To_Float (N : Node_Id) is
Rng_Check : constant Boolean := Do_Range_Check (N);
Expr : constant Node_Id := Expression (N);
Source_Type : constant Entity_Id := Etype (Expr);
Small : constant Ureal := Small_Value (Source_Type);
begin
if Is_OK_Static_Expression (Expr) then
Expand_Convert_Fixed_Static (N);
return;
end if;
if Small = Ureal_1 then
Set_Result (N, Expr);
else
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Expr),
Real_Literal (N, Small)),
Rng_Check);
end if;
end Expand_Convert_Fixed_To_Float;
-------------------------------------
-- Expand_Convert_Fixed_To_Integer --
-------------------------------------
-- We have:
-- Result_Value = Source_Value * Source_Small
-- If the small value is a sufficiently small integer, then the perfect
-- result set is obtained by a single integer multiplication.
-- If the small value is the reciprocal of a sufficiently small integer,
-- then the perfect result set is obtained by a single integer division.
-- In other cases, we obtain the close result set by calculating the
-- result in floating-point.
procedure Expand_Convert_Fixed_To_Integer (N : Node_Id) is
Rng_Check : constant Boolean := Do_Range_Check (N);
Expr : constant Node_Id := Expression (N);
Source_Type : constant Entity_Id := Etype (Expr);
Small : constant Ureal := Small_Value (Source_Type);
Small_Num : constant Uint := Norm_Num (Small);
Small_Den : constant Uint := Norm_Den (Small);
Lit : Node_Id;
begin
if Is_OK_Static_Expression (Expr) then
Expand_Convert_Fixed_Static (N);
return;
end if;
if Small_Den = 1 then
Lit := Integer_Literal (N, Small_Num);
if Present (Lit) then
Set_Result (N, Build_Multiply (N, Expr, Lit), Rng_Check);
return;
end if;
elsif Small_Num = 1 then
Lit := Integer_Literal (N, Small_Den);
if Present (Lit) then
Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check);
return;
end if;
end if;
-- Fall through to use floating-point for the close result set case
-- either as a result of the small value not being an integer or the
-- reciprocal of an integer, or if the integer is out of range.
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Expr),
Real_Literal (N, Small)),
Rng_Check);
end Expand_Convert_Fixed_To_Integer;
-----------------------------------
-- Expand_Convert_Float_To_Fixed --
-----------------------------------
-- We have
-- Result_Value * Result_Small = Operand_Value
-- so compute:
-- Result_Value = Operand_Value * (1.0 / Result_Small)
-- We do the small scaling in floating-point, and we do a multiplication
-- rather than a division, since it is accurate enough for the perfect
-- result cases, and faster.
procedure Expand_Convert_Float_To_Fixed (N : Node_Id) is
Expr : constant Node_Id := Expression (N);
Orig_N : constant Node_Id := Original_Node (N);
Result_Type : constant Entity_Id := Etype (N);
Rng_Check : constant Boolean := Do_Range_Check (N);
Small : constant Ureal := Small_Value (Result_Type);
Truncate : Boolean;
begin
-- Optimize small = 1, where we can avoid the multiply completely
if Small = Ureal_1 then
Set_Result (N, Expr, Rng_Check, Trunc => True);
-- Normal case where multiply is required. Rounding is truncating
-- for decimal fixed point types only, see RM 4.6(29), except if the
-- conversion comes from an attribute reference 'Round (RM 3.5.10 (14)):
-- The attribute is implemented by means of a conversion that must
-- round.
else
if Is_Decimal_Fixed_Point_Type (Result_Type) then
Truncate :=
Nkind (Orig_N) /= N_Attribute_Reference
or else Get_Attribute_Id
(Attribute_Name (Orig_N)) /= Attribute_Round;
else
Truncate := False;
end if;
Set_Result
(N => N,
Expr =>
Build_Multiply
(N => N,
L => Fpt_Value (Expr),
R => Real_Literal (N, Ureal_1 / Small)),
Rchk => Rng_Check,
Trunc => Truncate);
end if;
end Expand_Convert_Float_To_Fixed;
-------------------------------------
-- Expand_Convert_Integer_To_Fixed --
-------------------------------------
-- We have
-- Result_Value * Result_Small = Operand_Value
-- Result_Value = Operand_Value / Result_Small
-- If the small value is a sufficiently small integer, then the perfect
-- result set is obtained by a single integer division.
-- If the small value is the reciprocal of a sufficiently small integer,
-- the perfect result set is obtained by a single integer multiplication.
-- In other cases, we obtain the close result set by calculating the
-- result in floating-point using a multiplication by the reciprocal
-- of the Result_Small.
procedure Expand_Convert_Integer_To_Fixed (N : Node_Id) is
Rng_Check : constant Boolean := Do_Range_Check (N);
Expr : constant Node_Id := Expression (N);
Result_Type : constant Entity_Id := Etype (N);
Small : constant Ureal := Small_Value (Result_Type);
Small_Num : constant Uint := Norm_Num (Small);
Small_Den : constant Uint := Norm_Den (Small);
Lit : Node_Id;
begin
if Small_Den = 1 then
Lit := Integer_Literal (N, Small_Num);
if Present (Lit) then
Set_Result (N, Build_Divide (N, Expr, Lit), Rng_Check);
return;
end if;
elsif Small_Num = 1 then
Lit := Integer_Literal (N, Small_Den);
if Present (Lit) then
Set_Result (N, Build_Multiply (N, Expr, Lit), Rng_Check);
return;
end if;
end if;
-- Fall through to use floating-point for the close result set case
-- either as a result of the small value not being an integer or the
-- reciprocal of an integer, or if the integer is out of range.
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Expr),
Real_Literal (N, Ureal_1 / Small)),
Rng_Check);
end Expand_Convert_Integer_To_Fixed;
--------------------------------
-- Expand_Decimal_Divide_Call --
--------------------------------
-- We have four operands
-- Dividend
-- Divisor
-- Quotient
-- Remainder
-- All of which are decimal types, and which thus have associated
-- decimal scales.
-- Computing the quotient is a similar problem to that faced by the
-- normal fixed-point division, except that it is simpler, because
-- we always have compatible smalls.
-- Quotient = (Dividend / Divisor) * 10**q
-- where 10 ** q = Dividend'Small / (Divisor'Small * Quotient'Small)
-- so q = Divisor'Scale + Quotient'Scale - Dividend'Scale
-- For q >= 0, we compute
-- Numerator := Dividend * 10 ** q
-- Denominator := Divisor
-- Quotient := Numerator / Denominator
-- For q < 0, we compute
-- Numerator := Dividend
-- Denominator := Divisor * 10 ** q
-- Quotient := Numerator / Denominator
-- Both these divisions are done in truncated mode, and the remainder
-- from these divisions is used to compute the result Remainder. This
-- remainder has the effective scale of the numerator of the division,
-- For q >= 0, the remainder scale is Dividend'Scale + q
-- For q < 0, the remainder scale is Dividend'Scale
-- The result Remainder is then computed by a normal truncating decimal
-- conversion from this scale to the scale of the remainder, i.e. by a
-- division or multiplication by the appropriate power of 10.
procedure Expand_Decimal_Divide_Call (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Dividend : Node_Id := First_Actual (N);
Divisor : Node_Id := Next_Actual (Dividend);
Quotient : Node_Id := Next_Actual (Divisor);
Remainder : Node_Id := Next_Actual (Quotient);
Dividend_Type : constant Entity_Id := Etype (Dividend);
Divisor_Type : constant Entity_Id := Etype (Divisor);
Quotient_Type : constant Entity_Id := Etype (Quotient);
Remainder_Type : constant Entity_Id := Etype (Remainder);
Dividend_Scale : constant Uint := Scale_Value (Dividend_Type);
Divisor_Scale : constant Uint := Scale_Value (Divisor_Type);
Quotient_Scale : constant Uint := Scale_Value (Quotient_Type);
Remainder_Scale : constant Uint := Scale_Value (Remainder_Type);
Q : Uint;
Numerator_Scale : Uint;
Stmts : List_Id;
Qnn : Entity_Id;
Rnn : Entity_Id;
Computed_Remainder : Node_Id;
Adjusted_Remainder : Node_Id;
Scale_Adjust : Uint;
begin
-- Relocate the operands, since they are now list elements, and we
-- need to reference them separately as operands in the expanded code.
Dividend := Relocate_Node (Dividend);
Divisor := Relocate_Node (Divisor);
Quotient := Relocate_Node (Quotient);
Remainder := Relocate_Node (Remainder);
-- Now compute Q, the adjustment scale
Q := Divisor_Scale + Quotient_Scale - Dividend_Scale;
-- If Q is non-negative then we need a scaled divide
if Q >= 0 then
Build_Scaled_Divide_Code
(N,
Dividend,
Integer_Literal (N, Uint_10 ** Q),
Divisor,
Qnn, Rnn, Stmts);
Numerator_Scale := Dividend_Scale + Q;
-- If Q is negative, then we need a double divide
else
Build_Double_Divide_Code
(N,
Dividend,
Divisor,
Integer_Literal (N, Uint_10 ** (-Q)),
Qnn, Rnn, Stmts);
Numerator_Scale := Dividend_Scale;
end if;
-- Add statement to set quotient value
-- Quotient := quotient-type!(Qnn);
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Quotient,
Expression =>
Unchecked_Convert_To (Quotient_Type,
Build_Conversion (N, Quotient_Type,
New_Occurrence_Of (Qnn, Loc)))));
-- Now we need to deal with computing and setting the remainder. The
-- scale of the remainder is in Numerator_Scale, and the desired
-- scale is the scale of the given Remainder argument. There are
-- three cases:
-- Numerator_Scale > Remainder_Scale
-- in this case, there are extra digits in the computed remainder
-- which must be eliminated by an extra division:
-- computed-remainder := Numerator rem Denominator
-- scale_adjust = Numerator_Scale - Remainder_Scale
-- adjusted-remainder := computed-remainder / 10 ** scale_adjust
-- Numerator_Scale = Remainder_Scale
-- in this case, the we have the remainder we need
-- computed-remainder := Numerator rem Denominator
-- adjusted-remainder := computed-remainder
-- Numerator_Scale < Remainder_Scale
-- in this case, we have insufficient digits in the computed
-- remainder, which must be eliminated by an extra multiply
-- computed-remainder := Numerator rem Denominator
-- scale_adjust = Remainder_Scale - Numerator_Scale
-- adjusted-remainder := computed-remainder * 10 ** scale_adjust
-- Finally we assign the adjusted-remainder to the result Remainder
-- with conversions to get the proper fixed-point type representation.
Computed_Remainder := New_Occurrence_Of (Rnn, Loc);
if Numerator_Scale > Remainder_Scale then
Scale_Adjust := Numerator_Scale - Remainder_Scale;
Adjusted_Remainder :=
Build_Divide
(N, Computed_Remainder, Integer_Literal (N, 10 ** Scale_Adjust));
elsif Numerator_Scale = Remainder_Scale then
Adjusted_Remainder := Computed_Remainder;
else -- Numerator_Scale < Remainder_Scale
Scale_Adjust := Remainder_Scale - Numerator_Scale;
Adjusted_Remainder :=
Build_Multiply
(N, Computed_Remainder, Integer_Literal (N, 10 ** Scale_Adjust));
end if;
-- Assignment of remainder result
Append_To (Stmts,
Make_Assignment_Statement (Loc,
Name => Remainder,
Expression =>
Unchecked_Convert_To (Remainder_Type, Adjusted_Remainder)));
-- Final step is to rewrite the call with a block containing the
-- above sequence of constructed statements for the divide operation.
Rewrite (N,
Make_Block_Statement (Loc,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Stmts)));
Analyze (N);
end Expand_Decimal_Divide_Call;
-----------------------------------------------
-- Expand_Divide_Fixed_By_Fixed_Giving_Fixed --
-----------------------------------------------
procedure Expand_Divide_Fixed_By_Fixed_Giving_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
begin
-- Suppress expansion of a fixed-by-fixed division if the
-- operation is supported directly by the target.
if Target_Has_Fixed_Ops (Etype (Left), Etype (Right), Etype (N)) then
return;
end if;
if Etype (Left) = Universal_Real then
Do_Divide_Universal_Fixed (N);
elsif Etype (Right) = Universal_Real then
Do_Divide_Fixed_Universal (N);
else
Do_Divide_Fixed_Fixed (N);
-- A focused optimization: if after constant folding the
-- expression is of the form: T ((Exp * D) / D), where D is
-- a static constant, return T (Exp). This form will show up
-- when D is the denominator of the static expression for the
-- 'small of fixed-point types involved. This transformation
-- removes a division that may be expensive on some targets.
if Nkind (N) = N_Type_Conversion
and then Nkind (Expression (N)) = N_Op_Divide
then
declare
Num : constant Node_Id := Left_Opnd (Expression (N));
Den : constant Node_Id := Right_Opnd (Expression (N));
begin
if Nkind (Den) = N_Integer_Literal
and then Nkind (Num) = N_Op_Multiply
and then Nkind (Right_Opnd (Num)) = N_Integer_Literal
and then Intval (Den) = Intval (Right_Opnd (Num))
then
Rewrite (Expression (N), Left_Opnd (Num));
end if;
end;
end if;
end if;
end Expand_Divide_Fixed_By_Fixed_Giving_Fixed;
-----------------------------------------------
-- Expand_Divide_Fixed_By_Fixed_Giving_Float --
-----------------------------------------------
-- The division is done in Universal_Real, and the result is multiplied
-- by the small ratio, which is Small (Right) / Small (Left). Special
-- treatment is required for universal operands, which represent their
-- own value and do not require conversion.
procedure Expand_Divide_Fixed_By_Fixed_Giving_Float (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Left_Type : constant Entity_Id := Etype (Left);
Right_Type : constant Entity_Id := Etype (Right);
begin
-- Case of left operand is universal real, the result we want is:
-- Left_Value / (Right_Value * Right_Small)
-- so we compute this as:
-- (Left_Value / Right_Small) / Right_Value
if Left_Type = Universal_Real then
Set_Result (N,
Build_Divide (N,
Real_Literal (N, Realval (Left) / Small_Value (Right_Type)),
Fpt_Value (Right)));
-- Case of right operand is universal real, the result we want is
-- (Left_Value * Left_Small) / Right_Value
-- so we compute this as:
-- Left_Value * (Left_Small / Right_Value)
-- Note we invert to a multiplication since usually floating-point
-- multiplication is much faster than floating-point division.
elsif Right_Type = Universal_Real then
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Left),
Real_Literal (N, Small_Value (Left_Type) / Realval (Right))));
-- Both operands are fixed, so the value we want is
-- (Left_Value * Left_Small) / (Right_Value * Right_Small)
-- which we compute as:
-- (Left_Value / Right_Value) * (Left_Small / Right_Small)
else
Set_Result (N,
Build_Multiply (N,
Build_Divide (N, Fpt_Value (Left), Fpt_Value (Right)),
Real_Literal (N,
Small_Value (Left_Type) / Small_Value (Right_Type))));
end if;
end Expand_Divide_Fixed_By_Fixed_Giving_Float;
-------------------------------------------------
-- Expand_Divide_Fixed_By_Fixed_Giving_Integer --
-------------------------------------------------
procedure Expand_Divide_Fixed_By_Fixed_Giving_Integer (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
begin
if Etype (Left) = Universal_Real then
Do_Divide_Universal_Fixed (N);
elsif Etype (Right) = Universal_Real then
Do_Divide_Fixed_Universal (N);
else
Do_Divide_Fixed_Fixed (N);
end if;
end Expand_Divide_Fixed_By_Fixed_Giving_Integer;
-------------------------------------------------
-- Expand_Divide_Fixed_By_Integer_Giving_Fixed --
-------------------------------------------------
-- Since the operand and result fixed-point type is the same, this is
-- a straight divide by the right operand, the small can be ignored.
procedure Expand_Divide_Fixed_By_Integer_Giving_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
begin
Set_Result (N, Build_Divide (N, Left, Right));
end Expand_Divide_Fixed_By_Integer_Giving_Fixed;
-------------------------------------------------
-- Expand_Multiply_Fixed_By_Fixed_Giving_Fixed --
-------------------------------------------------
procedure Expand_Multiply_Fixed_By_Fixed_Giving_Fixed (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
procedure Rewrite_Non_Static_Universal (Opnd : Node_Id);
-- The operand may be a non-static universal value, such an
-- exponentiation with a non-static exponent. In that case, treat
-- as a fixed * fixed multiplication, and convert the argument to
-- the target fixed type.
----------------------------------
-- Rewrite_Non_Static_Universal --
----------------------------------
procedure Rewrite_Non_Static_Universal (Opnd : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
begin
Rewrite (Opnd,
Make_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Etype (N), Loc),
Expression => Expression (Opnd)));
Analyze_And_Resolve (Opnd, Etype (N));
end Rewrite_Non_Static_Universal;
-- Start of processing for Expand_Multiply_Fixed_By_Fixed_Giving_Fixed
begin
-- Suppress expansion of a fixed-by-fixed multiplication if the
-- operation is supported directly by the target.
if Target_Has_Fixed_Ops (Etype (Left), Etype (Right), Etype (N)) then
return;
end if;
if Etype (Left) = Universal_Real then
if Nkind (Left) = N_Real_Literal then
Do_Multiply_Fixed_Universal (N, Left => Right, Right => Left);
elsif Nkind (Left) = N_Type_Conversion then
Rewrite_Non_Static_Universal (Left);
Do_Multiply_Fixed_Fixed (N);
end if;
elsif Etype (Right) = Universal_Real then
if Nkind (Right) = N_Real_Literal then
Do_Multiply_Fixed_Universal (N, Left, Right);
elsif Nkind (Right) = N_Type_Conversion then
Rewrite_Non_Static_Universal (Right);
Do_Multiply_Fixed_Fixed (N);
end if;
else
Do_Multiply_Fixed_Fixed (N);
end if;
end Expand_Multiply_Fixed_By_Fixed_Giving_Fixed;
-------------------------------------------------
-- Expand_Multiply_Fixed_By_Fixed_Giving_Float --
-------------------------------------------------
-- The multiply is done in Universal_Real, and the result is multiplied
-- by the adjustment for the smalls which is Small (Right) * Small (Left).
-- Special treatment is required for universal operands.
procedure Expand_Multiply_Fixed_By_Fixed_Giving_Float (N : Node_Id) is
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
Left_Type : constant Entity_Id := Etype (Left);
Right_Type : constant Entity_Id := Etype (Right);
begin
-- Case of left operand is universal real, the result we want is
-- Left_Value * (Right_Value * Right_Small)
-- so we compute this as:
-- (Left_Value * Right_Small) * Right_Value;
if Left_Type = Universal_Real then
Set_Result (N,
Build_Multiply (N,
Real_Literal (N, Realval (Left) * Small_Value (Right_Type)),
Fpt_Value (Right)));
-- Case of right operand is universal real, the result we want is
-- (Left_Value * Left_Small) * Right_Value
-- so we compute this as:
-- Left_Value * (Left_Small * Right_Value)
elsif Right_Type = Universal_Real then
Set_Result (N,
Build_Multiply (N,
Fpt_Value (Left),
Real_Literal (N, Small_Value (Left_Type) * Realval (Right))));
-- Both operands are fixed, so the value we want is
-- (Left_Value * Left_Small) * (Right_Value * Right_Small)
-- which we compute as:
-- (Left_Value * Right_Value) * (Right_Small * Left_Small)
else
Set_Result (N,
Build_Multiply (N,
Build_Multiply (N, Fpt_Value (Left), Fpt_Value (Right)),
Real_Literal (N,
Small_Value (Right_Type) * Small_Value (Left_Type))));
end if;
end Expand_Multiply_Fixed_By_Fixed_Giving_Float;
---------------------------------------------------
-- Expand_Multiply_Fixed_By_Fixed_Giving_Integer --
---------------------------------------------------
procedure Expand_Multiply_Fixed_By_Fixed_Giving_Integer (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
begin
if Etype (Left) = Universal_Real then
Do_Multiply_Fixed_Universal (N, Left => Right, Right => Left);
elsif Etype (Right) = Universal_Real then
Do_Multiply_Fixed_Universal (N, Left, Right);
-- If both types are equal and we need to avoid floating point
-- instructions, it's worth introducing a temporary with the
-- common type, because it may be evaluated more simply without
-- the need for run-time use of floating point.
elsif Etype (Right) = Etype (Left)
and then Restriction_Active (No_Floating_Point)
then
declare
Temp : constant Entity_Id := Make_Temporary (Loc, 'F');
Mult : constant Node_Id := Make_Op_Multiply (Loc, Left, Right);
Decl : constant Node_Id :=
Make_Object_Declaration (Loc,
Defining_Identifier => Temp,
Object_Definition => New_Occurrence_Of (Etype (Right), Loc),
Expression => Mult);
begin
Insert_Action (N, Decl);
Rewrite (N,
OK_Convert_To (Etype (N), New_Occurrence_Of (Temp, Loc)));
Analyze_And_Resolve (N, Standard_Integer);
end;
else
Do_Multiply_Fixed_Fixed (N);
end if;
end Expand_Multiply_Fixed_By_Fixed_Giving_Integer;
---------------------------------------------------
-- Expand_Multiply_Fixed_By_Integer_Giving_Fixed --
---------------------------------------------------
-- Since the operand and result fixed-point type is the same, this is
-- a straight multiply by the right operand, the small can be ignored.
procedure Expand_Multiply_Fixed_By_Integer_Giving_Fixed (N : Node_Id) is
begin
Set_Result (N,
Build_Multiply (N, Left_Opnd (N), Right_Opnd (N)));
end Expand_Multiply_Fixed_By_Integer_Giving_Fixed;
---------------------------------------------------
-- Expand_Multiply_Integer_By_Fixed_Giving_Fixed --
---------------------------------------------------
-- Since the operand and result fixed-point type is the same, this is
-- a straight multiply by the right operand, the small can be ignored.
procedure Expand_Multiply_Integer_By_Fixed_Giving_Fixed (N : Node_Id) is
begin
Set_Result (N,
Build_Multiply (N, Left_Opnd (N), Right_Opnd (N)));
end Expand_Multiply_Integer_By_Fixed_Giving_Fixed;
---------------
-- Fpt_Value --
---------------
function Fpt_Value (N : Node_Id) return Node_Id is
Typ : constant Entity_Id := Etype (N);
begin
if Is_Integer_Type (Typ)
or else Is_Floating_Point_Type (Typ)
then
return Build_Conversion (N, Universal_Real, N);
-- Fixed-point case, must get integer value first
else
return Build_Conversion (N, Universal_Real, N);
end if;
end Fpt_Value;
---------------------
-- Integer_Literal --
---------------------
function Integer_Literal
(N : Node_Id;
V : Uint;
Negative : Boolean := False) return Node_Id
is
T : Entity_Id;
L : Node_Id;
begin
if V < Uint_2 ** 7 then
T := Standard_Integer_8;
elsif V < Uint_2 ** 15 then
T := Standard_Integer_16;
elsif V < Uint_2 ** 31 then
T := Standard_Integer_32;
elsif V < Uint_2 ** 63 then
T := Standard_Integer_64;
else
return Empty;
end if;
if Negative then
L := Make_Integer_Literal (Sloc (N), UI_Negate (V));
else
L := Make_Integer_Literal (Sloc (N), V);
end if;
-- Set type of result in case used elsewhere (see note at start)
Set_Etype (L, T);
Set_Is_Static_Expression (L);
-- We really need to set Analyzed here because we may be creating a
-- very strange beast, namely an integer literal typed as fixed-point
-- and the analyzer won't like that.
Set_Analyzed (L);
return L;
end Integer_Literal;
------------------
-- Real_Literal --
------------------
function Real_Literal (N : Node_Id; V : Ureal) return Node_Id is
L : Node_Id;
begin
L := Make_Real_Literal (Sloc (N), V);
-- Set type of result in case used elsewhere (see note at start)
Set_Etype (L, Universal_Real);
return L;
end Real_Literal;
------------------------
-- Rounded_Result_Set --
------------------------
function Rounded_Result_Set (N : Node_Id) return Boolean is
K : constant Node_Kind := Nkind (N);
begin
if (K = N_Type_Conversion or else
K = N_Op_Divide or else
K = N_Op_Multiply)
and then
(Rounded_Result (N) or else Is_Integer_Type (Etype (N)))
then
return True;
else
return False;
end if;
end Rounded_Result_Set;
----------------
-- Set_Result --
----------------
procedure Set_Result
(N : Node_Id;
Expr : Node_Id;
Rchk : Boolean := False;
Trunc : Boolean := False)
is
Cnode : Node_Id;
Expr_Type : constant Entity_Id := Etype (Expr);
Result_Type : constant Entity_Id := Etype (N);
begin
-- No conversion required if types match and no range check or truncate
if Result_Type = Expr_Type and then not (Rchk or Trunc) then
Cnode := Expr;
-- Else perform required conversion
else
Cnode := Build_Conversion (N, Result_Type, Expr, Rchk, Trunc);
end if;
Rewrite (N, Cnode);
Analyze_And_Resolve (N, Result_Type);
end Set_Result;
end Exp_Fixd;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Containers.Ordered_Maps;
with League.Characters;
with Matreshka.Internals.URI_Utilities;
with XML.SAX.Input_Sources.Streams.Files;
package body SAX_Events_Writers is
use Ada.Characters.Wide_Wide_Latin_1;
use League.Strings;
package Universal_String_Integer_Maps is
new Ada.Containers.Ordered_Maps
(League.Strings.Universal_String, Positive);
function Escape_Character
(Item : League.Characters.Universal_Character)
return League.Strings.Universal_String;
-- Escapes control and special characters.
function Escape_String
(Item : League.Strings.Universal_String)
return League.Strings.Universal_String;
-- Escapes control and special character.
--------------
-- Add_Line --
--------------
not overriding procedure Add_Line
(Self : in out SAX_Events_Writer;
Item : League.Strings.Universal_String) is
begin
Self.Result.Append (Item & Ada.Characters.Wide_Wide_Latin_1.LF);
end Add_Line;
----------------
-- Characters --
----------------
overriding procedure Characters
(Self : in out SAX_Events_Writer;
Text : League.Strings.Universal_String;
Success : in out Boolean) is
begin
for J in 1 .. Text.Length loop
Self.Add_Line
(" <characters>"
& Escape_Character (Text.Element (J))
& "</characters>");
end loop;
end Characters;
----------
-- Done --
----------
procedure Done (Self : in out SAX_Events_Writer) is
begin
Self.Add_Line (To_Universal_String ("</SAXEvents>"));
end Done;
---------------
-- End_CDATA --
---------------
overriding procedure End_CDATA
(Self : in out SAX_Events_Writer;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <endCDATA/>"));
end End_CDATA;
------------------
-- End_Document --
------------------
overriding procedure End_Document
(Self : in out SAX_Events_Writer;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <endDocument/>"));
end End_Document;
-----------------
-- End_Element --
-----------------
overriding procedure End_Element
(Self : in out SAX_Events_Writer;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <endElement>"));
if Namespace_URI.Is_Empty then
Self.Add_Line (To_Universal_String (" <namespaceURI/>"));
else
Self.Add_Line
(" <namespaceURI>" & Namespace_URI & "</namespaceURI>");
end if;
if Local_Name.Is_Empty then
Self.Add_Line (To_Universal_String (" <localName/>"));
else
Self.Add_Line (" <localName>" & Local_Name & "</localName>");
end if;
if Qualified_Name.Is_Empty then
Self.Add_Line (To_Universal_String (" <qualifiedName/>"));
else
Self.Add_Line
(" <qualifiedName>" & Qualified_Name & "</qualifiedName>");
end if;
Self.Add_Line (To_Universal_String (" </endElement>"));
end End_Element;
------------------------
-- End_Prefix_Mapping --
------------------------
overriding procedure End_Prefix_Mapping
(Self : in out SAX_Events_Writer;
Prefix : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <endPrefixMapping>"));
if Prefix.Is_Empty then
Self.Add_Line (To_Universal_String (" <prefix/>"));
else
Self.Add_Line (" <prefix>" & Prefix & "</prefix>");
end if;
Self.Add_Line (To_Universal_String (" </endPrefixMapping>"));
end End_Prefix_Mapping;
-----------
-- Error --
-----------
overriding procedure Error
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception;
Success : in out Boolean) is
begin
Self.Errors := True;
Self.Add_Line
(" <error>" & Escape_String (Occurrence.Message) & "</error>");
end Error;
------------------
-- Error_String --
------------------
overriding function Error_String
(Self : SAX_Events_Writer)
return League.Strings.Universal_String is
begin
return Empty_Universal_String;
end Error_String;
----------------------
-- Escape_Character --
----------------------
function Escape_Character
(Item : League.Characters.Universal_Character)
return League.Strings.Universal_String
is
function Image (Item : Wide_Wide_Character)
return League.Strings.Universal_String;
-----------
-- Image --
-----------
function Image (Item : Wide_Wide_Character)
return League.Strings.Universal_String
is
To_Hex : constant array (0 .. 15) of Wide_Wide_Character
:= "0123456789ABCDEF";
Result : Wide_Wide_String (1 .. 6);
First : Integer := Result'Last + 1;
Aux : Integer := Wide_Wide_Character'Pos (Item);
begin
while Aux /= 0 loop
First := First - 1;
Result (First) := To_Hex (Aux mod 16);
Aux := Aux / 16;
end loop;
return
League.Strings.To_Universal_String
("&#x" & Result (First .. Result'Last) & ";");
end Image;
begin
case Item.To_Wide_Wide_Character is
when NUL .. ' ' | DEL .. APC =>
return Image (Item.To_Wide_Wide_Character);
when '&' =>
return To_Universal_String ("&");
when '<' =>
return To_Universal_String ("<");
when '>' =>
return To_Universal_String (">");
when others =>
return
To_Universal_String
(Wide_Wide_String'(1 => Item.To_Wide_Wide_Character));
end case;
end Escape_Character;
-------------------
-- Escape_String --
-------------------
function Escape_String
(Item : League.Strings.Universal_String)
return League.Strings.Universal_String
is
Result : League.Strings.Universal_String := Item;
begin
for J in reverse 1 .. Item.Length loop
case Result.Element (J).To_Wide_Wide_Character is
when HT =>
Result.Replace (J, J, "	");
when LF =>
Result.Replace (J, J, "
");
when CR =>
Result.Replace (J, J, "
");
when ' ' =>
Result.Replace (J, J, " ");
when '&' =>
Result.Replace (J, J, "&");
when '<' =>
Result.Replace (J, J, "<");
when '>' =>
Result.Replace (J, J, ">");
when ''' =>
Result.Replace (J, J, "'");
when '"' =>
Result.Replace (J, J, """);
when others =>
null;
end case;
end loop;
return Result;
end Escape_String;
----------------
-- Has_Errors --
----------------
not overriding function Has_Errors (Self : SAX_Events_Writer) return Boolean is
begin
return Self.Errors;
end Has_Errors;
-----------------
-- Fatal_Error --
-----------------
overriding procedure Fatal_Error
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception)
is
pragma Unrefernced (Self);
begin
Self.Fatal_Errors := True;
Self.Add_Line
(" <fatalError>"
& Escape_String (Occurrence.Message)
& "</fatalError>");
end Fatal_Error;
----------------------
-- Has_Fatal_Errors --
----------------------
not overriding function Has_Fatal_Errors
(Self : SAX_Events_Writer) return Boolean is
begin
return Self.Fatal_Errors;
end Has_Fatal_Errors;
--------------------------
-- Ignorable_Whitespace --
--------------------------
overriding procedure Ignorable_Whitespace
(Self : in out SAX_Events_Writer;
Text : League.Strings.Universal_String;
Success : in out Boolean) is
begin
for J in 1 .. Text.Length loop
Self.Add_Line
(" <ignorableWhitespace>"
& Escape_Character (Text.Element (J))
& "</ignorableWhitespace>");
end loop;
end Ignorable_Whitespace;
----------------
-- Initialize --
----------------
overriding procedure Initialize (Self : in out SAX_Events_Writer) is
begin
Self.Add_Line
(To_Universal_String ("<?xml version=""1.0"" encoding=""UTF-8""?>"));
Self.Add_Line (To_Universal_String ("<SAXEvents>"));
end Initialize;
--------------------------
-- Notation_Declaration --
--------------------------
overriding procedure Notation_Declaration
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <notation>"));
Self.Add_Line (" <name>" & Name & "</name>");
if not Public_Id.Is_Empty then
Self.Add_Line
(" <publicID>" & Escape_String (Public_Id) & "</publicID>");
end if;
if not System_Id.Is_Empty then
Self.Add_Line (" <systemID>" & System_Id & "</systemID>");
end if;
Self.Add_Line (To_Universal_String (" </notation>"));
end Notation_Declaration;
----------------------------
-- Processing_Instruction --
----------------------------
overriding procedure Processing_Instruction
(Self : in out SAX_Events_Writer;
Target : League.Strings.Universal_String;
Data : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <processingInstruction>"));
Self.Add_Line (" <target>" & Target & "</target>");
if Data.Is_Empty then
Self.Add_Line (To_Universal_String (" <data/>"));
else
Self.Add_Line (" <data>" & Escape_String (Data) & "</data>");
end if;
Self.Add_Line (To_Universal_String (" </processingInstruction>"));
end Processing_Instruction;
--------------------
-- Resolve_Entity --
--------------------
overriding procedure Resolve_Entity
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
Base_URI : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Source : out XML.SAX.Input_Sources.SAX_Input_Source_Access;
Success : in out Boolean)
is
use XML.SAX.Input_Sources.Streams.Files;
Actual_System_Id : constant League.Strings.Universal_String
:= Matreshka.Internals.URI_Utilities.Construct_System_Id
(Base_URI, System_Id);
Stripped_Base_URI : League.Strings.Universal_String := Base_URI;
begin
if Base_URI.Starts_With (Self.URI) then
Stripped_Base_URI :=
Base_URI.Slice (Self.URI.Length + 1, Base_URI.Length);
end if;
Self.Add_Line (To_Universal_String (" <resolveEntity>"));
Self.Add_Line (" <name>" & Escape_String (Name) & "</name>");
if not Public_Id.Is_Empty then
Self.Add_Line
(" <publicID>" & Escape_String (Public_Id) & "</publicID>");
end if;
if not Stripped_Base_URI.Is_Empty then
Self.Add_Line
(" <baseURI>" & Escape_String (Stripped_Base_URI) & "</baseURI>");
end if;
if not System_Id.Is_Empty then
Self.Add_Line (" <systemID>" & System_Id & "</systemID>");
end if;
Self.Add_Line (To_Universal_String (" </resolveEntity>"));
Source := new File_Input_Source;
File_Input_Source'Class (Source.all).Open_By_URI (Actual_System_Id);
end Resolve_Entity;
--------------------------
-- Set_Document_Locator --
--------------------------
overriding procedure Set_Document_Locator
(Self : in out SAX_Events_Writer;
Locator : XML.SAX.Locators.SAX_Locator) is
begin
null;
end Set_Document_Locator;
-----------------------
-- Set_Testsuite_URI --
-----------------------
not overriding procedure Set_Testsuite_URI
(Self : in out SAX_Events_Writer;
URI : League.Strings.Universal_String) is
begin
Self.URI := URI & '/';
end Set_Testsuite_URI;
--------------------
-- Skipped_Entity --
--------------------
overriding procedure Skipped_Entity
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Success : in out Boolean) is
begin
raise Constraint_Error;
end Skipped_Entity;
--------------------
-- Start_Document --
--------------------
overriding procedure Start_CDATA
(Self : in out SAX_Events_Writer;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <startCDATA/>"));
end Start_CDATA;
--------------------
-- Start_Document --
--------------------
overriding procedure Start_Document
(Self : in out SAX_Events_Writer;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <startDocument/>"));
end Start_Document;
-------------------
-- Start_Element --
-------------------
overriding procedure Start_Element
(Self : in out SAX_Events_Writer;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean)
is
use Universal_String_Integer_Maps;
Map : Universal_String_Integer_Maps.Map;
Position : Universal_String_Integer_Maps.Cursor;
Index : Positive;
begin
Self.Add_Line (To_Universal_String (" <startElement>"));
if Namespace_URI.Is_Empty then
Self.Add_Line (To_Universal_String (" <namespaceURI/>"));
else
Self.Add_Line
(" <namespaceURI>" & Namespace_URI & "</namespaceURI>");
end if;
if Local_Name.Is_Empty then
Self.Add_Line (To_Universal_String (" <localName/>"));
else
Self.Add_Line
(" <localName>" & Local_Name & "</localName>");
end if;
if Qualified_Name.Is_Empty then
Self.Add_Line (To_Universal_String (" <qualifiedName/>"));
else
Self.Add_Line
(" <qualifiedName>" & Qualified_Name & "</qualifiedName>");
end if;
if Attributes.Is_Empty then
Self.Add_Line (To_Universal_String (" <attributes/>"));
else
Self.Add_Line (To_Universal_String (" <attributes>"));
for J in 1 .. Attributes.Length loop
Map.Insert (Attributes.Qualified_Name (J), J);
end loop;
Position := Map.First;
while Has_Element (Position) loop
Index := Element (Position);
Self.Add_Line (To_Universal_String (" <attribute>"));
if Attributes.Namespace_URI (Index).Is_Empty then
Self.Add_Line (To_Universal_String (" <namespaceURI/>"));
else
Self.Add_Line
(" <namespaceURI>"
& Attributes.Namespace_URI (Index)
& "</namespaceURI>");
end if;
if Attributes.Local_Name (Index).Is_Empty then
Self.Add_Line (To_Universal_String (" <localName/>"));
else
Self.Add_Line
(" <localName>"
& Attributes.Local_Name (Index)
& "</localName>");
end if;
if Attributes.Qualified_Name (Index).Is_Empty then
Self.Add_Line
(To_Universal_String (" <qualifiedName/>"));
else
Self.Add_Line
(" <qualifiedName>"
& Attributes.Qualified_Name (Index)
& "</qualifiedName>");
end if;
if Attributes.Value (Index).Is_Empty then
Self.Add_Line
(To_Universal_String (" <value/>"));
else
Self.Add_Line
(" <value>"
& Escape_String (Attributes.Value (Index))
& "</value>");
end if;
Self.Add_Line
(" <type>" & Attributes.Value_Type (Index) & "</type>");
if Attributes.Is_Declared (Index) then
Self.Add_Line
(To_Universal_String
(" <isDeclared>true</isDeclared>"));
else
Self.Add_Line
(To_Universal_String
(" <isDeclared>false</isDeclared>"));
end if;
if Attributes.Is_Specified (Index) then
Self.Add_Line
(To_Universal_String
(" <isSpecified>true</isSpecified>"));
else
Self.Add_Line
(To_Universal_String
(" <isSpecified>false</isSpecified>"));
end if;
Self.Add_Line (To_Universal_String (" </attribute>"));
Next (Position);
end loop;
Self.Add_Line (To_Universal_String (" </attributes>"));
end if;
Self.Add_Line (To_Universal_String (" </startElement>"));
end Start_Element;
--------------------------
-- Start_Prefix_Mapping --
--------------------------
overriding procedure Start_Prefix_Mapping
(Self : in out SAX_Events_Writer;
Prefix : League.Strings.Universal_String;
URI : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <startPrefixMapping>"));
if Prefix.Is_Empty then
Self.Add_Line (To_Universal_String (" <prefix/>"));
else
Self.Add_Line (" <prefix>" & Prefix & "</prefix>");
end if;
if URI.Is_Empty then
Self.Add_Line (To_Universal_String (" <data/>"));
else
Self.Add_Line (" <data>" & URI & "</data>");
end if;
Self.Add_Line (To_Universal_String (" </startPrefixMapping>"));
end Start_Prefix_Mapping;
----------
-- Text --
----------
not overriding function Text
(Self : SAX_Events_Writer) return League.Strings.Universal_String is
begin
return Self.Result;
end Text;
---------------------------------
-- Unparsed_Entity_Declaration --
---------------------------------
overriding procedure Unparsed_Entity_Declaration
(Self : in out SAX_Events_Writer;
Name : League.Strings.Universal_String;
Public_Id : League.Strings.Universal_String;
System_Id : League.Strings.Universal_String;
Notation_Name : League.Strings.Universal_String;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <unparsedEntity>"));
Self.Add_Line (" <name>" & Name & "</name>");
if not Public_Id.Is_Empty then
Self.Add_Line
(" <publicID>" & Escape_String (Public_Id) & "</publicID>");
end if;
if not System_Id.Is_Empty then
Self.Add_Line (" <systemID>" & System_Id & "</systemID>");
end if;
Self.Add_Line (" <notation>" & Notation_Name & "</notation>");
Self.Add_Line (To_Universal_String (" </unparsedEntity>"));
end Unparsed_Entity_Declaration;
-------------
-- Warning --
-------------
overriding procedure Warning
(Self : in out SAX_Events_Writer;
Occurrence : XML.SAX.Parse_Exceptions.SAX_Parse_Exception;
Success : in out Boolean) is
begin
Self.Add_Line (To_Universal_String (" <warning/>"));
end Warning;
end SAX_Events_Writers;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with GDNative.Context;
with GDNative.Console;
with GDNative.Exceptions;
with Adventure;
package body Engine_Hooks is
procedure On_GDNative_Init (p_options : access Thin.godot_gdnative_init_options) is begin
Context.GDNative_Initialize (p_options);
Console.Put ("GDNative Initialized!");
end;
procedure On_GDNative_Terminate (p_options : access Thin.godot_gdnative_terminate_options) is begin
Console.Put ("GDNative Finalized!");
Context.GDNative_Finalize (p_options);
end;
procedure On_Nativescript_Init (p_handle : Thin.Nativescript_Handle) is begin
Console.Put ("Nativescript Initialzing");
Context.Nativescript_Initialize (p_handle);
Adventure.Register_Classes;
Console.Put ("Nativescript Initialized!");
exception
when Error : others => Exceptions.Put_Error (Error);
end;
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with TEXT_IO;
with INFLECTIONS_PACKAGE; use INFLECTIONS_PACKAGE;
with DICTIONARY_PACKAGE; use DICTIONARY_PACKAGE;
with ADDONS_PACKAGE; use ADDONS_PACKAGE;
with WORD_SUPPORT_PACKAGE; use WORD_SUPPORT_PACKAGE;
package WORD_PACKAGE is
LINE_NUMBER, WORD_NUMBER : INTEGER := 0;
type STEM_ARRAY_TYPE is array (INTEGER range <>) of STEM_TYPE;
subtype STEM_ARRAY is STEM_ARRAY_TYPE(0..MAX_STEM_SIZE);
NOT_A_STEM : constant STEM_TYPE := (others => 'x');
NOT_A_STEM_ARRAY : STEM_ARRAY := (others => NOT_A_STEM);
SA, SSA : STEM_ARRAY := NOT_A_STEM_ARRAY;
SSA_MAX : INTEGER := 0;
type PRUNED_DICTIONARY_ITEM is
record
DS : DICTIONARY_STEM;
D_K : DICTIONARY_KIND := DEFAULT_DICTIONARY_KIND;
end record;
NULL_PRUNED_DICTIONARY_ITEM : PRUNED_DICTIONARY_ITEM;
type PRUNED_DICTIONARY_LIST is array (1..80) of PRUNED_DICTIONARY_ITEM;
-- Aug 96 QU_PRON max 42, PACK max 54
-- Jan 97 QU_PRON max 42, PACK max 74 -- Might reduce
PDL : PRUNED_DICTIONARY_LIST := (others => NULL_PRUNED_DICTIONARY_ITEM);
PDL_INDEX : INTEGER := 0;
subtype SAL is PARSE_ARRAY(1..250);
type DICT_RESTRICTION is (X, REGULAR, QU_PRON_ONLY, PACK_ONLY);
XXX_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For TRICKS
YYY_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For SYNCOPE
NNN_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For Names
RRR_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For Roman Numerals
PPP_MEANING : MEANING_TYPE := NULL_MEANING_TYPE; -- For COMPOUNDED
SCROLL_LINE_NUMBER : INTEGER := 0;
OUTPUT_SCROLL_COUNT : INTEGER := 0;
procedure PAUSE(OUTPUT : TEXT_IO.FILE_TYPE);
function MIN(A, B : INTEGER) return INTEGER;
function LTU(C, D : CHARACTER) return BOOLEAN;
function EQU(C, D : CHARACTER) return BOOLEAN;
function GTU(C, D : CHARACTER) return BOOLEAN;
function LTU(S, T : STRING) return BOOLEAN;
function GTU(S, T : STRING) return BOOLEAN;
function EQU(S, T : STRING) return BOOLEAN;
procedure RUN_INFLECTIONS(S : in STRING; SL : in out SAL;
RESTRICTION : DICT_RESTRICTION := REGULAR);
procedure SEARCH_DICTIONARIES(SSA : in STEM_ARRAY_TYPE;
PREFIX : PREFIX_ITEM; SUFFIX : SUFFIX_ITEM;
RESTRICTION : DICT_RESTRICTION := REGULAR);
procedure WORD(RAW_WORD : in STRING;
PA : in out PARSE_ARRAY; PA_LAST : in out INTEGER);
procedure CHANGE_LANGUAGE(C : CHARACTER);
procedure INITIALIZE_WORD_PACKAGE;
end WORD_PACKAGE;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- * ISO C99: 7.18 Integer types <stdint.h>
--
-- Exact integral types.
-- Signed.
-- There is some amount of overlap with <sys/types.h> as known by inet code
-- Unsigned.
subtype uint8_t is unsigned_char; -- stdint.h:48
subtype uint16_t is unsigned_short; -- stdint.h:49
subtype uint32_t is unsigned; -- stdint.h:51
subtype uint64_t is unsigned_long; -- stdint.h:55
-- Small types.
-- Signed.
subtype int_least8_t is signed_char; -- stdint.h:65
subtype int_least16_t is short; -- stdint.h:66
subtype int_least32_t is int; -- stdint.h:67
subtype int_least64_t is long; -- stdint.h:69
-- Unsigned.
subtype uint_least8_t is unsigned_char; -- stdint.h:76
subtype uint_least16_t is unsigned_short; -- stdint.h:77
subtype uint_least32_t is unsigned; -- stdint.h:78
subtype uint_least64_t is unsigned_long; -- stdint.h:80
-- Fast types.
-- Signed.
subtype int_fast8_t is signed_char; -- stdint.h:90
subtype int_fast16_t is long; -- stdint.h:92
subtype int_fast32_t is long; -- stdint.h:93
subtype int_fast64_t is long; -- stdint.h:94
-- Unsigned.
subtype uint_fast8_t is unsigned_char; -- stdint.h:103
subtype uint_fast16_t is unsigned_long; -- stdint.h:105
subtype uint_fast32_t is unsigned_long; -- stdint.h:106
subtype uint_fast64_t is unsigned_long; -- stdint.h:107
-- Types for `void *' pointers.
subtype uintptr_t is unsigned_long; -- stdint.h:122
-- Largest integral types.
subtype intmax_t is long; -- stdint.h:134
subtype uintmax_t is unsigned_long; -- stdint.h:135
-- Limits of integral types.
-- Minimum of signed integral types.
-- Maximum of signed integral types.
-- Maximum of unsigned integral types.
-- Minimum of signed integral types having a minimum size.
-- Maximum of signed integral types having a minimum size.
-- Maximum of unsigned integral types having a minimum size.
-- Minimum of fast signed integral types having a minimum size.
-- Maximum of fast signed integral types having a minimum size.
-- Maximum of fast unsigned integral types having a minimum size.
-- Values to test for integral types holding `void *' pointer.
-- Minimum for largest signed integral type.
-- Maximum for largest signed integral type.
-- Maximum for largest unsigned integral type.
-- Limits of other integer types.
-- Limits of `ptrdiff_t' type.
-- Limits of `sig_atomic_t'.
-- Limit of `size_t' type.
-- Limits of `wchar_t'.
-- These constants might also be defined in <wchar.h>.
-- Limits of `wint_t'.
-- Signed.
-- Unsigned.
-- Maximal type.
end CUPS.stdint_h;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_Io;
with Ada.Integer_text_IO;
procedure Call_Back_Example is
-- Purpose: Apply a callback to an array
-- Output: Prints the squares of an integer array to the console
-- Define the callback procedure
procedure Display(Location : Positive; Value : Integer) is
begin
Ada.Text_Io.Put("array(");
Ada.Integer_Text_Io.Put(Item => Location, Width => 1);
Ada.Text_Io.Put(") = ");
Ada.Integer_Text_Io.Put(Item => Value * Value, Width => 1);
Ada.Text_Io.New_Line;
end Display;
-- Define an access type matching the signature of the callback procedure
type Call_Back_Access is access procedure(L : Positive; V : Integer);
-- Define an unconstrained array type
type Value_Array is array(Positive range <>) of Integer;
-- Define the procedure performing the callback
procedure Map(Values : Value_Array; Worker : Call_Back_Access) is
begin
for I in Values'range loop
Worker(I, Values(I));
end loop;
end Map;
-- Define and initialize the actual array
Sample : Value_Array := (5,4,3,2,1);
begin
Map(Sample, Display'access);
end Call_Back_Example;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with System.Storage_Elements;
function Storage_Array_To_String(X : System.Storage_Elements.Storage_Array)
return String is
use System.Storage_Elements;
begin
-- This compile-time check is useful for GNAT, but in GNATprove it currently
-- just generates a warning that it can not yet be proved correct.
pragma Warnings (GNATprove, Off, "Compile_Time_Error");
pragma Compile_Time_Error ((Character'Size /= Storage_Element'Size),
"Character and Storage_Element types are different sizes!");
pragma Warnings (GNATprove, On, "Compile_Time_Error");
return R : String(Integer(X'First) .. Integer(X'Last)) do
for I in X'Range loop
R(Integer(I)) := Character'Val(Storage_Element'Pos(X(I)));
end loop;
end return;
end Storage_Array_To_String;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.