repo_name
stringlengths 9
74
| language
stringclasses 1
value | length_bytes
int64 11
9.34M
| extension
stringclasses 2
values | content
stringlengths 11
9.34M
|
---|---|---|---|---|
sparre/JSA | Ada | 437 | adb | with
Ada.Directories;
package body JSA.Directories is
procedure Rename_As_Backup (Name : in String) is
use Ada.Directories;
Backup : constant String := Name & "~";
begin
if Exists (Name) then
if Exists (Backup) then
Delete_File (Backup);
end if;
Rename (Old_Name => Name,
New_Name => Backup);
end if;
end Rename_As_Backup;
end JSA.Directories;
|
AdaCore/libadalang | Ada | 71 | ads | with Pkg; use Pkg;
procedure Bar (X : Sub);
--% node.p_semantic_parent
|
ohenley/ada-util | Ada | 8,216 | adb | -----------------------------------------------------------------------
-- files.tests -- Unit tests for files
-- Copyright (C) 2009, 2010, 2011, 2012, 2013 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Directories;
with Util.Test_Caller;
package body Util.Files.Tests is
use Util.Tests;
package Caller is new Util.Test_Caller (Test, "Files");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Files.Read_File",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (missing)",
Test_Read_File_Missing'Access);
Caller.Add_Test (Suite, "Test Util.Files.Read_File (truncate)",
Test_Read_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Write_File",
Test_Write_File'Access);
Caller.Add_Test (Suite, "Test Util.Files.Iterate_Path",
Test_Iterate_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Find_File_Path",
Test_Find_File_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Compose_Path",
Test_Compose_Path'Access);
Caller.Add_Test (Suite, "Test Util.Files.Get_Relative_Path",
Test_Get_Relative_Path'Access);
end Add_Tests;
-- ------------------------------
-- Test reading a file into a string
-- Reads this ada source file and checks we have read it correctly
-- ------------------------------
procedure Test_Read_File (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result);
T.Assert (Index (Result, "Util.Files.Tests") > 0,
"Content returned by Read_File is not correct");
T.Assert (Index (Result, "end Util.Files.Tests;") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File;
procedure Test_Read_File_Missing (T : in out Test) is
Result : Unbounded_String;
pragma Unreferenced (Result);
begin
Read_File (Path => "regtests/files-test--util.adb", Into => Result);
T.Assert (False, "No exception raised");
exception
when others =>
null;
end Test_Read_File_Missing;
procedure Test_Read_File_Truncate (T : in out Test) is
Result : Unbounded_String;
begin
Read_File (Path => "regtests/util-files-tests.adb", Into => Result,
Max_Size => 50);
Assert_Equals (T, Length (Result), 50,
"Read_File did not truncate correctly");
T.Assert (Index (Result, "Apache License") > 0,
"Content returned by Read_File is not correct");
end Test_Read_File_Truncate;
-- ------------------------------
-- Check writing a file
-- ------------------------------
procedure Test_Write_File (T : in out Test) is
Path : constant String := Util.Tests.Get_Test_Path ("test-write.txt");
Content : constant String := "Testing Util.Files.Write_File" & ASCII.LF;
Result : Unbounded_String;
begin
Write_File (Path => Path, Content => Content);
Read_File (Path => Path, Into => Result);
Assert_Equals (T, To_String (Result), Content,
"Invalid content written or read");
end Test_Write_File;
-- ------------------------------
-- Check Find_File_Path
-- ------------------------------
procedure Test_Find_File_Path (T : in out Test) is
Dir : constant String := Util.Tests.Get_Path ("regtests");
Paths : constant String := ".;" & Dir;
begin
declare
P : constant String := Util.Files.Find_File_Path ("test.properties", Paths);
begin
Assert_Equals (T, Dir & "/test.properties", P,
"Invalid path returned");
end;
Assert_Equals (T, "blablabla.properties",
Util.Files.Find_File_Path ("blablabla.properties", Paths));
end Test_Find_File_Path;
-- ------------------------------
-- Check Iterate_Path
-- ------------------------------
procedure Test_Iterate_Path (T : in out Test) is
procedure Check_Path (Dir : in String;
Done : out Boolean);
Last : Unbounded_String;
procedure Check_Path (Dir : in String;
Done : out Boolean) is
begin
if Dir = "a" or Dir = "bc" or Dir = "de" then
Done := False;
else
Done := True;
end if;
Last := To_Unbounded_String (Dir);
end Check_Path;
begin
Iterate_Path ("a;bc;de;f", Check_Path'Access);
Assert_Equals (T, "f", Last, "Invalid last path");
Iterate_Path ("de;bc;de;b", Check_Path'Access);
Assert_Equals (T, "b", Last, "Invalid last path");
Iterate_Path ("de;bc;de;a", Check_Path'Access, Ada.Strings.Backward);
Assert_Equals (T, "de", Last, "Invalid last path");
end Test_Iterate_Path;
-- ------------------------------
-- Test the Compose_Path operation
-- ------------------------------
procedure Test_Compose_Path (T : in out Test) is
begin
Assert_Equals (T, "src/os-none",
Compose_Path ("src;regtests", "os-none"),
"Invalid path composition");
Assert_Equals (T, "regtests/bundles",
Compose_Path ("src;regtests", "bundles"),
"Invalid path composition");
if Ada.Directories.Exists ("/usr/bin") then
Assert_Equals (T, "/usr/bin;/usr/local/bin;/usr/bin",
Compose_Path ("/usr;/usr/local;/usr", "bin"),
"Invalid path composition");
end if;
end Test_Compose_Path;
-- ------------------------------
-- Test the Get_Relative_Path operation.
-- ------------------------------
procedure Test_Get_Relative_Path (T : in out Test) is
begin
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util",
Get_Relative_Path ("/home/john/src/asf/", "/home/john/src/util"),
"Invalid relative path");
Assert_Equals (T, "../util/b",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/util/b"),
"Invalid relative path");
Assert_Equals (T, "../as",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/as"),
"Invalid relative path");
Assert_Equals (T, "../../",
Get_Relative_Path ("/home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "/usr/share/admin",
Get_Relative_Path ("/home/john/src/asf", "/usr/share/admin"),
"Invalid absolute path");
Assert_Equals (T, "/home/john",
Get_Relative_Path ("home/john/src/asf", "/home/john"),
"Invalid relative path");
Assert_Equals (T, "e",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/e"),
"Invalid relative path");
Assert_Equals (T, ".",
Get_Relative_Path ("/home/john/src/asf", "/home/john/src/asf/"),
"Invalid relative path");
end Test_Get_Relative_Path;
end Util.Files.Tests;
|
reznikmm/matreshka | Ada | 17,948 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with AMF.Elements;
with AMF.Internals.Element_Collections;
with AMF.Internals.Helpers;
with AMF.Internals.Tables.UML_Attributes;
with AMF.Visitors.UML_Iterators;
with AMF.Visitors.UML_Visitors;
with League.Strings.Internals;
with Matreshka.Internals.Strings;
package body AMF.Internals.UML_Duration_Constraints is
-------------------
-- Enter_Element --
-------------------
overriding procedure Enter_Element
(Self : not null access constant UML_Duration_Constraint_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control) is
begin
if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then
AMF.Visitors.UML_Visitors.UML_Visitor'Class
(Visitor).Enter_Duration_Constraint
(AMF.UML.Duration_Constraints.UML_Duration_Constraint_Access (Self),
Control);
end if;
end Enter_Element;
-------------------
-- Leave_Element --
-------------------
overriding procedure Leave_Element
(Self : not null access constant UML_Duration_Constraint_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control) is
begin
if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then
AMF.Visitors.UML_Visitors.UML_Visitor'Class
(Visitor).Leave_Duration_Constraint
(AMF.UML.Duration_Constraints.UML_Duration_Constraint_Access (Self),
Control);
end if;
end Leave_Element;
-------------------
-- Visit_Element --
-------------------
overriding procedure Visit_Element
(Self : not null access constant UML_Duration_Constraint_Proxy;
Iterator : in out AMF.Visitors.Abstract_Iterator'Class;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control) is
begin
if Iterator in AMF.Visitors.UML_Iterators.UML_Iterator'Class then
AMF.Visitors.UML_Iterators.UML_Iterator'Class
(Iterator).Visit_Duration_Constraint
(Visitor,
AMF.UML.Duration_Constraints.UML_Duration_Constraint_Access (Self),
Control);
end if;
end Visit_Element;
---------------------
-- Get_First_Event --
---------------------
overriding function Get_First_Event
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.Boolean_Collections.Set_Of_Boolean is
begin
raise Program_Error;
return Get_First_Event (Self);
end Get_First_Event;
-----------------------
-- Get_Specification --
-----------------------
overriding function Get_Specification
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Duration_Intervals.UML_Duration_Interval_Access is
begin
return
AMF.UML.Duration_Intervals.UML_Duration_Interval_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Specification
(Self.Element)));
end Get_Specification;
-----------------------
-- Set_Specification --
-----------------------
overriding procedure Set_Specification
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Duration_Intervals.UML_Duration_Interval_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Specification
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Specification;
-----------------------
-- Get_Specification --
-----------------------
overriding function Get_Specification
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Intervals.UML_Interval_Access is
begin
return
AMF.UML.Intervals.UML_Interval_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Specification
(Self.Element)));
end Get_Specification;
-----------------------
-- Set_Specification --
-----------------------
overriding procedure Set_Specification
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Intervals.UML_Interval_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Specification
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Specification;
-----------------------------
-- Get_Constrained_Element --
-----------------------------
overriding function Get_Constrained_Element
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Elements.Collections.Ordered_Set_Of_UML_Element is
begin
return
AMF.UML.Elements.Collections.Wrap
(AMF.Internals.Element_Collections.Wrap
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Constrained_Element
(Self.Element)));
end Get_Constrained_Element;
-----------------
-- Get_Context --
-----------------
overriding function Get_Context
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access is
begin
raise Program_Error;
return Get_Context (Self);
end Get_Context;
-----------------
-- Set_Context --
-----------------
overriding procedure Set_Context
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Namespaces.UML_Namespace_Access) is
begin
raise Program_Error;
end Set_Context;
-----------------------
-- Get_Specification --
-----------------------
overriding function Get_Specification
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Value_Specifications.UML_Value_Specification_Access is
begin
return
AMF.UML.Value_Specifications.UML_Value_Specification_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Specification
(Self.Element)));
end Get_Specification;
-----------------------
-- Set_Specification --
-----------------------
overriding procedure Set_Specification
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Value_Specifications.UML_Value_Specification_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Specification
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Specification;
---------------------------
-- Get_Client_Dependency --
---------------------------
overriding function Get_Client_Dependency
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency is
begin
return
AMF.UML.Dependencies.Collections.Wrap
(AMF.Internals.Element_Collections.Wrap
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Client_Dependency
(Self.Element)));
end Get_Client_Dependency;
-------------------------
-- Get_Name_Expression --
-------------------------
overriding function Get_Name_Expression
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.String_Expressions.UML_String_Expression_Access is
begin
return
AMF.UML.String_Expressions.UML_String_Expression_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Name_Expression
(Self.Element)));
end Get_Name_Expression;
-------------------------
-- Set_Name_Expression --
-------------------------
overriding procedure Set_Name_Expression
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.String_Expressions.UML_String_Expression_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Name_Expression
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Name_Expression;
-------------------
-- Get_Namespace --
-------------------
overriding function Get_Namespace
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access is
begin
return
AMF.UML.Namespaces.UML_Namespace_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Namespace
(Self.Element)));
end Get_Namespace;
------------------------
-- Get_Qualified_Name --
------------------------
overriding function Get_Qualified_Name
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.Optional_String is
begin
declare
use type Matreshka.Internals.Strings.Shared_String_Access;
Aux : constant Matreshka.Internals.Strings.Shared_String_Access
:= AMF.Internals.Tables.UML_Attributes.Internal_Get_Qualified_Name (Self.Element);
begin
if Aux = null then
return (Is_Empty => True);
else
return (False, League.Strings.Internals.Create (Aux));
end if;
end;
end Get_Qualified_Name;
-----------------------------------
-- Get_Owning_Template_Parameter --
-----------------------------------
overriding function Get_Owning_Template_Parameter
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is
begin
return
AMF.UML.Template_Parameters.UML_Template_Parameter_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Owning_Template_Parameter
(Self.Element)));
end Get_Owning_Template_Parameter;
-----------------------------------
-- Set_Owning_Template_Parameter --
-----------------------------------
overriding procedure Set_Owning_Template_Parameter
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Owning_Template_Parameter
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Owning_Template_Parameter;
----------------------------
-- Get_Template_Parameter --
----------------------------
overriding function Get_Template_Parameter
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Template_Parameters.UML_Template_Parameter_Access is
begin
return
AMF.UML.Template_Parameters.UML_Template_Parameter_Access
(AMF.Internals.Helpers.To_Element
(AMF.Internals.Tables.UML_Attributes.Internal_Get_Template_Parameter
(Self.Element)));
end Get_Template_Parameter;
----------------------------
-- Set_Template_Parameter --
----------------------------
overriding procedure Set_Template_Parameter
(Self : not null access UML_Duration_Constraint_Proxy;
To : AMF.UML.Template_Parameters.UML_Template_Parameter_Access) is
begin
AMF.Internals.Tables.UML_Attributes.Internal_Set_Template_Parameter
(Self.Element,
AMF.Internals.Helpers.To_Element
(AMF.Elements.Element_Access (To)));
end Set_Template_Parameter;
-------------------------
-- All_Owning_Packages --
-------------------------
overriding function All_Owning_Packages
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Packages.Collections.Set_Of_UML_Package is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "All_Owning_Packages unimplemented");
raise Program_Error with "Unimplemented procedure UML_Duration_Constraint_Proxy.All_Owning_Packages";
return All_Owning_Packages (Self);
end All_Owning_Packages;
-----------------------------
-- Is_Distinguishable_From --
-----------------------------
overriding function Is_Distinguishable_From
(Self : not null access constant UML_Duration_Constraint_Proxy;
N : AMF.UML.Named_Elements.UML_Named_Element_Access;
Ns : AMF.UML.Namespaces.UML_Namespace_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Distinguishable_From unimplemented");
raise Program_Error with "Unimplemented procedure UML_Duration_Constraint_Proxy.Is_Distinguishable_From";
return Is_Distinguishable_From (Self, N, Ns);
end Is_Distinguishable_From;
---------------
-- Namespace --
---------------
overriding function Namespace
(Self : not null access constant UML_Duration_Constraint_Proxy)
return AMF.UML.Namespaces.UML_Namespace_Access is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Namespace unimplemented");
raise Program_Error with "Unimplemented procedure UML_Duration_Constraint_Proxy.Namespace";
return Namespace (Self);
end Namespace;
------------------------
-- Is_Compatible_With --
------------------------
overriding function Is_Compatible_With
(Self : not null access constant UML_Duration_Constraint_Proxy;
P : AMF.UML.Parameterable_Elements.UML_Parameterable_Element_Access)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Compatible_With unimplemented");
raise Program_Error with "Unimplemented procedure UML_Duration_Constraint_Proxy.Is_Compatible_With";
return Is_Compatible_With (Self, P);
end Is_Compatible_With;
---------------------------
-- Is_Template_Parameter --
---------------------------
overriding function Is_Template_Parameter
(Self : not null access constant UML_Duration_Constraint_Proxy)
return Boolean is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Is_Template_Parameter unimplemented");
raise Program_Error with "Unimplemented procedure UML_Duration_Constraint_Proxy.Is_Template_Parameter";
return Is_Template_Parameter (Self);
end Is_Template_Parameter;
end AMF.Internals.UML_Duration_Constraints;
|
MinimSecure/unum-sdk | Ada | 801 | ads | -- Copyright 2018-2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with System;
package Pck is
procedure Do_Nothing (A : System.Address);
end Pck;
|
charlie5/cBound | Ada | 1,674 | ads | -- This file is generated by SWIG. Please do not modify by hand.
--
with Interfaces;
with swig;
with Interfaces.C;
with Interfaces.C.Pointers;
package xcb.xcb_visibility_notify_event_t is
-- Item
--
type Item is record
response_type : aliased Interfaces.Unsigned_8;
pad0 : aliased Interfaces.Unsigned_8;
sequence : aliased Interfaces.Unsigned_16;
window : aliased xcb.xcb_window_t;
state : aliased Interfaces.Unsigned_8;
pad1 : aliased swig.int8_t_Array (0 .. 2);
end record;
-- Item_Array
--
type Item_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_visibility_notify_event_t
.Item;
-- Pointer
--
package C_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_visibility_notify_event_t.Item,
Element_Array => xcb.xcb_visibility_notify_event_t.Item_Array,
Default_Terminator => (others => <>));
subtype Pointer is C_Pointers.Pointer;
-- Pointer_Array
--
type Pointer_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_visibility_notify_event_t
.Pointer;
-- Pointer_Pointer
--
package C_Pointer_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_visibility_notify_event_t.Pointer,
Element_Array => xcb.xcb_visibility_notify_event_t.Pointer_Array,
Default_Terminator => null);
subtype Pointer_Pointer is C_Pointer_Pointers.Pointer;
end xcb.xcb_visibility_notify_event_t;
|
sungyeon/drake | Ada | 1,025 | ads | pragma License (Unrestricted);
-- implementation unit required by compiler
with Ada.Calendar.Naked;
private with System.Native_Time;
private package Ada.Calendar.Delays is
-- required for delay statement by compiler (a-caldel.ads)
procedure Delay_For (D : Duration);
pragma Inline (Delay_For); -- renamed
-- required for delay until statement by compiler (a-caldel.ads)
procedure Delay_Until (T : Time);
pragma Inline (Delay_Until); -- renamed
-- required by compiler (a-caldel.ads)
-- for select or delay expanded to Timed_Task_Entry_Call,
-- Timed_Protected_Entry_Call, or Timed_Selective_Wait (exp_ch9.adb)
function To_Duration (T : Time) return Duration
renames Calendar.Naked.Seconds_From_2150;
private
-- [gcc-4.8/4.9] Is_RTE returns False if it is renamed in the visible part.
procedure Delay_For (D : Duration)
renames System.Native_Time.Delay_For;
procedure Delay_Until (T : Time)
renames Calendar.Naked.Delay_Until;
end Ada.Calendar.Delays;
|
reznikmm/matreshka | Ada | 4,766 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
package Matreshka.ODF_Elements.Text.Notes_Configuration is
type Text_Notes_Configuration_Node is
new Matreshka.ODF_Elements.Text.Text_Node_Base with null record;
type Text_Notes_Configuration_Access is
access all Text_Notes_Configuration_Node'Class;
overriding procedure Enter_Element
(Self : not null access Text_Notes_Configuration_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding function Get_Local_Name
(Self : not null access constant Text_Notes_Configuration_Node)
return League.Strings.Universal_String;
overriding procedure Leave_Element
(Self : not null access Text_Notes_Configuration_Node;
Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class;
Control : in out XML.DOM.Visitors.Traverse_Control);
-- Dispatch call to corresponding subprogram of visitor interface.
overriding procedure Visit_Element
(Self : not null access Text_Notes_Configuration_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);
-- Dispatch call to corresponding subprogram of iterator interface.
end Matreshka.ODF_Elements.Text.Notes_Configuration;
|
pombredanne/ravenadm | Ada | 57,638 | adb | -- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../License.txt
with Ada.Characters.Latin_1;
with Ada.Strings.Fixed;
with Ada.Command_Line;
with Ada.Directories;
with Ada.Calendar;
with Ada.Text_IO;
with Specification_Parser;
with File_Operations;
with Information;
with Parameters;
with Replicant;
with Configure;
with Utilities;
with Signals;
with Unix;
with Port_Specification.Buildsheet;
with Port_Specification.Makefile;
with Port_Specification.Transform;
with Port_Specification.Web;
with PortScan.Operations;
with PortScan.Buildcycle;
with PortScan.Scan;
with PortScan.Log;
with Options_Dialog;
with Ravenports;
with Repository;
package body Pilot is
package UTL renames Utilities;
package REP renames Replicant;
package PM renames Parameters;
package NFO renames Information;
package FOP renames File_Operations;
package PAR renames Specification_Parser;
package PSB renames Port_Specification.Buildsheet;
package PSM renames Port_Specification.Makefile;
package PST renames Port_Specification.Transform;
package WEB renames Port_Specification.Web;
package OPS renames PortScan.Operations;
package CYC renames PortScan.Buildcycle;
package SCN renames PortScan.Scan;
package LOG renames PortScan.Log;
package OPT renames Options_Dialog;
package LAT renames Ada.Characters.Latin_1;
package CLI renames Ada.Command_Line;
package DIR renames Ada.Directories;
package CAL renames Ada.Calendar;
package TIO renames Ada.Text_IO;
package AS renames Ada.Strings;
--------------------------------------------------------------------------------------------
-- display_usage
--------------------------------------------------------------------------------------------
procedure display_usage is
begin
NFO.display_usage;
end display_usage;
--------------------------------------------------------------------------------------------
-- react_to_unknown_first_level_command
--------------------------------------------------------------------------------------------
procedure react_to_unknown_first_level_command (argument : String) is
begin
NFO.display_unknown_command (argument);
end react_to_unknown_first_level_command;
--------------------------------------------------------------------------------------------
-- react_to_unknown_second_level_command
--------------------------------------------------------------------------------------------
procedure react_to_unknown_second_level_command (level1, level2 : String) is
begin
NFO.display_unknown_command (level1, level2);
end react_to_unknown_second_level_command;
--------------------------------------------------------------------------------------------
-- show_short_help
--------------------------------------------------------------------------------------------
procedure show_short_help is
begin
NFO.short_help_screen;
end show_short_help;
--------------------------------------------------------------------------------------------
-- launch_man_page
--------------------------------------------------------------------------------------------
procedure launch_man_page (level2 : String)
is
result : Boolean;
level2ok : Boolean := False;
man_page : constant String :=
host_localbase & "/share/man/man8/ravenadm-" & level2 & ".8.gz";
begin
if
level2 = "dev" or else
level2 = "build" or else
level2 = "build-everything" or else
level2 = "force" or else
level2 = "test" or else
level2 = "test-everything" or else
level2 = "status" or else
level2 = "status-everything" or else
level2 = "configure" or else
level2 = "locate" or else
level2 = "purge-distfiles" or else
level2 = "set-options" or else
level2 = "check-ports" or else
level2 = "update-ports" or else
level2 = "generate-repository" or else
level2 = "generate-website" or else
level2 = "subpackages"
then
if DIR.Exists (man_page) then
result := Unix.external_command ("/usr/bin/man " & man_page);
else
TIO.Put_Line (errprefix & "the " & level2 & " man page is missing");
end if;
else
TIO.Put_Line ("'" & level2 & "' is not a valid command (so no help is available)");
end if;
end launch_man_page;
--------------------------------------------------------------------------------------------
-- dump_ravensource
--------------------------------------------------------------------------------------------
procedure dump_ravensource (optional_directory : String)
is
directory_specified : constant Boolean := (optional_directory /= "");
successful : Boolean;
specification : Port_Specification.Portspecs;
begin
if directory_specified then
declare
filename : String := optional_directory & "/" & specfile;
begin
if DIR.Exists (filename) then
PAR.parse_specification_file (dossier => filename,
specification => specification,
opsys_focus => platform_type,
arch_focus => sysrootver.arch,
success => successful,
stop_at_targets => False);
else
DNE (filename);
return;
end if;
end;
else
if DIR.Exists (specfile) then
PAR.parse_specification_file (dossier => specfile,
specification => specification,
opsys_focus => platform_type,
arch_focus => sysrootver.arch,
success => successful,
stop_at_targets => False);
else
DNE (specfile);
return;
end if;
end if;
if successful then
specification.dump_specification;
else
TIO.Put_Line (errprefix & "Failed to parse " & specfile);
TIO.Put_Line (PAR.get_parse_error);
end if;
end dump_ravensource;
--------------------------------------------------------------------------------------------
-- list_subpackages
--------------------------------------------------------------------------------------------
procedure list_subpackages
is
successful : Boolean := SCN.scan_provided_list_of_ports (False, sysrootver);
begin
if successful then
OPS.list_subpackages_of_queued_ports;
end if;
end list_subpackages;
--------------------------------------------------------------------------------------------
-- generate_makefile
--------------------------------------------------------------------------------------------
procedure generate_makefile (optional_directory : String;
optional_variant : String)
is
function get_variant return String;
directory_specified : constant Boolean := (optional_directory /= "");
successful : Boolean;
specification : Port_Specification.Portspecs;
dossier_text : HT.Text;
function get_variant return String is
begin
if optional_variant = "" then
return variant_standard;
else
return optional_variant;
end if;
end get_variant;
selected_variant : constant String := get_variant;
begin
if directory_specified then
dossier_text := HT.SUS (optional_directory & "/" & specfile);
else
dossier_text := HT.SUS (specfile);
end if;
if DIR.Exists (HT.USS (dossier_text)) then
OPS.parse_and_transform_buildsheet (specification => specification,
successful => successful,
buildsheet => HT.USS (dossier_text),
variant => selected_variant,
portloc => "",
excl_targets => False,
avoid_dialog => True,
for_webpage => False,
sysrootver => sysrootver);
else
DNE (HT.USS (dossier_text));
return;
end if;
if successful then
if not specification.post_transform_option_group_defaults_passes then
return;
end if;
PSM.generator (specs => specification,
variant => selected_variant,
opsys => platform_type,
arch => sysrootver.arch,
output_file => "");
else
TIO.Put_Line (errprefix & "Failed to parse " & specfile);
TIO.Put_Line (PAR.get_parse_error);
end if;
end generate_makefile;
--------------------------------------------------------------------------------------------
-- generate_webpage
--------------------------------------------------------------------------------------------
procedure generate_webpage (required_namebase : String;
optional_variant : String)
is
function get_variant return String;
successful : Boolean;
specification : Port_Specification.Portspecs;
bogustime : constant CAL.Time := CAL.Clock;
dossier : constant String := HT.USS (PM.configuration.dir_conspiracy) & "/bucket_" &
UTL.bucket (required_namebase) & "/" & required_namebase;
function get_variant return String is
begin
if optional_variant = "" then
return variant_standard;
else
return optional_variant;
end if;
end get_variant;
begin
if DIR.Exists (dossier) then
REP.launch_workzone;
OPS.parse_and_transform_buildsheet (specification => specification,
successful => successful,
buildsheet => dossier,
variant => get_variant,
portloc => REP.get_workzone_path,
excl_targets => False,
avoid_dialog => True,
for_webpage => True,
sysrootver => sysrootver);
else
DNE (dossier);
return;
end if;
if successful then
WEB.produce_page (specs => specification,
variant => get_variant,
dossier => TIO.Standard_Output,
portdir => REP.get_workzone_path,
blocked => "",
created => bogustime,
changed => bogustime,
devscan => True);
else
TIO.Put_Line (errprefix & "Failed to parse " & dossier);
TIO.Put_Line (PAR.get_parse_error);
end if;
REP.destroy_workzone;
end generate_webpage;
--------------------------------------------------------------------------------------------
-- generate_buildsheet
--------------------------------------------------------------------------------------------
procedure generate_buildsheet (sourcedir : String;
save_command : String)
is
save_it : Boolean := False;
successful : Boolean;
ravensrcdir : constant String := Unix.true_path (sourcedir);
filename : constant String := ravensrcdir & "/" & specfile;
specification : Port_Specification.Portspecs;
begin
if save_command = "save" then
save_it := True;
elsif save_command /= "" then
TIO.Put_Line (errprefix & "fourth argument can only be 'save'");
return;
end if;
if ravensrcdir = "" then
TIO.Put_Line (errprefix & "not a valid directory: " & sourcedir);
return;
end if;
if DIR.Exists (filename) then
PAR.parse_specification_file (dossier => filename,
specification => specification,
opsys_focus => platform_type, -- unused
arch_focus => sysrootver.arch,
success => successful,
stop_at_targets => False);
else
DNE (filename);
return;
end if;
if not successful then
TIO.Put_Line (errprefix & "Failed to parse " & specfile);
TIO.Put_Line (PAR.get_parse_error);
return;
end if;
PST.set_option_defaults
(specs => specification,
variant => specification.get_list_item (Port_Specification.sp_variants, 1),
opsys => platform_type,
arch_standard => sysrootver.arch,
osrelease => HT.USS (sysrootver.release));
if not specification.post_transform_option_group_defaults_passes then
successful := False;
return;
end if;
declare
namebase : String := specification.get_namebase;
output_file : String := HT.USS (PM.configuration.dir_conspiracy) & "/bucket_" &
UTL.bucket (palabra => namebase) & "/" & namebase;
begin
if save_it then
FOP.mkdirp_from_filename (output_file);
PSB.generator (specs => specification,
ravensrcdir => ravensrcdir,
output_file => output_file);
TIO.Put_Line (namebase & " buildsheet created at:");
TIO.Put_Line (output_file);
else
PSB.generator (specs => specification,
ravensrcdir => ravensrcdir,
output_file => "");
end if;
end;
end generate_buildsheet;
--------------------------------------------------------------------------------------------
-- DNE
--------------------------------------------------------------------------------------------
procedure DNE (filename : String) is
begin
TIO.Put_Line (errprefix & "File " & LAT.Quotation & filename & LAT.Quotation &
" does not exist.");
end DNE;
--------------------------------------------------------------------------------------------
-- TERM_defined_in_environment
--------------------------------------------------------------------------------------------
function TERM_defined_in_environment return Boolean
is
defined : constant Boolean := Unix.env_variable_defined ("TERM");
begin
if not defined then
TIO.Put_Line ("Please define TERM in environment first and retry.");
end if;
return defined;
end TERM_defined_in_environment;
--------------------------------------------------------------------------------------------
-- launch_clash_detected
--------------------------------------------------------------------------------------------
function launch_clash_detected return Boolean
is
cwd : constant String := DIR.Current_Directory;
sysroot : constant String := HT.USS (PM.configuration.dir_sysroot);
portsdir : constant String := HT.USS (PM.configuration.dir_conspiracy);
distfiles : constant String := HT.USS (PM.configuration.dir_distfiles);
packages : constant String := HT.USS (PM.configuration.dir_packages);
profile : constant String := HT.USS (PM.configuration.dir_profile);
ccache : constant String := HT.USS (PM.configuration.dir_ccache);
buildbase : constant String := HT.USS (PM.configuration.dir_buildbase) & "/";
begin
if HT.leads (cwd, sysroot) or else
HT.leads (cwd, portsdir) or else
HT.leads (cwd, distfiles) or else
HT.leads (cwd, packages) or else
HT.leads (cwd, profile) or else
HT.leads (cwd, ccache) or else
HT.leads (cwd, buildbase)
then
TIO.Put_Line ("Please change the current directory; " &
"ravenadm is unable to launch from here.");
return True;
else
return False;
end if;
end launch_clash_detected;
--------------------------------------------------------------------------------------------
-- insufficient_privileges
--------------------------------------------------------------------------------------------
function insufficient_privileges return Boolean
is
status : Integer;
command : constant String := "/usr/bin/id -u";
result : String := HT.USS (Unix.piped_command (command, status));
begin
if status /= 0 then
TIO.Put_Line ("command '" & command & "' failed. Output=" & result);
return True;
end if;
declare
resint : constant Integer := Integer'Value (HT.first_line (result));
begin
if resint = 0 then
return False;
else
TIO.Put_Line ("Only the root user can execute ravenadm.");
return True;
end if;
end;
end insufficient_privileges;
--------------------------------------------------------------------------------------------
-- already_running
--------------------------------------------------------------------------------------------
function already_running return Boolean is
begin
if DIR.Exists (pidfile) then
declare
textpid : constant String := FOP.head_n1 (pidfile);
command : constant String := "/bin/ps -p " & textpid;
pid : Integer;
comres : HT.Text;
status : Integer;
begin
-- test if valid by converting it (exception if fails)
pid := Integer'Value (textpid);
-- exception raised by line below if pid not found.
comres := Unix.piped_command (command, status);
if status = 0 and then
HT.contains (comres, "ravenadm")
then
TIO.Put_Line ("ravenadm is already running on this system.");
return True;
else
-- pidfile is obsolete, remove it.
DIR.Delete_File (pidfile);
return False;
end if;
exception
when others =>
-- pidfile contains garbage, remove it
DIR.Delete_File (pidfile);
return False;
end;
end if;
return False;
end already_running;
--------------------------------------------------------------------------------------------
-- create_pidfile
--------------------------------------------------------------------------------------------
procedure create_pidfile is
begin
FOP.create_pidfile (pidfile);
end create_pidfile;
--------------------------------------------------------------------------------------------
-- destroy_pidfile
--------------------------------------------------------------------------------------------
procedure destroy_pidfile is
begin
FOP.destroy_pidfile (pidfile);
end destroy_pidfile;
--------------------------------------------------------------------------------------------
-- previous_run_mounts_detected
--------------------------------------------------------------------------------------------
function previous_run_mounts_detected return Boolean is
begin
if REP.ravenadm_mounts_exist then
TIO.Put_Line ("Builder mounts detected; attempting to remove them automatically ...");
return True;
else
return False;
end if;
end previous_run_mounts_detected;
--------------------------------------------------------------------------------------------
-- previous_realfs_work_detected
--------------------------------------------------------------------------------------------
function previous_realfs_work_detected return Boolean is
begin
if REP.disk_workareas_exist then
TIO.Put_Line ("Old work directories detected; " &
"attempting to remove them automatically ...");
return True;
else
return False;
end if;
end previous_realfs_work_detected;
--------------------------------------------------------------------------------------------
-- old_mounts_successfully_removed
--------------------------------------------------------------------------------------------
function old_mounts_successfully_removed return Boolean is
begin
if REP.clear_existing_mounts then
TIO.Put_Line ("Dismounting successful!");
return True;
end if;
TIO.Put_Line ("The attempt failed. Check for stuck or ongoing processes and kill them.");
TIO.Put_Line ("After that try running ravenadm again or just manually unmount everything");
TIO.Put_Line ("that is still attached to " & HT.USS (PM.configuration.dir_buildbase));
return False;
end old_mounts_successfully_removed;
--------------------------------------------------------------------------------------------
-- old_realfs_work_successfully_removed
--------------------------------------------------------------------------------------------
function old_realfs_work_successfully_removed return Boolean is
begin
if REP.clear_existing_workareas then
TIO.Put_Line ("Directory removal successful!");
return True;
end if;
TIO.Put_Line ("The attempt to remove the work directories located at ");
TIO.Put_Line (HT.USS (PM.configuration.dir_buildbase) & " failed.");
TIO.Put_Line ("Please remove them manually before continuing.");
return False;
end old_realfs_work_successfully_removed;
--------------------------------------------------------------------------------------------
-- ravenexec_missing
--------------------------------------------------------------------------------------------
function ravenexec_missing return Boolean is
begin
if DIR.Exists (ravenexec) then
return False;
end if;
TIO.Put_Line (ravenexec & " missing!" & bailing);
return True;
end ravenexec_missing;
--------------------------------------------------------------------------------------------
-- launch_configure_menu
--------------------------------------------------------------------------------------------
procedure launch_configure_menu is
begin
Configure.launch_configure_menu;
end launch_configure_menu;
--------------------------------------------------------------------------------------------
-- locate
--------------------------------------------------------------------------------------------
procedure locate (candidate : String)
is
should_be : String := HT.USS (PM.configuration.dir_conspiracy) & "/bucket_" &
UTL.bucket (candidate) & LAT.Solidus & candidate;
begin
if candidate = "" then
TIO.Put_Line ("The locate command requires the port's name base as an argument");
return;
end if;
if DIR.Exists (should_be) then
TIO.Put_Line ("Found at " & should_be);
else
TIO.Put_Line ("Does not exist at " & should_be);
end if;
end locate;
--------------------------------------------------------------------------------------------
-- locate
--------------------------------------------------------------------------------------------
function slave_platform_determined return Boolean
is
base : String := HT.USS (PM.configuration.dir_sysroot) & "/usr/share/";
F1 : String := base & "OSRELEASE";
F2 : String := base & "OSMAJOR";
F3 : String := base & "OSVERSION";
F4 : String := base & "STDARCH";
begin
if not DIR.Exists (F1) or else
not DIR.Exists (F2) or else
not DIR.Exists (F3) or else
not DIR.Exists (F4)
then
TIO.Put_Line ("Platform type could not be determined (sysroot F1-F4 missing)");
return False;
end if;
sysrootver.release := HT.SUS (FOP.head_n1 (F1));
sysrootver.major := HT.SUS (FOP.head_n1 (F2));
sysrootver.version := HT.SUS (FOP.head_n1 (F3));
declare
candidate : String := FOP.head_n1 (F4);
begin
if UTL.valid_cpu_arch (candidate) then
sysrootver.arch := UTL.convert_cpu_arch (candidate);
else
TIO.Put_Line ("Platform type could not be determined (STDARCH conversion failed)");
return False;
end if;
end;
return True;
end slave_platform_determined;
--------------------------------------------------------------------------------------------
-- fully_scan_ports_tree
--------------------------------------------------------------------------------------------
function fully_scan_ports_tree return Boolean
is
successful : Boolean := SCN.scan_entire_ports_tree (sysrootver);
begin
if successful then
SCN.set_build_priority;
if PortScan.queue_is_empty then
successful := False;
TIO.Put_Line ("There are no valid ports to build." & bailing);
end if;
else
if Signals.graceful_shutdown_requested then
TIO.Put_Line (shutreq);
else
TIO.Put_Line ("Failed to scan ports tree " & bailing);
end if;
end if;
return successful;
end fully_scan_ports_tree;
--------------------------------------------------------------------------------------------
-- scan_stack_of_single_ports
--------------------------------------------------------------------------------------------
function scan_stack_of_single_ports (always_build : Boolean) return Boolean
is
successful : Boolean := SCN.scan_provided_list_of_ports (always_build, sysrootver);
begin
if successful then
SCN.set_build_priority;
if PortScan.queue_is_empty then
successful := False;
TIO.Put_Line ("There are no valid ports to build." & bailing);
end if;
else
if Signals.graceful_shutdown_requested then
TIO.Put_Line (shutreq);
end if;
end if;
return successful;
end scan_stack_of_single_ports;
--------------------------------------------------------------------------------------------
-- sanity_check_then_prefail
--------------------------------------------------------------------------------------------
function sanity_check_then_prefail
(delete_first : Boolean := False;
dry_run : Boolean := False) return Boolean
is
ptid : PortScan.port_id;
num_skipped : Natural;
block_remote : Boolean := True;
explicit_ravensys : Boolean := False;
update_external_repo : constant String := host_pkg8 & " update --quiet --repository ";
no_packages : constant String := "No prebuilt packages will be used as a result.";
begin
LOG.set_overall_start_time (CAL.Clock);
if delete_first and then not dry_run then
OPS.delete_existing_packages_of_ports_list;
end if;
if PM.configuration.defer_prebuilt then
-- Before any remote operations, find the external repo
if OPS.located_external_repository then
block_remote := False;
-- We're going to use prebuilt packages if available, so let's
-- prepare for that case by updating the external repository
TIO.Put ("Stand by, updating external repository catalogs ... ");
if Unix.external_command (update_external_repo & OPS.top_external_repository) then
TIO.Put_Line ("done.");
else
TIO.Put_Line ("Failed!");
TIO.Put_Line ("The external repository could not be updated.");
TIO.Put_Line (no_packages);
block_remote := True;
end if;
else
TIO.Put_Line ("The external repository does not seem to be configured.");
TIO.Put_Line (no_packages);
end if;
end if;
if delete_first then
explicit_ravensys := PortScan.jail_env_port_specified;
end if;
OPS.run_start_hook;
OPS.limited_sanity_check (repository => HT.USS (PM.configuration.dir_repository),
dry_run => dry_run,
rebuild_compiler => explicit_ravensys,
suppress_remote => block_remote);
LOG.set_build_counters (PortScan.queue_length, 0, 0, 0, 0);
if dry_run then
return True;
end if;
if Signals.graceful_shutdown_requested then
TIO.Put_Line (shutreq);
return False;
end if;
OPS.delete_existing_web_history_files;
LOG.start_logging (PortScan.total);
LOG.start_logging (PortScan.ignored);
LOG.start_logging (PortScan.skipped);
LOG.start_logging (PortScan.success);
LOG.start_logging (PortScan.failure);
loop
ptid := OPS.next_ignored_port;
exit when not PortScan.valid_port_id (ptid);
exit when Signals.graceful_shutdown_requested;
LOG.increment_build_counter (PortScan.ignored);
LOG.scribe (PortScan.total, LOG.elapsed_now & " " & PortScan.get_port_variant (ptid) &
" has been ignored: " & PortScan.ignore_reason (ptid), False);
LOG.scribe (PortScan.ignored, LOG.elapsed_now & " " & PortScan.get_port_variant (ptid) &
" ## reason: " & PortScan.ignore_reason (ptid), False);
OPS.cascade_failed_build (id => ptid,
numskipped => num_skipped);
OPS.record_history_ignored (elapsed => LOG.elapsed_now,
bucket => PortScan.get_bucket (ptid),
origin => PortScan.get_port_variant (ptid),
reason => PortScan.ignore_reason (ptid),
skips => num_skipped);
LOG.increment_build_counter (PortScan.skipped, num_skipped);
end loop;
LOG.stop_logging (PortScan.ignored);
LOG.scribe (PortScan.total, LOG.elapsed_now & " Sanity check complete. "
& "Ports remaining to build:" & PortScan.queue_length'Img, True);
if Signals.graceful_shutdown_requested then
TIO.Put_Line (shutreq);
else
if OPS.integrity_intact then
return True;
end if;
end if;
-- If here, we either got control-C or failed integrity check
if not Signals.graceful_shutdown_requested then
TIO.Put_Line ("Queue integrity lost! " & bailing);
end if;
LOG.stop_logging (PortScan.total);
LOG.stop_logging (PortScan.skipped);
LOG.stop_logging (PortScan.success);
LOG.stop_logging (PortScan.failure);
return False;
end sanity_check_then_prefail;
--------------------------------------------------------------------------------------------
-- perform_bulk_run
--------------------------------------------------------------------------------------------
procedure perform_bulk_run (testmode : Boolean)
is
num_builders : constant builders := PM.configuration.num_builders;
show_tally : Boolean := True;
begin
if PortScan.queue_is_empty then
TIO.Put_Line ("After inspection, it has been determined that there are no packages that");
TIO.Put_Line ("require rebuilding; the task is therefore complete.");
show_tally := False;
else
REP.initialize (testmode);
CYC.initialize (testmode);
OPS.initialize_web_report (num_builders);
OPS.initialize_display (num_builders);
OPS.parallel_bulk_run (num_builders, sysrootver);
REP.finalize;
end if;
LOG.set_overall_complete (CAL.Clock);
LOG.stop_logging (PortScan.total);
LOG.stop_logging (PortScan.success);
LOG.stop_logging (PortScan.failure);
LOG.stop_logging (PortScan.skipped);
if show_tally then
TIO.Put_Line (LAT.LF & LAT.LF);
TIO.Put_Line ("The task is complete. Final tally:");
TIO.Put_Line ("Initial queue size:" & LOG.port_counter_value (PortScan.total)'Img);
TIO.Put_Line (" packages built:" & LOG.port_counter_value (PortScan.success)'Img);
TIO.Put_Line (" ignored:" & LOG.port_counter_value (PortScan.ignored)'Img);
TIO.Put_Line (" skipped:" & LOG.port_counter_value (PortScan.skipped)'Img);
TIO.Put_Line (" failed:" & LOG.port_counter_value (PortScan.failure)'Img);
TIO.Put_Line ("");
TIO.Put_Line (LOG.bulk_run_duration);
TIO.Put_Line ("The build logs can be found at: " &
HT.USS (PM.configuration.dir_logs) & "/logs");
end if;
end perform_bulk_run;
--------------------------------------------------------------------------------------------
-- store_origins
--------------------------------------------------------------------------------------------
function store_origins (start_from : Positive) return Boolean
is
-- format is <namebase>:<variant>
begin
if CLI.Argument_Count < 2 then
TIO.Put_Line ("This command requires a list of one or more port origins.");
return False;
end if;
all_stdvar := True;
if CLI.Argument_Count = 2 then
-- Check if this is a file
declare
potential_file : String renames CLI.Argument (2);
use type DIR.File_Kind;
begin
if DIR.Exists (potential_file) and then
DIR.Kind (potential_file) = DIR.Ordinary_File
then
return valid_origin_file (potential_file);
end if;
end;
end if;
for k in start_from .. CLI.Argument_Count loop
declare
Argk : constant String := CLI.Argument (k);
bad_namebase : Boolean;
bad_format : Boolean;
add_standard : Boolean;
is_stdvar : Boolean;
begin
if valid_origin (Argk, bad_namebase, bad_format, add_standard, is_stdvar) then
if add_standard then
PortScan.insert_into_portlist (Argk & LAT.Colon & variant_standard);
else
PortScan.insert_into_portlist (Argk);
end if;
if not is_stdvar then
all_stdvar := False;
end if;
else
if bad_format then
TIO.Put_Line (badformat & "'" & Argk & "'");
elsif bad_namebase then
TIO.Put_Line (badname & "'" & Argk & "'");
else
TIO.Put_Line (badvariant & "'" & Argk & "'");
end if;
return False;
end if;
end;
end loop;
return True;
end store_origins;
--------------------------------------------------------------------------------------------
-- valid_origin
--------------------------------------------------------------------------------------------
function valid_origin
(port_variant : String;
bad_namebase : out Boolean;
bad_format : out Boolean;
assume_std : out Boolean;
known_std : out Boolean) return Boolean
is
function variant_valid (fileloc : String; variant : String) return Boolean;
numcolons : constant Natural := HT.count_char (port_variant, LAT.Colon);
num_spaces : constant Natural := HT.count_char (port_variant, LAT.Space);
function variant_valid (fileloc : String; variant : String) return Boolean
is
contents : String := FOP.get_file_contents (fileloc);
variants : constant String := "VARIANTS=" & LAT.HT & LAT.HT;
single_LF : constant String (1 .. 1) := (1 => LAT.LF);
variantsvar : Natural := AS.Fixed.Index (contents, variants);
begin
if variantsvar = 0 then
return False;
end if;
declare
nextlf : Natural := AS.Fixed.Index (Source => contents,
Pattern => single_LF,
From => variantsvar);
special : String :=
HT.strip_excessive_spaces (contents (variantsvar + variants'Length .. nextlf - 1));
begin
if nextlf = 0 then
return False;
end if;
return
special = variant or else
(special'First + variant'Length <= special'Last and then
special (special'First .. special'First + variant'Length) = variant & " ") or else
(special'Last > variant'Length and then
special (special'Last - variant'Length .. special'Last) = " " & variant) or else
AS.Fixed.Index (special, " " & variant & " ") /= 0;
end;
end variant_valid;
begin
bad_namebase := True;
assume_std := False;
if num_spaces > 0 or else numcolons > 1 then
bad_format := True;
return False;
end if;
bad_format := False;
if numcolons = 1 then
declare
namebase : String := HT.part_1 (port_variant, ":");
variant : String := HT.part_2 (port_variant, ":");
bsheetname : String := "/bucket_" & UTL.bucket (namebase) & "/" & namebase;
bsheetc : String := HT.USS (PM.configuration.dir_conspiracy) & bsheetname;
bsheetu : String := HT.USS (PM.configuration.dir_unkindness) & bsheetname;
begin
known_std := (variant = variant_standard);
if DIR.Exists (bsheetu) then
bad_namebase := False;
return variant_valid (bsheetu, variant);
elsif DIR.Exists (bsheetc) then
bad_namebase := False;
return variant_valid (bsheetc, variant);
else
return False;
end if;
end;
else
declare
bsheetname : String := "/bucket_" & UTL.bucket (port_variant) & "/" & port_variant;
bsheetc : String := HT.USS (PM.configuration.dir_conspiracy) & bsheetname;
bsheetu : String := HT.USS (PM.configuration.dir_unkindness) & bsheetname;
begin
assume_std := True;
known_std := True;
if DIR.Exists (bsheetu) then
bad_namebase := False;
return variant_valid (bsheetu, variant_standard);
elsif DIR.Exists (bsheetc) then
bad_namebase := False;
return variant_valid (bsheetc, variant_standard);
else
return False;
end if;
end;
end if;
end valid_origin;
--------------------------------------------------------------------------------------------
-- valid_origin_file
--------------------------------------------------------------------------------------------
function valid_origin_file (regular_file : String) return Boolean
is
origin_list : constant String := FOP.get_file_contents (regular_file);
markers : HT.Line_Markers;
good : Boolean := True;
total : Natural := 0;
begin
HT.initialize_markers (origin_list, markers);
loop
exit when not HT.next_line_present (origin_list, markers);
declare
line : constant String := HT.extract_line (origin_list, markers);
bad_namebase : Boolean;
bad_format : Boolean;
add_standard : Boolean;
is_stdvar : Boolean;
begin
if not HT.IsBlank (line) then
if valid_origin (line, bad_namebase, bad_format, add_standard, is_stdvar) then
if add_standard then
PortScan.insert_into_portlist (line & LAT.Colon & variant_standard);
else
PortScan.insert_into_portlist (line);
end if;
if not is_stdvar then
all_stdvar := False;
end if;
total := total + 1;
else
if bad_format then
TIO.Put_Line (badformat & "'" & line & "'");
elsif bad_namebase then
TIO.Put_Line (badname & "'" & line & "'");
else
TIO.Put_Line (badvariant & "'" & line & "'");
end if;
good := False;
exit;
end if;
end if;
end;
end loop;
return (total > 0) and then good;
end valid_origin_file;
--------------------------------------------------------------------------------------------
-- print_spec_template
--------------------------------------------------------------------------------------------
procedure print_spec_template (save_command : String)
is
save_here : constant Boolean := (save_command = "save");
begin
PSB.print_specification_template (save_here);
end print_spec_template;
--------------------------------------------------------------------------------------------
-- generate_distinfo
--------------------------------------------------------------------------------------------
procedure generate_distinfo
is
specfile : constant String := "specification";
portloc : String := HT.USS (PM.configuration.dir_buildbase) & ss_base & "/port";
makefile : String := portloc & "/Makefile";
successful : Boolean;
specification : Port_Specification.Portspecs;
begin
if not DIR.Exists (specfile) then
TIO.Put_Line ("No specification file found in current directory.");
return;
end if;
REP.initialize (testmode => False);
REP.launch_slave (scan_slave);
PAR.parse_specification_file (dossier => specfile,
specification => specification,
opsys_focus => platform_type,
arch_focus => x86_64,
success => successful,
stop_at_targets => True,
extraction_dir => portloc);
if not successful then
TIO.Put_Line (errprefix & "Failed to parse " & specfile);
TIO.Put_Line (PAR.get_parse_error);
goto endzone;
end if;
declare
variant : String := specification.get_list_item (Port_Specification.sp_variants, 1);
begin
PSM.generator (specs => specification,
variant => variant,
opsys => platform_type,
arch => x86_64,
output_file => makefile);
end;
CYC.run_makesum (scan_slave);
<<endzone>>
REP.destroy_slave (scan_slave);
REP.finalize;
end generate_distinfo;
--------------------------------------------------------------------------------------------
-- bulk_run_then_interact_with_final_port
--------------------------------------------------------------------------------------------
procedure bulk_run_then_interact_with_final_port
is
brkphase : constant String := Unix.env_variable_value (brkname);
buildres : Boolean;
ptid : PortScan.port_id := OPS.unlist_first_port;
pvname : constant String := PortScan.get_port_variant (ptid);
use_proc : constant Boolean := PortScan.requires_procfs (ptid);
begin
if not PortScan.valid_port_id (ptid) then
TIO.Put_Line ("Failed to remove first port from list." & bailing);
return;
end if;
perform_bulk_run (testmode => True);
if Signals.graceful_shutdown_requested then
return;
end if;
if LOG.port_counter_value (PortScan.ignored) > 0 or else
LOG.port_counter_value (PortScan.skipped) > 0 or else
LOG.port_counter_value (PortScan.failure) > 0
then
TIO.Put_Line ("It appears a prerequisite failed, so the interactive build of");
TIO.Put_Line (pvname & " has been cancelled.");
return;
end if;
TIO.Put_Line ("Starting interactive build of " & pvname);
TIO.Put_Line ("Stand by, building up to the point requested ...");
REP.initialize (testmode => True);
CYC.initialize (test_mode => True);
REP.launch_slave (scan_slave, use_proc);
Unix.cone_of_silence (deploy => False);
buildres := OPS.build_subpackages (builder => scan_slave,
sequence_id => ptid,
sysrootver => sysrootver,
interactive => True,
enterafter => brkphase);
REP.destroy_slave (scan_slave, use_proc);
REP.finalize;
end bulk_run_then_interact_with_final_port;
--------------------------------------------------------------------------------------------
-- interact_with_single_builder
--------------------------------------------------------------------------------------------
function interact_with_single_builder return Boolean
is
EA_defined : constant Boolean := Unix.env_variable_defined (brkname);
begin
if PortScan.build_request_length /= 1 then
return False;
end if;
if not EA_defined then
return False;
end if;
return CYC.valid_test_phase (Unix.env_variable_value (brkname));
end interact_with_single_builder;
--------------------------------------------------------------------------------------------
-- install_compiler_packages
--------------------------------------------------------------------------------------------
function install_compiler_packages return Boolean
is
function get_package_name (subpackage : String; use_prev : Boolean) return String;
function package_copy (subpackage : String) return Boolean;
binutils : constant String := "binutils";
function get_package_name (subpackage : String; use_prev : Boolean) return String is
begin
if use_prev then
if subpackage = binutils then
return "binutils-single-ravensys-" & previous_binutils & arc_ext;
else
return default_compiler & LAT.Hyphen & subpackage & LAT.Hyphen &
variant_standard & LAT.Hyphen & previous_compiler & arc_ext;
end if;
else
if subpackage = binutils then
return "binutils-single-ravensys-" & binutils_version & arc_ext;
else
return default_compiler & LAT.Hyphen & subpackage & LAT.Hyphen &
variant_standard & LAT.Hyphen & compiler_version & arc_ext;
end if;
end if;
end get_package_name;
function package_copy (subpackage : String) return Boolean
is
pkgname : constant String := get_package_name (subpackage, False);
tool_path : constant String := HT.USS (PM.configuration.dir_toolchain) & "/share/";
src_path : constant String := tool_path & pkgname;
dest_dir : constant String := HT.USS (PM.configuration.dir_repository);
dest_path : constant String := dest_dir & LAT.Solidus & pkgname;
begin
if not DIR.Exists (dest_path) then
if DIR.Exists (src_path) then
if not DIR.Exists (dest_dir) then
DIR.Create_Directory (dest_dir);
end if;
DIR.Copy_File (Source_Name => src_path, Target_Name => dest_path);
else
-- We didn't find the current binutils or compiler in the system root storage.
-- It's likely that we're in a transition with a new version of binutils or
-- gcc available, and a new system root needs to be generated. Assuming this,
-- try to copy the previously known compiler/binutils under the new name so
-- that package building doesn't break.
declare
old_pkg : constant String := get_package_name (subpackage, True);
old_path : constant String := tool_path & old_pkg;
begin
if DIR.Exists (old_path) then
if not DIR.Exists (dest_dir) then
DIR.Create_Directory (dest_dir);
end if;
DIR.Copy_File (Source_Name => old_path, Target_Name => dest_path);
else
TIO.Put_Line ("Compiler package " & src_path & " does not exist, nor does");
TIO.Put_Line ("Compiler package " & old_path & " exist.");
return False;
end if;
end;
end if;
end if;
return True;
exception
when DIR.Use_Error =>
TIO.Put_Line ("Failed to create " & dest_dir & " (repository directory)");
return False;
when others =>
TIO.Put_Line ("Failed to copy " & src_path & " to " & dest_path);
return False;
end package_copy;
begin
return
package_copy (binutils) and then
package_copy ("ada_run") and then
package_copy ("compilers") and then
package_copy ("complete") and then
package_copy ("cxx_run") and then
package_copy ("fortran_run") and then
package_copy ("infopages") and then
package_copy ("libs");
end install_compiler_packages;
--------------------------------------------------------------------------------------------
-- generate_ports_index
--------------------------------------------------------------------------------------------
procedure generate_ports_index is
begin
PortScan.Scan.generate_conspiracy_index (sysrootver);
end generate_ports_index;
--------------------------------------------------------------------------------------------
-- display_results_of_dry_run
--------------------------------------------------------------------------------------------
procedure display_results_of_dry_run is
begin
PortScan.Scan.display_results_of_dry_run;
end display_results_of_dry_run;
--------------------------------------------------------------------------------------------
-- purge_distfiles
--------------------------------------------------------------------------------------------
procedure purge_distfiles is
begin
if PortScan.Scan.gather_distfile_set (sysrootver)
then
PortScan.Scan.purge_obsolete_distfiles;
end if;
end purge_distfiles;
--------------------------------------------------------------------------------------------
-- change_options
--------------------------------------------------------------------------------------------
procedure change_options
is
number_ports : constant Natural := PortScan.build_request_length;
issues : HT.Text;
begin
-- First confirm all given origins are the standard variants
if not all_stdvar then
TIO.Put_Line ("User error: Only standard variants of ports have configurable options");
return;
end if;
for x in 1 .. number_ports loop
declare
specification : Port_Specification.Portspecs;
successful : Boolean;
buildsheet : constant String := PortScan.get_buildsheet_from_origin_list (x);
begin
OPS.parse_and_transform_buildsheet (specification => specification,
successful => successful,
buildsheet => buildsheet,
variant => variant_standard,
portloc => "",
excl_targets => True,
avoid_dialog => True,
for_webpage => False,
sysrootver => sysrootver);
if not specification.standard_options_present then
HT.SU.Append (issues, "User error: The " & specification.get_namebase &
" has no options to configure." & LAT.LF);
else
exit when not OPT.launch_dialog (specification);
end if;
end;
end loop;
if not HT.IsBlank (issues) then
TIO.Put (HT.USS (issues));
end if;
end change_options;
--------------------------------------------------------------------------------------------
-- check_ravenports_version
--------------------------------------------------------------------------------------------
procedure check_ravenports_version is
begin
Ravenports.check_version_available;
end check_ravenports_version;
--------------------------------------------------------------------------------------------
-- update_to_latest_ravenports
--------------------------------------------------------------------------------------------
procedure update_to_latest_ravenports is
begin
Ravenports.retrieve_latest_ravenports;
end update_to_latest_ravenports;
--------------------------------------------------------------------------------------------
-- generate_repository
--------------------------------------------------------------------------------------------
procedure generate_repository is
begin
if fully_scan_ports_tree then
Repository.rebuild_local_respository (remove_invalid_packages => True);
end if;
end generate_repository;
--------------------------------------------------------------------------------------------
-- generate_repository
--------------------------------------------------------------------------------------------
procedure check_that_ravenadm_is_modern_enough
is
raverreq : constant String := HT.USS (PM.configuration.dir_conspiracy) & "/Mk/Misc/raverreq";
begin
if not DIR.Exists (raverreq) then
return;
end if;
declare
filecon : constant String := FOP.get_file_contents (raverreq);
ravenadm_ver : constant Integer :=
Integer'Value (raven_version_major) * 100 +
Integer'Value (raven_version_minor);
required_ver : constant Integer := Integer'Value (HT.first_line (filecon));
stars : constant String (1 .. 51) := (others => '*');
Ch : Character;
begin
if ravenadm_ver < required_ver then
TIO.Put_Line
(LAT.LF & stars & LAT.LF &
"*** Please upgrade ravenadm as soon as possible ***" &
LAT.LF & stars & LAT.LF & LAT.LF &
"Either build and install ravenadm, or upgrade the ravenports package" & LAT.LF &
"This version of ravenadm will not recognize all directives in some ports.");
if Unix.env_variable_defined ("TERM") then
TIO.Put ("Press any key to acknowledge:");
Ada.Text_IO.Get_Immediate (Ch);
TIO.Put_Line ("");
end if;
end if;
end;
exception
when others =>
TIO.Put_Line ("check_that_ravenadm_is_modern_enough: exception");
end check_that_ravenadm_is_modern_enough;
--------------------------------------------------------------------------------------------
-- generate_website
--------------------------------------------------------------------------------------------
procedure generate_website
is
www_site : constant String := HT.USS (PM.configuration.dir_profile) & "/www";
begin
if not DIR.Exists (www_site) then
DIR.Create_Path (www_site);
end if;
if SCN.generate_entire_website (www_site, sysrootver) then
TIO.Put_Line ("The web site generation is complete.");
else
TIO.Put_Line ("The web site generation was not entirely successful.");
end if;
end generate_website;
end Pilot;
|
damaki/libkeccak | Ada | 3,072 | ads | -------------------------------------------------------------------------------
-- Copyright (c) 2019, Daniel King
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * The name of the copyright holder may not be used to endorse or promote
-- Products derived from this software without specific prior written
-- permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with Keccak.Generic_Duplex;
with Keccak.Generic_Sponge;
with Keccak.Padding;
pragma Elaborate_All (Keccak.Generic_Duplex);
pragma Elaborate_All (Keccak.Generic_Sponge);
-- @summary
-- Instantiation of Keccak-p[100,12], with a Sponge and Duplex built on top of it.
package Keccak.Keccak_100.Rounds_12
with SPARK_Mode => On
is
procedure Permute is new KeccakF_100_Permutation.Permute
(Num_Rounds => 12);
package Sponge is new Keccak.Generic_Sponge
(State_Size_Bits => KeccakF_100.State_Size_Bits,
State_Type => State,
Init_State => KeccakF_100.Init,
Permute => Permute,
XOR_Bits_Into_State => KeccakF_100_Lanes.XOR_Bits_Into_State,
Extract_Data => KeccakF_100_Lanes.Extract_Bytes,
Pad => Keccak.Padding.Pad101_Multi_Blocks);
package Duplex is new Keccak.Generic_Duplex
(State_Size_Bits => KeccakF_100.State_Size_Bits,
State_Type => State,
Init_State => KeccakF_100.Init,
Permute => Permute,
XOR_Bits_Into_State => KeccakF_100_Lanes.XOR_Bits_Into_State,
Extract_Bits => KeccakF_100_Lanes.Extract_Bits,
Pad => Keccak.Padding.Pad101_Single_Block,
Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits);
end Keccak.Keccak_100.Rounds_12;
|
sharkdp/bat | Ada | 33,355 | adb | [38;2;230;219;116mwith Chests.Ring_Buffers;[0m
[38;2;230;219;116mwith USB.Device.HID.Keyboard;[0m
[38;2;249;38;114mpackage[0m[38;2;248;248;242m [0m[38;2;249;38;114mbody[0m[38;2;248;248;242m [0m[38;2;166;226;46mClick[0m[38;2;248;248;242m [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m--------------[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m DEBOUNCE --[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m--------------[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Ideally, in a separate package.[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m should be [], but not fixed yet in GCC 11.[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCurrent_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Matrix := [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => False]];[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNew_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Matrix := [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => False]];[0m
[38;2;249;38;114m [0m[38;2;166;226;46mSince[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Nb_Bounce : Natural := 5;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mUpdate[0m[38;2;248;248;242m (NewS : Key_Matrix) [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Boolean [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m The new state is the same as the current stable state => Do nothing.[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Current_Status = NewS [0m[38;2;249;38;114mthen[0m
[38;2;249;38;114m [0m[38;2;166;226;46mSince[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m False;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m New_Status /= NewS [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m The new state differs from the previous[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m new state (bouncing) => reset[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNew_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= NewS;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mSince[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114melse[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m The new state hasn't changed since last[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m update => towards stabilization.[0m
[38;2;249;38;114m [0m[38;2;166;226;46mSince[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Since + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Since > Nb_Bounce [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;249;38;114mdeclare[0m
[38;2;249;38;114m [0m[38;2;166;226;46mTmp[0m[38;2;249;38;114m :[0m[38;2;248;248;242m [0m[38;2;249;38;114mconstant[0m[38;2;248;248;242m Key_Matrix := Current_Status;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m New state has been stable enough.[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Latch it and notifies caller.[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCurrent_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= New_Status;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNew_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Tmp;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mSince[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m True;[0m
[38;2;248;248;242m [0m[38;2;249;38;114melse[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Not there yet[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m False;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mUpdate[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Matrix[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Could use := []; but GNAT 12 has a bug (fixed in upcoming 13)[0m
[38;2;249;38;114m [0m[38;2;166;226;46mRead_Status[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Matrix := [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => False]];[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Events[0m[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Events [0m[38;2;249;38;114mis[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNum_Evt[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNew_S[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Matrix [0m[38;2;249;38;114mrenames[0m[38;2;248;248;242m Read_Status;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m Get_Matrix;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Update (New_S) [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m I [0m[38;2;249;38;114min[0m[38;2;248;248;242m Current_Status'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m ([0m[38;2;190;132;255m1[0m[38;2;248;248;242m) [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m J [0m[38;2;249;38;114min[0m[38;2;248;248;242m Current_Status'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m ([0m[38;2;190;132;255m2[0m[38;2;248;248;242m) [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m ([0m[38;2;249;38;114mnot[0m[38;2;248;248;242m New_Status (I, J) [0m[38;2;249;38;114mand[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m[38;2;248;248;242m Current_Status (I, J))[0m
[38;2;248;248;242m [0m[38;2;249;38;114mor[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m (New_Status (I, J) [0m[38;2;249;38;114mand[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m[38;2;248;248;242m [0m[38;2;249;38;114mnot[0m[38;2;248;248;242m Current_Status (I, J))[0m
[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;249;38;114m [0m[38;2;166;226;46mNum_Evt[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Num_Evt + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mdeclare[0m
[38;2;249;38;114m [0m[38;2;166;226;46mEvts[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Events (Natural [0m[38;2;249;38;114mrange[0m[38;2;248;248;242m [0m[38;2;190;132;255m1[0m[38;2;248;248;242m .. Num_Evt);[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCursor[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural [0m[38;2;249;38;114mrange[0m[38;2;248;248;242m [0m[38;2;190;132;255m1[0m[38;2;248;248;242m .. Num_Evt + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m := [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m I [0m[38;2;249;38;114min[0m[38;2;248;248;242m Current_Status'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m ([0m[38;2;190;132;255m1[0m[38;2;248;248;242m) [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m J [0m[38;2;249;38;114min[0m[38;2;248;248;242m Current_Status'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m ([0m[38;2;190;132;255m2[0m[38;2;248;248;242m) [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m [0m[38;2;249;38;114mnot[0m[38;2;248;248;242m New_Status (I, J)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mand[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m[38;2;248;248;242m Current_Status (I, J)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Pressing I, J[0m
[38;2;248;248;242m Evts (Cursor) := [[0m
[38;2;248;248;242m Evt => Press,[0m
[38;2;248;248;242m Col => I,[0m
[38;2;248;248;242m Row => J[0m
[38;2;248;248;242m ];[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCursor[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Cursor + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114melsif[0m[38;2;248;248;242m New_Status (I, J)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mand[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m[38;2;248;248;242m [0m[38;2;249;38;114mnot[0m[38;2;248;248;242m Current_Status (I, J)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Release I, J[0m
[38;2;248;248;242m Evts (Cursor) := [[0m
[38;2;248;248;242m Evt => Release,[0m
[38;2;248;248;242m Col => I,[0m
[38;2;248;248;242m Row => J[0m
[38;2;248;248;242m ];[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCursor[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Cursor + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Evts;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m [];[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Events[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Matrix[0m[38;2;248;248;242m [0m[38;2;249;38;114mis[0m[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m return Key_Matrix is[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m Row [0m[38;2;249;38;114min[0m[38;2;248;248;242m Keys.Rows'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m Keys.Rows (Row).Clear;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m Col [0m[38;2;249;38;114min[0m[38;2;248;248;242m Keys.Cols'[0m[38;2;249;38;114mRange[0m[38;2;248;248;242m [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m Read_Status (Col, Row) := [0m[38;2;249;38;114mnot[0m[38;2;248;248;242m Keys.Cols (Col).Set;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m Keys.Rows (Row).Set;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Matrix[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m End of DEBOUNCE[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m------------[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Layout --[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m------------[0m
[38;2;248;248;242m [0m[38;2;249;38;114mpackage[0m[38;2;248;248;242m [0m[38;2;166;226;46mEvents_Ring_Buffers[0m[38;2;248;248;242m [0m[38;2;249;38;114mis[0m[38;2;248;248;242m [0m[38;2;249;38;114mnew[0m[38;2;248;248;242m Chests.Ring_Buffers[0m
[38;2;248;248;242m (Element_Type => Event,[0m
[38;2;248;248;242m Capacity => [0m[38;2;190;132;255m16[0m[38;2;248;248;242m);[0m
[38;2;249;38;114m [0m[38;2;166;226;46mQueued_Events[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Events_Ring_Buffers.Ring_Buffer;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mtype[0m[38;2;248;248;242m Statet [0m[38;2;249;38;114mis[0m[38;2;248;248;242m (Normal_Key, Layer_Mod, None);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mtype[0m[38;2;248;248;242m State [0m[38;2;249;38;114mis[0m[38;2;248;248;242m [0m[38;2;249;38;114mrecord[0m
[38;2;249;38;114m [0m[38;2;166;226;46mTyp[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Statet;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCode[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Code_T;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mLayer_Value[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Col : ColR;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Row : RowR;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend record[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mtype[0m[38;2;248;248;242m State_Array [0m[38;2;249;38;114mis[0m[38;2;248;248;242m [0m[38;2;249;38;114marray[0m[38;2;248;248;242m (ColR, RowR) [0m[38;2;249;38;114mof[0m[38;2;248;248;242m State;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mStates[0m[38;2;249;38;114m :[0m[38;2;248;248;242m State_Array := [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => [[0m[38;2;249;38;114mothers[0m[38;2;248;248;242m => (Typ => None, Code => No, Layer_Value => [0m[38;2;190;132;255m0[0m[38;2;248;248;242m)]];[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mKw[0m[38;2;248;248;242m (Code : Key_Code_T) [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Action [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m (T => Key, C => Code, L => [0m[38;2;190;132;255m0[0m[38;2;248;248;242m);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mKw[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mLw[0m[38;2;248;248;242m (V : Natural) [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Action [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m (T => Layer, C => No, L => V);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mLw[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m FIXME: hardcoded max number of events[0m
[38;2;248;248;242m [0m[38;2;249;38;114msubtype[0m[38;2;248;248;242m Events_Range [0m[38;2;249;38;114mis[0m[38;2;248;248;242m Natural [0m[38;2;249;38;114mrange[0m[38;2;248;248;242m [0m[38;2;190;132;255m0[0m[38;2;248;248;242m .. [0m[38;2;190;132;255m60[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mtype[0m[38;2;248;248;242m Array_Of_Reg_Events [0m[38;2;249;38;114mis[0m[38;2;248;248;242m [0m[38;2;249;38;114marray[0m[38;2;248;248;242m (Events_Range) [0m[38;2;249;38;114mof[0m[38;2;248;248;242m Event;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mStamp[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mRegister_Events[0m[38;2;248;248;242m (L : Layout; Es : Events) [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;249;38;114m [0m[38;2;166;226;46mStamp[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Stamp + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m Log ([0m[38;2;230;219;116m"[0m[38;2;230;219;116mReg events: [0m[38;2;230;219;116m"[0m[38;2;248;248;242m & Stamp'Image);[0m
[38;2;248;248;242m Log (Es'Length'Image);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m E [0m[38;2;249;38;114mof[0m[38;2;248;248;242m Es [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mdeclare[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Events_Ring_Buffers.Is_Full (Queued_Events) [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;249;38;114mraise[0m[38;2;248;248;242m Program_Error;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m Events_Ring_Buffers.Append (Queued_Events, E);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Log ("Reg'ed events:" & Events_Mark'Image);[0m
[38;2;248;248;242m Log ([0m[38;2;230;219;116m"[0m[38;2;230;219;116mReg'ed events:[0m[38;2;230;219;116m"[0m[38;2;248;248;242m & Events_Ring_Buffers.Length (Queued_Events)'Image);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mRegister_Events[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mRelease[0m[38;2;248;248;242m (Col: Colr; Row: Rowr) [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m States (Col, Row).Typ = None [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;249;38;114mraise[0m[38;2;248;248;242m Program_Error;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m States (Col, Row) := (Typ => None, Code => No, Layer_Value => [0m[38;2;190;132;255m0[0m[38;2;248;248;242m);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mRelease[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Current_Layer[0m[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Natural [0m[38;2;249;38;114mis[0m
[38;2;249;38;114m [0m[38;2;166;226;46mL[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m S [0m[38;2;249;38;114mof[0m[38;2;248;248;242m States [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m S.Typ = Layer_Mod [0m[38;2;249;38;114mthen[0m
[38;2;249;38;114m [0m[38;2;166;226;46mL[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= L + S.Layer_Value;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m L;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Current_Layer[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Tick the event.[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m Returns TRUE if it needs to stay in the queued events[0m
[38;2;248;248;242m [0m[38;2;117;113;94m--[0m[38;2;117;113;94m FALSE if the event has been consumed.[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mTick[0m[38;2;248;248;242m (L: Layout; E : [0m[38;2;249;38;114min[0m[38;2;248;248;242m [0m[38;2;249;38;114mout[0m[38;2;248;248;242m Event) [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Boolean [0m[38;2;249;38;114mis[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCurrent_Layer[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := Get_Current_Layer;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mA[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Action [0m[38;2;249;38;114mrenames[0m[38;2;248;248;242m L (Current_Layer, E.Row, E.Col);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mcase[0m[38;2;248;248;242m E.Evt [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m Press =>[0m
[38;2;248;248;242m [0m[38;2;249;38;114mcase[0m[38;2;248;248;242m A.T [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m Key =>[0m
[38;2;248;248;242m States (E.Col, E.Row) :=[0m
[38;2;248;248;242m (Typ => Normal_Key,[0m
[38;2;248;248;242m Code => A.C,[0m
[38;2;248;248;242m Layer_Value => [0m[38;2;190;132;255m0[0m[38;2;248;248;242m);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m Layer =>[0m
[38;2;248;248;242m States (E.Col, E.Row) := (Typ => Layer_Mod, Layer_Value => A.L, Code => No);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m [0m[38;2;249;38;114mothers[0m[38;2;248;248;242m =>[0m
[38;2;248;248;242m [0m[38;2;249;38;114mraise[0m[38;2;248;248;242m Program_Error;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend case[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m Release =>[0m
[38;2;248;248;242m Release (E.Col, E.Row);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend case[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m False;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mTick[0m[38;2;248;248;242m;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mLast_Was_Empty_Log[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Boolean := False;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mTick[0m[38;2;248;248;242m (L : Layout) [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m I [0m[38;2;249;38;114min[0m[38;2;248;248;242m [0m[38;2;190;132;255m1[0m[38;2;248;248;242m .. Events_Ring_Buffers.Length(Queued_Events) [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mdeclare[0m
[38;2;249;38;114m [0m[38;2;166;226;46mE[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Event := Events_Ring_Buffers.Last_Element (Queued_Events);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m Events_Ring_Buffers.Delete_Last (Queued_Events);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Tick (L, E) [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m Events_Ring_Buffers.Prepend (Queued_Events, E);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m [0m[38;2;249;38;114mnot[0m[38;2;248;248;242m Last_Was_Empty_Log [0m[38;2;249;38;114mor[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m Events_Ring_Buffers.Length(Queued_Events) /= [0m[38;2;190;132;255m0[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m Log ([0m[38;2;230;219;116m"[0m[38;2;230;219;116mEnd Tick layout, events: [0m[38;2;230;219;116m"[0m[38;2;248;248;242m & Events_Ring_Buffers.Length(Queued_Events)'Image);[0m
[38;2;249;38;114m [0m[38;2;166;226;46mLast_Was_Empty_Log[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Events_Ring_Buffers.Length(Queued_Events) = [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mTick[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Key_Codes[0m[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Key_Codes_T [0m[38;2;249;38;114mis[0m
[38;2;249;38;114m [0m[38;2;166;226;46mCodes[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Codes_T ([0m[38;2;190;132;255m0[0m[38;2;248;248;242m .. [0m[38;2;190;132;255m10[0m[38;2;248;248;242m);[0m
[38;2;249;38;114m [0m[38;2;166;226;46mWm[0m[38;2;249;38;114m:[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m S [0m[38;2;249;38;114mof[0m[38;2;248;248;242m States [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m S.Typ = Normal_Key [0m[38;2;249;38;114mand[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m (S.Code < LCtrl [0m[38;2;249;38;114mor[0m[38;2;248;248;242m [0m[38;2;249;38;114melse[0m[38;2;248;248;242m S.Code > RGui)[0m
[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m Codes (Wm) := S.Code;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mWm[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= Wm + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m Wm = [0m[38;2;190;132;255m0[0m[38;2;248;248;242m [0m[38;2;249;38;114mthen[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m [];[0m
[38;2;248;248;242m [0m[38;2;249;38;114melse[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Codes ([0m[38;2;190;132;255m0[0m[38;2;248;248;242m .. Wm - [0m[38;2;190;132;255m1[0m[38;2;248;248;242m);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Key_Codes[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfunction[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Modifiers[0m[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m Key_Modifiers [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114muse[0m[38;2;248;248;242m USB.Device.HID.Keyboard;[0m
[38;2;249;38;114m [0m[38;2;166;226;46mKM[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Key_Modifiers ([0m[38;2;190;132;255m1[0m[38;2;248;248;242m..[0m[38;2;190;132;255m8[0m[38;2;248;248;242m);[0m
[38;2;249;38;114m [0m[38;2;166;226;46mI[0m[38;2;249;38;114m :[0m[38;2;248;248;242m Natural := [0m[38;2;190;132;255m0[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m [0m[38;2;249;38;114mfor[0m[38;2;248;248;242m S [0m[38;2;249;38;114mof[0m[38;2;248;248;242m States [0m[38;2;249;38;114mloop[0m
[38;2;248;248;242m [0m[38;2;249;38;114mif[0m[38;2;248;248;242m S.Typ = Normal_Key [0m[38;2;249;38;114mthen[0m
[38;2;249;38;114m [0m[38;2;166;226;46mI[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= I + [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mcase[0m[38;2;248;248;242m S.Code [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m LCtrl =>[0m
[38;2;248;248;242m KM(I) := Ctrl_Left;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m RCtrl =>[0m
[38;2;248;248;242m KM(I) := Ctrl_Right;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m LShift =>[0m
[38;2;248;248;242m KM(I) := Shift_Left;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m RShift =>[0m
[38;2;248;248;242m KM(I) := Shift_Right;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m LAlt =>[0m
[38;2;248;248;242m KM(I) := Alt_Left;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m RAlt =>[0m
[38;2;248;248;242m KM(I) := Alt_Right;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m LGui =>[0m
[38;2;248;248;242m KM(I) := Meta_Left;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m RGui =>[0m
[38;2;248;248;242m KM(I) := Meta_Right;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mwhen[0m[38;2;248;248;242m [0m[38;2;249;38;114mothers[0m[38;2;248;248;242m =>[0m
[38;2;249;38;114m [0m[38;2;166;226;46mI[0m[38;2;249;38;114m :[0m[38;2;248;248;242m= I - [0m[38;2;190;132;255m1[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend case[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend if[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend loop[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mreturn[0m[38;2;248;248;242m KM ([0m[38;2;190;132;255m1[0m[38;2;248;248;242m..I);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mGet_Modifiers[0m[38;2;248;248;242m;[0m
[38;2;248;248;242m [0m[38;2;249;38;114mprocedure[0m[38;2;248;248;242m [0m[38;2;166;226;46mInit[0m[38;2;248;248;242m [0m[38;2;249;38;114mis[0m
[38;2;248;248;242m [0m[38;2;249;38;114mbegin[0m
[38;2;248;248;242m Events_Ring_Buffers.Clear (Queued_Events);[0m
[38;2;248;248;242m [0m[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mInit[0m[38;2;248;248;242m;[0m
[38;2;249;38;114mend[0m[38;2;248;248;242m [0m[38;2;166;226;46mClick[0m[38;2;248;248;242m;[0m
|
godunko/adawebpack | Ada | 3,410 | adb | ------------------------------------------------------------------------------
-- --
-- AdaWebPack --
-- --
------------------------------------------------------------------------------
-- Copyright © 2020-2021, Vadim Godunko --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
------------------------------------------------------------------------------
with WASM.Attributes;
with WASM.Objects.Attributes;
package body Web.HTML.Buttons is
------------------
-- Get_Disabled --
------------------
function Get_Disabled (Self : HTML_Button_Element'Class) return Boolean is
begin
return
WASM.Objects.Attributes.Get_Boolean (Self, WASM.Attributes.Disabled);
end Get_Disabled;
------------------
-- Set_Disabled --
------------------
procedure Set_Disabled
(Self : in out HTML_Button_Element'Class; To : Boolean) is
begin
WASM.Objects.Attributes.Set_Boolean (Self, WASM.Attributes.Disabled, To);
end Set_Disabled;
end Web.HTML.Buttons;
|
MinimSecure/unum-sdk | Ada | 954 | adb | -- Copyright 2007-2016 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Pck; use Pck;
procedure Foo is
C : Character := 'a';
WC : Wide_Character := 'b';
WWC : Wide_Wide_Character := 'c';
begin
Do_Nothing (C'Address); -- START
Do_Nothing (WC'Address);
Do_Nothing (WWC'Address);
end Foo;
|
reznikmm/matreshka | Ada | 5,412 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
-- An element is a constituent of a model. As such, it has the capability of
-- owning other elements.
------------------------------------------------------------------------------
limited with AMF.UML.Comments.Collections;
limited with AMF.UML.Elements.Collections;
package AMF.UML.Elements is
pragma Preelaborate;
type UML_Element is limited interface;
type UML_Element_Access is
access all UML_Element'Class;
for UML_Element_Access'Storage_Size use 0;
not overriding function Get_Owned_Comment
(Self : not null access constant UML_Element)
return AMF.UML.Comments.Collections.Set_Of_UML_Comment is abstract;
-- Getter of Element::ownedComment.
--
-- The Comments owned by this element.
not overriding function Get_Owned_Element
(Self : not null access constant UML_Element)
return AMF.UML.Elements.Collections.Set_Of_UML_Element is abstract;
-- Getter of Element::ownedElement.
--
-- The Elements owned by this element.
not overriding function Get_Owner
(Self : not null access constant UML_Element)
return AMF.UML.Elements.UML_Element_Access is abstract;
-- Getter of Element::owner.
--
-- The Element that owns this element.
not overriding function All_Owned_Elements
(Self : not null access constant UML_Element)
return AMF.UML.Elements.Collections.Set_Of_UML_Element is abstract;
-- Operation Element::allOwnedElements.
--
-- The query allOwnedElements() gives all of the direct and indirect owned
-- elements of an element.
not overriding function Must_Be_Owned
(Self : not null access constant UML_Element)
return Boolean is abstract;
-- Operation Element::mustBeOwned.
--
-- The query mustBeOwned() indicates whether elements of this type must
-- have an owner. Subclasses of Element that do not require an owner must
-- override this operation.
end AMF.UML.Elements;
|
persan/A-gst | Ada | 1,649 | ads | pragma Ada_2005;
pragma Style_Checks (Off);
pragma Warnings (Off);
with Interfaces.C; use Interfaces.C;
with glib;
with glib.Values;
with System;
with GLIB; -- with GStreamer.GST_Low_Level.glibconfig_h;
package GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtsp_gstrtspbase64_h is
-- GStreamer
-- * Copyright (C) <2007> Mike Smith <[email protected]>
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Library General Public
-- * License as published by the Free Software Foundation; either
-- * version 2 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- * Library General Public License for more details.
-- *
-- * You should have received a copy of the GNU Library General Public
-- * License along with this library; if not, write to the
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-- * Boston, MA 02111-1307, USA.
--
function gst_rtsp_base64_encode (data : access GLIB.gchar; len : GLIB.gsize) return access GLIB.gchar; -- gst/rtsp/gstrtspbase64.h:28
pragma Import (C, gst_rtsp_base64_encode, "gst_rtsp_base64_encode");
procedure gst_rtsp_base64_decode_ip (data : access GLIB.gchar; len : access GLIB.gsize); -- gst/rtsp/gstrtspbase64.h:32
pragma Import (C, gst_rtsp_base64_decode_ip, "gst_rtsp_base64_decode_ip");
end GStreamer.GST_Low_Level.gstreamer_0_10_gst_rtsp_gstrtspbase64_h;
|
charlesdaniels/libagar | Ada | 152 | adb | with Ada.Text_IO;
package body myatexit is
procedure atexit is
begin
Ada.Text_IO.Put_Line("myatexit callback...");
end atexit;
end myatexit;
|
sungyeon/drake | Ada | 412 | ads | pragma License (Unrestricted);
with Interfaces.C.Char_Pointers;
with Interfaces.C.Generic_Strings;
package Interfaces.C.Strings is
new Generic_Strings (
Character_Type => Character,
String_Type => String,
Element => char,
Element_Array => char_array,
Pointers => Char_Pointers,
To_C => To_char_array,
To_Ada => To_String);
pragma Preelaborate (Interfaces.C.Strings);
|
charlie5/cBound | Ada | 1,793 | ads | -- This file is generated by SWIG. Please do not modify by hand.
--
with Interfaces;
with swig;
with Interfaces.C;
with Interfaces.C.Pointers;
package xcb.xcb_glx_get_tex_genfv_reply_t is
-- Item
--
type Item is record
response_type : aliased Interfaces.Unsigned_8;
pad0 : aliased Interfaces.Unsigned_8;
sequence : aliased Interfaces.Unsigned_16;
length : aliased Interfaces.Unsigned_32;
pad1 : aliased swig.int8_t_Array (0 .. 3);
n : aliased Interfaces.Unsigned_32;
datum : aliased xcb.xcb_glx_float32_t;
pad2 : aliased swig.int8_t_Array (0 .. 11);
end record;
-- Item_Array
--
type Item_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_glx_get_tex_genfv_reply_t
.Item;
-- Pointer
--
package C_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_glx_get_tex_genfv_reply_t.Item,
Element_Array => xcb.xcb_glx_get_tex_genfv_reply_t.Item_Array,
Default_Terminator => (others => <>));
subtype Pointer is C_Pointers.Pointer;
-- Pointer_Array
--
type Pointer_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_glx_get_tex_genfv_reply_t
.Pointer;
-- Pointer_Pointer
--
package C_Pointer_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_glx_get_tex_genfv_reply_t.Pointer,
Element_Array => xcb.xcb_glx_get_tex_genfv_reply_t.Pointer_Array,
Default_Terminator => null);
subtype Pointer_Pointer is C_Pointer_Pointers.Pointer;
end xcb.xcb_glx_get_tex_genfv_reply_t;
|
zhmu/ananas | Ada | 5,191 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S I N P U T . D --
-- --
-- B o d y --
-- --
-- Copyright (C) 2002-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Debug; use Debug;
with Osint; use Osint;
with Osint.C; use Osint.C;
with Output; use Output;
with System.OS_Lib; use System.OS_Lib;
package body Sinput.D is
Dfile : Source_File_Index;
-- Index of currently active debug source file
------------------------
-- Close_Debug_Source --
------------------------
procedure Close_Debug_Source is
FD : File_Descriptor;
SFR : Source_File_Record renames Source_File.Table (Dfile);
Src : Source_Buffer_Ptr;
begin
Trim_Lines_Table (Dfile);
Close_Debug_File;
-- Now we need to read the file that we wrote and store it in memory for
-- subsequent access.
Read_Source_File
(SFR.Full_Debug_Name, SFR.Source_First, SFR.Source_Last, Src, FD);
SFR.Source_Text := Src;
pragma Assert (SFR.Source_Text'First = SFR.Source_First);
pragma Assert (SFR.Source_Text'Last = SFR.Source_Last);
end Close_Debug_Source;
-------------------------
-- Create_Debug_Source --
-------------------------
procedure Create_Debug_Source
(Source : Source_File_Index;
Loc : out Source_Ptr)
is
begin
Loc :=
((Source_File.Table (Source_File.Last).Source_Last + Source_Align) /
Source_Align) * Source_Align;
Source_File.Append (Source_File.Table (Source));
Dfile := Source_File.Last;
declare
S : Source_File_Record renames Source_File.Table (Dfile);
begin
S.Index := Dfile;
S.Full_Debug_Name := Create_Debug_File (S.File_Name);
S.Debug_Source_Name := Strip_Directory (S.Full_Debug_Name);
S.Source_Text := null;
S.Source_First := Loc;
S.Source_Last := Loc;
S.Lines_Table := null;
S.Last_Source_Line := 1;
-- Allocate lines table, guess that it needs to be three times bigger
-- than the original source (in number of lines).
Alloc_Line_Tables
(S, Int (Source_File.Table (Source).Last_Source_Line * 3));
S.Lines_Table (1) := Loc;
if Debug_Flag_L then
Write_Str ("Sinput.D.Create_Debug_Source: created source ");
Write_Int (Int (Dfile));
Write_Str (" for ");
Write_Str (Get_Name_String (S.Full_Debug_Name));
Write_Line ("");
end if;
end;
end Create_Debug_Source;
----------------------
-- Write_Debug_Line --
----------------------
procedure Write_Debug_Line (Str : String; Loc : in out Source_Ptr) is
S : Source_File_Record renames Source_File.Table (Dfile);
begin
-- Ignore write request if null line at start of file
if Str'Length = 0 and then Loc = S.Source_First then
return;
-- Here we write the line, compute the source location for the following
-- line, allocate its table entry, and update the source record entry.
else
Write_Debug_Info (Str (Str'First .. Str'Last - 1));
Loc := Loc - 1 + Source_Ptr (Str'Length + Debug_File_Eol_Length);
Add_Line_Tables_Entry (S, Loc);
S.Source_Last := Loc;
Set_Source_File_Index_Table (Dfile);
end if;
end Write_Debug_Line;
end Sinput.D;
|
DavJo-dotdotdot/Ada_Drivers_Library | Ada | 17,234 | ads | -- Copyright (c) 2010 - 2018, Nordic Semiconductor ASA
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without modification,
-- are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form, except as embedded into a Nordic
-- Semiconductor ASA integrated circuit in a product or a software update for
-- such product, must reproduce the above copyright notice, this list of
-- conditions and the following disclaimer in the documentation and/or other
-- materials provided with the distribution.
--
-- 3. Neither the name of Nordic Semiconductor ASA nor the names of its
-- contributors may be used to endorse or promote products derived from this
-- software without specific prior written permission.
--
-- 4. This software, with or without modification, must only be used with a
-- Nordic Semiconductor ASA integrated circuit.
--
-- 5. Any software provided in binary form under this license must not be reverse
-- engineered, decompiled, modified and/or disassembled.
--
-- THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
-- OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
-- OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
-- GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-- HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-- LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
-- This spec has been automatically generated from nrf52.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package NRF_SVD.GPIO is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Pin 0
type OUT_PIN0_Field is
(-- Pin driver is low
Low,
-- Pin driver is high
High)
with Size => 1;
for OUT_PIN0_Field use
(Low => 0,
High => 1);
-- OUT_PIN array
type OUT_PIN_Field_Array is array (0 .. 31) of OUT_PIN0_Field
with Component_Size => 1, Size => 32;
-- Write GPIO port
type OUT_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : OUT_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for OUT_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Pin 0
type OUTSET_PIN0_Field is
(-- Read: pin driver is low
Low,
-- Read: pin driver is high
High)
with Size => 1;
for OUTSET_PIN0_Field use
(Low => 0,
High => 1);
-- Pin 0
type OUTSET_PIN0_Field_1 is
(-- Reset value for the field
Outset_Pin0_Field_Reset,
-- Write: writing a '1' sets the pin high; writing a '0' has no effect
Set)
with Size => 1;
for OUTSET_PIN0_Field_1 use
(Outset_Pin0_Field_Reset => 0,
Set => 1);
-- OUTSET_PIN array
type OUTSET_PIN_Field_Array is array (0 .. 31) of OUTSET_PIN0_Field_1
with Component_Size => 1, Size => 32;
-- Set individual bits in GPIO port
type OUTSET_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : OUTSET_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for OUTSET_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Pin 0
type OUTCLR_PIN0_Field is
(-- Read: pin driver is low
Low,
-- Read: pin driver is high
High)
with Size => 1;
for OUTCLR_PIN0_Field use
(Low => 0,
High => 1);
-- Pin 0
type OUTCLR_PIN0_Field_1 is
(-- Reset value for the field
Outclr_Pin0_Field_Reset,
-- Write: writing a '1' sets the pin low; writing a '0' has no effect
Clear)
with Size => 1;
for OUTCLR_PIN0_Field_1 use
(Outclr_Pin0_Field_Reset => 0,
Clear => 1);
-- OUTCLR_PIN array
type OUTCLR_PIN_Field_Array is array (0 .. 31) of OUTCLR_PIN0_Field_1
with Component_Size => 1, Size => 32;
-- Clear individual bits in GPIO port
type OUTCLR_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : OUTCLR_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for OUTCLR_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Pin 0
type IN_PIN0_Field is
(-- Pin input is low
Low,
-- Pin input is high
High)
with Size => 1;
for IN_PIN0_Field use
(Low => 0,
High => 1);
-- IN_PIN array
type IN_PIN_Field_Array is array (0 .. 31) of IN_PIN0_Field
with Component_Size => 1, Size => 32;
-- Read GPIO port
type IN_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : IN_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for IN_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Pin 0
type DIR_PIN0_Field is
(-- Pin set as input
Input,
-- Pin set as output
Output)
with Size => 1;
for DIR_PIN0_Field use
(Input => 0,
Output => 1);
-- DIR_PIN array
type DIR_PIN_Field_Array is array (0 .. 31) of DIR_PIN0_Field
with Component_Size => 1, Size => 32;
-- Direction of GPIO pins
type DIR_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : DIR_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DIR_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Set as output pin 0
type DIRSET_PIN0_Field is
(-- Read: pin set as input
Input,
-- Read: pin set as output
Output)
with Size => 1;
for DIRSET_PIN0_Field use
(Input => 0,
Output => 1);
-- Set as output pin 0
type DIRSET_PIN0_Field_1 is
(-- Reset value for the field
Dirset_Pin0_Field_Reset,
-- Write: writing a '1' sets pin to output; writing a '0' has no effect
Set)
with Size => 1;
for DIRSET_PIN0_Field_1 use
(Dirset_Pin0_Field_Reset => 0,
Set => 1);
-- DIRSET_PIN array
type DIRSET_PIN_Field_Array is array (0 .. 31) of DIRSET_PIN0_Field_1
with Component_Size => 1, Size => 32;
-- DIR set register
type DIRSET_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : DIRSET_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DIRSET_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Set as input pin 0
type DIRCLR_PIN0_Field is
(-- Read: pin set as input
Input,
-- Read: pin set as output
Output)
with Size => 1;
for DIRCLR_PIN0_Field use
(Input => 0,
Output => 1);
-- Set as input pin 0
type DIRCLR_PIN0_Field_1 is
(-- Reset value for the field
Dirclr_Pin0_Field_Reset,
-- Write: writing a '1' sets pin to input; writing a '0' has no effect
Clear)
with Size => 1;
for DIRCLR_PIN0_Field_1 use
(Dirclr_Pin0_Field_Reset => 0,
Clear => 1);
-- DIRCLR_PIN array
type DIRCLR_PIN_Field_Array is array (0 .. 31) of DIRCLR_PIN0_Field_1
with Component_Size => 1, Size => 32;
-- DIR clear register
type DIRCLR_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : DIRCLR_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DIRCLR_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Status on whether PIN0 has met criteria set in PIN_CNF0.SENSE register.
-- Write '1' to clear.
type LATCH_PIN0_Field is
(-- Criteria has not been met
Notlatched,
-- Criteria has been met
Latched)
with Size => 1;
for LATCH_PIN0_Field use
(Notlatched => 0,
Latched => 1);
-- LATCH_PIN array
type LATCH_PIN_Field_Array is array (0 .. 31) of LATCH_PIN0_Field
with Component_Size => 1, Size => 32;
-- Latch register indicating what GPIO pins that have met the criteria set
-- in the PIN_CNF[n].SENSE registers
type LATCH_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- PIN as a value
Val : HAL.UInt32;
when True =>
-- PIN as an array
Arr : LATCH_PIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for LATCH_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Select between default DETECT signal behaviour and LDETECT mode
type DETECTMODE_DETECTMODE_Field is
(-- DETECT directly connected to PIN DETECT signals
Default,
-- Use the latched LDETECT behaviour
Ldetect)
with Size => 1;
for DETECTMODE_DETECTMODE_Field use
(Default => 0,
Ldetect => 1);
-- Select between default DETECT signal behaviour and LDETECT mode
type DETECTMODE_Register is record
-- Select between default DETECT signal behaviour and LDETECT mode
DETECTMODE : DETECTMODE_DETECTMODE_Field := NRF_SVD.GPIO.Default;
-- unspecified
Reserved_1_31 : HAL.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DETECTMODE_Register use record
DETECTMODE at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-- Pin direction. Same physical register as DIR register
type PIN_CNF_DIR_Field is
(-- Configure pin as an input pin
Input,
-- Configure pin as an output pin
Output)
with Size => 1;
for PIN_CNF_DIR_Field use
(Input => 0,
Output => 1);
-- Connect or disconnect input buffer
type PIN_CNF_INPUT_Field is
(-- Connect input buffer
Connect,
-- Disconnect input buffer
Disconnect)
with Size => 1;
for PIN_CNF_INPUT_Field use
(Connect => 0,
Disconnect => 1);
-- Pull configuration
type PIN_CNF_PULL_Field is
(-- No pull
Disabled,
-- Pull down on pin
Pulldown,
-- Pull up on pin
Pullup)
with Size => 2;
for PIN_CNF_PULL_Field use
(Disabled => 0,
Pulldown => 1,
Pullup => 3);
-- Drive configuration
type PIN_CNF_DRIVE_Field is
(-- Standard '0', standard '1'
S0S1,
-- High drive '0', standard '1'
H0S1,
-- Standard '0', high drive '1'
S0H1,
-- High drive '0', high 'drive '1''
H0H1,
-- Disconnect '0' standard '1' (normally used for wired-or connections)
D0S1,
-- Disconnect '0', high drive '1' (normally used for wired-or connections)
D0H1,
-- Standard '0'. disconnect '1' (normally used for wired-and connections)
S0D1,
-- High drive '0', disconnect '1' (normally used for wired-and connections)
H0D1)
with Size => 3;
for PIN_CNF_DRIVE_Field use
(S0S1 => 0,
H0S1 => 1,
S0H1 => 2,
H0H1 => 3,
D0S1 => 4,
D0H1 => 5,
S0D1 => 6,
H0D1 => 7);
-- Pin sensing mechanism
type PIN_CNF_SENSE_Field is
(-- Disabled
Disabled,
-- Sense for high level
High,
-- Sense for low level
Low)
with Size => 2;
for PIN_CNF_SENSE_Field use
(Disabled => 0,
High => 2,
Low => 3);
-- Description collection[0]: Configuration of GPIO pins
type PIN_CNF_Register is record
-- Pin direction. Same physical register as DIR register
DIR : PIN_CNF_DIR_Field := NRF_SVD.GPIO.Input;
-- Connect or disconnect input buffer
INPUT : PIN_CNF_INPUT_Field := NRF_SVD.GPIO.Disconnect;
-- Pull configuration
PULL : PIN_CNF_PULL_Field := NRF_SVD.GPIO.Disabled;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
-- Drive configuration
DRIVE : PIN_CNF_DRIVE_Field := NRF_SVD.GPIO.S0S1;
-- unspecified
Reserved_11_15 : HAL.UInt5 := 16#0#;
-- Pin sensing mechanism
SENSE : PIN_CNF_SENSE_Field := NRF_SVD.GPIO.Disabled;
-- unspecified
Reserved_18_31 : HAL.UInt14 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PIN_CNF_Register use record
DIR at 0 range 0 .. 0;
INPUT at 0 range 1 .. 1;
PULL at 0 range 2 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
DRIVE at 0 range 8 .. 10;
Reserved_11_15 at 0 range 11 .. 15;
SENSE at 0 range 16 .. 17;
Reserved_18_31 at 0 range 18 .. 31;
end record;
-- Description collection[0]: Configuration of GPIO pins
type PIN_CNF_Registers is array (0 .. 31) of PIN_CNF_Register;
-----------------
-- Peripherals --
-----------------
-- GPIO Port 1
type GPIO_Peripheral is record
-- Write GPIO port
OUT_k : aliased OUT_Register;
-- Set individual bits in GPIO port
OUTSET : aliased OUTSET_Register;
-- Clear individual bits in GPIO port
OUTCLR : aliased OUTCLR_Register;
-- Read GPIO port
IN_k : aliased IN_Register;
-- Direction of GPIO pins
DIR : aliased DIR_Register;
-- DIR set register
DIRSET : aliased DIRSET_Register;
-- DIR clear register
DIRCLR : aliased DIRCLR_Register;
-- Latch register indicating what GPIO pins that have met the criteria
-- set in the PIN_CNF[n].SENSE registers
LATCH : aliased LATCH_Register;
-- Select between default DETECT signal behaviour and LDETECT mode
DETECTMODE : aliased DETECTMODE_Register;
-- Description collection[0]: Configuration of GPIO pins
PIN_CNF : aliased PIN_CNF_Registers;
end record
with Volatile;
for GPIO_Peripheral use record
OUT_k at 16#504# range 0 .. 31;
OUTSET at 16#508# range 0 .. 31;
OUTCLR at 16#50C# range 0 .. 31;
IN_k at 16#510# range 0 .. 31;
DIR at 16#514# range 0 .. 31;
DIRSET at 16#518# range 0 .. 31;
DIRCLR at 16#51C# range 0 .. 31;
LATCH at 16#520# range 0 .. 31;
DETECTMODE at 16#524# range 0 .. 31;
PIN_CNF at 16#700# range 0 .. 1023;
end record;
-- GPIO Port 0
GPIO_Periph : aliased GPIO_Peripheral
with Import, Address => P0_Base;
-- GPIO Port 1
GPIO_Periph1 : aliased GPIO_Peripheral
with Import, Address => P1_Base;
end NRF_SVD.GPIO;
|
AdaCore/libadalang | Ada | 119 | adb | package body Foo_Child_Only is
package body Bar is
procedure Baz is null;
end Bar;
end Foo_Child_Only;
|
stcarrez/ada-ado | Ada | 1,647 | ads | -----------------------------------------------------------------------
-- ado-statements-tests -- Test statements package
-- Copyright (C) 2015, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Tests;
package ADO.Statements.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Test creation of several rows in test_table with different column type.
procedure Test_Save (T : in out Test);
-- Test queries using the $entity_type[] cache group.
procedure Test_Entity_Types (T : in out Test);
-- Test executing a SQL query and getting an invalid column.
procedure Test_Invalid_Column (T : in out Test);
-- Test executing a SQL query and getting an invalid value.
procedure Test_Invalid_Type (T : in out Test);
-- Test executing a SQL query with an invalid SQL.
procedure Test_Invalid_Statement (T : in out Test);
end ADO.Statements.Tests;
|
DavJo-dotdotdot/Ada_Drivers_Library | Ada | 4,872 | ads | ------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2020, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with nRF.GPIO; use nRF.GPIO;
package MicroBit.IOs is
type Pin_Id is range 0 .. 34;
type IO_Features is (Digital, Analog, Touch);
function Supports (Pin : Pin_Id; Feature : IO_Features) return Boolean is
(case Feature is
when Digital => (case Pin is
when 0 .. 16 | 19 .. 34 => True,
when others => False),
when Analog => (case Pin is
when 0 .. 4 | 10 | 27 | 29 => True, --HACK: Pin 27 is NOT an AIN pin, the internal speaker module is connected to it and microbit-music implementation requires analog pin as pre-condition
when others => False),
when Touch => (case Pin is
when 0 | 1 | 2 | 26 => True,
when others => False));
procedure Set (Pin : Pin_Id; Value : Boolean)
with Pre => Supports (Pin, Digital);
function Set (Pin : Pin_Id) return Boolean
with Pre => Supports (Pin, Digital);
type Analog_Value is range 0 .. 1023; --since we use 10 bit resolution. But if we use 12 bit, we need to update to 4095
procedure Set_Analog_Period_Us (Period : Natural);
-- Set the period (in microseconds) of the PWM signal for all analog output
-- pins.
procedure Write (Pin : Pin_Id; Value : Analog_Value)
with Pre => Supports (Pin, Analog);
function Analog (Pin : Pin_Id) return Analog_Value
with Pre => Supports (Pin, Analog);
-- Read the voltagle applied to the pin. 0 means 0V 1023 means 3.3V
private
-- Mapping between pin id and GPIO_Points
Points : array (Pin_Id) of GPIO_Point :=
(0 => MB_P0,
1 => MB_P1,
2 => MB_P2,
3 => MB_P3,
4 => MB_P4,
5 => MB_P5,
6 => MB_P6,
7 => MB_P7,
8 => MB_P8,
9 => MB_P9,
10 => MB_P10,
11 => MB_P11,
12 => MB_P12,
13 => MB_P13,
14 => MB_P14,
15 => MB_P15,
16 => MB_P16,
17 => MB_P0, -- There's no pin17, using P0 to fill in...
18 => MB_P0, -- There's no pin18, using P0 to fill in...
19 => MB_P19,
20 => MB_P20,
21 => MB_P21,
22 => MB_P22,
23 => MB_P23,
24 => MB_P24,
25 => MB_P25,
26 => MB_P26,
27 => MB_P27,
28 => MB_P28,
29 => MB_P29,
30 => MB_P30,
31 => MB_P31,
32 => MB_P32,
33 => MB_P33,
34 => MB_P34
);
end MicroBit.IOs;
|
AdaCore/libadalang | Ada | 69 | adb | separate (Pkg.Proc_1)
procedure Proc_2 is
begin
null;
end Proc_2;
|
stcarrez/swagger-ada | Ada | 174 | adb | with Servlet.Server.EWS;
with TestAPI.Server;
procedure TestAPI_EWS is
Container : Servlet.Server.EWS.EWS_Container;
begin
TestAPI.Server (Container);
end TestAPI_EWS;
|
AdaCore/training_material | Ada | 88 | ads | O3 : A := [for I in 1 .. 10
=> (if I * I > 1 and I * I < 20 then I else 0)];
|
usainzg/EHU | Ada | 1,662 | adb | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Ver_Enesima_Potencia is
-- entrada: 2 natural
-- salida: 4 naturales y 1 natural, Pot (SE)
-- post: Los cuatro naturales corresponden a 4 de casos de prueba
-- pre: { True }
function Potencia (M: Natural; N: Natural) return Natural is
-- EJERCICIO 1 (Opcional)- ESPECIFICA E IMPLEMENTA recursivamente el subprograma
-- Potencia que calcula la n-�sima potencia de M.
begin
-- Completar
if N = 0 then
return 1;
end if;
if N > 0 then
return M * Potencia(M, N-1);
end if;
return 0;
end Potencia;
-- post: { M^N == Potencia(M, N) }
begin
---------- PRUEBAS EXPL�CITAS A PROBAR
Put_Line ("--------------------------------");
Put(" CASO1: 2^0= "); put(2**0, 0); put(", y con tu programa es --> "); Put (Potencia(2, 0), 0); Put_Line(".");
New_Line;New_Line;
Put_Line ("--------------------------------");
Put(" CASO2: 3^1= "); put(3**1, 0); put(", y con tu programa es --> "); Put (Potencia(3, 1), 0); Put_Line(".");
New_Line;New_Line;
Put_Line ("--------------------------------");
Put(" CASO3: 5^5= "); put(5**5, 0); put(", y con tu programa es --> "); Put (Potencia(5, 5), 0); Put_Line(".");
New_Line;New_Line;
Put_Line ("--------------------------------");
Put(" CASO4: 4^15= "); put(4**15, 0); put(", y con tu programa es --> "); Put (Potencia(4, 15), 0); put_line(".");
New_Line;New_Line;
Put_Line ("--------------------------------");
Put_Line ("--------------------------------");
end Ver_Enesima_Potencia;
|
thorstel/Advent-of-Code-2018 | Ada | 1,261 | adb | with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Text_IO;
use Ada.Containers;
use Ada.Text_IO;
procedure Day01 is
package Integer_Sets is new Ordered_Sets (Element_Type => Integer);
package Integer_Vectors is new Vectors (Index_Type => Natural,
Element_Type => Integer);
Frequency : Integer := 0;
Seen_Frequs : Integer_Sets.Set;
Inputs : Integer_Vectors.Vector;
begin
-- Parsing input file & Part 1
declare
Input : Integer;
File : File_Type;
begin
Open (File, In_File, "input.txt");
while not End_Of_File (File) loop
Input := Integer'Value (Get_Line (File));
Frequency := Frequency + Input;
Inputs.Append (Input);
end loop;
Close (File);
end;
Put_Line ("Part 1 =" & Integer'Image (Frequency));
-- Part 2
Seen_Frequs.Include (0);
Frequency := 0;
Infinite_Loop :
loop
for I in Inputs.Iterate loop
Frequency := Frequency + Inputs (I);
exit Infinite_Loop when Seen_Frequs.Contains (Frequency);
Seen_Frequs.Include (Frequency);
end loop;
end loop Infinite_Loop;
Put_Line ("Part 2 =" & Integer'Image (Frequency));
end Day01;
|
RREE/ada-util | Ada | 1,506 | adb | -----------------------------------------------------------------------
-- serialize -- JSON serialization
-- Copyright (C) 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Util.Serialize.IO.JSON;
with Util.Streams.Texts;
procedure Serialize is
Output : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Output.Initialize (Size => 10000);
Stream.Initialize (Output => Output'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("person");
Stream.Write_Entity ("name", "Harry Potter");
Stream.Write_Entity ("gender", "male");
Stream.Write_Entity ("age", 17);
Stream.End_Entity ("person");
Stream.End_Document;
Ada.Text_IO.Put_Line (Util.Streams.Texts.To_String (Output));
end Serialize;
|
leonhxx/pok | Ada | 1,076 | adb | -- POK header
--
-- The following file is a part of the POK project. Any modification should
-- be made according to the POK licence. You CANNOT use this file or a part
-- of a file for your own project.
--
-- For more information on the POK licence, please see our LICENCE FILE
--
-- Please follow the coding guidelines described in doc/CODING_GUIDELINES
--
-- Copyright (c) 2007-2021 POK team
package body Main is
procedure Printf (String : in Interfaces.C.char_array);
pragma Import (C, Printf, "printf");
procedure Compute is
begin
loop
Printf ("beep ");
end loop;
end Compute;
procedure Main is
Ret : Return_Code_Type;
Attr : Process_Attribute_Type;
Id : Process_Id_Type;
begin
Attr.Period := 1000;
Attr.Deadline := Soft;
Attr.Time_Capacity := 1;
Attr.Stack_Size := 4096;
Attr.Entry_Point := Compute'Address;
Create_Process (Attr, Id, Ret);
Set_Partition_Mode (Normal, Ret);
end Main;
end Main;
|
stcarrez/ada-awa | Ada | 16,550 | adb | -----------------------------------------------------------------------
-- awa-blogs-module -- Blog and post management module
-- Copyright (C) 2011, 2012, 2013, 2017, 2018, 2019, 2020, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Log.Loggers;
with Util.Beans.Objects;
with Util.Beans.Basic;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Blogs.Beans;
with AWA.Applications;
with AWA.Services.Contexts;
with AWA.Permissions;
with AWA.Workspaces.Models;
with AWA.Workspaces.Modules;
with AWA.Storages.Models;
with AWA.Storages.Modules;
with AWA.Storages.Services;
with ADO.Objects;
with ADO.Sessions;
with ADO.Statements;
package body AWA.Blogs.Modules is
package ASC renames AWA.Services.Contexts;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Blogs.Module");
package Register is new AWA.Modules.Beans (Module => Blog_Module,
Module_Access => Blog_Module_Access);
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref);
-- ------------------------------
-- Initialize the blog module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Blog_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the blogs module");
-- Setup the resource bundles.
App.Register ("blogMsg", "blogs");
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_Bean",
Handler => AWA.Blogs.Beans.Create_Post_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Post_List_Bean",
Handler => AWA.Blogs.Beans.Create_Post_List_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Admin_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Admin_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Blog_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Status_List_Bean",
Handler => AWA.Blogs.Beans.Create_Status_List'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Stat_Bean",
Handler => AWA.Blogs.Beans.Create_Blog_Stat_Bean'Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Blogs.Beans.Format_List_Bean",
Handler => AWA.Blogs.Beans.Create_Format_List_Bean'Access);
App.Add_Servlet ("blog-image", Plugin.Image_Servlet'Unchecked_Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
end Initialize;
-- ------------------------------
-- Configures the module after its initialization and after having read its XML configuration.
-- ------------------------------
overriding
procedure Configure (Plugin : in out Blog_Module;
Props : in ASF.Applications.Config) is
pragma Unreferenced (Props);
Image_Prefix : constant String := Plugin.Get_Config (PARAM_IMAGE_PREFIX);
begin
Plugin.Image_Prefix := Wiki.Strings.To_UString (Wiki.Strings.To_WString (Image_Prefix));
end Configure;
-- ------------------------------
-- Get the blog module instance associated with the current application.
-- ------------------------------
function Get_Blog_Module return Blog_Module_Access is
function Get is new AWA.Modules.Get (Blog_Module, Blog_Module_Access, NAME);
begin
return Get;
end Get_Blog_Module;
-- ------------------------------
-- Get the image prefix that was configured for the Blog module.
-- ------------------------------
function Get_Image_Prefix (Module : in Blog_Module)
return Wiki.Strings.UString is
begin
return Module.Image_Prefix;
end Get_Image_Prefix;
procedure Publish_Post (Module : in Blog_Module;
Post : in AWA.Blogs.Models.Post_Ref) is
Current_Entity : aliased AWA.Blogs.Models.Post_Ref := Post;
Ptr : constant Util.Beans.Basic.Readonly_Bean_Access
:= Current_Entity'Unchecked_Access;
Bean : constant Util.Beans.Objects.Object
:= Util.Beans.Objects.To_Object (Ptr, Util.Beans.Objects.STATIC);
Event : AWA.Events.Module_Event;
begin
Event.Set_Event_Kind (Post_Publish_Event.Kind);
Event.Set_Parameter ("summary", Post.Get_Summary);
Event.Set_Parameter ("title", Post.Get_Title);
Event.Set_Parameter ("uri", Post.Get_Uri);
Event.Set_Parameter ("format", Models.Format_Type_Objects.To_Object (Post.Get_Format));
Event.Set_Parameter ("post", Bean);
Event.Set_Parameter ("author", Post.Get_Author.Get_Name);
Module.Send_Event (Event);
end Publish_Post;
-- ------------------------------
-- Create a new blog for the user workspace.
-- ------------------------------
procedure Create_Blog (Model : in Blog_Module;
Title : in String;
Result : out ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
WS : AWA.Workspaces.Models.Workspace_Ref;
begin
Log.Info ("Creating blog {0} for user", Title);
Ctx.Start;
AWA.Workspaces.Modules.Get_Workspace (DB, Ctx, WS);
-- Check that the user has the create blog permission on the given workspace.
AWA.Permissions.Check (Permission => ACL_Create_Blog.Permission,
Entity => WS);
Blog.Set_Name (Title);
Blog.Set_Workspace (WS);
Blog.Set_Create_Date (Ada.Calendar.Clock);
Blog.Save (DB);
-- Add the permission for the user to use the new blog.
AWA.Workspaces.Modules.Add_Permission (Session => DB,
User => User,
Entity => Blog,
Workspace => WS.Get_Id,
List => (ACL_Delete_Blog.Permission,
ACL_Update_Post.Permission,
ACL_Create_Post.Permission,
ACL_Delete_Post.Permission));
Ctx.Commit;
Result := Blog.Get_Id;
Log.Info ("Blog {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
end Create_Blog;
-- ------------------------------
-- Create a new post associated with the given blog identifier.
-- ------------------------------
procedure Create_Post (Model : in Blog_Module;
Blog_Id : in ADO.Identifier;
Title : in String;
URI : in String;
Text : in String;
Summary : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Status : in AWA.Blogs.Models.Post_Status_Type;
Result : out ADO.Identifier) is
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Blog : AWA.Blogs.Models.Blog_Ref;
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Log.Debug ("Creating post for user");
Ctx.Start;
-- Get the blog instance.
Blog.Load (Session => DB,
Id => Blog_Id,
Found => Found);
if not Found then
Log.Error ("Blog {0} not found", ADO.Identifier'Image (Blog_Id));
raise Not_Found with "Blog not found";
end if;
-- Check that the user has the create post permission on the given blog.
AWA.Permissions.Check (Permission => ACL_Create_Post.Permission,
Entity => Blog);
-- Build the new post.
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Create_Date (Ada.Calendar.Clock);
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Uri (URI);
Post.Set_Author (Ctx.Get_User);
Post.Set_Status (Status);
Post.Set_Blog (Blog);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
Result := Post.Get_Id;
Log.Info ("Post {0} created for user {1}",
ADO.Identifier'Image (Result), ADO.Identifier'Image (User));
-- The post is published, post an event to trigger specific actions.
if Status = AWA.Blogs.Models.POST_PUBLISHED then
Publish_Post (Model, Post);
end if;
end Create_Post;
-- ------------------------------
-- Update the post title and text associated with the blog post identified by <b>Post</b>.
-- ------------------------------
procedure Update_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Title : in String;
Summary : in String;
URI : in String;
Text : in String;
Format : in AWA.Blogs.Models.Format_Type;
Comment : in Boolean;
Publish_Date : in ADO.Nullable_Time;
Status : in AWA.Blogs.Models.Post_Status_Type) is
use type AWA.Blogs.Models.Post_Status_Type;
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
Published : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the update post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Update_Post.Permission,
Entity => Post);
if not Publish_Date.Is_Null then
Post.Set_Publish_Date (Publish_Date);
end if;
Published := Status = AWA.Blogs.Models.POST_PUBLISHED and then Post.Get_Publish_Date.Is_Null;
if Published then
Post.Set_Publish_Date (ADO.Nullable_Time '(Is_Null => False,
Value => Ada.Calendar.Clock));
end if;
Post.Set_Title (Title);
Post.Set_Text (Text);
Post.Set_Summary (Summary);
Post.Set_Uri (URI);
Post.Set_Status (Status);
Post.Set_Format (Format);
Post.Set_Allow_Comments (Comment);
Post.Save (DB);
Ctx.Commit;
-- The post is published, post an event to trigger specific actions.
if Published then
Publish_Post (Model, Post);
end if;
end Update_Post;
-- ------------------------------
-- Delete the post identified by the given identifier.
-- ------------------------------
procedure Delete_Post (Model : in Blog_Module;
Post_Id : in ADO.Identifier) is
pragma Unreferenced (Model);
Ctx : constant ASC.Service_Context_Access := AWA.Services.Contexts.Current;
DB : ADO.Sessions.Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Post : AWA.Blogs.Models.Post_Ref;
Found : Boolean;
begin
Ctx.Start;
Post.Load (Session => DB, Id => Post_Id, Found => Found);
if not Found then
Log.Error ("Post {0} not found", ADO.Identifier'Image (Post_Id));
raise Not_Found;
end if;
-- Check that the user has the delete post permission on the given post.
AWA.Permissions.Check (Permission => ACL_Delete_Post.Permission,
Entity => Post);
Post.Delete (Session => DB);
Ctx.Commit;
end Delete_Post;
-- ------------------------------
-- Load the image data associated with a blog post. The image must be public and the
-- post visible for the image to be retrieved by anonymous users.
-- ------------------------------
procedure Load_Image (Model : in Blog_Module;
Post_Id : in ADO.Identifier;
Image_Id : in ADO.Identifier;
Width : in out Natural;
Height : in out Natural;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref) is
pragma Unreferenced (Model);
use type AWA.Storages.Models.Storage_Type;
Ctx : constant Services.Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : constant ADO.Sessions.Session := AWA.Services.Contexts.Get_Session (Ctx);
Query : ADO.Statements.Query_Statement;
Kind : AWA.Storages.Models.Storage_Type;
begin
if Width = Natural'Last or else Height = Natural'Last then
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
elsif Width > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Width_Get_Data);
Query.Bind_Param ("width", Width);
elsif Height > 0 then
Query := DB.Create_Statement (Models.Query_Blog_Image_Height_Get_Data);
Query.Bind_Param ("height", Height);
else
Query := DB.Create_Statement (Models.Query_Blog_Image_Get_Data);
end if;
Query.Bind_Param ("post_id", Post_Id);
Query.Bind_Param ("store_id", Image_Id);
Query.Bind_Param ("user_id", User);
Query.Execute;
if not Query.Has_Elements then
Log.Warn ("Blog post image entity {0} not found", ADO.Identifier'Image (Image_Id));
raise ADO.Objects.NOT_FOUND;
end if;
Mime := Query.Get_Unbounded_String (0);
Date := Query.Get_Time (1);
Width := Query.Get_Natural (4);
Height := Query.Get_Natural (5);
Kind := AWA.Storages.Models.Storage_Type'Val (Query.Get_Integer (3));
if Kind = AWA.Storages.Models.DATABASE then
Into := Query.Get_Blob (6);
else
declare
Mgr : constant AWA.Storages.Services.Storage_Service_Access
:= AWA.Storages.Modules.Get_Storage_Manager;
begin
Mgr.Load (From => Image_Id, Kind => Kind, Into => Into);
end;
end if;
end Load_Image;
end AWA.Blogs.Modules;
|
stcarrez/dynamo | Ada | 67,214 | adb | ------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A S I S . C O M P I L A T I O N _ U N I T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2009, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions; use Asis.Exceptions;
with Asis.Extensions; use Asis.Extensions;
with Asis.Implementation; use Asis.Implementation;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Opt; use A4G.A_Opt;
with A4G.A_Output; use A4G.A_Output;
with A4G.Vcheck; use A4G.Vcheck;
with A4G.Get_Unit; use A4G.Get_Unit;
with A4G.Contt; use A4G.Contt;
with A4G.Contt.UT; use A4G.Contt.UT;
with Lib; use Lib;
package body Asis.Compilation_Units is
Package_Name : constant String := "Asis.Compilation_Units.";
LT : Wide_String renames A4G.A_Types.Asis_Wide_Line_Terminator;
function "=" (Left, Right : Compilation_Unit) return Boolean
renames Asis.Set_Get."=";
----------------------
-- Attribute_Values --
----------------------
function Attribute_Values
(Compilation_Unit : Asis.Compilation_Unit;
Attribute : Wide_String)
return Wide_String
is
begin
pragma Unreferenced (Attribute);
Check_Validity (Compilation_Unit, Package_Name & "Attribute_Values");
return Nil_Asis_Wide_String;
end Attribute_Values;
-------------------------------
-- Attribute_Value_Delimiter --
-------------------------------
function Attribute_Value_Delimiter return Wide_String is
begin
return Asis_Wide_Line_Terminator;
end Attribute_Value_Delimiter;
-------------------------
-- Can_Be_Main_Program --
-------------------------
function Can_Be_Main_Program
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean
is
Result : Boolean := False;
begin
Check_Validity (Compilation_Unit, Package_Name & "Can_Be_Main_Program");
Reset_Context (Encl_Cont_Id (Compilation_Unit));
case Kind (Compilation_Unit) is
when A_Procedure |
A_Function |
A_Procedure_Body |
A_Function_Body |
A_Procedure_Renaming |
A_Function_Renaming |
A_Procedure_Instance |
A_Function_Instance =>
Result := Is_Main_Unit (Compilation_Unit);
when others =>
null;
end case;
return Result;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Can_Be_Main_Program");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Can_Be_Main_Program",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Can_Be_Main_Program;
--------------------------------------
-- Compilation_Command_Line_Options --
--------------------------------------
function Compilation_Command_Line_Options
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Arg_Len : Natural := 0; -- total length of compilation switches
Arg_Count : Nat := 0; -- total number of compilation switches
Arg_Ptr : String_Ptr;
Corr_Main_Unit_Id : Unit_Id := Nil_Unit;
Corresponding_Main_Unit : Asis.Compilation_Unit := Nil_Compilation_Unit;
begin
Check_Validity
(Compilation_Unit, Package_Name & "Compilation_Command_Line_Options");
Arg_Kind := Kind (Compilation_Unit);
if Arg_Kind not in A_Procedure .. A_Protected_Body_Subunit then
return Nil_Asis_Wide_String;
end if;
Arg_Cont_Id := Encl_Cont_Id (Compilation_Unit);
Reset_Context (Arg_Cont_Id);
if Is_Main_Unit_In_Tree (Compilation_Unit) then
Corresponding_Main_Unit := Compilation_Unit;
else
Arg_Unit_Id := Get_Unit_Id (Compilation_Unit);
-- Here we have to check if the argument unit should to
-- inherit command line options from some main unit:
if Arg_Kind in A_Procedure .. A_Package then
-- Here we have to check if the corresponding body is a
-- main unit of some compilation:
Corr_Main_Unit_Id := Get_Body (Arg_Cont_Id, Arg_Unit_Id);
elsif Arg_Kind in A_Procedure_Body_Subunit ..
A_Protected_Body_Subunit
then
-- We have to go to ancestor body and to check if it is a main
-- unit of some compilation
Corr_Main_Unit_Id :=
Get_Subunit_Parent_Body (Arg_Cont_Id, Arg_Unit_Id);
while Class (Arg_Cont_Id, Corr_Main_Unit_Id) = A_Separate_Body
loop
Corr_Main_Unit_Id :=
Get_Subunit_Parent_Body (Arg_Cont_Id, Corr_Main_Unit_Id);
end loop;
end if;
Corresponding_Main_Unit :=
Get_Comp_Unit (Corr_Main_Unit_Id, Arg_Cont_Id);
if not Is_Main_Unit_In_Tree (Corresponding_Main_Unit) then
Corresponding_Main_Unit := Nil_Compilation_Unit;
end if;
end if;
if Is_Nil (Corresponding_Main_Unit) then
return Nil_Asis_Wide_String;
else
Reset_Main_Tree (Corresponding_Main_Unit);
-- First, find the length of the string to return
Find_Arguments_Length : loop
Arg_Ptr := Get_Compilation_Switch (Arg_Count + 1);
exit Find_Arguments_Length when Arg_Ptr = null;
Arg_Count := Arg_Count + 1;
Arg_Len := Arg_Len + Arg_Ptr'Length + 1;
end loop Find_Arguments_Length;
if Arg_Count > 0 then
Arg_Len := Arg_Len - 1;
end if;
declare
Result : String (1 .. Arg_Len);
Next_Pos : Natural := 1;
Next_Arg_Len : Natural;
begin
-- Should be rewritten on the base of ASIS string buffer???
for Next_Arg in 1 .. Arg_Count loop
Arg_Ptr := Get_Compilation_Switch (Next_Arg);
Next_Arg_Len := Arg_Ptr'Length;
Result (Next_Pos .. Next_Pos + Next_Arg_Len - 1) := Arg_Ptr.all;
Next_Pos := Next_Pos + Next_Arg_Len;
if Next_Arg < Arg_Count then
Result (Next_Pos) := ' ';
Next_Pos := Next_Pos + 1;
end if;
end loop;
return To_Program_Text (Result);
end;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Compilation_Command_Line_Options");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Compilation_Command_Line_Options",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Compilation_Command_Line_Options;
-----------------------
-- Compilation_Units --
-----------------------
function Compilation_Units
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List
is
Res_Cont_Id : constant Context_Id := Get_Cont_Id (The_Context);
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (The_Context, Package_Name & "Compilation_Units");
Cont_Tree_Mode := Tree_Processing_Mode (Res_Cont_Id);
if not (Cont_Tree_Mode = Pre_Created or else
Cont_Tree_Mode = Incremental)
then
Set_Status
(Status => Use_Error,
Diagnosis =>
"Asis.Compilation_Units.Compilation_Units can not be used " &
LT & "for dynamic ASIS Context");
raise ASIS_Failed;
end if;
Reset_Context (Res_Cont_Id);
declare
Result_Len : constant Natural :=
Lib_Unit_Decls (Res_Cont_Id) + Comp_Unit_Bodies (Res_Cont_Id);
Result : Compilation_Unit_List (1 .. Result_Len);
begin
-- We have to skip A_Configuration_Compilation unit, it is the second
-- unit in the table
Result (1) := Get_Comp_Unit (Standard_Id, Res_Cont_Id);
for I in 2 .. Result_Len loop
Result (I) :=
Get_Comp_Unit (First_Unit_Id + Unit_Id (I), Res_Cont_Id);
end loop;
return Result;
end;
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Compilation_Units");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Compilation_Units",
Ex => Ex);
end Compilation_Units;
-----------------------------
-- Compilation_Unit_Bodies --
-----------------------------
function Compilation_Unit_Bodies
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List
is
Res_Cont_Id : constant Context_Id := Get_Cont_Id (The_Context);
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (The_Context, Package_Name & "Compilation_Unit_Bodies");
Cont_Tree_Mode := Tree_Processing_Mode (Res_Cont_Id);
if not (Cont_Tree_Mode = Pre_Created or else
Cont_Tree_Mode = Incremental)
then
Set_Status
(Status => Use_Error,
Diagnosis =>
"Asis.Compilation_Units.Compilation_Unit_Bodies can not be used "
& LT & "for dynamic ASIS Context");
raise ASIS_Failed;
end if;
Reset_Context (Res_Cont_Id);
declare
Result_Len : constant Natural := Comp_Unit_Bodies (Res_Cont_Id);
Result : Compilation_Unit_List (1 .. Result_Len);
L_U_Body : Unit_Id := First_Body;
begin
for I in 1 .. Result_Len loop
Result (I) := Get_Comp_Unit (L_U_Body, Res_Cont_Id);
L_U_Body := Next_Body (L_U_Body);
end loop;
return Result;
end;
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Compilation_Unit_Bodies");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Compilation_Unit_Bodies",
Ex => Ex);
end Compilation_Unit_Bodies;
---------------------------
-- Compilation_Unit_Body --
---------------------------
function Compilation_Unit_Body
(Name : Wide_String;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Result_Id : Unit_Id;
Result_Cont : Context_Id;
begin
Check_Validity (The_Context, Package_Name & "Compilation_Unit_Body");
Result_Cont := Get_Cont_Id (The_Context);
Reset_Context (Result_Cont);
Result_Id := Get_One_Unit (Name, Result_Cont, Spec => False);
return Get_Comp_Unit (Result_Id, Result_Cont);
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Compilation_Unit_Body");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Compilation_Unit_Body (" &
To_String (Name) & ")",
Ex => Ex);
end Compilation_Unit_Body;
------------------------
-- Corresponding_Body --
------------------------
function Corresponding_Body
(Library_Item : Asis.Compilation_Unit)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Result_Unit_Id : Unit_Id;
Result_Cont_Id : Context_Id;
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (Library_Item, Package_Name & "Corresponding_Body");
Result_Cont_Id := Encl_Cont_Id (Library_Item);
Reset_Context (Result_Cont_Id);
Arg_Kind := Kind (Library_Item);
if not (Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = An_Unknown_Unit or else
Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit or else
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Body");
end if;
if Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit or else
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body
then
return Library_Item;
end if;
if (Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Package)
and then
not Asis.Set_Get.Is_Body_Required (Library_Item)
then
return Nil_Compilation_Unit;
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Item);
Cont_Tree_Mode := Tree_Processing_Mode (Result_Cont_Id);
Result_Unit_Id := Get_Body (Result_Cont_Id, Arg_Unit_Id);
if No (Result_Unit_Id) and then
(Cont_Tree_Mode = On_The_Fly or else
Cont_Tree_Mode = Mixed or else
Cont_Tree_Mode = Incremental)
then
-- as a last escape, we try to create the result body by
-- compiling on the fly:
Result_Unit_Id :=
Get_One_Unit (Name => Unit_Full_Name (Library_Item),
Context => Result_Cont_Id,
Spec => False);
end if;
if No (Result_Unit_Id) then
Result_Unit_Id := Get_Nonexistent_Unit (Result_Cont_Id);
end if;
return Get_Comp_Unit (Result_Unit_Id, Result_Cont_Id);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Body");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Body",
Ex => Ex,
Arg_CU => Library_Item);
end Corresponding_Body;
function Corresponding_Body
(Library_Item : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
begin
Check_Validity (The_Context, Package_Name & "Corresponding_Body");
Check_Validity (Library_Item, Package_Name & "Corresponding_Body");
Arg_Cont_Id := Encl_Cont_Id (Library_Item);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Library_Item);
if not (Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = An_Unknown_Unit or else
Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit or else
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Body");
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Item);
Result_Cont_Id := Get_Cont_Id (The_Context);
New_Arg_Unit_Id :=
Get_Same_Unit (Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Corresponding_Body
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Body");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Body",
Ex => Ex,
Arg_CU => Library_Item,
Context_Par => True);
end Corresponding_Body;
----------------------------
-- Corresponding_Children --
----------------------------
function Corresponding_Children
(Library_Unit : Asis.Compilation_Unit)
return Asis.Compilation_Unit_List
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Res_Cont_Id : Context_Id;
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (Library_Unit, Package_Name & "Corresponding_Children");
Res_Cont_Id := Encl_Cont_Id (Library_Unit);
Reset_Context (Res_Cont_Id);
Arg_Kind := Kind (Library_Unit);
if not (Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Package_Instance)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Children");
end if;
Cont_Tree_Mode := Tree_Processing_Mode (Res_Cont_Id);
if not (Cont_Tree_Mode = Pre_Created or else
Cont_Tree_Mode = Incremental)
then
Set_Status
(Status => Use_Error,
Diagnosis =>
"Asis.Compilation_Units.Corresponding_Children can not be used "
& LT & "for dynamic ASIS Context");
raise ASIS_Failed;
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Unit);
declare
Result_Id_List : constant Unit_Id_List := Children (Arg_Unit_Id);
Result_List : constant Compilation_Unit_List :=
Get_Comp_Unit_List (Result_Id_List, Res_Cont_Id);
begin
return Result_List;
end;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Children");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Children",
Ex => Ex,
Arg_CU => Library_Unit);
end Corresponding_Children;
function Corresponding_Children
(Library_Unit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit_List
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (The_Context, Package_Name & "Corresponding_Children");
Check_Validity (Library_Unit, Package_Name & "Corresponding_Children");
Arg_Cont_Id := Encl_Cont_Id (Library_Unit);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Library_Unit);
if not (Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Package_Instance)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Children");
end if;
Result_Cont_Id := Get_Cont_Id (The_Context);
Cont_Tree_Mode := Tree_Processing_Mode (Result_Cont_Id);
if not (Cont_Tree_Mode = Pre_Created or else
Cont_Tree_Mode = Incremental)
then
Set_Status
(Status => Use_Error,
Diagnosis =>
"Asis.Compilation_Units.Corresponding_Children can not be used "
& LT & "for dynamic ASIS Context");
raise ASIS_Failed;
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Unit);
New_Arg_Unit_Id :=
Get_Same_Unit (Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Corresponding_Children
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit_List;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Children");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Children",
Ex => Ex,
Arg_CU => Library_Unit,
Context_Par => True);
end Corresponding_Children;
-------------------------------
-- Corresponding_Declaration --
-------------------------------
function Corresponding_Declaration
(Library_Item : Asis.Compilation_Unit)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Result_Unit_Id : Unit_Id;
Result_Cont_Id : Context_Id;
begin
Check_Validity
(Library_Item, Package_Name & "Corresponding_Declaration");
Result_Cont_Id := Encl_Cont_Id (Library_Item);
Reset_Context (Result_Cont_Id);
Arg_Kind := Kind (Library_Item);
if not (Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = An_Unknown_Unit or else
Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit or else
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Declaration");
end if;
if Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else -- ???
Arg_Kind = A_Function_Body_Subunit or else -- ???
Arg_Kind = A_Package_Body_Subunit or else -- ???
Arg_Kind = A_Task_Body_Subunit or else -- ???
Arg_Kind = A_Protected_Body_Subunit or else -- ???
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body -- ???
then
return Library_Item;
end if;
if (Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body)
and then
Class (Library_Item) = A_Public_Declaration_And_Body
then
return Nil_Compilation_Unit;
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Item);
Result_Unit_Id := Get_Declaration (Result_Cont_Id, Arg_Unit_Id);
return Get_Comp_Unit (Result_Unit_Id, Result_Cont_Id);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Declaration",
Ex => Ex,
Arg_CU => Library_Item);
end Corresponding_Declaration;
function Corresponding_Declaration
(Library_Item : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
begin
Check_Validity (The_Context, Package_Name & "Corresponding_Declaration");
Check_Validity
(Library_Item, Package_Name & "Corresponding_Declaration");
Arg_Cont_Id := Encl_Cont_Id (Library_Item);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Library_Item);
if not (Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = An_Unknown_Unit or else
Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit or else
Arg_Kind = A_Nonexistent_Declaration or else
Arg_Kind = A_Nonexistent_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Declaration");
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Item);
Result_Cont_Id := Get_Cont_Id (The_Context);
New_Arg_Unit_Id := Get_Same_Unit
(Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Corresponding_Declaration
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Corresponding_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Declaration",
Ex => Ex,
Arg_CU => Library_Item,
Context_Par => True);
end Corresponding_Declaration;
--------------------------------------
-- Corresponding_Parent_Declaration --
--------------------------------------
function Corresponding_Parent_Declaration
(Library_Unit : Asis.Compilation_Unit)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Res_Cont_Id : Context_Id;
Result_Id : Unit_Id;
begin
Check_Validity
(Library_Unit, Package_Name & "Corresponding_Parent_Declaration");
Res_Cont_Id := Encl_Cont_Id (Library_Unit);
Reset_Context (Res_Cont_Id);
Arg_Kind := Kind (Library_Unit);
if not (Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Parent_Declaration");
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Unit);
Result_Id := Get_Parent_Unit (Res_Cont_Id, Arg_Unit_Id);
-- Result_Id cannot be Nil_Unit here
return Get_Comp_Unit (Result_Id, Res_Cont_Id);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Corresponding_Parent_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Parent_Declaration",
Ex => Ex,
Arg_CU => Library_Unit);
end Corresponding_Parent_Declaration;
function Corresponding_Parent_Declaration
(Library_Unit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
begin
Check_Validity
(The_Context, Package_Name & "Corresponding_Parent_Declaration");
Check_Validity
(Library_Unit, Package_Name & "Corresponding_Parent_Declaration");
Arg_Cont_Id := Encl_Cont_Id (Library_Unit);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Library_Unit);
if not (Arg_Kind = A_Procedure or else
Arg_Kind = A_Function or else
Arg_Kind = A_Package or else
Arg_Kind = A_Generic_Procedure or else
Arg_Kind = A_Generic_Function or else
Arg_Kind = A_Generic_Package or else
Arg_Kind = A_Procedure_Instance or else
Arg_Kind = A_Function_Instance or else
Arg_Kind = A_Package_Instance or else
Arg_Kind = A_Procedure_Renaming or else
Arg_Kind = A_Function_Renaming or else
Arg_Kind = A_Package_Renaming or else
Arg_Kind = A_Generic_Procedure_Renaming or else
Arg_Kind = A_Generic_Function_Renaming or else
Arg_Kind = A_Generic_Package_Renaming or else
Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Parent_Declaration");
end if;
Arg_Unit_Id := Get_Unit_Id (Library_Unit);
Result_Cont_Id := Get_Cont_Id (The_Context);
New_Arg_Unit_Id :=
Get_Same_Unit (Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Corresponding_Parent_Declaration
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Corresponding_Parent_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Parent_Declaration",
Ex => Ex,
Arg_CU => Library_Unit,
Context_Par => True);
end Corresponding_Parent_Declaration;
---------------------------------------
-- Corresponding_Subunit_Parent_Body --
---------------------------------------
function Corresponding_Subunit_Parent_Body
(Subunit : Asis.Compilation_Unit)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Result_Unit_Id : Unit_Id;
Result_Cont_Id : Context_Id;
begin
Check_Validity
(Subunit, Package_Name & "Corresponding_Subunit_Parent_Body");
Result_Cont_Id := Encl_Cont_Id (Subunit);
Reset_Context (Result_Cont_Id);
Arg_Kind := Kind (Subunit);
if not (Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Subunit_Parent_Body");
end if;
Arg_Unit_Id := Get_Unit_Id (Subunit);
Result_Unit_Id := Get_Subunit_Parent_Body (Result_Cont_Id, Arg_Unit_Id);
return Get_Comp_Unit (Result_Unit_Id, Result_Cont_Id);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Corresponding_Subunit_Parent_Body");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Subunit_Parent_Body",
Ex => Ex,
Arg_CU => Subunit);
end Corresponding_Subunit_Parent_Body;
function Corresponding_Subunit_Parent_Body
(Subunit : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
begin
Check_Validity
(The_Context, Package_Name & "Corresponding_Subunit_Parent_Body");
Check_Validity
(Subunit, Package_Name & "Corresponding_Subunit_Parent_Body");
Arg_Cont_Id := Encl_Cont_Id (Subunit);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Subunit);
if not (Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Corresponding_Subunit_Parent_Body");
end if;
Arg_Unit_Id := Get_Unit_Id (Subunit);
Result_Cont_Id := Get_Cont_Id (The_Context);
New_Arg_Unit_Id := Get_Same_Unit
(Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Corresponding_Subunit_Parent_Body
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information (Outer_Call =>
Package_Name & "Corresponding_Subunit_Parent_Body");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Corresponding_Subunit_Parent_Body",
Ex => Ex,
Arg_CU => Subunit,
Context_Par => True);
end Corresponding_Subunit_Parent_Body;
-----------------
-- Debug_Image --
-----------------
function Debug_Image
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
LT : String renames A4G.A_Types.ASIS_Line_Terminator;
begin
return To_Wide_String (LT & "Compilation Unit Debug_Image: "
& Debug_String (Compilation_Unit));
exception
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Debug_Image",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Debug_Image;
-------------------------
-- Enclosing_Container --
-------------------------
function Enclosing_Container
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Ada_Environments.Containers.Container
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Enclosing_Container");
if Is_Nil (Compilation_Unit) then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Enclosing_Container");
else
-- For the currently implemented trivial Container model we have:
return Asis.Ada_Environments.Containers.Defining_Containers
(Enclosing_Context (Compilation_Unit)) (1);
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Enclosing_Container");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Enclosing_Container",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Enclosing_Container;
-----------------------
-- Enclosing_Context --
-----------------------
function Enclosing_Context
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Context
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Enclosing_Context");
if Is_Nil (Compilation_Unit) then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Enclosing_Context");
else
return Encl_Cont (Compilation_Unit);
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Enclosing_Context");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Enclosing_Context",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Enclosing_Context;
------------
-- Exists --
------------
function Exists
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean
is
Unit_Kind : Asis.Unit_Kinds;
begin
Check_Validity (Compilation_Unit, Package_Name & "Exists");
Reset_Context (Encl_Cont_Id (Compilation_Unit));
Unit_Kind := Kind (Compilation_Unit);
return not (Unit_Kind = Not_A_Unit or else
Unit_Kind = A_Nonexistent_Declaration or else
Unit_Kind = A_Nonexistent_Body);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Exists");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Exists",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Exists;
-------------------
-- Has_Attribute --
-------------------
function Has_Attribute
(Compilation_Unit : Asis.Compilation_Unit;
Attribute : Wide_String)
return Boolean
is
begin
pragma Unreferenced (Attribute);
Check_Validity (Compilation_Unit, Package_Name & "Has_Attribute");
return False;
end Has_Attribute;
----------------------
-- Is_Body_Required --
----------------------
function Is_Body_Required
(Compilation_Unit : Asis.Compilation_Unit)
return Boolean
is
Unit_Kind : constant Asis.Unit_Kinds := Kind (Compilation_Unit);
Result : Boolean := False;
begin
Check_Validity (Compilation_Unit, Package_Name & "Is_Body_Required");
Reset_Context (Encl_Cont_Id (Compilation_Unit));
case Unit_Kind is
when A_Package |
A_Generic_Package =>
Result := Asis.Set_Get.Is_Body_Required (Compilation_Unit);
when others =>
null;
end case;
return Result;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Is_Body_Required");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Body_Required",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Is_Body_Required;
--------------
-- Is_Equal --
--------------
function Is_Equal
(Left : Asis.Compilation_Unit;
Right : Asis.Compilation_Unit)
return Boolean
is
Left_Unit_Id : Unit_Id;
Right_Unit_Id : Unit_Id;
Left_Cont_Id : Context_Id;
Right_Cont_Id : Context_Id;
begin
Check_Validity (Left, Package_Name & "Is_Equal");
Check_Validity (Right, Package_Name & "Is_Equal");
Left_Unit_Id := Get_Unit_Id (Left);
Right_Unit_Id := Get_Unit_Id (Right);
if Left_Unit_Id = Nil_Unit and then Right_Unit_Id = Nil_Unit then
return True;
elsif (Right_Unit_Id = Nil_Unit and then Left_Unit_Id /= Nil_Unit)
or else
(Right_Unit_Id /= Nil_Unit and then Left_Unit_Id = Nil_Unit)
then
return False;
end if;
Left_Cont_Id := Encl_Cont_Id (Left);
Right_Cont_Id := Encl_Cont_Id (Right);
if Left_Cont_Id = Right_Cont_Id then
return Left_Unit_Id = Right_Unit_Id;
else
return Right_Unit_Id =
Get_Same_Unit (Left_Cont_Id, Left_Unit_Id, Right_Cont_Id);
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Is_Equal");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Equal",
Ex => Ex,
Arg_CU => Left,
Arg_CU_2 => Right);
end Is_Equal;
------------------
-- Is_Identical --
------------------
function Is_Identical
(Left : Asis.Compilation_Unit;
Right : Asis.Compilation_Unit)
return Boolean
is
Left_Cont_Id : Context_Id;
Right_Cont_Id : Context_Id;
begin
Check_Validity (Left, Package_Name & "Is_Identical");
Check_Validity (Right, Package_Name & "Is_Identical");
Left_Cont_Id := Encl_Cont_Id (Left);
Right_Cont_Id := Encl_Cont_Id (Right);
return Left_Cont_Id = Right_Cont_Id and then Is_Equal (Left, Right);
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Is_Identical");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Is_Identical",
Ex => Ex,
Arg_CU => Left,
Arg_CU_2 => Right);
end Is_Identical;
------------
-- Is_Nil --
------------
function Is_Nil (Right : Asis.Compilation_Unit) return Boolean is
begin
Check_Validity (Right, Package_Name & "Is_Nil");
return Right = Nil_Compilation_Unit;
end Is_Nil;
function Is_Nil (Right : Asis.Compilation_Unit_List) return Boolean is
begin
return Right = Nil_Compilation_Unit_List;
end Is_Nil;
------------------------------
-- Library_Unit_Declaration --
------------------------------
function Library_Unit_Declaration
(Name : Wide_String;
The_Context : Asis.Context)
return Asis.Compilation_Unit
is
Result_Id : Unit_Id;
Result_Cont : Context_Id;
begin
Check_Validity (The_Context, Package_Name & "Library_Unit_Declaration");
Result_Cont := Get_Cont_Id (The_Context);
Reset_Context (Result_Cont);
Result_Id := Get_One_Unit (Name, Result_Cont, Spec => True);
return Get_Comp_Unit (Result_Id, Result_Cont);
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Library_Unit_Declaration");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Library_Unit_Declaration (" &
To_String (Name) & ")",
Ex => Ex);
end Library_Unit_Declaration;
-------------------------------
-- Library_Unit_Declarations --
-------------------------------
function Library_Unit_Declarations
(The_Context : Asis.Context)
return Asis.Compilation_Unit_List
is
Res_Cont_Id : constant Context_Id := Get_Cont_Id (The_Context);
Cont_Tree_Mode : Tree_Mode;
begin
Check_Validity (The_Context, Package_Name & "Library_Unit_Declarations");
Cont_Tree_Mode := Tree_Processing_Mode (Res_Cont_Id);
if not (Cont_Tree_Mode = Pre_Created or else
Cont_Tree_Mode = Incremental)
then
Set_Status
(Status => Use_Error,
Diagnosis =>
"Asis.Compilation_Units.Library_Unit_Declarations "
& "can not be used "
& LT & "for dynamic ASIS Context");
raise ASIS_Failed;
end if;
Reset_Context (Res_Cont_Id);
declare
Result_Len : constant Natural := Lib_Unit_Decls (Res_Cont_Id);
Result : Compilation_Unit_List (1 .. Result_Len);
L_U_Decl : Unit_Id := First_Unit_Id; -- Standard
begin
for I in 1 .. Result_Len loop
Result (I) := Get_Comp_Unit (L_U_Decl, Res_Cont_Id);
L_U_Decl := Next_Decl (L_U_Decl);
end loop;
return Result;
end;
exception
when ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Library_Unit_Declarations");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Library_Unit_Declarations",
Ex => Ex);
end Library_Unit_Declarations;
-----------------
-- Object_Form --
-----------------
function Object_Form
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Object_Form");
return Nil_Asis_Wide_String;
end Object_Form;
-----------------
-- Object_Name --
-----------------
function Object_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Object_Name");
return Nil_Asis_Wide_String;
end Object_Name;
--------------
-- Subunits --
--------------
function Subunits
(Parent_Body : Asis.Compilation_Unit)
return Asis.Compilation_Unit_List
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Res_Cont_Id : Context_Id;
begin
Check_Validity (Parent_Body, Package_Name & "Subunits");
Res_Cont_Id := Encl_Cont_Id (Parent_Body);
Reset_Context (Res_Cont_Id);
Arg_Kind := Kind (Parent_Body);
if not (Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Subunits");
end if;
Arg_Unit_Id := Get_Unit_Id (Parent_Body);
declare
Result_Id_List : constant Unit_Id_List :=
Subunits (Res_Cont_Id, Arg_Unit_Id);
Result_List : constant Compilation_Unit_List :=
Get_Comp_Unit_List (Result_Id_List, Res_Cont_Id);
begin
return Result_List;
end;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Subunits");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Subunits",
Ex => Ex,
Arg_CU => Parent_Body);
end Subunits;
function Subunits
(Parent_Body : Asis.Compilation_Unit;
The_Context : Asis.Context)
return Asis.Compilation_Unit_List
is
Arg_Kind : Asis.Unit_Kinds;
Arg_Unit_Id : Unit_Id;
Arg_Cont_Id : Context_Id;
Result_Cont_Id : Context_Id;
New_Arg_Unit_Id : Unit_Id;
begin
Check_Validity (The_Context, Package_Name & "Subunits");
Check_Validity (Parent_Body, Package_Name & "Subunits");
Arg_Cont_Id := Encl_Cont_Id (Parent_Body);
Reset_Context (Arg_Cont_Id);
Arg_Kind := Kind (Parent_Body);
if not (Arg_Kind = A_Procedure_Body or else
Arg_Kind = A_Function_Body or else
Arg_Kind = A_Package_Body or else
Arg_Kind = A_Procedure_Body_Subunit or else
Arg_Kind = A_Function_Body_Subunit or else
Arg_Kind = A_Package_Body_Subunit or else
Arg_Kind = A_Task_Body_Subunit or else
Arg_Kind = A_Protected_Body_Subunit)
then
Raise_ASIS_Inappropriate_Compilation_Unit
(Diagnosis => Package_Name & "Subunits");
end if;
Result_Cont_Id := Get_Cont_Id (The_Context);
Arg_Unit_Id := Get_Unit_Id (Parent_Body);
New_Arg_Unit_Id := Get_Same_Unit
(Arg_Cont_Id, Arg_Unit_Id, Result_Cont_Id);
if Present (New_Arg_Unit_Id) then
return Subunits
(Get_Comp_Unit (New_Arg_Unit_Id, Result_Cont_Id));
else
return Nil_Compilation_Unit_List;
end if;
exception
when ASIS_Inappropriate_Compilation_Unit
| ASIS_Inappropriate_Context =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Subunits");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Subunits",
Ex => Ex,
Arg_CU => Parent_Body,
Context_Par => True);
end Subunits;
---------------
-- Text_Form --
---------------
function Text_Form
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Text_Form");
return Nil_Asis_Wide_String;
end Text_Form;
---------------
-- Text_Name --
---------------
function Text_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Text_Name");
if not Exists (Compilation_Unit) then
return Nil_Asis_Wide_String;
else
-- Exists resets the Context!
return To_Program_Text (Source_File (Compilation_Unit));
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Text_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Text_Name",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Text_Name;
-----------------
-- Unique_Name --
-----------------
function Unique_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
Arg_Kind : Unit_Kinds;
begin
Check_Validity (Compilation_Unit, Package_Name & "Unique_Name");
if Is_Nil (Compilation_Unit) then
return Nil_Asis_Wide_String;
else
Reset_Context (Encl_Cont_Id (Compilation_Unit));
Arg_Kind := Unit_Kind (Compilation_Unit);
-- ???!! Diagnosis_Buffer and Diagnosis_Len should not be used here!
Diagnosis_Len := 0;
A4G.Vcheck.Add (Context_Info (Compilation_Unit));
A4G.Vcheck.Add (": ");
A4G.Vcheck.Add (Unit_Name (Compilation_Unit));
case Arg_Kind is
when Asis.A_Library_Unit_Body =>
A4G.Vcheck.Add (" (body)");
when Asis.A_Subunit =>
A4G.Vcheck.Add (" (subunit)");
when others =>
A4G.Vcheck.Add (" (spec)");
end case;
return To_Program_Text (Diagnosis_Buffer (1 .. Diagnosis_Len));
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Unique_Name",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Unique_Name;
----------------
-- Unit_Class --
----------------
function Unit_Class
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Classes
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Unit_Class");
Reset_Context (Encl_Cont_Id (Compilation_Unit));
return Class (Compilation_Unit);
end Unit_Class;
--------------------
-- Unit_Full_Name --
--------------------
function Unit_Full_Name
(Compilation_Unit : Asis.Compilation_Unit)
return Wide_String
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Unit_Full_Name");
if Is_Nil (Compilation_Unit) or else
Unit_Kind (Compilation_Unit) = A_Configuration_Compilation
then
return Nil_Asis_Wide_String;
else
Reset_Context (Encl_Cont_Id (Compilation_Unit));
return To_Program_Text (Unit_Name (Compilation_Unit));
end if;
exception
when ASIS_Inappropriate_Compilation_Unit =>
raise;
when ASIS_Failed =>
if Status_Indicator = Unhandled_Exception_Error then
Add_Call_Information
(Outer_Call => Package_Name & "Unit_Full_Name");
end if;
raise;
when Ex : others =>
Report_ASIS_Bug
(Query_Name => Package_Name & "Unit_Full_Name",
Ex => Ex,
Arg_CU => Compilation_Unit);
end Unit_Full_Name;
---------------
-- Unit_Kind --
---------------
function Unit_Kind
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Kinds
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Unit_Kind");
return Kind (Compilation_Unit);
end Unit_Kind;
-----------------
-- Unit_Origin --
-----------------
function Unit_Origin
(Compilation_Unit : Asis.Compilation_Unit)
return Asis.Unit_Origins
is
begin
Check_Validity (Compilation_Unit, Package_Name & "Unit_Origin");
Reset_Context (Encl_Cont_Id (Compilation_Unit));
return Origin (Compilation_Unit);
end Unit_Origin;
end Asis.Compilation_Units;
|
reznikmm/matreshka | Ada | 4,021 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.DOM.Office_Server_Map_Attributes;
package Matreshka.ODF_Office.Server_Map_Attributes is
type Office_Server_Map_Attribute_Node is
new Matreshka.ODF_Office.Abstract_Office_Attribute_Node
and ODF.DOM.Office_Server_Map_Attributes.ODF_Office_Server_Map_Attribute
with null record;
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Office_Server_Map_Attribute_Node;
overriding function Get_Local_Name
(Self : not null access constant Office_Server_Map_Attribute_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Office.Server_Map_Attributes;
|
reznikmm/matreshka | Ada | 6,356 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
package AMF.Internals.Tables.OCL_Constructors is
function Create_OCL_Any_Type return AMF.Internals.AMF_Element;
function Create_OCL_Association_Class_Call_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Bag_Type return AMF.Internals.AMF_Element;
function Create_OCL_Boolean_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Collection_Item return AMF.Internals.AMF_Element;
function Create_OCL_Collection_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Collection_Range return AMF.Internals.AMF_Element;
function Create_OCL_Collection_Type return AMF.Internals.AMF_Element;
function Create_OCL_Enum_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Expression_In_Ocl return AMF.Internals.AMF_Element;
function Create_OCL_If_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Integer_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Invalid_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Invalid_Type return AMF.Internals.AMF_Element;
function Create_OCL_Iterate_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Iterator_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Let_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Message_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Message_Type return AMF.Internals.AMF_Element;
function Create_OCL_Null_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Operation_Call_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Ordered_Set_Type return AMF.Internals.AMF_Element;
function Create_OCL_Property_Call_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Real_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Sequence_Type return AMF.Internals.AMF_Element;
function Create_OCL_Set_Type return AMF.Internals.AMF_Element;
function Create_OCL_State_Exp return AMF.Internals.AMF_Element;
function Create_OCL_String_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Template_Parameter_Type return AMF.Internals.AMF_Element;
function Create_OCL_Tuple_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Tuple_Literal_Part return AMF.Internals.AMF_Element;
function Create_OCL_Tuple_Type return AMF.Internals.AMF_Element;
function Create_OCL_Type_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Unlimited_Natural_Literal_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Unspecified_Value_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Variable return AMF.Internals.AMF_Element;
function Create_OCL_Variable_Exp return AMF.Internals.AMF_Element;
function Create_OCL_Void_Type return AMF.Internals.AMF_Element;
end AMF.Internals.Tables.OCL_Constructors;
|
luk9400/nsi | Ada | 326 | ads | package Primes with SPARK_Mode is
function IsPrime (N : in Positive) return Boolean
with
SPARK_Mode,
Pre => N >= 2,
Post => (if IsPrime'Result then
(for all I in 2 .. N - 1 => N rem I /= 0)
else
(for some I in 2 .. N - 1 => N rem I = 0));
end Primes;
|
MinimSecure/unum-sdk | Ada | 2,107 | adb | -- Copyright 2009-2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
procedure Foo is
task type Caller is
entry Initialize;
entry Call_Break_Me;
entry Finalize;
end Caller;
type Caller_Ptr is access Caller;
procedure Break_Me is
begin
null;
end Break_Me;
task body Caller is
begin
accept Initialize do
null;
end Initialize;
accept Call_Break_Me do
Break_Me;
end Call_Break_Me;
accept Finalize do
null;
end Finalize;
end Caller;
Task_List : array (1 .. 3) of Caller_Ptr;
begin
-- Start all our tasks, and call the "Initialize" entry to make
-- sure all of them have now been started. We call that entry
-- immediately after having created the task in order to make sure
-- that we wait for that task to be created before we try to create
-- another one. That way, we know that the order in our Task_List
-- corresponds to the order in the GNAT runtime.
for J in Task_List'Range loop
Task_List (J) := new Caller;
Task_List (J).Initialize;
end loop;
-- Next, call their Call_Break_Me entry of each task, using the same
-- order as the order used to create them.
for J in Task_List'Range loop -- STOP_HERE
Task_List (J).Call_Break_Me;
end loop;
-- And finally, let all the tasks die...
for J in Task_List'Range loop
Task_List (J).Finalize;
end loop;
end Foo;
|
AdaCore/training_material | Ada | 222 | adb | package body Test_Suite.Test is
type TC_T is new Test_Case_T with null record;
procedure Run (TC : TC_T) is
begin
Run_Test (TC);
end Run;
begin
Register (new TC_T, Name);
end Test_Suite.Test;
|
osannolik/ada-canopen | Ada | 2,277 | adb | package body ACO.Utils.DS.Generic_Collection.Sorted is
overriding
procedure Insert
(C : in out Sorted_Collection;
Item : in Item_Type)
is
P : Collection renames Collection (C);
begin
for Index in 1 .. Length (P) loop
if not (Item_At (P, Index) < Item) then
Insert (P, Item, Index);
return;
end if;
end loop;
Append (P, Item);
end Insert;
overriding
procedure Insert
(C : in out Sorted_Collection;
Item : in Item_Type;
Before : in Positive)
is
P : Collection renames Collection (C);
Current : constant Item_Type := Item_At (C, Before);
begin
if Item < Current or else Current < Item then
Insert (C, Item);
else
Insert (P, Before => Before, Item => Item);
end if;
end Insert;
overriding
procedure Append
(C : in out Sorted_Collection;
Item : in Item_Type)
is
P : Collection renames Collection (C);
begin
for Index in 1 .. Length (P) loop
if Item < Item_At (P, Index) then
Insert (P, Item, Index);
return;
end if;
end loop;
Append (P, Item);
end Append;
overriding
procedure Append
(C : in out Sorted_Collection;
Item : in Item_Type;
After : in Positive)
is
P : Collection renames Collection (C);
Current : constant Item_Type := Item_At (C, After);
begin
if Item < Current or else Current < Item then
Append (C, Item);
else
Append (P, After => After, Item => Item);
end if;
end Append;
overriding
procedure Replace
(C : in out Sorted_Collection;
At_Index : in Positive;
Item : in Item_Type)
is
P : Collection renames Collection (C);
Current : constant Item_Type := Item_At (C, At_Index);
begin
if Item < Current then
Remove (C, At_Index);
Append (C, Item);
elsif Current < Item then
Remove (C, At_Index);
Insert (C, Item);
else
Replace (P, Index => At_Index, Item => Item);
end if;
end Replace;
end ACO.Utils.DS.Generic_Collection.Sorted;
|
zhmu/ananas | Ada | 60 | ads | generic
Param : String;
package Generic_Inst4_Gen is end;
|
onox/dcf-ada | Ada | 10,897 | adb | -- SPDX-License-Identifier: MIT
--
-- Copyright (c) 2016 - 2018 Gautier de Montmollin
-- SWITZERLAND
--
-- The copyright holder is only the maintainer of the Ada version;
-- authors of the C code and those of the algorithm are cited below.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
-- Author: lode.vandevenne [*] gmail [*] com (Lode Vandevenne)
-- Author: jyrki.alakuijala [*] gmail [*] com (Jyrki Alakuijala)
--
-- Bounded package merge algorithm, based on the paper
-- "A Fast and Space-Economical Algorithm for Length-Limited Coding
-- Jyrki Katajainen, Alistair Moffat, Andrew Turpin".
--
-- Translated by G. de Montmollin to Ada from katajainen.c (Zopfli project), 7-Feb-2016
--
-- Main technical differences to katajainen.c:
--
-- - Pointers are not used, array indices instead
-- - All structures are allocated on stack
-- - Sub-programs are nested, then unneeded parameters are removed
procedure DCF.Length_Limited_Huffman_Code_Lengths
(Frequencies : in Count_Array;
Bit_Lengths : out Length_Array)
is
subtype Index_Type is Count_Type;
Null_Index : constant Index_Type := Index_Type'Last;
-- Nodes forming chains
type Node is record
Weight : Count_Type;
Count : Count_Type; -- Number of leaves before this chain
Tail : Index_Type := Null_Index; -- Previous node(s) of this chain, or null_index if none
In_Use : Boolean := False; -- Tracking for garbage collection
end record;
type Leaf_Node is record
Weight : Count_Type;
Symbol : Alphabet;
end record;
-- Memory pool for nodes
Pool : array (0 .. Index_Type (2 * Max_Bits * (Max_Bits + 1) - 1)) of Node;
Pool_Next : Index_Type := Pool'First;
type Index_Pair is array (Index_Type'(0) .. 1) of Index_Type;
Lists : array (0 .. Index_Type (Max_Bits - 1)) of Index_Pair;
type Leaf_Array is array (Index_Type range <>) of Leaf_Node;
Leaves : Leaf_Array (0 .. Frequencies'Length - 1);
Num_Symbols : Count_Type := 0; -- Amount of symbols with frequency > 0
Num_Boundary_Pm_Runs : Count_Type;
Too_Many_Symbols_For_Length_Limit : exception;
Zero_Length_But_Nonzero_Frequency : exception;
Nonzero_Length_But_Zero_Frequency : exception;
Length_Exceeds_Length_Limit : exception;
Buggy_Sorting : exception;
procedure Init_Node (Weight, Count : Count_Type; Tail, Node_Idx : Index_Type) is
begin
Pool (Node_Idx).Weight := Weight;
Pool (Node_Idx).Count := Count;
Pool (Node_Idx).Tail := Tail;
Pool (Node_Idx).In_Use := True;
end Init_Node;
-- Finds a free location in the memory pool. Performs garbage collection if needed
-- If use_lists = True, used to mark in-use nodes during garbage collection
function Get_Free_Node (Use_Lists : Boolean) return Index_Type is
Node_Idx : Index_Type;
begin
loop
if Pool_Next > Pool'Last then
-- Garbage collection
for I in Pool'Range loop
Pool (I).In_Use := False;
end loop;
if Use_Lists then
for I in 0 .. Index_Type (Max_Bits * 2 - 1) loop
Node_Idx := Lists (I / 2) (I mod 2);
while Node_Idx /= Null_Index loop
Pool (Node_Idx).In_Use := True;
Node_Idx := Pool (Node_Idx).Tail;
end loop;
end loop;
end if;
Pool_Next := Pool'First;
end if;
exit when not Pool (Pool_Next).In_Use; -- Found one
Pool_Next := Pool_Next + 1;
end loop;
Pool_Next := Pool_Next + 1;
return Pool_Next - 1;
end Get_Free_Node;
-- Performs a Boundary Package-Merge step. Puts a new chain in the given list. The
-- new chain is, depending on the weights, a leaf or a combination of two chains
-- from the previous list.
-- index: The index of the list in which a new chain or leaf is required.
-- final: Whether this is the last time this function is called. If it is then it
-- is no more needed to recursively call self.
procedure Boundary_Pm (Index : Index_Type; Final : Boolean) is
Newchain : Index_Type;
Oldchain : Index_Type;
Lastcount : constant Count_Type :=
Pool (Lists (Index) (1)).Count; -- Count of last chain of list
Sum : Count_Type;
begin
if Index = 0 and Lastcount >= Num_Symbols then
return;
end if;
Newchain := Get_Free_Node (Use_Lists => True);
Oldchain := Lists (Index) (1);
-- These are set up before the recursive calls below, so that there is a list
-- pointing to the new node, to let the garbage collection know it's in use
Lists (Index) := (Oldchain, Newchain);
if Index = 0 then
-- New leaf node in list 0
Init_Node (Leaves (Lastcount).Weight, Lastcount + 1, Null_Index, Newchain);
else
Sum := Pool (Lists (Index - 1) (0)).Weight + Pool (Lists (Index - 1) (1)).Weight;
if Lastcount < Num_Symbols and then Sum > Leaves (Lastcount).Weight then
-- New leaf inserted in list, so count is incremented
Init_Node (Leaves (Lastcount).Weight, Lastcount + 1, Pool (Oldchain).Tail, Newchain);
else
Init_Node (Sum, Lastcount, Lists (Index - 1) (1), Newchain);
if not Final then
-- Two lookahead chains of previous list used up, create new ones
Boundary_Pm (Index - 1, False);
Boundary_Pm (Index - 1, False);
end if;
end if;
end if;
end Boundary_Pm;
-- Initializes each list with as lookahead chains the two leaves with lowest weights
procedure Init_Lists is
Node0 : constant Index_Type := Get_Free_Node (Use_Lists => False);
Node1 : constant Index_Type := Get_Free_Node (Use_Lists => False);
begin
Init_Node (Leaves (0).Weight, 1, Null_Index, Node0);
Init_Node (Leaves (1).Weight, 2, Null_Index, Node1);
Lists := (others => (Node0, Node1));
end Init_Lists;
-- Converts result of boundary package-merge to the bit_lengths. The result in the
-- last chain of the last list contains the amount of active leaves in each list.
-- chain: Chain to extract the bit length from (last chain from last list).
procedure Extract_Bit_Lengths (Chain : Index_Type) is
Node_Idx : Index_Type := Chain;
begin
while Node_Idx /= Null_Index loop
for I in 0 .. Pool (Node_Idx).Count - 1 loop
Bit_Lengths (Leaves (I).Symbol) := Bit_Lengths (Leaves (I).Symbol) + 1;
end loop;
Node_Idx := Pool (Node_Idx).Tail;
end loop;
end Extract_Bit_Lengths;
function "<" (A, B : Leaf_Node) return Boolean is
begin
return A.Weight < B.Weight;
end "<";
procedure Quick_Sort (A : in out Leaf_Array) is
N : constant Index_Type := A'Length;
I, J : Index_Type;
P, T : Leaf_Node;
begin
if N < 2 then
return;
end if;
P := A (N / 2 + A'First);
I := 0;
J := N - 1;
loop
while A (I + A'First) < P loop
I := I + 1;
end loop;
while P < A (J + A'First) loop
J := J - 1;
end loop;
exit when I >= J;
T := A (I + A'First);
A (I + A'First) := A (J + A'First);
A (J + A'First) := T;
I := I + 1;
J := J - 1;
end loop;
Quick_Sort (A (A'First .. A'First + I - 1));
Quick_Sort (A (A'First + I .. A'Last));
end Quick_Sort;
Paranoid : constant Boolean := False;
begin
Bit_Lengths := (others => 0);
-- Count used symbols and place them in the leaves
for A in Alphabet loop
if Frequencies (A) > 0 then
Leaves (Num_Symbols) := (Frequencies (A), A);
Num_Symbols := Num_Symbols + 1;
end if;
end loop;
-- Check special cases and error conditions
if Num_Symbols > 2**Max_Bits then
raise Too_Many_Symbols_For_Length_Limit; -- Error, too few max_bits to represent symbols
end if;
if Num_Symbols = 0 then
return; -- No symbols at all. OK
end if;
if Num_Symbols = 1 then
Bit_Lengths (Leaves (0).Symbol) := 1;
return; -- Only one symbol, give it bit length 1, not 0. OK
end if;
-- Sort the leaves from lightest to heaviest
Quick_Sort (Leaves (0 .. Num_Symbols - 1));
if Paranoid then
for I in 1 .. Num_Symbols - 1 loop
if Leaves (I) < Leaves (I - 1) then
raise Buggy_Sorting;
end if;
end loop;
end if;
Init_Lists;
-- In the last list, 2 * num_symbols - 2 active chains need to be created. Two
-- are already created in the initialization. Each Boundary_PM run creates one.
Num_Boundary_Pm_Runs := 2 * Num_Symbols - 4;
for I in 1 .. Num_Boundary_Pm_Runs loop
Boundary_Pm (Index_Type (Max_Bits - 1), I = Num_Boundary_Pm_Runs);
end loop;
Extract_Bit_Lengths (Lists (Index_Type (Max_Bits - 1)) (1));
if Paranoid then
-- Done; some checks before leaving. Not checked: completeness of Huffman codes
for A in Alphabet loop
if Frequencies (A) = 0 then
if Bit_Lengths (A) > 0 then
raise Nonzero_Length_But_Zero_Frequency; -- Never happened so far
end if;
else
if Bit_Lengths (A) = 0 then
raise Zero_Length_But_Nonzero_Frequency; -- Happened before null_index fix
elsif Bit_Lengths (A) > Max_Bits then
raise Length_Exceeds_Length_Limit; -- Never happened so far
end if;
end if;
end loop;
end if;
end DCF.Length_Limited_Huffman_Code_Lengths;
|
AdaCore/Ada_Drivers_Library | Ada | 3,902 | adb | with Ada.Text_IO;
with Logging_With_Priority;
procedure TC_Log_Priorities is
Maximum_Message_Length : constant := 64;
package Log is new Logging_With_Priority
(Priorities => Natural,
Maximum_Message_Length => Maximum_Message_Length,
Maximum_Number_Of_Messages => 6);
procedure Pop_And_Print;
procedure Fill_Queue;
procedure Empty_Queue;
-------------------
-- Pop_And_Print --
-------------------
procedure Pop_And_Print is
Str : String (1 .. Maximum_Message_Length);
Length : Natural;
Prio : Natural;
begin
Log.Pop (Str, Length, Prio);
if Length /= 0 then
Ada.Text_IO.Put_Line ("Prio:" & Prio'Img & " -> " &
Str (Str'First .. Str'First + Length - 1));
else
Ada.Text_IO.Put_Line ("Pop : The queue is empty");
end if;
end Pop_And_Print;
----------------
-- Fill_Queue --
----------------
procedure Fill_Queue is
begin
Log.Log_Line ("Prio 1 - 1", 1);
Log.Log_Line ("Prio 2 - 1", 2);
Log.Log_Line ("Prio 5 - 1", 5);
Log.Log_Line ("Prio 1 - 2", 1);
Log.Log_Line ("Prio 5 - 2", 5);
Log.Log_Line ("Prio 8 - 1", 8);
if not Log.Full then
raise Program_Error with "The queue should be full";
end if;
end Fill_Queue;
-----------------
-- Empty_Queue --
-----------------
procedure Empty_Queue is
begin
-- Empty the queue
for Cnt in 1 .. 6 loop
Pop_And_Print;
end loop;
if not Log.Empty then
raise Program_Error with "The queue should be empty";
end if;
end Empty_Queue;
begin
Ada.Text_IO.Put_Line ("--- Log test begin ---");
declare
begin
Ada.Text_IO.Put_Line ("--- Test priorities ---");
-- Try to print but there should be nothing in the queue
Pop_And_Print;
-- Insert a few messages with various priorities to check that the messages
-- will be properly sorted.
Fill_Queue;
Empty_Queue;
-- Try to print but there should be nothing in the queue
Pop_And_Print;
end;
declare
begin
Ada.Text_IO.Put_Line ("--- Test insert lower prio in full queue ---");
-- Insert a message with a prio below all the other priorities so it
-- should be rejected.
Fill_Queue;
Log.Log_Line ("Prio 0 - This message should be discarded", 0);
Empty_Queue;
-- Try to print but there should be nothing in the queue
Pop_And_Print;
end;
declare
begin
Ada.Text_IO.Put_Line ("--- Test insert low prio in full queue ---");
-- Insert a message with a prio equal to the lowest but it should be
-- rejected because there's no more room.
Fill_Queue;
Log.Log_Line ("Prio 1 - This message should be discarded", 1);
Empty_Queue;
-- Try to print but there should be nothing in the queue
Pop_And_Print;
end;
declare
begin
Ada.Text_IO.Put_Line ("--- Test insert high prio in full queue ---");
-- Insert a message with a prio above all the other priorities so it
-- should be accepted in the queue.
Fill_Queue;
Log.Log_Line ("Prio 9 - This message should be accepted", 9);
Empty_Queue;
-- Try to print but there should be nothing in the queue
Pop_And_Print;
end;
declare
Str : constant String (1 .. Maximum_Message_Length + 10) := (others => 'a');
begin
Ada.Text_IO.Put_Line ("--- Test insert too long message ---");
-- Insert a message with a length over the limit so it should be
-- rejected.
Fill_Queue;
Log.Log_Line (Str, 9);
Empty_Queue;
-- Try to print but there should be nothing in the queue
Pop_And_Print;
end;
Ada.Text_IO.Put_Line ("--- Log test end ---");
end TC_Log_Priorities;
|
DrenfongWong/tkm-rpc | Ada | 409 | ads | with Ada.Unchecked_Conversion;
package Tkmrpc.Response.Cfg.Tkm_Version.Convert is
function To_Response is new Ada.Unchecked_Conversion (
Source => Tkm_Version.Response_Type,
Target => Response.Data_Type);
function From_Response is new Ada.Unchecked_Conversion (
Source => Response.Data_Type,
Target => Tkm_Version.Response_Type);
end Tkmrpc.Response.Cfg.Tkm_Version.Convert;
|
godunko/adawebpack | Ada | 6,589 | ads | ------------------------------------------------------------------------------
-- --
-- AdaWebPack --
-- --
------------------------------------------------------------------------------
-- Copyright © 2020, Vadim Godunko --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
------------------------------------------------------------------------------
with Ada.Streams;
with WASM.Objects;
with Web.DOM.Event_Listeners;
with Web.DOM.Event_Targets;
with Web.Strings;
package Web.Sockets is
pragma Preelaborate;
type Web_Socket is new WASM.Objects.Object_Reference
and Web.DOM.Event_Targets.Event_Target
with null record;
overriding procedure Add_Event_Listener
(Self : in out Web_Socket;
Name : Web.Strings.Web_String;
Callback : not null Web.DOM.Event_Listeners.Event_Listener_Access;
Capture : Boolean := False);
function Create (URL : Web.Strings.Web_String) return Web_Socket;
-- Creates a new WebSocket object, immediately establishing the associated
-- WebSocket connection.
--
-- URL is a string giving the URL over which the connection is established.
-- Only "ws" or "wss" schemes are allowed; others will cause a
-- "SyntaxError" DOMException. URLs with fragments will also cause such an
-- exception.
function Get_URL (Self : Web_Socket'Class) return Web.Strings.Web_String;
-- Returns the URL that was used to establish the WebSocket connection.
type State is
(CONNECTING, -- The connection has not yet been established.
OPEN, -- The WebSocket connection is established and
-- communication is possible.
CLOSING, -- The connection is going through the closing handshake,
-- or the close () method has been invoked.
CLOSED); -- The connection has been closed or could not be opened.
for State use (CONNECTING => 0, OPEN => 1, CLOSING => 2, CLOSED => 3);
function Get_Ready_State (Self : Web_Socket'Class) return State;
-- Returns the state of the WebSocket object's connection. It can have the
-- values described below.
function Get_Buffered_Amount
(Self : Web_Socket'Class) return Ada.Streams.Stream_Element_Count;
-- Returns the number of bytes of application data (UTF-8 text and binary
-- data) that have been queued using send() but not yet been transmitted
-- to the network.
--
-- If the WebSocket connection is closed, this attribute's value will only
-- increase with each call to the send() method. (The number does not reset
-- to zero once the connection closes.)
function Get_Extensions
(Self : Web_Socket'Class) return Web.Strings.Web_String;
-- Returns the extensions selected by the server, if any.
function Get_Protocol
(Self : Web_Socket'Class) return Web.Strings.Web_String;
-- Returns the subprotocol selected by the server, if any. It can be used
-- in conjunction with the array form of the constructor's second argument
-- to perform subprotocol negotiation.
procedure Close (Self : in out Web_Socket'Class);
-- Closes the WebSocket connection, optionally using code as the the
-- WebSocket connection close code and reason as the the WebSocket
-- connection close reason.
type Binary_Type is (blob, arraybuffer);
-- * "blob" - Binary data is returned in Blob form.
-- * "arraybuffer" - Binary data is returned in ArrayBuffer form.
function Get_Binary_Type (Self : Web_Socket'Class) return Binary_Type;
-- Returns a string that indicates how binary data from the WebSocket
-- object is exposed to scripts.
--
-- Can be set, to change how binary data is returned. The default is blob.
procedure Set_Binary_Type
(Self : in out Web_Socket'Class;
Value : Binary_Type);
procedure Send
(Self : in out Web_Socket'Class;
Data : Web.Strings.Web_String);
-- Transmits data using the WebSocket connection. data can be a string, a
-- Blob, an ArrayBuffer, or an ArrayBufferView.
procedure Send
(Self : in out Web_Socket'Class;
Data : Ada.Streams.Stream_Element_Array);
-- The same for binary data
end Web.Sockets;
|
tj800x/SPARKNaCl | Ada | 37,990 | adb | with SPARKNaCl.Utils;
with SPARKNaCl.Hashing;
package body SPARKNaCl.Sign
with SPARK_Mode => On
is
--============================================
-- Local constants and types
--============================================
GF_D : constant Normal_GF := (16#78a3#, 16#1359#, 16#4dca#, 16#75eb#,
16#d8ab#, 16#4141#, 16#0a4d#, 16#0070#,
16#e898#, 16#7779#, 16#4079#, 16#8cc7#,
16#fe73#, 16#2b6f#, 16#6cee#, 16#5203#);
GF_I : constant Normal_GF := (16#a0b0#, 16#4a0e#, 16#1b27#, 16#c4ee#,
16#e478#, 16#ad2f#, 16#1806#, 16#2f43#,
16#d7a7#, 16#3dfb#, 16#0099#, 16#2b4d#,
16#df0b#, 16#4fc1#, 16#2480#, 16#2b83#);
GF_X : constant Normal_GF := (16#d51a#, 16#8f25#, 16#2d60#, 16#c956#,
16#a7b2#, 16#9525#, 16#c760#, 16#692c#,
16#dc5c#, 16#fdd6#, 16#e231#, 16#c0a4#,
16#53fe#, 16#cd6e#, 16#36d3#, 16#2169#);
GF_Y : constant Normal_GF := (16#6658#, 16#6666#, 16#6666#, 16#6666#,
16#6666#, 16#6666#, 16#6666#, 16#6666#,
16#6666#, 16#6666#, 16#6666#, 16#6666#,
16#6666#, 16#6666#, 16#6666#, 16#6666#);
-- Original TweetNaCl code computes Q(3) by multiplying GF_X by GF_Y,
-- but this is a constant (now called GF_XY), thus:
GF_XY : constant Normal_GF := (16#DD90#, 16#A5B7#, 16#8AB3#, 16#6DDE#,
16#52F5#, 16#7751#, 16#9F80#, 16#20F0#,
16#E37D#, 16#64AB#, 16#4E8E#, 16#66EA#,
16#7665#, 16#D78B#, 16#5F0F#, 16#E787#);
GF_D2 : constant Normal_GF := (16#f159#, 16#26b2#, 16#9b94#, 16#ebd6#,
16#b156#, 16#8283#, 16#149a#, 16#00e0#,
16#d130#, 16#eef3#, 16#80f2#, 16#198e#,
16#fce7#, 16#56df#, 16#d9dc#, 16#2406#);
type GF_Vector_4 is array (Index_4) of Normal_GF;
-- We make this constant library-level to ensure that its declaration
-- is only elaborated exactly once.
Scalarbase_Q : constant GF_Vector_4 := (0 => GF_X,
1 => GF_Y,
2 => GF_1,
3 => GF_XY);
-- MBP = "Max Byte Product"
MBP : constant := (255 * 255);
Max_X_Limb : constant := (32 * MBP) + 255;
--============================================
-- Local subprogram declarations
--============================================
function ModL (X : in I64_Seq_64) return Bytes_32
with Global => null,
Pre => (for all K in Index_64 => X (K) in 0 .. Max_X_Limb);
procedure Sanitize_GF_Vector_4 (R : out GF_Vector_4)
with Global => null;
-- Replaces function "add" in the TweetNaCl sources
procedure Add (Left : in out GF_Vector_4;
Right : in GF_Vector_4)
with Global => null;
procedure Double (P : in out GF_Vector_4)
with Global => null;
function Scalarmult (Q : in GF_Vector_4;
S : in Bytes_32) return GF_Vector_4
with Global => null;
function Scalarbase (S : in Bytes_32) return GF_Vector_4
with Global => null;
function Pack (P : in GF_Vector_4) return Bytes_32
with Global => null;
subtype Bit is Byte range 0 .. 1;
function Par_25519 (A : in Normal_GF) return Bit
with Global => null;
-- SPARKNaCl introduces this function to combine Hash and Reduce into
-- a single call. Former procedure Reduce removed.
function Hash_Reduce (M : in Byte_Seq) return Bytes_32
with Global => null;
procedure Unpackneg (R : out GF_Vector_4;
OK : out Boolean;
P : in Bytes_32)
with Global => null;
--============================================
-- Local subprogram bodies
--============================================
procedure Sanitize_GF_Vector_4 (R : out GF_Vector_4)
is
begin
for I in R'Range loop
Sanitize_GF (R (I));
end loop;
end Sanitize_GF_Vector_4;
procedure Add (Left : in out GF_Vector_4;
Right : in GF_Vector_4)
is
L0 : GF renames Left (0);
L1 : GF renames Left (1);
L2 : GF renames Left (2);
L3 : GF renames Left (3);
R0 : GF renames Right (0);
R1 : GF renames Right (1);
R2 : GF renames Right (2);
R3 : GF renames Right (3);
A, B, C, D, E, F : GF;
begin
A := (L1 - L0) * (R1 - R0);
B := (L0 + L1) * (R0 + R1);
E := B - A;
F := B + A;
-- We are now done with A and B, so these variables can now
-- be re-used. This saves yet more stack.
C := (L3 * R3) * GF_D2;
D := L2 * R2;
D := D + D;
A := D - C;
B := D + C;
-- Assign to Left element-by-element to avoid extra
-- temporary and copy needed by an aggregate assignment.
L0 := E * A;
L1 := F * B;
L2 := B * A;
L3 := E * F;
end Add;
procedure Double (P : in out GF_Vector_4)
is
-- Ada's anti-aliasing rules require an extra copy here.
T : constant GF_Vector_4 := P;
begin
Add (P, T);
end Double;
function Scalarmult (Q : in GF_Vector_4;
S : in Bytes_32) return GF_Vector_4
is
CB : Byte;
Swap : Boolean;
LP, LQ : GF_Vector_4;
procedure CSwap (P, Q : in out GF_Vector_4;
Swap : in Boolean)
with Global => null;
procedure CSwap (P, Q : in out GF_Vector_4;
Swap : in Boolean)
is
begin
for I in Index_4 loop
Utils.CSwap (P (I), Q (I), Swap);
end loop;
end CSwap;
begin
LP := (0 => GF_0,
1 => GF_1,
2 => GF_1,
3 => GF_0);
LQ := Q;
-- For each byte of S, starting at the MSB
for I in reverse Index_32 loop
CB := S (I);
-- For each bit of CB, starting with bit 7 (the MSB)
for J in reverse Natural range 0 .. 7 loop
Swap := Boolean'Val (Shift_Right (CB, J) mod 2);
CSwap (LP, LQ, Swap);
Add (LQ, LP);
Double (LP);
CSwap (LP, LQ, Swap);
end loop;
end loop;
return LP;
end Scalarmult;
function Scalarbase (S : in Bytes_32) return GF_Vector_4
is
begin
return Scalarmult (Scalarbase_Q, S);
end Scalarbase;
function Par_25519 (A : in Normal_GF) return Bit
is
D : Bytes_32;
begin
D := Utils.Pack_25519 (A);
return (D (0) mod 2);
end Par_25519;
function Pack (P : in GF_Vector_4) return Bytes_32
is
TX, TY, ZI : Normal_GF;
R : Bytes_32;
begin
ZI := Utils.Inv_25519 (P (2));
TX := P (0) * ZI;
TY := P (1) * ZI;
R := Utils.Pack_25519 (TY);
R (31) := R (31) xor (Par_25519 (TX) * 128);
return R;
end Pack;
-- RFC 7748 says the "order" of Curve25519 is
-- 2^252 + 0x14def9dea2f79cd65812631a5cf5d3ed
--
-- In little-endian radix 2**8 format, this is 256 bits, thus:
Max_L : constant := 16#f9#;
L0 : constant := 16#ed#;
subtype L_Limb is I64_Byte range 0 .. Max_L;
type L_Table is array (Index_32) of L_Limb;
L : constant L_Table := (L0, 16#d3#, 16#f5#, 16#5c#,
16#1a#, 16#63#, 16#12#, 16#58#,
16#d6#, 16#9c#, 16#f7#, 16#a2#,
16#de#, 16#f9#, 16#de#, 16#14#,
16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#10#);
function ModL (X : in I64_Seq_64) return Bytes_32
is
Max_Carry : constant := 2**14;
Min_Carry : constant := -2**25;
subtype Carry_T is I64 range Min_Carry .. Max_Carry;
Min_Adjustment : constant := (Min_Carry * 16 * Max_L);
Max_Adjustment : constant := ((Max_X_Limb + Max_Carry) * 16 * Max_L);
subtype Adjustment_T is I64
range Min_Adjustment .. Max_Adjustment;
subtype XL_Limb is I64
range -((Max_X_Limb + Max_Carry + Max_Adjustment) * 16 * Max_L) ..
((Max_X_Limb + Max_Carry + Max_Adjustment) * 16 * Max_L);
type XL_Table is array (Index_64) of XL_Limb;
XL : XL_Table;
-- "PRL" = "Partially Reduced Limb"
subtype PRL is I64 range -129 .. 128;
-- "FRL" = "Fully Reduced Limb"
subtype FRL is PRL range -128 .. 127;
R : Bytes_32;
-- The largest value of Carry is achieved when XL (63) = 0,
-- so that
-- Max_L63_Carry = ASR_8 (Max_X_Limb + Max_L63_Carry + 128)
-- Knowing that all the terms are positive means we can expand
-- ASR_8 and simplify.
-- This is declared here it can be used to derive subtype
-- XL51_T and used in the post-condition of Eliminate_Limb_63 below
Max_L63_Carry : constant := (Max_X_Limb + 128) / 255;
subtype XL51_T is I64 range 0 .. (Max_X_Limb + Max_L63_Carry);
procedure Initialize_XL
with Global => (Input => X,
Output => XL),
Pre => (for all K in Index_64 => X (K) in 0 .. Max_X_Limb),
Post => (for all K in Index_64 => XL (K) >= 0) and
(for all K in Index_64 => XL (K) <= Max_X_Limb) and
(for all K in Index_64 => XL (K) = XL_Limb (X (K)));
procedure Eliminate_Limb_63
with Global => (Proof_In => X,
In_Out => XL),
Pre => (for all K in Index_64 =>
X (K) in 0 .. Max_X_Limb) and then
(for all K in Index_64 => XL (K) >= 0) and then
(for all K in Index_64 => XL (K) <= Max_X_Limb) and then
(for all K in Index_64 => XL (K) = XL_Limb (X (K))),
Post => (for all K in Index_64 range 0 .. 30 =>
XL (K) = X (K)) and
(for all K in Index_64 range 31 .. 50 =>
XL (K) in FRL) and
(XL (51) in XL51_T) and
(for all K in Index_64 range 52 .. 62 =>
XL (K) = X (K)) and
(XL (63) = 0);
procedure Eliminate_Limbs_62_To_32
with Global => (Proof_In => X,
In_Out => XL),
Pre => ((for all K in Index_64 range 0 .. 30 =>
XL (K) = X (K) and
XL (K) in 0 .. Max_X_Limb) and
(for all K in Index_64 range 31 .. 50 =>
XL (K) in FRL) and
(XL (51) in XL51_T) and
(for all K in Index_64 range 52 .. 62 =>
XL (K) = X (K) and
XL (K) in 0 .. Max_X_Limb) and
(XL (63) = 0)),
Post => ((for all K in Index_64 range 0 .. 19 =>
XL (K) in FRL) and
(for all K in Index_64 range 20 .. 31 =>
XL (K) in PRL) and
(for all K in Index_64 range 32 .. 63 => XL (K) = 0));
procedure Finalize
with Global => (In_Out => XL,
Output => R),
Pre => ((for all K in Index_64 range 0 .. 19 =>
XL (K) in FRL) and
(for all K in Index_64 range 20 .. 31 =>
XL (K) in PRL) and
(for all K in Index_64 range 32 .. 63 => XL (K) = 0));
procedure Initialize_XL
is
begin
XL := (others => 0);
for K in Index_64 loop
XL (K) := XL_Limb (X (K));
pragma Loop_Invariant
(for all A in Index_64 range 0 .. K => XL (A) = XL_Limb (X (A)));
end loop;
end Initialize_XL;
procedure Eliminate_Limb_63
is
Max_L63_Adjustment : constant := 16 * Max_L * Max_X_Limb;
subtype L63_Adjustment_T is I64 range 0 .. Max_L63_Adjustment;
-- The most negative value of Carry is when XL (63) = Max_X_Limb and
-- L (J - 31) = Max_L and XL (J) = 0
-- so that
-- Min_L63_Carry =
-- ASR_8 (0 + Min_L63_Carry - Max_L63_Adjustment + 128)
Min_L63_Carry : constant := ((128 - Max_L63_Adjustment) / 255) - 1;
subtype L63_Carry_T is I64 range Min_L63_Carry .. Max_L63_Carry;
Carry : L63_Carry_T;
Adjustment : L63_Adjustment_T;
begin
Carry := 0;
-- In the TweetNaCl sources, this loop interates 20 times
-- covering elements of L from L (0) to L (19).
-- In this implementation, though, we choose to loop over the
-- first 16 elements of L first, since these are all non-zero,
-- and manually unroll the final 4 iterations where L (16)
-- through L (19) are all zero.
for J in I32 range 31 .. 46 loop
Adjustment := (16 * L (J - 31)) * XL (63);
XL (J) := XL (J) + Carry - Adjustment;
Carry := ASR_8 (XL (J) + 128);
XL (J) := XL (J) - (Carry * 256);
pragma Loop_Invariant
((for all K in Index_64 range 0 .. 30 =>
XL (K) = XL'Loop_Entry (K)) and
(for all K in Index_64 range 31 .. J =>
XL (K) in FRL) and
(for all K in Index_64 range J + 1 .. 63 =>
XL (K) = XL'Loop_Entry (K)));
end loop;
pragma Assert
((for all K in Index_64 range 0 .. 30 =>
XL (K) = X (K)) and
(for all K in Index_64 range 31 .. 46 =>
XL (K) in FRL) and
(for all K in Index_64 range 47 .. 63 =>
XL (K) = X (K)));
-- Final 4 limbs of XL (47) through XL (50)
-- For these limbs, we know that L (16) through L (19)
-- is zero, so the calculation of Adjustment can be eliminated.
--
-- As these final four limbs are processed, the upper bound
-- on Carry stays the same at Max_L63_Carry, but the lower bound
-- converges towards 0.
declare
-- Expand the definition of ASR_8 for values gives...
Min_XL47_Carry : constant :=
((Min_L63_Carry + 128 + 1) / 2**8) - 1;
pragma Assert (Min_XL47_Carry = -127006);
Min_XL48_Carry : constant :=
((Min_XL47_Carry + 128 + 1) / 2**8) - 1;
pragma Assert (Min_XL48_Carry = -496);
Min_XL49_Carry : constant :=
((Min_XL48_Carry + 128 + 1) / 2**8) - 1;
pragma Assert (Min_XL49_Carry = -2);
Min_XL50_Carry : constant := ((Min_XL49_Carry + 128) / 2**8);
pragma Assert (Min_XL50_Carry = 0);
begin
XL (47) := XL (47) + Carry;
Carry := ASR_8 (XL (47) + 128);
XL (47) := XL (47) - (Carry * 256);
pragma Assert (Carry >= Min_XL47_Carry);
XL (48) := XL (48) + Carry;
Carry := ASR_8 (XL (48) + 128);
XL (48) := XL (48) - (Carry * 256);
pragma Assert (Carry >= Min_XL48_Carry);
XL (49) := XL (49) + Carry;
Carry := ASR_8 (XL (49) + 128);
XL (49) := XL (49) - (Carry * 256);
pragma Assert (Carry >= Min_XL49_Carry);
XL (50) := XL (50) + Carry;
Carry := ASR_8 (XL (50) + 128);
XL (50) := XL (50) - (Carry * 256);
-- Lower bound on Carry should have converged to 0
pragma Assert (Min_XL50_Carry = 0);
pragma Assert (Carry >= Min_XL50_Carry);
end;
pragma Assert
((for all K in Index_64 range 0 .. 30 => XL (K) = X (K)) and
(for all K in Index_64 range 31 .. 50 => XL (K) in FRL) and
(for all K in Index_64 range 51 .. 63 => XL (K) = X (K)));
-- Note XL (51) is adjusted here but is NOT normalized
-- to be in FRL... hence it's a special case in the post-
-- condition above.
XL (51) := XL (51) + Carry;
pragma Assert (XL (51) in XL51_T);
XL (63) := 0;
end Eliminate_Limb_63;
procedure Eliminate_Limbs_62_To_32
is
Carry : Carry_T;
Adjustment : Adjustment_T;
begin
for I in reverse I32 range 32 .. 62 loop
Carry := 0;
-- As above, this loop iterates over limbs 0 .. 15 of L
-- leaving the final four (zero) limbs unrolled below.
for J in I32 range (I - 32) .. (I - 17) loop
Adjustment := (16 * L (J - (I - 32))) * XL (I);
XL (J) := XL (J) + Carry - Adjustment;
Carry := ASR_8 (XL (J) + 128);
XL (J) := XL (J) - (Carry * 256);
pragma Loop_Invariant
(for all K in Index_64 range 0 .. I - 33 =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range I - 32 .. J =>
XL (K) in FRL);
pragma Loop_Invariant
(for all K in Index_64 range J + 1 .. I32'Min (50, I - 1) =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range J + 1 .. I32'Min (50, I - 1) =>
XL (K) in PRL);
pragma Loop_Invariant
(for all K in Index_64 range I32'Max (I - 11, 52) .. I - 1 =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range I + 1 .. 63 => XL (K) = 0);
pragma Loop_Invariant
(for all K in Index_64 => XL (K) in PRL'First .. XL51_T'Last);
end loop;
-- 16 elements of XL(I-32) .. XL(I-17) are in now FRL
pragma Assert
(for all K in Index_64 range I - 32 .. I - 17 =>
XL (K) in FRL);
pragma Assert (XL (I - 16) in FRL);
-- Carry is in Carry_T here
XL (I - 16) := XL (I - 16) + Carry;
Carry := ASR_8 (XL (I - 16) + 128);
XL (I - 16) := XL (I - 16) - (Carry * 256);
-- 17 elements of XL are in FRL
pragma Assert
(for all K in Index_64 range I - 32 .. I - 16 =>
XL (K) in FRL);
pragma Assert (XL (I - 15) in FRL);
-- Now we can start to prove that Carry is converging.
-- Each further reduction reduces the lower and upper bound
-- of Carry by about 2**8, except that the addition of 128 and
-- ASR_8 actually mean that Carry converges on the range -1 .. 1
pragma Assert (Carry in -2**17 .. 64);
XL (I - 15) := XL (I - 15) + Carry;
Carry := ASR_8 (XL (I - 15) + 128);
XL (I - 15) := XL (I - 15) - (Carry * 256);
-- 18 elements of XL are in FRL
pragma Assert
(for all K in Index_64 range I - 32 .. I - 15 =>
XL (K) in FRL);
pragma Assert (XL (I - 14) in FRL);
pragma Assert (Carry in -512 .. 1);
XL (I - 14) := XL (I - 14) + Carry;
Carry := ASR_8 (XL (I - 14) + 128);
XL (I - 14) := XL (I - 14) - (Carry * 256);
-- 19 elements of XL are in FRL
pragma Assert
(for all K in Index_64 range I - 32 .. I - 14 =>
XL (K) in FRL);
pragma Assert (XL (I - 13) in FRL);
pragma Assert (Carry in -2 .. 1);
XL (I - 13) := XL (I - 13) + Carry;
Carry := ASR_8 (XL (I - 13) + 128);
XL (I - 13) := XL (I - 13) - (Carry * 256);
-- 20 elements of XL are in FRL
pragma Assert
(for all K in Index_64 range I - 32 .. I - 13 =>
XL (K) in FRL);
pragma Assert (XL (I - 12) in FRL);
pragma Assert (Carry in -1 .. 1);
-- If Carry in -1 .. 1, then the final adjustment of
-- XL (I - 12) means that this limb can end up being
-- -129 or +128, so in PRL but not in FRL
XL (I - 12) := XL (I - 12) + Carry;
pragma Assert (XL (I - 12) in PRL);
-- XL (I) is now eliminated, so it gets zeroed out now.
XL (I) := 0;
pragma Loop_Invariant
(for all K in Index_64 range 0 .. I - 33 =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range I - 32 .. I - 13 =>
XL (K) in FRL);
pragma Loop_Invariant
(XL (I - 12) in PRL);
pragma Loop_Invariant
(for all K in Index_64 range I - 11 .. I32'Min (50, I - 1) =>
XL (K) in PRL);
-- This is XL (51) for I in 52 .. 63
pragma Loop_Invariant
(if I >= 52 then
XL (51) >= XL'Loop_Entry (51) + Min_Carry);
pragma Loop_Invariant
(if I >= 52 then
XL (51) <= XL'Loop_Entry (51) + Max_Carry);
pragma Loop_Invariant
(for all K in Index_64 range I32'Max (I - 11, 52) .. I - 1 =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range I .. 63 => XL (K) = 0);
pragma Loop_Invariant
(for all K in Index_64 => XL (K) in PRL'First .. XL51_T'Last);
end loop;
end Eliminate_Limbs_62_To_32;
procedure Finalize
is
Final_Carry_Min : constant := -9;
Final_Carry_Max : constant := 9;
subtype Final_Carry_T is I64 range Final_Carry_Min .. Final_Carry_Max;
subtype Step1_XL_Limb is I64 range
(Final_Carry_Min * 256) ..
((Final_Carry_Max + 1) * 256) - 1;
subtype Step2_XL_Limb is I64 range
I64_Byte'First - (Final_Carry_Max * Max_L) ..
I64_Byte'Last - (Final_Carry_Min * Max_L);
Carry : Final_Carry_T;
begin
-- Step 1
Carry := 0;
for J in Index_32 loop
pragma Assert (XL (31) in PRL);
XL (J) := XL (J) + (Carry - ASR_4 (XL (31)) * L (J));
pragma Assert (XL (J) >= Step1_XL_Limb'First);
pragma Assert (XL (J) <= Step1_XL_Limb'Last);
Carry := ASR_8 (XL (J));
XL (J) := XL (J) mod 256;
-- Modified limbs 0 .. J are all in I64_Byte
pragma Loop_Invariant
(for all K in Index_64 range 0 .. J => XL (K) in I64_Byte);
-- Limbs J + 1 .. 31 are unmodified and in PRL
pragma Loop_Invariant
(for all K in Index_64 range J + 1 .. 31 =>
XL (K) = XL'Loop_Entry (K));
pragma Loop_Invariant
(for all K in Index_64 range J + 1 .. 31 =>
XL (K) in PRL);
-- Trailing 32 limbs are all 0
pragma Loop_Invariant
(for all K in Index_64 range 32 .. 63 => XL (K) = 0);
end loop;
-- Check first 32 limbs in I64_Byte
pragma Assert
(for all K in Index_64 range 0 .. 31 => XL (K) in I64_Byte);
-- Check later 32 limbs all 0
pragma Assert
(for all K in Index_64 range 32 .. 63 => XL (K) = 0);
-- Step 2
for J in Index_32 loop
XL (J) := XL (J) - Carry * L (J);
pragma Loop_Invariant
(for all K in Index_32 range 0 .. J =>
XL (K) in Step2_XL_Limb);
pragma Loop_Invariant
(for all K in Index_64 range 32 .. 63 => XL (K) = 0);
end loop;
pragma Assert
(for all K in Index_64 => XL (K) in Step2_XL_Limb);
pragma Assert
(for all K in Index_64 range 32 .. 63 => XL (K) = 0);
-- Step 3 - final carry chain from X (0) to X (32) and reduce
-- each limb mod 256
declare
-- In Step 3, XL(I+1) is added to ASR_8(XL(I)), so we need to know
-- the range of the ASR_8(XL(I)). A precise characterisation
-- of the bounds on XL (I+1) would be non-linear, so we fall
-- back on a linear over-approximation here, which suffices.
-- Max XL Carry - max magnitude of carry from XL(I) to XL(I+1)
MXLC : constant := 10;
-- Step 3 Carry
subtype S3CT is I64 range -MXLC .. MXLC;
S3C : S3CT;
begin
for I in Index_32 loop
pragma Assert (XL (I) >=
Step2_XL_Limb'First - MXLC * I64 (I));
S3C := ASR_8 (XL (I));
XL (I + 1) := XL (I + 1) + S3C;
R (I) := Byte (XL (I) mod 256);
pragma Loop_Invariant (XL (0) = XL'Loop_Entry (0));
pragma Loop_Invariant (XL (0) in Step2_XL_Limb);
pragma Loop_Invariant (if I <= 30 then XL (32) = 0);
pragma Loop_Invariant
(for all K in Index_32 range 1 .. 31 =>
XL (K) >= Step2_XL_Limb'First - (MXLC * I64 (K)));
pragma Loop_Invariant
(for all K in Index_32 range 1 .. 31 =>
XL (K) <= Step2_XL_Limb'Last + (MXLC * I64 (K)));
pragma Loop_Invariant
(for all K in Index_32 range I + 2 .. 31 =>
XL (K) in Step2_XL_Limb);
end loop;
end;
end Finalize;
begin
Initialize_XL;
Eliminate_Limb_63;
Eliminate_Limbs_62_To_32;
pragma Warnings (GNATProve, Off, "unused assignment");
-- Unused assignment to XL here expected
Finalize;
return R;
end ModL;
function Hash_Reduce (M : in Byte_Seq) return Bytes_32
is
R : Hashing.Digest;
X : I64_Seq_64;
begin
Hashing.Hash (R, M);
X := (others => 0);
for I in Index_64 loop
X (I) := I64 (R (I));
pragma Loop_Invariant
(for all K in Index_64 range 0 .. I => X (K) in I64_Byte);
end loop;
pragma Assert
(for all K in Index_64 => X (K) in I64_Byte);
return ModL (X);
end Hash_Reduce;
procedure Unpackneg (R : out GF_Vector_4;
OK : out Boolean;
P : in Bytes_32)
is
-- Local, time-constant equality test for GF
-- In the original TweetNaCl sources, this is called eq25519
function "=" (Left, Right : in Normal_GF) return Boolean
with Global => null;
function Pow_2523 (I : in Normal_GF) return Normal_GF
with Global => null;
function "=" (Left, Right : in Normal_GF) return Boolean
is
begin
return Equal (Bytes_32'(Utils.Pack_25519 (Left)),
Bytes_32'(Utils.Pack_25519 (Right)));
end "=";
function Pow_2523 (I : in Normal_GF) return Normal_GF
is
C, C2 : Normal_GF;
begin
C := I;
-- Note that 2**252 - 3 = 16#1111_1111 .. 1101#
-- with only "bit 1" set to 0
for A in reverse 0 .. 250 loop
C2 := Square (C);
if A = 1 then
C := C2;
else
C := C2 * I;
end if;
end loop;
return C;
end Pow_2523;
-- Note: refactoring here to functional/SSA form reduces the
-- number of calls to "*" from 8 in the original TweetNaCl code
-- to 5 from here until the initialization of R0, but only if
-- "*" on GF is commutative.
R1 : constant Normal_GF := Utils.Unpack_25519 (P);
R2 : Normal_GF renames GF_1;
R1_Squared : constant Normal_GF := Square (R1);
Num : constant Normal_GF := R1_Squared - R2;
Den : constant Normal_GF := R2 + (R1_Squared * GF_D);
Den_Power_2 : constant Normal_GF := Square (Den);
Den_Power_4 : constant Normal_GF := Square (Den_Power_2);
Num_Den2 : constant Normal_GF := (Num * Den) * Den_Power_2;
R0 : Normal_GF := Pow_2523 ((Den_Power_4 * Num_Den2)) * Num_Den2;
Check : Normal_GF;
begin
Check := Square (R0) * Den;
if Check /= Num then
R0 := R0 * GF_I;
end if;
Check := Square (R0) * Den;
if Check /= Num then
R := (others => GF_0);
OK := False;
return;
end if;
if Par_25519 (R0) = (P (31) / 128) then
R0 := GF_0 - R0;
end if;
R := (0 => R0,
1 => R1,
2 => R2,
3 => R0 * R1);
OK := True;
end Unpackneg;
--============================================
-- Exported subprogram bodies
--============================================
function Serialize (K : in Signing_SK) return Bytes_64
is
begin
return K.F;
end Serialize;
function Serialize (K : in Signing_PK) return Bytes_32
is
begin
return K.F;
end Serialize;
procedure Sanitize (K : out Signing_PK)
is
begin
SPARKNaCl.Sanitize (K.F);
end Sanitize;
procedure Sanitize (K : out Signing_SK)
is
begin
SPARKNaCl.Sanitize (K.F);
end Sanitize;
procedure Keypair_From_Bytes (SK_Raw : in Bytes_32; -- random please!
PK : out Signing_PK;
SK : out Signing_SK)
is
D : Bytes_64;
LPK : Bytes_32;
begin
Hashing.Hash (D, SK_Raw);
D (0) := D (0) and 248;
D (31) := (D (31) and 127) or 64;
LPK := Pack (Scalarbase (D (0 .. 31)));
PK.F := LPK;
SK.F := SK_Raw & LPK;
-- Sanitize intermediate values used in key generation
pragma Warnings (GNATProve, Off, "statement has no effect");
Sanitize (D);
Sanitize (LPK);
pragma Unreferenced (D);
pragma Unreferenced (LPK);
end Keypair_From_Bytes;
procedure Keypair (PK : out Signing_PK;
SK : out Signing_SK)
is
RB : Bytes_32;
begin
RB := Utils.Random_Bytes_32;
Keypair_From_Bytes (RB, PK, SK);
-- Sanitize intermediate values used in key generation
pragma Warnings (GNATProve, Off, "statement has no effect");
Sanitize (RB);
pragma Unreferenced (RB);
end Keypair;
procedure PK_From_Bytes (PK_Raw : in Bytes_32;
PK : out Signing_PK)
is
begin
PK.F := PK_Raw;
end PK_From_Bytes;
procedure Sign (SM : out Byte_Seq;
M : in Byte_Seq;
SK : in Signing_SK)
is
subtype Byte_Product is I64 range 0 .. MBP;
D : Bytes_64;
H, R : Bytes_32;
X : I64_Seq_64;
T : Byte_Product;
P : GF_Vector_4;
procedure Initialize_SM (X : out Byte_Seq)
with Global => (Input => (M, D)),
Depends => (X => (X, M, D)),
Pre => (M'First = 0 and
X'First = 0 and
M'Last <= N32'Last - Sign_Bytes) and then
(X'Length = M'Length + Sign_Bytes and
X'Last = M'Last + Sign_Bytes),
Post => (X = Zero_Bytes_32 & D (32 .. 63) & M) and
X'Initialized,
Relaxed_Initialization => X,
Inline;
procedure Initialize_SM (X : out Byte_Seq)
is
begin
-- Precondition ensures SM is exactly 64 bytes longer than M.
-- Don't use "&" here to avoid allocation of a dynamic-sized
-- object on the stack.
X (0 .. 31) := Zero_Bytes_32;
X (32 .. 63) := D (32 .. 63);
X (64 .. X'Last) := M;
end Initialize_SM;
begin
Hashing.Hash (D, Serialize (SK) (0 .. 31));
D (0) := D (0) and 248;
D (31) := (D (31) and 127) or 64;
Initialize_SM (SM);
R := Hash_Reduce (SM (32 .. SM'Last));
P := Scalarbase (R);
SM (0 .. 31) := Pack (P);
SM (32 .. 63) := Serialize (SK) (32 .. 63);
H := Hash_Reduce (SM);
X := (others => 0);
for I in Index_32 loop
X (I) := I64 (R (I));
pragma Loop_Invariant
((for all K in N32 range 0 .. I => X (K) in I64_Byte) and
(for all K in N32 range I + 1 .. 63 => X (K) = 0));
end loop;
pragma Assert
((for all K in N32 range 0 .. 31 => X (K) in I64_Byte) and
(for all K in N32 range 32 .. 63 => X (K) = 0) and
(for all K in Index_64 => X (K) in I64_Byte)
);
pragma Warnings (Off, "explicit membership test may be optimized");
for I in Index_32 loop
for J in Index_32 loop
T := Byte_Product (H (I)) * Byte_Product (D (J));
X (I + J) := X (I + J) + T;
-- This loop invariant follows the same pattern
-- as that in SPARKNaCl."*"
pragma Loop_Invariant
(
T in Byte_Product and
-- Lower bound
(for all K in Index_64 => X (K) >= 0) and
-- rising from 1 to I
(for all K in Index_64 range 0 .. (I - 1) =>
X (K) <= (I64 (K + 1) * MBP + 255)) and
-- flat at I + 1, just written
(for all K in Index_64 range I .. I32'Min (31, I + J) =>
X (K) <= (I64 (I + 1) * MBP + 255)) and
-- flat at I, not written yet
(for all K in Index_64 range I + J + 1 .. 31 =>
X (K) <= (I64 (I) * MBP + 255)) and
-- falling from I to 1, just written
(for all K in Index_64 range 32 .. (I + J) =>
X (K) <= (I64 (32 + I) - I64 (K)) * MBP + 255) and
-- falling, from I to 1, but not written yet
(for all K in Index_64 range
I32'Max (32, I + J + 1) .. (I + 31) =>
X (K) <= (I64 (31 + I) - I64 (K)) * MBP + 255) and
-- Zeroes - never written
(for all K in Index_64 range I + 32 .. 63 =>
X (K) = 0)
);
end loop;
-- Substitute J = 31 into the above yields
pragma Loop_Invariant
(
T in Byte_Product and
-- Lower bound
(for all K in Index_64 => X (K) >= 0) and
-- rising from 1 to I
(for all K in Index_64 range 0 .. (I - 1) =>
X (K) <= (I64 (K + 1) * MBP + 255)) and
-- flat at I + 1, just written
(for all K in Index_64 range I .. 31 =>
X (K) <= (I64 (I + 1) * MBP + 255)) and
-- falling from I to 1, just written
(for all K in Index_64 range 32 .. (I + 31) =>
X (K) <= (I64 (32 + I) - I64 (K)) * MBP + 255) and
-- Zeroes - never written
(for all K in Index_64 range I + 32 .. 63 =>
X (K) = 0)
);
end loop;
-- Substitute I = 31
pragma Assert
(
-- Lower bound
(for all K in Index_64 => X (K) >= 0) and
-- Upper bounds
(for all K in Index_64 range 0 .. 30 =>
X (K) <= (I64 (K + 1) * MBP + 255)) and
X (31) <= (32 * MBP + 255) and
(for all K in Index_64 range 32 .. 62 =>
X (K) <= (63 - I64 (K)) * MBP + 255) and
X (63) = 0
);
-- Simplify - this assert is equivalent to the precondition of ModL
pragma Assert
(for all K in Index_64 => X (K) in 0 .. (32 * MBP + 255));
SM (32 .. 63) := ModL (X);
Sanitize (D);
Sanitize (H);
Sanitize (R);
Sanitize_I64_Seq (X);
pragma Unreferenced (D, H, R, X);
end Sign;
procedure Open (M : out Byte_Seq;
Status : out Boolean;
MLen : out I32;
SM : in Byte_Seq;
PK : in Signing_PK)
is
T : Bytes_32;
P, Q : GF_Vector_4;
LN : I32;
begin
MLen := -1;
if SM'Length < 64 then
M := (others => 0);
Status := False;
-- No sanitization required before this return
return;
end if;
Unpackneg (Q, Status, Serialize (PK));
if not Status then
M := (others => 0);
Sanitize_GF_Vector_4 (Q);
return;
end if;
M := SM; -- precondition ensures lengths match
M (32 .. 63) := Serialize (PK);
P := Scalarmult (Q, Hash_Reduce (M));
Q := Scalarbase (SM (32 .. 63));
-- Call to user-defined "+" for GF_Vector_4
Add (P, Q);
T := Pack (P);
if not Equal (SM (0 .. 31), T) then
M := (others => 0);
Status := False;
Sanitize (T);
Sanitize_GF_Vector_4 (P);
Sanitize_GF_Vector_4 (Q);
return;
end if;
LN := I32 (I64 (SM'Length) - 64);
M (0 .. LN - 1) := SM (64 .. LN + 63);
MLen := LN;
Status := True;
Sanitize (T);
Sanitize_GF_Vector_4 (P);
Sanitize_GF_Vector_4 (Q);
pragma Unreferenced (T, P, Q);
end Open;
end SPARKNaCl.Sign;
|
AdaCore/training_material | Ada | 1,054 | adb | with Except;
with Screen_Output; use Screen_Output;
with Stack;
with Tokens; use Tokens;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
procedure Sdc is
File : File_Type;
begin
Msg ("Welcome to sdc. Go ahead type your commands ...");
if Argument_Count = 1 then
begin
Open (File, In_File, Argument (1));
exception
when Use_Error | Name_Error =>
Error_Msg ("Could not open input file, exiting.");
return;
end;
Set_Input (File);
end if;
loop
-- Open a block to catch Stack Overflow and Underflow exceptions.
begin
Process (Next);
-- Read the next Token from the input and process it.
exception
when Stack.Underflow =>
Error_Msg ("Not enough values in the Stack.");
when Stack.Overflow =>
null;
end;
end loop;
exception
when Except.Exit_SDC =>
Msg ("Thank you for using sdc.");
when others =>
Msg ("*** Internal Error ***.");
end Sdc;
|
onox/orka | Ada | 4,565 | adb | with AUnit.Reporter.Text;
with AUnit.Run;
with AUnit.Test_Suites;
with Test_SIMD_SSE_Arithmetic;
with Test_SIMD_SSE_Compare;
with Test_SIMD_SSE_Logical;
with Test_SIMD_SSE_Math;
with Test_SIMD_SSE_Swizzle;
with Test_SIMD_SSE2_Arithmetic;
with Test_SIMD_SSE2_Compare;
with Test_SIMD_SSE2_Convert;
with Test_SIMD_SSE2_Logical;
with Test_SIMD_SSE2_Shift;
with Test_SIMD_SSE4_1_Logical;
with Test_SIMD_SSE4_1_Math;
with Test_SIMD_AVX_Arithmetic;
with Test_SIMD_AVX_Compare;
with Test_SIMD_AVX_Math;
with Test_SIMD_AVX_Shift_Emulation;
with Test_SIMD_AVX_Swizzle;
with Test_SIMD_AVX2_Shift;
with Test_SIMD_AVX2_Swizzle;
with Test_SIMD_FMA_Singles_Arithmetic;
with Test_SIMD_FMA_Doubles_Arithmetic;
with Test_Transforms_Singles_Matrices;
with Test_Transforms_Singles_Quaternions;
with Test_Transforms_Singles_Vectors;
with Test_Transforms_Doubles_Matrices;
with Test_Transforms_Doubles_Quaternions;
with Test_Transforms_Doubles_Vectors;
with Test_Tensors_CPU_Singles_Vectors;
with Test_Tensors_CPU_Singles_Matrices;
with Test_Tensors_CPU_Doubles_Vectors;
with Test_Tensors_CPU_Doubles_Matrices;
with Test_Tensors_GPU_Singles_Vectors;
with Test_Tensors_GPU_Singles_Matrices;
with Test_Tensors_GPU_Doubles_Vectors;
with Test_Tensors_GPU_Doubles_Matrices;
with Test_Kalman_Filters;
with Test_Scene_Trees;
procedure Orka_Tests is
function Suite return AUnit.Test_Suites.Access_Test_Suite;
function Suite return AUnit.Test_Suites.Access_Test_Suite is
Result : constant AUnit.Test_Suites.Access_Test_Suite :=
AUnit.Test_Suites.New_Suite;
begin
-- SIMD > SSE (Single)
Result.Add_Test (Test_SIMD_SSE_Arithmetic.Suite);
Result.Add_Test (Test_SIMD_SSE_Compare.Suite);
Result.Add_Test (Test_SIMD_SSE_Logical.Suite);
Result.Add_Test (Test_SIMD_SSE_Math.Suite);
Result.Add_Test (Test_SIMD_SSE_Swizzle.Suite);
-- SIMD > SSE2 (Integers)
Result.Add_Test (Test_SIMD_SSE2_Arithmetic.Suite);
Result.Add_Test (Test_SIMD_SSE2_Compare.Suite);
Result.Add_Test (Test_SIMD_SSE2_Convert.Suite);
Result.Add_Test (Test_SIMD_SSE2_Logical.Suite);
Result.Add_Test (Test_SIMD_SSE2_Shift.Suite);
-- SIMD > SSE4.1 (Singles and Integers)
Result.Add_Test (Test_SIMD_SSE4_1_Math.Suite);
-- SIMD > SSE4.1 (Integers)
Result.Add_Test (Test_SIMD_SSE4_1_Logical.Suite);
-- SIMD > AVX (Doubles)
Result.Add_Test (Test_SIMD_AVX_Arithmetic.Suite);
Result.Add_Test (Test_SIMD_AVX_Compare.Suite);
Result.Add_Test (Test_SIMD_AVX_Math.Suite);
Result.Add_Test (Test_SIMD_AVX_Swizzle.Suite);
-- SIMD > AVX (Integers) (emulation of AVX2)
Result.Add_Test (Test_SIMD_AVX_Shift_Emulation.Suite);
-- SIMD > AVX2 (Doubles)
Result.Add_Test (Test_SIMD_AVX2_Swizzle.Suite);
-- SIMD > AVX2 (Integers)
Result.Add_Test (Test_SIMD_AVX2_Shift.Suite);
-- SIMD > FMA (Singles)
Result.Add_Test (Test_SIMD_FMA_Singles_Arithmetic.Suite);
-- SIMD > FMA (Doubles)
Result.Add_Test (Test_SIMD_FMA_Doubles_Arithmetic.Suite);
-- Transforms (Singles)
Result.Add_Test (Test_Transforms_Singles_Matrices.Suite);
Result.Add_Test (Test_Transforms_Singles_Vectors.Suite);
Result.Add_Test (Test_Transforms_Singles_Quaternions.Suite);
-- Transforms (Doubles)
Result.Add_Test (Test_Transforms_Doubles_Matrices.Suite);
Result.Add_Test (Test_Transforms_Doubles_Vectors.Suite);
Result.Add_Test (Test_Transforms_Doubles_Quaternions.Suite);
-- Trees
Result.Add_Test (Test_Scene_Trees.Suite);
-- Tensors on CPU (Singles)
Result.Add_Test (Test_Tensors_CPU_Singles_Vectors.Suite);
Result.Add_Test (Test_Tensors_CPU_Singles_Matrices.Suite);
-- Tensors on CPU (Doubles)
Result.Add_Test (Test_Tensors_CPU_Doubles_Vectors.Suite);
Result.Add_Test (Test_Tensors_CPU_Doubles_Matrices.Suite);
-- Tensors on GPU (Singles)
Result.Add_Test (Test_Tensors_GPU_Singles_Vectors.Suite);
Result.Add_Test (Test_Tensors_GPU_Singles_Matrices.Suite);
-- Tensors on GPU (Doubles)
Result.Add_Test (Test_Tensors_GPU_Doubles_Vectors.Suite);
Result.Add_Test (Test_Tensors_GPU_Doubles_Matrices.Suite);
-- Filters (Kalman)
Result.Add_Test (Test_Kalman_Filters.Suite);
return Result;
end Suite;
procedure Runner is new AUnit.Run.Test_Runner (Suite);
Reporter : AUnit.Reporter.Text.Text_Reporter;
begin
Reporter.Set_Use_ANSI_Colors (True);
Runner (Reporter);
end Orka_Tests;
|
reznikmm/matreshka | Ada | 3,953 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.DOM.Text_Issn_Attributes;
package Matreshka.ODF_Text.Issn_Attributes is
type Text_Issn_Attribute_Node is
new Matreshka.ODF_Text.Abstract_Text_Attribute_Node
and ODF.DOM.Text_Issn_Attributes.ODF_Text_Issn_Attribute
with null record;
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Text_Issn_Attribute_Node;
overriding function Get_Local_Name
(Self : not null access constant Text_Issn_Attribute_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Text.Issn_Attributes;
|
sungyeon/drake | Ada | 1,378 | adb | package body Ada.Containers.Unbounded_Synchronized_Queues is
use type Implementation.Node_Access;
protected body Queue is
-- overriding
entry Enqueue (New_Item : Queue_Interfaces.Element_Type) when True is
New_Node : constant Implementation.Node_Access :=
new Implementation.Node'(
Element => New_Item,
Next => null);
begin
if First = null then
First := New_Node;
else
Last.Next := New_Node;
end if;
Last := New_Node;
Current_Length := Current_Length + 1;
if Current_Length > Peak_Length then
Peak_Length := Current_Length;
end if;
end Enqueue;
-- overriding
entry Dequeue (Element : out Queue_Interfaces.Element_Type)
when First /= null is
begin
Element := First.Element;
First := First.Next;
if First = null then
Last := null;
end if;
Current_Length := Current_Length - 1;
end Dequeue;
-- overriding
function Current_Use return Count_Type is
begin
return Current_Length;
end Current_Use;
-- overriding
function Peak_Use return Count_Type is
begin
return Peak_Length;
end Peak_Use;
end Queue;
end Ada.Containers.Unbounded_Synchronized_Queues;
|
charlie5/lace | Ada | 53,889 | adb | -- A PNG stream is made of several "chunks" (see type PNG_Chunk_tag).
-- The image itself is contained in the IDAT chunk(s).
--
-- Steps for decoding an image (step numbers are from the ISO standard):
--
-- 10: Inflate deflated data; at each output buffer (slide),
-- process with step 9.
-- 9: Read filter code (row begin), or unfilter bytes, go with step 8
-- 8: Display pixels these bytes represent;
-- eventually, locate the interlaced image current point
--
-- Reference: Portable Network Graphics (PNG) Specification (Second Edition)
-- ISO/IEC 15948:2003 (E)
-- W3C Recommendation 10 November 2003
-- http://www.w3.org/TR/PNG/
--
with GID.Buffering, GID.Decoding_PNG.Huffman;
with Ada.Text_IO, Ada.Exceptions;
package body GID.Decoding_PNG is
generic
type Number is mod <>;
procedure Big_endian_number(
from : in out Input_buffer;
n : out Number
);
pragma Inline(Big_endian_number);
procedure Big_endian_number(
from : in out Input_buffer;
n : out Number
)
is
b: U8;
begin
n:= 0;
for i in 1..Number'Size/8 loop
Buffering.Get_Byte(from, b);
n:= n * 256 + Number(b);
end loop;
end Big_endian_number;
procedure Big_endian is new Big_endian_number( U32 );
use Ada.Exceptions;
----------
-- Read --
----------
procedure Read (image: in out image_descriptor; ch: out Chunk_head) is
str4: String(1..4);
b: U8;
begin
Big_endian(image.buffer, ch.length);
for i in str4'Range loop
Buffering.Get_Byte(image.buffer, b);
str4(i):= Character'Val(b);
end loop;
begin
ch.kind:= PNG_Chunk_tag'Value(str4);
if some_trace then
Ada.Text_IO.Put_Line(
"Chunk [" & str4 &
"], length:" & U32'Image(ch.length)
);
end if;
exception
when Constraint_Error =>
Raise_exception(
error_in_image_data'Identity,
"PNG chunk unknown: " &
Integer'Image(Character'Pos(str4(1))) &
Integer'Image(Character'Pos(str4(2))) &
Integer'Image(Character'Pos(str4(3))) &
Integer'Image(Character'Pos(str4(4))) &
" (" & str4 & ')'
);
end;
end Read;
package CRC32 is
procedure Init( CRC: out Unsigned_32 );
function Final( CRC: Unsigned_32 ) return Unsigned_32;
procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array );
pragma Inline( Update );
end CRC32;
package body CRC32 is
CRC32_Table : array( Unsigned_32'(0)..255 ) of Unsigned_32;
procedure Prepare_table is
-- CRC-32 algorithm, ISO-3309
Seed: constant:= 16#EDB88320#;
l: Unsigned_32;
begin
for i in CRC32_Table'Range loop
l:= i;
for bit in 0..7 loop
if (l and 1) = 0 then
l:= Shift_Right(l,1);
else
l:= Shift_Right(l,1) xor Seed;
end if;
end loop;
CRC32_Table(i):= l;
end loop;
end Prepare_table;
procedure Update( CRC: in out Unsigned_32; InBuf: Byte_array ) is
local_CRC: Unsigned_32;
begin
local_CRC:= CRC ;
for i in InBuf'Range loop
local_CRC :=
CRC32_Table( 16#FF# and ( local_CRC xor Unsigned_32( InBuf(i) ) ) )
xor
Shift_Right( local_CRC , 8 );
end loop;
CRC:= local_CRC;
end Update;
table_empty: Boolean:= True;
procedure Init( CRC: out Unsigned_32 ) is
begin
if table_empty then
Prepare_table;
table_empty:= False;
end if;
CRC:= 16#FFFF_FFFF#;
end Init;
function Final( CRC: Unsigned_32 ) return Unsigned_32 is
begin
return not CRC;
end Final;
end CRC32;
----------
-- Load --
----------
procedure Load (image: in out Image_descriptor) is
----------------------
-- Load_specialized --
----------------------
generic
-- These values are invariant through the whole picture,
-- so we can make them generic parameters. As a result, all
-- "if", "case", etc. using them at the center of the decoding
-- are optimized out at compile-time.
interlaced : Boolean;
bits_per_pixel : Positive;
bytes_to_unfilter : Positive;
-- ^ amount of bytes to unfilter at a time
-- = Integer'Max(1, bits_per_pixel / 8);
subformat_id : Natural;
procedure Load_specialized;
--
procedure Load_specialized is
use GID.Buffering;
subtype Mem_row_bytes_array is Byte_array(0..image.width*8);
--
mem_row_bytes: array(0..1) of Mem_row_bytes_array;
-- We need to memorize two image rows, for un-filtering
curr_row: Natural:= 1;
-- either current is 1 and old is 0, or the reverse
subtype X_range is Integer range -1..image.width-1;
subtype Y_range is Integer range 0..image.height-1;
-- X position -1 is for the row's filter methode code
x: X_range:= X_range'First;
y: Y_range:= Y_range'First;
x_max: X_range; -- for non-interlaced images: = X_range'Last
y_max: Y_range; -- for non-interlaced images: = Y_range'Last
pass: Positive range 1..7:= 1;
--------------------------
-- ** 9: Unfiltering ** --
--------------------------
-- http://www.w3.org/TR/PNG/#9Filters
type Filter_method_0 is (None, Sub, Up, Average, Paeth);
current_filter: Filter_method_0;
procedure Unfilter_bytes(
f: in Byte_array; -- filtered
u: out Byte_array -- unfiltered
)
is
pragma Inline(Unfilter_bytes);
-- Byte positions (f is the byte to be unfiltered):
--
-- c b
-- a f
a,b,c, p,pa,pb,pc,pr: Integer;
j: Integer:= 0;
begin
if full_trace and then x = 0 then
if y = 0 then
Ada.Text_IO.New_Line;
end if;
Ada.Text_IO.Put_Line(
"row" & Integer'Image(y) & ": filter= " &
Filter_method_0'Image(current_filter)
);
end if;
--
-- !! find a way to have f99n0g04.png decoded correctly...
-- seems a filter issue.
--
case current_filter is
when None =>
-- Recon(x) = Filt(x)
u:= f;
when Sub =>
-- Recon(x) = Filt(x) + Recon(a)
if x > 0 then
for i in f'Range loop
u(u'First+j):= f(i) + mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j);
j:= j + 1;
end loop;
else
u:= f;
end if;
when Up =>
-- Recon(x) = Filt(x) + Recon(b)
if y > 0 then
for i in f'Range loop
u(u'First+j):= f(i) + mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j);
j:= j + 1;
end loop;
else
u:= f;
end if;
when Average =>
-- Recon(x) = Filt(x) + floor((Recon(a) + Recon(b)) / 2)
for i in f'Range loop
if x > 0 then
a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j));
else
a:= 0;
end if;
if y > 0 then
b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j));
else
b:= 0;
end if;
u(u'First+j):= U8((Integer(f(i)) + (a+b)/2) mod 256);
j:= j + 1;
end loop;
when Paeth =>
-- Recon(x) = Filt(x) + PaethPredictor(Recon(a), Recon(b), Recon(c))
for i in f'Range loop
if x > 0 then
a:= Integer(mem_row_bytes(curr_row)((x-1)*bytes_to_unfilter+j));
else
a:= 0;
end if;
if y > 0 then
b:= Integer(mem_row_bytes(1-curr_row)(x*bytes_to_unfilter+j));
else
b:= 0;
end if;
if x > 0 and y > 0 then
c:= Integer(mem_row_bytes(1-curr_row)((x-1)*bytes_to_unfilter+j));
else
c:= 0;
end if;
p := a + b - c;
pa:= abs(p - a);
pb:= abs(p - b);
pc:= abs(p - c);
if pa <= pb and then pa <= pc then
pr:= a;
elsif pb <= pc then
pr:= b;
else
pr:= c;
end if;
u(u'First+j):= f(i) + U8(pr);
j:= j + 1;
end loop;
end case;
j:= 0;
for i in u'Range loop
mem_row_bytes(curr_row)(x*bytes_to_unfilter+j):= u(i);
j:= j + 1;
end loop;
-- if u'Length /= bytes_to_unfilter then
-- raise Constraint_Error;
-- end if;
end Unfilter_bytes;
filter_stat: array(Filter_method_0) of Natural:= (others => 0);
----------------------------------------------
-- ** 8: Interlacing and pass extraction ** --
----------------------------------------------
-- http://www.w3.org/TR/PNG/#8Interlace
-- Output bytes from decompression
--
procedure Output_uncompressed(
data : in Byte_array;
reject: out Natural
-- amount of bytes to be resent here next time,
-- in order to have a full multi-byte pixel
)
is
-- Display of pixels coded on 8 bits per channel in the PNG stream
procedure Out_Pixel_8(br, bg, bb, ba: U8) is
pragma Inline(Out_Pixel_8);
begin
case Primary_color_range'Modulus is
when 256 =>
Put_Pixel(
Primary_color_range(br),
Primary_color_range(bg),
Primary_color_range(bb),
Primary_color_range(ba)
);
when 65_536 =>
Put_Pixel(
16#101# * Primary_color_range(br),
16#101# * Primary_color_range(bg),
16#101# * Primary_color_range(bb),
16#101# * Primary_color_range(ba)
-- 16#101# because max intensity FF goes to FFFF
);
when others =>
raise invalid_primary_color_range;
end case;
end Out_Pixel_8;
procedure Out_Pixel_Palette(ix: U8) is
pragma Inline(Out_Pixel_Palette);
color_idx: constant Natural:= Integer(ix);
begin
Out_Pixel_8(
image.palette(color_idx).red,
image.palette(color_idx).green,
image.palette(color_idx).blue,
255
);
end Out_Pixel_Palette;
-- Display of pixels coded on 16 bits per channel in the PNG stream
procedure Out_Pixel_16(br, bg, bb, ba: U16) is
pragma Inline(Out_Pixel_16);
begin
case Primary_color_range'Modulus is
when 256 =>
Put_Pixel(
Primary_color_range(br / 256),
Primary_color_range(bg / 256),
Primary_color_range(bb / 256),
Primary_color_range(ba / 256)
);
when 65_536 =>
Put_Pixel(
Primary_color_range(br),
Primary_color_range(bg),
Primary_color_range(bb),
Primary_color_range(ba)
);
when others =>
raise invalid_primary_color_range;
end case;
end Out_Pixel_16;
procedure Inc_XY is
pragma Inline(Inc_XY);
xm, ym: Integer;
begin
if x < x_max then
x:= x + 1;
if interlaced then
-- Position of pixels depending on pass:
--
-- 1 6 4 6 2 6 4 6
-- 7 7 7 7 7 7 7 7
-- 5 6 5 6 5 6 5 6
-- 7 7 7 7 7 7 7 7
-- 3 6 4 6 3 6 4 6
-- 7 7 7 7 7 7 7 7
-- 5 6 5 6 5 6 5 6
-- 7 7 7 7 7 7 7 7
case pass is
when 1 =>
Set_X_Y( x*8, Y_range'Last - y*8);
when 2 =>
Set_X_Y(4 + x*8, Y_range'Last - y*8);
when 3 =>
Set_X_Y( x*4, Y_range'Last - 4 - y*8);
when 4 =>
Set_X_Y(2 + x*4, Y_range'Last - y*4);
when 5 =>
Set_X_Y( x*2, Y_range'Last - 2 - y*4);
when 6 =>
Set_X_Y(1 + x*2, Y_range'Last - y*2);
when 7 =>
null; -- nothing to to, pixel are contiguous
end case;
end if;
else
x:= X_range'First; -- New row
if y < y_max then
y:= y + 1;
curr_row:= 1-curr_row; -- swap row index for filtering
if not interlaced then
Feedback((y*100)/image.height);
end if;
elsif interlaced then -- last row has beed displayed
while pass < 7 loop
pass:= pass + 1;
y:= 0;
case pass is
when 1 =>
null;
when 2 =>
xm:= (image.width+3)/8 - 1;
ym:= (image.height+7)/8 - 1;
when 3 =>
xm:= (image.width+3)/4 - 1;
ym:= (image.height+3)/8 - 1;
when 4 =>
xm:= (image.width+1)/4 - 1;
ym:= (image.height+3)/4 - 1;
when 5 =>
xm:= (image.width+1)/2 - 1;
ym:= (image.height+1)/4 - 1;
when 6 =>
xm:= (image.width )/2 - 1;
ym:= (image.height+1)/2 - 1;
when 7 =>
xm:= image.width - 1;
ym:= image.height/2 - 1;
end case;
if xm >=0 and xm <= X_range'Last and ym in Y_range then
-- This pass is not empty (otherwise, we will continue
-- to the next one, if any).
x_max:= xm;
y_max:= ym;
exit;
end if;
end loop;
end if;
end if;
end Inc_XY;
uf: Byte_array(0..15); -- unfiltered bytes for a pixel
w1, w2: U16;
i: Integer;
begin
if some_trace then
Ada.Text_IO.Put("[UO]");
end if;
-- Depending on the row size, bpp, etc., we can have
-- several rows, or less than one, being displayed
-- with the present uncompressed data batch.
--
i:= data'First;
if i > data'Last then
reject:= 0;
return; -- data is empty, do nothing
end if;
--
-- Main loop over data
--
loop
if x = X_range'First then -- pseudo-column for filter method
exit when i > data'Last;
begin
current_filter:= Filter_method_0'Val(data(i));
if some_trace then
filter_stat(current_filter):= filter_stat(current_filter) + 1;
end if;
exception
when Constraint_Error =>
Raise_exception(
error_in_image_data'Identity,
"PNG: wrong filter code, row #" &
Integer'Image(y) & " code:" & U8'Image(data(i))
);
end;
if interlaced then
case pass is
when 1..6 =>
null; -- Set_X_Y for each pixel
when 7 =>
Set_X_Y(0, Y_range'Last - 1 - y*2);
end case;
else
Set_X_Y(0, Y_range'Last - y);
end if;
i:= i + 1;
else -- normal pixel
--
-- We quit the loop if all data has been used (except for an
-- eventual incomplete pixel)
exit when i > data'Last - (bytes_to_unfilter - 1);
-- NB, for per-channel bpp < 8:
-- 7.2 Scanlines - some low-order bits of the
-- last byte of a scanline may go unused.
case subformat_id is
when 0 =>
-----------------------
-- Type 0: Greyscale --
-----------------------
case bits_per_pixel is
when 1 | 2 | 4 =>
Unfilter_bytes(data(i..i), uf(0..0));
i:= i + 1;
declare
b: U8;
shift: Integer:= 8 - bits_per_pixel;
max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1);
-- Scaling factor to obtain the correct color value on a 0..255 range.
-- The division is exact in all cases (bpp=8,4,2,1),
-- since 255 = 3 * 5 * 17 and max = 255, 15, 3 or 1.
-- This factor ensures: 0 -> 0, max -> 255
factor: constant U8:= 255 / max;
begin
-- loop through the number of pixels in this byte:
for k in reverse 1..8/bits_per_pixel loop
b:= (max and U8(Shift_Right(Unsigned_8(uf(0)), shift))) * factor;
shift:= shift - bits_per_pixel;
Out_Pixel_8(b, b, b, 255);
exit when x >= x_max or k = 1;
Inc_XY;
end loop;
end;
when 8 =>
-- NB: with bpp as generic param, this case could be merged
-- into the general 1,2,4[,8] case without loss of performance
-- if the compiler is smart enough to simplify the code, given
-- the value of bits_per_pixel.
-- But we let it here for two reasons:
-- 1) a compiler might be not smart enough
-- 2) it is a very simple case, perhaps helpful for
-- understanding the algorithm.
Unfilter_bytes(data(i..i), uf(0..0));
i:= i + 1;
Out_Pixel_8(uf(0), uf(0), uf(0), 255);
when 16 =>
Unfilter_bytes(data(i..i+1), uf(0..1));
i:= i + 2;
w1:= U16(uf(0)) * 256 + U16(uf(1));
Out_Pixel_16(w1, w1, w1, 65535);
when others =>
null; -- undefined in PNG standard
end case;
when 2 =>
-----------------
-- Type 2: RGB --
-----------------
case bits_per_pixel is
when 24 =>
Unfilter_bytes(data(i..i+2), uf(0..2));
i:= i + 3;
Out_Pixel_8(uf(0), uf(1), uf(2), 255);
when 48 =>
Unfilter_bytes(data(i..i+5), uf(0..5));
i:= i + 6;
Out_Pixel_16(
U16(uf(0)) * 256 + U16(uf(1)),
U16(uf(2)) * 256 + U16(uf(3)),
U16(uf(4)) * 256 + U16(uf(5)),
65_535
);
when others =>
null;
end case;
when 3 =>
------------------------------
-- Type 3: RGB with palette --
------------------------------
Unfilter_bytes(data(i..i), uf(0..0));
i:= i + 1;
case bits_per_pixel is
when 1 | 2 | 4 =>
declare
shift: Integer:= 8 - bits_per_pixel;
max: constant U8:= U8(Shift_Left(Unsigned_32'(1), bits_per_pixel)-1);
begin
-- loop through the number of pixels in this byte:
for k in reverse 1..8/bits_per_pixel loop
Out_Pixel_Palette(max and U8(Shift_Right(Unsigned_8(uf(0)), shift)));
shift:= shift - bits_per_pixel;
exit when x >= x_max or k = 1;
Inc_XY;
end loop;
end;
when 8 =>
-- Same remark for this case (8bpp) as
-- within Image Type 0 / Greyscale above
Out_Pixel_Palette(uf(0));
when others =>
null;
end case;
when 4 =>
-------------------------------
-- Type 4: Greyscale & Alpha --
-------------------------------
case bits_per_pixel is
when 16 =>
Unfilter_bytes(data(i..i+1), uf(0..1));
i:= i + 2;
Out_Pixel_8(uf(0), uf(0), uf(0), uf(1));
when 32 =>
Unfilter_bytes(data(i..i+3), uf(0..3));
i:= i + 4;
w1:= U16(uf(0)) * 256 + U16(uf(1));
w2:= U16(uf(2)) * 256 + U16(uf(3));
Out_Pixel_16(w1, w1, w1, w2);
when others =>
null; -- undefined in PNG standard
end case;
when 6 =>
------------------
-- Type 6: RGBA --
------------------
case bits_per_pixel is
when 32 =>
Unfilter_bytes(data(i..i+3), uf(0..3));
i:= i + 4;
Out_Pixel_8(uf(0), uf(1), uf(2), uf(3));
when 64 =>
Unfilter_bytes(data(i..i+7), uf(0..7));
i:= i + 8;
Out_Pixel_16(
U16(uf(0)) * 256 + U16(uf(1)),
U16(uf(2)) * 256 + U16(uf(3)),
U16(uf(4)) * 256 + U16(uf(5)),
U16(uf(6)) * 256 + U16(uf(7))
);
when others =>
null;
end case;
when others =>
null; -- Unknown - exception already raised at header level
end case;
end if;
Inc_XY;
end loop;
-- i is between data'Last-(bytes_to_unfilter-2) and data'Last+1
reject:= (data'Last + 1) - i;
if reject > 0 then
if some_trace then
Ada.Text_IO.Put("[rj" & Integer'Image(reject) & ']');
end if;
end if;
end Output_uncompressed;
ch: Chunk_head;
-- Out of some intelligent design, there might be an IDAT chunk
-- boundary anywhere inside the zlib compressed block...
procedure Jump_IDAT is
dummy: U32;
begin
Big_endian(image.buffer, dummy); -- ending chunk's CRC
-- New chunk begins here.
loop
Read(image, ch);
exit when ch.kind /= IDAT or ch.length > 0;
end loop;
if ch.kind /= IDAT then
Raise_exception(
error_in_image_data'Identity,
"PNG additional data chunk must be an IDAT"
);
end if;
end Jump_IDAT;
---------------------------------------------------------------------
-- ** 10: Decompression ** --
-- Excerpt and simplification from UnZip.Decompress (Inflate only) --
---------------------------------------------------------------------
-- http://www.w3.org/TR/PNG/#10Compression
-- Size of sliding dictionary and circular output buffer
wsize: constant:= 16#10000#;
--------------------------------------
-- Specifications of UnZ_* packages --
--------------------------------------
package UnZ_Glob is
-- I/O Buffers
-- > Sliding dictionary for unzipping, and output buffer as well
slide: Byte_Array( 0..wsize );
slide_index: Integer:= 0; -- Current Position in slide
Zip_EOF : constant Boolean:= False;
crc32val : Unsigned_32; -- crc calculated from data
end UnZ_Glob;
package UnZ_IO is
procedure Init_Buffers;
procedure Read_raw_byte ( bt : out U8 );
pragma Inline(Read_raw_byte);
package Bit_buffer is
procedure Init;
-- Read at least n bits into the bit buffer, returns the n first bits
function Read ( n: Natural ) return Integer;
pragma Inline(Read);
function Read_U32 ( n: Natural ) return Unsigned_32;
pragma Inline(Read_U32);
-- Dump n bits no longer needed from the bit buffer
procedure Dump ( n: Natural );
pragma Inline(Dump);
procedure Dump_to_byte_boundary;
function Read_and_dump( n: Natural ) return Integer;
pragma Inline(Read_and_dump);
function Read_and_dump_U32( n: Natural ) return Unsigned_32;
pragma Inline(Read_and_dump_U32);
end Bit_buffer;
procedure Flush ( x: Natural ); -- directly from slide to output stream
procedure Flush_if_full(W: in out Integer);
pragma Inline(Flush_if_full);
procedure Copy(
distance, length: Natural;
index : in out Natural );
pragma Inline(Copy);
end UnZ_IO;
package UnZ_Meth is
deflate_e_mode: constant Boolean:= False;
procedure Inflate;
end UnZ_Meth;
------------------------------
-- Bodies of UnZ_* packages --
------------------------------
package body UnZ_IO is
procedure Init_Buffers is
begin
UnZ_Glob.slide_index := 0;
Bit_buffer.Init;
CRC32.Init( UnZ_Glob.crc32val );
end Init_Buffers;
procedure Read_raw_byte ( bt : out U8 ) is
begin
if ch.length = 0 then
-- We hit the end of a PNG 'IDAT' chunk, so we go to the next one
-- - in petto, it's strange design, but well...
-- This "feature" has taken some time (and nerves) to be addressed.
-- Incidentally, I have reprogrammed the whole Huffman
-- decoding, and looked at many other wrong places to solve
-- the mystery.
Jump_IDAT;
end if;
Buffering.Get_Byte(image.buffer, bt);
ch.length:= ch.length - 1;
end Read_raw_byte;
package body Bit_buffer is
B : Unsigned_32;
K : Integer;
procedure Init is
begin
B := 0;
K := 0;
end Init;
procedure Need( n : Natural ) is
pragma Inline(Need);
bt: U8;
begin
while K < n loop
Read_raw_byte( bt );
B:= B or Shift_Left( Unsigned_32( bt ), K );
K:= K + 8;
end loop;
end Need;
procedure Dump ( n : Natural ) is
begin
B := Shift_Right(B, n );
K := K - n;
end Dump;
procedure Dump_to_byte_boundary is
begin
Dump ( K mod 8 );
end Dump_to_byte_boundary;
function Read_U32 ( n: Natural ) return Unsigned_32 is
begin
Need(n);
return B and (Shift_Left(1,n) - 1);
end Read_U32;
function Read ( n: Natural ) return Integer is
begin
return Integer(Read_U32(n));
end Read;
function Read_and_dump( n: Natural ) return Integer is
res: Integer;
begin
res:= Read(n);
Dump(n);
return res;
end Read_and_dump;
function Read_and_dump_U32( n: Natural ) return Unsigned_32 is
res: Unsigned_32;
begin
res:= Read_U32(n);
Dump(n);
return res;
end Read_and_dump_U32;
end Bit_buffer;
old_bytes: Natural:= 0;
-- how many bytes to be resent from last Inflate output
byte_mem: Byte_array(1..8);
procedure Flush ( x: Natural ) is
use Ada.Streams;
begin
if full_trace then
Ada.Text_IO.Put("[Flush..." & Integer'Image(x));
end if;
CRC32.Update( UnZ_Glob.crc32val, UnZ_Glob.slide( 0..x-1 ) );
if old_bytes > 0 then
declare
app: constant Byte_array:=
byte_mem(1..old_bytes) & UnZ_Glob.slide(0..x-1);
begin
Output_uncompressed(app, old_bytes);
-- In extreme cases (x very small), we might have some of
-- the rejected bytes from byte_mem.
if old_bytes > 0 then
byte_mem(1..old_bytes):= app(app'Last-(old_bytes-1)..app'Last);
end if;
end;
else
Output_uncompressed(UnZ_Glob.slide(0..x-1), old_bytes);
if old_bytes > 0 then
byte_mem(1..old_bytes):= UnZ_Glob.slide(x-old_bytes..x-1);
end if;
end if;
if full_trace then
Ada.Text_IO.Put_Line("finished]");
end if;
end Flush;
procedure Flush_if_full(W: in out Integer) is
begin
if W = wsize then
Flush(wsize);
W:= 0;
end if;
end Flush_if_full;
----------------------------------------------------
-- Reproduction of sequences in the output slide. --
----------------------------------------------------
-- Internal:
procedure Adjust_to_Slide(
source : in out Integer;
remain : in out Natural;
part : out Integer;
index: Integer)
is
pragma Inline(Adjust_to_Slide);
begin
source:= source mod wsize;
-- source and index are now in 0..WSize-1
if source > index then
part:= wsize-source;
else
part:= wsize-index;
end if;
-- NB: part is in 1..WSize (part cannot be 0)
if part > remain then
part:= remain;
end if;
-- Now part <= remain
remain:= remain - part;
-- NB: remain cannot be < 0
end Adjust_to_Slide;
procedure Copy_range(source, index: in out Natural; amount: Positive) is
pragma Inline(Copy_range);
begin
if abs (index - source) < amount then
-- if source >= index, the effect of copy is
-- just like the non-overlapping case
for count in reverse 1..amount loop
UnZ_Glob.slide(index):= UnZ_Glob.slide(source);
index := index + 1;
source:= source + 1;
end loop;
else -- non-overlapping -> copy slice
UnZ_Glob.slide( index .. index+amount-1 ):=
UnZ_Glob.slide( source..source+amount-1 );
index := index + amount;
source:= source + amount;
end if;
end Copy_range;
-- The copying routines:
procedure Copy(
distance, length: Natural;
index : in out Natural )
is
source,part,remain: Integer;
begin
source:= index - distance;
remain:= length;
loop
Adjust_to_Slide(source,remain,part, index);
Copy_range(source, index, part);
Flush_if_full(index);
exit when remain = 0;
end loop;
end Copy;
end UnZ_IO;
package body UnZ_Meth is
use GID.Decoding_PNG.Huffman;
--------[ Method: Inflate ]--------
procedure Inflate_Codes ( Tl, Td: p_Table_list; Bl, Bd: Integer ) is
CTE : p_HufT; -- current table element
length : Natural;
E : Integer; -- table entry flag/number of extra bits
W : Integer:= UnZ_Glob.slide_index;
-- more local variable for slide index
begin
if full_trace then
Ada.Text_IO.Put_Line("Begin Inflate_codes");
end if;
-- inflate the coded data
main_loop:
while not UnZ_Glob.Zip_EOF loop
CTE:= Tl.table( UnZ_IO.Bit_buffer.Read(Bl) )'Access;
loop
E := CTE.extra_bits;
exit when E <= 16;
if E = invalid then
raise error_in_image_data;
end if;
-- then it's a literal
UnZ_IO.Bit_buffer.Dump( CTE.bits );
E:= E - 16;
CTE := CTE.next_table( UnZ_IO.Bit_buffer.Read(E) )'Access;
end loop;
UnZ_IO.Bit_buffer.Dump ( CTE.bits );
case E is
when 16 => -- CTE.N is a Litteral
UnZ_Glob.slide ( W ) := U8( CTE.n );
W:= W + 1;
UnZ_IO.Flush_if_full(W);
when 15 => -- End of block (EOB)
if full_trace then
Ada.Text_IO.Put_Line("Exit Inflate_codes, e=15 EOB");
end if;
exit main_loop;
when others => -- We have a length/distance
-- Get length of block to copy:
length:= CTE.n + UnZ_IO.Bit_buffer.Read_and_dump(E);
-- Decode distance of block to copy:
CTE := Td.table( UnZ_IO.Bit_buffer.Read(Bd) )'Access;
loop
E := CTE.extra_bits;
exit when E <= 16;
if E = invalid then
raise error_in_image_data;
end if;
UnZ_IO.Bit_buffer.Dump( CTE.bits );
E:= E - 16;
CTE := CTE.next_table( UnZ_IO.Bit_buffer.Read(E) )'Access;
end loop;
UnZ_IO.Bit_buffer.Dump( CTE.bits );
UnZ_IO.Copy(
distance => CTE.n + UnZ_IO.Bit_buffer.Read_and_dump(E),
length => length,
index => W
);
end case;
end loop main_loop;
UnZ_Glob.slide_index:= W;
if full_trace then
Ada.Text_IO.Put_Line("End Inflate_codes");
end if;
end Inflate_Codes;
procedure Inflate_stored_block is -- Actually, nothing to inflate
N : Integer;
begin
if full_trace then
Ada.Text_IO.Put_Line("Begin Inflate_stored_block");
end if;
UnZ_IO.Bit_buffer.Dump_to_byte_boundary;
-- Get the block length and its complement
N:= UnZ_IO.Bit_buffer.Read_and_dump( 16 );
if N /= Integer(
(not UnZ_IO.Bit_buffer.Read_and_dump_U32(16))
and 16#ffff#)
then
raise error_in_image_data;
end if;
while N > 0 and then not UnZ_Glob.Zip_EOF loop
-- Read and output the non-compressed data
N:= N - 1;
UnZ_Glob.slide ( UnZ_Glob.slide_index ) :=
U8( UnZ_IO.Bit_buffer.Read_and_dump(8) );
UnZ_Glob.slide_index:= UnZ_Glob.slide_index + 1;
UnZ_IO.Flush_if_full(UnZ_Glob.slide_index);
end loop;
if full_trace then
Ada.Text_IO.Put_Line("End Inflate_stored_block");
end if;
end Inflate_stored_block;
-- Copy lengths for literal codes 257..285
copy_lengths_literal : Length_array( 0..30 ) :=
( 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 );
-- Extra bits for literal codes 257..285
extra_bits_literal : Length_array( 0..30 ) :=
( 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, invalid, invalid );
-- Copy offsets for distance codes 0..29 (30..31: deflate_e)
copy_offset_distance : constant Length_array( 0..31 ) :=
( 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 32769, 49153 );
-- Extra bits for distance codes
extra_bits_distance : constant Length_array( 0..31 ) :=
( 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14 );
max_dist: Integer:= 29; -- changed to 31 for deflate_e
procedure Inflate_fixed_block is
Tl, -- literal/length code table
Td : p_Table_list; -- distance code table
Bl, Bd : Integer; -- lookup bits for tl/bd
huft_incomplete : Boolean;
-- length list for HufT_build (literal table)
L: constant Length_array( 0..287 ):=
( 0..143=> 8, 144..255=> 9, 256..279=> 7, 280..287=> 8);
begin
if full_trace then
Ada.Text_IO.Put_Line("Begin Inflate_fixed_block");
end if;
-- make a complete, but wrong code set
Bl := 7;
HufT_build(
L, 257, copy_lengths_literal, extra_bits_literal,
Tl, Bl, huft_incomplete
);
-- Make an incomplete code set
Bd := 5;
begin
HufT_build(
(0..max_dist => 5), 0,
copy_offset_distance, extra_bits_distance,
Td, Bd, huft_incomplete
);
if huft_incomplete then
if full_trace then
Ada.Text_IO.Put_Line(
"td is incomplete, pointer=null: " &
Boolean'Image(Td=null)
);
end if;
end if;
exception
when huft_out_of_memory | huft_error =>
HufT_free( Tl );
raise error_in_image_data;
end;
Inflate_Codes ( Tl, Td, Bl, Bd );
HufT_free ( Tl );
HufT_free ( Td );
if full_trace then
Ada.Text_IO.Put_Line("End Inflate_fixed_block");
end if;
end Inflate_fixed_block;
procedure Inflate_dynamic_block is
bit_order : constant array ( 0..18 ) of Natural :=
( 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 );
Lbits : constant:= 9;
Dbits : constant:= 6;
current_length: Natural;
defined, number_of_lengths: Natural;
Tl, -- literal/length code tables
Td : p_Table_list; -- distance code tables
CTE : p_HufT; -- current table element
Bl, Bd : Integer; -- lookup bits for tl/bd
Nb : Natural; -- number of bit length codes
Nl : Natural; -- number of literal length codes
Nd : Natural; -- number of distance codes
-- literal/length and distance code lengths
Ll: Length_array( 0 .. 288+32-1 ):= (others=> 0);
huft_incomplete : Boolean;
procedure Repeat_length_code( amount: Natural ) is
begin
if defined + amount > number_of_lengths then
raise error_in_image_data;
end if;
for c in reverse 1..amount loop
Ll ( defined ) := current_length;
defined:= defined + 1;
end loop;
end Repeat_length_code;
begin
if full_trace then
Ada.Text_IO.Put_Line("Begin Inflate_dynamic_block");
end if;
-- Read in table lengths
Nl := 257 + UnZ_IO.Bit_buffer.Read_and_dump(5);
Nd := 1 + UnZ_IO.Bit_buffer.Read_and_dump(5);
Nb := 4 + UnZ_IO.Bit_buffer.Read_and_dump(4);
if Nl > 288 or else Nd > 32 then
raise error_in_image_data;
end if;
-- Read in bit-length-code lengths.
-- The rest, Ll( Bit_Order( Nb .. 18 ) ), is already = 0
for J in 0 .. Nb - 1 loop
Ll ( bit_order( J ) ) := UnZ_IO.Bit_buffer.Read_and_dump(3);
end loop;
-- Build decoding table for trees--single level, 7 bit lookup
Bl := 7;
begin
HufT_build (
Ll( 0..18 ), 19, empty, empty, Tl, Bl, huft_incomplete
);
if huft_incomplete then
HufT_free(Tl);
raise error_in_image_data;
end if;
exception
when others =>
raise error_in_image_data;
end;
-- Read in literal and distance code lengths
number_of_lengths := Nl + Nd;
defined := 0;
current_length := 0;
while defined < number_of_lengths loop
CTE:= Tl.table( UnZ_IO.Bit_buffer.Read(Bl) )'Access;
UnZ_IO.Bit_buffer.Dump( CTE.bits );
case CTE.n is
when 0..15 => -- length of code in bits (0..15)
current_length:= CTE.n;
Ll (defined) := current_length;
defined:= defined + 1;
when 16 => -- repeat last length 3 to 6 times
Repeat_length_code(3 + UnZ_IO.Bit_buffer.Read_and_dump(2));
when 17 => -- 3 to 10 zero length codes
current_length:= 0;
Repeat_length_code(3 + UnZ_IO.Bit_buffer.Read_and_dump(3));
when 18 => -- 11 to 138 zero length codes
current_length:= 0;
Repeat_length_code(11 + UnZ_IO.Bit_buffer.Read_and_dump(7));
when others =>
if full_trace then
Ada.Text_IO.Put_Line(
"Illegal length code: " &
Integer'Image(CTE.n)
);
end if;
end case;
end loop;
HufT_free ( Tl ); -- free decoding table for trees
-- Build the decoding tables for literal/length codes
Bl := Lbits;
begin
HufT_build (
Ll( 0..Nl-1 ), 257,
copy_lengths_literal, extra_bits_literal,
Tl, Bl, huft_incomplete
);
if huft_incomplete then
HufT_free(Tl);
raise error_in_image_data;
end if;
exception
when others =>
raise error_in_image_data;
end;
-- Build the decoding tables for distance codes
Bd := Dbits;
begin
HufT_build (
Ll( Nl..Nl+Nd-1 ), 0,
copy_offset_distance, extra_bits_distance,
Td, Bd, huft_incomplete
);
if huft_incomplete then -- do nothing!
if full_trace then
Ada.Text_IO.Put_Line("PKZIP 1.93a bug workaround");
end if;
end if;
exception
when huft_out_of_memory | huft_error =>
HufT_free(Tl);
raise error_in_image_data;
end;
-- Decompress until an end-of-block code
Inflate_Codes ( Tl, Td, Bl, Bd );
HufT_free ( Tl );
HufT_free ( Td );
if full_trace then
Ada.Text_IO.Put_Line("End Inflate_dynamic_block");
end if;
end Inflate_dynamic_block;
procedure Inflate_Block( last_block: out Boolean ) is
begin
last_block:= Boolean'Val(UnZ_IO.Bit_buffer.Read_and_dump(1));
case UnZ_IO.Bit_buffer.Read_and_dump(2) is -- Block type = 0,1,2,3
when 0 => Inflate_stored_block;
when 1 => Inflate_fixed_block;
when 2 => Inflate_dynamic_block;
when others => raise error_in_image_data; -- Bad block type (3)
end case;
end Inflate_Block;
procedure Inflate is
is_last_block: Boolean;
blocks: Positive:= 1;
begin
if deflate_e_mode then
copy_lengths_literal(28):= 3; -- instead of 258
extra_bits_literal(28):= 16; -- instead of 0
max_dist:= 31;
end if;
loop
Inflate_Block ( is_last_block );
exit when is_last_block;
blocks:= blocks+1;
end loop;
UnZ_IO.Flush( UnZ_Glob.slide_index );
UnZ_Glob.slide_index:= 0;
if some_trace then
Ada.Text_IO.Put("# blocks:" & Integer'Image(blocks));
end if;
UnZ_Glob.crc32val := CRC32.Final( UnZ_Glob.crc32val );
end Inflate;
end UnZ_Meth;
--------------------------------------------------------------------
-- End of the Decompression part, and of UnZip.Decompress excerpt --
--------------------------------------------------------------------
b: U8;
z_crc, dummy: U32;
begin -- Load_specialized
--
-- For optimization reasons, bytes_to_unfilter is passed as a
-- generic parameter but should be always as below right to "/=" :
--
if bytes_to_unfilter /= Integer'Max(1, bits_per_pixel / 8) then
raise Program_Error;
end if;
if interlaced then
x_max:= (image.width+7)/8 - 1;
y_max:= (image.height+7)/8 - 1;
else
x_max:= X_range'Last;
y_max:= Y_range'Last;
end if;
main_chunk_loop:
loop
loop
Read(image, ch);
exit when ch.kind = IEND or ch.length > 0;
end loop;
case ch.kind is
when IEND => -- 11.2.5 IEND Image trailer
exit main_chunk_loop;
when IDAT => -- 11.2.4 IDAT Image data
--
-- NB: the compressed data may hold on several IDAT chunks.
-- It means that right in the middle of compressed data, you
-- can have a chunk crc, and a new IDAT header!...
--
UnZ_IO.Read_raw_byte(b); -- zlib compression method/flags code
UnZ_IO.Read_raw_byte(b); -- Additional flags/check bits
--
UnZ_IO.Init_Buffers;
-- ^ we indicate that we have a byte reserve of chunk's length,
-- minus both zlib header bytes.
UnZ_Meth.Inflate;
z_crc:= 0;
for i in 1..4 loop
begin
UnZ_IO.Read_raw_byte(b);
exception
when Error_in_image_data =>
-- vicious IEND at the wrong place
-- basi4a08.png test image (corrupt imho)
exit main_chunk_loop;
end;
z_crc:= z_crc * 256 + U32(b);
end loop;
-- z_crc : zlib Check value
-- if z_crc /= U32(UnZ_Glob.crc32val) then
-- ada.text_io.put(z_crc 'img & UnZ_Glob.crc32val'img);
-- Raise_exception(
-- error_in_image_data'Identity,
-- "PNG: deflate stream corrupt"
-- );
-- end if;
-- ** Mystery: this check fail even with images which decompress perfectly
-- ** Is CRC init value different between zip and zlib ? Is it Adler32 ?
Big_endian(image.buffer, dummy); -- chunk's CRC
-- last IDAT chunk's CRC (then, on compressed data)
--
when tEXt => -- 11.3.4.3 tEXt Textual data
for i in 1..ch.length loop
Get_Byte(image.buffer, b);
if some_trace then
if b=0 then -- separates keyword from message
Ada.Text_IO.New_Line;
else
Ada.Text_IO.Put(Character'Val(b));
end if;
end if;
end loop;
Big_endian(image.buffer, dummy); -- chunk's CRC
when others =>
-- Skip chunk data and CRC
for i in 1..ch.length + 4 loop
Get_Byte(image.buffer, b);
end loop;
end case;
end loop main_chunk_loop;
if some_trace then
for f in Filter_method_0 loop
Ada.Text_IO.Put_Line(
"Filter: " &
Filter_method_0'Image(f) &
Integer'Image(filter_stat(f))
);
end loop;
end if;
Feedback(100);
end Load_specialized;
-- Instances of Load_specialized, with hard-coded parameters.
-- They may take an insane amount of time to compile, and bloat the
-- .o code , but are significantly faster since they make the
-- compiler skip corresponding tests at pixel level.
-- These instances are for most current PNG sub-formats.
procedure Load_interlaced_1pal is new Load_specialized(True, 1, 1, 3);
procedure Load_interlaced_2pal is new Load_specialized(True, 2, 1 ,3);
procedure Load_interlaced_4pal is new Load_specialized(True, 4, 1, 3);
procedure Load_interlaced_8pal is new Load_specialized(True, 8, 1, 3);
procedure Load_interlaced_24 is new Load_specialized(True, 24, 3, 2);
procedure Load_interlaced_32 is new Load_specialized(True, 32, 4, 6);
--
procedure Load_straight_1pal is new Load_specialized(False, 1, 1, 3);
procedure Load_straight_2pal is new Load_specialized(False, 2, 1, 3);
procedure Load_straight_4pal is new Load_specialized(False, 4, 1, 3);
procedure Load_straight_8pal is new Load_specialized(False, 8, 1, 3);
procedure Load_straight_24 is new Load_specialized(False, 24, 3, 2);
procedure Load_straight_32 is new Load_specialized(False, 32, 4, 6);
--
-- For unusual sub-formats, we prefer to fall back to the
-- slightly slower, general version, where parameters values
-- are not known at compile-time:
--
procedure Load_general is new
Load_specialized(
interlaced => image.interlaced,
bits_per_pixel => image.bits_per_pixel,
bytes_to_unfilter => Integer'Max(1, image.bits_per_pixel / 8),
subformat_id => image.subformat_id
);
begin -- Load
--
-- All these case tests are better done at the picture
-- level than at the pixel level.
--
case image.subformat_id is
when 2 => -- RGB
case image.bits_per_pixel is
when 24 =>
if image.interlaced then
Load_interlaced_24;
else
Load_straight_24;
end if;
when others =>
Load_general;
end case;
when 3 => -- Palette
case image.bits_per_pixel is
when 1 =>
if image.interlaced then
Load_interlaced_1pal;
else
Load_straight_1pal;
end if;
when 2 =>
if image.interlaced then
Load_interlaced_2pal;
else
Load_straight_2pal;
end if;
when 4 =>
if image.interlaced then
Load_interlaced_4pal;
else
Load_straight_4pal;
end if;
when 8 =>
if image.interlaced then
Load_interlaced_8pal;
else
Load_straight_8pal;
end if;
when others =>
Load_general;
end case;
when 6 => -- RGBA
case image.bits_per_pixel is
when 32 =>
if image.interlaced then
Load_interlaced_32;
else
Load_straight_32;
end if;
when others =>
Load_general;
end case;
when others =>
Load_general;
end case;
end Load;
end GID.Decoding_PNG;
|
zhmu/ananas | Ada | 313 | adb | -- { dg-do compile }
procedure str1 is
Str : constant string := "--";
generic
package Gen is
procedure P;
end Gen;
package body Gen is
procedure P is
inner : String := Str;
begin
null;
end;
end Gen;
package Inst is new Gen;
begin
null;
end;
|
ekoeppen/STM32_Generic_Ada_Drivers | Ada | 7,483 | ads | -- This spec has been automatically generated from STM32F103.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with Interfaces; use Interfaces;
with System;
-- STM32F103
package STM32_SVD is
pragma Preelaborate;
---------------
-- Base type --
---------------
type UInt32 is new Interfaces.Unsigned_32;
type UInt16 is new Interfaces.Unsigned_16;
type Byte is new Interfaces.Unsigned_8;
type Bit is mod 2**1
with Size => 1;
type UInt2 is mod 2**2
with Size => 2;
type UInt3 is mod 2**3
with Size => 3;
type UInt4 is mod 2**4
with Size => 4;
type UInt5 is mod 2**5
with Size => 5;
type UInt6 is mod 2**6
with Size => 6;
type UInt7 is mod 2**7
with Size => 7;
type UInt9 is mod 2**9
with Size => 9;
type UInt10 is mod 2**10
with Size => 10;
type UInt11 is mod 2**11
with Size => 11;
type UInt12 is mod 2**12
with Size => 12;
type UInt13 is mod 2**13
with Size => 13;
type UInt14 is mod 2**14
with Size => 14;
type UInt15 is mod 2**15
with Size => 15;
type UInt17 is mod 2**17
with Size => 17;
type UInt18 is mod 2**18
with Size => 18;
type UInt19 is mod 2**19
with Size => 19;
type UInt20 is mod 2**20
with Size => 20;
type UInt21 is mod 2**21
with Size => 21;
type UInt22 is mod 2**22
with Size => 22;
type UInt23 is mod 2**23
with Size => 23;
type UInt24 is mod 2**24
with Size => 24;
type UInt25 is mod 2**25
with Size => 25;
type UInt26 is mod 2**26
with Size => 26;
type UInt27 is mod 2**27
with Size => 27;
type UInt28 is mod 2**28
with Size => 28;
type UInt29 is mod 2**29
with Size => 29;
type UInt30 is mod 2**30
with Size => 30;
type UInt31 is mod 2**31
with Size => 31;
--------------------
-- Base addresses --
--------------------
FSMC_Base : constant System.Address :=
System'To_Address (16#A0000000#);
PWR_Base : constant System.Address :=
System'To_Address (16#40007000#);
RCC_Base : constant System.Address :=
System'To_Address (16#40021000#);
GPIOA_Base : constant System.Address :=
System'To_Address (16#40010800#);
GPIOB_Base : constant System.Address :=
System'To_Address (16#40010C00#);
GPIOC_Base : constant System.Address :=
System'To_Address (16#40011000#);
GPIOD_Base : constant System.Address :=
System'To_Address (16#40011400#);
GPIOE_Base : constant System.Address :=
System'To_Address (16#40011800#);
GPIOF_Base : constant System.Address :=
System'To_Address (16#40011C00#);
GPIOG_Base : constant System.Address :=
System'To_Address (16#40012000#);
AFIO_Base : constant System.Address :=
System'To_Address (16#40010000#);
EXTI_Base : constant System.Address :=
System'To_Address (16#40010400#);
DMA1_Base : constant System.Address :=
System'To_Address (16#40020000#);
DMA2_Base : constant System.Address :=
System'To_Address (16#40020400#);
SDIO_Base : constant System.Address :=
System'To_Address (16#40018000#);
RTC_Base : constant System.Address :=
System'To_Address (16#40002800#);
BKP_Base : constant System.Address :=
System'To_Address (16#40006C00#);
IWDG_Base : constant System.Address :=
System'To_Address (16#40003000#);
WWDG_Base : constant System.Address :=
System'To_Address (16#40002C00#);
TIM1_Base : constant System.Address :=
System'To_Address (16#40012C00#);
TIM8_Base : constant System.Address :=
System'To_Address (16#40013400#);
TIM2_Base : constant System.Address :=
System'To_Address (16#40000000#);
TIM3_Base : constant System.Address :=
System'To_Address (16#40000400#);
TIM4_Base : constant System.Address :=
System'To_Address (16#40000800#);
TIM5_Base : constant System.Address :=
System'To_Address (16#40000C00#);
TIM9_Base : constant System.Address :=
System'To_Address (16#40014C00#);
TIM12_Base : constant System.Address :=
System'To_Address (16#40001800#);
TIM10_Base : constant System.Address :=
System'To_Address (16#40015000#);
TIM11_Base : constant System.Address :=
System'To_Address (16#40015400#);
TIM13_Base : constant System.Address :=
System'To_Address (16#40001C00#);
TIM14_Base : constant System.Address :=
System'To_Address (16#40002000#);
TIM6_Base : constant System.Address :=
System'To_Address (16#40001000#);
TIM7_Base : constant System.Address :=
System'To_Address (16#40001400#);
I2C1_Base : constant System.Address :=
System'To_Address (16#40005400#);
I2C2_Base : constant System.Address :=
System'To_Address (16#40005800#);
SPI1_Base : constant System.Address :=
System'To_Address (16#40013000#);
SPI2_Base : constant System.Address :=
System'To_Address (16#40003800#);
SPI3_Base : constant System.Address :=
System'To_Address (16#40003C00#);
USART1_Base : constant System.Address :=
System'To_Address (16#40013800#);
USART2_Base : constant System.Address :=
System'To_Address (16#40004400#);
USART3_Base : constant System.Address :=
System'To_Address (16#40004800#);
ADC1_Base : constant System.Address :=
System'To_Address (16#40012400#);
ADC2_Base : constant System.Address :=
System'To_Address (16#40012800#);
ADC3_Base : constant System.Address :=
System'To_Address (16#40013C00#);
CAN1_Base : constant System.Address :=
System'To_Address (16#40006400#);
CAN2_Base : constant System.Address :=
System'To_Address (16#40006800#);
DAC_Base : constant System.Address :=
System'To_Address (16#40007400#);
DBG_Base : constant System.Address :=
System'To_Address (16#E0042000#);
UART4_Base : constant System.Address :=
System'To_Address (16#40004C00#);
UART5_Base : constant System.Address :=
System'To_Address (16#40005000#);
CRC_Base : constant System.Address :=
System'To_Address (16#40023000#);
FLASH_Base : constant System.Address :=
System'To_Address (16#40022000#);
USB_Base : constant System.Address :=
System'To_Address (16#40005C00#);
OTG_FS_DEVICE_Base : constant System.Address :=
System'To_Address (16#50000800#);
OTG_FS_GLOBAL_Base : constant System.Address :=
System'To_Address (16#50000000#);
OTG_FS_HOST_Base : constant System.Address :=
System'To_Address (16#50000400#);
OTG_FS_PWRCLK_Base : constant System.Address :=
System'To_Address (16#50000E00#);
ETHERNET_MMC_Base : constant System.Address :=
System'To_Address (16#40028100#);
ETHERNET_MAC_Base : constant System.Address :=
System'To_Address (16#40028000#);
ETHERNET_PTP_Base : constant System.Address :=
System'To_Address (16#40028700#);
ETHERNET_DMA_Base : constant System.Address :=
System'To_Address (16#40029000#);
NVIC_Base : constant System.Address :=
System'To_Address (16#E000E100#);
MPU_Base : constant System.Address :=
System'To_Address (16#E000ED90#);
SCB_ACTRL_Base : constant System.Address :=
System'To_Address (16#E000E008#);
NVIC_STIR_Base : constant System.Address :=
System'To_Address (16#E000EF00#);
SCB_Base : constant System.Address :=
System'To_Address (16#E000ED00#);
STK_Base : constant System.Address :=
System'To_Address (16#E000E010#);
end STM32_SVD;
|
jwarwick/aoc_2020 | Ada | 164 | ads | -- AOC 2020, Day 20
package Day is
function image_checksum(filename : in String) return Long_Integer;
function water_roughness return Long_Integer;
end Day;
|
ohenley/ada-util | Ada | 8,801 | adb | -----------------------------------------------------------------------
-- util-texts-builders -- Text builder
-- Copyright (C) 2013, 2016, 2017 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
package body Util.Texts.Builders is
-- ------------------------------
-- Get the length of the item builder.
-- ------------------------------
function Length (Source : in Builder) return Natural is
begin
return Source.Length;
end Length;
-- ------------------------------
-- Get the capacity of the builder.
-- ------------------------------
function Capacity (Source : in Builder) return Natural is
B : constant Block_Access := Source.Current;
begin
return Source.Length + B.Len - B.Last;
end Capacity;
-- ------------------------------
-- Get the builder block size.
-- ------------------------------
function Block_Size (Source : in Builder) return Positive is
begin
return Source.Block_Size;
end Block_Size;
-- ------------------------------
-- Set the block size for the allocation of next chunks.
-- ------------------------------
procedure Set_Block_Size (Source : in out Builder;
Size : in Positive) is
begin
Source.Block_Size := Size;
end Set_Block_Size;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Input) is
B : Block_Access := Source.Current;
Start : Natural := New_Item'First;
Last : constant Natural := New_Item'Last;
begin
while Start <= Last loop
declare
Space : Natural := B.Len - B.Last;
Size : constant Natural := Last - Start + 1;
begin
if Space > Size then
Space := Size;
elsif Space = 0 then
if Size > Source.Block_Size then
B.Next_Block := new Block (Size);
else
B.Next_Block := new Block (Source.Block_Size);
end if;
B := B.Next_Block;
Source.Current := B;
if B.Len > Size then
Space := Size;
else
Space := B.Len;
end if;
end if;
B.Content (B.Last + 1 .. B.Last + Space) := New_Item (Start .. Start + Space - 1);
Source.Length := Source.Length + Space;
B.Last := B.Last + Space;
Start := Start + Space;
end;
end loop;
end Append;
-- ------------------------------
-- Append the <tt>New_Item</tt> at the end of the source growing the buffer if necessary.
-- ------------------------------
procedure Append (Source : in out Builder;
New_Item : in Element_Type) is
B : Block_Access := Source.Current;
begin
if B.Len = B.Last then
B.Next_Block := new Block (Source.Block_Size);
B := B.Next_Block;
Source.Current := B;
end if;
Source.Length := Source.Length + 1;
B.Last := B.Last + 1;
B.Content (B.Last) := New_Item;
end Append;
-- ------------------------------
-- Clear the source freeing any storage allocated for the buffer.
-- ------------------------------
procedure Clear (Source : in out Builder) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Block, Name => Block_Access);
Current, Next : Block_Access;
begin
Next := Source.First.Next_Block;
while Next /= null loop
Current := Next;
Next := Current.Next_Block;
Free (Current);
end loop;
Source.First.Next_Block := null;
Source.First.Last := 0;
Source.Current := Source.First'Unchecked_Access;
Source.Length := 0;
end Clear;
-- ------------------------------
-- Iterate over the buffer content calling the <tt>Process</tt> procedure with each
-- chunk.
-- ------------------------------
procedure Iterate (Source : in Builder;
Process : not null access procedure (Chunk : in Input)) is
begin
if Source.First.Last > 0 then
Process (Source.First.Content (1 .. Source.First.Last));
declare
B : Block_Access := Source.First.Next_Block;
begin
while B /= null loop
Process (B.Content (1 .. B.Last));
B := B.Next_Block;
end loop;
end;
end if;
end Iterate;
-- ------------------------------
-- Return the content starting from the tail and up to <tt>Length</tt> items.
-- ------------------------------
function Tail (Source : in Builder;
Length : in Natural) return Input is
Last : constant Natural := Source.Current.Last;
begin
if Last >= Length then
return Source.Current.Content (Last - Length + 1 .. Last);
elsif Length >= Source.Length then
return To_Array (Source);
else
declare
Result : Input (1 .. Length);
Offset : Natural := Source.Length - Length;
B : access constant Block := Source.First'Access;
Src_Pos : Positive := 1;
Dst_Pos : Positive := 1;
Len : Natural;
begin
-- Skip the data moving to next blocks as needed.
while Offset /= 0 loop
if Offset < B.Last then
Src_Pos := Offset + 1;
Offset := 0;
else
Offset := Offset - B.Last + 1;
B := B.Next_Block;
end if;
end loop;
-- Copy what remains until we reach the length.
while Dst_Pos <= Length loop
Len := B.Last - Src_Pos + 1;
Result (Dst_Pos .. Dst_Pos + Len - 1) := B.Content (Src_Pos .. B.Last);
Src_Pos := 1;
Dst_Pos := Dst_Pos + Len;
B := B.Next_Block;
end loop;
return Result;
end;
end if;
end Tail;
-- ------------------------------
-- Get the buffer content as an array.
-- ------------------------------
function To_Array (Source : in Builder) return Input is
Result : Input (1 .. Source.Length);
begin
if Source.First.Last > 0 then
declare
Pos : Positive := Source.First.Last;
B : Block_Access := Source.First.Next_Block;
begin
Result (1 .. Pos) := Source.First.Content (1 .. Pos);
while B /= null loop
Result (Pos + 1 .. Pos + B.Last) := B.Content (1 .. B.Last);
Pos := Pos + B.Last;
B := B.Next_Block;
end loop;
end;
end if;
return Result;
end To_Array;
-- ------------------------------
-- Call the <tt>Process</tt> procedure with the full buffer content, trying to avoid
-- secondary stack copies as much as possible.
-- ------------------------------
procedure Get (Source : in Builder) is
begin
if Source.Length < Source.First.Len then
Process (Source.First.Content (1 .. Source.Length));
else
declare
Content : constant Input := To_Array (Source);
begin
Process (Content);
end;
end if;
end Get;
-- ------------------------------
-- Setup the builder.
-- ------------------------------
overriding
procedure Initialize (Source : in out Builder) is
begin
Source.Current := Source.First'Unchecked_Access;
end Initialize;
-- ------------------------------
-- Finalize the builder releasing the storage.
-- ------------------------------
overriding
procedure Finalize (Source : in out Builder) is
begin
Clear (Source);
end Finalize;
end Util.Texts.Builders;
|
BrickBot/Bound-T-H8-300 | Ada | 3,170 | adb | -- String_Sets (body)
--
-- Author: Niklas Holsti, Tidorum Ltd
--
-- A component of the Bound-T Worst-Case Execution Time Tool.
--
-------------------------------------------------------------------------------
-- Copyright (c) 1999 .. 2015 Tidorum Ltd
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- This software is provided by the copyright holders and contributors "as is" and
-- any express or implied warranties, including, but not limited to, the implied
-- warranties of merchantability and fitness for a particular purpose are
-- disclaimed. In no event shall the copyright owner or contributors be liable for
-- any direct, indirect, incidental, special, exemplary, or consequential damages
-- (including, but not limited to, procurement of substitute goods or services;
-- loss of use, data, or profits; or business interruption) however caused and
-- on any theory of liability, whether in contract, strict liability, or tort
-- (including negligence or otherwise) arising in any way out of the use of this
-- software, even if advised of the possibility of such damage.
--
-- Other modules (files) of this software composition should contain their
-- own copyright statements, which may have different copyright and usage
-- conditions. The above conditions apply to this file.
-------------------------------------------------------------------------------
--
-- $Revision: 1.3 $
-- $Date: 2015/10/24 20:05:52 $
--
-- $Log: string_sets.adb,v $
-- Revision 1.3 2015/10/24 20:05:52 niklas
-- Moved to free licence.
--
-- Revision 1.2 2007-02-27 20:54:58 Niklas
-- Corrected renaming-as-body for To_List to real body, because the
-- renamed function To_Vector is inherited through type derivation
-- and therefore has "Intrinsic" convention and so cannot be used in
-- renaming-as-body.
--
-- Revision 1.1 2006/05/27 21:26:38 niklas
-- First version for BT-CH-0020.
--
package body String_Sets is
procedure Add (
Item : in String;
To : in out String_Set_T)
is
begin
Add (
Item => String_Pool.To_Item (Item),
To => To);
end Add;
procedure Add (
Item : in String_Pool.Item_T;
To : in out String_Set_T)
is
Index : Natural;
begin
Find_Or_Add (
Value => Item,
Vector => To,
Index => Index);
end Add;
function Is_Member (Item : String; Of_Set : String_Set_T)
return Boolean
is
begin
return Is_Element (Of_Set, String_Pool.To_Item (Item));
end Is_Member;
function To_List (Set : String_Set_T) return String_List_T
is
begin
return To_Vector (Set);
end To_List;
end String_Sets;
|
clairvoyant/anagram | Ada | 11,270 | adb | -- Copyright (c) 2010-2017 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Wide_Wide_Text_IO;
package body Anagram.Grammars_Checks is
use Anagram.Grammars;
---------------------
-- Is_L_Attributed --
---------------------
function Is_L_Attributed
(Self : Anagram.Grammars.Grammar)
return Boolean
is
function Check
(Part : Part_Index;
Attr : Attribute_Index) return Boolean;
-----------
-- Check --
-----------
function Check
(Part : Part_Index;
Attr : Attribute_Index) return Boolean is
begin
if Self.Attribute (Attr).Is_Left_Hand_Side then
return Self.Declaration
(Self.Attribute (Attr).Declaration).Is_Inherited;
else
return Self.Attribute (Attr).Origin < Part;
end if;
end Check;
begin
for J in 1 .. Self.Last_Rule loop
declare
Result : constant Attribute_Index := Self.Rule (J).Result;
Attr : Attribute renames Self.Attribute (Result);
Decl : Attribute_Declaration renames
Self.Declaration (Attr.Declaration);
begin
if Decl.Is_Inherited and not Attr.Is_Left_Hand_Side then
for A in
Self.Rule (J).First_Argument .. Self.Rule (J).Last_Argument
loop
if not Check (Attr.Origin, A) then
return False;
end if;
end loop;
end if;
end;
end loop;
return True;
end Is_L_Attributed;
--------------------
-- Is_Well_Formed --
--------------------
function Is_Well_Formed
(Self : Anagram.Grammars.Grammar;
Verbose : Boolean)
return Boolean
is
function Check
(NT : Non_Terminal_Index;
P : Production_Index)
return Boolean;
function Check_NT
(NT : Non_Terminal_Index;
From : Production_Index;
To : Production_Count)
return Boolean;
type Count_Array is array (Attribute_Declaration_Index range <>)
of Natural;
function Check_Count
(NT : Non_Terminal_Index;
Item : Non_Terminal_Index;
Count : Count_Array;
Prod : Production_Index;
Part : Part_Count := 0;
RHS : Boolean := True)
return Boolean;
function Check_Local
(NT : Non_Terminal_Index;
Prod : Production_Index;
Count : Count_Array)
return Boolean;
-----------------
-- Check_Count --
-----------------
function Check_Count
(NT : Non_Terminal_Index;
Item : Non_Terminal_Index;
Count : Count_Array;
Prod : Production_Index;
Part : Part_Count := 0;
RHS : Boolean := True)
return Boolean
is
function Part_Name return Wide_Wide_String;
function Part_Name return Wide_Wide_String is
begin
if RHS then
return Self.Non_Terminal (NT).Name.To_Wide_Wide_String & "." &
Self.Production (Prod).Name.To_Wide_Wide_String &
" " &
Self.Part (Part).Name.To_Wide_Wide_String &
".";
else
return Self.Non_Terminal (NT).Name.To_Wide_Wide_String & "." &
Self.Production (Prod).Name.To_Wide_Wide_String &
" LHS.";
end if;
end Part_Name;
Result : Boolean := True;
From : constant Attribute_Declaration_Index :=
Self.Non_Terminal (Item).First_Attribute;
To : constant Attribute_Declaration_Count :=
Self.Non_Terminal (Item).Last_Attribute;
begin
for Decl in From .. To loop
if Self.Declaration (Decl).Is_Inherited xor RHS then
if Count (Count'First + Decl - From) /= 0 then
if Verbose then
Ada.Wide_Wide_Text_IO.Put_Line
("Not Well Formed: unexpected rule for " &
Part_Name &
Self.Declaration (Decl).Name.To_Wide_Wide_String);
end if;
Result := False;
end if;
else
if Count (Count'First + Decl - From) = 0 then
if Verbose then
Ada.Wide_Wide_Text_IO.Put_Line
("Not Well Formed: no rule for " &
Part_Name &
Self.Declaration (Decl).Name.To_Wide_Wide_String);
end if;
Result := False;
elsif Count (Count'First + Decl - From) > 1 then
if Verbose then
Ada.Wide_Wide_Text_IO.Put_Line
("Not Well Formed: not unique rule for " &
Part_Name &
Self.Declaration (Decl).Name.To_Wide_Wide_String);
end if;
Result := False;
end if;
end if;
end loop;
return Result;
end Check_Count;
-----------------
-- Check_Local --
-----------------
function Check_Local
(NT : Non_Terminal_Index;
Prod : Production_Index;
Count : Count_Array) return Boolean
is
Result : Boolean := True;
From : constant Attribute_Declaration_Index :=
Self.Production (Prod).First_Attribute;
To : constant Attribute_Declaration_Count :=
Self.Production (Prod).Last_Attribute;
begin
for Decl in From .. To loop
if Count (Count'First + Decl - From) = 0 then
if Verbose then
Ada.Wide_Wide_Text_IO.Put_Line
("Not Well Formed: no rule for local attribute " &
Self.Non_Terminal (NT).Name.To_Wide_Wide_String & "." &
Self.Production (Prod).Name.To_Wide_Wide_String & " " &
Self.Declaration (Decl).Name.To_Wide_Wide_String);
end if;
Result := False;
elsif Count (Count'First + Decl - From) > 1 then
if Verbose then
Ada.Wide_Wide_Text_IO.Put_Line
("Not Well Formed: not unique rule for local attribute " &
Self.Non_Terminal (NT).Name.To_Wide_Wide_String & "." &
Self.Production (Prod).Name.To_Wide_Wide_String & " " &
Self.Declaration (Decl).Name.To_Wide_Wide_String);
end if;
Result := False;
end if;
end loop;
return Result;
end Check_Local;
-----------
-- Check --
-----------
function Check
(NT : Non_Terminal_Index;
P : Production_Index)
return Boolean
is
Result : Boolean := True;
From : constant Part_Index := Self.Production (P).First;
To : constant Part_Count := Self.Production (P).Last;
First : array (From .. To) of Attribute_Declaration_Index;
Offset : array (From .. To) of Attribute_Declaration_Count;
LHS : constant Attribute_Declaration_Count :=
Self.Non_Terminal (NT).Last_Attribute -
Self.Non_Terminal (NT).First_Attribute + 1;
Local : constant Attribute_Declaration_Count :=
Self.Production (P).Last_Attribute -
Self.Production (P).First_Attribute + 1;
Total : Attribute_Declaration_Count := LHS + Local;
begin
-- Fill Offset and First arrays
for J in Offset'Range loop
Offset (J) := Total + 1;
if Self.Part (J).Is_Non_Terminal_Reference then
declare
T : constant Non_Terminal_Index := Self.Part (J).Denote;
begin
First (J) := Self.Non_Terminal (T).First_Attribute;
Total := Total + Self.Non_Terminal (T).Last_Attribute -
First (J) + 1;
end;
else
First (J) := 1;
end if;
end loop;
declare
Count : Count_Array (1 .. Total) := (others => 0);
From : constant Rule_Index := Self.Production (P).First_Rule;
To : constant Rule_Count := Self.Production (P).Last_Rule;
Index : Attribute_Declaration_Index;
begin
-- Fill Count array
for R in From .. To loop
declare
Result : constant Attribute_Index := Self.Rule (R).Result;
Decl : constant Attribute_Declaration_Index :=
Self.Attribute (Result).Declaration;
begin
if Self.Declaration (Decl).Is_Local then
Index := LHS +
Decl -
Self.Production (P).First_Attribute + 1;
elsif Self.Attribute (Result).Is_Left_Hand_Side then
Index := Decl -
Self.Non_Terminal (NT).First_Attribute + 1;
else
Index := Offset (Self.Attribute (Result).Origin) +
Decl -
First (Self.Attribute (Result).Origin);
end if;
Count (Index) := Count (Index) + 1;
end;
end loop;
for J in Offset'Range loop
if Self.Part (J).Is_Non_Terminal_Reference and then
not Check_Count (NT,
Self.Part (J).Denote,
Count (Offset (J) .. Count'Last),
P,
J)
then
Result := False;
end if;
end loop;
if not Check_Count (NT, NT, Count, P, RHS => False) then
Result := False;
end if;
if not Check_Local (NT, P, Count (LHS + 1 .. LHS + Local)) then
Result := False;
end if;
end;
return Result;
end Check;
--------------
-- Check_NT --
--------------
function Check_NT
(NT : Non_Terminal_Index;
From : Production_Index;
To : Production_Count)
return Boolean
is
Result : Boolean := True;
begin
for P in From .. To loop
if not Check (NT, P) then
Result := False;
end if;
end loop;
return Result;
end Check_NT;
Result : Boolean := True;
begin
for NT in 1 .. Self.Last_Non_Terminal loop
if not Check_NT
(NT, Self.Non_Terminal (NT).First, Self.Non_Terminal (NT).Last)
then
Result := False;
end if;
end loop;
return Result;
end Is_Well_Formed;
end Anagram.Grammars_Checks;
|
AdaCore/libadalang | Ada | 457 | adb | procedure Main is
type Enum is (A, B, C);
for Enum use (A => -1, B => 0, C => 2);
type Enum2 is (E, F, G);
type Enum3 is (H, I, J);
for Enum3 use (H => 1, I => 2, J => 4);
Var : Enum;
X : Integer;
begin
X := Enum'Enum_Rep (Var);
pragma Test_Statement;
X := Enum2'Enum_Rep (E);
pragma Test_Statement;
X := Enum3'Enum_Rep (H);
pragma Test_Statement;
Var := Enum'Enum_Val (0);
pragma Test_Statement;
end Main;
|
optikos/oasis | Ada | 6,593 | ads | -- Copyright (c) 2019 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Lexical_Elements;
with Program.Elements.Return_Object_Specifications;
with Program.Element_Vectors;
with Program.Elements.Exception_Handlers;
with Program.Elements.Extended_Return_Statements;
with Program.Element_Visitors;
package Program.Nodes.Extended_Return_Statements is
pragma Preelaborate;
type Extended_Return_Statement is
new Program.Nodes.Node
and Program.Elements.Extended_Return_Statements
.Extended_Return_Statement
and Program.Elements.Extended_Return_Statements
.Extended_Return_Statement_Text
with private;
function Create
(Return_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Return_Object : not null Program.Elements
.Return_Object_Specifications.Return_Object_Specification_Access;
Do_Token : Program.Lexical_Elements.Lexical_Element_Access;
Statements : Program.Element_Vectors.Element_Vector_Access;
Exception_Token : Program.Lexical_Elements.Lexical_Element_Access;
Exception_Handlers : Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access;
End_Token : Program.Lexical_Elements.Lexical_Element_Access;
Return_Token_2 : Program.Lexical_Elements.Lexical_Element_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Extended_Return_Statement;
type Implicit_Extended_Return_Statement is
new Program.Nodes.Node
and Program.Elements.Extended_Return_Statements
.Extended_Return_Statement
with private;
function Create
(Return_Object : not null Program.Elements
.Return_Object_Specifications.Return_Object_Specification_Access;
Statements : Program.Element_Vectors.Element_Vector_Access;
Exception_Handlers : Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Extended_Return_Statement
with Pre =>
Is_Part_Of_Implicit or Is_Part_Of_Inherited or Is_Part_Of_Instance;
private
type Base_Extended_Return_Statement is
abstract new Program.Nodes.Node
and Program.Elements.Extended_Return_Statements
.Extended_Return_Statement
with record
Return_Object : not null Program.Elements
.Return_Object_Specifications.Return_Object_Specification_Access;
Statements : Program.Element_Vectors.Element_Vector_Access;
Exception_Handlers : Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access;
end record;
procedure Initialize
(Self : aliased in out Base_Extended_Return_Statement'Class);
overriding procedure Visit
(Self : not null access Base_Extended_Return_Statement;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class);
overriding function Return_Object
(Self : Base_Extended_Return_Statement)
return not null Program.Elements.Return_Object_Specifications
.Return_Object_Specification_Access;
overriding function Statements
(Self : Base_Extended_Return_Statement)
return Program.Element_Vectors.Element_Vector_Access;
overriding function Exception_Handlers
(Self : Base_Extended_Return_Statement)
return Program.Elements.Exception_Handlers
.Exception_Handler_Vector_Access;
overriding function Is_Extended_Return_Statement_Element
(Self : Base_Extended_Return_Statement)
return Boolean;
overriding function Is_Statement_Element
(Self : Base_Extended_Return_Statement)
return Boolean;
type Extended_Return_Statement is
new Base_Extended_Return_Statement
and Program.Elements.Extended_Return_Statements
.Extended_Return_Statement_Text
with record
Return_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Do_Token : Program.Lexical_Elements.Lexical_Element_Access;
Exception_Token : Program.Lexical_Elements.Lexical_Element_Access;
End_Token : Program.Lexical_Elements.Lexical_Element_Access;
Return_Token_2 : Program.Lexical_Elements.Lexical_Element_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
end record;
overriding function To_Extended_Return_Statement_Text
(Self : aliased in out Extended_Return_Statement)
return Program.Elements.Extended_Return_Statements
.Extended_Return_Statement_Text_Access;
overriding function Return_Token
(Self : Extended_Return_Statement)
return not null Program.Lexical_Elements.Lexical_Element_Access;
overriding function Do_Token
(Self : Extended_Return_Statement)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Exception_Token
(Self : Extended_Return_Statement)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function End_Token
(Self : Extended_Return_Statement)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Return_Token_2
(Self : Extended_Return_Statement)
return Program.Lexical_Elements.Lexical_Element_Access;
overriding function Semicolon_Token
(Self : Extended_Return_Statement)
return not null Program.Lexical_Elements.Lexical_Element_Access;
type Implicit_Extended_Return_Statement is
new Base_Extended_Return_Statement
with record
Is_Part_Of_Implicit : Boolean;
Is_Part_Of_Inherited : Boolean;
Is_Part_Of_Instance : Boolean;
end record;
overriding function To_Extended_Return_Statement_Text
(Self : aliased in out Implicit_Extended_Return_Statement)
return Program.Elements.Extended_Return_Statements
.Extended_Return_Statement_Text_Access;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Extended_Return_Statement)
return Boolean;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Extended_Return_Statement)
return Boolean;
overriding function Is_Part_Of_Instance
(Self : Implicit_Extended_Return_Statement)
return Boolean;
end Program.Nodes.Extended_Return_Statements;
|
reznikmm/gela | Ada | 8,404 | ads | -------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- 14 package Asis.Iterator
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
package Asis.Iterator is
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Asis.Iterator encapsulates the generic procedure Traverse_Element which
-- allows an ASIS application to perform an iterative traversal of a
-- logical syntax tree. It requires the use of two generic procedures,
-- Pre_Operation, which identifies processing for the traversal, and
-- Post_Operation, which identifies processing after the traversal.
-- The State_Information allows processing state to be passed during the
-- iteration of Traverse_Element.
--
-- Package Asis.Iterator is established as a child package to highlight the
-- iteration capability and to facilitate the translation of ASIS to IDL.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- 14.1 procedure Traverse_Element
-------------------------------------------------------------------------------
generic
type State_Information is limited private;
with procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
with procedure Post_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information) is <>;
procedure Traverse_Element
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out State_Information);
-------------------------------------------------------------------------------
-- Element - Specifies the initial element in the traversal
-- Control - Specifies what next to do with the traversal
-- State_Information - Specifies other information for the traversal
--
-- Traverses the element and all its component elements, if any.
-- Component elements are all elements that can be obtained by a combination
-- of the ASIS structural queries appropriate for the given element.
--
-- If an element has one or more component elements, each is called a child
-- element. An element's parent element is its Enclosing_Element. Children
-- with the same parent are sibling elements. The type Traverse_Control uses
-- the terms children and siblings to control the traverse.
--
-- For each element, the formal procedure Pre_Operation is called when first
-- visiting the element. Each of that element's children are then visited
-- and finally the formal procedure Post_Operation is called for the element.
--
-- The order of Element traversal is in terms of the textual representation of
-- the Elements. Elements are traversed in left-to-right and top-to-bottom
-- order.
--
-- Traversal of Implicit Elements:
--
-- Implicit elements are not traversed by default. However, they may be
-- explicitly queried and then passed to the traversal instance. Implicit
-- elements include implicit predefined operator declarations, implicit
-- inherited subprogram declarations, implicit expanded generic specifications
-- and bodies, default expressions supplied to procedure, function, and entry
-- calls, etc.
--
-- Applications that wish to traverse these implicit Elements shall query for
-- them at the appropriate places in a traversal and then recursively call
-- their instantiation of the traversal generic. (Implicit elements provided
-- by ASIS do not cover all possible Ada implicit constructs. For example,
-- implicit initializations for variables of an access type are not provided
-- by ASIS.)
--
-- Traversal of Association lists:
--
-- Argument and association lists for procedure calls, function calls, entry
-- calls, generic instantiations, and aggregates are traversed in their
-- unnormalized forms, as if the Normalized parameter was False for those
-- queries. Implementations that always normalize certain associations may
-- return Is_Normalized associations. See the Implementation Permissions
-- for the queries Discriminant_Associations, Generic_Actual_Part,
-- Call_Statement_Parameters, Record_Component_Associations, or
-- Function_Call_Parameters.
--
-- Applications that wish to explicitly traverse normalized associations can
-- do so by querying the appropriate locations in order to obtain the
-- normalized list. The list can then be traversed by recursively calling
-- the traverse instance. Once that sub-traversal is finished, the Control
-- parameter can be set to Abandon_Children to skip processing of the
-- unnormalized argument list.
--
-- Traversal can be controlled with the Control parameter.
--
-- A call to an instance of Traverse_Element will not result in calls to
-- Pre_Operation or Post_Operation unless Control is set to Continue.
--
-- The subprograms matching Pre_Operation and Post_Operation can set
-- their Control parameter to affect the traverse:
--
-- - Continue
--
-- o Continues the normal depth-first traversal.
--
-- - Abandon_Children
--
-- o Prevents traversal of the current element's children.
--
-- o If set in a Pre_Operation, traversal picks up with the next sibling
-- element of the current element.
--
-- o If set in a Post_Operation, this is the same as Continue, all children
-- will already have been traversed. Traversal picks up with the
-- Post_Operation of the parent.
--
-- - Abandon_Siblings
--
-- o Prevents traversal of the current element's children and remaining
-- siblings.
--
-- o If set in a Pre_Operation, this abandons the associated Post_Operation
-- for the current element. Traversal picks up with the Post_Operation
-- of the parent.
--
-- o If set in a Post_Operation, traversal picks up with the Post_Operation
-- of the parent.
--
-- - Terminate_Immediately
--
-- o Does exactly that.
--
-- Raises ASIS_Inappropriate_Element if the element is a Nil_Element
--
-------------------------------------------------------------------------------
end Asis.Iterator;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2014, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
stcarrez/ada-security | Ada | 4,674 | ads | -----------------------------------------------------------------------
-- security -- Security
-- Copyright (C) 2010, 2011, 2012, 2015, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
-- = Security =
-- The `Security` package provides a security framework that allows
-- an application to use OpenID or OAuth security frameworks. This security
-- framework was first developed within the Ada Server Faces project.
-- It was moved to a separate project so that it can easily be used with AWS.
-- This package defines abstractions that are close or similar to Java
-- security package.
--
-- The security framework uses the following abstractions:
--
-- * **Policy and policy manager**:
-- The `Policy` defines and implements the set of security rules that specify how to
-- protect the system or resources. The `Policy_Manager` maintains the security policies.
--
-- * **Principal**:
-- The `Principal` is the entity that can be authenticated. A principal is obtained
-- after successful authentication of a user or of a system through an authorization process.
-- The OpenID or OAuth authentication processes generate such security principal.
--
-- * **Permission**:
-- The `Permission` represents an access to a system or application resource.
-- A permission is checked by using the security policy manager. The policy manager uses a
-- security controller to enforce the permission.
--
-- The `Security_Context` holds the contextual information that the security controller
-- can use to verify the permission. The security context is associated with a principal and
-- a set of policy context.
--
-- == Overview ==
-- An application will create a security policy manager and register one or several security
-- policies (yellow). The framework defines a simple role based security policy and an URL
-- security policy intended to provide security in web applications. The security policy manager
-- reads some security policy configuration file which allows the security policies to configure
-- and create the security controllers. These controllers will enforce the security according
-- to the application security rules. All these components are built only once when
-- an application starts.
--
-- A user is authenticated through an authentication system which creates a `Principal`
-- instance that identifies the user (green). The security framework provides two authentication
-- systems: OpenID and OAuth 2.0 OpenID Connect.
--
-- [images/ModelOverview.png]
--
-- When a permission must be enforced, a security context is created and linked to the
-- `Principal` instance (blue). Additional security policy context can be added depending
-- on the application context. To check the permission, the security policy manager is called
-- and it will ask a security controller to verify the permission.
--
-- The framework allows an application to plug its own security policy, its own policy context,
-- its own principal and authentication mechanism.
--
-- @include security-permissions.ads
--
-- == Principal ==
-- A principal is created by using either the [Security_Auth OpenID],
-- the [Security_OAuth OAuth] or another authentication mechanism. The authentication produces
-- an object that must implement the `Principal` interface. For example:
--
-- P : Security.Auth.Principal_Access := Security.Auth.Create_Principal (Auth);
--
-- or
--
-- P : Security.OAuth.Clients.Access_Token_Access := Security.OAuth.Clients.Create_Access_Token
--
-- The principal is then stored in a security context.
--
-- @include security-contexts.ads
--
package Security is
pragma Preelaborate;
-- ------------------------------
-- Principal
-- ------------------------------
type Principal is limited interface;
type Principal_Access is access all Principal'Class;
-- Get the principal name.
function Get_Name (From : in Principal) return String is abstract;
end Security;
|
persan/A-gst | Ada | 16,700 | ads | pragma Ada_2005;
pragma Style_Checks (Off);
pragma Warnings (Off);
with Interfaces.C; use Interfaces.C;
with glib;
with glib.Values;
with System;
-- limited -- with GStreamer.GST_Low_Level.glib_2_0_glib_gthread_h;
-- limited with GStreamer.GST_Low_Level.glib_2_0_glib_gslist_h;
with GLIB; -- with GStreamer.GST_Low_Level.glibconfig_h;
with System;
limited with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstsegment_h;
with GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstobject_h;
with glib;
package GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstcollectpads_h is
-- unsupported macro: GST_TYPE_COLLECT_PADS (gst_collect_pads_get_type())
-- arg-macro: function GST_COLLECT_PADS (obj)
-- return G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_COLLECT_PADS,GstCollectPads);
-- arg-macro: function GST_COLLECT_PADS_CLASS (klass)
-- return G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_COLLECT_PADS,GstCollectPadsClass);
-- arg-macro: function GST_COLLECT_PADS_GET_CLASS (obj)
-- return G_TYPE_INSTANCE_GET_CLASS ((obj),GST_TYPE_COLLECT_PADS,GstCollectPadsClass);
-- arg-macro: function GST_IS_COLLECT_PADS (obj)
-- return G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_COLLECT_PADS);
-- arg-macro: function GST_IS_COLLECT_PADS_CLASS (klass)
-- return G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_COLLECT_PADS);
-- arg-macro: function GST_COLLECT_PADS_GET_PAD_LOCK (pads)
-- return ((GstCollectPads *)pads).abidata.ABI.pad_lock;
-- arg-macro: function GST_COLLECT_PADS_PAD_LOCK (pads)
-- return g_mutex_lock(GST_COLLECT_PADS_GET_PAD_LOCK (pads));
-- arg-macro: function GST_COLLECT_PADS_PAD_UNLOCK (pads)
-- return g_mutex_unlock(GST_COLLECT_PADS_GET_PAD_LOCK (pads));
-- arg-macro: function GST_COLLECT_PADS_GET_COND (pads)
-- return ((GstCollectPads *)pads).cond;
-- arg-macro: function GST_COLLECT_PADS_WAIT (pads)
-- return g_cond_wait (GST_COLLECT_PADS_GET_COND (pads), GST_OBJECT_GET_LOCK (pads));
-- arg-macro: function GST_COLLECT_PADS_SIGNAL (pads)
-- return g_cond_signal (GST_COLLECT_PADS_GET_COND (pads));
-- arg-macro: function GST_COLLECT_PADS_BROADCAST (pads)
-- return g_cond_broadcast (GST_COLLECT_PADS_GET_COND (pads));
-- GStreamer
-- * Copyright (C) 2005 Wim Taymans <[email protected]>
-- *
-- * gstcollect_pads.h:
-- *
-- * This library is free software; you can redistribute it and/or
-- * modify it under the terms of the GNU Library General Public
-- * License as published by the Free Software Foundation; either
-- * version 2 of the License, or (at your option) any later version.
-- *
-- * This library is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- * Library General Public License for more details.
-- *
-- * You should have received a copy of the GNU Library General Public
-- * License along with this library; if not, write to the
-- * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-- * Boston, MA 02111-1307, USA.
--
type GstCollectData;
type anon_302;
type anon_303 is record
flushing : aliased GLIB.gboolean; -- gst/base/gstcollectpads.h:98
new_segment : aliased GLIB.gboolean; -- gst/base/gstcollectpads.h:99
eos : aliased GLIB.gboolean; -- gst/base/gstcollectpads.h:100
refcount : aliased GLIB.gint; -- gst/base/gstcollectpads.h:101
end record;
pragma Convention (C_Pass_By_Copy, anon_303);
type u_GstCollectData_u_gst_reserved_array is array (0 .. 3) of System.Address;
type anon_302 (discr : unsigned := 0) is record
case discr is
when 0 =>
ABI : aliased anon_303; -- gst/base/gstcollectpads.h:102
when others =>
u_gst_reserved : u_GstCollectData_u_gst_reserved_array; -- gst/base/gstcollectpads.h:104
end case;
end record;
pragma Convention (C_Pass_By_Copy, anon_302);
pragma Unchecked_Union (anon_302);--subtype GstCollectData is u_GstCollectData; -- gst/base/gstcollectpads.h:36
type GstCollectPads;
type anon_304;
type anon_305 is record
pad_lock : access GStreamer.GST_Low_Level.glib_2_0_glib_gthread_h.GMutex; -- gst/base/gstcollectpads.h:162
pad_list : access GStreamer.GST_Low_Level.glib_2_0_glib_gslist_h.GSList; -- gst/base/gstcollectpads.h:163
pad_cookie : aliased GLIB.guint32; -- gst/base/gstcollectpads.h:164
priv : System.Address; -- gst/base/gstcollectpads.h:165
end record;
pragma Convention (C_Pass_By_Copy, anon_305);
type u_GstCollectPads_u_gst_reserved_array is array (0 .. 3) of System.Address;
type anon_304 (discr : unsigned := 0) is record
case discr is
when 0 =>
ABI : aliased anon_305; -- gst/base/gstcollectpads.h:166
when others =>
u_gst_reserved : u_GstCollectPads_u_gst_reserved_array; -- gst/base/gstcollectpads.h:168
end case;
end record;
pragma Convention (C_Pass_By_Copy, anon_304);
pragma Unchecked_Union (anon_304);--subtype GstCollectPads is u_GstCollectPads; -- gst/base/gstcollectpads.h:37
-- skipped empty struct u_GstCollectPadsPrivate
-- skipped empty struct GstCollectPadsPrivate
type GstCollectPadsClass;
type u_GstCollectPadsClass_u_gst_reserved_array is array (0 .. 3) of System.Address;
--subtype GstCollectPadsClass is u_GstCollectPadsClass; -- gst/base/gstcollectpads.h:39
--*
-- * GstCollectDataDestroyNotify:
-- * @data: the #GstCollectData that will be freed
-- *
-- * A function that will be called when the #GstCollectData will be freed.
-- * It is passed the pointer to the structure and should free any custom
-- * memory and resources allocated for it.
-- *
-- * Since: 0.10.12
--
type GstCollectDataDestroyNotify is access procedure (arg1 : access GstCollectData);
pragma Convention (C, GstCollectDataDestroyNotify); -- gst/base/gstcollectpads.h:51
--*
-- * GstCollectPadsClipFunction:
-- * @pads: a #GstCollectPads
-- * @data: a #GstCollectData
-- * @buffer: a #GstBuffer
-- * @user_data: user data
-- *
-- * A function that will be called when @buffer is received on the pad managed
-- * by @data in the collecpad object @pads.
-- *
-- * The function should use the segment of @data and the negotiated media type on
-- * the pad to perform clipping of @buffer.
-- *
-- * This function takes ownership of @buffer.
-- *
-- * Returns: a #GstBuffer that contains the clipped data of @buffer or NULL when
-- * the buffer has been clipped completely.
-- *
-- * Since: 0.10.26
--
type GstCollectPadsClipFunction is access function
(arg1 : access GstCollectPads;
arg2 : access GstCollectData;
arg3 : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer;
arg4 : System.Address) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer;
pragma Convention (C, GstCollectPadsClipFunction); -- gst/base/gstcollectpads.h:73
--*
-- * GstCollectData:
-- * @collect: owner #GstCollectPads
-- * @pad: #GstPad managed by this data
-- * @buffer: currently queued buffer.
-- * @pos: position in the buffer
-- * @segment: last segment received.
-- *
-- * Structure used by the collect_pads.
--
-- with LOCK of @collect
type GstCollectData is record
collect : access GstCollectPads; -- gst/base/gstcollectpads.h:89
pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad; -- gst/base/gstcollectpads.h:90
buffer : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/base/gstcollectpads.h:91
pos : aliased GLIB.guint; -- gst/base/gstcollectpads.h:92
segment : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstsegment_h.GstSegment; -- gst/base/gstcollectpads.h:93
abidata : aliased anon_302; -- gst/base/gstcollectpads.h:105
end record;
pragma Convention (C_Pass_By_Copy, GstCollectData); -- gst/base/gstcollectpads.h:86
--< private >
-- adding + 0 to mark ABI change to be undone later
--*
-- * GstCollectPadsFunction:
-- * @pads: the #GstCollectPads that triggered the callback
-- * @user_data: user data passed to gst_collect_pads_set_function()
-- *
-- * A function that will be called when all pads have received data.
-- *
-- * Returns: #GST_FLOW_OK for success
--
type GstCollectPadsFunction is access function (arg1 : access GstCollectPads; arg2 : System.Address) return GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstFlowReturn;
pragma Convention (C, GstCollectPadsFunction); -- gst/base/gstcollectpads.h:117
--*
-- * GstCollectPads:
-- * @data: #GList of #GstCollectData managed by this #GstCollectPads.
-- *
-- * Collectpads object.
-- * Note that @data is only reliable for iterating the list of #GstCollectData
-- * when inside the #GstCollectPadsFunction callback.
--
type GstCollectPads is record
object : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstobject_h.GstObject; -- gst/base/gstcollectpads.h:137
data : access GStreamer.GST_Low_Level.glib_2_0_glib_gslist_h.GSList; -- gst/base/gstcollectpads.h:140
cookie : aliased GLIB.guint32; -- gst/base/gstcollectpads.h:143
cond : access GStreamer.GST_Low_Level.glib_2_0_glib_gthread_h.GCond; -- gst/base/gstcollectpads.h:146
func : GstCollectPadsFunction; -- gst/base/gstcollectpads.h:148
user_data : System.Address; -- gst/base/gstcollectpads.h:149
numpads : aliased GLIB.guint; -- gst/base/gstcollectpads.h:151
queuedpads : aliased GLIB.guint; -- gst/base/gstcollectpads.h:152
eospads : aliased GLIB.guint; -- gst/base/gstcollectpads.h:153
started : aliased GLIB.gboolean; -- gst/base/gstcollectpads.h:156
abidata : aliased anon_304; -- gst/base/gstcollectpads.h:169
end record;
pragma Convention (C_Pass_By_Copy, GstCollectPads); -- gst/base/gstcollectpads.h:136
--< public >
-- with LOCK
-- list of CollectData items
--< private >
-- @data list cookie
-- with LOCK
-- to signal removal of data
-- function and user_data for callback
-- number of pads in @data
-- number of pads with a buffer
-- number of pads that are EOS
-- with LOCK and PAD_LOCK
--< private >
-- since 0.10.6
-- with PAD_LOCK
-- used to serialize add/remove
-- updated pad list
-- updated cookie
-- adding + 0 to mark ABI change to be undone later
type GstCollectPadsClass is record
parent_class : aliased GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstobject_h.GstObjectClass; -- gst/base/gstcollectpads.h:173
u_gst_reserved : u_GstCollectPadsClass_u_gst_reserved_array; -- gst/base/gstcollectpads.h:176
end record;
pragma Convention (C_Pass_By_Copy, GstCollectPadsClass); -- gst/base/gstcollectpads.h:172
--< private >
function gst_collect_pads_get_type return GLIB.GType; -- gst/base/gstcollectpads.h:179
pragma Import (C, gst_collect_pads_get_type, "gst_collect_pads_get_type");
-- creating the object
function gst_collect_pads_new return access GstCollectPads; -- gst/base/gstcollectpads.h:182
pragma Import (C, gst_collect_pads_new, "gst_collect_pads_new");
-- set the callbacks
procedure gst_collect_pads_set_function
(pads : access GstCollectPads;
func : GstCollectPadsFunction;
user_data : System.Address); -- gst/base/gstcollectpads.h:185
pragma Import (C, gst_collect_pads_set_function, "gst_collect_pads_set_function");
procedure gst_collect_pads_set_clip_function
(pads : access GstCollectPads;
clipfunc : GstCollectPadsClipFunction;
user_data : System.Address); -- gst/base/gstcollectpads.h:187
pragma Import (C, gst_collect_pads_set_clip_function, "gst_collect_pads_set_clip_function");
-- pad management
function gst_collect_pads_add_pad
(pads : access GstCollectPads;
pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad;
size : GLIB.guint) return access GstCollectData; -- gst/base/gstcollectpads.h:191
pragma Import (C, gst_collect_pads_add_pad, "gst_collect_pads_add_pad");
function gst_collect_pads_add_pad_full
(pads : access GstCollectPads;
pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad;
size : GLIB.guint;
destroy_notify : GstCollectDataDestroyNotify) return access GstCollectData; -- gst/base/gstcollectpads.h:192
pragma Import (C, gst_collect_pads_add_pad_full, "gst_collect_pads_add_pad_full");
function gst_collect_pads_remove_pad (pads : access GstCollectPads; pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad) return GLIB.gboolean; -- gst/base/gstcollectpads.h:195
pragma Import (C, gst_collect_pads_remove_pad, "gst_collect_pads_remove_pad");
function gst_collect_pads_is_active (pads : access GstCollectPads; pad : access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstPad) return GLIB.gboolean; -- gst/base/gstcollectpads.h:196
pragma Import (C, gst_collect_pads_is_active, "gst_collect_pads_is_active");
-- start/stop collection
function gst_collect_pads_collect (pads : access GstCollectPads) return GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstFlowReturn; -- gst/base/gstcollectpads.h:199
pragma Import (C, gst_collect_pads_collect, "gst_collect_pads_collect");
function gst_collect_pads_collect_range
(pads : access GstCollectPads;
offset : GLIB.guint64;
length : GLIB.guint) return GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstpad_h.GstFlowReturn; -- gst/base/gstcollectpads.h:200
pragma Import (C, gst_collect_pads_collect_range, "gst_collect_pads_collect_range");
procedure gst_collect_pads_start (pads : access GstCollectPads); -- gst/base/gstcollectpads.h:202
pragma Import (C, gst_collect_pads_start, "gst_collect_pads_start");
procedure gst_collect_pads_stop (pads : access GstCollectPads); -- gst/base/gstcollectpads.h:203
pragma Import (C, gst_collect_pads_stop, "gst_collect_pads_stop");
procedure gst_collect_pads_set_flushing (pads : access GstCollectPads; flushing : GLIB.gboolean); -- gst/base/gstcollectpads.h:204
pragma Import (C, gst_collect_pads_set_flushing, "gst_collect_pads_set_flushing");
-- get collected buffers
function gst_collect_pads_peek (pads : access GstCollectPads; data : access GstCollectData) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/base/gstcollectpads.h:207
pragma Import (C, gst_collect_pads_peek, "gst_collect_pads_peek");
function gst_collect_pads_pop (pads : access GstCollectPads; data : access GstCollectData) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/base/gstcollectpads.h:208
pragma Import (C, gst_collect_pads_pop, "gst_collect_pads_pop");
-- get collected bytes
function gst_collect_pads_available (pads : access GstCollectPads) return GLIB.guint; -- gst/base/gstcollectpads.h:211
pragma Import (C, gst_collect_pads_available, "gst_collect_pads_available");
function gst_collect_pads_read
(pads : access GstCollectPads;
data : access GstCollectData;
bytes : System.Address;
size : GLIB.guint) return GLIB.guint; -- gst/base/gstcollectpads.h:212
pragma Import (C, gst_collect_pads_read, "gst_collect_pads_read");
function gst_collect_pads_read_buffer
(pads : access GstCollectPads;
data : access GstCollectData;
size : GLIB.guint) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/base/gstcollectpads.h:214
pragma Import (C, gst_collect_pads_read_buffer, "gst_collect_pads_read_buffer");
function gst_collect_pads_take_buffer
(pads : access GstCollectPads;
data : access GstCollectData;
size : GLIB.guint) return access GStreamer.GST_Low_Level.gstreamer_0_10_gst_gstbuffer_h.GstBuffer; -- gst/base/gstcollectpads.h:216
pragma Import (C, gst_collect_pads_take_buffer, "gst_collect_pads_take_buffer");
function gst_collect_pads_flush
(pads : access GstCollectPads;
data : access GstCollectData;
size : GLIB.guint) return GLIB.guint; -- gst/base/gstcollectpads.h:218
pragma Import (C, gst_collect_pads_flush, "gst_collect_pads_flush");
end GStreamer.GST_Low_Level.gstreamer_0_10_gst_base_gstcollectpads_h;
|
edin/raytracer | Ada | 489 | ads | --
-- Raytracer implementation in Ada
-- by John Perry (github: johnperry-math)
-- 2021
--
-- specification for Cameras, that view the scene
--
-- local packages
with Vectors; use Vectors;
-- @summary Cameras that view the scene
package Cameras is
type Camera_Type is record
Forward, Right, Up, Position: Vector;
end record;
function Create_Camera(Position, Target: Vector) return Camera_Type;
-- creates a camera at Position that is looking at Target
end Cameras;
|
kontena/ruby-packer | Ada | 3,941 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding --
-- --
-- Terminal_Interface.Curses.Menus.Menu_User_Data --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998-2009,2014 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer, 1996
-- Version Control:
-- $Revision: 1.15 $
-- Binding Version 01.00
------------------------------------------------------------------------------
with Terminal_Interface.Curses.Aux; use Terminal_Interface.Curses.Aux;
package body Terminal_Interface.Curses.Menus.Menu_User_Data is
use type Interfaces.C.int;
procedure Set_User_Data (Men : Menu;
Data : User_Access)
is
function Set_Menu_Userptr (Men : Menu;
Data : User_Access) return Eti_Error;
pragma Import (C, Set_Menu_Userptr, "set_menu_userptr");
begin
Eti_Exception (Set_Menu_Userptr (Men, Data));
end Set_User_Data;
function Get_User_Data (Men : Menu) return User_Access
is
function Menu_Userptr (Men : Menu) return User_Access;
pragma Import (C, Menu_Userptr, "menu_userptr");
begin
return Menu_Userptr (Men);
end Get_User_Data;
procedure Get_User_Data (Men : Menu;
Data : out User_Access)
is
begin
Data := Get_User_Data (Men);
end Get_User_Data;
end Terminal_Interface.Curses.Menus.Menu_User_Data;
|
annexi-strayline/AURA | Ada | 8,254 | ads | ------------------------------------------------------------------------------
-- --
-- Ada User Repository Annex (AURA) --
-- ANNEXI-STRAYLINE Reference Implementation --
-- --
-- Command Line Interface --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2020-2021, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Richard Wai (ANNEXI-STRAYLINE) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- --
-- * Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A --
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- This package handles the transition from Compilation to the final result,
-- and is compiler-specific. This particular package is GNAT-specific
with Ada.Containers.Synchronized_Queue_Interfaces;
with Ada.Containers.Unbounded_Synchronized_Queues;
package Build.Linking is
package UBSQ is new Ada.Containers.Synchronized_Queue_Interfaces
(UBS.Unbounded_String);
package Unbounded_String_Queues is
new Ada.Containers.Unbounded_Synchronized_Queues (UBSQ);
------------------
-- All_Compiled --
------------------
-- Common precondition
use type Registrar.Library_Units.Library_Unit_State;
function All_Compiled
(Unit_Set: Registrar.Library_Units.Library_Unit_Sets.Set)
return Boolean
is (for all Unit of Unit_Set =>
Unit.State = Registrar.Library_Units.Compiled);
-------------------------
-- Scan_Linker_Options --
-------------------------
procedure Scan_Linker_Options
(Unit_Set: in Registrar.Library_Units.Library_Unit_Sets.Set)
with Pre => All_Compiled (Unit_Set);
Scan_Progress : aliased Progress.Progress_Tracker;
Linker_Options: Unbounded_String_Queues.Queue;
-- Scans all Units in Unit_Set, and adds any linker options retrieved to
-- the Linker_Options queue.
----------
-- Bind --
----------
procedure Bind
(Unit_Set : in Registrar.Library_Units.Library_Unit_Sets.Set;
Configuration: in Build_Configuration;
Errors : out UBS.Unbounded_String)
with Pre => All_Compiled (Unit_Set);
-- Generates and enters the binder source (unit name is "ada_main" for GNAT)
--
-- After calling Bind, and waiting for unit entry to complete, another
-- compilation run is needed to compile the binder source.
--
-- If the process is successful, Errors will have a zero length
----------
-- Link --
----------
procedure Link_Image
(Image_Path : in String;
Unit_Set : in Registrar.Library_Units.Library_Unit_Sets.Set;
Configuration: in Build_Configuration;
Errors : out UBS.Unbounded_String)
with Pre => Configuration.Mode in Image | Library
and All_Compiled (Unit_Set);
-- Shall be called after Bind.
-- Shall be called after Scan_Linker_Options has completed on Unit_Set.
--
-- This is the last phase of a build process.
--
-- Link_Image creates an executable image that is put in the project root
-- directory, and has the file name of Image_Name. It incorproates only
-- the object files for the units of Unit_Set.
procedure Link_Library
(Library_Path : in String;
Unit_Set : in Registrar.Library_Units.Library_Unit_Sets.Set;
Configuration: in Build_Configuration;
Errors : out UBS.Unbounded_String)
renames Link_Image;
-- Shall be called after Bind.
-- Shall be called after Scan_Linker_Options has completed on Unit_Set.
--
-- This is the last phase of a build process.
--
-- Links all compilation objects of Unit_Set into a single dynamic library,
-- of the file specified by Library_Path.
--
-- In the case of GNAT/gcc, linking a shared library is exactly the same
-- as linking an image, except for the extension of the output file
procedure Archive
(Archive_Path : in String;
Unit_Set : in Registrar.Library_Units.Library_Unit_Sets.Set;
Configuration: in Build_Configuration;
Errors : out UBS.Unbounded_String)
with Pre => Configuration.Mode = Library
and All_Compiled (Unit_Set);
-- Shall be called after Bind.
-- Shall be called after Scan_Linker_Options has completed on Unit_Set.
--
-- Creates an archive file in the project root directory named Base_Name.a
-- that contains all compilation objects of Unit_Set. Also generates
-- a Base_Name.linkopt that contains a string indicating all required
-- libraries and linker options loaded from Scan_Linker_Options.
---------------------
-- Link_Subsystems --
---------------------
procedure Link_Subsystems;
Link_Subsystems_Progress: aliased Progress.Progress_Tracker;
Link_Subsystems_Errors : Unbounded_String_Queues.Queue;
-- Link_Subsystems executes its own series of Linker_Option scans that are
-- specific to each registered Subsystem, and so Scan_Linker_Options
-- does NOT need to be run.
--
-- Link_Subsystems Creates a Ada-specific shared library for each registered
-- Subsystem, and places a shared library with the name of the subsystem
-- in the build root.
--
-- Linker command output is per subsystem
end Build.Linking;
|
MinimSecure/unum-sdk | Ada | 840 | adb | -- Copyright 2012-2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Pck; use Pck;
procedure Foo is
SA : Simple_Array := (1, 2, 3, 4);
begin
Update_Small (SA (3)); -- STOP
end Foo;
|
reznikmm/matreshka | Ada | 4,576 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Style.Lines_Attributes is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Style_Lines_Attribute_Node is
begin
return Self : Style_Lines_Attribute_Node do
Matreshka.ODF_Style.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Style_Prefix);
end return;
end Create;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Style_Lines_Attribute_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.Lines_Attribute;
end Get_Local_Name;
begin
Matreshka.DOM_Documents.Register_Attribute
(Matreshka.ODF_String_Constants.Style_URI,
Matreshka.ODF_String_Constants.Lines_Attribute,
Style_Lines_Attribute_Node'Tag);
end Matreshka.ODF_Style.Lines_Attributes;
|
zhmu/ananas | Ada | 2,815 | adb | ------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . T A S K _ I N F O --
-- --
-- B o d y --
-- (Compiler Interface) --
-- --
-- Copyright (C) 1998-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This is a dummy version of this package that is needed to solve bootstrap
-- problems when compiling a library that doesn't require s-tasinf.adb from
-- a compiler that contains one.
-- This package contains the definitions and routines associated with the
-- implementation of the Task_Info pragma.
package body System.Task_Info is
end System.Task_Info;
|
reznikmm/matreshka | Ada | 3,636 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Elements.Generic_Hash;
function AMF.CMOF.Redefinable_Elements.Hash is
new AMF.Elements.Generic_Hash (CMOF_Redefinable_Element, CMOF_Redefinable_Element_Access);
|
reznikmm/matreshka | Ada | 3,335 | ads | -- Copyright (c) 1990 Regents of the University of California.
-- All rights reserved.
--
-- The primary authors of ayacc were David Taback and Deepak Tolani.
-- Enhancements were made by Ronald J. Schmalz.
--
-- Send requests for ayacc information to [email protected]
-- Send bug reports for ayacc to [email protected]
--
-- Redistribution and use in source and binary forms are permitted
-- provided that the above copyright notice and this paragraph are
-- duplicated in all such forms and that any documentation,
-- advertising materials, and other materials related to such
-- distribution and use acknowledge that the software was developed
-- by the University of California, Irvine. The name of the
-- University may not be used to endorse or promote products derived
-- from this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
-- IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
-- WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
-- Module : options.ada
-- Component of : ayacc
-- Version : 1.2
-- Date : 11/21/86 12:31:39
-- SCCS File : disk21~/rschm/hasee/sccs/ayacc/sccs/sxoptions.ada
-- $Header: options.a,v 0.1 86/04/01 15:08:15 ada Exp $
-- $Log: options.a,v $
-- Revision 0.1 86/04/01 15:08:15 ada
-- This version fixes some minor bugs with empty grammars
-- and $$ expansion. It also uses vads5.1b enhancements
-- such as pragma inline.
--
--
-- Revision 0.0 86/02/19 18:37:34 ada
--
-- These files comprise the initial version of Ayacc
-- designed and implemented by David Taback and Deepak Tolani.
-- Ayacc has been compiled and tested under the Verdix Ada compiler
-- version 4.06 on a vax 11/750 running Unix 4.2BSD.
--
package Options is
procedure Set_Options(S: in String);
-- SET_OPTIONS sets the debug and verbose flags according
-- the the string S.
-- If S contains the characters 'v' or 'V', the verbose
-- option is set.
-- If S contains the charactars 'c' or 'C', the vebose conflicts
-- option is set.
-- If S contains the characters 'd' or 'D', the debug
-- option is set.
-- If S contains the characters 's' or 'S', the summary option
-- is set.
-- UMASS CODES :
-- If S contains the characters 'e' or 'E', the error recovery
-- extension option is set.
-- END OF UMASS CODES.
function Verbose return Boolean;
-- Returns TRUE if the verbose file is to be created.
function Verbose_Conflict return Boolean;
-- Returns TRUE if only the states involved in conflicts
-- are to printed.
function Debug return Boolean;
-- Returns TRUE if the YYPARSE procedure should generate
-- debugging output.
function Summary return Boolean;
-- Returns TRUE if a summary of statistics of the generated
-- parser should be printed.
function Interface_to_C return Boolean;
function Loud return Boolean;
-- Returns TRUE if Ayacc should output useless and annoying information
-- while it is running.
-- UMASS CODES :
function Error_Recovery_Extension return Boolean;
-- Returns TRUE if the codes of error recovery extension should
-- be generated.
-- END OF UMASS CODES.
Illegal_Option: exception;
end Options;
|
shintakezou/langkit | Ada | 13,421 | ads | --
-- Copyright (C) 2014-2022, AdaCore
-- SPDX-License-Identifier: Apache-2.0
--
with Ada.Strings.Unbounded;
with System;
with GNATCOLL.VFS;
with Langkit_Support.Slocs; use Langkit_Support.Slocs;
with Langkit_Support.Symbols; use Langkit_Support.Symbols;
with Langkit_Support.Text; use Langkit_Support.Text;
with Langkit_Support.Types; use Langkit_Support.Types;
with Langkit_Support.Vectors;
package Langkit_Support.Token_Data_Handlers is
type Raw_Token_Kind is new Natural;
-- Kind for a token, stored as a mere number
type Stored_Token_Data is record
Kind : Raw_Token_Kind;
Source_First : Positive;
Source_Last : Natural;
-- Bounds in the source buffer corresponding to this token
Symbol : Thin_Symbol;
-- Depending on the token kind (according to the lexer specification),
-- this is either null or the symbolization of the token text.
--
-- For instance: null for keywords but actual text for identifiers.
end record with Pack;
-- Holder for per-token data to be stored in the token data handler
-- Trivias are tokens that are not to be taken into account during parsing,
-- and are marked as so in the lexer definition. Conceptually, we want
-- to keep a (potentially empty) list of trivias for each token, which
-- is every trivia that is between the current token and the next token.
type Trivia_Node is record
T : aliased Stored_Token_Data;
Has_Next : Boolean;
end record with Pack;
-- This defines a node in a trivia linked list
package Token_Vectors is new Langkit_Support.Vectors
(Element_Type => Stored_Token_Data);
package Text_Vectors is new Langkit_Support.Vectors
(Element_Type => Text_Access);
package Trivia_Vectors is new Langkit_Support.Vectors
(Element_Type => Trivia_Node);
package Integer_Vectors is new Langkit_Support.Vectors
(Element_Type => Integer);
use Token_Vectors, Trivia_Vectors, Integer_Vectors;
type Token_Index is new Integer range
Token_Vectors.Index_Type'First - 1
.. Token_Vectors.Index_Type'Last;
-- Although we cannot use anything else than Natural as Token_Vectors
-- indexes, this type will be used outside this package so that typing
-- helps us finding index misuses.
No_Token_Index : constant Token_Index := Token_Index'First;
First_Token_Index : constant Token_Index := Token_Index'First + 1;
type Token_Or_Trivia_Index is record
Token, Trivia : Token_Index;
-- Indices that identify what this refers to.
--
-- * If this references a token, then Token is the corresponding index
-- in TDH.Tokens and Trivia is No_Token_Index.
--
-- * If this references a trivia that comes before the first token,
-- Token is No_Token_Index while Trivia is the corresponding index in
-- TDH.Trivias.
--
-- * If this references a trivia that comes after some token, Token is
-- the index for this token and Trivia is the corresponding index for
-- this trivia.
--
-- * If this references no token, both Token and Trivia are
-- No_Token_Index.
end record;
No_Token_Or_Trivia_Index : constant Token_Or_Trivia_Index :=
(No_Token_Index, No_Token_Index);
package Token_Index_Vectors is new Langkit_Support.Vectors
(Element_Type => Token_Index);
package Index_Vectors is new Langkit_Support.Vectors (Positive);
type Token_Data_Handler is record
-- Start of ABI area. In order to perform fast checks from foreign
-- languages, we maintain minimal ABI for token data handlers: this
-- allows us in language bindings to directly peek in this record rather
-- than rely on (slow) calls to getters.
Version : Version_Number;
-- Version number for this token data handler. Incremented each time the
-- handler is reset. This allows checking that token references are not
-- stale.
-- End of ABI area
Source_Buffer : Text_Access;
-- The whole source buffer. It belongs to this token data handler,
-- and will be deallocated along with it. WARNING: this buffer might
-- actually be *larger* than the real source, which is why we have the
-- ``Source_First``/``Source_Last`` fields below. We allocate a bigger
-- buffer pessimistically so we don't have to have a growable buffer.
Source_First : Positive;
Source_Last : Natural;
-- Actual bounds in Source_Buffer for the source text
Filename : GNATCOLL.VFS.Virtual_File;
-- If the source buffer comes from a file, Filename contains the name of
-- that file. No_File otherwise.
Charset : Ada.Strings.Unbounded.Unbounded_String;
-- If the source buffer was decoded, charset that was used to do so.
-- Empty string otherwise.
Tokens : Token_Vectors.Vector;
-- Sequence of tokens in the same order as found in the source file
Trivias : Trivia_Vectors.Vector;
-- Sequence of trivia in the same order as found in the source file.
-- Trivia are stored in a way that is related to the neighbor tokens:
--
-- * If a token T0 at index I0 is followed by trivias T1, T2, ..., TN,
-- then the (I0+1)'th entry in Tokens_To_Trivia will contain an index
-- I1. T1 is then to be found in Trivia at index I1.
--
-- If it's the only trivia before the next token, then Has_Next is
-- False for it, otherwise it is true and T2 is present at index I1+1.
-- The same goes on for T2, ..., until TN, the last trivia before the
-- next token, for which Has_Next is False.
--
-- * If T0 is not followed by any trivia before the next token, then
-- the (I0+1)'th entry in Tokens_To_Trivia is No_Token_Index.
Tokens_To_Trivias : Integer_Vectors.Vector;
-- This is the correspondence map between regular tokens and trivias:
-- see documentation for the Trivias field. Note that the first entry
-- stands for the leading trivia, i.e. trivia that come before the first
-- token, then the second entry stands for the trivia that come after
-- the first token, and so on.
Symbols : Symbol_Table;
-- Symbol table for this handler. Note that this can be shared accross
-- multiple Token_Data_Handlers.
Lines_Starts : Index_Vectors.Vector;
-- Table keeping count of line starts and line endings. The index of the
-- starting character for line N is at the Nth position in the vector.
Tab_Stop : Positive;
Owner : System.Address;
-- Untyped reference to the object that owns this token data handler.
-- Generated libraries use this to have a backlink to the analysis unit.
end record;
type Token_Data_Handler_Access is access all Token_Data_Handler;
function Initialized (TDH : Token_Data_Handler) return Boolean;
-- Return whether TDH has been initialized (see the Initialize procedure)
function Has_Source_Buffer (TDH : Token_Data_Handler) return Boolean
with Pre => Initialized (TDH);
-- Return whether TDH was used to lex some input source
procedure Initialize
(TDH : out Token_Data_Handler;
Symbols : Symbol_Table;
Owner : System.Address;
Tab_Stop : Positive := Default_Tab_Stop)
with Pre => Symbols /= No_Symbol_Table,
Post => Initialized (TDH) and then not Has_Source_Buffer (TDH);
-- Create a token data handler that is associated with the ``Symbols``
-- symbol table, and takes its value for the tabulation in the ``Tab_Stop``
-- access.
procedure Reset
(TDH : in out Token_Data_Handler;
Source_Buffer : Text_Access;
Source_First : Positive;
Source_Last : Natural)
with Pre => Initialized (TDH);
-- Free TDH's source buffer, remove all its tokens and associate another
-- source buffer to it. Unlike Free, this does not deallocate the vectors.
--
-- This is equivalent to calling Free and then Initialize on TDH except
-- from the performance point of view: this re-uses allocated resources.
procedure Free (TDH : in out Token_Data_Handler)
with Post => not Initialized (TDH);
-- Free all the resources allocated to TDH. After then, one must call
-- Initialize again in order to use the TDH.
procedure Move (Destination, Source : in out Token_Data_Handler)
with Pre => Initialized (Source) and then not Initialized (Destination),
Post => Initialized (Destination) and then not Initialized (Source);
-- Move data from the Source handler to the Destination one. All data in
-- Destination is overriden, so call Free on it first. Source is reset to
-- null.
function Get_Token
(TDH : Token_Data_Handler;
Index : Token_Index) return Stored_Token_Data;
-- Return data for the token at the given Index in TDH
function Last_Token (TDH : Token_Data_Handler) return Token_Index;
-- Return the index of the last token in TDH
function First_Token_Or_Trivia
(TDH : Token_Data_Handler) return Token_Or_Trivia_Index;
-- Return the first element in the logical sequence of tokens/trivias in
-- TDH.
function Last_Token_Or_Trivia
(TDH : Token_Data_Handler) return Token_Or_Trivia_Index;
-- Return the last element in the logical sequence of tokens/trivias in
-- TDH.
function Next
(Token : Token_Or_Trivia_Index;
TDH : Token_Data_Handler;
Exclude_Trivia : Boolean := False) return Token_Or_Trivia_Index;
-- Return the element that follows Token in the logical sequence of
-- tokens/trivias that TDH holds. If Exclude_Trivia is true, look for
-- tokens only. This just returns No_Token_Or_Trivia_Index if Token is
-- No_Token_Or_Trivia_Index or if it is the last sequence item.
function Previous
(Token : Token_Or_Trivia_Index;
TDH : Token_Data_Handler;
Exclude_Trivia : Boolean := False) return Token_Or_Trivia_Index;
-- Return the element that precedes Token in the logical sequence of
-- tokens/trivias that TDH holds. If Exclude_Trivia is true, look for
-- tokens only. This just returns No_Token_Or_Trivia_Index if Token is
-- No_Token_Or_Trivia_Index or if it is the first sequence item.
function Previous_Token
(Trivia : Token_Index; TDH : Token_Data_Handler) return Token_Index;
-- Given a trivia index in TDH, return the index of the token that precedes
-- it. Return No_Token_Index for a leading trivia.
function Lookup_Token
(TDH : Token_Data_Handler; Sloc : Source_Location)
return Token_Or_Trivia_Index;
-- Look for a token in TDH that contains the given source location.
--
-- We consider here both regular tokens and trivia as "tokens", both making
-- a logically continuous stream of token/trivia.
--
-- If Sloc falls before the first token, return the first token. If this
-- falls between two tokens, return the token that appears before. If this
-- falls after the last token, return the last token. If there is no token
-- in TDH, return No_Token_Or_Trivia_Index.
function Data
(Token : Token_Or_Trivia_Index;
TDH : Token_Data_Handler) return Stored_Token_Data;
-- Return the data associated to Token in TDH
function Get_Trivias
(TDH : Token_Data_Handler;
Index : Token_Index) return Token_Index_Vectors.Elements_Array;
function Get_Leading_Trivias
(TDH : Token_Data_Handler) return Token_Index_Vectors.Elements_Array;
function Text
(TDH : Token_Data_Handler;
T : Stored_Token_Data) return Text_Type
is (TDH.Source_Buffer.all (T.Source_First .. T.Source_Last));
-- Return the text associated to T, a token that belongs to TDH
function Image
(TDH : Token_Data_Handler;
T : Stored_Token_Data) return String
is (Image (Text (TDH, T)));
-- Debug helper: return a human-readable representation of T, a token that
-- belongs to TDH.
function Get_Line
(TDH : Token_Data_Handler; Line_Number : Positive) return Text_Type;
-- Get the source text of line at index ``Line_Number``
function Get_Sloc
(TDH : Token_Data_Handler; Index : Natural) return Source_Location;
-- Return the sloc for given ``Index`` in ``TDH``. If:
--
-- - ``Index`` is ``0``, return ``No_Source_Location``.
--
-- - ``Index`` is in range ``1 .. TDH.Source_Buffer'Last + 1``, return a
-- corresponding sloc (``TDH.Source_Buffer'Last + 1`` being the EOF
-- sloc).
--
-- - ``Index`` is bigger than ``TDH.Source_Buffer'Last + 1``: raise a
-- ``Constraint_Error``.
function Sloc_Start
(TDH : Token_Data_Handler;
Token : Stored_Token_Data) return Source_Location;
-- Get the starting sloc for given ``Token`` in ``TDH``
function Sloc_End
(TDH : Token_Data_Handler;
Token : Stored_Token_Data) return Source_Location;
-- Get the end sloc for given ``Token`` in ``TDH``
function Sloc_Range
(TDH : Token_Data_Handler;
Token : Stored_Token_Data) return Source_Location_Range;
-- Get the sloc range for given ``Token`` in ``TDH``
end Langkit_Support.Token_Data_Handlers;
|
sungyeon/drake | Ada | 1,026 | ads | pragma License (Unrestricted);
-- implementation unit required by compiler
with System.Packed_Arrays;
package System.Pack_48 is
pragma Preelaborate;
-- It can not be Pure, subprograms would become __attribute__((const)).
type Bits_48 is mod 2 ** 48;
for Bits_48'Size use 48;
package Indexing is new Packed_Arrays.Indexing (Bits_48);
-- required for accessing arrays by compiler
function Get_48 (
Arr : Address;
N : Natural;
Rev_SSO : Boolean)
return Bits_48
renames Indexing.Get;
procedure Set_48 (
Arr : Address;
N : Natural;
E : Bits_48;
Rev_SSO : Boolean)
renames Indexing.Set;
-- required for accessing unaligned arrays by compiler
function GetU_48 (
Arr : Address;
N : Natural;
Rev_SSO : Boolean)
return Bits_48
renames Indexing.Get;
procedure SetU_48 (
Arr : Address;
N : Natural;
E : Bits_48;
Rev_SSO : Boolean)
renames Indexing.Set;
end System.Pack_48;
|
jklmnn/esp8266-ada-example | Ada | 394 | adb |
with Componolit.Runtime.Debug;
procedure Main
is
procedure Delay_Ms(Ms : Natural) with
Import,
Convention => C,
External_Name => "delayMicroseconds";
function Message return String;
function Message return String
is
begin
return "Make with Ada!";
end Message;
begin
Componolit.Runtime.Debug.Log_Debug (Message);
Delay_Ms (500000);
end Main;
|
yannickmoy/SPARKNaCl | Ada | 1,764 | ads | with SPARKNaCl.Core; use SPARKNaCl.Core;
package SPARKNaCl.Stream
with Pure,
SPARK_Mode => On
is
-- Distinct from Bytes_32, but both inherit Equal,
-- Random_Bytes, and Sanitize primitive operations.
type HSalsa20_Nonce is new Bytes_24;
type Salsa20_Nonce is new Bytes_8;
--------------------------------------------------------
-- Secret key encryption (not authenticated)
--------------------------------------------------------
procedure HSalsa20 (C : out Byte_Seq; -- Output stream
N : in HSalsa20_Nonce; -- Nonce
K : in Salsa20_Key) -- Key
with Global => null,
Pre => C'First = 0;
procedure HSalsa20_Xor (C : out Byte_Seq; -- Output ciphertext
M : in Byte_Seq; -- Input message
N : in HSalsa20_Nonce; -- Nonce
K : in Salsa20_Key) -- Key
with Global => null,
Pre => M'First = 0 and
C'First = 0 and
C'Last = M'Last;
procedure Salsa20 (C : out Byte_Seq; -- Output stream
N : in Salsa20_Nonce; -- Nonce
K : in Salsa20_Key) -- Key
with Global => null,
Pre => C'First = 0;
procedure Salsa20_Xor (C : out Byte_Seq; -- Output stream
M : in Byte_Seq; -- Input message
N : in Salsa20_Nonce; -- Nonce
K : in Salsa20_Key) -- Key
with Global => null,
Pre => M'First = 0 and
C'First = 0 and
C'Last = M'Last;
end SPARKNaCl.Stream;
|
reznikmm/matreshka | Ada | 9,392 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
-- A component represents a modular part of a system that encapsulates its
-- contents and whose manifestation is replaceable within its environment.
--
-- In the namespace of a component, all model elements that are involved in
-- or related to its definition are either owned or imported explicitly. This
-- may include, for example, use cases and dependencies (e.g. mappings),
-- packages, components, and artifacts.
------------------------------------------------------------------------------
with AMF.UML.Classes;
limited with AMF.UML.Classifiers;
limited with AMF.UML.Component_Realizations.Collections;
limited with AMF.UML.Interfaces.Collections;
limited with AMF.UML.Packageable_Elements.Collections;
package AMF.UML.Components is
pragma Preelaborate;
type UML_Component is limited interface
and AMF.UML.Classes.UML_Class;
type UML_Component_Access is
access all UML_Component'Class;
for UML_Component_Access'Storage_Size use 0;
not overriding function Get_Is_Indirectly_Instantiated
(Self : not null access constant UML_Component)
return Boolean is abstract;
-- Getter of Component::isIndirectlyInstantiated.
--
-- isIndirectlyInstantiated : Boolean {default = true} The kind of
-- instantiation that applies to a Component. If false, the component is
-- instantiated as an addressable object. If true, the Component is
-- defined at design-time, but at run-time (or execution-time) an object
-- specified by the Component does not exist, that is, the component is
-- instantiated indirectly, through the instantiation of its realizing
-- classifiers or parts. Several standard stereotypes use this meta
-- attribute (e.g., «specification», «focus», «subsystem»).
not overriding procedure Set_Is_Indirectly_Instantiated
(Self : not null access UML_Component;
To : Boolean) is abstract;
-- Setter of Component::isIndirectlyInstantiated.
--
-- isIndirectlyInstantiated : Boolean {default = true} The kind of
-- instantiation that applies to a Component. If false, the component is
-- instantiated as an addressable object. If true, the Component is
-- defined at design-time, but at run-time (or execution-time) an object
-- specified by the Component does not exist, that is, the component is
-- instantiated indirectly, through the instantiation of its realizing
-- classifiers or parts. Several standard stereotypes use this meta
-- attribute (e.g., «specification», «focus», «subsystem»).
not overriding function Get_Packaged_Element
(Self : not null access constant UML_Component)
return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is abstract;
-- Getter of Component::packagedElement.
--
-- The set of PackageableElements that a Component owns. In the namespace
-- of a component, all model elements that are involved in or related to
-- its definition may be owned or imported explicitly. These may include
-- e.g. Classes, Interfaces, Components, Packages, Use cases, Dependencies
-- (e.g. mappings), and Artifacts.
not overriding function Get_Provided
(Self : not null access constant UML_Component)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Getter of Component::provided.
--
-- The interfaces that the component exposes to its environment. These
-- interfaces may be Realized by the Component or any of its
-- realizingClassifiers, or they may be the Interfaces that are provided
-- by its public Ports.
not overriding function Get_Realization
(Self : not null access constant UML_Component)
return AMF.UML.Component_Realizations.Collections.Set_Of_UML_Component_Realization is abstract;
-- Getter of Component::realization.
--
-- The set of Realizations owned by the Component. Realizations reference
-- the Classifiers of which the Component is an abstraction; i.e., that
-- realize its behavior.
not overriding function Get_Required
(Self : not null access constant UML_Component)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Getter of Component::required.
--
-- The interfaces that the component requires from other components in its
-- environment in order to be able to offer its full set of provided
-- functionality. These interfaces may be used by the Component or any of
-- its realizingClassifiers, or they may be the Interfaces that are
-- required by its public Ports.
not overriding function Provided
(Self : not null access constant UML_Component)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Operation Component::provided.
--
-- Missing derivation for Component::/provided : Interface
not overriding function Realized_Interfaces
(Self : not null access constant UML_Component;
Classifier : AMF.UML.Classifiers.UML_Classifier_Access)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Operation Component::realizedInterfaces.
--
-- Utility returning the set of realized interfaces of a component.
not overriding function Required
(Self : not null access constant UML_Component)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Operation Component::required.
--
-- Missing derivation for Component::/required : Interface
not overriding function Used_Interfaces
(Self : not null access constant UML_Component;
Classifier : AMF.UML.Classifiers.UML_Classifier_Access)
return AMF.UML.Interfaces.Collections.Set_Of_UML_Interface is abstract;
-- Operation Component::usedInterfaces.
--
-- Utility returning the set of used interfaces of a component.
end AMF.UML.Components;
|
stcarrez/ada-servlet | Ada | 30,571 | adb | -----------------------------------------------------------------------
-- servlet-routes -- Request routing
-- Copyright (C) 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Strings;
with Util.Beans.Objects;
with Util.Log.Loggers;
package body Servlet.Routes is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Servlet.Routes");
-- ------------------------------
-- Get path information after the routing.
-- ------------------------------
function Get_Path (Context : in Route_Context_Type;
Mode : in Path_Mode := FULL) return String is
begin
if Context.Path = null then
return "";
elsif Mode = FULL then
return Context.Path.all;
else
declare
Pos : constant Natural := Get_Path_Pos (Context);
begin
if Mode = PREFIX then
if Pos > Context.Path'Last then
return Context.Path.all;
elsif Pos /= 0 then
return Context.Path (Context.Path'First .. Pos - 1);
else
return "";
end if;
else
if Pos > Context.Path'Last then
return "";
elsif Pos >= Context.Path'First then
return Context.Path (Pos .. Context.Path'Last);
else
return Context.Path.all;
end if;
end if;
end;
end if;
end Get_Path;
-- ------------------------------
-- Get the path parameter value for the given parameter index.
-- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist.
-- ------------------------------
function Get_Parameter (Context : in Route_Context_Type;
Index : in Positive) return String is
begin
if Index > Context.Count then
raise No_Parameter;
else
declare
Param : Route_Param_Type renames Context.Params (Index);
begin
return Context.Path (Param.First .. Param.Last);
end;
end if;
end Get_Parameter;
-- ------------------------------
-- Get the number of path parameters that were extracted for the route.
-- ------------------------------
function Get_Parameter_Count (Context : in Route_Context_Type) return Natural is
begin
return Context.Count;
end Get_Parameter_Count;
-- ------------------------------
-- Return the route associated with the resolved route context.
-- ------------------------------
function Get_Route (Context : in Route_Context_Type) return Route_Type_Accessor is
begin
return Context.Route.Value;
end Get_Route;
function Get_Route (Context : in Route_Context_Type) return Route_Type_Ref is
begin
return Context.Route;
end Get_Route;
-- ------------------------------
-- Return True if there is no route.
-- ------------------------------
function Is_Null (Context : in Route_Context_Type) return Boolean is
begin
return Context.Route.Is_Null;
end Is_Null;
-- ------------------------------
-- Change the context to use a new route.
-- ------------------------------
procedure Change_Route (Context : in out Route_Context_Type;
To : in Route_Type_Ref) is
begin
Context.Route := To;
end Change_Route;
-- ------------------------------
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
-- ------------------------------
function Get_Path_Pos (Context : in Route_Context_Type) return Natural is
begin
if Context.Count = 0 then
return 0;
else
return Context.Params (Context.Count).Route.Get_Path_Pos (Context.Params (Context.Count));
end if;
end Get_Path_Pos;
-- ------------------------------
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
-- ------------------------------
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is
begin
if Context.Count > 0 then
Log.Debug ("Inject route parameters from {0}", Context.Path.all);
for I in 1 .. Context.Count loop
declare
Param : Route_Param_Type renames Context.Params (I);
begin
Param.Route.Inject_Parameter (Context.Path (Param.First .. Param.Last),
Into, ELContext);
end;
end loop;
end if;
end Inject_Parameters;
-- ------------------------------
-- Release the storage held by the route context.
-- ------------------------------
overriding
procedure Finalize (Context : in out Route_Context_Type) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => String, Name => String_Access);
begin
Free (Context.Path);
end Finalize;
-- ------------------------------
-- Insert the route node at the correct place in the children list
-- according to the rule kind.
-- ------------------------------
procedure Insert (Parent : in Route_Node_Access;
Node : in Route_Node_Access;
Kind : in Route_Match_Type) is
Previous, Current : Route_Node_Access;
begin
Current := Parent.Children;
case Kind is
-- Add at head of the list.
when YES_MATCH =>
null;
when MAYBE_MATCH =>
while Current /= null loop
if not (Current.all in Path_Node_Type'Class) then
exit;
end if;
Previous := Current;
Current := Current.Next_Route;
end loop;
-- Add before the
when EXT_MATCH =>
while Current /= null loop
if not (Current.all in Path_Node_Type'Class)
and then not (Current.all in Param_Node_Type'Class)
and then not (Current.all in EL_Node_Type'Class)
then
exit;
end if;
Previous := Current;
Current := Current.Next_Route;
end loop;
when WILDCARD_MATCH =>
while Current /= null loop
Previous := Current;
Current := Current.Next_Route;
end loop;
when others =>
null;
end case;
if Previous /= null then
Node.Next_Route := Previous.Next_Route;
Previous.Next_Route := Node;
else
Node.Next_Route := Parent.Children;
Parent.Children := Node;
end if;
end Insert;
-- ------------------------------
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
-- Once the route path is created, the <tt>Process</tt> procedure is called with the route
-- reference.
-- ------------------------------
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
ELContext : in EL.Contexts.ELContext'Class;
Process : not null access procedure (Route : in out Route_Type_Ref)) is
First : Natural := Pattern'First;
Pos : Natural;
Node : Route_Node_Access := Router.Route.Children;
Match : Route_Match_Type := NO_MATCH;
New_Path : Path_Node_Access;
Parent : Route_Node_Access := Router.Route'Unchecked_Access;
Parent2 : Route_Node_Access;
Found : Boolean;
begin
Log.Info ("Adding route {0}", Pattern);
loop
-- Ignore consecutive '/'.
while First <= Pattern'Last and then Pattern (First) = '/' loop
First := First + 1;
end loop;
-- Find the path component's end.
Pos := Util.Strings.Index (Pattern, '/', First);
if Pos = 0 then
Pos := Pattern'Last;
else
Pos := Pos - 1;
end if;
if First > Pattern'Last then
Found := False;
-- Find an exact match for this component.
while Node /= null loop
if Node.all in Path_Node_Type'Class then
Match := Node.Matches (Pattern (First .. Pos), Pos = Pattern'Last);
if Match = YES_MATCH then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
-- Add a path node matching the component at beginning of the children list.
-- (before the Param_Node and EL_Node instances if any).
if not Found then
New_Path := new Path_Node_Type (Len => 0);
Insert (Parent, New_Path.all'Access, YES_MATCH);
Parent := Parent.Children;
end if;
elsif Pattern (First) = '#' then
declare
E : EL_Node_Access;
begin
Found := False;
-- Find the EL_Node that have the same EL expression.
while Node /= null loop
if Node.all in EL_Node_Type'Class then
E := EL_Node_Type'Class (Node.all)'Access;
if E.Value.Get_Expression = Pattern (First .. Pos) then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
if not Found then
E := new EL_Node_Type;
E.Value := EL.Expressions.Create_Expression (Pattern (First .. Pos), ELContext);
Insert (Parent, E.all'Access, MAYBE_MATCH);
Parent := E.all'Access;
end if;
end;
elsif Pattern (First) = ':' then
declare
Param : Param_Node_Access;
begin
First := First + 1;
Found := False;
-- Find the Param_Node that have the same name.
while Node /= null loop
if Node.all in Param_Node_Type'Class then
Param := Param_Node_Type'Class (Node.all)'Access;
if Param.Name = Pattern (First .. Pos) then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
-- Append the param node for the component.
if not Found then
Param := new Param_Node_Type (Len => Pos - First + 1);
Param.Name := Pattern (First .. Pos);
Insert (Parent, Param.all'Access, MAYBE_MATCH);
Parent := Param.all'Access;
end if;
end;
elsif Pattern (First) = '{'
and then First < Pos - 1
and then Pattern (Pos) = '}'
then
declare
Param : Param_Node_Access;
begin
First := First + 1;
Found := False;
-- Find the Param_Node that have the same name.
while Node /= null loop
if Node.all in Param_Node_Type'Class then
Param := Param_Node_Type'Class (Node.all)'Access;
if Param.Name = Pattern (First .. Pos - 1) then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
-- Append the param node for the component.
if not Found then
Param := new Param_Node_Type (Len => Pos - 1 - First + 1);
Param.Name := Pattern (First .. Pos - 1);
Insert (Parent, Param.all'Access, MAYBE_MATCH);
Parent := Param.all'Access;
end if;
end;
elsif Pattern (First) = '*' and then First = Pattern'Last then
Found := False;
-- Find the Wildcard_Node.
while Node /= null loop
Found := Node.all in Wildcard_Node_Type'Class;
exit when Found;
Node := Node.Next_Route;
end loop;
if not Found then
declare
Wildcard : Wildcard_Node_Access;
begin
Wildcard := new Wildcard_Node_Type;
Node := Wildcard.all'Access;
Insert (Parent, Node, WILDCARD_MATCH);
end;
end if;
Parent2 := Parent;
Parent := Node;
elsif Pattern (First) = '*' and then Pos = Pattern'Last then
declare
Ext : Extension_Node_Access;
begin
First := First + 1;
Found := False;
-- Find the Extension_Node that have the same name.
while Node /= null loop
if Node.all in Extension_Node_Type'Class then
Ext := Extension_Node_Type'Class (Node.all)'Access;
if Ext.Ext = Pattern (First .. Pos) then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
if not Found then
Ext := new Extension_Node_Type (Len => Pos - First + 1);
Ext.Ext := Pattern (First .. Pos);
Insert (Parent, Ext.all'Access, EXT_MATCH);
Parent := Ext.all'Access;
end if;
end;
else
Found := False;
-- Find an exact match for this component.
while Node /= null loop
if Node.all in Path_Node_Type'Class then
Match := Node.Matches (Pattern (First .. Pos), Pos = Pattern'Last);
if Match = YES_MATCH then
Parent := Node;
Node := Node.Children;
Found := True;
exit;
end if;
end if;
Node := Node.Next_Route;
end loop;
-- Add a path node matching the component at beginning of the children list.
-- (before the Param_Node and EL_Node instances if any).
if not Found then
New_Path := new Path_Node_Type (Len => Pos - First + 1);
New_Path.Name := Pattern (First .. Pos);
Insert (Parent, New_Path.all'Access, YES_MATCH);
Parent := Parent.Children;
end if;
end if;
First := Pos + 2;
exit when First > Pattern'Last;
end loop;
Process (Parent.Route);
if Parent2 /= null then
Parent2.Route := Parent.Route;
end if;
end Add_Route;
-- ------------------------------
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
-- ------------------------------
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Accessor)) is
begin
Router.Route.Iterate ("", Process);
end Iterate;
-- ------------------------------
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
-- ------------------------------
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class) is
Match : Route_Match_Type;
begin
Log.Debug ("Finding route for {0}", Path);
Context.Path := new String '(Path);
Router.Route.Find_Match (Context.Path.all, Context.Path'First, Match, Context);
end Find_Route;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class) is
N : Route_Node_Access := Node.Children;
Pos : Natural := First;
Last : Natural;
begin
while Pos <= Path'Last and then Path (Pos) = '/' loop
Pos := Pos + 1;
end loop;
Last := Util.Strings.Index (Path, '/', Pos);
if Last = 0 then
Last := Path'Last;
else
Last := Last - 1;
end if;
while N /= null loop
Match := N.Matches (Path (Pos .. Last), Last = Path'Last);
case Match is
when YES_MATCH =>
if Last = Path'Last then
Context.Route := N.Route;
return;
end if;
N.Find_Match (Path, Last + 2, Match, Context);
if Match = YES_MATCH then
return;
end if;
when MAYBE_MATCH =>
declare
Count : constant Natural := Context.Count + 1;
begin
Context.Count := Count;
Context.Params (Count).Route := N;
Context.Params (Count).First := Pos;
Context.Params (Count).Last := Last;
-- We reached the end of the path and we have a route, this is a match.
if Last = Path'Last and then not N.Route.Is_Null then
Match := YES_MATCH;
Context.Route := N.Route;
return;
end if;
N.Find_Match (Path, Last + 2, Match, Context);
if Match = YES_MATCH then
return;
end if;
Context.Count := Count - 1;
end;
when WILDCARD_MATCH =>
declare
Ext : constant Natural := Util.Strings.Rindex (Path, '/');
Count : Natural;
begin
if Ext = 0 then
Match := N.Matches (Path, True);
else
Match := N.Matches (Path (Ext + 1 .. Path'Last), True);
end if;
if Match in YES_MATCH | WILDCARD_MATCH | EXT_MATCH then
Count := Context.Count + 1;
Context.Count := Count;
Context.Params (Count).Route := N;
Context.Params (Count).First := Pos;
Context.Params (Count).Last := Path'Last;
Context.Route := N.Route;
if Match in EXT_MATCH | WILDCARD_MATCH then
Match := YES_MATCH;
end if;
return;
end if;
end;
when EXT_MATCH =>
if Last = Path'Last then
declare
Count : Natural;
begin
Count := Context.Count + 1;
Context.Count := Context.Count + 1;
Context.Count := Count;
Context.Params (Count).Route := N;
Context.Params (Count).First := Pos;
Context.Params (Count).Last := Path'Last;
Context.Route := N.Route;
Match := YES_MATCH;
return;
end;
end if;
N.Find_Match (Path, Last + 2, Match, Context);
if Match = YES_MATCH then
return;
end if;
when NO_MATCH =>
null;
end case;
N := N.Next_Route;
end loop;
Match := NO_MATCH;
end Find_Match;
-- ------------------------------
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
-- ------------------------------
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Accessor)) is
Child : Route_Node_Access := Node.Children;
begin
if not Node.Route.Is_Null then
Process (Path, Node.Route.Value);
end if;
while Child /= null loop
Child.Iterate (Path & "/" & Child.Get_Pattern, Process);
Child := Child.Next_Route;
end loop;
end Iterate;
-- ------------------------------
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
-- ------------------------------
function Get_Path_Pos (Node : in Route_Node_Type;
Param : in Route_Param_Type) return Natural is
pragma Unreferenced (Node);
begin
return Param.Last + 1;
end Get_Path_Pos;
-- ------------------------------
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
-- ------------------------------
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is
pragma Unreferenced (Is_Last);
begin
if Node.Name = Name then
return YES_MATCH;
else
return NO_MATCH;
end if;
end Matches;
-- ------------------------------
-- Return the component path pattern that this route node represents (ie, 'Name').
-- ------------------------------
overriding
function Get_Pattern (Node : in Path_Node_Type) return String is
begin
return Node.Name;
end Get_Pattern;
-- ------------------------------
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
-- ------------------------------
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is
pragma Unreferenced (Node, Name, Is_Last);
begin
return MAYBE_MATCH;
end Matches;
-- ------------------------------
-- Return the component path pattern that this route node represents (ie, the EL expr).
-- ------------------------------
overriding
function Get_Pattern (Node : in EL_Node_Type) return String is
begin
return Node.Value.Get_Expression;
end Get_Pattern;
-- ------------------------------
-- Inject the parameter that was extracted from the path.
-- ------------------------------
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is
pragma Unreferenced (Into);
begin
Node.Value.Set_Value (Value => Util.Beans.Objects.To_Object (Param),
Context => ELContext);
end Inject_Parameter;
-- ------------------------------
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
-- ------------------------------
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is
pragma Unreferenced (Node, Name, Is_Last);
begin
return MAYBE_MATCH;
end Matches;
-- ------------------------------
-- Return the component path pattern that this route node represents (ie, Name).
-- ------------------------------
overriding
function Get_Pattern (Node : in Param_Node_Type) return String is
begin
return ":" & Node.Name;
end Get_Pattern;
-- ------------------------------
-- Inject the parameter that was extracted from the path.
-- ------------------------------
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is
pragma Unreferenced (ELContext);
begin
Into.Set_Value (Name => Node.Name, Value => Util.Beans.Objects.To_Object (Param));
end Inject_Parameter;
-- ------------------------------
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
-- ------------------------------
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is
Pos : Natural;
begin
if not Is_Last then
return WILDCARD_MATCH;
else
Pos := Util.Strings.Rindex (Name, '.');
if Pos = 0 then
return NO_MATCH;
elsif Name (Pos .. Name'Last) = Node.Ext then
return EXT_MATCH;
else
return NO_MATCH;
end if;
end if;
end Matches;
-- ------------------------------
-- Return the component path pattern that this route node represents (ie, *.Ext).
-- ------------------------------
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String is
begin
return "*" & Node.Ext;
end Get_Pattern;
-- ------------------------------
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
-- ------------------------------
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is
pragma Unreferenced (Node, Name, Is_Last);
begin
return WILDCARD_MATCH;
end Matches;
-- ------------------------------
-- Return the component path pattern that this route node represents (ie, *).
-- ------------------------------
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String is
pragma Unreferenced (Node);
begin
return "*";
end Get_Pattern;
-- ------------------------------
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
-- ------------------------------
overriding
function Get_Path_Pos (Node : in Wildcard_Node_Type;
Param : in Route_Param_Type) return Natural is
pragma Unreferenced (Node);
begin
return Param.First - 1;
end Get_Path_Pos;
-- ------------------------------
-- Release the storage held by the router.
-- ------------------------------
overriding
procedure Finalize (Router : in out Router_Type) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Route_Node_Type'Class,
Name => Route_Node_Access);
procedure Destroy (Node : in out Route_Node_Access);
-- ------------------------------
-- Destroy a node recursively.
-- ------------------------------
procedure Destroy (Node : in out Route_Node_Access) is
Child : Route_Node_Access;
begin
loop
Child := Node.Children;
exit when Child = null;
Node.Children := Child.Next_Route;
Destroy (Child);
end loop;
Free (Node);
end Destroy;
Child : Route_Node_Access;
begin
loop
Child := Router.Route.Children;
exit when Child = null;
Router.Route.Children := Child.Next_Route;
Destroy (Child);
end loop;
end Finalize;
end Servlet.Routes;
|
reznikmm/matreshka | Ada | 3,675 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with XML.DOM.Attributes;
package ODF.DOM.Attributes.Text.Start_Numbering_At is
type ODF_Text_Start_Numbering_At is
new XML.DOM.Attributes.DOM_Attribute with private;
private
type ODF_Text_Start_Numbering_At is
new XML.DOM.Attributes.DOM_Attribute with null record;
end ODF.DOM.Attributes.Text.Start_Numbering_At;
|
optikos/oasis | Ada | 6,945 | adb | -- Copyright (c) 2019 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
package body Program.Nodes.Generic_Procedure_Renaming_Declarations is
function Create
(Generic_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Procedure_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Name : not null Program.Elements.Defining_Names
.Defining_Name_Access;
Renames_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Renamed_Procedure : not null Program.Elements.Expressions
.Expression_Access;
With_Token : Program.Lexical_Elements.Lexical_Element_Access;
Aspects : Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Generic_Procedure_Renaming_Declaration is
begin
return Result : Generic_Procedure_Renaming_Declaration :=
(Generic_Token => Generic_Token, Procedure_Token => Procedure_Token,
Name => Name, Renames_Token => Renames_Token,
Renamed_Procedure => Renamed_Procedure, With_Token => With_Token,
Aspects => Aspects, Semicolon_Token => Semicolon_Token,
Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
function Create
(Name : not null Program.Elements.Defining_Names
.Defining_Name_Access;
Renamed_Procedure : not null Program.Elements.Expressions
.Expression_Access;
Aspects : Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Generic_Procedure_Renaming_Declaration is
begin
return Result : Implicit_Generic_Procedure_Renaming_Declaration :=
(Name => Name, Renamed_Procedure => Renamed_Procedure,
Aspects => Aspects, Is_Part_Of_Implicit => Is_Part_Of_Implicit,
Is_Part_Of_Inherited => Is_Part_Of_Inherited,
Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
overriding function Name
(Self : Base_Generic_Procedure_Renaming_Declaration)
return not null Program.Elements.Defining_Names.Defining_Name_Access is
begin
return Self.Name;
end Name;
overriding function Renamed_Procedure
(Self : Base_Generic_Procedure_Renaming_Declaration)
return not null Program.Elements.Expressions.Expression_Access is
begin
return Self.Renamed_Procedure;
end Renamed_Procedure;
overriding function Aspects
(Self : Base_Generic_Procedure_Renaming_Declaration)
return Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access is
begin
return Self.Aspects;
end Aspects;
overriding function Generic_Token
(Self : Generic_Procedure_Renaming_Declaration)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Generic_Token;
end Generic_Token;
overriding function Procedure_Token
(Self : Generic_Procedure_Renaming_Declaration)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Procedure_Token;
end Procedure_Token;
overriding function Renames_Token
(Self : Generic_Procedure_Renaming_Declaration)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Renames_Token;
end Renames_Token;
overriding function With_Token
(Self : Generic_Procedure_Renaming_Declaration)
return Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.With_Token;
end With_Token;
overriding function Semicolon_Token
(Self : Generic_Procedure_Renaming_Declaration)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Semicolon_Token;
end Semicolon_Token;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Generic_Procedure_Renaming_Declaration)
return Boolean is
begin
return Self.Is_Part_Of_Implicit;
end Is_Part_Of_Implicit;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Generic_Procedure_Renaming_Declaration)
return Boolean is
begin
return Self.Is_Part_Of_Inherited;
end Is_Part_Of_Inherited;
overriding function Is_Part_Of_Instance
(Self : Implicit_Generic_Procedure_Renaming_Declaration)
return Boolean is
begin
return Self.Is_Part_Of_Instance;
end Is_Part_Of_Instance;
procedure Initialize
(Self : aliased in out Base_Generic_Procedure_Renaming_Declaration'Class)
is
begin
Set_Enclosing_Element (Self.Name, Self'Unchecked_Access);
Set_Enclosing_Element (Self.Renamed_Procedure, Self'Unchecked_Access);
for Item in Self.Aspects.Each_Element loop
Set_Enclosing_Element (Item.Element, Self'Unchecked_Access);
end loop;
null;
end Initialize;
overriding function Is_Generic_Procedure_Renaming_Declaration_Element
(Self : Base_Generic_Procedure_Renaming_Declaration)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Generic_Procedure_Renaming_Declaration_Element;
overriding function Is_Declaration_Element
(Self : Base_Generic_Procedure_Renaming_Declaration)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Declaration_Element;
overriding procedure Visit
(Self : not null access Base_Generic_Procedure_Renaming_Declaration;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is
begin
Visitor.Generic_Procedure_Renaming_Declaration (Self);
end Visit;
overriding function To_Generic_Procedure_Renaming_Declaration_Text
(Self : aliased in out Generic_Procedure_Renaming_Declaration)
return Program.Elements.Generic_Procedure_Renaming_Declarations
.Generic_Procedure_Renaming_Declaration_Text_Access is
begin
return Self'Unchecked_Access;
end To_Generic_Procedure_Renaming_Declaration_Text;
overriding function To_Generic_Procedure_Renaming_Declaration_Text
(Self : aliased in out Implicit_Generic_Procedure_Renaming_Declaration)
return Program.Elements.Generic_Procedure_Renaming_Declarations
.Generic_Procedure_Renaming_Declaration_Text_Access is
pragma Unreferenced (Self);
begin
return null;
end To_Generic_Procedure_Renaming_Declaration_Text;
end Program.Nodes.Generic_Procedure_Renaming_Declarations;
|
docandrew/troodon | Ada | 28,989 | adb | with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with GNAT.OS_Lib;
with System; use System;
with Xlib;
with Xlib_xcb;
with xcb; use xcb;
with xproto; use xproto;
with xcb_ewmh; use xcb_ewmh;
-- Just for checking/enabling extensions
with xcb_composite;
with xcb_damage;
with xcb_glx;
with xcb_xfixes;
with xcb_xinerama;
with xcb_randr;
with xcb_render;
with xcb_shape;
with GLX;
with Interfaces;
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with Util; use Util;
package body Setup is
ewmhObj : aliased xcb_ewmh_connection_t;
---------------------------------------------------------------------------
-- initExtensions
-- @TODO we can use the extension's major, minor opcodes, etc. from the
-- filled-in query to come up with a better error-reporting mechanism.
---------------------------------------------------------------------------
procedure initExtensions (c : access xcb_connection_t) is
use xcb_glx;
use xcb_composite;
use xcb_damage;
use xcb_xfixes;
use xcb_xinerama;
use xcb_randr;
use xcb_render;
use xcb_shape;
-- GLX
GLXQuery : access constant xproto.xcb_query_extension_reply_t;
hasGLX : Boolean := False;
GLXVersionQuery : xcb_glx_query_version_cookie_t;
type GLXVersionReplyT is access all xcb_glx_query_version_reply_t;
GLXVersionReply : GLXVersionReplyT;
procedure free is new Ada.Unchecked_Deallocation (Object => xcb_glx_query_version_reply_t,
Name => GLXVersionReplyT);
-- XComposite
XCompositeQuery : access constant xproto.xcb_query_extension_reply_t;
hasXComposite : Boolean := False;
XCompositeVersionQuery : xcb_composite_query_version_cookie_t;
type XCompositeVersionReplyT is access all xcb_composite_query_version_reply_t;
XCompositeVersionReply : XCompositeVersionReplyT;
procedure free is new Ada.Unchecked_Deallocation (Object => xcb_composite_query_version_reply_t,
Name => XCompositeVersionReplyT);
-- XDamage
XDamageQuery : access constant xproto.xcb_query_extension_reply_t;
hasXDamage : Boolean := False;
XDamageVersionQuery : xcb_damage_query_version_cookie_t;
type XDamageVersionReplyT is access all xcb_damage_query_version_reply_t;
XDamageVersionReply : XDamageVersionReplyT;
procedure free is new Ada.Unchecked_Deallocation (Object => xcb_damage_query_version_reply_t,
Name => XDamageVersionReplyT);
-- XFixes
XFixesQuery : access constant xproto.xcb_query_extension_reply_t;
hasXFixes : Boolean := False;
XFixesVersionQuery : xcb_xfixes_query_version_cookie_t;
type XFixesVersionReplyT is access all xcb_xfixes_query_version_reply_t;
XFixesVersionReply : XFixesVersionReplyT;
procedure free is new Ada.Unchecked_Deallocation (Object => xcb_xfixes_query_version_reply_t,
Name => XFixesVersionReplyT);
XineramaQuery : access constant xproto.xcb_query_extension_reply_t;
hasXinerama : Boolean := False;
XineramaVersionQuery : xcb_xinerama_query_version_cookie_t;
XineramaVersionReply : access xcb_xinerama_query_version_reply_t;
XRandrQuery : access constant xproto.xcb_query_extension_reply_t;
hasXRandr : Boolean := False;
XRandrVersionQuery : xcb_randr_query_version_cookie_t;
XRandrVersionReply : access xcb_randr_query_version_reply_t;
XRenderQuery : access constant xproto.xcb_query_extension_reply_t;
hasXRender : Boolean := False;
XRenderVersionQuery : xcb_render_query_version_cookie_t;
XRenderVersionReply : access xcb_render_query_version_reply_t;
XShapeQuery : access constant xproto.xcb_query_extension_reply_t;
hasXShape : Boolean := False;
XShapeVersionQuery : xcb_shape_query_version_cookie_t;
XShapeVersionReply : access xcb_shape_query_version_reply_t;
error : access xcb_generic_error_t;
begin
Ada.Text_IO.Put_Line ("Troodon: checking for required extensions...");
GLXQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_glx.xcb_glx_id'Access);
XCompositeQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_composite.xcb_composite_id'Access);
XDamageQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_damage.xcb_damage_id'Access);
XFixesQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_xfixes.xcb_xfixes_id'Access);
XineramaQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_xinerama.xcb_xinerama_id'Access);
XRandrQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_randr.xcb_randr_id'Access);
XRenderQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_render.xcb_render_id'Access);
XShapeQuery := xcb.xcb_get_extension_data (c => c,
ext => xcb_shape.xcb_shape_id'Access);
if GLXQuery = null or
XCompositeQuery = null or
XDamageQuery = null or
XFixesQuery = null or
XineramaQuery = null or
XRandrQuery = null or
XRenderQuery = null or
XShapeQuery = null then
raise SetupException with "Unable to get extension data from X Server";
end if;
hasGLX := GLXQuery.present /= 0;
hasXComposite := XCompositeQuery.present /= 0;
hasXDamage := XDamageQuery.present /= 0;
hasXFixes := XFixesQuery.present /= 0;
hasXinerama := XineramaQuery.present /= 0;
hasXRandr := XRandrQuery.present /= 0;
hasXRender := XRenderQuery.present /= 0;
hasXShape := XShapeQuery.present /= 0;
if not (hasGLX and hasXComposite and
hasXDamage and hasXFixes and
hasXinerama and hasXRandr and
hasXRender and hasXShape) then
--@TODO for missing extensions, offer helpful hints about how to obtain them or otherwise
raise SetupException with " One or more required extensions is not enabled on the X Server, cannot run Troodon.";
end if;
-----------------------------------------------------------------------
-- Enable required extension versions
-----------------------------------------------------------------------
GLXVersionQuery := xcb_glx_query_version (c => c,
major_version => 1,
minor_version => 4);
GLXVersionReply := xcb_glx_query_version_reply (c => c,
cookie => GLXVersionQuery,
e => error'Address);
if error /= null then
raise SetupException with "Error getting GLX version, " & error.error_code'Image;
end if;
XFixesVersionQuery := xcb_xfixes_query_version (c => c,
client_major_version => 5,
client_minor_version => 0);
XFixesVersionReply := xcb_xfixes_query_version_reply (c => c,
cookie => XFixesVersionQuery,
e => error'Address);
if error /= null then
raise SetupException with "Error getting XFixes version, " & error.error_code'Image
& " response type:" & error.response_type'Image
& " major:" & error.major_code'Image
& " minor:" & error.minor_code'Image
& " resource:" & error.resource_id'Image
& " sequence:" & error.sequence'Image;
end if;
XCompositeVersionQuery := xcb_composite_query_version (c => c,
client_major_version => 0,
client_minor_version => 4);
XCompositeVersionReply := xcb_composite_query_version_reply (c => c,
cookie => XCompositeVersionQuery,
e => error'Address);
if error /= null then
raise SetupException with "Error getting XComposite version, " & error.error_code'Image
& " response type:" & error.response_type'Image
& " major:" & error.major_code'Image
& " minor:" & error.minor_code'Image
& " resource:" & error.resource_id'Image
& " sequence:" & error.sequence'Image;
end if;
XDamageVersionQuery := xcb_damage_query_version (c => c,
client_major_version => 1,
client_minor_version => 1);
XDamageVersionReply := xcb_damage_query_version_reply (c => c,
cookie => XDamageVersionQuery,
e => error'Address);
if error /= null then
raise SetupException with "Error getting XDamage version, " & error.error_code'Image
& " response type:" & error.response_type'Image
& " major:" & error.major_code'Image
& " minor:" & error.minor_code'Image
& " resource:" & error.resource_id'Image
& " sequence:" & error.sequence'Image;
end if;
-- Record Damage event # here.
DAMAGE_EVENT := XDamageQuery.first_event;
Ada.Text_IO.Put_Line ("Troodon: (Setup) Damage event base: " & DAMAGE_EVENT'Image);
Ada.Text_IO.Put_Line (" GLX.......: " & (if hasGLX then "Enabled" else "NOT ENABLED") &
" version" & GLXVersionReply.major_version'Image & "." & GLXVersionReply.minor_version'Image);
Ada.Text_IO.Put_Line (" XComposite: " & (if hasXComposite then "Enabled" else "NOT ENABLED") &
" version" & XCompositeVersionReply.major_version'Image & "." & XCompositeVersionReply.minor_version'Image);
Ada.Text_IO.Put_Line (" XDamage...: " & (if hasXComposite then "Enabled" else "NOT ENABLED") &
" version" & XDamageVersionReply.major_version'Image & "." & XDamageVersionReply.minor_version'Image);
Ada.Text_IO.Put_Line (" XFixes....: " & (if hasXFixes then "Enabled" else "NOT ENABLED") &
" version" & XFixesVersionReply.major_version'Image & "." & XFixesVersionReply.minor_version'Image);
Ada.Text_IO.Put_Line (" Xinerama..: " & (if hasXinerama then "Enabled" else "NOT ENABLED"));
Ada.Text_IO.Put_Line (" XRandr....: " & (if hasXRandr then "Enabled" else "NOT ENABLED"));
Ada.Text_IO.Put_Line (" XRender...: " & (if hasXRender then "Enabled" else "NOT ENABLED"));
Ada.Text_IO.Put_Line (" XShape....: " & (if hasXShape then "Enabled" else "NOT ENABLED"));
free (GLXVersionReply);
free (XCompositeVersionReply);
free (XDamageVersionReply);
free (XFixesVersionReply);
end initExtensions;
---------------------------------------------------------------------------
-- initEwmh
-- Set up the Extended Window Manager Hints connection
-- setup.emwh will be non-null if this succeeds.
---------------------------------------------------------------------------
procedure initEwmh (connection : access xcb_connection_t) is
ewmhCookie : aliased access xcb_intern_atom_cookie_t;
ewmhError : aliased access xcb_generic_error_t;
ignore : Interfaces.C.unsigned_char;
ignore2 : Interfaces.C.int;
begin
ewmhCookie := xcb_ewmh_init_atoms (connection, ewmhObj'Access);
ignore := xcb_ewmh_init_atoms_replies (ewmhObj'Access, ewmhCookie, ewmhError'Address);
if ewmhError /= null then
Ada.Text_IO.Put_Line("Error getting ewmh init atoms, error code:" & ewmhError.error_code'Image);
else
ewmh := ewmhObj'Access;
Ada.Text_IO.Put_Line("Received Extended Window Manager Hints Connection");
Ada.Text_IO.Put_Line("Atom values: ");
Ada.Text_IO.Put_Line("_NET_WM_NAME: " & ewmh.u_NET_WM_NAME'Image);
end if;
--ignore2 := xcb_flush(connection);
end initEwmh;
---------------------------------------------------------------------------
-- initDamage
-- Register for events when window contents change.
---------------------------------------------------------------------------
procedure initDamage (connection : access xcb_connection_t) is
use xcb_damage;
cookie : xcb_void_cookie_t;
error : access xcb_generic_error_t;
begin
Setup.damage := xcb_generate_id (connection);
cookie := xcb_damage.xcb_damage_create_checked (c => connection,
damage => Setup.damage,
drawable => Setup.getRootWindow (connection),
level => xcb_damage_report_level_t'Pos(XCB_DAMAGE_REPORT_LEVEL_NON_EMPTY));
error := xcb_request_check (connection, cookie);
if error /= null then
raise SetupException with "Troodon: (Setup) Unable to create damage request, error:" & error.error_code'Image;
end if;
end initDamage;
---------------------------------------------------------------------------
-- grabMouse
---------------------------------------------------------------------------
-- procedure grabMouse(connection : access xcb_connection_t) is
-- mouseCookie : xcb_void_cookie_t;
-- rootWindow : xcb_window_t := setup.getRootWindow(connection);
-- dummy : Interfaces.C.int;
-- begin
-- Ada.Text_IO.Put_Line("Grabbing mouse inputs for root window:" & rootWindow'Image);
-- -- Snag mouse button bindings
-- -- @TODO may be able to remove this code when we grab events in each frame window
-- -- grab button 1 (left click)
-- mouseCookie :=
-- xcb_grab_button_checked
-- (c => connection,
-- owner_events => 0,
-- grab_window => rootWindow,
-- event_mask => unsigned_short (XCB_EVENT_MASK_BUTTON_PRESS or XCB_EVENT_MASK_BUTTON_RELEASE),
-- pointer_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC),
-- keyboard_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC),
-- confine_to => rootWindow,
-- cursor => XCB_NONE,
-- button => 1,
-- modifiers => unsigned_short (XCB_MOD_MASK_ANY));
-- checkFatal(connection, mouseCookie, "Unable to grab mouse inputs");
-- -- grab button 3 (right click)
-- mouseCookie :=
-- xcb_grab_button_checked
-- (c => connection,
-- owner_events => 0,
-- grab_window => rootWindow,
-- event_mask => unsigned_short (XCB_EVENT_MASK_BUTTON_PRESS or XCB_EVENT_MASK_BUTTON_RELEASE),
-- pointer_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC),
-- keyboard_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC),
-- confine_to => rootWindow,
-- cursor => XCB_NONE,
-- button => 3,
-- modifiers => unsigned_short (XCB_MOD_MASK_ANY));
-- checkFatal(connection, mouseCookie, "Unable to grab mouse inputs (2)");
-- Ada.Text_IO.Put_Line("Grabbed mouse successfully.");
-- end grabMouse;
---------------------------------------------------------------------------
-- grabKeyboard
-- Grab any key in combination with a mod key such as Windows key, alt, etc.
---------------------------------------------------------------------------
procedure grabKeyboard(connection : access xcb_connection_t) is
--keyCookie : xcb_grab_keyboard_cookie_t;
cookie : xcb_void_cookie_t;
error : access xcb_generic_error_t;
-- type KeyReplyPtr is access all xcb_grab_keyboard_reply_t;
-- procedure free is new Ada.Unchecked_Deallocation (Object => xcb_grab_keyboard_reply_t, Name => KeyReplyPtr);
-- keyReply : KeyReplyPtr;
root : xcb_window_t := Setup.getRootWindow (connection);
-- every combination of Super + (caps lock and/or num lock).
modmask : unsigned_short := unsigned_short(XCB_MOD_MASK_4);
modmask2 : unsigned_short := unsigned_short(XCB_MOD_MASK_4 or XCB_MOD_MASK_LOCK);
modmask3 : unsigned_short := unsigned_short(XCB_MOD_MASK_4 or XCB_MOD_MASK_2);
modmask4 : unsigned_short := unsigned_short(XCB_MOD_MASK_4 or XCB_MOD_MASK_LOCK or XCB_MOD_MASK_2);
type ModmaskArr is array (1..4) of unsigned_short;
modmasks : ModmaskArr := (modmask, modmask2, modmask3, modmask4);
begin
Ada.Text_IO.Put_Line("Troodon: (Setup) Grabbing keyboard inputs for root window:" & root'Image);
for mask of modmasks loop
cookie := xcb_grab_key_checked (c => connection,
owner_events => 1,
grab_window => root,
modifiers => mask,
key => xcb_grab_t'Pos(XCB_GRAB_ANY),
pointer_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC),
keyboard_mode => xcb_grab_mode_t'Pos (XCB_GRAB_MODE_ASYNC));
error := xcb_request_check (connection, cookie);
if error /= null then
raise SetupException with "Troodon: (Setup) Unable to grab keyboard inputs, error:" & error.error_code'Image;
end if;
end loop;
-- numlock
-- keyCookie := xcb_grab_keyboard (c => connection,
-- owner_events => 1,
-- grab_window => rootWindow,
-- time => XCB_CURRENT_TIME,
-- pointer_mode => xcb_grab_mode_t'Pos(XCB_GRAB_MODE_ASYNC),
-- keyboard_mode => xcb_grab_mode_t'Pos(XCB_GRAB_MODE_ASYNC));
-- keyReply := keyReplyPtr(xcb_grab_keyboard_reply (c => connection,
-- cookie => keyCookie,
-- e => System.Null_Address));
-- if keyReply /= null then
-- if keyReply.status = xcb_grab_status_t'Pos(XCB_GRAB_STATUS_SUCCESS) then
-- Ada.Text_IO.Put_Line("Grabbed keyboard successfully.");
-- else
-- Ada.Text_IO.Put_Line("Failed to grab keyboard.");
-- end if;
-- free(keyReply);
-- end if;
end grabKeyboard;
---------------------------------------------------------------------------
-- initXlib
-- Connect to X server and get Display
---------------------------------------------------------------------------
function initXlib return access Xlib.Display is
display : access Xlib.Display;
begin
-- For OpenGL rendering to work, we'll need to use Xlib initially.
display := Xlib.XOpenDisplay(Interfaces.C.Strings.Null_Ptr);
if display = null then
Ada.Text_IO.Put_Line("Troodon: Unable to open display");
return null;
end if;
Ada.Text_IO.Put_Line("Troodon: Connected to X Server");
return display;
end initXlib;
---------------------------------------------------------------------------
-- initXcb
-- Take control over the X Server connection and set up event handlers.
-- @return connection if successful, null otherwise
---------------------------------------------------------------------------
function initXcb (display : not null access Xlib.Display) return access xcb_connection_t is
connection : access xcb_connection_t;
screenNumber : aliased int;
screen : access xcb_screen_t;
cookie : xcb_void_cookie_t;
screenIter : aliased xcb_screen_iterator_t;
-- depthIter : aliased xcb_depth_iterator_t;
-- visIter : aliased xcb_visualtype_iterator_t;
-- visualID : xcb_visualid_t;
-- visual : xcb_visualtype_t;
rootAttributes : aliased xcb_change_window_attributes_value_list_t;
numScreens : Natural := 0;
ignore : int;
begin
screenNumber := Xlib.XDefaultScreen(display);
-- Get XCB connection from display. Have to use Xlib here for OpenGL.
connection := Xlib_xcb.XGetXCBConnection(display);
if connection = null then
ignore := Xlib.XCloseDisplay(display);
raise SetupException with "Unable to get XCB connection from Xlib.";
end if;
if xcb_connection_has_error (connection) > 0 then
raise SetupException with "Could not open connection to X Server";
end if;
Ada.Text_IO.Put_Line ("Troodon: Received XCB connection from Xlib");
Ada.Text_IO.Put_Line (" Default screen # =" & screenNumber'Image);
-- Acquire event queue ownership
Xlib_xcb.XSetEventQueueOwner(display, Xlib_xcb.XCBOwnsEventQueue);
-- Get info about screens, have to iterate through them to find ours, if
-- there is more than one screen available.
screenIter := xcb_setup_roots_iterator (xcb_get_setup (connection));
-- Get screens of connection
while screenIter.c_rem >= 0 loop
if screenNumber = 0 then
numScreens := numScreens + 1;
screen := screenIter.data;
exit;
end if;
screenNumber := screenNumber - 1;
numScreens := numScreens + 1;
xcb_screen_next (screenIter'Access);
end loop;
if screen /= null then
Ada.Text_IO.Put_Line ("");
Ada.Text_IO.Put_Line ("Found" & numScreens'Image & " screen(s)");
Ada.Text_IO.Put_Line ("Information about screen" & screenNumber'Image);
Ada.Text_IO.Put_Line (" width...........:" & screen.width_in_pixels'Image);
Ada.Text_IO.Put_Line (" height..........:" & screen.height_in_pixels'Image);
Ada.Text_IO.Put_Line (" white pixel.....:" & screen.white_pixel'Image);
Ada.Text_IO.Put_Line (" black pixel.....:" & screen.black_pixel'Image);
Ada.Text_IO.Put_Line (" Root window ID..:" & screen.root'Image);
Ada.Text_IO.Put_Line (" Root pixel depth:" & screen.root_depth'Image);
Ada.Text_IO.Put_Line (" Visual ID.......:" & screen.root_visual'Image);
-- Get info about visuals
-- This block of code is roughly analogous to XMatchVisualInfo
-- depthIter := xcb_screen_allowed_depths_iterator (screen);
-- Ada.Text_IO.Put_Line (" Found" & xcb_screen_allowed_depths_length (screen)'Image & " depths for this screen");
-- loop
-- visIter := xcb_depth_visuals_iterator (depthIter.data);
-- Ada.Text_IO.Put_Line (" Depth:" & depthIter.data.depth'Image);
-- Ada.Text_IO.Put_Line (" Found" & xcb_depth_visuals_length (depthIter.data)'Image & " visuals for this depth");
-- loop
-- -- Ada.Text_IO.Put_Line (" Visual ID: " & visIter.data.visual_id'Image);
-- -- Ada.Text_IO.Put_Line (" Bits per rgb: " & visIter.data.bits_per_rgb_value'Image);
-- -- Ada.Text_IO.Put_Line (" Colormap Entries:" & visIter.data.colormap_entries'Image);
-- -- If we find a visual that matches our needs, keep it for later and move on
-- if depthIter.data.depth = 24 and visIter.data.bits_per_rgb_value = 8 then
-- visual24 := visIter.data.visual_id;
-- Ada.Text_IO.Put_Line (" using visual ID" & visual24'Image & " for 24-bit depth");
-- exit;
-- elsif depthIter.data.depth = 32 and visIter.data.bits_per_rgb_value = 8 then
-- visual32 := visIter.data.visual_id;
-- Ada.Text_IO.Put_Line (" using visual ID" & visual32'Image & " for 32-bit depth");
-- exit;
-- end if;
-- exit when visIter.c_rem = 0;
-- xcb_visualtype_next (visIter'Access);
-- end loop;
-- exit when depthIter.c_rem = 0;
-- xcb_depth_next (depthIter'Access);
-- end loop;
else
raise SetupException with "No screens found.";
end if;
-- Make sure another window manager isn't running, and register for events
-- which defines Troodon as _the_ window manager.
cookie := xcb_grab_server (connection);
rootAttributes.event_mask := XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY or -- if additional screen plugged in
XCB_EVENT_MASK_SUBSTRUCTURE_REDIRECT or -- resize
XCB_EVENT_MASK_POINTER_MOTION or
XCB_EVENT_MASK_BUTTON_PRESS or
XCB_EVENT_MASK_BUTTON_RELEASE or
XCB_EVENT_MASK_STRUCTURE_NOTIFY;
cookie := xcb_change_window_attributes_aux_checked(c => connection,
window => screen.root,
value_mask => XCB_CW_EVENT_MASK,
value_list => rootAttributes'Access);
checkFatal(connection, cookie, "Cannot start Troodon, another window manager is already running.");
cookie := xcb_ungrab_server (connection);
checkFatal(connection, cookie, "Cannot ungrab server.");
--grabMouse(connection);
grabKeyboard(connection);
return connection;
end initXcb;
---------------------------------------------------------------------------
-- getScreen
-- on multimonitor setups, I think we'll want to specify the screen num here.
---------------------------------------------------------------------------
function getScreen(connection : access xcb_connection_t) return access xcb_screen_t is
begin
return xcb_setup_roots_iterator (xcb_get_setup(connection)).data;
end getScreen;
---------------------------------------------------------------------------
-- getRootWindow
---------------------------------------------------------------------------
function getRootWindow(connection : access xcb_connection_t) return xcb_window_t is
begin
return getScreen(connection).root;
end getRootWindow;
end setup;
|
zhmu/ananas | Ada | 3,895 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . P A C K _ 7 6 --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2022, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Handling of packed arrays with Component_Size = 76
package System.Pack_76 is
pragma Preelaborate;
Bits : constant := 76;
type Bits_76 is mod 2 ** Bits;
for Bits_76'Size use Bits;
-- In all subprograms below, Rev_SSO is set True if the array has the
-- non-default scalar storage order.
function Get_76
(Arr : System.Address;
N : Natural;
Rev_SSO : Boolean) return Bits_76 with Inline;
-- Arr is the address of the packed array, N is the zero-based
-- subscript. This element is extracted and returned.
procedure Set_76
(Arr : System.Address;
N : Natural;
E : Bits_76;
Rev_SSO : Boolean) with Inline;
-- Arr is the address of the packed array, N is the zero-based
-- subscript. This element is set to the given value.
function GetU_76
(Arr : System.Address;
N : Natural;
Rev_SSO : Boolean) return Bits_76 with Inline;
-- Arr is the address of the packed array, N is the zero-based
-- subscript. This element is extracted and returned. This version
-- is used when Arr may represent an unaligned address.
procedure SetU_76
(Arr : System.Address;
N : Natural;
E : Bits_76;
Rev_SSO : Boolean) with Inline;
-- Arr is the address of the packed array, N is the zero-based
-- subscript. This element is set to the given value. This version
-- is used when Arr may represent an unaligned address
end System.Pack_76;
|
docandrew/troodon | Ada | 9,274 | adb | with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with GNAT.OS_Lib;
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with System;
package body util is
---------------------------------------------------------------------------
-- checkFatal
-- Given a connection and the cookie from an xcb request, if the request
-- failed, disconnect from the X Server, print the given error message, and
-- terminate the window server, exiting the program.
-- @TODO make sure Xlib display is closed out
---------------------------------------------------------------------------
procedure checkFatal(connection : access xcb_connection_t;
cookie : xcb_void_cookie_t;
message : String)
is
error : access xcb_generic_error_t := xcb_request_check(connection, cookie);
begin
if error /= null then
Ada.Text_IO.Put_Line("Troodon: " & message & " error code:" & error.error_code'Image);
xcb_disconnect(connection);
GNAT.OS_Lib.OS_Exit(1);
end if;
end checkFatal;
--------------------------------------------------------------------------
-- checkCritical
-- Given a connection and the cookie from an xcb request, if the request
-- failed, return False. Otherwise, return True.
--------------------------------------------------------------------------
-- function checkCritical(connection : access xcb_connection_t;
-- cookie : xcb_void_cookie_t) return Boolean
-- is
-- error : access xcb_generic_error_t := xcb_request_check(connection, cookie);
-- begin
-- return (error /= null);
-- end checkCritical;
---------------------------------------------------------------------------
-- charsToUBS
---------------------------------------------------------------------------
-- function charsToUBS(charPtr : Interfaces.C.Strings.chars_ptr;
-- len : Interfaces.C.unsigned) return Unbounded_String
-- is
-- begin
-- if len <= 0 then
-- return To_Unbounded_String("");
-- else
-- return To_Unbounded_String(Interfaces.C.Strings.Value (charPtr, size_t(len)));
-- end if;
-- end charsToUBS;
function charsToUBS(charPtr : System.Address;
len : Interfaces.C.int) return Unbounded_String
is
chars : Interfaces.C.char_array(1..size_t(len))
with Import, Address => charPtr;
adaStr : String := Interfaces.C.To_Ada(Item => chars, Trim_Nul => False);
begin
--Ada.Text_IO.Put_Line("charsToUBS: addr:" & unsigned(charPtr)'Image);
--Ada.Text_IO.Put_Line(adaStr);
return To_Unbounded_String (adaStr);
end charsToUBS;
---------------------------------------------------------------------------
-- getStringProperty
---------------------------------------------------------------------------
function getStringProperty(connection : access xcb_connection_t;
window : xcb_window_t;
name : xcb_atom_t) return Unbounded_String is
type PropertyReplyPtr is access all xcb_get_property_reply_t;
procedure free is new Ada.Unchecked_Deallocation(Object => xcb_get_property_reply_t, Name => PropertyReplyPtr);
propCookie : xcb_get_property_cookie_t;
reply : access xcb_get_property_reply_t;
len : Interfaces.C.int;
ret : Unbounded_String;
err : access xcb_generic_error_t;
begin
propCookie := xcb_get_property (c => connection,
u_delete => 0,
window => window,
property => name,
c_type => XCB_ATOM_STRING,
long_offset => 0,
long_length => 16#FFFF_FFFF#);
-- Ada.Text_IO.Put_Line("propCookie: " & propCookie.sequence'Image);
reply := xcb_get_property_reply(connection, propCookie, err'Address);
if err /= null then
Ada.Text_IO.Put_Line("Error during get_property: " & err.error_code'Image);
return To_Unbounded_String("");
end if;
if reply /= null and then reply.length > 0 then
-- Ada.Text_IO.Put_Line("Got property" & reply.response_type'Image & " reply length:" & reply.length'Image & " type:" & Integer(reply.c_type)'Image);
-- Ada.Text_IO.Put_Line(" Property Value length: " & xcb_get_property_value_length(reply)'Image & " reply.value_len:" & reply.value_len'Image);
-- Ada.Text_IO.Put_Line("A");
ret := charsToUBS (xcb_get_property_value(reply), xcb_get_property_value_length(reply));
-- Ada.Text_IO.Put_Line("B");
-- Ada.Text_IO.Put_Line(" received: " & To_String(ret));
free(PropertyReplyPtr(reply));
else
-- Ada.Text_IO.Put_Line("Error getting string property");
return To_Unbounded_String("");
end if;
return ret;
end getStringProperty;
---------------------------------------------------------------------------
-- getAtomProperty
---------------------------------------------------------------------------
function getAtomProperty(connection : access xcb_connection_t;
window : xcb_window_t;
name : xcb_atom_t) return xcb_atom_t is
type PropertyReplyPtr is access all xcb_get_property_reply_t;
procedure free is new Ada.Unchecked_Deallocation(Object => xcb_get_property_reply_t, Name => PropertyReplyPtr);
propCookie : xcb_get_property_cookie_t;
reply : access xcb_get_property_reply_t;
len : Interfaces.C.int;
ret : xcb_atom_t;
err : access xcb_generic_error_t;
begin
propCookie := xcb_get_property (c => connection,
u_delete => 0,
window => window,
property => name,
c_type => XCB_ATOM_ATOM,
long_offset => 0,
long_length => 4);
-- Ada.Text_IO.Put_Line("propCookie: " & propCookie.sequence'Image);
reply := xcb_get_property_reply(connection, propCookie, err'Address);
if err /= null then
Ada.Text_IO.Put_Line("Error during getAtomProperty: " & err.error_code'Image);
return XCB_ATOM_NONE;
end if;
if reply /= null and then reply.length > 0 then
declare
atomCopy : xcb_atom_t with Import, Address => xcb_get_property_value(reply);
begin
ret := atomCopy;
end;
free(PropertyReplyPtr(reply));
else
return XCB_ATOM_NONE;
end if;
return ret;
end getAtomProperty;
---------------------------------------------------------------------------
-- getWindowGeometry
-- convenience function for getting a geometry struct
-- @param error - out access xcb_generic_error_t, if necessary for checking
---------------------------------------------------------------------------
function getWindowGeometry(connection : access xcb_connection_t;
window : xcb_window_t;
error : out errorPtr) return xcb_get_geometry_reply_t is
type geomPtr is access all xcb_get_geometry_reply_t;
geom : geomPtr;
-- @TODO consider using the response_type field as a marker if this call was successful or not.
ret : xcb_get_geometry_reply_t := (x => 0,
y => 0,
width => 0,
height => 0,
others => <>);
procedure free is new Ada.Unchecked_Deallocation (Object => xcb_get_geometry_reply_t, Name => geomPtr);
begin
-- consider checking this
-- Ada.Text_IO.Put_Line("getting geometry for" & window'Image);
geom := xcb_get_geometry_reply (connection, xcb_get_geometry (connection, window), error'Address);
ret := xcb_get_geometry_reply_t (geom.all);
free(geom);
return ret;
end getWindowGeometry;
---------------------------------------------------------------------------
-- getWindowGeometry
-- convenience function for getting a geometry struct
---------------------------------------------------------------------------
function getWindowGeometry (connection : access xcb_connection_t;
window : xcb_window_t) return xcb_get_geometry_reply_t is
dummyError : errorPtr;
begin
return getWindowGeometry (connection, window, dummyError);
end getWindowGeometry;
end util; |
charlie5/lace | Ada | 13,264 | adb | with
openGL.Font,
freetype_c.Binding,
freetype_c.FT_GlyphSlot,
freetype_c.Pointers,
freetype_c.FT_Size_Metrics,
ada.unchecked_Deallocation;
package body openGL.FontImpl
is
use freetype_c.Pointers;
-----------
-- Utility
--
procedure deallocate is new ada.unchecked_Deallocation (Glyph.Container.item'Class,
glyph_Container_view);
---------
-- Forge
--
procedure define (Self : access Item; ftFont : access Font.item'Class;
fontFilePath : in String)
is
use freetype.Face,
openGL.Glyph.container,
Freetype_C,
Freetype_C.Binding;
use type FT_Error;
begin
Self.Face := Forge.to_Face (fontFilePath, precomputeKerning => True);
Self.load_Flags := FT_Int (FT_LOAD_DEFAULT_flag);
Self.Intf := ftFont;
Self.Err := Self.face.Error;
if Self.Err = 0
then
Self.glyphList := new Glyph.Container.item' (to_glyph_Container (Self.Face'Access));
else
raise Error with "Unable to create face for font '" & fontFilePath & "'.";
end if;
end define;
procedure define (Self : access Item; ftFont : access Font.item'Class;
pBufferBytes : access C.unsigned_char;
bufferSizeInBytes : in Integer)
is
use freetype.Face,
openGL.Glyph.container,
Freetype_C,
Freetype_c.Binding;
use type FT_Error;
begin
Self.Face := Forge.to_Face (pBufferBytes, bufferSizeInBytes, precomputeKerning => True);
Self.load_Flags := FT_Int (FT_LOAD_DEFAULT_flag);
Self.Intf := ftFont;
Self.Err := Self.face.Error;
if Self.Err = 0
then
Self.glyphList := new Glyph.Container.item' (to_glyph_Container (Self.Face'Access));
end if;
end define;
procedure destruct (Self : in out Item)
is
begin
if Self.glyphList /= null
then
Self.glyphList.destruct;
deallocate (Self.glyphList);
end if;
end destruct;
--------------
-- Attributes
--
function Err (Self : in Item) return freetype_c.FT_Error
is
begin
return Self.Err;
end Err;
function attach (Self : access Item; fontFilePath : in String) return Boolean
is
begin
if not Self.Face.attach (fontFilePath)
then
Self.Err := Self.Face.Error;
return False;
end if;
Self.Err := 0;
return True;
end attach;
function attach (Self : access Item; pBufferBytes : access C.unsigned_char;
bufferSizeInBytes : in Integer) return Boolean
is
begin
if not Self.Face.attach (pBufferBytes, bufferSizeInBytes)
then
Self.Err := Self.Face.Error;
return False;
end if;
Self.Err := 0;
return True;
end attach;
procedure GlyphLoadFlags (Self : in out Item; Flags : in freetype_c.FT_Int)
is
begin
Self.load_Flags := Flags;
end GlyphLoadFlags;
function CharMap (Self : access Item; Encoding : in freetype_c.FT_Encoding) return Boolean
is
Result : constant Boolean := Self.glyphList.CharMap (Encoding);
begin
Self.Err := Self.glyphList.Error;
return Result;
end CharMap;
function CharMapCount (Self : in Item) return Natural
is
begin
return Self.Face.CharMapCount;
end CharMapCount;
function CharMapList (Self : access Item) return freetype.face.FT_Encodings_view
is
begin
return Self.Face.CharMapList;
end CharMapList;
function Ascender (Self : in Item) return Real
is
begin
return Self.charSize.Ascender;
end Ascender;
function Descender (Self : in Item) return Real
is
begin
return Self.charSize.Descender;
end Descender;
function LineHeight (Self : in Item) return Real
is
begin
return Self.charSize.Height;
end LineHeight;
function FaceSize (Self : access Item; Size : in Natural;
x_Res, y_Res : in Natural) return Boolean
is
use Glyph.Container;
use type freetype_c.FT_Error;
begin
if Self.glyphList /= null
then
Self.glyphList.destruct;
deallocate (Self.glyphList);
end if;
Self.charSize := Self.Face.Size (Size, x_Res, y_Res);
Self.Err := Self.Face.Error;
if Self.Err /= 0 then
return False;
end if;
Self.glyphList := new Glyph.Container.item' (to_glyph_Container (Self.Face'unchecked_Access));
return True;
end FaceSize;
function FaceSize (Self : in Item) return Natural
is
begin
return Self.charSize.CharSize;
end FaceSize;
procedure Depth (Self : in out Item; Depth : in Real)
is
begin
null; -- NB: This is 'null' in FTGL also.
end Depth;
procedure Outset (Self : in out Item; Outset : in Real)
is
begin
null; -- NB: This is 'null' in FTGL also.
end Outset;
procedure Outset (Self : in out Item; Front : in Real;
Back : in Real)
is
begin
null; -- NB: This is 'null' in FTGL also.
end Outset;
function CheckGlyph (Self : access Item; Character : in freetype.charmap.CharacterCode) return Boolean
is
use type Glyph.Container.Glyph_view,
freetype_c.FT_Error;
glyphIndex : freetype.charMap.glyphIndex;
ftSlot : freetype_c.FT_GlyphSlot.item;
tempGlyph : glyph.Container.Glyph_view;
begin
if Self.glyphList.Glyph (Character) /= null
then
return True;
end if;
glyphIndex := freetype.charMap.glyphIndex (Self.glyphList.FontIndex (Character));
ftSlot := Self.Face.Glyph (glyphIndex, Self.load_flags);
if ftSlot = null
then
Self.Err := Self.Face.Error;
return False;
end if;
if Self.Intf = null
then
raise Error with "CheckGlyph ~ Self.Intf = null";
end if;
tempGlyph := Self.Intf.MakeGlyph (ftSlot);
if tempGlyph = null
then
if Self.Err = 0 then
Self.Err := 16#13#;
end if;
return False;
end if;
if Self.glyphList.Glyph (character) = null
then
Self.glyphList.add (tempGlyph, Character);
end if;
return True;
end CheckGlyph;
function BBox (Self : access Item; Text : in String;
Length : in Integer;
Position : in Vector_3;
Spacing : in Vector_3) return Bounds
is
pragma unreferenced (Length);
use freetype.charMap,
Geometry_3d;
Pos : Vector_3 := Position;
totalBBox : Bounds := null_Bounds;
begin
if Text = ""
then
totalBBox.Box := totalBBox.Box or Pos;
set_Ball_from_Box (totalBBox);
return totalBBox;
end if;
-- Only compute the bounds if string is non-empty.
--
if Text'Length > 0 -- TODO: Rid this useless check.
then
-- For multibyte, we can't rely on sizeof (T) == character
--
declare
use type freetype.charMap.characterCode;
thisChar : Character;
nextChar : Character;
begin
-- Expand totalBox by each glyph in string
--
for i in Text'Range
loop
thisChar := Text (i);
if i /= Text'Last
then nextChar := Text (i + 1);
else nextChar := ' ';
end if;
if Self.CheckGlyph (to_characterCode (thisChar))
then
declare
tempBBox : Bounds := Self.glyphList.BBox (to_characterCode (thisChar));
begin
tempBBox.Box := tempBBox.Box + Pos;
totalBBox.Box := totalBBox.Box or tempBBox.Box;
Pos := Pos + spacing;
Pos := Pos + Vector_3' (Self.glyphList.Advance (to_characterCode (thisChar),
to_characterCode (nextChar)),
0.0,
0.0);
end;
end if;
end loop;
end;
end if;
set_Ball_from_Box (totalBBox);
return totalBBox;
end BBox;
function kern_Advance (Self : in Item; From, To : in Character) return Real
is
use freetype.charMap;
begin
return Self.glyphList.Advance (to_characterCode (From),
to_characterCode (To));
end kern_Advance;
function x_PPEM (Self : in Item) return Real
is
use freetype_c.Binding;
ft_Size : constant FT_SizeRec_Pointer := FT_Face_Get_Size (Self.Face.freetype_Face);
ft_Metrics : constant freetype_c.FT_Size_Metrics.item := FT_Size_Get_Metrics (ft_Size);
begin
return Real (ft_Metrics.x_PPEM);
end x_PPEM;
function x_Scale (Self : in Item) return Real
is
use freetype_c.Binding;
ft_Size : constant FT_SizeRec_Pointer := FT_Face_Get_Size (Self.Face.freetype_Face);
ft_Metrics : constant freetype_c.FT_Size_Metrics.item := FT_Size_Get_Metrics (ft_Size);
begin
return Real (ft_Metrics.x_Scale);
end x_Scale;
function y_Scale (Self : in Item) return Real
is
use freetype_c.Binding;
ft_Size : constant FT_SizeRec_Pointer := FT_Face_Get_Size (Self.Face.freetype_Face);
ft_Metrics : constant freetype_c.FT_Size_Metrics.item := FT_Size_Get_Metrics (ft_Size);
begin
return Real (ft_Metrics.y_Scale);
end y_Scale;
function Advance (Self : access Item; Text : in String;
Length : in Integer;
Spacing : in Vector_3) return Real
is
pragma unreferenced (Length);
Advance : Real := 0.0;
ustr : Integer := 1;
i : Integer := 0;
begin
while i < Text'Length
loop
declare
use freetype.charMap;
use type freetype.charmap.characterCode;
thisChar : constant Character := Text (ustr);
nextChar : Character;
begin
ustr := ustr + 1;
if ustr <= Text'Length
then nextChar := Text (ustr);
else nextChar := Character'Val (0);
end if;
if nextChar /= Character'Val (0)
and then Self.CheckGlyph (to_characterCode (thisChar))
then
Advance := Advance + Self.glyphList.Advance (to_characterCode (thisChar),
to_characterCode (nextChar));
end if;
if nextChar /= Character'Val (0)
then
Advance := Advance + Spacing (1);
end if;
i := i + 1;
end;
end loop;
return advance;
end Advance;
--------------
--- Operations
--
function render (Self : access Item; Text : in String;
Length : in Integer;
Position : in Vector_3;
Spacing : in Vector_3;
renderMode : in Integer) return Vector_3
is
use type freetype.charMap.characterCode;
ustr : Integer := 1;
i : Integer := 0;
Pos : Vector_3 := Position;
begin
while (Length < 0 and then i < Text'Length)
or else (Length >= 0 and then i < Length)
loop
declare
use freetype.charMap;
thisChar : constant Character := Text (ustr);
nextChar : Character;
begin
ustr := ustr + 1;
if ustr <= Text'Length
then nextChar := Text (ustr);
else nextChar := Character'Val (0);
end if;
if nextChar /= Character'Val (0)
and then Self.CheckGlyph (to_characterCode (thisChar))
then
Pos := Pos + Self.glyphList.render (to_characterCode (thisChar),
to_characterCode (nextChar),
Position,
renderMode);
end if;
if nextChar /= Character'Val (0)
then
Pos := Pos + Spacing;
end if;
i := i + 1;
end;
end loop;
return Pos;
end Render;
end openGL.FontImpl;
|
sebsgit/textproc | Ada | 1,909 | adb | with Ada.Text_IO;
package body NNClassifier is
function create(config: NeuralNet.Config; numberOfClasses: Positive) return DNN is
result: DNN(config.size + 1);
configWithLogits: NeuralNet.Config(config.size + 1);
begin
configWithLogits.act := config.act;
configWithLogits.lr := config.lr;
configWithLogits.inputSize := config.inputSize;
configWithLogits.gradientClipAbs := config.gradientClipAbs;
for i in 1 .. config.size loop
configWithLogits.sizes(i) := config.sizes(i);
end loop;
configWithLogits.sizes(configWithLogits.sizes'Length) := numberOfClasses;
result.labelCount := numberOfClasses;
result.nn := NeuralNet.create(configWithLogits);
return result;
end create;
function oneHotEncode(label: Natural; labelCount: Positive) return MathUtils.Vector
with Pre => label < labelCount
is
result: MathUtils.Vector;
begin
result.Set_Length(Ada.Containers.Count_Type(labelCount));
for x of result loop
x := 0.0;
end loop;
result(label + 1) := 1.0;
return result;
end oneHotEncode;
procedure print(nn: in DNN) is
begin
nn.nn.print;
end print;
procedure train(nn: in out DNN; data: in DataBatch.Batch; labels: in LabelVector) is
li: Positive;
target: MathUtils.Vector;
begin
li := labels.First_Index;
for vec of data.data loop
target := oneHotEncode(labels(li), nn.labelCount);
nn.nn.train(input => vec,
target => target);
li := li + 1;
end loop;
end train;
function classify(nn: in out DNN; vec: MathUtils.Vector) return MathUtils.Vector is
result: MathUtils.Vector;
begin
result := nn.nn.forward(vec);
MathUtils.multiply(result, 10.0);
MathUtils.softmax(result);
return result;
end classify;
end NNClassifier;
|
michael-hardeman/contacts_app | Ada | 84,782 | adb | -- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with Ada.Exceptions;
with Ada.Calendar.Time_Zones;
with Ada.Unchecked_Conversion;
package body AdaBase.Statement.Base.MySQL is
package EX renames Ada.Exceptions;
package CTZ renames Ada.Calendar.Time_Zones;
--------------------
-- discard_rest --
--------------------
overriding
procedure discard_rest (Stmt : out MySQL_statement)
is
use type ABM.MYSQL_RES_Access;
use type ABM.MYSQL_STMT_Access;
begin
case Stmt.type_of_statement is
when direct_statement =>
if Stmt.result_handle /= null then
Stmt.rows_leftover := True;
Stmt.mysql_conn.free_result (Stmt.result_handle);
Stmt.clear_column_information;
end if;
when prepared_statement =>
if Stmt.stmt_handle /= null then
Stmt.rows_leftover := True;
Stmt.mysql_conn.prep_free_result (Stmt.stmt_handle);
end if;
end case;
Stmt.delivery := completed;
end discard_rest;
--------------------
-- column_count --
--------------------
overriding
function column_count (Stmt : MySQL_statement) return Natural is
begin
return Stmt.num_columns;
end column_count;
---------------------------
-- last_driver_message --
---------------------------
overriding
function last_driver_message (Stmt : MySQL_statement) return String is
begin
case Stmt.type_of_statement is
when direct_statement =>
return Stmt.mysql_conn.driverMessage;
when prepared_statement =>
return Stmt.mysql_conn.prep_DriverMessage
(Stmt.stmt_handle);
end case;
end last_driver_message;
----------------------
-- last_insert_id --
----------------------
overriding
function last_insert_id (Stmt : MySQL_statement) return Trax_ID is
begin
case Stmt.type_of_statement is
when direct_statement =>
return Stmt.mysql_conn.lastInsertID;
when prepared_statement =>
return Stmt.mysql_conn.prep_LastInsertID
(Stmt.stmt_handle);
end case;
end last_insert_id;
----------------------
-- last_sql_state --
----------------------
overriding
function last_sql_state (Stmt : MySQL_statement) return SQL_State is
begin
case Stmt.type_of_statement is
when direct_statement =>
return Stmt.mysql_conn.SqlState;
when prepared_statement =>
return Stmt.mysql_conn.prep_SqlState
(Stmt.stmt_handle);
end case;
end last_sql_state;
------------------------
-- last_driver_code --
------------------------
overriding
function last_driver_code (Stmt : MySQL_statement) return Driver_Codes is
begin
case Stmt.type_of_statement is
when direct_statement =>
return Stmt.mysql_conn.driverCode;
when prepared_statement =>
return Stmt.mysql_conn.prep_DriverCode
(Stmt.stmt_handle);
end case;
end last_driver_code;
----------------------------
-- execute (version 1) --
----------------------------
overriding
function execute (Stmt : out MySQL_statement) return Boolean
is
num_markers : constant Natural := Natural (Stmt.realmccoy.Length);
status_successful : Boolean := True;
begin
if Stmt.type_of_statement = direct_statement then
raise INVALID_FOR_DIRECT_QUERY
with "The execute command is for prepared statements only";
end if;
Stmt.successful_execution := False;
Stmt.rows_leftover := False;
if num_markers > 0 then
-- Check to make sure all prepared markers are bound
for sx in Natural range 1 .. num_markers loop
if not Stmt.realmccoy.Element (sx).bound then
raise STMT_PREPARATION
with "Prep Stmt column" & sx'Img & " unbound";
end if;
end loop;
declare
slots : ABM.MYSQL_BIND_Array (1 .. num_markers);
vault : mysql_canvases (1 .. num_markers);
begin
for sx in slots'Range loop
Stmt.construct_bind_slot (struct => slots (sx),
canvas => vault (sx),
marker => sx);
end loop;
if not Stmt.mysql_conn.prep_bind_parameters
(Stmt.stmt_handle, slots)
then
Stmt.log_problem (category => statement_preparation,
message => "failed to bind parameters",
pull_codes => True);
status_successful := False;
end if;
if status_successful then
Stmt.log_nominal (category => statement_execution,
message => "Exec with" & num_markers'Img &
" bound parameters");
if Stmt.mysql_conn.prep_execute (Stmt.stmt_handle) then
Stmt.successful_execution := True;
else
Stmt.log_problem (category => statement_execution,
message => "failed to exec prep stmt",
pull_codes => True);
status_successful := False;
end if;
end if;
-- Recover dynamically allocated data
for sx in slots'Range loop
free_binary (vault (sx).buffer_binary);
end loop;
end;
else
-- No binding required, just execute the prepared statement
Stmt.log_nominal (category => statement_execution,
message => "Exec without bound parameters");
if Stmt.mysql_conn.prep_execute (Stmt.stmt_handle) then
Stmt.successful_execution := True;
else
Stmt.log_problem (category => statement_execution,
message => "failed to exec prep stmt",
pull_codes => True);
status_successful := False;
end if;
end if;
Stmt.internal_post_prep_stmt;
return status_successful;
end execute;
----------------------------
-- execute (version 2) --
----------------------------
overriding
function execute (Stmt : out MySQL_statement; parameters : String;
delimiter : Character := '|') return Boolean
is
function parameters_given return Natural;
num_markers : constant Natural := Natural (Stmt.realmccoy.Length);
function parameters_given return Natural
is
result : Natural := 1;
begin
for x in parameters'Range loop
if parameters (x) = delimiter then
result := result + 1;
end if;
end loop;
return result;
end parameters_given;
begin
if Stmt.type_of_statement = direct_statement then
raise INVALID_FOR_DIRECT_QUERY
with "The execute command is for prepared statements only";
end if;
if num_markers /= parameters_given then
raise STMT_PREPARATION
with "Parameter number mismatch, " & num_markers'Img &
" expected, but" & parameters_given'Img & " provided.";
end if;
declare
index : Natural := 1;
arrow : Natural := parameters'First;
scans : Boolean := False;
start : Natural := 1;
stop : Natural := 0;
begin
for x in parameters'Range loop
if parameters (x) = delimiter then
if not scans then
Stmt.auto_assign (index, "");
else
Stmt.auto_assign (index, parameters (start .. stop));
scans := False;
end if;
index := index + 1;
else
stop := x;
if not scans then
start := x;
scans := True;
end if;
end if;
end loop;
if not scans then
Stmt.auto_assign (index, "");
else
Stmt.auto_assign (index, parameters (start .. stop));
end if;
end;
return Stmt.execute;
end execute;
------------------
-- initialize --
------------------
overriding
procedure initialize (Object : in out MySQL_statement)
is
use type ACM.MySQL_Connection_Access;
begin
if Object.mysql_conn = null then
return;
end if;
logger_access := Object.log_handler;
Object.dialect := driver_mysql;
Object.connection := ACB.Base_Connection_Access (Object.mysql_conn);
case Object.type_of_statement is
when direct_statement =>
Object.sql_final := new String'(CT.trim_sql
(Object.initial_sql.all));
Object.internal_direct_post_exec;
when prepared_statement =>
declare
use type ABM.MYSQL_RES_Access;
begin
Object.sql_final := new String'(Object.transform_sql
(Object.initial_sql.all));
Object.mysql_conn.initialize_and_prepare_statement
(stmt => Object.stmt_handle, sql => Object.sql_final.all);
declare
params : Natural := Object.mysql_conn.prep_markers_found
(stmt => Object.stmt_handle);
errmsg : String := "marker mismatch," &
Object.realmccoy.Length'Img & " expected but" &
params'Img & " found by MySQL";
begin
if params /= Natural (Object.realmccoy.Length) then
raise ILLEGAL_BIND_SQL with errmsg;
end if;
Object.log_nominal (category => statement_preparation,
message => Object.sql_final.all);
end;
Object.result_handle := Object.mysql_conn.prep_result_metadata
(Object.stmt_handle);
-- Direct statements always produce result sets, but prepared
-- statements very well may not. The next procedure ends early
-- after clearing column data if there is results.
Object.scan_column_information;
if Object.result_handle /= null then
Object.mysql_conn.free_result (Object.result_handle);
end if;
exception
when HELL : others =>
Object.log_problem (category => statement_preparation,
message => EX.Exception_Message (HELL));
raise;
end;
end case;
end initialize;
--------------
-- Adjust --
--------------
overriding
procedure Adjust (Object : in out MySQL_statement) is
begin
-- The stmt object goes through this evolution:
-- A) created in private_prepare()
-- B) copied to new object in prepare(), A) destroyed
-- C) copied to new object in program, B) destroyed
-- We don't want to take any action until C) is destroyed, so add a
-- reference counter upon each assignment. When finalize sees a
-- value of "2", it knows it is the program-level statement and then
-- it can release memory releases, but not before!
Object.assign_counter := Object.assign_counter + 1;
-- Since the finalization is looking for a specific reference
-- counter, any further assignments would fail finalization, so
-- just prohibit them outright.
if Object.assign_counter > 2 then
raise STMT_PREPARATION
with "Statement objects cannot be re-assigned.";
end if;
end Adjust;
----------------
-- finalize --
----------------
overriding
procedure finalize (Object : in out MySQL_statement) is
begin
if Object.assign_counter /= 2 then
return;
end if;
if Object.type_of_statement = prepared_statement then
if not Object.mysql_conn.prep_close_statement (Object.stmt_handle)
then
Object.log_problem (category => statement_preparation,
message => "Deallocating statement memory",
pull_codes => True);
end if;
end if;
free_sql (Object.sql_final);
Object.reclaim_canvas;
end finalize;
---------------------
-- direct_result --
---------------------
procedure process_direct_result (Stmt : out MySQL_statement)
is
use type ABM.MYSQL_RES_Access;
begin
case Stmt.con_buffered is
when True => Stmt.mysql_conn.store_result
(result_handle => Stmt.result_handle);
when False => Stmt.mysql_conn.use_result
(result_handle => Stmt.result_handle);
end case;
Stmt.result_present := (Stmt.result_handle /= null);
end process_direct_result;
---------------------
-- rows_returned --
---------------------
overriding
function rows_returned (Stmt : MySQL_statement) return Affected_Rows is
begin
if not Stmt.successful_execution then
raise PRIOR_EXECUTION_FAILED
with "Has query been executed yet?";
end if;
if Stmt.result_present then
if Stmt.con_buffered then
return Stmt.size_of_rowset;
else
raise INVALID_FOR_RESULT_SET
with "Row set size is not known (Use query buffers to fix)";
end if;
else
raise INVALID_FOR_RESULT_SET
with "Result set not found; use rows_affected";
end if;
end rows_returned;
----------------------
-- reclaim_canvas --
----------------------
procedure reclaim_canvas (Stmt : out MySQL_statement)
is
use type ABM.ICS.char_array_access;
begin
if Stmt.bind_canvas /= null then
for sx in Stmt.bind_canvas.all'Range loop
if Stmt.bind_canvas (sx).buffer_binary /= null then
free_binary (Stmt.bind_canvas (sx).buffer_binary);
end if;
end loop;
free_canvas (Stmt.bind_canvas);
end if;
end reclaim_canvas;
--------------------------------
-- clear_column_information --
--------------------------------
procedure clear_column_information (Stmt : out MySQL_statement) is
begin
Stmt.num_columns := 0;
Stmt.column_info.Clear;
Stmt.crate.Clear;
Stmt.headings_map.Clear;
Stmt.reclaim_canvas;
end clear_column_information;
-------------------------------
-- scan_column_information --
-------------------------------
procedure scan_column_information (Stmt : out MySQL_statement)
is
use type ABM.MYSQL_FIELD_Access;
use type ABM.MYSQL_RES_Access;
field : ABM.MYSQL_FIELD_Access;
function fn (raw : String) return CT.Text;
function sn (raw : String) return String;
function fn (raw : String) return CT.Text is
begin
case Stmt.con_case_mode is
when upper_case =>
return CT.SUS (ACH.To_Upper (raw));
when lower_case =>
return CT.SUS (ACH.To_Lower (raw));
when natural_case =>
return CT.SUS (raw);
end case;
end fn;
function sn (raw : String) return String is
begin
case Stmt.con_case_mode is
when upper_case =>
return ACH.To_Upper (raw);
when lower_case =>
return ACH.To_Lower (raw);
when natural_case =>
return raw;
end case;
end sn;
begin
Stmt.clear_column_information;
if Stmt.result_handle = null then
return;
end if;
Stmt.num_columns := Stmt.mysql_conn.fields_in_result
(Stmt.result_handle);
loop
field := Stmt.mysql_conn.fetch_field
(result_handle => Stmt.result_handle);
exit when field = null;
declare
info : column_info;
brec : bindrec;
begin
brec.v00 := False; -- placeholder
info.field_name := fn (Stmt.mysql_conn.field_name_field (field));
info.table := fn (Stmt.mysql_conn.field_name_table (field));
info.mysql_type := field.field_type;
info.null_possible := Stmt.mysql_conn.field_allows_null (field);
Stmt.mysql_conn.field_data_type (field => field,
std_type => info.field_type,
size => info.field_size);
if info.field_size > Stmt.con_max_blob then
info.field_size := Stmt.con_max_blob;
end if;
Stmt.column_info.Append (New_Item => info);
-- The following pre-populates for bind support
Stmt.crate.Append (New_Item => brec);
Stmt.headings_map.Insert
(Key => sn (Stmt.mysql_conn.field_name_field (field)),
New_Item => Stmt.crate.Last_Index);
end;
end loop;
end scan_column_information;
-------------------
-- column_name --
-------------------
overriding
function column_name (Stmt : MySQL_statement; index : Positive)
return String
is
maxlen : constant Natural := Natural (Stmt.column_info.Length);
begin
if index > maxlen then
raise INVALID_COLUMN_INDEX with "Max index is" & maxlen'Img &
" but" & index'Img & " attempted";
end if;
return CT.USS (Stmt.column_info.Element (Index => index).field_name);
end column_name;
--------------------
-- column_table --
--------------------
overriding
function column_table (Stmt : MySQL_statement; index : Positive)
return String
is
maxlen : constant Natural := Natural (Stmt.column_info.Length);
begin
if index > maxlen then
raise INVALID_COLUMN_INDEX with "Max index is" & maxlen'Img &
" but" & index'Img & " attempted";
end if;
return CT.USS (Stmt.column_info.Element (Index => index).table);
end column_table;
--------------------------
-- column_native_type --
--------------------------
overriding
function column_native_type (Stmt : MySQL_statement; index : Positive)
return field_types
is
maxlen : constant Natural := Natural (Stmt.column_info.Length);
begin
if index > maxlen then
raise INVALID_COLUMN_INDEX with "Max index is" & maxlen'Img &
" but" & index'Img & " attempted";
end if;
return Stmt.column_info.Element (Index => index).field_type;
end column_native_type;
------------------
-- fetch_next --
------------------
overriding
function fetch_next (Stmt : out MySQL_statement) return ARS.Datarow is
begin
if Stmt.delivery = completed then
return ARS.Empty_Datarow;
end if;
case Stmt.type_of_statement is
when prepared_statement =>
return Stmt.internal_ps_fetch_row;
when direct_statement =>
return Stmt.internal_fetch_row;
end case;
end fetch_next;
-------------------
-- fetch_bound --
-------------------
overriding
function fetch_bound (Stmt : out MySQL_statement) return Boolean is
begin
if Stmt.delivery = completed then
return False;
end if;
case Stmt.type_of_statement is
when prepared_statement =>
return Stmt.internal_ps_fetch_bound;
when direct_statement =>
return Stmt.internal_fetch_bound;
end case;
end fetch_bound;
-----------------
-- fetch_all --
-----------------
overriding
function fetch_all (Stmt : out MySQL_statement) return ARS.Datarow_Set
is
maxrows : Natural := Natural (Stmt.rows_returned);
tmpset : ARS.Datarow_Set (1 .. maxrows + 1);
nullset : ARS.Datarow_Set (1 .. 0);
index : Natural := 1;
row : ARS.Datarow;
begin
if (Stmt.delivery = completed) or else (maxrows = 0) then
return nullset;
end if;
-- It is possible that one or more rows was individually fetched
-- before the entire set was fetched. Let's consider this legal so
-- use a repeat loop to check each row and return a partial set
-- if necessary.
loop
tmpset (index) := Stmt.fetch_next;
exit when tmpset (index).data_exhausted;
index := index + 1;
exit when index > maxrows + 1; -- should never happen
end loop;
if index = 1 then
return nullset; -- nothing was fetched
end if;
return tmpset (1 .. index - 1);
end fetch_all;
----------------------
-- fetch_next_set --
----------------------
overriding
procedure fetch_next_set (Stmt : out MySQL_statement;
data_present : out Boolean;
data_fetched : out Boolean)
is
use type ABM.MYSQL_RES_Access;
begin
data_fetched := False;
if Stmt.result_handle /= null then
Stmt.mysql_conn.free_result (Stmt.result_handle);
end if;
data_present := Stmt.mysql_conn.fetch_next_set;
if not data_present then
return;
end if;
declare
begin
Stmt.process_direct_result;
exception
when others =>
Stmt.log_nominal (category => statement_execution,
message => "Result set missing from: "
& Stmt.sql_final.all);
return;
end;
Stmt.internal_direct_post_exec (newset => True);
data_fetched := True;
end fetch_next_set;
--------------------------
-- internal_fetch_row --
--------------------------
function internal_fetch_row (Stmt : out MySQL_statement)
return ARS.Datarow
is
use type ABM.ICS.chars_ptr;
use type ABM.MYSQL_ROW_access;
rptr : ABM.MYSQL_ROW_access :=
Stmt.mysql_conn.fetch_row (Stmt.result_handle);
begin
if rptr = null then
Stmt.delivery := completed;
Stmt.mysql_conn.free_result (Stmt.result_handle);
Stmt.clear_column_information;
return ARS.Empty_Datarow;
end if;
Stmt.delivery := progressing;
declare
maxlen : constant Natural := Natural (Stmt.column_info.Length);
bufmax : constant ABM.IC.size_t := ABM.IC.size_t (Stmt.con_max_blob);
subtype data_buffer is ABM.IC.char_array (1 .. bufmax);
type db_access is access all data_buffer;
type rowtype is array (1 .. maxlen) of db_access;
type rowtype_access is access all rowtype;
row : rowtype_access;
result : ARS.Datarow;
field_lengths : constant ACM.fldlen := Stmt.mysql_conn.fetch_lengths
(result_handle => Stmt.result_handle,
num_columns => maxlen);
function convert is new Ada.Unchecked_Conversion
(Source => ABM.MYSQL_ROW_access, Target => rowtype_access);
function db_convert (dba : db_access; size : Natural) return String;
function db_convert (dba : db_access; size : Natural) return String
is
max : Natural := size;
begin
if max > Stmt.con_max_blob then
max := Stmt.con_max_blob;
end if;
declare
result : String (1 .. max);
begin
for x in result'Range loop
result (x) := Character (dba.all (ABM.IC.size_t (x)));
end loop;
return result;
end;
end db_convert;
begin
row := convert (rptr);
for F in 1 .. maxlen loop
declare
colinfo : column_info renames Stmt.column_info.Element (F);
field : ARF.Std_Field;
last_one : constant Boolean := (F = maxlen);
heading : constant String := CT.USS (colinfo.field_name);
isnull : constant Boolean := (row (F) = null);
sz : constant Natural := field_lengths (F);
ST : constant String := db_convert (row (F), sz);
dvariant : ARF.Variant;
begin
if isnull then
field := ARF.spawn_null_field (colinfo.field_type);
else
case colinfo.field_type is
when ft_nbyte0 =>
dvariant := (datatype => ft_nbyte0, v00 => ST = "1");
when ft_nbyte1 =>
dvariant := (datatype => ft_nbyte1, v01 => convert (ST));
when ft_nbyte2 =>
dvariant := (datatype => ft_nbyte2, v02 => convert (ST));
when ft_nbyte3 =>
dvariant := (datatype => ft_nbyte3, v03 => convert (ST));
when ft_nbyte4 =>
dvariant := (datatype => ft_nbyte4, v04 => convert (ST));
when ft_nbyte8 =>
dvariant := (datatype => ft_nbyte8, v05 => convert (ST));
when ft_byte1 =>
dvariant := (datatype => ft_byte1, v06 => convert (ST));
when ft_byte2 =>
dvariant := (datatype => ft_byte2, v07 => convert (ST));
when ft_byte3 =>
dvariant := (datatype => ft_byte3, v08 => convert (ST));
when ft_byte4 =>
dvariant := (datatype => ft_byte4, v09 => convert (ST));
when ft_byte8 =>
dvariant := (datatype => ft_byte8, v10 => convert (ST));
when ft_real9 =>
dvariant := (datatype => ft_real9, v11 => convert (ST));
when ft_real18 =>
dvariant := (datatype => ft_real18, v12 => convert (ST));
when ft_textual =>
dvariant := (datatype => ft_textual, v13 => CT.SUS (ST));
when ft_widetext =>
dvariant := (datatype => ft_widetext,
v14 => convert (ST));
when ft_supertext =>
dvariant := (datatype => ft_supertext,
v15 => convert (ST));
when ft_utf8 =>
dvariant := (datatype => ft_utf8, v21 => CT.SUS (ST));
when ft_geometry =>
-- MySQL internal geometry format is SRID + WKB
-- Remove the first 4 bytes and save only the WKB
dvariant :=
(datatype => ft_geometry,
v22 => CT.SUS (ST (ST'First + 4 .. ST'Last)));
when ft_timestamp =>
begin
dvariant := (datatype => ft_timestamp,
v16 => ARC.convert (ST));
exception
when AR.CONVERSION_FAILED =>
dvariant := (datatype => ft_textual,
v13 => CT.SUS (ST));
end;
when ft_enumtype =>
dvariant := (datatype => ft_enumtype,
v18 => ARC.convert (CT.SUS (ST)));
when ft_chain => null;
when ft_settype => null;
when ft_bits => null;
end case;
case colinfo.field_type is
when ft_chain =>
field := ARF.spawn_field (binob => ARC.convert (ST));
when ft_bits =>
field := ARF.spawn_bits_field
(convert_to_bitstring (ST, colinfo.field_size * 8));
when ft_settype =>
field := ARF.spawn_field (enumset => ST);
when others =>
field := ARF.spawn_field (data => dvariant,
null_data => isnull);
end case;
end if;
result.push (heading => heading,
field => field,
last_field => last_one);
end;
end loop;
return result;
end;
end internal_fetch_row;
------------------
-- bincopy #1 --
------------------
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural) return String
is
reslen : Natural := datalen;
begin
if reslen > max_size then
reslen := max_size;
end if;
declare
result : String (1 .. reslen) := (others => '_');
begin
for x in result'Range loop
result (x) := Character (data.all (ABM.IC.size_t (x)));
end loop;
return result;
end;
end bincopy;
------------------
-- bincopy #2 --
------------------
function bincopy (data : ABM.ICS.char_array_access;
datalen, max_size : Natural;
hard_limit : Natural := 0) return AR.Chain
is
reslen : Natural := datalen;
chainlen : Natural := data.all'Length;
begin
if reslen > max_size then
reslen := max_size;
end if;
if hard_limit > 0 then
chainlen := hard_limit;
else
chainlen := reslen;
end if;
declare
result : AR.Chain (1 .. chainlen) := (others => 0);
jimmy : Character;
begin
for x in Natural range 1 .. reslen loop
jimmy := Character (data.all (ABM.IC.size_t (x)));
result (x) := AR.NByte1 (Character'Pos (jimmy));
end loop;
return result;
end;
end bincopy;
-----------------------------
-- internal_ps_fetch_row --
-----------------------------
function internal_ps_fetch_row (Stmt : out MySQL_statement)
return ARS.Datarow
is
use type ABM.ICS.chars_ptr;
use type ABM.MYSQL_ROW_access;
use type ACM.fetch_status;
status : ACM.fetch_status;
begin
status := Stmt.mysql_conn.prep_fetch_bound (Stmt.stmt_handle);
if status = ACM.spent then
Stmt.delivery := completed;
Stmt.clear_column_information;
elsif status = ACM.truncated then
Stmt.log_nominal (category => statement_execution,
message => "data truncated");
Stmt.delivery := progressing;
elsif status = ACM.error then
Stmt.log_problem (category => statement_execution,
message => "prep statement fetch error",
pull_codes => True);
Stmt.delivery := completed;
else
Stmt.delivery := progressing;
end if;
if Stmt.delivery = completed then
return ARS.Empty_Datarow;
end if;
declare
maxlen : constant Natural := Stmt.num_columns;
result : ARS.Datarow;
begin
for F in 1 .. maxlen loop
declare
use type ABM.enum_field_types;
function binary_string return String;
cv : mysql_canvas renames Stmt.bind_canvas (F);
colinfo : column_info renames Stmt.column_info.Element (F);
dvariant : ARF.Variant;
field : ARF.Std_Field;
last_one : constant Boolean := (F = maxlen);
datalen : constant Natural := Natural (cv.length);
heading : constant String := CT.USS (colinfo.field_name);
isnull : constant Boolean := (Natural (cv.is_null) = 1);
mtype : ABM.enum_field_types := colinfo.mysql_type;
function binary_string return String is
begin
return bincopy (data => cv.buffer_binary,
datalen => datalen,
max_size => Stmt.con_max_blob);
end binary_string;
begin
if isnull then
field := ARF.spawn_null_field (colinfo.field_type);
else
case colinfo.field_type is
when ft_nbyte0 =>
dvariant := (datatype => ft_nbyte0,
v00 => Natural (cv.buffer_uint8) = 1);
when ft_nbyte1 =>
dvariant := (datatype => ft_nbyte1,
v01 => AR.NByte1 (cv.buffer_uint8));
when ft_nbyte2 =>
dvariant := (datatype => ft_nbyte2,
v02 => AR.NByte2 (cv.buffer_uint16));
when ft_nbyte3 =>
dvariant := (datatype => ft_nbyte3,
v03 => AR.NByte3 (cv.buffer_uint32));
when ft_nbyte4 =>
dvariant := (datatype => ft_nbyte4,
v04 => AR.NByte4 (cv.buffer_uint32));
when ft_nbyte8 =>
dvariant := (datatype => ft_nbyte8,
v05 => AR.NByte8 (cv.buffer_uint64));
when ft_byte1 =>
dvariant := (datatype => ft_byte1,
v06 => AR.Byte1 (cv.buffer_int8));
when ft_byte2 =>
dvariant := (datatype => ft_byte2,
v07 => AR.Byte2 (cv.buffer_int16));
when ft_byte3 =>
dvariant := (datatype => ft_byte3,
v08 => AR.Byte3 (cv.buffer_int32));
when ft_byte4 =>
dvariant := (datatype => ft_byte4,
v09 => AR.Byte4 (cv.buffer_int32));
when ft_byte8 =>
dvariant := (datatype => ft_byte8,
v10 => AR.Byte8 (cv.buffer_int64));
when ft_real9 =>
if mtype = ABM.MYSQL_TYPE_NEWDECIMAL or else
mtype = ABM.MYSQL_TYPE_DECIMAL
then
dvariant := (datatype => ft_real9,
v11 => convert (binary_string));
else
dvariant := (datatype => ft_real9,
v11 => AR.Real9 (cv.buffer_float));
end if;
when ft_real18 =>
if mtype = ABM.MYSQL_TYPE_NEWDECIMAL or else
mtype = ABM.MYSQL_TYPE_DECIMAL
then
dvariant := (datatype => ft_real18,
v12 => convert (binary_string));
else
dvariant := (datatype => ft_real18,
v12 => AR.Real18 (cv.buffer_double));
end if;
when ft_textual =>
dvariant := (datatype => ft_textual,
v13 => CT.SUS (binary_string));
when ft_widetext =>
dvariant := (datatype => ft_widetext,
v14 => convert (binary_string));
when ft_supertext =>
dvariant := (datatype => ft_supertext,
v15 => convert (binary_string));
when ft_utf8 =>
dvariant := (datatype => ft_utf8,
v21 => CT.SUS (binary_string));
when ft_geometry =>
-- MySQL internal geometry format is SRID + WKB
-- Remove the first 4 bytes and save only the WKB
declare
ST : String := binary_string;
wkbstring : String := ST (ST'First + 4 .. ST'Last);
begin
dvariant := (datatype => ft_geometry,
v22 => CT.SUS (wkbstring));
end;
when ft_timestamp =>
declare
year : Natural := Natural (cv.buffer_time.year);
month : Natural := Natural (cv.buffer_time.month);
day : Natural := Natural (cv.buffer_time.day);
begin
if year < CAL.Year_Number'First or else
year > CAL.Year_Number'Last
then
year := CAL.Year_Number'First;
end if;
if month < CAL.Month_Number'First or else
month > CAL.Month_Number'Last
then
month := CAL.Month_Number'First;
end if;
if day < CAL.Day_Number'First or else
day > CAL.Day_Number'Last
then
day := CAL.Day_Number'First;
end if;
dvariant :=
(datatype => ft_timestamp,
v16 => CFM.Time_Of
(Year => year,
Month => month,
Day => day,
Hour => Natural (cv.buffer_time.hour),
Minute => Natural (cv.buffer_time.minute),
Second => Natural (cv.buffer_time.second),
Sub_Second => CFM.Second_Duration (Natural
(cv.buffer_time.second_part) / 1000000))
);
end;
when ft_enumtype =>
dvariant := (datatype => ft_enumtype,
v18 => ARC.convert (binary_string));
when ft_settype => null;
when ft_chain => null;
when ft_bits => null;
end case;
case colinfo.field_type is
when ft_chain =>
field := ARF.spawn_field
(binob => bincopy (cv.buffer_binary, datalen,
Stmt.con_max_blob));
when ft_bits =>
field := ARF.spawn_bits_field
(convert_to_bitstring
(binary_string, datalen * 8));
when ft_settype =>
field := ARF.spawn_field
(enumset => binary_string);
when others =>
field := ARF.spawn_field
(data => dvariant, null_data => isnull);
end case;
end if;
result.push (heading => heading,
field => field,
last_field => last_one);
end;
end loop;
return result;
end;
end internal_ps_fetch_row;
-------------------------------
-- internal_ps_fetch_bound --
-------------------------------
function internal_ps_fetch_bound (Stmt : out MySQL_statement)
return Boolean
is
use type ABM.ICS.chars_ptr;
use type ACM.fetch_status;
status : ACM.fetch_status;
begin
status := Stmt.mysql_conn.prep_fetch_bound (Stmt.stmt_handle);
if status = ACM.spent then
Stmt.delivery := completed;
Stmt.clear_column_information;
elsif status = ACM.truncated then
Stmt.log_nominal (category => statement_execution,
message => "data truncated");
Stmt.delivery := progressing;
elsif status = ACM.error then
Stmt.log_problem (category => statement_execution,
message => "prep statement fetch error",
pull_codes => True);
Stmt.delivery := completed;
else
Stmt.delivery := progressing;
end if;
if Stmt.delivery = completed then
return False;
end if;
declare
maxlen : constant Natural := Stmt.num_columns;
begin
for F in 1 .. maxlen loop
if not Stmt.crate.Element (Index => F).bound then
goto continue;
end if;
declare
use type ABM.enum_field_types;
function binary_string return String;
cv : mysql_canvas renames Stmt.bind_canvas (F);
colinfo : column_info renames Stmt.column_info.Element (F);
param : bindrec renames Stmt.crate.Element (F);
datalen : constant Natural := Natural (cv.length);
Tout : constant field_types := param.output_type;
Tnative : constant field_types := colinfo.field_type;
mtype : ABM.enum_field_types := colinfo.mysql_type;
errmsg : constant String := "native type : " &
field_types'Image (Tnative) & " binding type : " &
field_types'Image (Tout);
function binary_string return String is
begin
return bincopy (data => cv.buffer_binary,
datalen => datalen,
max_size => Stmt.con_max_blob);
end binary_string;
begin
-- Derivation of implementation taken from PostgreSQL
-- Only guaranteed successful converstions allowed though
case Tout is
when ft_nbyte2 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte3 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte4 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 | ft_nbyte4 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte8 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 | ft_nbyte4 |
ft_nbyte8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte2 =>
case Tnative is
when ft_byte1 | ft_byte2 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte3 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte4 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 | ft_byte4 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte8 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 | ft_byte4 |
ft_byte8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_real18 =>
case Tnative is
when ft_real9 | ft_real18 =>
null; -- guaranteed to convert without loss
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_textual =>
case Tnative is
when ft_textual | ft_utf8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when others =>
if Tnative /= Tout then
raise BINDING_TYPE_MISMATCH with errmsg;
end if;
end case;
case Tout is
when ft_nbyte0 => param.a00.all := (Natural (cv.buffer_uint8) = 1);
when ft_nbyte1 => param.a01.all := AR.NByte1 (cv.buffer_uint8);
when ft_nbyte2 => param.a02.all := AR.NByte2 (cv.buffer_uint16);
when ft_nbyte3 => param.a03.all := AR.NByte3 (cv.buffer_uint32);
when ft_nbyte4 => param.a04.all := AR.NByte4 (cv.buffer_uint32);
when ft_nbyte8 => param.a05.all := AR.NByte8 (cv.buffer_uint64);
when ft_byte1 => param.a06.all := AR.Byte1 (cv.buffer_int8);
when ft_byte2 => param.a07.all := AR.Byte2 (cv.buffer_int16);
when ft_byte3 => param.a08.all := AR.Byte3 (cv.buffer_int32);
when ft_byte4 => param.a09.all := AR.Byte4 (cv.buffer_int32);
when ft_byte8 => param.a10.all := AR.Byte8 (cv.buffer_int64);
when ft_real9 =>
if mtype = ABM.MYSQL_TYPE_NEWDECIMAL or else
mtype = ABM.MYSQL_TYPE_DECIMAL
then
param.a11.all := convert (binary_string);
else
param.a11.all := AR.Real9 (cv.buffer_float);
end if;
when ft_real18 =>
if mtype = ABM.MYSQL_TYPE_NEWDECIMAL or else
mtype = ABM.MYSQL_TYPE_DECIMAL
then
param.a12.all := convert (binary_string);
else
param.a12.all := AR.Real18 (cv.buffer_double);
end if;
when ft_textual => param.a13.all := CT.SUS (binary_string);
when ft_widetext => param.a14.all := convert (binary_string);
when ft_supertext => param.a15.all :=
convert (binary_string);
when ft_utf8 => param.a21.all := binary_string;
when ft_geometry =>
-- MySQL internal geometry format is SRID + WKB
-- Remove the first 4 bytes and translate WKB
declare
ST : String := binary_string;
wkbstring : String := ST (ST'First + 4 .. ST'Last);
begin
param.a22.all := WKB.Translate_WKB (wkbstring);
end;
when ft_timestamp =>
declare
year : Natural := Natural (cv.buffer_time.year);
month : Natural := Natural (cv.buffer_time.month);
day : Natural := Natural (cv.buffer_time.day);
begin
if year < CAL.Year_Number'First or else
year > CAL.Year_Number'Last
then
year := CAL.Year_Number'First;
end if;
if month < CAL.Month_Number'First or else
month > CAL.Month_Number'Last
then
month := CAL.Month_Number'First;
end if;
if day < CAL.Day_Number'First or else
day > CAL.Day_Number'Last
then
day := CAL.Day_Number'First;
end if;
param.a16.all := CFM.Time_Of
(Year => year,
Month => month,
Day => day,
Hour => Natural (cv.buffer_time.hour),
Minute => Natural (cv.buffer_time.minute),
Second => Natural (cv.buffer_time.second),
Sub_Second => CFM.Second_Duration (Natural
(cv.buffer_time.second_part) / 1000000));
end;
when ft_chain =>
if param.a17.all'Length < datalen then
raise BINDING_SIZE_MISMATCH with "native size : " &
param.a17.all'Length'Img &
" less than binding size : " & datalen'Img;
end if;
param.a17.all := bincopy
(cv.buffer_binary, datalen, Stmt.con_max_blob,
param.a17.all'Length);
when ft_bits =>
declare
strval : String := bincopy (cv.buffer_binary, datalen,
Stmt.con_max_blob);
FL : Natural := param.a20.all'Length;
DVLEN : Natural := strval'Length * 8;
begin
if FL < DVLEN then
raise BINDING_SIZE_MISMATCH with "native size : " &
FL'Img & " less than binding size : " & DVLEN'Img;
end if;
param.a20.all :=
ARC.convert (convert_to_bitstring (strval, FL));
end;
when ft_enumtype =>
param.a18.all :=
ARC.convert (CT.SUS (binary_string));
when ft_settype =>
declare
setstr : constant String := binary_string;
num_items : constant Natural := num_set_items (setstr);
begin
if param.a19.all'Length < num_items
then
raise BINDING_SIZE_MISMATCH with "native size : " &
param.a19.all'Length'Img &
" less than binding size : " & num_items'Img;
end if;
param.a19.all := ARC.convert (setstr,
param.a19.all'Length);
end;
end case;
end;
<<continue>>
null;
end loop;
return True;
end;
end internal_ps_fetch_bound;
-----------------------------------
-- internal_fetch_bound_direct --
-----------------------------------
function internal_fetch_bound (Stmt : out MySQL_statement) return Boolean
is
use type ABM.ICS.chars_ptr;
use type ABM.MYSQL_ROW_access;
rptr : ABM.MYSQL_ROW_access :=
Stmt.mysql_conn.fetch_row (Stmt.result_handle);
begin
if rptr = null then
Stmt.delivery := completed;
Stmt.mysql_conn.free_result (Stmt.result_handle);
Stmt.clear_column_information;
return False;
end if;
Stmt.delivery := progressing;
declare
maxlen : constant Natural := Natural (Stmt.column_info.Length);
bufmax : constant ABM.IC.size_t := ABM.IC.size_t (Stmt.con_max_blob);
subtype data_buffer is ABM.IC.char_array (1 .. bufmax);
type db_access is access all data_buffer;
type rowtype is array (1 .. maxlen) of db_access;
type rowtype_access is access all rowtype;
row : rowtype_access;
field_lengths : constant ACM.fldlen := Stmt.mysql_conn.fetch_lengths
(result_handle => Stmt.result_handle,
num_columns => maxlen);
function Convert is new Ada.Unchecked_Conversion
(Source => ABM.MYSQL_ROW_access, Target => rowtype_access);
function db_convert (dba : db_access; size : Natural) return String;
function db_convert (dba : db_access; size : Natural) return String
is
max : Natural := size;
begin
if max > Stmt.con_max_blob then
max := Stmt.con_max_blob;
end if;
declare
result : String (1 .. max);
begin
for x in result'Range loop
result (x) := Character (dba.all (ABM.IC.size_t (x)));
end loop;
return result;
end;
end db_convert;
begin
row := Convert (rptr);
for F in 1 .. maxlen loop
declare
use type ABM.enum_field_types;
dossier : bindrec renames Stmt.crate.Element (F);
colinfo : column_info renames Stmt.column_info.Element (F);
mtype : ABM.enum_field_types := colinfo.mysql_type;
isnull : constant Boolean := (row (F) = null);
sz : constant Natural := field_lengths (F);
ST : constant String := db_convert (row (F), sz);
Tout : constant field_types := dossier.output_type;
Tnative : constant field_types := colinfo.field_type;
errmsg : constant String := "native type : " &
field_types'Image (Tnative) & " binding type : " &
field_types'Image (Tout);
begin
if not dossier.bound then
goto continue;
end if;
if isnull or else CT.IsBlank (ST) then
set_as_null (dossier);
goto continue;
end if;
-- Derivation of implementation taken from PostgreSQL
-- Only guaranteed successful converstions allowed though
case Tout is
when ft_nbyte2 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte3 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte4 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 | ft_nbyte4 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_nbyte8 =>
case Tnative is
when ft_nbyte1 | ft_nbyte2 | ft_nbyte3 | ft_nbyte4 |
ft_nbyte8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte2 =>
case Tnative is
when ft_byte1 | ft_byte2 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte3 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte4 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 | ft_byte4 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_byte8 =>
case Tnative is
when ft_byte1 | ft_byte2 | ft_byte3 | ft_byte4 |
ft_byte8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_real18 =>
case Tnative is
when ft_real9 | ft_real18 =>
null; -- guaranteed to convert without loss
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when ft_textual =>
case Tnative is
when ft_textual | ft_utf8 =>
null;
when others =>
raise BINDING_TYPE_MISMATCH with errmsg;
end case;
when others =>
if Tnative /= Tout then
raise BINDING_TYPE_MISMATCH with errmsg;
end if;
end case;
case Tout is
when ft_nbyte0 => dossier.a00.all := (ST = "1");
when ft_nbyte1 => dossier.a01.all := convert (ST);
when ft_nbyte2 => dossier.a02.all := convert (ST);
when ft_nbyte3 => dossier.a03.all := convert (ST);
when ft_nbyte4 => dossier.a04.all := convert (ST);
when ft_nbyte8 => dossier.a05.all := convert (ST);
when ft_byte1 => dossier.a06.all := convert (ST);
when ft_byte2 => dossier.a07.all := convert (ST);
when ft_byte3 => dossier.a08.all := convert (ST);
when ft_byte4 => dossier.a09.all := convert (ST);
when ft_byte8 => dossier.a10.all := convert (ST);
when ft_real9 => dossier.a11.all := convert (ST);
when ft_real18 => dossier.a12.all := convert (ST);
when ft_widetext => dossier.a14.all := convert (ST);
when ft_supertext => dossier.a15.all := convert (ST);
when ft_enumtype => dossier.a18.all := ARC.convert (ST);
when ft_textual => dossier.a13.all := CT.SUS (ST);
when ft_utf8 => dossier.a21.all := ST;
when ft_geometry =>
-- MySQL internal geometry format is SRID + WKB
-- Remove the first 4 bytes and translate WKB
declare
wkbstring : String := ST (ST'First + 4 .. ST'Last);
begin
dossier.a22.all := WKB.Translate_WKB (wkbstring);
end;
when ft_timestamp =>
begin
dossier.a16.all := ARC.convert (ST);
exception
when AR.CONVERSION_FAILED =>
dossier.a16.all := AR.PARAM_IS_TIMESTAMP;
end;
when ft_chain =>
declare
FL : Natural := dossier.a17.all'Length;
DVLEN : Natural := ST'Length;
begin
if DVLEN > FL then
raise BINDING_SIZE_MISMATCH with "native size : " &
DVLEN'Img & " greater than binding size : " &
FL'Img;
end if;
dossier.a17.all := ARC.convert (ST, FL);
end;
when ft_bits =>
declare
FL : Natural := dossier.a20.all'Length;
DVLEN : Natural := ST'Length * 8;
begin
if DVLEN > FL then
raise BINDING_SIZE_MISMATCH with "native size : " &
DVLEN'Img & " greater than binding size : " &
FL'Img;
end if;
dossier.a20.all :=
ARC.convert (convert_to_bitstring (ST, FL));
end;
when ft_settype =>
declare
FL : Natural := dossier.a19.all'Length;
items : constant Natural := CT.num_set_items (ST);
begin
if items > FL then
raise BINDING_SIZE_MISMATCH with
"native size : " & items'Img &
" greater than binding size : " & FL'Img;
end if;
dossier.a19.all := ARC.convert (ST, FL);
end;
end case;
end;
<<continue>>
end loop;
return True;
end;
end internal_fetch_bound;
----------------------------------
-- internal_direct_post_exec --
----------------------------------
procedure internal_direct_post_exec (Stmt : out MySQL_statement;
newset : Boolean := False) is
begin
Stmt.successful_execution := False;
Stmt.size_of_rowset := 0;
if newset then
Stmt.log_nominal (category => statement_execution,
message => "Fetch next rowset from: "
& Stmt.sql_final.all);
else
Stmt.connection.execute (sql => Stmt.sql_final.all);
Stmt.log_nominal (category => statement_execution,
message => Stmt.sql_final.all);
Stmt.process_direct_result;
end if;
Stmt.successful_execution := True;
if Stmt.result_present then
Stmt.scan_column_information;
if Stmt.con_buffered then
Stmt.size_of_rowset := Stmt.mysql_conn.rows_in_result
(Stmt.result_handle);
end if;
Stmt.delivery := pending;
else
declare
returned_cols : Natural;
begin
returned_cols := Stmt.mysql_conn.field_count;
if returned_cols = 0 then
Stmt.impacted := Stmt.mysql_conn.rows_affected_by_execution;
else
raise ACM.RESULT_FAIL with "Columns returned without result";
end if;
end;
Stmt.delivery := completed;
end if;
exception
when ACM.QUERY_FAIL =>
Stmt.log_problem (category => statement_execution,
message => Stmt.sql_final.all,
pull_codes => True);
when RES : ACM.RESULT_FAIL =>
Stmt.log_problem (category => statement_execution,
message => EX.Exception_Message (X => RES),
pull_codes => True);
end internal_direct_post_exec;
-------------------------------
-- internal_post_prep_stmt --
-------------------------------
procedure internal_post_prep_stmt (Stmt : out MySQL_statement)
is
use type mysql_canvases_Access;
begin
Stmt.delivery := completed; -- default for early returns
if Stmt.num_columns = 0 then
Stmt.result_present := False;
Stmt.impacted := Stmt.mysql_conn.prep_rows_affected_by_execution
(Stmt.stmt_handle);
return;
end if;
Stmt.result_present := True;
if Stmt.bind_canvas /= null then
raise STMT_PREPARATION with
"Previous bind canvas present (expected to be null)";
end if;
Stmt.bind_canvas := new mysql_canvases (1 .. Stmt.num_columns);
declare
slots : ABM.MYSQL_BIND_Array (1 .. Stmt.num_columns);
ft : field_types;
fsize : Natural;
begin
for sx in slots'Range loop
slots (sx).is_null := Stmt.bind_canvas (sx).is_null'Access;
slots (sx).length := Stmt.bind_canvas (sx).length'Access;
slots (sx).error := Stmt.bind_canvas (sx).error'Access;
slots (sx).buffer_type := Stmt.column_info.Element (sx).mysql_type;
ft := Stmt.column_info.Element (sx).field_type;
case slots (sx).buffer_type is
when ABM.MYSQL_TYPE_DOUBLE =>
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_double'Address;
when ABM.MYSQL_TYPE_FLOAT =>
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_float'Address;
when ABM.MYSQL_TYPE_NEWDECIMAL | ABM.MYSQL_TYPE_DECIMAL =>
-- Don't set buffer_type to FLOAT or DOUBLE. MySQL will
-- automatically convert it, but precision will be lost.
-- Ask for a string and let's convert that ourselves.
slots (sx).buffer_type := ABM.MYSQL_TYPE_NEWDECIMAL;
fsize := Stmt.column_info.Element (sx).field_size;
slots (sx).buffer_length := ABM.IC.unsigned_long (fsize);
Stmt.bind_canvas (sx).buffer_binary := new ABM.IC.char_array
(1 .. ABM.IC.size_t (fsize));
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_binary.all'Address;
when ABM.MYSQL_TYPE_TINY =>
if ft = ft_nbyte0 or else ft = ft_nbyte1 then
slots (sx).is_unsigned := 1;
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_uint8'Address;
else
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_int8'Address;
end if;
when ABM.MYSQL_TYPE_SHORT | ABM.MYSQL_TYPE_YEAR =>
if ft = ft_nbyte2 then
slots (sx).is_unsigned := 1;
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_uint16'Address;
else
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_int16'Address;
end if;
when ABM.MYSQL_TYPE_INT24 | ABM.MYSQL_TYPE_LONG =>
if ft = ft_nbyte3 or else ft = ft_nbyte4 then
slots (sx).is_unsigned := 1;
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_uint32'Address;
else
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_int32'Address;
end if;
when ABM.MYSQL_TYPE_LONGLONG =>
if ft = ft_nbyte8 then
slots (sx).is_unsigned := 1;
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_uint64'Address;
else
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_int64'Address;
end if;
when ABM.MYSQL_TYPE_DATE | ABM.MYSQL_TYPE_TIMESTAMP |
ABM.MYSQL_TYPE_TIME | ABM.MYSQL_TYPE_DATETIME =>
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_time'Address;
when ABM.MYSQL_TYPE_BIT | ABM.MYSQL_TYPE_TINY_BLOB |
ABM.MYSQL_TYPE_MEDIUM_BLOB | ABM.MYSQL_TYPE_LONG_BLOB |
ABM.MYSQL_TYPE_BLOB | ABM.MYSQL_TYPE_STRING |
ABM.MYSQL_TYPE_VAR_STRING =>
fsize := Stmt.column_info.Element (sx).field_size;
slots (sx).buffer_length := ABM.IC.unsigned_long (fsize);
Stmt.bind_canvas (sx).buffer_binary := new ABM.IC.char_array
(1 .. ABM.IC.size_t (fsize));
slots (sx).buffer :=
Stmt.bind_canvas (sx).buffer_binary.all'Address;
when ABM.MYSQL_TYPE_NULL | ABM.MYSQL_TYPE_NEWDATE |
ABM.MYSQL_TYPE_VARCHAR | ABM.MYSQL_TYPE_GEOMETRY |
ABM.MYSQL_TYPE_ENUM | ABM.MYSQL_TYPE_SET =>
raise STMT_PREPARATION with
"Unsupported MySQL type for result binding attempted";
end case;
end loop;
if not Stmt.mysql_conn.prep_bind_result (Stmt.stmt_handle, slots)
then
Stmt.log_problem (category => statement_preparation,
message => "failed to bind result structures",
pull_codes => True);
return;
end if;
end;
if Stmt.con_buffered then
Stmt.mysql_conn.prep_store_result (Stmt.stmt_handle);
Stmt.size_of_rowset := Stmt.mysql_conn.prep_rows_in_result
(Stmt.stmt_handle);
end if;
Stmt.delivery := pending;
end internal_post_prep_stmt;
---------------------------
-- construct_bind_slot --
---------------------------
procedure construct_bind_slot (Stmt : MySQL_statement;
struct : out ABM.MYSQL_BIND;
canvas : out mysql_canvas;
marker : Positive)
is
procedure set_binary_buffer (Str : String);
zone : bindrec renames Stmt.realmccoy.Element (marker);
vartype : constant field_types := zone.output_type;
use type AR.NByte0_Access;
use type AR.NByte1_Access;
use type AR.NByte2_Access;
use type AR.NByte3_Access;
use type AR.NByte4_Access;
use type AR.NByte8_Access;
use type AR.Byte1_Access;
use type AR.Byte2_Access;
use type AR.Byte3_Access;
use type AR.Byte4_Access;
use type AR.Byte8_Access;
use type AR.Real9_Access;
use type AR.Real18_Access;
use type AR.Str1_Access;
use type AR.Str2_Access;
use type AR.Str4_Access;
use type AR.Time_Access;
use type AR.Enum_Access;
use type AR.Chain_Access;
use type AR.Settype_Access;
use type AR.Bits_Access;
use type AR.S_UTF8_Access;
use type AR.Geometry_Access;
procedure set_binary_buffer (Str : String)
is
len : constant ABM.IC.size_t := ABM.IC.size_t (Str'Length);
begin
canvas.buffer_binary := new ABM.IC.char_array (1 .. len);
canvas.buffer_binary.all := ABM.IC.To_C (Str, False);
canvas.length := ABM.IC.unsigned_long (len);
struct.buffer := canvas.buffer_binary.all'Address;
struct.buffer_length := ABM.IC.unsigned_long (len);
struct.length := canvas.length'Unchecked_Access;
struct.is_null := canvas.is_null'Unchecked_Access;
end set_binary_buffer;
begin
case vartype is
when ft_nbyte0 | ft_nbyte1 | ft_nbyte2 | ft_nbyte3 | ft_nbyte4 |
ft_nbyte8 => struct.is_unsigned := 1;
when others => null;
end case;
case vartype is
when ft_nbyte0 => struct.buffer_type := ABM.MYSQL_TYPE_TINY;
when ft_nbyte1 => struct.buffer_type := ABM.MYSQL_TYPE_TINY;
when ft_nbyte2 => struct.buffer_type := ABM.MYSQL_TYPE_SHORT;
when ft_nbyte3 => struct.buffer_type := ABM.MYSQL_TYPE_LONG;
when ft_nbyte4 => struct.buffer_type := ABM.MYSQL_TYPE_LONG;
when ft_nbyte8 => struct.buffer_type := ABM.MYSQL_TYPE_LONGLONG;
when ft_byte1 => struct.buffer_type := ABM.MYSQL_TYPE_TINY;
when ft_byte2 => struct.buffer_type := ABM.MYSQL_TYPE_SHORT;
when ft_byte3 => struct.buffer_type := ABM.MYSQL_TYPE_LONG;
when ft_byte4 => struct.buffer_type := ABM.MYSQL_TYPE_LONG;
when ft_byte8 => struct.buffer_type := ABM.MYSQL_TYPE_LONGLONG;
when ft_real9 => struct.buffer_type := ABM.MYSQL_TYPE_FLOAT;
when ft_real18 => struct.buffer_type := ABM.MYSQL_TYPE_DOUBLE;
when ft_textual => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_widetext => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_supertext => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_timestamp => struct.buffer_type := ABM.MYSQL_TYPE_DATETIME;
when ft_chain => struct.buffer_type := ABM.MYSQL_TYPE_BLOB;
when ft_enumtype => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_settype => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_bits => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_utf8 => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
when ft_geometry => struct.buffer_type := ABM.MYSQL_TYPE_STRING;
end case;
if zone.null_data then
canvas.is_null := 1;
struct.buffer_type := ABM.MYSQL_TYPE_NULL;
else
case vartype is
when ft_nbyte0 =>
struct.buffer := canvas.buffer_uint8'Address;
if zone.a00 = null then
if zone.v00 then
canvas.buffer_uint8 := 1;
end if;
else
if zone.a00.all then
canvas.buffer_uint8 := 1;
end if;
end if;
when ft_nbyte1 =>
struct.buffer := canvas.buffer_uint8'Address;
if zone.a01 = null then
canvas.buffer_uint8 := ABM.IC.unsigned_char (zone.v01);
else
canvas.buffer_uint8 := ABM.IC.unsigned_char (zone.a01.all);
end if;
when ft_nbyte2 =>
struct.buffer := canvas.buffer_uint16'Address;
if zone.a02 = null then
canvas.buffer_uint16 := ABM.IC.unsigned_short (zone.v02);
else
canvas.buffer_uint16 := ABM.IC.unsigned_short (zone.a02.all);
end if;
when ft_nbyte3 =>
struct.buffer := canvas.buffer_uint32'Address;
-- ABM.MYSQL_TYPE_INT24 not for input, use next biggest
if zone.a03 = null then
canvas.buffer_uint32 := ABM.IC.unsigned (zone.v03);
else
canvas.buffer_uint32 := ABM.IC.unsigned (zone.a03.all);
end if;
when ft_nbyte4 =>
struct.buffer := canvas.buffer_uint32'Address;
if zone.a04 = null then
canvas.buffer_uint32 := ABM.IC.unsigned (zone.v04);
else
canvas.buffer_uint32 := ABM.IC.unsigned (zone.a04.all);
end if;
when ft_nbyte8 =>
struct.buffer := canvas.buffer_uint64'Address;
if zone.a05 = null then
canvas.buffer_uint64 := ABM.IC.unsigned_long (zone.v05);
else
canvas.buffer_uint64 := ABM.IC.unsigned_long (zone.a05.all);
end if;
when ft_byte1 =>
struct.buffer := canvas.buffer_int8'Address;
if zone.a06 = null then
canvas.buffer_int8 := ABM.IC.signed_char (zone.v06);
else
canvas.buffer_int8 := ABM.IC.signed_char (zone.a06.all);
end if;
when ft_byte2 =>
struct.buffer := canvas.buffer_int16'Address;
if zone.a07 = null then
canvas.buffer_int16 := ABM.IC.short (zone.v07);
else
canvas.buffer_int16 := ABM.IC.short (zone.a07.all);
end if;
when ft_byte3 =>
struct.buffer := canvas.buffer_int32'Address;
-- ABM.MYSQL_TYPE_INT24 not for input, use next biggest
if zone.a08 = null then
canvas.buffer_int32 := ABM.IC.int (zone.v08);
else
canvas.buffer_int32 := ABM.IC.int (zone.a08.all);
end if;
when ft_byte4 =>
struct.buffer := canvas.buffer_int32'Address;
if zone.a09 = null then
canvas.buffer_int32 := ABM.IC.int (zone.v09);
else
canvas.buffer_int32 := ABM.IC.int (zone.a09.all);
end if;
when ft_byte8 =>
struct.buffer := canvas.buffer_int64'Address;
if zone.a10 = null then
canvas.buffer_int64 := ABM.IC.long (zone.v10);
else
canvas.buffer_int64 := ABM.IC.long (zone.a10.all);
end if;
when ft_real9 =>
struct.buffer := canvas.buffer_float'Address;
if zone.a11 = null then
canvas.buffer_float := ABM.IC.C_float (zone.v11);
else
canvas.buffer_float := ABM.IC.C_float (zone.a11.all);
end if;
when ft_real18 =>
struct.buffer := canvas.buffer_double'Address;
if zone.a12 = null then
canvas.buffer_double := ABM.IC.double (zone.v12);
else
canvas.buffer_double := ABM.IC.double (zone.a12.all);
end if;
when ft_textual =>
if zone.a13 = null then
set_binary_buffer (ARC.convert (zone.v13));
else
set_binary_buffer (ARC.convert (zone.a13.all));
end if;
when ft_widetext =>
if zone.a14 = null then
set_binary_buffer (ARC.convert (zone.v14));
else
set_binary_buffer (ARC.convert (zone.a14.all));
end if;
when ft_supertext =>
if zone.a15 = null then
set_binary_buffer (ARC.convert (zone.v15));
else
set_binary_buffer (ARC.convert (zone.a15.all));
end if;
when ft_utf8 =>
if zone.a21 = null then
set_binary_buffer (ARC.convert (zone.v21));
else
set_binary_buffer (zone.a21.all);
end if;
when ft_geometry =>
if zone.a22 = null then
set_binary_buffer (WKB.produce_WKT (zone.v22));
else
set_binary_buffer (Spatial_Data.Well_Known_Text (zone.a22.all));
end if;
when ft_timestamp =>
struct.buffer := canvas.buffer_time'Address;
declare
hack : CAL.Time;
begin
if zone.a16 = null then
hack := zone.v16;
else
hack := zone.a16.all;
end if;
-- Negative time not supported
canvas.buffer_time.year := ABM.IC.unsigned (CFM.Year (hack));
canvas.buffer_time.month := ABM.IC.unsigned (CFM.Month (hack));
canvas.buffer_time.day := ABM.IC.unsigned (CFM.Day (hack));
canvas.buffer_time.hour := ABM.IC.unsigned (CFM.Hour (hack));
canvas.buffer_time.minute := ABM.IC.unsigned
(CFM.Minute (hack));
canvas.buffer_time.second := ABM.IC.unsigned
(CFM.Second (hack));
canvas.buffer_time.second_part :=
ABM.IC.unsigned_long (CFM.Sub_Second (hack) * 1000000);
end;
when ft_chain =>
if zone.a17 = null then
set_binary_buffer (CT.USS (zone.v17));
else
set_binary_buffer (ARC.convert (zone.a17.all));
end if;
when ft_enumtype =>
if zone.a18 = null then
set_binary_buffer (ARC.convert (zone.v18.enumeration));
else
set_binary_buffer (ARC.convert (zone.a18.all.enumeration));
end if;
when ft_settype =>
if zone.a19 = null then
set_binary_buffer (CT.USS (zone.v19));
else
set_binary_buffer (ARC.convert (zone.a19.all));
end if;
when ft_bits =>
if zone.a20 = null then
set_binary_buffer (CT.USS (zone.v20));
else
set_binary_buffer (ARC.convert (zone.a20.all));
end if;
end case;
end if;
end construct_bind_slot;
-------------------
-- log_problem --
-------------------
procedure log_problem
(statement : MySQL_statement;
category : Log_Category;
message : String;
pull_codes : Boolean := False;
break : Boolean := False)
is
error_msg : CT.Text := CT.blank;
error_code : Driver_Codes := 0;
sqlstate : SQL_State := stateless;
begin
if pull_codes then
error_msg := CT.SUS (statement.last_driver_message);
error_code := statement.last_driver_code;
sqlstate := statement.last_sql_state;
end if;
logger_access.all.log_problem
(driver => statement.dialect,
category => category,
message => CT.SUS (message),
error_msg => error_msg,
error_code => error_code,
sqlstate => sqlstate,
break => break);
end log_problem;
---------------------
-- num_set_items --
---------------------
function num_set_items (nv : String) return Natural
is
result : Natural := 0;
begin
if not CT.IsBlank (nv) then
result := 1;
for x in nv'Range loop
if nv (x) = ',' then
result := result + 1;
end if;
end loop;
end if;
return result;
end num_set_items;
----------------------------
-- convert_to_bitstring --
----------------------------
function convert_to_bitstring (nv : String; width : Natural) return String
is
use type AR.NByte1;
result : String (1 .. width) := (others => '0');
marker : Natural;
lode : AR.NByte1;
mask : constant array (0 .. 7) of AR.NByte1 := (2 ** 0, 2 ** 1,
2 ** 2, 2 ** 3,
2 ** 4, 2 ** 5,
2 ** 6, 2 ** 7);
begin
-- We can't seem to get the true size, e.g 12 bits shows as 2,
-- for two bytes, which could represent up to 16 bits. Thus, we
-- return a variable width in multiples of 8. MySQL doesn't mind
-- leading zeros.
marker := result'Last;
for x in reverse nv'Range loop
lode := AR.NByte1 (Character'Pos (nv (x)));
for position in mask'Range loop
if (lode and mask (position)) > 0 then
result (marker) := '1';
end if;
exit when marker = result'First;
marker := marker - 1;
end loop;
end loop;
return result;
end convert_to_bitstring;
end AdaBase.Statement.Base.MySQL;
|
apple-oss-distributions/old_ncurses | Ada | 2,990 | ads | ------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- Tour --
-- --
-- S P E C --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer <[email protected]> 1996
-- Version Control
-- $Revision: 1.1.1.1 $
-- Binding Version 01.00
------------------------------------------------------------------------------
procedure Tour;
|
flyx/OpenGLAda | Ada | 19,722 | ads | -- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.Types;
package GL.Enums.Getter is
pragma Preelaborate;
type Parameter is
(Current_Color,
Current_Index,
Current_Normal,
Current_Texture_Coords,
Current_Raster_Color,
Current_Raster_Index,
Current_Raster_Texture_Coords,
Current_Raster_Position,
Current_Raster_Position_Valid,
Current_Raster_Distance,
Point_Smooth,
Point_Size,
Point_Size_Range,
Point_Size_Granularity,
Line_Smooth,
Line_Width,
Smooth_Line_Width_Range,
Smooth_Line_Width_Granularity,
Line_Stipple,
Line_Stipple_Pattern,
Line_Stipple_Repeat,
List_Mode,
Max_List_Nesting,
List_Base,
List_Index,
Polygon_Mode,
Polygon_Smooth,
Polygon_Stipple,
Edge_Flag,
Cull_Face,
Cull_Face_Mode,
Front_Face,
Lighting,
Light_Model_Local_Viewer,
Light_Model_Two_Side,
Light_Model_Ambient,
Shade_Model,
Color_Material_Face,
Color_Material_Parameter,
Color_Material,
Fog,
Fog_Index,
Fog_Density,
Fog_Start,
Fog_End,
Fog_Mode,
Fog_Color,
Depth_Range,
Depth_Test,
Depth_Writemask,
Depth_Clear_Value,
Depth_Func,
Accum_Clear_Value,
Stencil_Test,
Stencil_Clear_Value,
Stencil_Func,
Stencil_Value_Mask,
Stencil_Fail,
Stencil_Pass_Depth_Fail,
Stencil_Pass_Depth_Pass,
Stencil_Ref,
Stencil_Writemask,
Matrix_Mode,
Normalize,
Viewport,
Modelview_Stack_Depth,
Projection_Stack_Depth,
Texture_Stack_Depth,
Modelview_Matrix,
Projection_Matrix,
Texture_Matrix,
Attrib_Stack_Depth,
Client_Attrib_Stack_Depth,
Alpha_Test,
Alpha_Test_Func,
Alpha_Test_Ref,
Dither,
Blend_Dst,
Blend_Src,
Blend,
Logic_Op_Mode,
Index_Logic_Op,
Color_Logic_Op,
Aux_Buffers,
Draw_Buffer,
Read_Buffer,
Scissor_Box,
Scissor_Test,
Index_Clear_Value,
Index_Writemask,
Color_Clear_Value,
Color_Writemask,
Index_Mode,
Rgba_Mode,
Doublebuffer,
Stereo,
Render_Mode,
Perspective_Correction_Hint,
Point_Smooth_Hint,
Line_Smooth_Hint,
Polygon_Smooth_Hint,
Fog_Hint,
Texture_Gen_S,
Texture_Gen_T,
Texture_Gen_R,
Texture_Gen_Q,
Pixel_Map_I_To_I,
Pixel_Map_S_To_S,
Pixel_Map_I_To_R,
Pixel_Map_I_To_G,
Pixel_Map_I_To_B,
Pixel_Map_I_To_A,
Pixel_Map_R_To_R,
Pixel_Map_G_To_G,
Pixel_Map_B_To_B,
Pixel_Map_A_To_A,
Pixel_Map_I_To_I_Size,
Pixel_Map_S_To_S_Size,
Pixel_Map_I_To_R_Size,
Pixel_Map_I_To_G_Size,
Pixel_Map_I_To_B_Size,
Pixel_Map_I_To_A_Size,
Pixel_Map_R_To_R_Size,
Pixel_Map_G_To_G_Size,
Pixel_Map_B_To_B_Size,
Pixel_Map_A_To_A_Size,
Unpack_Swap_Bytes,
Unpack_Lsb_First,
Unpack_Row_Length,
Unpack_Skip_Rows,
Unpack_Skip_Pixels,
Unpack_Alignment,
Pack_Swap_Bytes,
Pack_Lsb_First,
Pack_Row_Length,
Pack_Skip_Rows,
Pack_Skip_Pixels,
Pack_Alignment,
Map_Color,
Map_Stencil,
Index_Shift,
Index_Offset,
Red_Scale,
Red_Bias,
Zoom_X,
Zoom_Y,
Green_Scale,
Green_Bias,
Blue_Scale,
Blue_Bias,
Alpha_Scale,
Alpha_Bias,
Depth_Scale,
Depth_Bias,
Max_Eval_Order,
Max_Lights,
Max_Clip_Planes,
Max_Texture_Size,
Max_Pixel_Map_Table,
Max_Attrib_Stack_Depth,
Max_Modelview_Stack_Depth,
Max_Name_Stack_Depth,
Max_Projection_Stack_Depth,
Max_Texture_Stack_Depth,
Max_Viewport_Dims,
Max_Client_Attrib_Stack_Depth,
Subpixel_Bits,
Index_Bits,
Red_Bits,
Green_Bits,
Blue_Bits,
Alpha_Bits,
Depth_Bits,
Stencil_Bits,
Accum_Red_Bits,
Accum_Green_Bits,
Accum_Blue_Bits,
Accum_Alpha_Bits,
Name_Stack_Depth,
Auto_Normal,
Map1_Color_4,
Map1_Index,
Map1_Normal,
Map1_Texture_Coord_1,
Map1_Texture_Coord_2,
Map1_Texture_Coord_3,
Map1_Texture_Coord_4,
Map1_Vertex_3,
Map1_Vertex_4,
Map2_Color_4,
Map2_Index,
Map2_Normal,
Map2_Texture_Coord_1,
Map2_Texture_Coord_2,
Map2_Texture_Coord_3,
Map2_Texture_Coord_4,
Map2_Vertex_3,
Map2_Vertex_4,
Map1_Grid_Domain,
Map1_Grid_Segments,
Map2_Grid_Domain,
Map2_Grid_Segments,
Texture_1D,
Texture_2D,
Feedback_Buffer_Pointer,
Feedback_Buffer_Size,
Feedback_Buffer_Type,
Selection_Buffer_Pointer,
Selection_Buffer_Size,
Blend_Color,
Blend_Equation_RGB,
Pack_Skip_Images,
Pack_Image_Height,
Unpack_Skip_Images,
Unpack_Image_Height,
Blend_Dst_RGB,
Blend_Src_RGB,
Blend_Dst_Alpha,
Blend_Src_Alpha,
Point_Fade_Threshold_Size,
Light_Model_Color_Control,
Major_Version,
Minor_Version,
Num_Extensions,
Debug_Next_Logged_Message_Length,
Num_Shading_Language_Versions,
Current_Fog_Coord,
Current_Secondary_Color,
Aliased_Line_Width_Range,
Active_Texture,
Stencil_Back_Func,
Stencil_Back_Fail,
Stencil_Back_Pass_Depth_Fail,
Stencil_Back_Pass_Depth_Pass,
Blend_Equation_Alpha,
Query_Result,
Query_Result_Available,
Max_Combined_Texture_Image_Units,
Stencil_Back_Ref,
Stencil_Back_Value_Mask,
Stencil_Back_Writemask,
Max_Debug_Message_Length,
Max_Debug_Logged_Messages,
Debug_Logged_Messages,
Max_Framebuffer_Width,
Max_Framebuffer_Height,
Max_Framebuffer_Layers,
Max_Framebuffer_Samples);
for Parameter use
(Current_Color => 16#0B00#,
Current_Index => 16#0B01#,
Current_Normal => 16#0B02#,
Current_Texture_Coords => 16#0B03#,
Current_Raster_Color => 16#0B04#,
Current_Raster_Index => 16#0B05#,
Current_Raster_Texture_Coords => 16#0B06#,
Current_Raster_Position => 16#0B07#,
Current_Raster_Position_Valid => 16#0B08#,
Current_Raster_Distance => 16#0B09#,
Point_Smooth => 16#0B10#,
Point_Size => 16#0B11#,
Point_Size_Range => 16#0B12#,
Point_Size_Granularity => 16#0B13#,
Line_Smooth => 16#0B20#,
Line_Width => 16#0B21#,
Smooth_Line_Width_Range => 16#0B22#,
Smooth_Line_Width_Granularity => 16#0B23#,
Line_Stipple => 16#0B24#,
Line_Stipple_Pattern => 16#0B25#,
Line_Stipple_Repeat => 16#0B26#,
List_Mode => 16#0B30#,
Max_List_Nesting => 16#0B31#,
List_Base => 16#0B32#,
List_Index => 16#0B33#,
Polygon_Mode => 16#0B40#,
Polygon_Smooth => 16#0B41#,
Polygon_Stipple => 16#0B42#,
Edge_Flag => 16#0B43#,
Cull_Face => 16#0B44#,
Cull_Face_Mode => 16#0B45#,
Front_Face => 16#0B46#,
Lighting => 16#0B50#,
Light_Model_Local_Viewer => 16#0B51#,
Light_Model_Two_Side => 16#0B52#,
Light_Model_Ambient => 16#0B53#,
Shade_Model => 16#0B54#,
Color_Material_Face => 16#0B55#,
Color_Material_Parameter => 16#0B56#,
Color_Material => 16#0B57#,
Fog => 16#0B60#,
Fog_Index => 16#0B61#,
Fog_Density => 16#0B62#,
Fog_Start => 16#0B63#,
Fog_End => 16#0B64#,
Fog_Mode => 16#0B65#,
Fog_Color => 16#0B66#,
Depth_Range => 16#0B70#,
Depth_Test => 16#0B71#,
Depth_Writemask => 16#0B72#,
Depth_Clear_Value => 16#0B73#,
Depth_Func => 16#0B74#,
Accum_Clear_Value => 16#0B80#,
Stencil_Test => 16#0B90#,
Stencil_Clear_Value => 16#0B91#,
Stencil_Func => 16#0B92#,
Stencil_Value_Mask => 16#0B93#,
Stencil_Fail => 16#0B94#,
Stencil_Pass_Depth_Fail => 16#0B95#,
Stencil_Pass_Depth_Pass => 16#0B96#,
Stencil_Ref => 16#0B97#,
Stencil_Writemask => 16#0B98#,
Matrix_Mode => 16#0BA0#,
Normalize => 16#0BA1#,
Viewport => 16#0BA2#,
Modelview_Stack_Depth => 16#0BA3#,
Projection_Stack_Depth => 16#0BA4#,
Texture_Stack_Depth => 16#0BA5#,
Modelview_Matrix => 16#0BA6#,
Projection_Matrix => 16#0BA7#,
Texture_Matrix => 16#0BA8#,
Attrib_Stack_Depth => 16#0BB0#,
Client_Attrib_Stack_Depth => 16#0BB1#,
Alpha_Test => 16#0BC0#,
Alpha_Test_Func => 16#0BC1#,
Alpha_Test_Ref => 16#0BC2#,
Dither => 16#0BD0#,
Blend_Dst => 16#0BE0#,
Blend_Src => 16#0BE1#,
Blend => 16#0BE2#,
Logic_Op_Mode => 16#0BF0#,
Index_Logic_Op => 16#0BF1#,
Color_Logic_Op => 16#0BF2#,
Aux_Buffers => 16#0C00#,
Draw_Buffer => 16#0C01#,
Read_Buffer => 16#0C02#,
Scissor_Box => 16#0C10#,
Scissor_Test => 16#0C11#,
Index_Clear_Value => 16#0C20#,
Index_Writemask => 16#0C21#,
Color_Clear_Value => 16#0C22#,
Color_Writemask => 16#0C23#,
Index_Mode => 16#0C30#,
Rgba_Mode => 16#0C31#,
Doublebuffer => 16#0C32#,
Stereo => 16#0C33#,
Render_Mode => 16#0C40#,
Perspective_Correction_Hint => 16#0C50#,
Point_Smooth_Hint => 16#0C51#,
Line_Smooth_Hint => 16#0C52#,
Polygon_Smooth_Hint => 16#0C53#,
Fog_Hint => 16#0C54#,
Texture_Gen_S => 16#0C60#,
Texture_Gen_T => 16#0C61#,
Texture_Gen_R => 16#0C62#,
Texture_Gen_Q => 16#0C63#,
Pixel_Map_I_To_I => 16#0C70#,
Pixel_Map_S_To_S => 16#0C71#,
Pixel_Map_I_To_R => 16#0C72#,
Pixel_Map_I_To_G => 16#0C73#,
Pixel_Map_I_To_B => 16#0C74#,
Pixel_Map_I_To_A => 16#0C75#,
Pixel_Map_R_To_R => 16#0C76#,
Pixel_Map_G_To_G => 16#0C77#,
Pixel_Map_B_To_B => 16#0C78#,
Pixel_Map_A_To_A => 16#0C79#,
Pixel_Map_I_To_I_Size => 16#0CB0#,
Pixel_Map_S_To_S_Size => 16#0CB1#,
Pixel_Map_I_To_R_Size => 16#0CB2#,
Pixel_Map_I_To_G_Size => 16#0CB3#,
Pixel_Map_I_To_B_Size => 16#0CB4#,
Pixel_Map_I_To_A_Size => 16#0CB5#,
Pixel_Map_R_To_R_Size => 16#0CB6#,
Pixel_Map_G_To_G_Size => 16#0CB7#,
Pixel_Map_B_To_B_Size => 16#0CB8#,
Pixel_Map_A_To_A_Size => 16#0CB9#,
Unpack_Swap_Bytes => 16#0CF0#,
Unpack_Lsb_First => 16#0CF1#,
Unpack_Row_Length => 16#0CF2#,
Unpack_Skip_Rows => 16#0CF3#,
Unpack_Skip_Pixels => 16#0CF4#,
Unpack_Alignment => 16#0CF5#,
Pack_Swap_Bytes => 16#0D00#,
Pack_Lsb_First => 16#0D01#,
Pack_Row_Length => 16#0D02#,
Pack_Skip_Rows => 16#0D03#,
Pack_Skip_Pixels => 16#0D04#,
Pack_Alignment => 16#0D05#,
Map_Color => 16#0D10#,
Map_Stencil => 16#0D11#,
Index_Shift => 16#0D12#,
Index_Offset => 16#0D13#,
Red_Scale => 16#0D14#,
Red_Bias => 16#0D15#,
Zoom_X => 16#0D16#,
Zoom_Y => 16#0D17#,
Green_Scale => 16#0D18#,
Green_Bias => 16#0D19#,
Blue_Scale => 16#0D1A#,
Blue_Bias => 16#0D1B#,
Alpha_Scale => 16#0D1C#,
Alpha_Bias => 16#0D1D#,
Depth_Scale => 16#0D1E#,
Depth_Bias => 16#0D1F#,
Max_Eval_Order => 16#0D30#,
Max_Lights => 16#0D31#,
Max_Clip_Planes => 16#0D32#,
Max_Texture_Size => 16#0D33#,
Max_Pixel_Map_Table => 16#0D34#,
Max_Attrib_Stack_Depth => 16#0D35#,
Max_Modelview_Stack_Depth => 16#0D36#,
Max_Name_Stack_Depth => 16#0D37#,
Max_Projection_Stack_Depth => 16#0D38#,
Max_Texture_Stack_Depth => 16#0D39#,
Max_Viewport_Dims => 16#0D3A#,
Max_Client_Attrib_Stack_Depth => 16#0D3B#,
Subpixel_Bits => 16#0D50#,
Index_Bits => 16#0D51#,
Red_Bits => 16#0D52#,
Green_Bits => 16#0D53#,
Blue_Bits => 16#0D54#,
Alpha_Bits => 16#0D55#,
Depth_Bits => 16#0D56#,
Stencil_Bits => 16#0D57#,
Accum_Red_Bits => 16#0D58#,
Accum_Green_Bits => 16#0D59#,
Accum_Blue_Bits => 16#0D5A#,
Accum_Alpha_Bits => 16#0D5B#,
Name_Stack_Depth => 16#0D70#,
Auto_Normal => 16#0D80#,
Map1_Color_4 => 16#0D90#,
Map1_Index => 16#0D91#,
Map1_Normal => 16#0D92#,
Map1_Texture_Coord_1 => 16#0D93#,
Map1_Texture_Coord_2 => 16#0D94#,
Map1_Texture_Coord_3 => 16#0D95#,
Map1_Texture_Coord_4 => 16#0D96#,
Map1_Vertex_3 => 16#0D97#,
Map1_Vertex_4 => 16#0D98#,
Map2_Color_4 => 16#0DB0#,
Map2_Index => 16#0DB1#,
Map2_Normal => 16#0DB2#,
Map2_Texture_Coord_1 => 16#0DB3#,
Map2_Texture_Coord_2 => 16#0DB4#,
Map2_Texture_Coord_3 => 16#0DB5#,
Map2_Texture_Coord_4 => 16#0DB6#,
Map2_Vertex_3 => 16#0DB7#,
Map2_Vertex_4 => 16#0DB8#,
Map1_Grid_Domain => 16#0DD0#,
Map1_Grid_Segments => 16#0DD1#,
Map2_Grid_Domain => 16#0DD2#,
Map2_Grid_Segments => 16#0DD3#,
Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Feedback_Buffer_Pointer => 16#0DF0#,
Feedback_Buffer_Size => 16#0DF1#,
Feedback_Buffer_Type => 16#0DF2#,
Selection_Buffer_Pointer => 16#0DF3#,
Selection_Buffer_Size => 16#0DF4#,
Blend_Color => 16#8005#,
Blend_Equation_RGB => 16#8009#,
Pack_Skip_Images => 16#806B#,
Pack_Image_Height => 16#806C#,
Unpack_Skip_Images => 16#806D#,
Unpack_Image_Height => 16#806E#,
Blend_Dst_RGB => 16#80C8#,
Blend_Src_RGB => 16#80C9#,
Blend_Dst_Alpha => 16#80CA#,
Blend_Src_Alpha => 16#80CB#,
Point_Fade_Threshold_Size => 16#8128#,
Light_Model_Color_Control => 16#81F8#,
Major_Version => 16#821B#,
Minor_Version => 16#821C#,
Num_Extensions => 16#821D#,
Debug_Next_Logged_Message_Length => 16#8243#,
Num_Shading_Language_Versions => 16#82E9#,
Current_Fog_Coord => 16#8453#,
Current_Secondary_Color => 16#8459#,
Aliased_Line_Width_Range => 16#846E#,
Active_Texture => 16#84E0#,
Stencil_Back_Func => 16#8800#,
Stencil_Back_Fail => 16#8801#,
Stencil_Back_Pass_Depth_Fail => 16#8802#,
Stencil_Back_Pass_Depth_Pass => 16#8803#,
Blend_Equation_Alpha => 16#883D#,
Query_Result => 16#8866#,
Query_Result_Available => 16#8867#,
Max_Combined_Texture_Image_Units => 16#8B4D#,
Stencil_Back_Ref => 16#8CA3#,
Stencil_Back_Value_Mask => 16#8CA4#,
Stencil_Back_Writemask => 16#8CA5#,
Max_Debug_Message_Length => 16#9143#,
Max_Debug_Logged_Messages => 16#9144#,
Debug_Logged_Messages => 16#9145#,
Max_Framebuffer_Width => 16#9315#,
Max_Framebuffer_Height => 16#9316#,
Max_Framebuffer_Layers => 16#9317#,
Max_Framebuffer_Samples => 16#9318#);
for Parameter'Size use Low_Level.Enum'Size;
type String_Parameter is
(Vendor, Renderer, Version, Extensions, Shading_Language_Version);
for String_Parameter use
(Vendor => 16#1F00#,
Renderer => 16#1F01#,
Version => 16#1F02#,
Extensions => 16#1F03#,
Shading_Language_Version => 16#8B8C#);
for String_Parameter'Size use Low_Level.Enum'Size;
type Renderbuffer_Parameter is (Width, Height, Internal_Format, Red_Size,
Green_Size, Blue_Size, Alpha_Size,
Depth_Size, Stencil_Size);
for Renderbuffer_Parameter use (Width => 16#8D42#,
Height => 16#8D43#,
Internal_Format => 16#8D44#,
Red_Size => 16#8D50#,
Green_Size => 16#8D51#,
Blue_Size => 16#8D52#,
Alpha_Size => 16#8D53#,
Depth_Size => 16#8D54#,
Stencil_Size => 16#8D55#);
for Renderbuffer_Parameter'Size use Low_Level.Enum'Size;
-- declared here so that Max in GL.Enums.Indexes works
function Get_Max (Getter_Param : Parameter) return Types.Int;
end GL.Enums.Getter;
|
reznikmm/matreshka | Ada | 3,768 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2013, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.Constants;
package body Matreshka.ODF_Attributes.FO.Keep_Together is
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant FO_Keep_Together_Node)
return League.Strings.Universal_String is
begin
return ODF.Constants.Keep_Together_Name;
end Get_Local_Name;
end Matreshka.ODF_Attributes.FO.Keep_Together;
|
LiberatorUSA/GUCEF | Ada | 1,379 | adb | package body agar.gui.widget.vbox is
package cbinds is
procedure set_homogenous
(box : vbox_access_t;
homogenous : c.int);
pragma import (c, set_homogenous, "agar_gui_widget_vbox_set_homogenous");
procedure set_padding
(box : vbox_access_t;
padding : c.int);
pragma import (c, set_padding, "agar_gui_widget_vbox_set_padding");
procedure set_spacing
(box : vbox_access_t;
spacing : c.int);
pragma import (c, set_spacing, "agar_gui_widget_vbox_set_spacing");
end cbinds;
procedure set_homogenous
(box : vbox_access_t;
homogenous : boolean := true) is
begin
if homogenous then
cbinds.set_homogenous (box, 1);
else
cbinds.set_homogenous (box, 0);
end if;
end set_homogenous;
procedure set_padding
(box : vbox_access_t;
padding : natural) is
begin
cbinds.set_padding
(box => box,
padding => c.int (padding));
end set_padding;
procedure set_spacing
(box : vbox_access_t;
spacing : natural) is
begin
cbinds.set_spacing
(box => box,
spacing => c.int (spacing));
end set_spacing;
function widget (box : vbox_access_t) return widget_access_t is
begin
return agar.gui.widget.box.widget (box.box'access);
end widget;
end agar.gui.widget.vbox;
|
AdaCore/libadalang | Ada | 74 | adb | pragma Cfg_2;
package body Pkg is
procedure Foo is separate;
end Pkg;
|
charlie5/cBound | Ada | 1,421 | ads | -- This file is generated by SWIG. Please do not modify by hand.
--
with Interfaces.C;
with Interfaces.C;
with Interfaces.C.Pointers;
package xcb.xcb_render_query_filters_cookie_t is
-- Item
--
type Item is record
sequence : aliased Interfaces.C.unsigned;
end record;
-- Item_Array
--
type Item_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_render_query_filters_cookie_t
.Item;
-- Pointer
--
package C_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_render_query_filters_cookie_t.Item,
Element_Array => xcb.xcb_render_query_filters_cookie_t.Item_Array,
Default_Terminator => (others => <>));
subtype Pointer is C_Pointers.Pointer;
-- Pointer_Array
--
type Pointer_Array is
array
(Interfaces.C
.size_t range <>) of aliased xcb.xcb_render_query_filters_cookie_t
.Pointer;
-- Pointer_Pointer
--
package C_Pointer_Pointers is new Interfaces.C.Pointers
(Index => Interfaces.C.size_t,
Element => xcb.xcb_render_query_filters_cookie_t.Pointer,
Element_Array => xcb.xcb_render_query_filters_cookie_t.Pointer_Array,
Default_Terminator => null);
subtype Pointer_Pointer is C_Pointer_Pointers.Pointer;
end xcb.xcb_render_query_filters_cookie_t;
|
reznikmm/matreshka | Ada | 3,985 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with ODF.DOM.Draw_Contrast_Attributes;
package Matreshka.ODF_Draw.Contrast_Attributes is
type Draw_Contrast_Attribute_Node is
new Matreshka.ODF_Draw.Abstract_Draw_Attribute_Node
and ODF.DOM.Draw_Contrast_Attributes.ODF_Draw_Contrast_Attribute
with null record;
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Draw_Contrast_Attribute_Node;
overriding function Get_Local_Name
(Self : not null access constant Draw_Contrast_Attribute_Node)
return League.Strings.Universal_String;
end Matreshka.ODF_Draw.Contrast_Attributes;
|
reznikmm/matreshka | Ada | 3,642 | ads | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Elements.Generic_Hash;
function AMF.UMLDI.UML_Activity_Diagrams.Hash is
new AMF.Elements.Generic_Hash (UMLDI_UML_Activity_Diagram, UMLDI_UML_Activity_Diagram_Access);
|
rogermc2/GA_Ada | Ada | 11,032 | ads | with Interfaces;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Blade;
with Blade_Types; use Blade_Types;
with GA_Maths;
with Metric; use Metric;
package Multivectors is
type Geometry_Type is (Geometry_Not_Set, E1_Geometry, E2_Geometry,
E3_Geometry, H3_Geometry, C3_Geometry);
type MV_Type is (MV_Multivector, MV_Scalar, MV_Vector, MV_Bivector,
MV_Trivector, MV_Rotor, MV_Point, MV_Normalized_Point,
MV_Line, MV_Circle, MV_Sphere, MV_Dual_Line, MV_Dual_Plane,
MV_Dual_Sphere, MV_TR_Versor);
type Grade_Status is (Grade_OK, Grade_Null, Grade_Inhomogeneous);
type Multivector (Type_Of_MV : MV_Type := MV_Multivector) is private;
type Multivector_List is private;
subtype Bivector is Multivector (Type_Of_MV => MV_Bivector);
subtype Circle is Multivector (Type_Of_MV => MV_Circle);
subtype Dual_Line is Multivector (Type_Of_MV => MV_Dual_Line);
subtype Dual_Plane is Multivector (Type_Of_MV => MV_Dual_Plane);
subtype Line is Multivector (Type_Of_MV => MV_Line);
subtype Normalized_Point is Multivector (Type_Of_MV => MV_Normalized_Point);
subtype Rotor is Multivector (Type_Of_MV => MV_Rotor);
subtype Scalar is Multivector (Type_Of_MV => MV_Scalar);
subtype TR_Versor is Multivector (Type_Of_MV => MV_TR_Versor);
subtype M_Vector is Multivector (Type_Of_MV => MV_Vector);
MV_Exception : Exception;
function "+" (MV : Multivector; S : Float) return Multivector;
function "+" (S : Float; MV : Multivector) return Multivector;
function "+" (MV1, MV2 : Multivector) return Multivector;
function "-" (MV : Multivector; S : Float) return Multivector;
function "-" (S : Float; MV : Multivector) return Multivector;
function "-" (MV : Multivector) return Multivector;
function "-" (MV1, MV2 : Multivector) return Multivector;
function "*" (Scale : float; MV : Multivector) return Multivector;
function "*" (MV : Multivector; Scale : float) return Multivector;
function "/" (MV : Multivector; Scale : float) return Multivector;
procedure Add_Blade (MV : in out Multivector; aBlade : Blade.Basis_Blade);
procedure Add_Blade (MV : in out Multivector; Index : E2_Base; Value : Float);
procedure Add_Blade (MV : in out Multivector; Index : E3_Base; Value : Float);
procedure Add_Blade (MV : in out Multivector; Index : C3_Base; Value : Float);
-- procedure Add_Complex_Blade (MV : in out Multivector; Index : C3_Base;
-- Value : GA_Maths.Complex_Types.Complex);
procedure Add_Multivector (MV_List : in out Multivector_List; MV : Multivector);
function Basis_Vector (Index : BV_Base) return M_Vector;
function Basis_Vector (Index : E2_Base) return M_Vector;
function Basis_Vector (Index : E3_Base) return M_Vector;
function Basis_Vector (Index : C3_Base) return M_Vector;
function Blades (MV : Multivector) return Blade.Blade_List;
function Component (MV : Multivector; BM : Interfaces.Unsigned_32)
return Float;
procedure Compress (MV : in out Multivector; Epsilon : Float);
function Cosine (MV : Multivector) return Multivector;
function Cosine (MV : Multivector; Order : Integer) return Multivector;
function Dot (MV1, MV2 : Multivector) return Multivector;
function Dual (MV : Multivector; Met : Metric_Record := C3_Metric)
return Multivector;
function Dual (MV : Multivector; Dim : Integer) return Multivector;
function Exp (MV : Multivector; Met : Metric_Record := C3_Metric;
Order : Integer := 12) return Multivector;
-- function Exp_Dual_Line (DL : Dual_Line; Met : Metric.Metric_Record)
-- return Dual_Line;
function Extract_Grade (MV : Multivector; Index : integer) return Multivector;
function From_Vector (V : M_Vector) return Multivector;
-- function General_Inverse (MV : Multivector) return Multivector;
function General_Inverse (MV : Multivector; Met : Metric_Record := C3_Metric)
return Multivector;
-- function Geometric_Product (MV1, MV2 : Multivector) return Multivector;
function Geometric_Product (MV1, MV2 : Multivector;
Met : Metric_Record := C3_Metric)
return Multivector;
function Geometric_Product (Sc : Float; MV : Multivector) return Multivector;
function Geometric_Product (MV : Multivector; Sc : Float) return Multivector;
-- Get_Basis_Vector returns multivector of the required base.
function Get_Blade (MV : Multivector; Index : Interfaces.Unsigned_32)
return Blade.Basis_Blade;
function Get_Blade (MV : Multivector; theBlade : out Multivector;
Index : Interfaces.Unsigned_32) return Boolean;
function Get_Blade_List (MV : Multivector) return Blade.Blade_List;
function Get_Multivector (MV_List : Multivector_List; Index : Positive)
return Multivector;
function Get_Random_Blade (Dim, Grade : Integer; Scale : Float)
return Multivector;
function Get_Random_Vector (Dim : Integer; Scale : Float) return Multivector;
function Grade (MV : Multivector; theGrade : out Integer) return Grade_Status;
function Grade_Use (MV : Multivector) return GA_Maths.Grade_Usage;
function Grade_Inversion (MV : Multivector) return Multivector;
function Highest_Grade (MV : Multivector) return Integer;
function Inner_Product (MV1, MV2 : Multivector; Cont : Blade.Contraction_Type)
return Multivector;
function Inner_Product (MV1, MV2 : Multivector; Met : Metric_Record;
Cont : Blade.Contraction_Type := Blade.Left_Contraction)
return Multivector;
function Inverse_Scalar (theScalar : Scalar) return Scalar;
function Inverse_Rotor (R : Rotor) return Rotor;
function Is_Null (MV : Multivector) return Boolean;
function Is_Null (MV : Multivector; Epsilon : Float) return Boolean;
function Is_Scalar (MV : Multivector) return Boolean;
function Largest_Basis_Blade (MV : Multivector) return Blade.Basis_Blade;
function Largest_Coordinate (MV : Multivector) return Float;
function Left_Contraction (MV1, MV2 : Multivector) return Multivector;
function Left_Contraction (MV1, MV2 : Multivector; Met : Metric_Record)
return Multivector;
function List_Length (MV_List : Multivector_List) return Integer;
function Multivector_List_String (Blades : Blade.Blade_List;
BV_Names : Blade_Types.Basis_Vector_Names)
return Ada.Strings.Unbounded.Unbounded_String;
function Multivector_String (MV : Multivector;
BV_Names : Blade_Types.Basis_Vector_Names)
return Ada.Strings.Unbounded.Unbounded_String;
function MV_Kind (MV : Multivector) return MV_Type;
function MV_Size (MV : Multivector) return Natural;
function Negate (MV : Multivector) return Multivector;
function New_Bivector (V1, V2 : M_Vector) return Bivector;
function New_Bivector (e1e2, e2e3, e3e1 : Float) return Bivector;
-- New_Multivector returns a multivector with a scalar blade only
function New_Multivector (Scalar_Weight : Float) return Multivector;
function New_Multivector (aBlade : Blade.Basis_Blade) return Multivector;
function New_Multivector (Blades : Blade.Blade_List) return Multivector;
-- function New_Normalized_Point return Normalized_Point;
function New_Normalized_Point (e1, e2, e3 : Float) return Normalized_Point;
-- function New_Rotor return Rotor;
function New_Rotor (Scalar_Weight : Float) return Rotor;
function New_Rotor (Scalar_Weight : Float; BV : Bivector) return Rotor;
function New_Rotor (Scalar_Weight, e1, e2, e3 : Float) return Rotor;
function New_Scalar (Scalar_Weight : Float := 0.0) return Scalar;
function New_TR_Versor (Scalar_Weight : Float := 0.0) return TR_Versor;
function New_Vector (e1, e2 : Float) return M_Vector;
function New_Vector (e1, e2, e3 : Float) return M_Vector;
function Norm_E (MV : Multivector) return Float;
function Norm_Esq (MV : Multivector) return Float;
function Outer_Product (MV1, MV2 : Multivector) return Multivector;
function Random_Blade (Dim, Grade : Integer; Scale : Float) return Multivector;
function Reverse_MV (MV : Multivector) return Multivector;
-- function Rotor_Inverse (R : Rotor; IR : out Rotor) return Boolean;
function Right_Contraction (MV1, MV2 : Multivector) return Multivector;
function Right_Contraction (MV1, MV2 : Multivector;
Met : Metric_Record)
return Multivector;
function Scalar_Part (MV : Multivector) return Float;
-- function Scalar_Product (MV1, MV2 : Multivector) return float;
function Scalar_Product (MV1, MV2 : Multivector;
Met : Metric_Record := C3_Metric) return float;
procedure Set_Geometry (theGeometry : Geometry_Type);
procedure Simplify (MV : in out Multivector);
function Sine (MV : Multivector) return Multivector;
function Sine (MV : Multivector; Order : Integer) return Multivector;
function Space_Dimension return Natural;
function Top_Grade_Index (MV : Multivector) return Integer;
function To_Bivector (R : Rotor) return Bivector;
function To_Circle (MV : Multivector) return Circle;
function To_Dual_Line (MV : Multivector) return Dual_Line;
function To_Dual_Plane (MV : Multivector) return Dual_Plane;
function To_Line (MV : Multivector) return Line;
function To_Normalized_Point (MV : Multivector) return Normalized_Point;
function To_Rotor (MV : Multivector) return Rotor;
function To_TRversor (MV : Multivector) return TR_Versor;
function To_Vector (MV : Multivector) return M_Vector;
function Unit_E (MV : Multivector) return Multivector;
-- function Unit_R (MV : Multivector) return Multivector;
function Unit_R (MV : Multivector; Met : Metric_Record := C3_Metric)
return Multivector;
procedure Update (MV : in out Multivector; Blades : Blade.Blade_List;
Sorted : Boolean := False);
procedure Update_Scalar_Part (MV : in out Multivector; Value : Float);
-- function Versor_Inverse (MV : Multivector) return Multivector;
function Versor_Inverse (MV : Multivector; Met : Metric_Record := C3_Metric)
return Multivector;
private
type Multivector (Type_Of_MV : MV_Type := MV_Multivector) is record
Blades : Blade.Blade_List;
Sorted : Boolean := False;
end record;
package MV_List_Package is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => Multivector);
type Multivector_List is new MV_List_Package.Vector with null Record;
end Multivectors;
|
Letractively/ada-el | Ada | 12,436 | adb | -----------------------------------------------------------------------
-- EL.Expressions -- Expression Language
-- Copyright (C) 2009, 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez ([email protected])
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions.Nodes;
with EL.Expressions.Parser;
with Util.Beans.Objects;
with Util.Concurrent.Counters;
package body EL.Expressions is
-- ------------------------------
-- Check whether the expression is a holds a constant value.
-- ------------------------------
function Is_Constant (Expr : Expression'Class) return Boolean is
begin
return Expr.Node = null;
end Is_Constant;
-- ------------------------------
-- Returns True if the expression is empty (no constant value and no expression).
-- ------------------------------
function Is_Null (Expr : in Expression'Class) return Boolean is
begin
return Expr.Node = null and Util.Beans.Objects.Is_Null (Expr.Value);
end Is_Null;
-- ------------------------------
-- Get the value of the expression using the given expression context.
-- ------------------------------
function Get_Value (Expr : Expression;
Context : ELContext'Class) return Object is
begin
if Expr.Node = null then
return Expr.Value;
end if;
return EL.Expressions.Nodes.Get_Value (Expr.Node.all, Context);
end Get_Value;
-- ------------------------------
-- Get the expression string that was parsed.
-- ------------------------------
function Get_Expression (Expr : in Expression) return String is
begin
return Ada.Strings.Unbounded.To_String (Expr.Expr);
end Get_Expression;
-- ------------------------------
-- Set the value of the expression to the given object value.
-- ------------------------------
procedure Set_Value (Expr : in Value_Expression;
Context : in ELContext'Class;
Value : in Object) is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Value expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
Node.Set_Value (Context, Value);
end;
end Set_Value;
-- ------------------------------
-- Returns true if the expression is read-only.
-- ------------------------------
function Is_Readonly (Expr : in Value_Expression;
Context : in ELContext'Class) return Boolean is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
return True;
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Is_Readonly (Context);
end;
end Is_Readonly;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
Result : Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
if Node /= null then
Result.Node := Node.all'Access;
end if;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
function Reduce_Expression (Expr : in Expression;
Context : in ELContext'Class)
return Expression is
use EL.Expressions.Nodes;
use Ada.Finalization;
begin
if Expr.Node = null then
return Expr;
end if;
declare
Result : constant Reduction := Expr.Node.Reduce (Context);
begin
return Expression '(Controlled with
Node => Result.Node,
Value => Result.Value,
Expr => Expr.Expr);
end;
end Reduce_Expression;
function Create_ValueExpression (Bean : EL.Objects.Object)
return Value_Expression is
Result : Value_Expression;
begin
Result.Value := Bean;
return Result;
end Create_ValueExpression;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- ------------------------------
function Create_Expression (Expr : String;
Context : ELContext'Class)
return Value_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Value_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a value expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Create a Value_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Value_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Value_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a value expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Unchecked_Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
-- ------------------------------
-- Create an EL expression from an object.
-- ------------------------------
function Create_Expression (Bean : in EL.Objects.Object)
return Expression is
Result : Expression;
begin
Result.Value := Bean;
return Result;
end Create_Expression;
overriding
function Reduce_Expression (Expr : Value_Expression;
Context : ELContext'Class)
return Value_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
procedure Adjust (Object : in out Expression) is
begin
if Object.Node /= null then
Util.Concurrent.Counters.Increment (Object.Node.Ref_Counter);
end if;
end Adjust;
procedure Finalize (Object : in out Expression) is
Node : EL.Expressions.Nodes.ELNode_Access;
begin
if Object.Node /= null then
Node := Object.Node.all'Access;
EL.Expressions.Nodes.Delete (Node);
Object.Node := null;
end if;
end Finalize;
-- ------------------------------
-- Evaluate the method expression and return the object and method
-- binding to execute the method. The result contains a pointer
-- to the bean object and a method binding. The method binding
-- contains the information to invoke the method
-- (such as an access to the function or procedure).
-- Raises the <b>Invalid_Method</b> exception if the method
-- cannot be resolved.
-- ------------------------------
function Get_Method_Info (Expr : in Method_Expression;
Context : in ELContext'Class)
return Method_Info is
use EL.Expressions.Nodes;
begin
if Expr.Node = null then
raise Invalid_Expression with "Method expression is empty";
end if;
declare
Node : constant ELValue_Access := ELValue'Class (Expr.Node.all)'Access;
begin
return Node.Get_Method_Info (Context);
end;
end Get_Method_Info;
-- ------------------------------
-- Parse an expression and return its representation ready for evaluation.
-- The context is used to resolve the functions. Variables will be
-- resolved during evaluation of the expression.
-- Raises <b>Invalid_Expression</b> if the expression is invalid.
-- ------------------------------
overriding
function Create_Expression (Expr : in String;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Method_Expression;
Node : EL.Expressions.Nodes.ELNode_Access;
begin
EL.Expressions.Parser.Parse (Expr => Expr, Context => Context, Result => Node);
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
EL.Expressions.Nodes.Delete (Node);
raise Invalid_Expression with "Expression is not a method expression";
end if;
Result.Node := Node.all'Access;
Result.Expr := Ada.Strings.Unbounded.To_Unbounded_String (Expr);
return Result;
end Create_Expression;
-- ------------------------------
-- Reduce the expression by eliminating known variables and computing
-- constant expressions. The result expression is either another
-- expression or a computed constant value.
-- ------------------------------
overriding
function Reduce_Expression (Expr : in Method_Expression;
Context : in EL.Contexts.ELContext'Class)
return Method_Expression is
pragma Unreferenced (Context);
begin
return Expr;
end Reduce_Expression;
-- ------------------------------
-- Create a Method_Expression from an expression.
-- Raises Invalid_Expression if the expression in not an lvalue.
-- ------------------------------
function Create_Expression (Expr : in Expression'Class)
return Method_Expression is
use type EL.Expressions.Nodes.ELNode_Access;
Result : Method_Expression;
Node : constant access EL.Expressions.Nodes.ELNode'Class := Expr.Node;
begin
-- The root of the method expression must be an ELValue node.
if Node = null or else not (Node.all in Nodes.ELValue'Class) then
raise Invalid_Expression with "Expression is not a method expression";
end if;
Util.Concurrent.Counters.Increment (Node.Ref_Counter);
Result.Node := Node.all'Unchecked_Access;
Result.Expr := Expr.Expr;
return Result;
end Create_Expression;
end EL.Expressions;
|
reznikmm/gela | Ada | 10,840 | adb | with Gela.Compilations;
with Gela.Element_Visiters;
with Gela.Elements.Defining_Identifiers;
with Gela.Elements.Function_Bodies;
with Gela.Elements.Function_Declarations;
with Gela.Elements.Parameter_Specifications;
with Gela.Elements.Procedure_Bodies;
with Gela.Elements.Procedure_Declarations;
with Gela.Type_Managers;
package body Gela.Profiles.Names is
-------------------------------
-- Allow_Empty_Argument_List --
-------------------------------
overriding function Allow_Empty_Argument_List
(Self : Profile) return Boolean is
begin
return Self.Empty;
end Allow_Empty_Argument_List;
------------
-- Create --
------------
function Create
(Env : Gela.Semantic_Types.Env_Index;
Name : Gela.Elements.Defining_Names.Defining_Name_Access)
return Gela.Profiles.Profile'Class
is
package Get_Length is
type Visiter is new Gela.Element_Visiters.Visiter with record
Length : Natural := 0;
end record;
procedure Add
(Self : in out Visiter;
List : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Access);
overriding procedure Function_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Bodies.
Function_Body_Access);
overriding procedure Function_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Declarations.
Function_Declaration_Access);
overriding procedure Procedure_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Bodies.
Procedure_Body_Access);
overriding procedure Procedure_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Declarations.
Procedure_Declaration_Access);
end Get_Length;
package body Get_Length is
procedure Add
(Self : in out Visiter;
List : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Access)
is
Cursor : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Cursor := List.First;
begin
while Cursor.Has_Element loop
declare
Param : constant Gela.Elements.Parameter_Specifications.
Parameter_Specification_Access := Cursor.Element;
Names : constant Gela.Elements.Defining_Identifiers.
Defining_Identifier_Sequence_Access := Param.Names;
Pos : Gela.Elements.Defining_Identifiers.
Defining_Identifier_Sequence_Cursor := Names.First;
begin
if not Pos.Has_Element then
Self.Length := Self.Length + 1;
end if;
while Pos.Has_Element loop
Self.Length := Self.Length + 1;
Pos.Next;
end loop;
Cursor.Next;
end;
end loop;
end Add;
overriding procedure Function_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Bodies.
Function_Body_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Function_Body;
overriding procedure Function_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Declarations.
Function_Declaration_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Function_Declaration;
overriding procedure Procedure_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Bodies.
Procedure_Body_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Procedure_Body;
overriding procedure Procedure_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Declarations.
Procedure_Declaration_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Procedure_Declaration;
end Get_Length;
Comp : constant Gela.Compilations.Compilation_Access :=
Name.Enclosing_Compilation;
TM : constant Gela.Type_Managers.Type_Manager_Access :=
Comp.Context.Types;
package Get is
type Visiter is new Gela.Element_Visiters.Visiter with record
Result : access Profile;
Index : Natural := 0;
end record;
procedure Add
(Self : in out Visiter;
List : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Access);
overriding procedure Function_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Bodies.
Function_Body_Access);
overriding procedure Function_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Declarations.
Function_Declaration_Access);
overriding procedure Procedure_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Bodies.
Procedure_Body_Access);
overriding procedure Procedure_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Declarations.
Procedure_Declaration_Access);
end Get;
package body Get is
procedure Add
(Self : in out Visiter;
List : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Access)
is
Cursor : Gela.Elements.Parameter_Specifications.
Parameter_Specification_Sequence_Cursor := List.First;
begin
while Cursor.Has_Element loop
declare
Name : Gela.Elements.Defining_Identifiers.
Defining_Identifier_Access;
Param : constant Gela.Elements.Parameter_Specifications.
Parameter_Specification_Access := Cursor.Element;
Tipe : constant Gela.Semantic_Types.Type_View_Index :=
TM.Type_Of_Object_Declaration
(Env, Gela.Elements.Element_Access (Param));
Names : constant Gela.Elements.Defining_Identifiers.
Defining_Identifier_Sequence_Access := Param.Names;
Pos : Gela.Elements.Defining_Identifiers.
Defining_Identifier_Sequence_Cursor := Names.First;
begin
if not Pos.Has_Element then
Self.Index := Self.Index + 1;
Self.Result.Params (Self.Index).Tipe := TM.Get (Tipe);
end if;
while Pos.Has_Element loop
Name := Pos.Element;
Self.Index := Self.Index + 1;
Self.Result.Params (Self.Index).Name :=
Gela.Elements.Defining_Names.Defining_Name_Access
(Name);
Self.Result.Params (Self.Index).Tipe := TM.Get (Tipe);
Pos.Next;
end loop;
Cursor.Next;
end;
end loop;
end Add;
overriding procedure Function_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Bodies.
Function_Body_Access) is
begin
Self.Add (Node.Parameter_Profile);
Self.Result.Funct := True;
Self.Result.Result :=
TM.Get (TM.Type_From_Subtype_Mark (Env, Node.Result_Subtype));
end Function_Body;
overriding procedure Function_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Function_Declarations.
Function_Declaration_Access) is
begin
Self.Add (Node.Parameter_Profile);
Self.Result.Funct := True;
Self.Result.Result :=
TM.Get (TM.Type_From_Subtype_Mark (Env, Node.Result_Subtype));
end Function_Declaration;
overriding procedure Procedure_Body
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Bodies.
Procedure_Body_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Procedure_Body;
overriding procedure Procedure_Declaration
(Self : in out Visiter;
Node : not null Gela.Elements.Procedure_Declarations.
Procedure_Declaration_Access) is
begin
Self.Add (Node.Parameter_Profile);
end Procedure_Declaration;
end Get;
VL : Get_Length.Visiter;
begin
Name.Enclosing_Element.Visit (VL);
return Result : aliased Profile (VL.Length) do
declare
V : Get.Visiter;
begin
Result.Name := Name;
V.Result := Result'Unchecked_Access;
Name.Enclosing_Element.Visit (V);
Result.Empty := (VL.Length = 0); -- FIXME
end;
end return;
end Create;
-----------------
-- Is_Function --
-----------------
overriding function Is_Function (Self : Profile) return Boolean is
begin
return Self.Funct;
end Is_Function;
------------
-- Length --
------------
overriding function Length (Self : Profile) return Natural is
begin
return Self.Length;
end Length;
-----------------
-- Return_Type --
-----------------
overriding function Return_Type
(Self : Profile) return Gela.Types.Type_View_Access is
begin
return Self.Result;
end Return_Type;
--------------
-- Get_Type --
--------------
overriding function Get_Type
(Self : Profile;
Index : Positive) return Gela.Types.Type_View_Access is
begin
return Self.Params (Index).Tipe;
end Get_Type;
--------------
-- Get_Name --
--------------
overriding function Get_Name
(Self : Profile;
Index : Positive)
return Gela.Elements.Defining_Names.Defining_Name_Access is
begin
return Self.Params (Index).Name;
end Get_Name;
---------------
-- Get_Index --
---------------
overriding function Get_Index
(Self : Profile;
Symbol : Gela.Lexical_Types.Symbol)
return Natural
is
begin
raise Constraint_Error with "Unimplemented function Get_Index";
return 0;
end Get_Index;
end Gela.Profiles.Names;
|
reznikmm/increment | Ada | 6,709 | adb | -- Copyright (c) 2015-2017 Maxim Reznik <[email protected]>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Incr.Nodes.Joints;
package body Incr.Nodes.Ultra_Roots is
-----------
-- Arity --
-----------
overriding function Arity (Self : Ultra_Root) return Natural is
pragma Unreferenced (Self);
begin
return 3;
end Arity;
-----------
-- Child --
-----------
overriding function Child
(Self : Ultra_Root;
Index : Positive;
Time : Version_Trees.Version)
return Node_Access
is
begin
case Index is
when 1 =>
return Node_Access (Self.BOS);
when 2 =>
return Versioned_Nodes.Get (Self.Root, Time);
when 3 =>
return Node_Access (Self.EOS);
when others =>
raise Constraint_Error;
end case;
end Child;
-------------
-- Discard --
-------------
overriding procedure Discard (Self : in out Ultra_Root) is
begin
raise Program_Error with "Unimplemented";
end Discard;
------------
-- Exists --
------------
overriding function Exists
(Self : Ultra_Root;
Time : Version_Trees.Version) return Boolean
is
pragma Unreferenced (Time, Self);
begin
return True;
end Exists;
--------------
-- Get_Flag --
--------------
overriding function Get_Flag
(Self : Ultra_Root;
Flag : Transient_Flags) return Boolean is
pragma Unreferenced (Self, Flag);
begin
return True;
end Get_Flag;
--------------
-- Is_Token --
--------------
overriding function Is_Token (Self : Ultra_Root) return Boolean is
pragma Unreferenced (Self);
begin
return False;
end Is_Token;
----------
-- Kind --
----------
overriding function Kind (Self : Ultra_Root) return Node_Kind is
pragma Unreferenced (Self);
begin
return 0;
end Kind;
-------------------
-- Local_Changes --
-------------------
overriding function Local_Changes
(Self : Ultra_Root;
From : Version_Trees.Version;
To : Version_Trees.Version) return Boolean
is
use type Version_Trees.Version;
Next : Version_Trees.Version := To;
Prev : Version_Trees.Version;
begin
loop
Prev := Self.Document.History.Parent (Next);
if Self.Child (2, Prev) /= Self.Child (2, Next) then
return True;
end if;
exit when From = Prev;
Next := Prev;
end loop;
return False;
end Local_Changes;
-------------------
-- Nested_Errors --
-------------------
overriding function Nested_Errors
(Self : Ultra_Root;
Time : Version_Trees.Version) return Boolean
is
Child : Nodes.Node_Access;
begin
for J in 1 .. 3 loop
Child := Self.Child (J, Time);
if Child /= null then
if Child.Local_Errors (Time) or Child.Nested_Errors (Time) then
return True;
end if;
end if;
end loop;
return False;
end Nested_Errors;
--------------------
-- Nested_Changes --
--------------------
overriding function Nested_Changes
(Self : Ultra_Root;
From : Version_Trees.Version;
To : Version_Trees.Version) return Boolean
is
pragma Unreferenced (Self, From, To);
begin
return True;
end Nested_Changes;
---------------
-- On_Commit --
---------------
overriding procedure On_Commit
(Self : in out Ultra_Root;
Parent : Node_Access)
is
Root : constant Node_Access :=
Versioned_Nodes.Get (Self.Root, Self.Document.History.Changing);
begin
pragma Assert (Parent = null);
Mark_Deleted_Children (Self);
Self.BOS.On_Commit (Self'Unchecked_Access);
if Root /= null then
Root.On_Commit (Self'Unchecked_Access);
end if;
Self.EOS.On_Commit (Self'Unchecked_Access);
end On_Commit;
------------
-- Parent --
------------
overriding function Parent
(Self : Ultra_Root;
Time : Version_Trees.Version) return Node_Access
is
pragma Unreferenced (Self, Time);
begin
return null;
end Parent;
---------------
-- Set_Child --
---------------
overriding procedure Set_Child
(Self : aliased in out Ultra_Root;
Index : Positive;
Value : Node_Access)
is
Now : constant Version_Trees.Version := Self.Document.History.Changing;
Old : constant Node_Access := Self.Child (Index, Now);
Ignore : Integer := 0;
begin
if Index /= 2 then
raise Constraint_Error;
elsif Old /= null then
Old.Set_Parent (null);
end if;
Versioned_Nodes.Set (Self.Root, Value, Now, Ignore);
if Value /= null then
Value.Set_Parent (Self'Unchecked_Access);
end if;
end Set_Child;
----------
-- Span --
----------
overriding function Span
(Self : aliased in out Ultra_Root;
Kind : Span_Kinds;
Time : Version_Trees.Version) return Natural
is
Root_Span : constant Natural := Self.Child (2, Time).Span (Kind, Time);
begin
case Kind is
when Text_Length =>
return Root_Span + 1; -- including end_of_stream character
when Token_Count =>
return Root_Span + 2; -- including sentinel tokens
when Line_Count =>
return Root_Span + 1; -- including end_of_stream character
end case;
end Span;
------------------
-- Constructors --
------------------
package body Constructors is
----------------
-- Initialize --
----------------
procedure Initialize
(Self : out Ultra_Root'Class;
Root : Nodes.Node_Access) is
begin
Self.BOS := new Nodes.Tokens.Token (Self.Document);
Nodes.Tokens.Constructors.Initialize_Ancient
(Self => Self.BOS.all,
Parent => Self'Unchecked_Access,
Back => 0);
Self.EOS := new Nodes.Tokens.Token (Self.Document);
Nodes.Tokens.Constructors.Initialize_Ancient
(Self => Self.EOS.all,
Parent => Self'Unchecked_Access,
Back => 1);
if Root /= null then
Nodes.Joints.Constructors.Initialize_Ancient
(Self => Nodes.Joints.Joint (Root.all),
Parent => Self'Unchecked_Access);
end if;
Versioned_Nodes.Initialize (Self.Root, Root);
end Initialize;
end Constructors;
end Incr.Nodes.Ultra_Roots;
|
BrickBot/Bound-T-H8-300 | Ada | 44,654 | ads | -- Flow.Computation (decl)
--
-- The computation performed by a subprogram is modelled by arithmetic
-- effects and conditions attached to the elements of the flow-graph of
-- the subprogram. During analysis, the computation model may be
-- refined or modified in various ways, probably depending on context
-- and stage of analysis.
--
-- A "computation model" based on a flow-graph G is a data structure
-- that attaches
--
-- > an Arithmetic.Effect_T to each step in G,
--
-- > an Arithmetic.Condition_T to each (step) edge in G,
--
-- > a feasibility (true or false) to each step and step-edge in G,
--
-- > a Calling.Protocol_T to each call in G, and
--
-- > a flag showing which calls in G can return to G.
--
-- Thus, a computation model is similar to the functions Flow.Effect (Step)
-- and Flow.Condition (Edge) which return the "primitive" arithmetic
-- effects and edge preconditions as defined when the flow graph was built,
-- plus the function Programs.Protocol that returns the "primitive"
-- calling protocol of a call as defined when the call was added to the
-- flow graph.
--
-- However, a Flow.Computation.Model_T is separate from the flow-graph
-- and thus there can be many such models and they can be created and
-- destroyed without impact on the flow-graph.
--
-- For convenience and consistency, a computation model also contains
-- references to the subprogram and flow-graph to which the model applies.
--
-- Finally, a computation model may contain further processor-specific
-- information, for use in processor-specific analyses.
--
-- A component of the Bound-T Worst-Case Execution Time Tool.
--
-------------------------------------------------------------------------------
-- Copyright (c) 1999 .. 2015 Tidorum Ltd
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- This software is provided by the copyright holders and contributors "as is" and
-- any express or implied warranties, including, but not limited to, the implied
-- warranties of merchantability and fitness for a particular purpose are
-- disclaimed. In no event shall the copyright owner or contributors be liable for
-- any direct, indirect, incidental, special, exemplary, or consequential damages
-- (including, but not limited to, procurement of substitute goods or services;
-- loss of use, data, or profits; or business interruption) however caused and
-- on any theory of liability, whether in contract, strict liability, or tort
-- (including negligence or otherwise) arising in any way out of the use of this
-- software, even if advised of the possibility of such damage.
--
-- Other modules (files) of this software composition should contain their
-- own copyright statements, which may have different copyright and usage
-- conditions. The above conditions apply to this file.
-------------------------------------------------------------------------------
--
-- $Revision: 1.20 $
-- $Date: 2015/10/24 19:36:48 $
--
-- $Log: flow-computation.ads,v $
-- Revision 1.20 2015/10/24 19:36:48 niklas
-- Moved to free licence.
--
-- Revision 1.19 2015/05/22 06:31:53 niklas
-- Added Model_T.Proc_Info, processor-specific information.
--
-- Revision 1.18 2011-09-06 17:50:00 niklas
-- Added Is_Final (Node_T, ..) for help with ALF export.
--
-- Revision 1.17 2008-04-22 12:40:42 niklas
-- Added Mark_Infeasible for a node edge.
--
-- Revision 1.16 2008/02/18 12:58:27 niklas
-- Added functions Final_Nodes and Successors (return Node_List_T)
-- for use in SPARC RW-trap analysis.
--
-- Revision 1.15 2007/12/17 13:54:36 niklas
-- BT-CH-0098: Assertions on stack usage and final stack height, etc.
--
-- Revision 1.14 2007/10/26 12:44:35 niklas
-- BT-CH-0091: Reanalyse a boundable edge only if its domain grows.
--
-- Revision 1.13 2007/10/02 20:49:22 niklas
-- Added Unresolved_Dynamic_Edges_From (Step, Model).
--
-- Revision 1.12 2007/08/06 09:21:31 niklas
-- Added Model_T.Index : Model_Index_T.
--
-- Revision 1.11 2007/04/18 18:34:38 niklas
-- BT-CH-0057.
--
-- Revision 1.10 2007/03/29 15:18:01 niklas
-- BT-CH-0056.
--
-- Revision 1.9 2007/01/13 13:51:03 niklas
-- BT-CH-0041.
--
-- Revision 1.8 2006/11/26 22:07:26 niklas
-- BT-CH-0039.
--
-- Revision 1.7 2006/10/24 08:44:31 niklas
-- BT-CH-0028.
--
-- Revision 1.6 2005/09/20 09:50:45 niklas
-- Added Mark_Infeasible (Loop).
--
-- Revision 1.5 2005/09/12 19:02:59 niklas
-- BT-CH-0008.
--
-- Revision 1.4 2005/06/29 19:35:55 niklas
-- Added Exit_Edges.
--
-- Revision 1.3 2005/05/09 15:28:17 niklas
-- Added the functions Feasible (Steps), Number_Into (Step), Final_Steps,
-- Successors (Step) and Total_Defining_Assignments, all to support
-- value-origin analysis.
--
-- Revision 1.2 2005/02/23 09:05:18 niklas
-- BT-CH-0005.
--
-- Revision 1.1 2005/02/16 21:11:43 niklas
-- BT-CH-0002.
--
--:dbpool with GNAT.Debug_Pools;
with Calling;
with Loops;
with Processor.Computation;
with Programs;
package Flow.Computation is
--
--- Models of computation over a flow-graph
--
subtype Model_Index_T is Positive;
--
-- A number that identifies a particular computation model (object).
type Effects_T is
array (Step_Index_T range <>) of Arithmetic.Effect_Ref;
--
-- An arithmetic effect for each step in a flow-graph.
type Feasibility_T is
array (Step_Index_T range <>) of Boolean;
--
-- A feasibility flag for each step in a flow-graph.
type Conditions_T is
array (Step_Edge_Index_T range <>) of Arithmetic.Condition_T;
--
-- An arithmetic precondition for each (step) edge in a flow-graph.
-- The precondition for a node edge is implicitly taken as the
-- precondition of the corresponding step edge.
type Protocols_T is
array (Programs.Call_Index_T range <>) of Calling.Protocol_Ref;
--
-- A calling protocol for each call in a flow-graph.
type Call_Set_T is array (Programs.Call_Index_T range <>) of Boolean;
--
-- A subset of the calls in the model.
-- Members are marked by True values.
type Model_T (
Steps : Step_Index_T;
Edges : Step_Edge_Count_T;
Calls : Natural)
is record
Index : Model_Index_T;
References : Natural := 0;
Clean : Boolean := True;
Subprogram : Programs.Subprogram_T;
Graph : Graph_T;
Pruned : Boolean := True;
Proc_Info : Processor.Computation.Info_T;
Effect : Effects_T (1 .. Steps);
Feasible : Feasibility_T (1 .. Steps);
Condition : Conditions_T (1 .. Edges);
Protocol : Protocols_T (1 .. Calls);
New_Proto : Call_Set_T (1 .. Calls);
Returns : Call_Set_T (1 .. Calls);
end record;
--
-- A model of the arithmetic computations and conditions and the
-- parameter-passing protocols in a flow-graph that has the given
-- number of Steps, (step) Edges and Calls to callees.
--
-- Steps
-- The number of steps in the graph (= the highest step index).
-- Edges
-- The number of step-edges in the graph.
-- Calls
-- The number of calls (call steps) in the graph.
-- Index
-- A number that identifies this Model_T object uniquely (for
-- models allocated from the heap, that is).
-- References
-- The number of references (Model_Ref, see below) to this
-- computation model object.
-- Clean
-- Whether the model is "clean", that is, it has no record
-- or memory of changed model elements.
-- Subprogram
-- The subprogram on which this model is based.
-- Note that Subprogram_T is a reference type.
-- Graph
-- The graph on which this model is based.
-- Note that Graph_T is a reference type.
-- Pruned
-- Whether the model has been "pruned", that is, whether the
-- feasibility or infeasibility has been propagated over the
-- Graph since some part was last marked as infeasible.
-- Proc_Info
-- Processor-specific information, generated and used by
-- processor-specific analyses of the computation model.
-- TBD if and how changes to Proc_Info are considered in
-- the copy-on-write management and reference counts.
-- Effect
-- The arithmetic effects attached to the steps in the model.
-- Feasible
-- Whether a step is feasible (True) or infeasible (False).
-- Condition
-- The arithmetic preconditions attached to the step-edges
-- in the model.
-- As usual, this is a necessary precondition for flow along
-- the edge, but not necessarily a sufficient one.
-- The edge is infeasible iff Condition is Arithmetic.Never.
-- Protocol
-- The calling protocol (parameter-passing map) used by the
-- calls in the model, indexed by Programs.Call_Index_T.
-- New_Proto
-- The subset of calls for which a new Protocol has been set,
-- since we last marked the model as "clean".
-- Returns
-- The subset of calls that can return to the caller.
--
-- A Model_T does not "own" the effects, assignments, expressions,
-- conditions and protocols to which it refers via Effect, Condition
-- Protocol; it may (and usually does) refer to effects etc. constructed
-- for other purposes (eg. the primitive objects created when the
-- flow-graph was built).
type Model_Ref is limited private;
--
-- A reference to a heap-allocated computation model. We handle
-- computation models by reference for two reasons:
--
-- > The same model may be reused in different contexts for the
-- same subprogram. Reuse by reference saves memory and time.
--
-- > Heap allocation can be preferred to stack allocation for large
-- graphs, where stack size could be a limiting factor.
--
-- Computation models are reference-counted to support copy-on-change
-- and memory reclamation when references are discarded. However, we
-- do not (yet) use controlled types for this.
--
-- Copy-on-change means that when we change a computation model
-- through a Model_Ref, and there are other Model_Refs to the same
-- model object, the model object is copied, the change is made in
-- the copy, and the Model_Ref is changed to refer to the copy.
-- The original (multiply referenced) computation model is not
-- changed. Any computation model with more than one reference is
-- immutable.
--
-- Memory reclamation means that when a Memory_Ref is Discarded,
-- the referenced computation model object is deallocated if this
-- was the last reference to the object.
--
-- Computation models record some of the changes that are made
-- to them, which is useful when updates to the model or to some
-- data derived from the model can be done incrementally, only
-- for the changed parts of the model. Changes are recorded from
-- the creation of the model. To forget old changes and start
-- recording a new batch of changes a client calls the operation
-- that marks the model as "clean".
type Model_Handle_T is access all Model_Ref;
--
-- A reference to a reference to a heap-allocated computation model.
-- This double-reference is useful when a data structure contains an
-- attribute of type Model_Ref, but this attribute is not public and
-- must be used via a query function, and yet we should be able to
-- update the model using copy-on-change. In such cases, the query
-- function returns a Model_Handle_T which means that its .all can
-- be associated with in-out parameters.
function Model (Ref : Model_Ref) return Model_T;
--
-- The computation model to which Ref refers.
-- This function is provided for completeness, but it is usually
-- more sensible to access parts of the model directly through the
-- reference, rather than make a whole copy as here.
function Is_Null (Model : Model_Ref) return Boolean;
--
-- Whether the Model reference is null, that is, refers to no
-- computation model. The default initial value of any Model_Ref
-- variable is the null reference.
procedure Discard (Model : in out Model_Ref);
--
-- Discards the Model reference and returns a null reference in Model.
-- If Model was the last active reference to the computation model
-- object, the object is deallocated (removed from the heap).
-- However, the parts of the computation model (effects, conditions,
-- calling protocols) are not deallocated (they may be used by
-- reference from other computation models).
procedure Refer (
From : in out Model_Ref;
To : in Model_Ref);
--
-- Changes the From reference to refer to the same computation
-- model as the To reference, as in "From := To". First, however,
-- the procedure Discards the old value of From (if it is not the
-- same as To already).
function Primitive_Model (Subprogram : Programs.Subprogram_T)
return Model_T;
--
-- The primitive computation model that is built into the flow-graph
-- for the given Subprogram. In this model:
--
-- > The step effects are those assigned by the Decoder.
-- > The edge conditions are those assigned by the Decoder
-- except for edges from non-returning calls, see below.
-- > All steps are marked "feasible" except the call-steps for
-- callees that are marked "unused"; those call-steps are
-- marked "infeasible".
-- > The calling protocols are those assigned by the Decoder.
-- > All calls are marked as returning or not returning,
-- depending on Programs.Returns (callee). All edges leaving
-- non-returning calls are marked "infeasible".
--
-- The fact that most steps are marked "feasible" will normally be
-- consistent with the feasibility of the edges, because the
-- Decoder should never add an explicitly infeasible edge to the
-- flow-graph (that is, the Cond parameter in Add_Edge should not
-- be Arithmetic.Never). However, the Decoder may (and normally
-- should) add call-steps to "unused" subprograms, although these
-- calls are also "unused".
--
-- The Subprogram also defines the set of calls for which the model
-- defines calling protocols. The primitive model (usually) does not
-- define the effects of call steps. To indicate that these effects are
-- absent, the resulting Model considers all calls to have a changed
-- calling protocol. Thus, the Model is "clean" only if there are
-- no feasible calls from the Subprogram.
--
-- The result has References = 0.
procedure Refer_To_Primitive_Model (
Subprogram : in Programs.Subprogram_T;
Model : in out Model_Ref);
--
-- Sets Model to refer to the primitive computation model that is
-- built into the flow-graph for the given Subprogram, after Discarding
-- the old (in) value of Model. See the function Primitive_Model for
-- a description of this model.
--
-- The Subprogram also defines the set of calls for which the Model
-- defines calling protocols. The primitive model (usually) does not
-- define the effects of call steps. To indicate that these effects are
-- absent, the resulting Model considers all calls to have a changed
-- calling protocol. Thus, the Model is "clean" only if there are
-- no feasible calls from the Subprogram.
--
-- The result may or may not be the only reference to the primitive
-- computation model.
function Changed (Model : in Model_Ref) return Boolean;
--
-- Whether the Model has as record or memory that some parts
-- of it have been changed since it was last marked "clean".
procedure Mark_Clean (Model : in Model_Ref);
--
-- Erases the record of changes to the Model and marks the
-- Model as "clean".
--
--- Properties of models
--
function Subprogram (Model : Model_Ref) return Programs.Subprogram_T;
--
-- The subprogram to which the Model applies.
function Program (Model : Model_Ref) return Programs.Program_T;
--
-- The program that contains the subprogram to which the Model applies.
-- Same as Programs.Program (Subprogram.Model).
function Graph (Under : Model_Ref) return Graph_T;
--
-- The flow-graph that lies Under the given model.
function Max_Step (Within : Model_Ref) return Step_Index_T;
--
-- Same as Max_Step (Graph (Within)).
function Effect (Step : Step_Index_T; Under : Model_Ref)
return Arithmetic.Effect_Ref;
--
-- The arithmetic effect of the Step with the given index,
-- Under the given model.
function Effect (Step : Step_T; Under : Model_Ref)
return Arithmetic.Effect_Ref;
--
-- Short for Effect (Index (Step), Under).
function Effect (Step : Step_T; Under : Model_Ref)
return Arithmetic.Effect_T;
--
-- Short for Effect (Index (Step), Under).all.
function Condition (Edge : Step_Edge_T; Under : Model_Ref)
return Arithmetic.Condition_T;
--
-- The precondition (necessary but perhaps not sufficient) for
-- executing the Edge, Under the given Model.
function Condition (Edge : Edge_T; Under : Model_Ref)
return Arithmetic.Condition_T;
--
-- The precondition (necessary but perhaps not sufficient) for
-- executing the Edge, Under the given Model.
function Is_Feasible (Model : Model_Ref) return Boolean;
--
-- Whether the whole Model is feasible, which is equivalent to
-- the feasibility of the entry step of the underlying graph
-- (assuming that feasibility has been propagated consistently).
function Is_Feasible (Step : Step_Index_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Step with the given index is feasible (can be
-- executed) Under this model.
function Is_Feasible (Step : Step_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Step is feasible (can be executed) Under this model.
function Is_Feasible (Edge : Step_Edge_Index_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Edge with the given index is feasible (can be
-- executed) Under this model.
function Is_Feasible (Edge : Step_Edge_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Edge is feasible (can be executed) Under this model.
function Is_Feasible (Node : Node_Index_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Node of the given index is feasible under this Model.
-- This is so if the first step of the Node is feasible.
function Is_Feasible (Node : Node_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Node is feasible under this Model.
-- This is so if the first step of the Node is feasible.
function Is_Feasible (Edge : Edge_Index_T; Under : Model_Ref)
return Boolean;
--
-- Whether the (node) Edge of the given index is feasible Under
-- this model.
-- This is equivalent to Is_Feasible (Step_Edge (Edge), Under).
function Is_Feasible (Edge : Edge_T; Under : Model_Ref)
return Boolean;
--
-- Whether the (node) Edge is feasible (can be executed) Under
-- this model.
-- This is equivalent to Is_Feasible (Step_Edge (Edge), Under).
function Some_Feasible (Edges : Edge_List_T; Under : Model_Ref)
return Boolean;
--
-- Whether at least one of the (node) Edges is feasible Under
-- this model.
--
-- If the Edges list is empty, the function returns False.
function Is_Feasible (Call : Programs.Call_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Call is feasible Under this model.
-- This is so if the call-step is feasible Under the model and
-- the Call itself is feasible on the universal level.
--
-- Precondition: Caller(Call) = Subprogram (Under).
function Is_Feasible (Luup : Loops.Loop_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Luup is feasible Under this model.
-- This is so if the head-step of the loop is feasible Under
-- the model.
function Is_Eternal (Luup : Loops.Loop_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Luup is eternal Under this model.
-- This is so if the Luup is eternal (has no exit edges) in the
-- underlying flow-graph or if all the exit edges are infeasible
-- Under the model.
function Is_Repeatable (Luup : Loops.Loop_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Luup can be repeated under this Model.
-- This is so if the Luup has some repeat edges that are feasible
-- Under the model. Otherwise (not repeatable) the Luup is not
-- really a loop Under this model, but just an acyclic part of
-- the flow-graph that is the ghost of a loop.
function Target_Range (Step : Step_T; Under : Model_Ref)
return Storage.Alias_Range_T;
--
-- The alias range that can be reached by the assignments in the
-- step's effect Under the given computation model.
function Calling_Protocol (
Call_Index : Programs.Call_Index_T;
Under : Model_Ref)
return Calling.Protocol_Ref;
--
-- The calling protocol (parameter-passing map) used by the call
-- with the given Call_Indexndex, Under the given computation model.
function Calling_Protocol (
Call : Programs.Call_T;
Under : Model_Ref)
return Calling.Protocol_Ref;
--
-- The calling protocol (parameter-passing map) used by the
-- given Call, Under the given computation model.
function Calling_Protocol_Is_Static (
Call : Programs.Call_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the calling protocol (parameter-passing map) used by the
-- given Call, Under the given computation model, is static in the
-- sense that it does not depend on any cells with unknown or too
-- weakly bounded values. For a static protocol, the map between
-- actual (caller) and formal (callee) parameters is known.
function Calling_Protocol_Changed (
Call : Programs.Call_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the calling protocol (parameter-passing map) used by
-- the given Call, Under the given computation model, has been
-- changed (with Set_Calling_Protocol) since the model was last
-- marked "clean".
function Returns (
Call : Programs.Call_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the given Call returns to the caller, Under the
-- given computation model. (To find out if a call returns
-- requires analysis of the callee, perhaps in a context derived
-- from this model, but here we just return the information
-- recorded in the model by Mark_No_Return.).
--
-- The feasible parts of a model, and their properties
--
-- The following functions are similar to like-named functions in the
-- Flow, Loops and Programs packages, but consider only those parts of
-- the underlying flow-graph or subprogram that are feasible under a
-- given model.
function Feasible (Steps : Step_List_T; Under : Model_Ref)
return Step_List_T;
--
-- Those Steps that are feasible Under the given model.
function Edges_Into (Step : Step_T; Under : Model_Ref)
return Step_Edge_List_T;
--
-- All the feasible edges that enter the step (Edge.Target = Step).
-- Loose edges are not included.
-- Precondition: the Step itself is feasible.
function Edges_From (Step : Step_T; Under : Model_Ref)
return Step_Edge_List_T;
--
-- All the feasible edges that leave the step (Edge.Source = Step).
-- Loose edges are not included.
-- Precondition: the Step itself is feasible.
function Number_Into (Step : Step_T; Under : Model_Ref)
return Natural;
--
-- The number of feasible edges that enter the step (Edge.Target = Step).
-- Loose edges are not included.
-- Precondition: the Step itself is feasible.
function Is_Final (Step : Step_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Step is a final step (a return from the subprogram)
-- Under the given model. In other words, whether the step has no
-- feasible leaving edges: Edges_From (Step, Under)'Length = 0.
function Final_Steps (Under : Model_Ref)
return Step_List_T;
--
-- The feasible final (return) steps of the graph, which are those
-- feasible steps that have no leaving edges. Note that a step for
-- which all leaving edges are infeasible does _not_ become a final
-- step, it becomes an infeasible step.
function Is_Final (Node : Node_T; Under : Model_Ref)
return Boolean;
--
-- Whether the Node is a final node (the last step in the Node is
-- a return from the subprogram) Under the given model. In other
-- words, whether the Node has no feasible leaving edges:
-- Edges_From (Node, Under)'Length = 0.
function Final_Nodes (Under : Model_Ref)
return Node_List_T;
--
-- The Final nodes, in other words, the nodes that contain
-- the Final_Steps.
function Returns (Under : Model_Ref) return Boolean;
--
-- Whether there are some feasible final (return) steps of the
-- graph, Under the given model.
function Non_Returning_Call_Steps (Under : Model_Ref)
return Step_List_T;
--
-- The call-steps that are feasible Under the given model but
-- do not return to the caller Under this model.
function Predecessors (Step : Step_T; Under : Model_Ref)
return Step_List_T;
--
-- All the feasible predecessors of the given Step, Under the
-- given model. In other words, all the steps from which there is
-- a feasible edge to the given Step.
function Successors (Step : Step_T; Under : Model_Ref)
return Step_List_T;
--
-- All the feasible successors of the given Step, Under the
-- given model. In other words, all the steps to which there is
-- a feasible edge from the given Step.
function Edges_Into (Node : Node_T; Under : Model_Ref)
return Edge_List_T;
--
-- All the feasible edges that enter the Node (Edge.Target = Node).
-- Loose edges are not included.
-- Precondition: the Node itself is feasible.
function Number_From (Node : Node_T; Under : Model_Ref)
return Natural;
--
-- The number of edges leaving the Node that are feasible Under the
-- given model.
function Edges_From (Node : Node_T; Under : Model_Ref)
return Edge_List_T;
--
-- All the feasible edges that leave the Node (Edge.Source = Node).
-- Loose edges are not included.
-- Precondition: the Node itself is feasible.
function Successors (Node : Node_T; Under : Model_Ref)
return Node_List_T;
--
-- All the feasible successors of the given Node, Under the
-- given model. In other words, all the nodes to which there is
-- a feasible edge from the given Node.
function Is_Feasible (Edge : Dynamic_Edge_T; Under : Model_Ref)
return Boolean;
--
-- Whether the dynamic Edge is feasible Under the given computation
-- model. This is defined by the feasibility of the Edge's source
-- step Under the model.
function Dynamic_Edges (Under : Model_Ref)
return Dynamic_Edge_List_T;
--
-- All the feasible dynamic edges in the graph Under the given model.
-- A dynamic edge is considered feasible iff the source step is
-- feasible. This does not necessarily mean that the dynamic edge
-- can spawn new feasible real edges.
function Unstable_Dynamic_Edges (Under : Model_Ref)
return Dynamic_Edge_List_T;
--
-- All those feasible dynamic edges in the graph, Under the given
-- model, that are not yet stably resolved (or stably unresolved).
-- A dynamic edge is considered feasible iff the source step is
-- feasible. A dynamic edge is considered unstable if the domain of
-- the edge has grown since the last analysis of the edge. (At this
-- point, such an edge will be in the Unresolved state, thanks to
-- Flow.Find_Unstable_Dynamic_Edges, but not all Unresolved edges
-- are unstable.) This does not necessarily mean that the dynamic
-- edge can spawn new feasible real edges.
function Unstable_Dynamic_Edges_From (
Source : Step_T;
Under : Model_Ref)
return Dynamic_Edge_List_T;
--
-- All those feasible and dynamic edges from the Source step, Under
-- the given model, that are not yet stably resolved (or stably
-- unresolved). A dynamic edge is considered feasible iff the Source
-- step is feasible. A dynamic edge is considered unstable if the domain
-- of the edge has grown since the last analysis of the edge. (At this
-- point, such an edge will be in the Unresolved state, thanks to
-- Flow.Find_Unstable_Dynamic_Edges, but not all Unresolved edges
-- are unstable.) This does not necessarily mean that the dynamic
-- edge can spawn new feasible real edges.
function Dynamic_Flow (Under : Model_Ref) return Edge_Resolution_T;
--
-- The overall state of resolution of the feasible dynamic edges
-- Under the given model. The three possible values are:
--
-- Growing if there is at least one feasible Growing edge.
-- Unresolved if there is at least one feasible Unresolved edge
-- and no feasible Growing edge.
-- Stable if all feasible dynamic edges are Stable or there
-- are no feasible dynamic edges at all.
--
-- A Growing result indicates that the flow-graph is still growing,
-- as a result of resolving dynamic edges. The flow-graph should be
-- elaborated by following its loose edges, decoding new instructions
-- and adding steps and edges until there are no more loose edges.
--
-- A Stable result indicates that the dynamic control flow has been
-- resolved to a consistent state that seems complete. The remaining
-- dynamic edges can be removed to leave a completed, static flow-graph.
--
-- An Unresolved result indicates that the dynamic control flow has
-- been resolved to a consistent state, although the bounds used
-- so far have been too weak to resolve all dynamic edges. If better
-- bounds are not available, the remaining dynamic edges can be
-- removed to leave a static flow-graph but the graph is probably
-- incomplete because of the Unresolved dynamic edges.
function Loops_Of (Model : Model_Ref)
return Loops.Loop_List_T;
--
-- All the loops within Subprogram (Model) that are feasible under
-- this Model and still exist (are repeatable) under this Model.
--
-- Note that the function returns a Loop_List_T, not a Loops.Loops_T.
-- Thus, some of the loops in the flow-graph may be omitted (if they
-- are infeasible or unrepeatable under this Model) and the indices
-- in the returned list are not the Loops.Loop_Index_T's of the loops.
-- However, the list is still in order of increasing Loop_Index_T and
-- thus has inner loops before the outer loops that contain them.
--
-- When all exit-edges of a loop are infeasible under the Model the
-- loop will appear as an eternal loop in the result, even for the
-- function Loops.Eternal.
function Feasible (Edges : Edge_List_T; Under : Model_Ref)
return Edge_List_T;
--
-- Those Edges that are feasible Under the given model.
function Entry_Edges (
Luup : Loops.Loop_T;
Under : Model_Ref)
return Flow.Edge_List_T;
--
-- Those entry edges of the Luup that are feasible Under the given
-- model.
function Neck_Edges (
Luup : Loops.Loop_T;
Under : Model_Ref)
return Flow.Edge_List_T;
--
-- Those neck edges of the Luup that are feasible Under the given
-- model.
function Repeat_Edges (
Luup : Loops.Loop_T;
Under : Model_Ref)
return Flow.Edge_List_T;
--
-- Those repeat edges of the Luup that are feasible Under the given
-- model.
function Exit_Edges (
Luup : Loops.Loop_T;
Under : Model_Ref)
return Flow.Edge_List_T;
--
-- Those exit edges of the Luup that are feasible Under the given
-- model.
function Cells_In (
Model : Model_Ref;
Calls : Boolean)
return Storage.Cell_Set_T;
--
-- All the cells (statically) named in the computation Model,
-- including cells used in arithmetic expressions or edge
-- conditions and target cells of assignments. However, only
-- the feasible parts of the model are considered. The cells
-- included are:
--
-- > cells used or defined in the effect of steps, including basis
-- cells for dynamic memory references; however, the effect of
-- call steps is included only if Calls is True,
--
-- > cells used in the preconditions of edges, including basis
-- cells for dynamic memory references,
--
-- > basis cells for dynamic edges, and
--
-- > basis cells for dynamic calling protocols.
--
-- Output cells from calls are included only when Calls is True and
-- only so far as they are given in the effects of the call steps.
-- Input cells to calls are omitted.
function Is_Defined (
Cell : Storage.Cell_T;
By : Step_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the given Cell is defined (assigned) By the effect of
-- the given step, Under the given computation model.
--
-- This is true iff the step is feasible and the Cell is the (static)
-- target of an assignment in the effect of the step. Aliasing is
-- not counted.
function Cells_Defined (By : Model_Ref) return Storage.Cell_Set_T;
--
-- The set of storage cells that are written (assigned) By the
-- feasible assignments in the given model.
--
-- Cells written by callees are included so far as they are
-- given in the effects of the call steps.
function Steps_Defining (Cell : Storage.Cell_T; Under : Model_Ref)
return Step_List_T;
--
-- All the feasible steps in the flow-graph that define (assign)
-- the given Cell, Under the given model.
--
-- A call that defines the Cell is included if this definition is
-- given in the effect of the call step.
function Max_Effect_Length (Under : Model_Ref)
return Natural;
--
-- The maximum length (number of assignments) of any feasible
-- effect in the computation model.
function Total_Defining_Assignments (Under : Model_Ref)
return Natural;
--
-- The total number of assignments (of Defining_Kind_T) in all
-- the feasible effects in the computation model.
--
-- The following "used/defined" queries are meant for use in
-- identifying loops and calls for assertions. Therefore, they
-- include infeasible as well as feasible parts of the model.
--
function Cells_Used (
Nodes : Node_List_T;
Under : Model_Ref)
return Storage.Cell_List_T;
--
-- The storage cells that are read in the Nodes listed or in the
-- preconditions on edges within or leaving the nodes, Under the
-- given computation model.
--
-- Basis cells for dynamic edges are included.
-- Basis cells for dynamic calling protocols are not included.
-- Cells read by callees are not included.
--
-- Note that cells used by infeasible steps/edges are included.
-- TBA option to omit infeasible steps/edges.
function Cells_Defined (
Nodes : Node_List_T;
Under : Model_Ref)
return Storage.Cell_List_T;
--
-- The storage cells that are written in the Nodes listed, Under
-- the given computation model.
--
-- Cells written by callees are included if they are listed in the
-- effect of the call-step.
--
-- Note that cells written by infeasible steps are included.
-- TBA option to omit infeasible steps.
function Is_Used (
Location : Storage.Location_T;
By : Node_List_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the given Location is used (read) By the steps in the
-- given nodes. A step is considered to use the Location if the
-- Location maps to a cell at the address of the step such that the
-- cell is
-- > used in a Defining assignment in the effect of the step, or
-- > used in the precondition of an edge leaving the step, or
-- > a member of the basis set for a dynamic edge leaving the step.
--
-- Basis cells for dynamic calling protocols are not considered.
--
-- Note that cells used by infeasible steps/edges are included.
-- TBA option to omit infeasible steps/edges.
function Is_Defined (
Location : Storage.Location_T;
By : Node_List_T;
Under : Model_Ref)
return Boolean;
--
-- Whether the given Location is defined (assigned) By the steps in
-- the given nodes. A step is considered to define the Location if the
-- Location maps to a cell at the address of the step such that the
-- cell is the target of a Defining assignment in the effect of the step.
--
-- Note that cells defined by infeasible steps are included.
-- TBA option to omit infeasible steps.
--
-- The following query functions again scan only feasible parts.
-- They are meant to locate the parts of the model that need to
-- be analysed and bounded.
--
function Steps_With_Dynamic_Effect (Under : Model_Ref)
return Step_List_T;
--
-- All the feasible flow-graph steps where the effect of the step,
-- Under the given computation model, contains some elements of the
-- class Storage.References.Boundable_T, either as assignments targets
-- or as parts in the arithmetic expressions.
function Edges_With_Dynamic_Condition (Under : Model_Ref)
return Step_Edge_List_T;
--
-- All the feasible step-edges in the flow-graph where the edge
-- precondition, Under the given computation model, contains some
-- parts of the class Storage.References.Boundable_T.
function Calls_From (Model : Model_Ref)
return Programs.Call_List_T;
--
-- All the calls from Subprogram (Model) to other subprograms,
-- but only those that are feasible under the given Model.
--
-- Operations to modify a model
--
procedure Set_Effect (
Step : in Step_T;
To : in Arithmetic.Effect_Ref;
Under : in out Model_Ref);
--
-- Sets (changes) the computational effect of the given Step,
-- Under a given computation model, To the given effect.
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean").
-- Has no effect on the pruning status of the model.
procedure Mark_Infeasible (
Step : in Step_T;
Under : in out Model_Ref);
--
-- Marks the given Step as infeasible (impossible to execute) Under
-- the given computation model. Note that only this Step is marked,
-- the logical implications are not propagated to other graph
-- elements (for example, all edges entering or leaving the Step
-- must also be infeasible). Use Flow.Pruning for the propagation.
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean") and "not pruned".
procedure Set_Condition (
On : in Step_Edge_T;
To : in Arithmetic.Condition_T;
Under : in out Model_Ref);
--
-- Sets (changes) the precondition of the given Edge, Under a
-- given computation model, To the given arithmetic condition.
-- If the condition is Arithmetic.Never, the edge becomes infeasible.
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean"). If the new
-- condition is Arithmetic.Never, marks the object as "not pruned".
procedure Mark_Infeasible (
Edge : in Step_Edge_T;
Under : in out Model_Ref);
--
-- Marks the given Edge as infeasible (impossible to execute) Under
-- the given computation model. Note that only this Edge is marked,
-- the logical implications are not propagated to other graph
-- elements (for example, if this is the only edge that enters or
-- leaves a step then the step must also be infeasible). Use
-- Flow.Pruning for the propagation.
--
-- This operation is equivalent to Set_Condition (Edge, Never, Under).
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean") and "not pruned".
procedure Mark_Infeasible (
Edges : in Step_Edge_List_T;
Under : in out Model_Ref);
--
-- Marks all the given Edges as infeasible Under the given computation
-- model. See Mark_Infeasible for a single Step_Edge_T for more info.
procedure Mark_Infeasible (
Edge : in Edge_T;
Under : in out Model_Ref);
--
-- Marks the (step) edge corresponding to the given (node) Edge as
-- infeasible Under the given computation model. See Mark_Infeasible
-- for a single Step_Edge_T for more info.
procedure Mark_Infeasible (
Edges : in Edge_List_T;
Under : in out Model_Ref);
--
-- Marks the (step) edges corresponding to the given (node) Edges
-- as infeasible Under the given computation model. Refer to the
-- Mark_Infeasible operation for Step_Edge_T for more info.
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean") and "not pruned".
procedure Mark_Infeasible (
Call : in Programs.Call_T;
Under : in out Model_Ref);
--
-- Marks the given Call as infeasible (impossible to execute) Under
-- the given computation model by marking its head-step as infeasible.
-- Marks the Under object as changed (not "clean") and "not pruned".
procedure Mark_Infeasible (
Luup : in Loops.Loop_T;
Under : in out Model_Ref);
--
-- Marks the given Luup as infeasible (impossible to execute) Under
-- the given computation model by marking its head-step as infeasible.
-- Marks the Under object as changed (not "clean") and "not pruned".
procedure Set_Calling_Protocol (
Call : in Programs.Call_T;
To : in Calling.Protocol_Ref;
Under : in out Model_Ref);
--
-- Sets (changes) the calling protocol for the given Call, To the
-- protocol, Under a given model structure.
--
-- The new calling protocol may mean that the effect of the Call
-- in this model changes or should change. However, this operation
-- does not itself update the effect.
--
-- Applies copy-on-change to the Under object.
-- Marks the Under object as changed (not "clean").
procedure Mark_No_Return (
From : in Programs.Call_T;
To : in out Model_Ref);
--
-- Marks the call as not returning From the callee To the caller,
-- under the caller's computation model. This has two effects:
--
-- > All edges leaving the call-step are marked infeasible.
-- A later pruning operation may propagate this infeasibility
-- to other parts of the flow-graph.
--
-- > If the call-step is itself feasible, the call-step is accepted
-- as the final point of a feasible path in the next pruning of
-- the flow-graph. Otherwise the call-step would become infeasible
-- since there is no path from the call-step to a return point or
-- to an eternal loop.
--
-- Marks the caller's computation model To as changed (not "clean")
-- and "not pruned".
procedure Prune (Model : in out Model_Ref);
--
-- Prunes away all infeasible parts of the computation model by
-- propagating the feasible/infeasible marks along the flow-graph
-- edges and then marks the Model as "pruned". Does nothing if the
-- model is already marked as "pruned".
-- Applies copy-on-change if the Model is not initially "pruned".
private
type Model_Access_T is access Model_T;
--
-- Refers to a computation model on the heap.
--:dbpool Model_Access_Pool : GNAT.Debug_Pools.Debug_Pool;
--:dbpool for Model_Access_T'Storage_Pool use Model_Access_Pool;
type Model_Ref is limited record
Ref : Model_Access_T;
end record;
--
-- A reference to the computation model Ref.all.
end Flow.Computation;
|
reznikmm/matreshka | Ada | 4,729 | adb | ------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Open Document Toolkit --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2014, Vadim Godunko <[email protected]> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.DOM_Documents;
with Matreshka.ODF_String_Constants;
with ODF.DOM.Iterators;
with ODF.DOM.Visitors;
package body Matreshka.ODF_Number.Transliteration_Country_Attributes is
------------
-- Create --
------------
overriding function Create
(Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters)
return Number_Transliteration_Country_Attribute_Node is
begin
return Self : Number_Transliteration_Country_Attribute_Node do
Matreshka.ODF_Number.Constructors.Initialize
(Self'Unchecked_Access,
Parameters.Document,
Matreshka.ODF_String_Constants.Number_Prefix);
end return;
end Create;
--------------------
-- Get_Local_Name --
--------------------
overriding function Get_Local_Name
(Self : not null access constant Number_Transliteration_Country_Attribute_Node)
return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return Matreshka.ODF_String_Constants.Transliteration_Country_Attribute;
end Get_Local_Name;
begin
Matreshka.DOM_Documents.Register_Attribute
(Matreshka.ODF_String_Constants.Number_URI,
Matreshka.ODF_String_Constants.Transliteration_Country_Attribute,
Number_Transliteration_Country_Attribute_Node'Tag);
end Matreshka.ODF_Number.Transliteration_Country_Attributes;
|
reznikmm/gela | Ada | 1,556 | ads | -- This package provides Source_Finder interface and its methods.
with League.Strings;
with Gela.Lexical_Types;
package Gela.Source_Finders is
pragma Preelaborate;
subtype File_Base_Name is League.Strings.Universal_String;
type Source_Finder is limited interface;
-- Type to find and read compilation sources.
type Source_Finder_Access is access all Source_Finder'Class;
for Source_Finder_Access'Storage_Size use 0;
not overriding procedure Lookup_Compilation
(Self : Source_Finder;
Name : League.Strings.Universal_String;
Found : out Boolean;
File : out League.Strings.Universal_String;
Source : out League.Strings.Universal_String) is abstract;
-- Find and read compilation of given Name.
-- Return full file name and content
not overriding procedure Lookup_Declaration
(Self : Source_Finder;
Symbol : Gela.Lexical_Types.Symbol;
Found : out Boolean;
File : out League.Strings.Universal_String;
Source : out League.Strings.Universal_String) is abstract;
-- Find and read library declaration unit with given Symbol.
-- Return full file name and content.
not overriding procedure Lookup_Body
(Self : Source_Finder;
Symbol : Gela.Lexical_Types.Symbol;
Found : out Boolean;
File : out League.Strings.Universal_String;
Source : out League.Strings.Universal_String) is abstract;
-- Find and read body or subunit with given Symbol.
-- Return full file name and content.
end Gela.Source_Finders;
|
zhmu/ananas | Ada | 125 | adb | -- { dg-do compile }
-- { dg-options "-gnatw.x -gnatd.a" }
package body Warn31 is
procedure Dummy is null;
end Warn31;
|
charlie5/lace | Ada | 5,355 | adb | with
openGL.Primitive.indexed,
openGL.Primitive,
ada.unchecked_Deallocation;
package body openGL.Model.segment_line
is
function to_segment_line_Model (Color : in openGL.Color) return Item
is
Self : constant Item := (Model.item with
+Color,
site_Vectors.empty_Vector,
others => <>);
begin
return Self;
end to_segment_line_Model;
function new_segment_line_Model (Color : in openGL.Color) return View
is
begin
return new Item' (to_segment_line_Model (Color));
end new_segment_line_Model;
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
is
pragma unreferenced (Textures, Fonts);
use Geometry.colored,
Primitive,
Primitive.indexed,
ada.Containers;
vertex_Count : constant Index_t := Index_t (Self.Points.Length);
indices_Count : constant long_Index_t := long_Index_t (vertex_Count);
the_Indices : aliased Indices := [1 .. indices_Count => <>];
begin
if Self.Points.Length <= 2
then
return [1..0 => <>];
end if;
for i in the_Indices'Range
loop
the_Indices (i) := Index_t (i);
end loop;
Self.Geometry := Geometry.colored.new_Geometry;
Self.Geometry.is_Transparent (False);
Self.Geometry.Vertices_are (Self.Vertices (1 .. Index_t (Self.vertex_Count)));
Self.Geometry.add (Primitive.view (new_Primitive (Line_Strip,
the_Indices)));
return [1 => Self.Geometry.all'Access];
end to_GL_Geometries;
function Site (Self : in Item; for_End : in Integer) return Vector_3
is
begin
return Self.Vertices (Index_t (for_End)).Site;
end Site;
function segment_Count (Self : in Item) return Natural
is
begin
return Natural (Self.Points.Length) - 1;
end segment_Count;
procedure add_1st_Segment (Self : in out Item; start_Site : in Vector_3;
end_Site : in Vector_3)
is
use site_Vectors;
begin
pragma assert (Self.Points.Is_Empty);
Self.Points.append (start_Site);
Self.Points.append (end_Site);
Self.vertex_Count := Self.vertex_Count + 1;
Self.Vertices (Index_t (Self.vertex_Count)).Site := start_Site;
Self.Vertices (Index_t (Self.vertex_Count)).Color := (Self.Color, opaque_Value);
Self.vertex_Count := Self.vertex_Count + 1;
Self.Vertices (Index_t (Self.vertex_Count)).Site := end_Site;
Self.Vertices (Index_t (Self.vertex_Count)).Color := (Self.Color, opaque_Value);
Self.needs_Rebuild := True;
end add_1st_Segment;
procedure add_Segment (Self : in out Item; end_Site : in Vector_3)
is
use type ada.Containers.Count_type;
procedure deallocate is new ada.unchecked_Deallocation (Geometry.colored.Vertex_array,
vertex_Array_view);
begin
pragma assert (not Self.Points.is_Empty);
Self.Points.append (end_Site);
if Self.Points.Length > Self.Vertices'Length
then
declare
new_Vertices : constant vertex_Array_view
:= new Geometry.colored.Vertex_array (1 .. 2 * Self.Vertices'Length);
begin
new_Vertices (1 .. Self.Vertices'Length) := Self.Vertices.all;
deallocate (Self.Vertices);
Self.Vertices := new_Vertices;
end;
end if;
Self.vertex_Count := Self.vertex_Count + 1;
Self.Vertices (Index_t (Self.vertex_Count)).Site := end_Site;
Self.Vertices (Index_t (Self.vertex_Count)).Color := (Self.Color, opaque_Value);
Self.needs_Rebuild := True;
end add_Segment;
procedure Site_is (Self : in out Item; Now : in Vector_3;
for_End : in Integer)
is
begin
Self.Vertices (Index_t (for_End)).Site := Now;
Self.Points.replace_Element (for_End, Now);
set_Bounds (Self);
Self.needs_Rebuild := True;
end Site_is;
procedure Color_is (Self : in out Item; Now : in Color;
for_End : in Integer)
is
begin
Self.Vertices (Index_t (for_End)).Color := (+Now, opaque_Value);
Self.needs_Rebuild := True;
end Color_is;
function Segments (Self : in Item) return Segments_t
is
the_Segments : Segments_t (1 .. Integer (Self.Points.Length) - 1);
begin
for Each in the_Segments'Range
loop
the_Segments (Each) := (First => Self.Points.Element (Each),
Last => Self.Points.Element (Each + 1));
end loop;
return the_Segments;
end Segments;
function Angle_in_xz_plane (the_Segment : in Segment) return Radians
is
use real_Functions;
the_Vector : constant Vector_3 := the_Segment.Last - the_Segment.First;
begin
return arcTan (the_Vector (3) / the_Vector (1));
end Angle_in_xz_plane;
end openGL.Model.segment_line;
|
MinimSecure/unum-sdk | Ada | 806 | adb | -- Copyright 2017-2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with B; use B;
with C;
procedure FOO is
begin
Doit;
B.Read_Small;
C.C_Doit;
end FOO;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.