content
stringlengths 23
1.05M
|
|---|
--
-- Copyright (C) 2016 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 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.
--
with HW.Time;
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Registers;
package body HW.GFX.GMA.Power_And_Clocks_Ironlake is
PCH_DREF_CONTROL_120MHZ_CPU_OUTPUT_MASK : constant := 3 * 2 ** 13;
PCH_DREF_CONTROL_120MHZ_CPU_OUTPUT_SSC : constant := 2 * 2 ** 13;
PCH_DREF_CONTROL_120MHZ_CPU_OUTPUT_NONSSC : constant := 3 * 2 ** 13;
PCH_DREF_CONTROL_120MHZ_SSC_EN_MASK : constant := 3 * 2 ** 11;
PCH_DREF_CONTROL_120MHZ_SSC_EN : constant := 2 * 2 ** 11;
PCH_DREF_CONTROL_120MHZ_NONSSC_EN_MASK : constant := 3 * 2 ** 9;
PCH_DREF_CONTROL_120MHZ_NONSSC_EN : constant := 2 * 2 ** 9;
PCH_DREF_CONTROL_120MHZ_SSC4_EN_MASK : constant := 3 * 2 ** 7;
PCH_DREF_CONTROL_120MHZ_SSC4_EN : constant := 2 * 2 ** 7;
PCH_DREF_CONTROL_120MHZ_SSC4_DOWNSPREAD : constant := 0 * 2 ** 6;
PCH_DREF_CONTROL_120MHZ_SSC4_CENTERSPREAD : constant := 1 * 2 ** 6;
PCH_DREF_CONTROL_120MHZ_SSC_MODULATION_EN : constant := 1 * 2 ** 1;
PCH_DREF_CONTROL_120MHZ_SSC4_MODULATION_EN : constant := 1 * 2 ** 0;
procedure Initialize is
begin
-- ILK: enable non-spread spectrum clock, enable spread spectrum clock
Registers.Write
(Register => Registers.PCH_DREF_CONTROL,
Value => PCH_DREF_CONTROL_120MHZ_SSC_EN or
PCH_DREF_CONTROL_120MHZ_NONSSC_EN or
PCH_DREF_CONTROL_120MHZ_SSC_MODULATION_EN);
Registers.Posting_Read (Registers.PCH_DREF_CONTROL);
Time.U_Delay (1);
if Config.Internal_Is_EDP then -- TODO: check for presence
-- always use spread spectrum clock for CPU output
Registers.Set_Mask
(Register => Registers.PCH_DREF_CONTROL,
Mask => PCH_DREF_CONTROL_120MHZ_CPU_OUTPUT_SSC);
Registers.Posting_Read (Registers.PCH_DREF_CONTROL);
Time.U_Delay (20); -- DMI latency
end if;
Config.Raw_Clock := Config.Default_RawClk_Freq;
end Initialize;
end HW.GFX.GMA.Power_And_Clocks_Ironlake;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . D I R E C T O R I E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2004-2005, Free Software Foundation, Inc. --
-- --
-- This specification is derived for use with GNAT from AI-00248, which is --
-- expected to be a part of a future expected revised Ada Reference Manual. --
-- The copyright notice above, and the license provisions that follow apply --
-- solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
--
--
--
--
--
--
--
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Ada 2005: Implementation of Ada.Directories (AI95-00248). Note that this
-- unit is available without -gnat05. That seems reasonable, since you only
-- get it if you explicitly ask for it.
-- External files may be classified as directories, special files, or ordinary
-- files. A directory is an external file that is a container for files on
-- the target system. A special file is an external file that cannot be
-- created or read by a predefined Ada Input-Output package. External files
-- that are not special files or directories are called ordinary files.
-- A file name is a string identifying an external file. Similarly, a
-- directory name is a string identifying a directory. The interpretation of
-- file names and directory names is implementation-defined.
-- The full name of an external file is a full specification of the name of
-- the file. If the external environment allows alternative specifications of
-- the name (for example, abbreviations), the full name should not use such
-- alternatives. A full name typically will include the names of all of
-- directories that contain the item. The simple name of an external file is
-- the name of the item, not including any containing directory names. Unless
-- otherwise specified, a file name or directory name parameter to a
-- predefined Ada input-output subprogram can be a full name, a simple name,
-- or any other form of name supported by the implementation.
-- The default directory is the directory that is used if a directory or
-- file name is not a full name (that is, when the name does not fully
-- identify all of the containing directories).
-- A directory entry is a single item in a directory, identifying a single
-- external file (including directories and special files).
-- For each function that returns a string, the lower bound of the returned
-- value is 1.
with Ada.Calendar;
with Ada.Finalization;
with Ada.IO_Exceptions;
with Ada.Strings.Unbounded;
package Ada.Directories is
pragma Ada_05;
-- To be removed later ???
-----------------------------------
-- Directory and File Operations --
-----------------------------------
function Current_Directory return String;
-- Returns the full directory name for the current default directory. The
-- name returned shall be suitable for a future call to Set_Directory.
-- The exception Use_Error is propagated if a default directory is not
-- supported by the external environment.
procedure Set_Directory (Directory : String);
-- Sets the current default directory. The exception Name_Error is
-- propagated if the string given as Directory does not identify an
-- existing directory. The exception Use_Error is propagated if the
-- external environment does not support making Directory (in the absence
-- of Name_Error) a default directory.
procedure Create_Directory
(New_Directory : String;
Form : String := "");
-- Creates a directory with name New_Directory. The Form parameter can be
-- used to give system-dependent characteristics of the directory; the
-- interpretation of the Form parameter is implementation-defined. A null
-- string for Form specifies the use of the default options of the
-- implementation of the new directory. The exception Name_Error is
-- propagated if the string given as New_Directory does not allow the
-- identification of a directory. The exception Use_Error is propagated if
-- the external environment does not support the creation of a directory
-- with the given name (in the absence of Name_Error) and form.
procedure Delete_Directory (Directory : String);
-- Deletes an existing empty directory with name Directory. The exception
-- Name_Error is propagated if the string given as Directory does not
-- identify an existing directory. The exception Use_Error is propagated
-- if the external environment does not support the deletion of the
-- directory (or some portion of its contents) with the given name (in the
-- absence of Name_Error).
procedure Create_Path
(New_Directory : String;
Form : String := "");
-- Creates zero or more directories with name New_Directory. Each
-- non-existent directory named by New_Directory is created. For example,
-- on a typical Unix system, Create_Path ("/usr/me/my"); would create
-- directory "me" in directory "usr", then create directory "my" in
-- directory "me". The Form can be used to give system-dependent
-- characteristics of the directory; the interpretation of the Form
-- parameter is implementation-defined. A null string for Form specifies
-- the use of the default options of the implementation of the new
-- directory. The exception Name_Error is propagated if the string given
-- as New_Directory does not allow the identification of any directory.
-- The exception Use_Error is propagated if the external environment does
-- not support the creation of any directories with the given name (in the
-- absence of Name_Error) and form.
procedure Delete_Tree (Directory : String);
-- Deletes an existing directory with name Directory. The directory and
-- all of its contents (possibly including other directories) are deleted.
-- The exception Name_Error is propagated if the string given as Directory
-- does not identify an existing directory. The exception Use_Error is
-- propagated if the external environment does not support the deletion of
-- the directory or some portion of its contents with the given name (in
-- the absence of Name_Error). If Use_Error is propagated, it is
-- unspecified if a portion of the contents of the directory are deleted.
procedure Delete_File (Name : String);
-- Deletes an existing ordinary or special file with Name. The exception
-- Name_Error is propagated if the string given as Name does not identify
-- an existing ordinary or special external file. The exception Use_Error
-- is propagated if the external environment does not support the deletion
-- of the file with the given name (in the absence of Name_Error).
procedure Rename (Old_Name, New_Name : String);
-- Renames an existing external file (including directories) with Old_Name
-- to New_Name. The exception Name_Error is propagated if the string given
-- as Old_Name does not identify an existing external file. The exception
-- Use_Error is propagated if the external environment does not support the
-- renaming of the file with the given name (in the absence of Name_Error).
-- In particular, Use_Error is propagated if a file or directory already
-- exists with New_Name.
procedure Copy_File
(Source_Name : String;
Target_Name : String;
Form : String := "");
-- Copies the contents of the existing external file with Source_Name
-- to Target_Name. The resulting external file is a duplicate of the source
-- external file. The Form can be used to give system-dependent
-- characteristics of the resulting external file; the interpretation of
-- the Form parameter is implementation-defined. Exception Name_Error is
-- propagated if the string given as Source_Name does not identify an
-- existing external ordinary or special file or if the string given as
-- Target_Name does not allow the identification of an external file.
-- The exception Use_Error is propagated if the external environment does
-- not support the creating of the file with the name given by Target_Name
-- and form given by Form, or copying of the file with the name given by
-- Source_Name (in the absence of Name_Error).
----------------------------------------
-- File and directory name operations --
----------------------------------------
function Full_Name (Name : String) return String;
-- Returns the full name corresponding to the file name specified by Name.
-- The exception Name_Error is propagated if the string given as Name does
-- not allow the identification of an external file (including directories
-- and special files).
function Simple_Name (Name : String) return String;
-- Returns the simple name portion of the file name specified by Name. The
-- exception Name_Error is propagated if the string given as Name does not
-- allow the identification of an external file (including directories and
-- special files).
function Containing_Directory (Name : String) return String;
-- Returns the name of the containing directory of the external file
-- (including directories) identified by Name. If more than one directory
-- can contain Name, the directory name returned is implementation-defined.
-- The exception Name_Error is propagated if the string given as Name does
-- not allow the identification of an external file. The exception
-- Use_Error is propagated if the external file does not have a containing
-- directory.
function Extension (Name : String) return String;
-- Returns the extension name corresponding to Name. The extension name is
-- a portion of a simple name (not including any separator characters),
-- typically used to identify the file class. If the external environment
-- does not have extension names, then the null string is returned.
-- The exception Name_Error is propagated if the string given as Name does
-- not allow the identification of an external file.
function Base_Name (Name : String) return String;
-- Returns the base name corresponding to Name. The base name is the
-- remainder of a simple name after removing any extension and extension
-- separators. The exception Name_Error is propagated if the string given
-- as Name does not allow the identification of an external file
-- (including directories and special files).
function Compose
(Containing_Directory : String := "";
Name : String;
Extension : String := "") return String;
-- Returns the name of the external file with the specified
-- Containing_Directory, Name, and Extension. If Extension is the null
-- string, then Name is interpreted as a simple name; otherwise Name is
-- interpreted as a base name. The exception Name_Error is propagated if
-- the string given as Containing_Directory is not null and does not allow
-- the identification of a directory, or if the string given as Extension
-- is not null and is not a possible extension, or if the string given as
-- Name is not a possible simple name (if Extension is null) or base name
-- (if Extension is non-null).
--------------------------------
-- File and directory queries --
--------------------------------
type File_Kind is (Directory, Ordinary_File, Special_File);
-- The type File_Kind represents the kind of file represented by an
-- external file or directory.
type File_Size is range 0 .. Long_Long_Integer'Last;
-- The type File_Size represents the size of an external file
function Exists (Name : String) return Boolean;
-- Returns True if external file represented by Name exists, and False
-- otherwise. The exception Name_Error is propagated if the string given as
-- Name does not allow the identification of an external file (including
-- directories and special files).
function Kind (Name : String) return File_Kind;
-- Returns the kind of external file represented by Name. The exception
-- Name_Error is propagated if the string given as Name does not allow the
-- identification of an existing external file.
function Size (Name : String) return File_Size;
-- Returns the size of the external file represented by Name. The size of
-- an external file is the number of stream elements contained in the file.
-- If the external file is discontiguous (not all elements exist), the
-- result is implementation-defined. If the external file is not an
-- ordinary file, the result is implementation-defined. The exception
-- Name_Error is propagated if the string given as Name does not allow the
-- identification of an existing external file. The exception
-- Constraint_Error is propagated if the file size is not a value of type
-- File_Size.
function Modification_Time (Name : String) return Ada.Calendar.Time;
-- Returns the time that the external file represented by Name was most
-- recently modified. If the external file is not an ordinary file, the
-- result is implementation-defined. The exception Name_Error is propagated
-- if the string given as Name does not allow the identification of an
-- existing external file. The exception Use_Error is propagated if the
-- external environment does not support the reading the modification time
-- of the file with the name given by Name (in the absence of Name_Error).
-------------------------
-- Directory Searching --
-------------------------
type Directory_Entry_Type is limited private;
-- The type Directory_Entry_Type represents a single item in a directory.
-- These items can only be created by the Get_Next_Entry procedure in this
-- package. Information about the item can be obtained from the functions
-- declared in this package. A default initialized object of this type is
-- invalid; objects returned from Get_Next_Entry are valid.
type Filter_Type is array (File_Kind) of Boolean;
-- The type Filter_Type specifies which directory entries are provided from
-- a search operation. If the Directory component is True, directory
-- entries representing directories are provided. If the Ordinary_File
-- component is True, directory entries representing ordinary files are
-- provided. If the Special_File component is True, directory entries
-- representing special files are provided.
type Search_Type is limited private;
-- The type Search_Type contains the state of a directory search. A
-- default-initialized Search_Type object has no entries available
-- (More_Entries returns False).
procedure Start_Search
(Search : in out Search_Type;
Directory : String;
Pattern : String;
Filter : Filter_Type := (others => True));
-- Starts a search in the directory entry in the directory named by
-- Directory for entries matching Pattern. Pattern represents a file name
-- matching pattern. If Pattern is null, all items in the directory are
-- matched; otherwise, the interpretation of Pattern is implementation-
-- defined. Only items which match Filter will be returned. After a
-- successful call on Start_Search, the object Search may have entries
-- available, but it may have no entries available if no files or
-- directories match Pattern and Filter. The exception Name_Error is
-- propagated if the string given by Directory does not identify an
-- existing directory, or if Pattern does not allow the identification of
-- any possible external file or directory. The exception Use_Error is
-- propagated if the external environment does not support the searching
-- of the directory with the given name (in the absence of Name_Error).
procedure End_Search (Search : in out Search_Type);
-- Ends the search represented by Search. After a successful call on
-- End_Search, the object Search will have no entries available. Note
-- that is is not necessary to call End_Search if the call to Start_Search
-- was unsuccessful and raised an exception (but it is harmless to make
-- the call in this case)>
function More_Entries (Search : Search_Type) return Boolean;
-- Returns True if more entries are available to be returned by a call
-- to Get_Next_Entry for the specified search object, and False otherwise.
procedure Get_Next_Entry
(Search : in out Search_Type;
Directory_Entry : out Directory_Entry_Type);
-- Returns the next Directory_Entry for the search described by Search that
-- matches the pattern and filter. If no further matches are available,
-- Status_Error is raised. It is implementation-defined as to whether the
-- results returned by this routine are altered if the contents of the
-- directory are altered while the Search object is valid (for example, by
-- another program). The exception Use_Error is propagated if the external
-- environment does not support continued searching of the directory
-- represented by Search.
-------------------------------------
-- Operations on Directory Entries --
-------------------------------------
function Simple_Name (Directory_Entry : Directory_Entry_Type) return String;
-- Returns the simple external name of the external file (including
-- directories) represented by Directory_Entry. The format of the name
-- returned is implementation-defined. The exception Status_Error is
-- propagated if Directory_Entry is invalid.
function Full_Name (Directory_Entry : Directory_Entry_Type) return String;
-- Returns the full external name of the external file (including
-- directories) represented by Directory_Entry. The format of the name
-- returned is implementation-defined. The exception Status_Error is
-- propagated if Directory_Entry is invalid.
function Kind (Directory_Entry : Directory_Entry_Type) return File_Kind;
-- Returns the kind of external file represented by Directory_Entry. The
-- exception Status_Error is propagated if Directory_Entry is invalid.
function Size (Directory_Entry : Directory_Entry_Type) return File_Size;
-- Returns the size of the external file represented by Directory_Entry.
-- The size of an external file is the number of stream elements contained
-- in the file. If the external file is discontiguous (not all elements
-- exist), the result is implementation-defined. If the external file
-- represented by Directory_Entry is not an ordinary file, the result is
-- implementation-defined. The exception Status_Error is propagated if
-- Directory_Entry is invalid. The exception Constraint_Error is propagated
-- if the file size is not a value of type File_Size.
function Modification_Time
(Directory_Entry : Directory_Entry_Type) return Ada.Calendar.Time;
-- Returns the time that the external file represented by Directory_Entry
-- was most recently modified. If the external file represented by
-- Directory_Entry is not an ordinary file, the result is
-- implementation-defined. The exception Status_Error is propagated if
-- Directory_Entry is invalid. The exception Use_Error is propagated if
-- the external environment does not support the reading the modification
-- time of the file represented by Directory_Entry.
----------------
-- Exceptions --
----------------
Status_Error : exception renames Ada.IO_Exceptions.Status_Error;
Name_Error : exception renames Ada.IO_Exceptions.Name_Error;
Use_Error : exception renames Ada.IO_Exceptions.Use_Error;
Device_Error : exception renames Ada.IO_Exceptions.Device_Error;
private
type Directory_Entry_Type is record
Is_Valid : Boolean := False;
Simple : Ada.Strings.Unbounded.Unbounded_String;
Full : Ada.Strings.Unbounded.Unbounded_String;
Kind : File_Kind := Ordinary_File;
end record;
-- The type Search_Data is defined in the body, so that the spec does not
-- depend on packages of the GNAT hierarchy.
type Search_Data;
type Search_Ptr is access Search_Data;
-- Search_Type need to be a controlled type, because it includes component
-- of type Dir_Type (in GNAT.Directory_Operations) that need to be closed
-- (if opened) during finalization. The component need to be an access
-- value, because Search_Data is not fully defined in the spec.
type Search_Type is new Ada.Finalization.Controlled with record
Value : Search_Ptr;
end record;
procedure Finalize (Search : in out Search_Type);
-- Close the directory, if opened, and deallocate Value
procedure End_Search (Search : in out Search_Type) renames Finalize;
end Ada.Directories;
|
-- Ada Keywords
abort abs abstract accept access aliased all and array at
begin body
case constant
declare delay delta digits do
else elsif end entry exception exit
for function
generic goto
if in interface is
limited loop
mod
new not null
of or others out overriding
package pragma private procedure protected
raise range record rem renames requeue return reverse
select separate some subtype synchronized
tagged task terminate then type
until use
when while with
xor
|
with Giza.Widget;
with Test_Tiles_Window; use Test_Tiles_Window;
with Giza.Types; use Giza.Types;
use Giza;
------------------------
-- Test_Scroll_Window --
------------------------
package body Test_Scroll_Window is
-------------
-- On_Init --
-------------
overriding procedure On_Init
(This : in out Scroll_Window)
is
Object : Tiles_Window_Ref;
Size : constant Size_T := This.Get_Size;
begin
On_Init (Test_Window (This));
This.Scroll_Vert := new Scrolling.Instance;
This.Scroll_Horizon := new Scrolling.Instance;
This.Scroll_Both := new Scrolling.Instance;
This.Scroll_Vert.Set_Size ((Size.W / 2, Size.H / 2));
Object := new Tiles_Window;
Object.Set_Size ((This.Scroll_Vert.Get_Size.W,
This.Scroll_Vert.Get_Size.H * 2));
Object.On_Init;
This.Scroll_Vert.Set_Child (Widget.Reference (Object));
This.Scroll_Horizon.Set_Size ((Size.W / 2, Size.H / 2));
Object := new Tiles_Window;
Object.Set_Size ((This.Scroll_Horizon.Get_Size.W * 2,
This.Scroll_Horizon.Get_Size.H));
Object.On_Init;
This.Scroll_Horizon.Set_Child (Widget.Reference (Object));
This.Scroll_Both.Set_Size ((Size.W, Size.H / 2));
Object := new Tiles_Window;
Object.Set_Size ((This.Scroll_Horizon.Get_Size.W * 2,
This.Scroll_Horizon.Get_Size.H * 2));
Object.On_Init;
This.Scroll_Both.Set_Child (Widget.Reference (Object));
This.Add_Child (Widget.Reference (This.Scroll_Vert),
(0, 0));
This.Add_Child (Widget.Reference (This.Scroll_Horizon),
(Size.W / 2, 0));
This.Add_Child (Widget.Reference (This.Scroll_Both),
(0, Size.H / 2));
end On_Init;
------------------
-- On_Displayed --
------------------
overriding procedure On_Displayed
(This : in out Scroll_Window)
is
begin
null;
end On_Displayed;
---------------
-- On_Hidden --
---------------
overriding procedure On_Hidden
(This : in out Scroll_Window)
is
begin
null;
end On_Hidden;
end Test_Scroll_Window;
|
with Ada.Real_Time;
package body STM32.OPAMP is
------------
-- Enable --
------------
procedure Enable (This : in out Operational_Amplifier) is
use Ada.Real_Time;
begin
This.CSR.OPAEN := True;
-- Delay 4 us for OPAMP startup time. See DS12110 Rev 8 chapter 7.3.27
-- Operational amplifier characteristics.
delay until Clock + Microseconds (4);
end Enable;
-------------
-- Disable --
-------------
procedure Disable (This : in out Operational_Amplifier) is
begin
This.CSR.OPAEN := False;
end Disable;
-------------
-- Enabled --
-------------
function Enabled (This : Operational_Amplifier) return Boolean is
begin
return This.CSR.OPAEN;
end Enabled;
-----------------------
-- Set_NI_Input_Mode --
-----------------------
procedure Set_NI_Input_Mode
(This : in out Operational_Amplifier;
Input : NI_Input_Mode) is
begin
This.CSR.FORCE_VP := Input = Calibration_Mode;
end Set_NI_Input_Mode;
-----------------------
-- Get_NI_Input_Mode --
-----------------------
function Get_NI_Input_Mode
(This : Operational_Amplifier) return NI_Input_Mode is
begin
return NI_Input_Mode'Val (Boolean'Pos (This.CSR.FORCE_VP));
end Get_NI_Input_Mode;
-----------------------
-- Set_NI_Input_Port --
-----------------------
procedure Set_NI_Input_Port
(This : in out Operational_Amplifier;
Input : NI_Input_Port) is
begin
This.CSR.VP_SEL := Input'Enum_Rep;
end Set_NI_Input_Port;
-----------------------
-- Get_NI_Input_Port --
-----------------------
function Get_NI_Input_Port
(This : Operational_Amplifier) return NI_Input_Port is
begin
return NI_Input_Port'Val (This.CSR.VP_SEL);
end Get_NI_Input_Port;
----------------------
-- Set_I_Input_Port --
----------------------
procedure Set_I_Input_Port
(This : in out Operational_Amplifier;
Input : I_Input_Port) is
begin
This.CSR.VM_SEL := Input'Enum_Rep;
end Set_I_Input_Port;
----------------------
-- Get_I_Input_Port --
----------------------
function Get_I_Input_Port
(This : Operational_Amplifier) return I_Input_Port is
begin
return I_Input_Port'Val (This.CSR.VM_SEL);
end Get_I_Input_Port;
-----------------------
-- Set_PGA_Mode_Gain --
-----------------------
procedure Set_PGA_Mode_Gain
(This : in out Operational_Amplifier;
Input : PGA_Mode_Gain) is
begin
This.CSR.PGA_GAIN := Input'Enum_Rep;
end Set_PGA_Mode_Gain;
-----------------------
-- Get_PGA_Mode_Gain --
-----------------------
function Get_PGA_Mode_Gain
(This : Operational_Amplifier) return PGA_Mode_Gain is
begin
return PGA_Mode_Gain'Val (This.CSR.PGA_GAIN);
end Get_PGA_Mode_Gain;
--------------------
-- Set_Speed_Mode --
--------------------
procedure Set_Speed_Mode
(This : in out Operational_Amplifier; Input : Speed_Mode) is
begin
This.CSR.OPAHSM := Input = HighSpeed_Mode;
end Set_Speed_Mode;
---------------------
-- Get_Speed_Mode --
---------------------
function Get_Speed_Mode
(This : Operational_Amplifier) return Speed_Mode is
begin
return Speed_Mode'Val (Boolean'Pos (This.CSR.OPAHSM));
end Get_Speed_Mode;
---------------------
-- Configure_Opamp --
---------------------
procedure Configure_Opamp
(This : in out Operational_Amplifier;
Param : Init_Parameters)
is
begin
This.CSR :=
(VM_SEL => Param.Input_Minus'Enum_Rep,
VP_SEL => Param.Input_Plus'Enum_Rep,
PGA_GAIN => Param.PGA_Mode'Enum_Rep,
OPAHSM => Boolean'Val (Param.Power_Mode'Enum_Rep),
others => <>);
end Configure_Opamp;
-----------------------
-- Set_User_Trimming --
-----------------------
procedure Set_User_Trimming
(This : in out Operational_Amplifier;
Enabled : Boolean) is
begin
This.CSR.USERTRIM := Enabled;
end Set_User_Trimming;
------------------------
-- Get_User_Trimming --
------------------------
function Get_User_Trimming
(This : Operational_Amplifier) return Boolean is
begin
return This.CSR.USERTRIM;
end Get_User_Trimming;
-------------------------
-- Set_Offset_Trimming --
-------------------------
procedure Set_Offset_Trimming
(This : in out Operational_Amplifier;
Pair : Differential_Pair;
Input : UInt5) is
begin
if This.CSR.OPAHSM then
case Pair is
when NMOS =>
This.HSOTR.TRIMHSOFFSETN := Input;
when PMOS =>
This.HSOTR.TRIMHSOFFSETP := Input;
end case;
else
case Pair is
when NMOS =>
This.OTR.TRIMOFFSETN := Input;
when PMOS =>
This.OTR.TRIMOFFSETP := Input;
end case;
end if;
end Set_Offset_Trimming;
--------------------------
-- Get_Offset_Trimming --
--------------------------
function Get_Offset_Trimming
(This : Operational_Amplifier;
Pair : Differential_Pair) return UInt5
is
begin
if This.CSR.OPAHSM then
case Pair is
when NMOS =>
return This.HSOTR.TRIMHSOFFSETN;
when PMOS =>
return This.HSOTR.TRIMHSOFFSETP;
end case;
else
case Pair is
when NMOS =>
return This.OTR.TRIMOFFSETN;
when PMOS =>
return This.OTR.TRIMOFFSETP;
end case;
end if;
end Get_Offset_Trimming;
--------------------------
-- Set_Calibration_Mode --
--------------------------
procedure Set_Calibration_Mode
(This : in out Operational_Amplifier;
Enabled : Boolean) is
begin
This.CSR.CALON := Enabled;
end Set_Calibration_Mode;
--------------------------
-- Get_Calibration_Mode --
--------------------------
function Get_Calibration_Mode
(This : Operational_Amplifier) return Boolean is
begin
return This.CSR.CALON;
end Get_Calibration_Mode;
---------------------------
-- Set_Calibration_Value --
---------------------------
procedure Set_Calibration_Value
(This : in out Operational_Amplifier;
Input : Calibration_Value) is
begin
This.CSR.CALSEL := Input'Enum_Rep;
end Set_Calibration_Value;
---------------------------
-- Get_Calibration_Value --
---------------------------
function Get_Calibration_Value
(This : Operational_Amplifier) return Calibration_Value is
begin
return Calibration_Value'Val (This.CSR.CALSEL);
end Get_Calibration_Value;
---------------
-- Calibrate --
---------------
procedure Calibrate (This : in out Operational_Amplifier) is
use Ada.Real_Time;
Trimoffset : UInt5 := 0;
begin
-- 1. Enable OPAMP by setting the OPAMPxEN bit.
if not Enabled (This) then
Enable (This);
end if;
-- 2. Enable the user offset trimming by setting the USERTRIM bit.
Set_User_Trimming (This, Enabled => True);
-- 3. Connect VM and VP to the internal reference voltage by setting
-- the CALON bit.
Set_Calibration_Mode (This, Enabled => True);
-- 4. Set CALSEL to 11 (OPAMP internal reference = 0.9 x VDDA) for NMOS,
-- Set CALSEL to 01 (OPAMP internal reference = 0.1 x VDDA) for PMOS.
for Pair in Differential_Pair'Range loop
if Pair = NMOS then
Set_Calibration_Value (This, Input => VREFOPAMP_Is_90_VDDA);
else
Set_Calibration_Value (This, Input => VREFOPAMP_Is_10_VDDA);
end if;
-- 5. In a loop, increment the TRIMOFFSETN (for NMOS) or TRIMOFFSETP
-- (for PMOS) value. To exit from the loop, the OUTCAL bit must be
-- reset (non-inverting < inverting).
-- In this case, the TRIMOFFSETN value must be stored.
Set_Offset_Trimming (This, Pair => Pair, Input => Trimoffset);
-- Wait the OFFTRIMmax delay timing specified < 1 ms.
delay until Clock + Milliseconds (1);
while Get_Output_Status_Flag (This) = NI_Greater_Then_I loop
Trimoffset := Trimoffset + 1;
Set_Offset_Trimming (This, Pair => Pair, Input => Trimoffset);
-- Wait the OFFTRIMmax delay timing specified < 1 ms.
delay until Clock + Milliseconds (1);
end loop;
end loop;
Set_User_Trimming (This, Enabled => False);
Set_Calibration_Mode (This, Enabled => False);
end Calibrate;
-----------------------------
-- Get_Output_Status_Flag --
-----------------------------
function Get_Output_Status_Flag
(This : Operational_Amplifier) return Output_Status_Flag is
begin
return Output_Status_Flag'Val (Boolean'Pos (This.CSR.CALOUT));
end Get_Output_Status_Flag;
end STM32.OPAMP;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, 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 System; use System;
pragma Warnings (Off, "* is an internal GNAT unit");
with System.BB.Parameters;
pragma Warnings (On, "* is an internal GNAT unit");
with STM32_SVD.RCC; use STM32_SVD.RCC;
package body STM32.Device is
HSE_VALUE : constant := System.BB.Parameters.HSE_Clock;
-- External oscillator in Hz
HSI_VALUE : constant := 16_000_000;
-- Internal oscillator in Hz
HPRE_Presc_Table : constant array (UInt4) of UInt32 :=
(1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 8, 16, 64, 128, 256, 512);
PPRE_Presc_Table : constant array (UInt3) of UInt32 :=
(1, 1, 1, 1, 2, 4, 8, 16);
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : aliased in out GPIO_Port) is
begin
if This'Address = GPIOA_Base then
RCC_Periph.AHB2ENR.GPIOAEN := True;
elsif This'Address = GPIOB_Base then
RCC_Periph.AHB2ENR.GPIOBEN := True;
elsif This'Address = GPIOC_Base then
RCC_Periph.AHB2ENR.GPIOCEN := True;
elsif This'Address = GPIOH_Base then
RCC_Periph.AHB2ENR.GPIOHEN := True;
else
raise Unknown_Device;
end if;
end Enable_Clock;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (Point : GPIO_Point)
is
begin
Enable_Clock (Point.Periph.all);
end Enable_Clock;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (Points : GPIO_Points)
is
begin
for Point of Points loop
Enable_Clock (Point.Periph.all);
end loop;
end Enable_Clock;
-----------
-- Reset --
-----------
procedure Reset (This : aliased in out GPIO_Port) is
begin
if This'Address = GPIOA_Base then
RCC_Periph.AHB2RSTR.GPIOARST := True;
RCC_Periph.AHB2RSTR.GPIOARST := False;
elsif This'Address = GPIOB_Base then
RCC_Periph.AHB2RSTR.GPIOBRST := True;
RCC_Periph.AHB2RSTR.GPIOBRST := False;
elsif This'Address = GPIOC_Base then
RCC_Periph.AHB2RSTR.GPIOCRST := True;
RCC_Periph.AHB2RSTR.GPIOCRST := False;
else
raise Unknown_Device;
end if;
end Reset;
-----------
-- Reset --
-----------
procedure Reset (Point : GPIO_Point) is
begin
Reset (Point.Periph.all);
end Reset;
-----------
-- Reset --
-----------
procedure Reset (Points : GPIO_Points)
is
Do_Reset : Boolean;
begin
for J in Points'Range loop
Do_Reset := True;
for K in Points'First .. J - 1 loop
if Points (K).Periph = Points (J).Periph then
Do_Reset := False;
exit;
end if;
end loop;
if Do_Reset then
Reset (Points (J).Periph.all);
end if;
end loop;
end Reset;
------------------------------
-- GPIO_Port_Representation --
------------------------------
function GPIO_Port_Representation (Port : GPIO_Port) return UInt3 is
begin
-- TODO: rather ugly to have this board-specific range here
if Port'Address = GPIOA_Base then
return 0;
elsif Port'Address = GPIOB_Base then
return 1;
elsif Port'Address = GPIOC_Base then
return 2;
elsif Port'Address = GPIOH_Base then
return 7;
else
raise Program_Error;
end if;
end GPIO_Port_Representation;
------------------
-- Enable_Clock --
------------------
-- procedure Enable_Clock (This : aliased in out DMA_Controller) is
-- begin
-- if This'Address = STM32_SVD.DMA1_Base then
-- RCC_Periph.AHB1ENR.DMA1EN := True;
-- elsif This'Address = STM32_SVD.DMA2_Base then
-- RCC_Periph.AHB1ENR.DMA2EN := True;
-- else
-- raise Unknown_Device;
-- end if;
-- end Enable_Clock;
-----------
-- Reset --
-----------
-- procedure Reset (This : aliased in out DMA_Controller) is
-- begin
-- if This'Address = STM32_SVD.DMA1_Base then
-- RCC_Periph.AHB1RSTR.DMA1RST := True;
-- RCC_Periph.AHB1RSTR.DMA1RST := False;
-- elsif This'Address = STM32_SVD.DMA2_Base then
-- RCC_Periph.AHB1RSTR.DMA2RST := True;
-- RCC_Periph.AHB1RSTR.DMA2RST := False;
-- else
-- raise Unknown_Device;
-- end if;
-- end Reset;
----------------
-- As_Port_Id --
----------------
function As_Port_Id (Port : I2C_Port) return I2C_Port_Id is
begin
if Port.Periph.all'Address = I2C1_Base then
return I2C_Id_1;
elsif Port.Periph.all'Address = I2C2_Base then
return I2C_Id_2;
elsif Port.Periph.all'Address = I2C3_Base then
return I2C_Id_3;
else
raise Unknown_Device;
end if;
end As_Port_Id;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : I2C_Port) is
begin
Enable_Clock (As_Port_Id (This));
end Enable_Clock;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : I2C_Port_Id) is
begin
case This is
when I2C_Id_1 =>
RCC_Periph.APB1ENR1.I2C1EN := True;
when I2C_Id_2 =>
RCC_Periph.APB1ENR1.I2C2EN := True;
when I2C_Id_3 =>
RCC_Periph.APB1ENR1.I2C3EN := True;
end case;
end Enable_Clock;
-----------
-- Reset --
-----------
procedure Reset (This : I2C_Port) is
begin
Reset (As_Port_Id (This));
end Reset;
-----------
-- Reset --
-----------
procedure Reset (This : I2C_Port_Id) is
begin
case This is
when I2C_Id_1 =>
RCC_Periph.APB1RSTR1.I2C1RST := True;
RCC_Periph.APB1RSTR1.I2C1RST := False;
when I2C_Id_2 =>
RCC_Periph.APB1RSTR1.I2C2RST := True;
RCC_Periph.APB1RSTR1.I2C2RST := False;
when I2C_Id_3 =>
RCC_Periph.APB1RSTR1.I2C3RST := True;
RCC_Periph.APB1RSTR1.I2C3RST := False;
end case;
end Reset;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : SPI_Port) is
begin
if This.Periph.all'Address = SPI1_Base then
RCC_Periph.APB2ENR.SPI1EN := True;
elsif This.Periph.all'Address = SPI2_Base then
RCC_Periph.APB1ENR1.SPI2S2EN := True;
elsif This.Periph.all'Address = SPI3_Base then
RCC_Periph.APB3ENR.SUBGHZSPIEN := True;
else
raise Unknown_Device;
end if;
end Enable_Clock;
-----------
-- Reset --
-----------
procedure Reset (This : in out SPI_Port) is
begin
if This.Periph.all'Address = SPI1_Base then
RCC_Periph.APB2RSTR.SPI1RST := True;
RCC_Periph.APB2RSTR.SPI1RST := False;
elsif This.Periph.all'Address = SPI2_Base then
RCC_Periph.APB1RSTR1.SPI2S2RST := True;
RCC_Periph.APB1RSTR1.SPI2S2RST := False;
elsif This.Periph.all'Address = SPI3_Base then
RCC_Periph.APB3RSTR.SUBGHZSPIRST := True;
RCC_Periph.APB3RSTR.SUBGHZSPIRST := False;
else
raise Unknown_Device;
end if;
end Reset;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : in out Timer) is
begin
if This'Address = TIM1_Base then
RCC_Periph.APB2ENR.TIM1EN := True;
elsif This'Address = TIM2_Base then
RCC_Periph.APB1ENR1.TIM2EN := True;
elsif This'Address = TIM16_Base then
RCC_Periph.APB2ENR.TIM16EN := True;
elsif This'Address = TIM17_Base then
RCC_Periph.APB2ENR.TIM17EN := True;
else
raise Unknown_Device;
end if;
end Enable_Clock;
-----------
-- Reset --
-----------
procedure Reset (This : in out Timer) is
begin
if This'Address = TIM1_Base then
RCC_Periph.APB2RSTR.TIM1RST := True;
RCC_Periph.APB2RSTR.TIM1RST := False;
elsif This'Address = TIM2_Base then
RCC_Periph.APB1RSTR1.TIM2RST := True;
RCC_Periph.APB1RSTR1.TIM2RST := False;
else
raise Unknown_Device;
end if;
end Reset;
------------------
-- Enable_Clock --
------------------
-- procedure Enable_Clock (This : aliased in out Analog_To_Digital_Converter)
-- is
-- begin
-- if This'Address = ADC_Base then
-- RCC_Periph.APB2ENR.ADCEN := True;
-- RCC_Periph.CCIPR.ADCSEL := 3; -- clock sel. Default is... none!
-- else
-- raise Unknown_Device;
-- end if;
-- end Enable_Clock;
-------------------------
-- Reset_All_ADC_Units --
-------------------------
-- procedure Reset_All_ADC_Units is
-- begin
-- RCC_Periph.APB2RSTR.ADCRST := True;
-- RCC_Periph.APB2RSTR.ADCRST := False;
-- end Reset_All_ADC_Units;
------------------------------
-- System_Clock_Frequencies --
------------------------------
function System_Clock_Frequencies return RCC_System_Clocks
is
Source : constant UInt2 := RCC_Periph.CFGR.SWS;
Result : RCC_System_Clocks;
begin
Result.I2SCLK := 0;
return Result;
end System_Clock_Frequencies;
------------------
-- Enable_Clock --
------------------
procedure Enable_Clock (This : in out CRC_32) is
pragma Unreferenced (This);
begin
RCC_Periph.AHB1ENR.CRCEN := True;
end Enable_Clock;
-------------------
-- Disable_Clock --
-------------------
procedure Disable_Clock (This : in out CRC_32) is
pragma Unreferenced (This);
begin
RCC_Periph.AHB1ENR.CRCEN := False;
end Disable_Clock;
-----------
-- Reset --
-----------
procedure Reset (This : in out CRC_32) is
pragma Unreferenced (This);
begin
-- RCC_Periph.AHBRSTR.CRCRST := True;
-- RCC_Periph.AHBRSTR.CRCRST := False;
null;
end Reset;
end STM32.Device;
|
with Ada.Streams;
with Ada.Text_IO;
with Crypto.SHA512; use Crypto.SHA512;
procedure Test_SHA512 is
procedure Test_01 is
use type Ada.Streams.Stream_Element_Array;
C : Context := Initial;
D : Fingerprint;
begin
Update (C, "a");
Final (C, D);
pragma Assert (
Image (D) =
"1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08"
& "d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75");
pragma Assert (D = Value (Image (D)));
end Test_01;
pragma Debug (Test_01);
begin
-- finish
Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error.all, "ok");
end Test_SHA512;
|
-----------------------------------------------------------------------
-- el-functions -- Functions to be plugged in expressions
-- Copyright (C) 2009, 2010, 2012, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
--
-- The expression context provides information to resolve runtime
-- information when evaluating an expression. The context provides
-- a resolver whose role is to find variables given their name.
with EL.Objects;
package EL.Functions is
pragma Preelaborate;
use EL.Objects;
No_Function : exception;
type Function_Type is (F_1_ARG, F_2_ARG, F_3_ARG, F_4_ARG);
-- Functions that can be plugged in a context and which can later
-- be used in an expression.
type Function_1_Access is access function (P : Object) return Object;
type Function_2_Access is access function (P1, P2 : Object) return Object;
type Function_3_Access is access function (P1, P2, P3 : Object) return Object;
type Function_4_Access is access function (P1, P2, P3, P4 : Object) return Object;
type Function_Access (Of_Type : Function_Type := F_1_ARG) is record
Optimize : Boolean := True;
case Of_Type is
when F_1_ARG =>
Func1 : Function_1_Access;
when F_2_ARG =>
Func2 : Function_2_Access;
when F_3_ARG =>
Func3 : Function_3_Access;
when F_4_ARG =>
Func4 : Function_4_Access;
end case;
end record;
-- ------------------------------
-- Function mapper
-- ------------------------------
--
type Function_Mapper is interface;
type Function_Mapper_Access is access all Function_Mapper'Class;
-- Find the function knowing its name.
function Get_Function (Mapper : Function_Mapper;
Namespace : String;
Name : String) return Function_Access is abstract;
-- Bind a name to a function in the given namespace.
procedure Set_Function (Mapper : in out Function_Mapper;
Namespace : in String;
Name : in String;
Func : in Function_Access) is abstract;
-- Bind a name to a function.
procedure Set_Function (Mapper : in out Function_Mapper'Class;
Namespace : in String;
Name : in String;
Func : in Function_1_Access;
Optimize : in Boolean := True);
-- Bind a name to a function.
procedure Set_Function (Mapper : in out Function_Mapper'Class;
Namespace : in String;
Name : in String;
Func : in Function_2_Access;
Optimize : in Boolean := True);
-- Bind a name to a function.
procedure Set_Function (Mapper : in out Function_Mapper'Class;
Namespace : in String;
Name : in String;
Func : in Function_3_Access;
Optimize : in Boolean := True);
-- Bind a name to a function.
procedure Set_Function (Mapper : in out Function_Mapper'Class;
Namespace : in String;
Name : in String;
Func : in Function_4_Access;
Optimize : in Boolean := True);
-- Register some pre-defined functions in the function mapper.
procedure Register_Predefined (Mapper : in out Function_Mapper'Class);
end EL.Functions;
|
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Containers.Vectors;
with Ada.Strings.Hash;
with Ada.Text_IO;
with GNAT.String_Split;
package body AOC.AOC_2019.Day06 is
type Planet is new String (1..3);
function Orbit_Maps_Hash (Key : Planet) return Ada.Containers.Hash_Type is
begin
return Ada.Strings.Hash (String (Key));
end;
package Planets is new Ada.Containers.Ordered_Sets
(Element_Type => Planet);
package Orbit_Maps is new
Ada.Containers.Hashed_Maps
(Key_Type => Planet,
Element_Type => Planets.Set,
Hash => Orbit_Maps_Hash,
Equivalent_Keys => "=",
"=" => Planets."=");
Orbits : Orbit_Maps.Map;
package Orbit_Paths is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Planet);
package Orbit_Processings is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Orbit_Paths.Vector,
"=" => Orbit_Paths."=");
Orbit_Processing : Orbit_Processings.Vector;
Total_Orbits : Natural := 0;
You_Path : Orbit_Paths.Vector;
San_Path : Orbit_Paths.Vector;
procedure Init (D : in out Day_06; Root : String) is
use Ada.Text_IO;
File : File_Type;
begin
Open (File => File,
Mode => In_File,
Name => Root & "/input/2019/day06.txt");
while not End_Of_File (File) loop
declare
use GNAT;
Orbit_Line : String := Get_Line (File);
Orbit_Set : String_Split.Slice_Set;
begin
String_Split.Create
(S => Orbit_Set,
From => Orbit_Line,
Separators => ")",
Mode => String_Split.Single);
declare
Key : Planet := Planet (String_Split.Slice (Orbit_Set, 1));
Value : Planet := Planet (String_Split.Slice (Orbit_Set, 2));
begin
if Orbits.Contains (Key) then
Orbits (Key).Insert (Value);
else
declare
Planets_Set : Planets.Set;
begin
Planets_Set.Insert (Value);
Orbits.Include (Key, Planets_Set);
end;
end if;
end;
end;
end loop;
declare
Com_Path : Orbit_Paths.Vector;
begin
Com_Path.Append ("COM");
Orbit_Processing.Append (Com_Path);
end;
while not Orbit_Processing.Is_Empty loop
declare
Path : Orbit_Paths.Vector := Orbit_Processing.First_Element;
Orbiter : Planet := Path.Last_Element;
begin
Total_Orbits := Total_Orbits + Natural (Path.Length) - 1;
Orbit_Processing.Delete_First;
if Orbits.Contains (Orbiter) then
for P of Orbits (Orbiter) loop
declare
New_Path : Orbit_Paths.Vector := Path;
begin
New_Path.Append (P);
Orbit_Processing.Append (New_Path);
end;
end loop;
elsif Orbiter = "YOU" then
You_Path := Path;
elsif Orbiter = "SAN" then
San_Path := Path;
end if;
end;
end loop;
end Init;
function Part_1 (D : Day_06) return String is
begin
return Total_Orbits'Image;
end Part_1;
function Part_2 (D : Day_06) return String is
Common_Orbit_Count : Natural := Natural'First;
begin
while You_Path (Common_Orbit_Count) = San_Path (Common_Orbit_Count) loop
Common_Orbit_Count := Common_Orbit_Count + 1;
end loop;
return Natural'Image (Natural (You_Path.Length) + Natural (San_Path.Length) - (Common_Orbit_Count + 1)*2);
end Part_2;
end AOC.AOC_2019.Day06;
|
with Ada.Text_IO;
-- This package is introduced to provide an exception free API
-- for text file input. The subprograms in the Ada.Text_IO package
-- may raise exceptions and they are therefore hidden in the body
-- of this package. A subprogram contains a declarative part and
-- and executable part:
--
-- procedure Subprogram_Name is
-- <declarative part>
-- begin
-- <executable part>
-- end Subprogram_Name;
--
-- To convince yourself that all subprograms in this package are
-- exception-free note that the declarative part of all subprogram
-- bodies are empty. This is important because introduction of a variable
-- here may raise Storage exception due to out of stack space.
-- Also note that each subprogram body contains an exception handler
-- that handles any exception raised in the executable part.
package File_IO with SPARK_Mode => On is
type Open_Result is (File_Open,
File_Closed,
Open_Error);
type File_Type is limited private with
Default_Initial_Condition => Open_Status (File_Type) = File_Closed;
procedure Open_Input_File (Name : String;
File : in out File_Type;
Is_Success : out Boolean) with
Pre => Open_Status (File) = File_Closed ,
Post => (if Is_Success then Open_Status (File) = File_Open);
function Open_Status (File : File_Type) return Open_Result;
type EOF_Result is (End_Reached,
More_Data_Exists,
EOF_Error);
function End_Of_File (File : File_Type) return EOF_Result;
subtype Last_Type is Natural range 0 .. 120;
type Read_Result (Last : Last_Type) is record
Is_Success : Boolean;
Text : String (1 .. Last);
end record;
function Read_Line (File : File_Type) return Read_Result;
procedure Close (File : in out File_Type;
Is_Success : out Boolean) with
Pre => Open_Status (File) = File_Open,
Post => Open_Status (File) = File_Closed;
private
pragma SPARK_Mode (Off);
type File_Type is limited record
Value : Ada.Text_IO.File_Type;
end record;
end File_IO;
|
with Ada.Exception_Identification.From_Here;
with Ada.Hierarchical_File_Names;
with System.Address_To_Named_Access_Conversions;
with System.Zero_Terminated_Strings;
with C.errno;
with C.stdlib;
with C.unistd;
package body System.Native_Directories.Temporary is
use Ada.Exception_Identification.From_Here;
use type C.char;
use type C.char_array;
use type C.char_ptr;
use type C.signed_int;
use type C.size_t;
package char_ptr_Conv is
new Address_To_Named_Access_Conversions (C.char, C.char_ptr);
Temp_Variable : constant C.char_array := "TMPDIR" & C.char'Val (0);
Temp_Template : constant C.char_array := "ADAXXXXXX" & C.char'Val (0);
procedure Put_Template (
Directory : String;
Template : not null C.char_ptr;
Length : out C.size_t);
procedure Put_Template (
Directory : String;
Template : not null C.char_ptr;
Length : out C.size_t)
is
Template_All : C.char_array (
0 ..
Directory'Length * Zero_Terminated_Strings.Expanding
+ 1 -- '/'
+ Temp_Template'Length);
for Template_All'Address use char_ptr_Conv.To_Address (Template);
begin
if Directory'Length = 0
or else Ada.Hierarchical_File_Names.Is_Current_Directory_Name (
Directory)
then
Length := 0;
else
Zero_Terminated_Strings.To_C (Directory, Template, Length);
if not Ada.Hierarchical_File_Names.Is_Path_Delimiter (
Character (Template_All (Length - 1))) -- Length > 0
then
Template_All (Length) :=
C.char (Ada.Hierarchical_File_Names.Default_Path_Delimiter);
Length := Length + 1;
end if;
end if;
Template_All (Length .. Length + (Temp_Template'Length - 1)) :=
Temp_Template;
Length := Length + (Temp_Template'Length - 1); -- exclude NUL
end Put_Template;
-- implementation
function Temporary_Directory return String is
Temp_Dir : C.char_ptr;
begin
Temp_Dir := C.stdlib.getenv (
Temp_Variable (Temp_Variable'First)'Access);
if Temp_Dir = null or else Temp_Dir.all = C.char'Val (0) then
return "."; -- Is_Current_Directory_Name (".") = True
else
return Zero_Terminated_Strings.Value (Temp_Dir);
end if;
end Temporary_Directory;
procedure Set_Temporary_Directory (Name : String) is
C_Name : C.char_array (
0 ..
Name'Length * Zero_Terminated_Strings.Expanding);
begin
Zero_Terminated_Strings.To_C (Name, C_Name (0)'Access);
if C.stdlib.setenv (
Temp_Variable (Temp_Variable'First)'Access,
C_Name (C_Name'First)'Access,
1) < 0
then
Raise_Exception (Use_Error'Identity);
end if;
end Set_Temporary_Directory;
function Create_Temporary_File (Directory : String) return String is
Template : C.char_array (
0 ..
Directory'Length * Zero_Terminated_Strings.Expanding
+ 1 -- '/'
+ Temp_Template'Length);
Length : C.size_t;
begin
Put_Template (Directory, Template (0)'Unchecked_Access, Length);
declare
Handle : C.signed_int;
begin
declare -- mkstemp where
use C.stdlib; -- Linux, POSIX.1-2008
use C.unistd; -- Darwin, FreeBSD
begin
Handle := mkstemp (Template (0)'Access);
end;
if Handle < 0 then
Raise_Exception (Named_IO_Exception_Id (C.errno.errno));
end if;
if C.unistd.close (Handle) < 0 then
Raise_Exception (IO_Exception_Id (C.errno.errno));
end if;
end;
return Zero_Terminated_Strings.Value (
Template (0)'Access,
Length);
end Create_Temporary_File;
function Create_Temporary_Directory (Directory : String) return String is
Template : C.char_array (
0 ..
Directory'Length * Zero_Terminated_Strings.Expanding
+ 1 -- '/'
+ Temp_Template'Length);
Length : C.size_t;
begin
Put_Template (Directory, Template (0)'Unchecked_Access, Length);
declare
Name : C.char_ptr;
begin
declare -- mkdtemp where
use C.stdlib; -- Linux, POSIX.1-2008
use C.unistd; -- Darwin, FreeBSD
begin
Name := mkdtemp (Template (0)'Access);
end;
if Name = null then
Raise_Exception (Named_IO_Exception_Id (C.errno.errno));
end if;
return Zero_Terminated_Strings.Value (Name, Length);
end;
end Create_Temporary_Directory;
end System.Native_Directories.Temporary;
|
package body Colors is
procedure Add
(Set : in out Color_Set_T;
Color : Color_T) is
begin
null;
end Add;
procedure Remove
(Set : in out Color_Set_T;
Color : Color_T) is
begin
null;
end Remove;
function Image
(Set : Color_Set_T)
return String is
begin
return "";
end Image;
end Colors;
|
with System;
with Ada.Text_IO;
procedure Impbit is
begin
Ada.Text_IO.Put_Line (System.Address'Size'Img);
end Impbit;
|
------------------------------------------------------------------------------
-- G E L A A S I S --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of this file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $:
-- Purpose:
-- Procedural wrapper over Object-Oriented ASIS implementation
------------------------------------------------------------------------------
-- Implementation restriction --
-- not implemented Inconsistent list generation --
------------------------------------------------------------------------------
with Ada.Finalization;
with Ada.Unchecked_Deallocation;
with System;
with Asis.Errors; use Asis.Errors;
with Asis.Exceptions;
with Asis.Implementation;
with Asis.Elements;
with Asis.Ada_Environments;
with Asis.Clauses;
with Asis.Expressions;
with Asis.Iterator;
with Ada.Wide_Text_IO;
package body Asis.Compilation_Units.Relations is
package Utils is
-- Compilation_Unit_List_Access --
type Compilation_Unit_List_Access is
access all Compilation_Unit_List;
procedure Deallocate is
new Ada.Unchecked_Deallocation
(Compilation_Unit_List, Compilation_Unit_List_Access);
function In_List
(List : in Compilation_Unit_List_Access;
Last : in ASIS_Integer;
Unit : in Compilation_Unit)
return Boolean;
function Append
(List : in Compilation_Unit_List_Access;
Unit : in Compilation_Unit)
return Compilation_Unit_List_Access;
function Append
(List : in Compilation_Unit_List_Access;
Units : in Compilation_Unit_List)
return Compilation_Unit_List_Access;
procedure Remove_From_List
(List : in out Compilation_Unit_List_Access;
Unit : in Compilation_Unit);
procedure Remove_From_List
(List : in out Compilation_Unit_List;
From : in List_Index;
Unit : in Compilation_Unit);
-- Tree --
type Root_Tree is
new Ada.Finalization.Limited_Controlled with private;
type Root_Tree_Access is access all Root_Tree;
type Tree_Node is
new Ada.Finalization.Limited_Controlled with private;
type Tree_Node_Access is access all Tree_Node;
-- Tree_Node_Array --
type Tree_Node_Array is array (Positive range <>) of Tree_Node_Access;
type Tree_Node_Array_Access is access all Tree_Node_Array;
procedure Deallocate is
new Ada.Unchecked_Deallocation
(Tree_Node_Array, Tree_Node_Array_Access);
function Append
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access;
function In_List
(List : in Tree_Node_Array_Access;
Last : in Natural;
Node : in Tree_Node_Access)
return Boolean;
-- Root_Tree --
type Orders is (Ascending, Descending);
procedure Dependence_Order
(This : in Root_Tree_Access;
Order : in Orders);
function Add_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access;
function Add_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Spec_Unit : in Compilation_Unit;
Body_Unit : in Compilation_Unit;
Skip_Spec : in Boolean := False)
return Tree_Node_Access;
function Add_Subunit
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access;
procedure Append
(This : in Root_Tree_Access;
Unit : in Compilation_Unit);
procedure Glue_Nodes
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access);
procedure Glue_Nodes_Checked
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access);
procedure Set_Parent
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Parent : in Tree_Node_Access);
procedure Clear
(This : in out Root_Tree);
procedure Add_Body_Dependents
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access);
function Find
(This : in Root_Tree_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access;
procedure Check
(This : in Root_Tree_Access;
The_Context : in Asis.Context);
function Generate_Relationship
(This : in Root_Tree_Access;
Limit_List : in Utils.Compilation_Unit_List_Access;
List_Last : in ASIS_Integer)
return Relationship;
function Create_Elaboration_Tree
(This : in Root_Tree_Access;
The_Context : in Asis.Context)
return Root_Tree_Access;
function Is_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access)
return Boolean;
function Is_Have_Circular_Dependences
(This : in Root_Tree_Access)
return Boolean;
-- Tree_Node --
function Is_Skip_Spec
(This : in Tree_Node_Access)
return Boolean;
procedure Skip_Spec
(This : in Tree_Node_Access;
Value : in Boolean);
function Nexts
(This : in Tree_Node_Access)
return Tree_Node_Array_Access;
function Get_Spec
(This : in Tree_Node_Access)
return Compilation_Unit;
function Get_Body
(This : in Tree_Node_Access)
return Compilation_Unit;
Use_Error : exception;
private
-- Tree_Node --
type Extended_Boolean is (Unknown, Extended_True, Extended_False);
type Tree_Node is
new Ada.Finalization.Limited_Controlled with record
Self : Tree_Node_Access := Tree_Node'Unchecked_Access;
-- ссылка на предыдущие елементы
Prevs : Tree_Node_Array_Access := null;
-- последующие елементы
Next : Tree_Node_Array_Access := null;
-- модуль_компиляции
Unit : Compilation_Unit := Nil_Compilation_Unit;
Unit_Body : Compilation_Unit := Nil_Compilation_Unit;
Skip_Spec : Boolean := False;
Added : Boolean := False;
Consistent : Boolean := True;
Body_Consistent : Boolean := True;
-- зависимости тела (with)
Body_Dependences : Tree_Node_Array_Access := null;
-- список циклических зависимостей
Circular : Compilation_Unit_List_Access := null;
Circular_Added : Boolean := False;
-- список пропавших юнитов
Missing : Compilation_Unit_List_Access := null;
Missing_Added : Boolean := False;
-- список несоглассованных юнитов
Inconsistent : Compilation_Unit_List_Access := null;
Inconsistent_Added : Boolean := False;
Elaborated : Boolean := False;
Body_Elaborated : Boolean := False;
Internal_Pure : Extended_Boolean := Unknown;
Internal_Preelaborate : Extended_Boolean := Unknown;
Internal_Spec_With_Body : Extended_Boolean := Unknown;
end record;
procedure Finalize
(This : in out Tree_Node);
function Is_Pure
(This : in Tree_Node_Access)
return Boolean;
function Is_Preelaborate
(This : in Tree_Node_Access)
return Boolean;
function Is_Elaborate_Body
(This : in Tree_Node_Access)
return Boolean;
procedure Retrive_Pragmas
(This : in Tree_Node_Access);
-- Root_Tree --
type Unit_Node is record
Unit : Compilation_Unit;
Node : Tree_Node_Access;
end record;
type Unit_Node_Array is array (Positive range <>) of Unit_Node;
type Unit_Node_Array_Access is access all Unit_Node_Array;
type Root_Tree is
new Ada.Finalization.Limited_Controlled with record
Self : Root_Tree_Access := Root_Tree'Unchecked_Access;
Order : Orders := Descending;
Next : Tree_Node_Array_Access := null;
-- сортированный список всех
-- елементов для быстрого
-- определения наличия елемента
-- в списке
Units : Unit_Node_Array_Access := null;
Last_Node : Tree_Node_Access := null;
end record;
procedure Finalize
(This : in out Root_Tree);
-- Additional --
procedure Deallocate is
new Ada.Unchecked_Deallocation
(Tree_Node, Tree_Node_Access);
procedure Deallocate is
new Ada.Unchecked_Deallocation
(Unit_Node_Array, Unit_Node_Array_Access);
type Positive_Access is access all Positive;
function Add_Node
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access;
procedure Remove
(List : in out Tree_Node_Array_Access;
Node : in Tree_Node_Access);
function Remove
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access;
function Add_Node_Ordered
(List : in Unit_Node_Array_Access;
Node : in Tree_Node_Access)
return Unit_Node_Array_Access;
function Find
(List : in Unit_Node_Array_Access;
Unit : in Compilation_Unit;
From : in Positive;
To : in Positive;
Index : in Positive_Access)
return Boolean;
function Compare
(Left : in Compilation_Unit;
Right : in Compilation_Unit)
return Integer;
function Is_Inconsistent
(Unit : in Compilation_Unit)
return Boolean;
function Is_Source_Changed
(Unit : in Compilation_Unit)
return Boolean;
end Utils;
procedure Deallocate is
new Ada.Unchecked_Deallocation
(Utils.Root_Tree, Utils.Root_Tree_Access);
procedure Check_Compilation_Unit
(Unit : in Compilation_Unit;
The_Context : in Asis.Context;
Message : in Wide_String);
procedure Normalize
(List : in Asis.Compilation_Unit_List;
Result : in Utils.Compilation_Unit_List_Access;
Last : out ASIS_Integer);
function Get_Ancestors
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
function Get_Descendants
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
function Get_Supporters
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
function Get_Dependents
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
function Get_Family
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
function Get_Needed_Units
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access;
procedure Get_Subunits
(Tree : in Utils.Root_Tree_Access;
Unit : in Compilation_Unit;
Node : in Utils.Tree_Node_Access;
The_Context : in Asis.Context);
function Get_Compilation_Unit
(Unit : in Compilation_Unit;
Target : in Asis.Element;
Number : in List_Index;
The_Context : in Asis.Context)
return Asis.Compilation_Unit;
function Have_With
(Library : in Compilation_Unit;
Unit : in Compilation_Unit;
The_Context : in Asis.Context)
return Boolean;
type Check_10_1_1_26c_26b_Information is record
Exceptions : Boolean := False;
System : Boolean := False;
end record;
function Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
The_Context : in Asis.Context)
return Check_10_1_1_26c_26b_Information;
----------------------------
-- Check_Compilation_Unit --
----------------------------
procedure Check_Compilation_Unit
(Unit : in Compilation_Unit;
The_Context : in Asis.Context;
Message : in Wide_String)
is
Kind : Asis.Unit_Kinds;
begin
Kind := Unit_Kind (Unit);
if Kind = Not_A_Unit
or else Kind = A_Nonexistent_Declaration
or else Kind = A_Nonexistent_Body
or else Kind = A_Configuration_Compilation
then
Asis.Implementation.Set_Status
(Data_Error, Message & " invalid unit " & Unit_Full_Name (Unit));
raise Asis.Exceptions.ASIS_Inappropriate_Compilation_Unit;
end if;
if not Asis.Ada_Environments.Is_Equal
(Enclosing_Context (Unit), The_Context)
then
Asis.Implementation.Set_Status
(Data_Error, Message & " invalid unit's context "
& Unit_Full_Name (Unit));
raise Asis.Exceptions.ASIS_Inappropriate_Compilation_Unit;
end if;
end Check_Compilation_Unit;
---------------
-- Normalize --
---------------
procedure Normalize
(List : in Asis.Compilation_Unit_List;
Result : in Utils.Compilation_Unit_List_Access;
Last : out ASIS_Integer)
is
Unit : Compilation_Unit;
begin
Last := 0;
for Index in List'Range loop
Unit := List (Index);
if not Is_Nil (Unit)
and then Unit_Kind (Unit) /= An_Unknown_Unit
then
if not Utils.In_List (Result, Last, Unit) then
Last := Last + 1;
Result (Last) := List (Index);
end if;
end if;
end loop;
end Normalize;
-------------------------
-- Elaboration_Order --
-------------------------
function Elaboration_Order
(Compilation_Units : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Relationship
is
procedure Clear;
Tree : Utils.Root_Tree_Access := null;
Elaborate_Tree : Utils.Root_Tree_Access := null;
Compilation_Units_Last : ASIS_Integer := 0;
Normalized_Compilation_Units :
Utils.Compilation_Unit_List_Access := null;
-- Clear --
procedure Clear is
begin
Deallocate (Tree);
Deallocate (Elaborate_Tree);
Utils.Deallocate (Normalized_Compilation_Units);
end Clear;
begin
if Compilation_Units = Nil_Compilation_Unit_List then
return Nil_Relationship;
end if;
for Index in Compilation_Units'Range loop
Check_Compilation_Unit
(Compilation_Units (Index), The_Context,
"Elaboration_Order:Compilation_Unit");
end loop;
Normalized_Compilation_Units := new
Asis.Compilation_Unit_List (1 .. Compilation_Units'Length);
Normalized_Compilation_Units.all := (others => Nil_Compilation_Unit);
Normalize (Compilation_Units,
Normalized_Compilation_Units,
Compilation_Units_Last);
Tree := Get_Needed_Units
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
Utils.Check (Tree, The_Context);
if Utils.Is_Have_Circular_Dependences (Tree) then
Clear;
Asis.Implementation.Set_Status
(Data_Error, "Elaboration_Order - "
& "Circular semantic dependence detected, can not create "
& "elaboration order");
raise Asis.Exceptions.ASIS_Failed;
end if;
Elaborate_Tree := Utils.Create_Elaboration_Tree (Tree, The_Context);
declare
Relation : Relationship := Utils.Generate_Relationship
(Elaborate_Tree, null, 0);
begin
Clear;
return Relation;
end;
exception
when others =>
Clear;
raise;
end Elaboration_Order;
---------------------------------
-- Semantic_Dependence_Order --
---------------------------------
function Semantic_Dependence_Order
(Compilation_Units : in Asis.Compilation_Unit_List;
Dependent_Units : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context;
Relation : in Asis.Relation_Kinds)
return Relationship
is
procedure Clear;
Compilation_Units_Last : ASIS_Integer := 0;
Normalized_Compilation_Units :
Utils.Compilation_Unit_List_Access := null;
Dependent_Units_Last : ASIS_Integer := 0;
Normalized_Dependent_Units :
Utils.Compilation_Unit_List_Access := null;
Tree : Utils.Root_Tree_Access := null;
procedure Clear is begin
Deallocate (Tree);
Utils.Deallocate (Normalized_Compilation_Units);
Utils.Deallocate (Normalized_Dependent_Units);
end Clear;
begin
if Compilation_Units = Nil_Compilation_Unit_List then
return Nil_Relationship;
end if;
for Index in Compilation_Units'Range loop
Check_Compilation_Unit
(Compilation_Units (Index), The_Context,
"Semantic_Dependence_Order:Compilation_Unit");
end loop;
Normalized_Compilation_Units := new
Asis.Compilation_Unit_List (1 .. Compilation_Units'Length);
Normalized_Compilation_Units.all := (others => Nil_Compilation_Unit);
Normalize (Compilation_Units,
Normalized_Compilation_Units,
Compilation_Units_Last);
-- Dependent_Units are ignored unless the Relation
-- is Descendants or Dependents
if (Relation = Descendants or else Relation = Dependents)
and then Dependent_Units /= Nil_Compilation_Unit_List
then
for Index in Dependent_Units'Range loop
Check_Compilation_Unit
(Dependent_Units (Index), The_Context,
"Semantic_Dependence_Order:Dependent_Unit");
end loop;
Normalized_Dependent_Units := new
Asis.Compilation_Unit_List (1 .. Dependent_Units'Length);
Normalized_Dependent_Units.all := (others => Nil_Compilation_Unit);
Normalize (Dependent_Units,
Normalized_Dependent_Units,
Dependent_Units_Last);
end if;
case Relation is
when Ancestors =>
Tree := Get_Ancestors
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
when Descendants =>
Tree := Get_Descendants
(Normalized_Compilation_Units
(1 .. Compilation_Units_Last), The_Context);
when Supporters =>
Tree := Get_Supporters
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
when Dependents =>
Tree := Get_Dependents
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
when Family =>
Tree := Get_Family
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
when Needed_Units =>
Tree := Get_Needed_Units
(Normalized_Compilation_Units (1 .. Compilation_Units_Last),
The_Context);
end case;
Utils.Check (Tree, The_Context);
declare
Relation : Relationship := Utils.Generate_Relationship
(Tree, Normalized_Dependent_Units, Dependent_Units_Last);
begin
Clear;
return Relation;
end;
exception
when others =>
Clear;
raise;
end Semantic_Dependence_Order;
-------------------
-- Get_Ancestors --
-------------------
function Get_Ancestors
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
Unit : Compilation_Unit;
Kinds : Unit_Kinds;
Result : Root_Tree_Access := new Root_Tree;
procedure Append_Node
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access);
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access);
-- Append_Node --
procedure Append_Node
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access)
is
Exist_Node : Tree_Node_Access;
begin
Exist_Node := Find (Result, Unit);
if Exist_Node /= null then
Glue_Nodes (Result, Node, Exist_Node);
Node := null;
else
Node := Add_Child (Result, Node, Unit);
end if;
end Append_Node;
-- Retrive --
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access)
is
Internal_Node : Tree_Node_Access := Node;
Internal_Unit : Compilation_Unit := Unit;
begin
while Unit_Kind (Internal_Unit) in
A_Procedure .. A_Generic_Package_Renaming
loop
Append_Node (Internal_Unit, Internal_Node);
if Internal_Node = null then
return;
end if;
Internal_Unit := Corresponding_Parent_Declaration (Internal_Unit);
end loop;
if not Is_Nil (Internal_Unit) then
Append_Node (Internal_Unit, Internal_Node);
if Internal_Node = null then
return;
end if;
-- add Standart as root
Append_Node
(Library_Unit_Declaration ("Standard", The_Context),
Internal_Node);
end if;
end Retrive;
begin
Dependence_Order (Result, Ascending);
for Index in List'Range loop
Unit := List (Index);
if Find (Result, Unit) = null then
Kinds := Unit_Kind (Unit);
if Kinds in A_Subunit then
Asis.Implementation.Set_Status
(Data_Error, "Subunit not valid for Ancestors request "
& Unit_Full_Name (Unit));
raise Asis.Exceptions.ASIS_Inappropriate_Compilation_Unit;
elsif Kinds in A_Library_Unit_Body then
Unit := Corresponding_Parent_Declaration (Unit, The_Context);
end if;
Retrive (Unit, null);
end if;
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Get_Ancestors;
---------------------
-- Get_Descendants --
---------------------
function Get_Descendants
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
Result : Root_Tree_Access := new Root_Tree;
Unit : Compilation_Unit;
Second_Unit : Compilation_Unit;
Kinds : Unit_Kinds;
procedure Retrive
(Target : in Compilation_Unit;
Node : in Utils.Tree_Node_Access);
-- Retrive --
procedure Retrive
(Target : in Compilation_Unit;
Node : in Utils.Tree_Node_Access)
is
function Process
(Index : in List_Index)
return Boolean;
Exist_Node : Utils.Tree_Node_Access := null;
Children_List : Asis.Compilation_Unit_List :=
Corresponding_Children (Target, The_Context);
-- Process --
function Process
(Index : in List_Index)
return Boolean
is
begin
Kinds := Unit_Kind (Unit);
Exist_Node := Find (Result, Unit);
Second_Unit := Nil_Compilation_Unit;
if Exist_Node /= null then
Glue_Nodes (Result, Node, Exist_Node);
if Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body (Unit, The_Context);
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration (Unit, The_Context);
end if;
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Unit)
then
Remove_From_List (Children_List, Index + 1, Second_Unit);
end if;
return False;
end if;
if Kinds in
A_Procedure_Instance .. A_Generic_Package_Renaming
then
Exist_Node := Add_Child (Result, Node, Unit);
elsif Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body (Unit, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Unit)
then
Exist_Node := Add_Child (Result, Node, Unit, Second_Unit);
Remove_From_List (Children_List, Index + 1, Second_Unit);
else
Exist_Node := Add_Child (Result, Node, Unit);
end if;
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration (Unit, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Unit)
then
Exist_Node := Add_Child (Result, Node, Second_Unit, Unit);
Remove_From_List (Children_List, Index + 1, Second_Unit);
Unit := Second_Unit;
else
Exist_Node := Add_Child (Result, Node, Unit);
end if;
else
Exist_Node := Add_Child (Result, Node, Unit);
end if;
return True;
end Process;
begin
for Index in Children_List'Range loop
Unit := Children_List (Index);
if not Is_Nil (Unit) then
if Process (Index) then
Kinds := Unit_Kind (Unit);
if Kinds = A_Package
or else Kinds = A_Generic_Package
or else Kinds = A_Package_Instance
then
Retrive (Unit, Exist_Node);
end if;
end if;
end if;
end loop;
end Retrive;
Declarations_List :
Utils.Compilation_Unit_List_Access := null;
Declarations_Last : ASIS_Integer := 0;
begin
Dependence_Order (Result, Descending);
Declarations_List := new Asis.Compilation_Unit_List (1 .. List'Length);
for Index in List'Range loop
Unit := List (Index);
Kinds := Unit_Kind (Unit);
if Kinds in A_Subunit then
Asis.Implementation.Set_Status
(Data_Error, "Subunit not valid for Descendants request "
& Unit_Full_Name (Unit));
end if;
if Kinds in A_Library_Unit_Body then
Unit := Corresponding_Declaration (Unit);
Kinds := Unit_Kind (Unit);
end if;
if Kinds = A_Package
or else Kinds = A_Generic_Package
or else Kinds = A_Package_Instance
then
if not In_List (Declarations_List, Declarations_Last, Unit) then
Declarations_Last := Declarations_Last + 1;
Declarations_List (Declarations_Last) := Unit;
end if;
end if;
end loop;
for Index in 1 .. Declarations_Last loop
Unit := Declarations_List (Index);
if Find (Result, Unit) = null then
Second_Unit := Corresponding_Body (Unit, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Unit)
then
Retrive (Unit, Add_Child (Result, null, Unit, Second_Unit));
else
Retrive (Unit, Add_Child (Result, null, Unit));
end if;
end if;
end loop;
Deallocate (Declarations_List);
return Result;
exception
when others =>
Deallocate (Declarations_List);
Deallocate (Result);
raise;
end Get_Descendants;
--------------------
-- Get_Supporters --
--------------------
function Get_Supporters
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
Unit : Compilation_Unit;
Kinds : Unit_Kinds;
Result : Root_Tree_Access := new Root_Tree;
Node : Tree_Node_Access := null;
Std : Compilation_Unit :=
Library_Unit_Declaration ("Standard", The_Context);
procedure Append_Unit
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access);
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean := False);
procedure Retrive_Declarations
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean);
procedure Retrive_Body
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean);
procedure Retrive_Subunit
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access);
procedure Retrive_With_Clause
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False);
procedure Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False);
-- Append_Unit --
procedure Append_Unit
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access)
is
Exist_Node : Tree_Node_Access;
begin
Exist_Node := Find (Result, Unit);
if Exist_Node = null then
Node := Add_Child (Result, Node, Unit);
else
if Node /= null then
Glue_Nodes_Checked (Result, Node, Exist_Node);
Node := null;
end if;
end if;
end Append_Unit;
-- Retrive --
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean := False)
is
Internal_Node : Tree_Node_Access := Node;
begin
if Is_Nil (Unit) then
return;
end if;
Kinds := Unit_Kind (Unit);
if Kinds in A_Nonexistent_Declaration .. An_Unknown_Unit then
Append_Unit (Std, Internal_Node);
elsif Kinds in A_Subunit then
Retrive_Subunit (Unit, Node);
elsif Kinds in A_Procedure_Body .. A_Package_Body then
Retrive_Body (Unit, Node, First_Node);
else
Retrive_Declarations (Unit, Node, First_Node);
end if;
end Retrive;
-- Retrive_Declarations --
procedure Retrive_Declarations
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean)
is
Parent : Compilation_Unit;
Internal_Node : Tree_Node_Access := Node;
begin
if not First_Node then
Append_Unit (Unit, Internal_Node);
if Internal_Node = null then
return;
end if;
end if;
if Is_Identical (Unit, Std) then
return;
end if;
Check_10_1_1_26c_26b (Unit, Internal_Node);
Retrive_With_Clause (Unit, Internal_Node);
Parent := Corresponding_Parent_Declaration (Unit, The_Context);
while Unit_Kind (Parent) in
A_Procedure .. A_Generic_Package_Renaming
loop
Append_Unit (Parent, Internal_Node);
if Internal_Node = null
or else Is_Identical (Unit, Std)
then
return;
end if;
Check_10_1_1_26c_26b (Parent, Internal_Node);
Retrive_With_Clause (Parent, Internal_Node);
Parent := Corresponding_Parent_Declaration (Parent, The_Context);
end loop;
Retrive (Parent, Internal_Node);
end Retrive_Declarations;
-- Retrive_Body --
procedure Retrive_Body
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
First_Node : in Boolean)
is
Internal_Node : Tree_Node_Access := Node;
begin
if not First_Node then
Append_Unit (Unit, Internal_Node);
if Internal_Node = null then
return;
end if;
end if;
Check_10_1_1_26c_26b (Unit, Internal_Node, True);
Retrive_With_Clause (Unit, Internal_Node, True);
Retrive
(Corresponding_Parent_Declaration (Unit, The_Context),
Internal_Node);
end Retrive_Body;
-- Retrive_Subunit --
procedure Retrive_Subunit
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access)
is
Parent : Compilation_Unit;
vNode : Tree_Node_Access := Node;
begin
Check_10_1_1_26c_26b (Unit, null, True);
Retrive_With_Clause (Unit, null, True);
Parent := Corresponding_Subunit_Parent_Body (Unit);
while Unit_Kind (Parent) in A_Subunit loop
Append_Unit (Unit, vNode);
if vNode = null then
return;
end if;
Check_10_1_1_26c_26b (Parent, vNode, True);
Retrive_With_Clause (Parent, vNode, True);
Parent := Corresponding_Subunit_Parent_Body (Parent);
end loop;
Retrive (Parent, vNode);
end Retrive_Subunit;
-- Retrive_With_Clause --
procedure Retrive_With_Clause
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False)
is
With_List : constant Asis.Context_Clause_List :=
Asis.Elements.Context_Clause_Elements (Unit);
Internal_Unit : Compilation_Unit;
Exist_Node : Tree_Node_Access;
begin
for Index in With_List'Range loop
if Clause_Kind (With_List (Index).all) = A_With_Clause then
Internal_Unit := Get_Compilation_Unit
(Unit, With_List (Index), Index, The_Context);
if not Is_Nil (Internal_Unit) then
if not For_Body then
Retrive (Internal_Unit, Node);
else
Exist_Node := Find (Result, Internal_Unit);
if Exist_Node = null then
Exist_Node := Add_Child (Result, null, Internal_Unit);
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
Retrive (Internal_Unit, Exist_Node, True);
else
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
end if;
end if;
end if;
end if;
end loop;
end Retrive_With_Clause;
-- Check_10_1_1_26c_26b --
procedure Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False)
is
procedure Retrive_For_Body
(Unit : in Compilation_Unit);
Except : Compilation_Unit := Library_Unit_Declaration
("Ada.Exceptions", The_Context);
Sys : Compilation_Unit := Library_Unit_Declaration
("System", The_Context);
State : Check_10_1_1_26c_26b_Information;
-- Retrive_For_Body --
procedure Retrive_For_Body
(Unit : in Compilation_Unit)
is
Exist_Node : Tree_Node_Access;
begin
Exist_Node := Find (Result, Unit);
if Exist_Node = null then
Exist_Node := Add_Child (Result, null, Unit);
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
Retrive (Unit, Exist_Node, True);
else
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
end if;
end Retrive_For_Body;
begin
State := Check_10_1_1_26c_26b (Unit, The_Context);
if State.Exceptions then
if not For_Body then
Retrive (Except, Node);
else
Retrive_For_Body (Except);
end if;
end if;
if State.System then
if not For_Body then
Retrive (Sys, Node);
else
Retrive_For_Body (Sys);
end if;
end if;
end Check_10_1_1_26c_26b;
begin
Dependence_Order (Result, Ascending);
for Index in List'Range loop
Unit := List (Index);
if Find (Result, Unit) = null then
Retrive (Unit, null, True);
end if;
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Get_Supporters;
--------------------
-- Get_Dependents --
--------------------
function Get_Dependents
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
procedure Append_To_Node
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Glued : in out Tree_Node_Array_Access);
procedure Post_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean);
function Have_Except
(Unit : in Compilation_Unit)
return Boolean;
function Have_Sys
(Unit : in Compilation_Unit)
return Boolean;
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access);
Result : Root_Tree_Access := new Root_Tree;
Unit, Body_Unit : Compilation_Unit;
Kinds : Unit_Kinds;
Except : Compilation_Unit := Library_Unit_Declaration
("Ada.Exceptions", The_Context);
Sys : Compilation_Unit := Library_Unit_Declaration
("System", The_Context);
procedure Append_To_Node
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Glued : in out Tree_Node_Array_Access)
is
Exist_Node : Tree_Node_Access := null;
Second_Unit : Compilation_Unit;
begin
Exist_Node := Find (Result, Unit);
Kinds := Unit_Kind (Unit);
if Kinds in A_Procedure .. A_Generic_Package then
if Exist_Node /= null then
if Is_Child (Result, Exist_Node) then
Set_Parent (Result, Exist_Node, Node);
else
Glue_Nodes_Checked (Result, Node, Exist_Node);
end if;
if not Is_Skip_Spec (Exist_Node) then
Glued := Append (Glued, Exist_Node);
else
Skip_Spec (Exist_Node, False);
end if;
else
Second_Unit := Corresponding_Body (Unit, The_Context);
Exist_Node := Add_Child (Result, Node, Unit, Second_Unit);
end if;
elsif Kinds in A_Library_Unit_Body then
if Exist_Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
else
Second_Unit := Corresponding_Declaration (Unit, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Unit)
then
Exist_Node := Find (Result, Second_Unit);
if Exist_Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
else
Exist_Node := Add_Child
(Result, null, Second_Unit, Unit, True);
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
else
Exist_Node := Add_Child (Result, null, Unit);
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
end if;
elsif Kinds in A_Subunit then
if Exist_Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
else
Exist_Node := Add_Child (Result, null, Unit);
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
else
if Exist_Node /= null then
Glue_Nodes_Checked (Result, Node, Exist_Node);
if not Is_Skip_Spec (Exist_Node) then
Glued := Append (Glued, Exist_Node);
else
Skip_Spec (Exist_Node, False);
end if;
else
Exist_Node := Add_Child (Result, Node, Unit);
end if;
end if;
end Append_To_Node;
procedure Post_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean)
is
begin
null;
end Post_Operation;
-- Have_Except --
function Have_Except
(Unit : in Compilation_Unit)
return Boolean
is
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean);
Control : Traverse_Control := Continue;
State : Boolean := False;
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean)
is
use Asis.Elements;
begin
if Declaration_Kind (Element) =
A_Choice_Parameter_Specification
then
State := True;
Control := Terminate_Immediately;
end if;
end Pre_Operation;
procedure Check_Choice_Iterator is new
Asis.Iterator.Traverse_Element
(Boolean, Pre_Operation, Post_Operation);
begin
Check_Choice_Iterator
(Asis.Elements.Unit_Declaration (Unit), Control, State);
return State;
end Have_Except;
-- Have_Sys --
function Have_Sys
(Unit : in Compilation_Unit)
return Boolean
is
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean);
Control : Traverse_Control := Continue;
State : Boolean := False;
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Boolean)
is
use Asis.Elements;
begin
if Expression_Kind (Element) = An_Attribute_Reference
and then Attribute_Kind (Element) = An_Address_Attribute
then
State := True;
Control := Terminate_Immediately;
end if;
end Pre_Operation;
procedure Check_Choice_Iterator is new
Asis.Iterator.Traverse_Element
(Boolean, Pre_Operation, Post_Operation);
begin
Check_Choice_Iterator
(Asis.Elements.Unit_Declaration (Unit), Control, State);
return State;
end Have_Sys;
-- Retrive --
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access)
is
use Utils;
Exist_Node : Tree_Node_Access := null;
Glued : Tree_Node_Array_Access := null;
begin
if Is_Nil (Unit) then
return;
end if;
-- subunits --
if not Is_Nil (Get_Body (Node)) then
Get_Subunits (Result, Get_Body (Node), Node, The_Context);
end if;
-- childrens --
declare
Children_List : Asis.Compilation_Unit_List :=
Corresponding_Children (Unit, The_Context);
Children : Compilation_Unit;
Second_Unit : Compilation_Unit;
begin
for Index in Children_List'Range loop
Children := Children_List (Index);
if not Is_Nil (Children) then
Second_Unit := Nil_Compilation_Unit;
Kinds := Unit_Kind (Children);
Exist_Node := Find (Result, Children);
if Exist_Node /= null then
if Is_Child (Result, Exist_Node) then
Set_Parent (Result, Exist_Node, Node);
else
Glue_Nodes_Checked (Result, Node, Exist_Node);
end if;
if not Is_Skip_Spec (Exist_Node) then
Glued := Append (Glued, Exist_Node);
else
Skip_Spec (Exist_Node, False);
end if;
if Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body
(Children, The_Context);
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration
(Children, The_Context);
end if;
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Remove_From_List
(Children_List, Index + 1, Second_Unit);
end if;
else
if Kinds in
A_Procedure_Instance .. A_Generic_Package_Renaming
then
Exist_Node := Add_Child (Result, Node, Children);
elsif Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body
(Children, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Exist_Node := Add_Child
(Result, Node, Children, Second_Unit);
Remove_From_List
(Children_List, Index + 1, Second_Unit);
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration
(Children, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Exist_Node := Add_Child
(Result, Node, Second_Unit, Children);
Remove_From_List
(Children_List, Index + 1, Second_Unit);
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
end if;
end if;
end loop;
end;
-- with --
declare
Units : Asis.Compilation_Unit_List :=
Compilation_Units (The_Context);
Library : Compilation_Unit;
begin
for Index in Units'Range loop
Library := Units (Index);
if not Is_Nil (Library) then
if Have_With (Library, Unit, The_Context) then
Append_To_Node (Library, Node, Glued);
end if;
end if;
end loop;
end;
-- Ada.Exceptions --
if Is_Identical (Unit, Except) then
declare
Units : Asis.Compilation_Unit_List :=
Compilation_Units (The_Context);
Library : Compilation_Unit;
begin
for Index in Units'Range loop
Library := Units (Index);
if not Is_Nil (Library) then
if Have_Except (Library) then
Append_To_Node (Library, Node, Glued);
end if;
end if;
end loop;
end;
end if;
-- System --
if Is_Identical (Unit, Sys) then
declare
Units : Asis.Compilation_Unit_List :=
Compilation_Units (The_Context);
Library : Compilation_Unit;
begin
for Index in Units'Range loop
Library := Units (Index);
if not Is_Nil (Library) then
if Have_Sys (Library) then
Append_To_Node (Library, Node, Glued);
end if;
end if;
end loop;
end;
end if;
declare
Next : Tree_Node_Array_Access := Nexts (Node);
Next_Node : Tree_Node_Access;
Next_Unit : Compilation_Unit;
begin
if Next /= null then
for Index in Next'Range loop
Next_Node := Next (Index);
if Glued = null
or else not Utils.In_List
(Glued, Glued.all'Last, Next_Node)
then
Next_Unit := Get_Spec (Next_Node);
Kinds := Unit_Kind (Next_Unit);
if Kinds in
A_Procedure .. A_Generic_Package_Renaming
then
Retrive (Next_Unit, Next_Node);
elsif Kinds in
A_Procedure_Body .. A_Package_Body
then
Get_Subunits
(Result, Next_Unit, Next_Node, The_Context);
end if;
end if;
end loop;
end if;
end;
Deallocate (Glued);
exception
when others =>
Deallocate (Glued);
raise;
end Retrive;
begin
Dependence_Order (Result, Descending);
for Index in List'Range loop
Unit := List (Index);
if Find (Result, Unit) = null then
Kinds := Unit_Kind (Unit);
if Kinds in A_Procedure .. A_Generic_Package_Renaming then
Body_Unit := Corresponding_Body (Unit, The_Context);
if not Is_Identical (Body_Unit, Unit) then
Retrive (Unit, Add_Child
(Result, null, Unit, Body_Unit, True));
else
Retrive (Unit, null);
end if;
elsif Kinds in A_Procedure_Body .. A_Protected_Body_Subunit then
Get_Subunits
(Result, Unit, Add_Child (Result, null, Unit), The_Context);
end if;
end if;
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Get_Dependents;
----------------
-- Get_Family --
----------------
function Get_Family
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access);
Result : Root_Tree_Access := new Root_Tree;
Unit, Body_Unit : Compilation_Unit;
Kinds : Unit_Kinds;
-- Retrive --
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access)
is
use Utils;
Exist_Node : Tree_Node_Access := null;
Glued : Tree_Node_Array_Access := null;
begin
if Is_Nil (Unit) then
return;
end if;
-- subunits --
if not Is_Nil (Get_Body (Node)) then
Get_Subunits (Result, Get_Body (Node), Node, The_Context);
end if;
-- childrens --
declare
Children_List : Asis.Compilation_Unit_List :=
Corresponding_Children (Unit, The_Context);
Children : Compilation_Unit;
Second_Unit : Compilation_Unit;
begin
for Index in Children_List'Range loop
Children := Children_List (Index);
if not Is_Nil (Children) then
Second_Unit := Nil_Compilation_Unit;
Kinds := Unit_Kind (Children);
Exist_Node := Find (Result, Children);
if Exist_Node /= null then
Glue_Nodes_Checked (Result, Node, Exist_Node);
if Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body
(Children, The_Context);
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration
(Children, The_Context);
end if;
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Remove_From_List
(Children_List, Index + 1, Second_Unit);
end if;
else
if Kinds in
A_Procedure_Instance .. A_Generic_Package_Renaming
then
Exist_Node := Add_Child (Result, Node, Children);
elsif Kinds in A_Procedure .. A_Generic_Package then
Second_Unit := Corresponding_Body
(Children, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Exist_Node := Add_Child
(Result, Node, Children, Second_Unit);
Remove_From_List
(Children_List, Index + 1, Second_Unit);
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
elsif Kinds in A_Library_Unit_Body then
Second_Unit := Corresponding_Declaration
(Children, The_Context);
if not Is_Nil (Second_Unit)
and then not Is_Identical (Second_Unit, Children)
then
Exist_Node := Add_Child
(Result, Node, Second_Unit, Children);
Remove_From_List
(Children_List, Index + 1, Second_Unit);
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
else
Exist_Node := Add_Child (Result, Node, Children);
end if;
end if;
end if;
end loop;
end;
declare
Next : Tree_Node_Array_Access := Nexts (Node);
Next_Node : Tree_Node_Access;
Next_Unit : Compilation_Unit;
begin
if Next /= null then
for Index in Next'Range loop
Next_Node := Next (Index);
Next_Unit := Get_Spec (Next_Node);
Kinds := Unit_Kind (Next_Unit);
if Kinds in
A_Procedure .. A_Generic_Package_Renaming
then
Retrive (Next_Unit, Next_Node);
elsif Kinds in
A_Procedure_Body .. A_Package_Body
then
Get_Subunits
(Result, Next_Unit, Next_Node, The_Context);
end if;
end loop;
end if;
end;
end Retrive;
begin
Dependence_Order (Result, Descending);
for Index in List'Range loop
Unit := List (Index);
if Find (Result, Unit) = null then
Kinds := Unit_Kind (Unit);
if Kinds in A_Procedure .. A_Generic_Package_Renaming then
Body_Unit := Corresponding_Body (Unit, The_Context);
elsif Kinds in A_Procedure_Body .. A_Protected_Body_Subunit then
Body_Unit := Unit;
Unit := Corresponding_Declaration (Unit, The_Context);
end if;
if not Is_Identical (Body_Unit, Unit) then
Retrive (Unit, Add_Child (Result, null, Unit, Body_Unit));
else
Retrive (Unit, Add_Child (Result, null, Unit));
end if;
end if;
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Get_Family;
----------------------
-- Get_Needed_Units --
----------------------
function Get_Needed_Units
(List : in Asis.Compilation_Unit_List;
The_Context : in Asis.Context)
return Utils.Root_Tree_Access
is
use Utils;
Result : Root_Tree_Access := new Root_Tree;
Unit, Body_Unit : Compilation_Unit;
Kinds : Unit_Kinds;
Std : Compilation_Unit :=
Library_Unit_Declaration ("Standard", The_Context);
procedure Append_Unit
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access;
Unit_Body : in Compilation_Unit := Nil_Compilation_Unit);
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean := True);
procedure Retrive_Declarations
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean);
procedure Retrive_Body
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean);
procedure Retrive_Subunits
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access);
procedure Retrive_With_Clause
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False);
procedure Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False);
-- Append_Unit --
procedure Append_Unit
(Unit : in Compilation_Unit;
Node : in out Tree_Node_Access;
Unit_Body : in Compilation_Unit := Nil_Compilation_Unit)
is
Exist_Node : Tree_Node_Access;
begin
Exist_Node := Find (Result, Unit);
if Exist_Node = null then
if Is_Identical (Unit, Std) then
Node := Add_Child
(Result, Node, Unit, Nil_Compilation_Unit, True);
Node := null;
else
Node := Add_Child (Result, Node, Unit, Unit_Body);
end if;
else
if Node /= null then
Glue_Nodes_Checked (Result, Node, Exist_Node);
Node := null;
end if;
end if;
end Append_Unit;
-- Retrive --
procedure Retrive
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean := True)
is
Internal_Node : Tree_Node_Access := Node;
begin
if Is_Nil (Unit) then
return;
end if;
Kinds := Unit_Kind (Unit);
if Kinds in A_Nonexistent_Declaration .. An_Unknown_Unit then
null;
elsif Kinds in A_Subunit then
declare
Internal_Unit : Compilation_Unit := Unit;
begin
while Unit_Kind (Internal_Unit) in A_Subunit loop
Internal_Unit := Corresponding_Subunit_Parent_Body
(Internal_Unit, The_Context);
end loop;
Retrive_Declarations
(Corresponding_Declaration (Internal_Unit, The_Context),
Node, Add_Node);
end;
elsif Kinds in A_Procedure_Body .. A_Package_Body then
Retrive_Body (Unit, Node, Add_Node);
else
Retrive_Declarations (Unit, Node, Add_Node);
end if;
end Retrive;
-- Retrive_Declarations --
procedure Retrive_Declarations
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean)
is
Parent : Compilation_Unit;
Internal_Node : Tree_Node_Access := Node;
begin
Body_Unit := Corresponding_Body (Unit, The_Context);
if Add_Node then
if not Is_Identical (Body_Unit, Unit) then
Append_Unit (Unit, Internal_Node, Body_Unit);
else
Append_Unit (Unit, Internal_Node);
end if;
if Internal_Node = null then
return;
end if;
end if;
if Is_Identical (Unit, Std) then
return;
end if;
Check_10_1_1_26c_26b (Unit, Internal_Node);
Retrive_With_Clause (Unit, Internal_Node);
if not Is_Nil (Body_Unit) then
Retrive_Body (Body_Unit, Internal_Node, False);
end if;
Parent := Corresponding_Parent_Declaration (Unit, The_Context);
while Unit_Kind (Parent) in
A_Procedure .. A_Generic_Package_Renaming
loop
Body_Unit := Corresponding_Body (Parent, The_Context);
if not Is_Identical (Body_Unit, Parent) then
Append_Unit (Parent, Internal_Node, Body_Unit);
else
Append_Unit (Parent, Internal_Node);
end if;
if Internal_Node = null then
return;
end if;
Check_10_1_1_26c_26b (Parent, Internal_Node);
Retrive_With_Clause (Parent, Internal_Node);
if not Is_Nil (Body_Unit) then
Retrive_Body (Body_Unit, Internal_Node, False);
end if;
Parent := Corresponding_Parent_Declaration (Parent, The_Context);
end loop;
Retrive (Parent, Internal_Node);
end Retrive_Declarations;
-- Retrive_Body --
procedure Retrive_Body
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
Add_Node : in Boolean)
is
Internal_Node : Tree_Node_Access := Node;
begin
if Is_Nil (Unit) then
return;
end if;
if Add_Node then
Append_Unit (Unit, Internal_Node);
if Internal_Node = null then
return;
end if;
end if;
Check_10_1_1_26c_26b (Unit, Internal_Node, True);
Retrive_With_Clause (Unit, Internal_Node, True);
Retrive_Subunits (Unit, Internal_Node);
end Retrive_Body;
-- Retrive_Subunits --
procedure Retrive_Subunits
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access)
is
Sub : Asis.Compilation_Unit_List := Subunits (Unit, The_Context);
Sub_Unit : Compilation_Unit;
Exist_Node : Tree_Node_Access;
vNode : Tree_Node_Access := Node;
begin
for Index in Sub'Range loop
Sub_Unit := Sub (Index);
if not Is_Nil (Sub_Unit) then
Exist_Node := Find (Result, Sub_Unit);
if Exist_Node = null then
Exist_Node := Add_Subunit (Result, Node, Sub_Unit);
Check_10_1_1_26c_26b (Unit, Exist_Node, True);
Retrive_With_Clause (Unit, Exist_Node, True);
Retrive_Subunits (Sub_Unit, Exist_Node);
else
Glue_Nodes (Result, Exist_Node, Node);
end if;
end if;
end loop;
end Retrive_Subunits;
-- Retrive_With_Clause --
procedure Retrive_With_Clause
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False)
is
With_List : constant Asis.Context_Clause_List :=
Asis.Elements.Context_Clause_Elements (Unit);
Internal_Unit : Compilation_Unit;
Exist_Node : Tree_Node_Access;
begin
for Index in With_List'Range loop
if Clause_Kind (With_List (Index).all) = A_With_Clause then
Internal_Unit := Get_Compilation_Unit
(Unit, With_List (Index), Index, The_Context);
if not Is_Nil (Internal_Unit) then
if not For_Body then
Retrive (Internal_Unit, Node);
else
Exist_Node := Find (Result, Internal_Unit);
if Exist_Node = null then
Body_Unit := Corresponding_Body
(Internal_Unit, The_Context);
if not Is_Identical (Body_Unit, Internal_Unit) then
Exist_Node := Add_Child
(Result, null, Internal_Unit, Body_Unit);
else
Exist_Node := Add_Child
(Result, null, Internal_Unit);
end if;
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
Retrive (Internal_Unit, Exist_Node, False);
else
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
end if;
end if;
end if;
end if;
end loop;
end Retrive_With_Clause;
-- Check_10_1_1_26c_26b --
procedure Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
Node : in Tree_Node_Access;
For_Body : in Boolean := False)
is
procedure Retrive_For_Body
(Unit : in Compilation_Unit);
Except : Compilation_Unit := Library_Unit_Declaration
("Ada.Exceptions", The_Context);
Sys : Compilation_Unit := Library_Unit_Declaration
("System", The_Context);
State : Check_10_1_1_26c_26b_Information;
-- Retrive_For_Body --
procedure Retrive_For_Body
(Unit : in Compilation_Unit)
is
Exist_Node : Tree_Node_Access;
begin
Exist_Node := Find (Result, Unit);
if Exist_Node = null then
Body_Unit := Corresponding_Body (Unit, The_Context);
if not Is_Identical (Body_Unit, Unit) then
Exist_Node := Add_Child (Result, null, Unit, Body_Unit);
else
Exist_Node := Add_Child (Result, null, Unit);
end if;
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
Retrive (Unit, Exist_Node, False);
else
if Node /= null then
Add_Body_Dependents (Result, Exist_Node, Node);
end if;
end if;
end Retrive_For_Body;
begin
State := Check_10_1_1_26c_26b (Unit, The_Context);
if State.Exceptions then
if not For_Body then
Retrive (Except, Node);
else
Retrive_For_Body (Except);
end if;
end if;
if State.System then
if not For_Body then
Retrive (Sys, Node);
else
Retrive_For_Body (Sys);
end if;
end if;
end Check_10_1_1_26c_26b;
begin
Dependence_Order (Result, Ascending);
for Index in List'Range loop
Unit := List (Index);
if Find (Result, Unit) = null then
Retrive (Unit, null);
end if;
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Get_Needed_Units;
--------------------
-- Get_Subunits --
--------------------
procedure Get_Subunits
(Tree : in Utils.Root_Tree_Access;
Unit : in Compilation_Unit;
Node : in Utils.Tree_Node_Access;
The_Context : in Asis.Context)
is
use Utils;
Sub : Asis.Compilation_Unit_List := Subunits (Unit, The_Context);
Sub_Unit : Compilation_Unit;
Exist_Node : Tree_Node_Access;
begin
for Index in Sub'Range loop
Sub_Unit := Sub (Index);
if not Is_Nil (Sub_Unit) then
Exist_Node := Find (Tree, Sub_Unit);
if Exist_Node = null then
Exist_Node := Add_Child (Tree, Node, Sub_Unit);
Get_Subunits (Tree, Sub_Unit, Exist_Node, The_Context);
else
Glue_Nodes (Tree, Node, Exist_Node);
end if;
end if;
end loop;
end Get_Subunits;
--------------------------
-- Get_Compilation_Unit --
--------------------------
function Get_Compilation_Unit
(Unit : in Compilation_Unit;
Target : in Asis.Element;
Number : in List_Index;
The_Context : in Asis.Context)
return Asis.Compilation_Unit
is
use Utils;
Names : constant Asis.Name_List := Asis.Clauses.Clause_Names (Target);
Declaration : Asis.Element;
Internal_Unit : Asis.Compilation_Unit;
Result_List : Compilation_Unit_List_Access := null;
begin
for Index in Names'Range loop
if Expression_Kind (Names (Index).all) = An_Identifier then
Declaration := Asis.Expressions.Corresponding_Name_Declaration
(Names (Index));
else
-- A_Selected_Component
Declaration := Asis.Expressions.Corresponding_Name_Declaration
(Asis.Expressions.Selector (Names (Index)));
end if;
if Assigned (Declaration) then
Internal_Unit :=
Asis.Elements.Enclosing_Compilation_Unit (Declaration);
if Unit_Kind (Internal_Unit) in
A_Procedure .. A_Generic_Package_Renaming
then
Result_List := Append (Result_List, Internal_Unit);
end if;
end if;
end loop;
if Result_List = null then
return Nil_Compilation_Unit;
end if;
if Result_List.all'Length > 1 then
Ada.Wide_Text_IO.Put_Line
("[Warning] Founded more then one unit for one with_clause "
& "in unit " & Unit_Full_Name (Unit) & " clause number "
& List_Index'Wide_Image (Number));
end if;
declare
Result : Asis.Compilation_Unit :=
Result_List.all (Result_List.all'First);
begin
Deallocate (Result_List);
if Is_Nil (Result) then
Ada.Wide_Text_IO.Put_Line
("[Warning] Unit for with_clause in unit "
& Unit_Full_Name (Unit) & " clause number "
& List_Index'Wide_Image (Number) & " not found");
else
if Unit_Kind (Result) in A_Procedure_Body .. A_Package_Body then
Result := Corresponding_Declaration (Result, The_Context);
end if;
end if;
return Result;
end;
end Get_Compilation_Unit;
---------------
-- Have_With --
---------------
function Have_With
(Library : in Compilation_Unit;
Unit : in Compilation_Unit;
The_Context : in Asis.Context)
return Boolean
is
With_List : constant Asis.Context_Clause_List :=
Asis.Elements.Context_Clause_Elements (Library);
Internal_Unit : Compilation_Unit;
begin
for Index in With_List'Range loop
if Clause_Kind (With_List (Index).all) = A_With_Clause then
Internal_Unit := Get_Compilation_Unit
(Library, With_List (Index), Index, The_Context);
if not Is_Nil (Internal_Unit)
and then Is_Identical (Internal_Unit, Unit)
then
return True;
end if;
end if;
end loop;
return False;
end Have_With;
--------------------------
-- Check_10_1_1_26c_26b --
--------------------------
function Check_10_1_1_26c_26b
(Unit : in Compilation_Unit;
The_Context : in Asis.Context)
return Check_10_1_1_26c_26b_Information
is
-- 10.1.1 (26.c)
-- 10.1.1 (26.b)
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Check_10_1_1_26c_26b_Information);
procedure Post_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Check_10_1_1_26c_26b_Information);
Except : Compilation_Unit := Library_Unit_Declaration
("Ada.Exceptions", The_Context);
Sys : Compilation_Unit := Library_Unit_Declaration
("System", The_Context);
Is_Except : Boolean;
Is_Sys : Boolean;
Control : Traverse_Control := Continue;
State : Check_10_1_1_26c_26b_Information;
procedure Pre_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Check_10_1_1_26c_26b_Information)
is
use Asis.Elements;
begin
if not Is_Except
and then Declaration_Kind (Element) =
A_Choice_Parameter_Specification
then
State.Exceptions := True;
end if;
if not Is_Sys
and then Expression_Kind (Element) = An_Attribute_Reference
and then Attribute_Kind (Element) = An_Address_Attribute
then
State.System := True;
end if;
end Pre_Operation;
procedure Post_Operation
(Element : in Asis.Element;
Control : in out Traverse_Control;
State : in out Check_10_1_1_26c_26b_Information)
is
begin
null;
end Post_Operation;
procedure Check_Choice_Iterator is new
Asis.Iterator.Traverse_Element
(Check_10_1_1_26c_26b_Information, Pre_Operation, Post_Operation);
begin
Is_Except := Is_Identical (Unit, Except);
Is_Sys := Is_Identical (Unit, Sys);
Check_Choice_Iterator
(Asis.Elements.Unit_Declaration (Unit), Control, State);
return State;
end Check_10_1_1_26c_26b;
------------
-- Utils --
------------
package body Utils is
-------------
-- In_List --
-------------
function In_List
(List : in Tree_Node_Array_Access;
Last : in Natural;
Node : in Tree_Node_Access)
return Boolean
is
begin
for Index in 1 .. Last loop
if List (Index) = Node then
return True;
end if;
end loop;
return False;
end In_List;
----------------------
-- Dependence_Order --
----------------------
procedure Dependence_Order
(This : in Root_Tree_Access;
Order : in Orders)
is
begin
This.Order := Order;
end Dependence_Order;
---------------
-- Add_Child --
---------------
function Add_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access
is
Kinds : Unit_Kinds;
begin
if Is_Nil (Unit) then
return Node;
end if;
declare
New_Node : Tree_Node_Access := new Tree_Node;
begin
Kinds := Unit_Kind (Unit);
if Kinds in A_Procedure .. A_Generic_Package_Renaming
or else Kinds = A_Nonexistent_Declaration
then
New_Node.Unit := Unit;
else
New_Node.Unit_Body := Unit;
end if;
if Node = null then
This.Next := Add_Node (This.Next, New_Node.Self);
else
Node.Next := Add_Node (Node.Next, New_Node.Self);
New_Node.Prevs := Add_Node (New_Node.Prevs, Node.Self);
end if;
This.Units := Add_Node_Ordered (This.Units, New_Node.Self);
return New_Node;
end;
end Add_Child;
-- Add_Child --
function Add_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Spec_Unit : in Compilation_Unit;
Body_Unit : in Compilation_Unit;
Skip_Spec : in Boolean := False)
return Tree_Node_Access
is
Kinds : Unit_Kinds;
begin
if Is_Nil (Spec_Unit)
and then Is_Nil (Body_Unit)
then
return Node;
end if;
if not Is_Nil (Spec_Unit) then
Kinds := Unit_Kind (Spec_Unit);
if Kinds not in A_Procedure .. A_Generic_Package_Renaming
and then Kinds = A_Nonexistent_Declaration
then
Asis.Implementation.Set_Status
(Data_Error, "Add_Child - "
& "invalid unit specification "
& Unit_Full_Name (Spec_Unit));
raise Asis.Exceptions.ASIS_Failed;
end if;
end if;
if not Is_Identical (Spec_Unit, Body_Unit) then
if not Is_Nil (Body_Unit) then
Kinds := Unit_Kind (Body_Unit);
if Kinds in A_Procedure .. A_Generic_Package_Renaming
or else Kinds = A_Nonexistent_Declaration
then
Asis.Implementation.Set_Status
(Data_Error, "Add_Child - "
& "invalid unit body " & Unit_Full_Name (Body_Unit));
raise Asis.Exceptions.ASIS_Failed;
end if;
end if;
end if;
declare
New_Node : Tree_Node_Access := new Tree_Node;
begin
New_Node.Unit := Spec_Unit;
if not Is_Identical (Spec_Unit, Body_Unit) then
New_Node.Unit_Body := Body_Unit;
end if;
New_Node.Skip_Spec := Skip_Spec;
if Node = null then
This.Next := Add_Node (This.Next, New_Node.Self);
else
Node.Next := Add_Node (Node.Next, New_Node.Self);
New_Node.Prevs := Add_Node (New_Node.Prevs, Node.Self);
end if;
This.Units := Add_Node_Ordered (This.Units, New_Node.Self);
return New_Node;
end;
end Add_Child;
-----------------
-- Add_Subunit --
-----------------
function Add_Subunit
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access
is
Kinds : Unit_Kinds;
begin
if Is_Nil (Unit) then
return Node;
end if;
Kinds := Unit_Kind (Unit);
if Kinds not in
A_Procedure_Body_Subunit .. A_Protected_Body_Subunit
then
Asis.Implementation.Set_Status
(Data_Error, "Add_Subunit - "
& "invalid subunit " & Unit_Full_Name (Unit));
raise Asis.Exceptions.ASIS_Failed;
end if;
declare
New_Node : Tree_Node_Access := new Tree_Node;
begin
New_Node.Unit_Body := Unit;
if Node = null then
This.Next := Add_Node (This.Next, New_Node.Self);
else
Node.Prevs := Add_Node (Node.Prevs, New_Node.Self);
New_Node.Next := Add_Node (New_Node.Next, Node.Self);
end if;
This.Units := Add_Node_Ordered (This.Units, New_Node.Self);
return New_Node;
end;
end Add_Subunit;
------------
-- Append --
------------
procedure Append
(This : in Root_Tree_Access;
Unit : in Compilation_Unit)
is
begin
if Is_Nil (Unit) then
return;
end if;
if Find (This, Unit) /= null then
Asis.Implementation.Set_Status
(Asis.Errors.Internal_Error,
"Elaboration order dublicate unit: " & Unit_Full_Name (Unit));
raise Asis.Exceptions.ASIS_Failed;
end if;
declare
Kinds : Unit_Kinds;
New_Node : Tree_Node_Access := new Tree_Node;
begin
Kinds := Unit_Kind (Unit);
if Kinds in A_Procedure .. A_Generic_Package_Renaming
or else Kinds = A_Nonexistent_Declaration
then
New_Node.Unit := Unit;
else
New_Node.Unit_Body := Unit;
end if;
if This.Last_Node = null then
This.Next := Add_Node (This.Next, New_Node.Self);
else
This.Last_Node.Next := Add_Node
(This.Last_Node.Next, New_Node.Self);
New_Node.Prevs := Add_Node
(New_Node.Prevs, This.Last_Node.Self);
end if;
This.Last_Node := New_Node;
This.Units := Add_Node_Ordered (This.Units, New_Node.Self);
end;
end Append;
----------------
-- Glue_Nodes --
----------------
procedure Glue_Nodes
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access)
is
begin
if To_Node.Prevs /= null
and then In_List (To_Node.Prevs, To_Node.Prevs'Last, Node)
then
return;
end if;
Node.Next := Add_Node (Node.Next, To_Node.Self);
To_Node.Prevs := Add_Node (To_Node.Prevs, Node.Self);
end Glue_Nodes;
------------------------
-- Glue_Nodes_Checked --
------------------------
procedure Glue_Nodes_Checked
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access)
is
Circular : Compilation_Unit_List_Access := null;
Prev_Node : Tree_Node_Access := null;
begin
if To_Node.Prevs /= null then
Prev_Node := To_Node.Prevs (To_Node.Prevs.all'First);
if In_List (To_Node.Prevs, To_Node.Prevs'Last, Node) then
return;
end if;
end if;
while Prev_Node /= null loop
if Prev_Node = To_Node then
if Circular /= null then
for Index in reverse Circular.all'Range loop
Node.Circular := Append (Node.Circular, Circular (Index));
end loop;
Node.Circular := Append (Node.Circular, Node.Unit);
Node.Circular := Append
(Node.Circular, Circular (Circular.all'Last));
Deallocate (Circular);
else
-- 2 pair (self and parent)
Node.Circular := Append
(Node.Circular,
(Prev_Node.Unit, Node.Unit, Prev_Node.Unit));
end if;
return;
end if;
Circular := Append (Circular, Prev_Node.Unit);
if Prev_Node.Prevs /= null then
Prev_Node := Prev_Node.Prevs (Prev_Node.Prevs.all'First);
else
Prev_Node := null;
end if;
end loop;
if Circular /= null then
Deallocate (Circular);
end if;
Node.Next := Add_Node (Node.Next, To_Node.Self);
To_Node.Prevs := Add_Node (To_Node.Prevs, Node.Self);
end Glue_Nodes_Checked;
-------------------------
-- Add_Body_Dependents --
-------------------------
procedure Add_Body_Dependents
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
To_Node : in Tree_Node_Access)
is
begin
Node.Body_Dependences := Add_Node (Node.Body_Dependences, To_Node);
end Add_Body_Dependents;
--------------
-- Is_Child --
--------------
function Is_Child
(This : in Root_Tree_Access;
Node : in Tree_Node_Access)
return Boolean
is
begin
if This.Next /= null then
return In_List (This.Next, This.Next'Last, Node);
else
return False;
end if;
end Is_Child;
----------------
-- Set_Parent --
----------------
procedure Set_Parent
(This : in Root_Tree_Access;
Node : in Tree_Node_Access;
Parent : in Tree_Node_Access)
is
begin
Parent.Next := Add_Node (Parent.Next, Node.Self);
Node.Prevs := Add_Node (Node.Prevs, Parent.Self);
end Set_Parent;
-----------
-- Clear --
-----------
procedure Clear
(This : in out Root_Tree)
is
begin
Finalize (This);
end Clear;
-----------
-- Check --
-----------
procedure Check
(This : in Root_Tree_Access;
The_Context : in Asis.Context)
is
Kinds, Parent_Kinds : Unit_Kinds;
Order : Orders;
procedure Check_Consistent
(Node : in Tree_Node_Access);
function Set_Inconsistent
(Node : in Tree_Node_Access;
Prev : in Tree_Node_Access;
List : in Compilation_Unit_List_Access)
return Compilation_Unit_List_Access;
procedure Check_Body_Consistent
(Node : in Tree_Node_Access);
procedure Check_Missing
(Node : in Tree_Node_Access);
procedure Asc
(Node : in Tree_Node_Access);
procedure Desc
(Node : in Tree_Node_Access);
-- Check_Consistent --
procedure Check_Consistent
(Node : in Tree_Node_Access)
is
Prev_Node : Tree_Node_Access;
begin
if Is_Inconsistent (Node.Unit) then
return;
end if;
Node.Consistent := False;
if Is_Source_Changed (Node.Unit) then
Node.Inconsistent := Append
(Node.Inconsistent, (Nil_Compilation_Unit, Node.Unit));
else
Prev_Node := null;
if Order = Ascending then
if Node.Prevs /= null then
Prev_Node := Node.Prevs (Node.Prevs.all'First);
end if;
else
if Node.Next /= null then
Prev_Node := Node.Next (Node.Next.all'First);
end if;
end if;
if Prev_Node /= null
and then not Is_Nil (Prev_Node.Unit)
then
Node.Inconsistent := Append
(Node.Inconsistent, (Prev_Node.Unit, Node.Unit));
else
Node.Inconsistent := Append
(Node.Inconsistent, (Node.Unit, Node.Unit));
end if;
end if;
if Order = Ascending then
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Node.Inconsistent := Set_Inconsistent
(Node.Next.all (Index), Node, Node.Inconsistent);
end loop;
end if;
else
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Node.Inconsistent := Set_Inconsistent
(Node.Prevs.all (Index), Node, Node.Inconsistent);
end loop;
end if;
end if;
end Check_Consistent;
-- Set_Inconsistent --
function Set_Inconsistent
(Node : in Tree_Node_Access;
Prev : in Tree_Node_Access;
List : in Compilation_Unit_List_Access)
return Compilation_Unit_List_Access
is
Result : Compilation_Unit_List_Access := List;
begin
if not Node.Consistent
and then Node.Inconsistent /= null
then
if Is_Nil
(Node.Inconsistent (Node.Inconsistent'First))
then
Result := Append
(Result, (Nil_Compilation_Unit, Node.Unit));
end if;
Node.Inconsistent (Node.Inconsistent'First) := Prev.Unit;
Result := Append (Result, Node.Inconsistent.all);
Deallocate (Node.Inconsistent);
return Result;
end if;
if not Is_Nil (Node.Unit) then
Node.Consistent := False;
Result := Append (Result, (Prev.Unit, Node.Unit));
end if;
if Order = Ascending then
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Result := Set_Inconsistent
(Node.Next.all (Index), Node, Result);
end loop;
end if;
else
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Result := Set_Inconsistent
(Node.Prevs.all (Index), Node, Result);
end loop;
end if;
end if;
return Result;
end Set_Inconsistent;
-- Check_Body_Consistent --
procedure Check_Body_Consistent
(Node : in Tree_Node_Access)
is
procedure Check_Body
(Target : in Tree_Node_Access);
Prev_Unit : Compilation_Unit;
-- Check_Body --
procedure Check_Body
(Target : in Tree_Node_Access)
is
begin
if not Is_Nil (Target.Unit_Body) then
Prev_Unit := Target.Unit_Body;
if not Target.Body_Consistent then
Node.Body_Consistent := False;
Node.Inconsistent := Append
(Node.Inconsistent, (Prev_Unit, Node.Unit_Body));
end if;
end if;
end Check_Body;
begin
if not Is_Nil (Node.Unit_Body) then
if not Node.Consistent then
Node.Body_Consistent := False;
Node.Inconsistent := Append
(Node.Inconsistent, (Node.Unit, Node.Unit_Body));
end if;
if not Is_Inconsistent (Node.Unit_Body) then
Node.Body_Consistent := False;
if Is_Source_Changed (Node.Unit_Body) then
Node.Inconsistent := Append
(Node.Inconsistent,
(Nil_Compilation_Unit, Node.Unit_Body));
else
Node.Inconsistent := Append
(Node.Inconsistent, (Node.Unit_Body, Node.Unit_Body));
end if;
end if;
if Node.Body_Dependences /= null then
for Index in Node.Body_Dependences.all'Range loop
Prev_Unit := Node.Body_Dependences (Index).Unit;
if not Is_Inconsistent (Prev_Unit) then
Node.Body_Consistent := False;
Node.Inconsistent := Append
(Node.Inconsistent, (Prev_Unit, Node.Unit_Body));
end if;
end loop;
end if;
if Unit_Kind (Node.Unit_Body) in A_Subunit then
if Order = Ascending then
if Node.Next /= null then
Check_Body (Node.Next (Node.Next'First));
end if;
else
if Node.Prevs /= null then
Check_Body (Node.Prevs (Node.Prevs'First));
end if;
end if;
end if;
end if;
if Order = Ascending then
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Check_Body_Consistent (Node.Next.all (Index));
end loop;
end if;
else
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Check_Body_Consistent (Node.Prevs.all (Index));
end loop;
end if;
end if;
end Check_Body_Consistent;
-- Check_Missing --
procedure Check_Missing
(Node : in Tree_Node_Access)
is
procedure Check_Missing
(Node : in Tree_Node_Access;
Target : in Tree_Node_Access)
is
begin
if Target = null
or else Is_Nil (Target.Unit)
then
return;
end if;
Parent_Kinds := Unit_Kind (Target.Unit);
if Parent_Kinds = A_Nonexistent_Declaration then
Node.Missing := Append
(Node.Missing, (Node.Unit, Target.Unit));
end if;
end Check_Missing;
begin
if Node.Missing /= null then
return;
end if;
if Order = Ascending then
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Check_Missing (Node, Node.Next (Index));
end loop;
end if;
else
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Check_Missing (Node, Node.Prevs (Index));
end loop;
end if;
end if;
if Is_Nil (Node.Unit_Body) then
return;
end if;
if Unit_Kind (Node.Unit) = A_Nonexistent_Declaration then
Node.Missing := Append
(Node.Missing, (Node.Unit_Body, Node.Unit));
end if;
if Node.Body_Dependences /= null then
for Index in Node.Body_Dependences.all'Range loop
Parent_Kinds :=
Unit_Kind (Node.Body_Dependences (Index).Unit);
if Parent_Kinds = A_Nonexistent_Declaration then
Node.Missing := Append
(Node.Missing,
(Node.Unit_Body,
Node.Body_Dependences (Index).Unit));
end if;
end loop;
end if;
if Unit_Kind (Node.Unit_Body) in A_Subunit then
if Order = Ascending then
if Node.Next /= null then
if Unit_Kind
(Node.Next (Node.Next'First).Unit_Body) =
A_Nonexistent_Body
then
Node.Missing := Append
(Node.Missing,
(Node.Unit_Body,
Node.Next (Node.Next'First).Unit_Body));
end if;
end if;
else
if Node.Prevs /= null then
if Unit_Kind
(Node.Prevs (Node.Prevs'First).Unit_Body) =
A_Nonexistent_Body
then
Node.Missing := Append
(Node.Missing,
(Node.Unit_Body,
Node.Prevs (Node.Prevs'First).Unit_Body));
end if;
end if;
end if;
end if;
end Check_Missing;
-- Asc --
procedure Asc
(Node : in Tree_Node_Access)
is
begin
if Node = null then
return;
end if;
if not Is_Nil (Node.Unit) then
if Node.Consistent then
Check_Consistent (Node);
end if;
Check_Missing (Node);
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Asc (Node.Prevs.all (Index));
end loop;
end if;
end Asc;
-- Desc --
procedure Desc
(Node : in Tree_Node_Access)
is
begin
if Node = null then
return;
end if;
if not Is_Nil (Node.Unit) then
Kinds := Unit_Kind (Node.Unit);
if Node.Consistent then
Check_Consistent (Node);
end if;
Check_Missing (Node);
end if;
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Desc (Node.Next (Index));
end loop;
end if;
end Desc;
Std_Node : Tree_Node_Access;
begin
Order := This.Order;
if This.Order = Ascending then
Std_Node := Find
(This, Library_Unit_Declaration ("Standard", The_Context));
if Std_Node /= null then
if Std_Node.Next /= null then
for Index in Std_Node.Next.all'Range loop
Asc (Std_Node.Next (Index));
end loop;
for Index in Std_Node.Next.all'Range loop
Check_Body_Consistent (Std_Node.Next (Index));
end loop;
end if;
end if;
else
if This.Next /= null then
for Index in This.Next.all'Range loop
Desc (This.Next (Index));
end loop;
for Index in This.Next.all'Range loop
Check_Body_Consistent (This.Next (Index));
end loop;
end if;
end if;
end Check;
---------------------------
-- Generate_Relationship --
---------------------------
function Generate_Relationship
(This : in Root_Tree_Access;
Limit_List : in Utils.Compilation_Unit_List_Access;
List_Last : in ASIS_Integer)
return Relationship
is
Consistent_List : Compilation_Unit_List_Access := null;
Inconsistent_List : Compilation_Unit_List_Access := null;
Missing_List : Compilation_Unit_List_Access := null;
Circular_List : Compilation_Unit_List_Access := null;
Consistent_Length : Asis.ASIS_Natural := 0;
Inconsistent_Length : Asis.ASIS_Natural := 0;
Missing_Length : Asis.ASIS_Natural := 0;
Circular_Length : Asis.ASIS_Natural := 0;
procedure Genegate_Inconsistent
(Node : in Tree_Node_Access);
procedure Genegate_Circular
(Node : in Tree_Node_Access);
procedure Genegate_Missing
(Node : in Tree_Node_Access);
procedure Process
(Node : in Tree_Node_Access);
-- Genegate_Inconsistent --
procedure Genegate_Inconsistent
(Node : in Tree_Node_Access)
is
begin
if Node.Inconsistent /= null
and then not Node.Inconsistent_Added
then
Node.Inconsistent_Added := True;
if Inconsistent_List = null then
Inconsistent_List := Append
(Inconsistent_List, Node.Inconsistent.all);
else
if not Is_Nil (Node.Inconsistent (Node.Inconsistent'First))
and then Is_Inconsistent
(Node.Inconsistent (Node.Inconsistent'First))
then
Node.Inconsistent (Node.Inconsistent'First) :=
Node.Inconsistent (Node.Inconsistent'First + 1);
end if;
Inconsistent_List := Append
(Inconsistent_List, Node.Inconsistent.all);
end if;
end if;
end Genegate_Inconsistent;
-- Genegate_Circular --
procedure Genegate_Circular
(Node : in Tree_Node_Access)
is
begin
if Node.Circular /= null
and then not Node.Circular_Added
then
Node.Circular_Added := True;
for Index in
Node.Circular.all'First .. Node.Circular.all'Last - 1
loop
Circular_List := Append
(Circular_List, (Node.Circular.all (Index),
Node.Circular.all (Index + 1))
);
end loop;
end if;
end Genegate_Circular;
-- Genegate_Missing --
procedure Genegate_Missing
(Node : in Tree_Node_Access)
is
begin
if Node.Missing /= null
and then not Node.Missing_Added
then
Node.Missing_Added := True;
Missing_List := Append (Missing_List, Node.Missing.all);
end if;
end Genegate_Missing;
-- Process --
procedure Process
(Node : in Tree_Node_Access)
is
-- Add_To_Consistent --
procedure Add_To_Consistent
(Unit : in Compilation_Unit)
is
begin
if Limit_List /= null then
if In_List (Limit_List, List_Last, Unit) then
Consistent_List := Append (Consistent_List, Unit);
end if;
else
Consistent_List := Append (Consistent_List, Unit);
end if;
end Add_To_Consistent;
begin
if Node.Added then
return;
end if;
Node.Added := True;
if Node.Consistent then
if not Node.Skip_Spec
and then not Is_Nil (Node.Unit)
then
Add_To_Consistent (Node.Unit);
end if;
if Node.Body_Consistent
and then not Is_Nil (Node.Unit_Body)
then
Add_To_Consistent (Node.Unit_Body);
end if;
end if;
Genegate_Inconsistent (Node);
Genegate_Missing (Node);
Genegate_Circular (Node);
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Process (Node.Next.all (Index));
end loop;
end if;
end Process;
begin
if This.Next = null then
return Nil_Relationship;
end if;
for Index in This.Next.all'Range loop
Process (This.Next.all (Index));
end loop;
if Consistent_List /= null then
Consistent_Length := Consistent_List.all'Length;
end if;
if Inconsistent_List /= null then
Inconsistent_Length := Inconsistent_List.all'Length;
end if;
if Missing_List /= null then
Missing_Length := Missing_List.all'Length;
end if;
if Circular_List /= null then
Circular_Length := Circular_List.all'Length;
end if;
declare
Result : Relationship
(Consistent_Length, Inconsistent_Length,
Missing_Length, Circular_Length);
begin
if Consistent_List /= null then
Result.Consistent := Consistent_List.all;
end if;
if Inconsistent_List /= null then
Result.Inconsistent := Inconsistent_List.all;
end if;
if Missing_List /= null then
Result.Missing := Missing_List.all;
end if;
if Circular_List /= null then
Result.Circular := Circular_List.all;
end if;
Deallocate (Consistent_List);
Deallocate (Inconsistent_List);
Deallocate (Missing_List);
Deallocate (Circular_List);
return Result;
end;
exception
when others =>
Deallocate (Consistent_List);
Deallocate (Inconsistent_List);
Deallocate (Missing_List);
Deallocate (Circular_List);
raise;
end Generate_Relationship;
----------------------------------
-- Is_Have_Circular_Dependences --
----------------------------------
function Is_Have_Circular_Dependences
(This : in Root_Tree_Access)
return Boolean
is
function Process
(Node : in Tree_Node_Access)
return Boolean;
Result : Boolean := False;
-- Process --
function Process
(Node : in Tree_Node_Access)
return Boolean
is
Result : Boolean := False;
begin
if Node.Circular /= null then
return True;
else
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Result := Process (Node.Next.all (Index));
exit when Result;
end loop;
end if;
end if;
return Result;
end Process;
begin
if This.Next /= null then
for Index in This.Next.all'Range loop
Result := Process (This.Next.all (Index));
exit when Result;
end loop;
end if;
return Result;
end Is_Have_Circular_Dependences;
-----------------------------
-- Create_Elaboration_Tree --
-----------------------------
-- A_Partition_Elaboration_Policy_Pragma, -- H.6 (3)
-- A_Preelaborable_Initialization_Pragma, -- 7.6 (5)
function Create_Elaboration_Tree
(This : in Root_Tree_Access;
The_Context : in Asis.Context)
return Root_Tree_Access
is
procedure Process_Pure_Spec
(Node : in Tree_Node_Access);
procedure Process_Pure_Body
(Node : in Tree_Node_Access);
procedure Process_Preelaborate_Spec
(Node : in Tree_Node_Access);
procedure Process_Preelaborate_Body
(Node : in Tree_Node_Access);
procedure Process_Spec
(Node : in Tree_Node_Access);
procedure Process_Body
(Node : in Tree_Node_Access);
procedure Elab_Spec
(Node : in Tree_Node_Access);
procedure Elab_Body
(Node : in Tree_Node_Access;
All_Bodys : in Boolean := False;
Only_Body : in Boolean := True);
procedure Elab_Subunits
(Node : in Tree_Node_Access;
All_Bodys : in Boolean);
procedure Elab_Pragmed_Bodys
(Node : in Tree_Node_Access;
Unit : in Compilation_Unit);
procedure Append_Inconsistent
(Node : in Tree_Node_Access);
Result : Root_Tree_Access := new Root_Tree;
Root_Node : Tree_Node_Access;
Std : Compilation_Unit :=
Library_Unit_Declaration ("Standard", The_Context);
-- for circular elaboration order
Elaboration_Line : Compilation_Unit_List_Access := null;
procedure Elab_Spec
(Node : in Tree_Node_Access)
is
begin
if not Node.Elaborated
and then Node.Consistent
and then not Is_Nil (Node.Unit)
then
if Elaboration_Line /= null then
-- test circular --
if In_List
(Elaboration_Line, Elaboration_Line.all'Last, Node.Unit)
then
Node.Circular := Append
(Node.Circular, Elaboration_Line.all);
return;
end if;
end if;
Elaboration_Line := Append
(Elaboration_Line, Node.Unit);
if Node.Next /= null then
for Index in Node.Next.all'Range loop
Elab_Spec (Node.Next (Index));
end loop;
end if;
Elab_Pragmed_Bodys (Node, Node.Unit);
Append (Result, Node.Unit);
Node.Elaborated := True;
Remove_From_List (Elaboration_Line, Node.Unit);
end if;
if Is_Elaborate_Body (Node) then
-- An_Elaborate_Body_Pragma -- 10.2.1(22)
Elab_Body (Node);
end if;
end Elab_Spec;
-- Elab_Body --
procedure Elab_Body
(Node : in Tree_Node_Access;
All_Bodys : in Boolean := False;
Only_Body : in Boolean := True)
is
Unit : Compilation_Unit := Node.Unit_Body;
begin
if Node.Body_Elaborated then
Elab_Subunits (Node, All_Bodys);
return;
end if;
if not Node.Body_Consistent
or else Is_Nil (Unit)
then
return;
end if;
if Only_Body
and then Unit_Kind (Unit) not in
A_Procedure_Body .. A_Package_Body
then
return;
end if;
if not Only_Body
and then Unit_Kind (Unit) not in A_Subunit
then
Elab_Subunits (Node, All_Bodys);
return;
end if;
if Elaboration_Line /= null then
-- test circular --
if In_List
(Elaboration_Line, Elaboration_Line.all'Last, Unit)
then
Node.Circular := Append
(Node.Circular, Elaboration_Line.all);
return;
end if;
end if;
Elaboration_Line := Append (Elaboration_Line, Unit);
if Node.Body_Dependences /= null then
for Index in Node.Body_Dependences.all'Range loop
Elab_Spec (Node.Body_Dependences (Index));
end loop;
end if;
Elab_Pragmed_Bodys (Node, Unit);
if All_Bodys then
if Node.Body_Dependences /= null then
for Index in Node.Body_Dependences.all'Range loop
Elab_Body (Node.Body_Dependences (Index), True, True);
end loop;
end if;
end if;
Append (Result, Unit);
Node.Body_Elaborated := True;
Remove_From_List (Elaboration_Line, Unit);
Elab_Subunits (Node, All_Bodys);
end Elab_Body;
-- Elab_Subunits --
procedure Elab_Subunits
(Node : in Tree_Node_Access;
All_Bodys : in Boolean)
is
Next_Node : Tree_Node_Access;
begin
if not Node.Body_Elaborated then
return;
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Next_Node := Node.Prevs (Index);
if Unit_Kind (Next_Node.Unit_Body) in
A_Procedure_Body_Subunit .. A_Protected_Body_Subunit
then
Elab_Body (Next_Node, All_Bodys, False);
end if;
end loop;
end if;
end Elab_Subunits;
-- Elab_Pragmed_Bodys --
procedure Elab_Pragmed_Bodys
(Node : in Tree_Node_Access;
Unit : in Compilation_Unit)
is
-- An_Elaborate_Pragma -- 10.2.1(20)
-- An_Elaborate_All_Pragma -- 10.2.1(21)
use Asis.Elements;
With_List : constant Asis.Context_Clause_List :=
Context_Clause_Elements (Unit, True);
El : Element;
Internal_Unit : Compilation_Unit;
begin
for Index in With_List'Range loop
El := With_List (Index);
if Element_Kind (El) = A_Pragma then
if Pragma_Kind (El) = An_Elaborate_Pragma then
Internal_Unit := Get_Compilation_Unit
(Unit, With_List (Index), Index, The_Context);
Elab_Body (Find (Result, Internal_Unit));
elsif Pragma_Kind (El) = An_Elaborate_All_Pragma then
Internal_Unit := Get_Compilation_Unit
(Unit, With_List (Index), Index, The_Context);
Elab_Body (Find (Result, Internal_Unit), True);
end if;
end if;
end loop;
end Elab_Pragmed_Bodys;
-- Process_Pure_Spec --
procedure Process_Pure_Spec
(Node : in Tree_Node_Access)
is
-- A_Pure_Pragma -- 10.2.1(14)
begin
if not Node.Elaborated
and then not Is_Nil (Node.Unit)
then
if Is_Pure (Node) then
Elab_Spec (Node);
end if;
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Pure_Spec (Node.Prevs (Index));
end loop;
end if;
end Process_Pure_Spec;
-- Process_Pure_Body --
procedure Process_Pure_Body
(Node : in Tree_Node_Access)
is
-- A_Pure_Pragma -- 10.2.1(14)
begin
if Is_Pure (Node) then
Elab_Body (Node);
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Pure_Body (Node.Prevs (Index));
end loop;
end if;
end Process_Pure_Body;
-- Process_Preelaborate_Spec --
procedure Process_Preelaborate_Spec
(Node : in Tree_Node_Access)
is
-- A_Preelaborate_Pragma -- 10.2.1(3)
begin
if not Node.Elaborated
and then not Is_Nil (Node.Unit)
then
if Is_Preelaborate (Node) then
Elab_Spec (Node);
end if;
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Preelaborate_Spec (Node.Prevs (Index));
end loop;
end if;
end Process_Preelaborate_Spec;
-- Process_Preelaborate_Body --
procedure Process_Preelaborate_Body
(Node : in Tree_Node_Access)
is
-- A_Preelaborate_Pragma -- 10.2.1(3)
begin
if Is_Preelaborate (Node) then
Elab_Body (Node);
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Preelaborate_Body (Node.Prevs (Index));
end loop;
end if;
end Process_Preelaborate_Body;
-- Process_Spec --
procedure Process_Spec
(Node : in Tree_Node_Access)
is
begin
if not Node.Elaborated
and then not Is_Nil (Node.Unit)
then
Elab_Spec (Node);
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Spec (Node.Prevs (Index));
end loop;
end if;
end Process_Spec;
-- Process_Body --
procedure Process_Body
(Node : in Tree_Node_Access)
is
begin
Elab_Body (Node);
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Process_Body (Node.Prevs (Index));
end loop;
end if;
end Process_Body;
-- Append_Inconsistent --
procedure Append_Inconsistent
(Node : in Tree_Node_Access)
is
begin
if Node.Inconsistent /= null then
Result.Next (Result.Next'First).Inconsistent :=
Append (Result.Next (Result.Next'First).Inconsistent,
Node.Inconsistent.all);
end if;
if Node.Prevs /= null then
for Index in Node.Prevs.all'Range loop
Append_Inconsistent (Node.Prevs (Index));
end loop;
end if;
end Append_Inconsistent;
begin
Root_Node := Find (This, Std);
Root_Node.Elaborated := True;
Append (Result, Std);
if Root_Node.Prevs = null then
return Result;
end if;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Pure_Spec (Root_Node.Prevs (Index));
end loop;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Pure_Body (Root_Node.Prevs (Index));
end loop;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Preelaborate_Spec (Root_Node.Prevs (Index));
end loop;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Preelaborate_Body (Root_Node.Prevs (Index));
end loop;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Spec (Root_Node.Prevs (Index));
end loop;
for Index in Root_Node.Prevs.all'Range loop
Deallocate (Elaboration_Line);
Process_Body (Root_Node.Prevs (Index));
end loop;
-- inconsistent
for Index in Root_Node.Prevs.all'Range loop
Append_Inconsistent (Root_Node.Prevs (Index));
end loop;
return Result;
exception
when others =>
Deallocate (Result);
raise;
end Create_Elaboration_Tree;
-------------
-- Is_Pure --
-------------
function Is_Pure
(This : in Tree_Node_Access)
return Boolean
is
begin
if This.Internal_Pure = Unknown then
Retrive_Pragmas (This);
end if;
if This.Internal_Pure = Extended_True then
return True;
else
return False;
end if;
end Is_Pure;
---------------------
-- Is_Preelaborate --
---------------------
function Is_Preelaborate
(This : in Tree_Node_Access)
return Boolean
is
begin
if This.Internal_Preelaborate = Unknown then
Retrive_Pragmas (This);
end if;
if This.Internal_Preelaborate = Extended_True then
return True;
else
return False;
end if;
end Is_Preelaborate;
-----------------------
-- Is_Elaborate_Body --
-----------------------
function Is_Elaborate_Body
(This : in Tree_Node_Access)
return Boolean
is
begin
if This.Internal_Spec_With_Body = Unknown then
Retrive_Pragmas (This);
end if;
if This.Internal_Spec_With_Body = Extended_True then
return True;
else
return False;
end if;
end Is_Elaborate_Body;
---------------------
-- Retrive_Pragmas --
---------------------
procedure Retrive_Pragmas
(This : in Tree_Node_Access)
is
begin
if Is_Nil (This.Unit) then
return;
end if;
declare
Pragma_List : constant Asis.Pragma_Element_List :=
Asis.Elements.Corresponding_Pragmas
(Asis.Elements.Unit_Declaration (This.Unit));
begin
for Index in Pragma_List'Range loop
if Pragma_Kind (Pragma_List (Index).all) = A_Pure_Pragma then
This.Internal_Pure := Extended_True;
end if;
if Pragma_Kind (Pragma_List (Index).all) =
A_Preelaborate_Pragma
then
This.Internal_Preelaborate := Extended_True;
end if;
if Pragma_Kind (Pragma_List (Index).all) =
An_Elaborate_Body_Pragma
then
This.Internal_Spec_With_Body := Extended_True;
end if;
end loop;
end;
if This.Internal_Pure = Unknown then
This.Internal_Pure := Extended_False;
end if;
if This.Internal_Preelaborate = Extended_True then
This.Internal_Preelaborate := Extended_False;
end if;
if This.Internal_Spec_With_Body = Unknown then
This.Internal_Spec_With_Body := Extended_False;
end if;
end Retrive_Pragmas;
------------------
-- Is_Skip_Spec --
------------------
function Is_Skip_Spec
(This : in Tree_Node_Access)
return Boolean
is
begin
return This.Skip_Spec;
end Is_Skip_Spec;
---------------
-- Skip_Spec --
---------------
procedure Skip_Spec
(This : in Tree_Node_Access;
Value : in Boolean)
is
begin
This.Skip_Spec := Value;
end Skip_Spec;
--------------
-- Get_Spec --
--------------
function Get_Spec
(This : in Tree_Node_Access)
return Compilation_Unit
is
begin
return This.Unit;
end Get_Spec;
--------------
-- Get_Body --
--------------
function Get_Body
(This : in Tree_Node_Access)
return Compilation_Unit
is
begin
return This.Unit_Body;
end Get_Body;
-----------
-- Nexts --
-----------
function Nexts
(This : in Tree_Node_Access)
return Tree_Node_Array_Access
is
begin
return This.Next;
end Nexts;
--------------
-- Finalize --
--------------
procedure Finalize
(This : in out Root_Tree)
is
Node : Tree_Node_Access;
begin
if This.Next /= null then
for Index in This.Next.all'Range loop
Node := This.Next.all (Index);
if Node /= null then
Deallocate (Node);
end if;
end loop;
Deallocate (This.Next);
end if;
Deallocate (This.Units);
end Finalize;
-- Finalize --
procedure Finalize
(This : in out Tree_Node)
is
Node : Tree_Node_Access;
begin
if This.Next /= null then
for Index in This.Next.all'Range loop
Node := This.Next.all (Index);
if Node /= null then
Deallocate (Node);
end if;
end loop;
Deallocate (This.Next);
end if;
if This.Prevs /= null then
for Index in This.Prevs.all'Range loop
Remove (This.Prevs (Index).Next, This.Self);
end loop;
Deallocate (This.Prevs);
end if;
Deallocate (This.Circular);
Deallocate (This.Missing);
Deallocate (This.Inconsistent);
Deallocate (This.Body_Dependences);
end Finalize;
----------
-- Find --
----------
function Find
(This : in Root_Tree_Access;
Unit : in Compilation_Unit)
return Tree_Node_Access
is
Index : aliased Positive;
begin
if This.Units = null then
return null;
end if;
if Find
(This.Units, Unit, 1, This.Units.all'Last, Index'Unchecked_Access)
then
return This.Units.all (Index).Node;
else
return null;
end if;
end Find;
------------
-- Append --
------------
function Append
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access
is
begin
return Add_Node (List, Node);
end Append;
--------------
-- Add_Node --
--------------
function Add_Node
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access
is
Array_Access : Tree_Node_Array_Access := List;
begin
if Array_Access = null then
Array_Access := new Tree_Node_Array (1 .. 1);
else
declare
Tmp_Array : Tree_Node_Array_Access :=
new Tree_Node_Array (1 .. Array_Access.all'Length + 1);
begin
Tmp_Array (1 .. Array_Access.all'Length) := Array_Access.all;
Deallocate (Array_Access);
Array_Access := Tmp_Array;
end;
end if;
Array_Access.all (Array_Access.all'Last) := Node;
return Array_Access;
end Add_Node;
------------
-- Remove --
------------
procedure Remove
(List : in out Tree_Node_Array_Access;
Node : in Tree_Node_Access)
is
begin
if List = null or else Node = null then
return;
end if;
for Index in List'Range loop
if List (Index) = Node then
List (Index) := null;
return;
end if;
end loop;
end Remove;
-- Remove --
function Remove
(List : in Tree_Node_Array_Access;
Node : in Tree_Node_Access)
return Tree_Node_Array_Access
is
Internal_List : Tree_Node_Array_Access := List;
begin
if Internal_List = null
or else Node = null
then
return Internal_List;
end if;
for Index in List'Range loop
if Internal_List (Index) = Node then
if List'Length = 1 then
Deallocate (Internal_List);
return null;
else
declare
New_Arry : constant Tree_Node_Array_Access :=
new Tree_Node_Array (1 .. List'Length - 1);
begin
New_Arry (1 .. Index - 1) := List (1 .. Index - 1);
New_Arry (Index .. New_Arry'Last) :=
List (Index + 1 .. List'Last);
Deallocate (Internal_List);
return New_Arry;
end;
end if;
end if;
end loop;
return List;
end Remove;
----------------------
-- Add_Node_Ordered --
----------------------
function Add_Node_Ordered
(List : in Unit_Node_Array_Access;
Node : in Tree_Node_Access)
return Unit_Node_Array_Access
is
procedure Process
(Unit : Compilation_Unit);
Array_Access : Unit_Node_Array_Access := List;
Index : aliased Positive;
procedure Process
(Unit : Compilation_Unit)
is
begin
if Array_Access = null then
Array_Access := new Unit_Node_Array (1 .. 1);
Array_Access.all (1) := (Unit, Node);
else
if Find
(Array_Access, Unit,
1, Array_Access.all'Last, Index'Unchecked_Access)
then
raise Use_Error;
end if;
declare
Tmp_Array : Unit_Node_Array_Access :=
new Unit_Node_Array (1 .. Array_Access.all'Length + 1);
begin
Tmp_Array (1 .. Index - 1) :=
Array_Access.all (1 .. Index - 1);
Tmp_Array (Index) := (Unit, Node);
Tmp_Array (Index + 1 .. Tmp_Array.all'Last) :=
Array_Access.all (Index .. Array_Access.all'Last);
Deallocate (Array_Access);
Array_Access := Tmp_Array;
end;
end if;
end Process;
begin
if not Is_Nil (Node.Unit) then
Process (Node.Unit);
end if;
if not Is_Nil (Node.Unit_Body) then
Process (Node.Unit_Body);
end if;
return Array_Access;
end Add_Node_Ordered;
----------
-- Find --
----------
function Find
(List : in Unit_Node_Array_Access;
Unit : in Compilation_Unit;
From : in Positive;
To : in Positive;
Index : in Positive_Access)
return Boolean
is
L, H, I : Natural;
C : Integer;
Result : Boolean := False;
begin
L := From;
H := To;
while L <= H loop
I := (L + H) / 2;
C := Compare (List.all (I).Unit, Unit);
if C < 0 then
L := I + 1;
else
H := I - 1;
if C = 0 then
Result := True;
L := I;
end if;
end if;
end loop;
Index.all := L;
return Result;
end Find;
-------------
-- Compare --
-------------
function Compare
(Left : in Compilation_Unit;
Right : in Compilation_Unit)
return Integer
is
use Asis;
use System;
begin
if Left.all'Address < Right.all'Address then
return -1;
elsif Left.all'Address > Right.all'Address then
return 1;
else
return 0;
end if;
end Compare;
-------------
-- In_List --
-------------
function In_List
(List : in Compilation_Unit_List_Access;
Last : in ASIS_Integer;
Unit : in Compilation_Unit)
return Boolean
is
begin
for Index in 1 .. Last loop
if Asis.Compilation_Units.Is_Identical (List (Index), Unit) then
return True;
end if;
end loop;
return False;
end In_List;
----------------------
-- Remove_From_List --
----------------------
procedure Remove_From_List
(List : in out Compilation_Unit_List_Access;
Unit : in Compilation_Unit)
is
begin
if List = null then
return;
end if;
for Index in List'Range loop
if Is_Identical (List (Index), Unit) then
if List'Length = 1 then
Deallocate (List);
else
declare
Internal : constant Compilation_Unit_List_Access :=
new Compilation_Unit_List (1 .. List'Length - 1);
begin
Internal (1 .. Index - 1) := List (1 .. Index - 1);
Internal (Index .. Internal'Last) :=
List (Index + 1 .. List'Last);
Deallocate (List);
List := Internal;
end;
end if;
exit;
end if;
end loop;
end Remove_From_List;
-- Remove_From_List --
procedure Remove_From_List
(List : in out Compilation_Unit_List;
From : in List_Index;
Unit : in Compilation_Unit)
is
begin
for Index in From .. List'Last loop
if Is_Identical (List (Index), Unit) then
List (Index) := Nil_Compilation_Unit;
return;
end if;
end loop;
end Remove_From_List;
------------
-- Append --
------------
function Append
(List : in Compilation_Unit_List_Access;
Unit : in Compilation_Unit)
return Compilation_Unit_List_Access
is
Result : Compilation_Unit_List_Access := List;
begin
if Result = null then
Result := new Compilation_Unit_List (1 .. 1);
else
declare
Tmp_Array : Compilation_Unit_List_Access :=
new Compilation_Unit_List (1 .. Result.all'Length + 1);
begin
Tmp_Array (1 .. Result.all'Length) := Result.all;
Deallocate (Result);
Result := Tmp_Array;
end;
end if;
Result.all (Result.all'Last) := Unit;
return Result;
end Append;
-- Append --
function Append
(List : in Compilation_Unit_List_Access;
Units : in Compilation_Unit_List)
return Compilation_Unit_List_Access
is
Result : Compilation_Unit_List_Access := List;
begin
if Result = null then
Result := new Compilation_Unit_List (1 .. Units'Length);
Result.all := Units;
else
declare
Tmp_Array : Compilation_Unit_List_Access :=
new Compilation_Unit_List
(1 .. Result.all'Length + Units'Length);
begin
Tmp_Array (1 .. Result.all'Length) := Result.all;
Tmp_Array (Result.all'Length + 1 .. Tmp_Array'Last) := Units;
Deallocate (Result);
Result := Tmp_Array;
end;
end if;
return Result;
end Append;
---------------------
-- Is_Inconsistent --
---------------------
function Is_Inconsistent
(Unit : in Compilation_Unit)
return Boolean
is
begin
return True;
end Is_Inconsistent;
-----------------------
-- Is_Source_Changed --
-----------------------
function Is_Source_Changed
(Unit : in Compilation_Unit)
return Boolean
is
begin
return False;
end Is_Source_Changed;
end Utils;
end Asis.Compilation_Units.Relations;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik, Andry Ogorodnik
-- 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.
------------------------------------------------------------------------------
|
with Ada.Text_IO;
procedure Test_For_Primes is
type Pascal_Triangle_Type is array (Natural range <>) of Long_Long_Integer;
function Calculate_Pascal_Triangle (N : in Natural) return Pascal_Triangle_Type is
Pascal_Triangle : Pascal_Triangle_Type (0 .. N);
begin
Pascal_Triangle (0) := 1;
for I in Pascal_Triangle'First .. Pascal_Triangle'Last - 1 loop
Pascal_Triangle (1 + I) := 1;
for J in reverse 1 .. I loop
Pascal_Triangle (J) := Pascal_Triangle (J - 1) - Pascal_Triangle (J);
end loop;
Pascal_Triangle (0) := -Pascal_Triangle (0);
end loop;
return Pascal_Triangle;
end Calculate_Pascal_Triangle;
function Is_Prime (N : Integer) return Boolean is
I : Integer;
Result : Boolean := True;
Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N);
begin
I := N / 2;
while Result and I > 1 loop
Result := Result and Pascal_Triangle (I) mod Long_Long_Integer (N) = 0;
I := I - 1;
end loop;
return Result;
end Is_Prime;
function Image (N : in Long_Long_Integer;
Sign : in Boolean := False) return String is
Image : constant String := N'Image;
begin
if N < 0 then
return Image;
else
if Sign then
return "+" & Image (Image'First + 1 .. Image'Last);
else
return Image (Image'First + 1 .. Image'Last);
end if;
end if;
end Image;
procedure Show (Triangle : in Pascal_Triangle_Type) is
use Ada.Text_IO;
Begin
for I in reverse Triangle'Range loop
Put (Image (Triangle (I), Sign => True));
Put ("x^");
Put (Image (Long_Long_Integer (I)));
Put (" ");
end loop;
end Show;
procedure Show_Pascal_Triangles is
use Ada.Text_IO;
begin
for N in 0 .. 9 loop
declare
Pascal_Triangle : constant Pascal_Triangle_Type := Calculate_Pascal_Triangle (N);
begin
Put ("(x-1)^" & Image (Long_Long_Integer (N)) & " = ");
Show (Pascal_Triangle);
New_Line;
end;
end loop;
end Show_Pascal_Triangles;
procedure Show_Primes is
use Ada.Text_IO;
begin
for N in 2 .. 63 loop
if Is_Prime (N) then
Put (N'Image);
end if;
end loop;
New_Line;
end Show_Primes;
begin
Show_Pascal_Triangles;
Show_Primes;
end Test_For_Primes;
|
with Trendy_Terminal.Histories;
with Trendy_Terminal.Lines.Line_Vectors;
with Trendy_Test.Assertions;
with Trendy_Test.Assertions.Integer_Assertions;
use Trendy_Test.Assertions;
use Trendy_Test.Assertions.Integer_Assertions;
package body Trendy_Terminal.Histories.Tests is
procedure Assert_Contains
(Op : in out Trendy_Test.Operation'Class;
Container : Lines.Line_Vectors.Vector;
Item : String) is
begin
Assert (Op, Container.Contains (Lines.Make (Item)));
end Assert_Contains;
procedure Assert_Not_Contains
(Op : in out Trendy_Test.Operation'Class;
Container : Lines.Line_Vectors.Vector;
Item : String) is
begin
Assert (Op, not Container.Contains (Lines.Make (Item)));
end Assert_Not_Contains;
procedure Test_Simple_Completion (Op : in out Trendy_Test.Operation'Class) is
begin
Op.Register;
declare
Sample : Histories.History;
Completions : Lines.Line_Vectors.Vector;
begin
Assert_EQ (Op, Num_Entries (Sample), 0);
Add (Sample, "this is a sample");
Add (Sample, "this is a test");
Assert_EQ (Op, Num_Entries (Sample), 2);
Completions := Completions_Matching (Sample, "this is a ");
Assert_EQ (Op, Integer (Lines.Line_Vectors.Length (Completions)), 2);
Assert_Contains (Op, Completions, "this is a sample");
Assert_Contains (Op, Completions, "this is a test");
Assert_Not_Contains (Op, Completions, "this is a failure");
end;
end Test_Simple_Completion;
---------------------------------------------------------------------------
-- Test Registry
---------------------------------------------------------------------------
function All_Tests return Trendy_Test.Test_Group is (
1 => Test_Simple_Completion'Access
);
end Trendy_Terminal.Histories.Tests;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ A U X --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Einfo; use Einfo;
with Nlists; use Nlists;
with Snames; use Snames;
with Stand; use Stand;
with Uintp; use Uintp;
package body Sem_Aux is
----------------------
-- Ancestor_Subtype --
----------------------
function Ancestor_Subtype (Typ : Entity_Id) return Entity_Id is
begin
-- If this is first subtype, or is a base type, then there is no
-- ancestor subtype, so we return Empty to indicate this fact.
if Is_First_Subtype (Typ) or else Is_Base_Type (Typ) then
return Empty;
end if;
declare
D : constant Node_Id := Declaration_Node (Typ);
begin
-- If we have a subtype declaration, get the ancestor subtype
if Nkind (D) = N_Subtype_Declaration then
if Nkind (Subtype_Indication (D)) = N_Subtype_Indication then
return Entity (Subtype_Mark (Subtype_Indication (D)));
else
return Entity (Subtype_Indication (D));
end if;
-- If not, then no subtype indication is available
else
return Empty;
end if;
end;
end Ancestor_Subtype;
--------------------
-- Available_View --
--------------------
function Available_View (Ent : Entity_Id) return Entity_Id is
begin
-- Obtain the non-limited view (if available)
if Has_Non_Limited_View (Ent) then
return Get_Full_View (Non_Limited_View (Ent));
-- In all other cases, return entity unchanged
else
return Ent;
end if;
end Available_View;
--------------------
-- Constant_Value --
--------------------
function Constant_Value (Ent : Entity_Id) return Node_Id is
D : constant Node_Id := Declaration_Node (Ent);
Full_D : Node_Id;
begin
-- If we have no declaration node, then return no constant value. Not
-- clear how this can happen, but it does sometimes and this is the
-- safest approach.
if No (D) then
return Empty;
-- Normal case where a declaration node is present
elsif Nkind (D) = N_Object_Renaming_Declaration then
return Renamed_Object (Ent);
-- If this is a component declaration whose entity is a constant, it is
-- a prival within a protected function (and so has no constant value).
elsif Nkind (D) = N_Component_Declaration then
return Empty;
-- If there is an expression, return it
elsif Present (Expression (D)) then
return Expression (D);
-- For a constant, see if we have a full view
elsif Ekind (Ent) = E_Constant
and then Present (Full_View (Ent))
then
Full_D := Parent (Full_View (Ent));
-- The full view may have been rewritten as an object renaming
if Nkind (Full_D) = N_Object_Renaming_Declaration then
return Name (Full_D);
else
return Expression (Full_D);
end if;
-- Otherwise we have no expression to return
else
return Empty;
end if;
end Constant_Value;
---------------------------------
-- Corresponding_Unsigned_Type --
---------------------------------
function Corresponding_Unsigned_Type (Typ : Entity_Id) return Entity_Id is
pragma Assert (Is_Signed_Integer_Type (Typ));
Siz : constant Uint := Esize (Base_Type (Typ));
begin
if Siz = Esize (Standard_Short_Short_Integer) then
return Standard_Short_Short_Unsigned;
elsif Siz = Esize (Standard_Short_Integer) then
return Standard_Short_Unsigned;
elsif Siz = Esize (Standard_Unsigned) then
return Standard_Unsigned;
elsif Siz = Esize (Standard_Long_Integer) then
return Standard_Long_Unsigned;
elsif Siz = Esize (Standard_Long_Long_Integer) then
return Standard_Long_Long_Unsigned;
else
raise Program_Error;
end if;
end Corresponding_Unsigned_Type;
-----------------------------
-- Enclosing_Dynamic_Scope --
-----------------------------
function Enclosing_Dynamic_Scope (Ent : Entity_Id) return Entity_Id is
S : Entity_Id;
begin
-- The following test is an error defense against some syntax errors
-- that can leave scopes very messed up.
if Ent = Standard_Standard then
return Ent;
end if;
-- Normal case, search enclosing scopes
-- Note: the test for Present (S) should not be required, it defends
-- against an ill-formed tree.
S := Scope (Ent);
loop
-- If we somehow got an empty value for Scope, the tree must be
-- malformed. Rather than blow up we return Standard in this case.
if No (S) then
return Standard_Standard;
-- Quit if we get to standard or a dynamic scope. We must also
-- handle enclosing scopes that have a full view; required to
-- locate enclosing scopes that are synchronized private types
-- whose full view is a task type.
elsif S = Standard_Standard
or else Is_Dynamic_Scope (S)
or else (Is_Private_Type (S)
and then Present (Full_View (S))
and then Is_Dynamic_Scope (Full_View (S)))
then
return S;
-- Otherwise keep climbing
else
S := Scope (S);
end if;
end loop;
end Enclosing_Dynamic_Scope;
------------------------
-- First_Discriminant --
------------------------
function First_Discriminant (Typ : Entity_Id) return Entity_Id is
Ent : Entity_Id;
begin
pragma Assert
(Has_Discriminants (Typ) or else Has_Unknown_Discriminants (Typ));
Ent := First_Entity (Typ);
-- The discriminants are not necessarily contiguous, because access
-- discriminants will generate itypes. They are not the first entities
-- either because the tag must be ahead of them.
if Chars (Ent) = Name_uTag then
Next_Entity (Ent);
end if;
-- Skip all hidden stored discriminants if any
while Present (Ent) loop
exit when Ekind (Ent) = E_Discriminant
and then not Is_Completely_Hidden (Ent);
Next_Entity (Ent);
end loop;
-- Call may be on a private type with unknown discriminants, in which
-- case Ent is Empty, and as per the spec, we return Empty in this case.
-- Historical note: The assertion in previous versions that Ent is a
-- discriminant was overly cautious and prevented convenient application
-- of this function in the gnatprove context.
return Ent;
end First_Discriminant;
-------------------------------
-- First_Stored_Discriminant --
-------------------------------
function First_Stored_Discriminant (Typ : Entity_Id) return Entity_Id is
Ent : Entity_Id;
function Has_Completely_Hidden_Discriminant
(Typ : Entity_Id) return Boolean;
-- Scans the Discriminants to see whether any are Completely_Hidden
-- (the mechanism for describing non-specified stored discriminants)
-- Note that the entity list for the type may contain anonymous access
-- types created by expressions that constrain access discriminants.
----------------------------------------
-- Has_Completely_Hidden_Discriminant --
----------------------------------------
function Has_Completely_Hidden_Discriminant
(Typ : Entity_Id) return Boolean
is
Ent : Entity_Id;
begin
pragma Assert (Ekind (Typ) = E_Discriminant);
Ent := Typ;
while Present (Ent) loop
-- Skip anonymous types that may be created by expressions
-- used as discriminant constraints on inherited discriminants.
if Is_Itype (Ent) then
null;
elsif Ekind (Ent) = E_Discriminant
and then Is_Completely_Hidden (Ent)
then
return True;
end if;
Next_Entity (Ent);
end loop;
return False;
end Has_Completely_Hidden_Discriminant;
-- Start of processing for First_Stored_Discriminant
begin
pragma Assert
(Has_Discriminants (Typ)
or else Has_Unknown_Discriminants (Typ));
Ent := First_Entity (Typ);
if Chars (Ent) = Name_uTag then
Next_Entity (Ent);
end if;
if Has_Completely_Hidden_Discriminant (Ent) then
while Present (Ent) loop
exit when Ekind (Ent) = E_Discriminant
and then Is_Completely_Hidden (Ent);
Next_Entity (Ent);
end loop;
end if;
pragma Assert (Ekind (Ent) = E_Discriminant);
return Ent;
end First_Stored_Discriminant;
-------------------
-- First_Subtype --
-------------------
function First_Subtype (Typ : Entity_Id) return Entity_Id is
B : constant Entity_Id := Base_Type (Typ);
F : constant Node_Id := Freeze_Node (B);
Ent : Entity_Id;
begin
-- If the base type has no freeze node, it is a type in Standard, and
-- always acts as its own first subtype, except where it is one of the
-- predefined integer types. If the type is formal, it is also a first
-- subtype, and its base type has no freeze node. On the other hand, a
-- subtype of a generic formal is not its own first subtype. Its base
-- type, if anonymous, is attached to the formal type declaration from
-- which the first subtype is obtained.
if No (F) then
if B = Base_Type (Standard_Integer) then
return Standard_Integer;
elsif B = Base_Type (Standard_Long_Integer) then
return Standard_Long_Integer;
elsif B = Base_Type (Standard_Short_Short_Integer) then
return Standard_Short_Short_Integer;
elsif B = Base_Type (Standard_Short_Integer) then
return Standard_Short_Integer;
elsif B = Base_Type (Standard_Long_Long_Integer) then
return Standard_Long_Long_Integer;
elsif Is_Generic_Type (Typ) then
if Present (Parent (B)) then
return Defining_Identifier (Parent (B));
else
return Defining_Identifier (Associated_Node_For_Itype (B));
end if;
else
return B;
end if;
-- Otherwise we check the freeze node, if it has a First_Subtype_Link
-- then we use that link, otherwise (happens with some Itypes), we use
-- the base type itself.
else
Ent := First_Subtype_Link (F);
if Present (Ent) then
return Ent;
else
return B;
end if;
end if;
end First_Subtype;
-------------------------
-- First_Tag_Component --
-------------------------
function First_Tag_Component (Typ : Entity_Id) return Entity_Id is
Comp : Entity_Id;
Ctyp : Entity_Id;
begin
Ctyp := Typ;
pragma Assert (Is_Tagged_Type (Ctyp));
if Is_Class_Wide_Type (Ctyp) then
Ctyp := Root_Type (Ctyp);
end if;
if Is_Private_Type (Ctyp) then
Ctyp := Underlying_Type (Ctyp);
-- If the underlying type is missing then the source program has
-- errors and there is nothing else to do (the full-type declaration
-- associated with the private type declaration is missing).
if No (Ctyp) then
return Empty;
end if;
end if;
Comp := First_Entity (Ctyp);
while Present (Comp) loop
if Is_Tag (Comp) then
return Comp;
end if;
Next_Entity (Comp);
end loop;
-- No tag component found
return Empty;
end First_Tag_Component;
---------------------
-- Get_Binary_Nkind --
---------------------
function Get_Binary_Nkind (Op : Entity_Id) return Node_Kind is
begin
case Chars (Op) is
when Name_Op_Add => return N_Op_Add;
when Name_Op_Concat => return N_Op_Concat;
when Name_Op_Expon => return N_Op_Expon;
when Name_Op_Subtract => return N_Op_Subtract;
when Name_Op_Mod => return N_Op_Mod;
when Name_Op_Multiply => return N_Op_Multiply;
when Name_Op_Divide => return N_Op_Divide;
when Name_Op_Rem => return N_Op_Rem;
when Name_Op_And => return N_Op_And;
when Name_Op_Eq => return N_Op_Eq;
when Name_Op_Ge => return N_Op_Ge;
when Name_Op_Gt => return N_Op_Gt;
when Name_Op_Le => return N_Op_Le;
when Name_Op_Lt => return N_Op_Lt;
when Name_Op_Ne => return N_Op_Ne;
when Name_Op_Or => return N_Op_Or;
when Name_Op_Xor => return N_Op_Xor;
when others => raise Program_Error;
end case;
end Get_Binary_Nkind;
-----------------------
-- Get_Called_Entity --
-----------------------
function Get_Called_Entity (Call : Node_Id) return Entity_Id is
Nam : constant Node_Id := Name (Call);
Id : Entity_Id;
begin
if Nkind (Nam) = N_Explicit_Dereference then
Id := Etype (Nam);
pragma Assert (Ekind (Id) = E_Subprogram_Type);
elsif Nkind (Nam) = N_Selected_Component then
Id := Entity (Selector_Name (Nam));
elsif Nkind (Nam) = N_Indexed_Component then
Id := Entity (Selector_Name (Prefix (Nam)));
else
Id := Entity (Nam);
end if;
return Id;
end Get_Called_Entity;
------------------
-- Get_Rep_Item --
------------------
function Get_Rep_Item
(E : Entity_Id;
Nam : Name_Id;
Check_Parents : Boolean := True) return Node_Id
is
N : Node_Id;
begin
N := First_Rep_Item (E);
while Present (N) loop
-- Only one of Priority / Interrupt_Priority can be specified, so
-- return whichever one is present to catch illegal duplication.
if Nkind (N) = N_Pragma
and then
(Pragma_Name_Unmapped (N) = Nam
or else (Nam = Name_Priority
and then Pragma_Name (N) =
Name_Interrupt_Priority)
or else (Nam = Name_Interrupt_Priority
and then Pragma_Name (N) = Name_Priority))
then
if Check_Parents then
return N;
-- If Check_Parents is False, return N if the pragma doesn't
-- appear in the Rep_Item chain of the parent.
else
declare
Par : constant Entity_Id := Nearest_Ancestor (E);
-- This node represents the parent type of type E (if any)
begin
if No (Par) then
return N;
elsif not Present_In_Rep_Item (Par, N) then
return N;
end if;
end;
end if;
elsif Nkind (N) = N_Attribute_Definition_Clause
and then
(Chars (N) = Nam
or else (Nam = Name_Priority
and then Chars (N) = Name_Interrupt_Priority))
then
if Check_Parents or else Entity (N) = E then
return N;
end if;
elsif Nkind (N) = N_Aspect_Specification
and then
(Chars (Identifier (N)) = Nam
or else
(Nam = Name_Priority
and then Chars (Identifier (N)) = Name_Interrupt_Priority))
then
if Check_Parents then
return N;
elsif Entity (N) = E then
return N;
end if;
-- A Ghost-related aspect, if disabled, may have been replaced by a
-- null statement.
elsif Nkind (N) = N_Null_Statement then
N := Original_Node (N);
end if;
Next_Rep_Item (N);
end loop;
return Empty;
end Get_Rep_Item;
function Get_Rep_Item
(E : Entity_Id;
Nam1 : Name_Id;
Nam2 : Name_Id;
Check_Parents : Boolean := True) return Node_Id
is
Nam1_Item : constant Node_Id := Get_Rep_Item (E, Nam1, Check_Parents);
Nam2_Item : constant Node_Id := Get_Rep_Item (E, Nam2, Check_Parents);
N : Node_Id;
begin
-- Check both Nam1_Item and Nam2_Item are present
if No (Nam1_Item) then
return Nam2_Item;
elsif No (Nam2_Item) then
return Nam1_Item;
end if;
-- Return the first node encountered in the list
N := First_Rep_Item (E);
while Present (N) loop
if N = Nam1_Item or else N = Nam2_Item then
return N;
end if;
Next_Rep_Item (N);
end loop;
return Empty;
end Get_Rep_Item;
--------------------
-- Get_Rep_Pragma --
--------------------
function Get_Rep_Pragma
(E : Entity_Id;
Nam : Name_Id;
Check_Parents : Boolean := True) return Node_Id
is
N : constant Node_Id := Get_Rep_Item (E, Nam, Check_Parents);
begin
if Present (N) and then Nkind (N) = N_Pragma then
return N;
end if;
return Empty;
end Get_Rep_Pragma;
function Get_Rep_Pragma
(E : Entity_Id;
Nam1 : Name_Id;
Nam2 : Name_Id;
Check_Parents : Boolean := True) return Node_Id
is
Nam1_Item : constant Node_Id := Get_Rep_Pragma (E, Nam1, Check_Parents);
Nam2_Item : constant Node_Id := Get_Rep_Pragma (E, Nam2, Check_Parents);
N : Node_Id;
begin
-- Check both Nam1_Item and Nam2_Item are present
if No (Nam1_Item) then
return Nam2_Item;
elsif No (Nam2_Item) then
return Nam1_Item;
end if;
-- Return the first node encountered in the list
N := First_Rep_Item (E);
while Present (N) loop
if N = Nam1_Item or else N = Nam2_Item then
return N;
end if;
Next_Rep_Item (N);
end loop;
return Empty;
end Get_Rep_Pragma;
---------------------
-- Get_Unary_Nkind --
---------------------
function Get_Unary_Nkind (Op : Entity_Id) return Node_Kind is
begin
case Chars (Op) is
when Name_Op_Abs => return N_Op_Abs;
when Name_Op_Subtract => return N_Op_Minus;
when Name_Op_Not => return N_Op_Not;
when Name_Op_Add => return N_Op_Plus;
when others => raise Program_Error;
end case;
end Get_Unary_Nkind;
---------------------------------
-- Has_External_Tag_Rep_Clause --
---------------------------------
function Has_External_Tag_Rep_Clause (T : Entity_Id) return Boolean is
begin
pragma Assert (Is_Tagged_Type (T));
return Has_Rep_Item (T, Name_External_Tag, Check_Parents => False);
end Has_External_Tag_Rep_Clause;
------------------
-- Has_Rep_Item --
------------------
function Has_Rep_Item
(E : Entity_Id;
Nam : Name_Id;
Check_Parents : Boolean := True) return Boolean
is
begin
return Present (Get_Rep_Item (E, Nam, Check_Parents));
end Has_Rep_Item;
function Has_Rep_Item
(E : Entity_Id;
Nam1 : Name_Id;
Nam2 : Name_Id;
Check_Parents : Boolean := True) return Boolean
is
begin
return Present (Get_Rep_Item (E, Nam1, Nam2, Check_Parents));
end Has_Rep_Item;
function Has_Rep_Item (E : Entity_Id; N : Node_Id) return Boolean is
Item : Node_Id;
begin
pragma Assert
(Nkind (N) in N_Aspect_Specification
| N_Attribute_Definition_Clause
| N_Enumeration_Representation_Clause
| N_Pragma
| N_Record_Representation_Clause);
Item := First_Rep_Item (E);
while Present (Item) loop
if Item = N then
return True;
end if;
Next_Rep_Item (Item);
end loop;
return False;
end Has_Rep_Item;
--------------------
-- Has_Rep_Pragma --
--------------------
function Has_Rep_Pragma
(E : Entity_Id;
Nam : Name_Id;
Check_Parents : Boolean := True) return Boolean
is
begin
return Present (Get_Rep_Pragma (E, Nam, Check_Parents));
end Has_Rep_Pragma;
function Has_Rep_Pragma
(E : Entity_Id;
Nam1 : Name_Id;
Nam2 : Name_Id;
Check_Parents : Boolean := True) return Boolean
is
begin
return Present (Get_Rep_Pragma (E, Nam1, Nam2, Check_Parents));
end Has_Rep_Pragma;
--------------------------------
-- Has_Unconstrained_Elements --
--------------------------------
function Has_Unconstrained_Elements (T : Entity_Id) return Boolean is
U_T : constant Entity_Id := Underlying_Type (T);
begin
if No (U_T) then
return False;
elsif Is_Record_Type (U_T) then
return Has_Discriminants (U_T) and then not Is_Constrained (U_T);
elsif Is_Array_Type (U_T) then
return Has_Unconstrained_Elements (Component_Type (U_T));
else
return False;
end if;
end Has_Unconstrained_Elements;
----------------------
-- Has_Variant_Part --
----------------------
function Has_Variant_Part (Typ : Entity_Id) return Boolean is
FSTyp : Entity_Id;
Decl : Node_Id;
TDef : Node_Id;
CList : Node_Id;
begin
if not Is_Type (Typ) then
return False;
end if;
FSTyp := First_Subtype (Typ);
if not Has_Discriminants (FSTyp) then
return False;
end if;
-- Proceed with cautious checks here, return False if tree is not
-- as expected (may be caused by prior errors).
Decl := Declaration_Node (FSTyp);
if Nkind (Decl) /= N_Full_Type_Declaration then
return False;
end if;
TDef := Type_Definition (Decl);
if Nkind (TDef) /= N_Record_Definition then
return False;
end if;
CList := Component_List (TDef);
if Nkind (CList) /= N_Component_List then
return False;
else
return Present (Variant_Part (CList));
end if;
end Has_Variant_Part;
---------------------
-- In_Generic_Body --
---------------------
function In_Generic_Body (Id : Entity_Id) return Boolean is
S : Entity_Id;
begin
-- Climb scopes looking for generic body
S := Id;
while Present (S) and then S /= Standard_Standard loop
-- Generic package body
if Ekind (S) = E_Generic_Package
and then In_Package_Body (S)
then
return True;
-- Generic subprogram body
elsif Is_Subprogram (S)
and then Nkind (Unit_Declaration_Node (S)) =
N_Generic_Subprogram_Declaration
then
return True;
end if;
S := Scope (S);
end loop;
-- False if top of scope stack without finding a generic body
return False;
end In_Generic_Body;
-------------------------------
-- Initialization_Suppressed --
-------------------------------
function Initialization_Suppressed (Typ : Entity_Id) return Boolean is
begin
return Suppress_Initialization (Typ)
or else Suppress_Initialization (Base_Type (Typ));
end Initialization_Suppressed;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Obsolescent_Warnings.Init;
end Initialize;
-------------
-- Is_Body --
-------------
function Is_Body (N : Node_Id) return Boolean is
begin
return Nkind (N) in
N_Body_Stub | N_Entry_Body | N_Package_Body | N_Protected_Body |
N_Subprogram_Body | N_Task_Body;
end Is_Body;
---------------------
-- Is_By_Copy_Type --
---------------------
function Is_By_Copy_Type (Ent : Entity_Id) return Boolean is
begin
-- If Id is a private type whose full declaration has not been seen,
-- we assume for now that it is not a By_Copy type. Clearly this
-- attribute should not be used before the type is frozen, but it is
-- needed to build the associated record of a protected type. Another
-- place where some lookahead for a full view is needed ???
return
Is_Elementary_Type (Ent)
or else (Is_Private_Type (Ent)
and then Present (Underlying_Type (Ent))
and then Is_Elementary_Type (Underlying_Type (Ent)));
end Is_By_Copy_Type;
--------------------------
-- Is_By_Reference_Type --
--------------------------
function Is_By_Reference_Type (Ent : Entity_Id) return Boolean is
Btype : constant Entity_Id := Base_Type (Ent);
begin
if Error_Posted (Ent) or else Error_Posted (Btype) then
return False;
elsif Is_Private_Type (Btype) then
declare
Utyp : constant Entity_Id := Underlying_Type (Btype);
begin
if No (Utyp) then
return False;
else
return Is_By_Reference_Type (Utyp);
end if;
end;
elsif Is_Incomplete_Type (Btype) then
declare
Ftyp : constant Entity_Id := Full_View (Btype);
begin
-- Return true for a tagged incomplete type built as a shadow
-- entity in Build_Limited_Views. It can appear in the profile
-- of a thunk and the back end needs to know how it is passed.
if No (Ftyp) then
return Is_Tagged_Type (Btype);
else
return Is_By_Reference_Type (Ftyp);
end if;
end;
elsif Is_Concurrent_Type (Btype) then
return True;
elsif Is_Record_Type (Btype) then
if Is_Limited_Record (Btype)
or else Is_Tagged_Type (Btype)
or else Is_Volatile (Btype)
then
return True;
else
declare
C : Entity_Id;
begin
C := First_Component (Btype);
while Present (C) loop
-- For each component, test if its type is a by reference
-- type and if its type is volatile. Also test the component
-- itself for being volatile. This happens for example when
-- a Volatile aspect is added to a component.
if Is_By_Reference_Type (Etype (C))
or else Is_Volatile (Etype (C))
or else Is_Volatile (C)
then
return True;
end if;
Next_Component (C);
end loop;
end;
return False;
end if;
elsif Is_Array_Type (Btype) then
return
Is_Volatile (Btype)
or else Is_By_Reference_Type (Component_Type (Btype))
or else Is_Volatile (Component_Type (Btype))
or else Has_Volatile_Components (Btype);
else
return False;
end if;
end Is_By_Reference_Type;
-------------------------
-- Is_Definite_Subtype --
-------------------------
function Is_Definite_Subtype (T : Entity_Id) return Boolean is
pragma Assert (Is_Type (T));
K : constant Entity_Kind := Ekind (T);
begin
if Is_Constrained (T) then
return True;
elsif K in Array_Kind
or else K in Class_Wide_Kind
or else Has_Unknown_Discriminants (T)
then
return False;
-- Known discriminants: definite if there are default values. Note that
-- if any discriminant has a default, they all do.
elsif Has_Discriminants (T) then
return Present (Discriminant_Default_Value (First_Discriminant (T)));
else
return True;
end if;
end Is_Definite_Subtype;
---------------------
-- Is_Derived_Type --
---------------------
function Is_Derived_Type (Ent : E) return B is
Par : Node_Id;
begin
if Is_Type (Ent)
and then Base_Type (Ent) /= Root_Type (Ent)
and then not Is_Class_Wide_Type (Ent)
-- An access_to_subprogram whose result type is a limited view can
-- appear in a return statement, without the full view of the result
-- type being available. Do not interpret this as a derived type.
and then Ekind (Ent) /= E_Subprogram_Type
then
if not Is_Numeric_Type (Root_Type (Ent)) then
return True;
else
Par := Parent (First_Subtype (Ent));
return Present (Par)
and then Nkind (Par) = N_Full_Type_Declaration
and then Nkind (Type_Definition (Par)) =
N_Derived_Type_Definition;
end if;
else
return False;
end if;
end Is_Derived_Type;
-----------------------
-- Is_Generic_Formal --
-----------------------
function Is_Generic_Formal (E : Entity_Id) return Boolean is
Kind : Node_Kind;
begin
if No (E) then
return False;
else
-- Formal derived types are rewritten as private extensions, so
-- examine original node.
Kind := Nkind (Original_Node (Parent (E)));
return
Kind in N_Formal_Object_Declaration | N_Formal_Type_Declaration
or else Is_Formal_Subprogram (E)
or else
(Ekind (E) = E_Package
and then Nkind (Original_Node (Unit_Declaration_Node (E))) =
N_Formal_Package_Declaration);
end if;
end Is_Generic_Formal;
-------------------------------
-- Is_Immutably_Limited_Type --
-------------------------------
function Is_Immutably_Limited_Type (Ent : Entity_Id) return Boolean is
Btype : constant Entity_Id := Available_View (Base_Type (Ent));
begin
if Is_Limited_Record (Btype) then
return True;
elsif Ekind (Btype) = E_Limited_Private_Type
and then Nkind (Parent (Btype)) = N_Formal_Type_Declaration
then
return not In_Package_Body (Scope ((Btype)));
elsif Is_Private_Type (Btype) then
-- AI05-0063: A type derived from a limited private formal type is
-- not immutably limited in a generic body.
if Is_Derived_Type (Btype)
and then Is_Generic_Type (Etype (Btype))
then
if not Is_Limited_Type (Etype (Btype)) then
return False;
-- A descendant of a limited formal type is not immutably limited
-- in the generic body, or in the body of a generic child.
elsif Ekind (Scope (Etype (Btype))) = E_Generic_Package then
return not In_Package_Body (Scope (Btype));
else
return False;
end if;
else
declare
Utyp : constant Entity_Id := Underlying_Type (Btype);
begin
if No (Utyp) then
return False;
else
return Is_Immutably_Limited_Type (Utyp);
end if;
end;
end if;
elsif Is_Concurrent_Type (Btype) then
return True;
else
return False;
end if;
end Is_Immutably_Limited_Type;
---------------------
-- Is_Limited_Type --
---------------------
function Is_Limited_Type (Ent : Entity_Id) return Boolean is
Btype : constant E := Base_Type (Ent);
Rtype : constant E := Root_Type (Btype);
begin
if not Is_Type (Ent) then
return False;
elsif Ekind (Btype) = E_Limited_Private_Type
or else Is_Limited_Composite (Btype)
then
return True;
elsif Is_Concurrent_Type (Btype) then
return True;
-- The Is_Limited_Record flag normally indicates that the type is
-- limited. The exception is that a type does not inherit limitedness
-- from its interface ancestor. So the type may be derived from a
-- limited interface, but is not limited.
elsif Is_Limited_Record (Ent)
and then not Is_Interface (Ent)
then
return True;
-- Otherwise we will look around to see if there is some other reason
-- for it to be limited, except that if an error was posted on the
-- entity, then just assume it is non-limited, because it can cause
-- trouble to recurse into a murky entity resulting from other errors.
elsif Error_Posted (Ent) then
return False;
elsif Is_Record_Type (Btype) then
if Is_Limited_Interface (Ent) then
return True;
-- AI-419: limitedness is not inherited from a limited interface
elsif Is_Limited_Record (Rtype) then
return not Is_Interface (Rtype)
or else Is_Protected_Interface (Rtype)
or else Is_Synchronized_Interface (Rtype)
or else Is_Task_Interface (Rtype);
elsif Is_Class_Wide_Type (Btype) then
return Is_Limited_Type (Rtype);
else
declare
C : E;
begin
C := First_Component (Btype);
while Present (C) loop
if Is_Limited_Type (Etype (C)) then
return True;
end if;
Next_Component (C);
end loop;
end;
return False;
end if;
elsif Is_Array_Type (Btype) then
return Is_Limited_Type (Component_Type (Btype));
else
return False;
end if;
end Is_Limited_Type;
---------------------
-- Is_Limited_View --
---------------------
function Is_Limited_View (Ent : Entity_Id) return Boolean is
Btype : constant Entity_Id := Available_View (Base_Type (Ent));
begin
if Is_Limited_Record (Btype) then
return True;
elsif Ekind (Btype) = E_Limited_Private_Type
and then Nkind (Parent (Btype)) = N_Formal_Type_Declaration
then
return not In_Package_Body (Scope ((Btype)));
elsif Is_Private_Type (Btype) then
-- AI05-0063: A type derived from a limited private formal type is
-- not immutably limited in a generic body.
if Is_Derived_Type (Btype)
and then Is_Generic_Type (Etype (Btype))
then
if not Is_Limited_Type (Etype (Btype)) then
return False;
-- A descendant of a limited formal type is not immutably limited
-- in the generic body, or in the body of a generic child.
elsif Ekind (Scope (Etype (Btype))) = E_Generic_Package then
return not In_Package_Body (Scope (Btype));
else
return False;
end if;
else
declare
Utyp : constant Entity_Id := Underlying_Type (Btype);
begin
if No (Utyp) then
return False;
else
return Is_Limited_View (Utyp);
end if;
end;
end if;
elsif Is_Concurrent_Type (Btype) then
return True;
elsif Is_Record_Type (Btype) then
-- Note that we return True for all limited interfaces, even though
-- (unsynchronized) limited interfaces can have descendants that are
-- nonlimited, because this is a predicate on the type itself, and
-- things like functions with limited interface results need to be
-- handled as build in place even though they might return objects
-- of a type that is not inherently limited.
if Is_Class_Wide_Type (Btype) then
return Is_Limited_View (Root_Type (Btype));
else
declare
C : Entity_Id;
begin
C := First_Component (Btype);
while Present (C) loop
-- Don't consider components with interface types (which can
-- only occur in the case of a _parent component anyway).
-- They don't have any components, plus it would cause this
-- function to return true for nonlimited types derived from
-- limited interfaces.
if not Is_Interface (Etype (C))
and then Is_Limited_View (Etype (C))
then
return True;
end if;
Next_Component (C);
end loop;
end;
return False;
end if;
elsif Is_Array_Type (Btype) then
return Is_Limited_View (Component_Type (Btype));
else
return False;
end if;
end Is_Limited_View;
----------------------------
-- Is_Protected_Operation --
----------------------------
function Is_Protected_Operation (E : Entity_Id) return Boolean is
begin
return
Is_Entry (E)
or else (Is_Subprogram (E)
and then Nkind (Parent (Unit_Declaration_Node (E))) =
N_Protected_Definition);
end Is_Protected_Operation;
-------------------------------
-- Is_Record_Or_Limited_Type --
-------------------------------
function Is_Record_Or_Limited_Type (Typ : Entity_Id) return Boolean is
begin
return Is_Record_Type (Typ) or else Is_Limited_Type (Typ);
end Is_Record_Or_Limited_Type;
----------------------
-- Nearest_Ancestor --
----------------------
function Nearest_Ancestor (Typ : Entity_Id) return Entity_Id is
D : constant Node_Id := Original_Node (Declaration_Node (Typ));
-- We use the original node of the declaration, because derived
-- types from record subtypes are rewritten as record declarations,
-- and it is the original declaration that carries the ancestor.
begin
-- If we have a subtype declaration, get the ancestor subtype
if Nkind (D) = N_Subtype_Declaration then
if Nkind (Subtype_Indication (D)) = N_Subtype_Indication then
return Entity (Subtype_Mark (Subtype_Indication (D)));
else
return Entity (Subtype_Indication (D));
end if;
-- If derived type declaration, find who we are derived from
elsif Nkind (D) = N_Full_Type_Declaration
and then Nkind (Type_Definition (D)) = N_Derived_Type_Definition
then
declare
DTD : constant Entity_Id := Type_Definition (D);
SI : constant Entity_Id := Subtype_Indication (DTD);
begin
if Is_Entity_Name (SI) then
return Entity (SI);
else
return Entity (Subtype_Mark (SI));
end if;
end;
-- If this is a concurrent declaration with a nonempty interface list,
-- get the first progenitor. Account for case of a record type created
-- for a concurrent type (which is the only case that seems to occur
-- in practice).
elsif Nkind (D) = N_Full_Type_Declaration
and then (Is_Concurrent_Type (Defining_Identifier (D))
or else Is_Concurrent_Record_Type (Defining_Identifier (D)))
and then Is_Non_Empty_List (Interface_List (Type_Definition (D)))
then
return Entity (First (Interface_List (Type_Definition (D))));
-- If derived type and private type, get the full view to find who we
-- are derived from.
elsif Is_Derived_Type (Typ)
and then Is_Private_Type (Typ)
and then Present (Full_View (Typ))
then
return Nearest_Ancestor (Full_View (Typ));
-- Otherwise, nothing useful to return, return Empty
else
return Empty;
end if;
end Nearest_Ancestor;
---------------------------
-- Nearest_Dynamic_Scope --
---------------------------
function Nearest_Dynamic_Scope (Ent : Entity_Id) return Entity_Id is
begin
if Is_Dynamic_Scope (Ent) then
return Ent;
else
return Enclosing_Dynamic_Scope (Ent);
end if;
end Nearest_Dynamic_Scope;
------------------------
-- Next_Tag_Component --
------------------------
function Next_Tag_Component (Tag : Entity_Id) return Entity_Id is
Comp : Entity_Id;
begin
pragma Assert (Is_Tag (Tag));
-- Loop to look for next tag component
Comp := Next_Entity (Tag);
while Present (Comp) loop
if Is_Tag (Comp) then
pragma Assert (Chars (Comp) /= Name_uTag);
return Comp;
end if;
Next_Entity (Comp);
end loop;
-- No tag component found
return Empty;
end Next_Tag_Component;
-----------------------
-- Number_Components --
-----------------------
function Number_Components (Typ : Entity_Id) return Nat is
N : Nat := 0;
Comp : Entity_Id;
begin
-- We do not call Einfo.First_Component_Or_Discriminant, as this
-- function does not skip completely hidden discriminants, which we
-- want to skip here.
if Has_Discriminants (Typ) then
Comp := First_Discriminant (Typ);
else
Comp := First_Component (Typ);
end if;
while Present (Comp) loop
N := N + 1;
Next_Component_Or_Discriminant (Comp);
end loop;
return N;
end Number_Components;
--------------------------
-- Number_Discriminants --
--------------------------
function Number_Discriminants (Typ : Entity_Id) return Pos is
N : Nat := 0;
Discr : Entity_Id := First_Discriminant (Typ);
begin
while Present (Discr) loop
N := N + 1;
Next_Discriminant (Discr);
end loop;
return N;
end Number_Discriminants;
----------------------------------------------
-- Object_Type_Has_Constrained_Partial_View --
----------------------------------------------
function Object_Type_Has_Constrained_Partial_View
(Typ : Entity_Id;
Scop : Entity_Id) return Boolean
is
begin
return Has_Constrained_Partial_View (Typ)
or else (In_Generic_Body (Scop)
and then Is_Generic_Type (Base_Type (Typ))
and then (Is_Private_Type (Base_Type (Typ))
or else Is_Derived_Type (Base_Type (Typ)))
and then not Is_Tagged_Type (Typ)
and then not (Is_Array_Type (Typ)
and then not Is_Constrained (Typ))
and then Has_Discriminants (Typ));
end Object_Type_Has_Constrained_Partial_View;
------------------
-- Package_Body --
------------------
function Package_Body (E : Entity_Id) return Node_Id is
N : Node_Id;
begin
if Ekind (E) = E_Package_Body then
N := Parent (E);
if Nkind (N) = N_Defining_Program_Unit_Name then
N := Parent (N);
end if;
else
N := Package_Spec (E);
if Present (Corresponding_Body (N)) then
N := Parent (Corresponding_Body (N));
if Nkind (N) = N_Defining_Program_Unit_Name then
N := Parent (N);
end if;
else
N := Empty;
end if;
end if;
return N;
end Package_Body;
------------------
-- Package_Spec --
------------------
function Package_Spec (E : Entity_Id) return Node_Id is
begin
return Parent (Package_Specification (E));
end Package_Spec;
---------------------------
-- Package_Specification --
---------------------------
function Package_Specification (E : Entity_Id) return Node_Id is
N : Node_Id;
begin
N := Parent (E);
if Nkind (N) = N_Defining_Program_Unit_Name then
N := Parent (N);
end if;
return N;
end Package_Specification;
---------------------
-- Subprogram_Body --
---------------------
function Subprogram_Body (E : Entity_Id) return Node_Id is
Body_E : constant Entity_Id := Subprogram_Body_Entity (E);
begin
if No (Body_E) then
return Empty;
else
return Parent (Subprogram_Specification (Body_E));
end if;
end Subprogram_Body;
----------------------------
-- Subprogram_Body_Entity --
----------------------------
function Subprogram_Body_Entity (E : Entity_Id) return Entity_Id is
N : constant Node_Id := Parent (Subprogram_Specification (E));
-- Declaration for E
begin
-- If this declaration is not a subprogram body, then it must be a
-- subprogram declaration or body stub, from which we can retrieve the
-- entity for the corresponding subprogram body if any, or an abstract
-- subprogram declaration, for which we return Empty.
case Nkind (N) is
when N_Subprogram_Body =>
return E;
when N_Subprogram_Body_Stub
| N_Subprogram_Declaration
=>
return Corresponding_Body (N);
when others =>
return Empty;
end case;
end Subprogram_Body_Entity;
---------------------
-- Subprogram_Spec --
---------------------
function Subprogram_Spec (E : Entity_Id) return Node_Id is
N : constant Node_Id := Parent (Subprogram_Specification (E));
-- Declaration for E
begin
-- This declaration is either subprogram declaration or a subprogram
-- body, in which case return Empty.
if Nkind (N) = N_Subprogram_Declaration then
return N;
else
return Empty;
end if;
end Subprogram_Spec;
------------------------------
-- Subprogram_Specification --
------------------------------
function Subprogram_Specification (E : Entity_Id) return Node_Id is
N : Node_Id;
begin
N := Parent (E);
if Nkind (N) = N_Defining_Program_Unit_Name then
N := Parent (N);
end if;
-- If the Parent pointer of E is not a subprogram specification node
-- (going through an intermediate N_Defining_Program_Unit_Name node
-- for subprogram units), then E is an inherited operation. Its parent
-- points to the type derivation that produces the inheritance: that's
-- the node that generates the subprogram specification. Its alias
-- is the parent subprogram, and that one points to a subprogram
-- declaration, or to another type declaration if this is a hierarchy
-- of derivations.
if Nkind (N) not in N_Subprogram_Specification then
pragma Assert (Present (Alias (E)));
N := Subprogram_Specification (Alias (E));
end if;
return N;
end Subprogram_Specification;
--------------------
-- Ultimate_Alias --
--------------------
function Ultimate_Alias (Prim : Entity_Id) return Entity_Id is
E : Entity_Id := Prim;
begin
while Present (Alias (E)) loop
pragma Assert (Alias (E) /= E);
E := Alias (E);
end loop;
return E;
end Ultimate_Alias;
--------------------------
-- Unit_Declaration_Node --
--------------------------
function Unit_Declaration_Node (Unit_Id : Entity_Id) return Node_Id is
N : Node_Id := Parent (Unit_Id);
begin
-- Predefined operators do not have a full function declaration
if Ekind (Unit_Id) = E_Operator then
return N;
end if;
-- Isn't there some better way to express the following ???
while Nkind (N) /= N_Abstract_Subprogram_Declaration
and then Nkind (N) /= N_Entry_Body
and then Nkind (N) /= N_Entry_Declaration
and then Nkind (N) /= N_Formal_Package_Declaration
and then Nkind (N) /= N_Function_Instantiation
and then Nkind (N) /= N_Generic_Package_Declaration
and then Nkind (N) /= N_Generic_Subprogram_Declaration
and then Nkind (N) /= N_Package_Declaration
and then Nkind (N) /= N_Package_Body
and then Nkind (N) /= N_Package_Instantiation
and then Nkind (N) /= N_Package_Renaming_Declaration
and then Nkind (N) /= N_Procedure_Instantiation
and then Nkind (N) /= N_Protected_Body
and then Nkind (N) /= N_Protected_Type_Declaration
and then Nkind (N) /= N_Subprogram_Declaration
and then Nkind (N) /= N_Subprogram_Body
and then Nkind (N) /= N_Subprogram_Body_Stub
and then Nkind (N) /= N_Subprogram_Renaming_Declaration
and then Nkind (N) /= N_Task_Body
and then Nkind (N) /= N_Task_Type_Declaration
and then Nkind (N) not in N_Formal_Subprogram_Declaration
and then Nkind (N) not in N_Generic_Renaming_Declaration
loop
N := Parent (N);
-- We don't use Assert here, because that causes an infinite loop
-- when assertions are turned off. Better to crash.
if No (N) then
raise Program_Error;
end if;
end loop;
return N;
end Unit_Declaration_Node;
end Sem_Aux;
|
pragma Ada_2012;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings;
package bits_types_u_locale_t_h is
-- Definition of struct __locale_struct and __locale_t.
-- Copyright (C) 1997-2021 Free Software Foundation, Inc.
-- This file is part of the GNU C Library.
-- Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
-- The GNU C Library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- The GNU C Library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
-- You should have received a copy of the GNU Lesser General Public
-- License along with the GNU C Library; if not, see
-- <https://www.gnu.org/licenses/>.
-- POSIX.1-2008: the locale_t type, representing a locale context
-- (implementation-namespace version). This type should be treated
-- as opaque by applications; some details are exposed for the sake of
-- efficiency in e.g. ctype functions.
-- Note: LC_ALL is not a valid index into this array.
-- 13 = __LC_LAST.
type uu_locale_data;
type uu_locale_struct_array914 is array (0 .. 12) of access uu_locale_data;
type uu_locale_struct_array919 is array (0 .. 12) of Interfaces.C.Strings.chars_ptr;
type uu_locale_struct is record
uu_locales : uu_locale_struct_array914; -- /usr/include/bits/types/__locale_t.h:31
uu_ctype_b : access unsigned_short; -- /usr/include/bits/types/__locale_t.h:34
uu_ctype_tolower : access int; -- /usr/include/bits/types/__locale_t.h:35
uu_ctype_toupper : access int; -- /usr/include/bits/types/__locale_t.h:36
uu_names : uu_locale_struct_array919; -- /usr/include/bits/types/__locale_t.h:39
end record
with Convention => C_Pass_By_Copy; -- /usr/include/bits/types/__locale_t.h:28
type uu_locale_data is null record; -- incomplete struct
-- To increase the speed of this solution we add some special members.
-- Note: LC_ALL is not a valid index into this array.
type uu_locale_t is access all uu_locale_struct; -- /usr/include/bits/types/__locale_t.h:42
end bits_types_u_locale_t_h;
|
-- Generated at 2015-03-31 18:55:08 +0000 by Natools.Static_Hash_Maps
-- from src/natools-s_expressions-conditionals-strings-maps.sx
function Natools.Static_Maps.S_Expressions.Conditionals.Strings.T
return Boolean;
pragma Pure (Natools.Static_Maps.S_Expressions.Conditionals.Strings.T);
|
-- C45252A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- FOR FIXED POINT TYPES, CHECK THAT
-- CONSTRAINT_ERROR IS RAISED WHEN A LITERAL USED IN A COMPARISON OR
-- MEMBERSHIP OPERATION (AS THE FIRST OPERAND) DOES NOT BELONG TO THE
-- BASE TYPE.
--
-- CHECK THAT NO EXCEPTION IS RAISED FOR A FIXED POINT RELATIONAL OR
-- MEMBERSHIP OPERATION IF LITERAL VALUES BELONG TO THE BASE TYPE.
-- CASE A: BASIC TYPES THAT FIT THE CHARACTERISTICS OF DURATION'BASE.
-- *** NOTE: This test has been modified since ACVC version 1.11 to -- 9X
-- *** remove incompatibilities associated with the transition -- 9X
-- *** to Ada 9X. -- 9X
-- WRG 9/10/86
-- JRL 03/30/93 REMOVED NUMERIC_ERROR FROM TEST.
WITH REPORT; USE REPORT;
PROCEDURE C45252A IS
-- THE NAME OF EACH TYPE OR SUBTYPE ENDS WITH THAT TYPE'S
-- 'MANTISSA VALUE.
TYPE MIDDLE_M3 IS DELTA 0.5 RANGE 0.0 .. 2.5;
TYPE LIKE_DURATION_M23 IS DELTA 0.020 RANGE -86_400.0 .. 86_400.0;
BEGIN
TEST ("C45252A", "CHECK RAISING OF EXCEPTIONS BY RELATIONAL " &
"OPERATIONS FOR FIXED POINT TYPES - BASIC TYPES");
-------------------------------------------------------------------
BEGIN
-- 2.0 ** 31 < 2.9E9 < 2.0 ** 32.
IF 2.9E9 <= LIKE_DURATION_M23'LAST THEN
FAILED ("2.9E9 <= LIKE_DURATION_M23'LAST");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
COMMENT ("CONSTRAINT_ERROR RAISED BY COMPARISON " &
"""2.9E9 <= LIKE_DURATION_M23'LAST""");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED BY COMPARISON " &
"""2.9E9 <= LIKE_DURATION_M23'LAST""");
END;
-------------------------------------------------------------------
BEGIN
-- 2.0 ** 63 < 1.0E19 < 2.0 ** 64.
IF 1.0E19 IN LIKE_DURATION_M23 THEN
FAILED ("1.0E19 IN LIKE_DURATION_M23");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
COMMENT ("CONSTRAINT_ERROR RAISED BY MEMBERSHIP TEST " &
"""1.0E19 IN LIKE_DURATION_M23""");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED BY MEMBERSHIP TEST " &
"""1.0E19 IN LIKE_DURATION_M23""");
END;
-------------------------------------------------------------------
BEGIN
-- 2.0 ** 63 < 1.0E19 < 2.0 ** 64.
IF 1.0E19 <= MIDDLE_M3'LAST THEN
FAILED ("1.0E19 <= MIDDLE_M3'LAST");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
COMMENT ("CONSTRAINT_ERROR RAISED BY COMPARISON " &
"""1.0E19 <= MIDDLE_M3'LAST""");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED BY COMPARISON " &
"""1.0E19 <= MIDDLE_M3'LAST""");
END;
-------------------------------------------------------------------
BEGIN
-- 2.0 ** 31 < 2.9E9 < 2.0 ** 32.
IF 2.9E9 IN MIDDLE_M3 THEN
FAILED ("2.9E9 IN MIDDLE_M3");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
COMMENT ("CONSTRAINT_ERROR RAISED BY MEMBERSHIP TEST " &
"""2.9E9 IN MIDDLE_M3""");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED BY MEMBERSHIP TEST " &
"""2.9E9 IN MIDDLE_M3""");
END;
-------------------------------------------------------------------
BEGIN
-- 3.5 IS A MODEL NUMBER OF THE TYPE MIDDLE_M3.
IF 3.5 <= MIDDLE_M3'LAST THEN
FAILED ("3.5 <= MIDDLE_M3'LAST");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("CONSTRAINT_ERROR RAISED BY COMPARISON " &
"""3.5 <= MIDDLE_M3'LAST""");
WHEN OTHERS =>
FAILED ("SOME EXCEPTION RAISED BY COMPARISON " &
"""3.5 <= MIDDLE_M3'LAST""");
END;
-------------------------------------------------------------------
BEGIN
IF 3.0 IN MIDDLE_M3 THEN
FAILED ("3.0 IN MIDDLE_M3");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("CONSTRAINT_ERROR RAISED BY MEMBERSHIP TEST " &
"""3.0 IN MIDDLE_M3""");
WHEN OTHERS =>
FAILED ("SOME EXCEPTION RAISED BY MEMBERSHIP TEST " &
"""3.0 IN MIDDLE_M3""");
END;
-------------------------------------------------------------------
BEGIN
IF 86_450.0 <= LIKE_DURATION_M23'LAST THEN
FAILED ("86_450.0 <= LIKE_DURATION_M23'LAST");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("CONSTRAINT_ERROR RAISED BY COMPARISON " &
"""86_450.0 <= LIKE_DURATION_M23'LAST""");
WHEN OTHERS =>
FAILED ("SOME EXCEPTION RAISED BY COMPARISON " &
"""86_450.0 <= LIKE_DURATION_M23'LAST""");
END;
-------------------------------------------------------------------
BEGIN
IF 86_500.0 IN LIKE_DURATION_M23 THEN
FAILED ("86_500.0 IN LIKE_DURATION_M23");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("CONSTRAINT_ERROR RAISED BY MEMBERSHIP TEST " &
"""86_500.0 IN LIKE_DURATION_M23""");
WHEN OTHERS =>
FAILED ("SOME EXCEPTION RAISED BY MEMBERSHIP TEST " &
"""86_500.0 IN LIKE_DURATION_M23""");
END;
-------------------------------------------------------------------
BEGIN
IF -86_450.0 IN LIKE_DURATION_M23 THEN
FAILED ("-86_450.0 IN LIKE_DURATION_M23");
END IF;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("CONSTRAINT_ERROR RAISED BY MEMBERSHIP TEST " &
"""-86_450.0 IN LIKE_DURATION_M23""");
WHEN OTHERS =>
FAILED ("SOME EXCEPTION RAISED BY MEMBERSHIP TEST " &
"""-86_450.0 IN LIKE_DURATION_M23""");
END;
-------------------------------------------------------------------
RESULT;
END C45252A;
|
with System;
package STM32F4xx is
Flash_Base : constant := 16#0800_0000#;
VECT_TAB_OFFSET : constant := 16#00#;
Peripherals : constant := 16#4000_0000#;
type Uint8 is range 0 .. 255;
for Uint8'Size use 8;
type Uint32 is mod 2 ** 32;
type UInt8_Array is array (Positive range <>) of Uint8;
type Int_Array is array (Positive range <>) of Uint32;
type RCC_Type is
record
CR : Uint32;
PLLCFGR : Uint32;
CFGR : Uint32;
CIR : Uint32;
AHB1RSTR : Uint32;
AHB2RSTR : Uint32;
AHB3RSTR : Uint32;
RESERVED0 : Uint32;
APB1RSTR : Uint32;
APB2RSTR : Uint32;
RESERVED1 : Int_Array (1 .. 2);
AHB1ENR : Uint32;
AHB2ENR : Uint32;
AHB3ENR : Uint32;
RESERVED2 : Uint32;
APB1ENR : Uint32;
APB2ENR : Uint32;
RESERVED3 : Int_Array (1 .. 2);
AHB1LPENR : Uint32;
AHB2LPENR : Uint32;
AHB3LPENR : Uint32;
RESERVED4 : Uint32;
APB1LPENR : Uint32;
APB2LPENR : Uint32;
RESERVED5 : Int_Array (1 .. 2);
BDCR : Uint32;
CSR : Uint32;
RESERVED6 : Int_Array (1 .. 2);
SSCGR : Uint32;
PLLI2SCFGR : Uint32;
end record;
RCC : RCC_Type;
pragma Import (ASM, RCC);
for RCC'Address use System'To_Address (Peripherals + 16#3800#);
type SCB_Type is
record
CPUID : Uint32;
ICSR : Uint32;
VTOR : Uint32;
AIRCR : Uint32;
SCR : Uint32;
CCR : Uint32;
SHP : UInt8_Array (1 .. 12);
SHCSR : Uint32;
CFSR : Uint32;
HFSR : Uint32;
DFSR : Uint32;
MMFAR : Uint32;
BFAR : Uint32;
AFSR : Uint32;
PFR : Int_Array (1 .. 2);
DFR : Uint32;
ADR : Uint32;
MMFR : Int_Array (1 .. 4);
ISAR : Int_Array (1 .. 5);
RESERVED0 : Int_Array (1 .. 5);
CPACR : Uint32;
end record;
SCB : SCB_Type;
pragma Import (ASM, SCB);
for SCB'Address use System'To_Address (16#E000_E000# + 16#0D00#);
type PWR_Type is
record
CR : Uint32;
CSR : Uint32;
end record;
PWR : PWR_Type;
pragma Import (ASM, PWR);
for PWR'Address use System'To_Address (Peripherals + 16#7000#);
type Flash_Type is
record
ACR : Uint32;
KEYR : Uint32;
OPTKEYR : Uint32;
SR : Uint32;
CR : Uint32;
OPTCR : Uint32;
end record;
Flash : Flash_Type;
pragma Import (ASM, Flash);
for Flash'Address use System'To_Address (Flash_Base);
RCC_CR_HSEON : constant := 16#0001_0000#;
RCC_CR_HSERDY : constant := 16#0002_0000#;
RCC_CR_PLLON : constant := 16#0100_0000#;
RCC_CR_PLLRDY : constant := 16#0200_0000#;
HSE_STARTUP_TIMEOUT : constant := 16#0500#;
RESET : constant := 0;
SET : constant := 16#FFFF_FFFF#;
RCC_APB1ENR_PWREN : constant := 16#1000_0000#;
RCC_CFGR_HPRE_DIV1 : constant := 16#0000_0000#;
RCC_CFGR_HPRE_DIV2 : constant := 16#0000_0080#;
RCC_CFGR_HPRE_DIV4 : constant := 16#0000_0090#;
RCC_CFGR_HPRE_DIV8 : constant := 16#0000_00A0#;
RCC_CFGR_PPRE1_DIV4 : constant := 16#0000_1400#;
RCC_CFGR_PPRE2_DIV2 : constant := 16#0000_8000#;
RCC_CFGR_PPRE2_DIV4 : constant := 16#0000_A000#;
RCC_PLLCFGR_PLLSRC_HSE : constant := 16#0040_0000#;
FLASH_ACR_LATENCY_5WS : constant := 16#0000_0005#;
FLASH_ACR_ICEN : constant := 16#0000_0200#;
FLASH_ACR_DCEN : constant := 16#0000_0400#;
RCC_CFGR_SW : constant := 16#0000_0003#;
RCC_CFGR_SW_PLL : constant := 16#0000_0008#;
RCC_CFGR_SWS : constant := 16#0000_000C#;
RCC_CFGR_SWS_PLL : constant := 16#0000_0008#;
PWR_CR_VOS : constant := 16#4000#;
procedure Initialise;
pragma Export (ASM, Initialise, "SystemInit");
procedure Set_Clock;
end STM32F4xx;
|
------------------------------------------------------------------------------
-- --
-- GNU ADA RUNTIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . T A S K _ P R I M I T I V E S --
-- --
-- S p e c --
-- --
-- $Revision: 1.1 $ --
-- --
-- Copyright (C) 1991,1992,1993,1994,1995,1996 Florida State University --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNARL 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 GNARL; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. It is --
-- now maintained by Ada Core Technologies Inc. in cooperation with Florida --
-- State University (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
with Interfaces.C;
-- Used for Size_t;
with Interfaces.C.Pthreads;
-- Used for, size_t,
-- pthread_mutex_t,
-- pthread_cond_t,
-- pthread_t
with Interfaces.C.POSIX_RTE;
-- Used for, Signal,
-- siginfo_ptr,
with System.Task_Clock;
-- Used for, Stimespec
with Unchecked_Conversion;
pragma Elaborate_All (Interfaces.C.Pthreads);
with System.Task_Info;
package System.Task_Primitives is
-- Low level Task size and state definition
type LL_Task_Procedure_Access is access procedure (Arg : System.Address);
type Pre_Call_State is new System.Address;
type Task_Storage_Size is new Interfaces.C.size_t;
type Machine_Exceptions is new Interfaces.C.POSIX_RTE.Signal;
type Error_Information is new Interfaces.C.POSIX_RTE.siginfo_ptr;
type Lock is private;
type Condition_Variable is private;
-- The above types should both be limited. They are not due to a hack in
-- ATCB allocation which allocates a block of the correct size and then
-- assigns an initialized ATCB to it. This won't work with limited types.
-- When allocation is done with new, these can become limited once again.
-- ???
type Task_Control_Block is record
LL_Entry_Point : LL_Task_Procedure_Access;
LL_Arg : System.Address;
Thread : aliased Interfaces.C.Pthreads.pthread_t;
Stack_Size : Task_Storage_Size;
Stack_Limit : System.Address;
end record;
type TCB_Ptr is access all Task_Control_Block;
-- Task ATCB related and variables.
function Address_To_TCB_Ptr is new
Unchecked_Conversion (System.Address, TCB_Ptr);
procedure Initialize_LL_Tasks (T : TCB_Ptr);
-- Initialize GNULLI. T points to the Task Control Block that should
-- be initialized for use by the environment task.
function Self return TCB_Ptr;
-- Return a pointer to the Task Control Block of the calling task.
procedure Initialize_Lock (Prio : System.Any_Priority; L : in out Lock);
-- Initialize a lock object. Prio is the ceiling priority associated
-- with the lock.
procedure Finalize_Lock (L : in out Lock);
-- Finalize a lock object, freeing any resources allocated by the
-- corresponding Initialize_Lock.
procedure Write_Lock (L : in out Lock; Ceiling_Violation : out Boolean);
pragma Inline (Write_Lock);
-- Lock a lock object for write access to a critical section. After
-- this operation returns, the calling task owns the lock, and
-- no other Write_Lock or Read_Lock operation on the same object will
-- return the owner executes an Unlock operation on the same object.
procedure Read_Lock (L : in out Lock; Ceiling_Violation : out Boolean);
pragma Inline (Read_Lock);
-- Lock a lock object for read access to a critical section. After
-- this operation returns, the calling task owns the lock, and
-- no other Write_Lock operation on the same object will return until
-- the owner(s) execute Unlock operation(s) on the same object.
-- A Read_Lock to an owned lock object may return while the lock is
-- still owned, though an implementation may also implement
-- Read_Lock to have the same semantics.
procedure Unlock (L : in out Lock);
pragma Inline (Unlock);
-- Unlock a locked lock object. The results are undefined if the
-- calling task does not own the lock. Lock/Unlock operations must
-- be nested, that is, the argument to Unlock must be the object
-- most recently locked.
procedure Initialize_Cond (Cond : in out Condition_Variable);
-- Initialize a condition variable object.
procedure Finalize_Cond (Cond : in out Condition_Variable);
-- Finalize a condition variable object, recovering any resources
-- allocated for it by Initialize_Cond.
procedure Cond_Wait (Cond : in out Condition_Variable; L : in out Lock);
pragma Inline (Cond_Wait);
-- Wait on a condition variable. The mutex object L is unlocked
-- atomically, such that another task that is able to lock the mutex
-- can be assured that the wait has actually commenced, and that
-- a Cond_Signal operation will cause the waiting task to become
-- eligible for execution once again. Before Cond_Wait returns,
-- the waiting task will again lock the mutex. The waiting task may become
-- eligible for execution at any time, but will become eligible for
-- execution when a Cond_Signal operation is performed on the
-- same condition variable object. The effect of more than one
-- task waiting on the same condition variable is unspecified.
procedure Cond_Timed_Wait
(Cond : in out Condition_Variable;
L : in out Lock; Abs_Time : System.Task_Clock.Stimespec;
Timed_Out : out Boolean);
pragma Inline (Cond_Timed_Wait);
-- Wait on a condition variable, as for Cond_Wait, above. In addition,
-- the waiting task will become eligible for execution again
-- when the absolute time specified by Timed_Out arrives.
procedure Cond_Signal (Cond : in out Condition_Variable);
pragma Inline (Cond_Signal);
-- Wake up a task waiting on the condition variable object specified
-- by Cond, making it eligible for execution once again.
procedure Set_Priority (T : TCB_Ptr; Prio : System.Any_Priority);
pragma Inline (Set_Priority);
-- Set the priority of the task specified by T to P.
procedure Set_Own_Priority (Prio : System.Any_Priority);
pragma Inline (Set_Own_Priority);
-- Set the priority of the calling task to P.
function Get_Priority (T : TCB_Ptr) return System.Any_Priority;
pragma Inline (Get_Priority);
-- Return the priority of the task specified by T.
function Get_Own_Priority return System.Any_Priority;
pragma Inline (Get_Own_Priority);
-- Return the priority of the calling task.
procedure Create_LL_Task
(Priority : System.Any_Priority;
Stack_Size : Task_Storage_Size;
Task_Info : System.Task_Info.Task_Info_Type;
LL_Entry_Point : LL_Task_Procedure_Access;
Arg : System.Address;
T : TCB_Ptr);
-- Create a new low-level task with priority Priority. A new thread
-- of control is created with a stack size of at least Stack_Size,
-- and the procedure LL_Entry_Point is called with the argument Arg
-- from this new thread of control. The Task Control Block pointed
-- to by T is initialized to refer to this new task.
procedure Exit_LL_Task;
-- Exit a low-level task. The resources allocated for the task
-- by Create_LL_Task are recovered. The task no longer executes, and
-- the effects of further operations on task are unspecified.
procedure Abort_Task (T : TCB_Ptr);
-- Abort the task specified by T (the target task). This causes
-- the target task to asynchronously execute the handler procedure
-- installed by the target task using Install_Abort_Handler. The
-- effect of this operation is unspecified if there is no abort
-- handler procedure for the target task.
procedure Test_Abort;
-- ??? Obsolete? This is intended to allow implementation of
-- abortion and ATC in the absence of an asynchronous Abort_Task,
-- but I think that we decided that GNARL can handle this on
-- its own by making sure that there is an Undefer_Abortion at
-- every abortion synchronization point.
type Abort_Handler_Pointer is access procedure (Context : Pre_Call_State);
procedure Install_Abort_Handler (Handler : Abort_Handler_Pointer);
-- Install an abort handler procedure. This procedure is called
-- asynchronously by the calling task whenever a call to Abort_Task
-- specifies the calling task as the target. If the abort handler
-- procedure is asynchronously executed during a GNULLI operation
-- and then calls some other GNULLI operation, the effect is unspecified.
procedure Install_Error_Handler (Handler : System.Address);
-- Install an error handler for the calling task. The handler will
-- be called synchronously if an error is encountered during the
-- execution of the calling task.
procedure LL_Assert (B : Boolean; M : String);
-- If B is False, print the string M to the console and halt the
-- program.
Task_Wrapper_Frame : constant Integer := 72;
-- This is the size of the frame for the Pthread_Wrapper procedure.
type Proc is access procedure (Addr : System.Address);
-- Test and Set support
type TAS_Cell is private;
-- On some systems we can not assume that an arbitrary memory location
-- can be used in an atomic test and set instruction (e.g. on some
-- multiprocessor machines, only memory regions are cache interlocked).
-- TAS_Cell is private to facilitate adaption to a variety of
-- implementations.
procedure Initialize_TAS_Cell (Cell : out TAS_Cell);
pragma Inline (Initialize_TAS_Cell);
-- Initialize a Test And Set Cell. On some targets this will allocate
-- a system-level lock object from a special pool. For most systems,
-- this is a nop.
procedure Finalize_TAS_Cell (Cell : in out TAS_Cell);
pragma Inline (Finalize_TAS_Cell);
-- Finalize a Test and Set cell, freeing any resources allocated by the
-- corresponding Initialize_TAS_Cell.
procedure Clear (Cell : in out TAS_Cell);
pragma Inline (Clear);
-- Set the state of the named TAS_Cell such that a subsequent call to
-- Is_Set will return False. This operation must be atomic with
-- respect to the Is_Set and Test_And_Set operations for the same
-- cell.
procedure Test_And_Set (Cell : in out TAS_Cell; Result : out Boolean);
pragma Inline (Test_And_Set);
-- Modify the state of the named TAS_Cell such that a subsequent call
-- to Is_Set will return True. Result is set to True if Is_Set
-- was False prior to the call, False otherwise. This operation must
-- be atomic with respect to the Clear and Is_Set operations for the
-- same cell.
function Is_Set (Cell : in TAS_Cell) return Boolean;
pragma Inline (Is_Set);
-- Returns the current value of the named TAS_Cell. This operation
-- must be atomic with respect to the Clear and Test_And_Set operations
-- for the same cell.
private
type Lock is
record
mutex : aliased Interfaces.C.Pthreads.pthread_mutex_t;
end record;
type Condition_Variable is
record
CV : aliased Interfaces.C.Pthreads.pthread_cond_t;
end record;
type TAS_Cell is
record
Value : aliased Interfaces.C.unsigned := 0;
end record;
end System.Task_Primitives;
|
with Ada.Containers.Indefinite_Ordered_Maps;
with Ada.Containers.Indefinite_Holders;
with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants, Ada.Strings.Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
--
--
-- Syntax:
--
-- line = [header] parameter ("," parameter)*
-- header = name ":"
-- parameter = name ["=" value]
-- value = "{" [^}]* "}" | [^{][^,]*
-- name = begin body* (S body+)*
--
generic
type Name_Type (<>) is private;
type Value_Type (<>) is private;
No_Value : Value_Type;
with function "<" (X, Y : Name_Type) return Boolean is <>;
with function To_Name (X : String) return Name_Type;
with function To_Value (X : String) return Value_Type;
package Config_String_Parsers is
-- This type is used to describe the parameters that we expect,
-- if they are mandatory or not and any default value.
type Syntax_Descriptor is private;
Empty_Syntax : constant Syntax_Descriptor;
-- What to do when a mandatory parameter is missing
type Missing_Action is (Die, -- raise Parsing_Error
Ignore, -- OK, the parameter is optional
Use_Default); -- use a default value
-- Add a new parameter to the descriptor. Note that the precondition
-- requires that Default is specified only if If_Missing = Use_Default
procedure Add_Parameter_Syntax (Syntax : in out Syntax_Descriptor;
Parameter_Name : Name_Type;
If_Missing : Missing_Action;
Default : Value_Type := No_Value)
with
Pre => (if Default /= No_Value then If_Missing = Use_Default);
package Parameter_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Name_Type,
Element_Type => Value_Type);
-- This type represents the result of a parsing. It holds the
-- header value (if present) and the parameter list as a map
-- parameter -> value
type Parsing_Result is private;
-- Return true if an header was given
function Has_Header (H : Parsing_Result) return Boolean;
-- Return the name used for the header
function Header (H : Parsing_Result) return Name_Type
with Pre => Has_Header (H);
-- Return the parameter list
function Parameters (H : Parsing_Result) return Parameter_Maps.Map;
-- This type is used to hold several "configuration options" of the
-- parser, for example: the separator after the header, the separator
-- between parameters, etc.
type Parser_Options (<>) is private;
-- Is the header required?
type Header_Expected is
(Yes, -- The header is mandatory
No, -- The header is prohibited
Maybe); -- The header is optional
-- What to do when a parameter not included in the syntax is found?
type Unknown_Name_Action is
(OK, -- accept it
Die, -- raise Parsing_Error
Default); -- Like OK if no syntax is specified, otherwise Die
-- Create a Parser_Options specifier. Note that all parameters are
-- optional, so that only the parameters that need to change need to
-- be specified.
function Config
(Expect_Header : Header_Expected := No;
Name_Start : Character_Set := Letter_Set;
Name_Body : Character_Set := Alphanumeric_Set;
Name_Separators : Character_Set := To_Set ("-_");
Header_Separator : String := ":";
Parameter_Separator : String := ",";
Value_Separator : String := "=";
Open_Block : String := "{";
Close_Block : String := "}")
return Parser_Options;
function Parse
(Input : String;
Syntax : Syntax_Descriptor := Empty_Syntax;
On_Unknown_Name : Unknown_Name_Action := Default;
Options : Parser_Options := Config)
return Parsing_Result;
function Parse
(Input : String;
Syntax : String;
On_Unknown_Name : Unknown_Name_Action := Default;
Options : Parser_Options := Config)
return Parsing_Result
with Pre => False;
pragma Compile_Time_Warning (Standard.True, "Parse version unimplemented");
Parsing_Error : exception;
private
package Value_Holders is
new Ada.Containers.Indefinite_Holders (Value_Type);
package Name_Holders is
new Ada.Containers.Indefinite_Holders (Name_Type);
-- overriding function Copy (X : Parameter_Holder) return Parameter_Holder;
type Parsing_Result is
record
Parameters : Parameter_Maps.Map;
Header : Name_Holders.Holder;
end record;
function Has_Header (H : Parsing_Result) return Boolean
is (not H.Header.Is_Empty);
function Header (H : Parsing_Result) return Name_Type
is (H.Header.Element);
function Parameters (H : Parsing_Result) return Parameter_Maps.Map
is (H.Parameters);
type Parser_Options is
record
Expect_Header : Header_Expected;
Name_Start : Character_Set;
Name_Body : Character_Set;
Name_Separators : Character_Set;
Header_Separator : Unbounded_String;
Parameter_Separator : Unbounded_String;
Value_Separator : Unbounded_String;
Open_Block : Unbounded_String;
Close_Block : Unbounded_String;
end record;
type Syntax_Entry is
record
If_Missing : Missing_Action;
Default : Value_Holders.Holder;
end record;
package Syntax_Maps is
new Ada.Containers.Indefinite_Ordered_Maps (Key_Type => Name_Type,
Element_Type => Syntax_Entry);
type Syntax_Descriptor is
record
S : Syntax_Maps.Map;
end record;
Empty_Syntax : constant Syntax_Descriptor := (S => Syntax_Maps.Empty_Map);
end Config_String_Parsers;
|
-- { dg-do compile }
procedure Protected_Self_Ref2 is
protected type P is
procedure Foo;
end P;
protected body P is
procedure Foo is
D : Integer;
begin
D := P'Digits; -- { dg-error "denotes current instance" }
end;
end P;
begin
null;
end Protected_Self_Ref2;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- P A R . L A B L --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-1998, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
separate (Par)
procedure Labl is
Enclosing_Body_Or_Block : Node_Id;
-- Innermost enclosing body or block statement
Label_Decl_Node : Node_Id;
-- Implicit label declaration node
Defining_Ident_Node : Node_Id;
-- Defining identifier node for implicit label declaration
Next_Label_Elmt : Elmt_Id;
-- Next element on label element list
Label_Node : Node_Id;
-- Next label node to process
function Find_Enclosing_Body_Or_Block (N : Node_Id) return Node_Id;
-- Find the innermost body or block that encloses N.
function Find_Enclosing_Body (N : Node_Id) return Node_Id;
-- Find the innermost body that encloses N.
procedure Check_Distinct_Labels;
-- Checks the rule in RM-5.1(11), which requires distinct identifiers
-- for all the labels in a given body.
---------------------------
-- Check_Distinct_Labels --
---------------------------
procedure Check_Distinct_Labels is
Label_Id : constant Node_Id := Identifier (Label_Node);
Enclosing_Body : constant Node_Id :=
Find_Enclosing_Body (Enclosing_Body_Or_Block);
-- Innermost enclosing body
Next_Other_Label_Elmt : Elmt_Id := First_Elmt (Label_List);
-- Next element on label element list
Other_Label : Node_Id;
-- Next label node to process
begin
-- Loop through all the labels, and if we find some other label
-- (i.e. not Label_Node) that has the same identifier,
-- and whose innermost enclosing body is the same,
-- then we have an error.
-- Note that in the worst case, this is quadratic in the number
-- of labels. However, labels are not all that common, and this
-- is only called for explicit labels.
-- ???Nonetheless, the efficiency could be improved. For example,
-- call Labl for each body, rather than once per compilation.
while Present (Next_Other_Label_Elmt) loop
Other_Label := Node (Next_Other_Label_Elmt);
exit when Label_Node = Other_Label;
if Chars (Label_Id) = Chars (Identifier (Other_Label))
and then Enclosing_Body = Find_Enclosing_Body (Other_Label)
then
Error_Msg_Sloc := Sloc (Other_Label);
Error_Msg_N ("& conflicts with label#", Label_Id);
exit;
end if;
Next_Elmt (Next_Other_Label_Elmt);
end loop;
end Check_Distinct_Labels;
-------------------------
-- Find_Enclosing_Body --
-------------------------
function Find_Enclosing_Body (N : Node_Id) return Node_Id is
Result : Node_Id := N;
begin
-- This is the same as Find_Enclosing_Body_Or_Block, except
-- that we skip block statements and accept statements, instead
-- of stopping at them.
while Present (Result)
and then Nkind (Result) /= N_Entry_Body
and then Nkind (Result) /= N_Task_Body
and then Nkind (Result) /= N_Package_Body
and then Nkind (Result) /= N_Subprogram_Body
loop
Result := Parent (Result);
end loop;
return Result;
end Find_Enclosing_Body;
----------------------------------
-- Find_Enclosing_Body_Or_Block --
----------------------------------
function Find_Enclosing_Body_Or_Block (N : Node_Id) return Node_Id is
Result : Node_Id := Parent (N);
begin
-- Climb up the parent chain until we find a body or block.
while Present (Result)
and then Nkind (Result) /= N_Accept_Statement
and then Nkind (Result) /= N_Entry_Body
and then Nkind (Result) /= N_Task_Body
and then Nkind (Result) /= N_Package_Body
and then Nkind (Result) /= N_Subprogram_Body
and then Nkind (Result) /= N_Block_Statement
loop
Result := Parent (Result);
end loop;
return Result;
end Find_Enclosing_Body_Or_Block;
-- Start of processing for Par.Labl
begin
Next_Label_Elmt := First_Elmt (Label_List);
while Present (Next_Label_Elmt) loop
Label_Node := Node (Next_Label_Elmt);
if not Comes_From_Source (Label_Node) then
goto Next_Label;
end if;
-- Find the innermost enclosing body or block, which is where
-- we need to implicitly declare this label
Enclosing_Body_Or_Block := Find_Enclosing_Body_Or_Block (Label_Node);
-- If we didn't find a parent, then the label in question never got
-- hooked into a reasonable declarative part. This happens only in
-- error situations, and we simply ignore the entry (we aren't going
-- to get into the semantics in any case given the error).
if Present (Enclosing_Body_Or_Block) then
Check_Distinct_Labels;
-- Now create the implicit label declaration node and its
-- corresponding defining identifier. Note that the defining
-- occurrence of a label is the implicit label declaration that
-- we are creating. The label itself is an applied occurrence.
Label_Decl_Node :=
New_Node (N_Implicit_Label_Declaration, Sloc (Label_Node));
Defining_Ident_Node :=
New_Entity (N_Defining_Identifier, Sloc (Identifier (Label_Node)));
Set_Chars (Defining_Ident_Node, Chars (Identifier (Label_Node)));
Set_Defining_Identifier (Label_Decl_Node, Defining_Ident_Node);
Set_Label_Construct (Label_Decl_Node, Label_Node);
-- Now attach the implicit label declaration to the appropriate
-- declarative region, creating a declaration list if none exists
if not Present (Declarations (Enclosing_Body_Or_Block)) then
Set_Declarations (Enclosing_Body_Or_Block, New_List);
end if;
Append (Label_Decl_Node, Declarations (Enclosing_Body_Or_Block));
end if;
<<Next_Label>>
Next_Elmt (Next_Label_Elmt);
end loop;
end Labl;
|
with
any_Math;
package long_Math is new any_Math (Real_t => long_Float);
pragma Pure (long_Math);
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S O C K E T S . T H I N --
-- --
-- S p e c --
-- --
-- Copyright (C) 2001-2020, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides a target dependent thin interface to the sockets
-- layer for use by the GNAT.Sockets package (g-socket.ads). This package
-- should not be directly with'ed by an applications program.
-- This version is for NT
with Interfaces.C;
with GNAT.Sockets.Thin_Common;
with System;
with System.CRTL;
package GNAT.Sockets.Thin is
use Thin_Common;
package C renames Interfaces.C;
function Socket_Errno return Integer;
-- Returns last socket error number
procedure Set_Socket_Errno (Errno : Integer);
-- Set last socket error number
function Socket_Error_Message (Errno : Integer) return String;
-- Returns the error message string for the error number Errno. If Errno is
-- not known, returns "Unknown system error".
function Host_Errno return Integer;
pragma Import (C, Host_Errno, "__gnat_get_h_errno");
-- Returns last host error number
package Host_Error_Messages is
function Host_Error_Message (H_Errno : Integer) return String;
-- Returns the error message string for the host error number H_Errno.
-- If H_Errno is not known, returns "Unknown system error".
end Host_Error_Messages;
--------------------------------
-- Standard library functions --
--------------------------------
function C_Accept
(S : C.int;
Addr : System.Address;
Addrlen : not null access C.int) return C.int;
function C_Bind
(S : C.int;
Name : System.Address;
Namelen : C.int) return C.int;
function C_Close
(Fd : C.int) return C.int;
function C_Connect
(S : C.int;
Name : System.Address;
Namelen : C.int) return C.int;
function C_Gethostname
(Name : System.Address;
Namelen : C.int) return C.int;
function C_Getpeername
(S : C.int;
Name : System.Address;
Namelen : not null access C.int) return C.int;
function C_Getsockname
(S : C.int;
Name : System.Address;
Namelen : not null access C.int) return C.int;
function C_Getsockopt
(S : C.int;
Level : C.int;
Optname : C.int;
Optval : System.Address;
Optlen : not null access C.int) return C.int;
function Socket_Ioctl
(S : C.int;
Req : SOSC.IOCTL_Req_T;
Arg : access C.int) return C.int;
function C_Listen
(S : C.int;
Backlog : C.int) return C.int;
function C_Recv
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int) return C.int;
function C_Recvfrom
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
From : System.Address;
Fromlen : not null access C.int) return C.int;
function C_Recvmsg
(S : C.int;
Msg : System.Address;
Flags : C.int) return System.CRTL.ssize_t;
function C_Select
(Nfds : C.int;
Readfds : access Fd_Set;
Writefds : access Fd_Set;
Exceptfds : access Fd_Set;
Timeout : Timeval_Access) return C.int;
function C_Sendmsg
(S : C.int;
Msg : System.Address;
Flags : C.int) return System.CRTL.ssize_t;
function C_Sendto
(S : C.int;
Msg : System.Address;
Len : C.int;
Flags : C.int;
To : System.Address;
Tolen : C.int) return C.int;
function C_Setsockopt
(S : C.int;
Level : C.int;
Optname : C.int;
Optval : System.Address;
Optlen : C.int) return C.int;
function C_Shutdown
(S : C.int;
How : C.int) return C.int;
function C_Socket
(Domain : C.int;
Typ : C.int;
Protocol : C.int) return C.int;
Default_Socket_Pair_Family : constant := SOSC.AF_INET;
-- Windows has not socketpair system call, and C_Socketpair below is
-- implemented on loopback connected network sockets.
function C_Socketpair
(Domain : C.int;
Typ : C.int;
Protocol : C.int;
Fds : not null access Fd_Pair) return C.int;
-- Creates pair of connected sockets
function C_System
(Command : System.Address) return C.int;
function WSAStartup
(WS_Version : Interfaces.C.unsigned_short;
WSADataAddress : System.Address) return Interfaces.C.int;
-------------------------------------------------------
-- Signalling file descriptors for selector abortion --
-------------------------------------------------------
package Signalling_Fds is
function Create (Fds : not null access Fd_Pair) return C.int;
pragma Convention (C, Create);
-- Create a pair of connected descriptors suitable for use with C_Select
-- (used for signalling in Selector objects).
function Read (Rsig : C.int) return C.int;
pragma Convention (C, Read);
-- Read one byte of data from rsig, the read end of a pair of signalling
-- fds created by Create_Signalling_Fds.
function Write (Wsig : C.int) return C.int;
pragma Convention (C, Write);
-- Write one byte of data to wsig, the write end of a pair of signalling
-- fds created by Create_Signalling_Fds.
procedure Close (Sig : C.int);
pragma Convention (C, Close);
-- Close one end of a pair of signalling fds (ignoring any error)
end Signalling_Fds;
procedure WSACleanup;
procedure Initialize;
procedure Finalize;
private
pragma Import (Stdcall, C_Accept, "accept");
pragma Import (Stdcall, C_Bind, "bind");
pragma Import (Stdcall, C_Close, "closesocket");
pragma Import (Stdcall, C_Gethostname, "gethostname");
pragma Import (Stdcall, C_Getpeername, "getpeername");
pragma Import (Stdcall, C_Getsockname, "getsockname");
pragma Import (Stdcall, C_Getsockopt, "getsockopt");
pragma Import (Stdcall, C_Listen, "listen");
pragma Import (Stdcall, C_Recv, "recv");
pragma Import (Stdcall, C_Recvfrom, "recvfrom");
pragma Import (Stdcall, C_Sendto, "sendto");
pragma Import (Stdcall, C_Setsockopt, "setsockopt");
pragma Import (Stdcall, C_Shutdown, "shutdown");
pragma Import (Stdcall, C_Socket, "socket");
pragma Import (C, C_System, "_system");
pragma Import (Stdcall, Socket_Errno, "WSAGetLastError");
pragma Import (Stdcall, Set_Socket_Errno, "WSASetLastError");
pragma Import (Stdcall, WSAStartup, "WSAStartup");
pragma Import (Stdcall, WSACleanup, "WSACleanup");
end GNAT.Sockets.Thin;
|
pragma Check_Policy (Validate => Disable);
-- with Ada.Strings.Naked_Maps.Debug;
with Ada.UCD.Case_Folding;
with System.Once;
with System.Reference_Counting;
package body Ada.Strings.Naked_Maps.Case_Folding is
use type UCD.Difference_Base;
use type UCD.UCS_4;
procedure Decode (
Mapping : in out Character_Mapping_Data;
I : in out Positive;
Table : UCD.Map_16x1_Type);
procedure Decode (
Mapping : in out Character_Mapping_Data;
I : in out Positive;
Table : UCD.Map_16x1_Type) is
begin
for J in Table'Range loop
declare
F : UCD.Map_16x1_Item_Type renames Table (J);
begin
Mapping.From (I) := Character_Type'Val (F.Code);
Mapping.To (I) := Character_Type'Val (F.Mapping);
end;
I := I + 1;
end loop;
end Decode;
procedure Decode (
Mapping : in out Character_Mapping_Data;
I : in out Positive;
Table : UCD.Case_Folding.Compressed_Type;
Offset : UCD.Difference_Base);
procedure Decode (
Mapping : in out Character_Mapping_Data;
I : in out Positive;
Table : UCD.Case_Folding.Compressed_Type;
Offset : UCD.Difference_Base) is
begin
for J in Table'Range loop
declare
F : UCD.Case_Folding.Compressed_Item_Type renames Table (J);
From : Character_Type :=
Character_Type'Val (UCD.Difference_Base (F.Start) + Offset);
To : Character_Type :=
Character_Type'Val (Character_Type'Pos (From) + F.Diff);
begin
for K in 1 .. F.Length loop
Mapping.From (I) := From;
Mapping.To (I) := To;
From := Character_Type'Succ (From);
To := Character_Type'Succ (To);
I := I + 1;
end loop;
end;
end loop;
end Decode;
type Character_Mapping_Access_With_Pool is access Character_Mapping_Data;
Mapping : Character_Mapping_Access_With_Pool;
Mapping_Flag : aliased System.Once.Flag := 0;
procedure Mapping_Init;
procedure Mapping_Init is
begin
Mapping := new Character_Mapping_Data'(
Length => UCD.Case_Folding.C_Total + UCD.Case_Folding.S_Total,
Reference_Count => System.Reference_Counting.Static,
From => <>,
To => <>);
declare
I : Positive := Mapping.From'First;
begin
-- 16#0041# ..
Decode (
Mapping.all,
I,
UCD.Case_Folding.C_Table_XXXXx1_Compressed,
Offset => 0);
-- 16#00B5# ..
Decode (
Mapping.all,
I,
UCD.Case_Folding.C_Table_XXXXx1);
-- 16#1E9E# ..
Decode (
Mapping.all,
I,
UCD.Case_Folding.S_Table_XXXXx1);
-- 16#1F88# ..
Decode (
Mapping.all,
I,
UCD.Case_Folding.S_Table_XXXXx1_Compressed,
Offset => 0);
-- 16#10400# ..
Decode (
Mapping.all,
I,
UCD.Case_Folding.C_Table_1XXXXx1_Compressed,
Offset => 16#10000#);
pragma Assert (I = Mapping.From'Last + 1);
end;
Sort (Mapping.From, Mapping.To);
pragma Check (Validate, Debug.Valid (Mapping.all));
end Mapping_Init;
-- implementation
function Case_Folding_Map return not null Character_Mapping_Access is
begin
System.Once.Initialize (Mapping_Flag'Access, Mapping_Init'Access);
return Character_Mapping_Access (Mapping);
end Case_Folding_Map;
end Ada.Strings.Naked_Maps.Case_Folding;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016-2017, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Command Line Interface for primitives in Natools.Smaz.Tools. --
------------------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Ada.Command_Line;
with Ada.Containers.Indefinite_Doubly_Linked_Lists;
with Ada.Containers.Indefinite_Holders;
with Ada.Streams;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO.Text_Streams;
with Natools.Getopt_Long;
with Natools.Parallelism;
with Natools.S_Expressions.Parsers;
with Natools.S_Expressions.Printers;
with Natools.Smaz;
with Natools.Smaz.Tools;
with Natools.Smaz_256;
with Natools.Smaz_4096;
with Natools.Smaz_64;
with Natools.Smaz_Generic.Tools;
with Natools.Smaz_Implementations.Base_4096;
with Natools.Smaz_Implementations.Base_64_Tools;
with Natools.Smaz_Tools;
with Natools.Smaz_Tools.GNAT;
with Natools.String_Escapes;
procedure Smaz is
function To_SEA (S : String) return Ada.Streams.Stream_Element_Array
renames Natools.S_Expressions.To_Atom;
package Tools_256 is new Natools.Smaz_256.Tools;
package Tools_4096 is new Natools.Smaz_4096.Tools;
package Tools_64 is new Natools.Smaz_64.Tools;
package Methods renames Natools.Smaz_Tools.Methods;
package Actions is
type Enum is
(Nothing,
Adjust_Dictionary,
Decode,
Encode,
Evaluate);
end Actions;
package Algorithms is
type Enum is
(Base_256,
Base_4096,
Base_64,
Base_256_Retired);
end Algorithms;
package Dict_Sources is
type Enum is
(S_Expression,
Text_List,
Unoptimized_Text_List);
end Dict_Sources;
package Options is
type Id is
(Base_256,
Base_4096,
Base_64,
Output_Ada_Dict,
Check_Roundtrip,
Dictionary_Input,
Decode,
Encode,
Evaluate,
Filter_Threshold,
Output_Hash,
Job_Count,
Help,
Sx_Dict_Output,
Min_Sub_Size,
Max_Sub_Size,
Dict_Size,
Max_Pending,
Base_256_Retired,
Stat_Output,
No_Stat_Output,
Text_List_Input,
Fast_Text_Input,
Max_Word_Size,
Sx_Output,
No_Sx_Output,
Force_Word,
Max_Dict_Size,
Min_Dict_Size,
No_Vlen_Verbatim,
Score_Method,
Vlen_Verbatim);
end Options;
package Getopt is new Natools.Getopt_Long (Options.Id);
type Callback is new Getopt.Handlers.Callback with record
Algorithm : Algorithms.Enum := Algorithms.Base_256;
Display_Help : Boolean := False;
Need_Dictionary : Boolean := False;
Stat_Output : Boolean := False;
Sx_Output : Boolean := False;
Sx_Dict_Output : Boolean := False;
Min_Sub_Size : Positive := 1;
Max_Sub_Size : Positive := 3;
Max_Word_Size : Positive := 10;
Max_Dict_Size : Positive := 254;
Min_Dict_Size : Positive := 254;
Vlen_Verbatim : Boolean := True;
Max_Pending : Ada.Containers.Count_Type
:= Ada.Containers.Count_Type'Last;
Job_Count : Natural := 0;
Filter_Threshold : Natools.Smaz_Tools.String_Count := 0;
Score_Method : Methods.Enum := Methods.Encoded;
Action : Actions.Enum := Actions.Nothing;
Ada_Dictionary : Ada.Strings.Unbounded.Unbounded_String;
Hash_Package : Ada.Strings.Unbounded.Unbounded_String;
Dict_Source : Dict_Sources.Enum := Dict_Sources.S_Expression;
Check_Roundtrip : Boolean := False;
Forced_Words : Natools.Smaz_Tools.String_Lists.List;
end record;
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String);
overriding procedure Argument
(Handler : in out Callback;
Argument : in String)
is null;
function Activate_Dictionary (Dict : in Natools.Smaz_256.Dictionary)
return Natools.Smaz_256.Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz_4096.Dictionary)
return Natools.Smaz_4096.Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz_64.Dictionary)
return Natools.Smaz_64.Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz.Dictionary)
return Natools.Smaz.Dictionary;
-- Update Dictionary.Hash so that it can be actually used
procedure Build_Perfect_Hash
(Word_List : in Natools.Smaz.Tools.String_Lists.List;
Package_Name : in String);
-- Adapter between Smaz_256 generator and retired Smaz types
procedure Convert
(Input : in Natools.Smaz_Tools.String_Lists.List;
Output : out Natools.Smaz.Tools.String_Lists.List);
-- Convert between old and new string lists
function Getopt_Config return Getopt.Configuration;
-- Build the configuration object
function Last_Code (Dict : in Natools.Smaz_256.Dictionary)
return Ada.Streams.Stream_Element
is (Dict.Last_Code);
function Last_Code (Dict : in Natools.Smaz_4096.Dictionary)
return Natools.Smaz_Implementations.Base_4096.Base_4096_Digit
is (Dict.Last_Code);
function Last_Code (Dict : in Natools.Smaz_64.Dictionary)
return Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit
is (Dict.Last_Code);
function Last_Code (Dict : in Natools.Smaz.Dictionary)
return Ada.Streams.Stream_Element
is (Dict.Dict_Last);
-- Return the last valid entry
function Length (Dict : in Natools.Smaz_256.Dictionary) return Positive
is (Dict.Offsets'Length + 1);
function Length (Dict : in Natools.Smaz_4096.Dictionary) return Positive
is (Dict.Offsets'Length + 1);
function Length (Dict : in Natools.Smaz_64.Dictionary) return Positive
is (Dict.Offsets'Length + 1);
function Length (Dict : in Natools.Smaz.Dictionary) return Positive
is (Dict.Offsets'Length);
-- Return the number of entries in Dict
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_256.Dictionary;
Hash_Package_Name : in String := "");
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_4096.Dictionary;
Hash_Package_Name : in String := "");
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_64.Dictionary;
Hash_Package_Name : in String := "");
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "");
-- print the given dictionary in the given file
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type);
-- Print the help text to the given file
generic
type Dictionary (<>) is private;
type Dictionary_Entry is (<>);
type Methods is (<>);
type Score_Value is range <>;
type String_Count is range <>;
type Word_Counter is private;
type Dictionary_Counts is array (Dictionary_Entry) of String_Count;
with package String_Lists
is new Ada.Containers.Indefinite_Doubly_Linked_Lists (String);
with function Activate_Dictionary (Dict : in Dictionary)
return Dictionary is <>;
with procedure Add_Substrings
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
with procedure Add_Words
(Counter : in out Word_Counter;
Phrase : in String;
Min_Size : in Positive;
Max_Size : in Positive);
with function Append_String
(Dict : in Dictionary;
Element : in String)
return Dictionary;
with procedure Build_Perfect_Hash
(Word_List : in String_Lists.List;
Package_Name : in String);
with function Compress
(Dict : in Dictionary;
Input : in String)
return Ada.Streams.Stream_Element_Array;
with function Decompress
(Dict : in Dictionary;
Input : in Ada.Streams.Stream_Element_Array)
return String;
with function Dict_Entry
(Dict : in Dictionary;
Element : in Dictionary_Entry)
return String;
with procedure Evaluate_Dictionary
(Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts);
with procedure Evaluate_Dictionary_Partial
(Dict : in Dictionary;
Corpus_Entry : in String;
Compressed_Size : in out Ada.Streams.Stream_Element_Count;
Counts : in out Dictionary_Counts);
with procedure Filter_By_Count
(Counter : in out Word_Counter;
Threshold_Count : in String_Count);
with function Last_Code (Dict : in Dictionary) return Dictionary_Entry;
with function Length (Dict : in Dictionary) return Positive is <>;
with procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dict : in Dictionary;
Hash_Package_Name : in String := "")
is <>;
with function Remove_Element
(Dict : in Dictionary;
Element : in Dictionary_Entry)
return Dictionary;
with function Replace_Element
(Dict : in Dictionary;
Element : in Dictionary_Entry;
Value : in String)
return Dictionary;
Score_Encoded, Score_Frequency, Score_Gain : in access function
(D : in Dictionary;
C : in Dictionary_Counts;
E : in Dictionary_Entry)
return Score_Value;
with function Simple_Dictionary
(Counter : in Word_Counter;
Word_Count : in Natural;
Method : in Methods)
return String_Lists.List;
with procedure Simple_Dictionary_And_Pending
(Counter : in Word_Counter;
Word_Count : in Natural;
Selected : out String_Lists.List;
Pending : out String_Lists.List;
Method : in Methods;
Max_Pending_Count : in Ada.Containers.Count_Type);
with function To_Dictionary
(List : in String_Lists.List;
Variable_Length_Verbatim : in Boolean)
return Dictionary;
with function Worst_Element
(Dict : in Dictionary;
Counts : in Dictionary_Counts;
Method : in Methods;
First, Last : in Dictionary_Entry)
return Dictionary_Entry;
package Dictionary_Subprograms is
package Holders is new Ada.Containers.Indefinite_Holders (Dictionary);
function Adjust_Dictionary
(Handler : in Callback'Class;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Method : in Methods)
return Dictionary;
-- Adjust the given dictionary according to info in Handle
procedure Evaluate_Dictionary
(Job_Count : in Natural;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts);
-- Dispatch to parallel or non-parallel version of
-- Evaluate_Dictionary depending on Job_Count.
function Image
(Dict : in Dictionary;
Code : in Dictionary_Entry)
return Natools.S_Expressions.Atom;
-- S-expression image of Code
function Is_In_Dict (Dict : Dictionary; Word : String) return Boolean;
-- Return whether Word is in Dict (inefficient)
function Make_Word_Counter
(Handler : in Callback'Class;
Input : in String_Lists.List)
return Word_Counter;
-- Make a word counter from an input word list
procedure Optimization_Round
(Dict : in out Holders.Holder;
Score : in out Ada.Streams.Stream_Element_Count;
Counts : in out Dictionary_Counts;
First : in Dictionary_Entry;
Pending_Words : in out String_Lists.List;
Input_Texts : in String_Lists.List;
Job_Count : in Natural;
Method : in Methods;
Min_Dict_Size : in Positive;
Max_Dict_Size : in Positive;
Updated : out Boolean);
-- Try to improve on Dict by replacing a single entry from it with
-- one of the substring in Pending_Words.
function Optimize_Dictionary
(Base : in Dictionary;
First : in Dictionary_Entry;
Pending_Words : in String_Lists.List;
Input_Texts : in String_Lists.List;
Job_Count : in Natural;
Method : in Methods;
Min_Dict_Size : in Positive;
Max_Dict_Size : in Positive)
return Dictionary;
-- Optimize the dictionary on Input_Texts, starting with Base and
-- adding substrings from Pending_Words. Operates only on words
-- at First and beyond.
procedure Parallel_Evaluate_Dictionary
(Job_Count : in Positive;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts);
-- Return the same results as Natools.Smaz.Tools.Evaluate_Dictionary,
-- but hopefully more quickly, using Job_Count tasks.
procedure Print_Dictionary
(Filename : in String;
Dict : in Dictionary;
Hash_Package_Name : in String := "");
-- print the given dictionary in the given file
procedure Process
(Handler : in Callback'Class;
Word_List : in String_Lists.List;
Data_List : in String_Lists.List;
Method : in Methods);
-- Perform the requested operations
function To_Dictionary
(Handler : in Callback'Class;
Input : in String_Lists.List;
Data_List : in String_Lists.List;
Method : in Methods)
return Dictionary;
-- Convert the input into a dictionary given the option in Handler
end Dictionary_Subprograms;
package body Dictionary_Subprograms is
function Adjust_Dictionary
(Handler : in Callback'Class;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Method : in Methods)
return Dictionary is
begin
if Handler.Forced_Words.Is_Empty or else Corpus.Is_Empty then
return Dict;
end if;
Add_Forced_Words :
declare
Actual_Dict : constant Dictionary := Activate_Dictionary (Dict);
Counts : Dictionary_Counts;
Discarded_Size : Ada.Streams.Stream_Element_Count;
Replacement_Count : String_Count;
Current : Holders.Holder := Holders.To_Holder (Actual_Dict);
begin
Evaluate_Dictionary
(Handler.Job_Count, Actual_Dict, Corpus, Discarded_Size, Counts);
Replacement_Count := Counts (Counts'First);
for I in Counts'Range loop
if Replacement_Count < Counts (I) then
Replacement_Count := Counts (I);
end if;
end loop;
for Word of Handler.Forced_Words loop
if not Is_In_Dict (Actual_Dict, Word) then
declare
Worst_Index : constant Dictionary_Entry
:= Worst_Element
(Actual_Dict, Counts, Method,
Dictionary_Entry'First, Last_Code (Actual_Dict));
New_Dict : constant Dictionary
:= Replace_Element (Current.Element, Worst_Index, Word);
begin
Ada.Text_IO.Put_Line
(Ada.Text_IO.Current_Error,
"Removing"
& Counts (Worst_Index)'Img & "x "
& Natools.String_Escapes.C_Escape_Hex
(Dict_Entry (Actual_Dict, Worst_Index), True)
& " at"
& Worst_Index'Img
& ", replaced by "
& Natools.String_Escapes.C_Escape_Hex (Word, True));
Current := Holders.To_Holder (New_Dict);
Counts (Worst_Index) := Replacement_Count;
end;
end if;
end loop;
return Current.Element;
end Add_Forced_Words;
end Adjust_Dictionary;
procedure Evaluate_Dictionary
(Job_Count : in Natural;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts)
is
Actual_Dict : constant Dictionary := Activate_Dictionary (Dict);
begin
if Job_Count > 0 then
Parallel_Evaluate_Dictionary (Job_Count,
Actual_Dict, Corpus, Compressed_Size, Counts);
else
Evaluate_Dictionary
(Actual_Dict, Corpus, Compressed_Size, Counts);
end if;
end Evaluate_Dictionary;
function Image
(Dict : in Dictionary;
Code : in Dictionary_Entry)
return Natools.S_Expressions.Atom is
begin
return Compress (Dict, Dict_Entry (Dict, Code));
end Image;
function Is_In_Dict (Dict : Dictionary; Word : String) return Boolean is
begin
for Code in Dictionary_Entry'First .. Last_Code (Dict) loop
if Dict_Entry (Dict, Code) = Word then
return True;
end if;
end loop;
return False;
end Is_In_Dict;
function Make_Word_Counter
(Handler : in Callback'Class;
Input : in String_Lists.List)
return Word_Counter
is
use type Natools.Smaz_Tools.String_Count;
Counter : Word_Counter;
begin
for S of Input loop
Add_Substrings
(Counter, S,
Handler.Min_Sub_Size, Handler.Max_Sub_Size);
if Handler.Max_Word_Size > Handler.Max_Sub_Size then
Add_Words
(Counter, S,
Handler.Max_Sub_Size + 1, Handler.Max_Word_Size);
end if;
end loop;
if Handler.Filter_Threshold > 0 then
Filter_By_Count (Counter, String_Count (Handler.Filter_Threshold));
end if;
return Counter;
end Make_Word_Counter;
procedure Optimization_Round
(Dict : in out Holders.Holder;
Score : in out Ada.Streams.Stream_Element_Count;
Counts : in out Dictionary_Counts;
First : in Dictionary_Entry;
Pending_Words : in out String_Lists.List;
Input_Texts : in String_Lists.List;
Job_Count : in Natural;
Method : in Methods;
Min_Dict_Size : in Positive;
Max_Dict_Size : in Positive;
Updated : out Boolean)
is
use type Ada.Streams.Stream_Element_Offset;
No_Longer_Pending : String_Lists.Cursor;
Log_Message : Ada.Strings.Unbounded.Unbounded_String;
Original : constant Dictionary := Dict.Element;
Worst_Index : constant Dictionary_Entry
:= Worst_Element
(Original, Counts, Method, First, Last_Code (Original));
Worst_Value : constant String
:= Dict_Entry (Original, Worst_Index);
Worst_Count : constant String_Count := Counts (Worst_Index);
Worst_Removed : Boolean := False;
Base : constant Dictionary
:= Remove_Element (Original, Worst_Index);
Old_Score : constant Ada.Streams.Stream_Element_Count := Score;
begin
Updated := False;
for Position in Pending_Words.Iterate loop
declare
Word : constant String := String_Lists.Element (Position);
New_Dict : constant Dictionary := Append_String (Base, Word);
New_Score : Ada.Streams.Stream_Element_Count;
New_Counts : Dictionary_Counts;
begin
Evaluate_Dictionary
(Job_Count, New_Dict, Input_Texts, New_Score, New_Counts);
if New_Score < Score then
Dict := Holders.To_Holder (New_Dict);
Score := New_Score;
Counts := New_Counts;
No_Longer_Pending := Position;
Worst_Removed := True;
Updated := True;
Log_Message := Ada.Strings.Unbounded.To_Unbounded_String
("Removing"
& Worst_Count'Img & "x "
& Natools.String_Escapes.C_Escape_Hex (Worst_Value, True)
& ", adding"
& Counts (Last_Code (New_Dict))'Img & "x "
& Natools.String_Escapes.C_Escape_Hex (Word, True)
& ", size"
& Score'Img
& " ("
& Ada.Streams.Stream_Element_Offset'Image
(Score - Old_Score)
& ')');
end if;
end;
end loop;
if Length (Original) < Max_Dict_Size then
for Position in Pending_Words.Iterate loop
declare
Word : constant String := String_Lists.Element (Position);
New_Dict : constant Dictionary
:= Append_String (Original, Word);
New_Score : Ada.Streams.Stream_Element_Count;
New_Counts : Dictionary_Counts;
begin
Evaluate_Dictionary
(Job_Count, New_Dict, Input_Texts, New_Score, New_Counts);
if New_Score < Score then
Dict := Holders.To_Holder (New_Dict);
Score := New_Score;
Counts := New_Counts;
No_Longer_Pending := Position;
Worst_Removed := False;
Updated := True;
Log_Message := Ada.Strings.Unbounded.To_Unbounded_String
("Adding"
& Counts (Last_Code (New_Dict))'Img & "x "
& Natools.String_Escapes.C_Escape_Hex (Word, True)
& ", size"
& Score'Img
& " ("
& Ada.Streams.Stream_Element_Offset'Image
(Score - Old_Score)
& ')');
end if;
end;
end loop;
end if;
if Length (Base) >= Min_Dict_Size then
declare
New_Score : Ada.Streams.Stream_Element_Count;
New_Counts : Dictionary_Counts;
begin
Evaluate_Dictionary
(Job_Count, Base, Input_Texts, New_Score, New_Counts);
if New_Score <= Score then
Dict := Holders.To_Holder (Base);
Score := New_Score;
Counts := New_Counts;
No_Longer_Pending := String_Lists.No_Element;
Worst_Removed := True;
Updated := True;
Log_Message := Ada.Strings.Unbounded.To_Unbounded_String
("Removing"
& Worst_Count'Img & "x "
& Natools.String_Escapes.C_Escape_Hex (Worst_Value, True)
& ", size"
& Score'Img
& " ("
& Ada.Streams.Stream_Element_Offset'Image
(Score - Old_Score)
& ')');
end if;
end;
end if;
if Updated then
if String_Lists.Has_Element (No_Longer_Pending) then
Pending_Words.Delete (No_Longer_Pending);
end if;
if Worst_Removed then
Pending_Words.Append (Worst_Value);
end if;
Ada.Text_IO.Put_Line
(Ada.Text_IO.Current_Error,
Ada.Strings.Unbounded.To_String (Log_Message));
end if;
end Optimization_Round;
function Optimize_Dictionary
(Base : in Dictionary;
First : in Dictionary_Entry;
Pending_Words : in String_Lists.List;
Input_Texts : in String_Lists.List;
Job_Count : in Natural;
Method : in Methods;
Min_Dict_Size : in Positive;
Max_Dict_Size : in Positive)
return Dictionary
is
Holder : Holders.Holder := Holders.To_Holder (Base);
Pending : String_Lists.List := Pending_Words;
Score : Ada.Streams.Stream_Element_Count;
Counts : Dictionary_Counts;
Running : Boolean := True;
begin
Evaluate_Dictionary
(Job_Count, Base, Input_Texts, Score, Counts);
while Running loop
Optimization_Round
(Holder,
Score,
Counts,
First,
Pending,
Input_Texts,
Job_Count,
Method,
Min_Dict_Size,
Max_Dict_Size,
Running);
end loop;
return Holder.Element;
end Optimize_Dictionary;
procedure Parallel_Evaluate_Dictionary
(Job_Count : in Positive;
Dict : in Dictionary;
Corpus : in String_Lists.List;
Compressed_Size : out Ada.Streams.Stream_Element_Count;
Counts : out Dictionary_Counts)
is
type Result_Values is record
Compressed_Size : Ada.Streams.Stream_Element_Count;
Counts : Dictionary_Counts;
end record;
procedure Initialize (Result : in out Result_Values);
procedure Get_Next_Job
(Global : in out String_Lists.Cursor;
Job : out String_Lists.Cursor;
Terminated : out Boolean);
procedure Do_Job
(Result : in out Result_Values;
Job : in String_Lists.Cursor);
procedure Gather_Result
(Global : in out String_Lists.Cursor;
Partial : in Result_Values);
procedure Initialize (Result : in out Result_Values) is
begin
Result := (Compressed_Size => 0,
Counts => (others => 0));
end Initialize;
procedure Get_Next_Job
(Global : in out String_Lists.Cursor;
Job : out String_Lists.Cursor;
Terminated : out Boolean) is
begin
Job := Global;
Terminated := not String_Lists.Has_Element (Global);
if not Terminated then
String_Lists.Next (Global);
end if;
end Get_Next_Job;
procedure Do_Job
(Result : in out Result_Values;
Job : in String_Lists.Cursor) is
begin
Evaluate_Dictionary_Partial
(Dict,
String_Lists.Element (Job),
Result.Compressed_Size,
Result.Counts);
end Do_Job;
procedure Gather_Result
(Global : in out String_Lists.Cursor;
Partial : in Result_Values)
is
pragma Unreferenced (Global);
use type Ada.Streams.Stream_Element_Count;
use type Natools.Smaz_Tools.String_Count;
begin
Compressed_Size := Compressed_Size + Partial.Compressed_Size;
for I in Counts'Range loop
Counts (I) := Counts (I) + Partial.Counts (I);
end loop;
end Gather_Result;
procedure Parallel_Run
is new Natools.Parallelism.Per_Task_Accumulator_Run
(String_Lists.Cursor, Result_Values, String_Lists.Cursor);
Cursor : String_Lists.Cursor := String_Lists.First (Corpus);
begin
Compressed_Size := 0;
Counts := (others => 0);
Parallel_Run (Cursor, Job_Count);
end Parallel_Evaluate_Dictionary;
procedure Print_Dictionary
(Filename : in String;
Dict : in Dictionary;
Hash_Package_Name : in String := "") is
begin
if Filename = "-" then
Print_Dictionary
(Ada.Text_IO.Current_Output, Dict, Hash_Package_Name);
elsif Filename'Length > 0 then
declare
File : Ada.Text_IO.File_Type;
begin
Ada.Text_IO.Create (File, Name => Filename);
Print_Dictionary (File, Dict, Hash_Package_Name);
Ada.Text_IO.Close (File);
end;
end if;
end Print_Dictionary;
procedure Process
(Handler : in Callback'Class;
Word_List : in String_Lists.List;
Data_List : in String_Lists.List;
Method : in Methods)
is
Dict : constant Dictionary := Activate_Dictionary
(To_Dictionary (Handler, Word_List, Data_List, Method));
Sx_Output : Natools.S_Expressions.Printers.Canonical
(Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Output));
Ada_Dictionary : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Ada_Dictionary);
Hash_Package : constant String
:= Ada.Strings.Unbounded.To_String (Handler.Hash_Package);
begin
if Ada_Dictionary'Length > 0 then
Print_Dictionary (Ada_Dictionary, Dict, Hash_Package);
end if;
if Hash_Package'Length > 0 then
Build_Perfect_Hash (Word_List, Hash_Package);
end if;
if Handler.Sx_Dict_Output then
Sx_Output.Open_List;
for I in Dictionary_Entry'First .. Last_Code (Dict) loop
Sx_Output.Append_String (Dict_Entry (Dict, I));
end loop;
Sx_Output.Close_List;
end if;
case Handler.Action is
when Actions.Nothing | Actions.Adjust_Dictionary => null;
when Actions.Decode =>
if Handler.Sx_Output then
Sx_Output.Open_List;
for S of Data_List loop
Sx_Output.Append_String (Decompress (Dict, To_SEA (S)));
end loop;
Sx_Output.Close_List;
end if;
if Handler.Check_Roundtrip then
for S of Data_List loop
declare
use type Ada.Streams.Stream_Element_Array;
Input : constant Ada.Streams.Stream_Element_Array
:= To_SEA (S);
Processed : constant String
:= Decompress (Dict, Input);
Roundtrip : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, Processed);
begin
if Input /= Roundtrip then
Sx_Output.Open_List;
Sx_Output.Append_String
("decompress-roundtrip-failed");
Sx_Output.Append_Atom (Input);
Sx_Output.Append_String (Processed);
Sx_Output.Append_Atom (Roundtrip);
Sx_Output.Close_List;
end if;
end;
end loop;
end if;
if Handler.Stat_Output then
declare
procedure Print_Line (Original, Output : Natural);
procedure Print_Line (Original, Output : Natural) is
begin
Ada.Text_IO.Put_Line
(Natural'Image (Original)
& Ada.Characters.Latin_1.HT
& Natural'Image (Output)
& Ada.Characters.Latin_1.HT
& Float'Image (Float (Original) / Float (Output)));
end Print_Line;
Original_Total : Natural := 0;
Output_Total : Natural := 0;
begin
for S of Data_List loop
declare
Original_Size : constant Natural := S'Length;
Output_Size : constant Natural
:= Decompress (Dict, To_SEA (S))'Length;
begin
Print_Line (Original_Size, Output_Size);
Original_Total := Original_Total + Original_Size;
Output_Total := Output_Total + Output_Size;
end;
end loop;
Print_Line (Original_Total, Output_Total);
end;
end if;
when Actions.Encode =>
if Handler.Sx_Output then
Sx_Output.Open_List;
for S of Data_List loop
Sx_Output.Append_Atom (Compress (Dict, S));
end loop;
Sx_Output.Close_List;
end if;
if Handler.Check_Roundtrip then
for S of Data_List loop
declare
Processed : constant Ada.Streams.Stream_Element_Array
:= Compress (Dict, S);
Roundtrip : constant String
:= Decompress (Dict, Processed);
begin
if S /= Roundtrip then
Sx_Output.Open_List;
Sx_Output.Append_String
("compress-roundtrip-failed");
Sx_Output.Append_String (S);
Sx_Output.Append_Atom (Processed);
Sx_Output.Append_String (Roundtrip);
Sx_Output.Close_List;
end if;
end;
end loop;
end if;
if Handler.Stat_Output then
declare
procedure Print_Line (Original, Output, Base64 : Natural);
procedure Print_Line
(Original, Output, Base64 : in Natural) is
begin
Ada.Text_IO.Put_Line
(Natural'Image (Original)
& Ada.Characters.Latin_1.HT
& Natural'Image (Output)
& Ada.Characters.Latin_1.HT
& Natural'Image (Base64)
& Ada.Characters.Latin_1.HT
& Float'Image (Float (Output) / Float (Original))
& Ada.Characters.Latin_1.HT
& Float'Image (Float (Base64) / Float (Original)));
end Print_Line;
Original_Total : Natural := 0;
Output_Total : Natural := 0;
Base64_Total : Natural := 0;
begin
for S of Data_List loop
declare
Original_Size : constant Natural := S'Length;
Output_Size : constant Natural
:= Compress (Dict, S)'Length;
Base64_Size : constant Natural
:= ((Output_Size + 2) / 3) * 4;
begin
Print_Line
(Original_Size, Output_Size, Base64_Size);
Original_Total := Original_Total + Original_Size;
Output_Total := Output_Total + Output_Size;
Base64_Total := Base64_Total + Base64_Size;
end;
end loop;
Print_Line (Original_Total, Output_Total, Base64_Total);
end;
end if;
when Actions.Evaluate =>
declare
Total_Size : Ada.Streams.Stream_Element_Count;
Counts : Dictionary_Counts;
begin
Evaluate_Dictionary (Handler.Job_Count,
Dict, Data_List, Total_Size, Counts);
if Handler.Sx_Output then
Sx_Output.Open_List;
Sx_Output.Append_String (Ada.Strings.Fixed.Trim
(Ada.Streams.Stream_Element_Count'Image (Total_Size),
Ada.Strings.Both));
for E in Dictionary_Entry'First .. Last_Code (Dict) loop
Sx_Output.Open_List;
Sx_Output.Append_Atom (Image (Dict, E));
Sx_Output.Append_String (Dict_Entry (Dict, E));
Sx_Output.Append_String (Ada.Strings.Fixed.Trim
(String_Count'Image (Counts (E)),
Ada.Strings.Both));
Sx_Output.Close_List;
end loop;
Sx_Output.Close_List;
end if;
if Handler.Stat_Output then
declare
procedure Print
(Label : in String;
E : in Dictionary_Entry;
Score : in Score_Value);
procedure Print_Min_Max
(Label : in String;
Score : not null access function
(D : in Dictionary;
C : in Dictionary_Counts;
E : in Dictionary_Entry)
return Score_Value);
procedure Print_Value
(Label : in String;
Score : not null access function
(D : in Dictionary;
C : in Dictionary_Counts;
E : in Dictionary_Entry)
return Score_Value;
Ref : in Score_Value);
procedure Print
(Label : in String;
E : in Dictionary_Entry;
Score : in Score_Value) is
begin
if Handler.Sx_Output then
Sx_Output.Open_List;
Sx_Output.Append_Atom (Image (Dict, E));
Sx_Output.Append_String (Dict_Entry (Dict, E));
Sx_Output.Append_String (Ada.Strings.Fixed.Trim
(Score'Img, Ada.Strings.Both));
Sx_Output.Close_List;
else
Ada.Text_IO.Put_Line
(Label
& Ada.Characters.Latin_1.HT
& Dictionary_Entry'Image (E)
& Ada.Characters.Latin_1.HT
& Natools.String_Escapes.C_Escape_Hex
(Dict_Entry (Dict, E), True)
& Ada.Characters.Latin_1.HT
& Score'Img);
end if;
end Print;
procedure Print_Min_Max
(Label : in String;
Score : not null access function
(D : in Dictionary;
C : in Dictionary_Counts;
E : in Dictionary_Entry)
return Score_Value)
is
Min_Score, Max_Score : Score_Value
:= Score (Dict, Counts, Dictionary_Entry'First);
S : Score_Value;
begin
for E in Dictionary_Entry'Succ
(Dictionary_Entry'First)
.. Last_Code (Dict)
loop
S := Score (Dict, Counts, E);
if S < Min_Score then
Min_Score := S;
end if;
if S > Max_Score then
Max_Score := S;
end if;
end loop;
Print_Value ("best-" & Label, Score, Max_Score);
Print_Value ("worst-" & Label, Score, Min_Score);
end Print_Min_Max;
procedure Print_Value
(Label : in String;
Score : not null access function
(D : in Dictionary;
C : in Dictionary_Counts;
E : in Dictionary_Entry)
return Score_Value;
Ref : in Score_Value) is
begin
if Handler.Sx_Output then
Sx_Output.Open_List;
Sx_Output.Append_String (Label);
end if;
for E in Dictionary_Entry'First .. Last_Code (Dict)
loop
if Score (Dict, Counts, E) = Ref then
Print (Label, E, Ref);
end if;
end loop;
if Handler.Sx_Output then
Sx_Output.Close_List;
end if;
end Print_Value;
begin
Print_Min_Max ("encoded", Score_Encoded);
Print_Min_Max ("frequency", Score_Frequency);
Print_Min_Max ("gain", Score_Gain);
end;
end if;
end;
end case;
end Process;
function To_Dictionary
(Handler : in Callback'Class;
Input : in String_Lists.List;
Data_List : in String_Lists.List;
Method : in Methods)
return Dictionary is
begin
case Handler.Dict_Source is
when Dict_Sources.S_Expression =>
return Adjust_Dictionary
(Handler,
To_Dictionary (Input, Handler.Vlen_Verbatim),
Data_List,
Method);
when Dict_Sources.Text_List =>
declare
Needed : constant Integer
:= Handler.Max_Dict_Size
- Natural (Handler.Forced_Words.Length);
Selected, Pending : String_Lists.List;
First : Dictionary_Entry := Dictionary_Entry'First;
begin
if Needed <= 0 then
for Word of reverse Handler.Forced_Words loop
Selected.Prepend (Word);
exit when Positive (Selected.Length)
= Handler.Max_Dict_Size;
end loop;
return To_Dictionary (Selected, Handler.Vlen_Verbatim);
end if;
Simple_Dictionary_And_Pending
(Make_Word_Counter (Handler, Input),
Needed,
Selected,
Pending,
Method,
Handler.Max_Pending);
for Word of reverse Handler.Forced_Words loop
Selected.Prepend (Word);
First := Dictionary_Entry'Succ (First);
end loop;
return Optimize_Dictionary
(To_Dictionary (Selected, Handler.Vlen_Verbatim),
First,
Pending,
Input,
Handler.Job_Count,
Method,
Handler.Min_Dict_Size,
Handler.Max_Dict_Size);
end;
when Dict_Sources.Unoptimized_Text_List =>
declare
Needed : constant Integer
:= Handler.Max_Dict_Size
- Natural (Handler.Forced_Words.Length);
All_Words : String_Lists.List;
begin
if Needed > 0 then
All_Words := Simple_Dictionary
(Make_Word_Counter (Handler, Input), Needed, Method);
for Word of reverse Handler.Forced_Words loop
All_Words.Prepend (Word);
end loop;
else
for Word of reverse Handler.Forced_Words loop
All_Words.Prepend (Word);
exit when Positive (All_Words.Length)
>= Handler.Max_Dict_Size;
end loop;
end if;
return To_Dictionary (All_Words, Handler.Vlen_Verbatim);
end;
end case;
end To_Dictionary;
end Dictionary_Subprograms;
package Dict_256 is new Dictionary_Subprograms
(Dictionary => Natools.Smaz_256.Dictionary,
Dictionary_Entry => Ada.Streams.Stream_Element,
Methods => Natools.Smaz_Tools.Methods.Enum,
Score_Value => Natools.Smaz_Tools.Score_Value,
String_Count => Natools.Smaz_Tools.String_Count,
Word_Counter => Natools.Smaz_Tools.Word_Counter,
Dictionary_Counts => Tools_256.Dictionary_Counts,
String_Lists => Natools.Smaz_Tools.String_Lists,
Add_Substrings => Natools.Smaz_Tools.Add_Substrings,
Add_Words => Natools.Smaz_Tools.Add_Words,
Append_String => Tools_256.Append_String,
Build_Perfect_Hash => Natools.Smaz_Tools.GNAT.Build_Perfect_Hash,
Compress => Natools.Smaz_256.Compress,
Decompress => Natools.Smaz_256.Decompress,
Dict_Entry => Natools.Smaz_256.Dict_Entry,
Evaluate_Dictionary => Tools_256.Evaluate_Dictionary,
Evaluate_Dictionary_Partial => Tools_256.Evaluate_Dictionary_Partial,
Filter_By_Count => Natools.Smaz_Tools.Filter_By_Count,
Last_Code => Last_Code,
Remove_Element => Tools_256.Remove_Element,
Replace_Element => Tools_256.Replace_Element,
Score_Encoded => Tools_256.Score_Encoded'Access,
Score_Frequency => Tools_256.Score_Frequency'Access,
Score_Gain => Tools_256.Score_Gain'Access,
Simple_Dictionary => Natools.Smaz_Tools.Simple_Dictionary,
Simple_Dictionary_And_Pending
=> Natools.Smaz_Tools.Simple_Dictionary_And_Pending,
To_Dictionary => Tools_256.To_Dictionary,
Worst_Element => Tools_256.Worst_Index);
package Dict_4096 is new Dictionary_Subprograms
(Dictionary => Natools.Smaz_4096.Dictionary,
Dictionary_Entry
=> Natools.Smaz_Implementations.Base_4096.Base_4096_Digit,
Methods => Natools.Smaz_Tools.Methods.Enum,
Score_Value => Natools.Smaz_Tools.Score_Value,
String_Count => Natools.Smaz_Tools.String_Count,
Word_Counter => Natools.Smaz_Tools.Word_Counter,
Dictionary_Counts => Tools_4096.Dictionary_Counts,
String_Lists => Natools.Smaz_Tools.String_Lists,
Add_Substrings => Natools.Smaz_Tools.Add_Substrings,
Add_Words => Natools.Smaz_Tools.Add_Words,
Append_String => Tools_4096.Append_String,
Build_Perfect_Hash => Natools.Smaz_Tools.GNAT.Build_Perfect_Hash,
Compress => Natools.Smaz_4096.Compress,
Decompress => Natools.Smaz_4096.Decompress,
Dict_Entry => Natools.Smaz_4096.Dict_Entry,
Evaluate_Dictionary => Tools_4096.Evaluate_Dictionary,
Evaluate_Dictionary_Partial => Tools_4096.Evaluate_Dictionary_Partial,
Filter_By_Count => Natools.Smaz_Tools.Filter_By_Count,
Last_Code => Last_Code,
Remove_Element => Tools_4096.Remove_Element,
Replace_Element => Tools_4096.Replace_Element,
Score_Encoded => Tools_4096.Score_Encoded'Access,
Score_Frequency => Tools_4096.Score_Frequency'Access,
Score_Gain => Tools_4096.Score_Gain'Access,
Simple_Dictionary => Natools.Smaz_Tools.Simple_Dictionary,
Simple_Dictionary_And_Pending
=> Natools.Smaz_Tools.Simple_Dictionary_And_Pending,
To_Dictionary => Tools_4096.To_Dictionary,
Worst_Element => Tools_4096.Worst_Index);
package Dict_64 is new Dictionary_Subprograms
(Dictionary => Natools.Smaz_64.Dictionary,
Dictionary_Entry
=> Natools.Smaz_Implementations.Base_64_Tools.Base_64_Digit,
Methods => Natools.Smaz_Tools.Methods.Enum,
Score_Value => Natools.Smaz_Tools.Score_Value,
String_Count => Natools.Smaz_Tools.String_Count,
Word_Counter => Natools.Smaz_Tools.Word_Counter,
Dictionary_Counts => Tools_64.Dictionary_Counts,
String_Lists => Natools.Smaz_Tools.String_Lists,
Add_Substrings => Natools.Smaz_Tools.Add_Substrings,
Add_Words => Natools.Smaz_Tools.Add_Words,
Append_String => Tools_64.Append_String,
Build_Perfect_Hash => Natools.Smaz_Tools.GNAT.Build_Perfect_Hash,
Compress => Natools.Smaz_64.Compress,
Decompress => Natools.Smaz_64.Decompress,
Dict_Entry => Natools.Smaz_64.Dict_Entry,
Evaluate_Dictionary => Tools_64.Evaluate_Dictionary,
Evaluate_Dictionary_Partial => Tools_64.Evaluate_Dictionary_Partial,
Filter_By_Count => Natools.Smaz_Tools.Filter_By_Count,
Last_Code => Last_Code,
Remove_Element => Tools_64.Remove_Element,
Replace_Element => Tools_64.Replace_Element,
Score_Encoded => Tools_64.Score_Encoded'Access,
Score_Frequency => Tools_64.Score_Frequency'Access,
Score_Gain => Tools_64.Score_Gain'Access,
Simple_Dictionary => Natools.Smaz_Tools.Simple_Dictionary,
Simple_Dictionary_And_Pending
=> Natools.Smaz_Tools.Simple_Dictionary_And_Pending,
To_Dictionary => Tools_64.To_Dictionary,
Worst_Element => Tools_64.Worst_Index);
package Dict_Retired is new Dictionary_Subprograms
(Dictionary => Natools.Smaz.Dictionary,
Dictionary_Entry => Ada.Streams.Stream_Element,
Methods => Natools.Smaz.Tools.Methods.Enum,
Score_Value => Natools.Smaz.Tools.Score_Value,
String_Count => Natools.Smaz.Tools.String_Count,
Word_Counter => Natools.Smaz.Tools.Word_Counter,
Dictionary_Counts => Natools.Smaz.Tools.Dictionary_Counts,
String_Lists => Natools.Smaz.Tools.String_Lists,
Add_Substrings => Natools.Smaz.Tools.Add_Substrings,
Add_Words => Natools.Smaz.Tools.Add_Words,
Append_String => Natools.Smaz.Tools.Append_String,
Build_Perfect_Hash => Build_Perfect_Hash,
Compress => Natools.Smaz.Compress,
Decompress => Natools.Smaz.Decompress,
Dict_Entry => Natools.Smaz.Dict_Entry,
Evaluate_Dictionary => Natools.Smaz.Tools.Evaluate_Dictionary,
Evaluate_Dictionary_Partial
=> Natools.Smaz.Tools.Evaluate_Dictionary_Partial,
Filter_By_Count => Natools.Smaz.Tools.Filter_By_Count,
Last_Code => Last_Code,
Remove_Element => Natools.Smaz.Tools.Remove_Element,
Replace_Element => Natools.Smaz.Tools.Replace_Element,
Score_Encoded => Natools.Smaz.Tools.Score_Encoded'Access,
Score_Frequency => Natools.Smaz.Tools.Score_Frequency'Access,
Score_Gain => Natools.Smaz.Tools.Score_Gain'Access,
Simple_Dictionary => Natools.Smaz.Tools.Simple_Dictionary,
Simple_Dictionary_And_Pending
=> Natools.Smaz.Tools.Simple_Dictionary_And_Pending,
To_Dictionary => Natools.Smaz.Tools.To_Dictionary,
Worst_Element => Natools.Smaz.Tools.Worst_Index);
overriding procedure Option
(Handler : in out Callback;
Id : in Options.Id;
Argument : in String) is
begin
case Id is
when Options.Help =>
Handler.Display_Help := True;
when Options.Decode =>
Handler.Need_Dictionary := True;
Handler.Action := Actions.Decode;
when Options.Encode =>
Handler.Need_Dictionary := True;
Handler.Action := Actions.Encode;
when Options.Evaluate =>
Handler.Need_Dictionary := True;
Handler.Action := Actions.Evaluate;
when Options.No_Stat_Output =>
Handler.Stat_Output := False;
when Options.No_Sx_Output =>
Handler.Sx_Output := False;
when Options.Output_Ada_Dict =>
Handler.Need_Dictionary := True;
if Argument'Length > 0 then
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
else
Handler.Ada_Dictionary
:= Ada.Strings.Unbounded.To_Unbounded_String ("-");
end if;
when Options.Output_Hash =>
Handler.Need_Dictionary := True;
Handler.Hash_Package
:= Ada.Strings.Unbounded.To_Unbounded_String (Argument);
when Options.Stat_Output =>
Handler.Stat_Output := True;
when Options.Sx_Output =>
Handler.Sx_Output := True;
when Options.Dictionary_Input =>
Handler.Dict_Source := Dict_Sources.S_Expression;
when Options.Text_List_Input =>
Handler.Dict_Source := Dict_Sources.Text_List;
when Options.Fast_Text_Input =>
Handler.Dict_Source := Dict_Sources.Unoptimized_Text_List;
when Options.Sx_Dict_Output =>
Handler.Need_Dictionary := True;
Handler.Sx_Dict_Output := True;
when Options.Min_Sub_Size =>
Handler.Min_Sub_Size := Positive'Value (Argument);
when Options.Max_Sub_Size =>
Handler.Max_Sub_Size := Positive'Value (Argument);
when Options.Max_Word_Size =>
Handler.Max_Word_Size := Positive'Value (Argument);
when Options.Job_Count =>
Handler.Job_Count := Natural'Value (Argument);
when Options.Filter_Threshold =>
Handler.Filter_Threshold
:= Natools.Smaz_Tools.String_Count'Value (Argument);
when Options.Score_Method =>
Handler.Score_Method := Methods.Enum'Value (Argument);
when Options.Max_Pending =>
Handler.Max_Pending := Ada.Containers.Count_Type'Value (Argument);
when Options.Dict_Size =>
Handler.Min_Dict_Size := Positive'Value (Argument);
Handler.Max_Dict_Size := Positive'Value (Argument);
when Options.Vlen_Verbatim =>
Handler.Vlen_Verbatim := True;
when Options.No_Vlen_Verbatim =>
Handler.Vlen_Verbatim := False;
when Options.Base_256 =>
Handler.Algorithm := Algorithms.Base_256;
when Options.Base_256_Retired =>
Handler.Algorithm := Algorithms.Base_256_Retired;
when Options.Base_64 =>
Handler.Algorithm := Algorithms.Base_64;
when Options.Base_4096 =>
Handler.Algorithm := Algorithms.Base_4096;
when Options.Check_Roundtrip =>
Handler.Check_Roundtrip := True;
when Options.Force_Word =>
if Argument'Length > 0 then
Handler.Need_Dictionary := True;
Handler.Forced_Words.Append (Argument);
if Handler.Action in Actions.Nothing then
Handler.Action := Actions.Adjust_Dictionary;
end if;
end if;
when Options.Max_Dict_Size =>
Handler.Max_Dict_Size := Positive'Value (Argument);
when Options.Min_Dict_Size =>
Handler.Min_Dict_Size := Positive'Value (Argument);
end case;
end Option;
function Activate_Dictionary (Dict : in Natools.Smaz_256.Dictionary)
return Natools.Smaz_256.Dictionary
is
Result : Natools.Smaz_256.Dictionary := Dict;
begin
Natools.Smaz_Tools.Set_Dictionary_For_Trie_Search
(Tools_256.To_String_List (Result));
Result.Hash := Natools.Smaz_Tools.Trie_Search'Access;
pragma Assert (Natools.Smaz_256.Is_Valid (Result));
return Result;
end Activate_Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz_4096.Dictionary)
return Natools.Smaz_4096.Dictionary
is
Result : Natools.Smaz_4096.Dictionary := Dict;
begin
Natools.Smaz_Tools.Set_Dictionary_For_Trie_Search
(Tools_4096.To_String_List (Result));
Result.Hash := Natools.Smaz_Tools.Trie_Search'Access;
pragma Assert (Natools.Smaz_4096.Is_Valid (Result));
return Result;
end Activate_Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz_64.Dictionary)
return Natools.Smaz_64.Dictionary
is
Result : Natools.Smaz_64.Dictionary := Dict;
begin
Natools.Smaz_Tools.Set_Dictionary_For_Trie_Search
(Tools_64.To_String_List (Result));
Result.Hash := Natools.Smaz_Tools.Trie_Search'Access;
pragma Assert (Natools.Smaz_64.Is_Valid (Result));
return Result;
end Activate_Dictionary;
function Activate_Dictionary (Dict : in Natools.Smaz.Dictionary)
return Natools.Smaz.Dictionary
is
Result : Natools.Smaz.Dictionary := Dict;
begin
Natools.Smaz.Tools.Set_Dictionary_For_Trie_Search (Result);
Result.Hash := Natools.Smaz.Tools.Trie_Search'Access;
for I in Result.Offsets'Range loop
if Natools.Smaz.Tools.Trie_Search (Natools.Smaz.Dict_Entry
(Result, I)) /= Natural (I)
then
Ada.Text_IO.Put_Line
(Ada.Text_IO.Current_Error,
"Fail at" & Ada.Streams.Stream_Element'Image (I)
& " -> " & Natools.String_Escapes.C_Escape_Hex
(Natools.Smaz.Dict_Entry (Result, I), True)
& " ->" & Natural'Image (Natools.Smaz.Tools.Trie_Search
(Natools.Smaz.Dict_Entry (Result, I))));
end if;
end loop;
return Result;
end Activate_Dictionary;
procedure Build_Perfect_Hash
(Word_List : in Natools.Smaz.Tools.String_Lists.List;
Package_Name : in String)
is
Other_Word_List : Natools.Smaz_Tools.String_Lists.List;
begin
for S of Word_List loop
Natools.Smaz_Tools.String_Lists.Append (Other_Word_List, S);
end loop;
Natools.Smaz_Tools.GNAT.Build_Perfect_Hash
(Other_Word_List, Package_Name);
end Build_Perfect_Hash;
procedure Convert
(Input : in Natools.Smaz_Tools.String_Lists.List;
Output : out Natools.Smaz.Tools.String_Lists.List) is
begin
Natools.Smaz.Tools.String_Lists.Clear (Output);
for S of Input loop
Natools.Smaz.Tools.String_Lists.Append (Output, S);
end loop;
end Convert;
function Getopt_Config return Getopt.Configuration is
use Getopt;
use Options;
R : Getopt.Configuration;
begin
R.Add_Option ("base-256", '2', No_Argument, Base_256);
R.Add_Option ("base-4096", '4', No_Argument, Base_4096);
R.Add_Option ("base-64", '6', No_Argument, Base_64);
R.Add_Option ("ada-dict", 'A', Optional_Argument, Output_Ada_Dict);
R.Add_Option ("check", 'C', No_Argument, Check_Roundtrip);
R.Add_Option ("decode", 'd', No_Argument, Decode);
R.Add_Option ("dict", 'D', No_Argument, Dictionary_Input);
R.Add_Option ("encode", 'e', No_Argument, Encode);
R.Add_Option ("evaluate", 'E', No_Argument, Evaluate);
R.Add_Option ("filter", 'F', Required_Argument, Filter_Threshold);
R.Add_Option ("help", 'h', No_Argument, Help);
R.Add_Option ("hash-pkg", 'H', Required_Argument, Output_Hash);
R.Add_Option ("jobs", 'j', Required_Argument, Job_Count);
R.Add_Option ("sx-dict", 'L', No_Argument, Sx_Dict_Output);
R.Add_Option ("min-substring", 'm', Required_Argument, Min_Sub_Size);
R.Add_Option ("max-substring", 'M', Required_Argument, Max_Sub_Size);
R.Add_Option ("dict-size", 'n', Required_Argument, Dict_Size);
R.Add_Option ("max-pending", 'N', Required_Argument, Max_Pending);
R.Add_Option ("retired", 'R', No_Argument, Base_256_Retired);
R.Add_Option ("stats", 's', No_Argument, Stat_Output);
R.Add_Option ("no-stats", 'S', No_Argument, No_Stat_Output);
R.Add_Option ("text-list", 't', No_Argument, Text_List_Input);
R.Add_Option ("fast-text-list", 'T', No_Argument, Fast_Text_Input);
R.Add_Option ("max-word-len", 'W', Required_Argument, Max_Word_Size);
R.Add_Option ("s-expr", 'x', No_Argument, Sx_Output);
R.Add_Option ("no-s-expr", 'X', No_Argument, No_Sx_Output);
R.Add_Option ("force-word", Required_Argument, Force_Word);
R.Add_Option ("max-dict-size", Required_Argument, Max_Dict_Size);
R.Add_Option ("min-dict-size", Required_Argument, Min_Dict_Size);
R.Add_Option ("no-vlen-verbatim", No_Argument, No_Vlen_Verbatim);
R.Add_Option ("score-method", Required_Argument, Score_Method);
R.Add_Option ("vlen-verbatim", No_Argument, Vlen_Verbatim);
return R;
end Getopt_Config;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_256.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Tools_256.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_4096.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Tools_4096.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz_64.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Tools_64.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Dictionary
(Output : in Ada.Text_IO.File_Type;
Dictionary : in Natools.Smaz.Dictionary;
Hash_Package_Name : in String := "")
is
procedure Put_Line (Line : in String);
procedure Put_Line (Line : in String) is
begin
Ada.Text_IO.Put_Line (Output, Line);
end Put_Line;
procedure Print_Dictionary_In_Ada is
new Natools.Smaz.Tools.Print_Dictionary_In_Ada (Put_Line);
begin
if Hash_Package_Name'Length > 0 then
Print_Dictionary_In_Ada
(Dictionary,
Hash_Image => Hash_Package_Name & ".Hash'Access");
else
Print_Dictionary_In_Ada (Dictionary);
end if;
end Print_Dictionary;
procedure Print_Help
(Opt : in Getopt.Configuration;
Output : in Ada.Text_IO.File_Type)
is
use Ada.Text_IO;
Indent : constant String := " ";
begin
Put_Line (Output, "Usage:");
for Id in Options.Id loop
Put (Output, Indent & Opt.Format_Names (Id));
case Id is
when Options.Help =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Display this help text");
when Options.Decode =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Read a list of strings and decode them");
when Options.Encode =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Read a list of strings and encode them");
when Options.No_Stat_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Do not output filter statistics");
when Options.No_Sx_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Do not output filtered results in a S-expression");
when Options.Output_Ada_Dict =>
Put_Line (Output, " [filename]");
Put_Line (Output, Indent & Indent
& "Output the current dictionary as Ada code in the given");
Put_Line (Output, Indent & Indent
& "file, or standard output if filename is empty or ""-""");
when Options.Output_Hash =>
Put_Line (Output, " <Hash_Package_Name>");
Put_Line (Output, Indent & Indent
& "Build a package with a perfect hash function for the");
Put_Line (Output, Indent & Indent
& "current dictionary.");
when Options.Stat_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Output filter statistics");
when Options.Sx_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Output filtered results in a S-expression");
when Options.Dictionary_Input =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Read dictionary directly in input S-expression (default)");
when Options.Text_List_Input =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Compute dictionary from sample texts"
& " in input S-expression");
when Options.Fast_Text_Input =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Compute dictionary from sample texts"
& " in input S-expression, without optimization");
when Options.Sx_Dict_Output =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Output the dictionary as a S-expression");
when Options.Min_Sub_Size =>
Put_Line (Output, " <length>");
Put_Line (Output, Indent & Indent
& "Minimum substring size when building a dictionary");
when Options.Max_Sub_Size =>
Put_Line (Output, " <length>");
Put_Line (Output, Indent & Indent
& "Maximum substring size when building a dictionary");
when Options.Max_Word_Size =>
Put_Line (Output, " <length>");
Put_Line (Output, Indent & Indent
& "Maximum word size when building a dictionary");
when Options.Evaluate =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Evaluate the dictionary on the input given corpus");
when Options.Job_Count =>
Put_Line (Output, " <number>");
Put_Line (Output, Indent & Indent
& "Number of parallel jobs in long calculations");
when Options.Filter_Threshold =>
Put_Line (Output, " <threshold>");
Put_Line (Output, Indent & Indent
& "Before building a dictionary from substrings, remove");
Put_Line (Output, Indent & Indent
& "substrings whose count is below the threshold.");
when Options.Score_Method =>
Put_Line (Output, " <method>");
Put_Line (Output, Indent & Indent
& "Select heuristic method to replace dictionary items"
& " during optimization");
when Options.Max_Pending =>
Put_Line (Output, " <count>");
Put_Line (Output, Indent & Indent
& "Maximum size of candidate list"
& " when building a dictionary");
when Options.Dict_Size =>
Put_Line (Output, " <count>");
Put_Line (Output, Indent & Indent
& "Number of words in the dictionary to build");
when Options.Vlen_Verbatim =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Enable variable-length verbatim in built dictionary");
when Options.No_Vlen_Verbatim =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Disable variable-length verbatim in built dictionary");
when Options.Base_256 =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Use base-256 implementation (default)");
when Options.Base_256_Retired =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Use retired base-256 implementation");
when Options.Base_64 =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Use base-64 implementation");
when Options.Base_4096 =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Use base-4096 implementation");
when Options.Check_Roundtrip =>
New_Line (Output);
Put_Line (Output, Indent & Indent
& "Check roundtrip of compression or decompression");
when Options.Force_Word =>
Put_Line (Output, " <word>");
Put_Line (Output, Indent & Indent
& "Force <word> into the dictionary,"
& " replacing the worst entry");
Put_Line (Output, Indent & Indent
& "Can be specified multiple times to force many words.");
when Options.Max_Dict_Size =>
Put_Line (Output, " <count>");
Put_Line (Output, Indent & Indent
& "Maximum number of words in the dictionary to build");
when Options.Min_Dict_Size =>
Put_Line (Output, " <count>");
Put_Line (Output, Indent & Indent
& "Minimum number of words in the dictionary to build");
end case;
end loop;
end Print_Help;
Opt_Config : constant Getopt.Configuration := Getopt_Config;
Handler : Callback;
Input_List, Input_Data : Natools.Smaz_Tools.String_Lists.List;
begin
Process_Command_Line :
begin
Opt_Config.Process (Handler);
exception
when Getopt.Option_Error =>
Print_Help (Opt_Config, Ada.Text_IO.Current_Error);
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end Process_Command_Line;
if Handler.Display_Help then
Print_Help (Opt_Config, Ada.Text_IO.Current_Output);
end if;
if not Handler.Need_Dictionary then
return;
end if;
if not (Handler.Stat_Output or Handler.Sx_Output or Handler.Check_Roundtrip)
then
Handler.Sx_Output := True;
end if;
Read_Input_List :
declare
use type Actions.Enum;
Input : constant access Ada.Streams.Root_Stream_Type'Class
:= Ada.Text_IO.Text_Streams.Stream (Ada.Text_IO.Current_Input);
Parser : Natools.S_Expressions.Parsers.Stream_Parser (Input);
begin
Parser.Next;
Natools.Smaz_Tools.Read_List (Input_List, Parser);
if Handler.Action /= Actions.Nothing then
Parser.Next;
Natools.Smaz_Tools.Read_List (Input_Data, Parser);
end if;
end Read_Input_List;
case Handler.Algorithm is
when Algorithms.Base_256 =>
Dict_256.Process
(Handler, Input_List, Input_Data, Handler.Score_Method);
when Algorithms.Base_64 =>
Dict_64.Process
(Handler, Input_List, Input_Data, Handler.Score_Method);
when Algorithms.Base_4096 =>
Dict_4096.Process
(Handler, Input_List, Input_Data, Handler.Score_Method);
when Algorithms.Base_256_Retired =>
declare
Converted_Input_List : Natools.Smaz.Tools.String_Lists.List;
Converted_Input_Data : Natools.Smaz.Tools.String_Lists.List;
begin
Convert (Input_List, Converted_Input_List);
Convert (Input_Data, Converted_Input_Data);
Dict_Retired.Process
(Handler, Converted_Input_List, Converted_Input_Data,
Natools.Smaz.Tools.Methods.Enum'Val
(Natools.Smaz_Tools.Methods.Enum'Pos (Handler.Score_Method)));
end;
end case;
end Smaz;
|
with gnatcoll.SQL.Postgres; use gnatcoll.SQL.Postgres;
with gnatcoll.SQL.Exec; use gnatcoll.SQL.Exec;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
package Dbase is
-- pragma Pure (Message);
Version : constant String := "0.0.1";
DB : Database_Connection;
DB_Background : Database_Connection;
DB_Damage : Database_Connection;
DB_Torpedo : Database_Connection;
MyLocX : Long_Long_Float := Long_Long_Float(0);
MyLocY : Long_Long_Float := Long_Long_Float(0);
MyLocZ : Long_Long_Float := Long_Long_Float(0);
UserLoggedIn : Boolean := False;
UserLoggedName : Unbounded_String;
UserLoggedFullName : Unbounded_String;
UserLoggedUserId : Unbounded_String;
ShipDestroyed : Boolean := False;
end Dbase;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . G U I . V I E W --
-- --
-- B o d y --
-- --
-- --
-- Copyright (C) 2014 David Botton --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- 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/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- For more information please go to http://www.gnoga.com --
------------------------------------------------------------------------------
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;
with Ada_GUI.Gnoga.Gui.Document;
with Ada_GUI.Gnoga.Gui.Element.Common;
with Ada_GUI.Gnoga.Server.Connection;
with Ada_GUI.Gnoga.Server.Template_Parser.Simple;
package body Ada_GUI.Gnoga.Gui.View is
--------------
-- Finalize --
--------------
overriding
procedure Finalize (Object : in out View_Base_Type) is
begin
if not Gnoga.Server.Connection.Shutting_Down then
for i in
Object.Child_Array.First_Index .. Object.Child_Array.Last_Index
loop
if Object.Child_Array.Element (i).Dynamic then
Object.Child_Array.Element (i).Free;
end if;
end loop;
end if;
Gnoga.Gui.Element.Element_Type (Object).Finalize;
end Finalize;
------------
-- Create --
------------
procedure Create
(View : in out View_Type;
Parent : in out Gnoga.Gui.Base_Type'Class;
ID : in String := "")
is
begin
View.Create_From_HTML (Parent, "<div />", ID);
end Create;
--------------------
-- On_Child_Added --
--------------------
overriding
procedure On_Child_Added (View : in out View_Base_Type;
Child : in out Gnoga.Gui.Base_Type'Class)
is
use Gnoga.Gui.Element;
begin
if Child in Element_Type'Class then
if Element_Type (Child).Auto_Place then
Element_Type (Child).Place_Inside_Bottom_Of (View);
end if;
end if;
if Child.Dynamic then
View.Child_Array.Append (Child'Unchecked_Access);
end if;
end On_Child_Added;
------------------
-- Fill_Parent --
------------------
procedure Fill_Parent (View : in out View_Base_Type) is
use Gnoga.Gui.Element;
begin
View.Position (Absolute);
View.Box_Height ("100%");
View.Box_Width ("100%");
if View.Height = 0 then
View.Position (Relative);
end if;
end Fill_Parent;
--------------
-- Put_Line --
--------------
procedure Put_Line (View : in out View_Base_Type;
Message : in String;
Class : in String := "";
ID : in String := "")
is
D : Gnoga.Gui.Element.Common.DIV_Type;
begin
D.Create (View, Message, ID);
if Class /= "" then
D.Class_Name (Class);
end if;
end Put_Line;
---------
-- Put --
---------
procedure Put (View : in out View_Base_Type;
Message : in String;
Class : in String := "";
ID : in String := "")
is
S : Gnoga.Gui.Element.Common.Span_Type;
begin
S.Create (View, Message, ID);
if Class /= "" then
S.Class_Name (Class);
end if;
end Put;
--------------
-- Put_HTML --
--------------
procedure Put_HTML (View : in out View_Base_Type;
HTML : in String;
Class : in String := "";
ID : in String := "")
is
D : Gnoga.Gui.Element.Element_Type;
begin
D.Create_From_HTML (View, Escape_Quotes (HTML), ID);
if Class /= "" then
D.Class_Name (Class);
end if;
end Put_HTML;
--------------
-- New_Line --
--------------
procedure New_Line (View : in out View_Base_Type) is
begin
View.Put_HTML ("<br />");
end New_Line;
---------------------
-- Horizontal_Rule --
---------------------
procedure Horizontal_Rule (View : in out View_Base_Type) is
begin
View.Put_HTML ("<hr />");
end Horizontal_Rule;
---------------
-- Load_File --
---------------
procedure Load_File (View : in out View_Base_Type;
File_Name : in String;
Class : in String := "";
ID : in String := "")
is
S : constant String :=
Gnoga.Server.Template_Parser.Simple.Load_View (File_Name);
begin
View.Put_Line (S, Class, ID);
end Load_File;
---------------
-- Load_HTML --
---------------
procedure Load_HTML (View : in out View_Base_Type;
File_Name : in String;
Class : in String := "";
ID : in String := "")
is
use Ada.Strings.Fixed;
use Ada.Strings.Maps.Constants;
S : constant String :=
Gnoga.Server.Template_Parser.Simple.Load_View (File_Name);
B : constant Natural := Index (Source => S,
Pattern => "<body",
Mapping => Lower_Case_Map);
T : constant Natural := Index (Source => S,
Pattern => ">",
From => B);
E : constant Natural := Index (Source => S,
Pattern => "</body",
Mapping => Lower_Case_Map);
begin
if B > 0 and E > 0 then
View.Put_HTML (S (T + 1 .. E - 1), Class, ID);
end if;
end Load_HTML;
--------------
-- Load_CSS --
--------------
procedure Load_CSS (View : in out View_Base_Type;
URL : in String)
is
Document : Gnoga.Gui.Document.Document_Type;
begin
Document.Attach (View.Connection_ID);
Document.Head_Element.jQuery_Execute
("append ('" & Escape_Quotes ("<link rel='stylesheet' href='" &
Escape_Inner_Quotes (URL) & "' />") & "')");
end Load_CSS;
-------------------
-- Load_CSS_File --
-------------------
procedure Load_CSS_File (View : in out View_Base_Type;
File_Name : in String)
is
S : constant String :=
Gnoga.Server.Template_Parser.Simple.Load_View (File_Name);
Document : Gnoga.Gui.Document.Document_Type;
begin
Document.Attach (View.Connection_ID);
Document.Head_Element.jQuery_Execute
("append ('<style>" & Escape_Quotes (S) & "</style>'");
end Load_CSS_File;
-----------------
-- Add_Element --
-----------------
procedure Add_Element
(View : in out View_Base_Type;
Name : in String;
Element : Gnoga.Gui.Element.Pointer_To_Element_Class)
is
begin
View.Element_Map.Include (Key => Name,
New_Item => Element);
end Add_Element;
-----------------
-- New_Element --
-----------------
function New_Element
(View : access View_Base_Type;
Name : String;
Element : Gnoga.Gui.Element.Pointer_To_Element_Class)
return Gnoga.Gui.Element.Pointer_To_Element_Class
is
begin
View.Add_Element (Name, Element);
Element.Dynamic;
return Element.all'Unrestricted_Access;
end New_Element;
---------
-- Add --
---------
function Add
(View : access View_Base_Type;
Element : access Gnoga.Gui.Element.Element_Type'Class)
return Gnoga.Gui.Element.Pointer_To_Element_Class
is
pragma Unreferenced (View);
begin
Element.Dynamic;
return Element.all'Unrestricted_Access;
end Add;
-------------
-- Element --
-------------
function Element (View : View_Base_Type; Name : String)
return Gnoga.Gui.Element.Pointer_To_Element_Class
is
begin
if View.Element_Map.Contains (Name) then
return View.Element_Map.Element (Name);
else
return null;
end if;
end Element;
-------------------
-- Element_Names --
-------------------
function Element_Names (View : View_Base_Type)
return Gnoga.Data_Array_Type
is
Names : Gnoga.Data_Array_Type;
procedure Add_Name (C : in Gnoga.Gui.Element.Element_Type_Maps.Cursor);
procedure Add_Name (C : in Gnoga.Gui.Element.Element_Type_Maps.Cursor) is
begin
Names.Append (String'(Gnoga.Gui.Element.Element_Type_Maps.Key (C)));
end Add_Name;
begin
View.Element_Map.Iterate (Add_Name'Access);
return Names;
end Element_Names;
end Ada_GUI.Gnoga.Gui.View;
|
-----------------------------------------------------------------------
-- awa-questions-modules -- Module questions
-- Copyright (C) 2012, 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with ADO;
with Security.Permissions;
with ASF.Applications;
with AWA.Modules;
with AWA.Questions.Models;
package AWA.Questions.Modules is
-- The name under which the module is registered.
NAME : constant String := "questions";
-- Define the permissions.
package ACL_Create_Questions is new Security.Permissions.Definition ("question-create");
package ACL_Delete_Questions is new Security.Permissions.Definition ("question-delete");
package ACL_Update_Questions is new Security.Permissions.Definition ("question-update");
package ACL_Answer_Questions is new Security.Permissions.Definition ("answer-create");
package ACL_Delete_Answer is new Security.Permissions.Definition ("answer-delete");
-- The maximum length for a short description.
SHORT_DESCRIPTION_LENGTH : constant Positive := 200;
-- ------------------------------
-- Module questions
-- ------------------------------
type Question_Module is new AWA.Modules.Module with private;
type Question_Module_Access is access all Question_Module'Class;
-- Initialize the questions module.
overriding
procedure Initialize (Plugin : in out Question_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config);
-- Get the questions module.
function Get_Question_Module return Question_Module_Access;
-- Create or save the question.
procedure Save_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Delete the question.
procedure Delete_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class);
-- Load the question.
procedure Load_Question (Model : in Question_Module;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier;
Found : out Boolean);
-- Create or save the answer.
procedure Save_Answer (Model : in Question_Module;
Question : in AWA.Questions.Models.Question_Ref'Class;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Delete the answer.
procedure Delete_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class);
-- Load the answer.
procedure Load_Answer (Model : in Question_Module;
Answer : in out AWA.Questions.Models.Answer_Ref'Class;
Question : in out AWA.Questions.Models.Question_Ref'Class;
Id : in ADO.Identifier;
Found : out Boolean);
private
type Question_Module is new AWA.Modules.Module with null record;
end AWA.Questions.Modules;
|
--
-- Copyright (C) 2021 Jeremy Grosser <jeremy@synack.me>
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with Graphics;
package Bitmaps is
Width : constant := 8;
Height : constant := 8;
-- All bitmaps are stored as row-major, 2-bit per pixel color value. The
-- actual display color is determined by a lookup from this value into a
-- Graphics.Color_Palette.
type Bitmap is array (1 .. Height, 1 .. Width) of Graphics.Color_Value
with Component_Size => Graphics.Color_Value'Size;
type Any_Bitmap is access all Bitmap;
X : aliased Bitmap
with Import, External_Name => "_binary_x_bin_start";
Blank : aliased Bitmap
with Import, External_Name => "_binary_blank_bin_start";
end Bitmaps;
|
--------------------------------------------------------------------------------
-- Copyright (C) 2020 by Heisenbug Ltd. (gh+owm@heisenbug.eu)
--
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
--------------------------------------------------------------------------------
pragma License (Unrestricted);
--------------------------------------------------------------------------------
--% @summary
--% Open_Weather_Map.City_Ids
--
--% @description
--% Provides the Ada language version of city Ids.
--
-- Please note that this list may change, the actual list can be downloaded
-- from <http://bulk.openwathermap.org/sample/city.list.json.gz>).
--------------------------------------------------------------------------------
package Open_Weather_Map.City_Ids is
package Mexico is
-- Mexico/Guerrero (B. smithii)
Acapulco_de_Juarez : constant City_Id := 3533462;
Chacalapa_Acapulco : constant City_Id := 3531263;
Coyuca_de_Benitez : constant City_Id := 4012608;
Las_Guacamayas : constant City_Id := 4026075;
Tierra_Colorada : constant City_Id := 3515643;
Xaltianguis : constant City_Id := 3514583;
end Mexico;
package India is
-- India (P. Metallica)
Giddalur : constant City_Id := 1271213;
Nandyal : constant City_Id := 1261927;
end India;
end Open_Weather_Map.City_Ids;
|
-- Copyright (c) 2017, Leo Brewin <Leo.Brewin@monash.edu>
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
generic
type Float is digits <>;
n_simp1_max : Integer := 64; -- max. number of legs in the lattice
n_simp2_max : Integer := 1; -- max. number of bones in the lattice
n_loop02_max : Integer := 10; -- max. number of vertices in the loop around a bone
package regge is
subtype Real is Float;
type bone_type is (timelike, spacelike);
type Array1dReal is array (Integer range <>) of Real;
type Array2dReal is array (Integer range <>, Integer range <>) of Real;
type Array1dIntg is array (Integer range <>) of Integer;
function "*" (Left : Integer; Right : Real) return Real;
function "*" (Left : Real; Right : Integer) return Real;
function get_signature
(bone : Integer) return bone_type;
procedure set_metric
(metric : out Array2dReal;
bone : Integer;
index : Integer);
procedure get_defect
(defect : out Real; -- the defect
bone : Integer; -- the bone
n_vertex : Integer); -- the number of vertices that enclose the bone
procedure get_defect_deriv
(deriv : out Real; -- the derivative of the defect
bone : Integer; -- the bone
n_vertex : Integer; -- the number of vertices that enclose the bone
leg_pq : Integer); -- use this leg to compute the derivative
procedure get_defect_and_deriv
(defect : out Real; -- the defect
deriv : out Real; -- the derivative of the defect
bone : Integer; -- the bone
n_vertex : Integer; -- the number of vertices that enclose the bone
leg_pq : Integer); -- use this leg to compute the derivative
bone_signature : bone_type;
n_simp12_max : Integer := 3 + 4*n_loop02_max; -- max. number of legs in the loop around a bone
n_lsq_max : Integer := n_simp1_max; -- max. number of legs in the lattice
n_simp1 : Integer := 0; -- number of legs in the lattice
n_simp2 : Integer := 0; -- number of bones in the lattice
n_loop02 : Array1dIntg (1 .. n_simp2_max); -- number of vertices in the loop around a bone
n_simp12 : Array1dIntg (1 .. n_simp2_max); -- number of legs in the loop around a bone
lsq : Array1dReal (1..n_lsq_max); -- the lsq's of the lattice
simp12 : Array (1 .. n_simp2_max) of Array1dIntg (1 .. n_simp12_max); -- all legs for each bone
end regge;
|
with Ada.Containers; use Ada.Containers;
with Ada.Containers.Formal_Ordered_Maps;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings; use Ada.Strings;
with Ada.Text_IO; use Ada.Text_IO;
with Algebra; use Algebra;
with Bounded_Stack;
with Int64_Parsing; use Int64_Parsing;
package body Assignment_Tree_Branch_Bound with SPARK_Mode is
---------------------------------------------------
-- Types used in the computation of the solution --
---------------------------------------------------
type VehicleAssignmentCost is record
TotalTime : Int64;
Last_TaskOption : TaskOption;
end record
with Predicate => TotalTime >= 0;
package Int64_VehicleAssignmentCost_Maps is new Ada.Containers.Formal_Hashed_Maps
(Key_Type => Int64,
Element_Type => VehicleAssignmentCost,
Hash => Int64_Hash);
use Int64_VehicleAssignmentCost_Maps;
subtype Int64_VAC_Map is Int64_VehicleAssignmentCost_Maps.Map (10, Int64_VehicleAssignmentCost_Maps.Default_Modulus (10));
package Int64_VehicleAssignmentCost_Maps_P renames Int64_VehicleAssignmentCost_Maps.Formal_Model.P;
package Int64_VehicleAssignmentCost_Maps_K renames Int64_VehicleAssignmentCost_Maps.Formal_Model.K;
use Int64_VehicleAssignmentCost_Maps.Formal_Model;
type Assignment_Info is record
Assignment_Sequence : TaskAssignment_Sequence;
Vehicle_Assignments : Int64_VAC_Map;
end record;
package Assignment_Stack is new Bounded_Stack (Assignment_Info);
type Stack is new Assignment_Stack.Stack;
type Children_Arr is array (Positive range <>) of Assignment_Info;
package Int64_Unbounded_String_Maps is new Ada.Containers.Functional_Maps
(Key_Type => Int64,
Element_Type => Unbounded_String);
type Int64_Unbounded_String_Map is new Int64_Unbounded_String_Maps.Map;
-----------------------
-- Local subprograms --
-----------------------
function Children
(Assignment : Assignment_Info;
Algebra : not null access constant Algebra_Tree_Cell;
Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
Assignment_Cost_Matrix : AssignmentCostMatrix)
return Children_Arr
with
Pre =>
Valid_AssignmentCostMatrix (Assignment_Cost_Matrix)
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
Valid_Assignment (Assignment, TaskPlanOptions_Map, Automation_Request)
and then
All_Actions_In_Map (Algebra, TaskPlanOptions_Map)
and then
All_EligibleEntities_In_EntityList (Automation_Request, TaskPlanOptions_Map)
and then
All_Travels_In_CostMatrix (Automation_Request, TaskPlanOptions_Map, Assignment_Cost_Matrix),
Post =>
(for all Child of Children'Result => Valid_Assignment (Child, TaskPlanOptions_Map, Automation_Request));
-- Returns a sequence of Elements corresponding to all the possible
-- assignments considering Assignment.
function Corresponding_TaskOption
(TaskPlanOptions_Map : Int64_TPO_Map;
TaskOptionId : Int64)
return TaskOption
with
Pre =>
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then TaskOptionId in 0 .. 9_999_999_999
and then TaskOptionId_In_Map (TaskOptionId, TaskPlanOptions_Map),
Post =>
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
Corresponding_TaskOption'Result = Option))
and then Corresponding_TaskOption'Result.TaskID = Get_TaskID (TaskOptionId)
and then Corresponding_TaskOption'Result.OptionID = Get_OptionID (TaskOptionId)
and then Get_TaskOptionID (Corresponding_TaskOption'Result.TaskID, Corresponding_TaskOption'Result.OptionID) = TaskOptionId
and then Corresponding_TaskOption'Result.Cost >= 0;
-- Returns the TaskOption corresponding to TaskOptionId in TaskPlanOptions_Map
function Corresponding_TaskOptionCost
(Assignment_Cost_Matrix : AssignmentCostMatrix;
VehicleId : Int64;
DestTaskOption : TaskOption)
return TaskOptionCost
with
Pre =>
Valid_AssignmentCostMatrix (Assignment_Cost_Matrix)
and then Travel_In_CostMatrix (VehicleId, DestTaskOption, Assignment_Cost_Matrix),
Post =>
VehicleId = Corresponding_TaskOptionCost'Result.VehicleID
and then 0 = Corresponding_TaskOptionCost'Result.InitialTaskID
and then 0 = Corresponding_TaskOptionCost'Result.InitialTaskOption
and then DestTaskOption.TaskID = Corresponding_TaskOptionCost'Result.DestinationTaskID
and then DestTaskOption.OptionID = Corresponding_TaskOptionCost'Result.DestinationTaskOption
and then Corresponding_TaskOptionCost'Result.TimeToGo >= 0;
function Corresponding_TaskOptionCost
(Assignment_Cost_Matrix : AssignmentCostMatrix;
VehicleId : Int64;
InitTaskOption, DestTaskOption : TaskOption)
return TaskOptionCost
with
Pre =>
Valid_AssignmentCostMatrix (Assignment_Cost_Matrix)
and then Travel_In_CostMatrix (VehicleId, InitTaskOption, DestTaskOption, Assignment_Cost_Matrix),
Post =>
VehicleId = Corresponding_TaskOptionCost'Result.VehicleID
and then InitTaskOption.TaskID = Corresponding_TaskOptionCost'Result.InitialTaskID
and then InitTaskOption.OptionID = Corresponding_TaskOptionCost'Result.InitialTaskOption
and then DestTaskOption.TaskID = Corresponding_TaskOptionCost'Result.DestinationTaskID
and then DestTaskOption.OptionID = Corresponding_TaskOptionCost'Result.DestinationTaskOption
and then Corresponding_TaskOptionCost'Result.TimeToGo >= 0;
-- Returns the TaskOptionCost corresponding to VehicleId going from
-- InitTaskOptionId to DestTaskOptionId.
function Cost (Assignment : Assignment_Info; Cost_Function : Cost_Function_Kind) return Int64;
-- Returns the cost of an assignment. This function can be expanded to
-- support other cost functions.
procedure Initialize_Algebra
(Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
Algebra : out Algebra_Tree;
Error : out Boolean;
Message : out Unbounded_String)
with Post => (if not Error then Algebra /= null and then All_Actions_In_Map (Algebra, TaskPlanOptions_Map));
-- Returns the algebra tree corresponding to the formulas stored in
-- Automation_Request and the several TaskPlanOptions.
function New_Assignment
(Assignment : Assignment_Info;
VehicleId : Int64;
TaskOpt : TaskOption;
Assignment_Cost_Matrix : AssignmentCostMatrix;
TaskPlanOptions_Map : Int64_TPO_Map;
Automation_Request : UniqueAutomationRequest)
return Assignment_Info
with
Pre =>
Valid_AssignmentCostMatrix (Assignment_Cost_Matrix)
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
Valid_Assignment (Assignment, TaskPlanOptions_Map, Automation_Request)
and then TaskOpt.TaskID in 0 .. 99_999
and then TaskOpt.OptionID in 0 .. 99_999
and then
(for some TOC of Assignment_Cost_Matrix.CostMatrix => TOC.VehicleID = VehicleId)
and then
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(TaskOpt = Option
and then Is_Eligible (Automation_Request, TaskOpt, VehicleId))))
and then
(if Contains (Assignment.Vehicle_Assignments, VehicleId)
then Travel_In_CostMatrix (VehicleId, Element (Assignment.Vehicle_Assignments, VehicleId).Last_TaskOption, TaskOpt, Assignment_Cost_Matrix)
else Travel_In_CostMatrix (VehicleId, TaskOpt, Assignment_Cost_Matrix)),
Post =>
Valid_Assignment (New_Assignment'Result, TaskPlanOptions_Map, Automation_Request);
-- This function returns a new Element. It assigns the TaskOptionId to
-- VehicleId in the enclosing assignment, and computes the new totalTime
-- of VehicleId.
-----------------------
-- Ghost subprograms --
-----------------------
function All_Actions_In_Map
(Algebra : not null access constant Algebra_Tree_Cell;
TaskPlanOptions_Map : Int64_TPO_Map)
return Boolean
with Ghost;
pragma Annotate (GNATprove, Terminating, All_Actions_In_Map);
function TaskOptionId_In_Map
(TaskOptionId : Int64;
TaskPlanOptions_Map : Int64_TPO_Map)
return Boolean
with Ghost, Pre => TaskOptionId in 0 .. 9_999_999_999;
function Valid_Assignment
(Assignment : Assignment_Info;
TaskPlanOptions_Map : Int64_TPO_Map;
Automation_Request : UniqueAutomationRequest)
return Boolean
with Ghost, Pre => Valid_TaskPlanOptions (TaskPlanOptions_Map);
------------------------
-- Useful subprograms --
------------------------
function Contains_Corresponding_TaskOption
(Assignment_Sequence : TaskAssignment_Sequence;
TaskOpt : TaskOption)
return Boolean
is
(for some TaskAssignment of Assignment_Sequence =>
(TaskAssignment.TaskID = TaskOpt.TaskID
and then TaskAssignment.OptionID = TaskOpt.OptionID));
function Has_Corresponding_Option
(Automation_Request : UniqueAutomationRequest;
Options : TaskOption_Seq;
TaskOpt : TaskOption;
EntityId : Int64)
return Boolean
is
(for some Option of Options =>
(Option = TaskOpt
and then
Is_Eligible (Automation_Request, TaskOpt, EntityId)));
function Contains_Corresponding_TaskOption
(Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
TaskOpt : TaskOption;
EntityId : Int64)
return Boolean
is
(for some TaskID of TaskPlanOptions_Map =>
(Has_Corresponding_Option
(Automation_Request,
Get (TaskPlanOptions_Map, TaskID).Options,
TaskOpt,
EntityId)));
procedure Equal_TaskOpt_Lemma
(Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
TaskOpt_1, TaskOpt_2 : TaskOption;
EntityId : Int64)
with
Ghost,
Pre =>
Contains_Corresponding_TaskOption (Automation_Request, TaskPlanOptions_Map, TaskOpt_1, EntityId)
and then TaskOpt_1 = TaskOpt_2,
Post => Contains_Corresponding_TaskOption (Automation_Request, TaskPlanOptions_Map, TaskOpt_2, EntityId);
procedure Equal_TaskOpt_Lemma
(Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
TaskOpt_1, TaskOpt_2 : TaskOption;
EntityId : Int64)
is null;
------------------------
-- All_Actions_In_Map --
------------------------
function All_Actions_In_Map
(Algebra : not null access constant Algebra_Tree_Cell;
TaskPlanOptions_Map : Int64_TPO_Map)
return Boolean
is
(case Algebra.all.Node_Kind is
when Action =>
Algebra.all.TaskOptionId in 0 .. 9_999_999_999
and then
TaskOptionId_In_Map (Algebra.all.TaskOptionId, TaskPlanOptions_Map),
when Operator =>
(for all J in 1 .. Algebra.all.Collection.Num_Children =>
(All_Actions_In_Map (Algebra.all.Collection.Children (J), TaskPlanOptions_Map))),
when Undefined => False);
----------------------------
-- Check_Assignment_Ready --
----------------------------
procedure Check_Assignment_Ready
(Mailbox : in out Assignment_Tree_Branch_Bound_Mailbox;
Data : Assignment_Tree_Branch_Bound_Configuration_Data;
State : in out Assignment_Tree_Branch_Bound_State;
ReqId : Int64)
is
begin
if not Contains (State.m_uniqueAutomationRequests, ReqId)
or else not Contains (State.m_assignmentCostMatrixes, ReqId)
or else not Contains (State.m_taskPlanOptions, ReqId)
or else
(for some TaskId of Element (State.m_uniqueAutomationRequests, ReqId).TaskList =>
not Has_Key (Element (State.m_taskPlanOptions, ReqId), TaskId))
then
return;
end if;
Send_TaskAssignmentSummary (Mailbox, Data, State, ReqId);
end Check_Assignment_Ready;
--------------
-- Children --
--------------
function Children
(Assignment : Assignment_Info;
Algebra : not null access constant Algebra_Tree_Cell;
Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
Assignment_Cost_Matrix : AssignmentCostMatrix)
return Children_Arr
is
procedure Prove_TaskOpt_Different_From_Last_TaskOption
(EntityId : Int64;
TaskOpt : TaskOption)
with
Ghost,
Pre =>
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
Valid_Assignment (Assignment, TaskPlanOptions_Map, Automation_Request)
and then
TaskOpt.TaskID in 0 .. 99_999
and then
TaskOpt.OptionID in 0 .. 99_999
and then
not Contains (To_Sequence_Of_TaskOptionId (Assignment),
TO_Sequences.First,
Last (To_Sequence_Of_TaskOptionId (Assignment)),
Get_TaskOptionID (TaskOpt.TaskID, TaskOpt.OptionID)),
Post =>
(if Contains (Assignment.Vehicle_Assignments, EntityId)
then
(TaskOpt /= Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption
and then
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(Option = Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption
and then
Is_Eligible (Automation_Request,
Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption,
EntityId))))));
procedure Prove_TaskOptionId_In_Map
(ID : Int64;
Alg : not null access constant Algebra_Tree_Cell)
with
Ghost,
Pre => Is_Present (Alg, ID) and then All_Actions_In_Map (Alg, TaskPlanOptions_Map),
Post => ID in 0 .. 9_999_999_999 and then TaskOptionId_In_Map (ID, TaskPlanOptions_Map);
pragma Annotate (GNATprove, Terminating, Prove_TaskOptionId_In_Map);
procedure Prove_Travel_In_CostMatrix
(EntityId : Int64;
TaskOpt : TaskOption)
with
Ghost,
Pre =>
All_Travels_In_CostMatrix (Automation_Request, TaskPlanOptions_Map, Assignment_Cost_Matrix)
and then
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(TaskOpt = Option
and then Is_Eligible (Automation_Request, TaskOpt, EntityId))))
and then
Contains (Automation_Request.EntityList, TO_Sequences.First, Last (Automation_Request.EntityList), EntityId)
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
(if Contains (Assignment.Vehicle_Assignments, EntityId)
then
(TaskOpt /= Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption
and then
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(Option = Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption
and then Is_Eligible (Automation_Request, Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption, EntityId)))))),
Post =>
(if not Contains (Assignment.Vehicle_Assignments, EntityId)
then Travel_In_CostMatrix (EntityId,
TaskOpt,
Assignment_Cost_Matrix)
else Travel_In_CostMatrix (EntityId,
Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption,
TaskOpt,
Assignment_Cost_Matrix));
function To_Sequence_Of_TaskOptionId
(Assignment : Assignment_Info)
return Int64_Seq
with
Pre =>
(for all TaskAssignment of Assignment.Assignment_Sequence =>
(TaskAssignment.TaskID in 0 .. 99_999
and then
TaskAssignment.OptionID in 0 .. 99_999)),
Post =>
(for all TaskAssignment of Assignment.Assignment_Sequence =>
(for some TaskOptionId of To_Sequence_Of_TaskOptionId'Result =>
(Get_TaskOptionID (TaskAssignment.TaskID, TaskAssignment.OptionID) = TaskOptionId)));
--------------------------------------------------
-- Prove_TaskOpt_Different_From_Last_TaskOption --
--------------------------------------------------
procedure Prove_TaskOpt_Different_From_Last_TaskOption
(EntityId : Int64;
TaskOpt : TaskOption)
is
begin
if Contains (Assignment.Vehicle_Assignments, EntityId) then
declare
Last_TaskOption : constant TaskOption := Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption;
begin
pragma Assert
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(Option = Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption
and then
Is_Eligible (Automation_Request, Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption, EntityId))));
pragma Assert
(not Contains (To_Sequence_Of_TaskOptionId (Assignment),
TO_Sequences.First,
Last (To_Sequence_Of_TaskOptionId (Assignment)),
Get_TaskOptionID (TaskOpt.TaskID, TaskOpt.OptionID)));
pragma Assert
(for some TaskAssignment of Assignment.Assignment_Sequence =>
(TaskAssignment.TaskID = Last_TaskOption.TaskID
and then TaskAssignment.OptionID = Last_TaskOption.OptionID
and then Get_TaskOptionID (TaskAssignment.TaskID, TaskAssignment.OptionID)
= Get_TaskOptionID (Last_TaskOption.TaskID, Last_TaskOption.OptionID)));
pragma Assert
(Contains
(To_Sequence_Of_TaskOptionId (Assignment),
TO_Sequences.First,
Last (To_Sequence_Of_TaskOptionId (Assignment)),
Get_TaskOptionID (Last_TaskOption.TaskID, Last_TaskOption.OptionID)));
end;
end if;
end Prove_TaskOpt_Different_From_Last_TaskOption;
-------------------------------
-- Prove_TaskOptionId_In_Map --
-------------------------------
procedure Prove_TaskOptionId_In_Map
(ID : Int64;
Alg : not null access constant Algebra_Tree_Cell) is
begin
case Alg.Node_Kind is
when Action =>
pragma Assert (ID = Alg.TaskOptionId);
pragma Assert (TaskOptionId_In_Map (Alg.all.TaskOptionId, TaskPlanOptions_Map));
pragma Assert (TaskOptionId_In_Map (ID, TaskPlanOptions_Map));
when Operator =>
for J in 1 .. Alg.Collection.Num_Children loop
pragma Loop_Invariant
(for all K in 1 .. J - 1 =>
not Is_Present (Alg.Collection.Children (K), ID));
pragma Loop_Invariant
(for some K in J .. Alg.Collection.Num_Children =>
Is_Present (Alg.Collection.Children (K), ID));
if Is_Present (Alg.Collection.Children (J), ID) then
Prove_TaskOptionId_In_Map (ID, Alg.Collection.Children (J));
exit;
end if;
end loop;
when Undefined =>
raise Program_Error;
end case;
end Prove_TaskOptionId_In_Map;
--------------------------------
-- Prove_Travel_In_CostMatrix --
--------------------------------
procedure Prove_Travel_In_CostMatrix
(EntityId : Int64;
TaskOpt : TaskOption)
is
begin
if not Contains (Assignment.Vehicle_Assignments, EntityId) then
pragma Assert
(for all TaskId of TaskPlanOptions_Map =>
(for all Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(if Is_Eligible (Automation_Request, Option, EntityId)
then Travel_In_CostMatrix (EntityId, Option, Assignment_Cost_Matrix))));
else
declare
Last_Option : constant TaskOption := Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption;
begin
pragma Assert
(for all TaskId of TaskPlanOptions_Map =>
(for all Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(if Is_Eligible (Automation_Request, Option, EntityId)
then
(for all TaskId_2 of TaskPlanOptions_Map =>
(for all Option_2 of Get (TaskPlanOptions_Map, TaskId_2).Options =>
(if Option /= Option_2 and then Is_Eligible (Automation_Request, Option_2, EntityId)
then Travel_In_CostMatrix (EntityId,
Option,
Option_2,
Assignment_Cost_Matrix)))))));
pragma Assert
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(Option = Last_Option
and then Is_Eligible (Automation_Request, Last_Option, EntityId)
and then
(for all TaskId_2 of TaskPlanOptions_Map =>
(for all Option_2 of Get (TaskPlanOptions_Map, TaskId_2).Options =>
(if Option /= Option_2 and then Is_Eligible (Automation_Request, Option_2, EntityId)
then Travel_In_CostMatrix (EntityId,
Option,
Option_2,
Assignment_Cost_Matrix)))))));
pragma Assert
(for all TaskId of TaskPlanOptions_Map =>
(for all Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(if Option /= Last_Option and then Is_Eligible (Automation_Request, Option, EntityId)
then Travel_In_CostMatrix (EntityId,
Last_Option,
Option,
Assignment_Cost_Matrix))));
pragma Assert
(Travel_In_CostMatrix (EntityId, Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption, TaskOpt, Assignment_Cost_Matrix));
end;
end if;
end Prove_Travel_In_CostMatrix;
---------------------------------
-- To_Sequence_Of_TaskOptionId --
---------------------------------
function To_Sequence_Of_TaskOptionId
(Assignment : Assignment_Info)
return Int64_Seq
is
use all type TaskAssignment_Sequence;
Result : Int64_Seq;
begin
for J in TO_Sequences.First .. Last (Assignment.Assignment_Sequence) loop
pragma Assume (Length (Result) < Count_Type'Last);
Result :=
Add (Result,
Get_TaskOptionID
(Get (Assignment.Assignment_Sequence, J).TaskID,
Get (Assignment.Assignment_Sequence, J).OptionID));
pragma Loop_Invariant
(for all K in TO_Sequences.First .. J =>
(for some TaskOptionID of Result =>
(TaskOptionID = Get_TaskOptionID (Get (Assignment.Assignment_Sequence, K).TaskID, Get (Assignment.Assignment_Sequence, K).OptionID))));
end loop;
return Result;
end To_Sequence_Of_TaskOptionId;
Result : Children_Arr (1 .. 500);
Children_Nb : Natural := 0;
Objectives_IDs : constant Int64_Seq :=
Get_Next_Objectives_Ids
(To_Sequence_Of_TaskOptionId (Assignment),
Algebra);
TaskOpt : TaskOption;
-- List of TaskOptionIds to be assigned for the next iteration
begin
for Objective_ID of Objectives_IDs loop
Prove_TaskOptionId_In_Map (Objective_ID, Algebra);
pragma Assert (TaskOptionId_In_Map (Objective_ID, TaskPlanOptions_Map));
TaskOpt := Corresponding_TaskOption (TaskPlanOptions_Map, Objective_ID);
-- We add a new Assignment to Result for each eligible entity
-- for Objective_Id.
for EntityId of TaskOpt.EligibleEntities loop
pragma Assume (Children_Nb < 500);
Children_Nb := Children_Nb + 1;
Prove_TaskOpt_Different_From_Last_TaskOption (EntityId, TaskOpt);
Prove_Travel_In_CostMatrix (EntityId, TaskOpt);
Result (Children_Nb) := New_Assignment (Assignment, EntityId, TaskOpt, Assignment_Cost_Matrix, TaskPlanOptions_Map, Automation_Request);
pragma Loop_Invariant (Children_Nb <= 500);
pragma Loop_Invariant (for all J in 1 .. Children_Nb => Valid_Assignment (Result (J), TaskPlanOptions_Map, Automation_Request));
end loop;
pragma Loop_Invariant (Children_Nb <= 500);
pragma Loop_Invariant (for all J in 1 .. Children_Nb => Valid_Assignment (Result (J), TaskPlanOptions_Map, Automation_Request));
end loop;
return Result (1 .. Children_Nb);
end Children;
------------------------------
-- Corresponding_TaskOption --
------------------------------
function Corresponding_TaskOption
(TaskPlanOptions_Map : Int64_TPO_Map;
TaskOptionId : Int64)
return TaskOption
is
TaskId : constant Int64 := Get_TaskID (TaskOptionId);
OptionId : constant Int64 := Get_OptionID (TaskOptionId);
Associated_TPO : constant TaskPlanOptions := Get (TaskPlanOptions_Map, TaskId);
begin
for Pos in TO_Sequences.First .. Last (Associated_TPO.Options) loop
if Get (Associated_TPO.Options, Pos).OptionID = OptionId then
return Get (Associated_TPO.Options, Pos);
end if;
pragma Loop_Invariant
(for all J in TO_Sequences.First .. Pos => Get (Associated_TPO.Options, J).OptionID /= OptionId);
end loop;
raise Program_Error;
end Corresponding_TaskOption;
----------------------------------
-- Corresponding_TaskOptionCost --
----------------------------------
function Corresponding_TaskOptionCost
(Assignment_Cost_Matrix : AssignmentCostMatrix;
VehicleId : Int64;
DestTaskOption : TaskOption)
return TaskOptionCost
is
begin
for Pos in TOC_Sequences.First .. Last (Assignment_Cost_Matrix.CostMatrix) loop
pragma Loop_Invariant
(for all J in TOC_Sequences.First .. Pos - 1 =>
(VehicleId /= Get (Assignment_Cost_Matrix.CostMatrix, J).VehicleID
or else 0 /= Get (Assignment_Cost_Matrix.CostMatrix, J).InitialTaskID
or else 0 /= Get (Assignment_Cost_Matrix.CostMatrix, J).InitialTaskOption
or else DestTaskOption.TaskID /= Get (Assignment_Cost_Matrix.CostMatrix, J).DestinationTaskID
or else DestTaskOption.OptionID /= Get (Assignment_Cost_Matrix.CostMatrix, J).DestinationTaskOption));
declare
TOC : constant TaskOptionCost := Get (Assignment_Cost_Matrix.CostMatrix, Pos);
begin
if
VehicleId = TOC.VehicleID
and then 0 = TOC.InitialTaskID
and then 0 = TOC.InitialTaskOption
and then DestTaskOption.TaskID = TOC.DestinationTaskID
and then DestTaskOption.OptionID = TOC.DestinationTaskOption
then
return TOC;
end if;
end;
end loop;
raise Program_Error;
end Corresponding_TaskOptionCost;
----------------------------------
-- Corresponding_TaskOptionCost --
----------------------------------
function Corresponding_TaskOptionCost
(Assignment_Cost_Matrix : AssignmentCostMatrix;
VehicleId : Int64;
InitTaskOption, DestTaskOption : TaskOption)
return TaskOptionCost
is
begin
for Pos in TOC_Sequences.First .. Last (Assignment_Cost_Matrix.CostMatrix) loop
pragma Loop_Invariant
(for all J in TOC_Sequences.First .. Pos - 1 =>
(VehicleId /= Get (Assignment_Cost_Matrix.CostMatrix, J).VehicleID
or else InitTaskOption.TaskID /= Get (Assignment_Cost_Matrix.CostMatrix, J).InitialTaskID
or else InitTaskOption.OptionID /= Get (Assignment_Cost_Matrix.CostMatrix, J).InitialTaskOption
or else DestTaskOption.TaskID /= Get (Assignment_Cost_Matrix.CostMatrix, J).DestinationTaskID
or else DestTaskOption.OptionID /= Get (Assignment_Cost_Matrix.CostMatrix, J).DestinationTaskOption));
declare
TOC : constant TaskOptionCost := Get (Assignment_Cost_Matrix.CostMatrix, Pos);
begin
if
VehicleId = TOC.VehicleID
and then InitTaskOption.TaskID = TOC.InitialTaskID
and then InitTaskOption.OptionID = TOC.InitialTaskOption
and then DestTaskOption.TaskID = TOC.DestinationTaskID
and then DestTaskOption.OptionID = TOC.DestinationTaskOption
then
return TOC;
end if;
end;
end loop;
raise Program_Error;
end Corresponding_TaskOptionCost;
----------
-- Cost --
----------
function Cost (Assignment : Assignment_Info; Cost_Function : Cost_Function_Kind) return Int64 is
Result : Int64 := 0;
begin
case Cost_Function is
when Minmax =>
for VehicleID of Assignment.Vehicle_Assignments loop
declare
TotalTime : constant Int64 := Element (Assignment.Vehicle_Assignments, VehicleID).TotalTime;
begin
if TotalTime > Result then
Result := TotalTime;
end if;
end;
end loop;
when Cumulative =>
for VehicleId of Assignment.Vehicle_Assignments loop
pragma Assume (Result < Int64'Last - Element (Assignment.Vehicle_Assignments, VehicleId).TotalTime);
Result := Result + Element (Assignment.Vehicle_Assignments, VehicleId).TotalTime;
end loop;
end case;
return Result;
end Cost;
-----------------------------------
-- Handle_Assignment_Cost_Matrix --
-----------------------------------
procedure Handle_Assignment_Cost_Matrix
(Mailbox : in out Assignment_Tree_Branch_Bound_Mailbox;
Data : Assignment_Tree_Branch_Bound_Configuration_Data;
State : in out Assignment_Tree_Branch_Bound_State;
Matrix : AssignmentCostMatrix)
is
Old_AssignmentCostMatrixes : constant Int64_AssignmentCostMatrix_Map := State.m_assignmentCostMatrixes with Ghost;
procedure Insert
(assignmentCostMatrixes : in out Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all ReqId of assignmentCostMatrixes =>
(Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, ReqId))
and then
Contains (uniqueAutomationRequests, ReqId)
and then
Contains (taskPlanOptions, ReqId)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId),
Element (assignmentCostMatrixes, ReqId))))
and then
not Contains (assignmentCostMatrixes, Matrix.CorrespondingAutomationRequestID)
and then Valid_AssignmentCostMatrix (Matrix)
and then Contains (uniqueAutomationRequests, Matrix.CorrespondingAutomationRequestID)
and then Contains (taskPlanOptions, Matrix.CorrespondingAutomationRequestID)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Matrix.CorrespondingAutomationRequestID),
Element (taskPlanOptions, Matrix.CorrespondingAutomationRequestID),
Matrix),
Post =>
(for all ReqId of assignmentCostMatrixes =>
(Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, ReqId))
and then
Contains (uniqueAutomationRequests, ReqId)
and then
Contains (taskPlanOptions, ReqId)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId),
Element (assignmentCostMatrixes, ReqId))));
------------
-- Insert --
------------
procedure Insert
(assignmentCostMatrixes : in out Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
begin
Insert (assignmentCostMatrixes, Matrix.CorrespondingAutomationRequestID, Matrix);
end Insert;
begin
Insert (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
Check_Assignment_Ready (Mailbox, Data, State, Matrix.CorrespondingAutomationRequestID);
end Handle_Assignment_Cost_Matrix;
------------------------------
-- Handle_Task_Plan_Options --
------------------------------
procedure Handle_Task_Plan_Options
(Mailbox : in out Assignment_Tree_Branch_Bound_Mailbox;
Data : Assignment_Tree_Branch_Bound_Configuration_Data;
State : in out Assignment_Tree_Branch_Bound_State;
Options : TaskPlanOptions)
is
ReqId : constant Int64 := Options.CorrespondingAutomationRequestID;
procedure Add_TaskPlanOption
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
Contains (taskPlanOptions, ReqId)
and then
not Has_Key (Element (taskPlanOptions, ReqId), Options.TaskID)
and then
(for all TaskOption of Options.Options =>
(TaskOption.Cost >= 0
and then Options.TaskID = TaskOption.TaskID)),
Post =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)));
procedure Insert_Empty_TPO_Map
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
not Contains (taskPlanOptions, ReqId)
and then
Contains (uniqueAutomationRequests, ReqId)
and then
(for all Option of Options.Options =>
(for all EntityId of Option.EligibleEntities =>
Contains (Element (uniqueAutomationRequests, ReqId).EntityList,
TO_Sequences.First,
Last (Element (uniqueAutomationRequests, ReqId).EntityList),
EntityId))),
Post =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
Contains (taskPlanOptions, ReqId)
and then
not Has_Key (Element (taskPlanOptions, ReqId), Options.TaskID);
------------------------
-- Add_TaskPlanOption --
------------------------
procedure Add_TaskPlanOption
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
New_Int64_TPO_Map : Int64_TPO_Map;
begin
New_Int64_TPO_Map := Add (Element (taskPlanOptions, ReqId), Options.TaskID, Options);
Replace
(taskPlanOptions,
ReqId,
New_Int64_TPO_Map);
end Add_TaskPlanOption;
--------------------------
-- Insert_Empty_TPO_Map --
--------------------------
procedure Insert_Empty_TPO_Map
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
Empty_Int64_TPO_Map : Int64_TPO_Map;
begin
Insert (taskPlanOptions, ReqId, Empty_Int64_TPO_Map);
end Insert_Empty_TPO_Map;
begin
if not Contains (State.m_taskPlanOptions, ReqId) then
Insert_Empty_TPO_Map (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
end if;
Add_TaskPlanOption (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
Check_Assignment_Ready (Mailbox, Data, State, Options.CorrespondingAutomationRequestID);
end Handle_Task_Plan_Options;
--------------------------------------
-- Handle_Unique_Automation_Request --
--------------------------------------
procedure Handle_Unique_Automation_Request
(Mailbox : in out Assignment_Tree_Branch_Bound_Mailbox;
Data : Assignment_Tree_Branch_Bound_Configuration_Data;
State : in out Assignment_Tree_Branch_Bound_State;
Areq : UniqueAutomationRequest)
is
procedure Insert
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : in out Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all ReqId of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, ReqId))
and then Contains (uniqueAutomationRequests, ReqId)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId))))
and then
(for all ReqId of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, ReqId))
and then Contains (uniqueAutomationRequests, ReqId)
and then Contains (taskPlanOptions, ReqId)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId),
Element (assignmentCostMatrixes, ReqId)))
and then
not Contains (uniqueAutomationRequests, Areq.RequestID)
and then
not Contains (assignmentCostMatrixes, Areq.RequestID),
Post =>
(for all ReqId of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, ReqId))
and then Contains (uniqueAutomationRequests, ReqId)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId))))
and then
(for all ReqId of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, ReqId))
and then Contains (uniqueAutomationRequests, ReqId)
and then Contains (taskPlanOptions, ReqId)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, ReqId),
Element (taskPlanOptions, ReqId),
Element (assignmentCostMatrixes, ReqId)));
------------
-- Insert --
------------
procedure Insert
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : in out Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
begin
Insert (uniqueAutomationRequests, Areq.RequestID, Areq);
end Insert;
begin
Insert (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
Check_Assignment_Ready (Mailbox, Data, State, Areq.RequestID);
end Handle_Unique_Automation_Request;
------------------------
-- Initialize_Algebra --
------------------------
procedure Initialize_Algebra
(Automation_Request : UniqueAutomationRequest;
TaskPlanOptions_Map : Int64_TPO_Map;
Algebra : out Algebra_Tree;
Error : out Boolean;
Message : out Unbounded_String)
is
package Unb renames Common.Unbounded_Strings_Subprograms;
taskIdVsAlgebraString : Int64_Unbounded_String_Map;
algebraString : Unbounded_String := To_Unbounded_String ("");
begin
Algebra := null;
Message := Null_Unbounded_String;
Error := False;
for taskId of TaskPlanOptions_Map loop
if taskId not in 0 .. 99_999 then
Append_To_Msg (Message, "TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " should be in range 0 .. 99_999.");
Error := True;
return;
end if;
declare
compositionString : Unbounded_String :=
Get (TaskPlanOptions_Map, taskId).Composition;
algebraCompositionTaskOptionId : Unbounded_String :=
Unb.To_Unbounded_String ("");
isFinished : Boolean := False;
begin
if Length (compositionString) = Natural'Last then
Append_To_Msg (Message, "Composition string of TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " is too long.");
Error := True;
return;
end if;
while not isFinished loop
pragma Loop_Invariant (Length (compositionString) < Natural'Last);
if Length (compositionString) > 0 then
declare
position : Natural := Unb.Index (compositionString, "p");
begin
if position > 0 then
if Length (algebraCompositionTaskOptionId) >= Natural'Last - position then
Append_To_Msg (Message, "Composition string of TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " is too long.");
Error := True;
return;
end if;
algebraCompositionTaskOptionId :=
algebraCompositionTaskOptionId
& Unb.Slice (compositionString, 1, position);
declare
positionAfterId : Natural;
positionSpace : constant Natural :=
Unb.Index (compositionString, " ", position);
positionParen : constant Natural :=
Unb.Index (compositionString, ")", position);
begin
if positionSpace = 0 and then positionParen = 0 then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Unb.Slice (compositionString, position, Length (compositionString)));
Append_To_Msg (Message, '"' & ": optionID after character 'p' should be followed by character ' ' or ')'.");
Error := True;
return;
elsif positionSpace /= 0 and then positionParen /= 0 then
positionAfterId := Natural'Min (positionSpace, positionParen);
else
positionAfterId := Natural'Max (positionSpace, positionParen);
end if;
if positionAfterId - 1 < position + 1 then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Unb.Slice (compositionString, position, Length (compositionString)));
Append_To_Msg (Message, '"' & ": character 'p' should be followed by an optionID.");
Error := True;
return;
end if;
declare
optionId, taskOptionId : Int64;
Parsing_Error : Boolean;
begin
Parse_Int64 (Unb.Slice (compositionString, position + 1, positionAfterId - 1), optionId, Parsing_Error);
if Parsing_Error then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Unb.Slice (compositionString, position + 1, positionAfterId - 1));
Append_To_Msg (Message, '"' & ": does not correspond to an Int64.");
Error := True;
return;
end if;
if optionId not in 0 .. 99_999 then
Append_To_Msg (Message, "OptionID ");
Append_To_Msg (Message, Print_Int64 (optionId));
Append_To_Msg (Message, " should be in range 0 .. 99_999.");
Error := True;
return;
end if;
taskOptionId := Get_TaskOptionID (taskId, optionId);
declare
Image : String := Print_Int64 (taskOptionId);
begin
if Length (algebraCompositionTaskOptionId) >= Natural'Last - Image'Length then
Append_To_Msg (Message, "Composition string of TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " is too long.");
Error := True;
return;
end if;
algebraCompositionTaskOptionId :=
algebraCompositionTaskOptionId & Image;
end;
Delete (compositionString, 1, positionAfterId - 1);
end;
end;
else
algebraCompositionTaskOptionId :=
algebraCompositionTaskOptionId & compositionString;
taskIdVsAlgebraString :=
Add (taskIdVsAlgebraString, taskId, algebraCompositionTaskOptionId);
isFinished := True;
end if;
end;
else
isFinished := True;
end if;
end loop;
end;
end loop;
if Length (Automation_Request.TaskRelationships) > 0 then
declare
isFinished : Boolean := False;
TaskRelationships : Unbounded_String := Automation_Request.TaskRelationships;
begin
if Length (TaskRelationships) = Natural'Last then
Append_To_Msg (Message, "TaskRelationships string is too long.");
Error := True;
return;
end if;
while not isFinished loop
pragma Loop_Invariant (Length (TaskRelationships) < Natural'Last);
if Length (TaskRelationships) > 0 then
declare
position : Natural := Unb.Index (TaskRelationships, "p");
begin
if position > 0 then
if Length (algebraString) >= Natural'Last - position + 1 then
Append_To_Msg (Message, "Algebra string is too long.");
Error := True;
return;
end if;
algebraString :=
algebraString &
Unb.Slice (TaskRelationships, 1, position - 1);
declare
positionAfterId : Natural;
positionSpace : constant Natural :=
Unb.Index (TaskRelationships, " ", position);
positionParen : constant Natural :=
Unb.Index (TaskRelationships, ")", position);
begin
if positionSpace = 0 and then positionParen = 0 then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Slice (TaskRelationships, position, Length (TaskRelationships)));
Append_To_Msg (Message, '"' & ": taskID after character 'p' should be followed by character ' ' or ')'.");
Error := True;
return;
elsif positionSpace /= 0 and then positionParen /= 0 then
positionAfterId := Natural'Min (positionSpace, positionParen);
else
positionAfterId := Natural'Max (positionSpace, positionParen);
end if;
if positionAfterId - 1 < position + 1 then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Unb.Slice (TaskRelationships, position, Length (TaskRelationships)));
Append_To_Msg (Message, '"' & ": character 'p' should be followed by an optionID.");
Error := True;
return;
end if;
declare
taskId : Int64;
Parsing_Error : Boolean;
begin
Parse_Int64 (Unb.Slice (TaskRelationships, position + 1, positionAfterId - 1), taskId, Parsing_Error);
if Parsing_Error then
Append_To_Msg (Message, "Substring " & '"');
Append_To_Msg (Message, Unb.Slice (TaskRelationships, position + 1, positionAfterId - 1));
Append_To_Msg (Message, '"' & ": does not correspond to an Int64.");
Error := True;
return;
end if;
if taskId not in 0 .. 99_999 then
Append_To_Msg (Message, "TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " should be in range 0 .. 99_999.");
Error := True;
return;
end if;
if Has_Key (taskIdVsAlgebraString, taskId) then
if Length (algebraString) > Natural'Last - Length (Get (taskIdVsAlgebraString, taskId)) then
Append_To_Msg (Message, "Algebra string is too long.");
Error := True;
return;
end if;
algebraString :=
algebraString & Get (taskIdVsAlgebraString, taskId);
else
Append_To_Msg (Message, "TaskID ");
Append_To_Msg (Message, Print_Int64 (taskId));
Append_To_Msg (Message, " does not exist.");
Error := True;
return;
end if;
Delete (TaskRelationships, 1, positionAfterId - 1);
end;
end;
else
algebraString := algebraString & TaskRelationships;
isFinished := True;
end if;
end;
else
isFinished := True;
end if;
end loop;
end;
else
algebraString := algebraString & "|(";
for taskID of taskIdVsAlgebraString loop
if Length (algebraString) >= Natural'Last - 1 - Length (Get (taskIdVsAlgebraString, taskID)) then
Append_To_Msg (Message, "Algebra string is too long.");
Error := True;
return;
end if;
algebraString :=
algebraString
& Get (taskIdVsAlgebraString, taskID)
& " ";
end loop;
algebraString := algebraString & ")";
pragma Assert (Length (algebraString) > 0);
end if;
Put ("AlgebraString: ");
Put_Line (To_String (algebraString));
if Length (algebraString) <= 1 then
Append_To_Msg (Message, "Algebra string is too short.");
Error := True;
return;
end if;
if not Error then
Parse_Formula (algebraString, Algebra, Error, Message);
if not Error then
declare
procedure Check_Actions_In_Map_Rec (Tree : not null Algebra_Tree) with
Post => (if not Error then All_Actions_In_Map (Tree, TaskPlanOptions_Map));
pragma Annotate (GNATprove, Terminating, Check_Actions_In_Map_Rec);
procedure Check_Actions_In_Map_Rec (Tree : not null Algebra_Tree) is
begin
case Tree.all.Node_Kind is
when Action =>
if Tree.TaskOptionId not in 0 .. 9_999_999_999 then
Append_To_Msg (Message, "TaskOptionId ");
Append_To_Msg (Message, Print_Int64 (Tree.TaskOptionId));
Append_To_Msg (Message, " should be in range 0 .. 9_999_999_999.");
Error := True;
return;
end if;
if
(for all TaskId of TaskPlanOptions_Map =>
(for all TaskOption of Get (TaskPlanOptions_Map, TaskId).Options =>
(TaskId /= TaskOption.TaskID
or else TaskOption.TaskID /= Get_TaskID (Tree.TaskOptionId)
or else TaskOption.OptionID /= Get_OptionID (Tree.TaskOptionId))))
then
Append_To_Msg (Message, "OptionId ");
Append_To_Msg (Message, Print_Int64 (Get_OptionID (Tree.TaskOptionId)));
Append_To_Msg (Message, " does not exist for TaskId ");
Append_To_Msg (Message, Print_Int64 (Get_TaskID (Tree.TaskOptionId)));
Append_To_Msg (Message, '.');
Error := True;
return;
end if;
when Operator =>
for J in 1 .. Tree.Collection.Num_Children loop
Check_Actions_In_Map_Rec (Tree.Collection.Children (J));
if Error then
return;
end if;
pragma Loop_Invariant (for all K in 1 .. J => All_Actions_In_Map (Tree.Collection.Children (K), TaskPlanOptions_Map));
end loop;
when Undefined =>
Append_To_Msg (Message, "Algebra tree is not well formed.");
Error := True;
return;
end case;
end Check_Actions_In_Map_Rec;
begin
Check_Actions_In_Map_Rec (Algebra);
end;
end if;
end if;
end Initialize_Algebra;
--------------------
-- New_Assignment --
--------------------
function New_Assignment
(Assignment : Assignment_Info;
VehicleId : Int64;
TaskOpt : TaskOption;
Assignment_Cost_Matrix : AssignmentCostMatrix;
TaskPlanOptions_Map : Int64_TPO_Map;
Automation_Request : UniqueAutomationRequest)
return Assignment_Info
is
Result : Assignment_Info;
Vehicle_Assignment : constant VehicleAssignmentCost :=
(if Contains (Assignment.Vehicle_Assignments, VehicleId)
then Element (Assignment.Vehicle_Assignments, VehicleId)
else VehicleAssignmentCost'(0, TaskOpt));
pragma Assume
(Vehicle_Assignment.TotalTime
<= Int64'Last
- (if Contains (Assignment.Vehicle_Assignments, VehicleId)
then Corresponding_TaskOptionCost (Assignment_Cost_Matrix,
VehicleId,
Vehicle_Assignment.Last_TaskOption,
TaskOpt).TimeToGo
else Corresponding_TaskOptionCost (Assignment_Cost_Matrix,
VehicleId,
TaskOpt).TimeToGo));
TimeThreshold : constant Int64 :=
Vehicle_Assignment.TotalTime
+ (if Contains (Assignment.Vehicle_Assignments, VehicleId)
then Corresponding_TaskOptionCost (Assignment_Cost_Matrix,
VehicleId,
Vehicle_Assignment.Last_TaskOption,
TaskOpt).TimeToGo
else Corresponding_TaskOptionCost (Assignment_Cost_Matrix,
VehicleId,
TaskOpt).TimeToGo);
pragma Assume
(TimeThreshold <= Int64'Last - TaskOpt.Cost);
TimeTaskCompleted : constant Int64 :=
TimeThreshold
+ TaskOpt.Cost;
procedure Prove_Final_Value_Is_Valid with
Ghost,
Pre =>
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then Valid_Assignment (Assignment, TaskPlanOptions_Map, Automation_Request)
and then Length (Assignment.Assignment_Sequence) < Count_Type'Last
and then TaskOpt.TaskID in 0 .. 99_999
and then TaskOpt.OptionID in 0 .. 99_999
and then Result.Assignment_Sequence = Add (Assignment.Assignment_Sequence,
(TaskOpt.TaskID,
TaskOpt.OptionID,
VehicleId,
TimeThreshold,
TimeTaskCompleted))
and then
(for some TaskAssignment of Result.Assignment_Sequence =>
(TaskAssignment.TaskID = TaskOpt.TaskID and then TaskAssignment.OptionID = TaskOpt.OptionID))
and then
Contains_Corresponding_TaskOption (Automation_Request, TaskPlanOptions_Map, TaskOpt, VehicleId)
and then
(for all EntityId of Result.Vehicle_Assignments =>
(if EntityId /= VehicleId
then Contains (Assignment.Vehicle_Assignments, EntityId)
and then Element (Result.Vehicle_Assignments, EntityId) = Element (Assignment.Vehicle_Assignments, EntityId)
else Element (Result.Vehicle_Assignments, EntityId).Last_TaskOption = TaskOpt)),
Post => Valid_Assignment (Result, TaskPlanOptions_Map, Automation_Request);
procedure Prove_Initial_Value_Is_Valid with
Ghost,
Pre =>
Length (Assignment.Assignment_Sequence) < Count_Type'Last
and then TaskOpt.TaskID in 0 .. 99_999
and then TaskOpt.OptionID in 0 .. 99_999
and then
Result.Assignment_Sequence = Add (Assignment.Assignment_Sequence,
(TaskOpt.TaskID,
TaskOpt.OptionID,
VehicleId,
TimeThreshold,
TimeTaskCompleted))
and then Assignment.Vehicle_Assignments = Result.Vehicle_Assignments
and then Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then Valid_Assignment (Assignment, TaskPlanOptions_Map, Automation_Request),
Post =>
Valid_Assignment (Result, TaskPlanOptions_Map, Automation_Request);
--------------------------------
-- Prove_Final_Value_Is_Valid --
--------------------------------
procedure Prove_Final_Value_Is_Valid is
I : Int64_VehicleAssignmentCost_Maps.Cursor := First (Result.Vehicle_Assignments);
begin
while Has_Element (Result.Vehicle_Assignments, I) loop
if Key (Result.Vehicle_Assignments, I) = VehicleId then
pragma Assert
(Contains_Corresponding_TaskOption (Automation_Request, TaskPlanOptions_Map, TaskOpt, Key (Result.Vehicle_Assignments, I)));
Equal_TaskOpt_Lemma (Automation_Request,
TaskPlanOptions_Map,
TaskOpt,
Element (Result.Vehicle_Assignments, I).Last_TaskOption,
Key (Result.Vehicle_Assignments, I));
else
pragma Assert
(Contains (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I))
and then Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I))
= Element (Result.Vehicle_Assignments, I));
pragma Assert
(Contains_Corresponding_TaskOption
(Assignment.Assignment_Sequence,
Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)).Last_TaskOption));
pragma Assert
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)).Last_TaskOption,
Key (Result.Vehicle_Assignments, I)));
Equal_TaskOpt_Lemma (Automation_Request,
TaskPlanOptions_Map,
Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)).Last_TaskOption,
Element (Result.Vehicle_Assignments, I).Last_TaskOption,
Key (Result.Vehicle_Assignments, I));
end if;
pragma Loop_Invariant (Has_Element (Result.Vehicle_Assignments, I));
pragma Loop_Invariant
(for all K in 1 .. Int64_VehicleAssignmentCost_Maps_P.Get (Positions (Result.Vehicle_Assignments), I) =>
(Contains_Corresponding_TaskOption
(Result.Assignment_Sequence,
Element (Result.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)).Last_TaskOption)
and then
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (Result.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)).Last_TaskOption,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)))));
Next (Result.Vehicle_Assignments, I);
end loop;
for J in TO_Sequences.First .. Last (Result.Assignment_Sequence) loop
if J /= Last (Result.Assignment_Sequence) then
pragma Assert (Get (Result.Assignment_Sequence, J) = Get (Assignment.Assignment_Sequence, J));
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, J).OptionID in 0 .. 99_999);
else
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID = TaskOpt.TaskID
and then Get (Result.Assignment_Sequence, J).OptionID = TaskOpt.OptionID);
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, J).OptionID in 0 .. 99_999);
end if;
pragma Loop_Invariant
(for all K in TO_Sequences.First .. J =>
(Get (Result.Assignment_Sequence, K).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, K).OptionID in 0 .. 99_999));
end loop;
end Prove_Final_Value_Is_Valid;
----------------------------------
-- Prove_Initial_Value_Is_Valid --
----------------------------------
procedure Prove_Initial_Value_Is_Valid is
I : Int64_VehicleAssignmentCost_Maps.Cursor := First (Result.Vehicle_Assignments);
begin
while Has_Element (Result.Vehicle_Assignments, I) loop
pragma Assert
(Contains (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I))
and then Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)) = Element (Result.Vehicle_Assignments, I));
pragma Assert
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)).Last_TaskOption,
Key (Result.Vehicle_Assignments, I)));
Equal_TaskOpt_Lemma (Automation_Request,
TaskPlanOptions_Map,
Element (Assignment.Vehicle_Assignments, Key (Result.Vehicle_Assignments, I)).Last_TaskOption,
Element (Result.Vehicle_Assignments, I).Last_TaskOption,
Key (Result.Vehicle_Assignments, I));
pragma Loop_Invariant (Has_Element (Result.Vehicle_Assignments, I));
pragma Loop_Invariant
(for all K in 1 .. Int64_VehicleAssignmentCost_Maps_P.Get (Positions (Result.Vehicle_Assignments), I) =>
(Contains_Corresponding_TaskOption
(Result.Assignment_Sequence,
Element (Result.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)).Last_TaskOption)
and then
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (Result.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)).Last_TaskOption,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (Result.Vehicle_Assignments), K)))));
Next (Result.Vehicle_Assignments, I);
end loop;
for J in TO_Sequences.First .. Last (Result.Assignment_Sequence) loop
if J /= Last (Result.Assignment_Sequence) then
pragma Assert (Get (Result.Assignment_Sequence, J) = Get (Assignment.Assignment_Sequence, J));
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, J).OptionID in 0 .. 99_999);
else
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID = TaskOpt.TaskID
and then Get (Result.Assignment_Sequence, J).OptionID = TaskOpt.OptionID);
pragma Assert (Get (Result.Assignment_Sequence, J).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, J).OptionID in 0 .. 99_999);
end if;
pragma Loop_Invariant
(for all K in TO_Sequences.First .. J =>
(Get (Result.Assignment_Sequence, K).TaskID in 0 .. 99_999
and then Get (Result.Assignment_Sequence, K).OptionID in 0 .. 99_999));
end loop;
end Prove_Initial_Value_Is_Valid;
begin
-- The assignment sequence is the enclosing assignment sequence with
-- the new TaskAssignment added at the end.
pragma Assume (Length (Assignment.Assignment_Sequence) < Count_Type'Last);
Result.Assignment_Sequence :=
Add (Assignment.Assignment_Sequence,
(TaskOpt.TaskID,
TaskOpt.OptionID,
VehicleId,
TimeThreshold,
TimeTaskCompleted));
Result.Vehicle_Assignments := Assignment.Vehicle_Assignments;
Prove_Initial_Value_Is_Valid;
pragma Assert (Valid_Assignment (Result, TaskPlanOptions_Map, Automation_Request));
declare
VAC : VehicleAssignmentCost := (TimeTaskCompleted, TaskOpt);
begin
pragma Assert
(for some TaskId of TaskPlanOptions_Map =>
(for some Option of Get (TaskPlanOptions_Map, TaskId).Options =>
(Option = VAC.Last_TaskOption
and then Is_Eligible (Automation_Request, VAC.Last_TaskOption, VehicleId))));
if Contains (Result.Vehicle_Assignments, VehicleId) then
Replace (Result.Vehicle_Assignments, VehicleId, VAC);
Prove_Final_Value_Is_Valid;
pragma Assert (Valid_Assignment (Result, TaskPlanOptions_Map, Automation_Request));
else
pragma Assume (Length (Result.Vehicle_Assignments) < Result.Vehicle_Assignments.Capacity, "we have enough space for another vehicle");
Insert (Result.Vehicle_Assignments, VehicleId, VAC);
Prove_Final_Value_Is_Valid;
pragma Assert (Valid_Assignment (Result, TaskPlanOptions_Map, Automation_Request));
end if;
end;
return Result;
end New_Assignment;
------------------------------
-- Run_Calculate_Assignment --
------------------------------
procedure Run_Calculate_Assignment
(Data : Assignment_Tree_Branch_Bound_Configuration_Data;
Automation_Request : UniqueAutomationRequest;
Assignment_Cost_Matrix : AssignmentCostMatrix;
TaskPlanOptions_Map : Int64_TPO_Map;
Summary : out TaskAssignmentSummary;
Error : out Boolean;
Message : out Unbounded_String)
is
procedure Bubble_Sort (Arr : in out Children_Arr)
with
Pre =>
Arr'Length > 0
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
(for all Child of Arr =>
(Valid_Assignment (Child, TaskPlanOptions_Map, Automation_Request))),
Post =>
(for all Child of Arr =>
(Valid_Assignment (Child, TaskPlanOptions_Map, Automation_Request)));
-- Sorts the array of assignments in the ascending order of cost.
procedure Equal_Implies_Valid_Assignment (A, B : Assignment_Info) with
Ghost,
Pre => A = B and then Valid_TaskPlanOptions (TaskPlanOptions_Map) and then Valid_Assignment (A, TaskPlanOptions_Map, Automation_Request),
Post => Valid_Assignment (B, TaskPlanOptions_Map, Automation_Request);
procedure Pop_Wrapper (Search_Stack : in out Stack; Current_Element : out Assignment_Info) with
Pre =>
Size (Search_Stack) > Assignment_Stack.Empty
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
(for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request)),
Post =>
Size (Search_Stack) = Size (Search_Stack'Old) - 1
and then
Valid_Assignment (Current_Element, TaskPlanOptions_Map, Automation_Request)
and then
(for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
procedure Push_Wrapper (Search_Stack : in out Stack; Current_Element : Assignment_Info) with
Pre =>
Size (Search_Stack) < Assignment_Stack.Capacity
and then
Valid_TaskPlanOptions (TaskPlanOptions_Map)
and then
(for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request))
and then
Valid_Assignment (Current_Element, TaskPlanOptions_Map, Automation_Request),
Post =>
Size (Search_Stack) = Size (Search_Stack'Old) + 1
and then
(for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
-----------------
-- Bubble_Sort --
-----------------
procedure Bubble_Sort (Arr : in out Children_Arr) is
Switched : Boolean;
begin
loop
Switched := False;
pragma Loop_Invariant (for all Child of Arr => Valid_Assignment (Child, TaskPlanOptions_Map, Automation_Request));
for J in Arr'First .. Arr'Last - 1 loop
pragma Loop_Invariant (for all Child of Arr => Valid_Assignment (Child, TaskPlanOptions_Map, Automation_Request));
if Cost (Arr (J + 1), Data.Cost_Function) < Cost (Arr (J), Data.Cost_Function) then
declare
Tmp : Assignment_Info := Arr (J + 1);
begin
Equal_Implies_Valid_Assignment (Arr (J + 1), Tmp);
Arr (J + 1) := Arr (J);
Equal_Implies_Valid_Assignment (Arr (J), Arr (J + 1));
Arr (J) := Tmp;
Equal_Implies_Valid_Assignment (Tmp, Arr (J));
Switched := True;
end;
end if;
end loop;
exit when not Switched;
end loop;
end Bubble_Sort;
------------------------------------
-- Equal_Implies_Valid_Assignment --
------------------------------------
procedure Equal_Implies_Valid_Assignment (A, B : Assignment_Info) is
I : Int64_VehicleAssignmentCost_Maps.Cursor := First (B.Vehicle_Assignments);
begin
while Has_Element (B.Vehicle_Assignments, I) loop
pragma Assert
(Contains (A.Vehicle_Assignments, Key (B.Vehicle_Assignments, I))
and then Element (A.Vehicle_Assignments, Key (B.Vehicle_Assignments, I)) = Element (B.Vehicle_Assignments, I));
pragma Assert
(Contains_Corresponding_TaskOption
(A.Assignment_Sequence,
Element (A.Vehicle_Assignments, Key (B.Vehicle_Assignments, I)).Last_TaskOption));
pragma Assert
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (A.Vehicle_Assignments, Key (B.Vehicle_Assignments, I)).Last_TaskOption,
Key (B.Vehicle_Assignments, I)));
Equal_TaskOpt_Lemma
(Automation_Request,
TaskPlanOptions_Map,
Element (A.Vehicle_Assignments, Key (B.Vehicle_Assignments, I)).Last_TaskOption,
Element (B.Vehicle_Assignments, I).Last_TaskOption,
Key (B.Vehicle_Assignments, I));
pragma Loop_Invariant (Has_Element (B.Vehicle_Assignments, I));
pragma Loop_Invariant
(for all K in 1 .. Int64_VehicleAssignmentCost_Maps_P.Get (Positions (B.Vehicle_Assignments), I) =>
(Contains_Corresponding_TaskOption
(B.Assignment_Sequence,
Element (B.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (B.Vehicle_Assignments), K)).Last_TaskOption)
and then
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (B.Vehicle_Assignments,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (B.Vehicle_Assignments), K)).Last_TaskOption,
Int64_VehicleAssignmentCost_Maps_K.Get (Keys (B.Vehicle_Assignments), K)))));
Next (B.Vehicle_Assignments, I);
end loop;
end Equal_Implies_Valid_Assignment;
-----------------
-- Pop_Wrapper --
-----------------
procedure Pop_Wrapper (Search_Stack : in out Stack; Current_Element : out Assignment_Info) is
Old_Stack : constant Stack := Search_Stack with Ghost;
begin
Pop (Search_Stack, Current_Element);
Equal_Implies_Valid_Assignment (Element (Old_Stack, Size (Old_Stack)), Current_Element);
for K in 1 .. Size (Search_Stack) loop
Equal_Implies_Valid_Assignment (Element (Old_Stack, K), Element (Search_Stack, K));
pragma Loop_Invariant
(for all J in 1 .. K => Valid_Assignment (Element (Search_Stack, J), TaskPlanOptions_Map, Automation_Request));
end loop;
end Pop_Wrapper;
------------------
-- Push_Wrapper --
------------------
procedure Push_Wrapper (Search_Stack : in out Stack; Current_Element : Assignment_Info) is
Old_Stack : constant Stack := Search_Stack with Ghost;
begin
Push (Search_Stack, Current_Element);
for K in 1 .. Size (Search_Stack) loop
if K < Size (Search_Stack) then
Equal_Implies_Valid_Assignment (Element (Old_Stack, K), Element (Search_Stack, K));
else
Equal_Implies_Valid_Assignment (Current_Element, Element (Search_Stack, K));
end if;
pragma Loop_Invariant
(for all J in 1 .. K => Valid_Assignment (Element (Search_Stack, J), TaskPlanOptions_Map, Automation_Request));
end loop;
end Push_Wrapper;
type Min_Option (Found : Boolean := False) is record
case Found is
when True =>
Info : Assignment_Info;
Cost : Int64;
when False =>
null;
end case;
end record;
Algebra : Algebra_Tree;
Min : Min_Option := (Found => False);
Search_Stack : Stack;
Current_Element : Assignment_Info;
Empty_TA_Seq : TaskAssignment_Sequence;
Empty_VA_Map : Int64_VAC_Map;
Nodes_Visited : Int64 := 0;
begin
Initialize_Algebra (Automation_Request, TaskPlanOptions_Map, Algebra, Error, Message);
Put_Line (To_String (Message));
if not Error then
Put_Line ("Algebra Tree:");
Print_Tree (Algebra);
-- The first element is a null assignment
Push_Wrapper (Search_Stack,
(Empty_TA_Seq,
Empty_VA_Map));
pragma Assert (for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
-- If the stack is empty, all solutions have been explored
while Size (Search_Stack) /= 0
-- We continue at least until we find a solution
and then (if Min.Found
then (Nodes_Visited in 1 .. Data.Number_Nodes_Maximum - 1))
loop
pragma Loop_Invariant (for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
-- The element at the top of the stack is popped
Pop_Wrapper (Search_Stack, Current_Element);
if not Min.Found or else Cost (Current_Element, Data.Cost_Function) < Min.Cost then
declare
Children_A : Children_Arr :=
Children (Current_Element,
Algebra,
Automation_Request,
TaskPlanOptions_Map,
Assignment_Cost_Matrix);
Current_Cost : constant Int64 := Cost (Current_Element, Data.Cost_Function);
begin
-- If this element has no children, it means that this node
-- has assigned every task, so we compare it to the current
-- assignment that minimizes the cost.
if Children_A'Length = 0 then
if not Min.Found or else Current_Cost < Min.Cost then
Min := (Found => True, Info => Current_Element, Cost => Current_Cost);
end if;
-- Else, we compute the cost for every child and push them into the
-- stack if their cost is lower than the current minimal cost.
else
Bubble_Sort (Children_A);
for J in reverse Children_A'Range loop
pragma Loop_Invariant (for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
declare
Child : Assignment_Info := Children_A (J);
begin
if not Min.Found or else Cost (Child, Data.Cost_Function) < Min.Cost then
pragma Assume (Size (Search_Stack) < Assignment_Stack.Capacity, "we have space for another child");
Push_Wrapper (Search_Stack, Child);
end if;
end;
end loop;
pragma Assert (for all K in 1 .. Size (Search_Stack) => Valid_Assignment (Element (Search_Stack, K), TaskPlanOptions_Map, Automation_Request));
end if;
end;
pragma Assume (Nodes_Visited < Int64'Last, "a solution is found in less than Int64'Last steps");
Nodes_Visited := Nodes_Visited + 1;
end if;
end loop;
Summary.CorrespondingAutomationRequestID := Automation_Request.RequestID;
Summary.OperatingRegion := Automation_Request.OperatingRegion;
Summary.TaskList := Min.Info.Assignment_Sequence;
else
declare
Null_TAS : TaskAssignmentSummary;
begin
Summary := Null_TAS;
end;
end if;
Free_Tree (Algebra);
end Run_Calculate_Assignment;
---------------------------------
-- Send_TaskAssignmentSummary --
---------------------------------
procedure Send_TaskAssignmentSummary
(Mailbox : in out Assignment_Tree_Branch_Bound_Mailbox;
Data : Assignment_Tree_Branch_Bound_Configuration_Data;
State : in out Assignment_Tree_Branch_Bound_State;
ReqId : Int64)
is
Summary : TaskAssignmentSummary;
procedure Delete_AssignmentCostMatrix
(assignmentCostMatrixes : in out Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
Contains (assignmentCostMatrixes, ReqId),
Post =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
not Contains (assignmentCostMatrixes, ReqId);
procedure Delete_TaskPlanOption
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
not Contains (assignmentCostMatrixes, ReqId)
and then
Contains (taskPlanOptions, ReqId),
Post =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
not Contains (assignmentCostMatrixes, ReqId)
and then
not Contains (taskPlanOptions, ReqId);
procedure Delete_UniqueAutomationRequest
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : in out Int64_UniqueAutomationRequest_Map)
with
Pre =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)))
and then
not Contains (assignmentCostMatrixes, ReqId)
and then
not Contains (taskPlanOptions, ReqId)
and then
Contains (uniqueAutomationRequests, ReqId),
Post =>
(for all Req of taskPlanOptions =>
(Valid_TaskPlanOptions (Element (taskPlanOptions, Req))
and then Contains (uniqueAutomationRequests, Req)
and then
All_EligibleEntities_In_EntityList
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req))))
and then
(for all Req of assignmentCostMatrixes =>
Valid_AssignmentCostMatrix (Element (assignmentCostMatrixes, Req))
and then Contains (uniqueAutomationRequests, Req)
and then Contains (taskPlanOptions, Req)
and then
All_Travels_In_CostMatrix
(Element (uniqueAutomationRequests, Req),
Element (taskPlanOptions, Req),
Element (assignmentCostMatrixes, Req)));
---------------------------------
-- Delete_AssignmentCostMatrix --
---------------------------------
procedure Delete_AssignmentCostMatrix
(assignmentCostMatrixes : in out Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
begin
Delete (assignmentCostMatrixes, ReqId);
end Delete_AssignmentCostMatrix;
---------------------------
-- Delete_TaskPlanOption --
---------------------------
procedure Delete_TaskPlanOption
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : in out Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
begin
Delete (taskPlanOptions, ReqId);
end Delete_TaskPlanOption;
------------------------------------
-- Delete_UniqueAutomationRequest --
------------------------------------
procedure Delete_UniqueAutomationRequest
(assignmentCostMatrixes : Int64_AssignmentCostMatrix_Map;
taskPlanOptions : Int64_TaskPlanOptions_Map_Map;
uniqueAutomationRequests : in out Int64_UniqueAutomationRequest_Map)
is
pragma SPARK_Mode (Off);
begin
Delete (uniqueAutomationRequests, ReqId);
end Delete_UniqueAutomationRequest;
Error : Boolean;
Message : Unbounded_String;
begin
pragma Assert
(Contains (State.m_assignmentCostMatrixes, ReqId));
pragma Assert
(All_Travels_In_CostMatrix
(Element (State.m_uniqueAutomationRequests, ReqId),
Element (State.m_taskPlanOptions, ReqId),
Element (State.m_assignmentCostMatrixes, ReqId)));
Run_Calculate_Assignment
(Data,
Element (State.m_uniqueAutomationRequests, ReqId),
Element (State.m_assignmentCostMatrixes, ReqId),
Element (State.m_taskPlanOptions, ReqId),
Summary,
Error,
Message);
if not Error then
sendBroadcastMessage (Mailbox, Summary);
else
sendErrorMessage (Mailbox, Message);
end if;
Delete_AssignmentCostMatrix (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
Delete_TaskPlanOption (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
Delete_UniqueAutomationRequest (State.m_assignmentCostMatrixes, State.m_taskPlanOptions, State.m_uniqueAutomationRequests);
end Send_TaskAssignmentSummary;
-------------------------
-- TaskOptionId_In_Map --
-------------------------
function TaskOptionId_In_Map
(TaskOptionId : Int64;
TaskPlanOptions_Map : Int64_TPO_Map)
return Boolean
is
(for some TaskId of TaskPlanOptions_Map =>
(for some TaskOption of Get (TaskPlanOptions_Map, TaskId).Options =>
(TaskId = TaskOption.TaskID
and then TaskOption.TaskID = Get_TaskID (TaskOptionId)
and then TaskOption.OptionID = Get_OptionID (TaskOptionId))));
----------------------
-- Valid_Assignment --
----------------------
function Valid_Assignment
(Assignment : Assignment_Info;
TaskPlanOptions_Map : Int64_TPO_Map;
Automation_Request : UniqueAutomationRequest)
return Boolean
is
((for all TaskAssignment of Assignment.Assignment_Sequence =>
(TaskAssignment.TaskID in 0 .. 99_999
and then
TaskAssignment.OptionID in 0 .. 99_999))
and then
(for all EntityId of Assignment.Vehicle_Assignments =>
(Contains_Corresponding_TaskOption
(Assignment.Assignment_Sequence,
Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption)
and then
(Contains_Corresponding_TaskOption
(Automation_Request,
TaskPlanOptions_Map,
Element (Assignment.Vehicle_Assignments, EntityId).Last_TaskOption,
EntityId)))));
end Assignment_Tree_Branch_Bound;
|
-- Copyright (c) 2019-2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Exceptions;
with Ada.Unchecked_Conversion;
with Interfaces;
with GNAT.SHA1;
with Torrent.Downloaders;
with Torrent.Handshakes; use Torrent.Handshakes;
with Torrent.Logs;
package body Torrent.Connections is
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Array;
use type Ada.Streams.Stream_Element_Offset;
subtype Int_Buffer is Ada.Streams.Stream_Element_Array (1 .. 4);
function To_Int (Value : Natural) return Int_Buffer;
Expire_Loops : constant := 3;
-- Protection from lost of requests
function Get_Handshake (Self : Connection'Class) return Handshake_Image;
function Get_Int
(Data : Ada.Streams.Stream_Element_Array;
From : Ada.Streams.Stream_Element_Count := 0) return Natural;
function Is_Valid_Piece
(Self : Connection'Class;
Piece : Piece_Index) return Boolean;
procedure Send_Message
(Self : in out Connection'Class;
Data : Ada.Streams.Stream_Element_Array);
procedure Send_Have
(Self : in out Connection'Class;
Piece : Piece_Index);
procedure Send_Bitfield
(Self : in out Connection'Class;
Completed : Piece_Index_Array);
procedure Send_Pieces
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time);
procedure Unreserve_Intervals (Self : in out Connection'Class);
procedure Close_Connection (Self : in out Connection'Class);
----------------------
-- Close_Connection --
----------------------
procedure Close_Connection (Self : in out Connection'Class) is
begin
GNAT.Sockets.Close_Socket (Self.Socket);
Self.Closed := True;
Self.Unreserve_Intervals;
end Close_Connection;
---------------
-- Connected --
---------------
function Connected (Self : Connection'Class) return Boolean is
begin
return not Self.Closed;
end Connected;
------------------
-- Do_Handshake --
------------------
procedure Do_Handshake
(Self : in out Connection'Class;
Socket : GNAT.Sockets.Socket_Type;
Completed : Piece_Index_Array;
Inbound : Boolean)
is
Last : Ada.Streams.Stream_Element_Count;
begin
Self.Socket := Socket;
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Self.Get_Handshake,
Last => Last);
pragma Assert (Last = Handshake_Image'Last);
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout, 0.0));
Self.Initialize (Self.My_Peer_Id, Self.Peer, Self.Listener);
Self.Sent_Handshake := True;
Self.Got_Handshake := Inbound;
Self.Send_Bitfield (Completed);
Self.Last_Completed := Completed'Last;
exception
when E : others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Do_Handshake:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end Do_Handshake;
----------------
-- Downloaded --
----------------
function Downloaded (Self : in out Connection'Class) return Piece_Offset is
begin
return Result : constant Piece_Offset := Self.Downloaded do
Self.Downloaded := Self.Downloaded / 3;
end return;
end Downloaded;
-------------------
-- Get_Handshake --
-------------------
function Get_Handshake (Self : Connection'Class) return Handshake_Image is
Result : Handshake_Type;
begin
Result.Info_Hash := Self.Meta.Info_Hash;
Result.Peer_Id := Self.My_Peer_Id;
return +Result;
end Get_Handshake;
-------------
-- Get_Int --
-------------
function Get_Int
(Data : Ada.Streams.Stream_Element_Array;
From : Ada.Streams.Stream_Element_Count := 0) return Natural
is
subtype X is Natural;
begin
return
((X (Data (Data'First + From)) * 256
+ X (Data (Data'First + From + 1))) * 256
+ X (Data (Data'First + From + 2))) * 256
+ X (Data (Data'First + From + 3));
end Get_Int;
----------------
-- Initialize --
----------------
procedure Initialize
(Self : in out Connection'Class;
My_Id : SHA1;
Peer : GNAT.Sockets.Sock_Addr_Type;
Listener : Connection_State_Listener_Access)
is
begin
Self.Peer := Peer;
Self.Sent_Handshake := False;
Self.Got_Handshake := False;
Self.Closed := False;
Self.We_Choked := True;
Self.He_Choked := True;
Self.Choked_Sent := True;
Self.We_Intrested := False;
Self.He_Intrested := False;
Self.My_Peer_Id := My_Id;
Self.Last_Request := 0;
Self.Last_Completed := 0;
Self.Listener := Listener;
Self.Downloaded := 0;
Self.Current_Piece := (0, Intervals => <>);
Self.Piece_Map := (others => False);
end Initialize;
------------
-- Insert --
------------
procedure Insert
(List : in out Interval_Vectors.Vector;
Value : Interval)
is
M, N : Natural := 0;
Next : Interval := Value;
begin
if (for some X of List => X.From <= Next.From and X.To >= Next.To) then
return;
end if;
loop
M := 0;
N := 0;
for J in 1 .. List.Last_Index loop
if List (J).To + 1 = Next.From then
M := J;
exit;
elsif Next.To + 1 = List (J).From then
N := J;
exit;
end if;
end loop;
if M > 0 then
Next := (List (M).From, Next.To);
List.Swap (M, List.Last_Index);
List.Delete_Last;
elsif N > 0 then
Next := (Next.From, List (N).To);
List.Swap (N, List.Last_Index);
List.Delete_Last;
else
List.Append (Next);
exit;
end if;
end loop;
end Insert;
---------------
-- Intrested --
---------------
function Intrested (Self : Connection'Class) return Boolean is
begin
return not Self.Closed and Self.He_Intrested;
end Intrested;
--------------------
-- Is_Valid_Piece --
--------------------
function Is_Valid_Piece
(Self : Connection'Class;
Piece : Piece_Index) return Boolean is
begin
return Is_Valid_Piece (Self.Meta, Self.Storage.all, Piece);
end Is_Valid_Piece;
--------------------
-- Is_Valid_Piece --
--------------------
function Is_Valid_Piece
(Meta : not null Torrent.Metainfo_Files.Metainfo_File_Access;
Storage : in out Torrent.Storages.Storage;
Piece : Piece_Index) return Boolean
is
Context : GNAT.SHA1.Context;
From : Ada.Streams.Stream_Element_Offset :=
Piece_Offset (Piece - 1) * Meta.Piece_Length;
Left : Ada.Streams.Stream_Element_Offset;
Data : Ada.Streams.Stream_Element_Array (1 .. Max_Interval_Size);
Value : SHA1;
begin
Storage.Start_Reading; -- Block storage
if Piece = Meta.Piece_Count then
Left := Meta.Last_Piece_Length;
else
Left := Meta.Piece_Length;
end if;
while Left > Data'Length loop
Storage.Read (From, Data);
From := From + Data'Length;
Left := Left - Data'Length;
GNAT.SHA1.Update (Context, Data);
end loop;
if Left > 0 then
Storage.Read (From, Data (1 .. Left));
GNAT.SHA1.Update (Context, Data (1 .. Left));
end if;
Value := GNAT.SHA1.Digest (Context);
Storage.Stop_Reading; -- Unblock storage
return Meta.Piece_SHA1 (Piece) = Value;
end Is_Valid_Piece;
----------
-- Peer --
----------
function Peer
(Self : Connection'Class) return GNAT.Sockets.Sock_Addr_Type is
begin
return Self.Peer;
end Peer;
-------------------
-- Send_Bitfield --
-------------------
procedure Send_Bitfield
(Self : in out Connection'Class;
Completed : Piece_Index_Array)
is
Length : constant Piece_Offset :=
Piece_Offset (Self.Piece_Count + 7) / 8;
Data : Ada.Streams.Stream_Element_Array (0 .. Length - 1) :=
(others => 0); -- Zero based
Mask : Interfaces.Unsigned_8;
begin
for X of Completed loop
Mask := Interfaces.Shift_Right (128, Natural ((X - 1) mod 8));
Data (Piece_Offset (X - 1) / 8) := Data (Piece_Offset (X - 1) / 8)
or Ada.Streams.Stream_Element (Mask);
end loop;
Self.Send_Message (To_Int (Positive (Length) + 1) & 05 & Data);
end Send_Bitfield;
---------------
-- Send_Have --
---------------
procedure Send_Have
(Self : in out Connection'Class;
Piece : Piece_Index) is
begin
Self.Send_Message
((00, 00, 00, 05, 04) & -- have
To_Int (Natural (Piece - 1)));
end Send_Have;
------------------
-- Send_Message --
------------------
procedure Send_Message
(Self : in out Connection'Class;
Data : Ada.Streams.Stream_Element_Array)
is
Last : Ada.Streams.Stream_Element_Offset;
begin
if Self.Closed then
return;
end if;
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Data,
Last => Last);
pragma Assert (Last = Data'Last);
if Data'Length <= 4 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send keepalive " & GNAT.Sockets.Image (Self.Peer)));
elsif Data (Data'First + 4) = 6 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send request "
& GNAT.Sockets.Image (Self.Peer)
& Integer'Image (Get_Int (Data, 5) + 1)
& Integer'Image (Get_Int (Data, 9))
& Integer'Image (Get_Int (Data, 13))));
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send "
& GNAT.Sockets.Image (Self.Peer)
& (Data (Data'First + 4)'Img)));
end if;
exception
when E : GNAT.Sockets.Socket_Error =>
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout,
GNAT.Sockets.Forever));
Self.Send_Message (Data);
return;
end if;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send_Message:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
end Send_Message;
-----------------
-- Send_Pieces --
-----------------
procedure Send_Pieces
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
Total_Sent : Ada.Streams.Stream_Element_Count := 0;
begin -- FIXME check if unchoked
while not Self.Requests.Is_Empty loop
declare
Last : Ada.Streams.Stream_Element_Count;
Item : constant Piece_Interval := Self.Requests.Last_Element;
Data : Ada.Streams.Stream_Element_Array
(Item.Span.From - 4 - 1 - 4 - 4 .. Item.Span.To);
begin
Self.Storage.Start_Reading;
Self.Storage.Read
(Offset => Ada.Streams.Stream_Element_Count (Item.Piece - 1)
* Self.Meta.Piece_Length
+ Ada.Streams.Stream_Element_Count (Item.Span.From),
Data => Data (Item.Span.From .. Item.Span.To));
Self.Storage.Stop_Reading;
Data (Data'First .. Data'First + 3) := -- Message length
To_Int (Data'Length - 4);
Data (Data'First + 4) := 7; -- piece
Data (Data'First + 5 .. Data'First + 8) :=
To_Int (Positive (Item.Piece) - 1);
Data (Data'First + 9 .. Data'First + 12) :=
To_Int (Natural (Item.Span.From));
exit when Self.Closed;
GNAT.Sockets.Set_Socket_Option
(Socket => Self.Socket,
Level => GNAT.Sockets.Socket_Level,
Option => (GNAT.Sockets.Receive_Timeout,
Limit - Ada.Calendar.Clock));
GNAT.Sockets.Send_Socket
(Socket => Self.Socket,
Item => Data,
Last => Last);
pragma Assert (Last = Data'Last);
Total_Sent := Total_Sent + Data'Length;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send piece "
& GNAT.Sockets.Image (Self.Peer)
& Piece_Count'Image (Item.Piece)
& Piece_Offset'Image (Item.Span.From)));
Self.Requests.Delete_Last;
-- FIXME Increment send statistic.
end;
end loop;
Self.Listener.Interval_Sent (Total_Sent);
exception
when E : GNAT.Sockets.Socket_Error =>
Self.Listener.Interval_Sent (Total_Sent);
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
return;
end if;
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Send_Pieces:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
end Send_Pieces;
-----------
-- Serve --
-----------
procedure Serve
(Self : in out Connection'Class;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
procedure Check_Intrested;
procedure Send_Initial_Requests;
function Get_Handshake
(Data : Ada.Streams.Stream_Element_Array) return Boolean;
function Get_Length
(Data : Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Offset;
procedure Read_Messages
(Data : in out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Count);
procedure On_Message (Data : Ada.Streams.Stream_Element_Array);
procedure Save_Piece
(Index : Piece_Index;
Offset : Natural;
Data : Ada.Streams.Stream_Element_Array);
---------------------
-- Check_Intrested --
---------------------
procedure Check_Intrested is
begin
if not Self.We_Intrested
and then Self.Listener.We_Are_Intrested (Self.Piece_Map)
then
Self.Send_Message ((00, 00, 00, 01, 02)); -- interested
Self.We_Intrested := True;
end if;
end Check_Intrested;
-------------------
-- Get_Handshake --
-------------------
function Get_Handshake
(Data : Ada.Streams.Stream_Element_Array) return Boolean
is
function "+" is new Ada.Unchecked_Conversion
(Handshake_Image, Handshake_Type);
HS : constant Handshake_Type := +Data (1 .. Handshake_Image'Length);
begin
if HS.Length = Header'Length
and then HS.Head = Header
and then HS.Info_Hash = Self.Meta.Info_Hash
then
Self.Got_Handshake := True;
Self.Unparsed.Clear;
Self.Unparsed.Append
(Data (Handshake_Image'Length + 1 .. Data'Last));
return True;
else
return False;
end if;
end Get_Handshake;
----------------
-- Get_Length --
----------------
function Get_Length
(Data : Ada.Streams.Stream_Element_Array)
return Ada.Streams.Stream_Element_Offset
is
subtype X is Ada.Streams.Stream_Element_Offset;
begin
return ((X (Data (Data'First)) * 256
+ X (Data (Data'First + 1))) * 256
+ X (Data (Data'First + 2))) * 256
+ X (Data (Data'First + 3));
end Get_Length;
----------------
-- On_Message --
----------------
procedure On_Message (Data : Ada.Streams.Stream_Element_Array) is
function Get_Int
(From : Ada.Streams.Stream_Element_Count := 0) return Natural
is (Get_Int (Data, From));
Index : Piece_Index;
begin
case Data (Data'First) is
when 0 => -- choke
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " choke"));
Self.We_Choked := True;
Self.Unreserve_Intervals;
when 1 => -- unchoke
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " unchoke"));
Self.We_Choked := False;
Send_Initial_Requests;
when 2 => -- interested
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " interested"));
Self.He_Intrested := True;
when 3 => -- not interested
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " not interested"));
Self.He_Intrested := False;
when 4 => -- have
declare
Index : constant Piece_Index :=
Piece_Index (Get_Int (1) + 1);
begin
if Index in Self.Piece_Map'Range then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer)
& " have" & (Index'Img)));
Self.Piece_Map (Index) := True;
Check_Intrested;
end if;
end;
when 5 => -- bitfield
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " bitfield"));
Index := 1;
Each_Byte :
for X of Data (Data'First + 1 .. Data'Last) loop
declare
use type Interfaces.Unsigned_8;
Byte : Interfaces.Unsigned_8 := Interfaces.Unsigned_8 (X);
begin
for J in 1 .. 8 loop
if (Byte and 16#80#) /= 0 then
Self.Piece_Map (Index) := True;
end if;
Byte := Interfaces.Shift_Left (Byte, 1);
Index := Index + 1;
exit Each_Byte when Index > Self.Piece_Count;
end loop;
end;
end loop Each_Byte;
Check_Intrested;
when 6 => -- request
declare
Next : Piece_Interval :=
(Piece => Piece_Count (Get_Int (1) + 1),
Span => (From => Piece_Offset (Get_Int (5)),
To => Piece_Offset (Get_Int (9))));
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " request"
& (Next.Piece'Img) & (Next.Span.From'Img)));
if Next.Span.To > Max_Interval_Size then
return;
else
Next.Span.To := Next.Span.From + Next.Span.To - 1;
end if;
if Next.Piece in Self.Piece_Map'Range
and then not Self.He_Choked
then
Self.Requests.Append (Next);
end if;
end;
when 7 => -- piece
declare
Index : constant Piece_Index :=
Piece_Index (Get_Int (1) + 1);
Offset : constant Natural := Get_Int (5);
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " piece"
& (Index'Img) & (Offset'Img)));
if Index in Self.Piece_Map'Range
and then Data'Length > 9
then
Save_Piece
(Index, Offset, Data (Data'First + 9 .. Data'Last));
end if;
end;
when 8 => -- cancel
declare
Next : Piece_Interval :=
(Piece => Piece_Count (Get_Int (1) + 1),
Span => (From => Piece_Offset (Get_Int (5)),
To => Piece_Offset (Get_Int (9))));
Cursor : Natural;
begin
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " cancel"
& (Next.Piece'Img) & (Next.Span.From'Img)));
Next.Span.To := Next.Span.From + Next.Span.To - 1;
Cursor := Self.Requests.Find_Index (Next);
if Cursor /= 0 then
Self.Requests.Swap (Cursor, Self.Requests.Last_Index);
Self.Requests.Delete_Last;
end if;
end;
when others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(GNAT.Sockets.Image (Self.Peer) & " unkown"
& (Data (Data'First)'Img)));
end case;
end On_Message;
-------------------
-- Read_Messages --
-------------------
procedure Read_Messages
(Data : in out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Count)
is
From : Ada.Streams.Stream_Element_Count := Data'First;
Length : Ada.Streams.Stream_Element_Count;
begin
loop
exit when Data'Length - From + 1 < 4;
Length := Get_Length (Data (From .. Data'Last));
exit when Data'Length - From + 1 < 4 + Length;
From := From + 4;
if Length > 0 then
On_Message (Data (From .. From + Length - 1));
From := From + Length;
else
Self.Send_Message ((00, 00, 00, 00)); -- keepalive
end if;
end loop;
if From > Data'First then
Last := Data'Length - From + 1;
Data (1 .. Last) := Data (From .. Data'Last);
else
Last := Data'Last;
end if;
end Read_Messages;
----------------
-- Save_Piece --
----------------
procedure Save_Piece
(Index : Piece_Index;
Offset : Natural;
Data : Ada.Streams.Stream_Element_Array)
is
procedure Swap (Left, Right : Piece_Interval_Count);
----------
-- Swap --
----------
procedure Swap (Left, Right : Piece_Interval_Count) is
Request : constant Piece_Interval :=
Self.Pipelined.Request.List (Left);
Expire : constant Natural := Self.Pipelined.Expire (Left);
begin
Self.Pipelined.Request.List (Left) :=
Self.Pipelined.Request.List (Right);
Self.Pipelined.Request.List (Right) := Request;
Self.Pipelined.Expire (Left) := Self.Pipelined.Expire (Right);
Self.Pipelined.Expire (Right) := Expire;
end Swap;
Last : Boolean;
From : constant Piece_Offset := Piece_Offset (Offset);
J : Natural := 1;
begin
Self.Downloaded := Self.Downloaded + Data'Length;
Self.Storage.Write
(Offset => Ada.Streams.Stream_Element_Count (Index - 1)
* Self.Meta.Piece_Length
+ Ada.Streams.Stream_Element_Count (Offset),
Data => Data);
Self.Listener.Interval_Saved
(Index, (From, From + Data'Length - 1), Last);
if Last then
if Self.Is_Valid_Piece (Index) then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Piece completed" & (Index'Img)));
Self.Listener.Piece_Completed (Index, True);
Self.Send_Have (Index);
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Piece FAILED!" & (Index'Img)));
Self.Listener.Piece_Completed (Index, False);
end if;
end if;
if Self.Current_Piece.Intervals.Is_Empty then
Self.Listener.Reserve_Intervals
(Map => Self.Piece_Map,
Value => Self.Current_Piece);
end if;
while J <= Self.Pipelined.Length loop
if Self.Pipelined.Request.List (J).Piece = Index
and Self.Pipelined.Request.List (J).Span.From = From
then
if Self.Current_Piece.Intervals.Is_Empty then
Swap (J, Self.Pipelined.Length);
Self.Pipelined :=
(Self.Pipelined.Length - 1,
Request =>
(Self.Pipelined.Length - 1,
Self.Pipelined.Request.List
(1 .. Self.Pipelined.Length - 1)),
Expire => Self.Pipelined.Expire
(1 .. Self.Pipelined.Length - 1));
else
declare
Last : constant Interval :=
Self.Current_Piece.Intervals.Last_Element;
begin
Self.Current_Piece.Intervals.Delete_Last;
Self.Pipelined.Request.List (J) :=
(Self.Current_Piece.Piece, Last);
Self.Pipelined.Expire (J) :=
Self.Pipelined.Length * Expire_Loops;
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural (Self.Current_Piece.Piece - 1)) &
To_Int (Natural (Last.From)) &
To_Int (Natural (Last.To - Last.From + 1)));
J := J + 1;
end;
end if;
else -- Check if some request was lost
Self.Pipelined.Expire (J) := Self.Pipelined.Expire (J) - 1;
if Self.Pipelined.Expire (J) = 0 then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print ("Re-send lost request:"));
Self.Pipelined.Expire (J) :=
Self.Pipelined.Length * Expire_Loops;
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural
(Self.Pipelined.Request.List (J).Piece - 1)) &
To_Int (Natural (Self.Pipelined.Request.List (J)
.Span.From)) &
To_Int (Natural (Self.Pipelined.Request.List (J)
.Span.To
- Self.Pipelined.Request.List (J)
.Span.From + 1)));
end if;
J := J + 1;
end if;
end loop;
end Save_Piece;
---------------------------
-- Send_Initial_Requests --
---------------------------
procedure Send_Initial_Requests is
Length : Piece_Interval_Count;
begin
if Self.Current_Piece.Intervals.Is_Empty then
Self.Listener.Reserve_Intervals
(Map => Self.Piece_Map,
Value => Self.Current_Piece);
end if;
Length := Piece_Interval_Count'Min
(Piece_Interval_Count'Last,
Self.Current_Piece.Intervals.Last_Index);
Self.Pipelined :=
(Length => Length,
Expire => (1 .. Length => Length * Expire_Loops),
Request => (Length, others => <>));
for J in 1 .. Length loop
declare
Last : constant Interval :=
Self.Current_Piece.Intervals.Last_Element;
Index : constant Piece_Index := Self.Current_Piece.Piece;
Offset : constant Piece_Offset := Last.From;
Length : constant Piece_Offset := Last.To - Offset + 1;
begin
Self.Send_Message
((00, 00, 00, 13, 06) &
To_Int (Natural (Index - 1)) &
To_Int (Natural (Offset)) &
To_Int (Natural (Length)));
Self.Pipelined.Request.List (J) :=
(Piece => Self.Current_Piece.Piece,
Span => (Offset, Last.To));
Self.Current_Piece.Intervals.Delete_Last;
end;
end loop;
end Send_Initial_Requests;
Completed : constant Piece_Index_Array := Self.Downloader.Completed;
Last : Ada.Streams.Stream_Element_Count := Self.Unparsed.Length;
Data : Ada.Streams.Stream_Element_Array (1 .. Max_Interval_Size + 20);
begin
if Self.Closed then
return;
end if;
if not Self.Choked_Sent then
Self.Choked_Sent := True;
if Self.He_Choked then
Self.Send_Message ((00, 00, 00, 01, 00)); -- choke
Self.Requests.Clear;
else
Self.Send_Message ((00, 00, 00, 01, 01)); -- unchoke
end if;
end if;
for J in Self.Last_Completed + 1 .. Completed'Last loop
Self.Send_Have (Completed (J));
end loop;
Self.Last_Completed := Completed'Last;
Data (1 .. Last) := Self.Unparsed.To_Stream_Element_Array;
Self.Unparsed.Clear;
loop
declare
Read : Ada.Streams.Stream_Element_Count;
begin
if Self.Closed then
return;
end if;
GNAT.Sockets.Receive_Socket
(Socket => Self.Socket,
Item => Data (Last + 1 .. Data'Last),
Last => Read);
if Read = Last then
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Closed on Read:" & GNAT.Sockets.Image (Self.Peer)));
Self.Close_Connection;
return;
else
Last := Read;
end if;
exception
when E : GNAT.Sockets.Socket_Error =>
if GNAT.Sockets.Resolve_Exception (E) in
GNAT.Sockets.Resource_Temporarily_Unavailable
then
null; -- Timeout on Read
else
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Read:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end if;
end;
if Self.Got_Handshake then
Read_Messages (Data (1 .. Last), Last);
elsif Last >= Handshake_Image'Length
and then Get_Handshake (Data (1 .. Last))
then
Data (1 .. Last - Handshake_Image'Length) :=
Data (Handshake_Image'Last + 1 .. Last);
Last := Last - Handshake_Image'Length;
Read_Messages (Data (1 .. Last), Last);
end if;
Self.Send_Pieces (Limit);
exit when Ada.Calendar.Clock > Limit;
end loop;
if Last > 0 then
Self.Unparsed.Append (Data (1 .. Last));
end if;
exception
when E : others =>
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
("Raised on Serve:" & GNAT.Sockets.Image (Self.Peer)));
pragma Debug
(Torrent.Logs.Enabled,
Torrent.Logs.Print
(Ada.Exceptions.Exception_Information (E)));
Self.Close_Connection;
return;
end Serve;
---------------
-- Serve_All --
---------------
procedure Serve_All
(Selector : GNAT.Sockets.Selector_Type;
Vector : in out Connection_Vectors.Vector;
Except : Connection_Access_Array;
Limit : Ada.Calendar.Time)
is
use type Ada.Calendar.Time;
Now : Ada.Calendar.Time;
Status : GNAT.Sockets.Selector_Status;
R_Set : GNAT.Sockets.Socket_Set_Type;
W_Set : GNAT.Sockets.Socket_Set_Type;
begin
loop
for C of Vector loop
if C.Connected
and then not (for some X of Except => X = C)
then
GNAT.Sockets.Set (R_Set, C.Socket);
end if;
end loop;
Now := Ada.Calendar.Clock;
if GNAT.Sockets.Is_Empty (R_Set) or Now >= Limit then
return;
end if;
GNAT.Sockets.Check_Selector
(Selector => Selector,
R_Socket_Set => R_Set,
W_Socket_Set => W_Set,
Status => Status,
Timeout => Limit - Now);
if Status in GNAT.Sockets.Completed then
for C of Vector loop
if C.Connected
and then GNAT.Sockets.Is_Set (R_Set, C.Socket)
then
GNAT.Sockets.Clear (R_Set, C.Socket);
C.Serve (Now);
end if;
end loop;
end if;
GNAT.Sockets.Empty (R_Set);
end loop;
end Serve_All;
------------------
-- Serve_Needed --
------------------
function Serve_Needed (Self : Connection'Class) return Boolean is
begin
return not Self.Choked_Sent;
end Serve_Needed;
----------------
-- Set_Choked --
----------------
procedure Set_Choked (Self : in out Connection'Class; Value : Boolean) is
begin
if Self.He_Choked /= Value then
Self.He_Choked := Value;
Self.Choked_Sent := not Self.Choked_Sent;
end if;
end Set_Choked;
-------------
-- To_Int --
-------------
function To_Int (Value : Natural) return Int_Buffer is
use type Interfaces.Unsigned_32;
Result : Int_Buffer;
Next : Interfaces.Unsigned_32 := Interfaces.Unsigned_32 (Value);
begin
for X of reverse Result loop
X := Ada.Streams.Stream_Element (Next mod 256);
Next := Interfaces.Shift_Right (Next, 8);
end loop;
return Result;
end To_Int;
-------------------------
-- Unreserve_Intervals --
-------------------------
procedure Unreserve_Intervals (Self : in out Connection'Class) is
Back : Piece_Interval_Array
(1 .. Self.Current_Piece.Intervals.Last_Index);
begin
for J in Back'Range loop
Back (J).Piece := Self.Current_Piece.Piece;
Back (J).Span := Self.Current_Piece.Intervals (J);
end loop;
Self.Listener.Unreserve_Intervals (Self.Pipelined.Request.List & Back);
Self.Current_Piece := (0, Interval_Vectors.Empty_Vector);
Self.Pipelined := (0, Request => (0, others => <>), Expire => <>);
end Unreserve_Intervals;
end Torrent.Connections;
|
------------------------------------------------------------------------------
-- Copyright (c) 2015, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Natools.Web.Escapes provdes primitives for HTML-style escaping. --
------------------------------------------------------------------------------
with Ada.Streams;
with Natools.S_Expressions.Atom_Refs;
package Natools.Web.Escapes is
pragma Preelaborate;
type Escape_Set is record
Gt_Lt : Boolean := False;
Amp : Boolean := False;
Apos : Boolean := False;
Quot : Boolean := False;
end record;
function Is_Empty (Set : in Escape_Set) return Boolean
is (Set.Gt_Lt or Set.Amp or Set.Apos or Set.Quot);
HTML_Attribute : constant Escape_Set;
HTML_Body : constant Escape_Set;
function Escaped_Length
(Data : in S_Expressions.Atom;
Set : in Escape_Set)
return S_Expressions.Count;
-- Return the number of octet in the escaped version of Data
procedure Write
(Output : in out Ada.Streams.Root_Stream_Type'Class;
Data : in S_Expressions.Atom;
Set : in Escape_Set);
-- Escape octets from Data in Set, and write them into Output
procedure Write
(Output : in out Ada.Streams.Root_Stream_Type'Class;
Text : in String;
Set : in Escape_Set);
-- Escape octets from Text in Set, and write them into Output
function Escape
(Data : in S_Expressions.Atom;
Set : in Escape_Set)
return S_Expressions.Atom;
-- Escape Data and return it directly as an atom
function Escape
(Data : in S_Expressions.Atom;
Set : in Escape_Set)
return S_Expressions.Atom_Refs.Immutable_Reference;
-- Escape Data and return it in a newly-created reference
function Escape
(Data : in S_Expressions.Atom_Refs.Immutable_Reference;
Set : in Escape_Set)
return S_Expressions.Atom_Refs.Immutable_Reference;
-- Escape Data if needed, otherwise duplicate the reference
private
type Atom_Stream (Data : not null access S_Expressions.Atom)
is new Ada.Streams.Root_Stream_Type
with record
Last : S_Expressions.Offset;
end record;
overriding procedure Read
(Stream : in out Atom_Stream;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
overriding procedure Write
(Stream : in out Atom_Stream;
Item : in Ada.Streams.Stream_Element_Array);
type Count_Stream is new Ada.Streams.Root_Stream_Type with record
Count : S_Expressions.Count := 0;
end record;
overriding procedure Read
(Stream : in out Count_Stream;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
overriding procedure Write
(Stream : in out Count_Stream;
Item : in Ada.Streams.Stream_Element_Array);
type Octet_Set is array (S_Expressions.Octet) of Boolean;
procedure Update_Set (Octets : in out Octet_Set; Set : in Escape_Set);
-- Convert an escape set to an octet set
HTML_Attribute : constant Escape_Set := (Apos => False, others => True);
HTML_Body : constant Escape_Set
:= (Gt_Lt | Amp => True, others => False);
end Natools.Web.Escapes;
|
package body calc with SPARK_Mode is
procedure Forgetful_Assert (X, Y : out Integer) with
SPARK_Mode
is
begin
X := 1;
Y := 2;
pragma Assert (X = 1);
pragma Assert (Y = 2);
pragma Assert_And_Cut (X > 0); -- also forgets about Y
pragma Assert (Y = 2);
pragma Assert (X > 0);
pragma Assert (X = 1);
end Forgetful_Assert;
end calc;
|
with Interfaces.C;
private with color_h;
package Libtcod.Color is
type RGB_Component is new Interfaces.C.unsigned_char;
type Alpha is new Interfaces.C.unsigned_char;
type Hue is new Float range 0.0 .. 360.0;
type Saturation is new Float range 0.0 .. 1.0;
type Value is new Float range 0.0 .. 1.0;
type Color_Factor is new Float;
-- A three channel color struct
type RGB_Color is private;
type RGBA_Color is private;
-- Constructors --
function make_RGB_color(r, g, b : RGB_Component) return RGB_Color;
function make_HSV_color(h : Hue; s : Saturation; v : Value) return RGB_Color;
-- Setters/getters --
procedure set_RGB(color : in out RGB_Color; r, g, b : RGB_Component) with Inline;
procedure set_RGBA(color : in out RGBA_Color; r, g, b : RGB_Component;
a : Alpha) with Inline;
procedure set_red(color : in out RGB_Color; r : RGB_Component) with Inline;
function get_red(color : RGB_Color) return RGB_Component with Inline;
procedure set_red(color : in out RGBA_Color; r : RGB_Component) with Inline;
function get_red(color : RGBA_Color) return RGB_Component with Inline;
procedure set_green(color : in out RGB_Color; g : RGB_Component) with Inline;
function get_green(color : RGB_Color) return RGB_Component with Inline;
procedure set_green(color : in out RGBA_Color; g : RGB_Component) with Inline;
function get_green(color : RGBA_Color) return RGB_Component with Inline;
procedure set_blue(color : in out RGB_Color; b : RGB_Component) with Inline;
function get_blue(color : RGB_Color) return RGB_Component with Inline;
procedure set_blue(color : in out RGBA_Color; b : RGB_Component) with Inline;
function get_blue(color : RGBA_Color) return RGB_Component with Inline;
procedure set_alpha(color : in out RGBA_Color; a : Alpha) with Inline;
function get_alpha(color : RGBA_Color) return Alpha with Inline;
-- HSV --
procedure set_HSV(color : aliased in out RGB_Color;
h : Hue; s : Saturation; v : Value) with Inline;
procedure get_HSV(color : RGB_Color;
h : out Hue; s : out Saturation; v : out Value) with Inline;
procedure set_hue(color : aliased in out RGB_Color; h : Hue);
function get_hue(color : RGB_Color) return Hue;
procedure set_saturation(color : aliased in out RGB_Color; s : Saturation);
function get_saturation(color : RGB_Color) return Saturation;
procedure set_value(color : aliased in out RGB_Color; v : Value);
function get_value(color : RGB_Color) return Value;
-- Operators --
function "="(a, b : RGB_Color) return Boolean
with Inline;
function "-"(a, b : RGB_Color) return RGB_Color
with Inline;
function "+"(a, b : RGB_Color) return RGB_Color
with Inline;
function "*"(a, b : RGB_Color) return RGB_Color
with Inline;
function "*"(a : RGB_Color; scalar : Color_Factor) return RGB_Color
with Inline;
-- Operations --
function interpolate(a, b : RGB_Color; coeff : Color_Factor) return RGB_Color
with Inline;
procedure shift_hue(color : aliased in out RGB_Color; shift : Hue);
procedure scale_HSV(color : aliased in out RGB_Color;
sat_coeff : Saturation; value_coeff : Value);
-- Constants --
-- grey levels
black : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_black";
darkest_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_grey";
darker_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_grey";
dark_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_grey";
grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_grey";
light_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_grey";
lighter_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_grey";
lightest_grey : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_grey";
darkest_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_gray";
darker_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_gray";
dark_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_gray";
gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_gray";
light_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_gray";
lighter_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_gray";
lightest_gray : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_gray";
white : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_white";
-- sepia
darkest_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_sepia";
darker_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_sepia";
dark_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_sepia";
sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_sepia";
light_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_sepia";
lighter_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_sepia";
lightest_sepia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_sepia";
-- standard colors
red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_red";
flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_flame";
orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_orange";
amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_amber";
yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_yellow";
lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lime";
chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_chartreuse";
green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_green";
sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_sea";
turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_turquoise";
cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_cyan";
sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_sky";
azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_azure";
blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_blue";
han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_han";
violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_violet";
purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_purple";
fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_fuchsia";
magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_magenta";
pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_pink";
crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_crimson";
-- dark colors
dark_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_red";
dark_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_flame";
dark_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_orange";
dark_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_amber";
dark_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_yellow";
dark_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_lime";
dark_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_chartreuse";
dark_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_green";
dark_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_sea";
dark_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_turquoise";
dark_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_cyan";
dark_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_sky";
dark_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_azure";
dark_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_blue";
dark_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_han";
dark_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_violet";
dark_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_purple";
dark_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_fuchsia";
dark_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_magenta";
dark_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_pink";
dark_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_dark_crimson";
-- darker colors
darker_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_red";
darker_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_flame";
darker_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_orange";
darker_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_amber";
darker_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_yellow";
darker_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_lime";
darker_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_chartreuse";
darker_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_green";
darker_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_sea";
darker_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_turquoise";
darker_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_cyan";
darker_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_sky";
darker_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_azure";
darker_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_blue";
darker_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_han";
darker_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_violet";
darker_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_purple";
darker_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_fuchsia";
darker_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_magenta";
darker_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_pink";
darker_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darker_crimson";
-- darkest colors
darkest_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_red";
darkest_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_flame";
darkest_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_orange";
darkest_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_amber";
darkest_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_yellow";
darkest_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_lime";
darkest_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_chartreuse";
darkest_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_green";
darkest_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_sea";
darkest_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_turquoise";
darkest_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_cyan";
darkest_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_sky";
darkest_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_azure";
darkest_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_blue";
darkest_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_han";
darkest_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_violet";
darkest_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_purple";
darkest_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_fuchsia";
darkest_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_magenta";
darkest_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_pink";
darkest_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_darkest_crimson";
-- light colors
light_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_red";
light_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_flame";
light_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_orange";
light_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_amber";
light_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_yellow";
light_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_lime";
light_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_chartreuse";
light_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_green";
light_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_sea";
light_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_turquoise";
light_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_cyan";
light_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_sky";
light_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_azure";
light_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_blue";
light_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_han";
light_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_violet";
light_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_purple";
light_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_fuchsia";
light_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_magenta";
light_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_pink";
light_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_light_crimson";
-- lighter colors
lighter_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_red";
lighter_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_flame";
lighter_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_orange";
lighter_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_amber";
lighter_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_yellow";
lighter_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_lime";
lighter_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_chartreuse";
lighter_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_green";
lighter_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_sea";
lighter_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_turquoise";
lighter_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_cyan";
lighter_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_sky";
lighter_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_azure";
lighter_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_blue";
lighter_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_han";
lighter_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_violet";
lighter_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_purple";
lighter_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_fuchsia";
lighter_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_magenta";
lighter_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_pink";
lighter_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lighter_crimson";
-- lightest colors
lightest_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_red";
lightest_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_flame";
lightest_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_orange";
lightest_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_amber";
lightest_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_yellow";
lightest_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_lime";
lightest_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_chartreuse";
lightest_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_green";
lightest_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_sea";
lightest_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_turquoise";
lightest_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_cyan";
lightest_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_sky";
lightest_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_azure";
lightest_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_blue";
lightest_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_han";
lightest_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_violet";
lightest_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_purple";
lightest_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_fuchsia";
lightest_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_magenta";
lightest_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_pink";
lightest_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_lightest_crimson";
-- desaturated
desaturated_red : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_red";
desaturated_flame : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_flame";
desaturated_orange : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_orange";
desaturated_amber : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_amber";
desaturated_yellow : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_yellow";
desaturated_lime : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_lime";
desaturated_chartreuse : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_chartreuse";
desaturated_green : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_green";
desaturated_sea : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_sea";
desaturated_turquoise : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_turquoise";
desaturated_cyan : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_cyan";
desaturated_sky : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_sky";
desaturated_azure : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_azure";
desaturated_blue : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_blue";
desaturated_han : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_han";
desaturated_violet : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_violet";
desaturated_purple : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_purple";
desaturated_fuchsia : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_fuchsia";
desaturated_magenta : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_magenta";
desaturated_pink : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_pink";
desaturated_crimson : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_desaturated_crimson";
-- metallic
brass : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_brass";
copper : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_copper";
gold : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_gold";
silver : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_silver";
-- miscellaneous
celadon : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_celadon";
peach : aliased constant RGB_Color
with Import => True,
Convention => C,
External_Name => "TCOD_peach";
private
type RGB_Color is new color_h.TCOD_ColorRGB;
type RGBA_Color is new color_h.TCOD_ColorRGBA;
end Libtcod.Color;
|
-- { dg-do compile }
with Text_IO; use Text_IO;
procedure Deferred_Const1 is
I : Integer := 16#20_3A_2D_28#;
S : constant string(1..4);
for S'address use I'address; -- { dg-warning "constant overlays a variable" }
pragma Import (Ada, S);
begin
Put_Line (S);
end;
|
-- Copyright (c) 2020-2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- 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 Ada.Text_IO;
with Ada.Directories;
with Ada.Strings.UTF_Encoding.Wide_Strings;
with Interfaces.C.Strings;
with GNAT.Directory_Operations;
with Tcl.Tk.Ada;
with Tcl.Tk.Ada.Widgets;
with Tcl.Tk.Ada.Widgets.TtkButton;
with Tcl.Tk.Ada.Widgets.TtkLabel;
with Config; use Config;
with CoreUI;
with Game;
package body Themes is
procedure Load_Themes is
use Ada.Text_IO;
use Ada.Directories;
use GNAT.Directory_Operations;
use Game;
Themes_Directories, Files: Search_Type;
Found_Directory, Found_File: Directory_Entry_Type;
Config_File: File_Type;
Raw_Data, Field_Name, Value: Unbounded_String := Null_Unbounded_String;
Equal_Index: Natural := 0;
Temp_Record: Theme_Record := Default_Theme;
begin
Temp_Record.Name := To_Unbounded_String(Source => "Default theme");
Temp_Record.File_Name :=
Data_Directory &
To_Unbounded_String(Source => "ui" & Dir_Separator & "theme.tcl");
Themes_Container.Include
(Container => Themes_List, Key => "steamsky", New_Item => Temp_Record);
Temp_Record := Default_Theme;
Start_Search
(Search => Themes_Directories,
Directory => To_String(Source => Themes_Directory), Pattern => "",
Filter => (Directory => True, others => False));
Load_Themes_Loop :
while More_Entries(Search => Themes_Directories) loop
Get_Next_Entry
(Search => Themes_Directories, Directory_Entry => Found_Directory);
if Simple_Name(Directory_Entry => Found_Directory) in "." | ".." then
goto End_Of_Load_Themes_Loop;
end if;
Start_Search
(Search => Files,
Directory => Full_Name(Directory_Entry => Found_Directory),
Pattern => "*.cfg");
Load_Config_Loop :
while More_Entries(Search => Files) loop
Get_Next_Entry(Search => Files, Directory_Entry => Found_File);
Open
(File => Config_File, Mode => In_File,
Name => Full_Name(Directory_Entry => Found_File));
Load_Config_Data_Loop :
while not End_Of_File(File => Config_File) loop
Raw_Data :=
To_Unbounded_String(Source => Get_Line(File => Config_File));
if Length(Source => Raw_Data) = 0 then
goto End_Of_Load_Config_Loop;
end if;
Equal_Index := Index(Source => Raw_Data, Pattern => "=");
Field_Name :=
Head(Source => Raw_Data, Count => Equal_Index - 2);
Value :=
Tail
(Source => Raw_Data,
Count => Length(Source => Raw_Data) - Equal_Index - 1);
if Field_Name = To_Unbounded_String(Source => "Name") then
Temp_Record.Name := Value;
elsif Field_Name =
To_Unbounded_String(Source => "FileName") then
Temp_Record.File_Name :=
To_Unbounded_String
(Source =>
Full_Name(Directory_Entry => Found_Directory) &
Dir_Separator) &
Value;
elsif Field_Name =
To_Unbounded_String(Source => "EnemyShipIcon") then
Temp_Record.Enemy_Ship_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "AttackOnBaseIcon") then
Temp_Record.Attack_On_Base_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "DiseaseIcon") then
Temp_Record.Disease_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "DoublePriceIcon") then
Temp_Record.Double_Price_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "FullDocksIcon") then
Temp_Record.Full_Docks_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "EnemyPatrolIcon") then
Temp_Record.Enemy_Patrol_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "TraderIcon") then
Temp_Record.Trader_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "FriendlyShipIcon") then
Temp_Record.Friendly_Ship_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "DeliverIcon") then
Temp_Record.Deliver_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "DestroyIcon") then
Temp_Record.Destroy_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "PatrolIcon") then
Temp_Record.Patrol_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "ExploreIcon") then
Temp_Record.Explore_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "PassengerIcon") then
Temp_Record.Passenger_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "PilotIcon") then
Temp_Record.Pilot_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "EngineerIcon") then
Temp_Record.Engineer_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "GunnerIcon") then
Temp_Record.Gunner_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "CrewTraderIcon") then
Temp_Record.Crew_Trader_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "RepairIcon") then
Temp_Record.Repair_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "UpgradeIcon") then
Temp_Record.Upgrade_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "CleanIcon") then
Temp_Record.Clean_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "ManufactureIcon") then
Temp_Record.Manufacture_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "MoveMapUpIcon") then
Temp_Record.Move_Map_Up_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "MoveMapDownIcon") then
Temp_Record.Move_Map_Down_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "MoveMapLeftIcon") then
Temp_Record.Move_Map_Left_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "MoveMapRightIcon") then
Temp_Record.Move_Map_Right_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "NoFuelIcon") then
Temp_Record.No_Fuel_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "NoFoodIcon") then
Temp_Record.No_Food_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "NoDrinksIcon") then
Temp_Record.No_Drinks_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "NotVisitedBaseIcon") then
Temp_Record.Not_Visited_Base_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "EmptyMapIcon") then
Temp_Record.Empty_Map_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "TargetIcon") then
Temp_Record.Target_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "StoryIcon") then
Temp_Record.Story_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
elsif Field_Name =
To_Unbounded_String(Source => "OverloadedIcon") then
Temp_Record.Overloaded_Icon :=
Wide_Character'Val
(Natural'Value
("16#" & To_String(Source => Value) & "#"));
end if;
<<End_Of_Load_Config_Loop>>
end loop Load_Config_Data_Loop;
Close(File => Config_File);
Themes_Container.Include
(Container => Themes_List,
Key => Simple_Name(Directory_Entry => Found_Directory),
New_Item => Temp_Record);
Temp_Record := Default_Theme;
end loop Load_Config_Loop;
End_Search(Search => Files);
<<End_Of_Load_Themes_Loop>>
end loop Load_Themes_Loop;
End_Search(Search => Themes_Directories);
if not Themes_List.Contains
(Key => To_String(Source => Game_Settings.Interface_Theme)) then
Game_Settings.Interface_Theme :=
To_Unbounded_String(Source => "steamsky");
end if;
end Load_Themes;
procedure Set_Theme is
use Ada.Strings.UTF_Encoding.Wide_Strings;
use Interfaces.C.Strings;
use Tcl.Tk.Ada.Widgets;
use Tcl.Tk.Ada.Widgets.TtkButton;
use Tcl.Tk.Ada.Widgets.TtkLabel;
use CoreUI;
Label: Ttk_Label := Get_Widget(pathName => Game_Header & ".nofuel");
Button: Ttk_Button :=
Get_Widget(pathName => Main_Paned & ".mapframe.buttons.show");
begin
Set_Theme_Loop :
for I in Themes_List.Iterate loop
if Themes_Container.Key(Position => I) /=
Game_Settings.Interface_Theme then
goto End_Of_Set_Theme_Loop;
end if;
Label.Name := New_String(Str => Game_Header & ".nofuel");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).No_Fuel_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".nofood");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).No_Food_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".nodrink");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).No_Drinks_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".overloaded");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Overloaded_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".pilot");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Pilot_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".engineer");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Engineer_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".gunner");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Gunner_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".talk");
configure
(Widgt => Label,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Crew_Trader_Icon) & "}");
Label.Name := New_String(Str => Game_Header & ".repairs");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Repair_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".upgrade");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Upgrade_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".clean");
configure
(Widgt => Label,
options =>
"-text {" & Encode(Item => "" & Themes_List(I).Clean_Icon) &
"}");
Label.Name := New_String(Str => Game_Header & ".crafting");
configure
(Widgt => Label,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Manufacture_Icon) & "}");
Button.Name :=
New_String(Str => Main_Paned & ".mapframe.buttons.show");
configure
(Widgt => Button,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Move_Map_Up_Icon) & "}");
Button.Name :=
New_String(Str => Main_Paned & ".mapframe.buttons.hide");
configure
(Widgt => Button,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Move_Map_Down_Icon) & "}");
Button.Name :=
New_String(Str => Main_Paned & ".mapframe.buttons.left");
configure
(Widgt => Button,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Move_Map_Left_Icon) & "}");
Button.Name :=
New_String(Str => Main_Paned & ".mapframe.buttons.right");
configure
(Widgt => Button,
options =>
"-text {" &
Encode(Item => "" & Themes_List(I).Move_Map_Right_Icon) & "}");
<<End_Of_Set_Theme_Loop>>
end loop Set_Theme_Loop;
end Set_Theme;
end Themes;
|
with Ada.Exceptions;
package Exception_Declarations is
Value_Exceed_Max : Exception;
Value_Exceed_Min : Exception;
Excecution_Time_Overun : Exception;
-- Gyro_Not_Available : Exception;
--Acc_Not_Available : Exception;
-- Like an object. *NOT* a type !
end Exception_Declarations;
|
with Racionalisok, Ada.Integer_Text_IO, Ada.Text_IO;
use Racionalisok, Ada.Integer_Text_IO, Ada.Text_IO;
procedure RacionalisDemo is
X: Racionalis := 1/2;
Y: Racionalis := 3/5;
R: Racionalis := 1/1;
-- X: Racionális := 3/4/5;
begin
--R := R / (R/2);
--Put( Szamlalo(R) );
--Put( '/' );
--Put( Nevezo(R) );
R := X + Y;
Put( Szamlalo(R) );
Put( '/' );
Put( Nevezo(R) );
end;
|
-- { dg-do compile }
-- { dg-options "-gnatws" }
procedure Bit_Packed_Array2 is
type Bit_Array is array (integer range <>) of Boolean;
pragma Pack(Bit_Array);
b1 : Bit_Array(1..64);
b2 : Bit_array(1..64);
res : Bit_array(1..64);
begin
if (not((not b1) or (not b2))) /= res then
null;
end if;
end;
|
pragma Ada_2005;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
package bmiintrin_h is
-- Copyright (C) 2010-2017 Free Software Foundation, Inc.
-- This file is part of GCC.
-- GCC 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, or (at your option)
-- any later version.
-- GCC 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.
-- 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/>.
-- skipped func __tzcnt_u16
-- skipped func __andn_u32
-- skipped func __bextr_u32
-- skipped func _bextr_u32
-- skipped func __blsi_u32
-- skipped func _blsi_u32
-- skipped func __blsmsk_u32
-- skipped func _blsmsk_u32
-- skipped func __blsr_u32
-- skipped func _blsr_u32
-- skipped func __tzcnt_u32
-- skipped func _tzcnt_u32
-- skipped func __andn_u64
-- skipped func __bextr_u64
-- skipped func _bextr_u64
-- skipped func __blsi_u64
-- skipped func _blsi_u64
-- skipped func __blsmsk_u64
-- skipped func _blsmsk_u64
-- skipped func __blsr_u64
-- skipped func _blsr_u64
-- skipped func __tzcnt_u64
-- skipped func _tzcnt_u64
end bmiintrin_h;
|
with Ada.Containers.Indefinite_Hashed_Maps,
Ada.Containers.Indefinite_Hashed_Sets,
Ada.Containers.Indefinite_Vectors,
Ada.Containers.Synchronized_Queue_Interfaces,
Ada.Containers.Unbounded_Synchronized_Queues,
Ada.Execution_Time,
Ada.Integer_Text_IO,
Ada.Real_Time,
Ada.Strings.Fixed,
Ada.Strings.Hash,
Ada.Strings.Unbounded,
Ada.Text_IO;
with Utils;
procedure Main is
use Ada.Execution_Time,
Ada.Real_Time,
Ada.Strings.Unbounded,
Ada.Text_IO;
use Utils;
subtype Big_Cave_Character is Character range 'A' .. 'Z';
subtype Small_Cave_Character is Character range 'a' .. 'z';
package Cave_Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive,
Element_Type => String,
"=" => "=");
use Cave_Vectors;
type Cave_Kind is (K_Start, K_Big, K_Small, K_End);
Start_Name : constant String := "start";
End_Name : constant String := "end";
-- Given the name of a node, it retreive the corresponding kind
function Get_Kind (Name : String) return Cave_Kind;
--------------
-- Get_Kind --
--------------
function Get_Kind (Name : String) return Cave_Kind is
begin
if Name = Start_Name then
return K_Start;
elsif Name = End_Name then
return K_End;
elsif Name (Name'First) in Big_Cave_Character then
return K_Big;
elsif Name (Name'First) in Small_Cave_Character then
return K_Small;
end if;
raise Constraint_Error with "Unexpected cave name: " & Name;
end Get_Kind;
type Cave_Info (Length : Positive) is record
Name : String (1 .. Length);
Kind : Cave_Kind;
Adjacent : Vector;
end record;
package Cave_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String,
Element_Type => Cave_Info,
Hash => Ada.Strings.Hash,
Equivalent_Keys => "=");
package String_Sets is new Ada.Containers.Indefinite_Hashed_Sets (Element_Type => String,
Hash => Ada.Strings.Hash,
Equivalent_Elements => "=",
"=" => "=");
type Cave_Explorer is record
Name : Unbounded_String;
Already_Visited_Small_Cave_Name : Unbounded_String;
Already_Visited_Small_Cave : String_Sets.Set;
end record;
package Explored_Cave_Interfaces is
new Ada.Containers.Synchronized_Queue_Interfaces
(Element_Type => Cave_Explorer);
package Explored_Cave_Queue is new Ada.Containers.Unbounded_Synchronized_Queues
(Queue_Interfaces => Explored_Cave_Interfaces);
File : File_Type;
Start_Time, End_Time : CPU_Time;
Execution_Duration : Time_Span;
File_Is_Empty : Boolean := True;
Result : Natural := Natural'First;
Nodes : Cave_Maps.Map := Cave_Maps.Empty_Map;
begin
Get_File (File);
-- Get all values
begin
while not End_Of_File (File) loop
declare
Str : constant String := Get_Line (File);
Separator_Index : constant Integer :=
Ada.Strings.Fixed.Index (Source => Str (1 .. Str'Last), Pattern => "-");
Node_1 : constant String := Str (1 .. Separator_Index - 1);
Node_2 : constant String := Str (Separator_Index + 1 .. Str'Last);
begin
declare
Cave_Node_1 : Cave_Info := (Length => Node_1'Length,
Name => Node_1,
Kind => Get_Kind (Node_1),
Adjacent => Empty_Vector);
Cave_Node_2 : Cave_Info := (Length => Node_2'Length,
Name => Node_2,
Kind => Get_Kind (Node_2),
Adjacent => Empty_Vector);
begin
if Nodes.Contains (Node_1) then
Cave_Node_1 := Nodes.Element (Node_1);
end if;
if Nodes.Contains (Node_2) then
Cave_Node_2 := Nodes.Element (Node_2);
end if;
Cave_Node_1.Adjacent.Append (Node_2);
Cave_Node_2.Adjacent.Append (Node_1);
Nodes.Include (Node_1, Cave_Node_1);
Nodes.Include (Node_2, Cave_Node_2);
end;
File_Is_Empty := False;
end;
end loop;
end;
-- Exit the program if there is no values
if File_Is_Empty then
Close_If_Open (File);
Put_Line ("The input file is empty.");
return;
end if;
-- Do the puzzle
Start_Time := Ada.Execution_Time.Clock;
Solve_Puzzle : declare
use Ada.Containers, Explored_Cave_Queue;
Current_Cave : Cave_Explorer;
Cave_Explorer_Queue : Explored_Cave_Queue.Queue;
begin
Current_Cave.Name := To_Unbounded_String (Start_Name);
Current_Cave.Already_Visited_Small_Cave_Name := Null_Unbounded_String;
Current_Cave.Already_Visited_Small_Cave.Include (Start_Name);
Cave_Explorer_Queue.Enqueue (Current_Cave);
while Cave_Explorer_Queue.Current_Use > 0 loop
Cave_Explorer_Queue.Dequeue (Current_Cave);
if Nodes.Element (To_String (Current_Cave.Name)).Kind = K_End then
Result := Result + 1;
goto Continue;
end if;
-- Get all adjacent nodes (cave) to explore them
for Node of Nodes.Element (To_String (Current_Cave.Name)).Adjacent loop
if not Current_Cave.Already_Visited_Small_Cave.Contains (Node) then
declare
Next_Already_Visited_Small_Cave : String_Sets.Set :=
String_Sets.Copy (Current_Cave.Already_Visited_Small_Cave);
begin
if Get_Kind (Node) = K_Small then
Next_Already_Visited_Small_Cave.Include (Node);
end if;
Cave_Explorer_Queue.Enqueue
((Name => To_Unbounded_String (Node),
Already_Visited_Small_Cave_Name => Current_Cave.Already_Visited_Small_Cave_Name,
Already_Visited_Small_Cave => Next_Already_Visited_Small_Cave));
end;
elsif Current_Cave.Already_Visited_Small_Cave_Name = Null_Unbounded_String
and Get_Kind (Node) = K_Small
then
Cave_Explorer_Queue.Enqueue
((Name => To_Unbounded_String (Node),
Already_Visited_Small_Cave_Name => To_Unbounded_String (Node),
Already_Visited_Small_Cave => Current_Cave.Already_Visited_Small_Cave));
end if;
end loop;
<<Continue>>
end loop;
end Solve_Puzzle;
End_Time := Ada.Execution_Time.Clock;
Execution_Duration := End_Time - Start_Time;
Put ("Result: ");
Ada.Integer_Text_IO.Put (Item => Result,
Width => 0);
New_Line;
Put_Line ("(Took " & Duration'Image (To_Duration (Execution_Duration) * 1_000_000) & "µs)");
exception
when others =>
Close_If_Open (File);
raise;
end Main;
|
package Packet is
Sensor_Reading_Tag : constant Natural := 6;
Voltage_Tag : constant Natural := 7;
Temperature_Tag : constant Natural := 8;
Humidity_Tag : constant Natural := 9;
Pressure_Tag : constant Natural := 10;
Lux_Tag : constant Natural := 11;
UV_Index_Tag : constant Natural := 12;
Motion_Tag : constant Natural := 13;
Sound_Level_Tag : constant Natural := 14;
CO2_Tag : constant Natural := 15;
Test_Packet_Tag : constant Natural := 64;
Heartbeat_Tag : constant Natural := 65;
Log_Message_Tag : constant Natural := 66;
Ping_Tag : constant Natural := 67;
Register_Value_Tag : constant Natural := 68;
Error_Message_Tag : constant Natural := 69;
Status_Cmd_Tag : constant Natural := 256;
Ping_Cmd_Tag : constant Natural := 257;
Reset_Cmd_Tag : constant Natural := 258;
end Packet;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
with Sessions;
with Configs;
with Rules;
with Rule_Lists;
package Config_Lists is
subtype Rule_Access is Rule_Lists.Rule_Access;
procedure Init;
-- Initialized the configuration list builder.
function Add
(Rule : in Rule_Access;
Dot : in Rules.Dot_Type) return Configs.Config_Access;
-- Add another configuration to the configuration list.
function Add_Basis
(Rule : in Rule_Access;
Dot : in Rules.Dot_Type) return Configs.Config_Access;
-- Add a basis configuration to the configuration List.
procedure Closure (Session : in Sessions.Session_Type);
-- Compute the closure of the configuration List.
procedure Sort;
-- Sort the configuration list.
procedure Sort_Basis;
-- Sort the basis configuration list.
function Xreturn return Configs.Config_Access;
-- Return a pointer to the head of the configuration list and
-- reset the List.
function Basis return Configs.Config_Access;
-- Return a pointer to the head of the configuration list and
-- reset the list.
procedure Eat (Config : in out Configs.Config_Access);
-- Free all elements of the given configuration List.
procedure Reset;
-- Initialized the configuration list Builder.
end Config_Lists;
|
-- The Village of Vampire by YT, このソースコードはNYSLです
with Ada.Calendar;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
with Tabula.Calendar;
with Tabula.Casts;
with Tabula.Villages;
package Vampire.Villages is
use Tabula.Villages;
Default_Long_Day_Duration : constant Duration := 2 * 24 * 60 * 60 * 1.0;
Default_Short_Day_Duration : constant Duration := 15 * 60.0;
Default_Night_Duration : constant Duration := 0.0;
Epilogue_Min_Duration : constant Duration := 60 * 60.0;
Vote_Duration : constant Duration := 5 * 60.0;
Speech_Simultaneous : constant Duration := 30.0;
Minimum_Number_Of_Persons : constant := 7;
Maximum_Number_Of_Persons : constant := 16;
Speech_Limit : constant := 20;
Encouraged_Speech_Limit : constant := 2;
Ghost_Limit : constant := 10;
Monologue_Limit : constant := 10;
Max_Length_Of_Message : constant := 1024;
-- オプションルール
type Vote_Mode is (Unsigned, Preliminary_And_Final);
type Execution_Mode is (
Dummy_Killed_And_From_First, Infection_And_From_First, From_First,
From_Second);
type Formation_Mode is (Public, Hidden);
type Attack_Mode is (Two, Nocturnal_Chain_Infecting, Unanimity);
type Vampire_Action_Set_Mode is (None, Gaze, Gaze_And_Cancel);
type Servant_Knowing_Mode is (None, Vampire_K, All_Vampires);
type Monster_Side_Mode is (Fixed, Shuffling, Gremlin);
type Daytime_Preview_Mode is (None, Role_Only, Message_Only, Role_And_Message);
type Doctor_Infected_Mode is (Cure, Find_Infection);
type Hunter_Silver_Bullet_Mode is (Target, Target_And_Self);
type Unfortunate_Mode is (None, Appear, Infected_Only);
type Obsolete_Teaming_Mode is (
Low_Density, Liner_2, Shuffling_Headless, Shuffling_Euro, Shuffling,
Shuffling_Gremlin, Hiding, Hiding_Gremlin);
Initial_Vote : constant Vote_Mode := Unsigned;
Initial_Execution : constant Execution_Mode := From_First;
Initial_Formation : constant Formation_Mode := Public;
Initial_Monster_Side : constant Monster_Side_Mode := Fixed;
Initial_Attack : constant Attack_Mode := Nocturnal_Chain_Infecting;
Initial_Vampire_Action_Set : constant Vampire_Action_Set_Mode := Gaze;
Initial_Servant_Knowing : constant Servant_Knowing_Mode := Vampire_K;
Initial_Daytime_Preview : constant Daytime_Preview_Mode := Message_Only;
Initial_Doctor_Infected : constant Doctor_Infected_Mode := Find_Infection;
Initial_Hunter_Silver_Bullet : constant Hunter_Silver_Bullet_Mode := Target_And_Self;
Initial_Unfortunate : constant Unfortunate_Mode := Infected_Only;
Initial_Obsolete_Teaming : constant Obsolete_Teaming_Mode := Shuffling;
Is_Obsolete_Teaming : constant array (Obsolete_Teaming_Mode) of Boolean := (
Liner_2 | Shuffling | Hiding => False,
Low_Density | Shuffling_Headless | Shuffling_Euro | Shuffling_Gremlin
| Hiding_Gremlin => True);
-- 配役
type Person_Role is (
Vampire_K, Vampire_Q, Vampire_J, Servant,
Inhabitant,
Loved_Inhabitant,
Unfortunate_Inhabitant,
Detective, Doctor, Astronomer, Hunter,
Lover, Sweetheart_M, Sweetheart_F,
Gremlin);
subtype Matrix_Role is Person_Role range Detective .. Hunter;
subtype Night_Role is Person_Role range Astronomer .. Hunter;
subtype Daytime_Role is Person_Role range Detective .. Doctor;
subtype Vampire_Role is Person_Role range Vampire_K .. Vampire_J;
type Role_Appearance is (None, Random, Force);
type Role_Appearances is
array (Unfortunate_Inhabitant .. Lover) of Role_Appearance;
type Role_Images is
array (Villages.Person_Role) of not null access constant String;
type Ability_State is (Disallowed, Allowed, Already_Used);
-- 参加者
type Requested_Role is (Random, Rest,
Inhabitant, Detective, Astronomer, Doctor, Hunter, Sweetheart,
Servant, Vampire,
Village_Side, Vampire_Side, Gremlin);
type Person_State is (Normal, Infected, Died);
type Person_Record is record
State : Person_State;
Vote : Person_Index'Base;
Provisional_Vote : Person_Index'Base; -- 仮投票
Candidate : Boolean; -- 投票の候補
Target : Person_Index'Base;
Special : Boolean;
Note : aliased Ada.Strings.Unbounded.Unbounded_String;
end record;
Default_Person_Record : constant Person_Record := (
State => Normal,
Vote => No_Person,
Provisional_Vote => No_Person,
Candidate => True,
Target => No_Person,
Special => False,
Note => Ada.Strings.Unbounded.Null_Unbounded_String);
package Person_Records is new Ada.Containers.Vectors (Natural, Person_Record);
type Person_Type is new Tabula.Villages.Person_Type with record
Request : Requested_Role;
Ignore_Request : Boolean;
Role : Person_Role;
Records : aliased Person_Records.Vector;
Commited : Boolean;
end record;
Empty_Person : constant Person_Type := (Casts.Empty_Person with
Id => Ada.Strings.Unbounded.Null_Unbounded_String,
Request => Random,
Ignore_Request => False,
Role => Inhabitant,
Records => Person_Records.Empty_Vector,
Commited => False);
package People is new Ada.Containers.Vectors (Person_Index, Person_Type);
-- ログ
type Message_Kind is (
Narration, -- ト書き
Escape, -- 村を出る
Escaped_Join, -- 村を出た者の参加
Escaped_Speech, -- 村を出た者の会話
Join, -- 参加
Speech, -- 通常会話
Monologue, -- 独り言
Ghost, -- 墓場
Howling, -- 夜間の会話
Howling_Blocked, -- 夜間の会話が妨害された
Action_Wake, -- 起こす
Action_Encourage, -- 促し
Action_Vampire_Gaze, -- 視線
Action_Vampire_Gaze_Blocked, -- 視線が妨害された
Action_Vampire_Cancel, -- 襲撃取り消し
Action_Vampire_Canceled, -- 自分の襲撃設定が取り消された
Doctor_Cure, -- 治療
Doctor_Cure_Preview, -- 治療
Doctor_Found_Infection, -- 感染を発見しただけ
Doctor_Found_Infection_Preview, -- 感染を発見しただけ
Doctor_Failed, -- 診察はしたが感染させられた患者では無かった
Doctor_Failed_Preview, -- 診察はしたが感染させられた患者では無かった
Doctor_Found_Gremlin, -- 妖魔を見つけた
Doctor_Found_Gremlin_Preview, -- 妖魔を見つけた
Detective_Survey, -- 調査
Detective_Survey_Preview, -- 調査
Detective_Survey_Victim, -- 初日犠牲者の調査
Preliminary_Vote, -- 一次開票
Execution, -- 処刑
Awareness, -- 自覚
Astronomer_Observation, -- 観測
Meeting, -- 吸血鬼の会話
Vampire_Infection_In_First, -- 初日の感染
Vampire_Failed_In_First, -- 初日の感染に失敗
Vampire_Murder, -- 襲撃
Vampire_Murder_And_Killed, -- 襲撃に成功し相打ちで銀の弾丸を撃ちこまれた
Vampire_Infection, -- 感染
Vampire_Infection_And_Killed, -- 感染に成功し相打ちで銀の弾丸を撃ちこまれた
Vampire_Failed, -- 襲撃に失敗
Vampire_Failed_And_Killed, -- 襲撃に失敗し銀の弾丸を撃ちこまれた
Hunter_Guard_No_Response, -- 護衛していた(手応えなし)
Hunter_Guard, -- 護衛に成功した
Hunter_Guard_With_Silver, -- 護衛に成功し銀の弾丸を撃ちこんだ
Hunter_Nothing_With_Silver, -- 銀の弾丸を込めていたが何も無かった
Hunter_Infected_With_Silver, -- 誰かを護衛していたわけではないが自分が襲われたので銀の弾丸で反撃した
Hunter_Killed_With_Silver, -- 銀の弾丸で相打ち
Hunter_Failed, -- ガードしたが吸血鬼は来なかった
Hunter_Failed_With_Silver, -- ガードしたが吸血鬼は来ず銀の弾丸を無駄遣いした
Gremlin_Sense, -- 妖魔が吸血鬼の残数を知る
Sweetheart_Incongruity, -- 違和感
Sweetheart_Suicide, -- 後追い
Servant_Knew_Vampire_K, -- Kを知る
Servant_Knew_Vampires, -- 吸血鬼全員を知る
List, -- 一覧
Foreboding, -- 初日感染の公開メッセージ
Introduction, -- 序文
Breakdown); -- 開始
subtype Action_Message_Kind is
Message_Kind range Action_Wake .. Action_Vampire_Gaze_Blocked;
subtype Doctor_Message_Kind is
Message_Kind range Doctor_Cure .. Doctor_Found_Gremlin_Preview;
subtype Detective_Message_Kind is
Message_Kind range Detective_Survey .. Detective_Survey_Victim;
subtype Hunter_Message_Kind is
Message_Kind range Hunter_Guard_No_Response .. Hunter_Failed_With_Silver;
subtype Vampire_Message_Kind is
Message_Kind range Vampire_Infection_In_First .. Vampire_Failed_And_Killed;
subtype Servant_Message_Kind is
Message_Kind range Servant_Knew_Vampire_K .. Servant_Knew_Vampires;
type Message is record
Day : Integer;
Time : Ada.Calendar.Time;
Kind : Message_Kind;
Subject : Person_Index'Base;
Target : Person_Index'Base;
Text : aliased Ada.Strings.Unbounded.Unbounded_String;
end record;
Default_Message : constant Message := (
Day => -1,
Time => Calendar.Null_Time,
Kind => Narration,
Subject => No_Person,
Target => No_Person,
Text => Ada.Strings.Unbounded.Null_Unbounded_String);
package Messages is new Ada.Containers.Vectors (Message_Index, Message);
type Message_Count is record
Speech, Monologue, Ghost : Natural;
Wake, Encourage, Encouraged, Vampire_Gaze, Vampire_Cancel : Natural;
Last_Action_Time : Ada.Calendar.Time ;
end record;
type Message_Counts is array (Person_Index range <>) of Message_Count;
type Voted_Counts is array (Person_Index range <>) of Natural;
type Voted_Count_Info (Last : Person_Index'Base) is record
Max : Natural;
Counts : Voted_Counts (Person_Index'First .. Last);
end record;
type Vote_State_Type is (Disallowed, Allowed_For_Preliminary, Allowed);
-- 村
type Village_Time is (Daytime, Vote, Night);
type Village_Type is limited new Tabula.Villages.Village_Type with record
Day_Duration : Duration := Default_Long_Day_Duration;
Night_Duration : Duration := Default_Night_Duration;
State : Village_State := Prologue;
Today : Integer := 0;
Time : Village_Time := Daytime;
Dawn : Ada.Calendar.Time := Calendar.Null_Time;
-- 更新時刻(1日目は夜を飛ばすため調整)
Vote : Vote_Mode := Unsigned;
Execution : Execution_Mode := From_First;
Formation : Formation_Mode := Public;
Monster_Side : Monster_Side_Mode := Fixed;
Attack : Attack_Mode := Two;
Vampire_Action_Set : Vampire_Action_Set_Mode := Gaze;
Servant_Knowing : Servant_Knowing_Mode := None;
Daytime_Preview : Daytime_Preview_Mode := Role_And_Message;
Doctor_Infected : Doctor_Infected_Mode := Cure;
Hunter_Silver_Bullet : Hunter_Silver_Bullet_Mode := Target_And_Self;
Unfortunate : Unfortunate_Mode := None;
Obsolete_Teaming : Obsolete_Teaming_Mode := Shuffling_Headless;
Appearance : Role_Appearances := (others => Random);
Dummy_Role : aliased Person_Role := Inhabitant;
People : aliased Villages.People.Vector;
Escaped_People : aliased Villages.People.Vector;
Messages : aliased Villages.Messages.Vector;
end record;
-- 作成
function Create (
Name : String;
By : String;
Term : Village_Term;
Time : Ada.Calendar.Time)
return Village_Type;
-- 発言数
function Count_Messages (Village : Village_Type; Day : Natural)
return Message_Counts;
-- 更新予定時刻
function Night_To_Daytime (Village : Village_Type) return Ada.Calendar.Time;
function Infection_In_First_Time (Village : Village_Type)
return Ada.Calendar.Time;
function Preliminary_Vote_Time (Village : Village_Type)
return Ada.Calendar.Time;
function Daytime_To_Vote (Village : Village_Type) return Ada.Calendar.Time;
function Vote_To_Night (Village : Village_Type) return Ada.Calendar.Time;
function No_Commit (Village : Village_Type) return Boolean;
function Commit_Finished (Village : Village_Type) return Boolean;
-- 参加
procedure Join (
Village : in out Village_Type;
Id : in String;
Group : in Casts.Group;
Figure : in Casts.Person;
Work : in Casts.Work;
Request : in Requested_Role;
Ignore_Request : in Boolean;
Time : in Ada.Calendar.Time);
-- 村抜け
function Escape_Duration (Village : Village_Type) return Duration;
procedure Escape (
Village : in out Village_Type;
Subject : in Person_Index;
Time : in Ada.Calendar.Time);
-- 投票
function Vote_State (Village : Village_Type) return Vote_State_Type;
function Vote_Finished (Village : Village_Type) return Boolean;
function Voted_Count (
Village : Village_Type;
Day : Natural;
Preliminary : Boolean)
return Voted_Count_Info;
procedure Vote (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index'Base);
-- アクション
function Can_Gaze (Village : Village_Type) return Boolean;
procedure Wake (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index;
Time : in Ada.Calendar.Time);
procedure Encourage (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index;
Time : in Ada.Calendar.Time);
procedure Vampire_Gaze (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index;
Time : in Ada.Calendar.Time);
procedure Vampire_Cancel (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index;
Time : in Ada.Calendar.Time);
-- 能力者
function Infected_In_First (Village : Village_Type) return Boolean;
function Is_Anyone_Died (Village : Village_Type; Day : Natural)
return Boolean;
function Find_Superman (Village : Village_Type; Role : Person_Role)
return Person_Index'Base;
function Target_Day (Village : Village_Type) return Integer;
function Astronomer_Target_Day (Village : Village_Type) return Integer;
function Already_Used_Special (Village : Village_Type; Subject : Person_Index)
return Boolean;
function Detective_State (Village : Village_Type; Subject : Person_Index)
return Ability_State;
function Doctor_State (Village : Village_Type; Subject : Person_Index)
return Ability_State;
function Superman_State (Village : Village_Type; Subject : Person_Index)
return Ability_State;
function Silver_Bullet_State (Village : Village_Type; Subject : Person_Index)
return Ability_State;
procedure Select_Target (
Village : in out Village_Type;
Subject : in Person_Index;
Target : in Person_Index'Base;
Special : in Boolean := False;
Time : in Ada.Calendar.Time);
procedure Night_Talk (
Village : in out Village_Type;
Subject : in Person_Index;
Text : in String;
Time : in Ada.Calendar.Time);
-- 会話
procedure Speech (
Village : in out Village_Type;
Subject : in Person_Index;
Text : in String;
Time : in Ada.Calendar.Time);
procedure Monologue (
Village : in out Village_Type;
Subject : in Person_Index;
Text : in String;
Time : in Ada.Calendar.Time);
procedure Ghost (
Village : in out Village_Type;
Subject : in Person_Index;
Text : in String;
Time : in Ada.Calendar.Time);
-- Administrator操作
procedure Narration (
Village : in out Village_Type;
Text : in String;
Time : in Ada.Calendar.Time);
overriding function Term (Village : Village_Type) return Village_Term;
overriding procedure Get_State (
Village : in Village_Type;
State : out Village_State;
Today : out Natural);
overriding procedure Iterate_People (
Village : in Village_Type;
Process : not null access procedure (
Index : Person_Index;
Item : in Tabula.Villages.Person_Type'Class));
overriding procedure Iterate_Escaped_People (
Village : in Village_Type;
Process : not null access procedure (
Index : Person_Index;
Item : in Tabula.Villages.Person_Type'Class));
overriding function Speech_Range (
Village : Village_Type;
Day : Natural)
return Speech_Range_Type;
overriding function Recent_Only_Speech_Range (
Village : Village_Type;
Day : Natural;
Now : Ada.Calendar.Time)
return Speech_Range_Type;
overriding procedure Iterate_Options (
Village : in Village_Type;
Process : not null access procedure (
Item : in Root_Option_Item'Class));
package Options is
package Day_Duration is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Day_Duration;
package Night_Duration is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Night_Duration;
package Vote is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Vote;
package Execution is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Execution;
package Formation is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Formation;
package Monster_Side is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Monster_Side;
package Attack is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Attack;
package Vampire_Action_Set is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Vampire_Action_Set;
package Servant_Knowing is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Servant_Knowing;
package Daytime_Preview is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Daytime_Preview;
package Doctor_Infected is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Doctor_Infected;
package Hunter_Silver_Bullet is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Hunter_Silver_Bullet;
package Unfortunate is
type Option_Item (Village : not null access constant Village_Type) is
new Root_Option_Item with null record;
overriding function Available (Item : Option_Item) return Boolean;
overriding function Name (Item : Option_Item) return String;
overriding function Changed (Item : Option_Item) return Boolean;
overriding procedure Iterate (
Item : in Option_Item;
Process : not null access procedure (
Value : in String;
Selected : in Boolean;
Message : in String;
Unrecommended : in Boolean));
overriding procedure Change (
Village : in out Tabula.Villages.Village_Type'Class;
Item : in Option_Item;
Value : in String);
end Unfortunate;
end Options;
end Vampire.Villages;
|
--
-- Copyright (c) 2007-2011 Tero Koskinen <tero.koskinen@iki.fi>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ada.Strings;
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with Ada.Exceptions;
with Ahven.Long_AStrings;
with Util.Measures;
with Util.Log.Loggers;
package body Ahven.Framework is
use Ahven.AStrings;
procedure Log_Test_Start (Name : in String);
procedure Log_Test_End;
procedure Log_Test_Fail;
procedure Log_Test_Timeout;
-- A few local procedures, so we do not need to duplicate code.
procedure Free_Test is
new Ada.Unchecked_Deallocation (Object => Test'Class,
Name => Test_Class_Access);
generic
with procedure Action is <>;
procedure Execute_Internal
(Test_Object : in out Test'Class;
Listener_Object : in out Listeners.Result_Listener'Class);
-- Logic for Execute procedures. Action is specified by the caller.
-- When `Log_Enable_Flag` is set, a message is printed before immediately running
-- a test and after its execution. Such verbose execution is intended to help in
-- trouble shotting test execution when nasty problem occurs (timeout, crashes, ...).
Log_Output_File : constant Ada.Text_IO.File_Type := Ada.Text_IO.Standard_Output;
Log_Enable_Flag : Boolean := False;
procedure Set_Logging (Flag : in Boolean) is
begin
Log_Enable_Flag := Flag;
end Set_Logging;
procedure Log_Test_Start (Name : in String) is
begin
if Log_Enable_Flag then
Ada.Text_IO.Put (Log_Output_File, "Run '");
Ada.Text_IO.Put (Log_Output_File, Name);
Ada.Text_IO.Put (Log_Output_File, "' ...");
end if;
exception
when others =>
null; -- corruption guard: we don't want exceptions to be raised here.
end Log_Test_Start;
procedure Log_Test_End is
begin
if Log_Enable_Flag then
Ada.Text_IO.Put_Line (Log_Output_File, ": PASS");
end if;
exception
when others =>
null; -- corruption guard: we don't want exceptions to be raised here.
end Log_Test_End;
procedure Log_Test_Fail is
begin
if Log_Enable_Flag then
Ada.Text_IO.Put_Line (Log_Output_File, ": FAIL");
end if;
exception
when others =>
null; -- corruption guard: we don't want exceptions to be raised here.
end Log_Test_Fail;
procedure Log_Test_Timeout is
begin
if Log_Enable_Flag then
Ada.Text_IO.Put_Line (Log_Output_File, ": TIMEOUT");
end if;
exception
when others =>
null; -- corruption guard: we don't want exceptions to be raised here.
end Log_Test_Timeout;
procedure Set_Up (T : in out Test) is
begin
null; -- empty by default
end Set_Up;
procedure Tear_Down (T : in out Test) is
begin
null; -- empty by default
end Tear_Down;
procedure Run (T : in out Test;
Listener : in out Listeners.Result_Listener'Class) is
begin
Run (T => Test'Class (T), Listener => Listener, Timeout => 0.0);
end Run;
procedure Run (T : in out Test;
Test_Name : String;
Listener : in out Listeners.Result_Listener'Class) is
begin
Run (T => Test'Class (T),
Test_Name => Test_Name,
Listener => Listener,
Timeout => 0.0);
end Run;
procedure Execute_Internal
(Test_Object : in out Test'Class;
Listener_Object : in out Listeners.Result_Listener'Class)
is
use Ahven.Listeners;
begin
-- This Start_Test here is called for Test_Suites and Test_Cases.
-- Info includes only the name of the test suite/case.
--
-- There is a separate Start_Test/End_Test pair for test routines
-- in the Run (T : in out Test_Case; ...) procedure.
Listeners.Start_Test
(Listener_Object,
(Phase => TEST_BEGIN,
Test_Name => To_Bounded_String (Get_Name (Test_Object)),
Test_Kind => CONTAINER));
Action;
-- Like Start_Test, only for Test_Suites and Test_Cases.
Listeners.End_Test
(Listener_Object,
(Phase => TEST_END,
Test_Name => To_Bounded_String (Get_Name (Test_Object)),
Test_Kind => CONTAINER));
end Execute_Internal;
procedure Execute (T : in out Test'Class;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration) is
procedure Run_Impl is
begin
Run (T, Listener, Timeout);
end Run_Impl;
procedure Execute_Impl is new Execute_Internal (Action => Run_Impl);
begin
Execute_Impl (Test_Object => T, Listener_Object => Listener);
end Execute;
procedure Execute (T : in out Test'Class;
Test_Name : String;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration) is
procedure Run_Impl is
begin
Run (T => T,
Test_Name => Test_Name,
Listener => Listener,
Timeout => Timeout);
end Run_Impl;
procedure Execute_Impl is new Execute_Internal (Action => Run_Impl);
begin
Execute_Impl (Test_Object => T, Listener_Object => Listener);
end Execute;
----------- Test_Case ------------------------------
-- Wrap an "object" routine inside a Test_Command record
-- and add it to the test command list.
--
-- Name of the test will be silently cut if it does not
-- fit completely into AStrings.Bounded_String.
procedure Add_Test_Routine (T : in out Test_Case'Class;
Routine : Object_Test_Routine_Access;
Name : String)
is
Command : constant Test_Command :=
(Command_Kind => OBJECT,
Name => To_Bounded_String
(Source => Name,
Drop => Ada.Strings.Right),
Object_Routine => Routine);
begin
Test_Command_List.Append (T.Routines, Command);
end Add_Test_Routine;
-- Wrap a "simple" routine inside a Test_Command record
-- and add it to the test command list.
--
-- Name of the test will be silently cut if it does not
-- fit completely into AStrings.Bounded_String.
procedure Add_Test_Routine (T : in out Test_Case'Class;
Routine : Simple_Test_Routine_Access;
Name : String)
is
Command : constant Test_Command :=
(Command_Kind => SIMPLE,
Name => To_Bounded_String
(Source => Name,
Drop => Ada.Strings.Right),
Simple_Routine => Routine);
begin
Test_Command_List.Append (T.Routines, Command);
end Add_Test_Routine;
-- The heart of the package.
-- Run one test routine (well, Command at this point) and
-- notify listeners about the result.
procedure Run_Command (Command : Test_Command;
Info : Listeners.Context;
Timeout : Test_Duration;
Listener : in out Listeners.Result_Listener'Class;
T : in out Test_Case'Class) is
use Ahven.Listeners;
use Ahven.Long_AStrings;
type Test_Status is
(TEST_PASS, TEST_FAIL, TEST_ERROR, TEST_TIMEOUT, TEST_SKIP);
protected type Test_Results is
function Get_Status return Test_Status;
procedure Set_Status (Value : Test_Status);
function Get_Message return AStrings.Bounded_String;
procedure Set_Message (Value : AStrings.Bounded_String);
function Get_Long_Message return Long_AStrings.Bounded_String;
procedure Set_Long_Message (Value : Long_AStrings.Bounded_String);
private
Status : Test_Status := TEST_ERROR;
Message : AStrings.Bounded_String;
Long_Message : Long_AStrings.Bounded_String;
end Test_Results;
protected body Test_Results is
function Get_Status return Test_Status is
begin
return Status;
end Get_Status;
procedure Set_Status (Value : Test_Status) is
begin
Status := Value;
end Set_Status;
function Get_Message return AStrings.Bounded_String is
begin
return Message;
end Get_Message;
procedure Set_Message (Value : AStrings.Bounded_String) is
begin
Message := Value;
end Set_Message;
function Get_Long_Message return Long_AStrings.Bounded_String is
begin
return Long_Message;
end Get_Long_Message;
procedure Set_Long_Message (Value : Long_AStrings.Bounded_String) is
begin
Long_Message := Value;
end Set_Long_Message;
end Test_Results;
Result : Test_Results;
-- In order to collect all the performance measures in a same set, use the same
-- measure set on the test running task and on the main task. This allows us to
-- save all the measures together in an XML result file at the end.
Perf : constant Util.Measures.Measure_Set_Access := Util.Measures.Get_Current;
task type Command_Task is
entry Start_Command;
entry End_Command;
end Command_Task;
procedure Run_A_Command is
procedure Set_Status (S : Test_Status;
Message : String;
Long_Message : String;
R : in out Test_Results)
is
begin
R.Set_Status (S);
R.Set_Message (To_Bounded_String
(Source => Message,
Drop => Ada.Strings.Right));
R.Set_Long_Message (To_Bounded_String
(Source => Long_Message,
Drop => Ada.Strings.Right));
end Set_Status;
begin
Util.Measures.Set_Current (Perf);
begin
Run (Command, T);
Result.Set_Status (TEST_PASS);
exception
when E : Assertion_Error =>
Set_Status
(S => TEST_FAIL,
Message => Ada.Exceptions.Exception_Message (E),
Long_Message => Util.Log.Loggers.Traceback (E),
R => Result);
when E : Test_Skipped_Error =>
Set_Status
(S => TEST_SKIP,
Message => Ada.Exceptions.Exception_Message (E),
Long_Message => Util.Log.Loggers.Traceback (E),
R => Result);
when E : others =>
Set_Status
(S => TEST_ERROR,
Message => Ada.Exceptions.Exception_Message (E),
Long_Message => Util.Log.Loggers.Traceback (E),
R => Result);
end;
end Run_A_Command;
task body Command_Task is
begin
accept Start_Command;
Run_A_Command;
accept End_Command;
end Command_Task;
Status : Test_Status;
begin
if Timeout > 0.0 then
declare
Command_Runner : Command_Task;
begin
Command_Runner.Start_Command;
select
Command_Runner.End_Command;
or
delay Duration (Timeout);
Log_Test_Timeout;
abort Command_Runner;
Result.Set_Status (TEST_TIMEOUT);
end select;
end;
else
Run_A_Command;
end if;
Status := Result.Get_Status;
case Status is
when TEST_PASS =>
Listeners.Add_Pass (Listener, Info);
when TEST_FAIL =>
Listeners.Add_Failure
(Listener,
(Phase => TEST_RUN,
Test_Name => Info.Test_Name,
Test_Kind => CONTAINER,
Routine_Name => Info.Routine_Name,
Message => Result.Get_Message,
Long_Message => Long_AStrings.Null_Bounded_String));
when TEST_ERROR =>
Listeners.Add_Error
(Listener,
(Phase => Listeners.TEST_RUN,
Test_Name => Info.Test_Name,
Test_Kind => CONTAINER,
Routine_Name => Info.Routine_Name,
Message => Result.Get_Message,
Long_Message => Result.Get_Long_Message));
when TEST_TIMEOUT =>
Listeners.Add_Error
(Listener,
(Phase => Listeners.TEST_RUN,
Test_Name => Info.Test_Name,
Test_Kind => CONTAINER,
Routine_Name => Info.Routine_Name,
Message => To_Bounded_String ("TIMEOUT"),
Long_Message => Long_AStrings.Null_Bounded_String));
when TEST_SKIP =>
Listeners.Add_Skipped
(Listener,
(Phase => TEST_RUN,
Test_Name => Info.Test_Name,
Test_Kind => CONTAINER,
Routine_Name => Info.Routine_Name,
Message => Result.Get_Message,
Long_Message => Long_AStrings.Null_Bounded_String));
end case;
end Run_Command;
function Get_Name (T : Test_Case) return String is
begin
return To_String (T.Name);
end Get_Name;
procedure Run_Internal
(T : in out Test_Case;
Listener : in out Listeners.Result_Listener'Class;
Command : Test_Command;
Test_Name : String;
Routine_Name : String;
Timeout : Test_Duration)
is
use Ahven.Listeners;
begin
Listeners.Start_Test
(Listener,
(Phase => Ahven.Listeners.TEST_BEGIN,
Test_Name => To_Bounded_String (Test_Name),
Test_Kind => ROUTINE));
Run_Command (Command => Command,
Info =>
(Phase => Listeners.TEST_RUN,
Test_Name => To_Bounded_String (Test_Name),
Test_Kind => ROUTINE,
Routine_Name =>
To_Bounded_String (Routine_Name),
Message => AStrings.Null_Bounded_String,
Long_Message => Long_AStrings.Null_Bounded_String),
Timeout => Timeout,
Listener => Listener,
T => T);
Listeners.End_Test
(Listener,
(Phase => Ahven.Listeners.TEST_END,
Test_Name => To_Bounded_String (Test_Name),
Test_Kind => ROUTINE));
end Run_Internal;
-- Run procedure for Test_Case.
--
-- Loops over the test routine list and executes the routines.
procedure Run (T : in out Test_Case;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration)
is
procedure Exec (Cmd : in out Test_Command) is
begin
Run_Internal (T => T,
Listener => Listener,
Command => Cmd,
Timeout => Timeout,
Test_Name => Get_Name (T),
Routine_Name => To_String (Cmd.Name));
end Exec;
procedure Run_All is new Test_Command_List.For_Each
(Action => Exec);
begin
Run_All (T.Routines);
end Run;
-- Purpose of the procedure is to run all
-- test routines with name Test_Name.
procedure Run (T : in out Test_Case;
Test_Name : String;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration)
is
procedure Exec (Cmd : in out Test_Command) is
begin
if To_String (Cmd.Name) = Test_Name then
Run_Internal (T => T,
Listener => Listener,
Command => Cmd,
Timeout => Timeout,
Test_Name => Get_Name (T),
Routine_Name => To_String (Cmd.Name));
end if;
end Exec;
procedure Run_All is new Test_Command_List.For_Each (Action => Exec);
begin
Run_All (T.Routines);
end Run;
function Test_Count (T : Test_Case) return Test_Count_Type is
begin
return Test_Count_Type (Test_Command_List.Length (T.Routines));
end Test_Count;
function Test_Count (T : Test_Case; Test_Name : String)
return Test_Count_Type
is
Counter : Test_Count_Type := 0;
procedure Increase (Cmd : in out Test_Command) is
begin
if To_String (Cmd.Name) = Test_Name then
Counter := Counter + 1;
end if;
end Increase;
procedure Count_Commands is new
Test_Command_List.For_Each (Action => Increase);
begin
Count_Commands (T.Routines);
return Counter;
end Test_Count;
procedure Finalize (T : in out Test_Case) is
begin
Test_Command_List.Clear (T.Routines);
end Finalize;
procedure Set_Name (T : in out Test_Case; Name : String) is
begin
T.Name := To_Bounded_String (Source => Name, Drop => Ada.Strings.Right);
end Set_Name;
----------- Test_Suite -----------------------------
function Create_Suite (Suite_Name : String)
return Test_Suite_Access is
begin
return
new Test_Suite'
(Ada.Finalization.Controlled with
Suite_Name => To_Bounded_String
(Source => Suite_Name,
Drop => Ada.Strings.Right),
Test_Cases => Test_List.Empty_List,
Static_Test_Cases => Indefinite_Test_List.Empty_List);
end Create_Suite;
function Create_Suite (Suite_Name : String)
return Test_Suite is
begin
return (Ada.Finalization.Controlled with
Suite_Name => To_Bounded_String
(Source => Suite_Name,
Drop => Ada.Strings.Right),
Test_Cases => Test_List.Empty_List,
Static_Test_Cases => Indefinite_Test_List.Empty_List);
end Create_Suite;
procedure Add_Test (Suite : in out Test_Suite; T : Test_Class_Access) is
begin
Test_List.Append (Suite.Test_Cases, (Ptr => T));
end Add_Test;
procedure Add_Test (Suite : in out Test_Suite; T : Test_Suite_Access) is
begin
Add_Test (Suite, Test_Class_Access (T));
end Add_Test;
procedure Add_Static_Test
(Suite : in out Test_Suite; T : Test'Class) is
begin
Indefinite_Test_List.Append (Suite.Static_Test_Cases, T);
end Add_Static_Test;
function Get_Name (T : Test_Suite) return String is
begin
return To_String (T.Suite_Name);
end Get_Name;
procedure Run (T : in out Test_Suite;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration)
is
-- Some nested procedure exercises here.
--
-- Execute_Cases is for normal test list
-- and Execute_Static_Cases is for indefinite test list.
--
-- Normal test list does not have For_Each procedure,
-- so we need to loop manually.
-- A helper procedure which runs Execute for the given test.
procedure Execute_Test (Current : in out Test'Class) is
begin
Execute (Current, Listener, Timeout);
end Execute_Test;
procedure Execute_Test_Ptr (Current : in out Test_Class_Wrapper) is
begin
Execute (Current.Ptr.all, Listener, Timeout);
end Execute_Test_Ptr;
procedure Execute_Static_Cases is
new Indefinite_Test_List.For_Each (Action => Execute_Test);
procedure Execute_Cases is
new Test_List.For_Each (Action => Execute_Test_Ptr);
begin
Execute_Cases (T.Test_Cases);
Execute_Static_Cases (T.Static_Test_Cases);
end Run;
procedure Run (T : in out Test_Suite;
Test_Name : String;
Listener : in out Listeners.Result_Listener'Class;
Timeout : Test_Duration)
is
procedure Execute_Test (Current : in out Test'Class) is
begin
if Get_Name (Current) = Test_Name then
Execute (T => Current, Listener => Listener, Timeout => Timeout);
else
Execute (T => Current,
Test_Name => Test_Name,
Listener => Listener,
Timeout => Timeout);
end if;
end Execute_Test;
procedure Execute_Test_Ptr (Current : in out Test_Class_Wrapper) is
begin
Execute_Test (Current.Ptr.all);
end Execute_Test_Ptr;
procedure Execute_Cases is
new Test_List.For_Each (Action => Execute_Test_Ptr);
procedure Execute_Static_Cases is
new Indefinite_Test_List.For_Each (Action => Execute_Test);
begin
if Test_Name = To_String (T.Suite_Name) then
Run (T, Listener, Timeout);
else
Execute_Cases (T.Test_Cases);
Execute_Static_Cases (T.Static_Test_Cases);
end if;
end Run;
function Test_Count (T : Test_Suite) return Test_Count_Type is
Counter : Test_Count_Type := 0;
procedure Inc_Counter (Test_Obj : in out Test'Class) is
begin
Counter := Counter + Test_Count (Test_Obj);
end Inc_Counter;
procedure Inc_Counter_Ptr (Wrapper : in out Test_Class_Wrapper) is
begin
Inc_Counter (Wrapper.Ptr.all);
end Inc_Counter_Ptr;
begin
declare
use Test_List;
procedure Count_All is new For_Each (Action => Inc_Counter_Ptr);
begin
Count_All (T.Test_Cases);
end;
declare
use Indefinite_Test_List;
procedure Count_All is new For_Each (Action => Inc_Counter);
begin
Count_All (T.Static_Test_Cases);
end;
return Counter;
end Test_Count;
function Test_Count (T : Test_Suite; Test_Name : String)
return Test_Count_Type is
Counter : Test_Count_Type := 0;
procedure Handle_Test (Test_Object : in out Test'Class) is
begin
if Get_Name (Test_Object) = Test_Name then
Counter := Counter + Test_Count (Test_Object);
else
Counter := Counter + Test_Count (Test_Object, Test_Name);
end if;
end Handle_Test;
procedure Handle_Test_Ptr (Obj : in out Test_Class_Wrapper) is
begin
Handle_Test (Obj.Ptr.all);
end Handle_Test_Ptr;
procedure Count_Static is
new Indefinite_Test_List.For_Each (Action => Handle_Test);
procedure Count_Tests is
new Test_List.For_Each (Action => Handle_Test_Ptr);
begin
if Test_Name = To_String (T.Suite_Name) then
return Test_Count (T);
end if;
Count_Tests (T.Test_Cases);
Count_Static (T.Static_Test_Cases);
return Counter;
end Test_Count;
procedure Adjust (T : in out Test_Suite) is
use Test_List;
New_List : List := Empty_List;
procedure Create_Copy (Item : in out Test_Class_Wrapper) is
begin
Append (New_List, (Ptr => new Test'Class'(Item.Ptr.all)));
end Create_Copy;
procedure Copy_All is new For_Each (Action => Create_Copy);
begin
Copy_All (T.Test_Cases);
T.Test_Cases := New_List;
end Adjust;
procedure Finalize (T : in out Test_Suite) is
use Test_List;
procedure Free_Item (Item : in out Test_Class_Wrapper) is
begin
Free_Test (Item.Ptr);
end Free_Item;
procedure Free_All is new For_Each (Action => Free_Item);
begin
Free_All (T.Test_Cases);
Clear (T.Test_Cases);
end Finalize;
procedure Release_Suite (T : Test_Suite_Access) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Test_Suite,
Name => Test_Suite_Access);
Ptr : Test_Suite_Access := T;
begin
Free (Ptr);
end Release_Suite;
procedure Run (Command : Test_Command; T : in out Test_Case'Class) is
Name : constant String := To_String (Command.Name);
begin
Log_Test_Start (Name);
case Command.Command_Kind is
when SIMPLE =>
Command.Simple_Routine.all;
when OBJECT =>
Set_Up (T);
begin
Command.Object_Routine.all (T);
exception
when others =>
-- Make sure Tear_Down is called even if the test failed.
Tear_Down (T);
Log_Test_Fail;
raise;
end;
Tear_Down (T);
end case;
Log_Test_End;
end Run;
----------- Indefinite_Test_List -------------------
package body Indefinite_Test_List is
procedure Remove (Ptr : Node_Access) is
procedure Free is
new Ada.Unchecked_Deallocation (Object => Node,
Name => Node_Access);
My_Ptr : Node_Access := Ptr;
begin
Ptr.Next := null;
Free_Test (My_Ptr.Data);
My_Ptr.Data := null;
Free (My_Ptr);
end Remove;
procedure Append (Target : in out List;
Node_Data : Test'Class) is
New_Node : Node_Access := null;
begin
New_Node := new Node'(Data => new Test'Class'(Node_Data),
Next => null);
if Target.Last = null then
Target.Last := New_Node;
Target.First := New_Node;
else
Target.Last.Next := New_Node;
Target.Last := New_Node;
end if;
end Append;
procedure Clear (Target : in out List) is
Current_Node : Node_Access := Target.First;
Next_Node : Node_Access := null;
begin
while Current_Node /= null loop
Next_Node := Current_Node.Next;
Remove (Current_Node);
Current_Node := Next_Node;
end loop;
Target.First := null;
Target.Last := null;
end Clear;
procedure For_Each (Target : List) is
Current_Node : Node_Access := Target.First;
begin
while Current_Node /= null loop
Action (Current_Node.Data.all);
Current_Node := Current_Node.Next;
end loop;
end For_Each;
procedure Initialize (Target : in out List) is
begin
Target.Last := null;
Target.First := null;
end Initialize;
procedure Finalize (Target : in out List) is
begin
Clear (Target);
end Finalize;
procedure Adjust (Target : in out List) is
Target_Last : Node_Access := null;
Target_First : Node_Access := null;
Current : Node_Access := Target.First;
New_Node : Node_Access;
begin
while Current /= null loop
New_Node := new Node'(Data => new Test'Class'(Current.Data.all),
Next => null);
if Target_Last = null then
Target_First := New_Node;
else
Target_Last.Next := New_Node;
end if;
Target_Last := New_Node;
Current := Current.Next;
end loop;
Target.First := Target_First;
Target.Last := Target_Last;
end Adjust;
end Indefinite_Test_List;
end Ahven.Framework;
|
-- part of ParserTools, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with Ada.Unchecked_Deallocation;
package body Lexer.Base is
procedure Free is new Ada.Unchecked_Deallocation
(String, Buffer_Type);
subtype Line_End is Character with Static_Predicate =>
Line_End in Line_Feed | Carriage_Return | End_Of_Input;
procedure Init (Object : in out Instance; Input : Source.Pointer;
Initial_Buffer_Size : Positive :=
Default_Initial_Buffer_Size) is
begin
Object.Internal.Input := Input;
Object.Buffer := new String (1 .. Initial_Buffer_Size);
Object.Internal.Sentinel := Initial_Buffer_Size + 1;
Refill_Buffer (Object);
end Init;
procedure Init (Object : in out Instance; Input : String) is
begin
Object.Internal.Input := null;
Object.Buffer := new String (1 .. Input'Length + 1);
Object.Internal.Sentinel := Input'Length + 2;
Object.Buffer.all := Input & End_Of_Input;
end Init;
function Next (Object : in out Instance) return Character is
begin
return C : constant Character := Object.Buffer (Object.Pos) do
Object.Pos := Object.Pos + 1;
end return;
end Next;
procedure Refill_Buffer (L : in out Instance) is
Bytes_To_Copy : constant Natural := L.Buffer'Last + 1 - L.Internal.Sentinel;
Fill_At : Positive := Bytes_To_Copy + 1;
Bytes_Read : Positive;
function Search_Sentinel return Boolean with Inline is
Peek : Positive := L.Buffer'Last;
begin
while not (L.Buffer (Peek) in Line_End) loop
if Peek = Fill_At then
return False;
else
Peek := Peek - 1;
end if;
end loop;
L.Internal.Sentinel := Peek + 1;
return True;
end Search_Sentinel;
begin
if Bytes_To_Copy > 0 then
L.Buffer (1 .. Bytes_To_Copy) :=
L.Buffer (L.Internal.Sentinel .. L.Buffer'Last);
end if;
loop
L.Internal.Input.Read_Data
(L.Buffer (Fill_At .. L.Buffer'Last), Bytes_Read);
if Bytes_Read < L.Buffer'Last - Fill_At then
L.Internal.Sentinel := Fill_At + Bytes_Read + 1;
L.Buffer (L.Internal.Sentinel - 1) := End_Of_Input;
exit;
else
exit when Search_Sentinel;
Fill_At := L.Buffer'Last + 1;
declare
New_Buffer : constant Buffer_Type :=
new String (1 .. 2 * L.Buffer'Last);
begin
New_Buffer.all (L.Buffer'Range) := L.Buffer.all;
Free (L.Buffer);
L.Buffer := New_Buffer;
end;
end if;
end loop;
end Refill_Buffer;
procedure Handle_CR (L : in out Instance) is
begin
if L.Buffer (L.Pos) = Line_Feed then
L.Pos := L.Pos + 1;
else
raise Lexer_Error with "pure CR line breaks not allowed.";
end if;
L.Prev_Lines_Chars :=
L.Prev_Lines_Chars + L.Pos - L.Line_Start;
if L.Pos = L.Internal.Sentinel then
Refill_Buffer (L);
L.Pos := 1;
end if;
L.Line_Start := L.Pos;
L.Cur_Line := L.Cur_Line + 1;
end Handle_CR;
procedure Handle_LF (L : in out Instance) is
begin
L.Prev_Lines_Chars :=
L.Prev_Lines_Chars + L.Pos - L.Line_Start;
if L.Pos = L.Internal.Sentinel then
Refill_Buffer (L);
L.Pos := 1;
end if;
L.Line_Start := L.Pos;
L.Cur_Line := L.Cur_Line + 1;
end Handle_LF;
procedure Finalize (Object : in out Instance) is
procedure Free is new Ada.Unchecked_Deallocation
(Source.Instance'Class, Source.Pointer);
use type Source.Pointer;
begin
if Object.Internal.Input /= null then
Free (Object.Internal.Input);
end if;
end Finalize;
end Lexer.Base;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure adademo2 is
type Day_type is range 1 .. 31;
type Month_type is range 1 .. 12;
type Year_type is range 1800 .. 2100;
type Hours is mod 24;
type Weekday is
(Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
type Date is record
Day : Day_type;
Month : Month_type;
Year : Year_type;
end record;
subtype Working_Hours is
Hours range 0 .. 12; -- at most 12 Hours to work a day
subtype Working_Day is Weekday range Monday .. Friday; -- Days to work
--begin
--Work_Load: constant array(Working_Day) of Working_Hours -- implicit type declaration
-- := (Friday => 6, Monday => 4, others => 10); -- lookup table for working hours with initialization
-- while a is not equal to b, loop.
--while a /= b loop
-- Ada.Text_IO.Put_Line ("Waiting");
--end loop;
--make into a procedure or function
--if a > b then
-- Ada.Text_IO.Put_Line ("Condition met");
--else
-- Ada.Text_IO.Put_Line ("Condition not met");
--end if;
begin
--loop
-- a := a + 1; how to define a
-- exit when a = 10;
--end loop;
for aWeekday in Weekday'Range loop -- loop over an enumeration
Put_Line
(Weekday'Image
(aWeekday)); -- output string representation of an enumeration
if aWeekday in
Working_Day
then -- check of a subtype of an enumeration
Put_Line (" to work for "); --&
-- Working_Hours'Image (Work_Load(aWeekday)) ); -- access into a lookup table
end if;
end loop;
end adademo2;
|
with External; use External;
package Logger is
task type LoggerReceiver is
entry Log(message: String);
entry Stop;
end LoggerReceiver;
type pLoggerReceiver is access LoggerReceiver;
end Logger;
|
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr>
-- MIT license. Please refer to the LICENSE file.
package body Apsepp.Test_Event_Class.Generic_Assert_Num_Mixin is
----------------------------------------------------------------------------
overriding
procedure Set (Obj : in out Child_W_Assert_Num; Data : Test_Event_Data) is
begin
Parent (Obj).Set (Data); -- Inherited procedure call.
Obj.Assert_Num := Data.Assert_Num;
end Set;
----------------------------------------------------------------------------
overriding
function Assert_Num (Obj : Child_W_Assert_Num) return Test_Assert_Count
is (Obj.Assert_Num);
----------------------------------------------------------------------------
end Apsepp.Test_Event_Class.Generic_Assert_Num_Mixin;
|
-- -*- Mode: Ada -*-
-- Filename : ether.adb
-- Description : Body root of the Ether SCGI library.
-- Author : Luke A. Guest
-- Created On : Thu May 3 15:32:35 2012
with Ada.Directories;
package body Ether is
procedure Initialise
(Bytes : in Positive;
Upload_Dir : in String;
Temp_Dir : in String) is
package Dirs renames Ada.Directories;
begin
Max_Request_Bytes := Bytes;
if Dirs.Exists (Upload_Dir) then
Uploads := US.To_Unbounded_String (Upload_Dir);
if Dirs.Exists (Temp_Dir) then
Temps := US.To_Unbounded_String (Temp_Dir);
Initialised := True;
else
raise Initialisation_Error with
"[Ether] Temporary directory """ & Temp_Dir & """ does not exist!";
end if;
else
raise Initialisation_Error with
"[Ether] Upload directory """ & Upload_Dir & """ does not exist!";
end if;
end Initialise;
function Is_Initialised return Boolean is
begin
return Initialised;
end Is_Initialised;
function Max_Request_Size return Positive is
begin
return Max_Request_Bytes;
end Max_Request_Size;
function Upload_Dir return String is
begin
return US.To_String (Uploads);
end Upload_Dir;
function Temp_Dir return String is
begin
return US.To_String (Temps);
end Temp_Dir;
end Ether;
|
with QtQuick; use QtQuick;
procedure Hello is
begin
Qt_Main ("hello.qml");
end Hello;
|
-- { dg-do compile }
procedure Discr5 is
type Enum is (Ten, Twenty);
for Enum use (10, 20);
type Arr is array (Enum range <>) of Integer;
type Rec (Discr: Enum := Ten) is record
case Discr is
when others =>
A: Arr (Ten .. Discr);
end case;
end record;
begin
null;
end;
|
package HTTPd is
pragma Pure;
Host : constant String := "localhost";
Port : constant := 8080;
end HTTPd;
|
package body Ada.Text_IO.Terminal.Colors is
function "+" (Item : Boolean) return Boolean_Parameter is
begin
return (Changing => True, Item => Item);
end "+";
function "+" (Item : Color) return Color_Parameter is
begin
return (Changing => True, Item => Item);
end "+";
procedure Set_Color (
File : File_Type; -- Output_File_Type
Reset : Boolean := False;
Bold : Boolean_Parameter := (Changing => False);
Underline : Boolean_Parameter := (Changing => False);
Blink : Boolean_Parameter := (Changing => False);
Reversed : Boolean_Parameter := (Changing => False);
Foreground : Color_Parameter := (Changing => False);
Background : Color_Parameter := (Changing => False))
is
pragma Check (Dynamic_Predicate,
Check => Is_Open (File) or else raise Status_Error);
pragma Check (Dynamic_Predicate,
Check => Mode (File) /= In_File or else raise Mode_Error);
Bold_Item : Boolean;
Underline_Item : Boolean;
Blink_Item : Boolean;
Reversed_Item : Boolean;
Foreground_Item : System.Native_Text_IO.Terminal_Colors.Color;
Background_Item : System.Native_Text_IO.Terminal_Colors.Color;
begin
if Bold.Changing then
Bold_Item := Bold.Item;
end if;
if Underline.Changing then
Underline_Item := Underline.Item;
end if;
if Blink.Changing then
Blink_Item := Blink.Item;
end if;
if Reversed.Changing then
Reversed_Item := Reversed.Item;
end if;
if Foreground.Changing then
Foreground_Item :=
System.Native_Text_IO.Terminal_Colors.Color (Foreground.Item);
end if;
if Background.Changing then
Background_Item :=
System.Native_Text_IO.Terminal_Colors.Color (Background.Item);
end if;
declare
NC_File : Naked_Text_IO.Non_Controlled_File_Type
renames Controlled.Reference (File).all;
begin
System.Native_Text_IO.Terminal_Colors.Set (
Naked_Text_IO.Terminal_Handle (NC_File),
Reset,
Bold.Changing,
Bold_Item,
Underline.Changing,
Underline_Item,
Blink.Changing,
Blink_Item,
Reversed.Changing,
Reversed_Item,
Foreground.Changing,
Foreground_Item,
Background.Changing,
Background_Item);
end;
end Set_Color;
procedure Reset_Color (
File : File_Type)
is
pragma Check (Dynamic_Predicate,
Check => Is_Open (File) or else raise Status_Error);
pragma Check (Dynamic_Predicate,
Check => Mode (File) /= In_File or else raise Mode_Error);
NC_File : Naked_Text_IO.Non_Controlled_File_Type
renames Controlled.Reference (File).all;
begin
System.Native_Text_IO.Terminal_Colors.Reset (
Naked_Text_IO.Terminal_Handle (NC_File));
end Reset_Color;
end Ada.Text_IO.Terminal.Colors;
|
with Ada.Finalization; use Ada.Finalization;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Containers.Vectors; use Ada.Containers;
with Distribution; use Distribution;
with Util; use Util;
-- Base package for memory components.
-- This package has prototypes for simulating and generating VHDL.
package Memory is
-- An exception that is raised when the simulation of a memory
-- can complete early. This is used for superoptimization to avoid
-- fully evaluating a memory trace.
Prune_Error : exception;
-- The base data type for memory components.
-- This type should be extended to create new main memories.
-- See Memory.Container to create components.
type Memory_Type is abstract new Controlled with private;
type Memory_Pointer is access all Memory_Type'Class;
-- Type to represent a port.
type Port_Type is record
id : Natural; -- Memory identifier for the port.
word_size : Positive; -- Size of a word in bytes.
addr_bits : Positive; -- Size of an address in bits.
end record;
-- Vector of ports.
package Port_Vectors is new Vectors(Natural, Port_Type);
subtype Port_Vector_Type is Port_Vectors.Vector;
-- Clone this memory.
-- This will allocate a new instance of the memory.
function Clone(mem : Memory_Type) return Memory_Pointer is abstract;
-- Permute some aspect of the current memory component.
procedure Permute(mem : in out Memory_Type;
generator : in Distribution_Type;
max_cost : in Cost_Type) is null;
-- Determine if the evaulation is finished or if the benchmark
-- needs to be re-run.
function Done(mem : Memory_Type) return Boolean;
-- Reset the memory. This should be called between benchmark runs.
-- context is the context being started. This is used for
-- superoptimization of multiple traces.
procedure Reset(mem : in out Memory_Type;
context : in Natural);
-- Set the port being used to access memory.
-- This is used to inform arbiters where an access is coming from.
procedure Set_Port(mem : in out Memory_Type;
port : in Natural;
ready : out Boolean) is null;
-- Simulate a memory read.
procedure Read(mem : in out Memory_Type;
address : in Address_Type;
size : in Positive) is abstract;
-- Simulate a memory write.
procedure Write(mem : in out Memory_Type;
address : in Address_Type;
size : in Positive) is abstract;
-- Simulate idle time.
procedure Idle(mem : in out Memory_Type;
cycles : in Time_Type);
-- Get the current time in cycles.
function Get_Time(mem : Memory_Type) return Time_Type;
-- Get the number of writes to the main memory.
function Get_Writes(mem : Memory_Type) return Long_Integer is abstract;
-- Show statistics.
procedure Show_Stats(mem : in out Memory_Type);
-- Show access statistics (called from Show_Stats).
procedure Show_Access_Stats(mem : in out Memory_Type) is null;
-- Get a string representation of the memory.
function To_String(mem : Memory_Type) return Unbounded_String is abstract;
-- Get the cost of this memory.
function Get_Cost(mem : Memory_Type) return Cost_Type is abstract;
-- Get the word size in bytes.
function Get_Word_Size(mem : Memory_Type) return Positive is abstract;
-- Get the length of the longest path in levels of logic.
-- This is an estimate used to insert registers.
function Get_Path_Length(mem : Memory_Type) return Natural;
-- Generate VHDL for a memory.
procedure Generate(mem : in Memory_Type;
sigs : in out Unbounded_String;
code : in out Unbounded_String) is null;
-- Destroy a memory.
procedure Destroy(mem : in out Memory_Pointer);
-- Get the total access time.
-- This is used for optimization to minimize access time.
function Get_Time(mem : access Memory_Type'Class) return Time_Type;
-- Get the total number of writes.
-- This is used for optimization to minimize writes.
function Get_Writes(mem : access Memory_Type'Class) return Long_Integer;
-- Return 0.
-- This is used for optimization to perform a random walk.
function Get_Zero(mem : access Memory_Type'Class) return Natural;
-- Get a unique identifier for this memory component.
function Get_ID(mem : Memory_Type'Class) return Natural;
-- Advance the access time.
procedure Advance(mem : in out Memory_Type'Class;
cycles : in Time_Type);
-- Get the maximum path length in levels of logic.
function Get_Max_Length(mem : access Memory_Type'Class;
result : Natural := 0) return Natural;
-- Get a vector of end-points.
function Get_Ports(mem : Memory_Type) return Port_Vector_Type is abstract;
private
type Memory_Type is abstract new Controlled with record
id : Natural;
time : Time_Type := 0;
end record;
overriding
procedure Initialize(mem : in out Memory_Type);
overriding
procedure Adjust(mem : in out Memory_Type);
function Get_Port(mem : Memory_Type'Class) return Port_Type;
procedure Declare_Signals(sigs : in out Unbounded_String;
name : in String;
word_bits : in Positive);
procedure Line(dest : in out Unbounded_String;
str : in String := "");
function To_String(a : Address_Type) return String;
function To_String(t : Time_Type) return String;
function To_String(i : Integer) return String renames Util.To_String;
function To_String(i : Long_Integer) return String renames Util.To_String;
function To_String(f : Long_Float) return String renames Util.To_String;
end Memory;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . --
-- H A S H _ T A B L E S . G E N E R I C _ O P E R A T I O N S --
-- --
-- S p e c --
-- --
-- This specification is adapted from the Ada Reference Manual for use with --
-- GNAT. In accordance with the copyright of that document, you can freely --
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
with Ada.Streams;
generic
with package HT_Types is
new Generic_Hash_Table_Types (<>);
use HT_Types;
with function Hash_Node (Node : Node_Access) return Hash_Type;
with function Next (Node : Node_Access) return Node_Access;
with procedure Set_Next
(Node : Node_Access;
Next : Node_Access);
with function Copy_Node (Source : Node_Access) return Node_Access;
with procedure Free (X : in out Node_Access);
package Ada.Containers.Hash_Tables.Generic_Operations is
pragma Preelaborate;
procedure Free_Hash_Table (Buckets : in out Buckets_Access);
function Index
(Buckets : Buckets_Type;
Node : Node_Access) return Hash_Type;
pragma Inline (Index);
function Index
(Hash_Table : Hash_Table_Type;
Node : Node_Access) return Hash_Type;
pragma Inline (Index);
procedure Adjust (HT : in out Hash_Table_Type);
procedure Finalize (HT : in out Hash_Table_Type);
generic
with function Find
(HT : Hash_Table_Type;
Key : Node_Access) return Boolean;
function Generic_Equal
(L, R : Hash_Table_Type) return Boolean;
procedure Clear (HT : in out Hash_Table_Type);
procedure Move (Target, Source : in out Hash_Table_Type);
function Capacity (HT : Hash_Table_Type) return Count_Type;
procedure Reserve_Capacity
(HT : in out Hash_Table_Type;
N : Count_Type);
procedure Delete_Node_Sans_Free
(HT : in out Hash_Table_Type;
X : Node_Access);
function First (HT : Hash_Table_Type) return Node_Access;
function Next
(HT : Hash_Table_Type;
Node : Node_Access) return Node_Access;
generic
with procedure Process (Node : Node_Access);
procedure Generic_Iteration (HT : Hash_Table_Type);
generic
use Ada.Streams;
with procedure Write
(Stream : access Root_Stream_Type'Class;
Node : Node_Access);
procedure Generic_Write
(Stream : access Root_Stream_Type'Class;
HT : Hash_Table_Type);
generic
use Ada.Streams;
with function New_Node (Stream : access Root_Stream_Type'Class)
return Node_Access;
procedure Generic_Read
(Stream : access Root_Stream_Type'Class;
HT : out Hash_Table_Type);
end Ada.Containers.Hash_Tables.Generic_Operations;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Tools Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2009-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Ada.Text_IO;
with Matreshka.Internals.Unicode.Ucd;
with Put_File_Header;
with Ucd_Data;
with Utils;
procedure Gen_Props is
use Matreshka.Internals.Unicode;
use Matreshka.Internals.Unicode.Ucd;
use Ucd_Data;
use Utils;
type Group_Info is record
Share : First_Stage_Index;
Count : Natural;
Index : First_Stage_Index;
end record;
type Constant_String_Access is access constant String;
procedure Put (Item : Core_Values);
-- Put code for properties initialization.
GC_Control_Image : aliased constant String := "Control";
GC_Format_Image : aliased constant String := "Format";
GC_Unassigned_Image : aliased constant String := "Unassigned";
GC_Private_Use_Image : aliased constant String := "Private_Use";
GC_Surrogate_Image : aliased constant String := "Surrogate";
GC_Lowercase_Letter_Image : aliased constant String := "Lowercase_Letter";
GC_Modifier_Letter_Image : aliased constant String := "Modifier_Letter";
GC_Other_Letter_Image : aliased constant String := "Other_Letter";
GC_Titlecase_Letter_Image : aliased constant String := "Titlecase_Letter";
GC_Uppercase_Letter_Image : aliased constant String := "Uppercase_Letter";
GC_Spacing_Mark_Image : aliased constant String := "Spacing_Mark";
GC_Enclosing_Mark_Image : aliased constant String := "Enclosing_Mark";
GC_Nonspacing_Mark_Image : aliased constant String := "Nonspacing_Mark";
GC_Decimal_Number_Image : aliased constant String := "Decimal_Number";
GC_Letter_Number_Image : aliased constant String := "Letter_Number";
GC_Other_Number_Image : aliased constant String := "Other_Number";
GC_Connector_Punctuation_Image :
aliased constant String := "Connector_Punctuation";
GC_Dash_Punctuation_Image : aliased constant String := "Dash_Punctuation";
GC_Close_Punctuation_Image : aliased constant String := "Close_Punctuation";
GC_Final_Punctuation_Image : aliased constant String := "Final_Punctuation";
GC_Initial_Punctuation_Image :
aliased constant String := "Initial_Punctuation";
GC_Other_Punctuation_Image : aliased constant String := "Other_Punctuation";
GC_Open_Punctuation_Image : aliased constant String := "Open_Punctuation";
GC_Currency_Symbol_Image : aliased constant String := "Currency_Symbol";
GC_Modifier_Symbol_Image : aliased constant String := "Modifier_Symbol";
GC_Math_Symbol_Image : aliased constant String := "Math_Symbol";
GC_Other_Symbol_Image : aliased constant String := "Other_Symbol";
GC_Line_Separator_Image : aliased constant String := "Line_Separator";
GC_Paragraph_Separator_Image :
aliased constant String := "Paragraph_Separator";
GC_Space_Separator_Image : aliased constant String := "Space_Separator";
General_Category_Image : constant
array (General_Category) of Constant_String_Access
:= (Control => GC_Control_Image'Access,
Format => GC_Format_Image'Access,
Unassigned => GC_Unassigned_Image'Access,
Private_Use => GC_Private_Use_Image'Access,
Surrogate => GC_Surrogate_Image'Access,
Lowercase_Letter => GC_Lowercase_Letter_Image'Access,
Modifier_Letter => GC_Modifier_Letter_Image'Access,
Other_Letter => GC_Other_Letter_Image'Access,
Titlecase_Letter => GC_Titlecase_Letter_Image'Access,
Uppercase_Letter => GC_Uppercase_Letter_Image'Access,
Spacing_Mark => GC_Spacing_Mark_Image'Access,
Enclosing_Mark => GC_Enclosing_Mark_Image'Access,
Nonspacing_Mark => GC_Nonspacing_Mark_Image'Access,
Decimal_Number => GC_Decimal_Number_Image'Access,
Letter_Number => GC_Letter_Number_Image'Access,
Other_Number => GC_Other_Number_Image'Access,
Connector_Punctuation => GC_Connector_Punctuation_Image'Access,
Dash_Punctuation => GC_Dash_Punctuation_Image'Access,
Close_Punctuation => GC_Close_Punctuation_Image'Access,
Final_Punctuation => GC_Final_Punctuation_Image'Access,
Initial_Punctuation => GC_Initial_Punctuation_Image'Access,
Other_Punctuation => GC_Other_Punctuation_Image'Access,
Open_Punctuation => GC_Open_Punctuation_Image'Access,
Currency_Symbol => GC_Currency_Symbol_Image'Access,
Modifier_Symbol => GC_Modifier_Symbol_Image'Access,
Math_Symbol => GC_Math_Symbol_Image'Access,
Other_Symbol => GC_Other_Symbol_Image'Access,
Line_Separator => GC_Line_Separator_Image'Access,
Paragraph_Separator => GC_Paragraph_Separator_Image'Access,
Space_Separator => GC_Space_Separator_Image'Access);
GCB_Other_Image : aliased constant String := "Other";
GCB_CR_Image : aliased constant String := "CR";
GCB_LF_Image : aliased constant String := "LF";
GCB_Control_Image : aliased constant String := "Control";
GCB_Extend_Image : aliased constant String := "Extend";
GCB_Prepend_Image : aliased constant String := "Prepend";
GCB_Spacing_Mark_Image : aliased constant String := "Spacing_Mark";
GCB_L_Image : aliased constant String := "L";
GCB_V_Image : aliased constant String := "V";
GCB_T_Image : aliased constant String := "T";
GCB_LV_Image : aliased constant String := "LV";
GCB_LVT_Image : aliased constant String := "LVT";
GCB_Regional_Indicator_Image :
aliased constant String := "Regional_Indicator";
Grapheme_Cluster_Break_Image : constant
array (Grapheme_Cluster_Break) of Constant_String_Access
:= (Other => GCB_Other_Image'Access,
CR => GCB_CR_Image'Access,
LF => GCB_LF_Image'Access,
Control => GCB_Control_Image'Access,
Extend => GCB_Extend_Image'Access,
Prepend => GCB_Prepend_Image'Access,
Spacing_Mark => GCB_Spacing_Mark_Image'Access,
L => GCB_L_Image'Access,
V => GCB_V_Image'Access,
T => GCB_T_Image'Access,
LV => GCB_LV_Image'Access,
LVT => GCB_LVT_Image'Access,
Regional_Indicator => GCB_Regional_Indicator_Image'Access);
Ambiguous_Image : aliased constant String := "Ambiguous";
Fullwidth_Image : aliased constant String := "Fullwidth";
Halfwidth_Image : aliased constant String := "Halfwidth";
Neutral_Image : aliased constant String := "Neutral";
Narrow_Image : aliased constant String := "Narrow";
Wide_Image : aliased constant String := "Wide";
East_Asian_Width_Image : constant
array (East_Asian_Width) of Constant_String_Access
:= (Ambiguous => Ambiguous_Image'Access,
Fullwidth => Fullwidth_Image'Access,
Halfwidth => Halfwidth_Image'Access,
Neutral => Neutral_Image'Access,
Narrow => Narrow_Image'Access,
Wide => Wide_Image'Access);
WB_Other_Image : aliased constant String := "Other";
WB_CR_Image : aliased constant String := "CR";
WB_LF_Image : aliased constant String := "LF";
WB_Newline_Image : aliased constant String := "Newline";
WB_Katakana_Image : aliased constant String := "Katakana";
WB_A_Letter_Image : aliased constant String := "A_Letter";
WB_Mid_Letter_Image : aliased constant String := "Mid_Letter";
WB_Mid_Num_Image : aliased constant String := "Mid_Num";
WB_Mid_Num_Let_Image : aliased constant String := "Mid_Num_Let";
WB_Numeric_Image : aliased constant String := "Numeric";
WB_Extend_Num_Let_Image : aliased constant String := "Extend_Num_Let";
WB_Format_Image : aliased constant String := "Format";
WB_Extend_Image : aliased constant String := "Extend";
WB_Regional_Indicator_Image :
aliased constant String := "Regional_Indicator";
WB_Hebrew_Letter_Image : aliased constant String := "Hebrew_Letter";
WB_Single_Quote_Image : aliased constant String := "Single_Quote";
WB_Double_Quote_Image : aliased constant String := "Double_Quote";
Word_Break_Image : constant array (Word_Break) of Constant_String_Access
:= (Other => WB_Other_Image'Access,
CR => WB_CR_Image'Access,
LF => WB_LF_Image'Access,
Newline => WB_Newline_Image'Access,
Katakana => WB_Katakana_Image'Access,
A_Letter => WB_A_Letter_Image'Access,
Mid_Letter => WB_Mid_Letter_Image'Access,
Mid_Num => WB_Mid_Num_Image'Access,
Mid_Num_Let => WB_Mid_Num_Let_Image'Access,
Numeric => WB_Numeric_Image'Access,
Extend_Num_Let => WB_Extend_Num_Let_Image'Access,
Format => WB_Format_Image'Access,
Extend => WB_Extend_Image'Access,
Regional_Indicator => WB_Regional_Indicator_Image'Access,
Hebrew_Letter => WB_Hebrew_Letter_Image'Access,
Single_Quote => WB_Single_Quote_Image'Access,
Double_Quote => WB_Double_Quote_Image'Access);
SB_Other_Image : aliased constant String := "Other";
SB_CR_Image : aliased constant String := "CR";
SB_LF_Image : aliased constant String := "LF";
SB_Sep_Image : aliased constant String := "Sep";
SB_Sp_Image : aliased constant String := "Sp";
SB_Lower_Image : aliased constant String := "Lower";
SB_Upper_Image : aliased constant String := "Upper";
SB_O_Letter_Image : aliased constant String := "O_Letter";
SB_Numeric_Image : aliased constant String := "Numeric";
SB_A_Term_Image : aliased constant String := "A_Term";
SB_S_Term_Image : aliased constant String := "S_Term";
SB_Close_Image : aliased constant String := "Close";
SB_S_Continue_Image : aliased constant String := "S_Continue";
SB_Format_Image : aliased constant String := "Format";
SB_Extend_Image : aliased constant String := "Extend";
Sentence_Break_Image : constant
array (Sentence_Break) of Constant_String_Access
:= (Other => SB_Other_Image'Access,
CR => SB_CR_Image'Access,
LF => SB_LF_Image'Access,
Sep => SB_Sep_Image'Access,
Sp => SB_Sp_Image'Access,
Lower => SB_Lower_Image'Access,
Upper => SB_Upper_Image'Access,
O_Letter => SB_O_Letter_Image'Access,
Numeric => SB_Numeric_Image'Access,
A_Term => SB_A_Term_Image'Access,
S_Term => SB_S_Term_Image'Access,
Close => SB_Close_Image'Access,
S_Continue => SB_S_Continue_Image'Access,
Format => SB_Format_Image'Access,
Extend => SB_Extend_Image'Access);
LB_Ambiguous_Image : aliased constant String := "Ambiguous";
LB_Alphabetic_Image : aliased constant String := "Alphabetic";
LB_Break_Both_Image : aliased constant String := "Break_Both";
LB_Break_After_Image : aliased constant String := "Break_After";
LB_Break_Before_Image : aliased constant String := "Break_Before";
LB_Mandatory_Break_Image : aliased constant String := "Mandatory_Break";
LB_Contingent_Break_Image : aliased constant String := "Contingent_Break";
LB_Conditional_Japanese_Starter_Image :
aliased constant String := "Conditional_Japanese_Starter";
LB_Close_Punctuation_Image : aliased constant String := "Close_Punctuation";
LB_Combining_Mark_Image : aliased constant String := "Combining_Mark";
LB_Close_Parenthesis_Image : aliased constant String := "Close_Parenthesis";
LB_Carriage_Return_Image : aliased constant String := "Carriage_Return";
LB_Exclamation_Image : aliased constant String := "Exclamation";
LB_Glue_Image : aliased constant String := "Glue";
LB_H2_Image : aliased constant String := "H2";
LB_H3_Image : aliased constant String := "H3";
LB_Hebrew_Letter_Image : aliased constant String := "Hebrew_Letter";
LB_Hyphen_Image : aliased constant String := "Hyphen";
LB_Ideographic_Image : aliased constant String := "Ideographic";
LB_Inseparable_Image : aliased constant String := "Inseparable";
LB_Infix_Numeric_Image : aliased constant String := "Infix_Numeric";
LB_JL_Image : aliased constant String := "JL";
LB_JT_Image : aliased constant String := "JT";
LB_JV_Image : aliased constant String := "JV";
LB_Line_Feed_Image : aliased constant String := "Line_Feed";
LB_Next_Line_Image : aliased constant String := "Next_Line";
LB_Nonstarter_Image : aliased constant String := "Nonstarter";
LB_Numeric_Image : aliased constant String := "Numeric";
LB_Open_Punctuation_Image : aliased constant String := "Open_Punctuation";
LB_Postfix_Numeric_Image : aliased constant String := "Postfix_Numeric";
LB_Prefix_Numeric_Image : aliased constant String := "Prefix_Numeric";
LB_Quotation_Image : aliased constant String := "Quotation";
LB_Complex_Context_Image : aliased constant String := "Complex_Context";
LB_Surrogate_Image : aliased constant String := "Surrogate";
LB_Space_Image : aliased constant String := "Space";
LB_Break_Symbols_Image : aliased constant String := "Break_Symbols";
LB_Word_Joiner_Image : aliased constant String := "Word_Joiner";
LB_Unknown_Image : aliased constant String := "Unknown";
LB_ZW_Space_Image : aliased constant String := "ZW_Space";
LB_Regional_Indicator_Image :
aliased constant String := "Regional_Indicator";
Line_Break_Image : constant array (Line_Break) of Constant_String_Access
:= (Ambiguous => LB_Ambiguous_Image'Access,
Alphabetic => LB_Alphabetic_Image'Access,
Break_Both => LB_Break_Both_Image'Access,
Break_After => LB_Break_After_Image'Access,
Break_Before => LB_Break_Before_Image'Access,
Mandatory_Break => LB_Mandatory_Break_Image'Access,
Contingent_Break => LB_Contingent_Break_Image'Access,
Conditional_Japanese_Starter =>
LB_Conditional_Japanese_Starter_Image'Access,
Close_Punctuation => LB_Close_Punctuation_Image'Access,
Combining_Mark => LB_Combining_Mark_Image'Access,
Close_Parenthesis => LB_Close_Parenthesis_Image'Access,
Carriage_Return => LB_Carriage_Return_Image'Access,
Exclamation => LB_Exclamation_Image'Access,
Glue => LB_Glue_Image'Access,
H2 => LB_H2_Image'Access,
H3 => LB_H3_Image'Access,
Hebrew_Letter => LB_Hebrew_Letter_Image'Access,
Hyphen => LB_Hyphen_Image'Access,
Ideographic => LB_Ideographic_Image'Access,
Inseparable => LB_Inseparable_Image'Access,
Infix_Numeric => LB_Infix_Numeric_Image'Access,
JL => LB_JL_Image'Access,
JT => LB_JT_Image'Access,
JV => LB_JV_Image'Access,
Line_Feed => LB_Line_Feed_Image'Access,
Next_Line => LB_Next_Line_Image'Access,
Nonstarter => LB_Nonstarter_Image'Access,
Numeric => LB_Numeric_Image'Access,
Open_Punctuation => LB_Open_Punctuation_Image'Access,
Postfix_Numeric => LB_Postfix_Numeric_Image'Access,
Prefix_Numeric => LB_Prefix_Numeric_Image'Access,
Quotation => LB_Quotation_Image'Access,
Complex_Context => LB_Complex_Context_Image'Access,
Surrogate => LB_Surrogate_Image'Access,
Space => LB_Space_Image'Access,
Break_Symbols => LB_Break_Symbols_Image'Access,
Word_Joiner => LB_Word_Joiner_Image'Access,
Unknown => LB_Unknown_Image'Access,
ZW_Space => LB_ZW_Space_Image'Access,
Regional_Indicator => LB_Regional_Indicator_Image'Access);
BP_ASCII_Hex_Digit_Image : aliased constant String := "ASCII_Hex_Digit";
BP_Alphabetic_Image : aliased constant String := "Alphabetic";
BP_Bidi_Control_Image : aliased constant String := "Bidi_Control";
BP_Bidi_Mirrored_Image : aliased constant String := "Bidi_Mirrored";
BP_Changes_When_NFKC_Casefolded_Image :
aliased constant String := "Changes_When_NFKC_Casefolded";
BP_Composition_Exclusion_Image :
aliased constant String := "Composition_Exclusion";
BP_Full_Composition_Exclusion_Image :
aliased constant String := "Full_Composition_Exclusion";
BP_Dash_Image : aliased constant String := "Dash";
BP_Deprecated_Image : aliased constant String := "Deprecated";
BP_Default_Ignorable_Code_Point_Image :
aliased constant String := "Default_Ignorable_Code_Point";
BP_Diacritic_Image : aliased constant String := "Diacritic";
BP_Extender_Image : aliased constant String := "Extender";
BP_Grapheme_Base_Image : aliased constant String := "Grapheme_Base";
BP_Grapheme_Extend_Image : aliased constant String := "Grapheme_Extend";
BP_Grapheme_Link_Image : aliased constant String := "Grapheme_Link";
BP_Hex_Digit_Image : aliased constant String := "Hex_Digit";
BP_Hyphen_Image : aliased constant String := "Hyphen";
BP_ID_Continue_Image : aliased constant String := "ID_Continue";
BP_Ideographic_Image : aliased constant String := "Ideographic";
BP_ID_Start_Image : aliased constant String := "ID_Start";
BP_IDS_Binary_Operator_Image :
aliased constant String := "IDS_Binary_Operator";
BP_IDS_Trinary_Operator_Image :
aliased constant String := "IDS_Trinary_Operator";
BP_Join_Control_Image : aliased constant String := "Join_Control";
BP_Logical_Order_Exception_Image :
aliased constant String := "Logical_Order_Exception";
BP_Lowercase_Image : aliased constant String := "Lowercase";
BP_Math_Image : aliased constant String := "Math";
BP_Noncharacter_Code_Point_Image :
aliased constant String := "Noncharacter_Code_Point";
BP_Other_Alphabetic_Image : aliased constant String := "Other_Alphabetic";
BP_Other_Default_Ignorable_Code_Point_Image :
aliased constant String := "Other_Default_Ignorable_Code_Point";
BP_Other_Grapheme_Extend_Image :
aliased constant String := "Other_Grapheme_Extend";
BP_Other_ID_Continue_Image : aliased constant String := "Other_ID_Continue";
BP_Other_ID_Start_Image : aliased constant String := "Other_ID_Start";
BP_Other_Lowercase_Image : aliased constant String := "Other_Lowercase";
BP_Other_Math_Image : aliased constant String := "Other_Math";
BP_Other_Uppercase_Image : aliased constant String := "Other_Uppercase";
BP_Pattern_Syntax_Image : aliased constant String := "Pattern_Syntax";
BP_Pattern_White_Space_Image :
aliased constant String := "Pattern_White_Space";
BP_Quotation_Mark_Image : aliased constant String := "Quotation_Mark";
BP_Radical_Image : aliased constant String := "Radical";
BP_Soft_Dotted_Image : aliased constant String := "Soft_Dotted";
BP_STerm_Image : aliased constant String := "STerm";
BP_Terminal_Punctuation_Image :
aliased constant String := "Terminal_Punctuation";
BP_Unified_Ideograph_Image : aliased constant String := "Unified_Ideograph";
BP_Uppercase_Image : aliased constant String := "Uppercase";
BP_Variation_Selector_Image :
aliased constant String := "Variation_Selector";
BP_White_Space_Image : aliased constant String := "White_Space";
BP_XID_Continue_Image : aliased constant String := "XID_Continue";
BP_XID_Start_Image : aliased constant String := "XID_Start";
BP_Expands_On_NFC_Image : aliased constant String := "Expands_On_NFC";
BP_Expands_On_NFD_Image : aliased constant String := "Expands_On_NFD";
BP_Expands_On_NFKC_Image : aliased constant String := "Expands_On_NFKC";
BP_Expands_On_NFKD_Image : aliased constant String := "Expands_On_NFKD";
BP_Cased_Image : aliased constant String := "Cased";
BP_Case_Ignorable_Image : aliased constant String := "Case_Ignorable";
BP_Changes_When_Lowercased_Image :
aliased constant String := "Changes_When_Lowercased";
BP_Changes_When_Uppercased_Image :
aliased constant String := "Changes_When_Uppercased";
BP_Changes_When_Titlecased_Image :
aliased constant String := "Changes_When_Titlecased";
BP_Changes_When_Casefolded_Image :
aliased constant String := "Changes_When_Casefolded";
BP_Changes_When_Casemapped_Image :
aliased constant String := "Changes_When_Casemapped";
Boolean_Properties_Image : constant
array (Overridable_Boolean_Properties) of Constant_String_Access
:= (ASCII_Hex_Digit => BP_ASCII_Hex_Digit_Image'Access,
Alphabetic => BP_Alphabetic_Image'Access,
Bidi_Control => BP_Bidi_Control_Image'Access,
-- Bidi_Mirrored => BP_Bidi_Mirrored_Image'Access,
Changes_When_NFKC_Casefolded =>
BP_Changes_When_NFKC_Casefolded_Image'Access,
Dash => BP_Dash_Image'Access,
Deprecated => BP_Deprecated_Image'Access,
Default_Ignorable_Code_Point =>
BP_Default_Ignorable_Code_Point_Image'Access,
Diacritic => BP_Diacritic_Image'Access,
Extender => BP_Extender_Image'Access,
Grapheme_Base => BP_Grapheme_Base_Image'Access,
Grapheme_Extend => BP_Grapheme_Extend_Image'Access,
Grapheme_Link => BP_Grapheme_Link_Image'Access,
Hex_Digit => BP_Hex_Digit_Image'Access,
Hyphen => BP_Hyphen_Image'Access,
ID_Continue => BP_ID_Continue_Image'Access,
Ideographic => BP_Ideographic_Image'Access,
ID_Start => BP_ID_Start_Image'Access,
IDS_Binary_Operator => BP_IDS_Binary_Operator_Image'Access,
IDS_Trinary_Operator => BP_IDS_Trinary_Operator_Image'Access,
Join_Control => BP_Join_Control_Image'Access,
Logical_Order_Exception => BP_Logical_Order_Exception_Image'Access,
Lowercase => BP_Lowercase_Image'Access,
Math => BP_Math_Image'Access,
Noncharacter_Code_Point => BP_Noncharacter_Code_Point_Image'Access,
Other_Alphabetic => BP_Other_Alphabetic_Image'Access,
Other_Default_Ignorable_Code_Point =>
BP_Other_Default_Ignorable_Code_Point_Image'Access,
Other_Grapheme_Extend => BP_Other_Grapheme_Extend_Image'Access,
Other_ID_Continue => BP_Other_ID_Continue_Image'Access,
Other_ID_Start => BP_Other_ID_Start_Image'Access,
Other_Lowercase => BP_Other_Lowercase_Image'Access,
Other_Math => BP_Other_Math_Image'Access,
Other_Uppercase => BP_Other_Uppercase_Image'Access,
Pattern_Syntax => BP_Pattern_Syntax_Image'Access,
Pattern_White_Space => BP_Pattern_White_Space_Image'Access,
Quotation_Mark => BP_Quotation_Mark_Image'Access,
Radical => BP_Radical_Image'Access,
Soft_Dotted => BP_Soft_Dotted_Image'Access,
STerm => BP_STerm_Image'Access,
Terminal_Punctuation => BP_Terminal_Punctuation_Image'Access,
Unified_Ideograph => BP_Unified_Ideograph_Image'Access,
Uppercase => BP_Uppercase_Image'Access,
Variation_Selector => BP_Variation_Selector_Image'Access,
White_Space => BP_White_Space_Image'Access,
XID_Continue => BP_XID_Continue_Image'Access,
XID_Start => BP_XID_Start_Image'Access,
Cased => BP_Cased_Image'Access,
Case_Ignorable => BP_Case_Ignorable_Image'Access,
Changes_When_Lowercased => BP_Changes_When_Lowercased_Image'Access,
Changes_When_Uppercased => BP_Changes_When_Uppercased_Image'Access,
Changes_When_Titlecased => BP_Changes_When_Titlecased_Image'Access,
Changes_When_Casefolded => BP_Changes_When_Casefolded_Image'Access,
Changes_When_Casemapped => BP_Changes_When_Casemapped_Image'Access);
---------
-- Put --
---------
procedure Put (Item : Core_Values) is
use type Ada.Text_IO.Count;
Indent : Ada.Text_IO.Count := Ada.Text_IO.Col + 1;
Counts : array (Boolean) of Natural := (0, 0);
Default : Boolean;
N : Natural := 0;
begin
Ada.Text_IO.Put
('('
& General_Category_Image (Item.GC).all
& ", "
& East_Asian_Width_Image (Item.EA).all
& ",");
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put
(Grapheme_Cluster_Break_Image (Item.GCB).all
& ", "
& Word_Break_Image (Item.WB).all
& ", "
& Sentence_Break_Image (Item.SB).all
& ", "
& Line_Break_Image (Item.LB).all
& ',');
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put ('(');
for J in Item.B'Range loop
Counts (Item.B (J)) := Counts (Item.B (J)) + 1;
end loop;
Default := Counts (False) < Counts (True);
for J in Item.B'Range loop
if Item.B (J) /= Default then
N := N + 1;
if N = 1 then
Ada.Text_IO.Put (Boolean_Properties_Image (J).all);
else
Ada.Text_IO.Set_Col (Indent + 3);
Ada.Text_IO.Put ("| " & Boolean_Properties_Image (J).all);
end if;
end if;
end loop;
if N /= 0 then
if Ada.Text_IO.Col > 68 then
Ada.Text_IO.Set_Col (Indent + 6);
end if;
if not Default then
Ada.Text_IO.Put (" => True,");
else
Ada.Text_IO.Put (" => False,");
end if;
Ada.Text_IO.Set_Col (Indent + 1);
end if;
if Default then
Ada.Text_IO.Put ("others => True))");
else
Ada.Text_IO.Put ("others => False))");
end if;
end Put;
Groups : array (First_Stage_Index) of Group_Info
:= (others => (0, 0, 0));
Generated : array (First_Stage_Index) of Boolean := (others => False);
Default : First_Stage_Index := 0;
Index : First_Stage_Index := 0;
begin
Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, " ... core");
-- Pack groups: reuse groups with the same values.
for J in Groups'Range loop
for K in 0 .. J loop
if Core (Code_Unit_32 (K) * 256 .. Code_Unit_32 (K) * 256 + 255)
= Core (Code_Unit_32 (J) * 256 .. Code_Unit_32 (J) * 256 + 255)
then
Groups (J).Share := K;
Groups (K).Count := Groups (K).Count + 1;
if J = K then
Groups (K).Index := Index;
Index := Index + 1;
end if;
exit;
end if;
end loop;
end loop;
-- Generate core properties data file
for J in Groups'Range loop
if not Generated (Groups (J).Share) then
declare
Default : Core_Values;
Current : Core_Values;
First : Second_Stage_Index;
Last : Second_Stage_Index;
First_Code : Code_Point;
Last_Code : Code_Point;
begin
-- Looking for most useful set of values, it will be used for
-- others selector for generate more compact code.
declare
type Value_Count_Pair is record
V : Core_Values;
C : Natural;
end record;
Counts : array (Positive range 1 .. 256) of Value_Count_Pair
:= (others => <>);
Last : Natural := 0;
Maximum : Natural := 0;
Index : Positive := 1;
begin
for K in Second_Stage_Index loop
declare
C : constant Code_Point
:= Code_Unit_32 (J) * 256 + Code_Unit_32 (K);
R : Core_Values renames Core (C);
F : Boolean := False;
begin
-- Go throught known values and try to find the same
-- value.
for L in 1 .. Last loop
if Counts (L).V = R then
F := True;
Counts (L).C := Counts (L).C + 1;
if Maximum < Counts (L).C then
Maximum := Counts (L).C;
Default := Counts (L).V;
end if;
exit;
end if;
end loop;
-- If value is not found, then add it to the end of list.
if not F then
Last := Last + 1;
Counts (Last) := (R, 1);
end if;
end;
end loop;
end;
Put_File_Header
("Localization, Internationalization, Globalization for Ada",
2012,
2015);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
("pragma Restrictions (No_Elaboration_Code);");
Ada.Text_IO.Put_Line
("-- GNAT: enforce generation of preinitialized data section"
& " instead of");
Ada.Text_IO.Put_Line ("-- generation of elaboration code.");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
("package Matreshka.Internals.Unicode.Ucd.Core_"
& First_Stage_Image (Groups (J).Share)
& " is");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" pragma Preelaborate;");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
(" Group_" & First_Stage_Image (Groups (J).Share)
& " : aliased constant Core_Second_Stage");
Ada.Text_IO.Put (" := (");
for K in Second_Stage_Index loop
declare
Code : constant Code_Point
:= Code_Unit_32 (J) * 256 + Code_Unit_32 (K);
begin
if K = Second_Stage_Index'First then
Current := Core (Code);
First := K;
Last := First;
First_Code := Code;
Last_Code := Code;
elsif Core (Code) = Current then
Last := K;
Last_Code := Code;
else
if Current /= Default then
if First /= Last then
Ada.Text_IO.Put_Line
("16#"
& Second_Stage_Image (First)
& "# .. 16#"
& Second_Stage_Image (Last)
& "# => -- "
& Code_Point_Image (First_Code)
& " .. "
& Code_Point_Image (Last_Code));
Ada.Text_IO.Set_Col (11);
Put (Current);
Ada.Text_IO.Put (',');
else
Ada.Text_IO.Put_Line
("16#"
& Second_Stage_Image (First)
& "# => -- "
& Code_Point_Image (First_Code));
Ada.Text_IO.Set_Col (11);
Put (Current);
Ada.Text_IO.Put (',');
end if;
Ada.Text_IO.New_Line;
Ada.Text_IO.Set_Col (10);
end if;
Current := Core (Code);
First := K;
Last := First;
First_Code := Code;
Last_Code := First_Code;
end if;
end;
end loop;
if Current /= Default then
if First /= Last then
Ada.Text_IO.Put_Line
("16#"
& Second_Stage_Image (First)
& "# .. 16#"
& Second_Stage_Image (Last)
& "# => -- "
& Code_Point_Image (First_Code)
& " .. "
& Code_Point_Image (Last_Code));
Ada.Text_IO.Set_Col (11);
Put (Current);
Ada.Text_IO.Put (',');
else
Ada.Text_IO.Put_Line
("16#"
& Second_Stage_Image (First)
& "# => -- "
& Code_Point_Image (First_Code));
Ada.Text_IO.Set_Col (11);
Put (Current);
Ada.Text_IO.Put (',');
end if;
Ada.Text_IO.New_Line;
Ada.Text_IO.Set_Col (10);
end if;
Ada.Text_IO.Put_Line ("others =>");
Ada.Text_IO.Set_Col (11);
Put (Default);
Ada.Text_IO.Put_Line (");");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
("end Matreshka.Internals.Unicode.Ucd.Core_"
& First_Stage_Image (Groups (J).Share)
& ";");
Generated (J) := True;
end;
end if;
end loop;
Put_File_Header
("Localization, Internationalization, Globalization for Ada",
2009,
2012);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("pragma Restrictions (No_Elaboration_Code);");
Ada.Text_IO.Put_Line
("-- GNAT: enforce generation of preinitialized data section instead of");
Ada.Text_IO.Put_Line ("-- generation of elaboration code.");
Ada.Text_IO.New_Line;
for J in Groups'Range loop
if Groups (J).Share = J then
Ada.Text_IO.Put_Line
("with Matreshka.Internals.Unicode.Ucd.Core_"
& First_Stage_Image (J)
& ";");
end if;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("package Matreshka.Internals.Unicode.Ucd.Core is");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" pragma Preelaborate;");
Ada.Text_IO.New_Line;
for J in Groups'Range loop
if Groups (J).Share = J then
Ada.Text_IO.Put_Line
(" use Matreshka.Internals.Unicode.Ucd.Core_"
& First_Stage_Image (J)
& ";");
end if;
end loop;
declare
Maximum : Natural := 0;
N : Natural := 0;
begin
for J in Groups'Range loop
if Maximum < Groups (J).Count then
Maximum := Groups (J).Count;
Default := J;
end if;
end loop;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" Property : aliased constant Core_First_Stage");
Ada.Text_IO.Put (" := (");
for J in Groups'Range loop
if Groups (J).Share /= Default then
Ada.Text_IO.Put
("16#"
& First_Stage_Image (J)
& "# => Group_"
& First_Stage_Image (Groups (J).Share)
& "'Access,");
case N mod 2 is
when 0 =>
Ada.Text_IO.Set_Col (41);
when 1 =>
Ada.Text_IO.New_Line;
Ada.Text_IO.Set_Col (10);
when others =>
raise Program_Error;
end case;
N := N + 1;
end if;
end loop;
Ada.Text_IO.Put_Line
("others => Group_" & First_Stage_Image (Default) & "'Access);");
end;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("end Matreshka.Internals.Unicode.Ucd.Core;");
Ada.Text_IO.Put_Line (Ada.Text_IO.Standard_Error, " ... indexes");
Put_File_Header
("Localization, Internationalization, Globalization for Ada",
2011,
2011);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("pragma Restrictions (No_Elaboration_Code);");
Ada.Text_IO.Put_Line
("-- GNAT: enforce generation of preinitialized data section instead of");
Ada.Text_IO.Put_Line ("-- generation of elaboration code.");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("package Matreshka.Internals.Unicode.Ucd.Indexes is");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" pragma Preelaborate;");
declare
N : Natural := 0;
begin
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
(" Group_Index : constant array (First_Stage_Index) "
& "of First_Stage_Index");
Ada.Text_IO.Put (" := (");
for J in Groups'Range loop
if Groups (J).Share /= Default then
Ada.Text_IO.Put
("16#"
& First_Stage_Image (J)
& "# => 16#"
& First_Stage_Image (Groups (Groups (J).Share).Index)
& "#,");
case N mod 3 is
when 0 =>
Ada.Text_IO.Set_Col (32);
when 1 =>
Ada.Text_IO.Set_Col (54);
when 2 =>
Ada.Text_IO.New_Line;
Ada.Text_IO.Set_Col (10);
when others =>
raise Program_Error;
end case;
N := N + 1;
end if;
end loop;
Ada.Text_IO.Put_Line
("others => 16#"
& First_Stage_Image (Groups (Default).Index)
& "#);");
end;
declare
Count : Natural := 0;
begin
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
(" Base : constant array (First_Stage_Index range <>)"
& " of First_Stage_Index");
Ada.Text_IO.Put (" := (");
for J in Groups'Range loop
if Groups (J).Share = J then
if J /= 0 then
Ada.Text_IO.Put (',');
if Count mod 7 = 0 then
Ada.Text_IO.New_Line;
Ada.Text_IO.Put (" ");
else
Ada.Text_IO.Put (' ');
end if;
end if;
Ada.Text_IO.Put ("16#" & First_Stage_Image (J) & "#");
Count := Count + 1;
end if;
end loop;
Ada.Text_IO.Put_Line (");");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line
(" Base_Last : constant First_Stage_Index :="
& Natural'Image (Count - 1) & ";");
end;
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("end Matreshka.Internals.Unicode.Ucd.Indexes;");
end Gen_Props;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- P R J . E R R --
-- --
-- B o d y --
-- --
-- Copyright (C) 2002-2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Err_Vars;
with Output; use Output;
with Stringt; use Stringt;
package body Prj.Err is
---------------
-- Post_Scan --
---------------
procedure Post_Scan is
Debug_Tokens : constant Boolean := False;
begin
-- Change operator symbol to literal strings, since that's the way
-- we treat all strings in a project file.
if Token = Tok_Operator_Symbol
or else Token = Tok_String_Literal
then
Token := Tok_String_Literal;
String_To_Name_Buffer (String_Literal_Id);
Token_Name := Name_Find;
end if;
if Debug_Tokens then
Write_Line (Token_Type'Image (Token));
if Token = Tok_Identifier
or else Token = Tok_String_Literal
then
Write_Line (" " & Get_Name_String (Token_Name));
end if;
end if;
end Post_Scan;
---------------
-- Error_Msg --
---------------
procedure Error_Msg
(Flags : Processing_Flags;
Msg : String;
Location : Source_Ptr := No_Location;
Project : Project_Id := null)
is
Real_Location : Source_Ptr := Location;
begin
-- Don't post message if incompleted with's (avoid junk cascaded errors)
if Flags.Incomplete_Withs then
return;
end if;
-- Display the error message in the traces so that it appears in the
-- correct location in the traces (otherwise error messages are only
-- displayed at the end and it is difficult to see when they were
-- triggered)
if Current_Verbosity = High then
Debug_Output ("ERROR: " & Msg);
end if;
-- If location of error is unknown, use the location of the project
if Real_Location = No_Location
and then Project /= null
then
Real_Location := Project.Location;
end if;
if Real_Location = No_Location then
-- If still null, we are parsing a project that was created in-memory
-- so we shouldn't report errors for projects that the user has no
-- access to in any case.
if Current_Verbosity = High then
Debug_Output ("Error in in-memory project, ignored");
end if;
return;
end if;
-- Report the error through Errutil, so that duplicate errors are
-- properly removed, messages are sorted, and correctly interpreted,...
Errutil.Error_Msg (Msg, Real_Location);
-- Let the application know there was an error
if Flags.Report_Error /= null then
Flags.Report_Error
(Project,
Is_Warning =>
Msg (Msg'First) = '?'
or else (Msg (Msg'First) = '<'
and then Err_Vars.Error_Msg_Warn)
or else (Msg (Msg'First) = '\'
and then Msg (Msg'First + 1) = '<'
and then Err_Vars.Error_Msg_Warn));
end if;
end Error_Msg;
end Prj.Err;
|
package physics.Joint.hinge
--
-- An interface to a hinge joint.
--
is
type Item is limited interface
and Joint.item;
type View is access all Item'Class;
procedure Limits_are (Self : in out Item; Low, High : in Real;
Softness : in Real := 0.9;
biasFactor : in Real := 0.3;
relaxationFactor : in Real := 1.0) is abstract;
function lower_Limit (Self : in Item) return Real is abstract;
function upper_Limit (Self : in Item) return Real is abstract;
function Angle (Self : in Item) return Real is abstract;
end physics.Joint.hinge;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This package provides set of Intel's specific data types for MMX/SSE/AVX
-- instruction sets. Children packages provide operations on this types,
-- one child package covers one instruction set. Types declarations are
-- specific for GNAT compiler. The way how subprograms are defined is also
-- GNAT specific, it allows to highly optimize code and replace one function
-- by one instruction in most cases.
------------------------------------------------------------------------------
with Ada.Unchecked_Conversion;
with Interfaces;
package Matreshka.SIMD.Intel is
pragma Pure;
-- 256-bit types
type v32qi is array (1 .. 32) of Interfaces.Integer_8;
for v32qi'Alignment use 32;
pragma Machine_Attribute (v32qi, "vector_type");
pragma Machine_Attribute (v32qi, "may_alias");
type v16hi is array (1 .. 16) of Interfaces.Integer_16;
for v16hi'Alignment use 32;
pragma Machine_Attribute (v16hi, "vector_type");
pragma Machine_Attribute (v16hi, "may_alias");
type v8si is array (1 .. 8) of Interfaces.Integer_32;
for v8si'Alignment use 32;
pragma Machine_Attribute (v8si, "vector_type");
pragma Machine_Attribute (v8si, "may_alias");
type v4di is array (1 .. 4) of Interfaces.Integer_64;
for v4di'Alignment use 32;
pragma Machine_Attribute (v4di, "vector_type");
pragma Machine_Attribute (v4di, "may_alias");
type v8sf is array (1 .. 8) of Interfaces.IEEE_Float_32;
for v8sf'Alignment use 32;
pragma Machine_Attribute (v8sf, "vector_type");
pragma Machine_Attribute (v8sf, "may_alias");
type v4df is array (1 .. 4) of Interfaces.IEEE_Float_64;
for v4df'Alignment use 32;
pragma Machine_Attribute (v4df, "vector_type");
pragma Machine_Attribute (v4df, "may_alias");
-- 128-bit types
type v16qi is array (1 .. 16) of Interfaces.Integer_8;
for v16qi'Alignment use 16;
pragma Machine_Attribute (v16qi, "vector_type");
pragma Machine_Attribute (v16qi, "may_alias");
type v8hi is array (1 .. 8) of Interfaces.Integer_16;
for v8hi'Alignment use 16;
pragma Machine_Attribute (v8hi, "vector_type");
pragma Machine_Attribute (v8hi, "may_alias");
type v4si is array (1 .. 4) of Interfaces.Integer_32;
for v4si'Alignment use 16;
pragma Machine_Attribute (v4si, "vector_type");
pragma Machine_Attribute (v4si, "may_alias");
type v2di is array (1 .. 2) of Interfaces.Integer_64;
for v2di'Alignment use 16;
pragma Machine_Attribute (v2di, "vector_type");
pragma Machine_Attribute (v2di, "may_alias");
type v4sf is array (1 .. 4) of Interfaces.IEEE_Float_32;
for v4sf'Alignment use 16;
pragma Machine_Attribute (v4sf, "vector_type");
pragma Machine_Attribute (v4sf, "may_alias");
type v2df is array (1 .. 2) of Interfaces.IEEE_Float_64;
for v2df'Alignment use 16;
pragma Machine_Attribute (v2df, "vector_type");
pragma Machine_Attribute (v2df, "may_alias");
-- 64-bit types
type v8qi is array (1 .. 8) of Interfaces.Integer_8;
for v8qi'Alignment use 8;
pragma Machine_Attribute (v8qi, "vector_type");
pragma Machine_Attribute (v8qi, "may_alias");
type v4hi is array (1 .. 4) of Interfaces.Integer_16;
for v4hi'Alignment use 8;
pragma Machine_Attribute (v4hi, "vector_type");
pragma Machine_Attribute (v4hi, "may_alias");
type v2si is array (1 .. 2) of Interfaces.Integer_32;
for v2si'Alignment use 8;
pragma Machine_Attribute (v2si, "vector_type");
pragma Machine_Attribute (v2si, "may_alias");
type v1di is array (1 .. 1) of Interfaces.Integer_64;
for v1di'Alignment use 8;
pragma Machine_Attribute (v1di, "vector_type");
pragma Machine_Attribute (v1di, "may_alias");
-- Type conversion operations.
function To_v16hi is new Ada.Unchecked_Conversion (v4df, v16hi);
function To_v4df is new Ada.Unchecked_Conversion (v16hi, v4df);
function To_v16qi is new Ada.Unchecked_Conversion (v8hi, v16qi);
function To_v8hi is new Ada.Unchecked_Conversion (v4si, v8hi);
function To_v8hi is new Ada.Unchecked_Conversion (v2di, v8hi);
function To_v4si is new Ada.Unchecked_Conversion (v8hi, v4si);
function To_v2di is new Ada.Unchecked_Conversion (v4si, v2di);
function To_v2di is new Ada.Unchecked_Conversion (v8hi, v2di);
function To_v8qi is new Ada.Unchecked_Conversion (v2si, v8qi);
function To_v4hi is new Ada.Unchecked_Conversion (v8qi, v4hi);
function To_v4hi is new Ada.Unchecked_Conversion (v2si, v4hi);
function To_v2si is new Ada.Unchecked_Conversion (v4hi, v2si);
function To_v2si is new Ada.Unchecked_Conversion (v8qi, v2si);
end Matreshka.SIMD.Intel;
|
procedure Reversal (T: in out Tomb) is
I : Index := T'First;
J : Index := T'Last;
begin
for S in 1 .. (T'Length / 2) loop
Swap(T(I), T(J));
I := Index'Succ(I);
J := Index'Pred(J);
end loop;
end Reversal;
-- http://zsv.web.elte.hu/ada_regizhk/
-- http://zsv.web.elte.hu/ada_regizhk/regizh.pdf
|
-- Concurrency can be offered by the OS, the language, or a combination
-- Link to some papers that say that threading can't be a library.
-- Ousterhout has an interesting paper here that shows that you can't guarantee pthreads correctness.
-- Processes offer protection but are too heavy-weight.
-- Compiler must take care of low-level thread management, as opposed to RTOS
with Ada.Text_IO;
procedure Tasking is
-- Specification of nested task
task HelloTask;
task body HelloTask is
begin
-- Task body begins executing as soon as Tasking starts
for idx in 1 .. 5 loop
Ada.Text_IO.Put_Line("The task says hello.");
delay 1.0;
end loop;
end HelloTask;
begin
Ada.Text_IO.Put_Line("Starting Program!");
-- Tasking ends when both the body and task have ended
-- Task must terminate
end Tasking;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed;
package body Aids.Env is
Function Find(Env : in Typ;
Key : in String;
Found : in out Boolean
) return String is
Begin
Found := Env.Contains( Key );
Return (if not Found then "" else Env(Key));
End Find;
function Index_Of(Line: in String; X: in Character; Result: out Integer) return Boolean is
Index : Natural renames Ada.strings.Fixed.Index(
Source => Line, -- The String we're searching,
Pattern => (1 => X), -- the *Substring* to search for;
From => Line'First -- the point we start from.
);
begin
Return Found : constant Boolean := Index in Positive do
Result:= Index;
End return;
end;
function Slurp(File_Path: String) return Env_Hashed_Map.Map is
File: File_Type;
Line_Number: Integer := 1;
begin
Return Result: Env_Hashed_Map.Map do
Open(File => File,
Mode => In_File,
Name => File_Path);
while not End_Of_File(File) loop
declare
Line: String := Get_Line(File);
Index : Integer;
begin
if Index_Of(Line, '=', Index) then
declare
Use Ada.Strings;
Prev : Natural renames Positive'Pred( Index );
Next : Positive renames Positive'Succ( index );
-- Rename the Trim-function, and give it default for
-- "both sides"; this handles a line like:
-- " This_key = Some_Value "
Function Trim(Object : String;
Sides : Trim_End:= Both
) return String
renames Fixed.Trim;
Key : String renames Trim(Line(Line'First..Prev));
Value : String renames Trim(Line(Next..Line'Last) );
begin
Env_Hashed_Map.Insert(Result, Key, Value);
end;
else
raise Syntax_Error with (File_Path
& ":"
& Integer'Image(Line_Number)
& ": Expected separator `=`");
end if;
Line_Number := Line_Number + 1;
end;
end loop;
Close(File);
End return;
end;
function Find(Env: in Typ; Key: in Unbounded_String; Value: out Unbounded_String) return Boolean is
Use Env_Hashed_Map;
-- Renaming a function's return.
C : Cursor renames Find(Env, To_String(Key));
begin
-- Extended return example.
Return Occupied : Constant Boolean := Has_Element(C) do
if Occupied then
Value := To_Unbounded_String( Env_Hashed_Map.Element(C) );
end if;
End return;
end;
end Aids.Env;
|
private with Interfaces.C;
package GNATCOLL.uuid is
type UUID_Variant is (NCS, DCE, MICROSOFT, OTHER);
type UUID_Type is (DCE_TIME, DCE_RANDOM, DCE_UNDEFINED);
type UUID is tagged private;
procedure Clear (this : in out UUID);
function "<" (l, r : UUID) return Boolean;
function ">" (l, r : UUID) return Boolean;
function "=" (l, r : UUID) return Boolean;
procedure Generate (this : out UUID);
function Generate return UUID;
function Generate_Random return UUID;
procedure Generate_Random (this : out UUID);
function Generate_Time return UUID;
procedure Generate_Time (this : out UUID);
function Is_Null (this : UUID) return Boolean;
function Parse (data : String) return UUID;
function Unparse (this : UUID) return String;
function Unparse_Lower (this : UUID) return String;
function Unparse_Upper (this : UUID) return String;
-- function time (arg1 : access uuid;
-- arg2 : access bits_time_h.timeval) return time_h.time_t;
--
function Get_Type (this : UUID) return UUID_Type;
function Get_Variant (this : UUID) return UUID_Variant;
PARSE_ERROR : exception;
private
type uuid_t is array (0 .. 15) of aliased Interfaces.C.unsigned_char;
type UUID is tagged record
data : uuid_t;
end record;
end gnatcoll.uuid;
|
-- { dg-compile }
-- { dg-options "-O2 -gnato -fdump-tree-optimized" }
package body Opt37 is
function To_Unchecked (Bits : T_Bit_Array) return Unsigned32 is
Value : Unsigned32 := 0;
begin
for I in Bits'Range loop
Value := Value * 2 + Unsigned32 (Bits(I));
end loop;
return Value;
end;
function To_Scalar (Bits : T_Bit_Array) return Positive is
Tmp : Unsigned32;
Value : Positive;
begin
Tmp := To_Unchecked (Bits);
if Tmp in 0 .. Unsigned32 (Positive'last) then
Value := Positive (Tmp);
else
Value := -Positive (Unsigned32'last - Tmp);
if Value > Positive'first then
Value := Value - 1;
else
raise Program_Error;
end if;
end if;
return Value;
end;
function Func (Bit_Array : T_Bit_Array;
Bit_Index : T_Bit_Index) return Positive is
begin
return To_Scalar (Bit_Array (Bit_Index .. Bit_Index + 1));
end;
end Opt37;
-- { dg-final { scan-tree-dump-not "alloca" "optimized" } }
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . D I S P A T C H I N G . E D F --
-- --
-- S p e c --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. In accordance with the copyright of that document, you can freely --
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
-- This unit is not implemented in typical GNAT implementations that lie on
-- top of operating systems, because it is infeasible to implement in such
-- environments.
-- If a target environment provides appropriate support for this package,
-- then the Unimplemented_Unit pragma should be removed from this spec and
-- an appropriate body provided.
with Ada.Real_Time;
with Ada.Task_Identification;
package Ada.Dispatching.EDF is
pragma Preelaborate;
pragma Unimplemented_Unit;
subtype Deadline is Ada.Real_Time.Time;
Default_Deadline : constant Deadline := Ada.Real_Time.Time_Last;
procedure Set_Deadline
(D : Deadline;
T : Ada.Task_Identification.Task_Id :=
Ada.Task_Identification.Current_Task);
procedure Delay_Until_And_Set_Deadline
(Delay_Until_Time : Ada.Real_Time.Time;
Deadline_Offset : Ada.Real_Time.Time_Span);
function Get_Deadline
(T : Ada.Task_Identification.Task_Id :=
Ada.Task_Identification.Current_Task)
return Deadline
with
SPARK_Mode,
Volatile_Function,
Global => Ada.Task_Identification.Tasking_State;
end Ada.Dispatching.EDF;
|
pragma Style_Checks (Off);
-- This spec has been automatically generated from ATSAMD51G19A.svd
pragma Restrictions (No_Elaboration_Code);
with HAL;
with System;
package SAM_SVD.CCL is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Control
type CCL_CTRL_Register is record
-- Software Reset
SWRST : Boolean := False;
-- Enable
ENABLE : Boolean := False;
-- unspecified
Reserved_2_5 : HAL.UInt4 := 16#0#;
-- Run in Standby
RUNSTDBY : Boolean := False;
-- unspecified
Reserved_7_7 : HAL.Bit := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for CCL_CTRL_Register use record
SWRST at 0 range 0 .. 0;
ENABLE at 0 range 1 .. 1;
Reserved_2_5 at 0 range 2 .. 5;
RUNSTDBY at 0 range 6 .. 6;
Reserved_7_7 at 0 range 7 .. 7;
end record;
-- Sequential Selection
type SEQCTRL_SEQSELSelect is
(-- Sequential logic is disabled
DISABLE,
-- D flip flop
DFF,
-- JK flip flop
JK,
-- D latch
LATCH,
-- RS latch
RS)
with Size => 4;
for SEQCTRL_SEQSELSelect use
(DISABLE => 0,
DFF => 1,
JK => 2,
LATCH => 3,
RS => 4);
-- SEQ Control x
type CCL_SEQCTRL_Register is record
-- Sequential Selection
SEQSEL : SEQCTRL_SEQSELSelect := SAM_SVD.CCL.DISABLE;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 8,
Bit_Order => System.Low_Order_First;
for CCL_SEQCTRL_Register use record
SEQSEL at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
end record;
-- SEQ Control x
type CCL_SEQCTRL_Registers is array (0 .. 1) of CCL_SEQCTRL_Register;
-- Filter Selection
type LUTCTRL_FILTSELSelect is
(-- Filter disabled
DISABLE,
-- Synchronizer enabled
SYNCH,
-- Filter enabled
FILTER)
with Size => 2;
for LUTCTRL_FILTSELSelect use
(DISABLE => 0,
SYNCH => 1,
FILTER => 2);
-- Input Selection 0
type LUTCTRL_INSEL0Select is
(-- Masked input
MASK,
-- Feedback input source
FEEDBACK,
-- Linked LUT input source
LINK,
-- Event input source
EVENT,
-- I/O pin input source
IO,
-- AC input source
AC,
-- TC input source
TC,
-- Alternate TC input source
ALTTC,
-- TCC input source
TCC,
-- SERCOM input source
SERCOM)
with Size => 4;
for LUTCTRL_INSEL0Select use
(MASK => 0,
FEEDBACK => 1,
LINK => 2,
EVENT => 3,
IO => 4,
AC => 5,
TC => 6,
ALTTC => 7,
TCC => 8,
SERCOM => 9);
-- Input Selection 1
type LUTCTRL_INSEL1Select is
(-- Masked input
MASK,
-- Feedback input source
FEEDBACK,
-- Linked LUT input source
LINK,
-- Event input source
EVENT,
-- I/O pin input source
IO,
-- AC input source
AC,
-- TC input source
TC,
-- Alternate TC input source
ALTTC,
-- TCC input source
TCC,
-- SERCOM input source
SERCOM)
with Size => 4;
for LUTCTRL_INSEL1Select use
(MASK => 0,
FEEDBACK => 1,
LINK => 2,
EVENT => 3,
IO => 4,
AC => 5,
TC => 6,
ALTTC => 7,
TCC => 8,
SERCOM => 9);
-- Input Selection 2
type LUTCTRL_INSEL2Select is
(-- Masked input
MASK,
-- Feedback input source
FEEDBACK,
-- Linked LUT input source
LINK,
-- Event input source
EVENT,
-- I/O pin input source
IO,
-- AC input source
AC,
-- TC input source
TC,
-- Alternate TC input source
ALTTC,
-- TCC input source
TCC,
-- SERCOM input source
SERCOM)
with Size => 4;
for LUTCTRL_INSEL2Select use
(MASK => 0,
FEEDBACK => 1,
LINK => 2,
EVENT => 3,
IO => 4,
AC => 5,
TC => 6,
ALTTC => 7,
TCC => 8,
SERCOM => 9);
subtype CCL_LUTCTRL_TRUTH_Field is HAL.UInt8;
-- LUT Control x
type CCL_LUTCTRL_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
-- LUT Enable
ENABLE : Boolean := False;
-- unspecified
Reserved_2_3 : HAL.UInt2 := 16#0#;
-- Filter Selection
FILTSEL : LUTCTRL_FILTSELSelect := SAM_SVD.CCL.DISABLE;
-- unspecified
Reserved_6_6 : HAL.Bit := 16#0#;
-- Edge Selection
EDGESEL : Boolean := False;
-- Input Selection 0
INSEL0 : LUTCTRL_INSEL0Select := SAM_SVD.CCL.MASK;
-- Input Selection 1
INSEL1 : LUTCTRL_INSEL1Select := SAM_SVD.CCL.MASK;
-- Input Selection 2
INSEL2 : LUTCTRL_INSEL2Select := SAM_SVD.CCL.MASK;
-- Inverted Event Input Enable
INVEI : Boolean := False;
-- LUT Event Input Enable
LUTEI : Boolean := False;
-- LUT Event Output Enable
LUTEO : Boolean := False;
-- unspecified
Reserved_23_23 : HAL.Bit := 16#0#;
-- Truth Value
TRUTH : CCL_LUTCTRL_TRUTH_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CCL_LUTCTRL_Register use record
Reserved_0_0 at 0 range 0 .. 0;
ENABLE at 0 range 1 .. 1;
Reserved_2_3 at 0 range 2 .. 3;
FILTSEL at 0 range 4 .. 5;
Reserved_6_6 at 0 range 6 .. 6;
EDGESEL at 0 range 7 .. 7;
INSEL0 at 0 range 8 .. 11;
INSEL1 at 0 range 12 .. 15;
INSEL2 at 0 range 16 .. 19;
INVEI at 0 range 20 .. 20;
LUTEI at 0 range 21 .. 21;
LUTEO at 0 range 22 .. 22;
Reserved_23_23 at 0 range 23 .. 23;
TRUTH at 0 range 24 .. 31;
end record;
-- LUT Control x
type CCL_LUTCTRL_Registers is array (0 .. 3) of CCL_LUTCTRL_Register;
-----------------
-- Peripherals --
-----------------
-- Configurable Custom Logic
type CCL_Peripheral is record
-- Control
CTRL : aliased CCL_CTRL_Register;
-- SEQ Control x
SEQCTRL : aliased CCL_SEQCTRL_Registers;
-- LUT Control x
LUTCTRL : aliased CCL_LUTCTRL_Registers;
end record
with Volatile;
for CCL_Peripheral use record
CTRL at 16#0# range 0 .. 7;
SEQCTRL at 16#4# range 0 .. 15;
LUTCTRL at 16#8# range 0 .. 127;
end record;
-- Configurable Custom Logic
CCL_Periph : aliased CCL_Peripheral
with Import, Address => CCL_Base;
end SAM_SVD.CCL;
|
with Ada.Directories;
with Ada.Text_IO;
with SDL.RWops.Streams;
procedure Rwops is
package Text_IO renames Ada.Text_IO;
package Directories renames Ada.Directories;
procedure RWops_Tests is
begin
declare
use type SDL.RWops.Offsets;
Op : constant SDL.RWops.RWops := SDL.RWops.From_File ("test", SDL.RWops.Read_Binary);
Offset : SDL.RWops.Offsets := SDL.RWops.Error_Offset;
begin
Text_IO.Put_Line ("Testing RW_Seek, RW_Tell and RW_Size:");
-- Moving the file offset in steps of size 10.
for I in 1 .. 10 loop
Offset := SDL.RWops.Seek (Context => Op,
Offset => 10,
Whence => SDL.RWops.RW_Seek_Cur);
Text_IO.Put ("Current offset (should be" & Integer'Image (10 * I) & "):");
Text_IO.Put (SDL.RWops.Offsets'Image (Offset) & " (returned value) ");
Offset := SDL.RWops.Tell (Context => Op);
Text_IO.Put (SDL.RWops.Offsets'Image (Offset) & " (from RW_Tell)");
Text_IO.New_Line;
end loop;
Text_IO.New_Line;
Offset := SDL.RWops.Seek
(Context => Op,
Offset => -10,
Whence => SDL.RWops.RW_Seek_End);
Text_IO.Put_Line ("offset 10 before end of file:" & SDL.RWops.Offsets'Image (Offset));
Offset := SDL.RWops.Size (Op);
Text_IO.Put_Line ("offset Rw_Size (should be previous value + 10):" & SDL.RWops.Offsets'Image (Offset));
SDL.RWops.Close (Op);
end;
declare
use type SDL.RWops.Offsets;
Op : constant SDL.RWops.RWops := SDL.RWops.From_File ("test.bin", SDL.RWops.Create_To_Write);
begin
Text_IO.New_Line;
Text_IO.Put_Line ("Writing some numbers as Uint8 into a file...");
for I in 1 .. 16 loop
SDL.RWops.Write_U_8 (Op, SDL.RWops.Uint8 (I));
end loop;
SDL.RWops.Close (Op);
end;
declare
use type SDL.RWops.Offsets;
Op : SDL.RWops.RWops := SDL.RWops.From_File ("test.bin", SDL.RWops.Read_Binary);
Result8 : SDL.RWops.Uint8 := 0;
Result32 : SDL.RWops.Uint32 := 0;
begin
Text_IO.Put_Line ("Reading Uint8 from file...");
for I in 1 .. 16 loop
Result8 := SDL.RWops.Read_U_8 (Op);
Text_IO.Put_Line ("read Uint8:" & SDL.RWops.Uint8'Image (Result8));
end loop;
SDL.RWops.Close (Op);
Text_IO.New_Line;
Text_IO.Put_Line ("Reading Uint32 from file...");
SDL.RWops.From_File ("test.bin", SDL.RWops.Read_Binary, Op);
for I in 1 .. 4 loop
Result32 := SDL.RWops.Read_LE_32 (Op);
Text_IO.Put_Line ("read Uint32:" & SDL.RWops.Uint32'Image (Result32));
end loop;
SDL.RWops.Close (Op);
end;
Text_IO.New_Line;
Text_IO.Put_Line ("Base path: " & SDL.RWops.Base_Path);
declare
Tmp_Path : constant String := Directories.Current_Directory;
Pref_Path : constant String := SDL.RWops.Preferences_Path ("org", "app");
begin
Text_IO.Put_Line ("Pref path: " & Pref_Path);
if Directories.Exists (Pref_Path) then
-- Remove app/org if it was created.
Directories.Set_Directory (Pref_Path);
Directories.Set_Directory ("..");
Directories.Delete_Directory ("app");
Directories.Set_Directory ("..");
Directories.Delete_Directory ("org");
Directories.Set_Directory (Tmp_Path);
end if;
end;
end RWops_Tests;
procedure RWops_Streams_Test is
-- Dummy type to write into and read from stream.
type Complicated_Union (B : Boolean := True) is
record
I : Integer := 0;
S : String (1 .. 5) := "hello";
case B is
when True =>
T : String (1 .. 4) := "true";
F : Long_Float := 3.14159265;
when False =>
C : Character := 'X';
end case;
end record;
begin
Text_IO.Put_Line ("Testing RWops.Streams:");
Text_IO.Put_Line ("Creating file-stream ""out.bin""...");
declare
W_Stream : aliased SDL.RWops.Streams.RWops_Stream := SDL.RWops.Streams.Open
(SDL.RWops.From_File
("out.bin",
SDL.RWops.Create_To_Write_Binary));
I : constant Integer := 42;
S : constant String := "Hello, world!!!";
T_True : Complicated_Union;
T_False : Complicated_Union (False);
begin
Text_IO.Put_Line ("Writing:" & I'Img);
Integer'Write (W_Stream'Access, I);
Text_IO.Put_Line ("Writing: " & S);
String'Write (W_Stream'Access, S);
Text_IO.Put_Line ("Writing two objects of a more complex type...");
Complicated_Union'Output (W_Stream'Access, T_True);
Complicated_Union'Output (W_Stream'Access, T_False);
Text_IO.Put_Line ("Closing stream.");
W_Stream.Close;
end;
declare
R_Stream : aliased SDL.RWops.Streams.RWops_Stream := SDL.RWops.Streams.Open
(SDL.RWops.From_File
("out.bin",
SDL.RWops.Read_Binary));
I : Integer := 0;
S : String := "xxxxxxxxxxxxxxx";
T_True : Complicated_Union;
T_False : Complicated_Union;
begin
Text_IO.Put_Line ("Now reading from file-stream...");
Integer'Read (R_Stream'Access, I);
String'Read (R_Stream'Access, S);
T_True := Complicated_Union'Input (R_Stream'Access);
T_False := Complicated_Union'Input (R_Stream'Access);
R_Stream.Close;
Text_IO.Put_Line (I'Img);
Text_IO.Put_Line (S);
Text_IO.Put_Line (T_True.F'Img);
Text_IO.Put_Line (T_False.C'Img);
end;
declare
Op : SDL.RWops.RWops;
Stream : aliased SDL.RWops.Streams.RWops_Stream;
I : Integer := 0;
S : String := "xxxxxxxxxxxxxxx";
T_True : Complicated_Union;
T_False : Complicated_Union;
begin
SDL.RWops.From_File (File_Name => "out.bin",
Mode => SDL.RWops.Read_Binary,
Ops => Op);
SDL.RWops.Streams.Open
(Op => Op,
Stream => Stream);
Integer'Read (Stream'Access, I);
String'Read (Stream'Access, S);
T_True := Complicated_Union'Input (Stream'Access);
T_False := Complicated_Union'Input (Stream'Access);
Stream.Close;
Text_IO.Put_Line (I'Img);
Text_IO.Put_Line (S);
Text_IO.Put_Line (T_True.F'Img);
Text_IO.Put_Line (T_False.C'Img);
end;
end RWops_Streams_Test;
begin
RWops_Tests;
RWops_Streams_Test;
exception
when SDL.RWops.RWops_Error =>
Text_IO.Put_Line ("Make sure you have a file named 'test' in this directory, it can be any file.");
end Rwops;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- SYSTEM.MACHINE_STATE_OPERATIONS --
-- --
-- B o d y --
-- (Version for Alpha/VMS) --
-- --
-- $Revision$
-- --
-- Copyright (C) 2001 Ada Core Technologies, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This version of System.Machine_State_Operations is for use on
-- Alpha systems running VMS.
with System.Memory;
with System.Aux_DEC; use System.Aux_DEC;
with Unchecked_Conversion;
package body System.Machine_State_Operations is
use System.Exceptions;
subtype Cond_Value_Type is Unsigned_Longword;
-- Record layouts copied from Starlet.
type ICB_Fflags_Bits_Type is record
Exception_Frame : Boolean;
Ast_Frame : Boolean;
Bottom_Of_Stack : Boolean;
Base_Frame : Boolean;
Filler_1 : Unsigned_20;
end record;
for ICB_Fflags_Bits_Type use record
Exception_Frame at 0 range 0 .. 0;
Ast_Frame at 0 range 1 .. 1;
Bottom_Of_Stack at 0 range 2 .. 2;
Base_Frame at 0 range 3 .. 3;
Filler_1 at 0 range 4 .. 23;
end record;
for ICB_Fflags_Bits_Type'Size use 24;
ICB_Fflags_Bits_Type_Init : constant ICB_Fflags_Bits_Type :=
(ExceptIon_Frame => False,
Ast_Frame => False,
Bottom_Of_STACK => False,
Base_Frame => False,
Filler_1 => 0);
type ICB_Hdr_Quad_Type is record
Context_Length : Unsigned_Longword;
Fflags_Bits : ICB_Fflags_Bits_Type;
Block_Version : Unsigned_Byte;
end record;
for ICB_Hdr_Quad_Type use record
Context_Length at 0 range 0 .. 31;
Fflags_Bits at 4 range 0 .. 23;
Block_Version at 7 range 0 .. 7;
end record;
for ICB_Hdr_Quad_Type'Size use 64;
ICB_Hdr_Quad_Type_Init : constant ICB_Hdr_Quad_Type :=
(Context_Length => 0,
Fflags_Bits => ICB_Fflags_Bits_Type_Init,
Block_Version => 0);
type Invo_Context_Blk_Type is record
--
-- The first quadword contains:
-- o The length of the structure in bytes (a longword field)
-- o The frame flags (a 3 byte field of bits)
-- o The version number (a 1 byte field)
--
Hdr_Quad : ICB_Hdr_Quad_Type;
--
-- The address of the procedure descriptor for the procedure.
--
Procedure_Descriptor : Unsigned_Quadword;
--
-- The current PC of a given procedure invocation.
--
Program_Counter : Integer_64;
--
-- The current PS of a given procedure invocation.
--
Processor_Status : Integer_64;
--
-- The register contents areas. 31 for scalars, 31 for float.
--
Ireg : Unsigned_Quadword_Array (0 .. 30);
Freg : Unsigned_Quadword_Array (0 .. 30);
--
-- The following is an "internal" area that's reserved for use by
-- the operating system. It's size may vary over time.
--
System_Defined : Unsigned_Quadword_Array (0 .. 1);
----Component(s) below are defined as comments since they
----overlap other fields
----
----Chfctx_Addr : Unsigned_Quadword;
--
-- Align to octaword.
--
Filler_1 : String (1 .. 0);
end record;
for Invo_Context_Blk_Type use record
Hdr_Quad at 0 range 0 .. 63;
Procedure_Descriptor at 8 range 0 .. 63;
Program_Counter at 16 range 0 .. 63;
Processor_Status at 24 range 0 .. 63;
Ireg at 32 range 0 .. 1983;
Freg at 280 range 0 .. 1983;
System_Defined at 528 range 0 .. 127;
----Component representation spec(s) below are defined as
----comments since they overlap other fields
----
----Chfctx_Addr at 528 range 0 .. 63;
Filler_1 at 544 range 0 .. -1;
end record;
for Invo_Context_Blk_Type'Size use 4352;
Invo_Context_Blk_Type_Init : constant Invo_Context_Blk_Type :=
(Hdr_Quad => ICB_Hdr_Quad_Type_Init,
Procedure_Descriptor => (0, 0),
Program_Counter => 0,
Processor_Status => 0,
Ireg => (others => (0, 0)),
Freg => (others => (0, 0)),
System_Defined => (others => (0, 0)),
Filler_1 => (others => ASCII.NUL));
subtype Invo_Handle_Type is Unsigned_Longword;
type Invo_Handle_Access_Type is access all Invo_Handle_Type;
function Fetch is new Fetch_From_Address (Code_Loc);
function To_Invo_Handle_Access is new Unchecked_Conversion
(Machine_State, Invo_Handle_Access_Type);
function To_Machine_State is new Unchecked_Conversion
(System.Address, Machine_State);
function To_Code_Loc is new Unchecked_Conversion
(Unsigned_Longword, Code_Loc);
----------------------------
-- Allocate_Machine_State --
----------------------------
function Allocate_Machine_State return Machine_State is
begin
return To_Machine_State
(Memory.Alloc (Invo_Handle_Type'Max_Size_In_Storage_Elements));
end Allocate_Machine_State;
-------------------
-- Enter_Handler --
-------------------
procedure Enter_Handler (M : Machine_State; Handler : Handler_Loc) is
procedure Get_Invo_Context (
Result : out Unsigned_Longword; -- return value
Invo_Handle : in Invo_Handle_Type;
Invo_Context : out Invo_Context_Blk_Type);
pragma Interface (External, Get_Invo_Context);
pragma Import_Valued_Procedure (Get_Invo_Context, "LIB$GET_INVO_CONTEXT",
(Unsigned_Longword, Invo_Handle_Type, Invo_Context_Blk_Type),
(Value, Value, Reference));
ICB : Invo_Context_Blk_Type;
procedure Goto_Unwind (
Status : out Cond_Value_Type; -- return value
Target_Invo : in Address := Address_Zero;
Target_PC : in Address := Address_Zero;
New_R0 : in Unsigned_Quadword
:= Unsigned_Quadword'Null_Parameter;
New_R1 : in Unsigned_Quadword
:= Unsigned_Quadword'Null_Parameter);
pragma Interface (External, Goto_Unwind);
pragma Import_Valued_Procedure
(Goto_Unwind, "SYS$GOTO_UNWIND",
(Cond_Value_Type, Address, Address,
Unsigned_Quadword, Unsigned_Quadword),
(Value, Reference, Reference,
Reference, Reference));
Status : Cond_Value_Type;
begin
Get_Invo_Context (Status, To_Invo_Handle_Access (M).all, ICB);
Goto_Unwind
(Status, System.Address (To_Invo_Handle_Access (M).all), Handler);
end Enter_Handler;
----------------
-- Fetch_Code --
----------------
function Fetch_Code (Loc : Code_Loc) return Code_Loc is
begin
-- The starting address is in the second longword pointed to by Loc.
return Fetch (System.Aux_DEC."+" (Loc, 8));
end Fetch_Code;
------------------------
-- Free_Machine_State --
------------------------
procedure Free_Machine_State (M : in out Machine_State) is
procedure Gnat_Free (M : in Invo_Handle_Access_Type);
pragma Import (C, Gnat_Free, "__gnat_free");
begin
Gnat_Free (To_Invo_Handle_Access (M));
M := Machine_State (Null_Address);
end Free_Machine_State;
------------------
-- Get_Code_Loc --
------------------
function Get_Code_Loc (M : Machine_State) return Code_Loc is
procedure Get_Invo_Context (
Result : out Unsigned_Longword; -- return value
Invo_Handle : in Invo_Handle_Type;
Invo_Context : out Invo_Context_Blk_Type);
pragma Interface (External, Get_Invo_Context);
pragma Import_Valued_Procedure (Get_Invo_Context, "LIB$GET_INVO_CONTEXT",
(Unsigned_Longword, Invo_Handle_Type, Invo_Context_Blk_Type),
(Value, Value, Reference));
Asm_Call_Size : constant := 4;
-- Under VMS a call
-- asm instruction takes 4 bytes. So we must remove this amount.
ICB : Invo_Context_Blk_Type;
Status : Cond_Value_Type;
begin
Get_Invo_Context (Status, To_Invo_Handle_Access (M).all, ICB);
if (Status and 1) /= 1 then
return Code_Loc (System.Null_Address);
end if;
return Code_Loc (ICB.Program_Counter - Asm_Call_Size);
end Get_Code_Loc;
--------------------------
-- Machine_State_Length --
--------------------------
function Machine_State_Length
return System.Storage_Elements.Storage_Offset
is
use System.Storage_Elements;
begin
return Invo_Handle_Type'Size / 8;
end Machine_State_Length;
---------------
-- Pop_Frame --
---------------
procedure Pop_Frame
(M : Machine_State;
Info : Subprogram_Info_Type)
is
procedure Get_Prev_Invo_Handle (
Result : out Invo_Handle_Type; -- return value
ICB : in Invo_Handle_Type);
pragma Interface (External, Get_Prev_Invo_Handle);
pragma Import_Valued_Procedure
(Get_Prev_Invo_Handle, "LIB$GET_PREV_INVO_HANDLE",
(Invo_Handle_Type, Invo_Handle_Type),
(Value, Value));
Prev_Handle : aliased Invo_Handle_Type;
begin
Get_Prev_Invo_Handle (Prev_Handle, To_Invo_Handle_Access (M).all);
To_Invo_Handle_Access (M).all := Prev_Handle;
end Pop_Frame;
-----------------------
-- Set_Machine_State --
-----------------------
procedure Set_Machine_State (M : Machine_State) is
procedure Get_Curr_Invo_Context
(Invo_Context : out Invo_Context_Blk_Type);
pragma Interface (External, Get_Curr_Invo_Context);
pragma Import_Valued_Procedure
(Get_Curr_Invo_Context, "LIB$GET_CURR_INVO_CONTEXT",
(Invo_Context_Blk_Type),
(Reference));
procedure Get_Invo_Handle (
Result : out Invo_Handle_Type; -- return value
Invo_Context : in Invo_Context_Blk_Type);
pragma Interface (External, Get_Invo_Handle);
pragma Import_Valued_Procedure (Get_Invo_Handle, "LIB$GET_INVO_HANDLE",
(Invo_Handle_Type, Invo_Context_Blk_Type),
(Value, Reference));
ICB : Invo_Context_Blk_Type;
Invo_Handle : aliased Invo_Handle_Type;
begin
Get_Curr_Invo_Context (ICB);
Get_Invo_Handle (Invo_Handle, ICB);
To_Invo_Handle_Access (M).all := Invo_Handle;
Pop_Frame (M, System.Null_Address);
end Set_Machine_State;
------------------------------
-- Set_Signal_Machine_State --
------------------------------
procedure Set_Signal_Machine_State
(M : Machine_State;
Context : System.Address) is
begin
null;
end Set_Signal_Machine_State;
end System.Machine_State_Operations;
|
package STM32GD.Clock is
pragma Preelaborate;
type Clock_Type is (SYSCLK, PCLK1, PCLK2, MSI, HSI, LSI, LSE, HCLK, PLLCLK, RTCCLK);
type PLL_Source_Type is (HSI, HSE);
type RTC_Source_Type is (LSE, HSE, LSI);
type SYSCLK_Source_Type is (PLL, HSI, HSE, MSI);
subtype MSI_Range is Integer range 1024 * 64 .. 4 * 1024 * 1024;
subtype HSE_Range is Integer range 4_000_000 .. 32_000_000;
subtype PLL_Prediv_Range is Integer range 1 .. 16;
subtype PLL_Mul_Range is Integer range 1 .. 16;
subtype PLL_Range is Integer range 16_000_000 .. 48_000_000;
subtype PLL_Input_Range is Integer range 4_000_000 .. 32_000_000;
subtype SYSCLK_Speed is Integer range 4_000_000 .. 48_000_000;
type AHB_Prescaler_Type is (DIV1, DIV2, DIV4, DIV8, DIV16,
DIV64, DIV128, DIV256, DIV512);
type APB1_Prescaler_Type is (DIV1, DIV2, DIV4, DIV8, DIV16);
type APB2_Prescaler_Type is (DIV1, DIV2, DIV4, DIV8, DIV16);
HSI_Value : constant Integer := 16_000_000;
MSI_Value : constant Integer := 2 * 1024 * 1024;
LSI_Value : constant Integer := 40_000;
LSE_Value : constant Integer := 32_768;
end STM32GD.Clock;
|
------------------------------------------------------------------------------
-- --
-- Hardware Abstraction Layer for STM32 Targets --
-- --
-- Copyright (C) 2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package body STM32F4.RCC is
HSE_VALUE : constant := 8_000_000; -- External oscillator in Hz
HSI_VALUE : constant := 16_000_000; -- Internal oscillator in Hz
HPRE_Presc_Table : constant array (Bits_4) of Word :=
(1, 1, 1, 1, 1, 1, 1, 1, 2, 4, 8, 16, 64, 128, 256, 512);
PPRE_Presc_Table : constant array (Bits_3) of Word :=
(1, 1, 1, 1, 2, 4, 8, 16);
-------------------------
-- Get_Clock_Frequency --
-------------------------
function System_Clock_Frequencies return RCC_System_Clocks is
RCC_CFGR_SWS : constant := 16#C#;
Source : constant Word := Register.CFGR and RCC_CFGR_SWS;
Result : RCC_System_Clocks;
begin
case Source is
when 16#00# =>
-- HSI as source
Result.SYSCLK := HSI_VALUE;
when 16#04# =>
-- HSE as source
Result.SYSCLK := HSE_VALUE;
when 16#08# =>
-- PLL as source
declare
Pllsource : constant Word :=
(Register.PLLCFGR and 16#00400000#) / (2**22);
Pllm : constant Word := Register.PLLCFGR and 16#0000003F#;
Plln : constant Word := (Register.PLLCFGR and 16#00007FC0#) / (2**6);
Pllp : constant Word := (((Register.PLLCFGR and 16#00030000#) / (2**16)) + 1) * 2;
Pllvco : Word;
begin
if Pllsource /= 0 then
Pllvco := (HSE_VALUE / Pllm) * Plln;
else
Pllvco := (HSI_VALUE / Pllm) * Plln;
end if;
Result.SYSCLK := Pllvco / Pllp;
end;
when others =>
Result.SYSCLK := HSI_VALUE;
end case;
declare
HPRE : constant Bits_4 := Bits_4 ((Register.CFGR and 16#00F0#) / (2**4));
PPRE1 : constant Bits_3 := Bits_3 ((Register.CFGR and 16#1C00#) / (2**10));
PPRE2 : constant Bits_3 := Bits_3 ((Register.CFGR and 16#E000#) / (2**13));
TIMPR : constant Word := (Register.DCKCFGR / (2**24)) and 1;
begin
Result.HCLK := Result.SYSCLK / HPRE_Presc_Table (HPRE);
Result.PCLK1 := Result.HCLK / PPRE_Presc_Table (PPRE1);
Result.PCLK2 := Result.HCLK / PPRE_Presc_Table (PPRE2);
-- Timer clocks
-- See Dedicated clock cfg register documentation.
if TIMPR = 0 then
if PPRE_Presc_Table (PPRE1) = 1 then
Result.TIMCLK1 := Result.PCLK1;
else
Result.TIMCLK1 := Result.PCLK1 * 2;
end if;
if PPRE_Presc_Table (PPRE2) = 1 then
Result.TIMCLK2 := Result.PCLK2;
else
Result.TIMCLK2 := Result.PCLK2 * 2;
end if;
else
if PPRE_Presc_Table (PPRE1) in 1 .. 4 then
Result.TIMCLK1 := Result.HCLK;
else
Result.TIMCLK1 := Result.PCLK1 * 4;
end if;
if PPRE_Presc_Table (PPRE2) in 1 .. 4 then
Result.TIMCLK2 := Result.HCLK;
else
Result.TIMCLK2 := Result.PCLK1 * 4;
end if;
end if;
end;
return Result;
end System_Clock_Frequencies;
------------------------
-- Set_PLLSAI_Factors --
------------------------
procedure Set_PLLSAI_Factors (LCD : Bits_3;
SAI1 : Bits_4;
VCO : Bits_9;
DivR : Bits_2) is
begin
Register.PLLSAICFGR := (Word (VCO) * (2**6)) or
(Word (SAI1) * (2**24)) or
(Word (LCD) * (2**28));
Register.DCKCFGR := Register.DCKCFGR and (not (16#30000#));
Register.DCKCFGR := Register.DCKCFGR or (Word(DivR) * (2**16));
end Set_PLLSAI_Factors;
-------------------
-- Enable_PLLSAI --
-------------------
procedure Enable_PLLSAI is
begin
Register.CR := Register.CR or (2**28);
-- Wait for PLLSAI activation
loop
exit when (Register.CR and (2**29)) /= 0;
end loop;
end Enable_PLLSAI;
---------------------------------------------------------------------------
------- Enable/Disable/Reset Routines -----------------------------------
---------------------------------------------------------------------------
procedure GPIOA_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOAEN;
end GPIOA_Clock_Enable;
procedure GPIOB_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOBEN;
end GPIOB_Clock_Enable;
procedure GPIOC_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOCEN;
end GPIOC_Clock_Enable;
procedure GPIOD_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIODEN;
end GPIOD_Clock_Enable;
procedure GPIOE_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOEEN;
end GPIOE_Clock_Enable;
procedure GPIOF_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOFEN;
end GPIOF_Clock_Enable;
procedure GPIOG_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOGEN;
end GPIOG_Clock_Enable;
procedure GPIOH_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOHEN;
end GPIOH_Clock_Enable;
procedure GPIOI_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOIEN;
end GPIOI_Clock_Enable;
procedure GPIOJ_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOJEN;
end GPIOJ_Clock_Enable;
procedure GPIOK_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_GPIOKEN;
end GPIOK_Clock_Enable;
procedure CRC_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_CRCEN;
end CRC_Clock_Enable;
procedure BKPSRAM_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_BKPSRAMEN;
end BKPSRAM_Clock_Enable;
procedure CCMDATARAMEN_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_CCMDATARAMEN;
end CCMDATARAMEN_Clock_Enable;
procedure DMA1_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_DMA1EN;
end DMA1_Clock_Enable;
procedure DMA2_Clock_Enable is
begin
Register.AHB1ENR := Register.AHB1ENR or AHB1ENR_DMA2EN;
end DMA2_Clock_Enable;
procedure GPIOA_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOAEN;
end GPIOA_Clock_Disable;
procedure GPIOB_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOBEN;
end GPIOB_Clock_Disable;
procedure GPIOC_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOCEN;
end GPIOC_Clock_Disable;
procedure GPIOD_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIODEN;
end GPIOD_Clock_Disable;
procedure GPIOE_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOEEN;
end GPIOE_Clock_Disable;
procedure GPIOF_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOFEN;
end GPIOF_Clock_Disable;
procedure GPIOG_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOGEN;
end GPIOG_Clock_Disable;
procedure GPIOH_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOHEN;
end GPIOH_Clock_Disable;
procedure GPIOI_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOIEN;
end GPIOI_Clock_Disable;
procedure GPIOJ_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOJEN;
end GPIOJ_Clock_Disable;
procedure GPIOK_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_GPIOKEN;
end GPIOK_Clock_Disable;
procedure CRC_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_CRCEN;
end CRC_Clock_Disable;
procedure BKPSRAM_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_BKPSRAMEN;
end BKPSRAM_Clock_Disable;
procedure CCMDATARAMEN_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_CCMDATARAMEN;
end CCMDATARAMEN_Clock_Disable;
procedure DMA1_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_DMA1EN;
end DMA1_Clock_Disable;
procedure DMA2_Clock_Disable is
begin
Register.AHB1ENR := Register.AHB1ENR and not AHB1ENR_DMA2EN;
end DMA2_Clock_Disable;
procedure RNG_Clock_Enable is
begin
Register.AHB2ENR := Register.AHB2ENR or AHB2ENR_RNGEN;
end RNG_Clock_Enable;
procedure RNG_Clock_Disable is
begin
Register.AHB2ENR := Register.AHB2ENR and not AHB2ENR_RNGEN;
end RNG_Clock_Disable;
procedure TIM2_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM2EN;
end TIM2_Clock_Enable;
procedure TIM3_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM3EN;
end TIM3_Clock_Enable;
procedure TIM4_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM4EN;
end TIM4_Clock_Enable;
procedure TIM5_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM5EN;
end TIM5_Clock_Enable;
procedure TIM6_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM6EN;
end TIM6_Clock_Enable;
procedure TIM7_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM7EN;
end TIM7_Clock_Enable;
procedure TIM12_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM12EN;
end TIM12_Clock_Enable;
procedure TIM13_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM13EN;
end TIM13_Clock_Enable;
procedure TIM14_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_TIM14EN;
end TIM14_Clock_Enable;
procedure WWDG_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_WWDGEN;
end WWDG_Clock_Enable;
procedure SPI2_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_SPI2EN;
end SPI2_Clock_Enable;
procedure SPI3_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_SPI3EN;
end SPI3_Clock_Enable;
procedure USART2_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_USART2EN;
end USART2_Clock_Enable;
procedure USART3_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_USART3EN;
end USART3_Clock_Enable;
procedure UART4_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_UART4EN;
end UART4_Clock_Enable;
procedure UART5_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_UART5EN;
end UART5_Clock_Enable;
procedure UART7_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_UART7EN;
end UART7_Clock_Enable;
procedure UART8_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_UART8EN;
end UART8_Clock_Enable;
procedure I2C1_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_I2C1EN;
end I2C1_Clock_Enable;
procedure I2C2_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_I2C2EN;
end I2C2_Clock_Enable;
procedure I2C3_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_I2C3EN;
end I2C3_Clock_Enable;
procedure PWR_Clock_Enable is
begin
Register.APB1ENR := Register.APB1ENR or APB1ENR_PWREN;
end PWR_Clock_Enable;
procedure TIM2_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM2EN;
end TIM2_Clock_Disable;
procedure TIM3_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM3EN;
end TIM3_Clock_Disable;
procedure TIM4_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM4EN;
end TIM4_Clock_Disable;
procedure TIM5_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM5EN;
end TIM5_Clock_Disable;
procedure TIM6_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM6EN;
end TIM6_Clock_Disable;
procedure TIM7_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM7EN;
end TIM7_Clock_Disable;
procedure TIM12_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM12EN;
end TIM12_Clock_Disable;
procedure TIM13_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM13EN;
end TIM13_Clock_Disable;
procedure TIM14_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_TIM14EN;
end TIM14_Clock_Disable;
procedure WWDG_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_WWDGEN;
end WWDG_Clock_Disable;
procedure SPI2_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_SPI2EN;
end SPI2_Clock_Disable;
procedure SPI3_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_SPI3EN;
end SPI3_Clock_Disable;
procedure USART2_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_USART2EN;
end USART2_Clock_Disable;
procedure USART3_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_USART3EN;
end USART3_Clock_Disable;
procedure UART4_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_UART4EN;
end UART4_Clock_Disable;
procedure UART5_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_UART5EN;
end UART5_Clock_Disable;
procedure UART7_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_UART7EN;
end UART7_Clock_Disable;
procedure UART8_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_UART8EN;
end UART8_Clock_Disable;
procedure I2C1_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_I2C1EN;
end I2C1_Clock_Disable;
procedure I2C2_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_I2C2EN;
end I2C2_Clock_Disable;
procedure I2C3_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_I2C3EN;
end I2C3_Clock_Disable;
procedure PWR_Clock_Disable is
begin
Register.APB1ENR := Register.APB1ENR and not APB1ENR_PWREN;
end PWR_Clock_Disable;
procedure TIM1_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_TIM1EN;
end TIM1_Clock_Enable;
procedure TIM8_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_TIM8EN;
end TIM8_Clock_Enable;
procedure USART1_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_USART1EN;
end USART1_Clock_Enable;
procedure USART6_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_USART6EN;
end USART6_Clock_Enable;
procedure ADC1_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_ADC1EN;
end ADC1_Clock_Enable;
procedure SDIO_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SDIOEN;
end SDIO_Clock_Enable;
procedure SPI1_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SPI1EN;
end SPI1_Clock_Enable;
procedure SPI4_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SPI4EN;
end SPI4_Clock_Enable;
procedure SYSCFG_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SYSCFGEN;
end SYSCFG_Clock_Enable;
procedure TIM9_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_TIM9EN;
end TIM9_Clock_Enable;
procedure TIM10_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_TIM10EN;
end TIM10_Clock_Enable;
procedure TIM11_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_TIM11EN;
end TIM11_Clock_Enable;
procedure SPI5_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SPI5EN;
end SPI5_Clock_Enable;
procedure SPI6_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_SPI6EN;
end SPI6_Clock_Enable;
procedure LTDC_Clock_Enable is
begin
Register.APB2ENR := Register.APB2ENR or APB2ENR_LTDCEN;
end LTDC_Clock_Enable;
procedure TIM1_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_TIM1EN;
end TIM1_Clock_Disable;
procedure TIM8_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_TIM8EN;
end TIM8_Clock_Disable;
procedure USART1_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_USART1EN;
end USART1_Clock_Disable;
procedure USART6_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_USART6EN;
end USART6_Clock_Disable;
procedure ADC1_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_ADC1EN;
end ADC1_Clock_Disable;
procedure SDIO_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SDIOEN;
end SDIO_Clock_Disable;
procedure SPI1_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SPI1EN;
end SPI1_Clock_Disable;
procedure SPI4_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SPI4EN;
end SPI4_Clock_Disable;
procedure SYSCFG_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SYSCFGEN;
end SYSCFG_Clock_Disable;
procedure TIM9_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_TIM9EN;
end TIM9_Clock_Disable;
procedure TIM10_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_TIM10EN;
end TIM10_Clock_Disable;
procedure TIM11_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_TIM11EN;
end TIM11_Clock_Disable;
procedure SPI5_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SPI5EN;
end SPI5_Clock_Disable;
procedure SPI6_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_SPI6EN;
end SPI6_Clock_Disable;
procedure LTDC_Clock_Disable is
begin
Register.APB2ENR := Register.APB2ENR and not APB2ENR_LTDCEN;
end LTDC_Clock_Disable;
procedure AHB1_Force_Reset is
begin
Register.AHB1RSTR := 16#FFFF_FFFF#;
end AHB1_Force_Reset;
procedure GPIOA_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIOARST;
end GPIOA_Force_Reset;
procedure GPIOB_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIOBRST;
end GPIOB_Force_Reset;
procedure GPIOC_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIOCRST;
end GPIOC_Force_Reset;
procedure GPIOD_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIODRST;
end GPIOD_Force_Reset;
procedure GPIOE_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIOERST;
end GPIOE_Force_Reset;
procedure GPIOH_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_GPIOHRST;
end GPIOH_Force_Reset;
procedure CRC_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_CRCRST;
end CRC_Force_Reset;
procedure DMA1_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_DMA1RST;
end DMA1_Force_Reset;
procedure DMA2_Force_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR or AHB1RSTR_DMA2RST;
end DMA2_Force_Reset;
procedure AHB1_Release_Reset is
begin
Register.AHB1RSTR := 0;
end AHB1_Release_Reset;
procedure GPIOA_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOARST;
end GPIOA_Release_Reset;
procedure GPIOB_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOBRST;
end GPIOB_Release_Reset;
procedure GPIOC_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOCRST;
end GPIOC_Release_Reset;
procedure GPIOD_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIODRST;
end GPIOD_Release_Reset;
procedure GPIOE_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOERST;
end GPIOE_Release_Reset;
procedure GPIOF_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOFRST;
end GPIOF_Release_Reset;
procedure GPIOG_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOGRST;
end GPIOG_Release_Reset;
procedure GPIOH_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOHRST;
end GPIOH_Release_Reset;
procedure GPIOI_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_GPIOIRST;
end GPIOI_Release_Reset;
procedure CRC_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_CRCRST;
end CRC_Release_Reset;
procedure DMA1_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_DMA1RST;
end DMA1_Release_Reset;
procedure DMA2_Release_Reset is
begin
Register.AHB1RSTR := Register.AHB1RSTR and not AHB1RSTR_DMA2RST;
end DMA2_Release_Reset;
procedure AHB2_Force_Reset is
begin
Register.AHB2RSTR := 16#FFFF_FFFF#;
end AHB2_Force_Reset;
procedure OTGFS_Force_Reset is
begin
Register.AHB2RSTR := Register.AHB2RSTR or AHB2RSTR_OTGFSRST;
end OTGFS_Force_Reset;
procedure AHB2_Release_Reset is
begin
Register.AHB2RSTR := 0;
end AHB2_Release_Reset;
procedure OTGFS_Release_Reset is
begin
Register.AHB2RSTR := Register.AHB2RSTR and not AHB2RSTR_OTGFSRST;
end OTGFS_Release_Reset;
procedure RNG_Force_Reset is
begin
Register.AHB2RSTR := Register.AHB2RSTR or AHB2RSTR_RNGRST;
end RNG_Force_Reset;
procedure RNG_Release_Reset is
begin
Register.AHB2RSTR := Register.AHB2RSTR and not AHB2RSTR_RNGRST;
end RNG_Release_Reset;
procedure APB1_Force_Reset is
begin
Register.APB1RSTR := 16#FFFF_FFFF#;
end APB1_Force_Reset;
procedure TIM2_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM2RST;
end TIM2_Force_Reset;
procedure TIM3_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM3RST;
end TIM3_Force_Reset;
procedure TIM4_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM4RST;
end TIM4_Force_Reset;
procedure TIM5_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM5RST;
end TIM5_Force_Reset;
procedure TIM6_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM6RST;
end TIM6_Force_Reset;
procedure TIM7_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM7RST;
end TIM7_Force_Reset;
procedure TIM12_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM12RST;
end TIM12_Force_Reset;
procedure TIM13_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM13RST;
end TIM13_Force_Reset;
procedure TIM14_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_TIM14RST;
end TIM14_Force_Reset;
procedure WWDG_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_WWDGRST;
end WWDG_Force_Reset;
procedure SPI2_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_SPI2RST;
end SPI2_Force_Reset;
procedure SPI3_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_SPI3RST;
end SPI3_Force_Reset;
procedure USART2_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_USART2RST;
end USART2_Force_Reset;
procedure I2C1_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_I2C1RST;
end I2C1_Force_Reset;
procedure I2C2_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_I2C2RST;
end I2C2_Force_Reset;
procedure I2C3_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_I2C3RST;
end I2C3_Force_Reset;
procedure PWR_Force_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR or APB1RSTR_PWRRST;
end PWR_Force_Reset;
procedure APB1_Release_Reset is
begin
Register.APB1RSTR := 0;
end APB1_Release_Reset;
procedure TIM2_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM2RST;
end TIM2_Release_Reset;
procedure TIM3_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM3RST;
end TIM3_Release_Reset;
procedure TIM4_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM4RST;
end TIM4_Release_Reset;
procedure TIM5_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM5RST;
end TIM5_Release_Reset;
procedure TIM6_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM6RST;
end TIM6_Release_Reset;
procedure TIM7_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM7RST;
end TIM7_Release_Reset;
procedure TIM12_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM12RST;
end TIM12_Release_Reset;
procedure TIM13_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM13RST;
end TIM13_Release_Reset;
procedure TIM14_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_TIM14RST;
end TIM14_Release_Reset;
procedure WWDG_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_WWDGRST;
end WWDG_Release_Reset;
procedure SPI2_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_SPI2RST;
end SPI2_Release_Reset;
procedure SPI3_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_SPI3RST;
end SPI3_Release_Reset;
procedure USART2_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_USART2RST;
end USART2_Release_Reset;
procedure I2C1_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_I2C1RST;
end I2C1_Release_Reset;
procedure I2C2_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_I2C2RST;
end I2C2_Release_Reset;
procedure I2C3_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_I2C3RST;
end I2C3_Release_Reset;
procedure PWR_Release_Reset is
begin
Register.APB1RSTR := Register.APB1RSTR and not APB1RSTR_PWRRST;
end PWR_Release_Reset;
procedure APB2_Force_Reset is
begin
Register.APB2RSTR := 16#FFFF_FFFF#;
end APB2_Force_Reset;
procedure TIM1_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_TIM1RST;
end TIM1_Force_Reset;
procedure TIM8_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_TIM8RST;
end TIM8_Force_Reset;
procedure USART1_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_USART1RST;
end USART1_Force_Reset;
procedure USART6_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_USART6RST;
end USART6_Force_Reset;
procedure ADC_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_ADCRST;
end ADC_Force_Reset;
procedure SDIO_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SDIORST;
end SDIO_Force_Reset;
procedure SPI1_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SPI1RST;
end SPI1_Force_Reset;
procedure SPI4_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SPI4RST;
end SPI4_Force_Reset;
procedure SYSCFG_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SYSCFGRST;
end SYSCFG_Force_Reset;
procedure TIM9_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_TIM9RST;
end TIM9_Force_Reset;
procedure TIM10_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_TIM10RST;
end TIM10_Force_Reset;
procedure TIM11_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_TIM11RST;
end TIM11_Force_Reset;
procedure SPI5_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SPI5RST;
end SPI5_Force_Reset;
procedure SPI6_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_SPI6RST;
end SPI6_Force_Reset;
procedure LTDC_Force_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR or APB2RSTR_LTDCRST;
end LTDC_Force_Reset;
procedure APB2_Release_Reset is
begin
Register.APB2RSTR := 0;
end APB2_Release_Reset;
procedure TIM1_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_TIM1RST;
end TIM1_Release_Reset;
procedure TIM8_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_TIM8RST;
end TIM8_Release_Reset;
procedure USART1_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_USART1RST;
end USART1_Release_Reset;
procedure USART6_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_USART6RST;
end USART6_Release_Reset;
procedure ADC_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_ADCRST;
end ADC_Release_Reset;
procedure SDIO_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SDIORST;
end SDIO_Release_Reset;
procedure SPI1_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SPI1RST;
end SPI1_Release_Reset;
procedure SPI4_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SPI4RST;
end SPI4_Release_Reset;
procedure SYSCFG_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SYSCFGRST;
end SYSCFG_Release_Reset;
procedure TIM9_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_TIM9RST;
end TIM9_Release_Reset;
procedure TIM10_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_TIM10RST;
end TIM10_Release_Reset;
procedure TIM11_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_TIM11RST;
end TIM11_Release_Reset;
procedure SPI5_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SPI5RST;
end SPI5_Release_Reset;
procedure SPI6_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_SPI6RST;
end SPI6_Release_Reset;
procedure LTDC_Release_Reset is
begin
Register.APB2RSTR := Register.APB2RSTR and not APB2RSTR_LTDCRST;
end LTDC_Release_Reset;
procedure FSMC_Clock_Enable is
begin
Register.AHB3ENR := Register.AHB3ENR or AHB3ENR_FSMCEN;
end FSMC_Clock_Enable;
procedure FSMC_Clock_Disable is
begin
Register.AHB3ENR := Register.AHB3ENR and not AHB3ENR_FSMCEN;
end FSMC_Clock_Disable;
end STM32F4.RCC;
|
generic
type Item is digits <>;
type Items_Array is array (Positive range <>) of Item;
function Generic_Max (List : Items_Array) return Item;
|
-- { dg-do compile }
-- { dg-options "-O3" }
package body Loop_Optimization1 is
procedure Create (A : in out D; Val : Integer) is
M : constant Group_Chain_List := Group_Chains(Val);
G : constant Group_List := Groups(Val);
function Is_Visible (Group : Number) return Boolean is
begin
for I in M'Range loop
if Group = M(I).Groups(M(I).Length) then
return True;
end if;
end loop;
return False;
end;
begin
for I in A.L'Range loop
A.L(I) := new R(Is_Visible(G(I)));
end loop;
end;
end Loop_Optimization1;
|
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
package body Messages is
-----------
-- Print --
-----------
procedure Print (Item : Message) is
The_Year : Year_Number;
The_Month : Month_Number;
The_Day : Day_Number;
Seconds : Day_Duration;
begin
Split(Date => Item.Timestamp, Year => The_Year,
Month => The_Month, Day => The_Day, Seconds => Seconds);
Put("Time Stamp:");
Put(Item => The_Year, Width => 4);
Put("-");
Put(Item => The_Month, Width => 1);
Put("-");
Put(Item => The_Day, Width => 1);
New_Line;
end Print;
-----------
-- Print --
-----------
procedure Print (Item : Sensor_Message) is
begin
Print(Message(Item));
Put("Sensor Id: ");
Put(Item => Item.Sensor_Id, Width => 1);
New_Line;
Put("Reading: ");
Put(Item => Item.Reading, Fore => 1, Aft => 4, Exp => 0);
New_Line;
end Print;
-----------
-- Print --
-----------
procedure Print (Item : Control_Message) is
begin
Print(Message(Item));
Put("Actuator Id: ");
Put(Item => Item.Actuator_Id, Width => 1);
New_Line;
Put("Command: ");
Put(Item => Item.Command, Fore => 1, Aft => 4, Exp => 0);
New_Line;
end Print;
-------------
---Display --
-------------
procedure Display(Item : Message'Class) is
begin
Print(Item);
end Display;
end Messages;
|
with
AdaM.a_Type.enumeration_type,
Glib,
Glib.Error,
Gtk.Builder,
Gtk.Handlers;
package body aIDE.Editor.of_enumeration_literal
is
use Gtk.Builder,
Glib,
glib.Error;
function on_name_Entry_leave (the_Entry : access Gtk_Entry_Record'Class;
Target : in AdaM.a_Type.enumeration_literal.view) return Boolean
is
the_Text : constant String := the_Entry.Get_Text;
begin
Target.Name_is (the_Text);
return False;
end on_name_Entry_leave;
procedure on_rid_Button_clicked (the_Button : access Gtk_Button_Record'Class;
the_Editor : in aIDE.Editor.of_enumeration_literal.view)
is
use AdaM;
begin
the_Editor.Targets_Parent.rid_Literal (+the_Editor.Target.Name);
the_Button.get_Parent.destroy;
end on_rid_Button_clicked;
package Entry_return_Callbacks is new Gtk.Handlers.User_Return_Callback (Gtk_Entry_Record,
Boolean,
AdaM.a_Type.enumeration_literal.view);
package Button_Callbacks is new Gtk.Handlers.User_Callback (Gtk_Button_Record,
aIDE.Editor.of_enumeration_literal.view);
package body Forge
is
function to_Editor (the_Target : in AdaM.a_Type.enumeration_literal.view;
targets_Parent : in enumeration_type_view) return View
is
use AdaM;
Self : constant Editor.of_enumeration_literal.view := new Editor.of_enumeration_literal.item;
the_Builder : Gtk_Builder;
Error : aliased GError;
Result : Guint;
pragma Unreferenced (Result);
begin
Self.Target := the_Target;
Self.Targets_Parent := targets_Parent;
Gtk_New (the_Builder);
Result := the_Builder.Add_From_File ("glade/editor/enumeration_literal_editor.glade", Error'Access);
if Error /= null then
raise Program_Error with "Error: adam.Editor.of_enumeration_literal ~ " & Get_Message (Error);
end if;
Self.top_Box := gtk_Box (the_Builder.get_Object ("top_Box"));
Self.name_Entry := Gtk_Entry (the_Builder.get_Object ("name_Entry"));
Self.rid_Button := gtk_Button (the_Builder.get_Object ("rid_Button"));
Self.name_Entry.Set_Text (+Self.Target.Name);
Entry_return_Callbacks.connect (Self.name_Entry,
"focus-out-event",
on_name_Entry_leave'Access,
the_Target);
Button_Callbacks.Connect (Self.rid_Button,
"clicked",
on_rid_Button_clicked'Access,
Self);
return Self;
end to_Editor;
end Forge;
overriding
function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget
is
begin
return gtk.Widget.Gtk_Widget (Self.top_Box);
end top_Widget;
end aIDE.Editor.of_enumeration_literal;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M L I B . U T L --
-- --
-- B o d y --
-- --
-- Copyright (C) 2002-2006, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with MLib.Fil; use MLib.Fil;
with MLib.Tgt; use MLib.Tgt;
with Namet; use Namet;
with Opt;
with Osint;
with Output; use Output;
with GNAT; use GNAT;
package body MLib.Utl is
Initialized : Boolean := False;
Gcc_Name : constant String := Osint.Program_Name ("gcc").all;
Gcc_Exec : OS_Lib.String_Access;
Ar_Name : OS_Lib.String_Access;
Ar_Exec : OS_Lib.String_Access;
Ar_Options : OS_Lib.String_List_Access;
Ranlib_Name : OS_Lib.String_Access;
Ranlib_Exec : OS_Lib.String_Access := null;
Ranlib_Options : OS_Lib.String_List_Access := null;
procedure Initialize;
-- Look for the tools in the path and record the full path for each one
--------
-- Ar --
--------
procedure Ar (Output_File : String; Objects : Argument_List) is
Full_Output_File : constant String :=
Ext_To (Output_File, Archive_Ext);
Arguments : OS_Lib.Argument_List_Access;
Success : Boolean;
Line_Length : Natural := 0;
begin
Utl.Initialize;
Arguments :=
new String_List (1 .. 1 + Ar_Options'Length + Objects'Length);
Arguments (1 .. Ar_Options'Length) := Ar_Options.all; -- "ar cr ..."
Arguments (Ar_Options'Length + 1) := new String'(Full_Output_File);
Arguments (Ar_Options'Length + 2 .. Arguments'Last) := Objects;
Delete_File (Full_Output_File);
if not Opt.Quiet_Output then
Write_Str (Ar_Name.all);
Line_Length := Ar_Name'Length;
for J in Arguments'Range loop
-- Make sure the Output buffer does not overflow
if Line_Length + 1 + Arguments (J)'Length > Buffer_Max then
Write_Eol;
Line_Length := 0;
end if;
Write_Char (' ');
Write_Str (Arguments (J).all);
Line_Length := Line_Length + 1 + Arguments (J)'Length;
end loop;
Write_Eol;
end if;
OS_Lib.Spawn (Ar_Exec.all, Arguments.all, Success);
if not Success then
Fail (Ar_Name.all, " execution error.");
end if;
-- If we have found ranlib, run it over the library
if Ranlib_Exec /= null then
if not Opt.Quiet_Output then
Write_Str (Ranlib_Name.all);
Write_Char (' ');
Write_Line (Arguments (Ar_Options'Length + 1).all);
end if;
OS_Lib.Spawn
(Ranlib_Exec.all,
Ranlib_Options.all & (Arguments (Ar_Options'Length + 1)),
Success);
if not Success then
Fail (Ranlib_Name.all, " execution error.");
end if;
end if;
end Ar;
-----------------
-- Delete_File --
-----------------
procedure Delete_File (Filename : String) is
File : constant String := Filename & ASCII.Nul;
Success : Boolean;
begin
OS_Lib.Delete_File (File'Address, Success);
if Opt.Verbose_Mode then
if Success then
Write_Str ("deleted ");
else
Write_Str ("could not delete ");
end if;
Write_Line (Filename);
end if;
end Delete_File;
---------
-- Gcc --
---------
procedure Gcc
(Output_File : String;
Objects : Argument_List;
Options : Argument_List;
Options_2 : Argument_List;
Driver_Name : Name_Id := No_Name)
is
Arguments :
OS_Lib.Argument_List
(1 .. 7 + Objects'Length + Options'Length + Options_2'Length);
A : Natural := 0;
Success : Boolean;
Out_Opt : constant OS_Lib.String_Access :=
new String'("-o");
Out_V : constant OS_Lib.String_Access :=
new String'(Output_File);
Lib_Dir : constant OS_Lib.String_Access :=
new String'("-L" & Lib_Directory);
Lib_Opt : constant OS_Lib.String_Access :=
new String'(Dynamic_Option);
Driver : String_Access;
begin
Utl.Initialize;
if Driver_Name = No_Name then
Driver := Gcc_Exec;
else
Driver := OS_Lib.Locate_Exec_On_Path (Get_Name_String (Driver_Name));
if Driver = null then
Fail (Get_Name_String (Driver_Name), " not found in path");
end if;
end if;
if Lib_Opt'Length /= 0 then
A := A + 1;
Arguments (A) := Lib_Opt;
end if;
A := A + 1;
Arguments (A) := Out_Opt;
A := A + 1;
Arguments (A) := Out_V;
A := A + 1;
Arguments (A) := Lib_Dir;
A := A + Options'Length;
Arguments (A - Options'Length + 1 .. A) := Options;
A := A + Objects'Length;
Arguments (A - Objects'Length + 1 .. A) := Objects;
A := A + Options_2'Length;
Arguments (A - Options_2'Length + 1 .. A) := Options_2;
if not Opt.Quiet_Output then
Write_Str (Driver.all);
for J in 1 .. A loop
Write_Char (' ');
Write_Str (Arguments (J).all);
end loop;
Write_Eol;
end if;
OS_Lib.Spawn (Driver.all, Arguments (1 .. A), Success);
if not Success then
if Driver_Name = No_Name then
Fail (Gcc_Name, " execution error");
else
Fail (Get_Name_String (Driver_Name), " execution error");
end if;
end if;
end Gcc;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
if not Initialized then
Initialized := True;
-- gcc
Gcc_Exec := OS_Lib.Locate_Exec_On_Path (Gcc_Name);
if Gcc_Exec = null then
Fail (Gcc_Name, " not found in path");
elsif Opt.Verbose_Mode then
Write_Str ("found ");
Write_Line (Gcc_Exec.all);
end if;
-- ar
Ar_Name := Osint.Program_Name (Archive_Builder);
Ar_Exec := OS_Lib.Locate_Exec_On_Path (Ar_Name.all);
if Ar_Exec = null then
Fail (Ar_Name.all, " not found in path");
elsif Opt.Verbose_Mode then
Write_Str ("found ");
Write_Line (Ar_Exec.all);
end if;
Ar_Options := Archive_Builder_Options;
-- ranlib
Ranlib_Name := Osint.Program_Name (Archive_Indexer);
if Ranlib_Name'Length > 0 then
Ranlib_Exec := OS_Lib.Locate_Exec_On_Path (Ranlib_Name.all);
if Ranlib_Exec /= null and then Opt.Verbose_Mode then
Write_Str ("found ");
Write_Line (Ranlib_Exec.all);
end if;
end if;
Ranlib_Options := Archive_Indexer_Options;
end if;
end Initialize;
-------------------
-- Lib_Directory --
-------------------
function Lib_Directory return String is
Libgnat : constant String := Tgt.Libgnat;
begin
Name_Len := Libgnat'Length;
Name_Buffer (1 .. Name_Len) := Libgnat;
Get_Name_String (Osint.Find_File (Name_Enter, Osint.Library));
-- Remove libgnat.a
return Name_Buffer (1 .. Name_Len - Libgnat'Length);
end Lib_Directory;
end MLib.Utl;
|
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Ada.Iterator_Interfaces;
package Program.Interpretations.Expressions is
pragma Preelaborate;
type Cursor is private;
function Type_View (Self : Cursor) return Program.Visibility.View;
function "+" (Self : Cursor) return Program.Visibility.View
renames Type_View;
function Solution (Self : Cursor) return Program.Interpretations.Solution;
function "-" (Self : Cursor) return Program.Interpretations.Solution
renames Solution;
function Has_Element (Self : Cursor) return Boolean;
package Iterators is new Ada.Iterator_Interfaces (Cursor, Has_Element);
type Iterator is new Iterators.Forward_Iterator with private;
function Each (Set : Interpretation_Set) return Iterator;
-- Return each interpretation for an expression.
function Each_Of_Type
(Set : Interpretation_Set;
Expected_Type : Program.Visibility.View) return Iterator;
-- Return expression interpretation of given Expected_Type.
-- Include expression category is matching expected type.
private
type Optional_View (Is_Set : Boolean := False) is record
case Is_Set is
when True =>
View : Program.Visibility.View;
when False =>
null;
end case;
end record;
type Cursor_State (Kind : Interpretation_Kind := Symbol) is record
case Kind is
when Symbol =>
Iter : Program.Visibility.Directly_Visible_Name_Iterator;
Cursor : Program.Visibility.View_Cursor;
when Name =>
View : Program.Visibility.View;
when Expression | Expression_Category =>
Type_View : Program.Visibility.View;
Tuple : Solution_Tuple_Access;
end case;
end record;
type Cursor is record
Index : Natural;
State : Cursor_State;
end record;
type Iterator is new Iterators.Forward_Iterator with record
Set : Interpretation_Set;
Expected : Optional_View;
end record;
overriding function First (Self : Iterator) return Cursor;
overriding function Next
(Self : Iterator;
Position : Cursor) return Cursor;
end Program.Interpretations.Expressions;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . C L I E N T . S T O R A G E --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2014 David Botton --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- 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/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- For more information please go to http://www.gnoga.com --
------------------------------------------------------------------------------
with Ada_GUI.Gnoga.Gui;
package Ada_GUI.Gnoga.Client_Storage is
-------------------------------------------------------------------------
-- Storage_Type
-------------------------------------------------------------------------
-- Base class for client side storage of data.
-- In order to ease access to client side data, the Storage_Type can be
-- accessed using any object instead of just through the parent window.
-- One local and one session storage is available across an entire
-- location defined as scheme://domain:port.
type Storage_Type is tagged private;
type Storage_Access is access all Storage_Type;
type Pointer_To_Storage_Class is access all Storage_Type'Class;
function Length (Storage : Storage_Type) return Natural;
-- Number of entries in Storage
function Key (Storage : Storage_Type; Value : Positive) return String;
-- Return the Key at Value
procedure Set (Storage : in out Storage_Type; Name, Value : String);
-- Set Name=Value in Storage
function Get (Storage : Storage_Type; Name : String) return String;
-- Get Value for Name in Storage. If Name does not exist returns "null"
function Script_Accessor (Storage : Storage_Type) return String;
type Local_Storage_Type is new Storage_Type with private;
type Local_Storage_Access is access all Local_Storage_Type;
type Pointer_To_Local_Storage_Class is access all Local_Storage_Type'Class;
function Local_Storage (Object : Gnoga.Gui.Base_Type'Class)
return Local_Storage_Type;
overriding
function Script_Accessor (Storage : Local_Storage_Type) return String;
type Session_Storage_Type is new Storage_Type with private;
type Session_Storage_Access is access all Session_Storage_Type;
type Pointer_To_Session_Storage_Class is
access all Session_Storage_Type'Class;
function Session_Storage (Object : Gnoga.Gui.Base_Type'Class)
return Session_Storage_Type;
overriding
function Script_Accessor (Storage : Session_Storage_Type) return String;
private
type Storage_Type is tagged
record
Connection_ID : Gnoga.Connection_ID :=
Gnoga.No_Connection;
end record;
type Local_Storage_Type is new Storage_Type with null record;
type Session_Storage_Type is new Storage_Type with null record;
end Ada_GUI.Gnoga.Client_Storage;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- A D A . C O N T A I N E R S . F O R M A L _ O R D E R E D _ S E T S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2004-2021, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
------------------------------------------------------------------------------
-- This spec is derived from package Ada.Containers.Bounded_Ordered_Sets in
-- the Ada 2012 RM. The modifications are meant to facilitate formal proofs by
-- making it easier to express properties, and by making the specification of
-- this unit compatible with SPARK 2014. Note that the API of this unit may be
-- subject to incompatible changes as SPARK 2014 evolves.
-- The modifications are:
-- A parameter for the container is added to every function reading the
-- content of a container: Key, Element, Next, Query_Element, Previous,
-- Has_Element, Iterate, Reverse_Iterate. This change is motivated by the
-- need to have cursors which are valid on different containers (typically
-- a container C and its previous version C'Old) for expressing properties,
-- which is not possible if cursors encapsulate an access to the underlying
-- container. The operators "<" and ">" that could not be modified that way
-- have been removed.
with Ada.Containers.Functional_Maps;
with Ada.Containers.Functional_Sets;
with Ada.Containers.Functional_Vectors;
private with Ada.Containers.Red_Black_Trees;
generic
type Element_Type is private;
with function "<" (Left, Right : Element_Type) return Boolean is <>;
package Ada.Containers.Formal_Ordered_Sets with
SPARK_Mode
is
-- Contracts in this unit are meant for analysis only, not for run-time
-- checking.
pragma Assertion_Policy (Pre => Ignore);
pragma Assertion_Policy (Post => Ignore);
pragma Annotate (CodePeer, Skip_Analysis);
function Equivalent_Elements (Left, Right : Element_Type) return Boolean
with
Global => null,
Post =>
Equivalent_Elements'Result =
(not (Left < Right) and not (Right < Left));
pragma Annotate (GNATprove, Inline_For_Proof, Equivalent_Elements);
type Set (Capacity : Count_Type) is private with
Iterable => (First => First,
Next => Next,
Has_Element => Has_Element,
Element => Element),
Default_Initial_Condition => Is_Empty (Set);
pragma Preelaborable_Initialization (Set);
type Cursor is record
Node : Count_Type;
end record;
No_Element : constant Cursor := (Node => 0);
function Length (Container : Set) return Count_Type with
Global => null,
Post => Length'Result <= Container.Capacity;
pragma Unevaluated_Use_Of_Old (Allow);
package Formal_Model with Ghost is
subtype Positive_Count_Type is Count_Type range 1 .. Count_Type'Last;
package M is new Ada.Containers.Functional_Sets
(Element_Type => Element_Type,
Equivalent_Elements => Equivalent_Elements);
function "="
(Left : M.Set;
Right : M.Set) return Boolean renames M."=";
function "<="
(Left : M.Set;
Right : M.Set) return Boolean renames M."<=";
package E is new Ada.Containers.Functional_Vectors
(Element_Type => Element_Type,
Index_Type => Positive_Count_Type);
function "="
(Left : E.Sequence;
Right : E.Sequence) return Boolean renames E."=";
function "<"
(Left : E.Sequence;
Right : E.Sequence) return Boolean renames E."<";
function "<="
(Left : E.Sequence;
Right : E.Sequence) return Boolean renames E."<=";
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
with
Global => null,
Pre => Lst <= E.Length (Container),
Post =>
E_Bigger_Than_Range'Result =
(for all I in Fst .. Lst => E.Get (Container, I) < Item);
pragma Annotate (GNATprove, Inline_For_Proof, E_Bigger_Than_Range);
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Item : Element_Type) return Boolean
with
Global => null,
Pre => Lst <= E.Length (Container),
Post =>
E_Smaller_Than_Range'Result =
(for all I in Fst .. Lst => Item < E.Get (Container, I));
pragma Annotate (GNATprove, Inline_For_Proof, E_Smaller_Than_Range);
function E_Is_Find
(Container : E.Sequence;
Item : Element_Type;
Position : Count_Type) return Boolean
with
Global => null,
Pre => Position - 1 <= E.Length (Container),
Post =>
E_Is_Find'Result =
((if Position > 0 then
E_Bigger_Than_Range (Container, 1, Position - 1, Item))
and (if Position < E.Length (Container) then
E_Smaller_Than_Range
(Container,
Position + 1,
E.Length (Container),
Item)));
pragma Annotate (GNATprove, Inline_For_Proof, E_Is_Find);
function Find
(Container : E.Sequence;
Item : Element_Type) return Count_Type
-- Search for Item in Container
with
Global => null,
Post =>
(if Find'Result > 0 then
Find'Result <= E.Length (Container)
and Equivalent_Elements (Item, E.Get (Container, Find'Result)));
function E_Elements_Included
(Left : E.Sequence;
Right : E.Sequence) return Boolean
-- The elements of Left are contained in Right
with
Global => null,
Post =>
E_Elements_Included'Result =
(for all I in 1 .. E.Length (Left) =>
Find (Right, E.Get (Left, I)) > 0
and then E.Get (Right, Find (Right, E.Get (Left, I))) =
E.Get (Left, I));
pragma Annotate (GNATprove, Inline_For_Proof, E_Elements_Included);
function E_Elements_Included
(Left : E.Sequence;
Model : M.Set;
Right : E.Sequence) return Boolean
-- The elements of Container contained in Model are in Right
with
Global => null,
Post =>
E_Elements_Included'Result =
(for all I in 1 .. E.Length (Left) =>
(if M.Contains (Model, E.Get (Left, I)) then
Find (Right, E.Get (Left, I)) > 0
and then E.Get (Right, Find (Right, E.Get (Left, I))) =
E.Get (Left, I)));
pragma Annotate (GNATprove, Inline_For_Proof, E_Elements_Included);
function E_Elements_Included
(Container : E.Sequence;
Model : M.Set;
Left : E.Sequence;
Right : E.Sequence) return Boolean
-- The elements of Container contained in Model are in Left and others
-- are in Right.
with
Global => null,
Post =>
E_Elements_Included'Result =
(for all I in 1 .. E.Length (Container) =>
(if M.Contains (Model, E.Get (Container, I)) then
Find (Left, E.Get (Container, I)) > 0
and then E.Get (Left, Find (Left, E.Get (Container, I))) =
E.Get (Container, I)
else
Find (Right, E.Get (Container, I)) > 0
and then E.Get (Right, Find (Right, E.Get (Container, I))) =
E.Get (Container, I)));
pragma Annotate (GNATprove, Inline_For_Proof, E_Elements_Included);
package P is new Ada.Containers.Functional_Maps
(Key_Type => Cursor,
Element_Type => Positive_Count_Type,
Equivalent_Keys => "=",
Enable_Handling_Of_Equivalence => False);
function "="
(Left : P.Map;
Right : P.Map) return Boolean renames P."=";
function "<="
(Left : P.Map;
Right : P.Map) return Boolean renames P."<=";
function P_Positions_Shifted
(Small : P.Map;
Big : P.Map;
Cut : Positive_Count_Type;
Count : Count_Type := 1) return Boolean
with
Global => null,
Post =>
P_Positions_Shifted'Result =
-- Big contains all cursors of Small
(P.Keys_Included (Small, Big)
-- Cursors located before Cut are not moved, cursors located
-- after are shifted by Count.
and (for all I of Small =>
(if P.Get (Small, I) < Cut then
P.Get (Big, I) = P.Get (Small, I)
else
P.Get (Big, I) - Count = P.Get (Small, I)))
-- New cursors of Big (if any) are between Cut and Cut - 1 +
-- Count.
and (for all I of Big =>
P.Has_Key (Small, I)
or P.Get (Big, I) - Count in Cut - Count .. Cut - 1));
function Mapping_Preserved
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map) return Boolean
with
Ghost,
Global => null,
Post =>
(if Mapping_Preserved'Result then
-- Right contains all the cursors of Left
P.Keys_Included (P_Left, P_Right)
-- Right contains all the elements of Left
and E_Elements_Included (E_Left, E_Right)
-- Mappings from cursors to elements induced by E_Left, P_Left
-- and E_Right, P_Right are the same.
and (for all C of P_Left =>
E.Get (E_Left, P.Get (P_Left, C)) =
E.Get (E_Right, P.Get (P_Right, C))));
function Mapping_Preserved_Except
(E_Left : E.Sequence;
E_Right : E.Sequence;
P_Left : P.Map;
P_Right : P.Map;
Position : Cursor) return Boolean
with
Ghost,
Global => null,
Post =>
(if Mapping_Preserved_Except'Result then
-- Right contains all the cursors of Left
P.Keys_Included (P_Left, P_Right)
-- Mappings from cursors to elements induced by E_Left, P_Left
-- and E_Right, P_Right are the same except for Position.
and (for all C of P_Left =>
(if C /= Position then
E.Get (E_Left, P.Get (P_Left, C)) =
E.Get (E_Right, P.Get (P_Right, C)))));
function Model (Container : Set) return M.Set with
-- The high-level model of a set is a set of elements. Neither cursors
-- nor order of elements are represented in this model. Elements are
-- modeled up to equivalence.
Ghost,
Global => null,
Post => M.Length (Model'Result) = Length (Container);
function Elements (Container : Set) return E.Sequence with
-- The Elements sequence represents the underlying list structure of
-- sets that is used for iteration. It stores the actual values of
-- elements in the set. It does not model cursors.
Ghost,
Global => null,
Post =>
E.Length (Elements'Result) = Length (Container)
-- It only contains keys contained in Model
and (for all Item of Elements'Result =>
M.Contains (Model (Container), Item))
-- It contains all the elements contained in Model
and (for all Item of Model (Container) =>
(Find (Elements'Result, Item) > 0
and then Equivalent_Elements
(E.Get (Elements'Result, Find (Elements'Result, Item)),
Item)))
-- It is sorted in increasing order
and (for all I in 1 .. Length (Container) =>
Find (Elements'Result, E.Get (Elements'Result, I)) = I
and
E_Is_Find
(Elements'Result, E.Get (Elements'Result, I), I));
pragma Annotate (GNATprove, Iterable_For_Proof, "Model", Elements);
function Positions (Container : Set) return P.Map with
-- The Positions map is used to model cursors. It only contains valid
-- cursors and maps them to their position in the container.
Ghost,
Global => null,
Post =>
not P.Has_Key (Positions'Result, No_Element)
-- Positions of cursors are smaller than the container's length
and then
(for all I of Positions'Result =>
P.Get (Positions'Result, I) in 1 .. Length (Container)
-- No two cursors have the same position. Note that we do not
-- state that there is a cursor in the map for each position, as
-- it is rarely needed.
and then
(for all J of Positions'Result =>
(if P.Get (Positions'Result, I) = P.Get (Positions'Result, J)
then I = J)));
procedure Lift_Abstraction_Level (Container : Set) with
-- Lift_Abstraction_Level is a ghost procedure that does nothing but
-- assume that we can access the same elements by iterating over
-- positions or cursors.
-- This information is not generally useful except when switching from
-- a low-level, cursor-aware view of a container, to a high-level,
-- position-based view.
Ghost,
Global => null,
Post =>
(for all Item of Elements (Container) =>
(for some I of Positions (Container) =>
E.Get (Elements (Container), P.Get (Positions (Container), I)) =
Item));
function Contains
(C : M.Set;
K : Element_Type) return Boolean renames M.Contains;
-- To improve readability of contracts, we rename the function used to
-- search for an element in the model to Contains.
end Formal_Model;
use Formal_Model;
Empty_Set : constant Set;
function "=" (Left, Right : Set) return Boolean with
Global => null,
Post =>
-- If two sets are equal, they contain the same elements in the same
-- order.
(if "="'Result then Elements (Left) = Elements (Right)
-- If they are different, then they do not contain the same elements
else
not E_Elements_Included (Elements (Left), Elements (Right))
or not E_Elements_Included (Elements (Right), Elements (Left)));
function Equivalent_Sets (Left, Right : Set) return Boolean with
Global => null,
Post => Equivalent_Sets'Result = (Model (Left) = Model (Right));
function To_Set (New_Item : Element_Type) return Set with
Global => null,
Post =>
M.Is_Singleton (Model (To_Set'Result), New_Item)
and Length (To_Set'Result) = 1
and E.Get (Elements (To_Set'Result), 1) = New_Item;
function Is_Empty (Container : Set) return Boolean with
Global => null,
Post => Is_Empty'Result = (Length (Container) = 0);
procedure Clear (Container : in out Set) with
Global => null,
Post => Length (Container) = 0 and M.Is_Empty (Model (Container));
procedure Assign (Target : in out Set; Source : Set) with
Global => null,
Pre => Target.Capacity >= Length (Source),
Post =>
Model (Target) = Model (Source)
and Elements (Target) = Elements (Source)
and Length (Target) = Length (Source);
function Copy (Source : Set; Capacity : Count_Type := 0) return Set with
Global => null,
Pre => Capacity = 0 or else Capacity >= Source.Capacity,
Post =>
Model (Copy'Result) = Model (Source)
and Elements (Copy'Result) = Elements (Source)
and Positions (Copy'Result) = Positions (Source)
and (if Capacity = 0 then
Copy'Result.Capacity = Source.Capacity
else
Copy'Result.Capacity = Capacity);
function Element
(Container : Set;
Position : Cursor) return Element_Type
with
Global => null,
Pre => Has_Element (Container, Position),
Post =>
Element'Result =
E.Get (Elements (Container), P.Get (Positions (Container), Position));
pragma Annotate (GNATprove, Inline_For_Proof, Element);
procedure Replace_Element
(Container : in out Set;
Position : Cursor;
New_Item : Element_Type)
with
Global => null,
Pre => Has_Element (Container, Position),
Post =>
Length (Container) = Length (Container)'Old
-- Position now maps to New_Item
and Element (Container, Position) = New_Item
-- New_Item is contained in Container
and Contains (Model (Container), New_Item)
-- Other elements are preserved
and M.Included_Except
(Model (Container)'Old,
Model (Container),
Element (Container, Position)'Old)
and M.Included_Except
(Model (Container),
Model (Container)'Old,
New_Item)
-- Mapping from cursors to elements is preserved
and Mapping_Preserved_Except
(E_Left => Elements (Container)'Old,
E_Right => Elements (Container),
P_Left => Positions (Container)'Old,
P_Right => Positions (Container),
Position => Position)
and Positions (Container) = Positions (Container)'Old;
function Constant_Reference
(Container : aliased Set;
Position : Cursor) return not null access constant Element_Type
with
Global => null,
Pre => Has_Element (Container, Position),
Post =>
Constant_Reference'Result.all =
E.Get (Elements (Container), P.Get (Positions (Container), Position));
procedure Move (Target : in out Set; Source : in out Set) with
Global => null,
Pre => Target.Capacity >= Length (Source),
Post =>
Model (Target) = Model (Source)'Old
and Elements (Target) = Elements (Source)'Old
and Length (Source)'Old = Length (Target)
and Length (Source) = 0;
procedure Insert
(Container : in out Set;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
with
Global => null,
Pre =>
Length (Container) < Container.Capacity
or Contains (Container, New_Item),
Post =>
Contains (Container, New_Item)
and Has_Element (Container, Position)
and Equivalent_Elements (Element (Container, Position), New_Item)
and E_Is_Find
(Elements (Container),
New_Item,
P.Get (Positions (Container), Position)),
Contract_Cases =>
-- If New_Item is already in Container, it is not modified and Inserted
-- is set to False.
(Contains (Container, New_Item) =>
not Inserted
and Model (Container) = Model (Container)'Old
and Elements (Container) = Elements (Container)'Old
and Positions (Container) = Positions (Container)'Old,
-- Otherwise, New_Item is inserted in Container and Inserted is set to
-- True
others =>
Inserted
and Length (Container) = Length (Container)'Old + 1
-- Position now maps to New_Item
and Element (Container, Position) = New_Item
-- Other elements are preserved
and Model (Container)'Old <= Model (Container)
and M.Included_Except
(Model (Container),
Model (Container)'Old,
New_Item)
-- The elements of Container located before Position are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => P.Get (Positions (Container), Position) - 1)
-- Other elements are shifted by 1
and E.Range_Shifted
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => P.Get (Positions (Container), Position),
Lst => Length (Container)'Old,
Offset => 1)
-- A new cursor has been inserted at position Position in
-- Container.
and P_Positions_Shifted
(Positions (Container)'Old,
Positions (Container),
Cut => P.Get (Positions (Container), Position)));
procedure Insert
(Container : in out Set;
New_Item : Element_Type)
with
Global => null,
Pre =>
Length (Container) < Container.Capacity
and then (not Contains (Container, New_Item)),
Post =>
Length (Container) = Length (Container)'Old + 1
and Contains (Container, New_Item)
-- New_Item is inserted in the set
and E.Get (Elements (Container),
Find (Elements (Container), New_Item)) = New_Item
-- Other mappings are preserved
and Model (Container)'Old <= Model (Container)
and M.Included_Except
(Model (Container),
Model (Container)'Old,
New_Item)
-- The elements of Container located before New_Item are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), New_Item) - 1)
-- Other elements are shifted by 1
and E.Range_Shifted
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => Find (Elements (Container), New_Item),
Lst => Length (Container)'Old,
Offset => 1)
-- A new cursor has been inserted in Container
and P_Positions_Shifted
(Positions (Container)'Old,
Positions (Container),
Cut => Find (Elements (Container), New_Item));
procedure Include
(Container : in out Set;
New_Item : Element_Type)
with
Global => null,
Pre =>
Length (Container) < Container.Capacity
or Contains (Container, New_Item),
Post => Contains (Container, New_Item),
Contract_Cases =>
-- If New_Item is already in Container
(Contains (Container, New_Item) =>
-- Elements are preserved
Model (Container)'Old = Model (Container)
-- Cursors are preserved
and Positions (Container) = Positions (Container)'Old
-- The element equivalent to New_Item in Container is replaced by
-- New_Item.
and E.Get (Elements (Container),
Find (Elements (Container), New_Item)) = New_Item
and E.Equal_Except
(Elements (Container)'Old,
Elements (Container),
Find (Elements (Container), New_Item)),
-- Otherwise, New_Item is inserted in Container
others =>
Length (Container) = Length (Container)'Old + 1
-- Other elements are preserved
and Model (Container)'Old <= Model (Container)
and M.Included_Except
(Model (Container),
Model (Container)'Old,
New_Item)
-- New_Item is inserted in Container
and E.Get (Elements (Container),
Find (Elements (Container), New_Item)) = New_Item
-- The Elements of Container located before New_Item are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), New_Item) - 1)
-- Other Elements are shifted by 1
and E.Range_Shifted
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => Find (Elements (Container), New_Item),
Lst => Length (Container)'Old,
Offset => 1)
-- A new cursor has been inserted in Container
and P_Positions_Shifted
(Positions (Container)'Old,
Positions (Container),
Cut => Find (Elements (Container), New_Item)));
procedure Replace
(Container : in out Set;
New_Item : Element_Type)
with
Global => null,
Pre => Contains (Container, New_Item),
Post =>
-- Elements are preserved
Model (Container)'Old = Model (Container)
-- Cursors are preserved
and Positions (Container) = Positions (Container)'Old
-- The element equivalent to New_Item in Container is replaced by
-- New_Item.
and E.Get (Elements (Container),
Find (Elements (Container), New_Item)) = New_Item
and E.Equal_Except
(Elements (Container)'Old,
Elements (Container),
Find (Elements (Container), New_Item));
procedure Exclude
(Container : in out Set;
Item : Element_Type)
with
Global => null,
Post => not Contains (Container, Item),
Contract_Cases =>
-- If Item is not in Container, nothing is changed
(not Contains (Container, Item) =>
Model (Container) = Model (Container)'Old
and Elements (Container) = Elements (Container)'Old
and Positions (Container) = Positions (Container)'Old,
-- Otherwise, Item is removed from Container
others =>
Length (Container) = Length (Container)'Old - 1
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M.Included_Except
(Model (Container)'Old,
Model (Container),
Item)
-- The elements of Container located before Item are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), Item)'Old - 1)
-- The elements located after Item are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => Find (Elements (Container), Item)'Old,
Lst => Length (Container),
Offset => 1)
-- A cursor has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => Find (Elements (Container), Item)'Old));
procedure Delete
(Container : in out Set;
Item : Element_Type)
with
Global => null,
Pre => Contains (Container, Item),
Post =>
Length (Container) = Length (Container)'Old - 1
-- Item is no longer in Container
and not Contains (Container, Item)
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M.Included_Except
(Model (Container)'Old,
Model (Container),
Item)
-- The elements of Container located before Item are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), Item)'Old - 1)
-- The elements located after Item are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => Find (Elements (Container), Item)'Old,
Lst => Length (Container),
Offset => 1)
-- A cursor has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => Find (Elements (Container), Item)'Old);
procedure Delete
(Container : in out Set;
Position : in out Cursor)
with
Global => null,
Depends => (Container =>+ Position, Position => null),
Pre => Has_Element (Container, Position),
Post =>
Position = No_Element
and Length (Container) = Length (Container)'Old - 1
-- The element at position Position is no longer in Container
and not Contains (Container, Element (Container, Position)'Old)
and not P.Has_Key (Positions (Container), Position'Old)
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M.Included_Except
(Model (Container)'Old,
Model (Container),
Element (Container, Position)'Old)
-- The elements of Container located before Position are preserved.
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => P.Get (Positions (Container)'Old, Position'Old) - 1)
-- The elements located after Position are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => P.Get (Positions (Container)'Old, Position'Old),
Lst => Length (Container),
Offset => 1)
-- Position has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => P.Get (Positions (Container)'Old, Position'Old));
procedure Delete_First (Container : in out Set) with
Global => null,
Contract_Cases =>
(Length (Container) = 0 => Length (Container) = 0,
others =>
Length (Container) = Length (Container)'Old - 1
-- The first element has been removed from Container
and not Contains (Container, First_Element (Container)'Old)
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M.Included_Except
(Model (Container)'Old,
Model (Container),
First_Element (Container)'Old)
-- Other elements are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => 1,
Lst => Length (Container),
Offset => 1)
-- First has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => 1));
procedure Delete_Last (Container : in out Set) with
Global => null,
Contract_Cases =>
(Length (Container) = 0 => Length (Container) = 0,
others =>
Length (Container) = Length (Container)'Old - 1
-- The last element has been removed from Container
and not Contains (Container, Last_Element (Container)'Old)
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M.Included_Except
(Model (Container)'Old,
Model (Container),
Last_Element (Container)'Old)
-- Others elements of Container are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Length (Container))
-- Last cursor has been removed from Container
and Positions (Container) <= Positions (Container)'Old);
procedure Union (Target : in out Set; Source : Set) with
Global => null,
Pre =>
Length (Source) - Length (Target and Source) <=
Target.Capacity - Length (Target),
Post =>
Length (Target) = Length (Target)'Old
- M.Num_Overlaps (Model (Target)'Old, Model (Source))
+ Length (Source)
-- Elements already in Target are still in Target
and Model (Target)'Old <= Model (Target)
-- Elements of Source are included in Target
and Model (Source) <= Model (Target)
-- Elements of Target come from either Source or Target
and
M.Included_In_Union
(Model (Target), Model (Source), Model (Target)'Old)
-- Actual value of elements come from either Left or Right
and
E_Elements_Included
(Elements (Target),
Model (Target)'Old,
Elements (Target)'Old,
Elements (Source))
and
E_Elements_Included
(Elements (Target)'Old, Model (Target)'Old, Elements (Target))
and
E_Elements_Included
(Elements (Source),
Model (Target)'Old,
Elements (Source),
Elements (Target))
-- Mapping from cursors of Target to elements is preserved
and Mapping_Preserved
(E_Left => Elements (Target)'Old,
E_Right => Elements (Target),
P_Left => Positions (Target)'Old,
P_Right => Positions (Target));
function Union (Left, Right : Set) return Set with
Global => null,
Pre => Length (Left) <= Count_Type'Last - Length (Right),
Post =>
Length (Union'Result) = Length (Left)
- M.Num_Overlaps (Model (Left), Model (Right))
+ Length (Right)
-- Elements of Left and Right are in the result of Union
and Model (Left) <= Model (Union'Result)
and Model (Right) <= Model (Union'Result)
-- Elements of the result of union come from either Left or Right
and
M.Included_In_Union
(Model (Union'Result), Model (Left), Model (Right))
-- Actual value of elements come from either Left or Right
and
E_Elements_Included
(Elements (Union'Result),
Model (Left),
Elements (Left),
Elements (Right))
and
E_Elements_Included
(Elements (Left), Model (Left), Elements (Union'Result))
and
E_Elements_Included
(Elements (Right),
Model (Left),
Elements (Right),
Elements (Union'Result));
function "or" (Left, Right : Set) return Set renames Union;
procedure Intersection (Target : in out Set; Source : Set) with
Global => null,
Post =>
Length (Target) =
M.Num_Overlaps (Model (Target)'Old, Model (Source))
-- Elements of Target were already in Target
and Model (Target) <= Model (Target)'Old
-- Elements of Target are in Source
and Model (Target) <= Model (Source)
-- Elements both in Source and Target are in the intersection
and
M.Includes_Intersection
(Model (Target), Model (Source), Model (Target)'Old)
-- Actual value of elements of Target is preserved
and E_Elements_Included (Elements (Target), Elements (Target)'Old)
and
E_Elements_Included
(Elements (Target)'Old, Model (Source), Elements (Target))
-- Mapping from cursors of Target to elements is preserved
and Mapping_Preserved
(E_Left => Elements (Target),
E_Right => Elements (Target)'Old,
P_Left => Positions (Target),
P_Right => Positions (Target)'Old);
function Intersection (Left, Right : Set) return Set with
Global => null,
Post =>
Length (Intersection'Result) =
M.Num_Overlaps (Model (Left), Model (Right))
-- Elements in the result of Intersection are in Left and Right
and Model (Intersection'Result) <= Model (Left)
and Model (Intersection'Result) <= Model (Right)
-- Elements both in Left and Right are in the result of Intersection
and
M.Includes_Intersection
(Model (Intersection'Result), Model (Left), Model (Right))
-- Actual value of elements come from Left
and
E_Elements_Included
(Elements (Intersection'Result), Elements (Left))
and
E_Elements_Included
(Elements (Left), Model (Right), Elements (Intersection'Result));
function "and" (Left, Right : Set) return Set renames Intersection;
procedure Difference (Target : in out Set; Source : Set) with
Global => null,
Post =>
Length (Target) = Length (Target)'Old -
M.Num_Overlaps (Model (Target)'Old, Model (Source))
-- Elements of Target were already in Target
and Model (Target) <= Model (Target)'Old
-- Elements of Target are not in Source
and M.No_Overlap (Model (Target), Model (Source))
-- Elements in Target but not in Source are in the difference
and
M.Included_In_Union
(Model (Target)'Old, Model (Target), Model (Source))
-- Actual value of elements of Target is preserved
and E_Elements_Included (Elements (Target), Elements (Target)'Old)
and
E_Elements_Included
(Elements (Target)'Old, Model (Target), Elements (Target))
-- Mapping from cursors of Target to elements is preserved
and Mapping_Preserved
(E_Left => Elements (Target),
E_Right => Elements (Target)'Old,
P_Left => Positions (Target),
P_Right => Positions (Target)'Old);
function Difference (Left, Right : Set) return Set with
Global => null,
Post =>
Length (Difference'Result) = Length (Left) -
M.Num_Overlaps (Model (Left), Model (Right))
-- Elements of the result of Difference are in Left
and Model (Difference'Result) <= Model (Left)
-- Elements of the result of Difference are in Right
and M.No_Overlap (Model (Difference'Result), Model (Right))
-- Elements in Left but not in Right are in the difference
and
M.Included_In_Union
(Model (Left), Model (Difference'Result), Model (Right))
-- Actual value of elements come from Left
and
E_Elements_Included (Elements (Difference'Result), Elements (Left))
and
E_Elements_Included
(Elements (Left),
Model (Difference'Result),
Elements (Difference'Result));
function "-" (Left, Right : Set) return Set renames Difference;
procedure Symmetric_Difference (Target : in out Set; Source : Set) with
Global => null,
Pre =>
Length (Source) - Length (Target and Source) <=
Target.Capacity - Length (Target) + Length (Target and Source),
Post =>
Length (Target) = Length (Target)'Old -
2 * M.Num_Overlaps (Model (Target)'Old, Model (Source)) +
Length (Source)
-- Elements of the difference were not both in Source and in Target
and M.Not_In_Both (Model (Target), Model (Target)'Old, Model (Source))
-- Elements in Target but not in Source are in the difference
and
M.Included_In_Union
(Model (Target)'Old, Model (Target), Model (Source))
-- Elements in Source but not in Target are in the difference
and
M.Included_In_Union
(Model (Source), Model (Target), Model (Target)'Old)
-- Actual value of elements come from either Left or Right
and
E_Elements_Included
(Elements (Target),
Model (Target)'Old,
Elements (Target)'Old,
Elements (Source))
and
E_Elements_Included
(Elements (Target)'Old, Model (Target), Elements (Target))
and
E_Elements_Included
(Elements (Source), Model (Target), Elements (Target));
function Symmetric_Difference (Left, Right : Set) return Set with
Global => null,
Pre => Length (Left) <= Count_Type'Last - Length (Right),
Post =>
Length (Symmetric_Difference'Result) = Length (Left) -
2 * M.Num_Overlaps (Model (Left), Model (Right)) +
Length (Right)
-- Elements of the difference were not both in Left and Right
and
M.Not_In_Both
(Model (Symmetric_Difference'Result), Model (Left), Model (Right))
-- Elements in Left but not in Right are in the difference
and
M.Included_In_Union
(Model (Left), Model (Symmetric_Difference'Result), Model (Right))
-- Elements in Right but not in Left are in the difference
and
M.Included_In_Union
(Model (Right), Model (Symmetric_Difference'Result), Model (Left))
-- Actual value of elements come from either Left or Right
and
E_Elements_Included
(Elements (Symmetric_Difference'Result),
Model (Left),
Elements (Left),
Elements (Right))
and
E_Elements_Included
(Elements (Left),
Model (Symmetric_Difference'Result),
Elements (Symmetric_Difference'Result))
and
E_Elements_Included
(Elements (Right),
Model (Symmetric_Difference'Result),
Elements (Symmetric_Difference'Result));
function "xor" (Left, Right : Set) return Set
renames Symmetric_Difference;
function Overlap (Left, Right : Set) return Boolean with
Global => null,
Post =>
Overlap'Result = not (M.No_Overlap (Model (Left), Model (Right)));
function Is_Subset (Subset : Set; Of_Set : Set) return Boolean with
Global => null,
Post => Is_Subset'Result = (Model (Subset) <= Model (Of_Set));
function First (Container : Set) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0 =>
First'Result = No_Element,
others =>
Has_Element (Container, First'Result)
and P.Get (Positions (Container), First'Result) = 1);
function First_Element (Container : Set) return Element_Type with
Global => null,
Pre => not Is_Empty (Container),
Post =>
First_Element'Result = E.Get (Elements (Container), 1)
and E_Smaller_Than_Range
(Elements (Container),
2,
Length (Container),
First_Element'Result);
function Last (Container : Set) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0 =>
Last'Result = No_Element,
others =>
Has_Element (Container, Last'Result)
and P.Get (Positions (Container), Last'Result) =
Length (Container));
function Last_Element (Container : Set) return Element_Type with
Global => null,
Pre => not Is_Empty (Container),
Post =>
Last_Element'Result = E.Get (Elements (Container), Length (Container))
and E_Bigger_Than_Range
(Elements (Container),
1,
Length (Container) - 1,
Last_Element'Result);
function Next (Container : Set; Position : Cursor) return Cursor with
Global => null,
Pre =>
Has_Element (Container, Position) or else Position = No_Element,
Contract_Cases =>
(Position = No_Element
or else P.Get (Positions (Container), Position) = Length (Container)
=>
Next'Result = No_Element,
others =>
Has_Element (Container, Next'Result)
and then P.Get (Positions (Container), Next'Result) =
P.Get (Positions (Container), Position) + 1);
procedure Next (Container : Set; Position : in out Cursor) with
Global => null,
Pre =>
Has_Element (Container, Position) or else Position = No_Element,
Contract_Cases =>
(Position = No_Element
or else P.Get (Positions (Container), Position) = Length (Container)
=>
Position = No_Element,
others =>
Has_Element (Container, Position)
and then P.Get (Positions (Container), Position) =
P.Get (Positions (Container), Position'Old) + 1);
function Previous (Container : Set; Position : Cursor) return Cursor with
Global => null,
Pre =>
Has_Element (Container, Position) or else Position = No_Element,
Contract_Cases =>
(Position = No_Element
or else P.Get (Positions (Container), Position) = 1
=>
Previous'Result = No_Element,
others =>
Has_Element (Container, Previous'Result)
and then P.Get (Positions (Container), Previous'Result) =
P.Get (Positions (Container), Position) - 1);
procedure Previous (Container : Set; Position : in out Cursor) with
Global => null,
Pre =>
Has_Element (Container, Position) or else Position = No_Element,
Contract_Cases =>
(Position = No_Element
or else P.Get (Positions (Container), Position) = 1
=>
Position = No_Element,
others =>
Has_Element (Container, Position)
and then P.Get (Positions (Container), Position) =
P.Get (Positions (Container), Position'Old) - 1);
function Find (Container : Set; Item : Element_Type) return Cursor with
Global => null,
Contract_Cases =>
-- If Item is not contained in Container, Find returns No_Element
(not Contains (Model (Container), Item) =>
not P.Has_Key (Positions (Container), Find'Result)
and Find'Result = No_Element,
-- Otherwise, Find returns a valid cursor in Container
others =>
P.Has_Key (Positions (Container), Find'Result)
and P.Get (Positions (Container), Find'Result) =
Find (Elements (Container), Item)
-- The element designated by the result of Find is Item
and Equivalent_Elements
(Element (Container, Find'Result), Item));
function Floor (Container : Set; Item : Element_Type) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0 or else Item < First_Element (Container) =>
Floor'Result = No_Element,
others =>
Has_Element (Container, Floor'Result)
and
not (Item < E.Get (Elements (Container),
P.Get (Positions (Container), Floor'Result)))
and E_Is_Find
(Elements (Container),
Item,
P.Get (Positions (Container), Floor'Result)));
function Ceiling (Container : Set; Item : Element_Type) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0 or else Last_Element (Container) < Item =>
Ceiling'Result = No_Element,
others =>
Has_Element (Container, Ceiling'Result)
and
not (E.Get (Elements (Container),
P.Get (Positions (Container), Ceiling'Result)) <
Item)
and E_Is_Find
(Elements (Container),
Item,
P.Get (Positions (Container), Ceiling'Result)));
function Contains (Container : Set; Item : Element_Type) return Boolean with
Global => null,
Post => Contains'Result = Contains (Model (Container), Item);
pragma Annotate (GNATprove, Inline_For_Proof, Contains);
function Has_Element (Container : Set; Position : Cursor) return Boolean
with
Global => null,
Post =>
Has_Element'Result = P.Has_Key (Positions (Container), Position);
pragma Annotate (GNATprove, Inline_For_Proof, Has_Element);
generic
type Key_Type (<>) is private;
with function Key (Element : Element_Type) return Key_Type;
with function "<" (Left, Right : Key_Type) return Boolean is <>;
package Generic_Keys with SPARK_Mode is
function Equivalent_Keys (Left, Right : Key_Type) return Boolean with
Global => null,
Post =>
Equivalent_Keys'Result = (not (Left < Right) and not (Right < Left));
pragma Annotate (GNATprove, Inline_For_Proof, Equivalent_Keys);
package Formal_Model with Ghost is
function E_Bigger_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
with
Global => null,
Pre => Lst <= E.Length (Container),
Post =>
E_Bigger_Than_Range'Result =
(for all I in Fst .. Lst =>
Generic_Keys.Key (E.Get (Container, I)) < Key);
pragma Annotate (GNATprove, Inline_For_Proof, E_Bigger_Than_Range);
function E_Smaller_Than_Range
(Container : E.Sequence;
Fst : Positive_Count_Type;
Lst : Count_Type;
Key : Key_Type) return Boolean
with
Global => null,
Pre => Lst <= E.Length (Container),
Post =>
E_Smaller_Than_Range'Result =
(for all I in Fst .. Lst =>
Key < Generic_Keys.Key (E.Get (Container, I)));
pragma Annotate (GNATprove, Inline_For_Proof, E_Smaller_Than_Range);
function E_Is_Find
(Container : E.Sequence;
Key : Key_Type;
Position : Count_Type) return Boolean
with
Global => null,
Pre => Position - 1 <= E.Length (Container),
Post =>
E_Is_Find'Result =
((if Position > 0 then
E_Bigger_Than_Range (Container, 1, Position - 1, Key))
and (if Position < E.Length (Container) then
E_Smaller_Than_Range
(Container,
Position + 1,
E.Length (Container),
Key)));
pragma Annotate (GNATprove, Inline_For_Proof, E_Is_Find);
function Find
(Container : E.Sequence;
Key : Key_Type) return Count_Type
-- Search for Key in Container
with
Global => null,
Post =>
(if Find'Result > 0 then
Find'Result <= E.Length (Container)
and Equivalent_Keys
(Key, Generic_Keys.Key (E.Get (Container, Find'Result)))
and E_Is_Find (Container, Key, Find'Result));
function M_Included_Except
(Left : M.Set;
Right : M.Set;
Key : Key_Type) return Boolean
with
Global => null,
Post =>
M_Included_Except'Result =
(for all E of Left =>
Contains (Right, E)
or Equivalent_Keys (Generic_Keys.Key (E), Key));
end Formal_Model;
use Formal_Model;
function Key (Container : Set; Position : Cursor) return Key_Type with
Global => null,
Post => Key'Result = Key (Element (Container, Position));
pragma Annotate (GNATprove, Inline_For_Proof, Key);
function Element (Container : Set; Key : Key_Type) return Element_Type
with
Global => null,
Pre => Contains (Container, Key),
Post =>
Element'Result = Element (Container, Find (Container, Key));
pragma Annotate (GNATprove, Inline_For_Proof, Element);
procedure Replace
(Container : in out Set;
Key : Key_Type;
New_Item : Element_Type)
with
Global => null,
Pre => Contains (Container, Key),
Post =>
Length (Container) = Length (Container)'Old
-- Key now maps to New_Item
and Element (Container, Key) = New_Item
-- New_Item is contained in Container
and Contains (Model (Container), New_Item)
-- Other elements are preserved
and M_Included_Except
(Model (Container)'Old,
Model (Container),
Key)
and M.Included_Except
(Model (Container),
Model (Container)'Old,
New_Item)
-- Mapping from cursors to elements is preserved
and Mapping_Preserved_Except
(E_Left => Elements (Container)'Old,
E_Right => Elements (Container),
P_Left => Positions (Container)'Old,
P_Right => Positions (Container),
Position => Find (Container, Key))
and Positions (Container) = Positions (Container)'Old;
procedure Exclude (Container : in out Set; Key : Key_Type) with
Global => null,
Post => not Contains (Container, Key),
Contract_Cases =>
-- If Key is not in Container, nothing is changed
(not Contains (Container, Key) =>
Model (Container) = Model (Container)'Old
and Elements (Container) = Elements (Container)'Old
and Positions (Container) = Positions (Container)'Old,
-- Otherwise, Key is removed from Container
others =>
Length (Container) = Length (Container)'Old - 1
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M_Included_Except
(Model (Container)'Old,
Model (Container),
Key)
-- The elements of Container located before Key are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), Key)'Old - 1)
-- The elements located after Key are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => Find (Elements (Container), Key)'Old,
Lst => Length (Container),
Offset => 1)
-- A cursor has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => Find (Elements (Container), Key)'Old));
procedure Delete (Container : in out Set; Key : Key_Type) with
Global => null,
Pre => Contains (Container, Key),
Post =>
Length (Container) = Length (Container)'Old - 1
-- Key is no longer in Container
and not Contains (Container, Key)
-- Other elements are preserved
and Model (Container) <= Model (Container)'Old
and M_Included_Except
(Model (Container)'Old,
Model (Container),
Key)
-- The elements of Container located before Key are preserved
and E.Range_Equal
(Left => Elements (Container)'Old,
Right => Elements (Container),
Fst => 1,
Lst => Find (Elements (Container), Key)'Old - 1)
-- The elements located after Key are shifted by 1
and E.Range_Shifted
(Left => Elements (Container),
Right => Elements (Container)'Old,
Fst => Find (Elements (Container), Key)'Old,
Lst => Length (Container),
Offset => 1)
-- A cursor has been removed from Container
and P_Positions_Shifted
(Positions (Container),
Positions (Container)'Old,
Cut => Find (Elements (Container), Key)'Old);
function Find (Container : Set; Key : Key_Type) return Cursor with
Global => null,
Contract_Cases =>
-- If Key is not contained in Container, Find returns No_Element
((for all E of Model (Container) =>
not Equivalent_Keys (Key, Generic_Keys.Key (E))) =>
not P.Has_Key (Positions (Container), Find'Result)
and Find'Result = No_Element,
-- Otherwise, Find returns a valid cursor in Container
others =>
P.Has_Key (Positions (Container), Find'Result)
and P.Get (Positions (Container), Find'Result) =
Find (Elements (Container), Key)
-- The element designated by the result of Find is Key
and Equivalent_Keys
(Generic_Keys.Key (Element (Container, Find'Result)), Key));
function Floor (Container : Set; Key : Key_Type) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0
or else Key < Generic_Keys.Key (First_Element (Container)) =>
Floor'Result = No_Element,
others =>
Has_Element (Container, Floor'Result)
and
not (Key <
Generic_Keys.Key
(E.Get (Elements (Container),
P.Get (Positions (Container), Floor'Result))))
and E_Is_Find
(Elements (Container),
Key,
P.Get (Positions (Container), Floor'Result)));
function Ceiling (Container : Set; Key : Key_Type) return Cursor with
Global => null,
Contract_Cases =>
(Length (Container) = 0
or else Generic_Keys.Key (Last_Element (Container)) < Key =>
Ceiling'Result = No_Element,
others =>
Has_Element (Container, Ceiling'Result)
and
not (Generic_Keys.Key
(E.Get (Elements (Container),
P.Get (Positions (Container), Ceiling'Result)))
< Key)
and E_Is_Find
(Elements (Container),
Key,
P.Get (Positions (Container), Ceiling'Result)));
function Contains (Container : Set; Key : Key_Type) return Boolean with
Global => null,
Post =>
Contains'Result =
(for some E of Model (Container) =>
Equivalent_Keys (Key, Generic_Keys.Key (E)));
end Generic_Keys;
private
pragma SPARK_Mode (Off);
pragma Inline (Next);
pragma Inline (Previous);
type Node_Type is record
Has_Element : Boolean := False;
Parent : Count_Type := 0;
Left : Count_Type := 0;
Right : Count_Type := 0;
Color : Red_Black_Trees.Color_Type;
Element : aliased Element_Type;
end record;
package Tree_Types is
new Red_Black_Trees.Generic_Bounded_Tree_Types (Node_Type);
type Set (Capacity : Count_Type) is record
Content : Tree_Types.Tree_Type (Capacity);
end record;
use Red_Black_Trees;
Empty_Set : constant Set := (Capacity => 0, others => <>);
end Ada.Containers.Formal_Ordered_Sets;
|
with GPIO;
with SPI;
with Interfaces; use Interfaces;
with Ada.Text_IO;
package body OLED_SH1106.Display is
procedure Reset is
begin
GPIO.Write(OLED_RST, 1);
delay 0.1;
GPIO.Write(OLED_RST, 0);
delay 0.1;
GPIO.Write(OLED_RST, 1);
delay 0.1;
end Reset;
procedure Write_Reg(Reg: Unsigned_8) is
begin
GPIO.Write(OLED_DC, 0);
SPI.Write(Reg);
end Write_Reg;
procedure Start_Data is
begin
GPIO.Write(OLED_DC, 1);
end Start_Data;
procedure Write_Data(Data: Unsigned_8) is
begin
SPI.Write(Data);
end Write_Data;
procedure Init_Reg is
begin
Write_Reg(16#AE#); -- --turn off oled panel
Write_Reg(16#02#); -- ---set low column address
Write_Reg(16#10#); -- ---set high column address
Write_Reg(16#40#); -- --set start line address Set Mapping RAM Display Start Line (0x00~0x3F)
Write_Reg(16#81#); -- --set contrast control register
Write_Reg(16#A0#); -- --Set SEG/Column Mapping
Write_Reg(16#C0#); -- Set COM/Row Scan Direction
Write_Reg(16#A6#); -- --set normal display
Write_Reg(16#A8#); -- --set multiplex ratio(1 to 64)
Write_Reg(16#3F#); -- --1/64 duty
Write_Reg(16#D3#); -- -set display offset Shift Mapping RAM Counter (0x00~0x3F)
Write_Reg(16#00#); -- -not offset
Write_Reg(16#d5#); -- --set display clock divide ratio/oscillator frequency
Write_Reg(16#80#); -- --set divide ratio, Set Clock as 100 Frames/Sec
Write_Reg(16#D9#); -- --set pre-charge period
Write_Reg(16#F1#); -- Set Pre-Charge as 15 Clocks & Discharge as 1 Clock
Write_Reg(16#DA#); -- --set com pins hardware configuration
Write_Reg(16#12#);
Write_Reg(16#DB#); -- --set vcomh
Write_Reg(16#40#); -- Set VCOM Deselect Level
Write_Reg(16#20#); -- -Set Page Addressing Mode (0x00/0x01/0x02)
Write_Reg(16#02#); --
Write_Reg(16#A4#); -- Disable Entire Display On (0xa4/0xa5)
Write_Reg(16#A6#); -- Disable Inverse Display On (0xa6/a7)
end Init_Reg;
procedure Init_GPIOs is
begin
GPIO.Set_Mode(OLED_RST, GPIO.MODE_OUTPUT);
GPIO.Set_Mode(OLED_DC, GPIO.MODE_OUTPUT);
GPIO.Set_Mode(OLED_CS, GPIO.MODE_OUTPUT);
GPIO.Set_Mode(KEY_UP_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY_DOWN_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY_LEFT_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY_RIGHT_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY_PRESS_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY1_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY2_PIN, GPIO.MODE_INPUT);
GPIO.Set_Mode(KEY3_PIN, GPIO.MODE_INPUT);
end Init_GPIOs;
function Module_Init return Boolean is
begin
if GPIO.Init = 0 then
return false;
end if;
Init_GPIOs;
SPI.Start;
SPI.Set_Bit_Order(SPI.BIT_ORDER_MSBFIRST);
SPI.Set_Data_Mode(SPI.MODE0);
SPI.Set_Clock_Divider(SPI.CLOCK_DIVIDER_128);
SPI.Set_Chip_Select(SPI.CS0);
SPI.Set_Chip_Select_Polarity(SPI.CS0, SPI.LOW);
return true;
end Module_Init;
end OLED_SH1106.Display;
|
-- The Cupcake GUI Toolkit
-- (c) Kristian Klomsten Skordal 2012 <kristian.skordal@gmail.com>
-- Report bugs and issues on <http://github.com/skordal/cupcake/issues>
-- vim:ts=3:sw=3:et:si:sta
with Cupcake.Colors;
with Cupcake.Primitives;
with Cupcake.Backends;
private with Ada.Containers.Doubly_Linked_Lists;
package Cupcake.Windows is
-- Normal window type:
type Window_Record (<>) is tagged limited private;
type Window is access all Window_Record'Class;
-- Creates a new window:
function New_Window (Width, Height : in Positive; Title : in String)
return Window;
function New_Window (Size : in Primitives.Dimension; Title : in String)
return Window;
-- Destroys a window:
procedure Destroy (Object : not null access Window_Record);
-- Sets the visibility of a window; this is used to show and close windows:
procedure Set_Visible (This : access Window_Record'Class;
Visible : Boolean := True);
-- Window size operations:
function Get_Size (This : in Window_Record'Class)
return Primitives.Dimension with Inline, Pure_Function;
procedure Set_Size (This : in out Window_Record'Class;
Size : in Primitives.Dimension) with Inline;
-- Window color operations:
function Get_Background_Color (This : in Window_Record'Class)
return Colors.Color with Inline, Pure_Function;
procedure Set_Background_Color (This : out Window_Record'Class;
Color : in Colors.Color) with Inline;
-- Expose handler for windows:
procedure Expose_Handler (This : in Window_Record'Class);
-- Resize handler for windows:
procedure Resize_Handler (This : in out Window_Record'Class;
New_Size : in Primitives.Dimension);
-- Close event handler for windows; returns true if the window should
-- close:
function Close_Handler (This : in Window_Record'Class) return Boolean;
---- BACKEND OPERATIONS: ----
-- Posts an expose event to a window; this causes a redraw of the entire
-- window:
procedure Post_Expose (ID : in Backends.Window_ID_Type);
pragma Export (C, Post_Expose);
procedure Post_Expose (This : in Window_Record'Class);
-- Posts a resize event to a window:
procedure Post_Resize (ID : in Backends.Window_ID_Type;
Width, Height : in Natural);
pragma Export (C, Post_Resize);
procedure Post_Resize (ID : in Backends.Window_ID_Type;
New_Size : in Primitives.Dimension);
-- Posts a close request to a window:
procedure Post_Close_Event (ID : in Backends.Window_ID_Type);
pragma Export (C, Post_Close_Event);
private
-- List of active (visible) windows, for event propagation:
package Window_Lists is new Ada.Containers.Doubly_Linked_Lists (
Element_Type => Window);
Visible_Window_List : Window_Lists.List;
-- Gets a window pointer by ID if the window is visible; returns null
-- otherwise:
function Get_Visible_Window (ID : in Backends.Window_ID_Type) return Window;
function Get_Visible_Window (ID : in Backends.Window_ID_Type)
return Backends.Window_Data_Pointer;
pragma Export (C, Get_Visible_Window);
-- Normal window type definition:
type Window_Record is tagged limited record
Size : Primitives.Dimension;
Background_Color : Colors.Color := Colors.DEFAULT_BACKGROUND_COLOR;
Backend_Data : Backends.Window_Data_Pointer;
ID : Backends.Window_ID_Type;
end record;
end Cupcake.Windows;
|
-----------------------------------------------------------------------
-- gen-model-xmi -- UML-XMI model
-- Copyright (C) 2012, 2013, 2015, 2016, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Tags;
with Util.Strings;
with Util.Log.Loggers;
package body Gen.Model.XMI is
use Ada.Strings.Unbounded;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Gen.Model.XMI");
procedure Append_Message (Into : in out UString;
Message : in String);
-- ------------------------------
-- Append a message to the error message. A newline is inserted if the buffer contains
-- an existing message.
-- ------------------------------
procedure Append_Message (Into : in out UString;
Message : in String) is
begin
if Length (Into) > 0 then
Append (Into, ASCII.LF);
end if;
Append (Into, Message);
end Append_Message;
-- ------------------------------
-- Iterate on the model element of the type <tt>On</tt> and execute the <tt>Process</tt>
-- procedure.
-- ------------------------------
procedure Iterate (Model : in Model_Map.Map;
On : in Element_Type;
Process : not null access procedure (Id : in UString;
Node : in Model_Element_Access)) is
Iter : Model_Map_Cursor := Model.First;
begin
while Has_Element (Iter) loop
declare
Node : constant Model_Element_Access := Element (Iter);
begin
if Node.Get_Type = On then
Process (Model_Map.Key (Iter), Node);
end if;
end;
Next (Iter);
end loop;
end Iterate;
-- ------------------------------
-- Iterate over the model elements of the list.
-- ------------------------------
procedure Iterate_Elements (Closure : in out T;
List : in Model_Vector;
Process : not null access
procedure (Closure : in out T;
Node : in Model_Element_Access)) is
Iter : Model_Cursor := List.First;
begin
while Model_Vectors.Has_Element (Iter) loop
Process (Closure, Model_Vectors.Element (Iter));
Model_Vectors.Next (Iter);
end loop;
end Iterate_Elements;
-- ------------------------------
-- Find the model element with the given XMI id or given name.
-- Returns null if the model element is not found.
-- ------------------------------
function Find (Model : in Model_Map.Map;
Key : in String;
Mode : in Search_Type := BY_ID) return Model_Element_Access is
begin
if Mode = BY_ID then
declare
Pos : constant Model_Map_Cursor := Model.Find (To_UString (Key));
begin
if Has_Element (Pos) then
return Element (Pos);
else
Log.Error ("Model element id '{0}' not found", Key);
return null;
end if;
end;
else
declare
Iter : Model_Map_Cursor := Model.First;
Pos : Natural;
begin
if Key (Key'First) /= '@' then
Pos := Util.Strings.Index (Key, '.');
else
Pos := 0;
end if;
while Has_Element (Iter) loop
declare
Node : Model_Element_Access := Element (Iter);
begin
-- Find in the package only. If there is no '.', check the package name only.
if Node.Get_Type = XMI_PACKAGE then
if Pos = 0 and Node.Name = Key then
return Node;
end if;
-- Check that the package name matches and look in it.
if Pos > 0 and then Node.Name = Key (Key'First .. Pos - 1) then
Node := Node.Find (Key (Pos + 1 .. Key'Last));
if Node /= null then
return Node;
end if;
end if;
end if;
end;
Next (Iter);
end loop;
end;
return null;
end if;
end Find;
-- ------------------------------
-- Find from the model file identified by <tt>Name</tt>, the model element with the
-- identifier or name represented by <tt>Key</tt>.
-- Returns null if the model element is not found.
-- ------------------------------
function Find_Element (Model : in UML_Model;
Name : in String;
Key : in String;
Mode : in Search_Type := BY_ID)
return Element_Type_Access is
Model_Pos : constant UML_Model_Map.Cursor := Model.Find (To_UString (Name));
Item : Model_Element_Access;
begin
if UML_Model_Map.Has_Element (Model_Pos) then
if Mode = BY_ID or Mode = BY_NAME then
Item := Find (UML_Model_Map.Element (Model_Pos), Key, Mode);
else
declare
Iter : Model_Map_Cursor := UML_Model_Map.Element (Model_Pos).First;
begin
while Has_Element (Iter) loop
declare
Node : constant Model_Element_Access := Element (Iter);
begin
if Node.all in Element_Type'Class and then Node.Name = Key then
return Element_Type'Class (Node.all)'Access;
end if;
end;
Next (Iter);
end loop;
end;
end if;
if Item = null then
Log.Error ("The model file {0} does not define {1}",
Name, Key);
return null;
end if;
if not (Item.all in Element_Type'Class) then
Log.Error ("The model file {0} defines the element {1}",
Name, Key);
return null;
end if;
return Element_Type'Class (Item.all)'Access;
else
Log.Error ("Model file {0} not found", Name);
return null;
end if;
end Find_Element;
-- ------------------------------
-- Find the model element within all loaded UML models.
-- Returns null if the model element is not found.
-- ------------------------------
function Find (Model : in UML_Model;
Current : in Model_Map.Map;
Id : in UString)
return Model_Element_Access is
Pos : constant Natural := Index (Id, "#");
First : Natural;
begin
if Pos = 0 then
return Find (Current, To_String (Id));
end if;
First := Index (Id, "/", Pos, Ada.Strings.Backward);
if First = 0 then
First := 1;
else
First := First + 1;
end if;
declare
Len : constant Natural := Length (Id);
Name : constant UString := Unbounded_Slice (Id, First, Pos - 1);
Model_Pos : constant UML_Model_Map.Cursor := Model.Find (Name);
begin
if UML_Model_Map.Has_Element (Model_Pos) then
return Find (UML_Model_Map.Element (Model_Pos),
Slice (Id, Pos + 1, Len));
else
Log.Error ("Model element {0} not found", To_String (Id));
return null;
end if;
end;
end Find;
-- ------------------------------
-- Dump the XMI model elements.
-- ------------------------------
procedure Dump (Map : in Model_Map.Map) is
Iter : Model_Map_Cursor := Map.First;
begin
while Has_Element (Iter) loop
Element (Iter).Dump;
Next (Iter);
end loop;
end Dump;
-- ------------------------------
-- Reconcile all the UML model elements by resolving all the references to UML elements.
-- ------------------------------
procedure Reconcile (Model : in out UML_Model;
Debug : in Boolean := False) is
procedure Reconcile_Model (Key : in UString;
Map : in out Model_Map.Map);
procedure Reconcile_Model (Key : in UString;
Map : in out Model_Map.Map) is
pragma Unreferenced (Key);
Iter : Model_Map_Cursor := Map.First;
begin
while Has_Element (Iter) loop
declare
Node : constant Model_Element_Access := Element (Iter);
begin
Node.Reconcile (Model);
end;
Next (Iter);
end loop;
if Debug then
Gen.Model.XMI.Dump (Map);
end if;
end Reconcile_Model;
Iter : UML_Model_Map.Cursor := Model.First;
begin
while UML_Model_Map.Has_Element (Iter) loop
UML_Model_Map.Update_Element (Model, Iter, Reconcile_Model'Access);
UML_Model_Map.Next (Iter);
end loop;
end Reconcile;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
procedure Reconcile (Node : in out Model_Element;
Model : in UML_Model) is
Iter : Model_Cursor := Node.Stereotypes.First;
begin
while Model_Vectors.Has_Element (Iter) loop
Model_Vectors.Element (Iter).Reconcile (Model);
Model_Vectors.Next (Iter);
end loop;
end Reconcile;
-- ------------------------------
-- Find the element with the given name. If the name is a qualified name, navigate
-- down the package/class to find the appropriate element.
-- Returns null if the element was not found.
-- ------------------------------
function Find (Node : in Model_Element;
Name : in String) return Model_Element_Access is
Pos : constant Natural := Util.Strings.Index (Name, '.');
Iter : Model_Cursor;
Item : Model_Element_Access;
begin
if Pos = 0 or Name (Name'First) = '@' then
Iter := Node.Elements.First;
while Model_Vectors.Has_Element (Iter) loop
Item := Model_Vectors.Element (Iter);
if Item.Name = Name then
return Item;
end if;
Model_Vectors.Next (Iter);
end loop;
return null;
else
Item := Node.Find (Name (Name'First .. Pos - 1));
if Item = null then
return null;
end if;
return Item.Find (Name (Pos + 1 .. Name'Last));
end if;
end Find;
-- ------------------------------
-- Set the model name.
-- ------------------------------
procedure Set_Name (Node : in out Model_Element;
Value : in UBO.Object) is
begin
if not UBO.Is_Null (Value) then
Node.Set_Name (UBO.To_Unbounded_String (Value));
end if;
end Set_Name;
-- ------------------------------
-- Set the model XMI unique id.
-- ------------------------------
procedure Set_XMI_Id (Node : in out Model_Element;
Value : in UBO.Object) is
begin
Node.XMI_Id := UBO.To_Unbounded_String (Value);
end Set_XMI_Id;
-- ------------------------------
-- Validate the node definition as much as we can before the reconcile phase.
-- If an error is detected, return a message. Returns an empty string if everything is ok.
-- ------------------------------
function Get_Error_Message (Node : in Model_Element) return String is
Result : UString;
begin
if Length (Node.XMI_Id) = 0 then
Append (Result, "the 'xmi.id' attribute is empty");
end if;
return To_String (Result);
end Get_Error_Message;
-- ------------------------------
-- Dump the node to get some debugging description about it.
-- ------------------------------
procedure Dump (Node : in Model_Element) is
begin
Log.Info ("XMI {0} - {2}: {1}",
Element_Type'Image (Model_Element'Class (Node).Get_Type),
To_String (Node.XMI_Id), To_String (Node.Name));
if Node.Parent /= null then
Log.Info (" Parent: {0} ({1})", To_String (Node.Parent.Name),
Element_Type'Image (Node.Parent.Get_Type));
end if;
declare
Iter : Model_Cursor := Node.Tagged_Values.First;
Tag : Tagged_Value_Element_Access;
begin
while Model_Vectors.Has_Element (Iter) loop
Tag := Tagged_Value_Element'Class (Model_Vectors.Element (Iter).all)'Access;
if Tag.Tag_Def /= null then
Log.Info (" Tag: {0} = {1}",
To_String (Tag.Tag_Def.Name),
To_String (Tag.Value));
else
Log.Info (" Undef tag: {0} = {1}",
To_String (Tag.XMI_Id), To_String (Tag.Value));
end if;
Model_Vectors.Next (Iter);
end loop;
end;
declare
Stereotype : Model_Cursor := Node.Stereotypes.First;
begin
while Model_Vectors.Has_Element (Stereotype) loop
Log.Info (" Stereotype: <<{0}>>: {1}",
To_String (Model_Vectors.Element (Stereotype).Name),
To_String (Model_Vectors.Element (Stereotype).XMI_Id));
Model_Vectors.Next (Stereotype);
end loop;
end;
end Dump;
-- ------------------------------
-- Find the tag value element with the given name.
-- Returns null if there is no such tag.
-- ------------------------------
function Find_Tag_Value (Node : in Model_Element;
Name : in String) return Tagged_Value_Element_Access is
Pos : Model_Cursor := Node.Tagged_Values.First;
Tag : Model_Element_Access;
begin
while Model_Vectors.Has_Element (Pos) loop
Tag := Model_Vectors.Element (Pos);
if Tag.Name = Name then
return Tagged_Value_Element'Class (Tag.all)'Access;
end if;
Model_Vectors.Next (Pos);
end loop;
return null;
end Find_Tag_Value;
-- ------------------------------
-- Find the tag value associated with the given tag definition.
-- Returns the tag value if it was found, otherwise returns the default
-- ------------------------------
function Find_Tag_Value (Node : in Model_Element;
Definition : in Tag_Definition_Element_Access;
Default : in String := "") return String is
Pos : Model_Cursor := Node.Tagged_Values.First;
Tag : Model_Element_Access;
begin
while Model_Vectors.Has_Element (Pos) loop
Tag := Model_Vectors.Element (Pos);
if Tag.all in Tagged_Value_Element'Class and then
Tagged_Value_Element'Class (Tag.all).Tag_Def = Definition
then
return To_String (Tagged_Value_Element'Class (Tag.all).Value);
end if;
Model_Vectors.Next (Pos);
end loop;
return Default;
end Find_Tag_Value;
-- ------------------------------
-- Get the documentation and comment associated with the model element.
-- Returns the empty string if there is no comment.
-- ------------------------------
function Get_Comment (Node : in Model_Element) return String is
procedure Collect_Comment (Id : in UString;
Item : in Model_Element_Access);
Doc : constant Tagged_Value_Element_Access := Node.Find_Tag_Value (TAG_DOCUMENTATION);
Result : UString;
procedure Collect_Comment (Id : in UString;
Item : in Model_Element_Access) is
pragma Unreferenced (Id);
Comment : constant Comment_Element_Access := Comment_Element'Class (Item.all)'Access;
begin
if Comment.Ref_Id = Node.XMI_Id then
Append (Result, Comment.Text);
end if;
end Collect_Comment;
begin
Iterate (Node.Model.all, XMI_COMMENT, Collect_Comment'Access);
if Doc /= null then
Append (Result, Doc.Value);
end if;
return To_String (Result);
end Get_Comment;
-- ------------------------------
-- Get the full qualified name for the element.
-- ------------------------------
function Get_Qualified_Name (Node : in Model_Element) return String is
begin
if Node.Parent /= null then
return Node.Parent.Get_Qualified_Name & "." & To_String (Node.Name);
else
return To_String (Node.Name);
end if;
end Get_Qualified_Name;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Ref_Type_Element) return Element_Type is
begin
if Node.Ref /= null then
return Node.Ref.Get_Type;
else
return XMI_UNKNOWN;
end if;
end Get_Type;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Ref_Type_Element;
Model : in UML_Model) is
Item : constant Model_Element_Access := Find (Model, Node.Model.all, Node.Ref_Id);
begin
if Item /= null then
Node.Set_Name (Item.Name);
Node.Ref := Item;
Node.XMI_Id := Item.XMI_Id;
end if;
Model_Element (Node).Reconcile (Model);
end Reconcile;
-- ------------------------------
-- Set the reference id and collect in the profiles set the UML profiles that must
-- be loaded to get the reference.
-- ------------------------------
procedure Set_Reference_Id (Node : in out Ref_Type_Element;
Ref : in String;
Profiles : in out Util.Strings.Sets.Set) is
Pos : constant Natural := Util.Strings.Index (Ref, '#');
begin
Node.Ref_Id := To_UString (Ref);
if Pos > 0 then
declare
First : constant Natural := Util.Strings.Rindex (Ref, '/', Pos);
begin
Profiles.Include (Ref (First + 1 .. Pos - 1));
end;
end if;
end Set_Reference_Id;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Data_Type_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_DATA_TYPE;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Enum_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_ENUMERATION;
end Get_Type;
-- ------------------------------
-- Validate the node definition as much as we can before the reconcile phase.
-- An enum must not be empty, it must have at least one literal.
-- If an error is detected, return a message. Returns an empty string if everything is ok.
-- ------------------------------
overriding
function Get_Error_Message (Node : in Enum_Element) return String is
Result : UString;
begin
Append (Result, Model_Element (Node).Get_Error_Message);
if Node.Elements.Is_Empty then
Append_Message (Result, "the enum '" & To_String (Node.Name) & "' is empty.");
end if;
return To_String (Result);
end Get_Error_Message;
-- ------------------------------
-- Create an enum literal and add it to the enum.
-- ------------------------------
procedure Add_Literal (Node : in out Enum_Element;
Id : in UBO.Object;
Name : in UBO.Object;
Literal : out Literal_Element_Access) is
begin
Literal := new Literal_Element (Node.Model);
Literal.XMI_Id := UBO.To_Unbounded_String (Id);
Literal.Set_Name (UBO.To_Unbounded_String (Name));
Node.Elements.Append (Literal.all'Access);
end Add_Literal;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Literal_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_ENUMERATION_LITERAL;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Stereotype_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_STEREOTYPE;
end Get_Type;
-- ------------------------------
-- Returns True if the model element has the stereotype with the given name.
-- ------------------------------
function Has_Stereotype (Node : in Model_Element'Class;
Stereotype : in Stereotype_Element_Access) return Boolean is
Iter : Model_Cursor := Node.Stereotypes.First;
begin
if Stereotype = null then
return False;
end if;
while Model_Vectors.Has_Element (Iter) loop
declare
S : constant Model_Element_Access := Model_Vectors.Element (Iter);
begin
if S = Stereotype.all'Access then
return True;
end if;
if S.XMI_Id = Stereotype.XMI_Id then
return True;
end if;
end;
Model_Vectors.Next (Iter);
end loop;
return False;
end Has_Stereotype;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Comment_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_COMMENT;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Operation_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_OPERATION;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Attribute_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_ATTRIBUTE;
end Get_Type;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Attribute_Element;
Model : in UML_Model) is
Item : Model_Element_Access;
begin
if Length (Node.Ref_Id) = 0 then
return;
end if;
Item := Find (Model, Node.Model.all, Node.Ref_Id);
Model_Element (Node).Reconcile (Model);
if Item = null then
return;
end if;
if not (Item.all in Data_Type_Element'Class) then
Log.Error ("Invalid data type {0}", To_String (Node.Ref_Id));
return;
end if;
Node.Data_Type := Data_Type_Element'Class (Item.all)'Access;
end Reconcile;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Parameter_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_PARAMETER;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Association_End_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_ASSOCIATION_END;
end Get_Type;
-- ------------------------------
-- Get the documentation and comment associated with the model element.
-- Integrates the comment from the association itself as well as this association end.
-- Returns the empty string if there is no comment.
-- ------------------------------
overriding
function Get_Comment (Node : in Association_End_Element) return String is
Comment : constant String := Model_Element (Node).Get_Comment;
Association_Comment : constant String := Node.Parent.Get_Comment;
begin
if Association_Comment'Length = 0 then
return Comment;
elsif Comment'Length = 0 then
return Association_Comment;
else
return Association_Comment & ASCII.LF & Comment;
end if;
end Get_Comment;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Association_End_Element;
Model : in UML_Model) is
begin
Model_Element (Node).Reconcile (Model);
end Reconcile;
-- ------------------------------
-- Make the association between the two ends.
-- ------------------------------
procedure Make_Association (From : in out Association_End_Element;
To : in out Association_End_Element'Class;
Model : in UML_Model) is
Target : Model_Element_Access;
Source : Model_Element_Access;
begin
Log.Info ("Reconcile association {0} - {1}",
To_String (From.Name), To_String (To.Name));
Target := Find (Model, From.Model.all, To.Ref_Id);
if Target = null then
Log.Error ("Association end {0} not found", To_String (From.Name));
return;
end if;
Source := Find (Model, From.Model.all, From.Ref_Id);
if Source = null then
Log.Error ("Association end {0} not found", To_String (To.Name));
return;
end if;
if From.Navigable then
Class_Element'Class (Target.all).Associations.Append (From'Unchecked_Access);
From.Target_Element := Target.all'Access;
From.Source_Element := Source.all'Access;
Log.Info ("Class {0} { {1}: {2} }",
To_String (Target.Name),
To_String (From.Name),
To_String (Source.Name));
if Length (From.Name) = 0 then
Log.Error ("Class {0}: missing association end name to class {1}",
To_String (Target.Name), To_String (Source.Name));
end if;
end if;
end Make_Association;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Association_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_ASSOCIATION;
end Get_Type;
-- ------------------------------
-- Validate the node definition as much as we can before the reconcile phase.
-- An association must contain two ends and a name is necessary on the navigable ends.
-- If an error is detected, return a message. Returns an empty string if everything is ok.
-- ------------------------------
overriding
function Get_Error_Message (Node : in Association_Element) return String is
use type Ada.Containers.Count_Type;
Result : UString;
begin
Append (Result, Model_Element (Node).Get_Error_Message);
if Length (Node.Name) = 0 then
Append_Message (Result, "Association has an empty name.");
end if;
if Node.Connections.Length = 2 then
declare
First, Second : Association_End_Element_Access;
begin
First := Association_End_Element'Class (Node.Connections.Element (1).all)'Access;
Second := Association_End_Element'Class (Node.Connections.Element (2).all)'Access;
if First.Navigable and Length (First.Name) = 0 then
Append_Message (Result, "Association '" & To_String (Node.Name) &
"' has a navigable association end with an empty name.");
end if;
if Second.Navigable and Length (Second.Name) = 0 then
Append_Message (Result, "Association '" & To_String (Node.Name) &
"' has a navigable association end with an empty name.");
end if;
if not First.Navigable and not Second.Navigable then
Append_Message (Result, "Association '" & To_String (Node.Name) &
"' has no navigable association ends.");
end if;
end;
elsif Node.Connections.Length /= 0 then
Append_Message (Result, "Association '" & To_String (Node.Name)
& "' needs 2 association ends");
end if;
return To_String (Result);
end Get_Error_Message;
-- ------------------------------
-- Reconcile the association between classes in the package. Find the association
-- ends and add the necessary links to the corresponding class elements.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Association_Element;
Model : in UML_Model) is
use type Ada.Containers.Count_Type;
begin
Model_Element (Node).Reconcile (Model);
if Node.Connections.Length >= 2 then
declare
First, Second : Association_End_Element_Access;
begin
First := Association_End_Element'Class (Node.Connections.Element (1).all)'Access;
Second := Association_End_Element'Class (Node.Connections.Element (2).all)'Access;
First.Make_Association (Second.all, Model);
Second.Make_Association (First.all, Model);
end;
elsif Node.Connections.Length > 0 then
Log.Info ("Association {0} needs 2 association ends", To_String (Node.Name));
end if;
end Reconcile;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Generalization_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_GENERALIZATION;
end Get_Type;
-- ------------------------------
-- Reconcile the association between classes in the package. Find the association
-- ends and add the necessary links to the corresponding class elements.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Generalization_Element;
Model : in UML_Model) is
begin
Ref_Type_Element (Node).Reconcile (Model);
Node.Child_Class := Find (Model, Node.Model.all, Node.Child_Id);
if Node.Child_Class /= null then
if Node.Child_Class.all in Class_Element'Class then
Class_Element'Class (Node.Child_Class.all).Parent_Class := Node'Unchecked_Access;
elsif Node.Child_Class.all in Data_Type_Element'Class then
Data_Type_Element'Class (Node.Child_Class.all).Parent_Type := Node'Unchecked_Access;
end if;
end if;
end Reconcile;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Tagged_Value_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_TAGGED_VALUE;
end Get_Type;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Tagged_Value_Element;
Model : in UML_Model) is
Item : constant Model_Element_Access := Find (Model, Node.Model.all, Node.Ref_Id);
begin
Model_Element (Node).Reconcile (Model);
if Item /= null then
Node.Set_Name (Item.Name);
if not (Item.all in Tag_Definition_Element'Class) then
Log.Error ("Element {0} is not a tag definition. Tag is {1}, reference is {2}",
To_String (Item.Name),
Ada.Tags.Expanded_Name (Item'Tag),
To_String (Node.Ref_Id));
else
Node.Tag_Def := Tag_Definition_Element'Class (Item.all)'Access;
end if;
end if;
end Reconcile;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Tag_Definition_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_TAG_DEFINITION;
end Get_Type;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Class_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_CLASS;
end Get_Type;
-- ------------------------------
-- Reconcile the element by resolving the references to other elements in the model.
-- ------------------------------
overriding
procedure Reconcile (Node : in out Class_Element;
Model : in UML_Model) is
begin
if Node.Parent_Class /= null then
Node.Parent_Class.Reconcile (Model);
end if;
Data_Type_Element (Node).Reconcile (Model);
end Reconcile;
-- ------------------------------
-- Get the element type.
-- ------------------------------
overriding
function Get_Type (Node : in Package_Element) return Element_Type is
pragma Unreferenced (Node);
begin
return XMI_PACKAGE;
end Get_Type;
end Gen.Model.XMI;
|
pragma License (Unrestricted);
-- implementation unit
private package Ada.UCD is
-- This is the parent package of Unicode Character Database.
pragma Pure;
Version : constant String (1 .. 11) := "Unicode 6.1";
-- difference between two code points
type Difference_Base is range -(2 ** 31) .. 2 ** 31 - 1;
for Difference_Base'Size use 32;
subtype Difference_8 is Difference_Base range -(2 ** 7) .. 2 ** 7 - 1;
subtype Difference_16 is Difference_Base range -(2 ** 15) .. 2 ** 15 - 1;
subtype Difference_32 is Difference_Base;
-- code point types
type UCS_4 is mod 16#80000000#; -- same as System.UTF_Conversions.UCS_4
type UCS_4_Array is array (Positive range <>) of UCS_4;
for UCS_4_Array'Component_Size use 32;
pragma Suppress_Initialization (UCS_4_Array);
subtype UCS_2 is UCS_4 range 0 .. 16#ffff#;
type UCS_2_Array is array (Positive range <>) of UCS_2;
for UCS_2_Array'Component_Size use 16;
pragma Suppress_Initialization (UCS_2_Array);
type Combining_Class_Type is mod 2 ** 8;
type East_Asian_Width_Type is (N, Na, H, A, W, F);
-- same order as Ada.Strings.East_Asian_Width.Width_Kind
pragma Discard_Names (East_Asian_Width_Type);
-- set
type Set_16_Item_Type is record
Low : UCS_2;
High : UCS_2;
end record;
pragma Suppress_Initialization (Set_16_Item_Type);
for Set_16_Item_Type'Size use 32; -- 16 + 16
for Set_16_Item_Type use record
Low at 0 range 0 .. 15;
High at 0 range 16 .. 31;
end record;
type Set_16_Type is array (Positive range <>) of Set_16_Item_Type;
pragma Suppress_Initialization (Set_16_Type);
for Set_16_Type'Component_Size use 32;
type Set_32_Item_Type is record
Low : UCS_4;
High : UCS_4;
end record;
pragma Suppress_Initialization (Set_32_Item_Type);
for Set_32_Item_Type'Size use 64; -- 32 + 32
type Set_32_Type is array (Positive range <>) of Set_32_Item_Type;
pragma Suppress_Initialization (Set_32_Type);
for Set_32_Type'Component_Size use 64;
-- map
type Map_16x1_Item_Type is record
Code : UCS_2;
Mapping : UCS_2;
end record;
pragma Suppress_Initialization (Map_16x1_Item_Type);
for Map_16x1_Item_Type'Size use 32; -- 16 + 16
for Map_16x1_Item_Type use record
Code at 0 range 0 .. 15;
Mapping at 0 range 16 .. 31;
end record;
type Map_16x1_Type is array (Positive range <>) of Map_16x1_Item_Type;
pragma Suppress_Initialization (Map_16x1_Type);
for Map_16x1_Type'Component_Size use 32;
type Map_32x1_Item_Type is record
Code : UCS_4;
Mapping : UCS_4;
end record;
pragma Suppress_Initialization (Map_32x1_Item_Type);
for Map_32x1_Item_Type'Size use 64; -- 32 + 32
type Map_32x1_Type is array (Positive range <>) of Map_32x1_Item_Type;
pragma Suppress_Initialization (Map_32x1_Type);
for Map_32x1_Type'Component_Size use 64;
type Map_16x2_Item_Type is record
Code : UCS_2;
Mapping : UCS_2_Array (1 .. 2);
end record;
pragma Suppress_Initialization (Map_16x2_Item_Type);
for Map_16x2_Item_Type'Size use 48; -- 16 + 16 * 2
for Map_16x2_Item_Type use record
Code at 0 range 0 .. 15;
Mapping at 0 range 16 .. 47;
end record;
type Map_16x2_Type is array (Positive range <>) of Map_16x2_Item_Type;
pragma Suppress_Initialization (Map_16x2_Type);
for Map_16x2_Type'Component_Size use 48;
type Map_32x2_Item_Type is record
Code : UCS_4;
Mapping : UCS_4_Array (1 .. 2);
end record;
pragma Suppress_Initialization (Map_32x2_Item_Type);
for Map_32x2_Item_Type'Size use 96; -- 16 + 16 * 2
type Map_32x2_Type is array (Positive range <>) of Map_32x2_Item_Type;
pragma Suppress_Initialization (Map_32x2_Type);
for Map_32x2_Type'Component_Size use 96;
type Map_16x3_Item_Type is record
Code : UCS_2;
Mapping : UCS_2_Array (1 .. 3);
end record;
pragma Suppress_Initialization (Map_16x3_Item_Type);
for Map_16x3_Item_Type'Size use 64; -- 16 + 16 * 3
for Map_16x3_Item_Type use record
Code at 0 range 0 .. 15;
Mapping at 0 range 16 .. 63;
end record;
type Map_16x3_Type is array (Positive range <>) of Map_16x3_Item_Type;
pragma Suppress_Initialization (Map_16x3_Type);
for Map_16x3_Type'Component_Size use 64;
-- non-generated tables
-- see http://www.unicode.org/reports/tr15/#Hangul
package Hangul is
SBase : constant := 16#AC00#;
LBase : constant := 16#1100#;
VBase : constant := 16#1161#;
TBase : constant := 16#11A7#;
LCount : constant := 19;
VCount : constant := 21;
TCount : constant := 28;
NCount : constant := VCount * TCount; -- 588
SCount : constant := LCount * NCount; -- 11172
end Hangul;
end Ada.UCD;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- X R _ T A B L S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Types; use Types;
with Osint;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Ada.Strings.Fixed;
with Ada.Strings;
with Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with GNAT.HTable; use GNAT.HTable;
with GNAT.Heap_Sort_G;
package body Xr_Tabls is
type HTable_Headers is range 1 .. 10000;
procedure Set_Next (E : File_Reference; Next : File_Reference);
function Next (E : File_Reference) return File_Reference;
function Get_Key (E : File_Reference) return Cst_String_Access;
function Hash (F : Cst_String_Access) return HTable_Headers;
function Equal (F1, F2 : Cst_String_Access) return Boolean;
-- The five subprograms above are used to instantiate the static
-- htable to store the files that should be processed.
package File_HTable is new GNAT.HTable.Static_HTable
(Header_Num => HTable_Headers,
Element => File_Record,
Elmt_Ptr => File_Reference,
Null_Ptr => null,
Set_Next => Set_Next,
Next => Next,
Key => Cst_String_Access,
Get_Key => Get_Key,
Hash => Hash,
Equal => Equal);
-- A hash table to store all the files referenced in the
-- application. The keys in this htable are the name of the files
-- themselves, therefore it is assumed that the source path
-- doesn't contain twice the same source or ALI file name
type Unvisited_Files_Record;
type Unvisited_Files_Access is access Unvisited_Files_Record;
type Unvisited_Files_Record is record
File : File_Reference;
Next : Unvisited_Files_Access;
end record;
-- A special list, in addition to File_HTable, that only stores
-- the files that haven't been visited so far. Note that the File
-- list points to some data in File_HTable, and thus should never be freed.
function Next (E : Declaration_Reference) return Declaration_Reference;
procedure Set_Next (E, Next : Declaration_Reference);
function Get_Key (E : Declaration_Reference) return Cst_String_Access;
-- The subprograms above are used to instantiate the static
-- htable to store the entities that have been found in the application
package Entities_HTable is new GNAT.HTable.Static_HTable
(Header_Num => HTable_Headers,
Element => Declaration_Record,
Elmt_Ptr => Declaration_Reference,
Null_Ptr => null,
Set_Next => Set_Next,
Next => Next,
Key => Cst_String_Access,
Get_Key => Get_Key,
Hash => Hash,
Equal => Equal);
-- A hash table to store all the entities defined in the
-- application. For each entity, we store a list of its reference
-- locations as well.
-- The keys in this htable should be created with Key_From_Ref,
-- and are the file, line and column of the declaration, which are
-- unique for every entity.
Entities_Count : Natural := 0;
-- Number of entities in Entities_HTable. This is used in the end
-- when sorting the table.
Longest_File_Name_In_Table : Natural := 0;
Unvisited_Files : Unvisited_Files_Access := null;
Directories : Project_File_Ptr;
Default_Match : Boolean := False;
-- The above need commenting ???
function Parse_Gnatls_Src return String;
-- Return the standard source directories (taking into account the
-- ADA_INCLUDE_PATH environment variable, if Osint.Add_Default_Search_Dirs
-- was called first).
function Parse_Gnatls_Obj return String;
-- Return the standard object directories (taking into account the
-- ADA_OBJECTS_PATH environment variable).
function Key_From_Ref
(File_Ref : File_Reference;
Line : Natural;
Column : Natural)
return String;
-- Return a key for the symbol declared at File_Ref, Line,
-- Column. This key should be used for lookup in Entity_HTable
function Is_Less_Than (Decl1, Decl2 : Declaration_Reference) return Boolean;
-- Compare two declarations (the comparison is case-insensitive)
function Is_Less_Than (Ref1, Ref2 : Reference) return Boolean;
-- Compare two references
procedure Store_References
(Decl : Declaration_Reference;
Get_Writes : Boolean := False;
Get_Reads : Boolean := False;
Get_Bodies : Boolean := False;
Get_Declaration : Boolean := False;
Arr : in out Reference_Array;
Index : in out Natural);
-- Store in Arr, starting at Index, all the references to Decl. The Get_*
-- parameters can be used to indicate which references should be stored.
-- Constraint_Error will be raised if Arr is not big enough.
procedure Sort (Arr : in out Reference_Array);
-- Sort an array of references (Arr'First must be 1)
--------------
-- Set_Next --
--------------
procedure Set_Next (E : File_Reference; Next : File_Reference) is
begin
E.Next := Next;
end Set_Next;
procedure Set_Next
(E : Declaration_Reference; Next : Declaration_Reference) is
begin
E.Next := Next;
end Set_Next;
-------------
-- Get_Key --
-------------
function Get_Key (E : File_Reference) return Cst_String_Access is
begin
return E.File;
end Get_Key;
function Get_Key (E : Declaration_Reference) return Cst_String_Access is
begin
return E.Key;
end Get_Key;
----------
-- Hash --
----------
function Hash (F : Cst_String_Access) return HTable_Headers is
function H is new GNAT.HTable.Hash (HTable_Headers);
begin
return H (F.all);
end Hash;
-----------
-- Equal --
-----------
function Equal (F1, F2 : Cst_String_Access) return Boolean is
begin
return F1.all = F2.all;
end Equal;
------------------
-- Key_From_Ref --
------------------
function Key_From_Ref
(File_Ref : File_Reference;
Line : Natural;
Column : Natural)
return String
is
begin
return File_Ref.File.all & Natural'Image (Line) & Natural'Image (Column);
end Key_From_Ref;
---------------------
-- Add_Declaration --
---------------------
function Add_Declaration
(File_Ref : File_Reference;
Symbol : String;
Line : Natural;
Column : Natural;
Decl_Type : Character;
Is_Parameter : Boolean := False;
Remove_Only : Boolean := False;
Symbol_Match : Boolean := True)
return Declaration_Reference
is
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(Declaration_Record, Declaration_Reference);
Key : aliased constant String := Key_From_Ref (File_Ref, Line, Column);
New_Decl : Declaration_Reference :=
Entities_HTable.Get (Key'Unchecked_Access);
Is_Param : Boolean := Is_Parameter;
begin
-- Insert the Declaration in the table. There might already be a
-- declaration in the table if the entity is a parameter, so we
-- need to check that first.
if New_Decl /= null and then New_Decl.Symbol_Length = 0 then
Is_Param := Is_Parameter or else New_Decl.Is_Parameter;
Entities_HTable.Remove (Key'Unrestricted_Access);
Entities_Count := Entities_Count - 1;
Free (New_Decl.Key);
Unchecked_Free (New_Decl);
New_Decl := null;
end if;
-- The declaration might also already be there for parent types. In
-- this case, we should keep the entry, since some other entries are
-- pointing to it.
if New_Decl = null
and then not Remove_Only
then
New_Decl :=
new Declaration_Record'
(Symbol_Length => Symbol'Length,
Symbol => Symbol,
Key => new String'(Key),
Decl => new Reference_Record'
(File => File_Ref,
Line => Line,
Column => Column,
Source_Line => null,
Next => null),
Is_Parameter => Is_Param,
Decl_Type => Decl_Type,
Body_Ref => null,
Ref_Ref => null,
Modif_Ref => null,
Match => Symbol_Match
and then
(Default_Match
or else Match (File_Ref, Line, Column)),
Par_Symbol => null,
Next => null);
Entities_HTable.Set (New_Decl);
Entities_Count := Entities_Count + 1;
if New_Decl.Match then
Longest_File_Name_In_Table :=
Natural'Max (File_Ref.File'Length, Longest_File_Name_In_Table);
end if;
elsif New_Decl /= null
and then not New_Decl.Match
then
New_Decl.Match := Default_Match
or else Match (File_Ref, Line, Column);
New_Decl.Is_Parameter := New_Decl.Is_Parameter or Is_Param;
elsif New_Decl /= null then
New_Decl.Is_Parameter := New_Decl.Is_Parameter or Is_Param;
end if;
return New_Decl;
end Add_Declaration;
----------------------
-- Add_To_Xref_File --
----------------------
function Add_To_Xref_File
(File_Name : String;
Visited : Boolean := True;
Emit_Warning : Boolean := False;
Gnatchop_File : String := "";
Gnatchop_Offset : Integer := 0) return File_Reference
is
Base : aliased constant String := Base_Name (File_Name);
Dir : constant String := Dir_Name (File_Name);
Dir_Acc : GNAT.OS_Lib.String_Access := null;
Ref : File_Reference;
begin
-- Do we have a directory name as well?
if File_Name /= Base then
Dir_Acc := new String'(Dir);
end if;
Ref := File_HTable.Get (Base'Unchecked_Access);
if Ref = null then
Ref := new File_Record'
(File => new String'(Base),
Dir => Dir_Acc,
Lines => null,
Visited => Visited,
Emit_Warning => Emit_Warning,
Gnatchop_File => new String'(Gnatchop_File),
Gnatchop_Offset => Gnatchop_Offset,
Next => null);
File_HTable.Set (Ref);
if not Visited then
-- Keep a separate list for faster access
Set_Unvisited (Ref);
end if;
end if;
return Ref;
end Add_To_Xref_File;
--------------
-- Add_Line --
--------------
procedure Add_Line
(File : File_Reference;
Line : Natural;
Column : Natural)
is
begin
File.Lines := new Ref_In_File'(Line => Line,
Column => Column,
Next => File.Lines);
end Add_Line;
----------------
-- Add_Parent --
----------------
procedure Add_Parent
(Declaration : in out Declaration_Reference;
Symbol : String;
Line : Natural;
Column : Natural;
File_Ref : File_Reference)
is
begin
Declaration.Par_Symbol :=
Add_Declaration
(File_Ref, Symbol, Line, Column,
Decl_Type => ' ',
Symbol_Match => False);
end Add_Parent;
-------------------
-- Add_Reference --
-------------------
procedure Add_Reference
(Declaration : Declaration_Reference;
File_Ref : File_Reference;
Line : Natural;
Column : Natural;
Ref_Type : Character;
Labels_As_Ref : Boolean)
is
New_Ref : Reference;
New_Decl : Declaration_Reference;
pragma Unreferenced (New_Decl);
begin
case Ref_Type is
when ' ' | 'b' | 'c' | 'H' | 'i' | 'm' | 'o' | 'r' | 'R' | 's' | 'x'
=>
null;
when 'l' | 'w' =>
if not Labels_As_Ref then
return;
end if;
when '=' | '<' | '>' | '^' =>
-- Create dummy declaration in table to report it as a parameter
-- In a given ALI file, the declaration of the subprogram comes
-- before the declaration of the parameter. However, it is
-- possible that another ALI file has been parsed that also
-- references the parameter (for instance a named parameter in
-- a call), so we need to check whether there already exists a
-- declaration for the parameter.
New_Decl :=
Add_Declaration
(File_Ref => File_Ref,
Symbol => "",
Line => Line,
Column => Column,
Decl_Type => ' ',
Is_Parameter => True);
when 'd' | 'e' | 'E' | 'k' | 'p' | 'P' | 't' | 'z' =>
return;
when others =>
Ada.Text_IO.Put_Line ("Unknown reference type: " & Ref_Type);
return;
end case;
New_Ref := new Reference_Record'
(File => File_Ref,
Line => Line,
Column => Column,
Source_Line => null,
Next => null);
-- We can insert the reference into the list directly, since all the
-- references will appear only once in the ALI file corresponding to the
-- file where they are referenced. This saves a lot of time compared to
-- checking the list to check if it exists.
case Ref_Type is
when 'b' | 'c' =>
New_Ref.Next := Declaration.Body_Ref;
Declaration.Body_Ref := New_Ref;
when ' ' | 'H' | 'i' | 'l' | 'o' | 'r' | 'R' | 's' | 'w' | 'x' =>
New_Ref.Next := Declaration.Ref_Ref;
Declaration.Ref_Ref := New_Ref;
when 'm' =>
New_Ref.Next := Declaration.Modif_Ref;
Declaration.Modif_Ref := New_Ref;
when others =>
null;
end case;
if not Declaration.Match then
Declaration.Match := Match (File_Ref, Line, Column);
end if;
if Declaration.Match then
Longest_File_Name_In_Table :=
Natural'Max (File_Ref.File'Length, Longest_File_Name_In_Table);
end if;
end Add_Reference;
-------------------
-- ALI_File_Name --
-------------------
function ALI_File_Name (Ada_File_Name : String) return String is
-- ??? Should ideally be based on the naming scheme defined in
-- project files.
Index : constant Natural :=
Ada.Strings.Fixed.Index
(Ada_File_Name, ".", Going => Ada.Strings.Backward);
begin
if Index /= 0 then
return Ada_File_Name (Ada_File_Name'First .. Index)
& Osint.ALI_Suffix.all;
else
return Ada_File_Name & "." & Osint.ALI_Suffix.all;
end if;
end ALI_File_Name;
------------------
-- Is_Less_Than --
------------------
function Is_Less_Than (Ref1, Ref2 : Reference) return Boolean is
begin
if Ref1 = null then
return False;
elsif Ref2 = null then
return True;
end if;
if Ref1.File.File.all < Ref2.File.File.all then
return True;
elsif Ref1.File.File.all = Ref2.File.File.all then
return (Ref1.Line < Ref2.Line
or else (Ref1.Line = Ref2.Line
and then Ref1.Column < Ref2.Column));
end if;
return False;
end Is_Less_Than;
------------------
-- Is_Less_Than --
------------------
function Is_Less_Than (Decl1, Decl2 : Declaration_Reference) return Boolean
is
-- We cannot store the data case-insensitive in the table,
-- since we wouldn't be able to find the right casing for the
-- display later on.
S1 : constant String := To_Lower (Decl1.Symbol);
S2 : constant String := To_Lower (Decl2.Symbol);
begin
if S1 < S2 then
return True;
elsif S1 > S2 then
return False;
end if;
return Decl1.Key.all < Decl2.Key.all;
end Is_Less_Than;
-------------------------
-- Create_Project_File --
-------------------------
procedure Create_Project_File (Name : String) is
Obj_Dir : Unbounded_String := Null_Unbounded_String;
Src_Dir : Unbounded_String := Null_Unbounded_String;
Build_Dir : GNAT.OS_Lib.String_Access := new String'("");
F : File_Descriptor;
Len : Positive;
File_Name : aliased String := Name & ASCII.NUL;
begin
-- Read the size of the file
F := Open_Read (File_Name'Address, Text);
-- Project file not found
if F /= Invalid_FD then
Len := Positive (File_Length (F));
declare
Buffer : String (1 .. Len);
Index : Positive := Buffer'First;
Last : Positive;
begin
Len := Read (F, Buffer'Address, Len);
Close (F);
-- First, look for Build_Dir, since all the source and object
-- path are relative to it.
while Index <= Buffer'Last loop
-- Find the end of line
Last := Index;
while Last <= Buffer'Last
and then Buffer (Last) /= ASCII.LF
and then Buffer (Last) /= ASCII.CR
loop
Last := Last + 1;
end loop;
if Index <= Buffer'Last - 9
and then Buffer (Index .. Index + 9) = "build_dir="
then
Index := Index + 10;
while Index <= Last
and then (Buffer (Index) = ' '
or else Buffer (Index) = ASCII.HT)
loop
Index := Index + 1;
end loop;
Free (Build_Dir);
Build_Dir := new String'(Buffer (Index .. Last - 1));
end if;
Index := Last + 1;
-- In case we had a ASCII.CR/ASCII.LF end of line, skip the
-- remaining symbol
if Index <= Buffer'Last
and then Buffer (Index) = ASCII.LF
then
Index := Index + 1;
end if;
end loop;
-- Now parse the source and object paths
Index := Buffer'First;
while Index <= Buffer'Last loop
-- Find the end of line
Last := Index;
while Last <= Buffer'Last
and then Buffer (Last) /= ASCII.LF
and then Buffer (Last) /= ASCII.CR
loop
Last := Last + 1;
end loop;
if Index <= Buffer'Last - 7
and then Buffer (Index .. Index + 7) = "src_dir="
then
Append (Src_Dir, Normalize_Pathname
(Name => Ada.Strings.Fixed.Trim
(Buffer (Index + 8 .. Last - 1), Ada.Strings.Both),
Directory => Build_Dir.all) & Path_Separator);
elsif Index <= Buffer'Last - 7
and then Buffer (Index .. Index + 7) = "obj_dir="
then
Append (Obj_Dir, Normalize_Pathname
(Name => Ada.Strings.Fixed.Trim
(Buffer (Index + 8 .. Last - 1), Ada.Strings.Both),
Directory => Build_Dir.all) & Path_Separator);
end if;
-- In case we had a ASCII.CR/ASCII.LF end of line, skip the
-- remaining symbol
Index := Last + 1;
if Index <= Buffer'Last
and then Buffer (Index) = ASCII.LF
then
Index := Index + 1;
end if;
end loop;
end;
end if;
Osint.Add_Default_Search_Dirs;
declare
Src : constant String := Parse_Gnatls_Src;
Obj : constant String := Parse_Gnatls_Obj;
begin
Directories := new Project_File'
(Src_Dir_Length => Length (Src_Dir) + Src'Length,
Obj_Dir_Length => Length (Obj_Dir) + Obj'Length,
Src_Dir => To_String (Src_Dir) & Src,
Obj_Dir => To_String (Obj_Dir) & Obj,
Src_Dir_Index => 1,
Obj_Dir_Index => 1,
Last_Obj_Dir_Start => 0);
end;
Free (Build_Dir);
end Create_Project_File;
---------------------
-- Current_Obj_Dir --
---------------------
function Current_Obj_Dir return String is
begin
return Directories.Obj_Dir
(Directories.Last_Obj_Dir_Start .. Directories.Obj_Dir_Index - 2);
end Current_Obj_Dir;
----------------
-- Get_Column --
----------------
function Get_Column (Decl : Declaration_Reference) return String is
begin
return Ada.Strings.Fixed.Trim (Natural'Image (Decl.Decl.Column),
Ada.Strings.Left);
end Get_Column;
function Get_Column (Ref : Reference) return String is
begin
return Ada.Strings.Fixed.Trim (Natural'Image (Ref.Column),
Ada.Strings.Left);
end Get_Column;
---------------------
-- Get_Declaration --
---------------------
function Get_Declaration
(File_Ref : File_Reference;
Line : Natural;
Column : Natural)
return Declaration_Reference
is
Key : aliased constant String := Key_From_Ref (File_Ref, Line, Column);
begin
return Entities_HTable.Get (Key'Unchecked_Access);
end Get_Declaration;
----------------------
-- Get_Emit_Warning --
----------------------
function Get_Emit_Warning (File : File_Reference) return Boolean is
begin
return File.Emit_Warning;
end Get_Emit_Warning;
--------------
-- Get_File --
--------------
function Get_File
(Decl : Declaration_Reference;
With_Dir : Boolean := False) return String
is
begin
return Get_File (Decl.Decl.File, With_Dir);
end Get_File;
function Get_File
(Ref : Reference;
With_Dir : Boolean := False) return String
is
begin
return Get_File (Ref.File, With_Dir);
end Get_File;
function Get_File
(File : File_Reference;
With_Dir : Boolean := False;
Strip : Natural := 0) return String
is
Tmp : GNAT.OS_Lib.String_Access;
function Internal_Strip (Full_Name : String) return String;
-- Internal function to process the Strip parameter
--------------------
-- Internal_Strip --
--------------------
function Internal_Strip (Full_Name : String) return String is
Unit_End : Natural;
Extension_Start : Natural;
S : Natural;
begin
if Strip = 0 then
return Full_Name;
end if;
-- Isolate the file extension
Extension_Start := Full_Name'Last;
while Extension_Start >= Full_Name'First
and then Full_Name (Extension_Start) /= '.'
loop
Extension_Start := Extension_Start - 1;
end loop;
-- Strip the right number of subunit_names
S := Strip;
Unit_End := Extension_Start - 1;
while Unit_End >= Full_Name'First
and then S > 0
loop
if Full_Name (Unit_End) = '-' then
S := S - 1;
end if;
Unit_End := Unit_End - 1;
end loop;
if Unit_End < Full_Name'First then
return "";
else
return Full_Name (Full_Name'First .. Unit_End)
& Full_Name (Extension_Start .. Full_Name'Last);
end if;
end Internal_Strip;
-- Start of processing for Get_File;
begin
-- If we do not want the full path name
if not With_Dir then
return Internal_Strip (File.File.all);
end if;
if File.Dir = null then
if Ada.Strings.Fixed.Tail (File.File.all, 3) =
Osint.ALI_Suffix.all
then
Tmp := Locate_Regular_File
(Internal_Strip (File.File.all), Directories.Obj_Dir);
else
Tmp := Locate_Regular_File
(File.File.all, Directories.Src_Dir);
end if;
if Tmp = null then
File.Dir := new String'("");
else
File.Dir := new String'(Dir_Name (Tmp.all));
Free (Tmp);
end if;
end if;
return Internal_Strip (File.Dir.all & File.File.all);
end Get_File;
------------------
-- Get_File_Ref --
------------------
function Get_File_Ref (Ref : Reference) return File_Reference is
begin
return Ref.File;
end Get_File_Ref;
-----------------------
-- Get_Gnatchop_File --
-----------------------
function Get_Gnatchop_File
(File : File_Reference;
With_Dir : Boolean := False)
return String
is
begin
if File.Gnatchop_File.all = "" then
return Get_File (File, With_Dir);
else
return File.Gnatchop_File.all;
end if;
end Get_Gnatchop_File;
function Get_Gnatchop_File
(Ref : Reference;
With_Dir : Boolean := False)
return String
is
begin
return Get_Gnatchop_File (Ref.File, With_Dir);
end Get_Gnatchop_File;
function Get_Gnatchop_File
(Decl : Declaration_Reference;
With_Dir : Boolean := False)
return String
is
begin
return Get_Gnatchop_File (Decl.Decl.File, With_Dir);
end Get_Gnatchop_File;
--------------
-- Get_Line --
--------------
function Get_Line (Decl : Declaration_Reference) return String is
begin
return Ada.Strings.Fixed.Trim (Natural'Image (Decl.Decl.Line),
Ada.Strings.Left);
end Get_Line;
function Get_Line (Ref : Reference) return String is
begin
return Ada.Strings.Fixed.Trim (Natural'Image (Ref.Line),
Ada.Strings.Left);
end Get_Line;
----------------
-- Get_Parent --
----------------
function Get_Parent
(Decl : Declaration_Reference)
return Declaration_Reference
is
begin
return Decl.Par_Symbol;
end Get_Parent;
---------------------
-- Get_Source_Line --
---------------------
function Get_Source_Line (Ref : Reference) return String is
begin
if Ref.Source_Line /= null then
return Ref.Source_Line.all;
else
return "";
end if;
end Get_Source_Line;
function Get_Source_Line (Decl : Declaration_Reference) return String is
begin
if Decl.Decl.Source_Line /= null then
return Decl.Decl.Source_Line.all;
else
return "";
end if;
end Get_Source_Line;
----------------
-- Get_Symbol --
----------------
function Get_Symbol (Decl : Declaration_Reference) return String is
begin
return Decl.Symbol;
end Get_Symbol;
--------------
-- Get_Type --
--------------
function Get_Type (Decl : Declaration_Reference) return Character is
begin
return Decl.Decl_Type;
end Get_Type;
----------
-- Sort --
----------
procedure Sort (Arr : in out Reference_Array) is
Tmp : Reference;
function Lt (Op1, Op2 : Natural) return Boolean;
procedure Move (From, To : Natural);
-- See GNAT.Heap_Sort_G
--------
-- Lt --
--------
function Lt (Op1, Op2 : Natural) return Boolean is
begin
if Op1 = 0 then
return Is_Less_Than (Tmp, Arr (Op2));
elsif Op2 = 0 then
return Is_Less_Than (Arr (Op1), Tmp);
else
return Is_Less_Than (Arr (Op1), Arr (Op2));
end if;
end Lt;
----------
-- Move --
----------
procedure Move (From, To : Natural) is
begin
if To = 0 then
Tmp := Arr (From);
elsif From = 0 then
Arr (To) := Tmp;
else
Arr (To) := Arr (From);
end if;
end Move;
package Ref_Sort is new GNAT.Heap_Sort_G (Move, Lt);
-- Start of processing for Sort
begin
Ref_Sort.Sort (Arr'Last);
end Sort;
-----------------------
-- Grep_Source_Files --
-----------------------
procedure Grep_Source_Files is
Length : Natural := 0;
Decl : Declaration_Reference := Entities_HTable.Get_First;
Arr : Reference_Array_Access;
Index : Natural;
End_Index : Natural;
Current_File : File_Reference;
Current_Line : Cst_String_Access;
Buffer : GNAT.OS_Lib.String_Access;
Ref : Reference;
Line : Natural;
begin
-- Create a temporary array, where all references will be
-- sorted by files. This way, we only have to read the source
-- files once.
while Decl /= null loop
-- Add 1 for the declaration itself
Length := Length + References_Count (Decl, True, True, True) + 1;
Decl := Entities_HTable.Get_Next;
end loop;
Arr := new Reference_Array (1 .. Length);
Index := Arr'First;
Decl := Entities_HTable.Get_First;
while Decl /= null loop
Store_References (Decl, True, True, True, True, Arr.all, Index);
Decl := Entities_HTable.Get_Next;
end loop;
Sort (Arr.all);
-- Now traverse the whole array and find the appropriate source
-- lines.
for R in Arr'Range loop
Ref := Arr (R);
if Ref.File /= Current_File then
Free (Buffer);
begin
Read_File (Get_File (Ref.File, With_Dir => True), Buffer);
End_Index := Buffer'First - 1;
Line := 0;
exception
when Ada.Text_IO.Name_Error | Ada.Text_IO.End_Error =>
Line := Natural'Last;
end;
Current_File := Ref.File;
end if;
if Ref.Line > Line then
-- Do not free Current_Line, it is referenced by the last
-- Ref we processed.
loop
Index := End_Index + 1;
loop
End_Index := End_Index + 1;
exit when End_Index > Buffer'Last
or else Buffer (End_Index) = ASCII.LF;
end loop;
-- Skip spaces at beginning of line
while Index < End_Index and then
(Buffer (Index) = ' ' or else Buffer (Index) = ASCII.HT)
loop
Index := Index + 1;
end loop;
Line := Line + 1;
exit when Ref.Line = Line;
end loop;
Current_Line := new String'(Buffer (Index .. End_Index - 1));
end if;
Ref.Source_Line := Current_Line;
end loop;
Free (Buffer);
Free (Arr);
end Grep_Source_Files;
---------------
-- Read_File --
---------------
procedure Read_File
(File_Name : String;
Contents : out GNAT.OS_Lib.String_Access)
is
Name_0 : constant String := File_Name & ASCII.NUL;
FD : constant File_Descriptor := Open_Read (Name_0'Address, Binary);
Length : Natural;
begin
if FD = Invalid_FD then
raise Ada.Text_IO.Name_Error;
end if;
-- Include room for EOF char
Length := Natural (File_Length (FD));
declare
Buffer : String (1 .. Length + 1);
This_Read : Integer;
Read_Ptr : Natural := 1;
begin
loop
This_Read := Read (FD,
A => Buffer (Read_Ptr)'Address,
N => Length + 1 - Read_Ptr);
Read_Ptr := Read_Ptr + Integer'Max (This_Read, 0);
exit when This_Read <= 0;
end loop;
Buffer (Read_Ptr) := EOF;
Contents := new String'(Buffer (1 .. Read_Ptr));
if Read_Ptr /= Length + 1 then
raise Ada.Text_IO.End_Error;
end if;
Close (FD);
end;
end Read_File;
-----------------------
-- Longest_File_Name --
-----------------------
function Longest_File_Name return Natural is
begin
return Longest_File_Name_In_Table;
end Longest_File_Name;
-----------
-- Match --
-----------
function Match
(File : File_Reference;
Line : Natural;
Column : Natural)
return Boolean
is
Ref : Ref_In_File_Ptr := File.Lines;
begin
while Ref /= null loop
if (Ref.Line = 0 or else Ref.Line = Line)
and then (Ref.Column = 0 or else Ref.Column = Column)
then
return True;
end if;
Ref := Ref.Next;
end loop;
return False;
end Match;
-----------
-- Match --
-----------
function Match (Decl : Declaration_Reference) return Boolean is
begin
return Decl.Match;
end Match;
----------
-- Next --
----------
function Next (E : File_Reference) return File_Reference is
begin
return E.Next;
end Next;
function Next (E : Declaration_Reference) return Declaration_Reference is
begin
return E.Next;
end Next;
------------------
-- Next_Obj_Dir --
------------------
function Next_Obj_Dir return String is
First : constant Integer := Directories.Obj_Dir_Index;
Last : Integer;
begin
Last := Directories.Obj_Dir_Index;
if Last > Directories.Obj_Dir_Length then
return String'(1 .. 0 => ' ');
end if;
while Directories.Obj_Dir (Last) /= Path_Separator loop
Last := Last + 1;
end loop;
Directories.Obj_Dir_Index := Last + 1;
Directories.Last_Obj_Dir_Start := First;
return Directories.Obj_Dir (First .. Last - 1);
end Next_Obj_Dir;
-------------------------
-- Next_Unvisited_File --
-------------------------
function Next_Unvisited_File return File_Reference is
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(Unvisited_Files_Record, Unvisited_Files_Access);
Ref : File_Reference;
Tmp : Unvisited_Files_Access;
begin
if Unvisited_Files = null then
return Empty_File;
else
Tmp := Unvisited_Files;
Ref := Unvisited_Files.File;
Unvisited_Files := Unvisited_Files.Next;
Unchecked_Free (Tmp);
return Ref;
end if;
end Next_Unvisited_File;
----------------------
-- Parse_Gnatls_Src --
----------------------
function Parse_Gnatls_Src return String is
Length : Natural;
begin
Length := 0;
for J in 1 .. Osint.Nb_Dir_In_Src_Search_Path loop
if Osint.Dir_In_Src_Search_Path (J)'Length = 0 then
Length := Length + 2;
else
Length := Length + Osint.Dir_In_Src_Search_Path (J)'Length + 1;
end if;
end loop;
declare
Result : String (1 .. Length);
L : Natural;
begin
L := Result'First;
for J in 1 .. Osint.Nb_Dir_In_Src_Search_Path loop
if Osint.Dir_In_Src_Search_Path (J)'Length = 0 then
Result (L .. L + 1) := "." & Path_Separator;
L := L + 2;
else
Result (L .. L + Osint.Dir_In_Src_Search_Path (J)'Length - 1) :=
Osint.Dir_In_Src_Search_Path (J).all;
L := L + Osint.Dir_In_Src_Search_Path (J)'Length;
Result (L) := Path_Separator;
L := L + 1;
end if;
end loop;
return Result;
end;
end Parse_Gnatls_Src;
----------------------
-- Parse_Gnatls_Obj --
----------------------
function Parse_Gnatls_Obj return String is
Length : Natural;
begin
Length := 0;
for J in 1 .. Osint.Nb_Dir_In_Obj_Search_Path loop
if Osint.Dir_In_Obj_Search_Path (J)'Length = 0 then
Length := Length + 2;
else
Length := Length + Osint.Dir_In_Obj_Search_Path (J)'Length + 1;
end if;
end loop;
declare
Result : String (1 .. Length);
L : Natural;
begin
L := Result'First;
for J in 1 .. Osint.Nb_Dir_In_Obj_Search_Path loop
if Osint.Dir_In_Obj_Search_Path (J)'Length = 0 then
Result (L .. L + 1) := "." & Path_Separator;
L := L + 2;
else
Result (L .. L + Osint.Dir_In_Obj_Search_Path (J)'Length - 1) :=
Osint.Dir_In_Obj_Search_Path (J).all;
L := L + Osint.Dir_In_Obj_Search_Path (J)'Length;
Result (L) := Path_Separator;
L := L + 1;
end if;
end loop;
return Result;
end;
end Parse_Gnatls_Obj;
-------------------
-- Reset_Obj_Dir --
-------------------
procedure Reset_Obj_Dir is
begin
Directories.Obj_Dir_Index := 1;
end Reset_Obj_Dir;
-----------------------
-- Set_Default_Match --
-----------------------
procedure Set_Default_Match (Value : Boolean) is
begin
Default_Match := Value;
end Set_Default_Match;
----------
-- Free --
----------
procedure Free (Str : in out Cst_String_Access) is
function Convert is new Ada.Unchecked_Conversion
(Cst_String_Access, GNAT.OS_Lib.String_Access);
S : GNAT.OS_Lib.String_Access := Convert (Str);
begin
Free (S);
Str := null;
end Free;
---------------------
-- Reset_Directory --
---------------------
procedure Reset_Directory (File : File_Reference) is
begin
Free (File.Dir);
end Reset_Directory;
-------------------
-- Set_Unvisited --
-------------------
procedure Set_Unvisited (File_Ref : File_Reference) is
F : constant String := Get_File (File_Ref, With_Dir => False);
begin
File_Ref.Visited := False;
-- ??? Do not add a source file to the list. This is true at
-- least for gnatxref, and probably for gnatfind as well
if F'Length > 4
and then F (F'Last - 3 .. F'Last) = "." & Osint.ALI_Suffix.all
then
Unvisited_Files := new Unvisited_Files_Record'
(File => File_Ref,
Next => Unvisited_Files);
end if;
end Set_Unvisited;
----------------------
-- Get_Declarations --
----------------------
function Get_Declarations
(Sorted : Boolean := True)
return Declaration_Array_Access
is
Arr : constant Declaration_Array_Access :=
new Declaration_Array (1 .. Entities_Count);
Decl : Declaration_Reference := Entities_HTable.Get_First;
Index : Natural := Arr'First;
Tmp : Declaration_Reference;
procedure Move (From : Natural; To : Natural);
function Lt (Op1, Op2 : Natural) return Boolean;
-- See GNAT.Heap_Sort_G
--------
-- Lt --
--------
function Lt (Op1, Op2 : Natural) return Boolean is
begin
if Op1 = 0 then
return Is_Less_Than (Tmp, Arr (Op2));
elsif Op2 = 0 then
return Is_Less_Than (Arr (Op1), Tmp);
else
return Is_Less_Than (Arr (Op1), Arr (Op2));
end if;
end Lt;
----------
-- Move --
----------
procedure Move (From : Natural; To : Natural) is
begin
if To = 0 then
Tmp := Arr (From);
elsif From = 0 then
Arr (To) := Tmp;
else
Arr (To) := Arr (From);
end if;
end Move;
package Decl_Sort is new GNAT.Heap_Sort_G (Move, Lt);
-- Start of processing for Get_Declarations
begin
while Decl /= null loop
Arr (Index) := Decl;
Index := Index + 1;
Decl := Entities_HTable.Get_Next;
end loop;
if Sorted and then Arr'Length /= 0 then
Decl_Sort.Sort (Entities_Count);
end if;
return Arr;
end Get_Declarations;
----------------------
-- References_Count --
----------------------
function References_Count
(Decl : Declaration_Reference;
Get_Reads : Boolean := False;
Get_Writes : Boolean := False;
Get_Bodies : Boolean := False)
return Natural
is
function List_Length (E : Reference) return Natural;
-- Return the number of references in E
-----------------
-- List_Length --
-----------------
function List_Length (E : Reference) return Natural is
L : Natural := 0;
E1 : Reference := E;
begin
while E1 /= null loop
L := L + 1;
E1 := E1.Next;
end loop;
return L;
end List_Length;
Length : Natural := 0;
-- Start of processing for References_Count
begin
if Get_Reads then
Length := List_Length (Decl.Ref_Ref);
end if;
if Get_Writes then
Length := Length + List_Length (Decl.Modif_Ref);
end if;
if Get_Bodies then
Length := Length + List_Length (Decl.Body_Ref);
end if;
return Length;
end References_Count;
----------------------
-- Store_References --
----------------------
procedure Store_References
(Decl : Declaration_Reference;
Get_Writes : Boolean := False;
Get_Reads : Boolean := False;
Get_Bodies : Boolean := False;
Get_Declaration : Boolean := False;
Arr : in out Reference_Array;
Index : in out Natural)
is
procedure Add (List : Reference);
-- Add all the references in List to Arr
---------
-- Add --
---------
procedure Add (List : Reference) is
E : Reference := List;
begin
while E /= null loop
Arr (Index) := E;
Index := Index + 1;
E := E.Next;
end loop;
end Add;
-- Start of processing for Store_References
begin
if Get_Declaration then
Add (Decl.Decl);
end if;
if Get_Reads then
Add (Decl.Ref_Ref);
end if;
if Get_Writes then
Add (Decl.Modif_Ref);
end if;
if Get_Bodies then
Add (Decl.Body_Ref);
end if;
end Store_References;
--------------------
-- Get_References --
--------------------
function Get_References
(Decl : Declaration_Reference;
Get_Reads : Boolean := False;
Get_Writes : Boolean := False;
Get_Bodies : Boolean := False)
return Reference_Array_Access
is
Length : constant Natural :=
References_Count (Decl, Get_Reads, Get_Writes, Get_Bodies);
Arr : constant Reference_Array_Access :=
new Reference_Array (1 .. Length);
Index : Natural := Arr'First;
begin
Store_References
(Decl => Decl,
Get_Writes => Get_Writes,
Get_Reads => Get_Reads,
Get_Bodies => Get_Bodies,
Get_Declaration => False,
Arr => Arr.all,
Index => Index);
if Arr'Length /= 0 then
Sort (Arr.all);
end if;
return Arr;
end Get_References;
----------
-- Free --
----------
procedure Free (Arr : in out Reference_Array_Access) is
procedure Internal is new Ada.Unchecked_Deallocation
(Reference_Array, Reference_Array_Access);
begin
Internal (Arr);
end Free;
------------------
-- Is_Parameter --
------------------
function Is_Parameter (Decl : Declaration_Reference) return Boolean is
begin
return Decl.Is_Parameter;
end Is_Parameter;
end Xr_Tabls;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2020 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- Based on Jonathan Dupuy's C++ LEB demo [1]. GLSL shaders of LEB library
-- and shaders for rendering of terrain are licensed under the MIT license.
--
-- Contributions:
--
-- * Initialize LEB buffers in a compute shader instead of on the CPU
--
-- * Avoid C implementation of LEB library and reuse the LEB GLSL code
-- to create a static meshlet on the GPU when rendering the terrain
--
-- * Update and render multiple terrain tiles. Use heuristics to
-- determine on the CPU which tiles need to be updated and rendered.
--
-- * Support flattened spheroids with warping to reduce RMSE when
-- projecting cubes on spheres.
--
-- [1] https://github.com/jdupuy/LongestEdgeBisectionDemos
with GL.Objects.Textures;
with GL.Types;
with Orka.Cameras;
with Orka.Rendering.Buffers;
with Orka.Rendering.Programs.Modules;
with Orka.Resources.Locations;
with Orka.Timers;
private with GL.Low_Level.Enums;
private with GL.Objects.Samplers;
private with Orka.Rendering.Programs.Uniforms;
private with Orka.Types;
package Orka.Features.Terrain is
pragma Preelaborate;
type Subdivision_Depth is range 0 .. 29;
type Meshlet_Subdivision_Depth is range 0 .. 3;
type Length_Target is range 2 .. 32;
type LoD_Deviation is digits 4 range 0.0 .. 1.0;
type Height_Scale is digits 4 range 0.0 .. 1.0;
type Subdivision_Parameters is record
Meshlet_Subdivision : Meshlet_Subdivision_Depth;
Edge_Length_Target : Length_Target;
Min_LoD_Standard_Dev : LoD_Deviation;
end record;
subtype Spheroid_Parameters is GL.Types.Single_Array (1 .. 4);
type Visible_Tile_Array is array (Positive range <>) of Boolean;
-----------------------------------------------------------------------------
type Terrain (Count : Positive) is tagged limited private;
function Create_Terrain
(Count : Positive;
Min_Depth, Max_Depth : Subdivision_Depth;
Scale : Height_Scale;
Wireframe : Boolean;
Location : Resources.Locations.Location_Ptr;
Render_Modules : Rendering.Programs.Modules.Module_Array;
Initialize_Render : access procedure
(Program : Rendering.Programs.Program)) return Terrain
with Pre => Min_Depth <= Max_Depth and Max_Depth >= 5;
-- Create and return a Terrain object that can generate
-- one or more terrain tiles
--
-- If Wireframe is True, then optionally a wireframe can be displayed
-- when rendering the terrain. In production, this parameter should
-- be set to False to avoid invoking a geometry shader.
--
-- One of the shaders in the module array must contain the following
-- function:
--
-- vec4 ShadeFragment(vec2 texCoord, vec4 worldPos);
procedure Render
(Object : in out Terrain;
Transforms, Spheres : Rendering.Buffers.Bindable_Buffer'Class;
Center : Cameras.Transforms.Matrix4;
Camera : Cameras.Camera_Ptr;
Parameters : Subdivision_Parameters;
Visible_Tiles : Visible_Tile_Array;
Update_Render : access procedure (Program : Rendering.Programs.Program);
Height_Map : GL.Objects.Textures.Texture;
Freeze, Wires : Boolean;
Timer_Update, Timer_Render : in out Orka.Timers.Timer)
with Pre => Transforms.Length = Object.Count
and Spheres.Length in Spheroid_Parameters'Length | Spheroid_Parameters'Length * Object.Count
and Visible_Tiles'Length = Object.Count;
-- Generate and render the terrain tiles
--
-- Buffer Transforms should contain matrices which transform the
-- terrain tiles.
--
-- Buffer Spheres should contain n spheroid parameters (each containing
-- 4 singles) for n terrain tiles if the sphere is flattened or 1 spheroid
-- parameters if all the tiles are part of a non-flattened sphere.
--
-- Center should contain a translation from the camera to the center
-- of the sphere. It should be scaled if the semi-major axis in the
-- spheroid parameters in Spheres is scaled.
--
-- If Freeze is True, then the generated terrain will not be
-- modified.
--
-- If Wires is True and if parameter Wireframe of function Create_Terrain
-- was True, then a wireframe will be displayed. If Wireframe was False,
-- then Wires has no effect.
function Get_Spheroid_Parameters
(Semi_Major_Axis : GL.Types.Single;
Flattening : GL.Types.Single := 0.0;
Side : Boolean := True) return Spheroid_Parameters;
-- Return the spheroid parameters needed to project a flat
-- terrain tile on a (non-)flattened sphere.
--
-- The returned spheroid parameters should be put in a buffer that
-- is given to the procedure Render above.
--
-- If the terrain tiles are part of a non-flattened sphere, then
-- this function can be called once with Flattening = 0.0.
--
-- If the sphere is flattened, this function needs to be called twice.
-- The returned spheroid parameters must be repeated 4 times for the
-- tiles on the side and 2 times for the top and bottom tiles.
--
-- If the semi-major axis is scaled, then the translation in Center
-- in the procedure Render should be scaled as well.
private
package LE renames GL.Low_Level.Enums;
type UInt_Buffer_Array is array (Positive range <>) of
Rendering.Buffers.Buffer (Types.UInt_Type);
type Terrain (Count : Positive) is tagged limited record
Max_Depth : Subdivision_Depth;
Scale : Height_Scale;
Split_Update : Boolean;
Wireframe : Boolean;
-- Update and reduction of LEB
Program_Leb_Update : Rendering.Programs.Program;
Program_Leb_Prepass : Rendering.Programs.Program;
Program_Leb_Reduction : Rendering.Programs.Program;
-- Prepare indirect commands and render geometry
Program_Indirect : Rendering.Programs.Program;
Program_Render : Rendering.Programs.Program;
Uniform_Update_Split : Rendering.Programs.Uniforms.Uniform (LE.Bool_Type);
Uniform_Update_Freeze : Rendering.Programs.Uniforms.Uniform (LE.Bool_Type);
Uniform_Update_LoD_Var : Rendering.Programs.Uniforms.Uniform (LE.Single_Type);
Uniform_Update_LoD_Factor : Rendering.Programs.Uniforms.Uniform (LE.Single_Type);
Uniform_Update_DMap_Factor : Rendering.Programs.Uniforms.Uniform (LE.Single_Type);
Uniform_Render_DMap_Factor : Rendering.Programs.Uniforms.Uniform (LE.Single_Type);
Uniform_Update_Leb_ID : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Indirect_Leb_ID : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Render_Leb_ID : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Prepass_Pass_ID : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Reduction_Pass_ID : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Indirect_Subdiv : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
Uniform_Render_Subdiv : Rendering.Programs.Uniforms.Uniform (LE.Int_Type);
-- Sampler for height and slope maps
Sampler : GL.Objects.Samplers.Sampler;
-- SSBO
Buffer_Draw : Rendering.Buffers.Buffer (Types.Arrays_Command_Type);
Buffer_Dispatch : Rendering.Buffers.Buffer (Types.Dispatch_Command_Type);
Buffer_Leb : UInt_Buffer_Array (1 .. Count);
Buffer_Leb_Nodes : UInt_Buffer_Array (1 .. Count);
Buffer_Leb_Node_Counter : Rendering.Buffers.Buffer (Types.UInt_Type);
-- UBO
Buffer_Matrices : Rendering.Buffers.Buffer (Types.Single_Matrix_Type);
end record;
end Orka.Features.Terrain;
|
private with Ada.Containers.Doubly_Linked_Lists;
generic
type State is (<>); -- State'First is starting state
type Symbol is (<>); -- Symbol'First is blank
package Turing is
Start: constant State := State'First;
Halt: constant State := State'Last;
subtype Action_State is State range Start .. State'Pred(Halt);
Blank: constant Symbol := Symbol'First;
type Movement is (Left, Stay, Right);
type Action is record
New_State: State;
Move_To: Movement;
New_Symbol: Symbol;
end record;
type Rules_Type is array(Action_State, Symbol) of Action;
type Tape_Type is limited private;
type Symbol_Map is array(Symbol) of Character;
function To_String(Tape: Tape_Type; Map: Symbol_Map) return String;
function Position_To_String(Tape: Tape_Type; Marker: Character := '^')
return String;
function To_Tape(Str: String; Map: Symbol_Map) return Tape_Type;
procedure Single_Step(Current: in out State;
Tape: in out Tape_Type;
Rules: Rules_Type);
procedure Run(The_Tape: in out Tape_Type;
Rules: Rules_Type;
Max_Steps: Natural := Natural'Last;
Print: access procedure(Tape: Tape_Type; Current: State));
-- runs from Start State until either Halt or # Steps exceeds Max_Steps
-- if # of steps exceeds Max_Steps, Constrained_Error is raised;
-- if Print is not null, Print is called at the beginning of each step
private
package Symbol_Lists is new Ada.Containers.Doubly_Linked_Lists(Symbol);
subtype List is Symbol_Lists.List;
type Tape_Type is record
Left: List;
Here: Symbol;
Right: List;
end record;
end Turing;
|
package Geometry is
type Point is record
x : Float;
y : Float;
z : Float;
end record;
type Angle is new Float range -360.0 .. 360.0;
type Axes is record
yaw : Angle;
pitch : Angle;
roll : Angle;
end record;
type Shape is tagged record
position : Point;
rotation : Axes;
end record;
type Rectangle is new Shape with record
width : Float;
length : Float;
height : Float;
end record;
function volume(s : Rectangle) return Float;
function surface_area(s : Rectangle) return Float;
type Circle is new Shape with record
radius : Float;
end record;
function surface_area(s : Circle) return Float;
function circumference(s : Circle) return Float;
type Ellipse is new Shape with record
a : Float;
b : Float;
end record;
function surface_area(s : Ellipse) return Float;
function circumference(s : Ellipse) return Float;
type Cylinder is new Shape with record
radius : Float;
height : Float;
end record;
function volume(s : Cylinder) return Float;
function surface_area(s : Cylinder) return Float;
type Sphere is new Shape with record
radius : Float;
end record;
function volume(s : Sphere) return Float;
function surface_area(s : Sphere) return Float;
function distance(point1, point2 : Point) return Float;
function midpoint(point1, point2 : Point) return Point;
end Geometry;
|
--caso de prueba 3: records, loop normal
--sacado de: http://www.dwheeler.com/lovelace/s6s6.htm
procedure Main is
--declaramos el record:
type Date is
record
Day : Integer range 1 .. 31;
Month : Integer range 1 .. 12;
Year : Integer range 1 .. 4000 := 1995;
end record;
--declaramos otra variable:
Prompt: Integer := 0;
--ahora, otro record
type Complex is
record
Real_Part, Imaginary_Part : Float := 0.0;
end record;
--ahora un procedure
procedure Demo_Date is
Ada_Birthday : Date;
begin
Ada_Birthday.Month := 12;
Ada_Birthday.Day := 10;
Ada_Birthday.Year := 1815;
end Demo_Date;
--ahora, otras variables:
ComplexPrompt: Complex;
rPrompt: Float:=0.0;
iPrompt: Float:=0.0;
--otra función:
function getPrompt(r,i:Float) return Complex is
retVal: Complex;
begin
retVal.Real_part:= get("escriba algún número...");
iPrompt.Imaginary_Part:= get("escriba algún otro número");
return retVal;
end;
begin --Main
loop
ComplexPrompt:= getPrompt(rPrompt, iPrompt);
put(getPrompt);
exit when ComplexPrompt.Real_Part>=0 and then ComplexPrompt.Imaginary_Part /= -1;
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- JSON Parser/Constructor --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2020-2021, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Richard Wai (ANNEXI-STRAYLINE) --
-- * Ensi Martini (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 is the unbounded codec
with Ada.Iterator_Interfaces;
private with Interfaces;
private with Ada.Finalization;
private with System.Storage_Pools.Subpools;
private with JSON.Fast_Slab_Allocators;
private with JSON.Parser_Machine;
package JSON.Unbounded_Codecs is
----------------
-- JSON_Value --
----------------
-- JSON_Values represent active members of an object, or elements of an
-- array, within a Codec
type JSON_Value(<>) is tagged limited private;
function Kind (Value: JSON_Value) return JSON_Value_Kind;
function Parent_Kind (Value: JSON_Value) return JSON_Structure_Kind;
-- Returns the structure kind of the Parent structure of Value
-- (JSON_Object or JSON_Array).
--
-- Invoking Parent_Kind on the Root object raises Contraint_Error
function Name (Value: JSON_Value) return JSON_String_Value with
Pre'Class => Value.Parent_Kind = JSON_Object;
function UTF8_Name (Value: JSON_Value) return UTF_8_String with
Pre'Class => Value.Parent_Kind = JSON_Object;
-- Returns the name of Value, if it is an Object Member.
-- Constraint_Error is raised if Value is not an Object Member.
function Index (Value: JSON_Value) return Natural;
-- Returns a zero-based index of Value in its structure. This value can be
-- produced for Object Members or Array Elements, but this Index can only
-- be used to index JSON_Array JSON_Structures. In both cases, Index is
-- in the order of deserialization or appendage of the value.
function Value (Value: JSON_Value) return Boolean;
function Value (Value: JSON_Value) return JSON_Integer_Value;
function Value (Value: JSON_Value) return JSON_Float_Value;
function Value (Value: JSON_Value) return JSON_String_Value;
function UTF8_Value (Value: JSON_Value) return UTF_8_String;
-- If the Kind of Value is incompatible with the expected return type,
-- a Discriminent_Check will fail at runtime
-- Note that for structural Kinds (JSON_Object and JSON_Array), the
-- corresponding JSON_Value can be used as an index value for the
-- Unbounded_JSON_Codec
-- Value editing operations --
procedure Value (Target: in out JSON_Value;
Value : in Boolean;
Mutate: in Boolean := False)
with Pre'Class =>
(if not Mutate then Target.Kind in JSON_Boolean | JSON_Null);
procedure Value (Target: in out JSON_Value;
Value : in JSON_Integer_Value;
Mutate: in Boolean := False)
with Pre'Class =>
(if not Mutate then Target.Kind in JSON_Integer | JSON_Null);
procedure Value (Target: in out JSON_Value;
Value : in JSON_Float_Value;
Mutate: in Boolean := False)
with Pre'Class =>
(if not Mutate then Target.Kind in JSON_Float | JSON_Null);
procedure Value (Target: in out JSON_Value;
Value : in JSON_String_Value;
Mutate: in Boolean := False)
with Pre'Class =>
(if not Mutate then Target.Kind in JSON_String | JSON_Null);
-- Sets the value of Target. If Mutate is False, Constraint_Error is
-- raised if the Kind of Target does not fit the type of Value.
--
-- Otherwise, is Mutuate is True, the Target is mutated into the
-- Kind associated with the type of Value.
--
-- Null values can always be set to any type, regardless of the
-- value of Mutate.
--
-- Note: Mutating a JSON_String value to a non-string value
-- of any kind causes the dynamically allocated value to be lost,
-- and the underlying storage is not reclaimed until the codec is
-- finalized.
--
-- It is certainly pathelogical to be mutating any Values frequently
-- or many times, but in the case of JSON_String values specifically,
-- this could appear to cause a memory leak until the Codec is
-- finalized. This behaviour is a result of the performance and low
-- memory fragmentation design, and the sane assumption that these
-- sorts of mutations will not happen more than once per JSON_String
-- value.
procedure Nullify (Target: in out JSON_Value);
-- Sets Target to a 'null' value.
type JSON_Value_Reference (Ref: not null access JSON_Value) is
null record with Implicit_Dereference => Ref;
type JSON_Value_Constant_Reference
(Ref: not null access constant JSON_Value) is
null record with Implicit_Dereference => Ref;
--------------------
-- JSON_Structure --
--------------------
type JSON_Structure is tagged limited private with
Constant_Indexing => Constant_Reference,
Iterator_Element => JSON_Value,
Default_Iterator => Iterate;
-- Represents the root of a JSON_Object or JSON_Array, and is referenced via
-- a corresponding JSON_Object or JSON_Array JSON_Value
function Kind (Structure: JSON_Structure) return JSON_Structure_Kind;
function Length (Structure: JSON_Structure) return Natural;
-- Returns the number of Elements or Members that are direct children of
-- Structure
-- Array indexing --
subtype JSON_Array_Index is Natural;
-- Using the Javascript convention for zero-based indexing
function Constant_Reference (Structure: JSON_Structure;
Index : JSON_Array_Index)
return JSON_Value_Constant_Reference with
Pre'Class => Structure.Kind = JSON_Array and Index < Structure.Length;
-- Index is a Javascript-style, zero-based array index. Note that,
-- internally, the Codec represents the entire JSON object as a tree, and
-- therefore Arrays are internally linked-lists. In order to provide the
-- expected runtime qualities, the first access of a JSON_Array object via
-- this index-based (Constant_)Reference operation causes the array to be
-- "vectorized". Vectorization is done "lazily" since it encurs a
-- potentially high memory cost.
--
-- If the Index is out of range (> Length), Contraint_Error is raised.
-- Object indexing --
function Has_Member (Structure: JSON_Structure; Name: JSON_String_Value)
return Boolean with
Pre'Class => Structure.Kind = JSON_Object;
-- Returns True iff Structure contains a member named Name.
-- A Discrimint_Check fails if Structure is not a JSON_Object.
function Constant_Reference (Structure: JSON_Structure;
Name : JSON_String_Value)
return JSON_Value_Constant_Reference with
Pre'Class => Structure.Has_Member (Name);
-- Name must be a direct name for a member in the the first level
-- of Structure (which must also be an object). Paths cannot be used on
-- JSON_Structure objects. For path indexing, use the Unbounded_JSON_Codec
-- Lookup indexing operations
--
-- If Has_Member (Name) = False, Constraint_Error is raised.
-- Structure Iteration --
type JSON_Structure_Cursor is limited private;
function Has_Value (Position: JSON_Structure_Cursor) return Boolean;
function Constant_Reference (Structure: JSON_Structure;
Position : JSON_Structure_Cursor)
return JSON_Value_Constant_Reference with
Pre'Class => Has_Value (Position);
-- Constraint_Error is raised if Position is not a valid cursor, either
-- because it is null, or because it belongs to a different codec.
package JSON_Structure_Iterators is new Ada.Iterator_Interfaces
(Cursor => JSON_Structure_Cursor,
Has_Element => Has_Value);
function Iterate (Structure: JSON_Structure) return
JSON_Structure_Iterators.Reversible_Iterator'Class;
----------------------------
-- JSON_Mutable_Structure --
----------------------------
type JSON_Mutable_Structure is new JSON_Structure with private with
Variable_Indexing => Reference;
-- JSON_Mutable_Structures are obtained via the Unbounded_JSON_Codec Delve
-- operation, and can be used to obtain variable references for all values
-- within the underlying structure value.
not overriding
function Reference (Structure: in out JSON_Mutable_Structure;
Index : in JSON_Array_Index)
return JSON_Value_Reference with
Pre'Class => Structure.Kind = JSON_Array and Index < Structure.Length;
not overriding
function Reference (Structure: in out JSON_Mutable_Structure;
Name : in JSON_String_Value)
return JSON_Value_Reference with
Pre'Class => Structure.Has_Member (Name);
not overriding
function Reference (Structure: in out JSON_Mutable_Structure;
Position : in JSON_Structure_Cursor)
return JSON_Value_Reference with
Pre'Class => Has_Value (Position);
-- Structure Building --
not overriding
function Append_Null_Member (Structure: in out JSON_Mutable_Structure;
Name : in JSON_String_Value)
return JSON_Value_Reference
with Pre'Class => Structure.Kind = JSON_Object and Name'Length > 0,
Post'Class => Append_Null_Member'Result.Ref.Kind = JSON_Null;
not overriding
function Append_Null_Element (Structure: in out JSON_Mutable_Structure)
return JSON_Value_Reference
with
Pre'Class => Structure.Kind = JSON_Array,
Post'Class => Append_Null_Element'Result.Ref.Kind = JSON_Null;
-- Appends a new null value member or element to the structure, and returns
-- a reference to the new value. The new value can then be mutated normally
not overriding
function Append_Structural_Member
(Structure: in out JSON_Mutable_Structure;
Name : in JSON_String_Value;
Kind : in JSON_Structure_Kind)
return JSON_Value_Reference
with Pre'Class => Structure.Kind = JSON_Object;
not overriding
function Append_Structural_Element
(Structure: in out JSON_Mutable_Structure;
Kind : in JSON_Structure_Kind)
return JSON_Value_Reference
with Pre'Class => Structure.Kind = JSON_Array;
-- Appends a new structure of Kind to Strucure, and returns a reference.
-- The returned reference can be used to obtain a JSON_(Mutable_)Structure
-- from the Codec.
--------------------------
-- Unbounded_JSON_Codec --
--------------------------
type Unbounded_JSON_Codec(<>) is tagged limited private with
Variable_Indexing => Lookup,
Constant_Indexing => Constant_Lookup;
-- Note that the indexing aspects of the codec are intended to facilitate
-- direct path-based lookup. Iteration over the entire Tree can easily be
-- acheived by iterating over the value of Root
-- Tree-wide lookup --
function Path_Exists (Codec: Unbounded_JSON_Codec;
Path : in JSON_String_Value)
return Boolean;
function Lookup (Codec: aliased in out Unbounded_JSON_Codec;
Path : in JSON_String_Value)
return JSON_Value_Reference
with Pre'Class => Codec.Path_Exists (Path);
function Constant_Lookup (Codec: aliased Unbounded_JSON_Codec;
Path : JSON_String_Value)
return JSON_Value_Constant_Reference
with Pre'Class => Codec.Path_Exists (Path);
-- Path is a dot-notation, javascript-style path to a member within some
-- hierarchy of JSON Objects in the Codec. Note that it is the
-- responsibility of the user to ensure name uniqueness, and to avoid using
-- '.' in names of members. Doing so may potentially cause unexpected
-- double-registration errors when deserializing or encoding.
--
-- If Path is not valid (no value exists), a Constraint_Error will be raised
-- due to the null exclusion of the returned reference type.
--
-- Paths CAN include array indexing ("[x]"). These follow javascript
-- conventions (zero-based indexing)
--
-- A hash table is used to accelerate path indexing, making this approach
-- extremely efficient for extracting expected items.
--
-- Examples of Lookup indexing:
--
-- declare
-- My_Codec: Unbounded_JSON_Codec := Unbounded_JSON_Codec'Input (...);
-- begin
-- if My_Codec("Country.Canada.Toronto.Temperatures[0]").Value > 20.0 then
-- ..
-- if My_Codec("My_3D_Array[12][1][0]").Kind = JSON_Null then
--
-- My_Codec("Sender_ID").Value (My_ID); -- Set the ID
function Root (Codec: aliased in out Unbounded_JSON_Codec)
return JSON_Mutable_Structure'Class;
function Constant_Root (Codec: aliased Unbounded_JSON_Codec)
return JSON_Structure'Class;
-- Returns the root structure the represents the entire deserialized
-- JSON object
--
-- If the tree is not Ready, Program_Error is raised.
function Delve (Codec : aliased in out Unbounded_JSON_Codec;
Structure: aliased in out JSON_Value'Class)
return JSON_Mutable_Structure'Class with
Pre'Class => Structure.Kind in JSON_Structure_Kind;
function Constant_Delve (Codec : aliased Unbounded_JSON_Codec;
Structure: aliased JSON_Value'Class)
return JSON_Structure'Class with
Pre'Class => Structure.Kind in JSON_Structure_Kind;
-- Delve effectivly converts a Structure JSON_Value_Reference into a
-- JSON_Structure object that can then be inspected.
--
-- Structure shall be a reference obtained from Codec, otherwise
-- Program_Error is raised.
--
-- Failing the precondition can result in a null check or a discriminent
-- check failure.
-- Construction --
function Construction_Codec (Format : JSON_Structure_Kind := JSON_Object;
Write_Only: Boolean := True)
return Unbounded_JSON_Codec;
-- Initializes a new Codec that is intended for object construction and
-- later serialization.
--
-- Format sets the Kind of the Root structure.
--
-- If Write_Only is True, paths are not registered, and path-based indexing
-- is not available. This improves performance and reduces memory usage for
-- constructions.
-- Parsing and Generation --
function Valid (Codec: Unbounded_JSON_Codec) return Boolean;
-- Returns False if the parser has discovered an invalid condition,
-- including for reasons not necessarily related to the parser (such as an
-- End_Error)
function Invalid_Because_End_Error (Codec: Unbounded_JSON_Codec)
return Boolean
with
Pre'Class => not Codec.Valid;
-- Returns True iff the inValid condition was specifically caused by the
-- raising of Ada.IO_Exceptions.End_Error, indicating the end of a stream.
--
-- The will only be useful when doing stream deserializations
function Error_Message (Codec: Unbounded_JSON_Codec) return String with
Pre'Class => not Codec.Valid;
-- Returns a messages explaining why the parser considers the input to
-- be invalid, which is prepended to a "Line:Column:" indication to
-- give an indication of where the error occured.
--
-- If the tree is Valid, Constraint_Error is raised
function Serialized_Length (Codec: in Unbounded_JSON_Codec)
return Natural;
-- Returns the number of ** UTF_8 ** characters required to serialize
-- (generate) the JSON string representation of the Root object. Note
-- that this value is generated by executing a Serialize dry-run and
-- metering the output.
procedure Serialize (Codec : in Unbounded_JSON_Codec;
Output: out UTF_8_String) with
Pre'Class => Output'Length = Codec.Serialized_Length;
-- Generates a UTF-8 encoded JSON string serialized from the tree.
-- If Output is not large enough, Constraint_Error is raised.
-- If Output is too large, the remaining space is filled with
-- whitespace.
function Serialize (Codec: in Unbounded_JSON_Codec)
return UTF_8_String with
Post'Class => Serialize'Result'Length = Codec.Serialized_Length;
-- Generates a UTF-8 encoded JSON string serialized from the tree. This
-- process is two-pass, since Serialized_Length is invoked to size the
-- returned string.
procedure Serialize
(Output_Stream: not null access Ada.Streams.Root_Stream_Type'Class;
Codec : in Unbounded_JSON_Codec);
-- Generates a UTF-8 encoded JSON string serialized from the tree, and
-- writes it to Output_Stream. Note that this is the most efficient
-- approach, as it is always single-pass.
-- -- NOTE --
-- Deserialization of a Codec never leaves the Codec in an inconsistent
-- state, even if the input is invalid. Serializing a Codec where Valid is
-- False will always produce valid JSON, however the contents of the Codec
-- will likely be incompelete.
function Deserialize (Input: UTF_8_String) return Unbounded_JSON_Codec;
-- Beware of extremely large Inputs. Input is converted into a
-- Wide_Wide_String, and if that fails (such as due to a Storage_Error),
-- the Codec will be invalidated with an "Emergency Stop", which may not
-- be a very helpful message without reading this comment.
function Deserialize
(Source: not null access Ada.Streams.Root_Stream_Type'Class)
return Unbounded_JSON_Codec;
function Deserialize
(Source: not null access Ada.Streams.Root_Stream_Type'Class;
Limits: Codec_Limits)
return Unbounded_JSON_Codec;
function Time_Bounded_Deserialize
(Source: not null access Ada.Streams.Root_Stream_Type'Class;
Budget: in Duration)
return Unbounded_JSON_Codec;
function Time_Bounded_Deserialize
(Source: not null access Ada.Streams.Root_Stream_Type'Class;
Limits: Codec_Limits;
Budget: in Duration)
return Unbounded_JSON_Codec;
-- Given a stream that shall be a UTF-8 text stream encoding a JSON
-- object, Deserialize parses the stream until a complete JSON object
-- has been deserialized.
--
-- Deserialize suppresses any exceptions experienced during the
-- deserialization process. If any such exception occurs, the Codec
-- returned, but is marked inValid.
--
-- The user should check Valid immediately after initializing a Codec
-- with Deserialize, or using 'Input.
--
-- In trule exceptional cases, if the Codec experiences exceptions during
-- initialization of the Unbounded_JSON_Codec object itself (likely
-- a Storage_Error), that exception is propegated.
--
-- This approach to error handling is intended for defensive server
-- environments where any erronious input is discarded as quickly as
-- possible, and the offending client disconnected.
--
-- For more complex error handling, particularily is client feedback
-- is needed, the user should implement their own processes via the
-- FSM_Push facilities
--
-- The Time_Bounded_Deserialize permutations implement integrated
-- "slow loris" attack protection by aborting the decode if the total
-- time spent decoding exceeds Budget before the decode completes.
--
-- The elapsed time is checked after each unicode character is decoded
-- from the Source stream.
--
-- A "slow loris" attack is when a client sends single character
-- transmissions at a rate that is (optimally) just below the connection's
-- receive timeout, thus allowing for a connection to remain active for
-- an extreme amount of time. These permuations thus protect against this
-- buy defining a hard deadline by which the decode operation must complete
procedure Disallowed_Read
(Stream: not null access Ada.Streams.Root_Stream_Type'Class;
Item : out Unbounded_JSON_Codec)
with No_Return;
-- 'Read is not supported, since Codecs are stateful, and thus would require
-- an in-out mode parameter. Invoking 'Read thus raised Program_Error.
for Unbounded_JSON_Codec'Write use Serialize;
for Unbounded_JSON_Codec'Output use Serialize;
for Unbounded_JSON_Codec'Read use Disallowed_Read;
for Unbounded_JSON_Codec'Input use Deserialize;
------------------------------
-- Unbounded_FSM_JSON_Codec --
------------------------------
type Unbounded_FSM_JSON_Codec is limited new Unbounded_JSON_Codec with
private;
-- Default initialized Unbounded_FSM_JSON_Codecs do not have valid
-- Roots. It must be initialized via repeated calls to FSM_Push as
-- described below.
not overriding
function Input_Limited_FSM (Limits: Codec_Limits)
return Unbounded_FSM_JSON_Codec;
-- Used to initalize a codec with input limits for the parser.
not overriding
procedure FSM_Push (Codec : in out Unbounded_FSM_JSON_Codec;
Next_Character: in Wide_Wide_Character;
Halt : out Boolean);
not overriding
procedure FSM_Push (Codec : in out Unbounded_FSM_JSON_Codec;
Next_Characters: in Wide_Wide_String;
Halt : out Boolean);
-- Drives the Finite State Machine parser directly with a single character
-- or sequence of characters.
--
-- FSM_Push should be invoked with new input until Halt is set to True.
--
-- The FSM will Halt for one of two reasons: Either it finished parsing
-- a complete JSON object, or it encountered invalid JSON.
--
-- If Valid is True and Halt is also True, the deserialization has completed
-- successfully.
--
-- Calling FSM_Push after Halt was signaled will have no effect on the
-- Codec, but will cause Error_Message to report encode an incorrect
-- position.
--
-- FSM_Push is not expected to raise exceptions related to the input.
--
-- These operations are exposed to allow for more direct control of
-- Deserialization streaming, particularily to prevent "slow loris" attacks.
--
-- ** FSM_Push must only be called from a Codec initailized from **
-- ** Manual_Parser, otherwise Program_Error is raised. **
--
-- Advanced Users:
-- ---------------
-- The Codec remains "consistent" during parsing, even in the event of an
-- inValid state. This means that the Codec can be queried and even modified
-- before parsing is completed, at the possible risk of exceptions. However
-- there is no danger of errnoneous execution other un-safe effects.
--
-- This could be potentialy useful for doing very early validation of
-- JSON blobs
not overriding
function Root_Initialized (Codec: Unbounded_FSM_JSON_Codec) return Boolean;
-- Returns True if the Root structure exists. This is useful for proactively
-- avoiding exceptions by querying Root before the FSM Halts. (See note for
-- "Advanced Users" above)
for Unbounded_FSM_JSON_Codec'Write use Serialize;
for Unbounded_FSM_JSON_Codec'Output use Serialize;
for Unbounded_FSM_JSON_Codec'Read use Disallowed_Read;
for Unbounded_FSM_JSON_Codec'Input use Deserialize;
-- Note that all of the deserialization operations work just as for regular
-- Unbounded_JSON_Codecs, but these operations drive the same internal FSM,
-- and will render FSM_Push useless, since the FSM state will Halted
-- immediately after deserialization in all cases, and new input will be
-- ignored.
private
--------------------------
-- Fast_Slab_Allocators --
--------------------------
-- A custom subpool-capable storage pool optimized to maximize performance,
-- and especially to minimize heap fragmentation for very high-throughput,
-- long-uptime server applications.
--
-- Each Unbounded_JSON_Codec allocates all items from its own Subpool, and
-- all deallocation occurs at finalization. Additionally, heap allocations
-- are done in constant-size (should be page-sized) allocations (slabs).
-- The Slab size can be set via the AURA configuration package with the
-- configuration value Unbounded_Codec_Slab_Size
package Fast_Slab_Allocators renames JSON.Fast_Slab_Allocators;
-- GNAT Bug workaround. See the Fast_Slab_Allocators spec for details.
Slab_Pool: Fast_Slab_Allocators.Slab_Pool_Designator
renames Fast_Slab_Allocators.Global_Slab_Pool;
subtype Subpool_Handle is System.Storage_Pools.Subpools.Subpool_Handle;
use type Subpool_Handle;
------------------
-- Slab_Strings --
------------------
-- Slab_String is a slab allocator-friendly (low fragmentation) unbounded
-- non-contigious string type
package Slab_Strings is
type Slab_String is private;
type Slab_String_Access is access Slab_String with
Storage_Pool => Slab_Pool;
-- Slab_String is kind of a super-private type. If it was general exposed
-- to the outside world, it would be limited. In this case, it is
-- non-limited to permit the mutability of JSON_Value objectes
--
-- Copying a Slab_String will not cause anything crazy to happen, except
-- that it might eventually result in a corrupted string, since two
-- "separate" strings would ultimately start overwriting eachother,
-- however it would still remain technically memory safe, since all
-- slab allocations are deallocated on dinalization of the entire Codec
--
-- Never make copies of Slab_String objects. Either use Transfer, or
-- or ensure the "original" is never used after the copy.
procedure Setup (Target : in out Slab_String;
Subpool: in not null Subpool_Handle);
-- Must be invoked prior to invoking any of the following operations.
function "=" (Left, Right: Slab_String) return Boolean;
procedure Append (Target: in out Slab_String;
Source: in JSON_String_Value);
procedure Clear (Target: in out Slab_String);
procedure Transfer (From: in out Slab_String;
To : out Slab_String);
-- After From is Transfered to To, From is Cleared. To does not need
-- to be Set-up first. To will be associated with the same Subpool as
-- From.
function Length (S: Slab_String) return Natural;
procedure To_JSON_String (Source: in Slab_String;
Target: out JSON_String_Value)
with Pre => Target'Length = Length (Source);
function To_JSON_String (Source: in Slab_String)
return JSON_String_Value;
procedure Write_Stream
(Stream: not null access Ada.Streams.Root_Stream_Type'Class;
Item : in Slab_String);
for Slab_String'Write use Write_Stream;
-- Stream Writing is intended for hashing
Chunk_Size: constant := 64;
-- The static Wide_Wide_Character'Length of each Subpool allocated
-- "chunk" (segment). The string will grow by this size on demand
private
subtype Slab_String_Chunk_Index is Natural range 0 .. Chunk_Size;
type Slab_String_Chunk;
type Slab_String_Chunk_Access is access Slab_String_Chunk with
Storage_Pool => Slab_Pool;
type Slab_String is
record
Subpool : Subpool_Handle := null;
Chain_First : Slab_String_Chunk_Access := null;
Chain_Last : Slab_String_Chunk_Access := null;
Current_Chunk: Slab_String_Chunk_Access := null;
Current_Last : Slab_String_Chunk_Index := 0;
-- Current_Last is the current index of the last character
-- of Current_Chunk, which is the last Chunk of the current
-- string. If Current_Chunk is not Chain_First, then it
-- is taken that all chunks before Current_Chunk are "full"
end record;
end Slab_Strings;
--------------------
-- JSON_Structure --
--------------------
type Node is access all JSON_Value with Storage_Pool => Slab_Pool;
-- We make Node a general access type so that we can assign values of
-- JSON_Value_Reference access discriminents to Node. This will always
-- be safe since the user is not able to create references to JSON_Values
-- that have no been generated via Node allocations, since JSON_Value has
-- unknown descriminents.
type JSON_Structure_Cursor is
record
Target: Node := null;
end record;
-- This is a general access type to allow us to assign reference values
-- (access descriminents pointing at a JSON_Value) to values of this type.
--
-- We know that all JSON_Values coming this way ultimately arrived via
-- allocators, since the user as no way of directly supplying
type Constant_Codec_Access is not null access constant Unbounded_JSON_Codec
with Storage_Size => 0;
type Mutable_Codec_Access is not null access all Unbounded_JSON_Codec
with Storage_Size => 0;
type JSON_Structure is tagged limited
record
Structure_Root: not null Node;
-- Always made to point to a JSON_Value with Kind of JSON_Object or
-- JSON_Array. All children of the structure are children of this
-- node.
Codec_Constant: Constant_Codec_Access;
end record;
type JSON_Mutable_Structure is new JSON_Structure with
record
Codec_Mutable: Mutable_Codec_Access;
end record;
--------------------
-- Node_Hash_Maps --
--------------------
package Node_Hash_Maps is
type Node_Hash_Map is private;
-- Node_Hash_Map is designed to be very compact on default initialization
-- so that it can be included in all structural nodes, only taking up
-- space as needed
--
-- Similar to Slab_Strings, Node_Hash_Map would be limited if it was not
-- such a private type. Copying Node_Hash_Maps will not really cause any
-- issue, except that the Performance values will not be accurate.
--
-- Node_Hash_Maps are made non-limited to preserve internal mutability of
-- the JSON_Value objects (which are publically limited)
procedure Setup (Map : in out Node_Hash_Map;
Subpool: in not null Subpool_Handle);
-- Configures a hash map with an appropriate Subpool for allocations
procedure Register (Path_Map : in out Node_Hash_Map;
Registrant: in not null Node);
-- Use Name or Index component of Registrant (depending on the Parent),
-- and adds that registration to the appropriate map of the Parent,
-- along with the computed full-path registration to the Path_Map
-- Both Register operations also register the full path with the Path_Map
-- Raises Constraint_Error if Path/Name/Index has already been registered
function Lookup_By_Path (Path_Map: Node_Hash_Map;
Path : JSON_String_Value)
return Node;
function Lookup_By_Name (Name_Map: Node_Hash_Map;
Name : JSON_String_Value)
return Node;
function Lookup_By_Index (Index_Map: Node_Hash_Map;
Index : Natural)
return Node;
-- If the lookup fails, a null value is returned
-- Monitoring services
type Match_Level is range 1 .. 4;
Performance_Monitoring: constant Boolean := True;
type Level_Registrations is array (Match_Level) of Natural;
-- Number of registrations per match level
type Performance_Counters is
record
Primary_Registrations : Level_Registrations := (others => 0);
Overflow_Registrations: Level_Registrations := (others => 0);
-- Primary_Registrations are registrations made to the "head table"
-- Secondary_Registrations are registrations made to additional
-- tables added on demand.
--
-- Each tables is indexed with two different alternating hash-based
-- strategies. These strategies are repeated over every even and
-- odd table in the table chain
--
-- Note that invalidation does not affect these numbers (no
-- decrementation)
Total_Tables : Natural := 1;
-- Gives the total number of tables allocated for this map
Saturation_High_Water : Natural := 0;
-- Gives the numer of contigious tables from the first table
-- to be fully saturated. This value gives indications into
-- how efficient registration is for very large or complicated
-- Codecs (particularily for Path_Maps)
Full_Collisions : Natural := 0;
-- Registrations where the full hash value is an exact match,
-- but the hashed name differs. Hopefully this never goes
-- above zero.
end record;
function Performance (Map: Node_Hash_Map) return Performance_Counters;
private
-- See the package body for more detailed discussion of the
-- Node_Hash_Maps architecture
type Node_Hash_Table;
type Node_Hash_Table_Access is access Node_Hash_Table with
Storage_Pool => Slab_Pool;
type Node_Hash_Map is
record
Subpool : Subpool_Handle := null;
Table_Chain : Node_Hash_Table_Access := null;
First_Unsaturated : Node_Hash_Table_Access := null;
Unsaturated_Sequence: Positive := 1;
-- Points to the first Table that is not yet saturated. This is
-- used for registration only, to save time from needing to scan
-- saturated tables, which will tend to be towards the start.
-- The sequence is the number of the table in the chain, which
-- is used to determine if a Primary (odd) or Secondary (even)
-- strategy should be used for that table.
Expected_ID : Slab_Strings.Slab_String_Access := null;
Candidate_ID : Slab_Strings.Slab_String_Access := null;
-- These values are used for name-based lookups, wither for
-- Path_Maps and Name_Maps. These are access values
-- to allow use even if Node_Hash_Map is being accessed with
-- a constant view. These are allocated during Setup.
Profile : Performance_Counters;
end record;
end Node_Hash_Maps;
------------------------
-- JSON_Value (Nodes) --
------------------------
type Value_Container (Kind: JSON_Value_Kind := JSON_Null) is
record
case Kind is
when JSON_Object =>
Name_Map: Node_Hash_Maps.Node_Hash_Map;
First_Member: Node := null;
Last_Member : Node := null;
Member_Count: Natural := 0;
when JSON_Array =>
Index_Map: Node_Hash_Maps.Node_Hash_Map;
First_Element: Node := null;
Last_Element : Node := null;
Element_Count: Natural := 0;
when JSON_String =>
String_Value: Slab_Strings.Slab_String;
when JSON_Integer =>
Integer_Value: JSON_Integer_Value;
when JSON_Float =>
Float_Value: JSON_Float_Value;
when JSON_Boolean =>
Boolean_Value: Boolean;
when JSON_Null =>
null;
end case;
end record;
type JSON_Value is tagged limited
record
Name: Slab_Strings.Slab_String;
-- Name only applies if the value is a direct child of a JSON_Object
Index: Natural;
Root, Parent, Next, Prev: Node := null;
-- Root always points at the Root node of the entire tree
-- (Codec-specific) to which this node belongs. This is used to
-- verify ownership.
--
-- For the actual root JSON_Value, Parent will be null, and Root
-- will be self-referencing (!)
--
-- In general, Root is not used for dereferencing, only for ownership
-- checking.
Codec_Subpool: Subpool_Handle := null;
-- Copied-in from the same-named property of the owning Codec on
-- creation. See that property of Unbounded_JSON_Codec below for
-- more details
Container: Value_Container;
-- The JSON_Value type itself is tagged for greater user convenience.
-- However this means that we cannot give a non-limited full view.
--
-- At the same time, we'd like the actual underlying value to be
-- mutable.
--
-- Keeping the public view limited is crucial for the ability to
-- directly use in-codec data without needing to copy the values,
-- which is a property we want to keep.
--
-- By including this mutable container type to contain the actual
-- value, we are able to get everything to work as we'd like
end record;
--------------------------
-- Unbounded_JSON_Codec --
--------------------------
package Parsers is new JSON.Parser_Machine
(JSON_String_Buffer => Slab_Strings.Slab_String,
JSON_String_Buffer_Config => Subpool_Handle,
Setup_Buffer => Slab_Strings.Setup,
Clear => Slab_Strings.Clear,
Append => Slab_Strings.Append,
Export => Slab_Strings.Transfer,
String_Chunk_Size => Slab_Strings.Chunk_Size);
type Unbounded_JSON_Codec is new Ada.Finalization.Limited_Controlled with
record
Write_Only : Boolean := False;
-- If true, all hashing on append is disabled, and all
-- hash-based lookup causes Constraint_Error
Codec_Subpool: Subpool_Handle := null;
-- For this design, we use a single subpool per Codec, which is
-- used to allocate all nodes, hash tables, and Slab_Strings.
Path_Buffer : Slab_Strings.Slab_String;
-- When appending items to any structure in this codec, a Full_Path
-- needs to be computed so that the path can be added to the Path_Map
--
-- Since Slab_Strings can never have their memory reclaimed until the
-- entire Codec is finalized, we put this one here in the Codec as
-- a kind of scratch buffer to quickly build-out the path when needed.
--
-- Since Slab_Strings are lazily allocated, if this never gets used,
-- that's fine too!
Path_Map : Node_Hash_Maps.Node_Hash_Map;
Root_Node : Node;
-- Root_Node is initialized as a JSON_Object
Parser : Parsers.Parser_FSM;
Current_Structure: Node;
-- Current_Structure is a bit of state that the FSM contracts out to
-- the operator (the Codec), who has a bigger picture, and is able
-- to easily know what kind of structure the parent structure is.
-- The FSM uses this to detect invalid JSON more immediately
-- (specifically object members missing names, or array elements
-- having names.
--
-- When the Codec is initialized, this component equals Root_Node
Error: Slab_Strings.Slab_String;
-- Contains a detailed error message when deserialization failed
-- to properly initialize the Codec
End_Error: Boolean := False;
-- Is set to True if an Ada.IO_Exceptions.End_Error is raised during
-- a stream deserialization
end record;
overriding
procedure Initialize (Codec: in out Unbounded_JSON_Codec);
overriding
procedure Finalize (Codec: in out Unbounded_JSON_Codec);
type Unbounded_FSM_JSON_Codec is limited new Unbounded_JSON_Codec with
null record;
end JSON.Unbounded_Codecs;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . F I N A L I Z A T I O N _ I M P L E M E N T A T I O N --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
--
--
--
--
--
--
--
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with System.Finalization_Root;
package System.Finalization_Implementation is
pragma Elaborate_Body;
package SFR renames System.Finalization_Root;
------------------------------------------------
-- Finalization Management Abstract Interface --
------------------------------------------------
Global_Final_List : SFR.Finalizable_Ptr;
-- This list stores the controlled objects defined in library-level
-- packages. They will be finalized after the main program completion.
procedure Finalize_Global_List;
-- The procedure to be called in order to finalize the global list;
procedure Attach_To_Final_List
(L : in out SFR.Finalizable_Ptr;
Obj : in out SFR.Finalizable;
Nb_Link : Short_Short_Integer);
-- Attach finalizable object Obj to the linked list L. Nb_Link controls
-- the number of link of the linked_list, and can be either 0 for no
-- attachement, 1 for simple linked lists or 2 for doubly linked lists
-- or even 3 for a simple attachement of a whole array of elements.
-- Attachement to a simply linked list is not protected against
-- concurrent access and should only be used in contexts where it
-- doesn't matter, such as for objects allocated on the stack. In the
-- case of an attachment on a doubly linked list, L must not be null
-- and Obj will be inserted AFTER the first element and the attachment
-- is protected against concurrent call. Typically used to attach to
-- a dynamically allocated object to a List_Controller (whose first
-- element is always a dummy element)
procedure Finalize_List (L : SFR.Finalizable_Ptr);
-- Call Finalize on each element of the list L;
procedure Finalize_One (Obj : in out SFR.Finalizable);
-- Call Finalize on Obj and remove its final list.
---------------------
-- Deep Procedures --
---------------------
procedure Deep_Tag_Initialize
(L : in out SFR.Finalizable_Ptr;
A : System.Address;
B : Short_Short_Integer);
-- Generic initialize for tagged objects with controlled components.
-- A is the address of the object, L the finalization list when it needs
-- to be attached and B the attachement level (see Attach_To_Final_List).
procedure Deep_Tag_Adjust
(L : in out SFR.Finalizable_Ptr;
A : System.Address;
B : Short_Short_Integer);
-- Generic adjust for tagged objects with controlled components.
-- A is the address of the object, L the finalization list when it needs
-- to be attached and B the attachement level (see Attach_To_Final_List).
procedure Deep_Tag_Finalize
(L : in out SFR.Finalizable_Ptr;
A : System.Address;
B : Boolean);
-- Generic finalize for tagged objects with controlled components.
-- A is the address of the object, L the finalization list when it needs
-- to be attached and B the attachement level (see Attach_To_Final_List).
procedure Deep_Tag_Attach
(L : in out SFR.Finalizable_Ptr;
A : System.Address;
B : Short_Short_Integer);
-- Generic attachement for tagged objects with controlled components.
-- A is the address of the object, L the finalization list when it needs
-- to be attached and B the attachement level (see Attach_To_Final_List).
-----------------------------
-- Record Controller Types --
-----------------------------
-- Definition of the types of the controller component that is included
-- in records containing controlled components. This controller is
-- attached to the finalization chain of the upper-level and carries
-- the pointer of the finalization chain for the lower level.
type Limited_Record_Controller is new SFR.Root_Controlled with record
F : SFR.Finalizable_Ptr;
end record;
procedure Initialize (Object : in out Limited_Record_Controller);
-- Does nothing.
procedure Finalize (Object : in out Limited_Record_Controller);
-- Finalize the controlled components of the enclosing record by
-- following the list starting at Object.F.
type Record_Controller is
new Limited_Record_Controller with record
My_Address : System.Address;
end record;
procedure Initialize (Object : in out Record_Controller);
-- Initialize the field My_Address to the Object'Address
procedure Adjust (Object : in out Record_Controller);
-- Adjust the components and their finalization pointers by subtracting
-- by the offset of the target and the source addresses of the assignment.
-- Inherit Finalize from Limited_Record_Controller
procedure Detach_From_Final_List (Obj : in out SFR.Finalizable);
-- Remove the specified object from its Final list, which must be a
-- doubly linked list.
end System.Finalization_Implementation;
|
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with League.Strings;
package Torrent.Logs is
Enabled : Boolean := False;
procedure Initialize (Output : League.Strings.Universal_String);
procedure Print (Text : String);
end Torrent.Logs;
|
with ada.unchecked_deallocation;
with ada.characters.latin_1;
use ada.characters.latin_1;
package body generic_linked_list is
-- Instanciation du deallocateur pour le pool d'access node_t
procedure node_unchecked_deallocation is new ada.unchecked_deallocation(node_t, node_ptr);
function create(element : element_t) return node_ptr is
node : constant node_ptr := new node_t;
begin
node.all := (element => element, next_node => null);
return node;
end;
function add_after(node : node_ptr; element : element_t) return node_ptr is
begin
add_after(node, element);
return move_next(node);
end;
procedure add_after(node : node_ptr; element : element_t) is
new_node : constant node_ptr := new node_t;
begin
new_node.all := (element => element, next_node => null);
node.next_node := new_node;
end;
procedure remove_next(node : node_ptr) is
next_node : node_ptr := node.next_node;
begin
if next_node = null then
raise no_node;
end if;
-- Supprime le noeud de la chaine
node.next_node := next_node.next_node;
-- Libération de la mémoire du noeud
node_unchecked_deallocation(next_node);
end;
function has_next(node : node_ptr) return boolean is
begin
return node.next_node /= null;
end;
function move_next(node : node_ptr) return node_ptr is
begin
if node.next_node = null then
raise no_node;
end if;
return node.next_node;
end;
function elem(node : node_ptr) return element_t is
begin
return node.all.element;
end;
procedure destroy(node : in out node_ptr) is
begin
if has_next(node) then
destroy(node.next_node);
end if;
node_unchecked_deallocation(node);
end;
function to_string(node : node_ptr; to_string : to_string_function_t) return string is
-- Helper de récursion permettant la génération de la chaine pour le to_string
function to_string_helper(node : node_ptr; to_string : to_string_function_t) return string is
s : constant string := ada.characters.latin_1.HT & to_string.all(elem(node));
begin
if has_next(node) then
return s
& ','
& ada.characters.latin_1.LF
& to_string_helper(move_next(node), to_string);
end if;
return s & ada.characters.latin_1.LF;
end;
begin
return "["
& ada.characters.latin_1.LF
& to_string_helper(node, to_string)
& ada.characters.latin_1.HT
& "]";
end;
end generic_linked_list;
|
pragma Ada_2012;
with Ada.Text_IO; use Ada.Text_IO;
package body Protypo.API.Consumers.File_Writer is
type Writer_Access is access Writer;
----------
-- Open --
----------
function Open (Target : Target_Name) return Consumer_Access is
use Ada.Finalization;
Result : constant Writer_Access := new Writer'(Limited_Controlled with
Target => Target.Class,
Open => True,
Output => <>);
begin
if Target.Class = File then
Ada.Text_IO.Create (File => Result.Output,
Mode => Ada.Text_IO.Out_File,
Name => Target.Name);
end if;
return Consumer_Access(Result);
end Open;
-------------
-- Process --
-------------
overriding procedure Process
(Consumer : in out Writer;
Parameter : String)
is
begin
case Consumer.Target is
when Stdout =>
Ada.Text_IO.Put (Parameter);
when Stderr =>
Ada.Text_IO.Put (Ada.Text_IO.Standard_Error, Parameter);
when File =>
Ada.Text_IO.Put (Consumer.Output, Parameter);
end case;
end Process;
-----------
-- Close --
-----------
procedure Close (Consumer : in out Writer)
is
begin
if Consumer.Open and Consumer.Target = File then
Ada.Text_Io.Close (Consumer.Output);
Consumer.Open := False;
end if;
end Close;
--------------
-- Finalize --
--------------
overriding procedure Finalize (Obj : in out Writer)
is
begin
Close (Obj);
end Finalize;
end Protypo.API.Consumers.File_Writer;
|
with Ada.Interrupts;
with STM32_SVD.USART;
with STM32_SVD; use STM32_SVD;
generic
with package USART is new STM32GD.USART.Peripheral (<>);
IRQ : Ada.Interrupts.Interrupt_ID;
package STM32GD.USART.IRQ is
procedure Init;
protected IRQ_Handler is
entry Wait;
private
procedure Handler;
pragma Attach_Handler (Handler, IRQ);
Data_Available : Boolean := False;
end IRQ_Handler;
end STM32GD.USART.IRQ;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.