content
stringlengths 23
1.05M
|
|---|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- ADA.DIRECTORIES.HIERARCHICAL_FILE_NAMES --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-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. --
-- --
-- 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. --
-- --
-- In particular, you can freely distribute your programs built with the --
-- GNAT Pro compiler, including any required library run-time units, using --
-- any licensing terms of your choosing. See the AdaCore Software License --
-- for full details. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Directories.Validity; use Ada.Directories.Validity;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with System; use System;
package body Ada.Directories.Hierarchical_File_Names is
Dir_Separator : constant Character;
pragma Import (C, Dir_Separator, "__gnat_dir_separator");
-- Running system default directory separator
-----------------
-- Subprograms --
-----------------
function Equivalent_File_Names
(Left : String;
Right : String)
return Boolean;
-- Perform an OS-independent comparison between two file paths
function Is_Absolute_Path (Name : String) return Boolean;
-- Returns True if Name is an absolute path name, i.e. it designates a
-- file or directory absolutely rather than relative to another directory.
---------------------------
-- Equivalent_File_Names --
---------------------------
function Equivalent_File_Names
(Left : String;
Right : String)
return Boolean
is
begin
-- Check the validity of the input paths
if not Is_Valid_Path_Name (Left)
or else not Is_Valid_Path_Name (Right)
then
return False;
end if;
-- Normalize the paths by removing any trailing directory separators and
-- perform the comparison.
declare
Normal_Left : constant String :=
(if Index (Left, Dir_Separator & "", Strings.Backward) = Left'Last
and then not Is_Root_Directory_Name (Left)
then
Left (Left'First .. Left'Last - 1)
else
Left);
Normal_Right : constant String :=
(if Index (Right, Dir_Separator & "", Strings.Backward) = Right'Last
and then not Is_Root_Directory_Name (Right)
then
Right (Right'First .. Right'Last - 1)
else
Right);
begin
-- Within Windows we assume case insensitivity
if not Windows then
return Normal_Left = Normal_Right;
end if;
-- Otherwise do a straight comparison
return To_Lower (Normal_Left) = To_Lower (Normal_Right);
end;
end Equivalent_File_Names;
----------------------
-- Is_Absolute_Path --
----------------------
function Is_Absolute_Path (Name : String) return Boolean is
function Is_Absolute_Path
(Name : Address;
Length : Integer) return Integer;
pragma Import (C, Is_Absolute_Path, "__gnat_is_absolute_path");
begin
return Is_Absolute_Path (Name'Address, Name'Length) /= 0;
end Is_Absolute_Path;
--------------------
-- Is_Simple_Name --
--------------------
function Is_Simple_Name (Name : String) return Boolean is
begin
-- Verify the file path name is valid and that it is not a root
if not Is_Valid_Path_Name (Name)
or else Is_Root_Directory_Name (Name)
then
return False;
end if;
-- Check for the special paths "." and "..", which are considered simple
if Is_Parent_Directory_Name (Name)
or else Is_Current_Directory_Name (Name)
then
return True;
end if;
-- Perform a comparison with the calculated simple path name
return Equivalent_File_Names (Simple_Name (Name), Name);
end Is_Simple_Name;
----------------------------
-- Is_Root_Directory_Name --
----------------------------
function Is_Root_Directory_Name (Name : String) return Boolean is
begin
-- Check if the path name is a root directory by looking for a slash in
-- the general case, and a drive letter in the case of Windows.
return Name = "/"
or else
(Windows
and then
(Name = "\"
or else
(Name'Length = 3
and then Name (Name'Last - 1) = ':'
and then Name (Name'Last) in '/' | '\'
and then (Name (Name'First) in 'a' .. 'z'
or else
Name (Name'First) in 'A' .. 'Z'))
or else
(Name'Length = 2
and then Name (Name'Last) = ':'
and then (Name (Name'First) in 'a' .. 'z'
or else
Name (Name'First) in 'A' .. 'Z'))));
end Is_Root_Directory_Name;
------------------------------
-- Is_Parent_Directory_Name --
------------------------------
function Is_Parent_Directory_Name (Name : String) return Boolean is
begin
return Name = "..";
end Is_Parent_Directory_Name;
-------------------------------
-- Is_Current_Directory_Name --
-------------------------------
function Is_Current_Directory_Name (Name : String) return Boolean is
begin
return Name = ".";
end Is_Current_Directory_Name;
------------------
-- Is_Full_Name --
------------------
function Is_Full_Name (Name : String) return Boolean is
begin
return Equivalent_File_Names (Full_Name (Name), Name);
end Is_Full_Name;
----------------------
-- Is_Relative_Name --
----------------------
function Is_Relative_Name (Name : String) return Boolean is
begin
return not Is_Absolute_Path (Name)
and then Is_Valid_Path_Name (Name);
end Is_Relative_Name;
-----------------------
-- Initial_Directory --
-----------------------
function Initial_Directory (Name : String) return String is
Start : constant Integer := Index (Name, Dir_Separator & "");
begin
-- Verify path name
if not Is_Valid_Path_Name (Name) then
raise Name_Error with "invalid path name """ & Name & '"';
end if;
-- When there is no starting directory separator or the path name is a
-- root directory then the path name is already simple - so return it.
if Is_Root_Directory_Name (Name) or else Start = 0 then
return Name;
end if;
-- When the initial directory of the path name is a root directory then
-- the starting directory separator is part of the result so we must
-- return it in the slice.
if Is_Root_Directory_Name (Name (Name'First .. Start)) then
return Name (Name'First .. Start);
end if;
-- Otherwise we grab a slice up to the starting directory separator
return Name (Name'First .. Start - 1);
end Initial_Directory;
-------------------
-- Relative_Name --
-------------------
function Relative_Name (Name : String) return String is
begin
-- We cannot derive a relative name if Name does not exist
if not Is_Relative_Name (Name)
and then not Is_Valid_Path_Name (Name)
then
raise Name_Error with "invalid relative path name """ & Name & '"';
end if;
-- Name only has a single part and thus cannot be made relative
if Is_Simple_Name (Name)
or else Is_Root_Directory_Name (Name)
then
raise Name_Error with
"relative path name """ & Name & """ is composed of a single part";
end if;
-- Trim the input according to the initial directory and maintain proper
-- directory separation due to the fact that root directories may
-- contain separators.
declare
Init_Dir : constant String := Initial_Directory (Name);
begin
if Init_Dir (Init_Dir'Last) = Dir_Separator then
return Name (Name'First + Init_Dir'Length .. Name'Last);
end if;
return Name (Name'First + Init_Dir'Length + 1 .. Name'Last);
end;
end Relative_Name;
-------------
-- Compose --
-------------
function Compose
(Directory : String := "";
Relative_Name : String;
Extension : String := "") return String
is
-- Append a directory separator if none is present
Separated_Dir : constant String :=
(if Directory = "" then ""
elsif Directory (Directory'Last) = Dir_Separator then Directory
else Directory & Dir_Separator);
begin
-- Check that relative name is valid
if not Is_Relative_Name (Relative_Name) then
raise Name_Error with
"invalid relative path name """ & Relative_Name & '"';
end if;
-- Check that directory is valid
if Separated_Dir /= ""
and then (not Is_Valid_Path_Name (Separated_Dir & Relative_Name))
then
raise Name_Error with
"invalid path composition """ & Separated_Dir & Relative_Name & '"';
end if;
-- Check that the extension is valid
if Extension /= ""
and then not Is_Valid_Path_Name
(Separated_Dir & Relative_Name & Extension)
then
raise Name_Error with
"invalid path composition """
& Separated_Dir & Relative_Name & Extension & '"';
end if;
-- Concatenate the result
return Separated_Dir & Relative_Name & Extension;
end Compose;
end Ada.Directories.Hierarchical_File_Names;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . B B . T I M I N G _ E V E N T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2011-2016, AdaCore --
-- --
-- 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 3, 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. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
------------------------------------------------------------------------------
with System.BB.CPU_Primitives.Multiprocessors;
with System.BB.Parameters;
with System.BB.Protection;
with System.BB.Threads;
with System.BB.Threads.Queues;
package body System.BB.Timing_Events is
use type System.BB.Time.Time;
use System.Multiprocessors;
use System.BB.CPU_Primitives.Multiprocessors;
use System.BB.Threads;
Events_Table : array (CPU) of Timing_Event_Access := (others => null);
-- One event list for each CPU
procedure Insert
(Event : not null Timing_Event_Access;
Is_First : out Boolean) with
-- Insert an event in the event list of the current CPU (Timeout order
-- then FIFO). Is_First is set to True when Event becomes the next timing
-- event to serve, False otherwise.
Pre =>
-- The first element in the list (if it exists) cannot have a previous
-- element.
(if Events_Table (Current_CPU) /= null then
Events_Table (Current_CPU).Prev = null)
-- The event should be set
and then Event.Handler /= null
-- The event should not be already inserted in a list
and then Event.Next = null and then Event.Prev = null
-- Timing Events must always be handled by the same CPU
and then (not System.BB.Parameters.Multiprocessor
or else Event.CPU = Current_CPU),
Post =>
-- Is_First is set to True when Event becomes the next timing event to
-- serve (because the list was empty or the list contained only events
-- with a later expiration time).
(if Events_Table (Current_CPU) = Event then
Is_First
and then Event.all.Prev = null
and then Event.all.Next = Events_Table'Old (Current_CPU)
-- If the event is not first then the head of queue does not change
else
Events_Table (Current_CPU) = Events_Table'Old (Current_CPU)
and then Event.all.Prev /= null)
-- The queue cannot be empty after insertion
and then Events_Table (Current_CPU) /= null
-- The first element in the list can never have a previous element
and then Events_Table (Current_CPU).Prev = null
-- The queue is always ordered by expiration time and then FIFO
and then (Event.all.Next = null
or else Event.all.Next.Timeout > Event.Timeout)
and then (Event.all.Prev = null
or else Event.all.Prev.Timeout <= Event.Timeout);
procedure Extract (Event : not null Timing_Event_Access;
Was_First : out Boolean) with
-- Extract an event from the event list of the current CPU. Was_First is
-- True when we extract the event that was first in the queue, else False.
Pre =>
-- There must be at least one element in the queue
Events_Table (Current_CPU) /= null
-- The first element in the list can never have a previous element
and then Events_Table (Current_CPU).Prev = null
-- The first element has Prev equal to null, but the others have Prev
-- pointing to another timing event.
and then (if Event /= Events_Table (Current_CPU) then
Event.Prev /= null)
-- The queue is always ordered by expiration time and then FIFO
and then (Event.Next = null
or else Event.Next.Timeout >= Event.Timeout)
and then (Event.Prev = null
or else Event.Prev.Timeout <= Event.Timeout)
-- Timing Events must always be handled by the same CPU
and then (not System.BB.Parameters.Multiprocessor
or else Event.CPU = Current_CPU),
Post =>
-- Was_First is set to True when we extract the event that was first
-- in the queue.
(if Events_Table'Old (Current_CPU) = Event then
Events_Table (Current_CPU) /= Events_Table'Old (Current_CPU)
and then Was_First)
-- The first element in the list (if it exists) cannot have a
-- previous element.
and then (if Events_Table (Current_CPU) /= null then
Events_Table (Current_CPU).Prev = null)
-- The Prev and Next pointers are set to null to indicate that the
-- event is no longer in the list.
and then Event.all.Prev = null
and then Event.all.Next = null;
-----------------
-- Set_Handler --
-----------------
procedure Set_Handler
(Event : in out Timing_Event;
At_Time : System.BB.Time.Time;
Handler : Timing_Event_Handler)
is
Next_Alarm : System.BB.Time.Time;
CPU_Id : constant CPU := Current_CPU;
Was_First : Boolean := False;
Is_First : Boolean := False;
begin
if Event.Handler /= null then
-- Extract if the event is already set
Extract (Event'Unchecked_Access, Was_First);
end if;
Event.Handler := Handler;
if Handler /= null then
-- Update event fields
Event.Timeout := At_Time;
Event.CPU := CPU_Id;
-- Insert event in the list
Insert (Event'Unchecked_Access, Is_First);
end if;
if Was_First or else Is_First then
-- Set the timer for the next alarm
Next_Alarm := Time.Get_Next_Timeout (CPU_Id);
Time.Update_Alarm (Next_Alarm);
end if;
-- The following pragma cannot be transformed into a post-condition
-- because the call to Leave_Kernel is a dispatching operation and the
-- status of the timing event handler may change (if may expire, for
-- example).
pragma Assert
((if Handler = null then
-- If Handler is null the event is cleared
Event.Handler = null
else
-- If Handler is not null then the timing event handler is set,
-- and the execution time for the event is set to At_Time in the
-- current CPU. Next timeout events can never be later than the
-- event that we have just inserted.
Event.Handler = Handler
and then Event.Timeout = At_Time
and then Time.Get_Next_Timeout (CPU_Id) <= At_Time));
end Set_Handler;
---------------------
-- Current_Handler --
---------------------
function Current_Handler
(Event : Timing_Event) return Timing_Event_Handler
is
begin
return Event.Handler;
end Current_Handler;
--------------------
-- Cancel_Handler --
--------------------
procedure Cancel_Handler
(Event : in out Timing_Event;
Cancelled : out Boolean)
is
Next_Alarm : System.BB.Time.Time;
CPU_Id : constant CPU := Current_CPU;
Was_First : Boolean;
begin
if Event.Handler /= null then
-- Extract if the event is already set
Extract (Event'Unchecked_Access, Was_First);
Cancelled := True;
Event.Handler := null;
if Was_First then
Next_Alarm := Time.Get_Next_Timeout (CPU_Id);
Time.Update_Alarm (Next_Alarm);
end if;
else
Cancelled := False;
end if;
pragma Assert (Event.Handler = null);
end Cancel_Handler;
-----------------------------------
-- Execute_Expired_Timing_Events --
-----------------------------------
procedure Execute_Expired_Timing_Events (Now : System.BB.Time.Time) is
CPU_Id : constant CPU := Current_CPU;
Event : Timing_Event_Access := Events_Table (CPU_Id);
Handler : Timing_Event_Handler;
Was_First : Boolean;
Self_Id : Thread_Id;
Caller_Priority : Integer;
begin
-- Fast path: no timing event
if Event = null then
return;
end if;
-- As required by RM D.15 (14/2), timing events must be executed at
-- the highest priority (Interrupt_Priority'Last). This is ensured by
-- executing this part at the highest interrupt priority (and not at the
-- one corresponding to the timer hardware interrupt). At the end of the
-- execution of any timing event handler the priority that is restored
-- is that of the alarm handler. If this part of the alarm handler
-- executes at a priority lower than Interrupt_Priority'Last then
-- the protection of the queues would not be guaranteed.
Self_Id := Thread_Self;
Caller_Priority := Get_Priority (Self_Id);
Queues.Change_Priority (Self_Id, Interrupt_Priority'Last);
-- Extract and execute all the expired timing events
while Event /= null and then Event.Timeout <= Now loop
-- Get handler
Handler := Event.Handler;
pragma Assert (Handler /= null);
-- Extract first event from the list
Extract (Event, Was_First);
pragma Assert (Was_First);
-- Clear the event. Do it before executing the handler before the
-- timing event can be reinserted in the handler.
Event.Handler := null;
-- Execute the handler
Handler (Event.all);
Event := Events_Table (CPU_Id);
end loop;
Queues.Change_Priority (Self_Id, Caller_Priority);
-- No more events to handle with an expiration time before Now
pragma Assert (Events_Table (CPU_Id) = null
or else Events_Table (CPU_Id).Timeout > Now);
end Execute_Expired_Timing_Events;
----------------------
-- Get_Next_Timeout --
----------------------
function Get_Next_Timeout
(CPU_Id : System.Multiprocessors.CPU) return System.BB.Time.Time
is
Event : constant Timing_Event_Access := Events_Table (CPU_Id);
begin
if Event = null then
return System.BB.Time.Time'Last;
else
return Event.all.Timeout;
end if;
end Get_Next_Timeout;
-------------------
-- Time_Of_Event --
-------------------
function Time_Of_Event (Event : Timing_Event) return System.BB.Time.Time is
begin
if Event.Handler = null then
return System.BB.Time.Time'First;
else
return Event.Timeout;
end if;
end Time_Of_Event;
-------------
-- Extract --
-------------
procedure Extract (Event : not null Timing_Event_Access;
Was_First : out Boolean)
is
CPU_Id : constant CPU := Current_CPU;
begin
-- Head extraction
if Events_Table (CPU_Id) = Event then
Was_First := True;
Events_Table (CPU_Id) := Event.Next;
-- Middle or tail extraction
else
pragma Assert (Event.Prev /= null);
Was_First := False;
Event.Prev.Next := Event.Next;
end if;
if Event.Next /= null then
Event.Next.Prev := Event.Prev;
end if;
Event.Next := null;
Event.Prev := null;
end Extract;
-------------
-- Insert --
-------------
procedure Insert
(Event : not null Timing_Event_Access;
Is_First : out Boolean)
is
CPU_Id : constant CPU := Current_CPU;
Aux_Pointer : Timing_Event_Access;
begin
-- Insert at the head if there is no other events with a smaller timeout
if Events_Table (CPU_Id) = null
or else Events_Table (CPU_Id).Timeout > Event.Timeout
then
Is_First := True;
Event.Next := Events_Table (CPU_Id);
if Events_Table (CPU_Id) /= null then
Events_Table (CPU_Id).Prev := Event;
end if;
Events_Table (CPU_Id) := Event;
-- Middle or tail insertion
else
pragma Assert (Events_Table (CPU_Id) /= null);
Is_First := False;
Aux_Pointer := Events_Table (CPU_Id);
while Aux_Pointer.Next /= null
and then Aux_Pointer.Next.Timeout <= Event.Timeout
loop
Aux_Pointer := Aux_Pointer.Next;
end loop;
-- Insert after the Aux_Pointer
Event.Next := Aux_Pointer.Next;
Event.Prev := Aux_Pointer;
if Aux_Pointer.Next /= null then
Aux_Pointer.Next.Prev := Event;
end if;
Aux_Pointer.Next := Event;
end if;
end Insert;
end System.BB.Timing_Events;
|
-- { dg-do run }
-- { dg-options "-O" }
with Return4_Pkg; use Return4_Pkg;
procedure Return4 is
type Local_Rec is record
C : Character;
R : Rec;
end record;
pragma Pack (Local_Rec);
L : Local_Rec;
for L'Alignment use 2;
begin
L.R := Get_Value (0);
if L.R.I1 /= 0 then
raise Program_Error;
end if;
end;
|
-- C32111A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT WHEN A VARIABLE OR CONSTANT HAVING AN ENUMERATION,
-- INTEGER, FLOAT OR FIXED TYPE IS DECLARED WITH AN INITIAL VALUE,
-- CONSTRAINT_ERROR IS RAISED IF THE INITIAL VALUE LIES OUTSIDE THE
-- RANGE OF THE SUBTYPE.
-- HISTORY:
-- RJW 07/20/86 CREATED ORIGINAL TEST.
-- JET 08/04/87 IMPROVED DEFEAT OF COMPILER OPTIMIZATION.
WITH REPORT; USE REPORT;
PROCEDURE C32111A IS
TYPE WEEKDAY IS (MON, TUES, WED, THURS, FRI);
SUBTYPE MIDWEEK IS WEEKDAY RANGE WED .. WED;
SUBTYPE DIGIT IS CHARACTER RANGE '0' .. '9';
SUBTYPE SHORT IS INTEGER RANGE -100 .. 100;
TYPE INT IS RANGE -10 .. 10;
SUBTYPE PINT IS INT RANGE 1 .. 10;
TYPE FLT IS DIGITS 3 RANGE -5.0 .. 5.0;
SUBTYPE SFLT IS FLT RANGE -5.0 .. 0.0;
TYPE FIXED IS DELTA 0.5 RANGE -5.0 .. 5.0;
SUBTYPE SFIXED IS FIXED RANGE 0.0 .. 5.0;
BEGIN
TEST ("C32111A", "CHECK THAT WHEN A VARIABLE OR CONSTANT " &
"HAVING AN ENUMERATION, INTEGER, FLOAT OR " &
"FIXED TYPE IS DECLARED WITH AN INITIAL " &
"VALUE, CONSTRAINT_ERROR IS RAISED IF THE " &
"INITIAL VALUE LIES OUTSIDE THE RANGE OF THE " &
"SUBTYPE" );
BEGIN
DECLARE
D : MIDWEEK := WEEKDAY'VAL (IDENT_INT (1));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'D'" );
IF D = TUES THEN
COMMENT ("VARIABLE 'D' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'D'" );
END;
BEGIN
DECLARE
D : CONSTANT WEEKDAY RANGE WED .. WED :=
WEEKDAY'VAL (IDENT_INT (3));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'D'" );
IF D = TUES THEN
COMMENT ("INITIALIZE VARIABLE 'D'");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'D'" );
END;
BEGIN
DECLARE
P : CONSTANT DIGIT := IDENT_CHAR ('/');
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'P'" );
IF P = '0' THEN
COMMENT ("VARIABLE 'P' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'P'" );
END;
BEGIN
DECLARE
Q : CHARACTER RANGE 'A' .. 'E' := IDENT_CHAR ('F');
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'Q'" );
IF Q = 'A' THEN
COMMENT ("VARIABLE 'Q' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'Q'" );
END;
BEGIN
DECLARE
I : SHORT := IDENT_INT (-101);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'I'" );
IF I = 1 THEN
COMMENT ("VARIABLE 'I' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'I'" );
END;
BEGIN
DECLARE
J : CONSTANT INTEGER RANGE 0 .. 100 := IDENT_INT (101);
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'J'" );
IF J = -1 THEN
COMMENT ("VARIABLE 'J' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'J'" );
END;
BEGIN
DECLARE
K : INT RANGE 0 .. 1 := INT (IDENT_INT (2));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'K'" );
IF K = 2 THEN
COMMENT ("VARIABLE 'K' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'K'" );
END;
BEGIN
DECLARE
L : CONSTANT PINT := INT (IDENT_INT (0));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'L'" );
IF L = 1 THEN
COMMENT ("VARIABLE 'L' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'L'" );
END;
BEGIN
DECLARE
FL : SFLT := FLT (IDENT_INT (1));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'FL'" );
IF FL = 3.14 THEN
COMMENT ("VARIABLE 'FL' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'FL'" );
END;
BEGIN
DECLARE
FL1 : CONSTANT FLT RANGE 0.0 .. 0.0 :=
FLT (IDENT_INT (-1));
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'FL1'" );
IF FL1 = 0.0 THEN
COMMENT ("VARIABLE 'FL1' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'FL1'" );
END;
BEGIN
DECLARE
FI : FIXED RANGE 0.0 .. 0.0 := IDENT_INT (1) * 0.5;
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'FI'" );
IF FI = 0.5 THEN
COMMENT ("VARIABLE 'FI' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF VARIABLE 'FI'" );
END;
BEGIN
DECLARE
FI1 : CONSTANT SFIXED := IDENT_INT (-1) * 0.5;
BEGIN
FAILED ( "NO EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'FI1'" );
IF FI1 = 0.5 THEN
COMMENT ("VARIABLE 'FI1' INITIALIZED");
END IF;
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED FOR INITIALIZATION " &
"OF CONSTANT 'FI1'" );
END;
RESULT;
END C32111A;
|
--
-- (c) Copyright 1993,1994,1995,1996 Silicon Graphics, Inc.
-- ALL RIGHTS RESERVED
-- Permission to use, copy, modify, and distribute this software for
-- any purpose and without fee is hereby granted, provided that the above
-- copyright notice appear in all copies and that both the copyright notice
-- and this permission notice appear in supporting documentation, and that
-- the name of Silicon Graphics, Inc. not be used in advertising
-- or publicity pertaining to distribution of the software without specific,
-- written prior permission.
--
-- THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
-- AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
-- INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
-- FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-- GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
-- SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
-- KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
-- LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
-- THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
-- ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
-- ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
-- POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
--
-- US Government Users Restricted Rights
-- Use, duplication, or disclosure by the Government is subject to
-- restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
-- (c)(1)(ii) of the Rights in Technical Data and Computer Software
-- clause at DFARS 252.227-7013 and/or in similar or successor
-- clauses in the FAR or the DOD or NASA FAR Supplement.
-- Unpublished-- rights reserved under the copyright laws of the
-- United States. Contractor/manufacturer is Silicon Graphics,
-- Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
--
-- OpenGL(TM) is a trademark of Silicon Graphics, Inc.
--
with System; use System;
with GL; use GL;
with Ada.Numerics; use Ada.Numerics;
with Ada.Numerics.Generic_Elementary_Functions;
package body Texturesurf_Procs is
package GLdouble_GEF is new
Generic_Elementary_Functions (GLfloat);
use GLdouble_GEF;
ctrlpoints : array (0 .. 3, 0 .. 3, 0 .. 2) of aliased GLfloat :=
(((-1.5, -1.5, 4.0), (-0.5, -1.5, 2.0),
(0.5, -1.5, -1.0), (1.5, -1.5, 2.0)),
((-1.5, -0.5, 1.0), (-0.5, -0.5, 3.0),
(0.5, -0.5, 0.0), (1.5, -0.5, -1.0)),
((-1.5, 0.5, 4.0), (-0.5, 0.5, 0.0),
(0.5, 0.5, 3.0), (1.5, 0.5, 4.0)),
((-1.5, 1.5, -2.0), (-0.5, 1.5, -2.0),
(0.5, 1.5, 0.0), (1.5, 1.5, -1.0)));
texpts : array (0 .. 1, 0 .. 1, 0 .. 1) of aliased GLfloat :=
(((0.0, 0.0), (0.0, 1.0)), ((1.0, 0.0), (1.0, 1.0)));
imageWidth : constant := 64;
imageHeight : constant := 64;
image : array (Integer range 0 .. (3*imageWidth*imageHeight))
of aliased GLubyte;
procedure makeImage is
ti, tj : GLfloat;
begin
for i in 0 .. (imageWidth - 1) loop
ti := 2.0*Pi*GLfloat (i)/GLfloat (imageWidth);
for j in 0 .. (imageHeight - 1) loop
tj := 2.0*Pi*GLfloat (j)/GLfloat (imageHeight);
image (3 * (imageHeight * i + j)) :=
GLubyte (127.0 * (1.0 + Sin (ti)));
image (3 * (imageHeight * i + j) + 1) :=
GLubyte (127.0 * (1.0 + Cos (2.0 * tj)));
image (3 * (imageHeight * i + j) + 2) :=
GLubyte (127.0 * (1.0 + Cos (ti + tj)));
end loop;
end loop;
end makeImage;
procedure DoInit is
begin
glMap2f (GL_MAP2_VERTEX_3, 0.0, 1.0, 3, 4,
0.0, 1.0, 12, 4, ctrlpoints (0, 0, 0)'Access);
glMap2f (GL_MAP2_TEXTURE_COORD_2, 0.0, 1.0, 2, 2,
0.0, 1.0, 4, 2, texpts (0, 0, 0)'Access);
glEnable (GL_MAP2_TEXTURE_COORD_2);
glEnable (GL_MAP2_VERTEX_3);
glMapGrid2f (20, 0.0, 1.0, 20, 0.0, 1.0);
makeImage;
glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D (GL_TEXTURE_2D, 0, 3, imageWidth, imageHeight, 0,
GL_RGB, GL_UNSIGNED_BYTE, image(0)'Access);
glEnable (GL_TEXTURE_2D);
glEnable (GL_DEPTH_TEST);
glEnable (GL_NORMALIZE);
glShadeModel (GL_FLAT);
end DoInit;
procedure DoDisplay is
begin
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glColor3f (1.0, 1.0, 1.0);
glEvalMesh2 (GL_FILL, 0, 20, 0, 20);
glFlush;
end DoDisplay;
procedure ReshapeCallback (w : Integer; h : Integer) is
begin
glViewport (0, 0, GLsizei(w), GLsizei(h));
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
if w <= h then
glOrtho (-4.0, 4.0, GLdouble (-4.0*GLdouble (h)/GLdouble (w)),
GLdouble (4.0*GLdouble (h)/GLdouble (w)), -4.0, 4.0);
else
glOrtho ((-4.0*GLdouble (w)/GLdouble (h)),
GLdouble (4.0*GLdouble (w)/GLdouble (h)), -4.0, 4.0, -4.0, 4.0);
end if;
glMatrixMode (GL_MODELVIEW);
glLoadIdentity;
glRotatef (85.0, 1.0, 1.0, 1.0);
end ReshapeCallback;
end Texturesurf_Procs;
|
--
-- Copyright 2018 The wookey project team <wookey@ssi.gouv.fr>
-- - Ryad Benadjila
-- - Arnauld Michelizza
-- - Mathieu Renard
-- - Philippe Thierry
-- - Philippe Trebuchet
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
with ada.unchecked_conversion;
package ewok.syscalls
with spark_mode => off
is
subtype t_syscall_ret is unsigned_32;
SYS_E_DONE : constant t_syscall_ret := 0; -- Syscall succesful
SYS_E_INVAL : constant t_syscall_ret := 1; -- Invalid input data
SYS_E_DENIED : constant t_syscall_ret := 2; -- Permission is denied
SYS_E_BUSY : constant t_syscall_ret := 3;
-- Target is busy OR not enough ressources OR ressource is already used
type t_svc_type is
(SVC_SYSCALL,
SVC_TASK_DONE,
SVC_ISR_DONE)
with size => 8;
function to_svc_type is new ada.unchecked_conversion
(unsigned_8, t_svc_type);
type t_syscall_type is
(SYS_YIELD,
SYS_INIT,
SYS_IPC,
SYS_CFG,
SYS_GETTICK,
SYS_RESET,
SYS_SLEEP,
SYS_LOCK,
SYS_GET_RANDOM,
SYS_LOG)
with size => 32;
type t_syscalls_init is
(INIT_DEVACCESS,
INIT_DMA,
INIT_DMA_SHM,
INIT_GETTASKID,
INIT_DONE);
type t_syscalls_ipc is
(IPC_RECV_SYNC,
IPC_SEND_SYNC,
IPC_RECV_ASYNC,
IPC_SEND_ASYNC);
type t_syscalls_cfg is
(CFG_GPIO_SET,
CFG_GPIO_GET,
CFG_GPIO_UNLOCK_EXTI,
CFG_DMA_RECONF,
CFG_DMA_RELOAD,
CFG_DMA_DISABLE,
CFG_DEV_MAP,
CFG_DEV_UNMAP,
CFG_DEV_RELEASE);
type t_syscalls_lock is
(LOCK_ENTER,
LOCK_EXIT);
type t_syscall_parameters is record
syscall_type : t_syscall_type;
args : aliased t_parameters;
end record
with pack;
end ewok.syscalls;
|
-- WORDS, a Latin dictionary, by Colonel William Whitaker (USAF, Retired)
--
-- Copyright William A. Whitaker (1936–2010)
--
-- This is a free program, which means it is proper to copy it and pass
-- it on to your friends. Consider it a developmental item for which
-- there is no charge. However, just for form, it is Copyrighted
-- (c). Permission is hereby freely given for any and all use of program
-- and data. You can sell it as your own, but at least tell me.
--
-- This version is distributed without obligation, but the developer
-- would appreciate comments and suggestions.
--
-- All parts of the WORDS system, source code and data files, are made freely
-- available to anyone who wishes to use them, for whatever purpose.
with Latin_Utils.Inflections_Package; use Latin_Utils.Inflections_Package;
with Latin_Utils.Dictionary_Package; use Latin_Utils.Dictionary_Package;
package Support_Utils.Uniques_Package is
type Unique_Item;
type Unique_List is access Unique_Item;
type Unique_Item is
record
Stem : Stem_Type := Null_Stem_Type;
Qual : Quality_Record := Null_Quality_Record;
Kind : Kind_Entry := Null_Kind_Entry;
MNPC : Dict_IO.Count := Null_MNPC;
Succ : Unique_List;
end record;
type Latin_Uniques is array (Character range 'a' .. 'z') of Unique_List;
Null_Latin_Uniques : Latin_Uniques := (others => null);
Unq : Latin_Uniques := Null_Latin_Uniques;
type Uniques_De_Array is
array (Dict_IO.Positive_Count range <>) of Dictionary_Entry;
Uniques_De : Uniques_De_Array (1 .. 100) :=
(others => Null_Dictionary_Entry);
end Support_Utils.Uniques_Package;
|
package Problem_57 is
-- It is possible to show that the square root of two can be expressed as an
-- infinite continued fraction.
--
-- 2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
--
-- By expanding this for the first four iterations, we get:
-- 1 + 1/2 = 3/2 = 1.5
-- 1 + 1/(2 + 1/2) = 7/5 = 1.4
-- 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
-- 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
--
-- The next three expansions are 99/70, 239/169, and 577/408, but the eighth
-- expansion, 1393/985, is the first example where the number of digits in
-- the numerator exceeds the number of digits in the denominator.
--
-- In the first one-thousand expansions, how many fractions contain a
-- numerator with more digits than denominator?
procedure Solve;
end Problem_57;
|
-- BSD 3-Clause License
--
-- Copyright (c) 2017, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
--
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- * Neither the name of the 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 League.Application;
with League.Calendars.ISO_8601;
with League.String_Vectors;
with League.Strings;
with CvsWeb.Loaders;
with CvsWeb.Pushers;
procedure CvsWeb2git is
function To_Date return League.Calendars.Date_Time;
Args : constant League.String_Vectors.Universal_String_Vector :=
League.Application.Arguments;
function To_Date return League.Calendars.Date_Time is
Result : League.Calendars.Date_Time :=
League.Calendars.ISO_8601.Create
(Year => 1999,
Month => 1,
Day => 1,
Hour => 0,
Minute => 0,
Second => 0,
Nanosecond_100 => 0);
begin
if Args.Length > 2 then
declare
use League.Calendars.ISO_8601;
List : constant League.String_Vectors.Universal_String_Vector :=
Args.Element (3).Split ('.');
begin
Result := League.Calendars.ISO_8601.Create
(Year => Year_Number'Wide_Wide_Value
(List (1).To_Wide_Wide_String),
Month => Month_Number'Wide_Wide_Value
(List (2).To_Wide_Wide_String),
Day => Day_Number'Wide_Wide_Value
(List (3).To_Wide_Wide_String),
Hour => Hour_Number'Wide_Wide_Value
(List (4).To_Wide_Wide_String),
Minute => Minute_Number'Wide_Wide_Value
(List (5).To_Wide_Wide_String),
Second => Second_Number'Wide_Wide_Value
(List (6).To_Wide_Wide_String),
Nanosecond_100 => 0);
end;
end if;
return Result;
end To_Date;
URL : League.Strings.Universal_String;
Root : League.Strings.Universal_String;
Loader : CvsWeb.Loaders.Loader;
Pusher : CvsWeb.Pushers.Pusher;
begin
URL := Args.Element (1);
Root := Args.Element (2);
Loader.Initialize (URL);
Pusher.Initialize (Root);
Pusher.Push (Loader, Skip => To_Date);
end CvsWeb2git;
|
package body Arbre_Genealogique is
procedure Initialiser (Arbre : out T_Arbre_Genealogique) is
begin
Initialiser (Arbre.Registre);
Initialiser (Arbre.Graphe);
Arbre.Auto_Increment := 1;
end Initialiser;
procedure Detruire (Arbre : in out T_Arbre_Genealogique) is
begin
Detruire (Arbre.Registre);
Detruire (Arbre.Graphe);
end Detruire;
procedure Ajouter_Personne
(Arbre : in out T_Arbre_Genealogique; Personne : in T_Personne;
Cle : out Integer)
is
begin
Cle := Arbre.Auto_Increment;
Attribuer (Arbre.Registre, Cle, Personne);
Ajouter_Sommet (Arbre.Graphe, Cle);
Arbre.Auto_Increment := Arbre.Auto_Increment + 1;
end Ajouter_Personne;
function Lire_Registre
(Arbre : T_Arbre_Genealogique; Cle : Integer) return T_Personne
is
begin
return Acceder (Arbre.Registre, Cle);
end Lire_Registre;
procedure Ajouter_Relation
(Arbre : in out T_Arbre_Genealogique;
Personne_Origine : in T_Etiquette_Sommet;
Relation : in T_Etiquette_Arete;
Personne_Destination : in T_Etiquette_Sommet)
is
Chaine : T_Liste_Adjacence;
Arete : T_Arete_Etiquetee;
begin
if Personne_Destination = Personne_Origine then
raise Relation_Existante;
end if;
Chaine_Adjacence (Chaine, Arbre.Graphe, Personne_Origine);
while Adjacence_Non_Vide (Chaine) loop
Arete_Suivante (Chaine, Arete);
if Arete.Destination = Personne_Destination then
raise Relation_Existante;
end if;
end loop;
case Relation is
when A_Pour_Parent =>
Ajouter_Arete
(Arbre.Graphe, Personne_Origine, A_Pour_Parent,
Personne_Destination);
Ajouter_Arete
(Arbre.Graphe, Personne_Destination, A_Pour_Enfant,
Personne_Origine);
when A_Pour_Enfant =>
Ajouter_Arete
(Arbre.Graphe, Personne_Origine, A_Pour_Enfant,
Personne_Destination);
Ajouter_Arete
(Arbre.Graphe, Personne_Destination, A_Pour_Parent,
Personne_Origine);
when others =>
Ajouter_Arete
(Arbre.Graphe, Personne_Origine, Relation, Personne_Destination);
Ajouter_Arete
(Arbre.Graphe, Personne_Destination, Relation, Personne_Origine);
end case;
end Ajouter_Relation;
procedure Liste_Relations
(Adjacence : out T_Liste_Relations; Arbre : in T_Arbre_Genealogique;
Origine : in T_Etiquette_Sommet)
is
begin
Chaine_Adjacence (Adjacence, Arbre.Graphe, Origine);
end Liste_Relations;
function Liste_Non_Vide (Adjacence : T_Liste_Relations) return Boolean is
begin
return Adjacence_Non_Vide (Adjacence);
end Liste_Non_Vide;
procedure Relation_Suivante
(Adjacence : in out T_Liste_Relations; Arete : out T_Arete_Etiquetee)
is
begin
Arete_Suivante (Adjacence, Arete);
end Relation_Suivante;
procedure Supprimer_Relation
(Arbre : in out T_Arbre_Genealogique;
Personne_Origine : in T_Etiquette_Sommet;
Relation : in T_Etiquette_Arete;
Personne_Destination : in T_Etiquette_Sommet)
is
begin
case Relation is
when A_Pour_Parent =>
Supprimer_Arete
(Arbre.Graphe, Personne_Origine, A_Pour_Parent,
Personne_Destination);
Supprimer_Arete
(Arbre.Graphe, Personne_Destination, A_Pour_Enfant,
Personne_Origine);
when A_Pour_Enfant =>
Supprimer_Arete
(Arbre.Graphe, Personne_Origine, A_Pour_Enfant,
Personne_Destination);
Supprimer_Arete
(Arbre.Graphe, Personne_Destination, A_Pour_Parent,
Personne_Origine);
when others =>
Supprimer_Arete
(Arbre.Graphe, Personne_Origine, Relation, Personne_Destination);
Supprimer_Arete
(Arbre.Graphe, Personne_Destination, Relation, Personne_Origine);
end case;
end Supprimer_Relation;
procedure Attribuer_Registre
(Arbre : in out T_Arbre_Genealogique; Cle : in Integer;
Element : in T_Personne)
is
begin
Attribuer (Arbre.Registre, Cle, Element);
end Attribuer_Registre;
function Existe_Registre
(Arbre : T_Arbre_Genealogique; Cle : Integer) return Boolean
is
begin
return Existe (Arbre.Registre, Cle);
end Existe_Registre;
procedure Appliquer_Sur_Registre (Arbre : in out T_Arbre_Genealogique) is
procedure Appliquer is new Appliquer_Sur_Tous (P);
begin
Appliquer (Arbre.Registre);
end Appliquer_Sur_Registre;
procedure Appliquer_Sur_Graphe (Arbre : in out T_Arbre_Genealogique) is
procedure Appliquer is new Appliquer_Sur_Tous_Sommets (P);
begin
Appliquer (Arbre.Graphe);
end Appliquer_Sur_Graphe;
end Arbre_Genealogique;
|
package body Plop is
function Ping(i: in Integer) return Integer is
begin
return i+1;
end Ping;
end Plop;
|
------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- Sample.Function_Key_Setting --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998,2004 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer, 1996
-- Version Control
-- $Revision: 1.13 $
-- $Date: 2004/08/21 21:37:00 $
-- Binding Version 01.00
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Sample.Manifest; use Sample.Manifest;
-- This package implements a simple stack of function key label environments.
--
package body Sample.Function_Key_Setting is
Max_Label_Length : constant Positive := 8;
Number_Of_Keys : Label_Number := Label_Number'Last;
Justification : Label_Justification := Left;
subtype Label is String (1 .. Max_Label_Length);
type Label_Array is array (Label_Number range <>) of Label;
type Key_Environment (N : Label_Number := Label_Number'Last);
type Env_Ptr is access Key_Environment;
pragma Controlled (Env_Ptr);
type String_Access is access String;
pragma Controlled (String_Access);
Active_Context : String_Access := new String'("MAIN");
Active_Notepad : Panel := Null_Panel;
type Key_Environment (N : Label_Number := Label_Number'Last) is
record
Prev : Env_Ptr;
Help : String_Access;
Notepad : Panel;
Labels : Label_Array (1 .. N);
end record;
procedure Release_String is
new Ada.Unchecked_Deallocation (String,
String_Access);
procedure Release_Environment is
new Ada.Unchecked_Deallocation (Key_Environment,
Env_Ptr);
Top_Of_Stack : Env_Ptr := null;
procedure Push_Environment (Key : in String;
Reset : in Boolean := True)
is
P : constant Env_Ptr := new Key_Environment (Number_Of_Keys);
begin
-- Store the current labels in the environment
for I in 1 .. Number_Of_Keys loop
Get_Soft_Label_Key (I, P.Labels (I));
if Reset then
Set_Soft_Label_Key (I, " ");
end if;
end loop;
P.Prev := Top_Of_Stack;
-- now store active help context and notepad
P.Help := Active_Context;
P.Notepad := Active_Notepad;
-- The notepad must now vanish and the new notepad is empty.
if P.Notepad /= Null_Panel then
Hide (P.Notepad);
Update_Panels;
end if;
Active_Notepad := Null_Panel;
Active_Context := new String'(Key);
Top_Of_Stack := P;
if Reset then
Refresh_Soft_Label_Keys_Without_Update;
end if;
end Push_Environment;
procedure Pop_Environment
is
P : Env_Ptr := Top_Of_Stack;
begin
if Top_Of_Stack = null then
raise Function_Key_Stack_Error;
else
for I in 1 .. Number_Of_Keys loop
Set_Soft_Label_Key (I, P.Labels (I), Justification);
end loop;
pragma Assert (Active_Context /= null);
Release_String (Active_Context);
Active_Context := P.Help;
Refresh_Soft_Label_Keys_Without_Update;
Notepad_To_Context (P.Notepad);
Top_Of_Stack := P.Prev;
Release_Environment (P);
end if;
end Pop_Environment;
function Context return String
is
begin
if Active_Context /= null then
return Active_Context.all;
else
return "";
end if;
end Context;
function Find_Context (Key : String) return Boolean
is
P : Env_Ptr := Top_Of_Stack;
begin
if Active_Context.all = Key then
return True;
else
loop
exit when P = null;
if P.Help.all = Key then
return True;
else
P := P.Prev;
end if;
end loop;
return False;
end if;
end Find_Context;
procedure Notepad_To_Context (Pan : in Panel)
is
W : Window;
begin
if Active_Notepad /= Null_Panel then
W := Get_Window (Active_Notepad);
Clear (W);
Delete (Active_Notepad);
Delete (W);
end if;
Active_Notepad := Pan;
if Pan /= Null_Panel then
Top (Pan);
end if;
Update_Panels;
Update_Screen;
end Notepad_To_Context;
procedure Initialize (Mode : Soft_Label_Key_Format := PC_Style;
Just : Label_Justification := Left)
is
begin
case Mode is
when PC_Style .. PC_Style_With_Index
=> Number_Of_Keys := 12;
when others
=> Number_Of_Keys := 8;
end case;
Init_Soft_Label_Keys (Mode);
Justification := Just;
end Initialize;
procedure Default_Labels
is
begin
Set_Soft_Label_Key (FKEY_QUIT, "Quit");
Set_Soft_Label_Key (FKEY_HELP, "Help");
Set_Soft_Label_Key (FKEY_EXPLAIN, "Keys");
Refresh_Soft_Label_Keys_Without_Update;
end Default_Labels;
function Notepad_Window return Window
is
begin
if Active_Notepad /= Null_Panel then
return Get_Window (Active_Notepad);
else
return Null_Window;
end if;
end Notepad_Window;
end Sample.Function_Key_Setting;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- G N A T . S P I T B O L . P A T T E R N S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-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. --
-- --
------------------------------------------------------------------------------
-- Note: the data structures and general approach used in this implementation
-- are derived from the original MINIMAL sources for SPITBOL. The code is not
-- a direct translation, but the approach is followed closely. In particular,
-- we use the one stack approach developed in the SPITBOL implementation.
with Ada.Strings.Unbounded.Aux; use Ada.Strings.Unbounded.Aux;
with GNAT.Debug_Utilities; use GNAT.Debug_Utilities;
with System; use System;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
package body GNAT.Spitbol.Patterns is
------------------------
-- Internal Debugging --
------------------------
Internal_Debug : constant Boolean := False;
-- Set this flag to True to activate some built-in debugging traceback
-- These are all lines output with PutD and Put_LineD.
procedure New_LineD;
pragma Inline (New_LineD);
-- Output new blank line with New_Line if Internal_Debug is True
procedure PutD (Str : String);
pragma Inline (PutD);
-- Output string with Put if Internal_Debug is True
procedure Put_LineD (Str : String);
pragma Inline (Put_LineD);
-- Output string with Put_Line if Internal_Debug is True
-----------------------------
-- Local Type Declarations --
-----------------------------
subtype String_Ptr is Ada.Strings.Unbounded.String_Access;
subtype File_Ptr is Ada.Text_IO.File_Access;
function To_Address is new Ada.Unchecked_Conversion (PE_Ptr, Address);
-- Used only for debugging output purposes
subtype AFC is Ada.Finalization.Controlled;
N : constant PE_Ptr := null;
-- Shorthand used to initialize Copy fields to null
type Natural_Ptr is access all Natural;
type Pattern_Ptr is access all Pattern;
--------------------------------------------------
-- Description of Algorithm and Data Structures --
--------------------------------------------------
-- A pattern structure is represented as a linked graph of nodes
-- with the following structure:
-- +------------------------------------+
-- I Pcode I
-- +------------------------------------+
-- I Index I
-- +------------------------------------+
-- I Pthen I
-- +------------------------------------+
-- I parameter(s) I
-- +------------------------------------+
-- Pcode is a code value indicating the type of the pattern node. This
-- code is used both as the discriminant value for the record, and as
-- the case index in the main match routine that branches to the proper
-- match code for the given element.
-- Index is a serial index number. The use of these serial index
-- numbers is described in a separate section.
-- Pthen is a pointer to the successor node, i.e the node to be matched
-- if the attempt to match the node succeeds. If this is the last node
-- of the pattern to be matched, then Pthen points to a dummy node
-- of kind PC_EOP (end of pattern), which initializes pattern exit.
-- The parameter or parameters are present for certain node types,
-- and the type varies with the pattern code.
type Pattern_Code is (
PC_Arb_Y,
PC_Assign,
PC_Bal,
PC_BreakX_X,
PC_Cancel,
PC_EOP,
PC_Fail,
PC_Fence,
PC_Fence_X,
PC_Fence_Y,
PC_R_Enter,
PC_R_Remove,
PC_R_Restore,
PC_Rest,
PC_Succeed,
PC_Unanchored,
PC_Alt,
PC_Arb_X,
PC_Arbno_S,
PC_Arbno_X,
PC_Rpat,
PC_Pred_Func,
PC_Assign_Imm,
PC_Assign_OnM,
PC_Any_VP,
PC_Break_VP,
PC_BreakX_VP,
PC_NotAny_VP,
PC_NSpan_VP,
PC_Span_VP,
PC_String_VP,
PC_Write_Imm,
PC_Write_OnM,
PC_Null,
PC_String,
PC_String_2,
PC_String_3,
PC_String_4,
PC_String_5,
PC_String_6,
PC_Setcur,
PC_Any_CH,
PC_Break_CH,
PC_BreakX_CH,
PC_Char,
PC_NotAny_CH,
PC_NSpan_CH,
PC_Span_CH,
PC_Any_CS,
PC_Break_CS,
PC_BreakX_CS,
PC_NotAny_CS,
PC_NSpan_CS,
PC_Span_CS,
PC_Arbno_Y,
PC_Len_Nat,
PC_Pos_Nat,
PC_RPos_Nat,
PC_RTab_Nat,
PC_Tab_Nat,
PC_Pos_NF,
PC_Len_NF,
PC_RPos_NF,
PC_RTab_NF,
PC_Tab_NF,
PC_Pos_NP,
PC_Len_NP,
PC_RPos_NP,
PC_RTab_NP,
PC_Tab_NP,
PC_Any_VF,
PC_Break_VF,
PC_BreakX_VF,
PC_NotAny_VF,
PC_NSpan_VF,
PC_Span_VF,
PC_String_VF);
type IndexT is range 0 .. +(2 **15 - 1);
type PE (Pcode : Pattern_Code) is record
Index : IndexT;
-- Serial index number of pattern element within pattern
Pthen : PE_Ptr;
-- Successor element, to be matched after this one
case Pcode is
when PC_Arb_Y
| PC_Assign
| PC_Bal
| PC_BreakX_X
| PC_Cancel
| PC_EOP
| PC_Fail
| PC_Fence
| PC_Fence_X
| PC_Fence_Y
| PC_Null
| PC_R_Enter
| PC_R_Remove
| PC_R_Restore
| PC_Rest
| PC_Succeed
| PC_Unanchored
=>
null;
when PC_Alt
| PC_Arb_X
| PC_Arbno_S
| PC_Arbno_X
=>
Alt : PE_Ptr;
when PC_Rpat =>
PP : Pattern_Ptr;
when PC_Pred_Func =>
BF : Boolean_Func;
when PC_Assign_Imm
| PC_Assign_OnM
| PC_Any_VP
| PC_Break_VP
| PC_BreakX_VP
| PC_NotAny_VP
| PC_NSpan_VP
| PC_Span_VP
| PC_String_VP
=>
VP : VString_Ptr;
when PC_Write_Imm
| PC_Write_OnM
=>
FP : File_Ptr;
when PC_String =>
Str : String_Ptr;
when PC_String_2 =>
Str2 : String (1 .. 2);
when PC_String_3 =>
Str3 : String (1 .. 3);
when PC_String_4 =>
Str4 : String (1 .. 4);
when PC_String_5 =>
Str5 : String (1 .. 5);
when PC_String_6 =>
Str6 : String (1 .. 6);
when PC_Setcur =>
Var : Natural_Ptr;
when PC_Any_CH
| PC_Break_CH
| PC_BreakX_CH
| PC_Char
| PC_NotAny_CH
| PC_NSpan_CH
| PC_Span_CH
=>
Char : Character;
when PC_Any_CS
| PC_Break_CS
| PC_BreakX_CS
| PC_NotAny_CS
| PC_NSpan_CS
| PC_Span_CS
=>
CS : Character_Set;
when PC_Arbno_Y
| PC_Len_Nat
| PC_Pos_Nat
| PC_RPos_Nat
| PC_RTab_Nat
| PC_Tab_Nat
=>
Nat : Natural;
when PC_Pos_NF
| PC_Len_NF
| PC_RPos_NF
| PC_RTab_NF
| PC_Tab_NF
=>
NF : Natural_Func;
when PC_Pos_NP
| PC_Len_NP
| PC_RPos_NP
| PC_RTab_NP
| PC_Tab_NP
=>
NP : Natural_Ptr;
when PC_Any_VF
| PC_Break_VF
| PC_BreakX_VF
| PC_NotAny_VF
| PC_NSpan_VF
| PC_Span_VF
| PC_String_VF
=>
VF : VString_Func;
end case;
end record;
subtype PC_Has_Alt is Pattern_Code range PC_Alt .. PC_Arbno_X;
-- Range of pattern codes that has an Alt field. This is used in the
-- recursive traversals, since these links must be followed.
EOP_Element : aliased constant PE := (PC_EOP, 0, N);
-- This is the end of pattern element, and is thus the representation of
-- a null pattern. It has a zero index element since it is never placed
-- inside a pattern. Furthermore it does not need a successor, since it
-- marks the end of the pattern, so that no more successors are needed.
EOP : constant PE_Ptr := EOP_Element'Unrestricted_Access;
-- This is the end of pattern pointer, that is used in the Pthen pointer
-- of other nodes to signal end of pattern.
-- The following array is used to determine if a pattern used as an
-- argument for Arbno is eligible for treatment using the simple Arbno
-- structure (i.e. it is a pattern that is guaranteed to match at least
-- one character on success, and not to make any entries on the stack.
OK_For_Simple_Arbno : constant array (Pattern_Code) of Boolean :=
(PC_Any_CS |
PC_Any_CH |
PC_Any_VF |
PC_Any_VP |
PC_Char |
PC_Len_Nat |
PC_NotAny_CS |
PC_NotAny_CH |
PC_NotAny_VF |
PC_NotAny_VP |
PC_Span_CS |
PC_Span_CH |
PC_Span_VF |
PC_Span_VP |
PC_String |
PC_String_2 |
PC_String_3 |
PC_String_4 |
PC_String_5 |
PC_String_6 => True,
others => False);
-------------------------------
-- The Pattern History Stack --
-------------------------------
-- The pattern history stack is used for controlling backtracking when
-- a match fails. The idea is to stack entries that give a cursor value
-- to be restored, and a node to be reestablished as the current node to
-- attempt an appropriate rematch operation. The processing for a pattern
-- element that has rematch alternatives pushes an appropriate entry or
-- entry on to the stack, and the proceeds. If a match fails at any point,
-- the top element of the stack is popped off, resetting the cursor and
-- the match continues by accessing the node stored with this entry.
type Stack_Entry is record
Cursor : Integer;
-- Saved cursor value that is restored when this entry is popped
-- from the stack if a match attempt fails. Occasionally, this
-- field is used to store a history stack pointer instead of a
-- cursor. Such cases are noted in the documentation and the value
-- stored is negative since stack pointer values are always negative.
Node : PE_Ptr;
-- This pattern element reference is reestablished as the current
-- Node to be matched (which will attempt an appropriate rematch).
end record;
subtype Stack_Range is Integer range -Stack_Size .. -1;
type Stack_Type is array (Stack_Range) of Stack_Entry;
-- The type used for a history stack. The actual instance of the stack
-- is declared as a local variable in the Match routine, to properly
-- handle recursive calls to Match. All stack pointer values are negative
-- to distinguish them from normal cursor values.
-- Note: the pattern matching stack is used only to handle backtracking.
-- If no backtracking occurs, its entries are never accessed, and never
-- popped off, and in particular it is normal for a successful match
-- to terminate with entries on the stack that are simply discarded.
-- Note: in subsequent diagrams of the stack, we always place element
-- zero (the deepest element) at the top of the page, then build the
-- stack down on the page with the most recent (top of stack) element
-- being the bottom-most entry on the page.
-- Stack checking is handled by labeling every pattern with the maximum
-- number of stack entries that are required, so a single check at the
-- start of matching the pattern suffices. There are two exceptions.
-- First, the count does not include entries for recursive pattern
-- references. Such recursions must therefore perform a specific
-- stack check with respect to the number of stack entries required
-- by the recursive pattern that is accessed and the amount of stack
-- that remains unused.
-- Second, the count includes only one iteration of an Arbno pattern,
-- so a specific check must be made on subsequent iterations that there
-- is still enough stack space left. The Arbno node has a field that
-- records the number of stack entries required by its argument for
-- this purpose.
---------------------------------------------------
-- Use of Serial Index Field in Pattern Elements --
---------------------------------------------------
-- The serial index numbers for the pattern elements are assigned as
-- a pattern is constructed from its constituent elements. Note that there
-- is never any sharing of pattern elements between patterns (copies are
-- always made), so the serial index numbers are unique to a particular
-- pattern as referenced from the P field of a value of type Pattern.
-- The index numbers meet three separate invariants, which are used for
-- various purposes as described in this section.
-- First, the numbers uniquely identify the pattern elements within a
-- pattern. If Num is the number of elements in a given pattern, then
-- the serial index numbers for the elements of this pattern will range
-- from 1 .. Num, so that each element has a separate value.
-- The purpose of this assignment is to provide a convenient auxiliary
-- data structure mechanism during operations which must traverse a
-- pattern (e.g. copy and finalization processing). Once constructed
-- patterns are strictly read only. This is necessary to allow sharing
-- of patterns between tasks. This means that we cannot go marking the
-- pattern (e.g. with a visited bit). Instead we construct a separate
-- vector that contains the necessary information indexed by the Index
-- values in the pattern elements. For this purpose the only requirement
-- is that they be uniquely assigned.
-- Second, the pattern element referenced directly, i.e. the leading
-- pattern element, is always the maximum numbered element and therefore
-- indicates the total number of elements in the pattern. More precisely,
-- the element referenced by the P field of a pattern value, or the
-- element returned by any of the internal pattern construction routines
-- in the body (that return a value of type PE_Ptr) always is this
-- maximum element,
-- The purpose of this requirement is to allow an immediate determination
-- of the number of pattern elements within a pattern. This is used to
-- properly size the vectors used to contain auxiliary information for
-- traversal as described above.
-- Third, as compound pattern structures are constructed, the way in which
-- constituent parts of the pattern are constructed is stylized. This is
-- an automatic consequence of the way that these compound structures
-- are constructed, and basically what we are doing is simply documenting
-- and specifying the natural result of the pattern construction. The
-- section describing compound pattern structures gives details of the
-- numbering of each compound pattern structure.
-- The purpose of specifying the stylized numbering structures for the
-- compound patterns is to help simplify the processing in the Image
-- function, since it eases the task of retrieving the original recursive
-- structure of the pattern from the flat graph structure of elements.
-- This use in the Image function is the only point at which the code
-- makes use of the stylized structures.
type Ref_Array is array (IndexT range <>) of PE_Ptr;
-- This type is used to build an array whose N'th entry references the
-- element in a pattern whose Index value is N. See Build_Ref_Array.
procedure Build_Ref_Array (E : PE_Ptr; RA : out Ref_Array);
-- Given a pattern element which is the leading element of a pattern
-- structure, and a Ref_Array with bounds 1 .. E.Index, fills in the
-- Ref_Array so that its N'th entry references the element of the
-- referenced pattern whose Index value is N.
-------------------------------
-- Recursive Pattern Matches --
-------------------------------
-- The pattern primitive (+P) where P is a Pattern_Ptr or Pattern_Func
-- causes a recursive pattern match. This cannot be handled by an actual
-- recursive call to the outer level Match routine, since this would not
-- allow for possible backtracking into the region matched by the inner
-- pattern. Indeed this is the classical clash between recursion and
-- backtracking, and a simple recursive stack structure does not suffice.
-- This section describes how this recursion and the possible associated
-- backtracking is handled. We still use a single stack, but we establish
-- the concept of nested regions on this stack, each of which has a stack
-- base value pointing to the deepest stack entry of the region. The base
-- value for the outer level is zero.
-- When a recursive match is established, two special stack entries are
-- made. The first entry is used to save the original node that starts
-- the recursive match. This is saved so that the successor field of
-- this node is accessible at the end of the match, but it is never
-- popped and executed.
-- The second entry corresponds to a standard new region action. A
-- PC_R_Remove node is stacked, whose cursor field is used to store
-- the outer stack base, and the stack base is reset to point to
-- this PC_R_Remove node. Then the recursive pattern is matched and
-- it can make history stack entries in the normal matter, so now
-- the stack looks like:
-- (stack entries made by outer level)
-- (Special entry, node is (+P) successor
-- cursor entry is not used)
-- (PC_R_Remove entry, "cursor" value is (negative) <-- Stack base
-- saved base value for the enclosing region)
-- (stack entries made by inner level)
-- If a subsequent failure occurs and pops the PC_R_Remove node, it
-- removes itself and the special entry immediately underneath it,
-- restores the stack base value for the enclosing region, and then
-- again signals failure to look for alternatives that were stacked
-- before the recursion was initiated.
-- Now we need to consider what happens if the inner pattern succeeds, as
-- signalled by accessing the special PC_EOP pattern primitive. First we
-- recognize the nested case by looking at the Base value. If this Base
-- value is Stack'First, then the entire match has succeeded, but if the
-- base value is greater than Stack'First, then we have successfully
-- matched an inner pattern, and processing continues at the outer level.
-- There are two cases. The simple case is when the inner pattern has made
-- no stack entries, as recognized by the fact that the current stack
-- pointer is equal to the current base value. In this case it is fine to
-- remove all trace of the recursion by restoring the outer base value and
-- using the special entry to find the appropriate successor node.
-- The more complex case arises when the inner match does make stack
-- entries. In this case, the PC_EOP processing stacks a special entry
-- whose cursor value saves the saved inner base value (the one that
-- references the corresponding PC_R_Remove value), and whose node
-- pointer references a PC_R_Restore node, so the stack looks like:
-- (stack entries made by outer level)
-- (Special entry, node is (+P) successor,
-- cursor entry is not used)
-- (PC_R_Remove entry, "cursor" value is (negative)
-- saved base value for the enclosing region)
-- (stack entries made by inner level)
-- (PC_Region_Replace entry, "cursor" value is (negative)
-- stack pointer value referencing the PC_R_Remove entry).
-- If the entire match succeeds, then these stack entries are, as usual,
-- ignored and abandoned. If on the other hand a subsequent failure
-- causes the PC_Region_Replace entry to be popped, it restores the
-- inner base value from its saved "cursor" value and then fails again.
-- Note that it is OK that the cursor is temporarily clobbered by this
-- pop, since the second failure will reestablish a proper cursor value.
---------------------------------
-- Compound Pattern Structures --
---------------------------------
-- This section discusses the compound structures used to represent
-- constructed patterns. It shows the graph structures of pattern
-- elements that are constructed, and in the case of patterns that
-- provide backtracking possibilities, describes how the history
-- stack is used to control the backtracking. Finally, it notes the
-- way in which the Index numbers are assigned to the structure.
-- In all diagrams, solid lines (built with minus signs or vertical
-- bars, represent successor pointers (Pthen fields) with > or V used
-- to indicate the direction of the pointer. The initial node of the
-- structure is in the upper left of the diagram. A dotted line is an
-- alternative pointer from the element above it to the element below
-- it. See individual sections for details on how alternatives are used.
-------------------
-- Concatenation --
-------------------
-- In the pattern structures listed in this section, a line that looks
-- like ----> with nothing to the right indicates an end of pattern
-- (EOP) pointer that represents the end of the match.
-- When a pattern concatenation (L & R) occurs, the resulting structure
-- is obtained by finding all such EOP pointers in L, and replacing
-- them to point to R. This is the most important flattening that
-- occurs in constructing a pattern, and it means that the pattern
-- matching circuitry does not have to keep track of the structure
-- of a pattern with respect to concatenation, since the appropriate
-- successor is always at hand.
-- Concatenation itself generates no additional possibilities for
-- backtracking, but the constituent patterns of the concatenated
-- structure will make stack entries as usual. The maximum amount
-- of stack required by the structure is thus simply the sum of the
-- maximums required by L and R.
-- The index numbering of a concatenation structure works by leaving
-- the numbering of the right hand pattern, R, unchanged and adjusting
-- the numbers in the left hand pattern, L up by the count of elements
-- in R. This ensures that the maximum numbered element is the leading
-- element as required (given that it was the leading element in L).
-----------------
-- Alternation --
-----------------
-- A pattern (L or R) constructs the structure:
-- +---+ +---+
-- | A |---->| L |---->
-- +---+ +---+
-- .
-- .
-- +---+
-- | R |---->
-- +---+
-- The A element here is a PC_Alt node, and the dotted line represents
-- the contents of the Alt field. When the PC_Alt element is matched,
-- it stacks a pointer to the leading element of R on the history stack
-- so that on subsequent failure, a match of R is attempted.
-- The A node is the highest numbered element in the pattern. The
-- original index numbers of R are unchanged, but the index numbers
-- of the L pattern are adjusted up by the count of elements in R.
-- Note that the difference between the index of the L leading element
-- the index of the R leading element (after building the alt structure)
-- indicates the number of nodes in L, and this is true even after the
-- structure is incorporated into some larger structure. For example,
-- if the A node has index 16, and L has index 15 and R has index
-- 5, then we know that L has 10 (15-5) elements in it.
-- Suppose that we now concatenate this structure to another pattern
-- with 9 elements in it. We will now have the A node with an index
-- of 25, L with an index of 24 and R with an index of 14. We still
-- know that L has 10 (24-14) elements in it, numbered 15-24, and
-- consequently the successor of the alternation structure has an
-- index with a value less than 15. This is used in Image to figure
-- out the original recursive structure of a pattern.
-- To clarify the interaction of the alternation and concatenation
-- structures, here is a more complex example of the structure built
-- for the pattern:
-- (V or W or X) (Y or Z)
-- where A,B,C,D,E are all single element patterns:
-- +---+ +---+ +---+ +---+
-- I A I---->I V I---+-->I A I---->I Y I---->
-- +---+ +---+ I +---+ +---+
-- . I .
-- . I .
-- +---+ +---+ I +---+
-- I A I---->I W I-->I I Z I---->
-- +---+ +---+ I +---+
-- . I
-- . I
-- +---+ I
-- I X I------------>+
-- +---+
-- The numbering of the nodes would be as follows:
-- +---+ +---+ +---+ +---+
-- I 8 I---->I 7 I---+-->I 3 I---->I 2 I---->
-- +---+ +---+ I +---+ +---+
-- . I .
-- . I .
-- +---+ +---+ I +---+
-- I 6 I---->I 5 I-->I I 1 I---->
-- +---+ +---+ I +---+
-- . I
-- . I
-- +---+ I
-- I 4 I------------>+
-- +---+
-- Note: The above structure actually corresponds to
-- (A or (B or C)) (D or E)
-- rather than
-- ((A or B) or C) (D or E)
-- which is the more natural interpretation, but in fact alternation
-- is associative, and the construction of an alternative changes the
-- left grouped pattern to the right grouped pattern in any case, so
-- that the Image function produces a more natural looking output.
---------
-- Arb --
---------
-- An Arb pattern builds the structure
-- +---+
-- | X |---->
-- +---+
-- .
-- .
-- +---+
-- | Y |---->
-- +---+
-- The X node is a PC_Arb_X node, which matches null, and stacks a
-- pointer to Y node, which is the PC_Arb_Y node that matches one
-- extra character and restacks itself.
-- The PC_Arb_X node is numbered 2, and the PC_Arb_Y node is 1
-------------------------
-- Arbno (simple case) --
-------------------------
-- The simple form of Arbno can be used where the pattern always
-- matches at least one character if it succeeds, and it is known
-- not to make any history stack entries. In this case, Arbno (P)
-- can construct the following structure:
-- +-------------+
-- | ^
-- V |
-- +---+ |
-- | S |----> |
-- +---+ |
-- . |
-- . |
-- +---+ |
-- | P |---------->+
-- +---+
-- The S (PC_Arbno_S) node matches null stacking a pointer to the
-- pattern P. If a subsequent failure causes P to be matched and
-- this match succeeds, then node A gets restacked to try another
-- instance if needed by a subsequent failure.
-- The node numbering of the constituent pattern P is not affected.
-- The S node has a node number of P.Index + 1.
--------------------------
-- Arbno (complex case) --
--------------------------
-- A call to Arbno (P), where P can match null (or at least is not
-- known to require a non-null string) and/or P requires pattern stack
-- entries, constructs the following structure:
-- +--------------------------+
-- | ^
-- V |
-- +---+ |
-- | X |----> |
-- +---+ |
-- . |
-- . |
-- +---+ +---+ +---+ |
-- | E |---->| P |---->| Y |--->+
-- +---+ +---+ +---+
-- The node X (PC_Arbno_X) matches null, stacking a pointer to the
-- E-P-X structure used to match one Arbno instance.
-- Here E is the PC_R_Enter node which matches null and creates two
-- stack entries. The first is a special entry whose node field is
-- not used at all, and whose cursor field has the initial cursor.
-- The second entry corresponds to a standard new region action. A
-- PC_R_Remove node is stacked, whose cursor field is used to store
-- the outer stack base, and the stack base is reset to point to
-- this PC_R_Remove node. Then the pattern P is matched, and it can
-- make history stack entries in the normal manner, so now the stack
-- looks like:
-- (stack entries made before assign pattern)
-- (Special entry, node field not used,
-- used only to save initial cursor)
-- (PC_R_Remove entry, "cursor" value is (negative) <-- Stack Base
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- If the match of P fails, then the PC_R_Remove entry is popped and
-- it removes both itself and the special entry underneath it,
-- restores the outer stack base, and signals failure.
-- If the match of P succeeds, then node Y, the PC_Arbno_Y node, pops
-- the inner region. There are two possibilities. If matching P left
-- no stack entries, then all traces of the inner region can be removed.
-- If there are stack entries, then we push an PC_Region_Replace stack
-- entry whose "cursor" value is the inner stack base value, and then
-- restore the outer stack base value, so the stack looks like:
-- (stack entries made before assign pattern)
-- (Special entry, node field not used,
-- used only to save initial cursor)
-- (PC_R_Remove entry, "cursor" value is (negative)
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- (PC_Region_Replace entry, "cursor" value is (negative)
-- stack pointer value referencing the PC_R_Remove entry).
-- Now that we have matched another instance of the Arbno pattern,
-- we need to move to the successor. There are two cases. If the
-- Arbno pattern matched null, then there is no point in seeking
-- alternatives, since we would just match a whole bunch of nulls.
-- In this case we look through the alternative node, and move
-- directly to its successor (i.e. the successor of the Arbno
-- pattern). If on the other hand a non-null string was matched,
-- we simply follow the successor to the alternative node, which
-- sets up for another possible match of the Arbno pattern.
-- As noted in the section on stack checking, the stack count (and
-- hence the stack check) for a pattern includes only one iteration
-- of the Arbno pattern. To make sure that multiple iterations do not
-- overflow the stack, the Arbno node saves the stack count required
-- by a single iteration, and the Concat function increments this to
-- include stack entries required by any successor. The PC_Arbno_Y
-- node uses this count to ensure that sufficient stack remains
-- before proceeding after matching each new instance.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the Y node is numbered N + 1,
-- the E node is N + 2, and the X node is N + 3.
----------------------
-- Assign Immediate --
----------------------
-- Immediate assignment (P * V) constructs the following structure
-- +---+ +---+ +---+
-- | E |---->| P |---->| A |---->
-- +---+ +---+ +---+
-- Here E is the PC_R_Enter node which matches null and creates two
-- stack entries. The first is a special entry whose node field is
-- not used at all, and whose cursor field has the initial cursor.
-- The second entry corresponds to a standard new region action. A
-- PC_R_Remove node is stacked, whose cursor field is used to store
-- the outer stack base, and the stack base is reset to point to
-- this PC_R_Remove node. Then the pattern P is matched, and it can
-- make history stack entries in the normal manner, so now the stack
-- looks like:
-- (stack entries made before assign pattern)
-- (Special entry, node field not used,
-- used only to save initial cursor)
-- (PC_R_Remove entry, "cursor" value is (negative) <-- Stack Base
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- If the match of P fails, then the PC_R_Remove entry is popped
-- and it removes both itself and the special entry underneath it,
-- restores the outer stack base, and signals failure.
-- If the match of P succeeds, then node A, which is the actual
-- PC_Assign_Imm node, executes the assignment (using the stack
-- base to locate the entry with the saved starting cursor value),
-- and the pops the inner region. There are two possibilities, if
-- matching P left no stack entries, then all traces of the inner
-- region can be removed. If there are stack entries, then we push
-- an PC_Region_Replace stack entry whose "cursor" value is the
-- inner stack base value, and then restore the outer stack base
-- value, so the stack looks like:
-- (stack entries made before assign pattern)
-- (Special entry, node field not used,
-- used only to save initial cursor)
-- (PC_R_Remove entry, "cursor" value is (negative)
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- (PC_Region_Replace entry, "cursor" value is the (negative)
-- stack pointer value referencing the PC_R_Remove entry).
-- If a subsequent failure occurs, the PC_Region_Replace node restores
-- the inner stack base value and signals failure to explore rematches
-- of the pattern P.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the A node is numbered N + 1,
-- and the E node is N + 2.
---------------------
-- Assign On Match --
---------------------
-- The assign on match (**) pattern is quite similar to the assign
-- immediate pattern, except that the actual assignment has to be
-- delayed. The following structure is constructed:
-- +---+ +---+ +---+
-- | E |---->| P |---->| A |---->
-- +---+ +---+ +---+
-- The operation of this pattern is identical to that described above
-- for deferred assignment, up to the point where P has been matched.
-- The A node, which is the PC_Assign_OnM node first pushes a
-- PC_Assign node onto the history stack. This node saves the ending
-- cursor and acts as a flag for the final assignment, as further
-- described below.
-- It then stores a pointer to itself in the special entry node field.
-- This was otherwise unused, and is now used to retrieve the address
-- of the variable to be assigned at the end of the pattern.
-- After that the inner region is terminated in the usual manner,
-- by stacking a PC_R_Restore entry as described for the assign
-- immediate case. Note that the optimization of completely
-- removing the inner region does not happen in this case, since
-- we have at least one stack entry (the PC_Assign one we just made).
-- The stack now looks like:
-- (stack entries made before assign pattern)
-- (Special entry, node points to copy of
-- the PC_Assign_OnM node, and the
-- cursor field saves the initial cursor).
-- (PC_R_Remove entry, "cursor" value is (negative)
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- (PC_Assign entry, saves final cursor)
-- (PC_Region_Replace entry, "cursor" value is (negative)
-- stack pointer value referencing the PC_R_Remove entry).
-- If a subsequent failure causes the PC_Assign node to execute it
-- simply removes itself and propagates the failure.
-- If the match succeeds, then the history stack is scanned for
-- PC_Assign nodes, and the assignments are executed (examination
-- of the above diagram will show that all the necessary data is
-- at hand for the assignment).
-- To optimize the common case where no assign-on-match operations
-- are present, a global flag Assign_OnM is maintained which is
-- initialize to False, and gets set True as part of the execution
-- of the PC_Assign_OnM node. The scan of the history stack for
-- PC_Assign entries is done only if this flag is set.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the A node is numbered N + 1,
-- and the E node is N + 2.
---------
-- Bal --
---------
-- Bal builds a single node:
-- +---+
-- | B |---->
-- +---+
-- The node B is the PC_Bal node which matches a parentheses balanced
-- string, starting at the current cursor position. It then updates
-- the cursor past this matched string, and stacks a pointer to itself
-- with this updated cursor value on the history stack, to extend the
-- matched string on a subsequent failure.
-- Since this is a single node it is numbered 1 (the reason we include
-- it in the compound patterns section is that it backtracks).
------------
-- BreakX --
------------
-- BreakX builds the structure
-- +---+ +---+
-- | B |---->| A |---->
-- +---+ +---+
-- ^ .
-- | .
-- | +---+
-- +<------| X |
-- +---+
-- Here the B node is the BreakX_xx node that performs a normal Break
-- function. The A node is an alternative (PC_Alt) node that matches
-- null, but stacks a pointer to node X (the PC_BreakX_X node) which
-- extends the match one character (to eat up the previously detected
-- break character), and then rematches the break.
-- The B node is numbered 3, the alternative node is 1, and the X
-- node is 2.
-----------
-- Fence --
-----------
-- Fence builds a single node:
-- +---+
-- | F |---->
-- +---+
-- The element F, PC_Fence, matches null, and stacks a pointer to a
-- PC_Cancel element which will abort the match on a subsequent failure.
-- Since this is a single element it is numbered 1 (the reason we
-- include it in the compound patterns section is that it backtracks).
--------------------
-- Fence Function --
--------------------
-- A call to the Fence function builds the structure:
-- +---+ +---+ +---+
-- | E |---->| P |---->| X |---->
-- +---+ +---+ +---+
-- Here E is the PC_R_Enter node which matches null and creates two
-- stack entries. The first is a special entry which is not used at
-- all in the fence case (it is present merely for uniformity with
-- other cases of region enter operations).
-- The second entry corresponds to a standard new region action. A
-- PC_R_Remove node is stacked, whose cursor field is used to store
-- the outer stack base, and the stack base is reset to point to
-- this PC_R_Remove node. Then the pattern P is matched, and it can
-- make history stack entries in the normal manner, so now the stack
-- looks like:
-- (stack entries made before fence pattern)
-- (Special entry, not used at all)
-- (PC_R_Remove entry, "cursor" value is (negative) <-- Stack Base
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- If the match of P fails, then the PC_R_Remove entry is popped
-- and it removes both itself and the special entry underneath it,
-- restores the outer stack base, and signals failure.
-- If the match of P succeeds, then node X, the PC_Fence_X node, gets
-- control. One might be tempted to think that at this point, the
-- history stack entries made by matching P can just be removed since
-- they certainly are not going to be used for rematching (that is
-- whole point of Fence after all). However, this is wrong, because
-- it would result in the loss of possible assign-on-match entries
-- for deferred pattern assignments.
-- Instead what we do is to make a special entry whose node references
-- PC_Fence_Y, and whose cursor saves the inner stack base value, i.e.
-- the pointer to the PC_R_Remove entry. Then the outer stack base
-- pointer is restored, so the stack looks like:
-- (stack entries made before assign pattern)
-- (Special entry, not used at all)
-- (PC_R_Remove entry, "cursor" value is (negative)
-- saved base value for the enclosing region)
-- (stack entries made by matching P)
-- (PC_Fence_Y entry, "cursor" value is (negative) stack
-- pointer value referencing the PC_R_Remove entry).
-- If a subsequent failure occurs, then the PC_Fence_Y entry removes
-- the entire inner region, including all entries made by matching P,
-- and alternatives prior to the Fence pattern are sought.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the X node is numbered N + 1,
-- and the E node is N + 2.
-------------
-- Succeed --
-------------
-- Succeed builds a single node:
-- +---+
-- | S |---->
-- +---+
-- The node S is the PC_Succeed node which matches null, and stacks
-- a pointer to itself on the history stack, so that a subsequent
-- failure repeats the same match.
-- Since this is a single node it is numbered 1 (the reason we include
-- it in the compound patterns section is that it backtracks).
---------------------
-- Write Immediate --
---------------------
-- The structure built for a write immediate operation (P * F, where
-- F is a file access value) is:
-- +---+ +---+ +---+
-- | E |---->| P |---->| W |---->
-- +---+ +---+ +---+
-- Here E is the PC_R_Enter node and W is the PC_Write_Imm node. The
-- handling is identical to that described above for Assign Immediate,
-- except that at the point where a successful match occurs, the matched
-- substring is written to the referenced file.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the W node is numbered N + 1,
-- and the E node is N + 2.
--------------------
-- Write On Match --
--------------------
-- The structure built for a write on match operation (P ** F, where
-- F is a file access value) is:
-- +---+ +---+ +---+
-- | E |---->| P |---->| W |---->
-- +---+ +---+ +---+
-- Here E is the PC_R_Enter node and W is the PC_Write_OnM node. The
-- handling is identical to that described above for Assign On Match,
-- except that at the point where a successful match has completed,
-- the matched substring is written to the referenced file.
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the W node is numbered N + 1,
-- and the E node is N + 2.
-----------------------
-- Constant Patterns --
-----------------------
-- The following pattern elements are referenced only from the pattern
-- history stack. In each case the processing for the pattern element
-- results in pattern match abort, or further failure, so there is no
-- need for a successor and no need for a node number
CP_Assign : aliased PE := (PC_Assign, 0, N);
CP_Cancel : aliased PE := (PC_Cancel, 0, N);
CP_Fence_Y : aliased PE := (PC_Fence_Y, 0, N);
CP_R_Remove : aliased PE := (PC_R_Remove, 0, N);
CP_R_Restore : aliased PE := (PC_R_Restore, 0, N);
-----------------------
-- Local Subprograms --
-----------------------
function Alternate (L, R : PE_Ptr) return PE_Ptr;
function "or" (L, R : PE_Ptr) return PE_Ptr renames Alternate;
-- Build pattern structure corresponding to the alternation of L, R.
-- (i.e. try to match L, and if that fails, try to match R).
function Arbno_Simple (P : PE_Ptr) return PE_Ptr;
-- Build simple Arbno pattern, P is a pattern that is guaranteed to
-- match at least one character if it succeeds and to require no
-- stack entries under all circumstances. The result returned is
-- a simple Arbno structure as previously described.
function Bracket (E, P, A : PE_Ptr) return PE_Ptr;
-- Given two single node pattern elements E and A, and a (possible
-- complex) pattern P, construct the concatenation E-->P-->A and
-- return a pointer to E. The concatenation does not affect the
-- node numbering in P. A has a number one higher than the maximum
-- number in P, and E has a number two higher than the maximum
-- number in P (see for example the Assign_Immediate structure to
-- understand a typical use of this function).
function BreakX_Make (B : PE_Ptr) return Pattern;
-- Given a pattern element for a Break pattern, returns the
-- corresponding BreakX compound pattern structure.
function Concat (L, R : PE_Ptr; Incr : Natural) return PE_Ptr;
-- Creates a pattern element that represents a concatenation of the
-- two given pattern elements (i.e. the pattern L followed by R).
-- The result returned is always the same as L, but the pattern
-- referenced by L is modified to have R as a successor. This
-- procedure does not copy L or R, so if a copy is required, it
-- is the responsibility of the caller. The Incr parameter is an
-- amount to be added to the Nat field of any P_Arbno_Y node that is
-- in the left operand, it represents the additional stack space
-- required by the right operand.
function C_To_PE (C : PChar) return PE_Ptr;
-- Given a character, constructs a pattern element that matches
-- the single character.
function Copy (P : PE_Ptr) return PE_Ptr;
-- Creates a copy of the pattern element referenced by the given
-- pattern element reference. This is a deep copy, which means that
-- it follows the Next and Alt pointers.
function Image (P : PE_Ptr) return String;
-- Returns the image of the address of the referenced pattern element.
-- This is equivalent to Image (To_Address (P));
function Is_In (C : Character; Str : String) return Boolean;
pragma Inline (Is_In);
-- Determines if the character C is in string Str
procedure Logic_Error;
-- Called to raise Program_Error with an appropriate message if an
-- internal logic error is detected.
function Str_BF (A : Boolean_Func) return String;
function Str_FP (A : File_Ptr) return String;
function Str_NF (A : Natural_Func) return String;
function Str_NP (A : Natural_Ptr) return String;
function Str_PP (A : Pattern_Ptr) return String;
function Str_VF (A : VString_Func) return String;
function Str_VP (A : VString_Ptr) return String;
-- These are debugging routines, which return a representation of the
-- given access value (they are called only by Image and Dump)
procedure Set_Successor (Pat : PE_Ptr; Succ : PE_Ptr);
-- Adjusts all EOP pointers in Pat to point to Succ. No other changes
-- are made. In particular, Succ is unchanged, and no index numbers
-- are modified. Note that Pat may not be equal to EOP on entry.
function S_To_PE (Str : PString) return PE_Ptr;
-- Given a string, constructs a pattern element that matches the string
procedure Uninitialized_Pattern;
pragma No_Return (Uninitialized_Pattern);
-- Called to raise Program_Error with an appropriate error message if
-- an uninitialized pattern is used in any pattern construction or
-- pattern matching operation.
procedure XMatch
(Subject : String;
Pat_P : PE_Ptr;
Pat_S : Natural;
Start : out Natural;
Stop : out Natural);
-- This is the common pattern match routine. It is passed a string and
-- a pattern, and it indicates success or failure, and on success the
-- section of the string matched. It does not perform any assignments
-- to the subject string, so pattern replacement is for the caller.
--
-- Subject The subject string. The lower bound is always one. In the
-- Match procedures, it is fine to use strings whose lower bound
-- is not one, but we perform a one time conversion before the
-- call to XMatch, so that XMatch does not have to be bothered
-- with strange lower bounds.
--
-- Pat_P Points to initial pattern element of pattern to be matched
--
-- Pat_S Maximum required stack entries for pattern to be matched
--
-- Start If match is successful, starting index of matched section.
-- This value is always non-zero. A value of zero is used to
-- indicate a failed match.
--
-- Stop If match is successful, ending index of matched section.
-- This can be zero if we match the null string at the start,
-- in which case Start is set to zero, and Stop to one. If the
-- Match fails, then the contents of Stop is undefined.
procedure XMatchD
(Subject : String;
Pat_P : PE_Ptr;
Pat_S : Natural;
Start : out Natural;
Stop : out Natural);
-- Identical in all respects to XMatch, except that trace information is
-- output on Standard_Output during execution of the match. This is the
-- version that is called if the original Match call has Debug => True.
---------
-- "&" --
---------
function "&" (L : PString; R : Pattern) return Pattern is
begin
return (AFC with R.Stk, Concat (S_To_PE (L), Copy (R.P), R.Stk));
end "&";
function "&" (L : Pattern; R : PString) return Pattern is
begin
return (AFC with L.Stk, Concat (Copy (L.P), S_To_PE (R), 0));
end "&";
function "&" (L : PChar; R : Pattern) return Pattern is
begin
return (AFC with R.Stk, Concat (C_To_PE (L), Copy (R.P), R.Stk));
end "&";
function "&" (L : Pattern; R : PChar) return Pattern is
begin
return (AFC with L.Stk, Concat (Copy (L.P), C_To_PE (R), 0));
end "&";
function "&" (L : Pattern; R : Pattern) return Pattern is
begin
return (AFC with L.Stk + R.Stk, Concat (Copy (L.P), Copy (R.P), R.Stk));
end "&";
---------
-- "*" --
---------
-- Assign immediate
-- +---+ +---+ +---+
-- | E |---->| P |---->| A |---->
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the A node is numbered N + 1,
-- and the E node is N + 2.
function "*" (P : Pattern; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_Imm, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with P.Stk + 3, Bracket (E, Pat, A));
end "*";
function "*" (P : PString; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := S_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_Imm, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with 3, Bracket (E, Pat, A));
end "*";
function "*" (P : PChar; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := C_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_Imm, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with 3, Bracket (E, Pat, A));
end "*";
-- Write immediate
-- +---+ +---+ +---+
-- | E |---->| P |---->| W |---->
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the W node is numbered N + 1,
-- and the E node is N + 2.
function "*" (P : Pattern; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_Imm, 0, EOP, Fil);
begin
return (AFC with 3, Bracket (E, Pat, W));
end "*";
function "*" (P : PString; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := S_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_Imm, 0, EOP, Fil);
begin
return (AFC with 3, Bracket (E, Pat, W));
end "*";
function "*" (P : PChar; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := C_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_Imm, 0, EOP, Fil);
begin
return (AFC with 3, Bracket (E, Pat, W));
end "*";
----------
-- "**" --
----------
-- Assign on match
-- +---+ +---+ +---+
-- | E |---->| P |---->| A |---->
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the A node is numbered N + 1,
-- and the E node is N + 2.
function "**" (P : Pattern; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_OnM, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with P.Stk + 3, Bracket (E, Pat, A));
end "**";
function "**" (P : PString; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := S_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_OnM, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with 3, Bracket (E, Pat, A));
end "**";
function "**" (P : PChar; Var : VString_Var) return Pattern is
Pat : constant PE_Ptr := C_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
A : constant PE_Ptr :=
new PE'(PC_Assign_OnM, 0, EOP, Var'Unrestricted_Access);
begin
return (AFC with 3, Bracket (E, Pat, A));
end "**";
-- Write on match
-- +---+ +---+ +---+
-- | E |---->| P |---->| W |---->
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the W node is numbered N + 1,
-- and the E node is N + 2.
function "**" (P : Pattern; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_OnM, 0, EOP, Fil);
begin
return (AFC with P.Stk + 3, Bracket (E, Pat, W));
end "**";
function "**" (P : PString; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := S_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_OnM, 0, EOP, Fil);
begin
return (AFC with 3, Bracket (E, Pat, W));
end "**";
function "**" (P : PChar; Fil : File_Access) return Pattern is
Pat : constant PE_Ptr := C_To_PE (P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
W : constant PE_Ptr := new PE'(PC_Write_OnM, 0, EOP, Fil);
begin
return (AFC with 3, Bracket (E, Pat, W));
end "**";
---------
-- "+" --
---------
function "+" (Str : VString_Var) return Pattern is
begin
return
(AFC with 0,
new PE'(PC_String_VP, 1, EOP, Str'Unrestricted_Access));
end "+";
function "+" (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_String_VF, 1, EOP, Str));
end "+";
function "+" (P : Pattern_Var) return Pattern is
begin
return
(AFC with 3,
new PE'(PC_Rpat, 1, EOP, P'Unrestricted_Access));
end "+";
function "+" (P : Boolean_Func) return Pattern is
begin
return (AFC with 3, new PE'(PC_Pred_Func, 1, EOP, P));
end "+";
----------
-- "or" --
----------
function "or" (L : PString; R : Pattern) return Pattern is
begin
return (AFC with R.Stk + 1, S_To_PE (L) or Copy (R.P));
end "or";
function "or" (L : Pattern; R : PString) return Pattern is
begin
return (AFC with L.Stk + 1, Copy (L.P) or S_To_PE (R));
end "or";
function "or" (L : PString; R : PString) return Pattern is
begin
return (AFC with 1, S_To_PE (L) or S_To_PE (R));
end "or";
function "or" (L : Pattern; R : Pattern) return Pattern is
begin
return (AFC with
Natural'Max (L.Stk, R.Stk) + 1, Copy (L.P) or Copy (R.P));
end "or";
function "or" (L : PChar; R : Pattern) return Pattern is
begin
return (AFC with 1, C_To_PE (L) or Copy (R.P));
end "or";
function "or" (L : Pattern; R : PChar) return Pattern is
begin
return (AFC with 1, Copy (L.P) or C_To_PE (R));
end "or";
function "or" (L : PChar; R : PChar) return Pattern is
begin
return (AFC with 1, C_To_PE (L) or C_To_PE (R));
end "or";
function "or" (L : PString; R : PChar) return Pattern is
begin
return (AFC with 1, S_To_PE (L) or C_To_PE (R));
end "or";
function "or" (L : PChar; R : PString) return Pattern is
begin
return (AFC with 1, C_To_PE (L) or S_To_PE (R));
end "or";
------------
-- Adjust --
------------
-- No two patterns share the same pattern elements, so the adjust
-- procedure for a Pattern assignment must do a deep copy of the
-- pattern element structure.
procedure Adjust (Object : in out Pattern) is
begin
Object.P := Copy (Object.P);
end Adjust;
---------------
-- Alternate --
---------------
function Alternate (L, R : PE_Ptr) return PE_Ptr is
begin
-- If the left pattern is null, then we just add the alternation
-- node with an index one greater than the right hand pattern.
if L = EOP then
return new PE'(PC_Alt, R.Index + 1, EOP, R);
-- If the left pattern is non-null, then build a reference vector
-- for its elements, and adjust their index values to accommodate
-- the right hand elements. Then add the alternation node.
else
declare
Refs : Ref_Array (1 .. L.Index);
begin
Build_Ref_Array (L, Refs);
for J in Refs'Range loop
Refs (J).Index := Refs (J).Index + R.Index;
end loop;
end;
return new PE'(PC_Alt, L.Index + 1, L, R);
end if;
end Alternate;
---------
-- Any --
---------
function Any (Str : String) return Pattern is
begin
return (AFC with 0, new PE'(PC_Any_CS, 1, EOP, To_Set (Str)));
end Any;
function Any (Str : VString) return Pattern is
begin
return Any (S (Str));
end Any;
function Any (Str : Character) return Pattern is
begin
return (AFC with 0, new PE'(PC_Any_CH, 1, EOP, Str));
end Any;
function Any (Str : Character_Set) return Pattern is
begin
return (AFC with 0, new PE'(PC_Any_CS, 1, EOP, Str));
end Any;
function Any (Str : not null access VString) return Pattern is
begin
return (AFC with 0, new PE'(PC_Any_VP, 1, EOP, VString_Ptr (Str)));
end Any;
function Any (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Any_VF, 1, EOP, Str));
end Any;
---------
-- Arb --
---------
-- +---+
-- | X |---->
-- +---+
-- .
-- .
-- +---+
-- | Y |---->
-- +---+
-- The PC_Arb_X element is numbered 2, and the PC_Arb_Y element is 1
function Arb return Pattern is
Y : constant PE_Ptr := new PE'(PC_Arb_Y, 1, EOP);
X : constant PE_Ptr := new PE'(PC_Arb_X, 2, EOP, Y);
begin
return (AFC with 1, X);
end Arb;
-----------
-- Arbno --
-----------
function Arbno (P : PString) return Pattern is
begin
if P'Length = 0 then
return (AFC with 0, EOP);
else
return (AFC with 0, Arbno_Simple (S_To_PE (P)));
end if;
end Arbno;
function Arbno (P : PChar) return Pattern is
begin
return (AFC with 0, Arbno_Simple (C_To_PE (P)));
end Arbno;
function Arbno (P : Pattern) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
begin
if P.Stk = 0
and then OK_For_Simple_Arbno (Pat.Pcode)
then
return (AFC with 0, Arbno_Simple (Pat));
end if;
-- This is the complex case, either the pattern makes stack entries
-- or it is possible for the pattern to match the null string (more
-- accurately, we don't know that this is not the case).
-- +--------------------------+
-- | ^
-- V |
-- +---+ |
-- | X |----> |
-- +---+ |
-- . |
-- . |
-- +---+ +---+ +---+ |
-- | E |---->| P |---->| Y |--->+
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the Y node is numbered N + 1,
-- the E node is N + 2, and the X node is N + 3.
declare
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
X : constant PE_Ptr := new PE'(PC_Arbno_X, 0, EOP, E);
Y : constant PE_Ptr := new PE'(PC_Arbno_Y, 0, X, P.Stk + 3);
EPY : constant PE_Ptr := Bracket (E, Pat, Y);
begin
X.Alt := EPY;
X.Index := EPY.Index + 1;
return (AFC with P.Stk + 3, X);
end;
end Arbno;
------------------
-- Arbno_Simple --
------------------
-- +-------------+
-- | ^
-- V |
-- +---+ |
-- | S |----> |
-- +---+ |
-- . |
-- . |
-- +---+ |
-- | P |---------->+
-- +---+
-- The node numbering of the constituent pattern P is not affected.
-- The S node has a node number of P.Index + 1.
-- Note that we know that P cannot be EOP, because a null pattern
-- does not meet the requirements for simple Arbno.
function Arbno_Simple (P : PE_Ptr) return PE_Ptr is
S : constant PE_Ptr := new PE'(PC_Arbno_S, P.Index + 1, EOP, P);
begin
Set_Successor (P, S);
return S;
end Arbno_Simple;
---------
-- Bal --
---------
function Bal return Pattern is
begin
return (AFC with 1, new PE'(PC_Bal, 1, EOP));
end Bal;
-------------
-- Bracket --
-------------
function Bracket (E, P, A : PE_Ptr) return PE_Ptr is
begin
if P = EOP then
E.Pthen := A;
E.Index := 2;
A.Index := 1;
else
E.Pthen := P;
Set_Successor (P, A);
E.Index := P.Index + 2;
A.Index := P.Index + 1;
end if;
return E;
end Bracket;
-----------
-- Break --
-----------
function Break (Str : String) return Pattern is
begin
return (AFC with 0, new PE'(PC_Break_CS, 1, EOP, To_Set (Str)));
end Break;
function Break (Str : VString) return Pattern is
begin
return Break (S (Str));
end Break;
function Break (Str : Character) return Pattern is
begin
return (AFC with 0, new PE'(PC_Break_CH, 1, EOP, Str));
end Break;
function Break (Str : Character_Set) return Pattern is
begin
return (AFC with 0, new PE'(PC_Break_CS, 1, EOP, Str));
end Break;
function Break (Str : not null access VString) return Pattern is
begin
return (AFC with 0,
new PE'(PC_Break_VP, 1, EOP, Str.all'Unchecked_Access));
end Break;
function Break (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Break_VF, 1, EOP, Str));
end Break;
------------
-- BreakX --
------------
function BreakX (Str : String) return Pattern is
begin
return BreakX_Make (new PE'(PC_BreakX_CS, 3, N, To_Set (Str)));
end BreakX;
function BreakX (Str : VString) return Pattern is
begin
return BreakX (S (Str));
end BreakX;
function BreakX (Str : Character) return Pattern is
begin
return BreakX_Make (new PE'(PC_BreakX_CH, 3, N, Str));
end BreakX;
function BreakX (Str : Character_Set) return Pattern is
begin
return BreakX_Make (new PE'(PC_BreakX_CS, 3, N, Str));
end BreakX;
function BreakX (Str : not null access VString) return Pattern is
begin
return BreakX_Make (new PE'(PC_BreakX_VP, 3, N, VString_Ptr (Str)));
end BreakX;
function BreakX (Str : VString_Func) return Pattern is
begin
return BreakX_Make (new PE'(PC_BreakX_VF, 3, N, Str));
end BreakX;
-----------------
-- BreakX_Make --
-----------------
-- +---+ +---+
-- | B |---->| A |---->
-- +---+ +---+
-- ^ .
-- | .
-- | +---+
-- +<------| X |
-- +---+
-- The B node is numbered 3, the alternative node is 1, and the X
-- node is 2.
function BreakX_Make (B : PE_Ptr) return Pattern is
X : constant PE_Ptr := new PE'(PC_BreakX_X, 2, B);
A : constant PE_Ptr := new PE'(PC_Alt, 1, EOP, X);
begin
B.Pthen := A;
return (AFC with 2, B);
end BreakX_Make;
---------------------
-- Build_Ref_Array --
---------------------
procedure Build_Ref_Array (E : PE_Ptr; RA : out Ref_Array) is
procedure Record_PE (E : PE_Ptr);
-- Record given pattern element if not already recorded in RA,
-- and also record any referenced pattern elements recursively.
---------------
-- Record_PE --
---------------
procedure Record_PE (E : PE_Ptr) is
begin
PutD (" Record_PE called with PE_Ptr = " & Image (E));
if E = EOP or else RA (E.Index) /= null then
Put_LineD (", nothing to do");
return;
else
Put_LineD (", recording" & IndexT'Image (E.Index));
RA (E.Index) := E;
Record_PE (E.Pthen);
if E.Pcode in PC_Has_Alt then
Record_PE (E.Alt);
end if;
end if;
end Record_PE;
-- Start of processing for Build_Ref_Array
begin
New_LineD;
Put_LineD ("Entering Build_Ref_Array");
Record_PE (E);
New_LineD;
end Build_Ref_Array;
-------------
-- C_To_PE --
-------------
function C_To_PE (C : PChar) return PE_Ptr is
begin
return new PE'(PC_Char, 1, EOP, C);
end C_To_PE;
------------
-- Cancel --
------------
function Cancel return Pattern is
begin
return (AFC with 0, new PE'(PC_Cancel, 1, EOP));
end Cancel;
------------
-- Concat --
------------
-- Concat needs to traverse the left operand performing the following
-- set of fixups:
-- a) Any successor pointers (Pthen fields) that are set to EOP are
-- reset to point to the second operand.
-- b) Any PC_Arbno_Y node has its stack count field incremented
-- by the parameter Incr provided for this purpose.
-- d) Num fields of all pattern elements in the left operand are
-- adjusted to include the elements of the right operand.
-- Note: we do not use Set_Successor in the processing for Concat, since
-- there is no point in doing two traversals, we may as well do everything
-- at the same time.
function Concat (L, R : PE_Ptr; Incr : Natural) return PE_Ptr is
begin
if L = EOP then
return R;
elsif R = EOP then
return L;
else
declare
Refs : Ref_Array (1 .. L.Index);
-- We build a reference array for L whose N'th element points to
-- the pattern element of L whose original Index value is N.
P : PE_Ptr;
begin
Build_Ref_Array (L, Refs);
for J in Refs'Range loop
P := Refs (J);
P.Index := P.Index + R.Index;
if P.Pcode = PC_Arbno_Y then
P.Nat := P.Nat + Incr;
end if;
if P.Pthen = EOP then
P.Pthen := R;
end if;
if P.Pcode in PC_Has_Alt and then P.Alt = EOP then
P.Alt := R;
end if;
end loop;
end;
return L;
end if;
end Concat;
----------
-- Copy --
----------
function Copy (P : PE_Ptr) return PE_Ptr is
begin
if P = null then
Uninitialized_Pattern;
else
declare
Refs : Ref_Array (1 .. P.Index);
-- References to elements in P, indexed by Index field
Copy : Ref_Array (1 .. P.Index);
-- Holds copies of elements of P, indexed by Index field
E : PE_Ptr;
begin
Build_Ref_Array (P, Refs);
-- Now copy all nodes
for J in Refs'Range loop
Copy (J) := new PE'(Refs (J).all);
end loop;
-- Adjust all internal references
for J in Copy'Range loop
E := Copy (J);
-- Adjust successor pointer to point to copy
if E.Pthen /= EOP then
E.Pthen := Copy (E.Pthen.Index);
end if;
-- Adjust Alt pointer if there is one to point to copy
if E.Pcode in PC_Has_Alt and then E.Alt /= EOP then
E.Alt := Copy (E.Alt.Index);
end if;
-- Copy referenced string
if E.Pcode = PC_String then
E.Str := new String'(E.Str.all);
end if;
end loop;
return Copy (P.Index);
end;
end if;
end Copy;
----------
-- Dump --
----------
procedure Dump (P : Pattern) is
procedure Write_Node_Id (E : PE_Ptr; Cols : Natural);
-- Writes out a string identifying the given pattern element. Cols is
-- the column indentation level.
-------------------
-- Write_Node_Id --
-------------------
procedure Write_Node_Id (E : PE_Ptr; Cols : Natural) is
begin
if E = EOP then
Put ("EOP");
for J in 4 .. Cols loop
Put (' ');
end loop;
else
declare
Str : String (1 .. Cols);
N : Natural := Natural (E.Index);
begin
Put ("#");
for J in reverse Str'Range loop
Str (J) := Character'Val (48 + N mod 10);
N := N / 10;
end loop;
Put (Str);
end;
end if;
end Write_Node_Id;
-- Local variables
Cols : Natural := 2;
-- Number of columns used for pattern numbers, minimum is 2
E : PE_Ptr;
subtype Count is Ada.Text_IO.Count;
Scol : Count;
-- Used to keep track of column in dump output
-- Start of processing for Dump
begin
New_Line;
Put
("Pattern Dump Output (pattern at "
& Image (P'Address)
& ", S = "
& Natural'Image (P.Stk) & ')');
New_Line;
Scol := Col;
while Col < Scol loop
Put ('-');
end loop;
New_Line;
-- If uninitialized pattern, dump line and we are done
if P.P = null then
Put_Line ("Uninitialized pattern value");
return;
end if;
-- If null pattern, just dump it and we are all done
if P.P = EOP then
Put_Line ("EOP (null pattern)");
return;
end if;
declare
Refs : Ref_Array (1 .. P.P.Index);
-- We build a reference array whose N'th element points to the
-- pattern element whose Index value is N.
begin
Build_Ref_Array (P.P, Refs);
-- Set number of columns required for node numbers
while 10 ** Cols - 1 < Integer (P.P.Index) loop
Cols := Cols + 1;
end loop;
-- Now dump the nodes in reverse sequence. We output them in reverse
-- sequence since this corresponds to the natural order used to
-- construct the patterns.
for J in reverse Refs'Range loop
E := Refs (J);
Write_Node_Id (E, Cols);
Set_Col (Count (Cols) + 4);
Put (Image (E));
Put (" ");
Put (Pattern_Code'Image (E.Pcode));
Put (" ");
Set_Col (21 + Count (Cols) + Address_Image_Length);
Write_Node_Id (E.Pthen, Cols);
Set_Col (24 + 2 * Count (Cols) + Address_Image_Length);
case E.Pcode is
when PC_Alt
| PC_Arb_X
| PC_Arbno_S
| PC_Arbno_X
=>
Write_Node_Id (E.Alt, Cols);
when PC_Rpat =>
Put (Str_PP (E.PP));
when PC_Pred_Func =>
Put (Str_BF (E.BF));
when PC_Assign_Imm
| PC_Assign_OnM
| PC_Any_VP
| PC_Break_VP
| PC_BreakX_VP
| PC_NotAny_VP
| PC_NSpan_VP
| PC_Span_VP
| PC_String_VP
=>
Put (Str_VP (E.VP));
when PC_Write_Imm
| PC_Write_OnM
=>
Put (Str_FP (E.FP));
when PC_String =>
Put (Image (E.Str.all));
when PC_String_2 =>
Put (Image (E.Str2));
when PC_String_3 =>
Put (Image (E.Str3));
when PC_String_4 =>
Put (Image (E.Str4));
when PC_String_5 =>
Put (Image (E.Str5));
when PC_String_6 =>
Put (Image (E.Str6));
when PC_Setcur =>
Put (Str_NP (E.Var));
when PC_Any_CH
| PC_Break_CH
| PC_BreakX_CH
| PC_Char
| PC_NotAny_CH
| PC_NSpan_CH
| PC_Span_CH
=>
Put (''' & E.Char & ''');
when PC_Any_CS
| PC_Break_CS
| PC_BreakX_CS
| PC_NotAny_CS
| PC_NSpan_CS
| PC_Span_CS
=>
Put ('"' & To_Sequence (E.CS) & '"');
when PC_Arbno_Y
| PC_Len_Nat
| PC_Pos_Nat
| PC_RPos_Nat
| PC_RTab_Nat
| PC_Tab_Nat
=>
Put (S (E.Nat));
when PC_Pos_NF
| PC_Len_NF
| PC_RPos_NF
| PC_RTab_NF
| PC_Tab_NF
=>
Put (Str_NF (E.NF));
when PC_Pos_NP
| PC_Len_NP
| PC_RPos_NP
| PC_RTab_NP
| PC_Tab_NP
=>
Put (Str_NP (E.NP));
when PC_Any_VF
| PC_Break_VF
| PC_BreakX_VF
| PC_NotAny_VF
| PC_NSpan_VF
| PC_Span_VF
| PC_String_VF
=>
Put (Str_VF (E.VF));
when others =>
null;
end case;
New_Line;
end loop;
New_Line;
end;
end Dump;
----------
-- Fail --
----------
function Fail return Pattern is
begin
return (AFC with 0, new PE'(PC_Fail, 1, EOP));
end Fail;
-----------
-- Fence --
-----------
-- Simple case
function Fence return Pattern is
begin
return (AFC with 1, new PE'(PC_Fence, 1, EOP));
end Fence;
-- Function case
-- +---+ +---+ +---+
-- | E |---->| P |---->| X |---->
-- +---+ +---+ +---+
-- The node numbering of the constituent pattern P is not affected.
-- Where N is the number of nodes in P, the X node is numbered N + 1,
-- and the E node is N + 2.
function Fence (P : Pattern) return Pattern is
Pat : constant PE_Ptr := Copy (P.P);
E : constant PE_Ptr := new PE'(PC_R_Enter, 0, EOP);
X : constant PE_Ptr := new PE'(PC_Fence_X, 0, EOP);
begin
return (AFC with P.Stk + 1, Bracket (E, Pat, X));
end Fence;
--------------
-- Finalize --
--------------
procedure Finalize (Object : in out Pattern) is
procedure Free is new Ada.Unchecked_Deallocation (PE, PE_Ptr);
procedure Free is new Ada.Unchecked_Deallocation (String, String_Ptr);
begin
-- Nothing to do if already freed
if Object.P = null then
return;
-- Otherwise we must free all elements
else
declare
Refs : Ref_Array (1 .. Object.P.Index);
-- References to elements in pattern to be finalized
begin
Build_Ref_Array (Object.P, Refs);
for J in Refs'Range loop
if Refs (J).Pcode = PC_String then
Free (Refs (J).Str);
end if;
Free (Refs (J));
end loop;
Object.P := null;
end;
end if;
end Finalize;
-----------
-- Image --
-----------
function Image (P : PE_Ptr) return String is
begin
return Image (To_Address (P));
end Image;
function Image (P : Pattern) return String is
begin
return S (Image (P));
end Image;
function Image (P : Pattern) return VString is
Kill_Ampersand : Boolean := False;
-- Set True to delete next & to be output to Result
Result : VString := Nul;
-- The result is accumulated here, using Append
Refs : Ref_Array (1 .. P.P.Index);
-- We build a reference array whose N'th element points to the
-- pattern element whose Index value is N.
procedure Delete_Ampersand;
-- Deletes the ampersand at the end of Result
procedure Image_Seq (E : PE_Ptr; Succ : PE_Ptr; Paren : Boolean);
-- E refers to a pattern structure whose successor is given by Succ.
-- This procedure appends to Result a representation of this pattern.
-- The Paren parameter indicates whether parentheses are required if
-- the output is more than one element.
procedure Image_One (E : in out PE_Ptr);
-- E refers to a pattern structure. This procedure appends to Result
-- a representation of the single simple or compound pattern structure
-- at the start of E and updates E to point to its successor.
----------------------
-- Delete_Ampersand --
----------------------
procedure Delete_Ampersand is
L : constant Natural := Length (Result);
begin
if L > 2 then
Delete (Result, L - 1, L);
end if;
end Delete_Ampersand;
---------------
-- Image_One --
---------------
procedure Image_One (E : in out PE_Ptr) is
ER : PE_Ptr := E.Pthen;
-- Successor set as result in E unless reset
begin
case E.Pcode is
when PC_Cancel =>
Append (Result, "Cancel");
when PC_Alt => Alt : declare
Elmts_In_L : constant IndexT := E.Pthen.Index - E.Alt.Index;
-- Number of elements in left pattern of alternation
Lowest_In_L : constant IndexT := E.Index - Elmts_In_L;
-- Number of lowest index in elements of left pattern
E1 : PE_Ptr;
begin
-- The successor of the alternation node must have a lower
-- index than any node that is in the left pattern or a
-- higher index than the alternation node itself.
while ER /= EOP
and then ER.Index >= Lowest_In_L
and then ER.Index < E.Index
loop
ER := ER.Pthen;
end loop;
Append (Result, '(');
E1 := E;
loop
Image_Seq (E1.Pthen, ER, False);
Append (Result, " or ");
E1 := E1.Alt;
exit when E1.Pcode /= PC_Alt;
end loop;
Image_Seq (E1, ER, False);
Append (Result, ')');
end Alt;
when PC_Any_CS =>
Append (Result, "Any (" & Image (To_Sequence (E.CS)) & ')');
when PC_Any_VF =>
Append (Result, "Any (" & Str_VF (E.VF) & ')');
when PC_Any_VP =>
Append (Result, "Any (" & Str_VP (E.VP) & ')');
when PC_Arb_X =>
Append (Result, "Arb");
when PC_Arbno_S =>
Append (Result, "Arbno (");
Image_Seq (E.Alt, E, False);
Append (Result, ')');
when PC_Arbno_X =>
Append (Result, "Arbno (");
Image_Seq (E.Alt.Pthen, Refs (E.Index - 2), False);
Append (Result, ')');
when PC_Assign_Imm =>
Delete_Ampersand;
Append (Result, "* " & Str_VP (Refs (E.Index).VP));
when PC_Assign_OnM =>
Delete_Ampersand;
Append (Result, "** " & Str_VP (Refs (E.Index).VP));
when PC_Any_CH =>
Append (Result, "Any ('" & E.Char & "')");
when PC_Bal =>
Append (Result, "Bal");
when PC_Break_CH =>
Append (Result, "Break ('" & E.Char & "')");
when PC_Break_CS =>
Append (Result, "Break (" & Image (To_Sequence (E.CS)) & ')');
when PC_Break_VF =>
Append (Result, "Break (" & Str_VF (E.VF) & ')');
when PC_Break_VP =>
Append (Result, "Break (" & Str_VP (E.VP) & ')');
when PC_BreakX_CH =>
Append (Result, "BreakX ('" & E.Char & "')");
ER := ER.Pthen;
when PC_BreakX_CS =>
Append (Result, "BreakX (" & Image (To_Sequence (E.CS)) & ')');
ER := ER.Pthen;
when PC_BreakX_VF =>
Append (Result, "BreakX (" & Str_VF (E.VF) & ')');
ER := ER.Pthen;
when PC_BreakX_VP =>
Append (Result, "BreakX (" & Str_VP (E.VP) & ')');
ER := ER.Pthen;
when PC_Char =>
Append (Result, ''' & E.Char & ''');
when PC_Fail =>
Append (Result, "Fail");
when PC_Fence =>
Append (Result, "Fence");
when PC_Fence_X =>
Append (Result, "Fence (");
Image_Seq (E.Pthen, Refs (E.Index - 1), False);
Append (Result, ")");
ER := Refs (E.Index - 1).Pthen;
when PC_Len_Nat =>
Append (Result, "Len (" & E.Nat & ')');
when PC_Len_NF =>
Append (Result, "Len (" & Str_NF (E.NF) & ')');
when PC_Len_NP =>
Append (Result, "Len (" & Str_NP (E.NP) & ')');
when PC_NotAny_CH =>
Append (Result, "NotAny ('" & E.Char & "')");
when PC_NotAny_CS =>
Append (Result, "NotAny (" & Image (To_Sequence (E.CS)) & ')');
when PC_NotAny_VF =>
Append (Result, "NotAny (" & Str_VF (E.VF) & ')');
when PC_NotAny_VP =>
Append (Result, "NotAny (" & Str_VP (E.VP) & ')');
when PC_NSpan_CH =>
Append (Result, "NSpan ('" & E.Char & "')");
when PC_NSpan_CS =>
Append (Result, "NSpan (" & Image (To_Sequence (E.CS)) & ')');
when PC_NSpan_VF =>
Append (Result, "NSpan (" & Str_VF (E.VF) & ')');
when PC_NSpan_VP =>
Append (Result, "NSpan (" & Str_VP (E.VP) & ')');
when PC_Null =>
Append (Result, """""");
when PC_Pos_Nat =>
Append (Result, "Pos (" & E.Nat & ')');
when PC_Pos_NF =>
Append (Result, "Pos (" & Str_NF (E.NF) & ')');
when PC_Pos_NP =>
Append (Result, "Pos (" & Str_NP (E.NP) & ')');
when PC_R_Enter =>
Kill_Ampersand := True;
when PC_Rest =>
Append (Result, "Rest");
when PC_Rpat =>
Append (Result, "(+ " & Str_PP (E.PP) & ')');
when PC_Pred_Func =>
Append (Result, "(+ " & Str_BF (E.BF) & ')');
when PC_RPos_Nat =>
Append (Result, "RPos (" & E.Nat & ')');
when PC_RPos_NF =>
Append (Result, "RPos (" & Str_NF (E.NF) & ')');
when PC_RPos_NP =>
Append (Result, "RPos (" & Str_NP (E.NP) & ')');
when PC_RTab_Nat =>
Append (Result, "RTab (" & E.Nat & ')');
when PC_RTab_NF =>
Append (Result, "RTab (" & Str_NF (E.NF) & ')');
when PC_RTab_NP =>
Append (Result, "RTab (" & Str_NP (E.NP) & ')');
when PC_Setcur =>
Append (Result, "Setcur (" & Str_NP (E.Var) & ')');
when PC_Span_CH =>
Append (Result, "Span ('" & E.Char & "')");
when PC_Span_CS =>
Append (Result, "Span (" & Image (To_Sequence (E.CS)) & ')');
when PC_Span_VF =>
Append (Result, "Span (" & Str_VF (E.VF) & ')');
when PC_Span_VP =>
Append (Result, "Span (" & Str_VP (E.VP) & ')');
when PC_String =>
Append (Result, Image (E.Str.all));
when PC_String_2 =>
Append (Result, Image (E.Str2));
when PC_String_3 =>
Append (Result, Image (E.Str3));
when PC_String_4 =>
Append (Result, Image (E.Str4));
when PC_String_5 =>
Append (Result, Image (E.Str5));
when PC_String_6 =>
Append (Result, Image (E.Str6));
when PC_String_VF =>
Append (Result, "(+" & Str_VF (E.VF) & ')');
when PC_String_VP =>
Append (Result, "(+" & Str_VP (E.VP) & ')');
when PC_Succeed =>
Append (Result, "Succeed");
when PC_Tab_Nat =>
Append (Result, "Tab (" & E.Nat & ')');
when PC_Tab_NF =>
Append (Result, "Tab (" & Str_NF (E.NF) & ')');
when PC_Tab_NP =>
Append (Result, "Tab (" & Str_NP (E.NP) & ')');
when PC_Write_Imm =>
Append (Result, '(');
Image_Seq (E, Refs (E.Index - 1), True);
Append (Result, " * " & Str_FP (Refs (E.Index - 1).FP));
ER := Refs (E.Index - 1).Pthen;
when PC_Write_OnM =>
Append (Result, '(');
Image_Seq (E.Pthen, Refs (E.Index - 1), True);
Append (Result, " ** " & Str_FP (Refs (E.Index - 1).FP));
ER := Refs (E.Index - 1).Pthen;
-- Other pattern codes should not appear as leading elements
when PC_Arb_Y
| PC_Arbno_Y
| PC_Assign
| PC_BreakX_X
| PC_EOP
| PC_Fence_Y
| PC_R_Remove
| PC_R_Restore
| PC_Unanchored
=>
Append (Result, "???");
end case;
E := ER;
end Image_One;
---------------
-- Image_Seq --
---------------
procedure Image_Seq (E : PE_Ptr; Succ : PE_Ptr; Paren : Boolean) is
Indx : constant Natural := Length (Result);
E1 : PE_Ptr := E;
Mult : Boolean := False;
begin
-- The image of EOP is "" (the null string)
if E = EOP then
Append (Result, """""");
-- Else generate appropriate concatenation sequence
else
loop
Image_One (E1);
exit when E1 = Succ;
exit when E1 = EOP;
Mult := True;
if Kill_Ampersand then
Kill_Ampersand := False;
else
Append (Result, " & ");
end if;
end loop;
end if;
if Mult and Paren then
Insert (Result, Indx + 1, "(");
Append (Result, ")");
end if;
end Image_Seq;
-- Start of processing for Image
begin
Build_Ref_Array (P.P, Refs);
Image_Seq (P.P, EOP, False);
return Result;
end Image;
-----------
-- Is_In --
-----------
function Is_In (C : Character; Str : String) return Boolean is
begin
for J in Str'Range loop
if Str (J) = C then
return True;
end if;
end loop;
return False;
end Is_In;
---------
-- Len --
---------
function Len (Count : Natural) return Pattern is
begin
-- Note, the following is not just an optimization, it is needed
-- to ensure that Arbno (Len (0)) does not generate an infinite
-- matching loop (since PC_Len_Nat is OK_For_Simple_Arbno).
if Count = 0 then
return (AFC with 0, new PE'(PC_Null, 1, EOP));
else
return (AFC with 0, new PE'(PC_Len_Nat, 1, EOP, Count));
end if;
end Len;
function Len (Count : Natural_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Len_NF, 1, EOP, Count));
end Len;
function Len (Count : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Len_NP, 1, EOP, Natural_Ptr (Count)));
end Len;
-----------------
-- Logic_Error --
-----------------
procedure Logic_Error is
begin
raise Program_Error with
"Internal logic error in GNAT.Spitbol.Patterns";
end Logic_Error;
-----------
-- Match --
-----------
function Match
(Subject : VString;
Pat : Pattern) return Boolean
is
S : Big_String_Access;
L : Natural;
Start : Natural;
Stop : Natural;
pragma Unreferenced (Stop);
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
return Start /= 0;
end Match;
function Match
(Subject : String;
Pat : Pattern) return Boolean
is
Start, Stop : Natural;
pragma Unreferenced (Stop);
subtype String1 is String (1 .. Subject'Length);
begin
if Debug_Mode then
XMatchD (String1 (Subject), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (String1 (Subject), Pat.P, Pat.Stk, Start, Stop);
end if;
return Start /= 0;
end Match;
function Match
(Subject : VString_Var;
Pat : Pattern;
Replace : VString) return Boolean
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start = 0 then
return False;
else
Get_String (Replace, S, L);
Replace_Slice
(Subject'Unrestricted_Access.all, Start, Stop, S (1 .. L));
return True;
end if;
end Match;
function Match
(Subject : VString_Var;
Pat : Pattern;
Replace : String) return Boolean
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start = 0 then
return False;
else
Replace_Slice
(Subject'Unrestricted_Access.all, Start, Stop, Replace);
return True;
end if;
end Match;
procedure Match
(Subject : VString;
Pat : Pattern)
is
S : Big_String_Access;
L : Natural;
Start : Natural;
Stop : Natural;
pragma Unreferenced (Start, Stop);
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
end Match;
procedure Match
(Subject : String;
Pat : Pattern)
is
Start, Stop : Natural;
pragma Unreferenced (Start, Stop);
subtype String1 is String (1 .. Subject'Length);
begin
if Debug_Mode then
XMatchD (String1 (Subject), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (String1 (Subject), Pat.P, Pat.Stk, Start, Stop);
end if;
end Match;
procedure Match
(Subject : in out VString;
Pat : Pattern;
Replace : VString)
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start /= 0 then
Get_String (Replace, S, L);
Replace_Slice (Subject, Start, Stop, S (1 .. L));
end if;
end Match;
procedure Match
(Subject : in out VString;
Pat : Pattern;
Replace : String)
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start /= 0 then
Replace_Slice (Subject, Start, Stop, Replace);
end if;
end Match;
function Match
(Subject : VString;
Pat : PString) return Boolean
is
Pat_Len : constant Natural := Pat'Length;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Anchored_Mode then
if Pat_Len > L then
return False;
else
return Pat = S (1 .. Pat_Len);
end if;
else
for J in 1 .. L - Pat_Len + 1 loop
if Pat = S (J .. J + (Pat_Len - 1)) then
return True;
end if;
end loop;
return False;
end if;
end Match;
function Match
(Subject : String;
Pat : PString) return Boolean
is
Pat_Len : constant Natural := Pat'Length;
Sub_Len : constant Natural := Subject'Length;
SFirst : constant Natural := Subject'First;
begin
if Anchored_Mode then
if Pat_Len > Sub_Len then
return False;
else
return Pat = Subject (SFirst .. SFirst + Pat_Len - 1);
end if;
else
for J in SFirst .. SFirst + Sub_Len - Pat_Len loop
if Pat = Subject (J .. J + (Pat_Len - 1)) then
return True;
end if;
end loop;
return False;
end if;
end Match;
function Match
(Subject : VString_Var;
Pat : PString;
Replace : VString) return Boolean
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
end if;
if Start = 0 then
return False;
else
Get_String (Replace, S, L);
Replace_Slice
(Subject'Unrestricted_Access.all, Start, Stop, S (1 .. L));
return True;
end if;
end Match;
function Match
(Subject : VString_Var;
Pat : PString;
Replace : String) return Boolean
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
end if;
if Start = 0 then
return False;
else
Replace_Slice
(Subject'Unrestricted_Access.all, Start, Stop, Replace);
return True;
end if;
end Match;
procedure Match
(Subject : VString;
Pat : PString)
is
S : Big_String_Access;
L : Natural;
Start : Natural;
Stop : Natural;
pragma Unreferenced (Start, Stop);
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
end if;
end Match;
procedure Match
(Subject : String;
Pat : PString)
is
Start, Stop : Natural;
pragma Unreferenced (Start, Stop);
subtype String1 is String (1 .. Subject'Length);
begin
if Debug_Mode then
XMatchD (String1 (Subject), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (String1 (Subject), S_To_PE (Pat), 0, Start, Stop);
end if;
end Match;
procedure Match
(Subject : in out VString;
Pat : PString;
Replace : VString)
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
end if;
if Start /= 0 then
Get_String (Replace, S, L);
Replace_Slice (Subject, Start, Stop, S (1 .. L));
end if;
end Match;
procedure Match
(Subject : in out VString;
Pat : PString;
Replace : String)
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
else
XMatch (S (1 .. L), S_To_PE (Pat), 0, Start, Stop);
end if;
if Start /= 0 then
Replace_Slice (Subject, Start, Stop, Replace);
end if;
end Match;
function Match
(Subject : VString_Var;
Pat : Pattern;
Result : Match_Result_Var) return Boolean
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start = 0 then
Result'Unrestricted_Access.all.Var := null;
return False;
else
Result'Unrestricted_Access.all.Var := Subject'Unrestricted_Access;
Result'Unrestricted_Access.all.Start := Start;
Result'Unrestricted_Access.all.Stop := Stop;
return True;
end if;
end Match;
procedure Match
(Subject : in out VString;
Pat : Pattern;
Result : out Match_Result)
is
Start : Natural;
Stop : Natural;
S : Big_String_Access;
L : Natural;
begin
Get_String (Subject, S, L);
if Debug_Mode then
XMatchD (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
else
XMatch (S (1 .. L), Pat.P, Pat.Stk, Start, Stop);
end if;
if Start = 0 then
Result.Var := null;
else
Result.Var := Subject'Unrestricted_Access;
Result.Start := Start;
Result.Stop := Stop;
end if;
end Match;
---------------
-- New_LineD --
---------------
procedure New_LineD is
begin
if Internal_Debug then
New_Line;
end if;
end New_LineD;
------------
-- NotAny --
------------
function NotAny (Str : String) return Pattern is
begin
return (AFC with 0, new PE'(PC_NotAny_CS, 1, EOP, To_Set (Str)));
end NotAny;
function NotAny (Str : VString) return Pattern is
begin
return NotAny (S (Str));
end NotAny;
function NotAny (Str : Character) return Pattern is
begin
return (AFC with 0, new PE'(PC_NotAny_CH, 1, EOP, Str));
end NotAny;
function NotAny (Str : Character_Set) return Pattern is
begin
return (AFC with 0, new PE'(PC_NotAny_CS, 1, EOP, Str));
end NotAny;
function NotAny (Str : not null access VString) return Pattern is
begin
return (AFC with 0, new PE'(PC_NotAny_VP, 1, EOP, VString_Ptr (Str)));
end NotAny;
function NotAny (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_NotAny_VF, 1, EOP, Str));
end NotAny;
-----------
-- NSpan --
-----------
function NSpan (Str : String) return Pattern is
begin
return (AFC with 0, new PE'(PC_NSpan_CS, 1, EOP, To_Set (Str)));
end NSpan;
function NSpan (Str : VString) return Pattern is
begin
return NSpan (S (Str));
end NSpan;
function NSpan (Str : Character) return Pattern is
begin
return (AFC with 0, new PE'(PC_NSpan_CH, 1, EOP, Str));
end NSpan;
function NSpan (Str : Character_Set) return Pattern is
begin
return (AFC with 0, new PE'(PC_NSpan_CS, 1, EOP, Str));
end NSpan;
function NSpan (Str : not null access VString) return Pattern is
begin
return (AFC with 0, new PE'(PC_NSpan_VP, 1, EOP, VString_Ptr (Str)));
end NSpan;
function NSpan (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_NSpan_VF, 1, EOP, Str));
end NSpan;
---------
-- Pos --
---------
function Pos (Count : Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Pos_Nat, 1, EOP, Count));
end Pos;
function Pos (Count : Natural_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Pos_NF, 1, EOP, Count));
end Pos;
function Pos (Count : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Pos_NP, 1, EOP, Natural_Ptr (Count)));
end Pos;
----------
-- PutD --
----------
procedure PutD (Str : String) is
begin
if Internal_Debug then
Put (Str);
end if;
end PutD;
---------------
-- Put_LineD --
---------------
procedure Put_LineD (Str : String) is
begin
if Internal_Debug then
Put_Line (Str);
end if;
end Put_LineD;
-------------
-- Replace --
-------------
procedure Replace
(Result : in out Match_Result;
Replace : VString)
is
S : Big_String_Access;
L : Natural;
begin
Get_String (Replace, S, L);
if Result.Var /= null then
Replace_Slice (Result.Var.all, Result.Start, Result.Stop, S (1 .. L));
Result.Var := null;
end if;
end Replace;
----------
-- Rest --
----------
function Rest return Pattern is
begin
return (AFC with 0, new PE'(PC_Rest, 1, EOP));
end Rest;
----------
-- Rpos --
----------
function Rpos (Count : Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_RPos_Nat, 1, EOP, Count));
end Rpos;
function Rpos (Count : Natural_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_RPos_NF, 1, EOP, Count));
end Rpos;
function Rpos (Count : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_RPos_NP, 1, EOP, Natural_Ptr (Count)));
end Rpos;
----------
-- Rtab --
----------
function Rtab (Count : Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_RTab_Nat, 1, EOP, Count));
end Rtab;
function Rtab (Count : Natural_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_RTab_NF, 1, EOP, Count));
end Rtab;
function Rtab (Count : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_RTab_NP, 1, EOP, Natural_Ptr (Count)));
end Rtab;
-------------
-- S_To_PE --
-------------
function S_To_PE (Str : PString) return PE_Ptr is
Len : constant Natural := Str'Length;
begin
case Len is
when 0 =>
return new PE'(PC_Null, 1, EOP);
when 1 =>
return new PE'(PC_Char, 1, EOP, Str (Str'First));
when 2 =>
return new PE'(PC_String_2, 1, EOP, Str);
when 3 =>
return new PE'(PC_String_3, 1, EOP, Str);
when 4 =>
return new PE'(PC_String_4, 1, EOP, Str);
when 5 =>
return new PE'(PC_String_5, 1, EOP, Str);
when 6 =>
return new PE'(PC_String_6, 1, EOP, Str);
when others =>
return new PE'(PC_String, 1, EOP, new String'(Str));
end case;
end S_To_PE;
-------------------
-- Set_Successor --
-------------------
-- Note: this procedure is not used by the normal concatenation circuit,
-- since other fixups are required on the left operand in this case, and
-- they might as well be done all together.
procedure Set_Successor (Pat : PE_Ptr; Succ : PE_Ptr) is
begin
if Pat = null then
Uninitialized_Pattern;
elsif Pat = EOP then
Logic_Error;
else
declare
Refs : Ref_Array (1 .. Pat.Index);
-- We build a reference array for L whose N'th element points to
-- the pattern element of L whose original Index value is N.
P : PE_Ptr;
begin
Build_Ref_Array (Pat, Refs);
for J in Refs'Range loop
P := Refs (J);
if P.Pthen = EOP then
P.Pthen := Succ;
end if;
if P.Pcode in PC_Has_Alt and then P.Alt = EOP then
P.Alt := Succ;
end if;
end loop;
end;
end if;
end Set_Successor;
------------
-- Setcur --
------------
function Setcur (Var : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Setcur, 1, EOP, Natural_Ptr (Var)));
end Setcur;
----------
-- Span --
----------
function Span (Str : String) return Pattern is
begin
return (AFC with 0, new PE'(PC_Span_CS, 1, EOP, To_Set (Str)));
end Span;
function Span (Str : VString) return Pattern is
begin
return Span (S (Str));
end Span;
function Span (Str : Character) return Pattern is
begin
return (AFC with 0, new PE'(PC_Span_CH, 1, EOP, Str));
end Span;
function Span (Str : Character_Set) return Pattern is
begin
return (AFC with 0, new PE'(PC_Span_CS, 1, EOP, Str));
end Span;
function Span (Str : not null access VString) return Pattern is
begin
return (AFC with 0, new PE'(PC_Span_VP, 1, EOP, VString_Ptr (Str)));
end Span;
function Span (Str : VString_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Span_VF, 1, EOP, Str));
end Span;
------------
-- Str_BF --
------------
function Str_BF (A : Boolean_Func) return String is
function To_A is new Ada.Unchecked_Conversion (Boolean_Func, Address);
begin
return "BF(" & Image (To_A (A)) & ')';
end Str_BF;
------------
-- Str_FP --
------------
function Str_FP (A : File_Ptr) return String is
begin
return "FP(" & Image (A.all'Address) & ')';
end Str_FP;
------------
-- Str_NF --
------------
function Str_NF (A : Natural_Func) return String is
function To_A is new Ada.Unchecked_Conversion (Natural_Func, Address);
begin
return "NF(" & Image (To_A (A)) & ')';
end Str_NF;
------------
-- Str_NP --
------------
function Str_NP (A : Natural_Ptr) return String is
begin
return "NP(" & Image (A.all'Address) & ')';
end Str_NP;
------------
-- Str_PP --
------------
function Str_PP (A : Pattern_Ptr) return String is
begin
return "PP(" & Image (A.all'Address) & ')';
end Str_PP;
------------
-- Str_VF --
------------
function Str_VF (A : VString_Func) return String is
function To_A is new Ada.Unchecked_Conversion (VString_Func, Address);
begin
return "VF(" & Image (To_A (A)) & ')';
end Str_VF;
------------
-- Str_VP --
------------
function Str_VP (A : VString_Ptr) return String is
begin
return "VP(" & Image (A.all'Address) & ')';
end Str_VP;
-------------
-- Succeed --
-------------
function Succeed return Pattern is
begin
return (AFC with 1, new PE'(PC_Succeed, 1, EOP));
end Succeed;
---------
-- Tab --
---------
function Tab (Count : Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Tab_Nat, 1, EOP, Count));
end Tab;
function Tab (Count : Natural_Func) return Pattern is
begin
return (AFC with 0, new PE'(PC_Tab_NF, 1, EOP, Count));
end Tab;
function Tab (Count : not null access Natural) return Pattern is
begin
return (AFC with 0, new PE'(PC_Tab_NP, 1, EOP, Natural_Ptr (Count)));
end Tab;
---------------------------
-- Uninitialized_Pattern --
---------------------------
procedure Uninitialized_Pattern is
begin
raise Program_Error with
"uninitialized value of type GNAT.Spitbol.Patterns.Pattern";
end Uninitialized_Pattern;
------------
-- XMatch --
------------
procedure XMatch
(Subject : String;
Pat_P : PE_Ptr;
Pat_S : Natural;
Start : out Natural;
Stop : out Natural)
is
Node : PE_Ptr;
-- Pointer to current pattern node. Initialized from Pat_P, and then
-- updated as the match proceeds through its constituent elements.
Length : constant Natural := Subject'Length;
-- Length of string (= Subject'Last, since Subject'First is always 1)
Cursor : Integer := 0;
-- If the value is non-negative, then this value is the index showing
-- the current position of the match in the subject string. The next
-- character to be matched is at Subject (Cursor + 1). Note that since
-- our view of the subject string in XMatch always has a lower bound
-- of one, regardless of original bounds, that this definition exactly
-- corresponds to the cursor value as referenced by functions like Pos.
--
-- If the value is negative, then this is a saved stack pointer,
-- typically a base pointer of an inner or outer region. Cursor
-- temporarily holds such a value when it is popped from the stack
-- by Fail. In all cases, Cursor is reset to a proper non-negative
-- cursor value before the match proceeds (e.g. by propagating the
-- failure and popping a "real" cursor value from the stack.
PE_Unanchored : aliased PE := (PC_Unanchored, 0, Pat_P);
-- Dummy pattern element used in the unanchored case
Stack : Stack_Type;
-- The pattern matching failure stack for this call to Match
Stack_Ptr : Stack_Range;
-- Current stack pointer. This points to the top element of the stack
-- that is currently in use. At the outer level this is the special
-- entry placed on the stack according to the anchor mode.
Stack_Init : constant Stack_Range := Stack'First + 1;
-- This is the initial value of the Stack_Ptr and Stack_Base. The
-- initial (Stack'First) element of the stack is not used so that
-- when we pop the last element off, Stack_Ptr is still in range.
Stack_Base : Stack_Range;
-- This value is the stack base value, i.e. the stack pointer for the
-- first history stack entry in the current stack region. See separate
-- section on handling of recursive pattern matches.
Assign_OnM : Boolean := False;
-- Set True if assign-on-match or write-on-match operations may be
-- present in the history stack, which must then be scanned on a
-- successful match.
procedure Pop_Region;
pragma Inline (Pop_Region);
-- Used at the end of processing of an inner region. If the inner
-- region left no stack entries, then all trace of it is removed.
-- Otherwise a PC_Restore_Region entry is pushed to ensure proper
-- handling of alternatives in the inner region.
procedure Push (Node : PE_Ptr);
pragma Inline (Push);
-- Make entry in pattern matching stack with current cursor value
procedure Push_Region;
pragma Inline (Push_Region);
-- This procedure makes a new region on the history stack. The
-- caller first establishes the special entry on the stack, but
-- does not push the stack pointer. Then this call stacks a
-- PC_Remove_Region node, on top of this entry, using the cursor
-- field of the PC_Remove_Region entry to save the outer level
-- stack base value, and resets the stack base to point to this
-- PC_Remove_Region node.
----------------
-- Pop_Region --
----------------
procedure Pop_Region is
begin
-- If nothing was pushed in the inner region, we can just get
-- rid of it entirely, leaving no traces that it was ever there
if Stack_Ptr = Stack_Base then
Stack_Ptr := Stack_Base - 2;
Stack_Base := Stack (Stack_Ptr + 2).Cursor;
-- If stuff was pushed in the inner region, then we have to
-- push a PC_R_Restore node so that we properly handle possible
-- rematches within the region.
else
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_R_Restore'Access;
Stack_Base := Stack (Stack_Base).Cursor;
end if;
end Pop_Region;
----------
-- Push --
----------
procedure Push (Node : PE_Ptr) is
begin
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Cursor;
Stack (Stack_Ptr).Node := Node;
end Push;
-----------------
-- Push_Region --
-----------------
procedure Push_Region is
begin
Stack_Ptr := Stack_Ptr + 2;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_R_Remove'Access;
Stack_Base := Stack_Ptr;
end Push_Region;
-- Start of processing for XMatch
begin
if Pat_P = null then
Uninitialized_Pattern;
end if;
-- Check we have enough stack for this pattern. This check deals with
-- every possibility except a match of a recursive pattern, where we
-- make a check at each recursion level.
if Pat_S >= Stack_Size - 1 then
raise Pattern_Stack_Overflow;
end if;
-- In anchored mode, the bottom entry on the stack is an abort entry
if Anchored_Mode then
Stack (Stack_Init).Node := CP_Cancel'Access;
Stack (Stack_Init).Cursor := 0;
-- In unanchored more, the bottom entry on the stack references
-- the special pattern element PE_Unanchored, whose Pthen field
-- points to the initial pattern element. The cursor value in this
-- entry is the number of anchor moves so far.
else
Stack (Stack_Init).Node := PE_Unanchored'Unchecked_Access;
Stack (Stack_Init).Cursor := 0;
end if;
Stack_Ptr := Stack_Init;
Stack_Base := Stack_Ptr;
Cursor := 0;
Node := Pat_P;
goto Match;
-----------------------------------------
-- Main Pattern Matching State Control --
-----------------------------------------
-- This is a state machine which uses gotos to change state. The
-- initial state is Match, to initiate the matching of the first
-- element, so the goto Match above starts the match. In the
-- following descriptions, we indicate the global values that
-- are relevant for the state transition.
-- Come here if entire match fails
<<Match_Fail>>
Start := 0;
Stop := 0;
return;
-- Come here if entire match succeeds
-- Cursor current position in subject string
<<Match_Succeed>>
Start := Stack (Stack_Init).Cursor + 1;
Stop := Cursor;
-- Scan history stack for deferred assignments or writes
if Assign_OnM then
for S in Stack_Init .. Stack_Ptr loop
if Stack (S).Node = CP_Assign'Access then
declare
Inner_Base : constant Stack_Range :=
Stack (S + 1).Cursor;
Special_Entry : constant Stack_Range :=
Inner_Base - 1;
Node_OnM : constant PE_Ptr :=
Stack (Special_Entry).Node;
Start : constant Natural :=
Stack (Special_Entry).Cursor + 1;
Stop : constant Natural := Stack (S).Cursor;
begin
if Node_OnM.Pcode = PC_Assign_OnM then
Set_Unbounded_String
(Node_OnM.VP.all, Subject (Start .. Stop));
elsif Node_OnM.Pcode = PC_Write_OnM then
Put_Line (Node_OnM.FP.all, Subject (Start .. Stop));
else
Logic_Error;
end if;
end;
end if;
end loop;
end if;
return;
-- Come here if attempt to match current element fails
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Fail>>
Cursor := Stack (Stack_Ptr).Cursor;
Node := Stack (Stack_Ptr).Node;
Stack_Ptr := Stack_Ptr - 1;
goto Match;
-- Come here if attempt to match current element succeeds
-- Cursor current position in subject string
-- Node pointer to node successfully matched
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Succeed>>
Node := Node.Pthen;
-- Come here to match the next pattern element
-- Cursor current position in subject string
-- Node pointer to node to be matched
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Match>>
--------------------------------------------------
-- Main Pattern Match Element Matching Routines --
--------------------------------------------------
-- Here is the case statement that processes the current node. The
-- processing for each element does one of five things:
-- goto Succeed to move to the successor
-- goto Match_Succeed if the entire match succeeds
-- goto Match_Fail if the entire match fails
-- goto Fail to signal failure of current match
-- Processing is NOT allowed to fall through
case Node.Pcode is
-- Cancel
when PC_Cancel =>
goto Match_Fail;
-- Alternation
when PC_Alt =>
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Any (one character case)
when PC_Any_CH =>
if Cursor < Length
and then Subject (Cursor + 1) = Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- Any (character set case)
when PC_Any_CS =>
if Cursor < Length
and then Is_In (Subject (Cursor + 1), Node.CS)
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- Any (string function case)
when PC_Any_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- Any (string pointer case)
when PC_Any_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- Arb (initial match)
when PC_Arb_X =>
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arb (extension)
when PC_Arb_Y =>
if Cursor < Length then
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
else
goto Fail;
end if;
-- Arbno_S (simple Arbno initialize). This is the node that
-- initiates the match of a simple Arbno structure.
when PC_Arbno_S =>
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arbno_X (Arbno initialize). This is the node that initiates
-- the match of a complex Arbno structure.
when PC_Arbno_X =>
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arbno_Y (Arbno rematch). This is the node that is executed
-- following successful matching of one instance of a complex
-- Arbno pattern.
when PC_Arbno_Y => declare
Null_Match : constant Boolean :=
Cursor = Stack (Stack_Base - 1).Cursor;
begin
Pop_Region;
-- If arbno extension matched null, then immediately fail
if Null_Match then
goto Fail;
end if;
-- Here we must do a stack check to make sure enough stack
-- is left. This check will happen once for each instance of
-- the Arbno pattern that is matched. The Nat field of a
-- PC_Arbno pattern contains the maximum stack entries needed
-- for the Arbno with one instance and the successor pattern
if Stack_Ptr + Node.Nat >= Stack'Last then
raise Pattern_Stack_Overflow;
end if;
goto Succeed;
end;
-- Assign. If this node is executed, it means the assign-on-match
-- or write-on-match operation will not happen after all, so we
-- is propagate the failure, removing the PC_Assign node.
when PC_Assign =>
goto Fail;
-- Assign immediate. This node performs the actual assignment
when PC_Assign_Imm =>
Set_Unbounded_String
(Node.VP.all,
Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor));
Pop_Region;
goto Succeed;
-- Assign on match. This node sets up for the eventual assignment
when PC_Assign_OnM =>
Stack (Stack_Base - 1).Node := Node;
Push (CP_Assign'Access);
Pop_Region;
Assign_OnM := True;
goto Succeed;
-- Bal
when PC_Bal =>
if Cursor >= Length or else Subject (Cursor + 1) = ')' then
goto Fail;
elsif Subject (Cursor + 1) = '(' then
declare
Paren_Count : Natural := 1;
begin
loop
Cursor := Cursor + 1;
if Cursor >= Length then
goto Fail;
elsif Subject (Cursor + 1) = '(' then
Paren_Count := Paren_Count + 1;
elsif Subject (Cursor + 1) = ')' then
Paren_Count := Paren_Count - 1;
exit when Paren_Count = 0;
end if;
end loop;
end;
end if;
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
-- Break (one character case)
when PC_Break_CH =>
while Cursor < Length loop
if Subject (Cursor + 1) = Node.Char then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- Break (character set case)
when PC_Break_CS =>
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), Node.CS) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- Break (string function case)
when PC_Break_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- Break (string pointer case)
when PC_Break_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX (one character case)
when PC_BreakX_CH =>
while Cursor < Length loop
if Subject (Cursor + 1) = Node.Char then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- BreakX (character set case)
when PC_BreakX_CS =>
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), Node.CS) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- BreakX (string function case)
when PC_BreakX_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX (string pointer case)
when PC_BreakX_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX_X (BreakX extension). See section on "Compound Pattern
-- Structures". This node is the alternative that is stacked to
-- skip past the break character and extend the break.
when PC_BreakX_X =>
Cursor := Cursor + 1;
goto Succeed;
-- Character (one character string)
when PC_Char =>
if Cursor < Length
and then Subject (Cursor + 1) = Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- End of Pattern
when PC_EOP =>
if Stack_Base = Stack_Init then
goto Match_Succeed;
-- End of recursive inner match. See separate section on
-- handing of recursive pattern matches for details.
else
Node := Stack (Stack_Base - 1).Node;
Pop_Region;
goto Match;
end if;
-- Fail
when PC_Fail =>
goto Fail;
-- Fence (built in pattern)
when PC_Fence =>
Push (CP_Cancel'Access);
goto Succeed;
-- Fence function node X. This is the node that gets control
-- after a successful match of the fenced pattern.
when PC_Fence_X =>
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_Fence_Y'Access;
Stack_Base := Stack (Stack_Base).Cursor;
goto Succeed;
-- Fence function node Y. This is the node that gets control on
-- a failure that occurs after the fenced pattern has matched.
-- Note: the Cursor at this stage is actually the inner stack
-- base value. We don't reset this, but we do use it to strip
-- off all the entries made by the fenced pattern.
when PC_Fence_Y =>
Stack_Ptr := Cursor - 2;
goto Fail;
-- Len (integer case)
when PC_Len_Nat =>
if Cursor + Node.Nat > Length then
goto Fail;
else
Cursor := Cursor + Node.Nat;
goto Succeed;
end if;
-- Len (Integer function case)
when PC_Len_NF => declare
N : constant Natural := Node.NF.all;
begin
if Cursor + N > Length then
goto Fail;
else
Cursor := Cursor + N;
goto Succeed;
end if;
end;
-- Len (integer pointer case)
when PC_Len_NP =>
if Cursor + Node.NP.all > Length then
goto Fail;
else
Cursor := Cursor + Node.NP.all;
goto Succeed;
end if;
-- NotAny (one character case)
when PC_NotAny_CH =>
if Cursor < Length
and then Subject (Cursor + 1) /= Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- NotAny (character set case)
when PC_NotAny_CS =>
if Cursor < Length
and then not Is_In (Subject (Cursor + 1), Node.CS)
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- NotAny (string function case)
when PC_NotAny_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if Cursor < Length
and then
not Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- NotAny (string pointer case)
when PC_NotAny_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if Cursor < Length
and then
not Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- NSpan (one character case)
when PC_NSpan_CH =>
while Cursor < Length
and then Subject (Cursor + 1) = Node.Char
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
-- NSpan (character set case)
when PC_NSpan_CS =>
while Cursor < Length
and then Is_In (Subject (Cursor + 1), Node.CS)
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
-- NSpan (string function case)
when PC_NSpan_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
end;
-- NSpan (string pointer case)
when PC_NSpan_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
while Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
end;
-- Null string
when PC_Null =>
goto Succeed;
-- Pos (integer case)
when PC_Pos_Nat =>
if Cursor = Node.Nat then
goto Succeed;
else
goto Fail;
end if;
-- Pos (Integer function case)
when PC_Pos_NF => declare
N : constant Natural := Node.NF.all;
begin
if Cursor = N then
goto Succeed;
else
goto Fail;
end if;
end;
-- Pos (integer pointer case)
when PC_Pos_NP =>
if Cursor = Node.NP.all then
goto Succeed;
else
goto Fail;
end if;
-- Predicate function
when PC_Pred_Func =>
if Node.BF.all then
goto Succeed;
else
goto Fail;
end if;
-- Region Enter. Initiate new pattern history stack region
when PC_R_Enter =>
Stack (Stack_Ptr + 1).Cursor := Cursor;
Push_Region;
goto Succeed;
-- Region Remove node. This is the node stacked by an R_Enter.
-- It removes the special format stack entry right underneath, and
-- then restores the outer level stack base and signals failure.
-- Note: the cursor value at this stage is actually the (negative)
-- stack base value for the outer level.
when PC_R_Remove =>
Stack_Base := Cursor;
Stack_Ptr := Stack_Ptr - 1;
goto Fail;
-- Region restore node. This is the node stacked at the end of an
-- inner level match. Its function is to restore the inner level
-- region, so that alternatives in this region can be sought.
-- Note: the Cursor at this stage is actually the negative of the
-- inner stack base value, which we use to restore the inner region.
when PC_R_Restore =>
Stack_Base := Cursor;
goto Fail;
-- Rest
when PC_Rest =>
Cursor := Length;
goto Succeed;
-- Initiate recursive match (pattern pointer case)
when PC_Rpat =>
Stack (Stack_Ptr + 1).Node := Node.Pthen;
Push_Region;
if Stack_Ptr + Node.PP.all.Stk >= Stack_Size then
raise Pattern_Stack_Overflow;
else
Node := Node.PP.all.P;
goto Match;
end if;
-- RPos (integer case)
when PC_RPos_Nat =>
if Cursor = (Length - Node.Nat) then
goto Succeed;
else
goto Fail;
end if;
-- RPos (integer function case)
when PC_RPos_NF => declare
N : constant Natural := Node.NF.all;
begin
if Length - Cursor = N then
goto Succeed;
else
goto Fail;
end if;
end;
-- RPos (integer pointer case)
when PC_RPos_NP =>
if Cursor = (Length - Node.NP.all) then
goto Succeed;
else
goto Fail;
end if;
-- RTab (integer case)
when PC_RTab_Nat =>
if Cursor <= (Length - Node.Nat) then
Cursor := Length - Node.Nat;
goto Succeed;
else
goto Fail;
end if;
-- RTab (integer function case)
when PC_RTab_NF => declare
N : constant Natural := Node.NF.all;
begin
if Length - Cursor >= N then
Cursor := Length - N;
goto Succeed;
else
goto Fail;
end if;
end;
-- RTab (integer pointer case)
when PC_RTab_NP =>
if Cursor <= (Length - Node.NP.all) then
Cursor := Length - Node.NP.all;
goto Succeed;
else
goto Fail;
end if;
-- Cursor assignment
when PC_Setcur =>
Node.Var.all := Cursor;
goto Succeed;
-- Span (one character case)
when PC_Span_CH => declare
P : Natural;
begin
P := Cursor;
while P < Length
and then Subject (P + 1) = Node.Char
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (character set case)
when PC_Span_CS => declare
P : Natural;
begin
P := Cursor;
while P < Length
and then Is_In (Subject (P + 1), Node.CS)
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (string function case)
when PC_Span_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
P : Natural;
begin
Get_String (U, S, L);
P := Cursor;
while P < Length
and then Is_In (Subject (P + 1), S (1 .. L))
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (string pointer case)
when PC_Span_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
P : Natural;
begin
Get_String (U, S, L);
P := Cursor;
while P < Length
and then Is_In (Subject (P + 1), S (1 .. L))
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (two character case)
when PC_String_2 =>
if (Length - Cursor) >= 2
and then Subject (Cursor + 1 .. Cursor + 2) = Node.Str2
then
Cursor := Cursor + 2;
goto Succeed;
else
goto Fail;
end if;
-- String (three character case)
when PC_String_3 =>
if (Length - Cursor) >= 3
and then Subject (Cursor + 1 .. Cursor + 3) = Node.Str3
then
Cursor := Cursor + 3;
goto Succeed;
else
goto Fail;
end if;
-- String (four character case)
when PC_String_4 =>
if (Length - Cursor) >= 4
and then Subject (Cursor + 1 .. Cursor + 4) = Node.Str4
then
Cursor := Cursor + 4;
goto Succeed;
else
goto Fail;
end if;
-- String (five character case)
when PC_String_5 =>
if (Length - Cursor) >= 5
and then Subject (Cursor + 1 .. Cursor + 5) = Node.Str5
then
Cursor := Cursor + 5;
goto Succeed;
else
goto Fail;
end if;
-- String (six character case)
when PC_String_6 =>
if (Length - Cursor) >= 6
and then Subject (Cursor + 1 .. Cursor + 6) = Node.Str6
then
Cursor := Cursor + 6;
goto Succeed;
else
goto Fail;
end if;
-- String (case of more than six characters)
when PC_String => declare
Len : constant Natural := Node.Str'Length;
begin
if (Length - Cursor) >= Len
and then Node.Str.all = Subject (Cursor + 1 .. Cursor + Len)
then
Cursor := Cursor + Len;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (function case)
when PC_String_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if (Length - Cursor) >= L
and then S (1 .. L) = Subject (Cursor + 1 .. Cursor + L)
then
Cursor := Cursor + L;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (pointer case)
when PC_String_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
if (Length - Cursor) >= L
and then S (1 .. L) = Subject (Cursor + 1 .. Cursor + L)
then
Cursor := Cursor + L;
goto Succeed;
else
goto Fail;
end if;
end;
-- Succeed
when PC_Succeed =>
Push (Node);
goto Succeed;
-- Tab (integer case)
when PC_Tab_Nat =>
if Cursor <= Node.Nat then
Cursor := Node.Nat;
goto Succeed;
else
goto Fail;
end if;
-- Tab (integer function case)
when PC_Tab_NF => declare
N : constant Natural := Node.NF.all;
begin
if Cursor <= N then
Cursor := N;
goto Succeed;
else
goto Fail;
end if;
end;
-- Tab (integer pointer case)
when PC_Tab_NP =>
if Cursor <= Node.NP.all then
Cursor := Node.NP.all;
goto Succeed;
else
goto Fail;
end if;
-- Unanchored movement
when PC_Unanchored =>
-- All done if we tried every position
if Cursor > Length then
goto Match_Fail;
-- Otherwise extend the anchor point, and restack ourself
else
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
end if;
-- Write immediate. This node performs the actual write
when PC_Write_Imm =>
Put_Line
(Node.FP.all,
Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor));
Pop_Region;
goto Succeed;
-- Write on match. This node sets up for the eventual write
when PC_Write_OnM =>
Stack (Stack_Base - 1).Node := Node;
Push (CP_Assign'Access);
Pop_Region;
Assign_OnM := True;
goto Succeed;
end case;
-- We are NOT allowed to fall though this case statement, since every
-- match routine must end by executing a goto to the appropriate point
-- in the finite state machine model.
pragma Warnings (Off);
Logic_Error;
pragma Warnings (On);
end XMatch;
-------------
-- XMatchD --
-------------
-- Maintenance note: There is a LOT of code duplication between XMatch
-- and XMatchD. This is quite intentional, the point is to avoid any
-- unnecessary debugging overhead in the XMatch case, but this does mean
-- that any changes to XMatchD must be mirrored in XMatch. In case of
-- any major changes, the proper approach is to delete XMatch, make the
-- changes to XMatchD, and then make a copy of XMatchD, removing all
-- calls to Dout, and all Put and Put_Line operations. This copy becomes
-- the new XMatch.
procedure XMatchD
(Subject : String;
Pat_P : PE_Ptr;
Pat_S : Natural;
Start : out Natural;
Stop : out Natural)
is
Node : PE_Ptr;
-- Pointer to current pattern node. Initialized from Pat_P, and then
-- updated as the match proceeds through its constituent elements.
Length : constant Natural := Subject'Length;
-- Length of string (= Subject'Last, since Subject'First is always 1)
Cursor : Integer := 0;
-- If the value is non-negative, then this value is the index showing
-- the current position of the match in the subject string. The next
-- character to be matched is at Subject (Cursor + 1). Note that since
-- our view of the subject string in XMatch always has a lower bound
-- of one, regardless of original bounds, that this definition exactly
-- corresponds to the cursor value as referenced by functions like Pos.
--
-- If the value is negative, then this is a saved stack pointer,
-- typically a base pointer of an inner or outer region. Cursor
-- temporarily holds such a value when it is popped from the stack
-- by Fail. In all cases, Cursor is reset to a proper non-negative
-- cursor value before the match proceeds (e.g. by propagating the
-- failure and popping a "real" cursor value from the stack.
PE_Unanchored : aliased PE := (PC_Unanchored, 0, Pat_P);
-- Dummy pattern element used in the unanchored case
Region_Level : Natural := 0;
-- Keeps track of recursive region level. This is used only for
-- debugging, it is the number of saved history stack base values.
Stack : Stack_Type;
-- The pattern matching failure stack for this call to Match
Stack_Ptr : Stack_Range;
-- Current stack pointer. This points to the top element of the stack
-- that is currently in use. At the outer level this is the special
-- entry placed on the stack according to the anchor mode.
Stack_Init : constant Stack_Range := Stack'First + 1;
-- This is the initial value of the Stack_Ptr and Stack_Base. The
-- initial (Stack'First) element of the stack is not used so that
-- when we pop the last element off, Stack_Ptr is still in range.
Stack_Base : Stack_Range;
-- This value is the stack base value, i.e. the stack pointer for the
-- first history stack entry in the current stack region. See separate
-- section on handling of recursive pattern matches.
Assign_OnM : Boolean := False;
-- Set True if assign-on-match or write-on-match operations may be
-- present in the history stack, which must then be scanned on a
-- successful match.
procedure Dout (Str : String);
-- Output string to standard error with bars indicating region level
procedure Dout (Str : String; A : Character);
-- Calls Dout with the string S ('A')
procedure Dout (Str : String; A : Character_Set);
-- Calls Dout with the string S ("A")
procedure Dout (Str : String; A : Natural);
-- Calls Dout with the string S (A)
procedure Dout (Str : String; A : String);
-- Calls Dout with the string S ("A")
function Img (P : PE_Ptr) return String;
-- Returns a string of the form #nnn where nnn is P.Index
procedure Pop_Region;
pragma Inline (Pop_Region);
-- Used at the end of processing of an inner region. If the inner
-- region left no stack entries, then all trace of it is removed.
-- Otherwise a PC_Restore_Region entry is pushed to ensure proper
-- handling of alternatives in the inner region.
procedure Push (Node : PE_Ptr);
pragma Inline (Push);
-- Make entry in pattern matching stack with current cursor value
procedure Push_Region;
pragma Inline (Push_Region);
-- This procedure makes a new region on the history stack. The
-- caller first establishes the special entry on the stack, but
-- does not push the stack pointer. Then this call stacks a
-- PC_Remove_Region node, on top of this entry, using the cursor
-- field of the PC_Remove_Region entry to save the outer level
-- stack base value, and resets the stack base to point to this
-- PC_Remove_Region node.
----------
-- Dout --
----------
procedure Dout (Str : String) is
begin
for J in 1 .. Region_Level loop
Put ("| ");
end loop;
Put_Line (Str);
end Dout;
procedure Dout (Str : String; A : Character) is
begin
Dout (Str & " ('" & A & "')");
end Dout;
procedure Dout (Str : String; A : Character_Set) is
begin
Dout (Str & " (" & Image (To_Sequence (A)) & ')');
end Dout;
procedure Dout (Str : String; A : Natural) is
begin
Dout (Str & " (" & A & ')');
end Dout;
procedure Dout (Str : String; A : String) is
begin
Dout (Str & " (" & Image (A) & ')');
end Dout;
---------
-- Img --
---------
function Img (P : PE_Ptr) return String is
begin
return "#" & Integer (P.Index) & " ";
end Img;
----------------
-- Pop_Region --
----------------
procedure Pop_Region is
begin
Region_Level := Region_Level - 1;
-- If nothing was pushed in the inner region, we can just get
-- rid of it entirely, leaving no traces that it was ever there
if Stack_Ptr = Stack_Base then
Stack_Ptr := Stack_Base - 2;
Stack_Base := Stack (Stack_Ptr + 2).Cursor;
-- If stuff was pushed in the inner region, then we have to
-- push a PC_R_Restore node so that we properly handle possible
-- rematches within the region.
else
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_R_Restore'Access;
Stack_Base := Stack (Stack_Base).Cursor;
end if;
end Pop_Region;
----------
-- Push --
----------
procedure Push (Node : PE_Ptr) is
begin
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Cursor;
Stack (Stack_Ptr).Node := Node;
end Push;
-----------------
-- Push_Region --
-----------------
procedure Push_Region is
begin
Region_Level := Region_Level + 1;
Stack_Ptr := Stack_Ptr + 2;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_R_Remove'Access;
Stack_Base := Stack_Ptr;
end Push_Region;
-- Start of processing for XMatchD
begin
New_Line;
Put_Line ("Initiating pattern match, subject = " & Image (Subject));
Put ("--------------------------------------");
for J in 1 .. Length loop
Put ('-');
end loop;
New_Line;
Put_Line ("subject length = " & Length);
if Pat_P = null then
Uninitialized_Pattern;
end if;
-- Check we have enough stack for this pattern. This check deals with
-- every possibility except a match of a recursive pattern, where we
-- make a check at each recursion level.
if Pat_S >= Stack_Size - 1 then
raise Pattern_Stack_Overflow;
end if;
-- In anchored mode, the bottom entry on the stack is an abort entry
if Anchored_Mode then
Stack (Stack_Init).Node := CP_Cancel'Access;
Stack (Stack_Init).Cursor := 0;
-- In unanchored more, the bottom entry on the stack references
-- the special pattern element PE_Unanchored, whose Pthen field
-- points to the initial pattern element. The cursor value in this
-- entry is the number of anchor moves so far.
else
Stack (Stack_Init).Node := PE_Unanchored'Unchecked_Access;
Stack (Stack_Init).Cursor := 0;
end if;
Stack_Ptr := Stack_Init;
Stack_Base := Stack_Ptr;
Cursor := 0;
Node := Pat_P;
goto Match;
-----------------------------------------
-- Main Pattern Matching State Control --
-----------------------------------------
-- This is a state machine which uses gotos to change state. The
-- initial state is Match, to initiate the matching of the first
-- element, so the goto Match above starts the match. In the
-- following descriptions, we indicate the global values that
-- are relevant for the state transition.
-- Come here if entire match fails
<<Match_Fail>>
Dout ("match fails");
New_Line;
Start := 0;
Stop := 0;
return;
-- Come here if entire match succeeds
-- Cursor current position in subject string
<<Match_Succeed>>
Dout ("match succeeds");
Start := Stack (Stack_Init).Cursor + 1;
Stop := Cursor;
Dout ("first matched character index = " & Start);
Dout ("last matched character index = " & Stop);
Dout ("matched substring = " & Image (Subject (Start .. Stop)));
-- Scan history stack for deferred assignments or writes
if Assign_OnM then
for S in Stack'First .. Stack_Ptr loop
if Stack (S).Node = CP_Assign'Access then
declare
Inner_Base : constant Stack_Range :=
Stack (S + 1).Cursor;
Special_Entry : constant Stack_Range :=
Inner_Base - 1;
Node_OnM : constant PE_Ptr :=
Stack (Special_Entry).Node;
Start : constant Natural :=
Stack (Special_Entry).Cursor + 1;
Stop : constant Natural := Stack (S).Cursor;
begin
if Node_OnM.Pcode = PC_Assign_OnM then
Set_Unbounded_String
(Node_OnM.VP.all, Subject (Start .. Stop));
Dout
(Img (Stack (S).Node) &
"deferred assignment of " &
Image (Subject (Start .. Stop)));
elsif Node_OnM.Pcode = PC_Write_OnM then
Put_Line (Node_OnM.FP.all, Subject (Start .. Stop));
Dout
(Img (Stack (S).Node) &
"deferred write of " &
Image (Subject (Start .. Stop)));
else
Logic_Error;
end if;
end;
end if;
end loop;
end if;
New_Line;
return;
-- Come here if attempt to match current element fails
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Fail>>
Cursor := Stack (Stack_Ptr).Cursor;
Node := Stack (Stack_Ptr).Node;
Stack_Ptr := Stack_Ptr - 1;
if Cursor >= 0 then
Dout ("failure, cursor reset to " & Cursor);
end if;
goto Match;
-- Come here if attempt to match current element succeeds
-- Cursor current position in subject string
-- Node pointer to node successfully matched
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Succeed>>
Dout ("success, cursor = " & Cursor);
Node := Node.Pthen;
-- Come here to match the next pattern element
-- Cursor current position in subject string
-- Node pointer to node to be matched
-- Stack_Base current stack base
-- Stack_Ptr current stack pointer
<<Match>>
--------------------------------------------------
-- Main Pattern Match Element Matching Routines --
--------------------------------------------------
-- Here is the case statement that processes the current node. The
-- processing for each element does one of five things:
-- goto Succeed to move to the successor
-- goto Match_Succeed if the entire match succeeds
-- goto Match_Fail if the entire match fails
-- goto Fail to signal failure of current match
-- Processing is NOT allowed to fall through
case Node.Pcode is
-- Cancel
when PC_Cancel =>
Dout (Img (Node) & "matching Cancel");
goto Match_Fail;
-- Alternation
when PC_Alt =>
Dout (Img (Node) & "setting up alternative " & Img (Node.Alt));
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Any (one character case)
when PC_Any_CH =>
Dout (Img (Node) & "matching Any", Node.Char);
if Cursor < Length
and then Subject (Cursor + 1) = Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- Any (character set case)
when PC_Any_CS =>
Dout (Img (Node) & "matching Any", Node.CS);
if Cursor < Length
and then Is_In (Subject (Cursor + 1), Node.CS)
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- Any (string function case)
when PC_Any_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Any", S (1 .. L));
if Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- Any (string pointer case)
when PC_Any_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Any", S (1 .. L));
if Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- Arb (initial match)
when PC_Arb_X =>
Dout (Img (Node) & "matching Arb");
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arb (extension)
when PC_Arb_Y =>
Dout (Img (Node) & "extending Arb");
if Cursor < Length then
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
else
goto Fail;
end if;
-- Arbno_S (simple Arbno initialize). This is the node that
-- initiates the match of a simple Arbno structure.
when PC_Arbno_S =>
Dout (Img (Node) &
"setting up Arbno alternative " & Img (Node.Alt));
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arbno_X (Arbno initialize). This is the node that initiates
-- the match of a complex Arbno structure.
when PC_Arbno_X =>
Dout (Img (Node) &
"setting up Arbno alternative " & Img (Node.Alt));
Push (Node.Alt);
Node := Node.Pthen;
goto Match;
-- Arbno_Y (Arbno rematch). This is the node that is executed
-- following successful matching of one instance of a complex
-- Arbno pattern.
when PC_Arbno_Y => declare
Null_Match : constant Boolean :=
Cursor = Stack (Stack_Base - 1).Cursor;
begin
Dout (Img (Node) & "extending Arbno");
Pop_Region;
-- If arbno extension matched null, then immediately fail
if Null_Match then
Dout ("Arbno extension matched null, so fails");
goto Fail;
end if;
-- Here we must do a stack check to make sure enough stack
-- is left. This check will happen once for each instance of
-- the Arbno pattern that is matched. The Nat field of a
-- PC_Arbno pattern contains the maximum stack entries needed
-- for the Arbno with one instance and the successor pattern
if Stack_Ptr + Node.Nat >= Stack'Last then
raise Pattern_Stack_Overflow;
end if;
goto Succeed;
end;
-- Assign. If this node is executed, it means the assign-on-match
-- or write-on-match operation will not happen after all, so we
-- is propagate the failure, removing the PC_Assign node.
when PC_Assign =>
Dout (Img (Node) & "deferred assign/write cancelled");
goto Fail;
-- Assign immediate. This node performs the actual assignment
when PC_Assign_Imm =>
Dout
(Img (Node) & "executing immediate assignment of " &
Image (Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor)));
Set_Unbounded_String
(Node.VP.all,
Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor));
Pop_Region;
goto Succeed;
-- Assign on match. This node sets up for the eventual assignment
when PC_Assign_OnM =>
Dout (Img (Node) & "registering deferred assignment");
Stack (Stack_Base - 1).Node := Node;
Push (CP_Assign'Access);
Pop_Region;
Assign_OnM := True;
goto Succeed;
-- Bal
when PC_Bal =>
Dout (Img (Node) & "matching or extending Bal");
if Cursor >= Length or else Subject (Cursor + 1) = ')' then
goto Fail;
elsif Subject (Cursor + 1) = '(' then
declare
Paren_Count : Natural := 1;
begin
loop
Cursor := Cursor + 1;
if Cursor >= Length then
goto Fail;
elsif Subject (Cursor + 1) = '(' then
Paren_Count := Paren_Count + 1;
elsif Subject (Cursor + 1) = ')' then
Paren_Count := Paren_Count - 1;
exit when Paren_Count = 0;
end if;
end loop;
end;
end if;
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
-- Break (one character case)
when PC_Break_CH =>
Dout (Img (Node) & "matching Break", Node.Char);
while Cursor < Length loop
if Subject (Cursor + 1) = Node.Char then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- Break (character set case)
when PC_Break_CS =>
Dout (Img (Node) & "matching Break", Node.CS);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), Node.CS) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- Break (string function case)
when PC_Break_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Break", S (1 .. L));
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- Break (string pointer case)
when PC_Break_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Break", S (1 .. L));
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX (one character case)
when PC_BreakX_CH =>
Dout (Img (Node) & "matching BreakX", Node.Char);
while Cursor < Length loop
if Subject (Cursor + 1) = Node.Char then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- BreakX (character set case)
when PC_BreakX_CS =>
Dout (Img (Node) & "matching BreakX", Node.CS);
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), Node.CS) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
-- BreakX (string function case)
when PC_BreakX_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching BreakX", S (1 .. L));
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX (string pointer case)
when PC_BreakX_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching BreakX", S (1 .. L));
while Cursor < Length loop
if Is_In (Subject (Cursor + 1), S (1 .. L)) then
goto Succeed;
else
Cursor := Cursor + 1;
end if;
end loop;
goto Fail;
end;
-- BreakX_X (BreakX extension). See section on "Compound Pattern
-- Structures". This node is the alternative that is stacked
-- to skip past the break character and extend the break.
when PC_BreakX_X =>
Dout (Img (Node) & "extending BreakX");
Cursor := Cursor + 1;
goto Succeed;
-- Character (one character string)
when PC_Char =>
Dout (Img (Node) & "matching '" & Node.Char & ''');
if Cursor < Length
and then Subject (Cursor + 1) = Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- End of Pattern
when PC_EOP =>
if Stack_Base = Stack_Init then
Dout ("end of pattern");
goto Match_Succeed;
-- End of recursive inner match. See separate section on
-- handing of recursive pattern matches for details.
else
Dout ("terminating recursive match");
Node := Stack (Stack_Base - 1).Node;
Pop_Region;
goto Match;
end if;
-- Fail
when PC_Fail =>
Dout (Img (Node) & "matching Fail");
goto Fail;
-- Fence (built in pattern)
when PC_Fence =>
Dout (Img (Node) & "matching Fence");
Push (CP_Cancel'Access);
goto Succeed;
-- Fence function node X. This is the node that gets control
-- after a successful match of the fenced pattern.
when PC_Fence_X =>
Dout (Img (Node) & "matching Fence function");
Stack_Ptr := Stack_Ptr + 1;
Stack (Stack_Ptr).Cursor := Stack_Base;
Stack (Stack_Ptr).Node := CP_Fence_Y'Access;
Stack_Base := Stack (Stack_Base).Cursor;
Region_Level := Region_Level - 1;
goto Succeed;
-- Fence function node Y. This is the node that gets control on
-- a failure that occurs after the fenced pattern has matched.
-- Note: the Cursor at this stage is actually the inner stack
-- base value. We don't reset this, but we do use it to strip
-- off all the entries made by the fenced pattern.
when PC_Fence_Y =>
Dout (Img (Node) & "pattern matched by Fence caused failure");
Stack_Ptr := Cursor - 2;
goto Fail;
-- Len (integer case)
when PC_Len_Nat =>
Dout (Img (Node) & "matching Len", Node.Nat);
if Cursor + Node.Nat > Length then
goto Fail;
else
Cursor := Cursor + Node.Nat;
goto Succeed;
end if;
-- Len (Integer function case)
when PC_Len_NF => declare
N : constant Natural := Node.NF.all;
begin
Dout (Img (Node) & "matching Len", N);
if Cursor + N > Length then
goto Fail;
else
Cursor := Cursor + N;
goto Succeed;
end if;
end;
-- Len (integer pointer case)
when PC_Len_NP =>
Dout (Img (Node) & "matching Len", Node.NP.all);
if Cursor + Node.NP.all > Length then
goto Fail;
else
Cursor := Cursor + Node.NP.all;
goto Succeed;
end if;
-- NotAny (one character case)
when PC_NotAny_CH =>
Dout (Img (Node) & "matching NotAny", Node.Char);
if Cursor < Length
and then Subject (Cursor + 1) /= Node.Char
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- NotAny (character set case)
when PC_NotAny_CS =>
Dout (Img (Node) & "matching NotAny", Node.CS);
if Cursor < Length
and then not Is_In (Subject (Cursor + 1), Node.CS)
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
-- NotAny (string function case)
when PC_NotAny_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching NotAny", S (1 .. L));
if Cursor < Length
and then
not Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- NotAny (string pointer case)
when PC_NotAny_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching NotAny", S (1 .. L));
if Cursor < Length
and then
not Is_In (Subject (Cursor + 1), S (1 .. L))
then
Cursor := Cursor + 1;
goto Succeed;
else
goto Fail;
end if;
end;
-- NSpan (one character case)
when PC_NSpan_CH =>
Dout (Img (Node) & "matching NSpan", Node.Char);
while Cursor < Length
and then Subject (Cursor + 1) = Node.Char
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
-- NSpan (character set case)
when PC_NSpan_CS =>
Dout (Img (Node) & "matching NSpan", Node.CS);
while Cursor < Length
and then Is_In (Subject (Cursor + 1), Node.CS)
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
-- NSpan (string function case)
when PC_NSpan_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching NSpan", S (1 .. L));
while Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
end;
-- NSpan (string pointer case)
when PC_NSpan_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching NSpan", S (1 .. L));
while Cursor < Length
and then Is_In (Subject (Cursor + 1), S (1 .. L))
loop
Cursor := Cursor + 1;
end loop;
goto Succeed;
end;
when PC_Null =>
Dout (Img (Node) & "matching null");
goto Succeed;
-- Pos (integer case)
when PC_Pos_Nat =>
Dout (Img (Node) & "matching Pos", Node.Nat);
if Cursor = Node.Nat then
goto Succeed;
else
goto Fail;
end if;
-- Pos (Integer function case)
when PC_Pos_NF => declare
N : constant Natural := Node.NF.all;
begin
Dout (Img (Node) & "matching Pos", N);
if Cursor = N then
goto Succeed;
else
goto Fail;
end if;
end;
-- Pos (integer pointer case)
when PC_Pos_NP =>
Dout (Img (Node) & "matching Pos", Node.NP.all);
if Cursor = Node.NP.all then
goto Succeed;
else
goto Fail;
end if;
-- Predicate function
when PC_Pred_Func =>
Dout (Img (Node) & "matching predicate function");
if Node.BF.all then
goto Succeed;
else
goto Fail;
end if;
-- Region Enter. Initiate new pattern history stack region
when PC_R_Enter =>
Dout (Img (Node) & "starting match of nested pattern");
Stack (Stack_Ptr + 1).Cursor := Cursor;
Push_Region;
goto Succeed;
-- Region Remove node. This is the node stacked by an R_Enter.
-- It removes the special format stack entry right underneath, and
-- then restores the outer level stack base and signals failure.
-- Note: the cursor value at this stage is actually the (negative)
-- stack base value for the outer level.
when PC_R_Remove =>
Dout ("failure, match of nested pattern terminated");
Stack_Base := Cursor;
Region_Level := Region_Level - 1;
Stack_Ptr := Stack_Ptr - 1;
goto Fail;
-- Region restore node. This is the node stacked at the end of an
-- inner level match. Its function is to restore the inner level
-- region, so that alternatives in this region can be sought.
-- Note: the Cursor at this stage is actually the negative of the
-- inner stack base value, which we use to restore the inner region.
when PC_R_Restore =>
Dout ("failure, search for alternatives in nested pattern");
Region_Level := Region_Level + 1;
Stack_Base := Cursor;
goto Fail;
-- Rest
when PC_Rest =>
Dout (Img (Node) & "matching Rest");
Cursor := Length;
goto Succeed;
-- Initiate recursive match (pattern pointer case)
when PC_Rpat =>
Stack (Stack_Ptr + 1).Node := Node.Pthen;
Push_Region;
Dout (Img (Node) & "initiating recursive match");
if Stack_Ptr + Node.PP.all.Stk >= Stack_Size then
raise Pattern_Stack_Overflow;
else
Node := Node.PP.all.P;
goto Match;
end if;
-- RPos (integer case)
when PC_RPos_Nat =>
Dout (Img (Node) & "matching RPos", Node.Nat);
if Cursor = (Length - Node.Nat) then
goto Succeed;
else
goto Fail;
end if;
-- RPos (integer function case)
when PC_RPos_NF => declare
N : constant Natural := Node.NF.all;
begin
Dout (Img (Node) & "matching RPos", N);
if Length - Cursor = N then
goto Succeed;
else
goto Fail;
end if;
end;
-- RPos (integer pointer case)
when PC_RPos_NP =>
Dout (Img (Node) & "matching RPos", Node.NP.all);
if Cursor = (Length - Node.NP.all) then
goto Succeed;
else
goto Fail;
end if;
-- RTab (integer case)
when PC_RTab_Nat =>
Dout (Img (Node) & "matching RTab", Node.Nat);
if Cursor <= (Length - Node.Nat) then
Cursor := Length - Node.Nat;
goto Succeed;
else
goto Fail;
end if;
-- RTab (integer function case)
when PC_RTab_NF => declare
N : constant Natural := Node.NF.all;
begin
Dout (Img (Node) & "matching RPos", N);
if Length - Cursor >= N then
Cursor := Length - N;
goto Succeed;
else
goto Fail;
end if;
end;
-- RTab (integer pointer case)
when PC_RTab_NP =>
Dout (Img (Node) & "matching RPos", Node.NP.all);
if Cursor <= (Length - Node.NP.all) then
Cursor := Length - Node.NP.all;
goto Succeed;
else
goto Fail;
end if;
-- Cursor assignment
when PC_Setcur =>
Dout (Img (Node) & "matching Setcur");
Node.Var.all := Cursor;
goto Succeed;
-- Span (one character case)
when PC_Span_CH => declare
P : Natural := Cursor;
begin
Dout (Img (Node) & "matching Span", Node.Char);
while P < Length
and then Subject (P + 1) = Node.Char
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (character set case)
when PC_Span_CS => declare
P : Natural := Cursor;
begin
Dout (Img (Node) & "matching Span", Node.CS);
while P < Length
and then Is_In (Subject (P + 1), Node.CS)
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (string function case)
when PC_Span_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
P : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Span", S (1 .. L));
P := Cursor;
while P < Length
and then Is_In (Subject (P + 1), S (1 .. L))
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- Span (string pointer case)
when PC_Span_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
P : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching Span", S (1 .. L));
P := Cursor;
while P < Length
and then Is_In (Subject (P + 1), S (1 .. L))
loop
P := P + 1;
end loop;
if P /= Cursor then
Cursor := P;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (two character case)
when PC_String_2 =>
Dout (Img (Node) & "matching " & Image (Node.Str2));
if (Length - Cursor) >= 2
and then Subject (Cursor + 1 .. Cursor + 2) = Node.Str2
then
Cursor := Cursor + 2;
goto Succeed;
else
goto Fail;
end if;
-- String (three character case)
when PC_String_3 =>
Dout (Img (Node) & "matching " & Image (Node.Str3));
if (Length - Cursor) >= 3
and then Subject (Cursor + 1 .. Cursor + 3) = Node.Str3
then
Cursor := Cursor + 3;
goto Succeed;
else
goto Fail;
end if;
-- String (four character case)
when PC_String_4 =>
Dout (Img (Node) & "matching " & Image (Node.Str4));
if (Length - Cursor) >= 4
and then Subject (Cursor + 1 .. Cursor + 4) = Node.Str4
then
Cursor := Cursor + 4;
goto Succeed;
else
goto Fail;
end if;
-- String (five character case)
when PC_String_5 =>
Dout (Img (Node) & "matching " & Image (Node.Str5));
if (Length - Cursor) >= 5
and then Subject (Cursor + 1 .. Cursor + 5) = Node.Str5
then
Cursor := Cursor + 5;
goto Succeed;
else
goto Fail;
end if;
-- String (six character case)
when PC_String_6 =>
Dout (Img (Node) & "matching " & Image (Node.Str6));
if (Length - Cursor) >= 6
and then Subject (Cursor + 1 .. Cursor + 6) = Node.Str6
then
Cursor := Cursor + 6;
goto Succeed;
else
goto Fail;
end if;
-- String (case of more than six characters)
when PC_String => declare
Len : constant Natural := Node.Str'Length;
begin
Dout (Img (Node) & "matching " & Image (Node.Str.all));
if (Length - Cursor) >= Len
and then Node.Str.all = Subject (Cursor + 1 .. Cursor + Len)
then
Cursor := Cursor + Len;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (function case)
when PC_String_VF => declare
U : constant VString := Node.VF.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching " & Image (S (1 .. L)));
if (Length - Cursor) >= L
and then S (1 .. L) = Subject (Cursor + 1 .. Cursor + L)
then
Cursor := Cursor + L;
goto Succeed;
else
goto Fail;
end if;
end;
-- String (vstring pointer case)
when PC_String_VP => declare
U : constant VString := Node.VP.all;
S : Big_String_Access;
L : Natural;
begin
Get_String (U, S, L);
Dout (Img (Node) & "matching " & Image (S (1 .. L)));
if (Length - Cursor) >= L
and then S (1 .. L) = Subject (Cursor + 1 .. Cursor + L)
then
Cursor := Cursor + L;
goto Succeed;
else
goto Fail;
end if;
end;
-- Succeed
when PC_Succeed =>
Dout (Img (Node) & "matching Succeed");
Push (Node);
goto Succeed;
-- Tab (integer case)
when PC_Tab_Nat =>
Dout (Img (Node) & "matching Tab", Node.Nat);
if Cursor <= Node.Nat then
Cursor := Node.Nat;
goto Succeed;
else
goto Fail;
end if;
-- Tab (integer function case)
when PC_Tab_NF => declare
N : constant Natural := Node.NF.all;
begin
Dout (Img (Node) & "matching Tab ", N);
if Cursor <= N then
Cursor := N;
goto Succeed;
else
goto Fail;
end if;
end;
-- Tab (integer pointer case)
when PC_Tab_NP =>
Dout (Img (Node) & "matching Tab ", Node.NP.all);
if Cursor <= Node.NP.all then
Cursor := Node.NP.all;
goto Succeed;
else
goto Fail;
end if;
-- Unanchored movement
when PC_Unanchored =>
Dout ("attempting to move anchor point");
-- All done if we tried every position
if Cursor > Length then
goto Match_Fail;
-- Otherwise extend the anchor point, and restack ourself
else
Cursor := Cursor + 1;
Push (Node);
goto Succeed;
end if;
-- Write immediate. This node performs the actual write
when PC_Write_Imm =>
Dout (Img (Node) & "executing immediate write of " &
Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor));
Put_Line
(Node.FP.all,
Subject (Stack (Stack_Base - 1).Cursor + 1 .. Cursor));
Pop_Region;
goto Succeed;
-- Write on match. This node sets up for the eventual write
when PC_Write_OnM =>
Dout (Img (Node) & "registering deferred write");
Stack (Stack_Base - 1).Node := Node;
Push (CP_Assign'Access);
Pop_Region;
Assign_OnM := True;
goto Succeed;
end case;
-- We are NOT allowed to fall though this case statement, since every
-- match routine must end by executing a goto to the appropriate point
-- in the finite state machine model.
pragma Warnings (Off);
Logic_Error;
pragma Warnings (On);
end XMatchD;
end GNAT.Spitbol.Patterns;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . V E C T O R S . B O O L E A N _ O P E R A T I O N S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2002-2019, 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 System.Vectors.Boolean_Operations is
SU : constant := Storage_Unit;
-- Convenient short hand, used throughout
-- The coding of this unit depends on the fact that the Component_Size
-- of a normally declared array of Boolean is equal to Storage_Unit. We
-- can't use the Component_Size directly since it is non-static. The
-- following declaration checks that this declaration is correct
type Boolean_Array is array (Integer range <>) of Boolean;
pragma Compile_Time_Error
(Boolean_Array'Component_Size /= SU, "run time compile failure");
-- NOTE: The boolean literals must be qualified here to avoid visibility
-- anomalies when this package is compiled through Rtsfind, in a context
-- that includes a user-defined type derived from boolean.
True_Val : constant Vector := Standard.True'Enum_Rep
+ Standard.True'Enum_Rep * 2**SU
+ Standard.True'Enum_Rep * 2**(SU * 2)
+ Standard.True'Enum_Rep * 2**(SU * 3)
+ Standard.True'Enum_Rep * 2**(SU * 4)
+ Standard.True'Enum_Rep * 2**(SU * 5)
+ Standard.True'Enum_Rep * 2**(SU * 6)
+ Standard.True'Enum_Rep * 2**(SU * 7);
-- This constant represents the bits to be flipped to perform a logical
-- "not" on a vector of booleans, independent of the actual
-- representation of True.
-- The representations of (False, True) are assumed to be zero/one and
-- the maximum number of unpacked booleans per Vector is assumed to be 8.
pragma Assert (Standard.False'Enum_Rep = 0);
pragma Assert (Standard.True'Enum_Rep = 1);
pragma Assert (Vector'Size / Storage_Unit <= 8);
-- The reason we need to do these gymnastics is that no call to
-- Unchecked_Conversion can be made at the library level since this
-- unit is pure. Also a conversion from the array type to the Vector type
-- inside the body of "not" is inefficient because of alignment issues.
-----------
-- "not" --
-----------
function "not" (Item : Vectors.Vector) return Vectors.Vector is
begin
return Item xor True_Val;
end "not";
----------
-- Nand --
----------
function Nand (Left, Right : Boolean) return Boolean is
begin
return not (Left and Right);
end Nand;
function Nand (Left, Right : Vectors.Vector) return Vectors.Vector is
begin
return not (Left and Right);
end Nand;
---------
-- Nor --
---------
function Nor (Left, Right : Boolean) return Boolean is
begin
return not (Left or Right);
end Nor;
function Nor (Left, Right : Vectors.Vector) return Vectors.Vector is
begin
return not (Left or Right);
end Nor;
----------
-- Nxor --
----------
function Nxor (Left, Right : Boolean) return Boolean is
begin
return not (Left xor Right);
end Nxor;
function Nxor (Left, Right : Vectors.Vector) return Vectors.Vector is
begin
return not (Left xor Right);
end Nxor;
end System.Vectors.Boolean_Operations;
|
with Ada.Calendar;
package Timer is
type T is tagged private;
function start return T;
function reset(tm: in out T) return Float;
procedure reset(tm: in out T);
procedure report(tm: in out T);
procedure report(tm: in out T; message: in String);
private
type T is tagged record
clock: Ada.Calendar.Time;
end record;
end Timer;
|
with Ada.Text_IO;
procedure Positives is
begin
for Value in Positive'Range loop
Ada.Text_IO.Put_Line (Positive'Image (Value));
end loop;
end Positives;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2017 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with GL.Debug;
package body Orka.Rendering.Fences is
use GL.Debug;
package Messages is new GL.Debug.Messages (Third_Party, Performance);
function Create_Buffer_Fence return Buffer_Fence is
begin
return Result : Buffer_Fence do
Result.Index := Index_Type'First;
end return;
end Create_Buffer_Fence;
procedure Prepare_Index (Object : in out Buffer_Fence; Status : out Fence_Status) is
use GL.Fences;
begin
if not Object.Fences (Object.Index).Initialized then
Status := Not_Initialized;
return;
end if;
case Object.Fences (Object.Index).Client_Wait (Maximum_Wait) is
when Condition_Satisfied =>
Messages.Log (Medium, "Fence not already signalled");
Status := Signaled;
when Timeout_Expired | Wait_Failed =>
Messages.Log (High, "Fence timed out or failed");
Status := Not_Signaled;
when Already_Signaled =>
Status := Signaled;
end case;
end Prepare_Index;
procedure Advance_Index (Object : in out Buffer_Fence) is
begin
Object.Fences (Object.Index).Set_Fence;
Object.Index := Object.Index + 1;
end Advance_Index;
end Orka.Rendering.Fences;
|
-----------------------------------------------------------------------
-- Appenders -- Log appenders
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011 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.Calendar.Formatting;
with Ada.Strings;
with Ada.Strings.Fixed;
with Util.Strings.Transforms;
with Util.Log.Loggers;
package body Util.Log.Appenders is
use Ada;
-- ------------------------------
-- Get the log level that triggers display of the log events
-- ------------------------------
function Get_Level (Self : in Appender) return Level_Type is
begin
return Self.Level;
end Get_Level;
-- ------------------------------
-- Set the log level.
-- ------------------------------
procedure Set_Level (Self : in out Appender;
Name : in String;
Properties : in Util.Properties.Manager;
Level : in Level_Type) is
Prop_Name : constant String := Name & ".level";
begin
if Properties.Exists (Prop_Name) then
Self.Level := Get_Level (Properties.Get (Prop_Name), Level);
else
Self.Level := Level;
end if;
end Set_Level;
-- ------------------------------
-- Set the log layout format.
-- ------------------------------
procedure Set_Layout (Self : in out Appender;
Name : in String;
Properties : in Util.Properties.Manager;
Layout : in Layout_Type) is
use Ada.Strings;
use Util.Strings.Transforms;
Prop_Name : constant String := Name & ".layout";
begin
if Properties.Exists (Prop_Name) then
declare
Value : constant String
:= To_Lower_Case (Fixed.Trim (Properties.Get (Prop_Name), Both));
begin
if Value = "message" then
Self.Layout := MESSAGE;
elsif Value = "level-message" then
Self.Layout := LEVEL_MESSAGE;
elsif Value = "date-level-message" or Value = "level-date-message" then
Self.Layout := DATE_LEVEL_MESSAGE;
else
Self.Layout := FULL;
end if;
end;
else
Self.Layout := Layout;
end if;
end Set_Layout;
-- ------------------------------
-- Format the event into a string
-- ------------------------------
function Format (Self : in Appender;
Event : in Log_Event) return String is
begin
case Self.Layout is
when MESSAGE =>
return To_String (Event.Message);
when LEVEL_MESSAGE =>
return Get_Level_Name (Event.Level) & ": " & To_String (Event.Message);
when DATE_LEVEL_MESSAGE =>
return "[" & Calendar.Formatting.Image (Event.Time) & "] "
& Get_Level_Name (Event.Level) & ": "
& To_String (Event.Message);
when FULL =>
return "[" & Calendar.Formatting.Image (Event.Time) & "] "
& Get_Level_Name (Event.Level) & " - "
& Loggers.Get_Logger_Name (Event.Logger.all) & " - "
& To_String (Event.Message);
end case;
end Format;
procedure Append (Self : in out File_Appender;
Event : in Log_Event) is
begin
if Self.Level >= Event.Level then
Text_IO.Put_Line (Self.Output, Format (Self, Event));
end if;
end Append;
-- ------------------------------
-- Flush the log events.
-- ------------------------------
overriding
procedure Flush (Self : in out File_Appender) is
begin
Text_IO.Flush (Self.Output);
end Flush;
-- Flush and close the file.
overriding
procedure Finalize (Self : in out File_Appender) is
begin
Self.Flush;
Text_IO.Close (File => Self.Output);
end Finalize;
-- ------------------------------
-- Create a file appender and configure it according to the properties
-- ------------------------------
function Create_File_Appender (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access is
Path : constant String := Properties.Get (Name & ".File");
Result : constant File_Appender_Access := new File_Appender;
begin
Result.Set_Level (Name, Properties, Default);
Result.Set_Layout (Name, Properties, FULL);
Text_IO.Open (File => Result.Output,
Name => Path,
Mode => Text_IO.Out_File);
return Result.all'Access;
exception
when Text_IO.Name_Error =>
Text_IO.Create (File => Result.Output, Name => Path);
return Result.all'Access;
end Create_File_Appender;
-- ------------------------------
-- Set the file where the appender will write the logs
-- ------------------------------
procedure Set_File (Self : in out File_Appender;
Path : in String) is
begin
Text_IO.Open (File => Self.Output,
Name => Path,
Mode => Text_IO.Out_File);
end Set_File;
procedure Append (Self : in out Console_Appender;
Event : in Log_Event) is
begin
if Self.Level >= Event.Level then
Text_IO.Put_Line (Format (Self, Event));
end if;
end Append;
-- ------------------------------
-- Flush the log events.
-- ------------------------------
overriding
procedure Flush (Self : in out Console_Appender) is
pragma Unreferenced (Self);
begin
Text_IO.Flush;
end Flush;
overriding
procedure Append (Self : in out List_Appender;
Event : in Log_Event) is
begin
for I in 1 .. Self.Count loop
Self.Appenders (I).Append (Event);
end loop;
end Append;
-- ------------------------------
-- Create a console appender and configure it according to the properties
-- ------------------------------
function Create_Console_Appender (Name : in String;
Properties : in Util.Properties.Manager;
Default : in Level_Type)
return Appender_Access is
Result : constant Console_Appender_Access := new Console_Appender;
begin
Result.Set_Level (Name, Properties, Default);
Result.Set_Layout (Name, Properties, FULL);
return Result.all'Access;
end Create_Console_Appender;
-- ------------------------------
-- Flush the log events.
-- ------------------------------
overriding
procedure Flush (Self : in out List_Appender) is
begin
for I in 1 .. Self.Count loop
Self.Appenders (I).Flush;
end loop;
end Flush;
-- ------------------------------
-- Add the appender to the list.
-- ------------------------------
procedure Add_Appender (Self : in out List_Appender;
Object : in Appender_Access) is
begin
if Self.Count < Self.Appenders'Last then
Self.Count := Self.Count + 1;
Self.Appenders (Self.Count) := Object;
end if;
end Add_Appender;
-- ------------------------------
-- Create a list appender and configure it according to the properties
-- ------------------------------
function Create_List_Appender return List_Appender_Access is
Result : constant List_Appender_Access := new List_Appender;
begin
return Result;
end Create_List_Appender;
end Util.Log.Appenders;
|
with Ada.Text_IO;
use Ada.Text_IO;
with Ada.Integer_Text_IO;
use Ada.Integer_Text_IO;
with P_StructuralTypes;
use P_StructuralTypes;
package body P_StepHandler.FeistelHandler is
function Make (Handler : in out FeistelHandler) return FeistelHandler is
S1, S2, S3, S4, S5, S6, S7, S8 : T_SBox;
begin
Handler.Ptr_BinaryContainer := null;
Handler.Ptr_SubKeyArray := null;
for i in Handler.SBoxOutputArray'Range loop
Handler.SBoxOutputArray(i) := Integer_To_Binary (i,4);
end loop;
S1 := ((14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7),
(0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8),
(4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0),
(15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13));
Handler.SBoxArray(1) := S1;
S2 := ((15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10),
(3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5),
(0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15),
(13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9));
Handler.SBoxArray(2) := S2;
S3 := ((10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8),
(13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1),
(13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7),
(1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12));
Handler.SBoxArray(3) := S3;
S4 := ((7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15),
(13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9),
(10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4),
(3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14));
Handler.SBoxArray(4) := S4;
S5 := ((2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9),
(14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6),
(4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14),
(11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3));
Handler.SBoxArray(5) := S5;
S6 := ((12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11),
(10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8),
(9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6),
(4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13));
Handler.SBoxArray(6) := S6;
S7 := ((4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1),
(13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6),
(1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2),
(6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12));
Handler.SBoxArray(7) := S7;
S8 := ((13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7),
(1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2),
(7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8),
(2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11));
Handler.SBoxArray(8) := S8;
return Handler;
end;
procedure Handle (Self : in out FeistelHandler) is
begin
-- ENCRYPTION MODE
if Self.Mode = 'E' then
for BlockIndex in Self.Ptr_BinaryContainer.all'Range loop
for Round in 1..16 loop
Feistel_Round(Self,Self.Ptr_BinaryContainer.all(BlockIndex),Round);
end loop;
FinalInversion(Self.Ptr_BinaryContainer.all(BlockIndex));
end loop;
-- DECRYPTION MODE
else
for BlockIndex in Self.Ptr_BinaryContainer.all'Range loop
for Round in 1..16 loop
Feistel_Round(Self,Self.Ptr_BinaryContainer.all(BlockIndex),17-Round);
end loop;
FinalInversion(Self.Ptr_BinaryContainer.all(BlockIndex));
end loop;
end if;
if Self.NextHandler /= null then
Self.NextHandler.Handle;
end if;
end;
function Process_Block (Self : in FeistelHandler;
Block : in out T_BinaryBlock)
return T_BinaryBlock is
begin
if Self.Mode = 'E' then
for Round in 1..16 loop
Feistel_Round(Self,Block,Round);
end loop;
else
for Round in 1..16 loop
Feistel_Round(Self,Block,17-Round);
end loop;
end if;
FinalInversion(Block);
return Block;
end;
procedure Feistel_Round (Self : in FeistelHandler;
Block : in out T_BinaryBlock;
Round : in Integer) is
TmpLeft, TmpRight : T_BinaryHalfBlock;
FeistelHalfBlock : T_BinaryHalfBlock;
begin
TmpLeft := Block(1..32);
TmpRight := Block(33..64);
FeistelHalfBlock :=
Feistel_Function(Self,
Block(33..64),
Self.Ptr_SubKeyArray.all(Round));
TmpLeft := O_plus(FeistelHalfBlock, Block(1..32));
Block(1..32) := TmpRight;
Block(33..64) := TmpLeft;
end;
function Feistel_Function (Self : in FeistelHandler;
HalfBlock : T_BinaryHalfBlock;
SubKey : T_BinarySubKey)
return T_BinaryHalfBlock is
ExpandedBlock : T_BinaryExpandedBlock;
FinalBlock : T_BinaryHalfBlock;
begin
ExpandedBlock := Expansion(HalfBlock);
ExpandedBlock := O_plus (ExpandedBlock,SubKey);
FinalBlock := SBox_Substitution(Self,ExpandedBlock);
FinalBlock := Permutation(FinalBlock);
return FinalBlock;
end;
function SBox_Substitution (Self : in FeistelHandler;
ExpandedBlock : T_BinaryExpandedBlock)
return T_BinaryHalfBlock is
CompressedBlock : T_BinaryHalfBlock;
begin
for i in 1..8 loop
CompressedBlock(1+(i-1)*4..4*i) :=
SBox_Output(Self,ExpandedBlock(1+(i-1)*6..6*i),i);
end loop;
return CompressedBlock;
end;
function SBox_Output (Self : in FeistelHandler;
Input : T_BinaryUnit;
SBoxNumber : Integer) return T_BinaryUnit is
ColumnNumber : Integer;
RowNumber : Integer;
begin
ColumnNumber :=
Integer(Input(Input'First+1))*8 +
Integer(Input(Input'First+2))*4 +
Integer(Input(Input'First+3))*2 +
Integer(Input(Input'First+4))*1;
RowNumber := Integer(Input(Input'First))*2 + Integer(Input(Input'Last))*1;
return Self.SBoxOutputArray(Self.SBoxArray(SBoxNumber)(RowNumber,ColumnNumber));
end;
function Expansion (HalfBlock : T_BinaryHalfBlock)
return T_BinaryExpandedBlock is
ExpandedBlock : T_BinaryExpandedBlock;
PermIndex : Integer;
begin
PermIndex := 0;
for Index in 2..47 loop
if Index mod 6 = 1 then
PermIndex := PermIndex - 1;
else
PermIndex := PermIndex + 1;
end if;
ExpandedBlock(Index) := HalfBlock(PermIndex);
end loop;
ExpandedBlock(1) := HalfBlock(32);
ExpandedBlock(48) := HalfBlock(1);
return ExpandedBlock;
end;
function Permutation (HalfBlock : T_BinaryHalfBlock)
return T_BinaryHalfBlock is
PermutedBlock : T_BinaryHalfBlock;
begin
PermutedBlock(1) := HalfBlock(16);
PermutedBlock(2) := HalfBlock(7);
PermutedBlock(3) := HalfBlock(20);
PermutedBlock(4) := HalfBlock(21);
PermutedBlock(5) := HalfBlock(29);
PermutedBlock(6) := HalfBlock(12);
PermutedBlock(7) := HalfBlock(28);
PermutedBlock(8) := HalfBlock(17);
PermutedBlock(9) := HalfBlock(1);
PermutedBlock(10) := HalfBlock(15);
PermutedBlock(11) := HalfBlock(23);
PermutedBlock(12) := HalfBlock(26);
PermutedBlock(13) := HalfBlock(5);
PermutedBlock(14) := HalfBlock(18);
PermutedBlock(15) := HalfBlock(31);
PermutedBlock(16) := HalfBlock(10);
PermutedBlock(17) := HalfBlock(2);
PermutedBlock(18) := HalfBlock(8);
PermutedBlock(19) := HalfBlock(24);
PermutedBlock(20) := HalfBlock(14);
PermutedBlock(21) := HalfBlock(32);
PermutedBlock(22) := HalfBlock(27);
PermutedBlock(23) := HalfBlock(3);
PermutedBlock(24) := HalfBlock(9);
PermutedBlock(25) := HalfBlock(19);
PermutedBlock(26) := HalfBlock(13);
PermutedBlock(27) := HalfBlock(30);
PermutedBlock(28) := HalfBlock(6);
PermutedBlock(29) := HalfBlock(22);
PermutedBlock(30) := HalfBlock(11);
PermutedBlock(31) := HalfBlock(4);
PermutedBlock(32) := HalfBlock(25);
return PermutedBlock;
end;
procedure FinalInversion (Block : in out T_BinaryBlock) is
TmpLeft, TmpRight : T_BinaryHalfBlock;
begin
TmpLeft := Block(1..32);
TmpRight := Block(33..64);
Block(1..32) := TmpRight;
Block(33..64) := TmpLeft;
end;
function Get_SBoxArray (Self : in out FeistelHandler) return T_SBoxArray is
begin
return Self.SBoxArray;
end;
function Get_SBoxOutputArray (Self : in out FeistelHandler)
return T_BinaryIntegerArray is
begin
return Self.SBoxOutputArray;
end;
procedure Set_SubKeyArrayAccess (Self : in out FeistelHandler;
Ptr : in BinarySubKeyArray_Access) is
begin
Self.Ptr_SubKeyArray := Ptr;
end;
procedure Set_Mode (Self : in out FeistelHandler;
Mode : Character) is
begin
Self.Mode := Mode;
end;
end P_StepHandler.FeistelHandler;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Numerics.Discrete_Random;
with Ada.Streams.Stream_IO;
with League.JSON.Arrays;
with League.JSON.Documents;
with League.JSON.Values;
with League.String_Vectors;
with Slim.Menu_Commands.Play_File_Commands;
with Slim.Menu_Commands.Play_Radio_Commands;
package body Slim.Menu_Models.JSON is
function Read_File
(File : League.Strings.Universal_String)
return League.JSON.Documents.JSON_Document;
function Play_Recursive
(Self : JSON_Menu_Model'Class;
Object : League.JSON.Objects.JSON_Object)
return Slim.Menu_Commands.Menu_Command_Access;
-------------------
-- Enter_Command --
-------------------
overriding function Enter_Command
(Self : JSON_Menu_Model;
Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access
is
String : League.Strings.Universal_String;
Object : League.JSON.Objects.JSON_Object;
Item : League.JSON.Arrays.JSON_Array :=
Self.Root.Value (Self.Nested).To_Array;
begin
for J in 1 .. Path.Length loop
Object := Item.Element (Path.List (J)).To_Object;
if Object.Contains (Self.Playlist) then
-- Delegate Enter_Command to playlist model
String := Object.Value (Self.Playlist).To_String;
return Self.Playlists (String).all.Enter_Command
((Length => Path.Length - J,
List => Path.List (J + 1 .. Path.Length)));
elsif J = Path.Length then
if not Object.Contains (Self.URL) then
return null;
end if;
return
new Slim.Menu_Commands.Play_Radio_Commands.Play_Radio_Command'
(Player => Self.Player,
URL => Object.Value (Self.URL).To_String);
else
Item := Object.Value (Self.Nested).To_Array;
end if;
end loop;
return null;
end Enter_Command;
----------------
-- Initialize --
----------------
procedure Initialize
(Self : in out JSON_Menu_Model'Class;
File : League.Strings.Universal_String)
is
procedure Read_Playlists
(Path : Menu_Path;
Object : League.JSON.Objects.JSON_Object);
--------------------
-- Read_Playlists --
--------------------
procedure Read_Playlists
(Path : Menu_Path;
Object : League.JSON.Objects.JSON_Object) is
begin
if Object.Contains (Self.Playlist) then
declare
Root : constant League.Strings.Universal_String :=
Object.Value (Self.Path).To_String;
Label : constant League.Strings.Universal_String :=
Object.Value (Self.Label).To_String;
Value : constant League.Strings.Universal_String :=
Object.Value (Self.Playlist).To_String;
Next : constant Play_List_Access := new
Slim.Menu_Models.Play_Lists.Play_List_Menu_Model
(Self.Player);
begin
Next.Initialize (Label => Label, Root => Root, File => Value);
Self.Playlists.Insert (Value, Next);
end;
elsif Object.Contains (Self.Nested) then
declare
List : constant League.JSON.Arrays.JSON_Array :=
Object.Value (Self.Nested).To_Array;
Next : Menu_Path := (Path.Length + 1, Path.List & 1);
begin
for J in 1 .. List.Length loop
Next.List (Next.Length) := J;
Read_Playlists (Next, List.Element (J).To_Object);
end loop;
end;
end if;
end Read_Playlists;
Document : constant League.JSON.Documents.JSON_Document :=
Read_File (File);
begin
Self.Root := Document.To_JSON_Object;
Self.Nested := League.Strings.To_Universal_String ("nested");
Self.Label := League.Strings.To_Universal_String ("label");
Self.URL := League.Strings.To_Universal_String ("url");
Self.Path := League.Strings.To_Universal_String ("path");
Self.Playlist := League.Strings.To_Universal_String ("playlist");
Read_Playlists (Menu_Models.Root (Self), Self.Root);
end Initialize;
----------------
-- Item_Count --
----------------
overriding function Item_Count
(Self : JSON_Menu_Model;
Path : Slim.Menu_Models.Menu_Path)
return Natural
is
String : League.Strings.Universal_String;
Object : League.JSON.Objects.JSON_Object;
Item : League.JSON.Arrays.JSON_Array :=
Self.Root.Value (Self.Nested).To_Array;
Result : Natural;
begin
for J in 1 .. Path.Length loop
Object := Item.Element (Path.List (J)).To_Object;
if Object.Contains (Self.Playlist) then
-- Delegate Item_Count to playlist model
String := Object.Value (Self.Playlist).To_String;
Result := Self.Playlists (String).all.Item_Count
((Length => Path.Length - J,
List => Path.List (J + 1 .. Path.Length)));
return Result;
else
Item := Object.Value (Self.Nested).To_Array;
end if;
end loop;
return Item.Length;
end Item_Count;
-----------
-- Label --
-----------
overriding function Label
(Self : JSON_Menu_Model; Path : Slim.Menu_Models.Menu_Path)
return League.Strings.Universal_String
is
String : League.Strings.Universal_String;
Object : League.JSON.Objects.JSON_Object;
Item : League.JSON.Arrays.JSON_Array :=
Self.Root.Value (Self.Nested).To_Array;
begin
for J in 1 .. Path.Length loop
Object := Item.Element (Path.List (J)).To_Object;
if Object.Contains (Self.Playlist) then
-- Delegate Label to playlist model
String := Object.Value (Self.Playlist).To_String;
String := Self.Playlists (String).all.Label
((Length => Path.Length - J,
List => Path.List (J + 1 .. Path.Length)));
return String;
elsif J = Path.Length then
String := Object.Value (Self.Label).To_String;
return String;
else
Item := Object.Value (Self.Nested).To_Array;
end if;
end loop;
return String;
end Label;
------------------
-- Play_Command --
------------------
overriding function Play_Command
(Self : JSON_Menu_Model;
Path : Menu_Path) return Slim.Menu_Commands.Menu_Command_Access
is
String : League.Strings.Universal_String;
Object : League.JSON.Objects.JSON_Object;
Item : League.JSON.Arrays.JSON_Array :=
Self.Root.Value (Self.Nested).To_Array;
begin
for J in 1 .. Path.Length loop
Object := Item.Element (Path.List (J)).To_Object;
if Object.Contains (Self.Playlist) then
-- Delegate Play_Command to playlist model
String := Object.Value (Self.Playlist).To_String;
return Self.Playlists (String).all.Play_Command
((Length => Path.Length - J,
List => Path.List (J + 1 .. Path.Length)));
elsif J = Path.Length then
if not Object.Contains (Self.URL) then
return Play_Recursive (Self, Object);
end if;
return
new Slim.Menu_Commands.Play_Radio_Commands.Play_Radio_Command'
(Player => Self.Player,
URL => Object.Value (Self.URL).To_String);
else
Item := Object.Value (Self.Nested).To_Array;
end if;
end loop;
return null;
end Play_Command;
--------------------
-- Play_Recursive --
--------------------
function Play_Recursive
(Self : JSON_Menu_Model'Class;
Object : League.JSON.Objects.JSON_Object)
return Slim.Menu_Commands.Menu_Command_Access
is
procedure Collect (Object : League.JSON.Objects.JSON_Object);
procedure Shuffle
(Origin_Paths : League.String_Vectors.Universal_String_Vector;
Origin_Titles : League.String_Vectors.Universal_String_Vector;
Paths : out League.String_Vectors.Universal_String_Vector;
Titles : out League.String_Vectors.Universal_String_Vector);
-------------
-- Shuffle --
-------------
procedure Shuffle
(Origin_Paths : League.String_Vectors.Universal_String_Vector;
Origin_Titles : League.String_Vectors.Universal_String_Vector;
Paths : out League.String_Vectors.Universal_String_Vector;
Titles : out League.String_Vectors.Universal_String_Vector)
is
package Randoms is new Ada.Numerics.Discrete_Random (Positive);
Generator : Randoms.Generator;
Map : array (1 .. Origin_Paths.Length) of Positive;
Last : Natural := Map'Last;
Index : Positive;
begin
Randoms.Reset (Generator);
for J in Map'Range loop
Map (J) := J;
end loop;
while Last > 0 loop
Index := (Randoms.Random (Generator) mod Last) + 1;
Paths.Append (Origin_Paths (Map (Index)));
Titles.Append (Origin_Titles (Map (Index)));
Map (Index) := Map (Last);
Last := Last - 1;
end loop;
end Shuffle;
Relative_Path_List : League.String_Vectors.Universal_String_Vector;
Title_List : League.String_Vectors.Universal_String_Vector;
-------------
-- Collect --
-------------
procedure Collect (Object : League.JSON.Objects.JSON_Object) is
String : League.Strings.Universal_String;
List : constant League.JSON.Arrays.JSON_Array :=
Object.Value (Self.Nested).To_Array;
begin
if Object.Contains (Self.Playlist) then
-- Delegate Collect to playlist model
String := Object.Value (Self.Playlist).To_String;
Self.Playlists (String).all.Collect
(Relative_Path_List, Title_List);
return;
end if;
for J in 1 .. List.Length loop
Collect (List (J).To_Object);
end loop;
end Collect;
begin
Collect (Object);
if Relative_Path_List.Is_Empty then
return null;
end if;
declare
use Slim.Menu_Commands.Play_File_Commands;
Result : constant Play_File_Command_Access :=
new Play_File_Command (Self.Player);
begin
Shuffle
(Relative_Path_List,
Title_List,
Result.Relative_Path_List,
Result.Title_List);
return Slim.Menu_Commands.Menu_Command_Access (Result);
end;
end Play_Recursive;
---------------
-- Read_File --
---------------
function Read_File
(File : League.Strings.Universal_String)
return League.JSON.Documents.JSON_Document
is
Input : Ada.Streams.Stream_IO.File_Type;
begin
Ada.Streams.Stream_IO.Open
(Input, Ada.Streams.Stream_IO.In_File, File.To_UTF_8_String);
declare
Size : constant Ada.Streams.Stream_Element_Count :=
Ada.Streams.Stream_Element_Count
(Ada.Streams.Stream_IO.Size (Input));
Buffer : Ada.Streams.Stream_Element_Array (1 .. Size);
Last : Ada.Streams.Stream_Element_Count;
begin
Ada.Streams.Stream_IO.Read (Input, Buffer, Last);
return Result : constant League.JSON.Documents.JSON_Document :=
League.JSON.Documents.From_JSON (Buffer (1 .. Last))
do
Ada.Streams.Stream_IO.Close (Input);
end return;
end;
end Read_File;
end Slim.Menu_Models.JSON;
|
-- Project: Strato
-- System: Stratosphere Balloon Flight Controller
-- Author: Martin Becker (becker@rcs.ei.tum.de)
-- @summary String functions
package MyStrings with SPARK_Mode is
function Is_AlNum (c : Character) return Boolean;
-- is the given character alphanumeric?
function Strip_Non_Alphanum (s : String) return String;
-- remove all non-alphanumeric characters from string
function StrChr (S : String; C : Character) return Integer with
Pre => S'Last < Natural'Last;
-- search for occurence of character in string.
-- return index in S, or S'Last + 1 if not found.
procedure StrCpySpace (outstring : out String; instring : String);
-- turn a string into a fixed-length string:
-- if too short, pad with spaces until it reaches the given length
-- if too long, then crop
function RTrim (S : String) return String;
-- remove trailing spaces
function LTrim (S : String) return String;
-- remove leading spaces
function Trim (S : String) return String;
-- remove leading and trailing spaces
end MyStrings;
|
-----------------------------------------------------------------------
-- Action_Bean - Simple bean with methods that can be called from EL
-- Copyright (C) 2010 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 EL.Objects;
with Util.Beans.Basic;
with Util.Beans.Methods;
with EL.Methods.Proc_1;
with EL.Methods.Proc_2;
with Test_Bean;
with Ada.Unchecked_Deallocation;
package Action_Bean is
type Action is new Util.Beans.Basic.Bean and Util.Beans.Methods.Method_Bean with record
Person : Test_Bean.Person;
Count : Natural;
end record;
type Action_Access is access all Action'Class;
-- Get the value identified by the name.
function Get_Value (From : Action; Name : String) return EL.Objects.Object;
-- Set the value identified by the name.
procedure Set_Value (From : in out Action;
Name : in String;
Value : in EL.Objects.Object);
-- Get the EL method bindings exposed by the Action type.
function Get_Method_Bindings (From : in Action)
return Util.Beans.Methods.Method_Binding_Array_Access;
-- Action with one parameter.
-- Sets the person.
procedure Notify (Target : in out Action;
Param : in out Test_Bean.Person);
-- Action with two parameters.
-- Sets the person object and the counter.
procedure Notify (Target : in out Action;
Param : in Test_Bean.Person;
Count : in Natural);
-- Action with one parameter
procedure Print (Target : in out Action;
Param : in out Test_Bean.Person);
-- Package to invoke an EL method with one <b>Person</b> as parameter.
package Proc_Action is new EL.Methods.Proc_1 (Param1_Type => Test_Bean.Person);
-- Package to invoke an EL method with <b>Person</b> as parameter and a <b>Natural</b>.
package Proc2_Action is
new EL.Methods.Proc_2 (Param1_Type => Test_Bean.Person,
Param2_Type => Natural);
procedure Free is new Ada.Unchecked_Deallocation (Object => Action'Class,
Name => Action_Access);
end Action_Bean;
|
------------------------------------------------------------------------------
-- Copyright (c) 2016, 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. --
------------------------------------------------------------------------------
with Ada.Characters.Latin_1;
with Natools.Smaz_256;
with Natools.Smaz_Original_Hash;
package Natools.Smaz_Original is
pragma Pure;
LF : constant Character := Ada.Characters.Latin_1.LF;
CR : constant Character := Ada.Characters.Latin_1.CR;
Dictionary : constant Natools.Smaz_256.Dictionary
:= (Last_Code => 253,
Values_Last => 593,
Variable_Length_Verbatim => True,
Max_Word_Length => 7,
Offsets => (2, 5, 6, 7, 8, 10, 11, 14, 15, 16, 17, 19, 20, 23, 25,
27, 29, 31, 32, 35, 37, 39, 40, 42, 43, 45, 47, 49, 50, 52, 54, 56,
59, 61, 64, 66, 68, 70, 71, 73, 76, 78, 80, 85, 86, 87, 89, 91, 95,
96, 99, 101, 103, 105, 107, 110, 112, 113, 115, 116, 117, 119, 121,
124, 127, 128, 130, 137, 140, 142, 145, 147, 150, 152, 154, 156,
159, 161, 164, 166, 168, 169, 172, 173, 175, 177, 181, 183, 185,
188, 189, 191, 193, 197, 199, 201, 203, 206, 208, 211, 216, 217,
219, 223, 225, 228, 230, 233, 235, 236, 237, 239, 242, 245, 247,
249, 252, 254, 257, 260, 262, 264, 267, 269, 272, 274, 277, 279,
283, 285, 287, 289, 292, 295, 298, 301, 303, 305, 307, 309, 312,
315, 318, 321, 323, 325, 328, 330, 333, 336, 338, 340, 342, 344,
347, 351, 354, 356, 359, 362, 365, 368, 371, 373, 375, 377, 379,
382, 385, 387, 390, 392, 395, 397, 400, 403, 406, 409, 411, 413,
415, 418, 420, 422, 425, 428, 430, 432, 435, 437, 440, 443, 445,
448, 450, 452, 454, 455, 459, 462, 464, 467, 470, 473, 474, 476,
479, 482, 484, 487, 492, 495, 497, 500, 502, 504, 507, 510, 513,
514, 516, 518, 519, 521, 523, 524, 526, 529, 531, 534, 536, 539,
541, 544, 546, 548, 550, 552, 555, 557, 559, 561, 563, 566, 569,
572, 575, 578, 581, 583, 584, 587, 590),
Values => " theetaofoandinse r th tinhethhhe to" & CR & LF & "ls d a"
& "anerc od on ofreof t , isuat n orwhichfmasitthat" & LF & "wa"
& "sen wes an i" & CR & "f gpnd snd ed wedhttp://forteingy The "
& "ctir hisst inarnt, toyng hwithlealto boubewere bseo enthang th"
& "eir""hifrom fin deionmev.veallre rirois cof tareea. her mer p"
& "es bytheydiraicnots, d tat celah neas tioon n tiowe a om, as o"
& "urlillchhadthise tg e" & CR & LF & " where coe oa us dss" & LF
& CR & LF & CR & LF & CR & "="" be es amaonet tor butelsol e ss,n"
& "oter waivhoe a rhats tnsch whtrut/havely ta ha ontha- latien p"
& "e rethereasssi fowaecourwhoitszfors>otun<imth ncate><verad wel"
& "yee nid clacil</rt widive, itwhi magexe cmen.com",
Hash => Natools.Smaz_Original_Hash.Hash'Access);
end Natools.Smaz_Original;
|
with Littlefs; use Littlefs;
with System.Storage_Elements; use System.Storage_Elements;
with Interfaces.C; use Interfaces.C;
with Interfaces; use Interfaces;
with System;
package body RAM_BD is
function Read (C : access constant LFS_Config;
Block : LFS_Block;
Off : LFS_Offset;
Buffer : System.Address;
Size : LFS_Size)
return int
with Convention => C;
function Prog (C : access constant LFS_Config;
Block : LFS_Block;
Off : LFS_Offset;
Buffer : System.Address;
Size : LFS_Size)
return int
with Convention => C;
function Erase (C : access constant LFS_Config;
Block : LFS_Block)
return int
with Convention => C;
function Sync (C : access constant LFS_Config) return int
with Convention => C;
----------
-- Read --
----------
function Read (C : access constant LFS_Config;
Block : LFS_Block;
Off : LFS_Offset;
Buffer : System.Address;
Size : LFS_Size)
return int
is
Offset : constant LFS_Offset := Off + C.Block_Size * LFS_Size (Block);
Dev_Buf : Storage_Array (1 .. Storage_Offset (Size))
with Address => To_Address
(To_Integer (C.Context) + Integer_Address (Offset));
Read_Buf : Storage_Array (1 .. Storage_Offset (Size))
with Address => Buffer;
begin
Read_Buf := Dev_Buf;
return 0;
end Read;
function Prog (C : access constant LFS_Config;
Block : LFS_Block;
Off : LFS_Offset;
Buffer : System.Address;
Size : LFS_Size)
return int
is
Offset : constant LFS_Offset := Off + C.Block_Size * LFS_Size (Block);
Dev_Buf : Storage_Array (1 .. Storage_Offset (Size))
with Address => To_Address
(To_Integer (C.Context) + Integer_Address (Offset));
Read_Buf : Storage_Array (1 .. Storage_Offset (Size))
with Address => Buffer;
begin
Dev_Buf := Read_Buf;
return 0;
end Prog;
function Erase (C : access constant LFS_Config;
Block : LFS_Block)
return int
is
pragma Unreferenced (Block, C);
begin
return 0;
end Erase;
function Sync (C : access constant LFS_Config) return int is
pragma Unreferenced (C);
begin
return 0;
end Sync;
type LFS_Config_Access is access all Littlefs.LFS_Config;
type Storage_Array_Access is access all Storage_Array;
------------
-- Create --
------------
function Create (Size : Littlefs.LFS_Size)
return access constant Littlefs.LFS_Config
is
Ret : constant LFS_Config_Access := new LFS_Config;
Buf : constant Storage_Array_Access :=
new Storage_Array (1 .. Storage_Offset (Size));
begin
Ret.Context := Buf (Buf'First)'Address;
Ret.Read := Read'Access;
Ret.Prog := Prog'Access;
Ret.Erase := Erase'Access;
Ret.Sync := Sync'Access;
Ret.Read_Size := 2048;
Ret.Prog_Size := 2048;
Ret.Block_Size := 2048;
Ret.Block_Count := Size / 2048;
Ret.Block_Cycles := 700;
Ret.Cache_Size := Ret.Block_Size;
Ret.Lookahead_Size := Ret.Block_Size;
Ret.Read_Buffer := System.Null_Address;
Ret.Prog_Buffer := System.Null_Address;
Ret.Lookahead_Buffer := System.Null_Address;
Ret.Name_Max := 0;
Ret.File_Max := 0;
Ret.Attr_Max := 0;
return Ret;
end Create;
end RAM_BD;
|
-- Gonzalo Martin Rodriguez
-- Ivan Fernandez Samaniego
with Kernel.Serial_Output; use Kernel.Serial_Output;
with Ada.Real_Time; use Ada.Real_Time;
with ada.strings.unbounded; use ada.strings.unbounded;
with ada.strings.unbounded.text_io; use ada.strings.unbounded.text_io;
with System; use System;
with Tools; use Tools;
with devices; use devices;
package body Driver is
task body Distance is
Current_D: Distance_Samples_Type := 0;
Current_V: Speed_Samples_Type := 0;
Recommended_Distance: float;
Siguiente_Instante: Time;
begin
Siguiente_Instante := Big_Bang + Milliseconds(300);
loop
Starting_Notice ("Distance");
Measures.Write_Distance;
Measures.Write_Speed;
Measures.Read_Distance (Current_D);
Measures.Read_Speed (Current_V);
Recommended_Distance := float ((Current_V/10)**2);
if (float(Current_D) < float(Recommended_Distance)/float(3000)) then
Symptoms.Write_Peligro_Colision (True);
Symptoms.Write_Distancia_Insegura (False);
Symptoms.Write_Distancia_Imprudente (False);
elsif (float(Current_D) < float(Recommended_Distance)/float(2000)) then
Symptoms.Write_Distancia_Imprudente (True);
Symptoms.Write_Distancia_Insegura (False);
Symptoms.Write_Peligro_Colision (False);
elsif (float(Current_D) < Recommended_Distance)then
Symptoms.Write_Distancia_Insegura (True);
Symptoms.Write_Distancia_Imprudente (False);
Symptoms.Write_Peligro_Colision (False);
else
Symptoms.Write_Distancia_Insegura (False);
Symptoms.Write_Distancia_Imprudente (False);
Symptoms.Write_Peligro_Colision (False);
end if;
Finishing_Notice ("Distance");
delay until Siguiente_Instante;
Siguiente_Instante := Siguiente_Instante + Milliseconds(300);
end loop;
end Distance;
task body Steering is
Previous_S : Steering_Samples_Type;
Current_S : Steering_Samples_Type := 0;
Speed: Speed_Samples_Type := 0;
Siguiente_Instante: Time;
begin
Siguiente_Instante := Big_Bang + Milliseconds(350);
loop
Starting_Notice ("Steering");
Previous_S := Current_S;
Symptoms.Write_Steering;
Measures.Write_Speed;
Symptoms.Read_Steering (Current_S);
Measures.Read_Speed (Speed);
if Previous_S - Current_S > abs(20) and Speed > 40 then
Symptoms.Write_Steering_Symptom (True);
else Symptoms.Write_Steering_Symptom (False);
end if;
Finishing_Notice ("Steering");
delay until Siguiente_Instante;
Siguiente_Instante := Siguiente_Instante + Milliseconds(350);
end loop;
end Steering;
task body Head is
Previous_H: HeadPosition_Samples_Type := (+2,-2);
Current_H: HeadPosition_Samples_Type := (+2, -2);
Current_S: Steering_Samples_Type;
Siguiente_Instante: Time;
begin
Siguiente_Instante := Big_Bang + Milliseconds(400);
loop
Starting_Notice ("Head");
Previous_H := Current_H;
Symptoms.Write_HeadPosition;
Symptoms.Write_Steering;
Symptoms.Read_HeadPosition (Current_H);
Symptoms.Read_Steering (Current_S);
if (((abs Previous_H(x) > 30) and (abs Current_H(x) > 30)) or
((Previous_H(y) > 30) and (Current_H(y) > 30) and (Current_S < 30)) or
((Previous_H(y) < 30) and (Current_H(y) < 30) and (Current_S > 30)))
then
Symptoms.Write_Head_Symptom (True);
else Symptoms.Write_Head_Symptom (False);
end if;
Finishing_Notice ("Head");
delay until Siguiente_Instante;
Siguiente_Instante := Siguiente_Instante + Milliseconds(400);
end loop;
end Head;
protected body Symptoms is
procedure Write_Head_Symptom (Value: in Boolean) is
begin
Head_Symptom := Value;
Execution_Time(Milliseconds(2));
end Write_Head_Symptom;
procedure Read_Head_Symptom (Value: out Boolean) is
begin
Value := Head_Symptom;
Execution_Time(Milliseconds(2));
end Read_Head_Symptom;
procedure Write_Distancia_Insegura (Value: in Boolean) is
begin
Distancia_Insegura := Value;
Execution_Time(Milliseconds(3));
end Write_Distancia_Insegura;
procedure Read_Distancia_Insegura (Value: out Boolean) is
begin
Value := Distancia_Insegura;
Execution_Time(Milliseconds(3));
end Read_Distancia_Insegura;
procedure Write_Distancia_Imprudente (Value: in Boolean) is
begin
Distancia_Imprudente := Value;
Execution_Time(Milliseconds(4));
end Write_Distancia_Imprudente;
procedure Read_Distancia_Imprudente (Value: out Boolean) is
begin
Value := Distancia_Imprudente;
Execution_Time(Milliseconds(4));
end Read_Distancia_Imprudente;
procedure Write_Peligro_Colision (Value: in Boolean) is
begin
Peligro_Colision := Value;
Execution_Time(Milliseconds(5));
end Write_Peligro_Colision;
procedure Read_Peligro_Colision (Value: out Boolean) is
begin
Value := Peligro_Colision;
Execution_Time(Milliseconds(5));
end Read_Peligro_Colision;
procedure Write_Steering_Symptom (Value: in Boolean) is
begin
Steering_Symptom := Value;
Execution_Time(Milliseconds(6));
end Write_Steering_Symptom;
procedure Read_Steering_Symptom (Value: out Boolean) is
begin
Value := Steering_Symptom;
Execution_Time(Milliseconds(6));
end Read_Steering_Symptom;
procedure Write_HeadPosition is
begin
Reading_HeadPosition(HeadPosition);
Execution_Time(Milliseconds(7));
end Write_HeadPosition;
procedure Read_HeadPosition (Value: out HeadPosition_Samples_Type) is
begin
Value := HeadPosition;
Execution_Time(Milliseconds(7));
end Read_HeadPosition;
procedure Write_Steering is
begin
Reading_Steering (Steering);
Execution_Time(Milliseconds(8));
end Write_Steering;
procedure Read_Steering (Value: out Steering_Samples_Type) is
begin
Value := Steering;
Execution_Time(Milliseconds(8));
end Read_Steering;
procedure Display_Symptom (Symptom: in Unbounded_String) is
begin
Current_Time (Big_Bang);
Put ("............# ");
Put ("Symptom: ");
Put (Symptom);
Execution_Time(Milliseconds(2));
end Display_Symptom;
procedure Show_Symptoms is
begin
if Head_Symptom then Display_Symptom (To_Unbounded_String("CABEZA INCLINADA")); end if;
if Steering_Symptom then Display_Symptom (To_Unbounded_String("VOLANTAZO")); end if;
if Distancia_Insegura then Display_Symptom (To_Unbounded_String("DISTANCIA INSEGURA")); end if;
if Distancia_Imprudente then Display_Symptom (To_Unbounded_String("DISTANCIA IMPRUDENTE")); end if;
if Peligro_Colision then Display_Symptom (To_Unbounded_String("PELIGRO COLISION")); end if;
Execution_Time(Milliseconds(6));
end Show_Symptoms;
end Symptoms;
protected body Measures is
procedure Read_Distance (Value: out Distance_Samples_Type) is
begin
Value := Distance;
Execution_Time(Milliseconds(2));
end Read_Distance;
procedure Write_Distance is
begin
Reading_Distance(Distance);
Execution_Time(Milliseconds(3));
end Write_Distance;
procedure Show_Distance is
begin
Display_Distance(Distance);
Execution_Time(Milliseconds(4));
end Show_Distance;
procedure Read_Speed (Value: out Speed_Samples_Type) is
begin
Value := Speed;
Execution_Time(Milliseconds(5));
end Read_Speed;
procedure Write_Speed is
begin
Reading_Speed(Speed);
Execution_Time(Milliseconds(6));
end Write_Speed;
procedure Show_Speed is
begin
Display_Speed(Speed);
Execution_Time(Milliseconds(7));
end Show_Speed;
end Measures;
begin
null;
end Driver;
|
M:assert
F:G$slab_Assert$0$0({2}DF,SV:S),C,0,0,0,0,0
S:G$slab_Assert$0$0({2}DF,SV:S),C,0,0
|
with
Interfaces.C,
System;
package GL_Types
--
-- Provides openGL types whose definitions may differ amongst platforms.
--
-- This file is generated by the 'generate_GL_types_Spec' tool.
--
is
pragma Pure;
use Interfaces;
subtype GLenum is C.unsigned;
subtype GLboolean is C.unsigned_char;
subtype GLbitfield is C.unsigned;
subtype GLvoid is system.Address;
subtype GLbyte is C.signed_char;
subtype GLshort is C.short;
subtype GLint is C.int;
subtype GLubyte is C.unsigned_char;
subtype GLushort is C.unsigned_short;
subtype GLuint is C.unsigned;
subtype GLsizei is C.int;
subtype GLfloat is C.C_float;
subtype GLclampf is C.C_float;
subtype GLdouble is C.double;
subtype GLclampd is C.double;
subtype GLchar is C.char;
subtype GLfixed is Integer_32;
end GL_Types;
|
-- Filename: wtp.adb
--
-- Description: Models the Water Tank Protection System
--
pragma SPARK_Mode (On);
package WTP
with
Abstract_State => State
is
procedure Control
with
Global => (Output => State),
Depends => (State => null);
end WTP;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Elements.Declarations;
with Program.Elements.Defining_Identifiers;
with Program.Lexical_Elements;
with Program.Elements.Discrete_Ranges;
package Program.Elements.Loop_Parameter_Specifications is
pragma Pure (Program.Elements.Loop_Parameter_Specifications);
type Loop_Parameter_Specification is
limited interface and Program.Elements.Declarations.Declaration;
type Loop_Parameter_Specification_Access is
access all Loop_Parameter_Specification'Class with Storage_Size => 0;
not overriding function Name
(Self : Loop_Parameter_Specification)
return not null Program.Elements.Defining_Identifiers
.Defining_Identifier_Access is abstract;
not overriding function Definition
(Self : Loop_Parameter_Specification)
return not null Program.Elements.Discrete_Ranges.Discrete_Range_Access
is abstract;
not overriding function Has_Reverse
(Self : Loop_Parameter_Specification)
return Boolean is abstract;
type Loop_Parameter_Specification_Text is limited interface;
type Loop_Parameter_Specification_Text_Access is
access all Loop_Parameter_Specification_Text'Class with Storage_Size => 0;
not overriding function To_Loop_Parameter_Specification_Text
(Self : in out Loop_Parameter_Specification)
return Loop_Parameter_Specification_Text_Access is abstract;
not overriding function In_Token
(Self : Loop_Parameter_Specification_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
not overriding function Reverse_Token
(Self : Loop_Parameter_Specification_Text)
return Program.Lexical_Elements.Lexical_Element_Access is abstract;
end Program.Elements.Loop_Parameter_Specifications;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- F N A M E . S F --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This child package contains a routine to read and process Source_File_Name
-- pragmas from the gnat.adc file in the current directory. In order to use
-- the routines in package Fname.UF, it is required that Source_File_Name
-- pragmas be processed. There are two places where such processing takes
-- place:
-- The compiler front end (par-prag.adb), which is the general circuit
-- for processing all pragmas, including Source_File_Name.
-- The stand alone routine in this unit, which is convenient to use
-- from tools that do not want to include the compiler front end.
-- Note that this unit does depend on several of the compiler front-end
-- sources, including osint. If it is necessary to scan source file name
-- pragmas with less dependence on such sources, look at unit SFN_Scan.
package Fname.SF is
procedure Read_Source_File_Name_Pragmas;
-- This procedure is called to read the gnat.adc file and process any
-- Source_File_Name pragmas contained in this file. All other pragmas
-- are ignored. The result is appropriate calls to routines in the
-- package Fname.UF to register the pragmas so that subsequent calls
-- to Get_File_Name work correctly.
--
-- Note: The caller must have made an appropriate call to the
-- Osint.Initialize routine to initialize Osint before calling
-- this procedure.
--
-- If a syntax error is detected while scanning the gnat.adc file,
-- then the exception SFN_Scan.Syntax_Error_In_GNAT_ADC is raised
-- and SFN_Scan.Cursor contains the approximate index relative to
-- the start of the gnat.adc file of the error.
end Fname.SF;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
with SDA_Exceptions; use SDA_Exceptions;
with Alea;
with TH;
-- Évaluer la qualité du générateur aléatoire et les SDA.
procedure Evaluer_Alea_TH is
-- Fonction Identité
function Identity(Nombre: in Integer) return Integer is
begin
return Nombre;
end Identity;
package TH_int_int is
new TH (Capacite => 1000, T_Cle => Integer, T_Donnee => Integer, Hachage => Identity);
use TH_int_int;
-- Afficher l'usage.
procedure Afficher_Usage is
begin
New_Line;
Put_Line ("Usage : " & Command_Name & " Borne Taille");
New_Line;
Put_Line (" Borne : les nombres sont tirés dans l'intervalle 1..Borne");
Put_Line (" Taille : la taille de l'échantillon");
New_Line;
end Afficher_Usage;
-- Afficher le Nom et la Valeur d'une variable.
-- La Valeur est affichée sur la Largeur_Valeur précisée.
procedure Afficher_Variable (Nom: String; Valeur: in Integer; Largeur_Valeur: in Integer := 1) is
begin
Put (Nom);
Put (" : ");
Put (Valeur, Largeur_Valeur);
New_Line;
end Afficher_Variable;
-- Évaluer la qualité du générateur de nombre aléatoire Alea sur un
-- intervalle donné en calculant les fréquences absolues minimales et
-- maximales des entiers obtenus lors de plusieurs tirages aléatoires.
--
-- Paramètres :
-- Borne: in Entier -- le nombre aléatoire est dans 1..Borne
-- Taille: in Entier -- nombre de tirages (taille de l'échantillon)
-- Min, Max: out Entier -- fréquence minimale et maximale
--
-- Nécessite :
-- Borne > 1
-- Taille > 1
--
-- Assure : -- poscondition peu intéressante !
-- 0 <= Min Et Min <= Taille
-- 0 <= Max Et Max <= Taille
-- Min + Max <= Taille
-- Min <= Moyenne Et Moyenne <= Max
--
-- Remarque : On ne peut ni formaliser les 'vraies' postconditions,
-- ni écrire de programme de test car on ne maîtrise par le générateur
-- aléatoire. Pour écrire un programme de test, on pourrait remplacer
-- le générateur par un générateur qui fournit une séquence connue
-- d'entiers et pour laquelle on pourrait déterminer les données
-- statistiques demandées.
-- Ici, pour tester on peut afficher les nombres aléatoires et refaire
-- les calculs par ailleurs pour vérifier que le résultat produit est
-- le bon.
procedure Calculer_Statistiques (
Borne : in Integer; -- Borne supérieur de l'intervalle de recherche
Taille : in Integer; -- Taille de l'échantillon
Min, Max : out Integer -- min et max des fréquences de l'échantillon
) with
Pre => Borne > 1 and Taille > 1,
Post => 0 <= Min and Min <= Taille
and 0 <= Max and Max <= Taille
and Min + Max <= Taille
is
-- Sous procedure mettant à jour le Max et Min.
procedure MAJ_Max_Min(Cle: Integer; Donnee: Integer) is
begin
if Max < Donnee then
Max := Donnee;
end if;
if Min > Donnee then
Min := Donnee;
end if;
end MAJ_Max_Min;
procedure Determiner_Max_Min is
new Pour_Chaque(MAJ_Max_Min);
package Mon_Alea is
new Alea (1, Borne);
use Mon_Alea;
SDA : T_TH;
Rand : Integer;
begin
-- Initialiser la TH.
Initialiser(SDA);
Min := Taille;
Max := 0;
for i in 1..Taille loop
Get_Random_Number(Rand);
begin
Enregistrer(SDA, Rand, La_Donnee(SDA, Rand)+1);
exception
when Cle_Absente_Exception =>
Enregistrer(SDA, Rand, 1);
end;
end loop;
Determiner_Max_Min(SDA);
end Calculer_Statistiques;
Min, Max: Integer; -- fréquence minimale et maximale d'un échantillon
Borne: Integer; -- les nombres aléatoire sont tirés dans 1..Borne
Taille: integer; -- nombre de tirages aléatoires
begin
if Argument_Count /= 2 then
Afficher_Usage;
else
-- Récupérer les arguments de la ligne de commande
begin
Borne := Integer'Value (Argument (1));
Taille := Integer'Value (Argument (2));
if Borne < 2 or Taille < 2 then
raise CONSTRAINT_ERROR;
end if;
exception
when CONSTRAINT_ERROR =>
Put_Line("Erreur d'entrée, vous devez entrer des nombres positifs >= 2.");
Afficher_Usage;
return;
end;
-- Afficher les valeur de Borne et Taille
Afficher_Variable ("Borne ", Borne);
Afficher_Variable ("Taille", Taille);
Calculer_Statistiques (Borne, Taille, Min, Max);
-- Afficher les fréquence Min et Max
Afficher_Variable ("Min", Min);
Afficher_Variable ("Max", Max);
end if;
end Evaluer_Alea_TH;
|
procedure hola is
I, X : Integer;
begin
I := 1;
X := 4;
while I <= 6 AND X = 4 loop
put(I);
I := I + 1;
end loop;
X := 4 + 4;
put("Fin del programa \n");
end hola;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
package body Program.Nodes.Discrete_Subtype_Indications is
function Create
(Subtype_Mark : not null Program.Elements.Expressions
.Expression_Access;
Constraint : Program.Elements.Constraints
.Constraint_Access;
Is_Discrete_Subtype_Definition : Boolean := False)
return Discrete_Subtype_Indication is
begin
return Result : Discrete_Subtype_Indication :=
(Subtype_Mark => Subtype_Mark, Constraint => Constraint,
Is_Discrete_Subtype_Definition => Is_Discrete_Subtype_Definition,
Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
function Create
(Subtype_Mark : not null Program.Elements.Expressions
.Expression_Access;
Constraint : Program.Elements.Constraints
.Constraint_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False;
Is_Discrete_Subtype_Definition : Boolean := False)
return Implicit_Discrete_Subtype_Indication is
begin
return Result : Implicit_Discrete_Subtype_Indication :=
(Subtype_Mark => Subtype_Mark, Constraint => Constraint,
Is_Part_Of_Implicit => Is_Part_Of_Implicit,
Is_Part_Of_Inherited => Is_Part_Of_Inherited,
Is_Part_Of_Instance => Is_Part_Of_Instance,
Is_Discrete_Subtype_Definition => Is_Discrete_Subtype_Definition,
Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
overriding function Subtype_Mark
(Self : Base_Discrete_Subtype_Indication)
return not null Program.Elements.Expressions.Expression_Access is
begin
return Self.Subtype_Mark;
end Subtype_Mark;
overriding function Constraint
(Self : Base_Discrete_Subtype_Indication)
return Program.Elements.Constraints.Constraint_Access is
begin
return Self.Constraint;
end Constraint;
overriding function Is_Discrete_Subtype_Definition
(Self : Base_Discrete_Subtype_Indication)
return Boolean is
begin
return Self.Is_Discrete_Subtype_Definition;
end Is_Discrete_Subtype_Definition;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Discrete_Subtype_Indication)
return Boolean is
begin
return Self.Is_Part_Of_Implicit;
end Is_Part_Of_Implicit;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Discrete_Subtype_Indication)
return Boolean is
begin
return Self.Is_Part_Of_Inherited;
end Is_Part_Of_Inherited;
overriding function Is_Part_Of_Instance
(Self : Implicit_Discrete_Subtype_Indication)
return Boolean is
begin
return Self.Is_Part_Of_Instance;
end Is_Part_Of_Instance;
procedure Initialize
(Self : aliased in out Base_Discrete_Subtype_Indication'Class) is
begin
Set_Enclosing_Element (Self.Subtype_Mark, Self'Unchecked_Access);
if Self.Constraint.Assigned then
Set_Enclosing_Element (Self.Constraint, Self'Unchecked_Access);
end if;
null;
end Initialize;
overriding function Is_Discrete_Subtype_Indication_Element
(Self : Base_Discrete_Subtype_Indication)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Discrete_Subtype_Indication_Element;
overriding function Is_Discrete_Range_Element
(Self : Base_Discrete_Subtype_Indication)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Discrete_Range_Element;
overriding function Is_Definition_Element
(Self : Base_Discrete_Subtype_Indication)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Definition_Element;
overriding procedure Visit
(Self : not null access Base_Discrete_Subtype_Indication;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is
begin
Visitor.Discrete_Subtype_Indication (Self);
end Visit;
overriding function To_Discrete_Subtype_Indication_Text
(Self : aliased in out Discrete_Subtype_Indication)
return Program.Elements.Discrete_Subtype_Indications
.Discrete_Subtype_Indication_Text_Access is
begin
return Self'Unchecked_Access;
end To_Discrete_Subtype_Indication_Text;
overriding function To_Discrete_Subtype_Indication_Text
(Self : aliased in out Implicit_Discrete_Subtype_Indication)
return Program.Elements.Discrete_Subtype_Indications
.Discrete_Subtype_Indication_Text_Access is
pragma Unreferenced (Self);
begin
return null;
end To_Discrete_Subtype_Indication_Text;
end Program.Nodes.Discrete_Subtype_Indications;
|
with Ada.Text_IO;
with Yaml.Servers;
with GNAT.Sockets.Server;
procedure Yaml.Server is
Factory : aliased Servers.Yaml_Factory (200, 80, 8192, 100);
Server : Servers.Server.Connections_Server (Factory'Access, 8088);
pragma Unreferenced (Server);
begin
Factory.Trace_On (GNAT.Sockets.Server.Trace_Decoded,
GNAT.Sockets.Server.Trace_Decoded);
Ada.Text_IO.Put_Line ("HTTP server started.");
loop
delay 60.0;
end loop;
end Yaml.Server;
|
package body Rational is
function gcd(a_in, b_in : Long_Long_Integer) return Long_Long_Integer is
a : Long_Long_Integer := a_in;
b : Long_Long_Integer := b_in;
begin
if a = 0 then
return b;
end if;
while b /= 0 loop
if a > b then
a := a - b;
else
b := b - a;
end if;
end loop;
return a;
end gcd;
function Create(num : in Long_Long_Integer; den : in Long_Long_Integer) return Rat is
r : Rat;
begin
r.numerator := num;
r.denomonator := den;
return r;
end;
function "+" (left, right: in Rat) return Rat is
result : Rat := left;
begin
Add(result, right);
return result;
end "+";
function "-" (left, right: in Rat) return Rat is
result : Rat := left;
begin
Subtract(result, right);
return result;
end "-";
function "*" (left, right: in Rat) return Rat is
result : Rat := left;
begin
Multiply(result, right);
return result;
end "*";
function Inverse(r : in Rat) return Rat is
result : Rat := r;
begin
Inverse(result);
return result;
end Inverse;
procedure Inverse(r : in out Rat) is
temp : constant Long_Long_Integer := r.numerator;
begin
r.numerator := r.denomonator;
r.denomonator := temp;
end Inverse;
procedure Add(left : in out Rat; right : in Rat) is
begin
left.numerator := left.numerator * right.denomonator + right.numerator * left.denomonator;
left.denomonator := left.denomonator * right.denomonator;
end Add;
procedure Subtract(left : in out Rat; right : in Rat) is
begin
left.numerator := left.numerator * right.denomonator - right.numerator * left.denomonator;
left.denomonator := left.denomonator * right.denomonator;
end Subtract;
procedure Multiply(left : in out Rat; right : in Rat) is
begin
left.numerator := left.numerator * right.numerator;
left.denomonator := left.denomonator * right.denomonator;
end Multiply;
function Numerator(r : in Rat) return Long_Long_Integer is
begin
return r.numerator;
end Numerator;
function Denomonator(r : in Rat) return Long_Long_Integer is
begin
return r.denomonator;
end Denomonator;
function Normalize(r : in Rat) return Rat is
result : Rat := r;
begin
Normalize(result);
return result;
end;
procedure Normalize(r : in out Rat) is
g : constant Long_Long_Integer := gcd(r.numerator, r.denomonator);
begin
r.numerator := r.numerator / g;
r.denomonator := r.denomonator / g;
end;
function ToString(r : in Rat) return String is
begin
return Long_Long_Integer'Image(r.numerator) & " / " & Long_Long_Integer'Image(r.denomonator);
end;
end Rational;
|
-----------------------------------------------------------------------
-- asf-cookies-tests - Unit tests for Cookies
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Measures;
with Ada.Strings.Fixed;
with Ada.Unchecked_Deallocation;
package body ASF.Cookies.Tests is
use Ada.Strings.Fixed;
use Util.Tests;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("ASF.Cookies.Tests");
procedure Free is new Ada.Unchecked_Deallocation (Cookie_Array, Cookie_Array_Access);
package Caller is new Util.Test_Caller (Test, "Cookies");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test ASF.Cookies.Create_Cookie",
Test_Create_Cookie'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.To_Http_Header",
Test_To_Http_Header'Access);
Caller.Add_Test (Suite, "Test ASF.Cookies.Get_Cookies",
Test_Parse_Http_Header'Access);
end Add_Tests;
-- ------------------------------
-- Test creation of cookie
-- ------------------------------
procedure Test_Create_Cookie (T : in out Test) is
C : constant Cookie := Create ("cookie", "value");
begin
T.Assert_Equals ("cookie", Get_Name (C), "Invalid name");
T.Assert_Equals ("value", Get_Value (C), "Invalid value");
T.Assert (not Is_Secure (C), "Invalid is_secure");
end Test_Create_Cookie;
-- ------------------------------
-- Test conversion of cookie for HTTP header
-- ------------------------------
procedure Test_To_Http_Header (T : in out Test) is
procedure Test_Cookie (C : in Cookie) is
S : constant String := To_Http_Header (C);
begin
Log.Info ("Cookie {0}: {1}", Get_Name (C), S);
T.Assert (S'Length > 0, "Invalid cookie length for: " & S);
T.Assert (Index (S, "=") > 0, "Invalid cookie format; " & S);
end Test_Cookie;
procedure Test_Cookie (Name : in String; Value : in String) is
C : Cookie := Create (Name, Value);
begin
Test_Cookie (C);
for I in 1 .. 24 loop
Set_Max_Age (C, I * 3600 + I);
Test_Cookie (C);
end loop;
Set_Secure (C, True);
Test_Cookie (C);
Set_Http_Only (C, True);
Test_Cookie (C);
Set_Domain (C, "world.com");
Test_Cookie (C);
Set_Path (C, "/some-path");
Test_Cookie (C);
end Test_Cookie;
begin
Test_Cookie ("a", "b");
Test_Cookie ("session_id", "79e2317bcabe731e2f681f5725bbc621-&v=1");
Test_Cookie ("p_41_zy", "");
Test_Cookie ("p_34", """quoted\t""");
Test_Cookie ("d", "s");
declare
C : Cookie := Create ("cookie-name", "79e2317bcabe731e2f681f5725bbc621");
Start : Util.Measures.Stamp;
begin
Set_Path (C, "/home");
Set_Domain (C, ".mydomain.example.com");
Set_Max_Age (C, 1000);
Set_Http_Only (C, True);
Set_Secure (C, True);
Set_Comment (C, "some comment");
for I in 1 .. 1000 loop
declare
S : constant String := To_Http_Header (C);
begin
if S'Length < 10 then
T.Assert (S'Length > 10, "Invalid cookie generation");
end if;
end;
end loop;
Util.Measures.Report (S => Start,
Title => "Generation of 1000 cookies");
end;
end Test_To_Http_Header;
-- ------------------------------
-- Test parsing of client cookie to build a list of Cookie objects
-- ------------------------------
procedure Test_Parse_Http_Header (T : in out Test) is
-- ------------------------------
-- Parse the header and check for the expected cookie count and verify
-- the value of a specific cookie
-- ------------------------------
procedure Test_Parse (Header : in String;
Count : in Natural;
Name : in String;
Value : in String) is
Start : Util.Measures.Stamp;
C : Cookie_Array_Access := Get_Cookies (Header);
Found : Boolean := False;
begin
Util.Measures.Report (S => Start,
Title => "Parsing of cookie " & Name);
T.Assert (C /= null, "Null value returned by Get_Cookies");
Assert_Equals (T, Count, C'Length, "Invalid count in result array");
for I in C'Range loop
Log.Debug ("Cookie: {0}={1}", Get_Name (C (I)), Get_Value (C (I)));
if Name = Get_Name (C (I)) then
Assert_Equals (T, Value, Get_Value (C (I)), "Invalid cookie: " & Name);
Found := True;
end if;
end loop;
T.Assert (Found, "Cookie " & Name & " not found");
Free (C);
end Test_Parse;
begin
Test_Parse ("A=B", 1, "A", "B");
Test_Parse ("A=B=", 1, "A", "B=");
Test_Parse ("CONTEXTE=mar=101&nab=84fbbe2a81887732fe9c635d9ac319b5"
& "&pfl=afide0&typsrv=we&sc=1&soumar=1011&srcurlconfigchapeau"
& "=sous_ouv_formulaire_chapeau_dei_config&nag=550®=14505; "
& "xtvrn=$354249$354336$; CEPORM=321169600.8782.0000; SES=auth=0&"
& "cartridge_url=&return_url=; CEPORC=344500416.8782.0000", 5,
"SES", "auth=0&cartridge_url=&return_url=");
Test_Parse ("s_nr=1298652863627; s_sq=%5B%5BB%5D%5D; s_cc=true; oraclelicense="
& "accept-dbindex-cookie; gpv_p24=no%20value; gpw_e24=no%20value",
6, "gpw_e24", "no%20value");
-- Parse a set of cookies from microsoft.com
Test_Parse ("WT_FPC=id=00.06.036.020-2037773472.29989343:lv=1300442685103:ss=1300442685103; "
& "MC1=GUID=9d86c397c1a5ea4cab48d9fe19b76b4e&HASH=97c3&LV=20092&V=3; "
& "A=I&I=AxUFAAAAAABwBwAALSllub5HorZBtWWX8ZeXcQ!!&CS=114[3B002j2p[0302g3V309; "
& "WT_NVR_RU=0=technet|msdn:1=:2=; mcI=Fri, 31 Dec 2010 10:44:31 GMT; "
& "omniID=beb780dd_ab6d_4802_9f37_e33dde280adb; CodeSnippetContainerLang="
& "Visual Basic; MSID=Microsoft.CreationDate=11/09/2010 10:08:25&Microsoft."
& "LastVisitDate=03/01/2011 17:08:34&Microsoft.VisitStartDate=03/01/2011 "
& "17:08:34&Microsoft.CookieId=882efa27-ee6c-40c5-96ba-2297f985d9e3&Microsoft"
& ".TokenId=0c0a5e07-37a6-4ca3-afc0-0edf3de329f6&Microsoft.NumberOfVisits="
& "60&Microsoft.IdentityToken=RojEm8r/0KbCYeKasdfwekl3FtctotD5ocj7WVR72795"
& "dBj23rXVz5/xeldkkKHr/NtXFN3xAvczHlHQHKw14/9f/VAraQFIzEYpypGE24z1AuPCzVwU"
& "l4HZPnOFH+IA0u2oarcR1n3IMC4Gk8D1UOPBwGlYMB2Xl2W+Up8kJikc4qUxmFG+X5SRrZ3m7"
& "LntAv92B4v7c9FPewcQHDSAJAmTOuy7+sl6zEwW2fGWjqGe3G7bh+qqUWPs4LrvSyyi7T3UCW"
& "anSWn6jqJInP/MSeAxAvjbTrBwlJlE3AoUfXUJgL81boPYsIXZ30lPpqjMkyc0Jd70dffNNTo5"
& "qwkvfFhyOvnfYoQ7dZ0REw+TRA01xHyyUSPINOVgM5Vcu4SdvcUoIlMR3Y097nK+lvx8SqV4UU"
& "+QENW1wbBDa7/u6AQqUuk0616tWrBQMR9pYKwYsORUqLkQY5URzhVVA7Py28dLX002Nehqjbh68"
& "4xQv/gQYbPZMZUq/wgmPsqA5mJU/lki6A0S/H/ULGbrJE0PBQr8T+Hd+Op4HxEHvjvkTs=&Micr"
& "osoft.MicrosoftId=0004-1282-6244-7365; msresearch=%7B%22version%22%3A%224.6"
& "%22%2C%22state%22%3A%7B%22name%22%3A%22IDLE%22%2C%22url%22%3Aundefined%2C%2"
& "2timestamp%22%3A1296211850175%7D%2C%22lastinvited%22%3A1296211850175%2C%22u"
& "serid%22%3A%2212962118501758905232121057759%22%2C%22vendorid%22%3A1%2C%22su"
& "rveys%22%3A%5Bundefined%5D%7D; s_sq=%5B%5BB%5D%5D; s_cc=true; "
& "GsfxStatsLog=true; GsfxSessionCookie=231210164895294015; ADS=SN=175A21EF;"
& ".ASPXANONYMOUS=HJbsF8QczAEkAAAAMGU4YjY4YTctNDJhNy00NmQ3LWJmOWEtNjVjMzFmODY"
& "1ZTA5dhasChFIbRm1YpxPXPteSbwdTE01",
15, "s_sq", "%5B%5BB%5D%5D");
end Test_Parse_Http_Header;
end ASF.Cookies.Tests;
|
with
GL.safe,
GL.lean,
GL.desk,
interfaces.C,
System;
procedure launch_GL_linkage_Test
--
-- This test is only intended to check that all GL functions link correctly.
-- It is not meant to be run.
--
-- todo: Add missing calls for each profile.
is
use GL;
begin
-- Make a call to each core function
--
declare
Result : GLenum;
Status : GLboolean;
begin
glActiveTexture (0);
glBindTexture (0, 0);
glBlendFunc (0, 0);
glClear (0);
glClearColor (0.0, 0.0, 0.0, 0.0);
glClearDepthf (0.0);
glClearStencil (0);
glColorMask (0, 0, 0, 0);
glCullFace (0);
glDepthFunc (0);
glDepthMask (0);
glDepthRangef (0.0, 0.0);
glDisable (0);
glDrawArrays (0, 0, 0);
glEnable (0);
glFinish;
glFlush;
glFrontFace (0);
Result := glGetError;
glHint (0, 0);
Status := glIsEnabled (0);
glLineWidth (0.0);
glPixelStorei (0, 0);
glPolygonOffset (0.0, 0.0);
glScissor (0, 0, 0, 0);
glStencilFunc (0, 0, 0);
glStencilMask (0);
glStencilOp (0, 0, 0);
glTexParameteri (0, 0, 0);
glViewport (0, 0, 0, 0);
end;
-- Make a call to each 'Safe' function
--
declare
use safe;
Result : access GLubyte;
begin
Result := glGetString (0);
glDrawElements (0, 0, 0, null);
glGenTextures (0, null);
glGetBooleanv (0, null);
glGetFloatv (0, null);
glGetIntegerv (0, null);
glGetTexParameteriv (0, 0, null);
glReadPixels (0, 0, 0, 0, 0, 0, null);
glTexImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
end;
-- Make a call to each 'Lean' function
--
declare
use lean, System;
a_GLenum : GLenum;
a_GLuint : GLuint;
a_GLboolean : GLboolean;
a_C_int : interfaces.C.int;
GLubyte_access : access GLubyte;
begin
glAttachShader (0, 0);
glBindAttribLocation (0, 0, null);
glBindBuffer (0, 0);
glBindFramebuffer (0, 0);
glBindRenderbuffer (0, 0);
glBlendColor (0.0, 0.0, 0.0, 0.0);
glBlendEquation (0);
glBlendEquationSeparate (0, 0);
glBlendFuncSeparate (0, 0, 0, 0);
glBufferData (0, 0, null, 0);
glBufferSubData (0, 0, 0, null);
a_GLenum := glCheckFramebufferStatus (0);
glCompileShader (0);
glCompressedTexImage2D (0, 0, 0, 0, 0, 0, 0, null);
glCompressedTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glCopyTexImage2D (0, 0, 0, 0, 0, 0, 0, 0);
glCopyTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0);
a_GLuint := glCreateProgram;
a_GLuint := glCreateShader (0);
glDeleteBuffers (0, null);
glDeleteFramebuffers (0, null);
glDeleteProgram (0);
glDeleteRenderbuffers (0, null);
glDeleteShader (0);
glDeleteTextures (0, null);
glDetachShader (0, 0);
glDisableVertexAttribArray(0);
glDrawElements (0, 0, 0, null);
glEnableVertexAttribArray (0);
glFramebufferRenderbuffer (0, 0, 0, 0);
glFramebufferTexture2D (0, 0, 0, 0, 0);
glGenBuffers (0, null);
glGenFramebuffers (0, null);
glGenRenderbuffers (0, null);
glGenTextures (0, null);
glGenerateMipmap (0);
glGetActiveAttrib (0, 0, 0, null, null, null, null);
glGetActiveUniform (0, 0, 0, null, null, null, null);
glGetAttachedShaders (0, 0, null, null);
a_C_int := glGetAttribLocation (0, null);
glGetBooleanv (0, null);
glGetBufferParameteriv (0, 0, null);
glGetFloatv (0, null);
glGetFramebufferAttachmentParameteriv
(0, 0, 0, null);
glGetIntegerv (0, null);
glGetProgramiv (0, 0, null);
glGetProgramInfoLog (0, 0, null, null);
glGetRenderbufferParameteriv
(0, 0, null);
glGetShaderiv (0, 0, null);
glGetShaderInfoLog (0, 0, null, null);
glGetShaderPrecisionFormat(0, 0, null, null);
glGetShaderSource (0, 0, null, null);
GLubyte_access := glGetString(0);
glGetTexParameterfv (0, 0, null_Address);
glGetTexParameteriv (0, 0, null);
glGetUniformfv (0, 0, null_Address);
glGetUniformiv (0, 0, null);
a_C_int := glGetUniformLocation (0, null);
glGetVertexAttribfv (0, 0, null_Address);
glGetVertexAttribiv (0, 0, null);
glGetVertexAttribPointerv (0, 0, null);
a_GLboolean := glIsBuffer (0);
a_GLboolean := glIsFramebuffer (0);
a_GLboolean := glIsProgram (0);
a_GLboolean := glIsRenderbuffer(0);
a_GLboolean := glIsShader (0);
a_GLboolean := glIsTexture (0);
glLinkProgram (0);
glReadPixels (0, 0, 0, 0, 0, 0, null);
glReleaseShaderCompiler;
glRenderbufferStorage (0, 0, 0, 0);
glSampleCoverage (0.0, 0);
glShaderBinary (0, null, 0, null, 0);
glShaderSource (0, 0, null, null);
glStencilFuncSeparate (0, 0, 0, 0);
glStencilMaskSeparate (0, 0);
glStencilOpSeparate (0, 0, 0, 0);
glTexImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glTexParameterf (0, 0, 0.0);
glTexParameterfv (0, 0, null_Address);
glTexParameteriv (0, 0, null);
glTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glUniform1f (0, 0.0);
glUniform1fv (0, 0, null_Address);
glUniform1i (0, 0);
glUniform1iv (0, 0, null);
glUniform2f (0, 0.0, 0.0);
glUniform2fv (0, 0, null_Address);
glUniform2i (0, 0, 0);
glUniform2iv (0, 0, null);
glUniform3f (0, 0.0, 0.0, 0.0);
glUniform3fv (0, 0, null_Address);
glUniform3i (0, 0, 0, 0);
glUniform3iv (0, 0, null);
glUniform4f (0, 0.0, 0.0, 0.0, 0.0);
glUniform4fv (0, 0, null_Address);
glUniform4i (0, 0, 0, 0, 0);
glUniform4iv (0, 0, null);
glUniformMatrix2fv (0, 0, 0, null_Address);
glUniformMatrix3fv (0, 0, 0, null_Address);
glUniformMatrix4fv (0, 0, 0, null_Address);
glUseProgram (0);
glValidateProgram (0);
glVertexAttrib1f (0, 0.0);
glVertexAttrib1fv (0, null_Address);
glVertexAttrib2f (0, 0.0, 0.0);
glVertexAttrib2fv (0, null_Address);
glVertexAttrib3f (0, 0.0, 0.0, 0.0);
glVertexAttrib3fv (0, null_Address);
glVertexAttrib4f (0, 0.0, 0.0, 0.0, 0.0);
glVertexAttrib4fv (0, null_Address);
glVertexAttribPointer (0, 0, 0, 0, 0, null);
end;
-- Make a call to each 'desk' function
--
declare
use desk;
a_GLboolean : GLboolean;
begin
glActiveTexture (0);
glBindTexture (0, 0);
glBlendColor (0.0, 0.0, 0.0, 0.0);
glBlendEquation (0);
glBlendEquationSeparate (0, 0);
glBlendFunc (0, 0);
glClearStencil (0);
glClearDepth (0.0);
glColorMask (0, 0, 0, 0);
glCompressedTexImage2D (0, 0, 0, 0, 0, 0, 0, null);
glCompressedTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glCopyTexImage2D (0, 0, 0, 0, 0, 0, 0, 0);
glCopyTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0);
glDeleteTextures (0, null);
glDepthMask (0);
glDisable (0);
glDrawArrays (0, 0, 0);
glGetBooleanv (0, null);
glGetFloatv (0, null);
glGetIntegerv (0, null);
glGetTexParameterfv (0, 0, null);
glGetTexParameteriv (0, 0, null);
a_GLboolean := glIsTexture(0);
glLineWidth (0.0);
glPixelStorei (0, 0);
glPolygonOffset (0.0, 0.0);
glReadPixels (0, 0, 0, 0, 0, 0, null);
glSampleCoverage (0.0, 0);
glStencilMask (0);
glStencilOp (0, 0, 0);
glTexImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
glTexParameterf (0, 0, 0.0);
glTexParameterfv (0, 0, null);
glTexParameteri (0, 0, 0);
glTexParameteriv (0, 0, null);
glTexSubImage2D (0, 0, 0, 0, 0, 0, 0, 0, null);
end;
end launch_GL_linkage_Test;
|
with Asis.Declarations;
with Asis.Elements;
package body Asis_Adapter.Element.Defining_Names is
------------
-- EXPORTED:
------------
procedure Do_Pre_Child_Processing
(Element : in Asis.Element; State : in out Class)
is
Parent_Name : constant String := Module_Name;
Module_Name : constant String := Parent_Name & ".Do_Pre_Child_Processing";
Result : a_nodes_h.Defining_Name_Struct :=
a_nodes_h.Support.Default_Defining_Name_Struct;
Defining_Name_Kind : Asis.Defining_Name_Kinds :=
Asis.Elements.Defining_Name_Kind (Element);
-- Supporting procedures are in alphabetical order:
procedure Add_Defining_Name_Image is
WS : constant Wide_String := Asis.Declarations.Defining_Name_Image (Element);
begin
State.Add_To_Dot_Label ("Defining_Name_Image", To_Quoted_String (WS));
Result.Defining_Name_Image := To_Chars_Ptr(WS);
end;
procedure Add_Defining_Prefix is
ID : constant a_nodes_h.Element_ID :=
Get_Element_ID (Asis.Declarations.Defining_Prefix (Element));
begin
State.Add_To_Dot_Label_And_Edge ("Defining_Prefix", ID);
Result.Defining_Prefix := ID;
end;
procedure Add_Defining_Selector is
ID : constant a_nodes_h.Element_ID :=
Get_Element_ID (Asis.Declarations.Defining_Selector (Element));
begin
State.Add_To_Dot_Label_And_Edge ("Defining_Selector", ID);
Result.Defining_Selector := ID;
end;
procedure Add_Position_Number_Image is
WS : constant Wide_String := Asis.Declarations.Position_Number_Image (Element);
begin
State.Add_To_Dot_Label ("Position_Number_Image", To_String (WS));
Result.Position_Number_Image := To_Chars_Ptr(WS);
end;
procedure Add_Representation_Value_Image is
WS : constant Wide_String := Asis.Declarations.Representation_Value_Image (Element);
begin
State.Add_To_Dot_Label ("Representation_Value_Image", To_String (WS));
Result.Representation_Value_Image := To_Chars_Ptr(WS);
end;
-- True if this is the name of a constant or a deferred constant.
-- TODO: Implement
function Is_Constant return Boolean is
(False);
procedure Add_Corresponding_Constant_Declaration is
ID : constant a_nodes_h.Element_ID :=
Get_Element_ID
(Asis.Declarations.Corresponding_Constant_Declaration (Element));
begin
State.Add_To_Dot_Label ("Corresponding_Constant_Declaration", To_String(ID));
Result.Corresponding_Constant_Declaration := ID;
end;
procedure Add_Common_Items is
begin
State.Add_To_Dot_Label
(Name => "Defining_Name_Kind", Value => Defining_Name_Kind'Image);
Result.Defining_Name_Kind :=
anhS.To_Defining_Name_Kinds (Defining_Name_Kind);
Add_Defining_Name_Image;
end Add_Common_Items;
use all type Asis.Defining_Name_Kinds;
begin
If Defining_Name_Kind /= Not_A_Defining_Name then
Add_Common_Items;
end if;
case Defining_Name_Kind is
when Not_A_Defining_Name =>
raise Program_Error with
Module_Name & " called with: " & Defining_Name_Kind'Image;
when A_Defining_Identifier =>
null; -- No more info
when A_Defining_Character_Literal |
A_Defining_Enumeration_Literal =>
Add_Position_Number_Image;
Add_Representation_Value_Image;
when A_Defining_Operator_Symbol =>
Result.Operator_Kind := Add_Operator_Kind (State, Element);
when A_Defining_Expanded_Name =>
Add_Defining_Prefix;
Add_Defining_Selector;
end case;
if Is_Constant then
Add_Corresponding_Constant_Declaration;
end if;
State.A_Element.Element_Kind := a_nodes_h.A_Defining_Name;
State.A_Element.The_Union.Defining_Name := Result;
end Do_Pre_Child_Processing;
end Asis_Adapter.Element.Defining_Names;
|
with Ada.Numerics.Discrete_Random;
package RandInt is
package RA is new Ada.Numerics.Discrete_Random(Natural);
function Next(n: in Natural) return Natural;
end RandInt ;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . T E X T _ I O --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
-- Minimal version of Text_IO body for use on STM32F4xxx, using USART1
with Interfaces; use Interfaces;
with Interfaces.STM32; use Interfaces.STM32;
with Interfaces.STM32.RCC; use Interfaces.STM32.RCC;
with Interfaces.STM32.GPIO; use Interfaces.STM32.GPIO;
with Interfaces.STM32.USART; use Interfaces.STM32.USART;
with System.STM32; use System.STM32;
with System.BB.Parameters;
package body System.Text_IO is
Baudrate : constant := 115_200;
-- Bitrate to use
----------------
-- Initialize --
----------------
procedure Initialize is
use System.BB.Parameters;
APB_Clock : constant Positive := Positive (STM32.System_Clocks.PCLK2);
Int_Divider : constant Positive := (25 * APB_Clock) / (4 * Baudrate);
Frac_Divider : constant Natural := Int_Divider rem 100;
Pins : constant array (1 .. 2) of Natural := (9, 14);
begin
Initialized := True;
RCC_Periph.APB2ENR.USART6EN := 1;
RCC_Periph.AHB1ENR.GPIOGEN := 1;
for Pin of Pins loop
GPIOG_Periph.MODER.Arr (Pin) := Mode_AF;
GPIOG_Periph.OSPEEDR.Arr (Pin) := Speed_50MHz;
GPIOG_Periph.OTYPER.OT.Arr (Pin) := Push_Pull;
GPIOG_Periph.PUPDR.Arr (Pin) := Pull_Up;
GPIOG_Periph.AFRL.Arr (Pin) := AF_USART6;
end loop;
USART6_Periph.BRR :=
(DIV_Fraction => UInt4 (((Frac_Divider * 16 + 50) / 100) mod 16),
DIV_Mantissa => UInt12 (Int_Divider / 100),
others => <>);
USART6_Periph.CR1 :=
(UE => 1,
RE => 1,
TE => 1,
others => <>);
USART6_Periph.CR2 := (others => <>);
USART6_Periph.CR3 := (others => <>);
end Initialize;
-----------------
-- Is_Tx_Ready --
-----------------
function Is_Tx_Ready return Boolean is
(USART6_Periph.SR.TC = 1);
-----------------
-- Is_Rx_Ready --
-----------------
function Is_Rx_Ready return Boolean is
(USART6_Periph.SR.RXNE = 1);
---------
-- Get --
---------
function Get return Character is (Character'Val (USART6_Periph.DR.DR));
---------
-- Put --
---------
procedure Put (C : Character) is
begin
USART6_Periph.DR.DR := Character'Pos (C);
end Put;
----------------------------
-- Use_Cr_Lf_For_New_Line --
----------------------------
function Use_Cr_Lf_For_New_Line return Boolean is (True);
end System.Text_IO;
|
--------------------------------------------------------------------------------------------------------------------
-- Copyright (c) 2013-2018 Luke A. Guest
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely, subject to the following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software
-- in a product, an acknowledgment in the product documentation would be
-- appreciated but is not required.
--
-- 2. Altered source versions must be plainly marked as such, and must not be
-- misrepresented as being the original software.
--
-- 3. This notice may not be removed or altered from any source
-- distribution.
--------------------------------------------------------------------------------------------------------------------
-- SDL.Events.Joysticks
--
-- Joystick specific events.
--------------------------------------------------------------------------------------------------------------------
package SDL.Events.Joysticks is
-- Joystick events.
Axis_Motion : constant Event_Types := 16#0000_0600#;
Ball_Motion : constant Event_Types := Axis_Motion + 1;
Hat_Motion : constant Event_Types := Axis_Motion + 2;
Button_Down : constant Event_Types := Axis_Motion + 3;
Button_Up : constant Event_Types := Axis_Motion + 4;
Device_Added : constant Event_Types := Axis_Motion + 5;
Device_Removed : constant Event_Types := Axis_Motion + 6;
type IDs is range -2 ** 31 .. 2 ** 31 - 1 with
Convention => C,
Size => 32;
type Axes is range 0 .. 255 with
Convention => C,
Size => 8;
type Axes_Values is range -32768 .. 32767 with
Convention => C,
Size => 16;
type Axis_Events is
record
Event_Type : Event_Types; -- Will be set to Axis_Motion.
Time_Stamp : Time_Stamps;
Which : IDs;
Axis : Axes;
Padding_1 : Padding_8;
Padding_2 : Padding_8;
Padding_3 : Padding_8;
Value : Axes_Values;
Padding_4 : Padding_16;
end record with
Convention => C;
type Balls is range 0 .. 255 with
Convention => C,
Size => 8;
type Ball_Values is range -32768 .. 32767 with
Convention => C,
Size => 16;
type Ball_Events is
record
Event_Type : Event_Types; -- Will be set to Ball_Motion.
Time_Stamp : Time_Stamps;
Which : IDs;
Ball : Balls;
Padding_1 : Padding_8;
Padding_2 : Padding_8;
Padding_3 : Padding_8;
X_Relative : Ball_Values;
Y_Relative : Ball_Values;
end record with
Convention => C;
type Hats is range 0 .. 255 with
Convention => C,
Size => 8;
type Hat_Positions is mod 2 ** 8 with
Convention => C,
Size => 8;
Hat_Centred : constant Hat_Positions := 0;
Hat_Up : constant Hat_Positions := 1;
Hat_Right : constant Hat_Positions := 2;
Hat_Down : constant Hat_Positions := 4;
Hat_Left : constant Hat_Positions := 8;
Hat_Right_Up : constant Hat_Positions := Hat_Right or Hat_Up;
Hat_Right_Down : constant Hat_Positions := Hat_Right or Hat_Down;
Hat_Left_Up : constant Hat_Positions := Hat_Left or Hat_Up;
Hat_Left_Down : constant Hat_Positions := Hat_Left or Hat_Down;
type Hat_Events is
record
Event_Type : Event_Types; -- Will be set to Hat_Motion.
Time_Stamp : Time_Stamps;
Which : IDs;
Hat : Hats;
Position : Hat_Positions;
Padding_1 : Padding_8;
Padding_2 : Padding_8;
end record with
Convention => C;
type Buttons is range 0 .. 255 with
Convention => C,
Size => 8;
type Button_Events is
record
Event_Type : Event_Types; -- Will be set to Button_Down or Button_Up.
Time_Stamp : Time_Stamps;
Which : IDs;
Button : Buttons;
State : Button_State;
Padding_1 : Padding_8;
Padding_2 : Padding_8;
end record with
Convention => C;
type Device_Events is
record
Event_Type : Event_Types; -- Will be set to Device_Added or Device_Removed.
Time_Stamp : Time_Stamps;
Which : IDs;
end record with
Convention => C;
-- Update the joystick event data. This is called by the event loop.
procedure Update with
Import => True,
Convention => C,
External_Name => "SDL_JoystickUpdate";
function Is_Polling_Enabled return Boolean;
procedure Enable_Polling with
Inline => True;
procedure Disable_Polling with
Inline => True;
private
for Axis_Events use
record
Event_Type at 0 * SDL.Word range 0 .. 31;
Time_Stamp at 1 * SDL.Word range 0 .. 31;
Which at 2 * SDL.Word range 0 .. 31;
Axis at 3 * SDL.Word range 0 .. 7;
Padding_1 at 3 * SDL.Word range 8 .. 15;
Padding_2 at 3 * SDL.Word range 16 .. 23;
Padding_3 at 3 * SDL.Word range 24 .. 31;
Value at 4 * SDL.Word range 0 .. 15;
Padding_4 at 4 * SDL.Word range 16 .. 31;
end record;
for Ball_Events use
record
Event_Type at 0 * SDL.Word range 0 .. 31;
Time_Stamp at 1 * SDL.Word range 0 .. 31;
Which at 2 * SDL.Word range 0 .. 31;
Ball at 3 * SDL.Word range 0 .. 7;
Padding_1 at 3 * SDL.Word range 8 .. 15;
Padding_2 at 3 * SDL.Word range 16 .. 23;
Padding_3 at 3 * SDL.Word range 24 .. 31;
X_Relative at 4 * SDL.Word range 0 .. 15;
Y_Relative at 4 * SDL.Word range 16 .. 31;
end record;
for Hat_Events use
record
Event_Type at 0 * SDL.Word range 0 .. 31;
Time_Stamp at 1 * SDL.Word range 0 .. 31;
Which at 2 * SDL.Word range 0 .. 31;
Hat at 3 * SDL.Word range 0 .. 7;
Position at 3 * SDL.Word range 8 .. 15;
Padding_1 at 3 * SDL.Word range 16 .. 23;
Padding_2 at 3 * SDL.Word range 24 .. 31;
end record;
for Button_Events use
record
Event_Type at 0 * SDL.Word range 0 .. 31;
Time_Stamp at 1 * SDL.Word range 0 .. 31;
Which at 2 * SDL.Word range 0 .. 31;
Button at 3 * SDL.Word range 0 .. 7;
State at 3 * SDL.Word range 8 .. 15;
Padding_1 at 3 * SDL.Word range 16 .. 23;
Padding_2 at 3 * SDL.Word range 24 .. 31;
end record;
for Device_Events use
record
Event_Type at 0 * SDL.Word range 0 .. 31;
Time_Stamp at 1 * SDL.Word range 0 .. 31;
Which at 2 * SDL.Word range 0 .. 31;
end record;
end SDL.Events.Joysticks;
|
with Interfaces;
package GESTE_Config is
type Color_Index is range 0 .. 77;
subtype Output_Color is Interfaces.Unsigned_16;
Transparent : constant Output_Color := 10067;
Tile_Size : constant := 8;
type Tile_Index is range 0 .. 194;
No_Tile : constant Tile_Index := 0;
end GESTE_Config;
|
-----------------------------------------------------------------------
-- awa-storages-services -- Storage service
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Calendar;
with Ada.Strings.Unbounded;
with Security.Permissions;
with ADO;
with ASF.Parts;
with AWA.Modules;
with AWA.Modules.Lifecycles;
with AWA.Storages.Models;
with AWA.Storages.Stores;
with AWA.Storages.Stores.Databases;
-- == Storage Service ==
-- The <tt>Storage_Service</tt> provides the operations to access and use the persisent storage.
-- It controls the permissions that grant access to the service for users.
--
-- Other modules can be notified of storage changes by registering a listener
-- on the storage module.
--
-- @include awa-storages-stores.ads
package AWA.Storages.Services is
package ACL_Create_Storage is new Security.Permissions.Definition ("storage-create");
package ACL_Delete_Storage is new Security.Permissions.Definition ("storage-delete");
package ACL_Create_Folder is new Security.Permissions.Definition ("folder-create");
type Read_Mode is (READ, WRITE);
type Expire_Type is (ONE_HOUR, ONE_DAY, TWO_DAYS, ONE_WEEK, ONE_YEAR, NEVER);
package Storage_Lifecycle is
new AWA.Modules.Lifecycles (Element_Type => AWA.Storages.Models.Storage_Ref'Class);
subtype Listener is Storage_Lifecycle.Listener;
-- ------------------------------
-- Storage Service
-- ------------------------------
-- The <b>Storage_Service</b> defines a set of operations to store and retrieve
-- a data object from the persistent storage. The data object is treated as a raw
-- byte stream. The persistent storage can be implemented by a database, a file
-- system or a remote service such as Amazon AWS.
type Storage_Service is new AWA.Modules.Module_Manager with private;
type Storage_Service_Access is access all Storage_Service'Class;
-- Initializes the storage service.
overriding
procedure Initialize (Service : in out Storage_Service;
Module : in AWA.Modules.Module'Class);
-- Get the persistent store that manages the data store identified by <tt>Kind</tt>.
function Get_Store (Service : in Storage_Service;
Kind : in AWA.Storages.Models.Storage_Type)
return AWA.Storages.Stores.Store_Access;
-- Create or save the folder.
procedure Save_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class);
-- Load the folder instance identified by the given identifier.
procedure Load_Folder (Service : in Storage_Service;
Folder : in out AWA.Storages.Models.Storage_Folder_Ref'Class;
Id : in ADO.Identifier);
-- Save the data object contained in the <b>Data</b> part element into the
-- target storage represented by <b>Into</b>.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Data : in ASF.Parts.Part'Class;
Storage : in AWA.Storages.Models.Storage_Type);
-- Save the file pointed to by the <b>Path</b> string in the storage
-- object represented by <b>Into</b> and managed by the storage service.
procedure Save (Service : in Storage_Service;
Into : in out AWA.Storages.Models.Storage_Ref'Class;
Path : in String;
Storage : in AWA.Storages.Models.Storage_Type);
-- Load the storage instance identified by the given identifier.
procedure Load_Storage (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class;
Id : in ADO.Identifier);
-- Load the storage content identified by <b>From</b> into the blob descriptor <b>Into</b>.
-- Raises the <b>NOT_FOUND</b> exception if there is no such storage.
procedure Load (Service : in Storage_Service;
From : in ADO.Identifier;
Name : out Ada.Strings.Unbounded.Unbounded_String;
Mime : out Ada.Strings.Unbounded.Unbounded_String;
Date : out Ada.Calendar.Time;
Into : out ADO.Blob_Ref);
-- Load the storage content into a file. If the data is not stored in a file, a temporary
-- file is created with the data content fetched from the store (ex: the database).
-- The `Mode` parameter indicates whether the file will be read or written.
-- The `Expire` parameter allows to control the expiration of the temporary file.
procedure Get_Local_File (Service : in Storage_Service;
From : in ADO.Identifier;
Mode : in Read_Mode := READ;
Into : out Storage_File);
procedure Create_Local_File (Service : in Storage_Service;
Into : out Storage_File);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in out AWA.Storages.Models.Storage_Ref'Class);
-- Deletes the storage instance.
procedure Delete (Service : in Storage_Service;
Storage : in ADO.Identifier);
private
type Store_Access_Array is
array (AWA.Storages.Models.Storage_Type) of AWA.Storages.Stores.Store_Access;
type Storage_Service is new AWA.Modules.Module_Manager with record
Stores : Store_Access_Array;
Database_Store : aliased AWA.Storages.Stores.Databases.Database_Store;
end record;
end AWA.Storages.Services;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B . L O A D --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This child package contains the function used to load a separately
-- compiled unit, as well as the routine used to initialize the unit
-- table and load the main source file.
package Lib.Load is
-------------------------------
-- Handling of Renamed Units --
-------------------------------
-- A compilation unit can be a renaming of another compilation unit.
-- Such renamed units are not allowed as parent units, that is you
-- cannot declare a unit:
-- with x;
-- package x.y is end;
-- where x is a renaming of some other package. However you can refer
-- to a renamed unit in a with clause:
-- package p is end;
-- package p.q is end;
-- with p;
-- package pr renames p;
-- with pr.q ....
-- This means that in the context of a with clause, the normal fixed
-- correspondence between unit and file names is broken. In the above
-- example, there is no file named pr-q.ads, since the actual child
-- unit is p.q, and it will be found in file p-q.ads.
-- In order to deal with this case, we have to first load pr.ads, and
-- then discover that it is a renaming of p, so that we know that pr.q
-- really refers to p.q. Furthermore this can happen at any level:
-- with p.q;
-- package p.r renames p.q;
-- with p.q;
-- package p.q.s is end;
-- with p.r.s ...
-- Now we have a case where the parent p.r is a child unit and is
-- a renaming. This shows that renaming can occur at any level.
-- Finally, consider:
-- with pr.q.s ...
-- Here the parent pr.q is not itself a renaming, but it really refers
-- to the unit p.q, and again we cannot know this without loading the
-- parent. The bottom line here is that while the file name of a unit
-- always corresponds to the unit name, the unit name as given to the
-- Load_Unit function may not be the real unit.
-----------------
-- Subprograms --
-----------------
procedure Initialize;
-- Initialize internal tables
procedure Initialize_Version (U : Unit_Number_Type);
-- This is called once the source file corresponding to unit U has been
-- fully scanned. At that point the checksum is computed, and can be used
-- to initialize the version number.
procedure Load_Main_Source;
-- Called at the start of compiling a new main source unit to initialize
-- the library processing for the new main source. Establishes and
-- initializes the units table entry for the new main unit (leaving
-- the Unit_File_Name entry of Main_Unit set to No_File if there are no
-- more files. Otherwise the main source file has been opened and read
-- and then closed on return.
function Load_Unit
(Load_Name : Unit_Name_Type;
Required : Boolean;
Error_Node : Node_Id;
Subunit : Boolean;
Corr_Body : Unit_Number_Type := No_Unit;
Renamings : Boolean := False;
With_Node : Node_Id := Empty;
PMES : Boolean := False) return Unit_Number_Type;
-- This function loads and parses the unit specified by Load_Name (or
-- returns the unit number for the previously constructed units table
-- entry if this is not the first call for this unit). Required indicates
-- the behavior on a file not found condition, as further described below,
-- and Error_Node is the node in the calling program to which error
-- messages are to be attached.
--
-- If the corresponding file is found, the value returned by Load is the
-- unit number that indexes the corresponding entry in the units table. If
-- a serious enough parser error occurs to prevent subsequent semantic
-- analysis, then the Fatal_Error flag of the returned entry is set and
-- in addition, the fatal error flag of the calling unit is also set.
--
-- If the corresponding file is not found, then the behavior depends on
-- the setting of Required. If Required is False, then No_Unit is returned
-- and no error messages are issued. If Required is True, then an error
-- message is posted, and No_Unit is returned.
--
-- A special case arises in the call from Rtsfind, where Error_Node is set
-- to Empty. In this case Required is False, and the caller in any case
-- treats any error as fatal.
--
-- The Subunit parameter is True to load a subunit, and False to load
-- any other kind of unit (including all specs, package bodies, and
-- subprogram bodies).
--
-- The Corr_Body argument is normally defaulted. It is set only in the
-- case of loading the corresponding spec when the main unit is a body.
-- In this case, Corr_Body is the unit number of this corresponding
-- body. This is used to set the Serial_Ref_Unit field of the unit
-- table entry. It is also used to deal with the special processing
-- required by RM 10.1.4(4). See description in lib.ads.
--
-- Renamings activates the handling of renamed units as separately
-- described in the documentation of this unit. If this parameter is
-- set to True, then Load_Name may not be the real unit name and it
-- is necessary to load parents to find the real name.
--
-- With_Node is set to the with_clause or limited_with_clause causing
-- the unit to be loaded, and is used to bypass the circular dependency
-- check in the case of a limited_with_clause (Ada 2005, AI-50217).
--
-- PMES indicates the required setting of Parsing_Main_Extended_Unit during
-- loading of the unit. This flag is saved and restored over the call.
-- Note: PMES is false for the subunit case, which seems wrong???
procedure Change_Main_Unit_To_Spec;
-- This procedure is called if the main unit file contains a No_Body pragma
-- and no other tokens. The effect is, if possible, to change the main unit
-- from the body it references now, to the corresponding spec. This has the
-- effect of ignoring the body, which is what we want. If it is impossible
-- to successfully make the change, then the call has no effect, and the
-- file is unchanged (this will lead to an error complaining about the
-- inappropriate No_Body spec).
function Create_Dummy_Package_Unit
(With_Node : Node_Id;
Spec_Name : Unit_Name_Type) return Unit_Number_Type;
-- With_Node is the Node_Id of a with statement for which the file could
-- not be found, and Spec_Name is the corresponding unit name. This call
-- creates a dummy package unit so that compilation can continue without
-- blowing up when the missing unit is referenced.
procedure Make_Child_Decl_Unit (N : Node_Id);
-- For a child subprogram body without a spec, we create a subprogram
-- declaration in order to attach the required parent link. We create
-- a Units_Table entry for this declaration, in order to maintain a
-- one-to-one correspondence between compilation units and table entries.
procedure Make_Instance_Unit (N : Node_Id; In_Main : Boolean);
-- When a compilation unit is an instantiation, it contains both the
-- declaration and the body of the instance, each of which can have its
-- own elaboration routine. The file itself corresponds to the declaration.
-- We create an additional entry for the body, so that the binder can
-- generate the proper elaboration calls to both. The argument N is the
-- compilation unit node created for the body.
--
-- If the instance is not the main program, we still generate the instance
-- body even though we do not generate code for it. In that case we still
-- generate a compilation unit node for it, and we need to make an entry
-- for it in the units table, so as to maintain a one-to-one mapping
-- between table and nodes. The table entry is used among other things to
-- provide a canonical traversal order for context units for CodePeer.
-- The flag In_Main indicates whether the instance is the main unit.
procedure Version_Update (U : Node_Id; From : Node_Id);
-- This routine is called when unit U is found to be semantically
-- dependent on unit From. It updates the version of U to register
-- dependence on the version of From. The arguments are compilation
-- unit nodes for the relevant library nodes.
end Lib.Load;
|
-- MIT License
-- Copyright (c) 2021 Stephen Merrony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
with Ada.Text_IO; use Ada.Text_IO;
with Interfaces; use Interfaces;
with Debug_Logs; use Debug_Logs;
with DG_Types; use DG_Types;
with Resolver; use Resolver;
package body Processor.Eagle_Op_P is
procedure Do_Eagle_Op (I : in Decoded_Instr_T; CPU : in out CPU_T) is
Acd_S16, S16 : Integer_16;
Acd_S32, Acs_S32, S32 : Integer_32;
S64 : Integer_64;
Shift : Integer;
procedure Set_OVR (New_OVR : in Boolean) is
begin
if New_OVR then
Set_W_Bit(CPU.PSR, 1);
else
Clear_W_Bit(CPU.PSR, 1);
end if;
end Set_OVR;
begin
case I.Instruction is
when I_CRYTC =>
CPU.Carry := not CPU.Carry;
when I_CRYTO =>
CPU.Carry := true;
when I_CRYTZ =>
CPU.Carry := false;
when I_CVWN =>
if ((CPU.AC(I.Ac) and 16#ffff_0000#) = 0) or ((CPU.AC(I.Ac) and 16#ffff_0000#) = 16#ffff_0000#) then
Set_OVR (true);
else
Set_OVR (false);
end if;
CPU.AC(I.Ac) := CPU.AC(I.Ac) and 16#0000_ffff#;
if Test_DW_Bit (CPU.AC(I.Ac), 16) then
CPU.AC(I.Ac) := CPU.AC(I.Ac) or 16#ffff_0000#;
end if;
when I_NADD =>
S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acd)))) +
Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acs))));
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
when I_NADDI =>
Acd_S16 := DG_Types.Word_To_Integer_16(Lower_Word(CPU.AC(I.Ac)));
S16 := Word_To_Integer_16(I.Word_2);
S32 := Integer_32(Acd_S16) + Integer_32(S16);
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Ac) := Integer_32_To_Dword(S32);
when I_NADI =>
S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Ac)))) +
Integer_32(I.Imm_U16);
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Ac) := Integer_32_To_Dword(S32);
when I_NDIV =>
Acd_S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acd))));
Acs_S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acs))));
if Acs_S32 = 0 then
CPU.Carry := true;
Set_OVR (true);
else
S32 := Acd_S32 / Acs_S32;
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
end if;
when I_NLDAI =>
CPU.AC(I.Ac) := Sext_Word_To_Dword(I.Word_2);
when I_NMUL =>
S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acd)))) *
Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acs))));
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
when I_NNEG =>
S32 := -Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acs))));
Set_OVR (CPU.AC(I.Acs) = 8#100000#);
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
when I_NSBI =>
S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Ac)))) -
Integer_32(I.Imm_U16);
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Ac) := Integer_32_To_Dword(S32);
when I_NSUB =>
S32 := Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acd)))) -
Integer_32(Word_To_Integer_16(DG_Types.Lower_Word(CPU.AC(I.Acs))));
CPU.Carry := (S32 > Max_Pos_S16) or (S32 < Min_Neg_S16);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
when I_SEX =>
CPU.AC(I.Acd) := CPU.AC(I.Acs) and 16#0000_ffff#;
if Test_DW_Bit (CPU.AC(I.Acd), 16) then
CPU.AC(I.Acd) := CPU.AC(I.Acd) or 16#ffff_0000#;
end if;
when I_SPSR =>
CPU.PSR := Lower_Word (CPU.AC(0));
when I_SSPT => -- NO-OP - see p.8-5 of MV/10000 Sys Func Chars
Loggers.Debug_Print(Debug_Log, "INFO: SSPT is a No-Op on this VM, continuing...");
when I_WADC =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Acd));
Acs_S32 := Dword_To_Integer_32(not CPU.AC(I.Acs));
S64 := Integer_64(Acd_S32) + Integer_64(Acs_S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR (CPU.Carry);
S64 := Integer_64(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
CPU.AC(I.Acd) := Dword_T(S64);
when I_WADD =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Acd));
Acs_S32 := Dword_To_Integer_32(CPU.AC(I.Acs));
S64 := Integer_64(Acd_S32) + Integer_64(Acs_S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR (CPU.Carry);
S64 := Integer_64(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
CPU.AC(I.Acd) := Dword_T(S64);
when I_WADDI =>
S32 := Dword_To_Integer_32(I.Imm_DW);
S64 := Integer_64(Dword_To_Integer_32(CPU.AC(I.Ac))) + Integer_64(S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR(CPU.Carry);
S64 := Integer_64(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
CPU.AC(I.Ac) := Dword_T(S64);
when I_WADI =>
S32 := Integer_32(Integer_16(I.Imm_U16));
S64 := Integer_64(Dword_To_Integer_32(CPU.AC(I.Ac))) + Integer_64(S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR(CPU.Carry);
S64 := Integer_64(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
CPU.AC(I.Ac) := Dword_T(S64);
when I_WANC => -- fnarr, fnarr
CPU.AC(I.Acd) := CPU.AC(I.Acd) and (not CPU.AC(I.Acs));
when I_WAND =>
CPU.AC(I.Acd) := CPU.AC(I.Acd) and CPU.AC(I.Acs);
when I_WANDI =>
CPU.AC(I.Ac) := CPU.AC(I.Ac) and I.Imm_DW;
when I_WASHI => -- "EAGLE"!
Shift := Integer(Integer_32(Word_To_Integer_16(I.Word_2)));
if (Shift /= 0) and (CPU.AC(I.Ac) /= 0) then
S32 := Dword_To_Integer_32(CPU.AC(I.Ac));
if Shift < 0 then
Shift := Shift * (-1);
S32 := S32 / (2 ** Shift);
else
S32 := S32 * (2 ** Shift);
end if;
CPU.AC(I.Ac) := Integer_32_To_Dword(S32);
end if;
when I_WCOM =>
CPU.AC(I.Acd) := not CPU.AC(I.Acs);
when I_WDIV =>
if CPU.AC(I.Acs) /= 0 then
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Acd));
Acs_S32 := Dword_To_Integer_32(CPU.AC(I.Acs));
S64 := Integer_64(Acd_S32) / Integer_64(Acs_S32);
if (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32) then
Set_OVR(true);
else
CPU.AC(I.Acd) := Dword_T(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
Set_OVR(false);
end if;
else
Set_OVR (true);
end if;
when I_WDIVS =>
declare
Divd : Integer_64;
begin
if CPU.AC(2) = 0 then
Set_OVR (true);
else
S64 := Integer_64(Qword_From_Two_Dwords(CPU.AC(0), CPU.AC(1)));
S32 := Dword_To_Integer_32(CPU.AC(2));
Divd := S64 / Integer_64(S32);
if (Divd < -2147483648) or (Divd > 2147483647) then
Set_OVR (true);
else
CPU.AC(0) := Dword_T(S64 mod Integer_64(S32));
CPU.AC(1) := Dword_T(Divd);
Set_OVR(false);
end if;
end if;
end;
when I_WHLV =>
S32 := Dword_To_Integer_32(CPU.AC(I.Ac)) / 2;
CPU.AC(I.Ac) := Integer_32_To_Dword(S32);
when I_WINC =>
CPU.Carry := CPU.AC(I.Acs) = 16#ffff_ffff#; -- TODO handle overflow flag
CPU.AC(I.Acd) := CPU.AC(I.Acs) + 1;
when I_WIOR =>
CPU.AC(I.Acd) := CPU.AC(I.Acd) or CPU.AC(I.Acs);
when I_WIORI =>
CPU.AC(I.Ac) := CPU.AC(I.Ac) or I.Imm_DW;
when I_WLDAI =>
CPU.AC(I.Ac) := I.Imm_DW;
when I_WLSH =>
Shift := Integer(Byte_To_Integer_8(Byte_T(CPU.AC(I.Acs) and 16#00ff#)));
if Shift < 0 then -- shift right
CPU.AC(I.Acd) := Shift_Right (CPU.AC(I.Acd), -Shift);
elsif Shift > 0 then -- shift left
CPU.AC(I.Acd) := Shift_Left (CPU.AC(I.Acd), Shift);
end if;
when I_WLSHI =>
Shift := Integer(Byte_To_Integer_8(Byte_T(I.Word_2 and 16#00ff#)));
if Shift < 0 then -- shift right
CPU.AC(I.Ac) := Shift_Right (CPU.AC(I.Ac), -Shift);
elsif Shift > 0 then -- shift left
CPU.AC(I.Ac) := Shift_Left (CPU.AC(I.Ac), Shift);
end if;
when I_WLSI =>
CPU.AC(I.Ac) := Shift_Left (CPU.AC(I.Ac), Integer(I.Imm_U16));
when I_WMOV =>
CPU.AC(I.Acd) := CPU.AC(I.Acs);
when I_WMOVR =>
CPU.AC(I.Ac) := Shift_Right(CPU.AC(I.Ac), 1);
when I_WMUL =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Acd));
Acs_S32 := Dword_To_Integer_32(CPU.AC(I.Acs));
S64 := Integer_64(Acd_S32) * Integer_64(Acs_S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Dword_T(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
when I_WMULS =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(1));
Acs_S32 := Dword_To_Integer_32(CPU.AC(2));
S64 := Integer_64(Acd_S32) * Integer_64(Acs_S32) + Integer_64(Dword_To_Integer_32(CPU.AC(0)));
CPU.AC(0) := Upper_Dword(Qword_T(Integer_64_To_Unsigned_64(S64)));
CPU.AC(1) := Lower_Dword(Qword_T(Integer_64_To_Unsigned_64(S64)));
when I_WNADI =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Ac));
S64 := Integer_64(Acd_S32) + Integer_64(Word_To_Integer_16(I.Word_2));
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR (CPU.Carry);
CPU.AC(I.Ac) := Dword_T(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
when I_WNEG =>
CPU.Carry := CPU.AC(I.Acs) = 16#8000_0000#; -- TODO Error in PoP?
Set_OVR(CPU.Carry);
S32 := (- Dword_To_Integer_32(CPU.AC(I.Acs)));
CPU.AC(I.Acd) := Integer_32_To_Dword(S32);
when I_WSBI =>
S32 := Integer_32(Integer_16(I.Imm_U16));
S64 := Integer_64(Dword_To_Integer_32(CPU.AC(I.Ac))) - Integer_64(S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR(CPU.Carry);
CPU.AC(I.Ac) := Dword_T(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
when I_WSUB =>
Acd_S32 := Dword_To_Integer_32(CPU.AC(I.Acd));
Acs_S32 := Dword_To_Integer_32(CPU.AC(I.Acs));
S64 := Integer_64(Acd_S32) - Integer_64(Acs_S32);
CPU.Carry := (S64 > Max_Pos_S32) or (S64 < Min_Neg_S32);
Set_OVR (CPU.Carry);
CPU.AC(I.Acd) := Dword_T(Integer_64_To_Unsigned_64(S64) and 16#0000_0000_ffff_ffff#);
when I_WXCH =>
declare
DW : Dword_T;
begin
DW := CPU.AC(I.Acs);
CPU.AC(I.Acs) := CPU.AC(I.Acd);
CPU.AC(I.Acd) := DW;
end;
when I_WXOR =>
CPU.AC(I.Acd) := CPU.AC(I.Acd) xor CPU.AC(I.Acs);
when I_WXORI =>
CPU.AC(I.Ac) := CPU.AC(I.Ac) xor I.Imm_DW;
when I_ZEX =>
CPU.AC(I.Acd) := 0 or Dword_T(DG_Types.Lower_Word(CPU.AC(I.Acs)));
when others =>
Put_Line ("ERROR: EAGLE_Op instruction " & To_String(I.Mnemonic) &
" not yet implemented");
raise Execution_Failure with "ERROR: EAGLE_Op instruction " & To_String(I.Mnemonic) &
" not yet implemented";
end case;
CPU.PC := CPU.PC + Phys_Addr_T(I.Instr_Len);
end Do_Eagle_Op;
end Processor.Eagle_Op_P;
|
with Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants;
package body kv.avm.Instructions is
----------------------------------------------------------------------------
function Encode_Operation(Op : Operation_Type) return String is
begin
case Op is
when Add => return "+";
when Sub => return "-";
when Mul => return "*";
when Div => return "/";
when Modulo => return "mod";
when Exp => return "^";
when Negate => return "not";
when Eq => return "=";
when Neq => return "/=";
when L_t => return "<";
when Lte => return "<=";
when G_t => return ">";
when Gte => return ">=";
when Shift_Right => return ">>";
when Shift_Left => return "<<";
when B_And => return "and";
when B_Or => return "or";
when B_Xor => return "xor";
when Op_Pos => return "+";
when Op_Neg => return "-";
end case;
end Encode_Operation;
----------------------------------------------------------------------------
function Decode_Operation(Op_Img : String) return Operation_Type is
Adjusted : constant String := Ada.Strings.Fixed.Translate(Op_Img, Ada.Strings.Maps.Constants.Lower_Case_Map);
begin
if Op_Img = "+" then return ADD;
elsif Op_Img = "-" then return SUB;
elsif Op_Img = "*" then return MUL;
elsif Op_Img = "/" then return DIV;
elsif (Op_Img = "%") or (Adjusted = "mod") then return Modulo;
elsif Op_Img = "^" then return Exp;
elsif (Op_Img = "~") or (Adjusted = "not") then return Negate;
elsif Op_Img = "=" then return Eq;
elsif (Op_Img = "/=") or (Op_Img = "!=") then return Neq;
elsif Op_Img = "<" then return L_t;
elsif Op_Img = "<=" then return Lte;
elsif Op_Img = ">" then return G_t;
elsif Op_Img = ">=" then return Gte;
elsif Op_Img = "<<" then return Shift_Left;
elsif Op_Img = ">>" then return Shift_Right;
elsif (Op_Img = "&") or (Adjusted = "and") then return B_And;
elsif (Op_Img = "|") or (Adjusted = "or") then return B_Or;
elsif Adjusted = "xor" then return B_Xor;
end if;
raise Invalid_Compute_Operation;
end Decode_Operation;
end kv.avm.Instructions;
|
pragma Ada_2012;
with GStreamer.Rtsp.Tests;
with GStreamer.Rtsp.url.Tests;
with GStreamer.Rtsp.Transport.Tests;
package body GStreamer.tests.Rtsp_Suit is
----------
-- Suit --
----------
Rtsp_Test : aliased GStreamer.Rtsp.Tests.Test_Case;
url_Test : aliased GStreamer.Rtsp.url.Tests.Test_Case;
Transport_Test : aliased GStreamer.Rtsp.Transport.Tests.Test_Case;
S : aliased AUnit.Test_Suites.Test_Suite;
function Suit return AUnit.Test_Suites.Access_Test_Suite is
begin
S.Add_Test (Rtsp_Test'Access);
S.Add_Test (url_Test'Access);
S.Add_Test (Transport_Test'Access);
return S'Unchecked_Access;
end Suit;
end GStreamer.tests.Rtsp_Suit;
|
with Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with GL.Types;
with Maths;
with Blade;
with Blade_Types;
with GA_Maths;
with GA_Utilities;
with Multivectors; use Multivectors;
with Multivector_Type;
with Multivector_Utilities;
procedure Test_MV_Factor is
use GL.Types;
use Blade;
-- use Blade.Names_Package;
no_bv : Multivector := Basis_Vector (Blade_Types.C3_no);
e1_bv : Multivector := Basis_Vector (Blade_Types.C3_e1);
e2_bv : Multivector := Basis_Vector (Blade_Types.C3_e2);
e3_bv : Multivector := Basis_Vector (Blade_Types.C3_e3);
ni_bv : Multivector := Basis_Vector (Blade_Types.C3_ni);
BV_Names : Blade.Basis_Vector_Names;
Dim : constant Integer := 8;
Scale : Float;
BL : Blade.Blade_List;
B_MV : Multivector;
R_MV : Multivector;
NP : Normalized_Point :=
New_Normalized_Point (-0.391495, -0.430912, 0.218277);
Factors : Multivector_List;
begin
Set_Geometry (C3_Geometry);
BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("no"));
BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e1"));
BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e2"));
BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("e3"));
BV_Names.Append (Ada.Strings.Unbounded.To_Unbounded_String ("ni"));
B_MV := Get_Random_Blade
(Dim, Integer (Maths.Random_Float * (Single (Dim) + 0.49)), 1.0);
BL.Add_Blade (New_Basis_Blade (30, -0.662244));
BL.Add_Blade (New_Basis_Blade (29, -0.391495));
BL.Add_Blade (New_Basis_Blade (27, -0.430912));
BL.Add_Blade (New_Basis_Blade (23, 0.218277));
BL.Add_Blade (New_Basis_Blade (15, -0.213881));
B_MV := New_Multivector (BL);
GA_Utilities.Print_Multivector ("B_MV", B_MV);
Factors := Multivector_Utilities.Factorize_Blades (B_MV, Scale);
GA_Utilities.Print_Multivector_List("Factors", Factors);
-- Reconstruct original
R_MV := New_Multivector (Scale);
for index in 1 .. List_Length (Factors) loop
R_MV := Outer_Product (R_MV, MV_Item (Factors, index));
end loop;
GA_Utilities.Print_Multivector ("R_MV", R_MV);
GA_Utilities.Print_Multivector ("NP", NP);
Factors := Multivector_Utilities.Factorize_Blades (NP, Scale);
GA_Utilities.Print_Multivector_List("Factors", Factors);
exception
when anError : others =>
Put_Line ("An exception occurred in Test_MV_Factor.");
raise;
end Test_MV_Factor;
|
-- Copyright 2016-2021 Bartek thindil Jasicki
--
-- This file is part of Steam Sky.
--
-- Steam Sky is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Steam Sky is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with Steam Sky. If not, see <http://www.gnu.org/licenses/>.
with Ada.Characters.Handling; use Ada.Characters.Handling;
with DOM.Core; use DOM.Core;
with DOM.Core.Documents;
with DOM.Core.Nodes; use DOM.Core.Nodes;
with DOM.Core.Elements; use DOM.Core.Elements;
with Log; use Log;
with Ships; use Ships;
with Ships.Cargo; use Ships.Cargo;
with Utils; use Utils;
with Crew; use Crew;
with Crew.Inventory; use Crew.Inventory;
with Crafts; use Crafts;
with Config; use Config;
package body Items is
procedure LoadItems(Reader: Tree_Reader) is
TempRecord: Object_Data;
NodesList, ChildNodes: Node_List;
ItemsData: Document;
TempValue: Integer_Container.Vector;
ItemNode, ChildNode: Node;
ItemIndex: Unbounded_String;
Action: Data_Action;
begin
ItemsData := Get_Tree(Reader);
NodesList :=
DOM.Core.Documents.Get_Elements_By_Tag_Name(ItemsData, "item");
Load_Items_Loop :
for I in 0 .. Length(NodesList) - 1 loop
TempRecord :=
(Name => Null_Unbounded_String, Weight => 1,
IType => Null_Unbounded_String, Price => 0, Value => TempValue,
ShowType => Null_Unbounded_String,
Description => Null_Unbounded_String, Reputation => -100);
ItemNode := Item(NodesList, I);
ItemIndex := To_Unbounded_String(Get_Attribute(ItemNode, "index"));
Action :=
(if Get_Attribute(ItemNode, "action")'Length > 0 then
Data_Action'Value(Get_Attribute(ItemNode, "action"))
else ADD);
if Action in UPDATE | REMOVE then
if not Objects_Container.Contains(Items_List, ItemIndex) then
raise Data_Loading_Error
with "Can't " & To_Lower(Data_Action'Image(Action)) &
" item '" & To_String(ItemIndex) &
"', there is no item with that index.";
end if;
elsif Objects_Container.Contains(Items_List, ItemIndex) then
raise Data_Loading_Error
with "Can't add item '" & To_String(ItemIndex) &
"', there is an item with that index.";
end if;
if Action /= REMOVE then
if Action = UPDATE then
TempRecord := Items_List(ItemIndex);
end if;
if Get_Attribute(ItemNode, "name")'Length > 0 then
TempRecord.Name :=
To_Unbounded_String(Get_Attribute(ItemNode, "name"));
end if;
if Get_Attribute(ItemNode, "weight")'Length > 0 then
TempRecord.Weight :=
Natural'Value(Get_Attribute(ItemNode, "weight"));
end if;
if Get_Attribute(ItemNode, "type")'Length > 0 then
TempRecord.IType :=
To_Unbounded_String(Get_Attribute(ItemNode, "type"));
end if;
if Get_Attribute(ItemNode, "showtype") /= "" then
TempRecord.ShowType :=
To_Unbounded_String(Get_Attribute(ItemNode, "showtype"));
end if;
if Get_Attribute(ItemNode, "reputation")'Length > 0 then
TempRecord.Reputation :=
Integer'Value(Get_Attribute(ItemNode, "reputation"));
end if;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(ItemNode, "trade");
Set_Buyable_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
ChildNode := Item(ChildNodes, J);
if Get_Attribute(ChildNode, "buyable") = "N" then
TempRecord.Price :=
Natural'Value(Get_Attribute(ChildNode, "price"));
exit Set_Buyable_Loop;
end if;
end loop Set_Buyable_Loop;
if Get_Attribute(ItemNode, "price")'Length > 0 then
TempRecord.Price :=
Natural'Value(Get_Attribute(ItemNode, "price"));
end if;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name(ItemNode, "data");
if Length(ChildNodes) > 0 then
TempRecord.Value.Clear;
end if;
Set_Value_Loop :
for J in 0 .. Length(ChildNodes) - 1 loop
TempRecord.Value.Append
(New_Item =>
Integer'Value
(Get_Attribute(Item(ChildNodes, J), "value")));
end loop Set_Value_Loop;
ChildNodes :=
DOM.Core.Elements.Get_Elements_By_Tag_Name
(ItemNode, "description");
if Length(ChildNodes) > 0 then
TempRecord.Description :=
To_Unbounded_String
(Node_Value(First_Child(Item(ChildNodes, 0))));
end if;
if ItemIndex = Money_Index then
Money_Name := TempRecord.Name;
end if;
-- Backward compatibility, all ammunitions are normal by default
if Length(TempRecord.IType) > 4
and then Slice(TempRecord.IType, 1, 4) = "Ammo"
and then TempRecord.Value.Length = 1 then
TempRecord.Value.Append(New_Item => 1);
end if;
if Action /= UPDATE then
Objects_Container.Include(Items_List, ItemIndex, TempRecord);
Log_Message
("Item added: " & To_String(TempRecord.Name), EVERYTHING);
else
Items_List(ItemIndex) := TempRecord;
Log_Message
("Item updated: " & To_String(TempRecord.Name), EVERYTHING);
end if;
else
Objects_Container.Exclude(Items_List, ItemIndex);
Log_Message("Item removed: " & To_String(ItemIndex), EVERYTHING);
end if;
end loop Load_Items_Loop;
Set_Items_Lists_Loop :
for I in Items_List.Iterate loop
if Items_List(I).IType = Weapon_Type then
Weapons_List.Append(New_Item => Objects_Container.Key(I));
elsif Items_List(I).IType = Shield_Type then
Shields_List.Append(New_Item => Objects_Container.Key(I));
elsif Items_List(I).IType = Head_Armor then
HeadArmors_List.Append(New_Item => Objects_Container.Key(I));
elsif Items_List(I).IType = Chest_Armor then
ChestArmors_List.Append(New_Item => Objects_Container.Key(I));
elsif Items_List(I).IType = Arms_Armor then
ArmsArmors_List.Append(New_Item => Objects_Container.Key(I));
elsif Items_List(I).IType = Legs_Armor then
LegsArmors_List.Append(New_Item => Objects_Container.Key(I));
end if;
end loop Set_Items_Lists_Loop;
end LoadItems;
function FindProtoItem
(ItemType: Unbounded_String) return Unbounded_String is
begin
Find_Proto_Loop :
for I in Items_List.Iterate loop
if Items_List(I).IType = ItemType then
return Objects_Container.Key(I);
end if;
end loop Find_Proto_Loop;
return Null_Unbounded_String;
end FindProtoItem;
function GetItemDamage
(ItemDurability: Items_Durability; ToLower: Boolean := False)
return String is
DamagePercent: Float range 0.0 .. 1.0;
DamageText: Unbounded_String;
begin
DamagePercent := 1.0 - (Float(ItemDurability) / 100.0);
DamageText :=
(if DamagePercent < 0.2 then To_Unbounded_String("Slightly used")
elsif DamagePercent < 0.5 then To_Unbounded_String("Damaged")
elsif DamagePercent < 0.8 then To_Unbounded_String("Heavily damaged")
else To_Unbounded_String("Almost destroyed"));
if ToLower then
DamageText := To_Unbounded_String(To_Lower(To_String(DamageText)));
end if;
return To_String(DamageText);
end GetItemDamage;
function GetItemName
(Item: InventoryData; DamageInfo, ToLower: Boolean := True)
return String is
ItemName: Unbounded_String;
begin
ItemName :=
(if Item.Name /= Null_Unbounded_String then Item.Name
else Items_List(Item.ProtoIndex).Name);
if DamageInfo and then Item.Durability < 100 then
Append
(ItemName, " (" & GetItemDamage(Item.Durability, ToLower) & ")");
end if;
return To_String(ItemName);
end GetItemName;
procedure DamageItem
(Inventory: in out Inventory_Container.Vector; ItemIndex: Positive;
SkillLevel, MemberIndex: Natural := 0) is
DamageChance: Integer :=
Items_List(Inventory(ItemIndex).ProtoIndex).Value(1);
I: Inventory_Container.Extended_Index := Inventory.First_Index;
begin
if SkillLevel > 0 then
DamageChance := DamageChance - (SkillLevel / 5);
if DamageChance < 1 then
DamageChance := 1;
end if;
end if;
if Get_Random(1, 100) > DamageChance then -- Item not damaged
return;
end if;
if Inventory(ItemIndex).Amount > 1 then
declare
Item: constant InventoryData := Inventory(ItemIndex);
begin
Inventory.Append
(New_Item =>
(ProtoIndex => Item.ProtoIndex, Amount => (Item.Amount - 1),
Name => Item.Name, Durability => Item.Durability,
Price => Item.Price));
end;
Inventory(ItemIndex).Amount := 1;
end if;
Inventory(ItemIndex).Durability := Inventory(ItemIndex).Durability - 1;
if Inventory(ItemIndex).Durability = 0 then -- Item destroyed
if MemberIndex = 0 then
UpdateCargo
(Ship => Player_Ship, CargoIndex => ItemIndex, Amount => -1);
else
UpdateInventory
(MemberIndex => MemberIndex, Amount => -1,
InventoryIndex => ItemIndex);
end if;
return;
end if;
Update_Inventory_Loop :
while I <= Inventory.Last_Index loop
Find_Item_Loop :
for J in Inventory.First_Index .. Inventory.Last_Index loop
if Inventory(I).ProtoIndex = Inventory(J).ProtoIndex and
Inventory(I).Durability = Inventory(J).Durability and I /= J then
if MemberIndex = 0 then
UpdateCargo
(Ship => Player_Ship, CargoIndex => J,
Amount => (0 - Inventory.Element(J).Amount));
UpdateCargo
(Ship => Player_Ship, CargoIndex => I,
Amount => Inventory.Element(J).Amount);
else
UpdateInventory
(MemberIndex => MemberIndex,
Amount => (0 - Inventory.Element(J).Amount),
InventoryIndex => J);
UpdateInventory
(MemberIndex => MemberIndex,
Amount => Inventory.Element(J).Amount,
InventoryIndex => I);
end if;
I := I - 1;
exit Find_Item_Loop;
end if;
end loop Find_Item_Loop;
I := I + 1;
end loop Update_Inventory_Loop;
end DamageItem;
function FindItem
(Inventory: Inventory_Container.Vector;
ProtoIndex, ItemType: Unbounded_String := Null_Unbounded_String;
Durability: Items_Durability := Items_Durability'Last;
Quality: Positive := 100) return Natural is
begin
if ProtoIndex /= Null_Unbounded_String then
Find_Item_With_Proto_Loop :
for I in Inventory.Iterate loop
if Inventory(I).ProtoIndex = ProtoIndex
and then
((Items_List(Inventory(I).ProtoIndex).Value.Length > 0
and then Items_List(Inventory(I).ProtoIndex).Value(1) <=
Quality) or
Items_List(Inventory(I).ProtoIndex).Value.Length = 0) then
if Durability < Items_Durability'Last
and then Inventory(I).Durability = Durability then
return Inventory_Container.To_Index(I);
else
return Inventory_Container.To_Index(I);
end if;
end if;
end loop Find_Item_With_Proto_Loop;
elsif ItemType /= Null_Unbounded_String then
Find_Item_Loop :
for I in Inventory.Iterate loop
if Items_List(Inventory(I).ProtoIndex).IType = ItemType
and then
((Items_List(Inventory(I).ProtoIndex).Value.Length > 0
and then Items_List(Inventory(I).ProtoIndex).Value(1) <=
Quality) or
Items_List(Inventory(I).ProtoIndex).Value.Length = 0) then
if Durability < Items_Durability'Last
and then Inventory(I).Durability = Durability then
return Inventory_Container.To_Index(I);
else
return Inventory_Container.To_Index(I);
end if;
end if;
end loop Find_Item_Loop;
end if;
return 0;
end FindItem;
procedure SetToolsList is
use Tiny_String;
begin
if Tools_List.Length > 0 then
return;
end if;
Tools_List.Append(New_Item => Repair_Tools);
Tools_List.Append(New_Item => Cleaning_Tools);
Tools_List.Append(New_Item => Alchemy_Tools);
Recipes_Loop :
for Recipe of Recipes_List loop
if Tools_List.Find_Index(Item => Recipe.Tool) =
UnboundedString_Container.No_Index then
Tools_List.Append(New_Item => Recipe.Tool);
end if;
end loop Recipes_Loop;
Skills_Loop :
for I in 1 .. Skills_Amount loop
if Tools_List.Find_Index
(Item =>
To_Unbounded_String
(To_String
(SkillsData_Container.Element(Skills_List, I).Tool))) =
UnboundedString_Container.No_Index then
Tools_List.Append
(New_Item =>
To_Unbounded_String
(To_String
(SkillsData_Container.Element(Skills_List, I).Tool)));
end if;
end loop Skills_Loop;
end SetToolsList;
function GetItemChanceToDamage(ItemData: Natural) return String is
begin
if Game_Settings.Show_Numbers then
return Natural'Image(ItemData) & "%";
end if;
case ItemData is
when 1 =>
return "Almost never";
when 2 =>
return "Very small";
when 3 =>
return "Small";
when 4 .. 9 =>
return "Below average";
when 10 .. 14 =>
return "Average";
when 15 .. 19 =>
return "High";
when others =>
return "Very high";
end case;
end GetItemChanceToDamage;
end Items;
|
with Ada.Characters;
with Ada.Characters.Handling;
package body Project_Processor.Projects.Identifiers is
-------------------------
-- Is_Valid_Identifier --
-------------------------
function Is_Valid_Identifier (X : String) return Boolean is
use Ada.Characters.Handling;
begin
if X'Length = 0 then
return False;
end if;
if not Is_Letter (X (X'First)) then
return False;
end if;
return (for all I in X'Range =>
(Is_Letter (X(I))
or Is_Decimal_Digit (X (I))
or X (I) = '_'
or X (I) = '-'));
end Is_Valid_Identifier;
-----------
-- To_ID --
-----------
function To_ID (X : String) return Identifier is
begin
if not Is_Valid_Identifier (X) then
raise Constraint_Error;
end if;
return Identifier (ID_Names.To_Bounded_String (X));
end To_ID;
---------------
-- To_String --
---------------
function To_String (X : Identifier) return String is
begin
return ID_Names.To_String (ID_Names.Bounded_String (X));
end To_String;
end Project_Processor.Projects.Identifiers;
|
with Test_Solution; use Test_Solution;
with Ada.Text_IO; use Ada.Text_IO;
package problem_16 is
function Solution_1(I : Integer) return Integer;
procedure Test_Solution_1;
function Get_Solutions return Solution_Case;
end problem_16;
|
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr>
-- MIT license. Please refer to the LICENSE file.
with Apsepp_Demo_OSASI_Instance_Controllers;
use Apsepp_Demo_OSASI_Instance_Controllers;
-- See comments in package bodies Apsepp_Demo_OSASI_Instance_Controllers and
-- Apsepp_Demo_OSASI_Instance_Client.
procedure Apsepp_Demo_Output_Sink_As_Shared_Instance is
begin
Show_Output_Sink_Instance_State; -- Output line A1.
Output_Sink_Instance_Controller;
Show_Output_Sink_Instance_State; -- Output line A4.
Deeper_Output_Sink_Instance_Controller;
Show_Output_Sink_Instance_State; -- Output line A6.
Deeper_Output_Sink_Instance_Controller (J_P => True);
Show_Output_Sink_Instance_State; -- Output line A8.
end Apsepp_Demo_Output_Sink_As_Shared_Instance;
|
with E2GA;
package body Mouse_Manager is
-- mouse position on last call to MouseButton() / MouseMotion()
Prev_Mouse_Pos : E2GA.Vector;
-- when true, MouseMotion() will rotate the model
Rotate_Model : Boolean := False;
Rotate_Model_Out_OfPPlane : Boolean := False;
-- rotation of the model
M_Model_Rotor : E2GA.Rotor;
-- -------------------------------------------------------------------------
procedure Mouse_Button (Button : Integer; State : Integer; X, Y : Integer) is
begin
null;
end Mouse_Button;
-- -------------------------------------------------------------------------
end Mouse_Manager;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L A Y O U T --
-- --
-- S p e c --
-- --
-- Copyright (C) 2000-2004 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package does front-end layout of types and objects. The result is
-- to annotate the tree with information on size and alignment of types
-- and objects. How much layout is performed depends on the setting of the
-- target dependent parameter Backend_Layout.
with Types; use Types;
package Layout is
-- The following procedures are called from Freeze, so all entities
-- for types and objects that get frozen (which should be all such
-- entities which are seen by the back end) will get layed out by one
-- of these two procedures.
procedure Layout_Type (E : Entity_Id);
-- This procedure may set or adjust the fields Esize, RM_Size and
-- Alignment in the non-generic type or subtype entity E. If the
-- Backend_Layout switch is False, then it is guaranteed that all
-- three fields will be properly set on return. Regardless of the
-- Backend_Layout value, it is guaranteed that all discrete types
-- will have both Esize and RM_Size fields set on return (since
-- these are static values). Note that Layout_Type is not called
-- for generic types, since these play no part in code generation,
-- and hence representation aspects are irrelevant.
procedure Layout_Object (E : Entity_Id);
-- E is either a variable (E_Variable), a constant (E_Constant),
-- a loop parameter (E_Loop_Parameter), or a formal parameter of
-- a non-generic subprogram (E_In_Parameter, E_In_Out_Parameter,
-- or E_Out_Parameter). This procedure may set or adjust the
-- Esize and Alignment fields of E. If Backend_Layout is False,
-- then it is guaranteed that both fields will be properly set
-- on return. If the Esize is still unknown in the latter case,
-- it means that the object must be allocated dynamically, since
-- its length is not known at compile time.
procedure Set_Discrete_RM_Size (Def_Id : Entity_Id);
-- Set proper RM_Size for discrete size, this is normally the minimum
-- number of bits to accommodate the range given, except in the case
-- where the subtype statically matches the first subtype, in which
-- case the size must be copied from the first subtype. For generic
-- types, the RM_Size is simply set to zero. This routine also sets
-- the Is_Constrained flag in Def_Id.
procedure Set_Elem_Alignment (E : Entity_Id);
-- The front end always sets alignments for elementary types by calling
-- this procedure. Note that we have to do this for discrete types (since
-- the Alignment attribute is static), so we might as well do it for all
-- elementary types, since the processing is the same.
end Layout;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . S T R E A M _ A T T R I B U T E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1996-2016, Free Software Foundation, Inc. --
-- --
-- GARLIC 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 file is an alternate version of s-stratt.adb based on the XDR
-- standard. It is especially useful for exchanging streams between two
-- different systems with different basic type representations and endianness.
pragma Warnings (Off, "*not allowed in compiler unit");
-- This body is used only when rebuilding the runtime library, not when
-- building the compiler, so it's OK to depend on features that would
-- otherwise break bootstrap (e.g. IF-expressions).
with Ada.IO_Exceptions;
with Ada.Streams; use Ada.Streams;
with Ada.Unchecked_Conversion;
package body System.Stream_Attributes is
pragma Suppress (Range_Check);
pragma Suppress (Overflow_Check);
use UST;
Data_Error : exception renames Ada.IO_Exceptions.End_Error;
-- Exception raised if insufficient data read (End_Error is mandated by
-- AI95-00132).
SU : constant := System.Storage_Unit;
-- The code in this body assumes that SU = 8
BB : constant := 2 ** SU; -- Byte base
BL : constant := 2 ** SU - 1; -- Byte last
BS : constant := 2 ** (SU - 1); -- Byte sign
US : constant := Unsigned'Size; -- Unsigned size
UB : constant := (US - 1) / SU + 1; -- Unsigned byte
UL : constant := 2 ** US - 1; -- Unsigned last
subtype SE is Ada.Streams.Stream_Element;
subtype SEA is Ada.Streams.Stream_Element_Array;
subtype SEO is Ada.Streams.Stream_Element_Offset;
generic function UC renames Ada.Unchecked_Conversion;
type Field_Type is
record
E_Size : Integer; -- Exponent bit size
E_Bias : Integer; -- Exponent bias
F_Size : Integer; -- Fraction bit size
E_Last : Integer; -- Max exponent value
F_Mask : SE; -- Mask to apply on first fraction byte
E_Bytes : SEO; -- N. of exponent bytes completely used
F_Bytes : SEO; -- N. of fraction bytes completely used
F_Bits : Integer; -- N. of bits used on first fraction word
end record;
type Precision is (Single, Double, Quadruple);
Fields : constant array (Precision) of Field_Type := (
-- Single precision
(E_Size => 8,
E_Bias => 127,
F_Size => 23,
E_Last => 2 ** 8 - 1,
F_Mask => 16#7F#, -- 2 ** 7 - 1,
E_Bytes => 2,
F_Bytes => 3,
F_Bits => 23 mod US),
-- Double precision
(E_Size => 11,
E_Bias => 1023,
F_Size => 52,
E_Last => 2 ** 11 - 1,
F_Mask => 16#0F#, -- 2 ** 4 - 1,
E_Bytes => 2,
F_Bytes => 7,
F_Bits => 52 mod US),
-- Quadruple precision
(E_Size => 15,
E_Bias => 16383,
F_Size => 112,
E_Last => 2 ** 8 - 1,
F_Mask => 16#FF#, -- 2 ** 8 - 1,
E_Bytes => 2,
F_Bytes => 14,
F_Bits => 112 mod US));
-- The representation of all items requires a multiple of four bytes
-- (or 32 bits) of data. The bytes are numbered 0 through n-1. The bytes
-- are read or written to some byte stream such that byte m always
-- precedes byte m+1. If the n bytes needed to contain the data are not
-- a multiple of four, then the n bytes are followed by enough (0 to 3)
-- residual zero bytes, r, to make the total byte count a multiple of 4.
-- An XDR signed integer is a 32-bit datum that encodes an integer
-- in the range [-2147483648,2147483647]. The integer is represented
-- in two's complement notation. The most and least significant bytes
-- are 0 and 3, respectively. Integers are declared as follows:
-- (MSB) (LSB)
-- +-------+-------+-------+-------+
-- |byte 0 |byte 1 |byte 2 |byte 3 |
-- +-------+-------+-------+-------+
-- <------------32 bits------------>
SSI_L : constant := 1;
SI_L : constant := 2;
I_L : constant := 4;
LI_L : constant := 8;
LLI_L : constant := 8;
subtype XDR_S_SSI is SEA (1 .. SSI_L);
subtype XDR_S_SI is SEA (1 .. SI_L);
subtype XDR_S_I is SEA (1 .. I_L);
subtype XDR_S_LI is SEA (1 .. LI_L);
subtype XDR_S_LLI is SEA (1 .. LLI_L);
function Short_Short_Integer_To_XDR_S_SSI is
new Ada.Unchecked_Conversion (Short_Short_Integer, XDR_S_SSI);
function XDR_S_SSI_To_Short_Short_Integer is
new Ada.Unchecked_Conversion (XDR_S_SSI, Short_Short_Integer);
function Short_Integer_To_XDR_S_SI is
new Ada.Unchecked_Conversion (Short_Integer, XDR_S_SI);
function XDR_S_SI_To_Short_Integer is
new Ada.Unchecked_Conversion (XDR_S_SI, Short_Integer);
function Integer_To_XDR_S_I is
new Ada.Unchecked_Conversion (Integer, XDR_S_I);
function XDR_S_I_To_Integer is
new Ada.Unchecked_Conversion (XDR_S_I, Integer);
function Long_Long_Integer_To_XDR_S_LI is
new Ada.Unchecked_Conversion (Long_Long_Integer, XDR_S_LI);
function XDR_S_LI_To_Long_Long_Integer is
new Ada.Unchecked_Conversion (XDR_S_LI, Long_Long_Integer);
function Long_Long_Integer_To_XDR_S_LLI is
new Ada.Unchecked_Conversion (Long_Long_Integer, XDR_S_LLI);
function XDR_S_LLI_To_Long_Long_Integer is
new Ada.Unchecked_Conversion (XDR_S_LLI, Long_Long_Integer);
-- An XDR unsigned integer is a 32-bit datum that encodes a nonnegative
-- integer in the range [0,4294967295]. It is represented by an unsigned
-- binary number whose most and least significant bytes are 0 and 3,
-- respectively. An unsigned integer is declared as follows:
-- (MSB) (LSB)
-- +-------+-------+-------+-------+
-- |byte 0 |byte 1 |byte 2 |byte 3 |
-- +-------+-------+-------+-------+
-- <------------32 bits------------>
SSU_L : constant := 1;
SU_L : constant := 2;
U_L : constant := 4;
LU_L : constant := 8;
LLU_L : constant := 8;
subtype XDR_S_SSU is SEA (1 .. SSU_L);
subtype XDR_S_SU is SEA (1 .. SU_L);
subtype XDR_S_U is SEA (1 .. U_L);
subtype XDR_S_LU is SEA (1 .. LU_L);
subtype XDR_S_LLU is SEA (1 .. LLU_L);
type XDR_SSU is mod BB ** SSU_L;
type XDR_SU is mod BB ** SU_L;
type XDR_U is mod BB ** U_L;
function Short_Unsigned_To_XDR_S_SU is
new Ada.Unchecked_Conversion (Short_Unsigned, XDR_S_SU);
function XDR_S_SU_To_Short_Unsigned is
new Ada.Unchecked_Conversion (XDR_S_SU, Short_Unsigned);
function Unsigned_To_XDR_S_U is
new Ada.Unchecked_Conversion (Unsigned, XDR_S_U);
function XDR_S_U_To_Unsigned is
new Ada.Unchecked_Conversion (XDR_S_U, Unsigned);
function Long_Long_Unsigned_To_XDR_S_LU is
new Ada.Unchecked_Conversion (Long_Long_Unsigned, XDR_S_LU);
function XDR_S_LU_To_Long_Long_Unsigned is
new Ada.Unchecked_Conversion (XDR_S_LU, Long_Long_Unsigned);
function Long_Long_Unsigned_To_XDR_S_LLU is
new Ada.Unchecked_Conversion (Long_Long_Unsigned, XDR_S_LLU);
function XDR_S_LLU_To_Long_Long_Unsigned is
new Ada.Unchecked_Conversion (XDR_S_LLU, Long_Long_Unsigned);
-- The standard defines the floating-point data type "float" (32 bits
-- or 4 bytes). The encoding used is the IEEE standard for normalized
-- single-precision floating-point numbers.
-- The standard defines the encoding used for the double-precision
-- floating-point data type "double" (64 bits or 8 bytes). The encoding
-- used is the IEEE standard for normalized double-precision floating-point
-- numbers.
SF_L : constant := 4; -- Single precision
F_L : constant := 4; -- Single precision
LF_L : constant := 8; -- Double precision
LLF_L : constant := 16; -- Quadruple precision
TM_L : constant := 8;
subtype XDR_S_TM is SEA (1 .. TM_L);
type XDR_TM is mod BB ** TM_L;
type XDR_SA is mod 2 ** Standard'Address_Size;
function To_XDR_SA is new UC (System.Address, XDR_SA);
function To_XDR_SA is new UC (XDR_SA, System.Address);
-- Enumerations have the same representation as signed integers.
-- Enumerations are handy for describing subsets of the integers.
-- Booleans are important enough and occur frequently enough to warrant
-- their own explicit type in the standard. Booleans are declared as
-- an enumeration, with FALSE = 0 and TRUE = 1.
-- The standard defines a string of n (numbered 0 through n-1) ASCII
-- bytes to be the number n encoded as an unsigned integer (as described
-- above), and followed by the n bytes of the string. Byte m of the string
-- always precedes byte m+1 of the string, and byte 0 of the string always
-- follows the string's length. If n is not a multiple of four, then the
-- n bytes are followed by enough (0 to 3) residual zero bytes, r, to make
-- the total byte count a multiple of four.
-- To fit with XDR string, do not consider character as an enumeration
-- type.
C_L : constant := 1;
subtype XDR_S_C is SEA (1 .. C_L);
-- Consider Wide_Character as an enumeration type
WC_L : constant := 4;
subtype XDR_S_WC is SEA (1 .. WC_L);
type XDR_WC is mod BB ** WC_L;
-- Consider Wide_Wide_Character as an enumeration type
WWC_L : constant := 8;
subtype XDR_S_WWC is SEA (1 .. WWC_L);
type XDR_WWC is mod BB ** WWC_L;
-- Optimization: if we already have the correct Bit_Order, then some
-- computations can be avoided since the source and the target will be
-- identical anyway. They will be replaced by direct unchecked
-- conversions.
Optimize_Integers : constant Boolean :=
Default_Bit_Order = High_Order_First;
-----------------
-- Block_IO_OK --
-----------------
-- We must inhibit Block_IO, because in XDR mode, each element is output
-- according to XDR requirements, which is not at all the same as writing
-- the whole array in one block.
function Block_IO_OK return Boolean is
begin
return False;
end Block_IO_OK;
----------
-- I_AD --
----------
function I_AD (Stream : not null access RST) return Fat_Pointer is
FP : Fat_Pointer;
begin
FP.P1 := I_AS (Stream).P1;
FP.P2 := I_AS (Stream).P1;
return FP;
end I_AD;
----------
-- I_AS --
----------
function I_AS (Stream : not null access RST) return Thin_Pointer is
S : XDR_S_TM;
L : SEO;
U : XDR_TM := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
else
for N in S'Range loop
U := U * BB + XDR_TM (S (N));
end loop;
return (P1 => To_XDR_SA (XDR_SA (U)));
end if;
end I_AS;
---------
-- I_B --
---------
function I_B (Stream : not null access RST) return Boolean is
begin
case I_SSU (Stream) is
when 0 => return False;
when 1 => return True;
when others => raise Data_Error;
end case;
end I_B;
---------
-- I_C --
---------
function I_C (Stream : not null access RST) return Character is
S : XDR_S_C;
L : SEO;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
else
-- Use Ada requirements on Character representation clause
return Character'Val (S (1));
end if;
end I_C;
---------
-- I_F --
---------
function I_F (Stream : not null access RST) return Float is
I : constant Precision := Single;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Last : Integer renames Fields (I).E_Last;
F_Mask : SE renames Fields (I).F_Mask;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
Is_Positive : Boolean;
Exponent : Long_Unsigned;
Fraction : Long_Unsigned;
Result : Float;
S : SEA (1 .. F_L);
L : SEO;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
end if;
-- Extract Fraction, Sign and Exponent
Fraction := Long_Unsigned (S (F_L + 1 - F_Bytes) and F_Mask);
for N in F_L + 2 - F_Bytes .. F_L loop
Fraction := Fraction * BB + Long_Unsigned (S (N));
end loop;
Result := Float'Scaling (Float (Fraction), -F_Size);
if BS <= S (1) then
Is_Positive := False;
Exponent := Long_Unsigned (S (1) - BS);
else
Is_Positive := True;
Exponent := Long_Unsigned (S (1));
end if;
for N in 2 .. E_Bytes loop
Exponent := Exponent * BB + Long_Unsigned (S (N));
end loop;
Exponent := Shift_Right (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
-- NaN or Infinities
if Integer (Exponent) = E_Last then
raise Constraint_Error;
elsif Exponent = 0 then
-- Signed zeros
if Fraction = 0 then
null;
-- Denormalized float
else
Result := Float'Scaling (Result, 1 - E_Bias);
end if;
-- Normalized float
else
Result := Float'Scaling
(1.0 + Result, Integer (Exponent) - E_Bias);
end if;
if not Is_Positive then
Result := -Result;
end if;
return Result;
end I_F;
---------
-- I_I --
---------
function I_I (Stream : not null access RST) return Integer is
S : XDR_S_I;
L : SEO;
U : XDR_U := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_I_To_Integer (S);
else
for N in S'Range loop
U := U * BB + XDR_U (S (N));
end loop;
-- Test sign and apply two complement notation
if S (1) < BL then
return Integer (U);
else
return Integer (-((XDR_U'Last xor U) + 1));
end if;
end if;
end I_I;
----------
-- I_LF --
----------
function I_LF (Stream : not null access RST) return Long_Float is
I : constant Precision := Double;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Last : Integer renames Fields (I).E_Last;
F_Mask : SE renames Fields (I).F_Mask;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
Is_Positive : Boolean;
Exponent : Long_Unsigned;
Fraction : Long_Long_Unsigned;
Result : Long_Float;
S : SEA (1 .. LF_L);
L : SEO;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
end if;
-- Extract Fraction, Sign and Exponent
Fraction := Long_Long_Unsigned (S (LF_L + 1 - F_Bytes) and F_Mask);
for N in LF_L + 2 - F_Bytes .. LF_L loop
Fraction := Fraction * BB + Long_Long_Unsigned (S (N));
end loop;
Result := Long_Float'Scaling (Long_Float (Fraction), -F_Size);
if BS <= S (1) then
Is_Positive := False;
Exponent := Long_Unsigned (S (1) - BS);
else
Is_Positive := True;
Exponent := Long_Unsigned (S (1));
end if;
for N in 2 .. E_Bytes loop
Exponent := Exponent * BB + Long_Unsigned (S (N));
end loop;
Exponent := Shift_Right (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
-- NaN or Infinities
if Integer (Exponent) = E_Last then
raise Constraint_Error;
elsif Exponent = 0 then
-- Signed zeros
if Fraction = 0 then
null;
-- Denormalized float
else
Result := Long_Float'Scaling (Result, 1 - E_Bias);
end if;
-- Normalized float
else
Result := Long_Float'Scaling
(1.0 + Result, Integer (Exponent) - E_Bias);
end if;
if not Is_Positive then
Result := -Result;
end if;
return Result;
end I_LF;
----------
-- I_LI --
----------
function I_LI (Stream : not null access RST) return Long_Integer is
S : XDR_S_LI;
L : SEO;
U : Unsigned := 0;
X : Long_Unsigned := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return Long_Integer (XDR_S_LI_To_Long_Long_Integer (S));
else
-- Compute using machine unsigned
-- rather than long_long_unsigned
for N in S'Range loop
U := U * BB + Unsigned (S (N));
-- We have filled an unsigned
if N mod UB = 0 then
X := Shift_Left (X, US) + Long_Unsigned (U);
U := 0;
end if;
end loop;
-- Test sign and apply two complement notation
if S (1) < BL then
return Long_Integer (X);
else
return Long_Integer (-((Long_Unsigned'Last xor X) + 1));
end if;
end if;
end I_LI;
-----------
-- I_LLF --
-----------
function I_LLF (Stream : not null access RST) return Long_Long_Float is
I : constant Precision := Quadruple;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Last : Integer renames Fields (I).E_Last;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
Is_Positive : Boolean;
Exponent : Long_Unsigned;
Fraction_1 : Long_Long_Unsigned := 0;
Fraction_2 : Long_Long_Unsigned := 0;
Result : Long_Long_Float;
HF : constant Natural := F_Size / 2;
S : SEA (1 .. LLF_L);
L : SEO;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
end if;
-- Extract Fraction, Sign and Exponent
for I in LLF_L - F_Bytes + 1 .. LLF_L - 7 loop
Fraction_1 := Fraction_1 * BB + Long_Long_Unsigned (S (I));
end loop;
for I in SEO (LLF_L - 6) .. SEO (LLF_L) loop
Fraction_2 := Fraction_2 * BB + Long_Long_Unsigned (S (I));
end loop;
Result := Long_Long_Float'Scaling (Long_Long_Float (Fraction_2), -HF);
Result := Long_Long_Float (Fraction_1) + Result;
Result := Long_Long_Float'Scaling (Result, HF - F_Size);
if BS <= S (1) then
Is_Positive := False;
Exponent := Long_Unsigned (S (1) - BS);
else
Is_Positive := True;
Exponent := Long_Unsigned (S (1));
end if;
for N in 2 .. E_Bytes loop
Exponent := Exponent * BB + Long_Unsigned (S (N));
end loop;
Exponent := Shift_Right (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
-- NaN or Infinities
if Integer (Exponent) = E_Last then
raise Constraint_Error;
elsif Exponent = 0 then
-- Signed zeros
if Fraction_1 = 0 and then Fraction_2 = 0 then
null;
-- Denormalized float
else
Result := Long_Long_Float'Scaling (Result, 1 - E_Bias);
end if;
-- Normalized float
else
Result := Long_Long_Float'Scaling
(1.0 + Result, Integer (Exponent) - E_Bias);
end if;
if not Is_Positive then
Result := -Result;
end if;
return Result;
end I_LLF;
-----------
-- I_LLI --
-----------
function I_LLI (Stream : not null access RST) return Long_Long_Integer is
S : XDR_S_LLI;
L : SEO;
U : Unsigned := 0;
X : Long_Long_Unsigned := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_LLI_To_Long_Long_Integer (S);
else
-- Compute using machine unsigned for computing
-- rather than long_long_unsigned.
for N in S'Range loop
U := U * BB + Unsigned (S (N));
-- We have filled an unsigned
if N mod UB = 0 then
X := Shift_Left (X, US) + Long_Long_Unsigned (U);
U := 0;
end if;
end loop;
-- Test sign and apply two complement notation
if S (1) < BL then
return Long_Long_Integer (X);
else
return Long_Long_Integer (-((Long_Long_Unsigned'Last xor X) + 1));
end if;
end if;
end I_LLI;
-----------
-- I_LLU --
-----------
function I_LLU (Stream : not null access RST) return Long_Long_Unsigned is
S : XDR_S_LLU;
L : SEO;
U : Unsigned := 0;
X : Long_Long_Unsigned := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_LLU_To_Long_Long_Unsigned (S);
else
-- Compute using machine unsigned
-- rather than long_long_unsigned.
for N in S'Range loop
U := U * BB + Unsigned (S (N));
-- We have filled an unsigned
if N mod UB = 0 then
X := Shift_Left (X, US) + Long_Long_Unsigned (U);
U := 0;
end if;
end loop;
return X;
end if;
end I_LLU;
----------
-- I_LU --
----------
function I_LU (Stream : not null access RST) return Long_Unsigned is
S : XDR_S_LU;
L : SEO;
U : Unsigned := 0;
X : Long_Unsigned := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return Long_Unsigned (XDR_S_LU_To_Long_Long_Unsigned (S));
else
-- Compute using machine unsigned
-- rather than long_unsigned.
for N in S'Range loop
U := U * BB + Unsigned (S (N));
-- We have filled an unsigned
if N mod UB = 0 then
X := Shift_Left (X, US) + Long_Unsigned (U);
U := 0;
end if;
end loop;
return X;
end if;
end I_LU;
----------
-- I_SF --
----------
function I_SF (Stream : not null access RST) return Short_Float is
I : constant Precision := Single;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Last : Integer renames Fields (I).E_Last;
F_Mask : SE renames Fields (I).F_Mask;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
Exponent : Long_Unsigned;
Fraction : Long_Unsigned;
Is_Positive : Boolean;
Result : Short_Float;
S : SEA (1 .. SF_L);
L : SEO;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
end if;
-- Extract Fraction, Sign and Exponent
Fraction := Long_Unsigned (S (SF_L + 1 - F_Bytes) and F_Mask);
for N in SF_L + 2 - F_Bytes .. SF_L loop
Fraction := Fraction * BB + Long_Unsigned (S (N));
end loop;
Result := Short_Float'Scaling (Short_Float (Fraction), -F_Size);
if BS <= S (1) then
Is_Positive := False;
Exponent := Long_Unsigned (S (1) - BS);
else
Is_Positive := True;
Exponent := Long_Unsigned (S (1));
end if;
for N in 2 .. E_Bytes loop
Exponent := Exponent * BB + Long_Unsigned (S (N));
end loop;
Exponent := Shift_Right (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
-- NaN or Infinities
if Integer (Exponent) = E_Last then
raise Constraint_Error;
elsif Exponent = 0 then
-- Signed zeros
if Fraction = 0 then
null;
-- Denormalized float
else
Result := Short_Float'Scaling (Result, 1 - E_Bias);
end if;
-- Normalized float
else
Result := Short_Float'Scaling
(1.0 + Result, Integer (Exponent) - E_Bias);
end if;
if not Is_Positive then
Result := -Result;
end if;
return Result;
end I_SF;
----------
-- I_SI --
----------
function I_SI (Stream : not null access RST) return Short_Integer is
S : XDR_S_SI;
L : SEO;
U : XDR_SU := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_SI_To_Short_Integer (S);
else
for N in S'Range loop
U := U * BB + XDR_SU (S (N));
end loop;
-- Test sign and apply two complement notation
if S (1) < BL then
return Short_Integer (U);
else
return Short_Integer (-((XDR_SU'Last xor U) + 1));
end if;
end if;
end I_SI;
-----------
-- I_SSI --
-----------
function I_SSI (Stream : not null access RST) return Short_Short_Integer is
S : XDR_S_SSI;
L : SEO;
U : XDR_SSU;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_SSI_To_Short_Short_Integer (S);
else
U := XDR_SSU (S (1));
-- Test sign and apply two complement notation
if S (1) < BL then
return Short_Short_Integer (U);
else
return Short_Short_Integer (-((XDR_SSU'Last xor U) + 1));
end if;
end if;
end I_SSI;
-----------
-- I_SSU --
-----------
function I_SSU (Stream : not null access RST) return Short_Short_Unsigned is
S : XDR_S_SSU;
L : SEO;
U : XDR_SSU := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
else
U := XDR_SSU (S (1));
return Short_Short_Unsigned (U);
end if;
end I_SSU;
----------
-- I_SU --
----------
function I_SU (Stream : not null access RST) return Short_Unsigned is
S : XDR_S_SU;
L : SEO;
U : XDR_SU := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_SU_To_Short_Unsigned (S);
else
for N in S'Range loop
U := U * BB + XDR_SU (S (N));
end loop;
return Short_Unsigned (U);
end if;
end I_SU;
---------
-- I_U --
---------
function I_U (Stream : not null access RST) return Unsigned is
S : XDR_S_U;
L : SEO;
U : XDR_U := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
elsif Optimize_Integers then
return XDR_S_U_To_Unsigned (S);
else
for N in S'Range loop
U := U * BB + XDR_U (S (N));
end loop;
return Unsigned (U);
end if;
end I_U;
----------
-- I_WC --
----------
function I_WC (Stream : not null access RST) return Wide_Character is
S : XDR_S_WC;
L : SEO;
U : XDR_WC := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
else
for N in S'Range loop
U := U * BB + XDR_WC (S (N));
end loop;
-- Use Ada requirements on Wide_Character representation clause
return Wide_Character'Val (U);
end if;
end I_WC;
-----------
-- I_WWC --
-----------
function I_WWC (Stream : not null access RST) return Wide_Wide_Character is
S : XDR_S_WWC;
L : SEO;
U : XDR_WWC := 0;
begin
Ada.Streams.Read (Stream.all, S, L);
if L /= S'Last then
raise Data_Error;
else
for N in S'Range loop
U := U * BB + XDR_WWC (S (N));
end loop;
-- Use Ada requirements on Wide_Wide_Character representation clause
return Wide_Wide_Character'Val (U);
end if;
end I_WWC;
----------
-- W_AD --
----------
procedure W_AD (Stream : not null access RST; Item : Fat_Pointer) is
S : XDR_S_TM;
U : XDR_TM;
begin
U := XDR_TM (To_XDR_SA (Item.P1));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
Ada.Streams.Write (Stream.all, S);
U := XDR_TM (To_XDR_SA (Item.P2));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
Ada.Streams.Write (Stream.all, S);
if U /= 0 then
raise Data_Error;
end if;
end W_AD;
----------
-- W_AS --
----------
procedure W_AS (Stream : not null access RST; Item : Thin_Pointer) is
S : XDR_S_TM;
U : XDR_TM := XDR_TM (To_XDR_SA (Item.P1));
begin
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
Ada.Streams.Write (Stream.all, S);
if U /= 0 then
raise Data_Error;
end if;
end W_AS;
---------
-- W_B --
---------
procedure W_B (Stream : not null access RST; Item : Boolean) is
begin
if Item then
W_SSU (Stream, 1);
else
W_SSU (Stream, 0);
end if;
end W_B;
---------
-- W_C --
---------
procedure W_C (Stream : not null access RST; Item : Character) is
S : XDR_S_C;
pragma Assert (C_L = 1);
begin
-- Use Ada requirements on Character representation clause
S (1) := SE (Character'Pos (Item));
Ada.Streams.Write (Stream.all, S);
end W_C;
---------
-- W_F --
---------
procedure W_F (Stream : not null access RST; Item : Float) is
I : constant Precision := Single;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
F_Mask : SE renames Fields (I).F_Mask;
Exponent : Long_Unsigned;
Fraction : Long_Unsigned;
Is_Positive : Boolean;
E : Integer;
F : Float;
S : SEA (1 .. F_L) := (others => 0);
begin
if not Item'Valid then
raise Constraint_Error;
end if;
-- Compute Sign
Is_Positive := (0.0 <= Item);
F := abs (Item);
-- Signed zero
if F = 0.0 then
Exponent := 0;
Fraction := 0;
else
E := Float'Exponent (F) - 1;
-- Denormalized float
if E <= -E_Bias then
F := Float'Scaling (F, F_Size + E_Bias - 1);
E := -E_Bias;
else
F := Float'Scaling (Float'Fraction (F), F_Size + 1);
end if;
-- Compute Exponent and Fraction
Exponent := Long_Unsigned (E + E_Bias);
Fraction := Long_Unsigned (F * 2.0) / 2;
end if;
-- Store Fraction
for I in reverse F_L - F_Bytes + 1 .. F_L loop
S (I) := SE (Fraction mod BB);
Fraction := Fraction / BB;
end loop;
-- Remove implicit bit
S (F_L - F_Bytes + 1) := S (F_L - F_Bytes + 1) and F_Mask;
-- Store Exponent (not always at the beginning of a byte)
Exponent := Shift_Left (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
for N in reverse 1 .. E_Bytes loop
S (N) := SE (Exponent mod BB) + S (N);
Exponent := Exponent / BB;
end loop;
-- Store Sign
if not Is_Positive then
S (1) := S (1) + BS;
end if;
Ada.Streams.Write (Stream.all, S);
end W_F;
---------
-- W_I --
---------
procedure W_I (Stream : not null access RST; Item : Integer) is
S : XDR_S_I;
U : XDR_U;
begin
if Optimize_Integers then
S := Integer_To_XDR_S_I (Item);
else
-- Test sign and apply two complement notation
U := (if Item < 0
then XDR_U'Last xor XDR_U (-(Item + 1))
else XDR_U (Item));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_I;
----------
-- W_LF --
----------
procedure W_LF (Stream : not null access RST; Item : Long_Float) is
I : constant Precision := Double;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
F_Mask : SE renames Fields (I).F_Mask;
Exponent : Long_Unsigned;
Fraction : Long_Long_Unsigned;
Is_Positive : Boolean;
E : Integer;
F : Long_Float;
S : SEA (1 .. LF_L) := (others => 0);
begin
if not Item'Valid then
raise Constraint_Error;
end if;
-- Compute Sign
Is_Positive := (0.0 <= Item);
F := abs (Item);
-- Signed zero
if F = 0.0 then
Exponent := 0;
Fraction := 0;
else
E := Long_Float'Exponent (F) - 1;
-- Denormalized float
if E <= -E_Bias then
E := -E_Bias;
F := Long_Float'Scaling (F, F_Size + E_Bias - 1);
else
F := Long_Float'Scaling (F, F_Size - E);
end if;
-- Compute Exponent and Fraction
Exponent := Long_Unsigned (E + E_Bias);
Fraction := Long_Long_Unsigned (F * 2.0) / 2;
end if;
-- Store Fraction
for I in reverse LF_L - F_Bytes + 1 .. LF_L loop
S (I) := SE (Fraction mod BB);
Fraction := Fraction / BB;
end loop;
-- Remove implicit bit
S (LF_L - F_Bytes + 1) := S (LF_L - F_Bytes + 1) and F_Mask;
-- Store Exponent (not always at the beginning of a byte)
Exponent := Shift_Left (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
for N in reverse 1 .. E_Bytes loop
S (N) := SE (Exponent mod BB) + S (N);
Exponent := Exponent / BB;
end loop;
-- Store Sign
if not Is_Positive then
S (1) := S (1) + BS;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LF;
----------
-- W_LI --
----------
procedure W_LI (Stream : not null access RST; Item : Long_Integer) is
S : XDR_S_LI;
U : Unsigned;
X : Long_Unsigned;
begin
if Optimize_Integers then
S := Long_Long_Integer_To_XDR_S_LI (Long_Long_Integer (Item));
else
-- Test sign and apply two complement notation
if Item < 0 then
X := Long_Unsigned'Last xor Long_Unsigned (-(Item + 1));
else
X := Long_Unsigned (Item);
end if;
-- Compute using machine unsigned rather than long_unsigned
for N in reverse S'Range loop
-- We have filled an unsigned
if (LU_L - N) mod UB = 0 then
U := Unsigned (X and UL);
X := Shift_Right (X, US);
end if;
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LI;
-----------
-- W_LLF --
-----------
procedure W_LLF (Stream : not null access RST; Item : Long_Long_Float) is
I : constant Precision := Quadruple;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
HFS : constant Integer := F_Size / 2;
Exponent : Long_Unsigned;
Fraction_1 : Long_Long_Unsigned;
Fraction_2 : Long_Long_Unsigned;
Is_Positive : Boolean;
E : Integer;
F : Long_Long_Float := Item;
S : SEA (1 .. LLF_L) := (others => 0);
begin
if not Item'Valid then
raise Constraint_Error;
end if;
-- Compute Sign
Is_Positive := (0.0 <= Item);
if F < 0.0 then
F := -Item;
end if;
-- Signed zero
if F = 0.0 then
Exponent := 0;
Fraction_1 := 0;
Fraction_2 := 0;
else
E := Long_Long_Float'Exponent (F) - 1;
-- Denormalized float
if E <= -E_Bias then
F := Long_Long_Float'Scaling (F, E_Bias - 1);
E := -E_Bias;
else
F := Long_Long_Float'Scaling
(Long_Long_Float'Fraction (F), 1);
end if;
-- Compute Exponent and Fraction
Exponent := Long_Unsigned (E + E_Bias);
F := Long_Long_Float'Scaling (F, F_Size - HFS);
Fraction_1 := Long_Long_Unsigned (Long_Long_Float'Floor (F));
F := F - Long_Long_Float (Fraction_1);
F := Long_Long_Float'Scaling (F, HFS);
Fraction_2 := Long_Long_Unsigned (Long_Long_Float'Floor (F));
end if;
-- Store Fraction_1
for I in reverse LLF_L - F_Bytes + 1 .. LLF_L - 7 loop
S (I) := SE (Fraction_1 mod BB);
Fraction_1 := Fraction_1 / BB;
end loop;
-- Store Fraction_2
for I in reverse LLF_L - 6 .. LLF_L loop
S (SEO (I)) := SE (Fraction_2 mod BB);
Fraction_2 := Fraction_2 / BB;
end loop;
-- Store Exponent (not always at the beginning of a byte)
Exponent := Shift_Left (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
for N in reverse 1 .. E_Bytes loop
S (N) := SE (Exponent mod BB) + S (N);
Exponent := Exponent / BB;
end loop;
-- Store Sign
if not Is_Positive then
S (1) := S (1) + BS;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LLF;
-----------
-- W_LLI --
-----------
procedure W_LLI
(Stream : not null access RST;
Item : Long_Long_Integer)
is
S : XDR_S_LLI;
U : Unsigned;
X : Long_Long_Unsigned;
begin
if Optimize_Integers then
S := Long_Long_Integer_To_XDR_S_LLI (Item);
else
-- Test sign and apply two complement notation
if Item < 0 then
X := Long_Long_Unsigned'Last xor Long_Long_Unsigned (-(Item + 1));
else
X := Long_Long_Unsigned (Item);
end if;
-- Compute using machine unsigned rather than long_long_unsigned
for N in reverse S'Range loop
-- We have filled an unsigned
if (LLU_L - N) mod UB = 0 then
U := Unsigned (X and UL);
X := Shift_Right (X, US);
end if;
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LLI;
-----------
-- W_LLU --
-----------
procedure W_LLU
(Stream : not null access RST;
Item : Long_Long_Unsigned)
is
S : XDR_S_LLU;
U : Unsigned;
X : Long_Long_Unsigned := Item;
begin
if Optimize_Integers then
S := Long_Long_Unsigned_To_XDR_S_LLU (Item);
else
-- Compute using machine unsigned rather than long_long_unsigned
for N in reverse S'Range loop
-- We have filled an unsigned
if (LLU_L - N) mod UB = 0 then
U := Unsigned (X and UL);
X := Shift_Right (X, US);
end if;
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LLU;
----------
-- W_LU --
----------
procedure W_LU (Stream : not null access RST; Item : Long_Unsigned) is
S : XDR_S_LU;
U : Unsigned;
X : Long_Unsigned := Item;
begin
if Optimize_Integers then
S := Long_Long_Unsigned_To_XDR_S_LU (Long_Long_Unsigned (Item));
else
-- Compute using machine unsigned rather than long_unsigned
for N in reverse S'Range loop
-- We have filled an unsigned
if (LU_L - N) mod UB = 0 then
U := Unsigned (X and UL);
X := Shift_Right (X, US);
end if;
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_LU;
----------
-- W_SF --
----------
procedure W_SF (Stream : not null access RST; Item : Short_Float) is
I : constant Precision := Single;
E_Size : Integer renames Fields (I).E_Size;
E_Bias : Integer renames Fields (I).E_Bias;
E_Bytes : SEO renames Fields (I).E_Bytes;
F_Bytes : SEO renames Fields (I).F_Bytes;
F_Size : Integer renames Fields (I).F_Size;
F_Mask : SE renames Fields (I).F_Mask;
Exponent : Long_Unsigned;
Fraction : Long_Unsigned;
Is_Positive : Boolean;
E : Integer;
F : Short_Float;
S : SEA (1 .. SF_L) := (others => 0);
begin
if not Item'Valid then
raise Constraint_Error;
end if;
-- Compute Sign
Is_Positive := (0.0 <= Item);
F := abs (Item);
-- Signed zero
if F = 0.0 then
Exponent := 0;
Fraction := 0;
else
E := Short_Float'Exponent (F) - 1;
-- Denormalized float
if E <= -E_Bias then
E := -E_Bias;
F := Short_Float'Scaling (F, F_Size + E_Bias - 1);
else
F := Short_Float'Scaling (F, F_Size - E);
end if;
-- Compute Exponent and Fraction
Exponent := Long_Unsigned (E + E_Bias);
Fraction := Long_Unsigned (F * 2.0) / 2;
end if;
-- Store Fraction
for I in reverse SF_L - F_Bytes + 1 .. SF_L loop
S (I) := SE (Fraction mod BB);
Fraction := Fraction / BB;
end loop;
-- Remove implicit bit
S (SF_L - F_Bytes + 1) := S (SF_L - F_Bytes + 1) and F_Mask;
-- Store Exponent (not always at the beginning of a byte)
Exponent := Shift_Left (Exponent, Integer (E_Bytes) * SU - E_Size - 1);
for N in reverse 1 .. E_Bytes loop
S (N) := SE (Exponent mod BB) + S (N);
Exponent := Exponent / BB;
end loop;
-- Store Sign
if not Is_Positive then
S (1) := S (1) + BS;
end if;
Ada.Streams.Write (Stream.all, S);
end W_SF;
----------
-- W_SI --
----------
procedure W_SI (Stream : not null access RST; Item : Short_Integer) is
S : XDR_S_SI;
U : XDR_SU;
begin
if Optimize_Integers then
S := Short_Integer_To_XDR_S_SI (Item);
else
-- Test sign and apply two complement's notation
U := (if Item < 0
then XDR_SU'Last xor XDR_SU (-(Item + 1))
else XDR_SU (Item));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_SI;
-----------
-- W_SSI --
-----------
procedure W_SSI
(Stream : not null access RST;
Item : Short_Short_Integer)
is
S : XDR_S_SSI;
U : XDR_SSU;
begin
if Optimize_Integers then
S := Short_Short_Integer_To_XDR_S_SSI (Item);
else
-- Test sign and apply two complement's notation
U := (if Item < 0
then XDR_SSU'Last xor XDR_SSU (-(Item + 1))
else XDR_SSU (Item));
S (1) := SE (U);
end if;
Ada.Streams.Write (Stream.all, S);
end W_SSI;
-----------
-- W_SSU --
-----------
procedure W_SSU
(Stream : not null access RST;
Item : Short_Short_Unsigned)
is
U : constant XDR_SSU := XDR_SSU (Item);
S : XDR_S_SSU;
begin
S (1) := SE (U);
Ada.Streams.Write (Stream.all, S);
end W_SSU;
----------
-- W_SU --
----------
procedure W_SU (Stream : not null access RST; Item : Short_Unsigned) is
S : XDR_S_SU;
U : XDR_SU := XDR_SU (Item);
begin
if Optimize_Integers then
S := Short_Unsigned_To_XDR_S_SU (Item);
else
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_SU;
---------
-- W_U --
---------
procedure W_U (Stream : not null access RST; Item : Unsigned) is
S : XDR_S_U;
U : XDR_U := XDR_U (Item);
begin
if Optimize_Integers then
S := Unsigned_To_XDR_S_U (Item);
else
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
if U /= 0 then
raise Data_Error;
end if;
end if;
Ada.Streams.Write (Stream.all, S);
end W_U;
----------
-- W_WC --
----------
procedure W_WC (Stream : not null access RST; Item : Wide_Character) is
S : XDR_S_WC;
U : XDR_WC;
begin
-- Use Ada requirements on Wide_Character representation clause
U := XDR_WC (Wide_Character'Pos (Item));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
Ada.Streams.Write (Stream.all, S);
if U /= 0 then
raise Data_Error;
end if;
end W_WC;
-----------
-- W_WWC --
-----------
procedure W_WWC
(Stream : not null access RST; Item : Wide_Wide_Character)
is
S : XDR_S_WWC;
U : XDR_WWC;
begin
-- Use Ada requirements on Wide_Wide_Character representation clause
U := XDR_WWC (Wide_Wide_Character'Pos (Item));
for N in reverse S'Range loop
S (N) := SE (U mod BB);
U := U / BB;
end loop;
Ada.Streams.Write (Stream.all, S);
if U /= 0 then
raise Data_Error;
end if;
end W_WWC;
end System.Stream_Attributes;
|
--
-- Copyright (C) 2021, AdaCore
--
pragma Style_Checks (Off);
-- This spec has been automatically generated from STM32H743x.svd
with System;
package Interfaces.STM32.SYSCFG is
pragma Preelaborate;
pragma No_Elaboration_Code_All;
---------------
-- Registers --
---------------
subtype PMCR_I2C1FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_I2C2FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_I2C3FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_I2C4FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_PB6FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_PB7FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_PB8FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_PB9FMP_Field is Interfaces.STM32.Bit;
subtype PMCR_BOOSTE_Field is Interfaces.STM32.Bit;
subtype PMCR_BOOSTVDDSEL_Field is Interfaces.STM32.Bit;
subtype PMCR_EPIS_Field is Interfaces.STM32.UInt3;
subtype PMCR_PA0SO_Field is Interfaces.STM32.Bit;
subtype PMCR_PA1SO_Field is Interfaces.STM32.Bit;
subtype PMCR_PC2SO_Field is Interfaces.STM32.Bit;
subtype PMCR_PC3SO_Field is Interfaces.STM32.Bit;
-- peripheral mode configuration register
type PMCR_Register is record
-- I2C1 Fm+
I2C1FMP : PMCR_I2C1FMP_Field := 16#0#;
-- I2C2 Fm+
I2C2FMP : PMCR_I2C2FMP_Field := 16#0#;
-- I2C3 Fm+
I2C3FMP : PMCR_I2C3FMP_Field := 16#0#;
-- I2C4 Fm+
I2C4FMP : PMCR_I2C4FMP_Field := 16#0#;
-- PB(6) Fm+
PB6FMP : PMCR_PB6FMP_Field := 16#0#;
-- PB(7) Fast Mode Plus
PB7FMP : PMCR_PB7FMP_Field := 16#0#;
-- PB(8) Fast Mode Plus
PB8FMP : PMCR_PB8FMP_Field := 16#0#;
-- PB(9) Fm+
PB9FMP : PMCR_PB9FMP_Field := 16#0#;
-- Booster Enable
BOOSTE : PMCR_BOOSTE_Field := 16#0#;
-- Analog switch supply voltage selection
BOOSTVDDSEL : PMCR_BOOSTVDDSEL_Field := 16#0#;
-- unspecified
Reserved_10_20 : Interfaces.STM32.UInt11 := 16#0#;
-- Ethernet PHY Interface Selection
EPIS : PMCR_EPIS_Field := 16#0#;
-- PA0 Switch Open
PA0SO : PMCR_PA0SO_Field := 16#0#;
-- PA1 Switch Open
PA1SO : PMCR_PA1SO_Field := 16#0#;
-- PC2 Switch Open
PC2SO : PMCR_PC2SO_Field := 16#0#;
-- PC3 Switch Open
PC3SO : PMCR_PC3SO_Field := 16#0#;
-- unspecified
Reserved_28_31 : Interfaces.STM32.UInt4 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PMCR_Register use record
I2C1FMP at 0 range 0 .. 0;
I2C2FMP at 0 range 1 .. 1;
I2C3FMP at 0 range 2 .. 2;
I2C4FMP at 0 range 3 .. 3;
PB6FMP at 0 range 4 .. 4;
PB7FMP at 0 range 5 .. 5;
PB8FMP at 0 range 6 .. 6;
PB9FMP at 0 range 7 .. 7;
BOOSTE at 0 range 8 .. 8;
BOOSTVDDSEL at 0 range 9 .. 9;
Reserved_10_20 at 0 range 10 .. 20;
EPIS at 0 range 21 .. 23;
PA0SO at 0 range 24 .. 24;
PA1SO at 0 range 25 .. 25;
PC2SO at 0 range 26 .. 26;
PC3SO at 0 range 27 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
-- EXTICR1_EXTI array element
subtype EXTICR1_EXTI_Element is Interfaces.STM32.UInt4;
-- EXTICR1_EXTI array
type EXTICR1_EXTI_Field_Array is array (0 .. 3) of EXTICR1_EXTI_Element
with Component_Size => 4, Size => 16;
-- Type definition for EXTICR1_EXTI
type EXTICR1_EXTI_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- EXTI as a value
Val : Interfaces.STM32.UInt16;
when True =>
-- EXTI as an array
Arr : EXTICR1_EXTI_Field_Array;
end case;
end record
with Unchecked_Union, Size => 16;
for EXTICR1_EXTI_Field use record
Val at 0 range 0 .. 15;
Arr at 0 range 0 .. 15;
end record;
-- external interrupt configuration register 1
type EXTICR1_Register is record
-- EXTI x configuration (x = 0 to 3)
EXTI : EXTICR1_EXTI_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_16_31 : Interfaces.STM32.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for EXTICR1_Register use record
EXTI at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- EXTICR2_EXTI array element
subtype EXTICR2_EXTI_Element is Interfaces.STM32.UInt4;
-- EXTICR2_EXTI array
type EXTICR2_EXTI_Field_Array is array (4 .. 7) of EXTICR2_EXTI_Element
with Component_Size => 4, Size => 16;
-- Type definition for EXTICR2_EXTI
type EXTICR2_EXTI_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- EXTI as a value
Val : Interfaces.STM32.UInt16;
when True =>
-- EXTI as an array
Arr : EXTICR2_EXTI_Field_Array;
end case;
end record
with Unchecked_Union, Size => 16;
for EXTICR2_EXTI_Field use record
Val at 0 range 0 .. 15;
Arr at 0 range 0 .. 15;
end record;
-- external interrupt configuration register 2
type EXTICR2_Register is record
-- EXTI x configuration (x = 4 to 7)
EXTI : EXTICR2_EXTI_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_16_31 : Interfaces.STM32.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for EXTICR2_Register use record
EXTI at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- EXTICR3_EXTI array element
subtype EXTICR3_EXTI_Element is Interfaces.STM32.UInt4;
-- EXTICR3_EXTI array
type EXTICR3_EXTI_Field_Array is array (8 .. 11) of EXTICR3_EXTI_Element
with Component_Size => 4, Size => 16;
-- Type definition for EXTICR3_EXTI
type EXTICR3_EXTI_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- EXTI as a value
Val : Interfaces.STM32.UInt16;
when True =>
-- EXTI as an array
Arr : EXTICR3_EXTI_Field_Array;
end case;
end record
with Unchecked_Union, Size => 16;
for EXTICR3_EXTI_Field use record
Val at 0 range 0 .. 15;
Arr at 0 range 0 .. 15;
end record;
-- external interrupt configuration register 3
type EXTICR3_Register is record
-- EXTI x configuration (x = 8 to 11)
EXTI : EXTICR3_EXTI_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_16_31 : Interfaces.STM32.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for EXTICR3_Register use record
EXTI at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- EXTICR4_EXTI array element
subtype EXTICR4_EXTI_Element is Interfaces.STM32.UInt4;
-- EXTICR4_EXTI array
type EXTICR4_EXTI_Field_Array is array (12 .. 15) of EXTICR4_EXTI_Element
with Component_Size => 4, Size => 16;
-- Type definition for EXTICR4_EXTI
type EXTICR4_EXTI_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- EXTI as a value
Val : Interfaces.STM32.UInt16;
when True =>
-- EXTI as an array
Arr : EXTICR4_EXTI_Field_Array;
end case;
end record
with Unchecked_Union, Size => 16;
for EXTICR4_EXTI_Field use record
Val at 0 range 0 .. 15;
Arr at 0 range 0 .. 15;
end record;
-- external interrupt configuration register 4
type EXTICR4_Register is record
-- EXTI x configuration (x = 12 to 15)
EXTI : EXTICR4_EXTI_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_16_31 : Interfaces.STM32.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for EXTICR4_Register use record
EXTI at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype CCCSR_EN_Field is Interfaces.STM32.Bit;
subtype CCCSR_CS_Field is Interfaces.STM32.Bit;
subtype CCCSR_READY_Field is Interfaces.STM32.Bit;
subtype CCCSR_HSLV_Field is Interfaces.STM32.Bit;
-- compensation cell control/status register
type CCCSR_Register is record
-- enable
EN : CCCSR_EN_Field := 16#0#;
-- Code selection
CS : CCCSR_CS_Field := 16#0#;
-- unspecified
Reserved_2_7 : Interfaces.STM32.UInt6 := 16#0#;
-- Compensation cell ready flag
READY : CCCSR_READY_Field := 16#0#;
-- unspecified
Reserved_9_15 : Interfaces.STM32.UInt7 := 16#0#;
-- High-speed at low-voltage
HSLV : CCCSR_HSLV_Field := 16#0#;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CCCSR_Register use record
EN at 0 range 0 .. 0;
CS at 0 range 1 .. 1;
Reserved_2_7 at 0 range 2 .. 7;
READY at 0 range 8 .. 8;
Reserved_9_15 at 0 range 9 .. 15;
HSLV at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype CCVR_NCV_Field is Interfaces.STM32.UInt4;
subtype CCVR_PCV_Field is Interfaces.STM32.UInt4;
-- SYSCFG compensation cell value register
type CCVR_Register is record
-- Read-only. NMOS compensation value
NCV : CCVR_NCV_Field;
-- Read-only. PMOS compensation value
PCV : CCVR_PCV_Field;
-- unspecified
Reserved_8_31 : Interfaces.STM32.UInt24;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CCVR_Register use record
NCV at 0 range 0 .. 3;
PCV at 0 range 4 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype CCCR_NCC_Field is Interfaces.STM32.UInt4;
subtype CCCR_PCC_Field is Interfaces.STM32.UInt4;
-- SYSCFG compensation cell code register
type CCCR_Register is record
-- NMOS compensation code
NCC : CCCR_NCC_Field := 16#0#;
-- PMOS compensation code
PCC : CCCR_PCC_Field := 16#0#;
-- unspecified
Reserved_8_31 : Interfaces.STM32.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CCCR_Register use record
NCC at 0 range 0 .. 3;
PCC at 0 range 4 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype PWRCR_ODEN_Field is Interfaces.STM32.Bit;
-- SYSCFG power control register
type PWRCR_Register is record
-- Overdrive enable
ODEN : PWRCR_ODEN_Field := 16#0#;
-- unspecified
Reserved_1_31 : Interfaces.STM32.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PWRCR_Register use record
ODEN at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
subtype PKGR_PKG_Field is Interfaces.STM32.UInt4;
-- SYSCFG package register
type PKGR_Register is record
-- Read-only. Package
PKG : PKGR_PKG_Field;
-- unspecified
Reserved_4_31 : Interfaces.STM32.UInt28;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PKGR_Register use record
PKG at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
subtype UR0_BKS_Field is Interfaces.STM32.Bit;
subtype UR0_RDP_Field is Interfaces.STM32.Byte;
-- SYSCFG user register 0
type UR0_Register is record
-- Read-only. Bank Swap
BKS : UR0_BKS_Field;
-- unspecified
Reserved_1_15 : Interfaces.STM32.UInt15;
-- Read-only. Readout protection
RDP : UR0_RDP_Field;
-- unspecified
Reserved_24_31 : Interfaces.STM32.Byte;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR0_Register use record
BKS at 0 range 0 .. 0;
Reserved_1_15 at 0 range 1 .. 15;
RDP at 0 range 16 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
subtype UR2_BORH_Field is Interfaces.STM32.UInt2;
subtype UR2_BOOT_ADD0_Field is Interfaces.STM32.UInt16;
-- SYSCFG user register 2
type UR2_Register is record
-- BOR_LVL Brownout Reset Threshold Level
BORH : UR2_BORH_Field := 16#0#;
-- unspecified
Reserved_2_15 : Interfaces.STM32.UInt14 := 16#0#;
-- Boot Address 0
BOOT_ADD0 : UR2_BOOT_ADD0_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR2_Register use record
BORH at 0 range 0 .. 1;
Reserved_2_15 at 0 range 2 .. 15;
BOOT_ADD0 at 0 range 16 .. 31;
end record;
subtype UR3_BOOT_ADD1_Field is Interfaces.STM32.UInt16;
-- SYSCFG user register 3
type UR3_Register is record
-- unspecified
Reserved_0_15 : Interfaces.STM32.UInt16 := 16#0#;
-- Boot Address 1
BOOT_ADD1 : UR3_BOOT_ADD1_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR3_Register use record
Reserved_0_15 at 0 range 0 .. 15;
BOOT_ADD1 at 0 range 16 .. 31;
end record;
subtype UR4_MEPAD_1_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 4
type UR4_Register is record
-- unspecified
Reserved_0_15 : Interfaces.STM32.UInt16;
-- Read-only. Mass Erase Protected Area Disabled for bank 1
MEPAD_1 : UR4_MEPAD_1_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR4_Register use record
Reserved_0_15 at 0 range 0 .. 15;
MEPAD_1 at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR5_MESAD_1_Field is Interfaces.STM32.Bit;
subtype UR5_WRPN_1_Field is Interfaces.STM32.Byte;
-- SYSCFG user register 5
type UR5_Register is record
-- Read-only. Mass erase secured area disabled for bank 1
MESAD_1 : UR5_MESAD_1_Field;
-- unspecified
Reserved_1_15 : Interfaces.STM32.UInt15;
-- Read-only. Write protection for flash bank 1
WRPN_1 : UR5_WRPN_1_Field;
-- unspecified
Reserved_24_31 : Interfaces.STM32.Byte;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR5_Register use record
MESAD_1 at 0 range 0 .. 0;
Reserved_1_15 at 0 range 1 .. 15;
WRPN_1 at 0 range 16 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
subtype UR6_PA_BEG_1_Field is Interfaces.STM32.UInt12;
subtype UR6_PA_END_1_Field is Interfaces.STM32.UInt12;
-- SYSCFG user register 6
type UR6_Register is record
-- Read-only. Protected area start address for bank 1
PA_BEG_1 : UR6_PA_BEG_1_Field;
-- unspecified
Reserved_12_15 : Interfaces.STM32.UInt4;
-- Read-only. Protected area end address for bank 1
PA_END_1 : UR6_PA_END_1_Field;
-- unspecified
Reserved_28_31 : Interfaces.STM32.UInt4;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR6_Register use record
PA_BEG_1 at 0 range 0 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
PA_END_1 at 0 range 16 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
subtype UR7_SA_BEG_1_Field is Interfaces.STM32.UInt12;
subtype UR7_SA_END_1_Field is Interfaces.STM32.UInt12;
-- SYSCFG user register 7
type UR7_Register is record
-- Read-only. Secured area start address for bank 1
SA_BEG_1 : UR7_SA_BEG_1_Field;
-- unspecified
Reserved_12_15 : Interfaces.STM32.UInt4;
-- Read-only. Secured area end address for bank 1
SA_END_1 : UR7_SA_END_1_Field;
-- unspecified
Reserved_28_31 : Interfaces.STM32.UInt4;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR7_Register use record
SA_BEG_1 at 0 range 0 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
SA_END_1 at 0 range 16 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
subtype UR8_MEPAD_2_Field is Interfaces.STM32.Bit;
subtype UR8_MESAD_2_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 8
type UR8_Register is record
-- Read-only. Mass erase protected area disabled for bank 2
MEPAD_2 : UR8_MEPAD_2_Field;
-- unspecified
Reserved_1_15 : Interfaces.STM32.UInt15;
-- Read-only. Mass erase secured area disabled for bank 2
MESAD_2 : UR8_MESAD_2_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR8_Register use record
MEPAD_2 at 0 range 0 .. 0;
Reserved_1_15 at 0 range 1 .. 15;
MESAD_2 at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR9_WRPN_2_Field is Interfaces.STM32.Byte;
subtype UR9_PA_BEG_2_Field is Interfaces.STM32.UInt12;
-- SYSCFG user register 9
type UR9_Register is record
-- Read-only. Write protection for flash bank 2
WRPN_2 : UR9_WRPN_2_Field;
-- unspecified
Reserved_8_15 : Interfaces.STM32.Byte;
-- Read-only. Protected area start address for bank 2
PA_BEG_2 : UR9_PA_BEG_2_Field;
-- unspecified
Reserved_28_31 : Interfaces.STM32.UInt4;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR9_Register use record
WRPN_2 at 0 range 0 .. 7;
Reserved_8_15 at 0 range 8 .. 15;
PA_BEG_2 at 0 range 16 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
subtype UR10_PA_END_2_Field is Interfaces.STM32.UInt12;
subtype UR10_SA_BEG_2_Field is Interfaces.STM32.UInt12;
-- SYSCFG user register 10
type UR10_Register is record
-- Read-only. Protected area end address for bank 2
PA_END_2 : UR10_PA_END_2_Field;
-- unspecified
Reserved_12_15 : Interfaces.STM32.UInt4;
-- Read-only. Secured area start address for bank 2
SA_BEG_2 : UR10_SA_BEG_2_Field;
-- unspecified
Reserved_28_31 : Interfaces.STM32.UInt4;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR10_Register use record
PA_END_2 at 0 range 0 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
SA_BEG_2 at 0 range 16 .. 27;
Reserved_28_31 at 0 range 28 .. 31;
end record;
subtype UR11_SA_END_2_Field is Interfaces.STM32.UInt12;
subtype UR11_IWDG1M_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 11
type UR11_Register is record
-- Read-only. Secured area end address for bank 2
SA_END_2 : UR11_SA_END_2_Field;
-- unspecified
Reserved_12_15 : Interfaces.STM32.UInt4;
-- Read-only. Independent Watchdog 1 mode
IWDG1M : UR11_IWDG1M_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR11_Register use record
SA_END_2 at 0 range 0 .. 11;
Reserved_12_15 at 0 range 12 .. 15;
IWDG1M at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR12_SECURE_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 12
type UR12_Register is record
-- unspecified
Reserved_0_15 : Interfaces.STM32.UInt16;
-- Read-only. Secure mode
SECURE : UR12_SECURE_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR12_Register use record
Reserved_0_15 at 0 range 0 .. 15;
SECURE at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR13_SDRS_Field is Interfaces.STM32.UInt2;
subtype UR13_D1SBRST_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 13
type UR13_Register is record
-- Read-only. Secured DTCM RAM Size
SDRS : UR13_SDRS_Field;
-- unspecified
Reserved_2_15 : Interfaces.STM32.UInt14;
-- Read-only. D1 Standby reset
D1SBRST : UR13_D1SBRST_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR13_Register use record
SDRS at 0 range 0 .. 1;
Reserved_2_15 at 0 range 2 .. 15;
D1SBRST at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR14_D1STPRST_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 14
type UR14_Register is record
-- D1 Stop Reset
D1STPRST : UR14_D1STPRST_Field := 16#0#;
-- unspecified
Reserved_1_31 : Interfaces.STM32.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR14_Register use record
D1STPRST at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
subtype UR15_FZIWDGSTB_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 15
type UR15_Register is record
-- unspecified
Reserved_0_15 : Interfaces.STM32.UInt16;
-- Read-only. Freeze independent watchdog in Standby mode
FZIWDGSTB : UR15_FZIWDGSTB_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR15_Register use record
Reserved_0_15 at 0 range 0 .. 15;
FZIWDGSTB at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR16_FZIWDGSTP_Field is Interfaces.STM32.Bit;
subtype UR16_PKP_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 16
type UR16_Register is record
-- Read-only. Freeze independent watchdog in Stop mode
FZIWDGSTP : UR16_FZIWDGSTP_Field;
-- unspecified
Reserved_1_15 : Interfaces.STM32.UInt15;
-- Read-only. Private key programmed
PKP : UR16_PKP_Field;
-- unspecified
Reserved_17_31 : Interfaces.STM32.UInt15;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR16_Register use record
FZIWDGSTP at 0 range 0 .. 0;
Reserved_1_15 at 0 range 1 .. 15;
PKP at 0 range 16 .. 16;
Reserved_17_31 at 0 range 17 .. 31;
end record;
subtype UR17_IO_HSLV_Field is Interfaces.STM32.Bit;
-- SYSCFG user register 17
type UR17_Register is record
-- Read-only. I/O high speed / low voltage
IO_HSLV : UR17_IO_HSLV_Field;
-- unspecified
Reserved_1_31 : Interfaces.STM32.UInt31;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for UR17_Register use record
IO_HSLV at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- System configuration controller
type SYSCFG_Peripheral is record
-- peripheral mode configuration register
PMCR : aliased PMCR_Register;
-- external interrupt configuration register 1
EXTICR1 : aliased EXTICR1_Register;
-- external interrupt configuration register 2
EXTICR2 : aliased EXTICR2_Register;
-- external interrupt configuration register 3
EXTICR3 : aliased EXTICR3_Register;
-- external interrupt configuration register 4
EXTICR4 : aliased EXTICR4_Register;
-- compensation cell control/status register
CCCSR : aliased CCCSR_Register;
-- SYSCFG compensation cell value register
CCVR : aliased CCVR_Register;
-- SYSCFG compensation cell code register
CCCR : aliased CCCR_Register;
-- SYSCFG power control register
PWRCR : aliased PWRCR_Register;
-- SYSCFG package register
PKGR : aliased PKGR_Register;
-- SYSCFG user register 0
UR0 : aliased UR0_Register;
-- SYSCFG user register 2
UR2 : aliased UR2_Register;
-- SYSCFG user register 3
UR3 : aliased UR3_Register;
-- SYSCFG user register 4
UR4 : aliased UR4_Register;
-- SYSCFG user register 5
UR5 : aliased UR5_Register;
-- SYSCFG user register 6
UR6 : aliased UR6_Register;
-- SYSCFG user register 7
UR7 : aliased UR7_Register;
-- SYSCFG user register 8
UR8 : aliased UR8_Register;
-- SYSCFG user register 9
UR9 : aliased UR9_Register;
-- SYSCFG user register 10
UR10 : aliased UR10_Register;
-- SYSCFG user register 11
UR11 : aliased UR11_Register;
-- SYSCFG user register 12
UR12 : aliased UR12_Register;
-- SYSCFG user register 13
UR13 : aliased UR13_Register;
-- SYSCFG user register 14
UR14 : aliased UR14_Register;
-- SYSCFG user register 15
UR15 : aliased UR15_Register;
-- SYSCFG user register 16
UR16 : aliased UR16_Register;
-- SYSCFG user register 17
UR17 : aliased UR17_Register;
end record
with Volatile;
for SYSCFG_Peripheral use record
PMCR at 16#4# range 0 .. 31;
EXTICR1 at 16#8# range 0 .. 31;
EXTICR2 at 16#C# range 0 .. 31;
EXTICR3 at 16#10# range 0 .. 31;
EXTICR4 at 16#14# range 0 .. 31;
CCCSR at 16#20# range 0 .. 31;
CCVR at 16#24# range 0 .. 31;
CCCR at 16#28# range 0 .. 31;
PWRCR at 16#2C# range 0 .. 31;
PKGR at 16#124# range 0 .. 31;
UR0 at 16#300# range 0 .. 31;
UR2 at 16#308# range 0 .. 31;
UR3 at 16#30C# range 0 .. 31;
UR4 at 16#310# range 0 .. 31;
UR5 at 16#314# range 0 .. 31;
UR6 at 16#318# range 0 .. 31;
UR7 at 16#31C# range 0 .. 31;
UR8 at 16#320# range 0 .. 31;
UR9 at 16#324# range 0 .. 31;
UR10 at 16#328# range 0 .. 31;
UR11 at 16#32C# range 0 .. 31;
UR12 at 16#330# range 0 .. 31;
UR13 at 16#334# range 0 .. 31;
UR14 at 16#338# range 0 .. 31;
UR15 at 16#33C# range 0 .. 31;
UR16 at 16#340# range 0 .. 31;
UR17 at 16#344# range 0 .. 31;
end record;
-- System configuration controller
SYSCFG_Periph : aliased SYSCFG_Peripheral
with Import, Address => SYSCFG_Base;
end Interfaces.STM32.SYSCFG;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2015, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
pragma Style_Checks (All_Checks);
-- Subprogram ordering not enforced in this unit
-- (because of some logical groupings).
with Atree; use Atree;
with Csets; use Csets;
with Einfo; use Einfo;
with Fname; use Fname;
with Nlists; use Nlists;
with Output; use Output;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Stand; use Stand;
with Stringt; use Stringt;
with Tree_IO; use Tree_IO;
with Uname; use Uname;
with Widechar; use Widechar;
package body Lib is
Switch_Storing_Enabled : Boolean := True;
-- Controlled by Enable_Switch_Storing/Disable_Switch_Storing
-----------------------
-- Local Subprograms --
-----------------------
type SEU_Result is (
Yes_Before, -- S1 is in same extended unit as S2 and appears before it
Yes_Same, -- S1 is in same extended unit as S2, Slocs are the same
Yes_After, -- S1 is in same extended unit as S2, and appears after it
No); -- S2 is not in same extended unit as S2
function Check_Same_Extended_Unit (S1, S2 : Source_Ptr) return SEU_Result;
-- Used by In_Same_Extended_Unit and Earlier_In_Extended_Unit. Returns
-- value as described above.
function Get_Code_Or_Source_Unit
(S : Source_Ptr;
Unwind_Instances : Boolean) return Unit_Number_Type;
-- Common code for Get_Code_Unit (get unit of instantiation for location)
-- and Get_Source_Unit (get unit of template for location).
--------------------------------------------
-- Access Functions for Unit Table Fields --
--------------------------------------------
function Cunit (U : Unit_Number_Type) return Node_Id is
begin
return Units.Table (U).Cunit;
end Cunit;
function Cunit_Entity (U : Unit_Number_Type) return Entity_Id is
begin
return Units.Table (U).Cunit_Entity;
end Cunit_Entity;
function Dependency_Num (U : Unit_Number_Type) return Nat is
begin
return Units.Table (U).Dependency_Num;
end Dependency_Num;
function Dynamic_Elab (U : Unit_Number_Type) return Boolean is
begin
return Units.Table (U).Dynamic_Elab;
end Dynamic_Elab;
function Error_Location (U : Unit_Number_Type) return Source_Ptr is
begin
return Units.Table (U).Error_Location;
end Error_Location;
function Expected_Unit (U : Unit_Number_Type) return Unit_Name_Type is
begin
return Units.Table (U).Expected_Unit;
end Expected_Unit;
function Fatal_Error (U : Unit_Number_Type) return Fatal_Type is
begin
return Units.Table (U).Fatal_Error;
end Fatal_Error;
function Generate_Code (U : Unit_Number_Type) return Boolean is
begin
return Units.Table (U).Generate_Code;
end Generate_Code;
function Has_RACW (U : Unit_Number_Type) return Boolean is
begin
return Units.Table (U).Has_RACW;
end Has_RACW;
function Ident_String (U : Unit_Number_Type) return Node_Id is
begin
return Units.Table (U).Ident_String;
end Ident_String;
function Loading (U : Unit_Number_Type) return Boolean is
begin
return Units.Table (U).Loading;
end Loading;
function Main_CPU (U : Unit_Number_Type) return Int is
begin
return Units.Table (U).Main_CPU;
end Main_CPU;
function Main_Priority (U : Unit_Number_Type) return Int is
begin
return Units.Table (U).Main_Priority;
end Main_Priority;
function Munit_Index (U : Unit_Number_Type) return Nat is
begin
return Units.Table (U).Munit_Index;
end Munit_Index;
function No_Elab_Code_All (U : Unit_Number_Type) return Boolean is
begin
return Units.Table (U).No_Elab_Code_All;
end No_Elab_Code_All;
function OA_Setting (U : Unit_Number_Type) return Character is
begin
return Units.Table (U).OA_Setting;
end OA_Setting;
function Source_Index (U : Unit_Number_Type) return Source_File_Index is
begin
return Units.Table (U).Source_Index;
end Source_Index;
function Unit_File_Name (U : Unit_Number_Type) return File_Name_Type is
begin
return Units.Table (U).Unit_File_Name;
end Unit_File_Name;
function Unit_Name (U : Unit_Number_Type) return Unit_Name_Type is
begin
return Units.Table (U).Unit_Name;
end Unit_Name;
------------------------------------------
-- Subprograms to Set Unit Table Fields --
------------------------------------------
procedure Set_Cunit (U : Unit_Number_Type; N : Node_Id) is
begin
Units.Table (U).Cunit := N;
end Set_Cunit;
procedure Set_Cunit_Entity (U : Unit_Number_Type; E : Entity_Id) is
begin
Units.Table (U).Cunit_Entity := E;
Set_Is_Compilation_Unit (E);
end Set_Cunit_Entity;
procedure Set_Dynamic_Elab (U : Unit_Number_Type; B : Boolean := True) is
begin
Units.Table (U).Dynamic_Elab := B;
end Set_Dynamic_Elab;
procedure Set_Error_Location (U : Unit_Number_Type; W : Source_Ptr) is
begin
Units.Table (U).Error_Location := W;
end Set_Error_Location;
procedure Set_Fatal_Error (U : Unit_Number_Type; V : Fatal_Type) is
begin
Units.Table (U).Fatal_Error := V;
end Set_Fatal_Error;
procedure Set_Generate_Code (U : Unit_Number_Type; B : Boolean := True) is
begin
Units.Table (U).Generate_Code := B;
end Set_Generate_Code;
procedure Set_Has_RACW (U : Unit_Number_Type; B : Boolean := True) is
begin
Units.Table (U).Has_RACW := B;
end Set_Has_RACW;
procedure Set_Ident_String (U : Unit_Number_Type; N : Node_Id) is
begin
Units.Table (U).Ident_String := N;
end Set_Ident_String;
procedure Set_Loading (U : Unit_Number_Type; B : Boolean := True) is
begin
Units.Table (U).Loading := B;
end Set_Loading;
procedure Set_Main_CPU (U : Unit_Number_Type; P : Int) is
begin
Units.Table (U).Main_CPU := P;
end Set_Main_CPU;
procedure Set_Main_Priority (U : Unit_Number_Type; P : Int) is
begin
Units.Table (U).Main_Priority := P;
end Set_Main_Priority;
procedure Set_No_Elab_Code_All
(U : Unit_Number_Type;
B : Boolean := True)
is
begin
Units.Table (U).No_Elab_Code_All := B;
end Set_No_Elab_Code_All;
procedure Set_OA_Setting (U : Unit_Number_Type; C : Character) is
begin
Units.Table (U).OA_Setting := C;
end Set_OA_Setting;
procedure Set_Unit_Name (U : Unit_Number_Type; N : Unit_Name_Type) is
begin
Units.Table (U).Unit_Name := N;
end Set_Unit_Name;
------------------------------
-- Check_Same_Extended_Unit --
------------------------------
function Check_Same_Extended_Unit (S1, S2 : Source_Ptr) return SEU_Result is
Sloc1 : Source_Ptr;
Sloc2 : Source_Ptr;
Sind1 : Source_File_Index;
Sind2 : Source_File_Index;
Inst1 : Source_Ptr;
Inst2 : Source_Ptr;
Unum1 : Unit_Number_Type;
Unum2 : Unit_Number_Type;
Unit1 : Node_Id;
Unit2 : Node_Id;
Depth1 : Nat;
Depth2 : Nat;
begin
if S1 = No_Location or else S2 = No_Location then
return No;
elsif S1 = Standard_Location then
if S2 = Standard_Location then
return Yes_Same;
else
return No;
end if;
elsif S2 = Standard_Location then
return No;
end if;
Sloc1 := S1;
Sloc2 := S2;
Unum1 := Get_Source_Unit (Sloc1);
Unum2 := Get_Source_Unit (Sloc2);
loop
-- Step 1: Check whether the two locations are in the same source
-- file.
Sind1 := Get_Source_File_Index (Sloc1);
Sind2 := Get_Source_File_Index (Sloc2);
if Sind1 = Sind2 then
if Sloc1 < Sloc2 then
return Yes_Before;
elsif Sloc1 > Sloc2 then
return Yes_After;
else
return Yes_Same;
end if;
end if;
-- Step 2: Check subunits. If a subunit is instantiated, follow the
-- instantiation chain rather than the stub chain.
Unit1 := Unit (Cunit (Unum1));
Unit2 := Unit (Cunit (Unum2));
Inst1 := Instantiation (Sind1);
Inst2 := Instantiation (Sind2);
if Nkind (Unit1) = N_Subunit
and then Present (Corresponding_Stub (Unit1))
and then Inst1 = No_Location
then
if Nkind (Unit2) = N_Subunit
and then Present (Corresponding_Stub (Unit2))
and then Inst2 = No_Location
then
-- Both locations refer to subunits which may have a common
-- ancestor. If they do, the deeper subunit must have a longer
-- unit name. Replace the deeper one with its corresponding
-- stub in order to find the nearest ancestor.
if Length_Of_Name (Unit_Name (Unum1)) <
Length_Of_Name (Unit_Name (Unum2))
then
Sloc2 := Sloc (Corresponding_Stub (Unit2));
Unum2 := Get_Source_Unit (Sloc2);
goto Continue;
else
Sloc1 := Sloc (Corresponding_Stub (Unit1));
Unum1 := Get_Source_Unit (Sloc1);
goto Continue;
end if;
-- Sloc1 in subunit, Sloc2 not
else
Sloc1 := Sloc (Corresponding_Stub (Unit1));
Unum1 := Get_Source_Unit (Sloc1);
goto Continue;
end if;
-- Sloc2 in subunit, Sloc1 not
elsif Nkind (Unit2) = N_Subunit
and then Present (Corresponding_Stub (Unit2))
and then Inst2 = No_Location
then
Sloc2 := Sloc (Corresponding_Stub (Unit2));
Unum2 := Get_Source_Unit (Sloc2);
goto Continue;
end if;
-- Step 3: Check instances. The two locations may yield a common
-- ancestor.
if Inst1 /= No_Location then
if Inst2 /= No_Location then
-- Both locations denote instantiations
Depth1 := Instantiation_Depth (Sloc1);
Depth2 := Instantiation_Depth (Sloc2);
if Depth1 < Depth2 then
Sloc2 := Inst2;
Unum2 := Get_Source_Unit (Sloc2);
goto Continue;
elsif Depth1 > Depth2 then
Sloc1 := Inst1;
Unum1 := Get_Source_Unit (Sloc1);
goto Continue;
else
Sloc1 := Inst1;
Sloc2 := Inst2;
Unum1 := Get_Source_Unit (Sloc1);
Unum2 := Get_Source_Unit (Sloc2);
goto Continue;
end if;
-- Sloc1 is an instantiation
else
Sloc1 := Inst1;
Unum1 := Get_Source_Unit (Sloc1);
goto Continue;
end if;
-- Sloc2 is an instantiation
elsif Inst2 /= No_Location then
Sloc2 := Inst2;
Unum2 := Get_Source_Unit (Sloc2);
goto Continue;
end if;
-- Step 4: One location in the spec, the other in the corresponding
-- body of the same unit. The location in the spec is considered
-- earlier.
if Nkind (Unit1) = N_Subprogram_Body
or else
Nkind (Unit1) = N_Package_Body
then
if Library_Unit (Cunit (Unum1)) = Cunit (Unum2) then
return Yes_After;
end if;
elsif Nkind (Unit2) = N_Subprogram_Body
or else
Nkind (Unit2) = N_Package_Body
then
if Library_Unit (Cunit (Unum2)) = Cunit (Unum1) then
return Yes_Before;
end if;
end if;
-- At this point it is certain that the two locations denote two
-- entirely separate units.
return No;
<<Continue>>
null;
end loop;
end Check_Same_Extended_Unit;
-------------------------------
-- Compilation_Switches_Last --
-------------------------------
function Compilation_Switches_Last return Nat is
begin
return Compilation_Switches.Last;
end Compilation_Switches_Last;
---------------------------
-- Enable_Switch_Storing --
---------------------------
procedure Enable_Switch_Storing is
begin
Switch_Storing_Enabled := True;
end Enable_Switch_Storing;
----------------------------
-- Disable_Switch_Storing --
----------------------------
procedure Disable_Switch_Storing is
begin
Switch_Storing_Enabled := False;
end Disable_Switch_Storing;
------------------------------
-- Earlier_In_Extended_Unit --
------------------------------
function Earlier_In_Extended_Unit (S1, S2 : Source_Ptr) return Boolean is
begin
return Check_Same_Extended_Unit (S1, S2) = Yes_Before;
end Earlier_In_Extended_Unit;
-----------------------
-- Exact_Source_Name --
-----------------------
function Exact_Source_Name (Loc : Source_Ptr) return String is
U : constant Unit_Number_Type := Get_Source_Unit (Loc);
Buf : constant Source_Buffer_Ptr := Source_Text (Source_Index (U));
Orig : constant Source_Ptr := Original_Location (Loc);
P : Source_Ptr;
WC : Char_Code;
Err : Boolean;
pragma Warnings (Off, WC);
pragma Warnings (Off, Err);
begin
-- Entity is character literal
if Buf (Orig) = ''' then
return String (Buf (Orig .. Orig + 2));
-- Entity is operator symbol
elsif Buf (Orig) = '"' or else Buf (Orig) = '%' then
P := Orig;
loop
P := P + 1;
exit when Buf (P) = Buf (Orig);
end loop;
return String (Buf (Orig .. P));
-- Entity is identifier
else
P := Orig;
loop
if Is_Start_Of_Wide_Char (Buf, P) then
Scan_Wide (Buf, P, WC, Err);
elsif not Identifier_Char (Buf (P)) then
exit;
else
P := P + 1;
end if;
end loop;
-- Write out the identifier by copying the exact source characters
-- used in its declaration. Note that this means wide characters will
-- be in their original encoded form.
return String (Buf (Orig .. P - 1));
end if;
end Exact_Source_Name;
----------------------------
-- Entity_Is_In_Main_Unit --
----------------------------
function Entity_Is_In_Main_Unit (E : Entity_Id) return Boolean is
S : Entity_Id;
begin
S := Scope (E);
while S /= Standard_Standard loop
if S = Main_Unit_Entity then
return True;
elsif Ekind (S) = E_Package and then Is_Child_Unit (S) then
return False;
else
S := Scope (S);
end if;
end loop;
return False;
end Entity_Is_In_Main_Unit;
--------------------------
-- Generic_May_Lack_ALI --
--------------------------
function Generic_May_Lack_ALI (Sfile : File_Name_Type) return Boolean is
begin
-- We allow internal generic units to be used without having a
-- corresponding ALI files to help bootstrapping with older compilers
-- that did not support generating ALIs for such generics. It is safe
-- to do so because the only thing the generated code would contain
-- is the elaboration boolean, and we are careful to elaborate all
-- predefined units first anyway.
return Is_Internal_File_Name
(Fname => Sfile,
Renamings_Included => True);
end Generic_May_Lack_ALI;
-----------------------------
-- Get_Code_Or_Source_Unit --
-----------------------------
function Get_Code_Or_Source_Unit
(S : Source_Ptr;
Unwind_Instances : Boolean) return Unit_Number_Type
is
begin
-- Search table unless we have No_Location, which can happen if the
-- relevant location has not been set yet. Happens for example when
-- we obtain Sloc (Cunit (Main_Unit)) before it is set.
if S /= No_Location then
declare
Source_File : Source_File_Index;
Source_Unit : Unit_Number_Type;
begin
Source_File := Get_Source_File_Index (S);
if Unwind_Instances then
while Template (Source_File) /= No_Source_File loop
Source_File := Template (Source_File);
end loop;
end if;
Source_Unit := Unit (Source_File);
if Source_Unit /= No_Unit then
return Source_Unit;
end if;
end;
end if;
-- If S was No_Location, or was not in the table, we must be in the main
-- source unit (and the value has not been placed in the table yet),
-- or in one of the configuration pragma files.
return Main_Unit;
end Get_Code_Or_Source_Unit;
-------------------
-- Get_Code_Unit --
-------------------
function Get_Code_Unit (S : Source_Ptr) return Unit_Number_Type is
begin
return Get_Code_Or_Source_Unit (Top_Level_Location (S),
Unwind_Instances => False);
end Get_Code_Unit;
function Get_Code_Unit (N : Node_Or_Entity_Id) return Unit_Number_Type is
begin
return Get_Code_Unit (Sloc (N));
end Get_Code_Unit;
----------------------------
-- Get_Compilation_Switch --
----------------------------
function Get_Compilation_Switch (N : Pos) return String_Ptr is
begin
if N <= Compilation_Switches.Last then
return Compilation_Switches.Table (N);
else
return null;
end if;
end Get_Compilation_Switch;
----------------------------------
-- Get_Cunit_Entity_Unit_Number --
----------------------------------
function Get_Cunit_Entity_Unit_Number
(E : Entity_Id) return Unit_Number_Type
is
begin
for U in Units.First .. Units.Last loop
if Cunit_Entity (U) = E then
return U;
end if;
end loop;
-- If not in the table, must be the main source unit, and we just
-- have not got it put into the table yet.
return Main_Unit;
end Get_Cunit_Entity_Unit_Number;
---------------------------
-- Get_Cunit_Unit_Number --
---------------------------
function Get_Cunit_Unit_Number (N : Node_Id) return Unit_Number_Type is
begin
for U in Units.First .. Units.Last loop
if Cunit (U) = N then
return U;
end if;
end loop;
-- If not in the table, must be a spec created for a main unit that is a
-- child subprogram body which we have not inserted into the table yet.
if N = Library_Unit (Cunit (Main_Unit)) then
return Main_Unit;
-- If it is anything else, something is seriously wrong, and we really
-- don't want to proceed, even if assertions are off, so we explicitly
-- raise an exception in this case to terminate compilation.
else
raise Program_Error;
end if;
end Get_Cunit_Unit_Number;
---------------------
-- Get_Source_Unit --
---------------------
function Get_Source_Unit (S : Source_Ptr) return Unit_Number_Type is
begin
return Get_Code_Or_Source_Unit (S, Unwind_Instances => True);
end Get_Source_Unit;
function Get_Source_Unit (N : Node_Or_Entity_Id) return Unit_Number_Type is
begin
return Get_Source_Unit (Sloc (N));
end Get_Source_Unit;
--------------------------------
-- In_Extended_Main_Code_Unit --
--------------------------------
function In_Extended_Main_Code_Unit
(N : Node_Or_Entity_Id) return Boolean
is
begin
if Sloc (N) = Standard_Location then
return False;
elsif Sloc (N) = No_Location then
return False;
-- Special case Itypes to test the Sloc of the associated node. The
-- reason we do this is for possible calls from gigi after -gnatD
-- processing is complete in sprint. This processing updates the
-- sloc fields of all nodes in the tree, but itypes are not in the
-- tree so their slocs do not get updated.
elsif Nkind (N) = N_Defining_Identifier
and then Is_Itype (N)
then
return In_Extended_Main_Code_Unit (Associated_Node_For_Itype (N));
-- Otherwise see if we are in the main unit
elsif Get_Code_Unit (Sloc (N)) = Get_Code_Unit (Cunit (Main_Unit)) then
return True;
-- Node may be in spec (or subunit etc) of main unit
else
return
In_Same_Extended_Unit (N, Cunit (Main_Unit));
end if;
end In_Extended_Main_Code_Unit;
function In_Extended_Main_Code_Unit (Loc : Source_Ptr) return Boolean is
begin
if Loc = Standard_Location then
return False;
elsif Loc = No_Location then
return False;
-- Otherwise see if we are in the main unit
elsif Get_Code_Unit (Loc) = Get_Code_Unit (Cunit (Main_Unit)) then
return True;
-- Location may be in spec (or subunit etc) of main unit
else
return
In_Same_Extended_Unit (Loc, Sloc (Cunit (Main_Unit)));
end if;
end In_Extended_Main_Code_Unit;
----------------------------------
-- In_Extended_Main_Source_Unit --
----------------------------------
function In_Extended_Main_Source_Unit
(N : Node_Or_Entity_Id) return Boolean
is
Nloc : constant Source_Ptr := Sloc (N);
Mloc : constant Source_Ptr := Sloc (Cunit (Main_Unit));
begin
-- If parsing, then use the global flag to indicate result
if Compiler_State = Parsing then
return Parsing_Main_Extended_Source;
-- Special value cases
elsif Nloc = Standard_Location then
return False;
elsif Nloc = No_Location then
return False;
-- Special case Itypes to test the Sloc of the associated node. The
-- reason we do this is for possible calls from gigi after -gnatD
-- processing is complete in sprint. This processing updates the
-- sloc fields of all nodes in the tree, but itypes are not in the
-- tree so their slocs do not get updated.
elsif Nkind (N) = N_Defining_Identifier
and then Is_Itype (N)
then
return In_Extended_Main_Source_Unit (Associated_Node_For_Itype (N));
-- Otherwise compare original locations to see if in same unit
else
return
In_Same_Extended_Unit
(Original_Location (Nloc), Original_Location (Mloc));
end if;
end In_Extended_Main_Source_Unit;
function In_Extended_Main_Source_Unit
(Loc : Source_Ptr) return Boolean
is
Mloc : constant Source_Ptr := Sloc (Cunit (Main_Unit));
begin
-- If parsing, then use the global flag to indicate result
if Compiler_State = Parsing then
return Parsing_Main_Extended_Source;
-- Special value cases
elsif Loc = Standard_Location then
return False;
elsif Loc = No_Location then
return False;
-- Otherwise compare original locations to see if in same unit
else
return
In_Same_Extended_Unit
(Original_Location (Loc), Original_Location (Mloc));
end if;
end In_Extended_Main_Source_Unit;
------------------------
-- In_Predefined_Unit --
------------------------
function In_Predefined_Unit (N : Node_Or_Entity_Id) return Boolean is
begin
return In_Predefined_Unit (Sloc (N));
end In_Predefined_Unit;
function In_Predefined_Unit (S : Source_Ptr) return Boolean is
Unit : constant Unit_Number_Type := Get_Source_Unit (S);
File : constant File_Name_Type := Unit_File_Name (Unit);
begin
return Is_Predefined_File_Name (File);
end In_Predefined_Unit;
-----------------------
-- In_Same_Code_Unit --
-----------------------
function In_Same_Code_Unit (N1, N2 : Node_Or_Entity_Id) return Boolean is
S1 : constant Source_Ptr := Sloc (N1);
S2 : constant Source_Ptr := Sloc (N2);
begin
if S1 = No_Location or else S2 = No_Location then
return False;
elsif S1 = Standard_Location then
return S2 = Standard_Location;
elsif S2 = Standard_Location then
return False;
end if;
return Get_Code_Unit (N1) = Get_Code_Unit (N2);
end In_Same_Code_Unit;
---------------------------
-- In_Same_Extended_Unit --
---------------------------
function In_Same_Extended_Unit
(N1, N2 : Node_Or_Entity_Id) return Boolean
is
begin
return Check_Same_Extended_Unit (Sloc (N1), Sloc (N2)) /= No;
end In_Same_Extended_Unit;
function In_Same_Extended_Unit (S1, S2 : Source_Ptr) return Boolean is
begin
return Check_Same_Extended_Unit (S1, S2) /= No;
end In_Same_Extended_Unit;
-------------------------
-- In_Same_Source_Unit --
-------------------------
function In_Same_Source_Unit (N1, N2 : Node_Or_Entity_Id) return Boolean is
S1 : constant Source_Ptr := Sloc (N1);
S2 : constant Source_Ptr := Sloc (N2);
begin
if S1 = No_Location or else S2 = No_Location then
return False;
elsif S1 = Standard_Location then
return S2 = Standard_Location;
elsif S2 = Standard_Location then
return False;
end if;
return Get_Source_Unit (N1) = Get_Source_Unit (N2);
end In_Same_Source_Unit;
-----------------------------
-- Increment_Serial_Number --
-----------------------------
function Increment_Serial_Number return Nat is
TSN : Int renames Units.Table (Current_Sem_Unit).Serial_Number;
begin
TSN := TSN + 1;
return TSN;
end Increment_Serial_Number;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Linker_Option_Lines.Init;
Notes.Init;
Load_Stack.Init;
Units.Init;
Compilation_Switches.Init;
end Initialize;
---------------
-- Is_Loaded --
---------------
function Is_Loaded (Uname : Unit_Name_Type) return Boolean is
begin
for Unum in Units.First .. Units.Last loop
if Uname = Unit_Name (Unum) then
return True;
end if;
end loop;
return False;
end Is_Loaded;
---------------
-- Last_Unit --
---------------
function Last_Unit return Unit_Number_Type is
begin
return Units.Last;
end Last_Unit;
----------
-- List --
----------
procedure List (File_Names_Only : Boolean := False) is separate;
----------
-- Lock --
----------
procedure Lock is
begin
Linker_Option_Lines.Locked := True;
Load_Stack.Locked := True;
Units.Locked := True;
Linker_Option_Lines.Release;
Load_Stack.Release;
Units.Release;
end Lock;
---------------
-- Num_Units --
---------------
function Num_Units return Nat is
begin
return Int (Units.Last) - Int (Main_Unit) + 1;
end Num_Units;
-----------------
-- Remove_Unit --
-----------------
procedure Remove_Unit (U : Unit_Number_Type) is
begin
if U = Units.Last then
Units.Decrement_Last;
end if;
end Remove_Unit;
----------------------------------
-- Replace_Linker_Option_String --
----------------------------------
procedure Replace_Linker_Option_String
(S : String_Id; Match_String : String)
is
begin
if Match_String'Length > 0 then
for J in 1 .. Linker_Option_Lines.Last loop
String_To_Name_Buffer (Linker_Option_Lines.Table (J).Option);
if Match_String = Name_Buffer (1 .. Match_String'Length) then
Linker_Option_Lines.Table (J).Option := S;
return;
end if;
end loop;
end if;
Store_Linker_Option_String (S);
end Replace_Linker_Option_String;
----------
-- Sort --
----------
procedure Sort (Tbl : in out Unit_Ref_Table) is separate;
------------------------------
-- Store_Compilation_Switch --
------------------------------
procedure Store_Compilation_Switch (Switch : String) is
begin
if Switch_Storing_Enabled then
Compilation_Switches.Increment_Last;
Compilation_Switches.Table (Compilation_Switches.Last) :=
new String'(Switch);
-- Fix up --RTS flag which has been transformed by the gcc driver
-- into -fRTS
if Switch'Last >= Switch'First + 4
and then Switch (Switch'First .. Switch'First + 4) = "-fRTS"
then
Compilation_Switches.Table
(Compilation_Switches.Last) (Switch'First + 1) := '-';
end if;
end if;
end Store_Compilation_Switch;
--------------------------------
-- Store_Linker_Option_String --
--------------------------------
procedure Store_Linker_Option_String (S : String_Id) is
begin
Linker_Option_Lines.Append ((Option => S, Unit => Current_Sem_Unit));
end Store_Linker_Option_String;
----------------
-- Store_Note --
----------------
procedure Store_Note (N : Node_Id) is
Sfile : constant Source_File_Index := Get_Source_File_Index (Sloc (N));
begin
-- Notes for a generic are emitted when processing the template, never
-- in instances.
if In_Extended_Main_Code_Unit (N)
and then Instance (Sfile) = No_Instance_Id
then
Notes.Append (N);
end if;
end Store_Note;
-------------------------------
-- Synchronize_Serial_Number --
-------------------------------
procedure Synchronize_Serial_Number is
TSN : Int renames Units.Table (Current_Sem_Unit).Serial_Number;
begin
TSN := TSN + 1;
end Synchronize_Serial_Number;
---------------
-- Tree_Read --
---------------
procedure Tree_Read is
N : Nat;
S : String_Ptr;
begin
Units.Tree_Read;
-- Read Compilation_Switches table. First release the memory occupied
-- by the previously loaded switches.
for J in Compilation_Switches.First .. Compilation_Switches.Last loop
Free (Compilation_Switches.Table (J));
end loop;
Tree_Read_Int (N);
Compilation_Switches.Set_Last (N);
for J in 1 .. N loop
Tree_Read_Str (S);
Compilation_Switches.Table (J) := S;
end loop;
end Tree_Read;
----------------
-- Tree_Write --
----------------
procedure Tree_Write is
begin
Units.Tree_Write;
-- Write Compilation_Switches table
Tree_Write_Int (Compilation_Switches.Last);
for J in 1 .. Compilation_Switches.Last loop
Tree_Write_Str (Compilation_Switches.Table (J));
end loop;
end Tree_Write;
------------
-- Unlock --
------------
procedure Unlock is
begin
Linker_Option_Lines.Locked := False;
Load_Stack.Locked := False;
Units.Locked := False;
end Unlock;
-----------------
-- Version_Get --
-----------------
function Version_Get (U : Unit_Number_Type) return Word_Hex_String is
begin
return Get_Hex_String (Units.Table (U).Version);
end Version_Get;
------------------------
-- Version_Referenced --
------------------------
procedure Version_Referenced (S : String_Id) is
begin
Version_Ref.Append (S);
end Version_Referenced;
---------------------
-- Write_Unit_Info --
---------------------
procedure Write_Unit_Info
(Unit_Num : Unit_Number_Type;
Item : Node_Id;
Prefix : String := "";
Withs : Boolean := False)
is
begin
Write_Str (Prefix);
Write_Unit_Name (Unit_Name (Unit_Num));
Write_Str (", unit ");
Write_Int (Int (Unit_Num));
Write_Str (", ");
Write_Int (Int (Item));
Write_Str ("=");
Write_Str (Node_Kind'Image (Nkind (Item)));
if Item /= Original_Node (Item) then
Write_Str (", orig = ");
Write_Int (Int (Original_Node (Item)));
Write_Str ("=");
Write_Str (Node_Kind'Image (Nkind (Original_Node (Item))));
end if;
Write_Eol;
-- Skip the rest if we're not supposed to print the withs
if not Withs then
return;
end if;
declare
Context_Item : Node_Id;
begin
Context_Item := First (Context_Items (Cunit (Unit_Num)));
while Present (Context_Item)
and then (Nkind (Context_Item) /= N_With_Clause
or else Limited_Present (Context_Item))
loop
Context_Item := Next (Context_Item);
end loop;
if Present (Context_Item) then
Indent;
Write_Line ("withs:");
Indent;
while Present (Context_Item) loop
if Nkind (Context_Item) = N_With_Clause
and then not Limited_Present (Context_Item)
then
pragma Assert (Present (Library_Unit (Context_Item)));
Write_Unit_Name
(Unit_Name
(Get_Cunit_Unit_Number (Library_Unit (Context_Item))));
if Implicit_With (Context_Item) then
Write_Str (" -- implicit");
end if;
Write_Eol;
end if;
Context_Item := Next (Context_Item);
end loop;
Outdent;
Write_Line ("end withs");
Outdent;
end if;
end;
end Write_Unit_Info;
end Lib;
|
with STM32GD.Clock.Tree;
generic
with package Clock_Tree is new STM32GD.Clock.Tree (<>);
package STM32GD.Timeout is
type Microseconds is new Natural;
type Milliseconds is new Natural;
type Seconds is new Natural;
procedure Set (T : Microseconds);
procedure Set (T : Milliseconds);
procedure Set (T : Seconds);
procedure Await;
function Expired return Boolean;
end STM32GD.Timeout;
|
-- --
-- package Strings_Edit.UTF8 Copyright (c) Dmitry A. Kazakov --
-- Interface Luebeck --
-- Spring, 2005 --
-- --
-- Last revision : 21:03 21 Apr 2009 --
-- --
-- This library 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 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 --
-- General Public License for more details. You should have --
-- received a copy of the GNU General Public License along with --
-- this library; if not, write to the Free Software Foundation, --
-- Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- 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. --
--____________________________________________________________________--
package Strings_Edit.UTF8 is
pragma Elaborate_Body (Strings_Edit.UTF8);
--
-- UTF8_Code_Point -- UFT-8 codespace
--
type Code_Point is mod 2**32;
subtype UTF8_Code_Point is Code_Point range 0..16#10FFFF#;
--
-- Script_Base -- Supported bases of sub- and superscript integers
--
subtype Script_Base is NumberBase range 2..10;
--
-- Script_Digit -- Sub- and superscript digits
--
type Script_Digit is range 0..9;
type Sign is (Minus, None, Plus);
--
-- Get -- Get one UTF-8 code point
--
-- Source - The source string
-- Pointer - The string position to start at
-- Value - The result
--
-- This procedure decodes one UTF-8 code point from the string Source.
-- It starts at Source (Pointer). After successful completion Pointer is
-- advanced to the first character following the input. The result is
-- returned through the parameter Value.
--
-- Exceptions :
--
-- Data_Error - UTF-8 syntax error
-- End_Error - Nothing found
-- Layout_Error - Pointer is not in Source'First..Source'Last + 1
--
procedure Get
( Source : String;
Pointer : in out Integer;
Value : out UTF8_Code_Point
);
--
-- Get_Backwards -- Get one UTF-8 code point
--
-- Source - The source string
-- Pointer - The string position to start at
-- Value - The result
--
-- This procedure decodes one UTF-8 code point from the string Source.
-- It starts at Source (Pointer - 1) and continues backwards. After
-- successful completion Pointer is moved to the first character of the
-- result. The result is returned through the parameter Value.
--
-- Exceptions :
--
-- Data_Error - UTF-8 syntax error
-- End_Error - Nothing found
-- Layout_Error - Pointer is not in Source'First..Source'Last + 1
--
procedure Get_Backwards
( Source : String;
Pointer : in out Integer;
Value : out UTF8_Code_Point
);
--
-- Image -- Of an UTF-8 code point
--
-- Value - The code point
--
-- Returns :
--
-- UTF-8 encoded equivalent
--
function Image (Value : UTF8_Code_Point) return String;
--
-- Put -- Put one UTF-8 code point
--
-- Destination - The target string
-- Pointer - The position where to place the character
-- Value - The code point to put
--
-- This procedure puts one UTF-8 code point into the string Source
-- starting from the position Source (Pointer). Pointer is then advanced
-- to the first character following the output.
--
-- Exceptions :
--
-- Layout_Error - Pointer is not in Destination'Range of there is no
-- room for output
--
procedure Put
( Destination : in out String;
Pointer : in out Integer;
Value : UTF8_Code_Point
);
--
-- Length -- The length of an UTF-8 string
--
-- Source - The string containing UTF-8 encoded code points
--
-- Returns :
--
-- The number of UTF-8 encoded code points in Source
--
-- Exceptions :
--
-- Data_Error - Invalid string
--
function Length (Source : String) return Natural;
--
-- Skip -- Skip UTF-8 code point
--
-- Source - UTF-8 encoded string
-- Pointer - The position of the first UTF-8 code point to skip
-- Count - The number of code points to skip
--
-- After successful completion Source (Pointer) is the first character
-- following Count skipped UTF-8 encoded code points.
--
-- Exceptions :
--
-- Data_Error - Invalid string
-- Layout_Error - Pointer is not in Source'First..Source'Last + 1
-- End_Error - Less than Count UTF-8 points to skip
--
procedure Skip
( Source : String;
Pointer : in out Integer;
Count : Natural := 1
);
--
-- Value -- Conversion to code point
--
-- Source - One UTF-8 encoded code point
--
-- Returns :
--
-- The code point
--
-- Exceptions :
--
-- Data_Error - Illegal UTF-8 string
--
function Value (Source : String) return UTF8_Code_Point;
--
-- Code_Points_Range -- A range of UTF-8 code points Low..High
--
type Code_Points_Range is record
Low : UTF8_Code_Point;
High : UTF8_Code_Point;
end record;
Full_Range : constant Code_Points_Range;
--
-- Code_Points_Ranges -- An array of ranges
--
type Code_Points_Ranges is
array (Positive range <>) of Code_Points_Range;
private
--
-- Reverse_Put -- Put one code point in reverse
--
-- Destination - The target string
-- Pointer - The position where to place the encoded point
-- Prefix - The prefix in UTF-8 encoding
-- Position - The position of the last encoded character
--
-- This procedure places Prefix & Character'Val (Position) in the
-- positions of Destination (..Pointer). Then Pointer is moved back to
-- the first position before the first character of the output.
--
-- Exceptions :
--
-- Layout_Error - No room for output
--
procedure Reverse_Put
( Destination : in out String;
Pointer : in out Integer;
Prefix : String;
Position : Natural
);
Full_Range : constant Code_Points_Range :=
( Low => UTF8_Code_Point'First,
High => UTF8_Code_Point'Last
);
end Strings_Edit.UTF8;
|
with Tkmrpc.Types;
with Tkmrpc.Results;
package Tkmrpc.Servers.Ees
is
procedure Init;
-- Initialize EES server.
procedure Finalize;
-- Finalize EES server.
procedure Esa_Acquire
(Result : out Results.Result_Type;
Sp_Id : Types.Sp_Id_Type);
-- Trigger 'Acquire' event for an ESP SA.
procedure Esa_Expire
(Result : out Results.Result_Type;
Sp_Id : Types.Sp_Id_Type;
Spi_Rem : Types.Esp_Spi_Type;
Protocol : Types.Protocol_Type;
Hard : Types.Expiry_Flag_Type);
-- Trigger 'Expire' event for an ESP SA.
end Tkmrpc.Servers.Ees;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
procedure Nested is
begin
Put_Line ("Hello World");
end Nested;
begin
Nested;
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ E L I M --
-- --
-- S p e c --
-- --
-- Copyright (C) 1997-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the routines used to process the Eliminate pragma
with Types; use Types;
package Sem_Elim is
procedure Initialize;
-- Initialize for new main souce program
procedure Process_Eliminate_Pragma
(Pragma_Node : Node_Id;
Arg_Unit_Name : Node_Id;
Arg_Entity : Node_Id;
Arg_Parameter_Types : Node_Id;
Arg_Result_Type : Node_Id;
Arg_Source_Location : Node_Id);
-- Process eliminate pragma (given by Pragma_Node). The number of
-- arguments has been checked, as well as possible optional identifiers,
-- but no other checks have been made. This subprogram completes the
-- checking, and then if the pragma is well formed, makes appropriate
-- entries in the internal tables used to keep track of Eliminate pragmas.
-- The other five arguments are expressions (rather than pragma argument
-- associations) for the possible pragma arguments. A parameter that
-- is not present is set to Empty.
procedure Check_Eliminated (E : Entity_Id);
-- Checks if entity E is eliminated, and if so sets the Is_Eliminated
-- flag on the given entity.
procedure Eliminate_Error_Msg (N : Node_Id; E : Entity_Id);
-- Called by the back end on encouterning a call to an eliminated
-- subprogram. N is the node for the call, and E is the entity of
-- the subprogram being eliminated.
end Sem_Elim;
|
-- { dg-do run }
-- { dg-options "-O -gnatn" }
with Loop_Optimization8_Pkg1;
procedure Loop_Optimization8 is
Data : Loop_Optimization8_Pkg1.T;
procedure Check_1 (N : in Natural) is
begin
if N /= 0 then
for I in 1 .. Data.Last loop
declare
F : constant Natural := Data.Elements (I);
begin
if F = N then
raise Program_Error;
end if;
end;
end loop;
end if;
end;
procedure Check is new Loop_Optimization8_Pkg1.Iter (Check_1);
begin
Data := Loop_Optimization8_Pkg1.Empty;
Check;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . W C H _ S T W --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the routine used to convert strings to wide (wide)
-- strings for use by wide (wide) image attribute.
with System.WCh_Con;
package System.WCh_StW is
pragma Pure;
procedure String_To_Wide_String
(S : String;
R : out Wide_String;
L : out Natural;
EM : System.WCh_Con.WC_Encoding_Method);
-- This routine simply takes its argument and converts it to wide string
-- format, storing the result in R (1 .. L), with L being set appropriately
-- on return. The caller guarantees that R is long enough to accommodate
-- the result. This is used in the context of the Wide_Image attribute,
-- where the argument is the corresponding 'Image attribute. Any wide
-- character escape sequences in the string are converted to the
-- corresponding wide character value. No syntax checks are made, it is
-- assumed that any such sequences are validly formed (this must be assured
-- by the caller), and results from the fact that Wide_Image is only used
-- on strings that have been built by the compiler, such as images of
-- enumeration literals. If the method for encoding is a shift-in,
-- shift-out convention, then it is assumed that normal (non-wide
-- character) mode holds at the start and end of the argument string. EM
-- indicates the wide character encoding method.
-- Note: in the WCEM_Brackets case, the brackets escape sequence is used
-- only for codes greater than 16#FF#.
procedure String_To_Wide_Wide_String
(S : String;
R : out Wide_Wide_String;
L : out Natural;
EM : System.WCh_Con.WC_Encoding_Method);
-- Same function with Wide_Wide_String output
end System.WCh_StW;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- F R O N T E N D --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2001 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Checks;
with CStand;
with Debug; use Debug;
with Elists;
with Exp_Ch11;
with Exp_Dbug;
with Fmap;
with Fname.UF;
with Hostparm; use Hostparm;
with Inline; use Inline;
with Lib; use Lib;
with Lib.Load; use Lib.Load;
with Live; use Live;
with Namet; use Namet;
with Nlists; use Nlists;
with Opt; use Opt;
with Osint;
with Output; use Output;
with Par;
with Rtsfind;
with Sprint;
with Scn; use Scn;
with Sem; use Sem;
with Sem_Ch8; use Sem_Ch8;
with Sem_Elab; use Sem_Elab;
with Sem_Prag; use Sem_Prag;
with Sem_Warn; use Sem_Warn;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Sinput.L; use Sinput.L;
with Types; use Types;
procedure Frontend is
Pragmas : List_Id;
Prag : Node_Id;
Save_Style_Check : constant Boolean := Opt.Style_Check;
-- Save style check mode so it can be restored later
begin
-- Carry out package initializations. These are initializations which
-- might logically be performed at elaboration time, were it not for
-- the fact that we may be doing things more than once in the big loop
-- over files. Like elaboration, the order in which these calls are
-- made is in some cases important. For example, Lib cannot be
-- initialized until Namet, since it uses names table entries.
Rtsfind.Initialize;
Atree.Initialize;
Nlists.Initialize;
Elists.Initialize;
Lib.Load.Initialize;
Sem_Ch8.Initialize;
Fname.UF.Initialize;
Exp_Ch11.Initialize;
Checks.Initialize;
-- Create package Standard
CStand.Create_Standard;
-- Read and process gnat.adc file if one is present
if Opt.Config_File then
-- We always analyze the gnat.adc file with style checks off,
-- since we don't want a miscellaneous gnat.adc that is around
-- to discombobulate intended -gnatg compilations.
Opt.Style_Check := False;
-- Capture current suppress options, which may get modified
Scope_Suppress := Opt.Suppress_Options;
Name_Buffer (1 .. 8) := "gnat.adc";
Name_Len := 8;
Source_gnat_adc := Load_Config_File (Name_Enter);
if Source_gnat_adc /= No_Source_File then
Initialize_Scanner (No_Unit, Source_gnat_adc);
Pragmas := Par (Configuration_Pragmas => True);
if Pragmas /= Error_List
and then Operating_Mode /= Check_Syntax
then
Prag := First (Pragmas);
while Present (Prag) loop
Analyze_Pragma (Prag);
Next (Prag);
end loop;
end if;
end if;
-- Restore style check, but if gnat.adc turned on checks, leave on!
Opt.Style_Check := Save_Style_Check or Style_Check;
-- Capture any modifications to suppress options from config pragmas
Opt.Suppress_Options := Scope_Suppress;
end if;
-- Read and process the configuration pragmas file if one is present
if Config_File_Name /= null then
declare
New_Pragmas : List_Id;
Style_Check_Saved : constant Boolean := Opt.Style_Check;
Source_Config_File : Source_File_Index := No_Source_File;
begin
-- We always analyze the config pragmas file with style checks off,
-- since we don't want it to discombobulate intended
-- -gnatg compilations.
Opt.Style_Check := False;
-- Capture current suppress options, which may get modified
Scope_Suppress := Opt.Suppress_Options;
Name_Buffer (1 .. Config_File_Name'Length) := Config_File_Name.all;
Name_Len := Config_File_Name'Length;
Source_Config_File := Load_Config_File (Name_Enter);
if Source_Config_File = No_Source_File then
Osint.Fail
("cannot find configuration pragmas file ",
Config_File_Name.all);
end if;
Initialize_Scanner (No_Unit, Source_Config_File);
New_Pragmas := Par (Configuration_Pragmas => True);
if New_Pragmas /= Error_List
and then Operating_Mode /= Check_Syntax
then
Prag := First (New_Pragmas);
while Present (Prag) loop
Analyze_Pragma (Prag);
Next (Prag);
end loop;
end if;
-- Restore style check, but if the config pragmas file
-- turned on checks, leave on!
Opt.Style_Check := Style_Check_Saved or Style_Check;
-- Capture any modifications to suppress options from config pragmas
Opt.Suppress_Options := Scope_Suppress;
end;
end if;
-- If there was a -gnatem switch, initialize the mappings of unit names to
-- file names and of file names to path names from the mapping file.
if Mapping_File_Name /= null then
Fmap.Initialize (Mapping_File_Name.all);
end if;
-- We have now processed the command line switches, and the gnat.adc
-- file, so this is the point at which we want to capture the values
-- of the configuration switches (see Opt for further details).
Opt.Register_Opt_Config_Switches;
-- Initialize the scanner. Note that we do this after the call to
-- Create_Standard, which uses the scanner in its processing of
-- floating-point bounds.
Initialize_Scanner (Main_Unit, Source_Index (Main_Unit));
-- Output header if in verbose mode or full list mode
if Verbose_Mode or Full_List then
Write_Eol;
if Operating_Mode = Generate_Code then
Write_Str ("Compiling: ");
else
Write_Str ("Checking: ");
end if;
Write_Name (Full_File_Name (Current_Source_File));
if not Debug_Flag_7 then
Write_Str (" (source file time stamp: ");
Write_Time_Stamp (Current_Source_File);
Write_Char (')');
end if;
Write_Eol;
end if;
-- Here we call the parser to parse the compilation unit (or units in
-- the check syntax mode, but in that case we won't go on to the
-- semantics in any case).
declare
Discard : List_Id;
begin
Discard := Par (Configuration_Pragmas => False);
end;
-- The main unit is now loaded, and subunits of it can be loaded,
-- without reporting spurious loading circularities.
Set_Loading (Main_Unit, False);
-- Now on to the semantics. We skip the semantics if we are in syntax
-- only mode, or if we encountered a fatal error during the parsing.
if Operating_Mode /= Check_Syntax
and then not Fatal_Error (Main_Unit)
then
-- Reset Operating_Mode to Check_Semantics for subunits. We cannot
-- actually generate code for subunits, so we suppress expansion.
-- This also corrects certain problems that occur if we try to
-- incorporate subunits at a lower level.
if Operating_Mode = Generate_Code
and then Nkind (Unit (Cunit (Main_Unit))) = N_Subunit
then
Operating_Mode := Check_Semantics;
end if;
-- Analyze (and possibly expand) main unit
Scope_Suppress := Suppress_Options;
Semantics (Cunit (Main_Unit));
-- Cleanup processing after completing main analysis
if Operating_Mode = Generate_Code
or else (Operating_Mode = Check_Semantics
and then Tree_Output)
then
Instantiate_Bodies;
end if;
if Operating_Mode = Generate_Code then
if Inline_Processing_Required then
Analyze_Inlined_Bodies;
end if;
-- Remove entities from program that do not have any
-- execution time references.
if Debug_Flag_UU then
Collect_Garbage_Entities;
end if;
Check_Elab_Calls;
-- Build unit exception table. We leave this up to the end to
-- make sure that all the necessary information is at hand.
Exp_Ch11.Generate_Unit_Exception_Table;
-- Save the unit name and list of packages named in Use_Package
-- clauses for subsequent use in generating a special symbol for
-- the debugger for certain targets that require this.
Exp_Dbug.Save_Unitname_And_Use_List
(Cunit (Main_Unit), Nkind (Unit (Cunit (Main_Unit))));
end if;
-- List library units if requested
if List_Units then
Lib.List;
end if;
-- Output any messages for unreferenced entities
Output_Unreferenced_Messages;
Sem_Warn.Check_Unused_Withs;
end if;
-- Qualify all entity names in inner packages, package bodies, etc.,
-- except when compiling for the JVM back end, which depends on
-- having unqualified names in certain cases and handles the generation
-- of qualified names when needed.
if not Java_VM then
Exp_Dbug.Qualify_All_Entity_Names;
Exp_Dbug.Generate_Auxiliary_Types;
end if;
-- Dump the source now. Note that we do this as soon as the analysis
-- of the tree is complete, because it is not just a dump in the case
-- of -gnatD, where it rewrites all source locations in the tree.
Sprint.Source_Dump;
end Frontend;
|
--
-- ABench2020 Benchmark Suite
--
-- Selection Sort Program
--
-- Licensed under the MIT License. See LICENSE file in the ABench root
-- directory for license information.
--
-- Uncomment the line below to print the result.
-- with Ada.Text_IO; use Ada.Text_IO;
procedure Selection_Sort is
type Vector is array (Positive range<>) of Integer;
procedure Sort (Sort_Array : in out Vector) is
Temp_Value : Integer;
begin
for I in 1 .. Sort_Array'Last loop
for J in I .. Sort_Array'Last loop
if Sort_Array (I) > Sort_Array (J) then
Temp_Value := Sort_Array (I);
Sort_Array (I) := Sort_Array (J);
Sort_Array (J) := Temp_Value;
end if;
end loop;
end loop;
end;
Sort_Array : Vector := (1, 9, 5, 31, 25, 46, 98, 17, 21, 82, 2, 33, 64, 73,
56, 567, 5, 45, 445, 4, 76, 22, 34, 45, 56, 888, 66, 89, 9, 32, 46, 78,
87, 23, 37, 12, 3, 6, 89, 7);
begin
loop
Sort (Sort_Array);
Sort_Array := (1, 9, 5, 31, 25, 46, 98, 17, 21, 82, 2, 33, 64, 73,
56, 567, 5, 45, 445, 4, 76, 22, 34, 45, 56, 888, 66, 89, 9, 32, 46, 78,
87, 23, 37, 12, 3, 6, 89, 7);
end loop;
-- Uncomment the lines below to print the result.
-- Put_Line("Sorted Array:");
-- for I in Sort_Array'Range loop
-- Put (Integer'Image (Sort_Array (I)) & " ");
-- end loop;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- L I B . X R E F --
-- --
-- B o d y --
-- --
-- Copyright (C) 1998-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Csets; use Csets;
with Elists; use Elists;
with Errout; use Errout;
with Lib.Util; use Lib.Util;
with Nlists; use Nlists;
with Opt; use Opt;
with Restrict; use Restrict;
with Rident; use Rident;
with Sem; use Sem;
with Sem_Aux; use Sem_Aux;
with Sem_Prag; use Sem_Prag;
with Sem_Util; use Sem_Util;
with Sem_Warn; use Sem_Warn;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames; use Snames;
with Stringt; use Stringt;
with Stand; use Stand;
with Table; use Table;
with GNAT.Heap_Sort_G;
with GNAT.HTable;
package body Lib.Xref is
------------------
-- Declarations --
------------------
package Deferred_References is new Table.Table (
Table_Component_Type => Deferred_Reference_Entry,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => 512,
Table_Increment => 200,
Table_Name => "Name_Deferred_References");
-- The Xref table is used to record references. The Loc field is set
-- to No_Location for a definition entry.
subtype Xref_Entry_Number is Int;
type Xref_Key is record
-- These are the components of Xref_Entry that participate in hash
-- lookups.
Ent : Entity_Id;
-- Entity referenced (E parameter to Generate_Reference)
Loc : Source_Ptr;
-- Location of reference (Original_Location (Sloc field of N parameter
-- to Generate_Reference)). Set to No_Location for the case of a
-- defining occurrence.
Typ : Character;
-- Reference type (Typ param to Generate_Reference)
Eun : Unit_Number_Type;
-- Unit number corresponding to Ent
Lun : Unit_Number_Type;
-- Unit number corresponding to Loc. Value is undefined and not
-- referenced if Loc is set to No_Location.
-- The following components are only used for SPARK cross-references
Ref_Scope : Entity_Id;
-- Entity of the closest subprogram or package enclosing the reference
Ent_Scope : Entity_Id;
-- Entity of the closest subprogram or package enclosing the definition,
-- which should be located in the same file as the definition itself.
end record;
type Xref_Entry is record
Key : Xref_Key;
Ent_Scope_File : Unit_Number_Type;
-- File for entity Ent_Scope
Def : Source_Ptr;
-- Original source location for entity being referenced. Note that these
-- values are used only during the output process, they are not set when
-- the entries are originally built. This is because private entities
-- can be swapped when the initial call is made.
HTable_Next : Xref_Entry_Number;
-- For use only by Static_HTable
end record;
package Xrefs is new Table.Table (
Table_Component_Type => Xref_Entry,
Table_Index_Type => Xref_Entry_Number,
Table_Low_Bound => 1,
Table_Initial => Alloc.Xrefs_Initial,
Table_Increment => Alloc.Xrefs_Increment,
Table_Name => "Xrefs");
--------------
-- Xref_Set --
--------------
-- We keep a set of xref entries, in order to avoid inserting duplicate
-- entries into the above Xrefs table. An entry is in Xref_Set if and only
-- if it is in Xrefs.
Num_Buckets : constant := 2**16;
subtype Header_Num is Integer range 0 .. Num_Buckets - 1;
type Null_Type is null record;
pragma Unreferenced (Null_Type);
function Hash (F : Xref_Entry_Number) return Header_Num;
function Equal (F1, F2 : Xref_Entry_Number) return Boolean;
procedure HT_Set_Next (E : Xref_Entry_Number; Next : Xref_Entry_Number);
function HT_Next (E : Xref_Entry_Number) return Xref_Entry_Number;
function Get_Key (E : Xref_Entry_Number) return Xref_Entry_Number;
pragma Inline (Hash, Equal, HT_Set_Next, HT_Next, Get_Key);
package Xref_Set is new GNAT.HTable.Static_HTable (
Header_Num,
Element => Xref_Entry,
Elmt_Ptr => Xref_Entry_Number,
Null_Ptr => 0,
Set_Next => HT_Set_Next,
Next => HT_Next,
Key => Xref_Entry_Number,
Get_Key => Get_Key,
Hash => Hash,
Equal => Equal);
-----------------------------
-- SPARK Xrefs Information --
-----------------------------
package body SPARK_Specific is separate;
------------------------
-- Local Subprograms --
------------------------
procedure Add_Entry (Key : Xref_Key; Ent_Scope_File : Unit_Number_Type);
-- Add an entry to the tables of Xref_Entries, avoiding duplicates
procedure Generate_Prim_Op_References (Typ : Entity_Id);
-- For a tagged type, generate implicit references to its primitive
-- operations, for source navigation. This is done right before emitting
-- cross-reference information rather than at the freeze point of the type
-- in order to handle late bodies that are primitive operations.
function Lt (T1, T2 : Xref_Entry) return Boolean;
-- Order cross-references
---------------
-- Add_Entry --
---------------
procedure Add_Entry (Key : Xref_Key; Ent_Scope_File : Unit_Number_Type) is
begin
Xrefs.Increment_Last; -- tentative
Xrefs.Table (Xrefs.Last).Key := Key;
-- Set the entry in Xref_Set, and if newly set, keep the above
-- tentative increment.
if Xref_Set.Set_If_Not_Present (Xrefs.Last) then
Xrefs.Table (Xrefs.Last).Ent_Scope_File := Ent_Scope_File;
-- Leave Def and HTable_Next uninitialized
Set_Has_Xref_Entry (Key.Ent);
-- It was already in Xref_Set, so throw away the tentatively-added entry
else
Xrefs.Decrement_Last;
end if;
end Add_Entry;
---------------------
-- Defer_Reference --
---------------------
procedure Defer_Reference (Deferred_Reference : Deferred_Reference_Entry) is
begin
-- If Get_Ignore_Errors, then we are in Preanalyze_Without_Errors, and
-- we should not record cross references, because that will cause
-- duplicates when we call Analyze.
if not Get_Ignore_Errors then
Deferred_References.Append (Deferred_Reference);
end if;
end Defer_Reference;
-----------
-- Equal --
-----------
function Equal (F1, F2 : Xref_Entry_Number) return Boolean is
Result : constant Boolean :=
Xrefs.Table (F1).Key = Xrefs.Table (F2).Key;
begin
return Result;
end Equal;
-------------------------
-- Generate_Definition --
-------------------------
procedure Generate_Definition (E : Entity_Id) is
begin
pragma Assert (Nkind (E) in N_Entity);
-- Note that we do not test Xref_Entity_Letters here. It is too early
-- to do so, since we are often called before the entity is fully
-- constructed, so that the Ekind is still E_Void.
if Opt.Xref_Active
-- Definition must come from source
-- We make an exception for subprogram child units that have no spec.
-- For these we generate a subprogram declaration for library use,
-- and the corresponding entity does not come from source.
-- Nevertheless, all references will be attached to it and we have
-- to treat is as coming from user code.
and then (Comes_From_Source (E) or else Is_Child_Unit (E))
-- And must have a reasonable source location that is not
-- within an instance (all entities in instances are ignored)
and then Sloc (E) > No_Location
and then Instantiation_Location (Sloc (E)) = No_Location
-- And must be a non-internal name from the main source unit
and then In_Extended_Main_Source_Unit (E)
and then not Is_Internal_Name (Chars (E))
then
Add_Entry
((Ent => E,
Loc => No_Location,
Typ => ' ',
Eun => Get_Source_Unit (Original_Location (Sloc (E))),
Lun => No_Unit,
Ref_Scope => Empty,
Ent_Scope => Empty),
Ent_Scope_File => No_Unit);
if In_Inlined_Body then
Set_Referenced (E);
end if;
end if;
end Generate_Definition;
---------------------------------
-- Generate_Operator_Reference --
---------------------------------
procedure Generate_Operator_Reference
(N : Node_Id;
T : Entity_Id)
is
begin
if not In_Extended_Main_Source_Unit (N) then
return;
end if;
-- If the operator is not a Standard operator, then we generate a real
-- reference to the user defined operator.
if Sloc (Entity (N)) /= Standard_Location then
Generate_Reference (Entity (N), N);
-- A reference to an implicit inequality operator is also a reference
-- to the user-defined equality.
if Nkind (N) = N_Op_Ne
and then not Comes_From_Source (Entity (N))
and then Present (Corresponding_Equality (Entity (N)))
then
Generate_Reference (Corresponding_Equality (Entity (N)), N);
end if;
-- For the case of Standard operators, we mark the result type as
-- referenced. This ensures that in the case where we are using a
-- derived operator, we mark an entity of the unit that implicitly
-- defines this operator as used. Otherwise we may think that no entity
-- of the unit is used. The actual entity marked as referenced is the
-- first subtype, which is the relevant user defined entity.
-- Note: we only do this for operators that come from source. The
-- generated code sometimes reaches for entities that do not need to be
-- explicitly visible (for example, when we expand the code for
-- comparing two record objects, the fields of the record may not be
-- visible).
elsif Comes_From_Source (N) then
Set_Referenced (First_Subtype (T));
end if;
end Generate_Operator_Reference;
---------------------------------
-- Generate_Prim_Op_References --
---------------------------------
procedure Generate_Prim_Op_References (Typ : Entity_Id) is
Base_T : Entity_Id;
Prim : Elmt_Id;
Prim_List : Elist_Id;
begin
-- Handle subtypes of synchronized types
if Ekind (Typ) = E_Protected_Subtype
or else Ekind (Typ) = E_Task_Subtype
then
Base_T := Etype (Typ);
else
Base_T := Typ;
end if;
-- References to primitive operations are only relevant for tagged types
if not Is_Tagged_Type (Base_T)
or else Is_Class_Wide_Type (Base_T)
then
return;
end if;
-- Ada 2005 (AI-345): For synchronized types generate reference to the
-- wrapper that allow us to dispatch calls through their implemented
-- abstract interface types.
-- The check for Present here is to protect against previously reported
-- critical errors.
Prim_List := Primitive_Operations (Base_T);
if No (Prim_List) then
return;
end if;
Prim := First_Elmt (Prim_List);
while Present (Prim) loop
-- If the operation is derived, get the original for cross-reference
-- reference purposes (it is the original for which we want the xref
-- and for which the comes_from_source test must be performed).
Generate_Reference
(Typ, Ultimate_Alias (Node (Prim)), 'p', Set_Ref => False);
Next_Elmt (Prim);
end loop;
end Generate_Prim_Op_References;
------------------------
-- Generate_Reference --
------------------------
procedure Generate_Reference
(E : Entity_Id;
N : Node_Id;
Typ : Character := 'r';
Set_Ref : Boolean := True;
Force : Boolean := False)
is
Actual_Typ : Character := Typ;
Call : Node_Id;
Def : Source_Ptr;
Ent : Entity_Id;
Ent_Scope : Entity_Id;
Formal : Entity_Id;
Kind : Entity_Kind;
Nod : Node_Id;
Ref : Source_Ptr;
Ref_Scope : Entity_Id;
function Get_Through_Renamings (E : Entity_Id) return Entity_Id;
-- Get the enclosing entity through renamings, which may come from
-- source or from the translation of generic instantiations.
function Is_On_LHS (Node : Node_Id) return Boolean;
-- Used to check if a node is on the left hand side of an assignment.
-- The following cases are handled:
--
-- Variable Node is a direct descendant of left hand side of an
-- assignment statement.
--
-- Prefix Of an indexed or selected component that is present in
-- a subtree rooted by an assignment statement. There is
-- no restriction of nesting of components, thus cases
-- such as A.B (C).D are handled properly. However a prefix
-- of a dereference (either implicit or explicit) is never
-- considered as on a LHS.
--
-- Out param Same as above cases, but OUT parameter
function OK_To_Set_Referenced return Boolean;
-- Returns True if the Referenced flag can be set. There are a few
-- exceptions where we do not want to set this flag, see body for
-- details of these exceptional cases.
---------------------------
-- Get_Through_Renamings --
---------------------------
function Get_Through_Renamings (E : Entity_Id) return Entity_Id is
begin
case Ekind (E) is
-- For subprograms we just need to check once if they are have a
-- Renamed_Entity, because Renamed_Entity is set transitively.
when Subprogram_Kind =>
declare
Renamed : constant Entity_Id := Renamed_Entity (E);
begin
if Present (Renamed) then
return Renamed;
else
return E;
end if;
end;
-- For objects we need to repeatedly call Renamed_Object, because
-- it is not transitive.
when Object_Kind =>
declare
Obj : Entity_Id := E;
begin
loop
pragma Assert (Present (Obj));
declare
Renamed : constant Entity_Id := Renamed_Object (Obj);
begin
if Present (Renamed) then
Obj := Get_Enclosing_Object (Renamed);
-- The renamed expression denotes a non-object,
-- e.g. function call, slicing of a function call,
-- pointer dereference, etc.
if No (Obj) then
return Empty;
end if;
else
return Obj;
end if;
end;
end loop;
end;
when others =>
return E;
end case;
end Get_Through_Renamings;
---------------
-- Is_On_LHS --
---------------
-- ??? There are several routines here and there that perform a similar
-- (but subtly different) computation, which should be factored:
-- Sem_Util.Is_LHS
-- Sem_Util.May_Be_Lvalue
-- Sem_Util.Known_To_Be_Assigned
-- Exp_Ch2.Expand_Entry_Parameter.In_Assignment_Context
-- Exp_Smem.Is_Out_Actual
function Is_On_LHS (Node : Node_Id) return Boolean is
N : Node_Id;
P : Node_Id;
K : Node_Kind;
begin
-- Only identifiers are considered, is this necessary???
if Nkind (Node) /= N_Identifier then
return False;
end if;
-- Immediate return if appeared as OUT parameter
if Kind = E_Out_Parameter then
return True;
end if;
-- Search for assignment statement subtree root
N := Node;
loop
P := Parent (N);
K := Nkind (P);
if K = N_Assignment_Statement then
return Name (P) = N;
-- Check whether the parent is a component and the current node is
-- its prefix, but return False if the current node has an access
-- type, as in that case the selected or indexed component is an
-- implicit dereference, and the LHS is the designated object, not
-- the access object.
-- ??? case of a slice assignment?
elsif (K = N_Selected_Component or else K = N_Indexed_Component)
and then Prefix (P) = N
then
-- Check for access type. First a special test, In some cases
-- this is called too early (see comments in Find_Direct_Name),
-- at a point where the tree is not fully typed yet. In that
-- case we may lack an Etype for N, and we can't check the
-- Etype. For now, we always return False in such a case,
-- but this is clearly not right in all cases ???
if No (Etype (N)) then
return False;
elsif Is_Access_Type (Etype (N)) then
return False;
-- Access type case dealt with, keep going
else
N := P;
end if;
-- All other cases, definitely not on left side
else
return False;
end if;
end loop;
end Is_On_LHS;
---------------------------
-- OK_To_Set_Referenced --
---------------------------
function OK_To_Set_Referenced return Boolean is
P : Node_Id;
begin
-- A reference from a pragma Unreferenced or pragma Unmodified or
-- pragma Warnings does not cause the Referenced flag to be set.
-- This avoids silly warnings about things being referenced and
-- not assigned when the only reference is from the pragma.
if Nkind (N) = N_Identifier then
P := Parent (N);
if Nkind (P) = N_Pragma_Argument_Association then
P := Parent (P);
if Nkind (P) = N_Pragma then
if Pragma_Name_Unmapped (P) in Name_Warnings
| Name_Unmodified
| Name_Unreferenced
then
return False;
end if;
end if;
-- A reference to a formal in a named parameter association does
-- not make the formal referenced. Formals that are unused in the
-- subprogram body are properly flagged as such, even if calls
-- elsewhere use named notation.
elsif Nkind (P) = N_Parameter_Association
and then N = Selector_Name (P)
then
return False;
end if;
end if;
return True;
end OK_To_Set_Referenced;
-- Start of processing for Generate_Reference
begin
-- If Get_Ignore_Errors, then we are in Preanalyze_Without_Errors, and
-- we should not record cross references, because that will cause
-- duplicates when we call Analyze.
if Get_Ignore_Errors then
return;
end if;
-- May happen in case of severe errors
if Nkind (E) not in N_Entity then
return;
end if;
Find_Actual (N, Formal, Call);
if Present (Formal) then
Kind := Ekind (Formal);
else
Kind := E_Void;
end if;
-- Check for obsolescent reference to package ASCII. GNAT treats this
-- element of annex J specially since in practice, programs make a lot
-- of use of this feature, so we don't include it in the set of features
-- diagnosed when Warn_On_Obsolescent_Features mode is set. However we
-- are required to note it as a violation of the RM defined restriction.
if E = Standard_ASCII then
Check_Restriction (No_Obsolescent_Features, N);
end if;
-- Check for reference to entity marked with Is_Obsolescent
-- Note that we always allow obsolescent references in the compiler
-- itself and the run time, since we assume that we know what we are
-- doing in such cases. For example the calls in Ada.Characters.Handling
-- to its own obsolescent subprograms are just fine.
-- In any case we only generate warnings if we are in the extended main
-- source unit, and the entity itself is not in the extended main source
-- unit, since we assume the source unit itself knows what is going on
-- (and for sure we do not want silly warnings, e.g. on the end line of
-- an obsolescent procedure body).
if Is_Obsolescent (E)
and then not GNAT_Mode
and then not In_Extended_Main_Source_Unit (E)
and then In_Extended_Main_Source_Unit (N)
then
Check_Restriction (No_Obsolescent_Features, N);
if Warn_On_Obsolescent_Feature then
Output_Obsolescent_Entity_Warnings (N, E);
end if;
end if;
-- Warn if reference to Ada 2005 entity not in Ada 2005 mode. We only
-- detect real explicit references (modifications and references).
if Comes_From_Source (N)
and then Is_Ada_2005_Only (E)
and then Ada_Version < Ada_2005
and then Warn_On_Ada_2005_Compatibility
and then (Typ = 'm' or else Typ = 'r' or else Typ = 's')
then
Error_Msg_NE ("& is only defined in Ada 2005?y?", N, E);
end if;
-- Warn if reference to Ada 2012 entity not in Ada 2012 mode. We only
-- detect real explicit references (modifications and references).
if Comes_From_Source (N)
and then Is_Ada_2012_Only (E)
and then Ada_Version < Ada_2012
and then Warn_On_Ada_2012_Compatibility
and then (Typ = 'm' or else Typ = 'r')
then
Error_Msg_NE ("& is only defined in Ada 2012?y?", N, E);
end if;
-- Do not generate references if we are within a postcondition sub-
-- program, because the reference does not comes from source, and the
-- preanalysis of the aspect has already created an entry for the ALI
-- file at the proper source location.
if Chars (Current_Scope) = Name_uPostconditions then
return;
end if;
-- Never collect references if not in main source unit. However, we omit
-- this test if Typ is 'e' or 'k', since these entries are structural,
-- and it is useful to have them in units that reference packages as
-- well as units that define packages. We also omit the test for the
-- case of 'p' since we want to include inherited primitive operations
-- from other packages.
-- We also omit this test is this is a body reference for a subprogram
-- instantiation. In this case the reference is to the generic body,
-- which clearly need not be in the main unit containing the instance.
-- For the same reason we accept an implicit reference generated for
-- a default in an instance.
-- We also set the referenced flag in a generic package that is not in
-- then main source unit, when the variable is of a formal private type,
-- to warn in the instance if the corresponding type is not a fully
-- initialized type.
if not In_Extended_Main_Source_Unit (N) then
if Typ = 'e' or else
Typ = 'I' or else
Typ = 'p' or else
Typ = 'i' or else
Typ = 'k'
or else (Typ = 'b' and then Is_Generic_Instance (E))
-- Allow the generation of references to reads, writes and calls
-- in SPARK mode when the related context comes from an instance.
or else
(GNATprove_Mode
and then In_Extended_Main_Code_Unit (N)
and then (Typ = 'm' or else Typ = 'r' or else Typ = 's'))
then
null;
elsif In_Instance_Body
and then In_Extended_Main_Code_Unit (N)
and then Is_Generic_Type (Etype (E))
then
Set_Referenced (E);
return;
elsif Inside_A_Generic
and then Is_Generic_Type (Etype (E))
then
Set_Referenced (E);
return;
else
return;
end if;
end if;
-- For reference type p, the entity must be in main source unit
if Typ = 'p' and then not In_Extended_Main_Source_Unit (E) then
return;
end if;
-- Unless the reference is forced, we ignore references where the
-- reference itself does not come from source.
if not Force and then not Comes_From_Source (N) then
return;
end if;
-- Deal with setting entity as referenced, unless suppressed. Note that
-- we still do Set_Referenced on entities that do not come from source.
-- This situation arises when we have a source reference to a derived
-- operation, where the derived operation itself does not come from
-- source, but we still want to mark it as referenced, since we really
-- are referencing an entity in the corresponding package (this avoids
-- wrong complaints that the package contains no referenced entities).
if Set_Ref then
-- Assignable object appearing on left side of assignment or as
-- an out parameter.
if Is_Assignable (E)
and then Is_On_LHS (N)
and then Ekind (E) /= E_In_Out_Parameter
then
-- For objects that are renamings, just set as simply referenced
-- we do not try to do assignment type tracking in this case.
if Present (Renamed_Object (E)) then
Set_Referenced (E);
-- Out parameter case
elsif Kind = E_Out_Parameter then
-- If warning mode for all out parameters is set, or this is
-- the only warning parameter, then we want to mark this for
-- later warning logic by setting Referenced_As_Out_Parameter
if Warn_On_Modified_As_Out_Parameter (Formal) then
Set_Referenced_As_Out_Parameter (E, True);
Set_Referenced_As_LHS (E, False);
-- For OUT parameter not covered by the above cases, we simply
-- regard it as a normal reference (in this case we do not
-- want any of the warning machinery for out parameters).
else
Set_Referenced (E);
end if;
-- For the left hand of an assignment case, we do nothing here.
-- The processing for Analyze_Assignment_Statement will set the
-- Referenced_As_LHS flag.
else
null;
end if;
-- Check for a reference in a pragma that should not count as a
-- making the variable referenced for warning purposes.
elsif Is_Non_Significant_Pragma_Reference (N) then
null;
-- A reference in an attribute definition clause does not count as a
-- reference except for the case of Address. The reason that 'Address
-- is an exception is that it creates an alias through which the
-- variable may be referenced.
elsif Nkind (Parent (N)) = N_Attribute_Definition_Clause
and then Chars (Parent (N)) /= Name_Address
and then N = Name (Parent (N))
then
null;
-- Constant completion does not count as a reference
elsif Typ = 'c'
and then Ekind (E) = E_Constant
then
null;
-- Record representation clause does not count as a reference
elsif Nkind (N) = N_Identifier
and then Nkind (Parent (N)) = N_Record_Representation_Clause
then
null;
-- Discriminants do not need to produce a reference to record type
elsif Typ = 'd'
and then Nkind (Parent (N)) = N_Discriminant_Specification
then
null;
-- All other cases
else
-- Special processing for IN OUT parameters, where we have an
-- implicit assignment to a simple variable.
if Kind = E_In_Out_Parameter
and then Is_Assignable (E)
then
-- For sure this counts as a normal read reference
Set_Referenced (E);
Set_Last_Assignment (E, Empty);
-- We count it as being referenced as an out parameter if the
-- option is set to warn on all out parameters, except that we
-- have a special exclusion for an intrinsic subprogram, which
-- is most likely an instantiation of Unchecked_Deallocation
-- which we do not want to consider as an assignment since it
-- generates false positives. We also exclude the case of an
-- IN OUT parameter if the name of the procedure is Free,
-- since we suspect similar semantics.
if Warn_On_All_Unread_Out_Parameters
and then Is_Entity_Name (Name (Call))
and then not Is_Intrinsic_Subprogram (Entity (Name (Call)))
and then Chars (Name (Call)) /= Name_Free
then
Set_Referenced_As_Out_Parameter (E, True);
Set_Referenced_As_LHS (E, False);
end if;
-- Don't count a recursive reference within a subprogram as a
-- reference (that allows detection of a recursive subprogram
-- whose only references are recursive calls as unreferenced).
elsif Is_Subprogram (E)
and then E = Nearest_Dynamic_Scope (Current_Scope)
then
null;
-- Any other occurrence counts as referencing the entity
elsif OK_To_Set_Referenced then
Set_Referenced (E);
-- If variable, this is an OK reference after an assignment
-- so we can clear the Last_Assignment indication.
if Is_Assignable (E) then
Set_Last_Assignment (E, Empty);
end if;
end if;
end if;
-- Check for pragma Unreferenced given and reference is within
-- this source unit (occasion for possible warning to be issued).
-- Note that the entity may be marked as unreferenced by pragma
-- Unused.
if Has_Unreferenced (E)
and then In_Same_Extended_Unit (E, N)
then
-- A reference as a named parameter in a call does not count as a
-- violation of pragma Unreferenced for this purpose...
if Nkind (N) = N_Identifier
and then Nkind (Parent (N)) = N_Parameter_Association
and then Selector_Name (Parent (N)) = N
then
null;
-- ... Neither does a reference to a variable on the left side of
-- an assignment.
elsif Is_On_LHS (N) then
null;
-- Do not consider F'Result as a violation of pragma Unreferenced
-- since the attribute acts as an anonymous alias of the function
-- result and not as a real reference to the function.
elsif Ekind (E) in E_Function | E_Generic_Function
and then Is_Entity_Name (N)
and then Is_Attribute_Result (Parent (N))
then
null;
-- No warning if the reference is in a call that does not come
-- from source (e.g. a call to a controlled type primitive).
elsif not Comes_From_Source (Parent (N))
and then Nkind (Parent (N)) = N_Procedure_Call_Statement
then
null;
-- For entry formals, we want to place the warning message on the
-- corresponding entity in the accept statement. The current scope
-- is the body of the accept, so we find the formal whose name
-- matches that of the entry formal (there is no link between the
-- two entities, and the one in the accept statement is only used
-- for conformance checking).
elsif Ekind (Scope (E)) = E_Entry then
declare
BE : Entity_Id;
begin
BE := First_Entity (Current_Scope);
while Present (BE) loop
if Chars (BE) = Chars (E) then
if Has_Pragma_Unused (E) then
Error_Msg_NE -- CODEFIX
("??pragma Unused given for&!", N, BE);
else
Error_Msg_NE -- CODEFIX
("??pragma Unreferenced given for&!", N, BE);
end if;
exit;
end if;
Next_Entity (BE);
end loop;
end;
-- Here we issue the warning, since this is a real reference
elsif Has_Pragma_Unused (E) then
Error_Msg_NE -- CODEFIX
("??pragma Unused given for&!", N, E);
else
Error_Msg_NE -- CODEFIX
("??pragma Unreferenced given for&!", N, E);
end if;
end if;
-- If this is a subprogram instance, mark as well the internal
-- subprogram in the wrapper package, which may be a visible
-- compilation unit.
if Is_Overloadable (E)
and then Is_Generic_Instance (E)
and then Present (Alias (E))
then
Set_Referenced (Alias (E));
end if;
end if;
-- Generate reference if all conditions are met:
if
-- Cross referencing must be active
Opt.Xref_Active
-- The entity must be one for which we collect references
and then Xref_Entity_Letters (Ekind (E)) /= ' '
-- Both Sloc values must be set to something sensible
and then Sloc (E) > No_Location
and then Sloc (N) > No_Location
-- Ignore references from within an instance. The only exceptions to
-- this are default subprograms, for which we generate an implicit
-- reference and compilations in SPARK mode.
and then
(Instantiation_Location (Sloc (N)) = No_Location
or else Typ = 'i'
or else GNATprove_Mode)
-- Ignore dummy references
and then Typ /= ' '
then
if Nkind (N) in N_Identifier
| N_Defining_Identifier
| N_Defining_Operator_Symbol
| N_Operator_Symbol
| N_Defining_Character_Literal
| N_Op
or else (Nkind (N) = N_Character_Literal
and then Sloc (Entity (N)) /= Standard_Location)
then
Nod := N;
elsif Nkind (N) in N_Expanded_Name | N_Selected_Component then
Nod := Selector_Name (N);
else
return;
end if;
-- Normal case of source entity comes from source
if Comes_From_Source (E) then
Ent := E;
-- Because a declaration may be generated for a subprogram body
-- without declaration in GNATprove mode, for inlining, some
-- parameters may end up being marked as not coming from source
-- although they are. Take these into account specially.
elsif GNATprove_Mode and then Is_Formal (E) then
Ent := E;
-- Entity does not come from source, but is a derived subprogram and
-- the derived subprogram comes from source (after one or more
-- derivations) in which case the reference is to parent subprogram.
elsif Is_Overloadable (E)
and then Present (Alias (E))
then
Ent := Alias (E);
while not Comes_From_Source (Ent) loop
if No (Alias (Ent)) then
return;
end if;
Ent := Alias (Ent);
end loop;
-- The internally created defining entity for a child subprogram
-- that has no previous spec has valid references.
elsif Is_Overloadable (E)
and then Is_Child_Unit (E)
then
Ent := E;
-- Ditto for the formals of such a subprogram
elsif Is_Overloadable (Scope (E))
and then Is_Child_Unit (Scope (E))
then
Ent := E;
-- Record components of discriminated subtypes or derived types must
-- be treated as references to the original component.
elsif Ekind (E) = E_Component
and then Comes_From_Source (Original_Record_Component (E))
then
Ent := Original_Record_Component (E);
-- If this is an expanded reference to a discriminant, recover the
-- original discriminant, which gets the reference.
elsif Ekind (E) = E_In_Parameter
and then Present (Discriminal_Link (E))
then
Ent := Discriminal_Link (E);
Set_Referenced (Ent);
-- Ignore reference to any other entity that is not from source
else
return;
end if;
-- In SPARK mode, consider the underlying entity renamed instead of
-- the renaming, which is needed to compute a valid set of effects
-- (reads, writes) for the enclosing subprogram.
if GNATprove_Mode then
Ent := Get_Through_Renamings (Ent);
-- If no enclosing object, then it could be a reference to any
-- location not tracked individually, like heap-allocated data.
-- Conservatively approximate this possibility by generating a
-- dereference, and return.
if No (Ent) then
if Actual_Typ = 'w' then
SPARK_Specific.Generate_Dereference (Nod, 'r');
SPARK_Specific.Generate_Dereference (Nod, 'w');
else
SPARK_Specific.Generate_Dereference (Nod, 'r');
end if;
return;
end if;
end if;
-- Record reference to entity
if Actual_Typ = 'p'
and then Is_Subprogram (Nod)
and then Present (Overridden_Operation (Nod))
then
Actual_Typ := 'P';
end if;
-- Comment needed here for special SPARK code ???
if GNATprove_Mode then
-- Ignore references to an entity which is a Part_Of single
-- concurrent object. Ideally we would prefer to add it as a
-- reference to the corresponding concurrent type, but it is quite
-- difficult (as such references are not currently added even for)
-- reads/writes of private protected components) and not worth the
-- effort.
if Ekind (Ent) in E_Abstract_State | E_Constant | E_Variable
and then Present (Encapsulating_State (Ent))
and then Is_Single_Concurrent_Object (Encapsulating_State (Ent))
then
return;
end if;
Ref := Sloc (Nod);
Def := Sloc (Ent);
Ref_Scope :=
SPARK_Specific.Enclosing_Subprogram_Or_Library_Package (Nod);
Ent_Scope :=
SPARK_Specific.Enclosing_Subprogram_Or_Library_Package (Ent);
-- Since we are reaching through renamings in SPARK mode, we may
-- end up with standard constants. Ignore those.
if Sloc (Ent_Scope) <= Standard_Location
or else Def <= Standard_Location
then
return;
end if;
Add_Entry
((Ent => Ent,
Loc => Ref,
Typ => Actual_Typ,
Eun => Get_Top_Level_Code_Unit (Def),
Lun => Get_Top_Level_Code_Unit (Ref),
Ref_Scope => Ref_Scope,
Ent_Scope => Ent_Scope),
Ent_Scope_File => Get_Top_Level_Code_Unit (Ent));
else
Ref := Original_Location (Sloc (Nod));
Def := Original_Location (Sloc (Ent));
-- If this is an operator symbol, skip the initial quote for
-- navigation purposes. This is not done for the end label,
-- where we want the actual position after the closing quote.
if Typ = 't' then
null;
elsif Nkind (N) = N_Defining_Operator_Symbol
or else Nkind (Nod) = N_Operator_Symbol
then
Ref := Ref + 1;
end if;
Add_Entry
((Ent => Ent,
Loc => Ref,
Typ => Actual_Typ,
Eun => Get_Source_Unit (Def),
Lun => Get_Source_Unit (Ref),
Ref_Scope => Empty,
Ent_Scope => Empty),
Ent_Scope_File => No_Unit);
-- Generate reference to the first private entity
if Typ = 'e'
and then Comes_From_Source (E)
and then Nkind (Ent) = N_Defining_Identifier
and then (Is_Package_Or_Generic_Package (Ent)
or else Is_Concurrent_Type (Ent))
and then Present (First_Private_Entity (E))
and then In_Extended_Main_Source_Unit (N)
then
-- Handle case in which the full-view and partial-view of the
-- first private entity are swapped.
declare
First_Private : Entity_Id := First_Private_Entity (E);
begin
if Is_Private_Type (First_Private)
and then Present (Full_View (First_Private))
then
First_Private := Full_View (First_Private);
end if;
Add_Entry
((Ent => Ent,
Loc => Sloc (First_Private),
Typ => 'E',
Eun => Get_Source_Unit (Def),
Lun => Get_Source_Unit (Ref),
Ref_Scope => Empty,
Ent_Scope => Empty),
Ent_Scope_File => No_Unit);
end;
end if;
end if;
end if;
end Generate_Reference;
-----------------------------------
-- Generate_Reference_To_Formals --
-----------------------------------
procedure Generate_Reference_To_Formals (E : Entity_Id) is
Formal : Entity_Id;
begin
if Is_Generic_Subprogram (E) then
Formal := First_Entity (E);
while Present (Formal)
and then not Is_Formal (Formal)
loop
Next_Entity (Formal);
end loop;
elsif Ekind (E) in Access_Subprogram_Kind then
Formal := First_Formal (Designated_Type (E));
else
Formal := First_Formal (E);
end if;
while Present (Formal) loop
if Ekind (Formal) = E_In_Parameter then
if Nkind (Parameter_Type (Parent (Formal))) = N_Access_Definition
then
Generate_Reference (E, Formal, '^', False);
else
Generate_Reference (E, Formal, '>', False);
end if;
elsif Ekind (Formal) = E_In_Out_Parameter then
Generate_Reference (E, Formal, '=', False);
else
Generate_Reference (E, Formal, '<', False);
end if;
Next_Formal (Formal);
end loop;
end Generate_Reference_To_Formals;
-------------------------------------------
-- Generate_Reference_To_Generic_Formals --
-------------------------------------------
procedure Generate_Reference_To_Generic_Formals (E : Entity_Id) is
Formal : Entity_Id;
begin
Formal := First_Entity (E);
while Present (Formal) loop
if Comes_From_Source (Formal) then
Generate_Reference (E, Formal, 'z', False);
end if;
Next_Entity (Formal);
end loop;
end Generate_Reference_To_Generic_Formals;
-------------
-- Get_Key --
-------------
function Get_Key (E : Xref_Entry_Number) return Xref_Entry_Number is
begin
return E;
end Get_Key;
----------------------------
-- Has_Deferred_Reference --
----------------------------
function Has_Deferred_Reference (Ent : Entity_Id) return Boolean is
begin
for J in Deferred_References.First .. Deferred_References.Last loop
if Deferred_References.Table (J).E = Ent then
return True;
end if;
end loop;
return False;
end Has_Deferred_Reference;
----------
-- Hash --
----------
function Hash (F : Xref_Entry_Number) return Header_Num is
-- It is unlikely to have two references to the same entity at the same
-- source location, so the hash function depends only on the Ent and Loc
-- fields.
XE : Xref_Entry renames Xrefs.Table (F);
type M is mod 2**32;
H : constant M := M (XE.Key.Ent) + 2 ** 7 * M (abs XE.Key.Loc);
-- It would be more natural to write:
--
-- H : constant M := M'Mod (XE.Key.Ent) + 2**7 * M'Mod (XE.Key.Loc);
--
-- But we can't use M'Mod, because it prevents bootstrapping with older
-- compilers. Loc can be negative, so we do "abs" before converting.
-- One day this can be cleaned up ???
begin
return Header_Num (H mod Num_Buckets);
end Hash;
-----------------
-- HT_Set_Next --
-----------------
procedure HT_Set_Next (E : Xref_Entry_Number; Next : Xref_Entry_Number) is
begin
Xrefs.Table (E).HTable_Next := Next;
end HT_Set_Next;
-------------
-- HT_Next --
-------------
function HT_Next (E : Xref_Entry_Number) return Xref_Entry_Number is
begin
return Xrefs.Table (E).HTable_Next;
end HT_Next;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Xrefs.Init;
end Initialize;
--------
-- Lt --
--------
function Lt (T1, T2 : Xref_Entry) return Boolean is
begin
-- First test: if entity is in different unit, sort by unit
if T1.Key.Eun /= T2.Key.Eun then
return Dependency_Num (T1.Key.Eun) < Dependency_Num (T2.Key.Eun);
-- Second test: within same unit, sort by entity Sloc
elsif T1.Def /= T2.Def then
return T1.Def < T2.Def;
-- Third test: sort definitions ahead of references
elsif T1.Key.Loc = No_Location then
return True;
elsif T2.Key.Loc = No_Location then
return False;
-- Fourth test: for same entity, sort by reference location unit
elsif T1.Key.Lun /= T2.Key.Lun then
return Dependency_Num (T1.Key.Lun) < Dependency_Num (T2.Key.Lun);
-- Fifth test: order of location within referencing unit
elsif T1.Key.Loc /= T2.Key.Loc then
return T1.Key.Loc < T2.Key.Loc;
-- Finally, for two locations at the same address, we prefer
-- the one that does NOT have the type 'r' so that a modification
-- or extension takes preference, when there are more than one
-- reference at the same location. As a result, in the case of
-- entities that are in-out actuals, the read reference follows
-- the modify reference.
else
return T2.Key.Typ = 'r';
end if;
end Lt;
-----------------------
-- Output_References --
-----------------------
procedure Output_References is
procedure Get_Type_Reference
(Ent : Entity_Id;
Tref : out Entity_Id;
Left : out Character;
Right : out Character);
-- Given an Entity_Id Ent, determines whether a type reference is
-- required. If so, Tref is set to the entity for the type reference
-- and Left and Right are set to the left/right brackets to be output
-- for the reference. If no type reference is required, then Tref is
-- set to Empty, and Left/Right are set to space.
procedure Output_Import_Export_Info (Ent : Entity_Id);
-- Output language and external name information for an interfaced
-- entity, using the format <language, external_name>.
------------------------
-- Get_Type_Reference --
------------------------
procedure Get_Type_Reference
(Ent : Entity_Id;
Tref : out Entity_Id;
Left : out Character;
Right : out Character)
is
Sav : Entity_Id;
begin
-- See if we have a type reference
Tref := Ent;
Left := '{';
Right := '}';
loop
Sav := Tref;
-- Processing for types
if Is_Type (Tref) then
-- Case of base type
if Base_Type (Tref) = Tref then
-- If derived, then get first subtype
if Tref /= Etype (Tref) then
Tref := First_Subtype (Etype (Tref));
-- Set brackets for derived type, but don't override
-- pointer case since the fact that something is a
-- pointer is more important.
if Left /= '(' then
Left := '<';
Right := '>';
end if;
-- If the completion of a private type is itself a derived
-- type, we need the parent of the full view.
elsif Is_Private_Type (Tref)
and then Present (Full_View (Tref))
and then Etype (Full_View (Tref)) /= Full_View (Tref)
then
Tref := Etype (Full_View (Tref));
if Left /= '(' then
Left := '<';
Right := '>';
end if;
-- If non-derived pointer, get directly designated type.
-- If the type has a full view, all references are on the
-- partial view that is seen first.
elsif Is_Access_Type (Tref) then
Tref := Directly_Designated_Type (Tref);
Left := '(';
Right := ')';
elsif Is_Private_Type (Tref)
and then Present (Full_View (Tref))
then
if Is_Access_Type (Full_View (Tref)) then
Tref := Directly_Designated_Type (Full_View (Tref));
Left := '(';
Right := ')';
-- If the full view is an array type, we also retrieve
-- the corresponding component type, because the ali
-- entry already indicates that this is an array.
elsif Is_Array_Type (Full_View (Tref)) then
Tref := Component_Type (Full_View (Tref));
Left := '(';
Right := ')';
end if;
-- If non-derived array, get component type. Skip component
-- type for case of String or Wide_String, saves worthwhile
-- space.
elsif Is_Array_Type (Tref)
and then Tref /= Standard_String
and then Tref /= Standard_Wide_String
then
Tref := Component_Type (Tref);
Left := '(';
Right := ')';
-- For other non-derived base types, nothing
else
exit;
end if;
-- For a subtype, go to ancestor subtype
else
Tref := Ancestor_Subtype (Tref);
-- If no ancestor subtype, go to base type
if No (Tref) then
Tref := Base_Type (Sav);
end if;
end if;
-- For objects, functions, enum literals, just get type from
-- Etype field.
elsif Is_Object (Tref)
or else Ekind (Tref) = E_Enumeration_Literal
or else Ekind (Tref) = E_Function
or else Ekind (Tref) = E_Operator
then
Tref := Etype (Tref);
-- Another special case: an object of a classwide type
-- initialized with a tag-indeterminate call gets a subtype
-- of the classwide type during expansion. See if the original
-- type in the declaration is named, and return it instead
-- of going to the root type. The expression may be a class-
-- wide function call whose result is on the secondary stack,
-- which forces the declaration to be rewritten as a renaming,
-- so examine the source declaration.
if Ekind (Tref) = E_Class_Wide_Subtype then
declare
Decl : constant Node_Id := Original_Node (Parent (Ent));
begin
if Nkind (Decl) = N_Object_Declaration
and then Is_Entity_Name
(Original_Node (Object_Definition (Decl)))
then
Tref :=
Entity (Original_Node (Object_Definition (Decl)));
end if;
end;
-- For a function that returns a class-wide type, Tref is
-- already correct.
elsif Is_Overloadable (Ent)
and then Is_Class_Wide_Type (Tref)
then
return;
end if;
-- For anything else, exit
else
exit;
end if;
-- Exit if no type reference, or we are stuck in some loop trying
-- to find the type reference, or if the type is standard void
-- type (the latter is an implementation artifact that should not
-- show up in the generated cross-references).
exit when No (Tref)
or else Tref = Sav
or else Tref = Standard_Void_Type;
-- If we have a usable type reference, return, otherwise keep
-- looking for something useful (we are looking for something
-- that either comes from source or standard)
if Sloc (Tref) = Standard_Location
or else Comes_From_Source (Tref)
then
-- If the reference is a subtype created for a generic actual,
-- go actual directly, the inner subtype is not user visible.
if Nkind (Parent (Tref)) = N_Subtype_Declaration
and then not Comes_From_Source (Parent (Tref))
and then
(Is_Wrapper_Package (Scope (Tref))
or else Is_Generic_Instance (Scope (Tref)))
then
Tref := First_Subtype (Base_Type (Tref));
end if;
return;
end if;
end loop;
-- If we fall through the loop, no type reference
Tref := Empty;
Left := ' ';
Right := ' ';
end Get_Type_Reference;
-------------------------------
-- Output_Import_Export_Info --
-------------------------------
procedure Output_Import_Export_Info (Ent : Entity_Id) is
Language_Name : Name_Id;
Conv : constant Convention_Id := Convention (Ent);
begin
-- Generate language name from convention
if Conv = Convention_C or else Conv in Convention_C_Variadic then
Language_Name := Name_C;
elsif Conv = Convention_CPP then
Language_Name := Name_CPP;
elsif Conv = Convention_Ada then
Language_Name := Name_Ada;
else
-- For the moment we ignore all other cases ???
return;
end if;
Write_Info_Char ('<');
Get_Unqualified_Name_String (Language_Name);
for J in 1 .. Name_Len loop
Write_Info_Char (Name_Buffer (J));
end loop;
if Present (Interface_Name (Ent)) then
Write_Info_Char (',');
String_To_Name_Buffer (Strval (Interface_Name (Ent)));
for J in 1 .. Name_Len loop
Write_Info_Char (Name_Buffer (J));
end loop;
end if;
Write_Info_Char ('>');
end Output_Import_Export_Info;
-- Start of processing for Output_References
begin
-- First we add references to the primitive operations of tagged types
-- declared in the main unit.
Handle_Prim_Ops : declare
Ent : Entity_Id;
begin
for J in 1 .. Xrefs.Last loop
Ent := Xrefs.Table (J).Key.Ent;
if Is_Type (Ent)
and then Is_Tagged_Type (Ent)
and then Is_Base_Type (Ent)
and then In_Extended_Main_Source_Unit (Ent)
then
Generate_Prim_Op_References (Ent);
end if;
end loop;
end Handle_Prim_Ops;
-- Before we go ahead and output the references we have a problem
-- that needs dealing with. So far we have captured things that are
-- definitely referenced by the main unit, or defined in the main
-- unit. That's because we don't want to clutter up the ali file
-- for this unit with definition lines for entities in other units
-- that are not referenced.
-- But there is a glitch. We may reference an entity in another unit,
-- and it may have a type reference to an entity that is not directly
-- referenced in the main unit, which may mean that there is no xref
-- entry for this entity yet in the list of references.
-- If we don't do something about this, we will end with an orphan type
-- reference, i.e. it will point to an entity that does not appear
-- within the generated references in the ali file. That is not good for
-- tools using the xref information.
-- To fix this, we go through the references adding definition entries
-- for any unreferenced entities that can be referenced in a type
-- reference. There is a recursion problem here, and that is dealt with
-- by making sure that this traversal also traverses any entries that
-- get added by the traversal.
Handle_Orphan_Type_References : declare
J : Nat;
Tref : Entity_Id;
Ent : Entity_Id;
L, R : Character;
pragma Warnings (Off, L);
pragma Warnings (Off, R);
procedure New_Entry (E : Entity_Id);
-- Make an additional entry into the Xref table for a type entity
-- that is related to the current entity (parent, type ancestor,
-- progenitor, etc.).
----------------
-- New_Entry --
----------------
procedure New_Entry (E : Entity_Id) is
begin
pragma Assert (Present (E));
if not Has_Xref_Entry (Implementation_Base_Type (E))
and then Sloc (E) > No_Location
then
Add_Entry
((Ent => E,
Loc => No_Location,
Typ => Character'First,
Eun => Get_Source_Unit (Original_Location (Sloc (E))),
Lun => No_Unit,
Ref_Scope => Empty,
Ent_Scope => Empty),
Ent_Scope_File => No_Unit);
end if;
end New_Entry;
-- Start of processing for Handle_Orphan_Type_References
begin
-- Note that this is not a for loop for a very good reason. The
-- processing of items in the table can add new items to the table,
-- and they must be processed as well.
J := 1;
while J <= Xrefs.Last loop
Ent := Xrefs.Table (J).Key.Ent;
-- Do not generate reference information for an ignored Ghost
-- entity because neither the entity nor its references will
-- appear in the final tree.
if Is_Ignored_Ghost_Entity (Ent) then
goto Orphan_Continue;
end if;
Get_Type_Reference (Ent, Tref, L, R);
if Present (Tref)
and then not Has_Xref_Entry (Tref)
and then Sloc (Tref) > No_Location
then
New_Entry (Tref);
if Is_Record_Type (Ent)
and then Present (Interfaces (Ent))
then
-- Add an entry for each one of the given interfaces
-- implemented by type Ent.
declare
Elmt : Elmt_Id := First_Elmt (Interfaces (Ent));
begin
while Present (Elmt) loop
New_Entry (Node (Elmt));
Next_Elmt (Elmt);
end loop;
end;
end if;
end if;
-- Collect inherited primitive operations that may be declared in
-- another unit and have no visible reference in the current one.
if Is_Type (Ent)
and then Is_Tagged_Type (Ent)
and then Is_Derived_Type (Ent)
and then Is_Base_Type (Ent)
and then In_Extended_Main_Source_Unit (Ent)
then
declare
Op_List : constant Elist_Id := Primitive_Operations (Ent);
Op : Elmt_Id;
Prim : Entity_Id;
function Parent_Op (E : Entity_Id) return Entity_Id;
-- Find original operation, which may be inherited through
-- several derivations.
function Parent_Op (E : Entity_Id) return Entity_Id is
Orig_Op : constant Entity_Id := Alias (E);
begin
if No (Orig_Op) then
return Empty;
elsif not Comes_From_Source (E)
and then not Has_Xref_Entry (Orig_Op)
and then Comes_From_Source (Orig_Op)
then
return Orig_Op;
else
return Parent_Op (Orig_Op);
end if;
end Parent_Op;
begin
Op := First_Elmt (Op_List);
while Present (Op) loop
Prim := Parent_Op (Node (Op));
if Present (Prim) then
Add_Entry
((Ent => Prim,
Loc => No_Location,
Typ => Character'First,
Eun => Get_Source_Unit (Sloc (Prim)),
Lun => No_Unit,
Ref_Scope => Empty,
Ent_Scope => Empty),
Ent_Scope_File => No_Unit);
end if;
Next_Elmt (Op);
end loop;
end;
end if;
<<Orphan_Continue>>
J := J + 1;
end loop;
end Handle_Orphan_Type_References;
-- Now we have all the references, including those for any embedded type
-- references, so we can sort them, and output them.
Output_Refs : declare
Nrefs : constant Nat := Xrefs.Last;
-- Number of references in table
Rnums : array (0 .. Nrefs) of Nat;
-- This array contains numbers of references in the Xrefs table.
-- This list is sorted in output order. The extra 0'th entry is
-- convenient for the call to sort. When we sort the table, we
-- move the entries in Rnums around, but we do not move the
-- original table entries.
Curxu : Unit_Number_Type;
-- Current xref unit
Curru : Unit_Number_Type;
-- Current reference unit for one entity
Curent : Entity_Id;
-- Current entity
Curnam : String (1 .. Name_Buffer'Length);
Curlen : Natural;
-- Simple name and length of current entity
Curdef : Source_Ptr;
-- Original source location for current entity
Crloc : Source_Ptr;
-- Current reference location
Ctyp : Character;
-- Entity type character
Prevt : Character;
-- reference kind of previous reference
Tref : Entity_Id;
-- Type reference
Rref : Node_Id;
-- Renaming reference
Trunit : Unit_Number_Type;
-- Unit number for type reference
function Lt (Op1, Op2 : Natural) return Boolean;
-- Comparison function for Sort call
function Name_Change (X : Entity_Id) return Boolean;
-- Determines if entity X has a different simple name from Curent
procedure Move (From : Natural; To : Natural);
-- Move procedure for Sort call
package Sorting is new GNAT.Heap_Sort_G (Move, Lt);
--------
-- Lt --
--------
function Lt (Op1, Op2 : Natural) return Boolean is
T1 : Xref_Entry renames Xrefs.Table (Rnums (Nat (Op1)));
T2 : Xref_Entry renames Xrefs.Table (Rnums (Nat (Op2)));
begin
return Lt (T1, T2);
end Lt;
----------
-- Move --
----------
procedure Move (From : Natural; To : Natural) is
begin
Rnums (Nat (To)) := Rnums (Nat (From));
end Move;
-----------------
-- Name_Change --
-----------------
-- Why a string comparison here??? Why not compare Name_Id values???
function Name_Change (X : Entity_Id) return Boolean is
begin
Get_Unqualified_Name_String (Chars (X));
if Name_Len /= Curlen then
return True;
else
return Name_Buffer (1 .. Curlen) /= Curnam (1 .. Curlen);
end if;
end Name_Change;
-- Start of processing for Output_Refs
begin
-- Capture the definition Sloc values. We delay doing this till now,
-- since at the time the reference or definition is made, private
-- types may be swapped, and the Sloc value may be incorrect. We
-- also set up the pointer vector for the sort.
-- For user-defined operators we need to skip the initial quote and
-- point to the first character of the name, for navigation purposes.
for J in 1 .. Nrefs loop
declare
E : constant Entity_Id := Xrefs.Table (J).Key.Ent;
Loc : constant Source_Ptr := Original_Location (Sloc (E));
begin
Rnums (J) := J;
if Nkind (E) = N_Defining_Operator_Symbol then
Xrefs.Table (J).Def := Loc + 1;
else
Xrefs.Table (J).Def := Loc;
end if;
end;
end loop;
-- Sort the references
Sorting.Sort (Integer (Nrefs));
-- Initialize loop through references
Curxu := No_Unit;
Curent := Empty;
Curdef := No_Location;
Curru := No_Unit;
Crloc := No_Location;
Prevt := 'm';
-- Loop to output references
for Refno in 1 .. Nrefs loop
Output_One_Ref : declare
Ent : Entity_Id;
XE : Xref_Entry renames Xrefs.Table (Rnums (Refno));
-- The current entry to be accessed
Left : Character;
Right : Character;
-- Used for {} or <> or () for type reference
procedure Check_Type_Reference
(Ent : Entity_Id;
List_Interface : Boolean;
Is_Component : Boolean := False);
-- Find whether there is a meaningful type reference for
-- Ent, and display it accordingly. If List_Interface is
-- true, then Ent is a progenitor interface of the current
-- type entity being listed. In that case list it as is,
-- without looking for a type reference for it. Flag is also
-- used for index types of an array type, where the caller
-- supplies the intended type reference. Is_Component serves
-- the same purpose, to display the component type of a
-- derived array type, for which only the parent type has
-- ben displayed so far.
procedure Output_Instantiation_Refs (Loc : Source_Ptr);
-- Recursive procedure to output instantiation references for
-- the given source ptr in [file|line[...]] form. No output
-- if the given location is not a generic template reference.
procedure Output_Overridden_Op (Old_E : Entity_Id);
-- For a subprogram that is overriding, display information
-- about the inherited operation that it overrides.
--------------------------
-- Check_Type_Reference --
--------------------------
procedure Check_Type_Reference
(Ent : Entity_Id;
List_Interface : Boolean;
Is_Component : Boolean := False)
is
begin
if List_Interface then
-- This is a progenitor interface of the type for which
-- xref information is being generated.
Tref := Ent;
Left := '<';
Right := '>';
-- The following is not documented in lib-xref.ads ???
elsif Is_Component then
Tref := Ent;
Left := '(';
Right := ')';
else
Get_Type_Reference (Ent, Tref, Left, Right);
end if;
if Present (Tref) then
-- Case of standard entity, output name
if Sloc (Tref) = Standard_Location then
Write_Info_Char (Left);
Write_Info_Name (Chars (Tref));
Write_Info_Char (Right);
-- Case of source entity, output location
else
Write_Info_Char (Left);
Trunit := Get_Source_Unit (Sloc (Tref));
if Trunit /= Curxu then
Write_Info_Nat (Dependency_Num (Trunit));
Write_Info_Char ('|');
end if;
Write_Info_Nat
(Int (Get_Logical_Line_Number (Sloc (Tref))));
declare
Ent : Entity_Id;
Ctyp : Character;
begin
Ent := Tref;
Ctyp := Xref_Entity_Letters (Ekind (Ent));
if Ctyp = '+'
and then Present (Full_View (Ent))
then
Ent := Underlying_Type (Ent);
if Present (Ent) then
Ctyp := Xref_Entity_Letters (Ekind (Ent));
end if;
end if;
Write_Info_Char (Ctyp);
end;
Write_Info_Nat
(Int (Get_Column_Number (Sloc (Tref))));
-- If the type comes from an instantiation, add the
-- corresponding info.
Output_Instantiation_Refs (Sloc (Tref));
Write_Info_Char (Right);
end if;
end if;
end Check_Type_Reference;
-------------------------------
-- Output_Instantiation_Refs --
-------------------------------
procedure Output_Instantiation_Refs (Loc : Source_Ptr) is
Iloc : constant Source_Ptr := Instantiation_Location (Loc);
Lun : Unit_Number_Type;
Cu : constant Unit_Number_Type := Curru;
begin
-- Nothing to do if this is not an instantiation
if Iloc = No_Location then
return;
end if;
-- Output instantiation reference
Write_Info_Char ('[');
Lun := Get_Source_Unit (Iloc);
if Lun /= Curru then
Curru := Lun;
Write_Info_Nat (Dependency_Num (Curru));
Write_Info_Char ('|');
end if;
Write_Info_Nat (Int (Get_Logical_Line_Number (Iloc)));
-- Recursive call to get nested instantiations
Output_Instantiation_Refs (Iloc);
-- Output final ] after call to get proper nesting
Write_Info_Char (']');
Curru := Cu;
return;
end Output_Instantiation_Refs;
--------------------------
-- Output_Overridden_Op --
--------------------------
procedure Output_Overridden_Op (Old_E : Entity_Id) is
Op : Entity_Id;
begin
-- The overridden operation has an implicit declaration
-- at the point of derivation. What we want to display
-- is the original operation, which has the actual body
-- (or abstract declaration) that is being overridden.
-- The overridden operation is not always set, e.g. when
-- it is a predefined operator.
if No (Old_E) then
return;
-- Follow alias chain if one is present
elsif Present (Alias (Old_E)) then
-- The subprogram may have been implicitly inherited
-- through several levels of derivation, so find the
-- ultimate (source) ancestor.
Op := Ultimate_Alias (Old_E);
-- Normal case of no alias present. We omit generated
-- primitives like tagged equality, that have no source
-- representation.
else
Op := Old_E;
end if;
if Present (Op)
and then Sloc (Op) /= Standard_Location
and then Comes_From_Source (Op)
then
declare
Loc : constant Source_Ptr := Sloc (Op);
Par_Unit : constant Unit_Number_Type :=
Get_Source_Unit (Loc);
begin
Write_Info_Char ('<');
if Par_Unit /= Curxu then
Write_Info_Nat (Dependency_Num (Par_Unit));
Write_Info_Char ('|');
end if;
Write_Info_Nat (Int (Get_Logical_Line_Number (Loc)));
Write_Info_Char ('p');
Write_Info_Nat (Int (Get_Column_Number (Loc)));
Write_Info_Char ('>');
end;
end if;
end Output_Overridden_Op;
-- Start of processing for Output_One_Ref
begin
Ent := XE.Key.Ent;
-- Do not generate reference information for an ignored Ghost
-- entity because neither the entity nor its references will
-- appear in the final tree.
if Is_Ignored_Ghost_Entity (Ent) then
goto Continue;
end if;
Ctyp := Xref_Entity_Letters (Ekind (Ent));
-- Skip reference if it is the only reference to an entity,
-- and it is an END line reference, and the entity is not in
-- the current extended source. This prevents junk entries
-- consisting only of packages with END lines, where no
-- entity from the package is actually referenced.
if XE.Key.Typ = 'e'
and then Ent /= Curent
and then (Refno = Nrefs
or else
Ent /= Xrefs.Table (Rnums (Refno + 1)).Key.Ent)
and then not In_Extended_Main_Source_Unit (Ent)
then
goto Continue;
end if;
-- For private type, get full view type
if Ctyp = '+'
and then Present (Full_View (XE.Key.Ent))
then
Ent := Underlying_Type (Ent);
if Present (Ent) then
Ctyp := Xref_Entity_Letters (Ekind (Ent));
end if;
end if;
-- Special exception for Boolean
if Ctyp = 'E' and then Is_Boolean_Type (Ent) then
Ctyp := 'B';
end if;
-- For variable reference, get corresponding type
if Ctyp = '*' then
Ent := Etype (XE.Key.Ent);
Ctyp := Fold_Lower (Xref_Entity_Letters (Ekind (Ent)));
-- If variable is private type, get full view type
if Ctyp = '+'
and then Present (Full_View (Etype (XE.Key.Ent)))
then
Ent := Underlying_Type (Etype (XE.Key.Ent));
if Present (Ent) then
Ctyp := Fold_Lower (Xref_Entity_Letters (Ekind (Ent)));
end if;
elsif Is_Generic_Type (Ent) then
-- If the type of the entity is a generic private type,
-- there is no usable full view, so retain the indication
-- that this is an object.
Ctyp := '*';
end if;
-- Special handling for access parameters and objects and
-- components of an anonymous access type.
if Ekind (Etype (XE.Key.Ent)) in
E_Anonymous_Access_Type
| E_Anonymous_Access_Subprogram_Type
| E_Anonymous_Access_Protected_Subprogram_Type
then
if Is_Formal (XE.Key.Ent)
or else
Ekind (XE.Key.Ent) in
E_Variable | E_Constant | E_Component
then
Ctyp := 'p';
end if;
-- Special handling for Boolean
elsif Ctyp = 'e' and then Is_Boolean_Type (Ent) then
Ctyp := 'b';
end if;
end if;
-- Special handling for abstract types and operations
if Is_Overloadable (XE.Key.Ent)
and then Is_Abstract_Subprogram (XE.Key.Ent)
then
if Ctyp = 'U' then
Ctyp := 'x'; -- Abstract procedure
elsif Ctyp = 'V' then
Ctyp := 'y'; -- Abstract function
end if;
elsif Is_Type (XE.Key.Ent)
and then Is_Abstract_Type (XE.Key.Ent)
then
if Is_Interface (XE.Key.Ent) then
Ctyp := 'h';
elsif Ctyp = 'R' then
Ctyp := 'H'; -- Abstract type
end if;
end if;
-- Only output reference if interesting type of entity
if Ctyp = ' '
-- Suppress references to object definitions, used for local
-- references.
or else XE.Key.Typ = 'D'
or else XE.Key.Typ = 'I'
-- Suppress self references, except for bodies that act as
-- specs.
or else (XE.Key.Loc = XE.Def
and then
(XE.Key.Typ /= 'b'
or else not Is_Subprogram (XE.Key.Ent)))
-- Also suppress definitions of body formals (we only
-- treat these as references, and the references were
-- separately recorded).
or else (Is_Formal (XE.Key.Ent)
and then Present (Spec_Entity (XE.Key.Ent)))
then
null;
else
-- Start new Xref section if new xref unit
if XE.Key.Eun /= Curxu then
if Write_Info_Col > 1 then
Write_Info_EOL;
end if;
Curxu := XE.Key.Eun;
Write_Info_Initiate ('X');
Write_Info_Char (' ');
Write_Info_Nat (Dependency_Num (XE.Key.Eun));
Write_Info_Char (' ');
Write_Info_Name
(Reference_Name (Source_Index (XE.Key.Eun)));
end if;
-- Start new Entity line if new entity. Note that we
-- consider two entities the same if they have the same
-- name and source location. This causes entities in
-- instantiations to be treated as though they referred
-- to the template.
if No (Curent)
or else
(XE.Key.Ent /= Curent
and then
(Name_Change (XE.Key.Ent) or else XE.Def /= Curdef))
then
Curent := XE.Key.Ent;
Curdef := XE.Def;
Get_Unqualified_Name_String (Chars (XE.Key.Ent));
Curlen := Name_Len;
Curnam (1 .. Curlen) := Name_Buffer (1 .. Curlen);
if Write_Info_Col > 1 then
Write_Info_EOL;
end if;
-- Write column number information
Write_Info_Nat (Int (Get_Logical_Line_Number (XE.Def)));
Write_Info_Char (Ctyp);
Write_Info_Nat (Int (Get_Column_Number (XE.Def)));
-- Write level information
Write_Level_Info : declare
function Is_Visible_Generic_Entity
(E : Entity_Id) return Boolean;
-- Check whether E is declared in the visible part
-- of a generic package. For source navigation
-- purposes, treat this as a visible entity.
function Is_Private_Record_Component
(E : Entity_Id) return Boolean;
-- Check whether E is a non-inherited component of a
-- private extension. Even if the enclosing record is
-- public, we want to treat the component as private
-- for navigation purposes.
---------------------------------
-- Is_Private_Record_Component --
---------------------------------
function Is_Private_Record_Component
(E : Entity_Id) return Boolean
is
S : constant Entity_Id := Scope (E);
begin
return
Ekind (E) = E_Component
and then Nkind (Declaration_Node (S)) =
N_Private_Extension_Declaration
and then Original_Record_Component (E) = E;
end Is_Private_Record_Component;
-------------------------------
-- Is_Visible_Generic_Entity --
-------------------------------
function Is_Visible_Generic_Entity
(E : Entity_Id) return Boolean
is
Par : Node_Id;
begin
-- The Present check here is an error defense
if Present (Scope (E))
and then Ekind (Scope (E)) /= E_Generic_Package
then
return False;
end if;
Par := Parent (E);
while Present (Par) loop
if
Nkind (Par) = N_Generic_Package_Declaration
then
-- Entity is a generic formal
return False;
elsif
Nkind (Parent (Par)) = N_Package_Specification
then
return
Is_List_Member (Par)
and then List_Containing (Par) =
Visible_Declarations (Parent (Par));
else
Par := Parent (Par);
end if;
end loop;
return False;
end Is_Visible_Generic_Entity;
-- Start of processing for Write_Level_Info
begin
if Is_Hidden (Curent)
or else Is_Private_Record_Component (Curent)
then
Write_Info_Char (' ');
elsif
Is_Public (Curent)
or else Is_Visible_Generic_Entity (Curent)
then
Write_Info_Char ('*');
else
Write_Info_Char (' ');
end if;
end Write_Level_Info;
-- Output entity name. We use the occurrence from the
-- actual source program at the definition point.
declare
Ent_Name : constant String :=
Exact_Source_Name (Sloc (XE.Key.Ent));
begin
for C in Ent_Name'Range loop
Write_Info_Char (Ent_Name (C));
end loop;
end;
-- See if we have a renaming reference
if Is_Object (XE.Key.Ent)
and then Present (Renamed_Object (XE.Key.Ent))
then
Rref := Renamed_Object (XE.Key.Ent);
elsif Is_Overloadable (XE.Key.Ent)
and then Nkind (Parent (Declaration_Node (XE.Key.Ent)))
= N_Subprogram_Renaming_Declaration
then
Rref := Name (Parent (Declaration_Node (XE.Key.Ent)));
elsif Ekind (XE.Key.Ent) = E_Package
and then Nkind (Declaration_Node (XE.Key.Ent)) =
N_Package_Renaming_Declaration
then
Rref := Name (Declaration_Node (XE.Key.Ent));
else
Rref := Empty;
end if;
if Present (Rref) then
if Nkind (Rref) = N_Expanded_Name then
Rref := Selector_Name (Rref);
end if;
if Nkind (Rref) = N_Identifier
or else Nkind (Rref) = N_Operator_Symbol
then
null;
-- For renamed array components, use the array name
-- for the renamed entity, which reflect the fact that
-- in general the whole array is aliased.
elsif Nkind (Rref) = N_Indexed_Component then
if Nkind (Prefix (Rref)) = N_Identifier then
Rref := Prefix (Rref);
elsif Nkind (Prefix (Rref)) = N_Expanded_Name then
Rref := Selector_Name (Prefix (Rref));
else
Rref := Empty;
end if;
else
Rref := Empty;
end if;
end if;
-- Write out renaming reference if we have one
if Present (Rref) then
Write_Info_Char ('=');
Write_Info_Nat
(Int (Get_Logical_Line_Number (Sloc (Rref))));
Write_Info_Char (':');
Write_Info_Nat
(Int (Get_Column_Number (Sloc (Rref))));
end if;
-- Indicate that the entity is in the unit of the current
-- xref section.
Curru := Curxu;
-- Write out information about generic parent, if entity
-- is an instance.
if Is_Generic_Instance (XE.Key.Ent) then
declare
Gen_Par : constant Entity_Id :=
Generic_Parent
(Specification
(Unit_Declaration_Node
(XE.Key.Ent)));
Loc : constant Source_Ptr := Sloc (Gen_Par);
Gen_U : constant Unit_Number_Type :=
Get_Source_Unit (Loc);
begin
Write_Info_Char ('[');
if Curru /= Gen_U then
Write_Info_Nat (Dependency_Num (Gen_U));
Write_Info_Char ('|');
end if;
Write_Info_Nat
(Int (Get_Logical_Line_Number (Loc)));
Write_Info_Char (']');
end;
end if;
-- See if we have a type reference and if so output
Check_Type_Reference (XE.Key.Ent, False);
-- Additional information for types with progenitors,
-- including synchronized tagged types.
declare
Typ : constant Entity_Id := XE.Key.Ent;
Elmt : Elmt_Id;
begin
if Is_Record_Type (Typ)
and then Present (Interfaces (Typ))
then
Elmt := First_Elmt (Interfaces (Typ));
elsif Is_Concurrent_Type (Typ)
and then Present (Corresponding_Record_Type (Typ))
and then Present (
Interfaces (Corresponding_Record_Type (Typ)))
then
Elmt :=
First_Elmt (
Interfaces (Corresponding_Record_Type (Typ)));
else
Elmt := No_Elmt;
end if;
while Present (Elmt) loop
Check_Type_Reference (Node (Elmt), True);
Next_Elmt (Elmt);
end loop;
end;
-- For array types, list index types as well. (This is
-- not C, indexes have distinct types).
if Is_Array_Type (XE.Key.Ent) then
declare
A_Typ : constant Entity_Id := XE.Key.Ent;
Indx : Node_Id;
begin
-- If this is a derived array type, we have
-- output the parent type, so add the component
-- type now.
if Is_Derived_Type (A_Typ) then
Check_Type_Reference
(Component_Type (A_Typ), False, True);
end if;
-- Add references to index types.
Indx := First_Index (XE.Key.Ent);
while Present (Indx) loop
Check_Type_Reference
(First_Subtype (Etype (Indx)), True);
Next_Index (Indx);
end loop;
end;
end if;
-- If the entity is an overriding operation, write info
-- on operation that was overridden.
if Is_Subprogram (XE.Key.Ent)
and then Present (Overridden_Operation (XE.Key.Ent))
then
Output_Overridden_Op
(Overridden_Operation (XE.Key.Ent));
end if;
-- End of processing for entity output
Crloc := No_Location;
end if;
-- Output the reference if it is not as the same location
-- as the previous one, or it is a read-reference that
-- indicates that the entity is an in-out actual in a call.
if XE.Key.Loc /= No_Location
and then
(XE.Key.Loc /= Crloc
or else (Prevt = 'm' and then XE.Key.Typ = 'r'))
then
Crloc := XE.Key.Loc;
Prevt := XE.Key.Typ;
-- Start continuation if line full, else blank
if Write_Info_Col > 72 then
Write_Info_EOL;
Write_Info_Initiate ('.');
end if;
Write_Info_Char (' ');
-- Output file number if changed
if XE.Key.Lun /= Curru then
Curru := XE.Key.Lun;
Write_Info_Nat (Dependency_Num (Curru));
Write_Info_Char ('|');
end if;
Write_Info_Nat
(Int (Get_Logical_Line_Number (XE.Key.Loc)));
Write_Info_Char (XE.Key.Typ);
if Is_Overloadable (XE.Key.Ent) then
if (Is_Imported (XE.Key.Ent) and then XE.Key.Typ = 'b')
or else
(Is_Exported (XE.Key.Ent) and then XE.Key.Typ = 'i')
then
Output_Import_Export_Info (XE.Key.Ent);
end if;
end if;
Write_Info_Nat (Int (Get_Column_Number (XE.Key.Loc)));
Output_Instantiation_Refs (Sloc (XE.Key.Ent));
end if;
end if;
end Output_One_Ref;
<<Continue>>
null;
end loop;
Write_Info_EOL;
end Output_Refs;
end Output_References;
---------------------------------
-- Process_Deferred_References --
---------------------------------
procedure Process_Deferred_References is
begin
for J in Deferred_References.First .. Deferred_References.Last loop
declare
D : Deferred_Reference_Entry renames Deferred_References.Table (J);
begin
case Is_LHS (D.N) is
when Yes =>
Generate_Reference (D.E, D.N, 'm');
when No =>
Generate_Reference (D.E, D.N, 'r');
-- Not clear if Unknown can occur at this stage, but if it
-- does we will treat it as a normal reference.
when Unknown =>
Generate_Reference (D.E, D.N, 'r');
end case;
end;
end loop;
-- Clear processed entries from table
Deferred_References.Init;
end Process_Deferred_References;
-- Start of elaboration for Lib.Xref
begin
-- Reset is necessary because Elmt_Ptr does not default to Null_Ptr,
-- because it's not an access type.
Xref_Set.Reset;
end Lib.Xref;
|
with agar.core.event;
with agar.core;
with agar.gui.widget.button;
with agar.gui.widget;
with agar.gui.window;
with agar.gui;
with demo;
with keyevent_callbacks;
procedure keyevent is
package gui_button renames agar.gui.widget.button;
package gui_event renames agar.core.event;
package gui_widget renames agar.gui.widget;
package gui_window renames agar.gui.window;
quit_button : gui_button.button_access_t;
begin
demo.init ("keyevent");
-- attach keydown handler function
gui_event.set
(object => gui_widget.object (gui_window.widget (demo.window)),
name => "key-down",
handler => keyevent_callbacks.keydown'access);
-- attach keyup handler function
gui_event.set
(object => gui_widget.object (gui_window.widget (demo.window)),
name => "key-up",
handler => keyevent_callbacks.keyup'access);
-- quit when closing window
gui_event.set
(object => gui_widget.object (gui_window.widget (demo.window)),
name => "window-close",
handler => keyevent_callbacks.quit'access);
-- create quit button
quit_button := gui_button.allocate_function
(parent => gui_window.widget (demo.window),
label => "quit",
callback => keyevent_callbacks.quit'access);
-- position and size
gui_widget.modify_position
(widget => gui_button.widget (quit_button),
y => 10);
gui_widget.set_size
(widget => gui_button.widget (quit_button),
width => 300,
height => 32);
demo.run;
demo.finish;
end keyevent;
|
with Text_IO;
procedure Main is
task type Blinker_Type is
entry Start(S : String);
entry Stop;
end Blinker_Type;
task Blinker_Control is
entry Blink_Left;
entry Blink_Right;
entry Blink_Emergency;
entry Blink_Stop;
end Blinker_Control;
Left_Blinker, Right_Blinker: Blinker_Type;
task body Blinker_Control is
Blinker_Left_Started : Boolean := False;
Blinker_Right_Started : Boolean := False;
begin
loop
select
when not Blinker_Left_Started =>
accept Blink_Left;
Left_Blinker.Start("left ");
Blinker_Left_Started := True;
or
when not Blinker_Right_Started =>
accept Blink_Right;
Right_Blinker.Start("right");
Blinker_Right_Started := True;
or
accept Blink_Emergency;
Left_Blinker.Start("left ");
Right_Blinker.Start("right");
Blinker_Left_Started := True;
Blinker_Right_Started := True;
or
when Blinker_Left_Started or Blinker_Right_Started =>
accept Blink_Stop;
if Blinker_Left_Started then
Left_Blinker.Stop;
end if;
if Blinker_Right_Started then
Right_Blinker.Stop;
end if;
or
terminate;
end select;
end loop;
end Blinker_Control;
task body Blinker_Type is
Id : String(1..5);
begin
loop
select
accept Start(S : String) do
Id := S;
end Start;
loop
select
accept Stop;
exit;
or
delay 0.5;
Text_Io.Put_Line("Blinker " & Id & " toggling");
end select;
end loop;
or terminate;
end select;
end loop;
end Blinker_Type;
begin
Blinker_Control.Blink_Left;
delay 3.0;
Blinker_Control.Blink_Stop;
delay 3.0;
Blinker_Control.Blink_Emergency;
delay 3.0;
Blinker_Control.Blink_Stop;
end;
|
------------------------------------------------------------------------------
-- File : GLOBE_3D - Random_extrusions.ads
-- Description : Algorithm to generate a Sci - Fi - style extruded surface
-- Date / Version : 14 - May - 2006
-- Copyright (c) Gautier de Montmollin 2006
------------------------------------------------------------------------------
generic
with procedure Geometric_mapping (u : in Point_3D; x : out Point_3D);
-- (u (1), u (2)) in [0;1] x [0;1]
--
-- Edge numbering:
-- (0, 1) 4 --< --3 (1, 1)
-- | |
-- (0, 0) 1 --> --2 (1, 0)
--
-- u (3) : elevation above surface
package GLOBE_3D.Random_extrusions is
procedure Extrude_on_rectangle (
T1, T2, T3, T4 : in Map_idx_pair; -- Texture edges, horizontal surface
V1, V2, V3, V4 : in Map_idx_pair; -- Texture edges, vertical surfaces
grid_1, grid_2 : in Positive;
T_ID, V_ID : in Image_ID; -- ID's of plane and vertical texture
max_u3 : in Real;
iterations : in Natural;
last_point : out Natural;
mesh : out Point_3D_array;
last_face : out Natural;
poly : out Face_array;
random_initiator : in Integer := 0 -- default 0 - > time - dependent seed
);
end GLOBE_3D.Random_extrusions;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . W I D E _ W I D E _ T E X T _ I O --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005, 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 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. --
-- --
------------------------------------------------------------------------------
-- Note: the generic subpackages of Wide_Wide_Text_IO (Integer_IO, Float_IO,
-- Fixed_IO, Modular_IO, Decimal_IO and Enumeration_IO) appear as private
-- children in GNAT. These children are with'ed automatically if they are
-- referenced, so this rearrangement is invisible to user programs, but has
-- the advantage that only the needed parts of Wide_Wide_Text_IO are processed
-- and loaded.
with Ada.IO_Exceptions;
with Ada.Streams;
with System;
with System.File_Control_Block;
with System.WCh_Con;
package Ada.Wide_Wide_Text_IO is
package WCh_Con renames System.WCh_Con;
type File_Type is limited private;
type File_Mode is (In_File, Out_File, Append_File);
-- The following representation clause allows the use of unchecked
-- conversion for rapid translation between the File_Mode type
-- used in this package and System.File_IO.
for File_Mode use
(In_File => 0, -- System.FIle_IO.File_Mode'Pos (In_File)
Out_File => 2, -- System.File_IO.File_Mode'Pos (Out_File)
Append_File => 3); -- System.File_IO.File_Mode'Pos (Append_File)
type Count is range 0 .. Natural'Last;
-- The value of Count'Last must be large enough so that the assumption
-- enough so that the assumption that the Line, Column and Page
-- counts can never exceed this value is a valid assumption.
subtype Positive_Count is Count range 1 .. Count'Last;
Unbounded : constant Count := 0;
-- Line and page length
subtype Field is Integer range 0 .. 255;
-- Note: if for any reason, there is a need to increase this value,
-- then it will be necessary to change the corresponding value in
-- System.Img_Real in file s-imgrea.adb.
subtype Number_Base is Integer range 2 .. 16;
type Type_Set is (Lower_Case, Upper_Case);
---------------------
-- File Management --
---------------------
procedure Create
(File : in out File_Type;
Mode : File_Mode := Out_File;
Name : String := "";
Form : String := "");
procedure Open
(File : in out File_Type;
Mode : File_Mode;
Name : String;
Form : String := "");
procedure Close (File : in out File_Type);
procedure Delete (File : in out File_Type);
procedure Reset (File : in out File_Type; Mode : File_Mode);
procedure Reset (File : in out File_Type);
function Mode (File : File_Type) return File_Mode;
function Name (File : File_Type) return String;
function Form (File : File_Type) return String;
function Is_Open (File : File_Type) return Boolean;
------------------------------------------------------
-- Control of default input, output and error files --
------------------------------------------------------
procedure Set_Input (File : File_Type);
procedure Set_Output (File : File_Type);
procedure Set_Error (File : File_Type);
function Standard_Input return File_Type;
function Standard_Output return File_Type;
function Standard_Error return File_Type;
function Current_Input return File_Type;
function Current_Output return File_Type;
function Current_Error return File_Type;
type File_Access is access constant File_Type;
function Standard_Input return File_Access;
function Standard_Output return File_Access;
function Standard_Error return File_Access;
function Current_Input return File_Access;
function Current_Output return File_Access;
function Current_Error return File_Access;
--------------------
-- Buffer control --
--------------------
-- Note: The paramter file is in out in the RM, but as pointed out
-- in <<95-5166.a Tucker Taft 95-6-23>> this is clearly an oversight.
procedure Flush (File : File_Type);
procedure Flush;
--------------------------------------------
-- Specification of line and page lengths --
--------------------------------------------
procedure Set_Line_Length (File : File_Type; To : Count);
procedure Set_Line_Length (To : Count);
procedure Set_Page_Length (File : File_Type; To : Count);
procedure Set_Page_Length (To : Count);
function Line_Length (File : File_Type) return Count;
function Line_Length return Count;
function Page_Length (File : File_Type) return Count;
function Page_Length return Count;
------------------------------------
-- Column, Line, and Page Control --
------------------------------------
procedure New_Line (File : File_Type; Spacing : Positive_Count := 1);
procedure New_Line (Spacing : Positive_Count := 1);
procedure Skip_Line (File : File_Type; Spacing : Positive_Count := 1);
procedure Skip_Line (Spacing : Positive_Count := 1);
function End_Of_Line (File : File_Type) return Boolean;
function End_Of_Line return Boolean;
procedure New_Page (File : File_Type);
procedure New_Page;
procedure Skip_Page (File : File_Type);
procedure Skip_Page;
function End_Of_Page (File : File_Type) return Boolean;
function End_Of_Page return Boolean;
function End_Of_File (File : File_Type) return Boolean;
function End_Of_File return Boolean;
procedure Set_Col (File : File_Type; To : Positive_Count);
procedure Set_Col (To : Positive_Count);
procedure Set_Line (File : File_Type; To : Positive_Count);
procedure Set_Line (To : Positive_Count);
function Col (File : File_Type) return Positive_Count;
function Col return Positive_Count;
function Line (File : File_Type) return Positive_Count;
function Line return Positive_Count;
function Page (File : File_Type) return Positive_Count;
function Page return Positive_Count;
----------------------------
-- Character Input-Output --
----------------------------
procedure Get (File : File_Type; Item : out Wide_Wide_Character);
procedure Get (Item : out Wide_Wide_Character);
procedure Put (File : File_Type; Item : Wide_Wide_Character);
procedure Put (Item : Wide_Wide_Character);
procedure Look_Ahead
(File : File_Type;
Item : out Wide_Wide_Character;
End_Of_Line : out Boolean);
procedure Look_Ahead
(Item : out Wide_Wide_Character;
End_Of_Line : out Boolean);
procedure Get_Immediate
(File : File_Type;
Item : out Wide_Wide_Character);
procedure Get_Immediate
(Item : out Wide_Wide_Character);
procedure Get_Immediate
(File : File_Type;
Item : out Wide_Wide_Character;
Available : out Boolean);
procedure Get_Immediate
(Item : out Wide_Wide_Character;
Available : out Boolean);
-------------------------
-- String Input-Output --
-------------------------
procedure Get (File : File_Type; Item : out Wide_Wide_String);
procedure Get (Item : out Wide_Wide_String);
procedure Put (File : File_Type; Item : Wide_Wide_String);
procedure Put (Item : Wide_Wide_String);
procedure Get_Line
(File : File_Type;
Item : out Wide_Wide_String;
Last : out Natural);
function Get_Line (File : File_Type) return Wide_Wide_String;
pragma Ada_05 (Get_Line);
function Get_Line return Wide_Wide_String;
pragma Ada_05 (Get_Line);
procedure Get_Line
(Item : out Wide_Wide_String;
Last : out Natural);
procedure Put_Line
(File : File_Type;
Item : Wide_Wide_String);
procedure Put_Line
(Item : Wide_Wide_String);
---------------------------------------
-- Generic packages for Input-Output --
---------------------------------------
-- The generic packages:
-- Ada.Wide_Wide_Text_IO.Integer_IO
-- Ada.Wide_Wide_Text_IO.Modular_IO
-- Ada.Wide_Wide_Text_IO.Float_IO
-- Ada.Wide_Wide_Text_IO.Fixed_IO
-- Ada.Wide_Wide_Text_IO.Decimal_IO
-- Ada.Wide_Wide_Text_IO.Enumeration_IO
-- are implemented as separate child packages in GNAT, so the
-- spec and body of these packages are to be found in separate
-- child units. This implementation detail is hidden from the
-- Ada programmer by special circuitry in the compiler that
-- treats these child packages as though they were nested in
-- Text_IO. The advantage of this special processing is that
-- the subsidiary routines needed if these generics are used
-- are not loaded when they are not used.
----------------
-- Exceptions --
----------------
Status_Error : exception renames IO_Exceptions.Status_Error;
Mode_Error : exception renames IO_Exceptions.Mode_Error;
Name_Error : exception renames IO_Exceptions.Name_Error;
Use_Error : exception renames IO_Exceptions.Use_Error;
Device_Error : exception renames IO_Exceptions.Device_Error;
End_Error : exception renames IO_Exceptions.End_Error;
Data_Error : exception renames IO_Exceptions.Data_Error;
Layout_Error : exception renames IO_Exceptions.Layout_Error;
private
-----------------------------------
-- Handling of Format Characters --
-----------------------------------
-- Line marks are represented by the single character ASCII.LF (16#0A#).
-- In DOS and similar systems, underlying file translation takes care
-- of translating this to and from the standard CR/LF sequences used in
-- these operating systems to mark the end of a line. On output there is
-- always a line mark at the end of the last line, but on input, this
-- line mark can be omitted, and is implied by the end of file.
-- Page marks are represented by the single character ASCII.FF (16#0C#),
-- The page mark at the end of the file may be omitted, and is normally
-- omitted on output unless an explicit New_Page call is made before
-- closing the file. No page mark is added when a file is appended to,
-- so, in accordance with the permission in (RM A.10.2(4)), there may
-- or may not be a page mark separating preexising text in the file
-- from the new text to be written.
-- A file mark is marked by the physical end of file. In DOS translation
-- mode on input, an EOF character (SUB = 16#1A#) gets translated to the
-- physical end of file, so in effect this character is recognized as
-- marking the end of file in DOS and similar systems.
LM : constant := Character'Pos (ASCII.LF);
-- Used as line mark
PM : constant := Character'Pos (ASCII.FF);
-- Used as page mark, except at end of file where it is implied
-------------------------------------
-- Wide_Wide_Text_IO File Control Block --
-------------------------------------
Default_WCEM : WCh_Con.WC_Encoding_Method := WCh_Con.WCEM_UTF8;
-- This gets modified during initialization (see body) using
-- the default value established in the call to Set_Globals.
package FCB renames System.File_Control_Block;
type Wide_Wide_Text_AFCB is new FCB.AFCB with record
Page : Count := 1;
Line : Count := 1;
Col : Count := 1;
Line_Length : Count := 0;
Page_Length : Count := 0;
Before_LM : Boolean := False;
-- This flag is used to deal with the anomolies introduced by the
-- peculiar definition of End_Of_File and End_Of_Page in Ada. These
-- functions require looking ahead more than one character. Since
-- there is no convenient way of backing up more than one character,
-- what we do is to leave ourselves positioned past the LM, but set
-- this flag, so that we know that from an Ada point of view we are
-- in front of the LM, not after it. A bit of a kludge, but it works!
Before_LM_PM : Boolean := False;
-- This flag similarly handles the case of being physically positioned
-- after a LM-PM sequence when logically we are before the LM-PM. This
-- flag can only be set if Before_LM is also set.
WC_Method : WCh_Con.WC_Encoding_Method := Default_WCEM;
-- Encoding method to be used for this file
Before_Wide_Wide_Character : Boolean := False;
-- This flag is set to indicate that a wide character in the input has
-- been read by Wide_Wide_Text_IO.Look_Ahead. If it is set to True,
-- then it means that the stream is logically positioned before the
-- character but is physically positioned after it. The character
-- involved must not be in the range 16#00#-16#7F#, i.e. if the flag is
-- set, then we know the next character has a code greater than 16#7F#,
-- and the value of this character is saved in
-- Saved_Wide_Wide_Character.
Saved_Wide_Wide_Character : Wide_Wide_Character;
-- This field is valid only if Before_Wide_Wide_Character is set. It
-- contains a wide character read by Look_Ahead. If Look_Ahead
-- reads a character in the range 16#0000# to 16#007F#, then it
-- can use ungetc to put it back, but ungetc cannot be called
-- more than once, so for characters above this range, we don't
-- try to back up the file. Instead we save the character in this
-- field and set the flag Before_Wide_Wide_Character to indicate that
-- we are logically positioned before this character even though
-- the stream is physically positioned after it.
end record;
type File_Type is access all Wide_Wide_Text_AFCB;
function AFCB_Allocate
(Control_Block : Wide_Wide_Text_AFCB) return FCB.AFCB_Ptr;
procedure AFCB_Close (File : access Wide_Wide_Text_AFCB);
procedure AFCB_Free (File : access Wide_Wide_Text_AFCB);
procedure Read
(File : in out Wide_Wide_Text_AFCB;
Item : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset);
-- Read operation used when Wide_Wide_Text_IO file is treated as a Stream
procedure Write
(File : in out Wide_Wide_Text_AFCB;
Item : Ada.Streams.Stream_Element_Array);
-- Write operation used when Wide_Wide_Text_IO file is treated as a Stream
------------------------
-- The Standard Files --
------------------------
Null_Str : aliased constant String := "";
-- Used as name and form of standard files
Standard_Err_AFCB : aliased Wide_Wide_Text_AFCB;
Standard_In_AFCB : aliased Wide_Wide_Text_AFCB;
Standard_Out_AFCB : aliased Wide_Wide_Text_AFCB;
Standard_Err : aliased File_Type := Standard_Err_AFCB'Access;
Standard_In : aliased File_Type := Standard_In_AFCB'Access;
Standard_Out : aliased File_Type := Standard_Out_AFCB'Access;
-- Standard files
Current_In : aliased File_Type := Standard_In;
Current_Out : aliased File_Type := Standard_Out;
Current_Err : aliased File_Type := Standard_Err;
-- Current files
-----------------------
-- Local Subprograms --
-----------------------
-- These subprograms are in the private part of the spec so that they can
-- be shared by the routines in the body of Ada.Text_IO.Wide_Wide_Text_IO.
-- Note: we use Integer in these declarations instead of the more accurate
-- Interfaces.C_Streams.int, because we do not want to drag in the spec of
-- this interfaces package with the spec of Ada.Text_IO, and we know that
-- in fact these types are identical
function Getc (File : File_Type) return Integer;
-- Gets next character from file, which has already been checked for
-- being in read status, and returns the character read if no error
-- occurs. The result is EOF if the end of file was read.
procedure Get_Character
(File : File_Type;
Item : out Character);
-- This is essentially a copy of the normal Get routine from Text_IO. It
-- obtains a single character from the input file File, and places it in
-- Item. This character may be the leading character of a
-- Wide_Wide_Character sequence, but that is up to the caller to deal
-- with.
function Get_Wide_Wide_Char
(C : Character;
File : File_Type) return Wide_Wide_Character;
-- This function is shared by Get and Get_Immediate to extract a wide
-- character value from the given File. The first byte has already been
-- read and is passed in C. The wide character value is returned as the
-- result, and the file pointer is bumped past the character.
function Nextc (File : File_Type) return Integer;
-- Returns next character from file without skipping past it (i.e. it
-- is a combination of Getc followed by an Ungetc).
procedure Putc (ch : Integer; File : File_Type);
-- Outputs the given character to the file, which has already been
-- checked for being in output status. Device_Error is raised if the
-- character cannot be written.
procedure Terminate_Line (File : File_Type);
-- If the file is in Write_File or Append_File mode, and the current
-- line is not terminated, then a line terminator is written using
-- New_Line. Note that there is no Terminate_Page routine, because
-- the page mark at the end of the file is implied if necessary.
procedure Ungetc (ch : Integer; File : File_Type);
-- Pushes back character into stream, using ungetc. The caller has
-- checked that the file is in read status. Device_Error is raised
-- if the character cannot be pushed back. An attempt to push back
-- and end of file character (EOF) is ignored.
end Ada.Wide_Wide_Text_IO;
|
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.MD5;
procedure MD5_Digest is
begin
Put(GNAT.MD5.Digest("Foo bar baz"));
end MD5_Digest;
|
-----------------------------------------------------------------------
-- util-properties -- Generic name/value property management
-- Copyright (C) 2001 - 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.Strings.Fixed;
with Ada.Strings.Unbounded.Text_IO;
with Ada.Strings.Maps;
with Ada.Unchecked_Deallocation;
with Util.Files;
with Util.Beans.Objects.Maps;
package body Util.Properties is
use Ada.Text_IO;
use Ada.Strings.Unbounded.Text_IO;
use Implementation;
use Util.Beans.Objects;
procedure Free is
new Ada.Unchecked_Deallocation (Object => Implementation.Shared_Manager'Class,
Name => Implementation.Shared_Manager_Access);
Trim_Chars : constant Ada.Strings.Maps.Character_Set
:= Ada.Strings.Maps.To_Set (" " & ASCII.HT);
package body Implementation is
procedure Create (Self : in out Util.Properties.Manager'Class) is
begin
if Self.Impl = null then
Self.Impl := Allocator;
elsif Self.Impl.Is_Shared then
declare
Old : Implementation.Shared_Manager_Access := Self.Impl;
Is_Zero : Boolean;
Impl : constant Implementation.Manager_Access := Create_Copy (Self.Impl.all);
begin
Self.Impl := Implementation.Shared_Manager'Class (Impl.all)'Access;
Old.Finalize (Is_Zero);
if Is_Zero then
Free (Old);
end if;
end;
end if;
end Create;
procedure Initialize (Self : in out Util.Properties.Manager'Class) is
Release : Boolean;
begin
if Self.Impl /= null then
Self.Impl.Finalize (Release);
if Release then
Free (Self.Impl);
end if;
end if;
Self.Impl := Allocator;
end Initialize;
package body Shared_Implementation is
overriding
function Is_Shared (Self : in Manager) return Boolean is
begin
return not Self.Shared and Util.Concurrent.Counters.Value (Self.Count) > 1;
end Is_Shared;
overriding
procedure Set_Shared (Self : in out Manager;
Shared : in Boolean) is
begin
Self.Shared := Shared;
end Set_Shared;
overriding
procedure Adjust (Self : in out Manager) is
begin
Util.Concurrent.Counters.Increment (Self.Count);
end Adjust;
overriding
procedure Finalize (Self : in out Manager;
Release : out Boolean) is
begin
Util.Concurrent.Counters.Decrement (Self.Count, Release);
end Finalize;
end Shared_Implementation;
end Implementation;
type Property_Map is limited new Implementation.Manager with record
Props : Util.Beans.Objects.Maps.Map_Bean;
end record;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
overriding
function Get_Value (From : in Property_Map;
Name : in String) return Util.Beans.Objects.Object;
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object);
-- Returns TRUE if the property exists.
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean;
-- Remove the property given its name.
overriding
procedure Remove (Self : in out Property_Map;
Name : in String);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object));
-- Deep copy of properties stored in 'From' to 'To'.
overriding
function Create_Copy (Self : in Property_Map)
return Implementation.Manager_Access;
package Shared_Property_Implementation is
new Implementation.Shared_Implementation (Property_Map);
subtype Property_Manager is Shared_Property_Implementation.Manager;
type Property_Manager_Access is access all Property_Manager'Class;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Property_Map;
Name : in String) return Util.Beans.Objects.Object is
begin
return From.Props.Get_Value (Name);
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Property_Map;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
From.Props.Set_Value (Name, Value);
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property exists.
-- ------------------------------
overriding
function Exists (Self : in Property_Map;
Name : in String)
return Boolean is
begin
return Self.Props.Contains (Name);
end Exists;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
overriding
procedure Remove (Self : in out Property_Map;
Name : in String) is
begin
Self.Props.Delete (Name);
end Remove;
-- ------------------------------
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
-- ------------------------------
overriding
procedure Iterate (Self : in Property_Map;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object)) is
Iter : Util.Beans.Objects.Maps.Cursor := Self.Props.First;
begin
while Util.Beans.Objects.Maps.Has_Element (Iter) loop
Util.Beans.Objects.Maps.Query_Element (Iter, Process);
Util.Beans.Objects.Maps.Next (Iter);
end loop;
end Iterate;
-- ------------------------------
-- Deep copy of properties stored in 'From' to 'To'.
-- ------------------------------
overriding
function Create_Copy (Self : in Property_Map)
return Implementation.Manager_Access is
Result : constant Property_Manager_Access := new Property_Manager;
begin
-- SCz 2017-07-20: the map assignment is buggy on GNAT 2016 because the copy of the
-- object also copies the internal Lock and Busy flags which makes the target copy
-- unusable because the Lock and Busy flag prevents modifications. Instead of the
-- Ada assignment, we use the Assign procedure which makes the deep copy of the map.
-- Result.Props := Self.Props;
Result.Props.Assign (Self.Props);
return Result.all'Access;
end Create_Copy;
function Allocate_Property return Implementation.Shared_Manager_Access is
(new Property_Manager);
-- Create a property implementation if there is none yet.
procedure Check_And_Create_Impl is
new Implementation.Create (Allocator => Allocate_Property);
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Manager;
Name : in String) return Util.Beans.Objects.Object is
begin
if From.Impl = null then
return Util.Beans.Objects.Null_Object;
else
return From.Impl.Get_Value (Name);
end if;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the map contains the given name, the value changed.
-- Otherwise name is added to the map and the value associated with it.
-- ------------------------------
overriding
procedure Set_Value (From : in out Manager;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
Check_And_Create_Impl (From);
From.Impl.Set_Value (Name, Value);
end Set_Value;
-- ------------------------------
-- Returns TRUE if the property manager is empty.
-- ------------------------------
function Is_Empty (Self : in Manager'Class) return Boolean is
begin
if Self.Impl = null then
return True;
else
return False;
end if;
end Is_Empty;
function Exists (Self : in Manager'Class;
Name : in String) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (Name);
end Exists;
function Exists (Self : in Manager'Class;
Name : in Unbounded_String) return Boolean is
begin
-- There is not yet an implementation, no property
return Self.Impl /= null and then Self.Impl.Exists (-Name);
end Exists;
function Get (Self : in Manager'Class;
Name : in String) return Unbounded_String is
Value : constant Util.Beans.Objects.Object := Self.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Value) then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return To_Unbounded_String (Value);
end Get;
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return Unbounded_String is
begin
return Self.Get (-Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String) return String is
Value : constant Util.Beans.Objects.Object := Self.Get_Value (Name);
begin
if Util.Beans.Objects.Is_Null (Value) then
raise NO_PROPERTY with "No property: '" & Name & "'";
end if;
return To_String (Value);
end Get;
function Get (Self : in Manager'Class;
Name : in Unbounded_String) return String is
begin
return Self.Get (-Name);
end Get;
function Get (Self : in Manager'Class;
Name : in String;
Default : in String) return String is
begin
if Exists (Self, Name) then
return Get (Self, Name);
else
return Default;
end if;
end Get;
-- ------------------------------
-- Returns a property manager that is associated with the given name.
-- Raises NO_PROPERTY if there is no such property manager or if a property exists
-- but is not a property manager.
-- ------------------------------
function Get (Self : in Manager'Class;
Name : in String) return Manager is
Value : constant Util.Beans.Objects.Object := Self.Get_Value (Name);
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Value);
begin
if Bean = null or else not (Bean.all in Manager'Class) then
raise NO_PROPERTY with "No property '" & Name & "'";
end if;
return Manager (Bean.all);
end Get;
-- ------------------------------
-- Create a property manager and associated it with the given name.
-- ------------------------------
function Create (Self : in out Manager'Class;
Name : in String) return Manager is
Result : Manager_Access;
begin
Check_And_Create_Impl (Self);
-- Create the property manager and make it shared so that it can be populated by
-- the caller.
Result := new Manager;
Check_And_Create_Impl (Result.all);
Result.Impl.Set_Shared (True);
Self.Impl.Set_Value (Name, Util.Beans.Objects.To_Object (Result.all'Access));
return Manager (Result.all);
end Create;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in String) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in String;
Item : in Unbounded_String) is
begin
Self.Set_Value (Name, To_Object (Item));
end Set;
-- ------------------------------
-- Set the value of the property. The property is created if it
-- does not exists.
-- ------------------------------
procedure Set (Self : in out Manager'Class;
Name : in Unbounded_String;
Item : in Unbounded_String) is
begin
Self.Set_Value (-Name, To_Object (Item));
end Set;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in String) is
begin
if Self.Impl = null then
raise NO_PROPERTY with "No property '" & Name & "'";
end if;
Check_And_Create_Impl (Self);
Remove (Self.Impl.all, Name);
end Remove;
-- ------------------------------
-- Remove the property given its name.
-- ------------------------------
procedure Remove (Self : in out Manager'Class;
Name : in Unbounded_String) is
begin
Self.Remove (-Name);
end Remove;
-- ------------------------------
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
-- ------------------------------
procedure Iterate (Self : in Manager'Class;
Process : access procedure (Name : in String;
Item : in Util.Beans.Objects.Object)) is
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process);
end if;
end Iterate;
-- ------------------------------
-- Get the property manager represented by the item value.
-- Raise the Conversion_Error exception if the value is not a property manager.
-- ------------------------------
function To_Manager (Item : in Value) return Manager is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Item);
begin
if Bean = null or else not (Bean.all in Manager'Class) then
raise Util.Beans.Objects.Conversion_Error;
end if;
return Manager (Bean.all);
end To_Manager;
-- ------------------------------
-- Returns True if the item value represents a property manager.
-- ------------------------------
function Is_Manager (Item : in Value) return Boolean is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Item);
begin
return Bean /= null and then (Bean.all in Manager'Class);
end Is_Manager;
-- ------------------------------
-- Collect the name of the properties defined in the manager.
-- When a prefix is specified, only the properties starting with the prefix are
-- returned.
-- ------------------------------
procedure Get_Names (Self : in Manager;
Into : in out Util.Strings.Vectors.Vector;
Prefix : in String := "") is
procedure Process (Name : in String;
Item : in Util.Beans.Objects.Object);
procedure Process (Name : in String;
Item : in Util.Beans.Objects.Object) is
pragma Unreferenced (Item);
begin
if Prefix'Length = 0 or else Ada.Strings.Fixed.Index (Name, Prefix) = 1 then
Into.Append (Name);
end if;
end Process;
begin
if Self.Impl /= null then
Self.Impl.Iterate (Process'Access);
end if;
end Get_Names;
overriding
procedure Adjust (Object : in out Manager) is
begin
if Object.Impl /= null then
Object.Impl.Adjust;
end if;
end Adjust;
overriding
procedure Finalize (Object : in out Manager) is
Is_Zero : Boolean;
begin
if Object.Impl /= null then
Object.Impl.Finalize (Is_Zero);
if Is_Zero then
Free (Object.Impl);
end if;
end if;
end Finalize;
procedure Load_Properties (Self : in out Manager'Class;
File : in File_Type;
Prefix : in String := "";
Strip : in Boolean := False) is
pragma Unreferenced (Strip);
Line : Unbounded_String;
Name : Unbounded_String;
Value : Unbounded_String;
Current : Manager;
Pos : Natural;
Len : Natural;
begin
Check_And_Create_Impl (Self);
Current := Manager (Self);
Current.Impl.Set_Shared (True);
while not End_Of_File (File) loop
Line := Get_Line (File);
Len := Length (Line);
if Len /= 0 then
case Element (Line, 1) is
when '!' | '#' =>
null;
when '[' =>
Pos := Index (Line, "]");
if Pos > 0 then
Current := Self.Create (To_String (Unbounded_Slice (Line, 2, Pos - 1)));
end if;
when others =>
Pos := Index (Line, "=");
if Pos > 0 and then Prefix'Length > 0 and then Index (Line, Prefix) = 1 then
Name := Unbounded_Slice (Line, Prefix'Length + 1, Pos - 1);
Value := Tail (Line, Len - Pos);
Trim (Name, Trim_Chars, Trim_Chars);
Trim (Value, Trim_Chars, Trim_Chars);
Current.Set (Name, Value);
elsif Pos > 0 and Prefix'Length = 0 then
Name := Head (Line, Pos - 1);
Value := Tail (Line, Len - Pos);
Trim (Name, Trim_Chars, Trim_Chars);
Trim (Value, Trim_Chars, Trim_Chars);
Current.Set (Name, Value);
end if;
end case;
end if;
end loop;
Self.Impl.Set_Shared (False);
exception
when End_Error =>
return;
end Load_Properties;
procedure Load_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "";
Strip : in Boolean := False) is
F : File_Type;
begin
Open (F, In_File, Path);
Load_Properties (Self, F, Prefix, Strip);
Close (F);
end Load_Properties;
-- ------------------------------
-- Save the properties in the given file path.
-- ------------------------------
procedure Save_Properties (Self : in out Manager'Class;
Path : in String;
Prefix : in String := "") is
procedure Save_Property (Name : in String;
Item : in Util.Beans.Objects.Object);
Tmp : constant String := Path & ".tmp";
F : File_Type;
Recurse : Boolean := False;
Level : Natural := 0;
Ini_Mode : Boolean := False;
procedure Save_Property (Name : in String;
Item : in Util.Beans.Objects.Object) is
Bean : constant access Util.Beans.Basic.Readonly_Bean'Class
:= Util.Beans.Objects.To_Bean (Item);
begin
if Bean /= null then
if Recurse then
New_Line (F);
Put (F, "[");
Put (F, Name);
Put (F, "]");
New_Line (F);
Level := Level + 1;
To_Manager (Item).Iterate (Save_Property'Access);
Level := Level - 1;
else
Ini_Mode := True;
end if;
elsif not Recurse or else Level > 0 then
if Prefix'Length > 0 then
if Name'Length < Prefix'Length then
return;
end if;
if Name (Name'First .. Prefix'Length - 1) /= Prefix then
return;
end if;
end if;
Put (F, Name);
Put (F, "=");
Put (F, Util.Beans.Objects.To_String (Item));
New_Line (F);
end if;
end Save_Property;
begin
Create (File => F, Name => Tmp);
Self.Iterate (Save_Property'Access);
if Ini_Mode then
Recurse := True;
Self.Iterate (Save_Property'Access);
end if;
Close (File => F);
-- Do a system atomic rename of old file in the new file.
-- Ada.Directories.Rename does not allow this.
Util.Files.Rename (Tmp, Path);
end Save_Properties;
-- ------------------------------
-- Copy the properties from FROM which start with a given prefix.
-- If the prefix is empty, all properties are copied. When <b>Strip</b> is True,
-- the prefix part is removed from the property name.
-- ------------------------------
procedure Copy (Self : in out Manager'Class;
From : in Manager'Class;
Prefix : in String := "";
Strip : in Boolean := False) is
procedure Process (Name : in String;
Value : in Util.Beans.Objects.Object);
procedure Process (Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Prefix'Length > 0 then
if Name'Length < Prefix'Length then
return;
end if;
if Name (Name'First .. Name'First + Prefix'Length - 1) /= Prefix then
return;
end if;
if Strip then
Self.Set_Value (Name (Name'First + Prefix'Length .. Name'Last), Value);
return;
end if;
end if;
Self.Set_Value (Name, Value);
end Process;
begin
From.Iterate (Process'Access);
end Copy;
end Util.Properties;
|
-- ============================================================================
-- Atmel Microcontroller Software Support
-- ============================================================================
-- Copyright (c) 2017 Atmel Corporation,
-- a wholly owned subsidiary of Microchip Technology Inc.
--
-- 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 Licence 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.
-- ============================================================================
-- This spec has been automatically generated from ATSAMD51J19A.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package SAM_SVD.GCLK is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Control
type GCLK_CTRLA_Register is record
-- Software Reset
SWRST : Boolean := False;
-- unspecified
Reserved_1_7 : HAL.UInt7 := 16#0#;
end record
with Volatile_Full_Access, Size => 8, Bit_Order => System.Low_Order_First;
for GCLK_CTRLA_Register use record
SWRST at 0 range 0 .. 0;
Reserved_1_7 at 0 range 1 .. 7;
end record;
-- Generic Clock Generator Control 0 Synchronization Busy bits
type SYNCBUSY_GENCTRL0Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL0Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 1 Synchronization Busy bits
type SYNCBUSY_GENCTRL1Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL1Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 2 Synchronization Busy bits
type SYNCBUSY_GENCTRL2Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL2Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 3 Synchronization Busy bits
type SYNCBUSY_GENCTRL3Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL3Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 4 Synchronization Busy bits
type SYNCBUSY_GENCTRL4Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL4Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 5 Synchronization Busy bits
type SYNCBUSY_GENCTRL5Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL5Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 6 Synchronization Busy bits
type SYNCBUSY_GENCTRL6Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL6Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 7 Synchronization Busy bits
type SYNCBUSY_GENCTRL7Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL7Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 8 Synchronization Busy bits
type SYNCBUSY_GENCTRL8Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL8Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 9 Synchronization Busy bits
type SYNCBUSY_GENCTRL9Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL9Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 10 Synchronization Busy bits
type SYNCBUSY_GENCTRL10Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL10Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Generic Clock Generator Control 11 Synchronization Busy bits
type SYNCBUSY_GENCTRL11Select is
(-- Generic clock generator 0
Gclk0,
-- Generic clock generator 1
Gclk1,
-- Generic clock generator 2
Gclk2,
-- Generic clock generator 3
Gclk3,
-- Generic clock generator 4
Gclk4,
-- Generic clock generator 5
Gclk5,
-- Generic clock generator 6
Gclk6,
-- Generic clock generator 7
Gclk7,
-- Generic clock generator 8
Gclk8,
-- Generic clock generator 9
Gclk9,
-- Generic clock generator 10
Gclk10,
-- Generic clock generator 11
Gclk11)
with Size => 12;
for SYNCBUSY_GENCTRL11Select use
(Gclk0 => 1,
Gclk1 => 2,
Gclk2 => 4,
Gclk3 => 8,
Gclk4 => 16,
Gclk5 => 32,
Gclk6 => 64,
Gclk7 => 128,
Gclk8 => 256,
Gclk9 => 512,
Gclk10 => 1024,
Gclk11 => 2048);
-- Synchronization Busy
type GCLK_SYNCBUSY_Register is record
-- Read-only. Software Reset Synchroniation Busy bit
SWRST : Boolean;
-- unspecified
Reserved_1_1 : HAL.Bit;
-- Read-only. Generic Clock Generator Control 0 Synchronization Busy
-- bits
GENCTRL : HAL.UInt12;
Reserved_14_31 : HAL.UInt18;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for GCLK_SYNCBUSY_Register use record
SWRST at 0 range 0 .. 0;
Reserved_1_1 at 0 range 1 .. 1;
GENCTRL at 0 range 2 .. 13;
Reserved_14_31 at 0 range 14 .. 31;
end record;
-- Source Select
type GENCTRL_SRCSelect is
(-- XOSC0 oscillator output
Xosc0,
-- XOSC1 oscillator output
Xosc1,
-- Generator input pad
Gclkin,
-- Generic clock generator 1 output
Gclkgen1,
-- OSCULP32K oscillator output
Osculp32K,
-- XOSC32K oscillator output
Xosc32K,
-- DFLL output
Dfll,
-- DPLL0 output
Dpll0,
-- DPLL1 output
Dpll1)
with Size => 4;
for GENCTRL_SRCSelect use
(Xosc0 => 0,
Xosc1 => 1,
Gclkin => 2,
Gclkgen1 => 3,
Osculp32K => 4,
Xosc32K => 5,
Dfll => 6,
Dpll0 => 7,
Dpll1 => 8);
subtype GCLK_GENCTRL_DIV_Field is HAL.UInt16;
-- Generic Clock Generator Control
type GCLK_GENCTRL_Register is record
-- Source Select
SRC : GENCTRL_SRCSelect := SAM_SVD.GCLK.Xosc0;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
-- Generic Clock Generator Enable
GENEN : Boolean := False;
-- Improve Duty Cycle
IDC : Boolean := False;
-- Output Off Value
OOV : Boolean := False;
-- Output Enable
OE : Boolean := False;
-- Divide Selection
DIVSEL : Boolean := False;
-- Run in Standby
RUNSTDBY : Boolean := False;
-- unspecified
Reserved_14_15 : HAL.UInt2 := 16#0#;
-- Division Factor
DIV : GCLK_GENCTRL_DIV_Field := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for GCLK_GENCTRL_Register use record
SRC at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
GENEN at 0 range 8 .. 8;
IDC at 0 range 9 .. 9;
OOV at 0 range 10 .. 10;
OE at 0 range 11 .. 11;
DIVSEL at 0 range 12 .. 12;
RUNSTDBY at 0 range 13 .. 13;
Reserved_14_15 at 0 range 14 .. 15;
DIV at 0 range 16 .. 31;
end record;
-- Generic Clock Generator Control
type GCLK_GENCTRL_Registers is array (0 .. 11) of GCLK_GENCTRL_Register;
-- Generic Clock Generator
type PCHCTRL_GENSelect is new HAL.UInt4
with Size => 4;
-- Peripheral Clock Control
type GCLK_PCHCTRL_Register is record
-- Generic Clock Generator
GEN : PCHCTRL_GENSelect;
-- unspecified
Reserved_4_5 : HAL.UInt2 := 16#0#;
-- Channel Enable
CHEN : Boolean := False;
-- Write Lock
WRTLOCK : Boolean := False;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for GCLK_PCHCTRL_Register use record
GEN at 0 range 0 .. 3;
Reserved_4_5 at 0 range 4 .. 5;
CHEN at 0 range 6 .. 6;
WRTLOCK at 0 range 7 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- Peripheral Clock Control
type GCLK_PCHCTRL_Registers is array (0 .. 47) of GCLK_PCHCTRL_Register;
-----------------
-- Peripherals --
-----------------
-- Generic Clock Generator
type GCLK_Peripheral is record
-- Control
CTRLA : aliased GCLK_CTRLA_Register;
-- Synchronization Busy
SYNCBUSY : aliased GCLK_SYNCBUSY_Register;
-- Generic Clock Generator Control
GENCTRL : aliased GCLK_GENCTRL_Registers;
-- Peripheral Clock Control
PCHCTRL : aliased GCLK_PCHCTRL_Registers;
end record
with Volatile;
for GCLK_Peripheral use record
CTRLA at 16#0# range 0 .. 7;
SYNCBUSY at 16#4# range 0 .. 31;
GENCTRL at 16#20# range 0 .. 383;
PCHCTRL at 16#80# range 0 .. 1535;
end record;
-- Generic Clock Generator
GCLK_Periph : aliased GCLK_Peripheral
with Import, Address => GCLK_Base;
end SAM_SVD.GCLK;
|
--------------------------------------------
-- --
-- PACKAGE GAME - PARTIE ADA --
-- --
-- GAME-GAUDIO.ADS --
-- --
-- Gestion du son (musique et "chunk") --
-- --
-- Créateur : CAPELLE Mikaël --
-- Adresse : capelle.mikael@gmail.com --
-- --
-- Dernière modification : 14 / 06 / 2011 --
-- --
--------------------------------------------
with Interfaces.C;
with Ada.Finalization;
package Game.gAudio is
-- Types servant à stocker des Musique ou des sons court
type Music is limited private;
type Chunk is limited private;
Max_Volume : constant := 128;
type Volume is range 0..Max_Volume;
----------------------------------------
-- FONCTIONS DE GESTION DE LA MUSIQUE --
----------------------------------------
-- Format supporté (en théorie, si erreur merci de me contacter) :
-- .wav
-- .aiff
-- .voc
-- .mod .xm .s3m .669 .it .med
-- .mid
-- .ogg
-- .mp3
-- Charge une musique
procedure Load_Music (Mus : out Music;
Name : in String);
-- Joue la musique
-- Une seule musique peut être joué à la fois
procedure Play_Music(Mus : in Music; -- Musique à jouer
Loops : in Boolean := True; -- En boucle ?
Nb : in Positive := 1); -- Nombre de fois (si pas de boucle)
-- Arrête la musique
procedure Stop_Music;
-- Met la musique en Pause si P vaut True, sinon enlève la pause
procedure Pause_Music(P : in Boolean := True);
-- Vérifie si la musique est en pause ou en train de joué
function Music_Paused return Boolean;
function Music_Playing return Boolean;
-- Recommence la musique depuis le début
procedure Restart_Music;
-- Change le volume de la musique
procedure Set_Music_Volume (V : in Volume);
-------------------------------------------------
-- FONCTION DE GESTION DES SONS COURTS (CHUNK) --
-------------------------------------------------
-- Chaque son court est joué sur un canal (channel) différent
-- Pour affecter un son court, vous devez affecter le canal sur
-- lequel il est joué
-- Format supporté (en théorie, si erreur merci de me contacter) :
-- .wav
-- .aiff
-- .voc
-- .riff
-- .ogg
-- Type Canal, vous pouvez avoir maximum 100 canaux (<=> sons) ouvert en même temps
Last_Channel : constant := 100 ;
type Channel is range 0 .. Last_Channel ;
-- Charge un son court
procedure Load_Chunk (Ch : out Chunk;
Name : in String);
-- Alloue Nb canaux
procedure Allocate_Channel (Nb : in Positive);
-- Joue le son Ch
-- Premier canal libre utilisé dans le premier cas
procedure Play_Channel(Ch : in Chunk; -- Chunk à joeur
Nb : in Positive := 1; -- Nombre de fois que le chunk est joué
Time : in Natural := 0); -- Temps du chunk (si 0, le chunk est joué en entier)
procedure Play_Channel(Ch : in Chunk; -- Chunk à jouer
Chan : in Channel; -- Canal sur lequel jouer le chunk
Nb : in Positive := 1; -- Nombre de fois que le chunk est joué
Time : in Natural := 0); -- Temps du chunk (si 0, le chunk est joué en entier)
-- Stop le canal Ch, pareil qu'au dessus si aucun canal n'est spécifié
procedure Stop_Channel;
procedure Stop_Channel(Ch : in Channel);
-- Met en pause le canal Ch, s'il n'est pas spécifié, met en pause tous les canaux
procedure Pause_Channel(P : in Boolean := True);
procedure Pause_Channel(Chan : in Channel;
P : in Boolean := True);
-- Test si le canal est en pause / en train de joué
function Channel_Paused (Ch : in Channel) return Boolean;
function Channel_Playing(Ch : in Channel) return Boolean;
-- Retourne le nombre de canaux en pause / en train de joué
function Nb_Chan_Paused return Natural;
function Nb_Chan_Playing return Natural;
-- Met le volume du canal C à V
procedure Set_Channel_Volume(V : in Volume);
procedure Set_Channel_Volume(C : in Channel; V : in Volume);
private
package AF renames Ada.Finalization;
-----------
-- MUSIC --
-----------
type SDL_Music is access all Interfaces.C.Int;
Null_SDL_Music : constant SDL_Music := null;
procedure Close_Music (M : in out Music);
type Music is new AF.Controlled with
record
Mus : SDL_Music := Null_SDL_Music;
end record;
procedure Initialize (M : in out Music);
procedure Finalize (M : in out Music);
-----------
-- CHUNK --
-----------
type SDL_Chunk is access all Interfaces.C.Int;
Null_SDL_Chunk : constant SDL_Chunk := null;
procedure Close_Chunk (C : in out Chunk);
type Chunk is new AF.Controlled with
record
Chu : SDL_Chunk := Null_SDL_Chunk;
end record;
procedure Initialize (C : in out Chunk);
procedure Finalize (C : in out Chunk);
end Game.gAudio;
|
package matrices is
type Matriz_De_Enteros is array (Integer range <>, Integer range <>) of Integer;
type Matriz_De_Reales is array (Integer range <>, Integer range <>) of Float;
type Matriz_De_Booleanos is array (Integer range <>, Integer range <>) of Boolean;
type Matriz_De_Caracteres is array (Integer range <>, Integer range <>) of Character;
end matrices;
|
-- { dg-do compile }
-- { dg-options "-gnatws" }
package Rep_Clause2 is
type S is new String;
for S'Component_Size use 256;
type T is new S(1..8);
end Rep_Clause2;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . B B . B O A R D _ S U P P O R T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1999-2002 Universidad Politecnica de Madrid --
-- Copyright (C) 2003-2006 The European Space Agency --
-- Copyright (C) 2003-2020, AdaCore --
-- --
-- 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 3, 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. --
-- --
-- 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/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
-- The port of GNARL to bare board targets was initially developed by the --
-- Real-Time Systems Group at the Technical University of Madrid. --
-- --
------------------------------------------------------------------------------
with Interfaces; use Interfaces;
with System.Machine_Code; use System.Machine_Code;
package body System.BB.Board_Support is
use BB.Interrupts;
-------------------------------
-- Real-Time Interrupt (RTI) --
-------------------------------
RTI_Base : constant Address := 16#FFFF_FC00#;
type RTI_Registers_Type is record
GCTRL : Unsigned_32;
TBCTRL : Unsigned_32;
CAPCTRL : Unsigned_32;
COMPCTRL : Unsigned_32;
FRC0 : Unsigned_32;
UC0 : Unsigned_32;
CPUC0 : Unsigned_32;
Pad_1c : Unsigned_32;
CAFRC0 : Unsigned_32;
CAUC0 : Unsigned_32;
Pad_28 : Unsigned_32;
Pad_2c : Unsigned_32;
FRC1 : Unsigned_32;
UC1 : Unsigned_32;
CPUC1 : Unsigned_32;
Pad_3c : Unsigned_32;
-- Offset: 0x40
CAFRC1 : Unsigned_32;
CAUC1 : Unsigned_32;
Pad_48 : Unsigned_32;
Pad_4c : Unsigned_32;
COMP0 : Unsigned_32;
UDCP0 : Unsigned_32;
COMP1 : Unsigned_32;
UDCP1 : Unsigned_32;
COMP2 : Unsigned_32;
UDCP2 : Unsigned_32;
COMP3 : Unsigned_32;
UDCP3 : Unsigned_32;
TBLCOMP : Unsigned_32;
TBHCOMP : Unsigned_32;
Pad_78 : Unsigned_32;
Pad_7c : Unsigned_32;
-- Offset: 0x80
SETINTENA : Unsigned_32;
CLEARINTENA : Unsigned_32;
INTFLAG : Unsigned_32;
Pad_8c : Unsigned_32;
DWDCTRL : Unsigned_32;
DWDPRLD : Unsigned_32;
WDSTATUS : Unsigned_32;
WDKEY : Unsigned_32;
DWDCNTR : Unsigned_32;
WWDRXNCTRL : Unsigned_32;
WWDSIZECTRL : Unsigned_32;
INTCLRENABLE : Unsigned_32;
COMP0CLR : Unsigned_32;
COMP1CLR : Unsigned_32;
COMP2CLR : Unsigned_32;
COMP3CLR : Unsigned_32;
end record;
RTI : RTI_Registers_Type with Volatile, Import, Address => RTI_Base;
RTI_Compare_Interrupt_3 : constant Interrupt_ID := 5;
-- We use the compare unit 3, so the first counter and the first three
-- compare units are available for use by the user.
procedure Irq_Interrupt_Handler;
pragma Export (C, Irq_Interrupt_Handler, "__gnat_irq_handler");
procedure Fiq_Interrupt_Handler;
pragma Export (C, Fiq_Interrupt_Handler, "__gnat_fiq_handler");
-- Low-level interrupt handlers
--------------------------------------
-- Vectored Interrupt Manager (VIM) --
--------------------------------------
VIM_Base : constant Address := 16#FFFF_FE00#;
type Unsigned_32_Array is array (Natural range <>) of Unsigned_32;
type VIM_Registers_Type is record
IRQINDEX : Unsigned_32;
FIQINDEX : Unsigned_32;
Pad_08 : Unsigned_32;
Pad_0c : Unsigned_32;
-- Register with one bit set for each interrupt that is an FIQ.
-- Interrupt sources 32 and over are not supported as FIQ by this run
-- time. These interrupts should be remapped to lower interrupt channels
-- when required as FIQ. The FIQ_Ints must always include the bits set
-- by NMI_Ints, as the hardware cannot mask these. Initialize_Boards
-- will update this register.
FIRQPR : Unsigned_32_Array (0 .. 3);
INTREQ : Unsigned_32_Array (0 .. 3);
-- Writing a bit mask to this register enables the interrupts
REQENASET : Unsigned_32_Array (0 .. 3);
-- Offset 0x40
-- Writing a bit mask to this register clears the interrupts
REQENACLR : Unsigned_32_Array (0 .. 3);
-- Bit mask allowing corresponding interrupts to wake the processor
WAKEENASET : Unsigned_32_Array (0 .. 3);
WAKEENACLR : Unsigned_32_Array (0 .. 3);
IRQVECREG : Unsigned_32;
FIQVECREG : Unsigned_32;
CAPEVT : Unsigned_32;
Pad_7c : Unsigned_32;
-- Offset 0x80
CHANCTRL : Unsigned_32_Array (0 .. 31);
end record;
VIM : VIM_Registers_Type with Volatile, Import, Address => VIM_Base;
procedure Enable_Interrupt_Request (Interrupt : Interrupt_ID);
-- Enable interrupt requests for the given interrupt
------------------------
-- Interrupt_Handlers --
------------------------
type Interrupt_Vector_Table is array (Interrupt_ID) of Address;
Interrupt_Vectors : Interrupt_Vector_Table;
pragma Volatile (Interrupt_Vectors);
for Interrupt_Vectors'Address use 16#FFF8_2004#;
FIQ_Prio : constant Interrupt_Priority := Interrupt_Priority'Last;
IRQ_Prio : constant Interrupt_Priority := Interrupt_Priority'First;
pragma Assert (FIQ_Prio = IRQ_Prio + 1);
NMI_Ints : constant Unsigned_32 := 3;
-- Bitmap of unmaskable interrupts, namely interrupt channel 0 and 1
FIQ_Masked : Boolean := False;
-- Reflects whether FIQ interrupts are masked in the VIM or not
procedure IRQ_Handler;
pragma Import (Asm, IRQ_Handler, "__gnat_irq_trap");
procedure FIQ_Handler;
pragma Import (Asm, FIQ_Handler, "__gnat_fiq_trap");
----------------------
-- Initialize_Board --
----------------------
procedure Initialize_Board
is
Dead : Unsigned_32 with Unreferenced;
begin
-- Disable all interrupts, except for NMIs
VIM.REQENACLR (0) := not NMI_Ints;
VIM.WAKEENACLR (0) := not 0;
VIM.REQENACLR (1) := not 0;
VIM.WAKEENACLR (1) := not 0;
VIM.REQENACLR (2) := not 0;
VIM.WAKEENACLR (2) := not 0;
if Interrupt_ID'Last > 96 then
VIM.REQENACLR (3) := not 0;
VIM.WAKEENACLR (3) := not 0;
end if;
-- Initialize timer
-- The counter needs to be disabled while programming it
RTI.GCTRL := 0; -- Turn off timers
RTI.TBCTRL := 0; -- Use RTIUC0 to clock counter 0
RTI.CPUC1 := 16#ffff_ffff#; -- Program prescaler compare
RTI.UC1 := 0; -- Start prescaler at 0
RTI.FRC1 := 0; -- Start clock at 0
RTI.CPUC0 := 1; -- Set minimal prescalar for alarm
RTI.COMPCTRL := 0; -- Use timer 0 for comparators
RTI.INTFLAG := 16#0000_700f#; -- Clear all pending interrupts
RTI.CLEARINTENA := 16#0007_0f0f#; -- Disable all interrupts
RTI.SETINTENA := 2**3; -- Enable Interrupt for comparator 3
RTI.GCTRL := 2; -- Turn timer/counter 1 on
end Initialize_Board;
package body Time is
Alarm_Interrupt_ID : constant Interrupt_ID := RTI_Compare_Interrupt_3;
-- Interrupt for the alarm
---------------
-- Set_Alarm --
---------------
procedure Set_Alarm (Ticks : BB.Time.Time)
is
use BB.Time;
Now : constant BB.Time.Time := Read_Clock;
Diff : constant Unsigned_64 := (if Now < Ticks
then Unsigned_64 (Ticks - Now)
else 1);
begin
if Ticks = BB.Time.Time'Last then
Clear_Alarm_Interrupt;
end if;
RTI.INTFLAG := 2**3; -- Clear any pending alarms
RTI.GCTRL := 2; -- Turn off timer/counter 0
RTI.UC0 := 0; -- Start at 0
RTI.FRC0 := 0;
if Diff < (2 ** 33 - 1) then
RTI.CPUC0 := 1; -- Minimal prescaler: RTICLK / 2
RTI.COMP3 := Unsigned_32 ((Diff + 1) / 2);
else
-- Raise an alarm around the target time: it'll be too early but
-- s-bbtime will then re-set it and this time allowing a fine
-- grain delay
RTI.CPUC0 := 16#FFFF_FFFF#;
RTI.COMP3 := Unsigned_32 (Shift_Right (Diff, 32));
end if;
RTI.GCTRL := 3; -- Enable timer 0 and 1
end Set_Alarm;
----------------
-- Read_Clock --
----------------
function Read_Clock return BB.Time.Time
is
Lo, Hi : Unsigned_32;
begin
-- According to TMS570 manual (RTI 17.2.1 Counter and Capture Read
-- Consistency), the free running counter must be read first.
Hi := RTI.FRC1;
Lo := RTI.UC1;
return BB.Time.Time
(Unsigned_64 (Lo) or Shift_Left (Unsigned_64 (Hi), 32));
end Read_Clock;
---------------------------
-- Clear_Alarm_Interrupt --
---------------------------
procedure Clear_Alarm_Interrupt is
begin
RTI.GCTRL := 2; -- Turn off timer/counter 0
RTI.INTFLAG := 2**3;
end Clear_Alarm_Interrupt;
---------------------------
-- Install_Alarm_Handler --
---------------------------
procedure Install_Alarm_Handler
(Handler : BB.Interrupts.Interrupt_Handler) is
begin
BB.Interrupts.Attach_Handler
(Handler,
Alarm_Interrupt_ID,
Interrupts.Priority_Of_Interrupt (Alarm_Interrupt_ID));
end Install_Alarm_Handler;
end Time;
---------------------------
-- Irq_Interrupt_Handler --
---------------------------
procedure Irq_Interrupt_Handler
is
Id : constant Unsigned_32 := VIM.IRQINDEX and 16#FF#;
begin
if Id = 0 then
-- Spurious interrupt
return;
end if;
Interrupt_Wrapper (Interrupt_ID (Id - 1));
end Irq_Interrupt_Handler;
---------------------------
-- Fiq_Interrupt_Handler --
---------------------------
procedure Fiq_Interrupt_Handler
is
Id : constant Unsigned_32 := VIM.FIQINDEX and 16#FF#;
begin
if Id = 0 then
-- Spurious interrupt
return;
end if;
Interrupt_Wrapper (Interrupt_ID (Id - 1));
end Fiq_Interrupt_Handler;
------------------------------
-- Enable_Interrupt_Request --
------------------------------
procedure Enable_Interrupt_Request (Interrupt : Interrupt_ID) is
Reg : constant Natural := Interrupt / 32;
Bit : constant Unsigned_32 := Shift_Left (1, Interrupt mod 32);
-- Many VIM registers use 3 words of 32 bits each to serve as a bitmap
-- for all interrupt channels. Regofs indicates register offset (0..2),
-- and Regbit indicates the mask required for addressing the bit.
begin
VIM.REQENASET (Reg) := Bit;
VIM.WAKEENASET (Reg) := Bit;
end Enable_Interrupt_Request;
package body Multiprocessors is separate;
package body Interrupts is
---------------------------
-- Priority_Of_Interrupt --
---------------------------
function Priority_Of_Interrupt
(Interrupt : Interrupt_ID)
return System.Any_Priority
is
(if Interrupt <= 31 and then (VIM.FIRQPR (0) and 2**Interrupt) /= 0
then FIQ_Prio
else IRQ_Prio);
--------------------------
-- Set_Current_Priority --
--------------------------
procedure Set_Current_Priority (Priority : Integer)
is
begin
-- On the TMS570, FIQs cannot be masked by the processor. So, we need
-- to disable them at the controller when required.
if (Priority = FIQ_Prio) xor FIQ_Masked then
if Priority = FIQ_Prio then
VIM.REQENACLR (0) := VIM.FIRQPR (0);
FIQ_Masked := True;
else
VIM.REQENASET (0) := VIM.FIRQPR (0);
FIQ_Masked := False;
end if;
end if;
end Set_Current_Priority;
-------------------------------
-- Install_Interrupt_Handler --
-------------------------------
procedure Install_Interrupt_Handler
(Interrupt : Interrupt_ID;
Prio : Interrupt_Priority)
is
pragma Unreferenced (Prio);
Hw_Prio : constant Any_Priority := Priority_Of_Interrupt (Interrupt);
begin
-- While we could directly have installed fixed IRQ and FIQ handlers,
-- this would have required that all IRQ and FIQ handlers go through
-- the Ravenscar run time, which is a bit of a limitation. By using
-- the vector capability of the interrupt handler, it is possible to
-- handle some interrupts directly for best performance.
case Interrupt_Priority (Hw_Prio) is
when IRQ_Prio =>
Interrupt_Vectors (Interrupt) := IRQ_Handler'Address;
when FIQ_Prio =>
Interrupt_Vectors (Interrupt) := FIQ_Handler'Address;
end case;
Enable_Interrupt_Request (Interrupt);
end Install_Interrupt_Handler;
----------------
-- Power_Down --
----------------
procedure Power_Down is
begin
Asm ("wfi", Volatile => True);
end Power_Down;
end Interrupts;
end System.BB.Board_Support;
|
with Ada.Unchecked_Deallocation;
package body Graphe is
procedure Initialiser (Graphe : out T_Graphe) is
begin
Graphe := null;
end Initialiser;
procedure Desallouer_Sommet is new Ada.Unchecked_Deallocation (T_Sommet,
T_Graphe);
procedure Desallouer_Arete is new Ada.Unchecked_Deallocation (T_Arete,
T_Liste_Adjacence);
procedure Detruire_Arete (Adjacence : in out T_Liste_Adjacence) is
begin
if Adjacence /= null then
Detruire_Arete (Adjacence.all.Suivante);
end if;
Desallouer_Arete (Adjacence);
end Detruire_Arete;
procedure Detruire (Graphe : in out T_Graphe) is
begin
if Graphe /= null then
-- Détruit proprement un sommet
Detruire_Arete (Graphe.all.Arete);
Detruire (Graphe.all.Suivant);
end if;
Desallouer_Sommet (Graphe);
end Detruire;
function Trouver_Pointeur_Sommet
(Graphe : T_Graphe; Etiquette : T_Etiquette_Sommet) return T_Graphe
is
begin
if Graphe = null then
raise Sommet_Non_Trouve;
elsif Graphe.all.Etiquette = Etiquette then
return Graphe;
else
return Trouver_Pointeur_Sommet (Graphe.all.Suivant, Etiquette);
end if;
end Trouver_Pointeur_Sommet;
procedure Ajouter_Sommet
(Graphe : in out T_Graphe; Etiquette : T_Etiquette_Sommet)
is
Nouveau_Graphe : T_Graphe;
begin
begin
-- On ignore l'ajout si une étiquette du même nom existe déjà
Nouveau_Graphe := Trouver_Pointeur_Sommet (Graphe, Etiquette);
exception
when Sommet_Non_Trouve =>
Nouveau_Graphe := new T_Sommet;
Nouveau_Graphe.all := (Etiquette, null, Graphe);
Graphe := Nouveau_Graphe;
end;
end Ajouter_Sommet;
function Indiquer_Sommet_Existe
(Graphe : T_Graphe; Etiquette : T_Etiquette_Sommet) return Boolean
is
begin
if Graphe = null then
return False;
elsif Graphe.all.Etiquette = Etiquette then
return True;
else
return Indiquer_Sommet_Existe (Graphe.all.Suivant, Etiquette);
end if;
end Indiquer_Sommet_Existe;
function Est_Vide (Graphe : T_Graphe) return Boolean is
begin
return Graphe = null;
end Est_Vide;
procedure Ajouter_Arete
(Graphe : in out T_Graphe; Origine : in T_Etiquette_Sommet;
Etiquette : in T_Etiquette_Arete; Destination : in T_Etiquette_Sommet)
is
Pointeur_Origine : T_Graphe;
Pointeur_Destination : T_Graphe;
Nouvelle_Arete : T_Liste_Adjacence;
begin
Pointeur_Origine := Trouver_Pointeur_Sommet (Graphe, Origine);
Pointeur_Destination := Trouver_Pointeur_Sommet (Graphe, Destination);
Nouvelle_Arete := new T_Arete;
Nouvelle_Arete.all :=
(Etiquette, Pointeur_Destination, Pointeur_Origine.all.Arete);
Pointeur_Origine.all.Arete := Nouvelle_Arete;
end Ajouter_Arete;
procedure Chaine_Adjacence
(Adjacence : out T_Liste_Adjacence; Graphe : in T_Graphe;
Origine : in T_Etiquette_Sommet)
is
begin
Adjacence := Trouver_Pointeur_Sommet (Graphe, Origine).all.Arete;
end Chaine_Adjacence;
function Adjacence_Non_Vide (Adjacence : T_Liste_Adjacence) return Boolean
is
begin
return Adjacence /= null;
end Adjacence_Non_Vide;
procedure Arete_Suivante
(Adjacence : in out T_Liste_Adjacence; Arete : out T_Arete_Etiquetee)
is
begin
if Adjacence = null then
raise Vide;
end if;
Arete :=
(Adjacence.all.Etiquette, Adjacence.all.Destination.all.Etiquette);
Adjacence := Adjacence.all.Suivante;
end Arete_Suivante;
procedure Supprimer_Arete
(Graphe : in T_Graphe; Origine : in T_Etiquette_Sommet;
Etiquette_Arete : in T_Etiquette_Arete;
Destination : in T_Etiquette_Sommet)
is
A_Detruire : T_Liste_Adjacence;
Pointeur : T_Graphe;
Pointeur_Arete : T_Liste_Adjacence;
begin
Pointeur := Trouver_Pointeur_Sommet (Graphe, Origine);
Pointeur_Arete := Pointeur.all.Arete;
if Pointeur_Arete = null then
return;
end if;
-- Cas où c'est au début de la liste d'adjacence
if Pointeur_Arete.all.Etiquette = Etiquette_Arete and
Pointeur_Arete.all.Destination.all.Etiquette = Destination
then
A_Detruire := Pointeur_Arete;
Pointeur.all.Arete := Pointeur_Arete.all.Suivante;
Detruire_Arete (A_Detruire);
return;
end if;
-- Cas général
while Pointeur_Arete.all.Suivante /= null loop
if Pointeur_Arete.all.Suivante.all.Etiquette = Etiquette_Arete and
Pointeur_Arete.all.Suivante.all.Destination.all.Etiquette =
Destination
then
A_Detruire := Pointeur_Arete.all.Suivante;
Pointeur_Arete.all.Suivante :=
Pointeur_Arete.all.Suivante.all.Suivante;
-- Bien nettoyer la mémoire
Desallouer_Arete (A_Detruire);
return;
end if;
Pointeur_Arete := Pointeur_Arete.all.Suivante;
end loop;
end Supprimer_Arete;
procedure Appliquer_Sur_Tous_Sommets (Graphe : in T_Graphe) is
begin
if Graphe /= null then
P (Graphe.all.Etiquette, Graphe.all.Arete);
Appliquer_Sur_Tous_Sommets (Graphe.all.Suivant);
end if;
end Appliquer_Sur_Tous_Sommets;
end Graphe;
|
-- SPDX-License-Identifier: MIT
--
-- Copyright (c) 1999 - 2018 Gautier de Montmollin
-- SWITZERLAND
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
with Ada.Unchecked_Deallocation;
package body DCF.Unzip.Decompress.Huffman is
-- Note from Pascal source:
-- C code by info-zip group, translated to pascal by Christian Ghisler
-- based on unz51g.zip
-- Free huffman tables starting with table where t points to
procedure Huft_Free (Tl : in out P_Table_List) is
procedure Dispose is new Ada.Unchecked_Deallocation (Huft_Table, P_Huft_Table);
procedure Dispose is new Ada.Unchecked_Deallocation (Table_List, P_Table_List);
Current : P_Table_List;
begin
while Tl /= null loop
Dispose (Tl.Table); -- Destroy the Huffman table
Current := Tl;
Tl := Tl.Next;
Dispose (Current); -- Destroy the current node
end loop;
end Huft_Free;
-- Build huffman table from code lengths given by array b
procedure Huft_Build
(B : Length_Array;
S : Integer;
D, E : Length_Array;
Tl : out P_Table_List;
M : in out Integer;
Huft_Incomplete : out Boolean)
is
B_Max : constant := 16;
B_Maxp1 : constant := B_Max + 1;
-- Bit length count table
Count : array (0 .. B_Maxp1) of Integer := (others => 0);
F : Integer; -- I repeats in table every f entries
G : Integer; -- Maximum code length
I : Integer; -- Counter, current code
J : Integer; -- Counter
Kcc : Integer; -- Number of bits in current code
C_Idx, V_Idx : Natural; -- Array indices
Current_Table_Ptr : P_Huft_Table := null;
Current_Node_Ptr : P_Table_List := null; -- Current node for the current table
New_Node_Ptr : P_Table_List; -- New node for the new table
New_Entry : Huft; -- Table entry for structure assignment
U : array (0 .. B_Max) of P_Huft_Table; -- Table stack
N_Max : constant := 288;
-- Values in order of bit length
V : array (0 .. N_Max) of Integer := (others => 0);
El_V, El_V_M_S : Integer;
W : Natural := 0; -- Bits before this table
Offset, Code_Stack : array (0 .. B_Maxp1) of Integer;
Table_Level : Integer := -1;
Bits : array (Integer'(-1) .. B_Maxp1) of Integer;
-- ^ bits(table_level) = # bits in table of level table_level
Y : Integer; -- Number of dummy codes added
Z : Natural := 0; -- Number of entries in current table
El : Integer; -- Length of eob code=code 256
No_Copy_Length_Array : constant Boolean := D'Length = 0 or E'Length = 0;
begin
Tl := null;
if B'Length > 256 then -- Set length of EOB code, if any
El := B (256);
else
El := B_Max;
end if;
-- Generate counts for each bit length
for K in B'Range loop
if B (K) > B_Max then
-- m := 0; -- GNAT 2005 doesn't like it (warning).
raise Huft_Error;
end if;
Count (B (K)) := Count (B (K)) + 1;
end loop;
if Count (0) = B'Length then
M := 0;
Huft_Incomplete := False; -- Spotted by Tucker Taft, 19-Aug-2004
return; -- Complete
end if;
-- Find minimum and maximum length, bound m by those
J := 1;
while J <= B_Max and then Count (J) = 0 loop
J := J + 1;
end loop;
Kcc := J;
if M < J then
M := J;
end if;
I := B_Max;
while I > 0 and then Count (I) = 0 loop
I := I - 1;
end loop;
G := I;
if M > I then
M := I;
end if;
-- Adjust last length count to fill out codes, if needed
Y := Integer (Shift_Left (Unsigned_32'(1), J)); -- y:= 2 ** j;
while J < I loop
Y := Y - Count (J);
if Y < 0 then
raise Huft_Error;
end if;
Y := Y * 2;
J := J + 1;
end loop;
Y := Y - Count (I);
if Y < 0 then
raise Huft_Error;
end if;
Count (I) := Count (I) + Y;
-- Generate starting offsets into the value table for each length
Offset (1) := 0;
J := 0;
for Idx in 2 .. I loop
J := J + Count (Idx - 1);
Offset (Idx) := J;
end loop;
-- Make table of values in order of bit length
for Idx in B'Range loop
J := B (Idx);
if J /= 0 then
V (Offset (J)) := Idx - B'First;
Offset (J) := Offset (J) + 1;
end if;
end loop;
-- Generate huffman codes and for each, make the table entries
Code_Stack (0) := 0;
I := 0;
V_Idx := V'First;
Bits (-1) := 0;
-- Go through the bit lengths (kcc already is bits in shortest code)
for K in Kcc .. G loop
for Am1 in reverse 0 .. Count (K) - 1 loop -- A counts codes of length k
-- Here i is the huffman code of length k bits for value v(v_idx)
while K > W + Bits (Table_Level) loop
W := W + Bits (Table_Level); -- Length of tables to this position
Table_Level := Table_Level + 1;
Z := G - W; -- Compute min size table <= m bits
if Z > M then
Z := M;
end if;
J := K - W;
F := Integer (Shift_Left (Unsigned_32'(1), J)); -- f:= 2 ** j;
if F > Am1 + 2 then
-- Try a k-w bit table
F := F - (Am1 + 2);
C_Idx := K;
-- Try smaller tables up to z bits
loop
J := J + 1;
exit when J >= Z;
F := F * 2;
C_Idx := C_Idx + 1;
exit when F - Count (C_Idx) <= 0;
F := F - Count (C_Idx);
end loop;
end if;
if W + J > El and then W < El then
J := El - W; -- Make EOB code end at table
end if;
if W = 0 then
J := M; -- Fix: main table always m bits!
end if;
Z := Integer (Shift_Left (Unsigned_32'(1), J)); -- z:= 2 ** j;
Bits (Table_Level) := J;
-- Allocate and link new table
begin
Current_Table_Ptr := new Huft_Table (0 .. Z);
New_Node_Ptr := new Table_List'(Current_Table_Ptr, null);
exception
when Storage_Error =>
raise Huft_Out_Of_Memory;
end;
if Current_Node_Ptr = null then -- First table
Tl := New_Node_Ptr;
else
Current_Node_Ptr.Next := New_Node_Ptr; -- Not my first...
end if;
Current_Node_Ptr := New_Node_Ptr; -- Always non-Null from there
U (Table_Level) := Current_Table_Ptr;
-- Connect to last table, if there is one
if Table_Level > 0 then
Code_Stack (Table_Level) := I;
New_Entry.Bits := Bits (Table_Level - 1);
New_Entry.Extra_Bits := 16 + J;
New_Entry.Next_Table := Current_Table_Ptr;
J :=
Integer
(Shift_Right
(Unsigned_32 (I) and (Shift_Left (Unsigned_32'(1), W) - 1),
W - Bits (Table_Level - 1)));
-- Test against bad input!
if J > U (Table_Level - 1)'Last then
raise Huft_Error;
end if;
U (Table_Level - 1) (J) := New_Entry;
end if;
end loop;
-- Set up table entry in new_entry
New_Entry.Bits := K - W;
New_Entry.Next_Table := null; -- Unused
if V_Idx >= B'Length then
New_Entry.Extra_Bits := Invalid;
else
El_V := V (V_Idx);
El_V_M_S := El_V - S;
if El_V_M_S < 0 then
-- Simple code, raw value
if El_V < 256 then
New_Entry.Extra_Bits := 16;
else
New_Entry.Extra_Bits := 15;
end if;
New_Entry.N := El_V;
else
-- Non-simple -> lookup in lists
if No_Copy_Length_Array then
raise Huft_Error;
end if;
New_Entry.Extra_Bits := E (El_V_M_S);
New_Entry.N := D (El_V_M_S);
end if;
V_Idx := V_Idx + 1;
end if;
-- Fill code-like entries with new_entry
F := Integer (Shift_Left (Unsigned_32'(1), K - W));
-- i.e. f := 2 ** (k-w);
J := Integer (Shift_Right (Unsigned_32 (I), W));
while J < Z loop
Current_Table_Ptr (J) := New_Entry;
J := J + F;
end loop;
-- Backwards increment the k-bit code i
J := Integer (Shift_Left (Unsigned_32'(1), K - 1));
-- i.e.: j:= 2 ** (k-1)
while (Unsigned_32 (I) and Unsigned_32 (J)) /= 0 loop
I := Integer (Unsigned_32 (I) xor Unsigned_32 (J));
J := J / 2;
end loop;
I := Integer (Unsigned_32 (I) xor Unsigned_32 (J));
-- Backup over finished tables
while Integer (Unsigned_32 (I) and (Shift_Left (1, W) - 1)) /= Code_Stack (Table_Level)
loop
Table_Level := Table_Level - 1;
W := W - Bits (Table_Level); -- Size of previous table!
end loop;
end loop;
end loop;
Huft_Incomplete := Y /= 0 and G /= 1;
exception
when others =>
Huft_Free (Tl);
raise;
end Huft_Build;
end DCF.Unzip.Decompress.Huffman;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M L I B . T G T --
-- (Default Version) --
-- --
-- B o d y --
-- --
-- $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. --
-- --
-- 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 is the default version which does not support libraries.
-- All subprograms are dummies, because they are never called,
-- except Libraries_Are_Supported which returns False.
package body MLib.Tgt is
-----------------
-- Archive_Ext --
-----------------
function Archive_Ext return String is
begin
return "";
end Archive_Ext;
-----------------
-- Base_Option --
-----------------
function Base_Option return String is
begin
return "";
end Base_Option;
---------------------------
-- Build_Dynamic_Library --
---------------------------
procedure Build_Dynamic_Library
(Ofiles : Argument_List;
Foreign : Argument_List;
Afiles : Argument_List;
Options : Argument_List;
Lib_Filename : String;
Lib_Dir : String;
Lib_Address : String := "";
Lib_Version : String := "";
Relocatable : Boolean := False)
is
begin
null;
end Build_Dynamic_Library;
--------------------
-- Copy_ALI_Files --
--------------------
procedure Copy_ALI_Files
(From : Name_Id;
To : Name_Id)
is
begin
null;
end Copy_ALI_Files;
-------------------------
-- Default_DLL_Address --
-------------------------
function Default_DLL_Address return String is
begin
return "";
end Default_DLL_Address;
-------------
-- DLL_Ext --
-------------
function DLL_Ext return String is
begin
return "";
end DLL_Ext;
--------------------
-- Dynamic_Option --
--------------------
function Dynamic_Option return String is
begin
return "";
end Dynamic_Option;
-------------------
-- Is_Object_Ext --
-------------------
function Is_Object_Ext (Ext : String) return Boolean is
begin
return False;
end Is_Object_Ext;
--------------
-- Is_C_Ext --
--------------
function Is_C_Ext (Ext : String) return Boolean is
begin
return False;
end Is_C_Ext;
--------------------
-- Is_Archive_Ext --
--------------------
function Is_Archive_Ext (Ext : String) return Boolean is
begin
return False;
end Is_Archive_Ext;
-------------
-- Libgnat --
-------------
function Libgnat return String is
begin
return "libgnat.a";
end Libgnat;
-----------------------------
-- Libraries_Are_Supported --
-----------------------------
function Libraries_Are_Supported return Boolean is
begin
return False;
end Libraries_Are_Supported;
--------------------------------
-- Linker_Library_Path_Option --
--------------------------------
function Linker_Library_Path_Option
(Directory : String)
return String_Access
is
begin
return null;
end Linker_Library_Path_Option;
----------------
-- Object_Ext --
----------------
function Object_Ext return String is
begin
return "";
end Object_Ext;
----------------
-- PIC_Option --
----------------
function PIC_Option return String is
begin
return "";
end PIC_Option;
end MLib.Tgt;
|
package AdaCar.Organizador_Movimiento is
procedure Nueva_Distancia_Sensor(Valor: Unidades_Distancia);
end AdaCar.Organizador_Movimiento;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
procedure Test_Loop_Break is
type Value_Type is range 0..19;
package Random_Values is new Ada.Numerics.Discrete_Random (Value_Type);
use Random_Values;
Dice : Generator;
A, B : Value_Type;
begin
loop
A := Random (Dice);
Put_Line (Value_Type'Image (A));
exit when A = 10;
B := Random (Dice);
Put_Line (Value_Type'Image (B));
end loop;
end Test_Loop_Break;
|
with
Interfaces.C.Strings,
System;
use type
System.Address;
package body FLTK.Widgets.Inputs.Outputs is
procedure output_set_draw_hook
(W, D : in System.Address);
pragma Import (C, output_set_draw_hook, "output_set_draw_hook");
pragma Inline (output_set_draw_hook);
procedure output_set_handle_hook
(W, H : in System.Address);
pragma Import (C, output_set_handle_hook, "output_set_handle_hook");
pragma Inline (output_set_handle_hook);
function new_fl_output
(X, Y, W, H : in Interfaces.C.int;
Text : in Interfaces.C.char_array)
return System.Address;
pragma Import (C, new_fl_output, "new_fl_output");
pragma Inline (new_fl_output);
procedure free_fl_output
(F : in System.Address);
pragma Import (C, free_fl_output, "free_fl_output");
pragma Inline (free_fl_output);
procedure fl_output_draw
(W : in System.Address);
pragma Import (C, fl_output_draw, "fl_output_draw");
pragma Inline (fl_output_draw);
function fl_output_handle
(W : in System.Address;
E : in Interfaces.C.int)
return Interfaces.C.int;
pragma Import (C, fl_output_handle, "fl_output_handle");
pragma Inline (fl_output_handle);
procedure Finalize
(This : in out Output) is
begin
if This.Void_Ptr /= System.Null_Address and then
This in Output'Class
then
free_fl_output (This.Void_Ptr);
This.Void_Ptr := System.Null_Address;
end if;
Finalize (Input (This));
end Finalize;
package body Forge is
function Create
(X, Y, W, H : in Integer;
Text : in String)
return Output is
begin
return This : Output do
This.Void_Ptr := new_fl_output
(Interfaces.C.int (X),
Interfaces.C.int (Y),
Interfaces.C.int (W),
Interfaces.C.int (H),
Interfaces.C.To_C (Text));
fl_widget_set_user_data
(This.Void_Ptr,
Widget_Convert.To_Address (This'Unchecked_Access));
output_set_draw_hook (This.Void_Ptr, Draw_Hook'Address);
output_set_handle_hook (This.Void_Ptr, Handle_Hook'Address);
end return;
end Create;
end Forge;
procedure Draw
(This : in out Output) is
begin
fl_output_draw (This.Void_Ptr);
end Draw;
function Handle
(This : in out Output;
Event : in Event_Kind)
return Event_Outcome is
begin
return Event_Outcome'Val
(fl_output_handle (This.Void_Ptr, Event_Kind'Pos (Event)));
end Handle;
end FLTK.Widgets.Inputs.Outputs;
|
package Yeison_Multi with Preelaborate is
type Any is tagged private;
type Scalar is tagged private with
Integer_Literal => To_Int,
String_Literal => To_Str;
function To_Int (Img : String) return Scalar;
function To_Str (Img : Wide_Wide_String) return Scalar;
type Map is tagged private with
Aggregate => (Empty => Empty,
Add_Named => Insert);
function Empty return Map;
procedure Insert (This : in out Map; Key : String; Val : Any'Class);
procedure Insert (This : in out Map; Key : String; Val : Scalar'Class);
procedure Insert (This : in out Map; Key : String; Val : Map);
private
type Any is tagged null record;
type Scalar is tagged null record;
type Map is tagged null record;
end Yeison_Multi;
|
-- { dg-do compile }
-- { dg-options "-O -gnatn" }
with Ada.Text_IO; use Ada.Text_IO;
with Controlled6_Pkg;
with Controlled6_Pkg.Iterators;
procedure Controlled6 is
type String_Access is access String;
package My_Q is new Controlled6_Pkg (String_Access);
package My_Iterators is new My_Q.Iterators (0);
use My_Iterators;
Iterator : Iterator_Type := Find;
begin
loop
exit when Is_Null (Iterator);
Put (Current (Iterator).all & ' ');
Find_Next (Iterator);
end loop;
end;
|
--//////////////////////////////////////////////////////////
-- SFML - Simple and Fast Multimedia Library
-- Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
-- This software is provided 'as-is', without any express or implied warranty.
-- In no event will the authors be held liable for any damages arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it freely,
-- subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented;
-- you must not claim that you wrote the original software.
-- If you use this software in a product, an acknowledgment
-- in the product documentation would be appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such,
-- and must not be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
with Sf.System.Time;
package Sf.Network.Http is
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--/ @brief Enumerate the available HTTP methods for a request
--/
--//////////////////////////////////////////////////////////
--/< Request in get mode, standard method to retrieve a page
--/< Request in post mode, usually to send data to a page
--/< Request a page's header only
--/< Request in put mode, useful for a REST API
--/< Request in delete mode, useful for a REST API
type sfHttpMethod is
(sfHttpGet,
sfHttpPost,
sfHttpHead,
sfHttpPut,
sfHttpDelete);
--//////////////////////////////////////////////////////////
--/ @brief Enumerate all the valid status codes for a response
--/
--//////////////////////////////////////////////////////////
-- 2xx: success
--/< Most common code returned when operation was successful
--/< The resource has successfully been created
--/< The request has been accepted, but will be processed later by the server
--/< Sent when the server didn't send any data in return
--/< The server informs the client that it should clear the view (form) that caused the request to be sent
--/< The server has sent a part of the resource, as a response to a partial GET request
-- 3xx: redirection
--/< The requested page can be accessed from several locations
--/< The requested page has permanently moved to a new location
--/< The requested page has temporarily moved to a new location
--/< For conditional requests, means the requested page hasn't changed and doesn't need to be refreshed
-- 4xx: client error
--/< The server couldn't understand the request (syntax error)
--/< The requested page needs an authentication to be accessed
--/< The requested page cannot be accessed at all, even with authentication
--/< The requested page doesn't exist
--/< The server can't satisfy the partial GET request (with a "Range" header field)
-- 5xx: server error
--/< The server encountered an unexpected error
--/< The server doesn't implement a requested feature
--/< The gateway server has received an error from the source server
--/< The server is temporarily unavailable (overloaded, in maintenance, ...)
--/< The gateway server couldn't receive a response from the source server
--/< The server doesn't support the requested HTTP version
-- 10xx: SFML custom codes
--/< Response is not a valid HTTP one
--/< Connection with server failed
subtype sfHttpStatus is sfUint32;
sfHttpOk : constant sfHttpStatus := 200;
sfHttpCreated : constant sfHttpStatus := 201;
sfHttpAccepted : constant sfHttpStatus := 202;
sfHttpNoContent : constant sfHttpStatus := 204;
sfHttpResetContent : constant sfHttpStatus := 205;
sfHttpPartialContent : constant sfHttpStatus := 206;
sfHttpMultipleChoices : constant sfHttpStatus := 300;
sfHttpMovedPermanently : constant sfHttpStatus := 301;
sfHttpMovedTemporarily : constant sfHttpStatus := 302;
sfHttpNotModified : constant sfHttpStatus := 304;
sfHttpBadRequest : constant sfHttpStatus := 400;
sfHttpUnauthorized : constant sfHttpStatus := 401;
sfHttpForbidden : constant sfHttpStatus := 403;
sfHttpNotFound : constant sfHttpStatus := 404;
sfHttpRangeNotSatisfiable : constant sfHttpStatus := 407;
sfHttpInternalServerError : constant sfHttpStatus := 500;
sfHttpNotImplemented : constant sfHttpStatus := 501;
sfHttpBadGateway : constant sfHttpStatus := 502;
sfHttpServiceNotAvailable : constant sfHttpStatus := 503;
sfHttpGatewayTimeout : constant sfHttpStatus := 504;
sfHttpVersionNotSupported : constant sfHttpStatus := 505;
sfHttpInvalidResponse : constant sfHttpStatus := 1000;
sfHttpConnectionFailed : constant sfHttpStatus := 1001;
package Request is
--//////////////////////////////////////////////////////////
--/ @brief Create a new HTTP request
--/
--/ @return A new sfHttpRequest object
--/
--//////////////////////////////////////////////////////////
function create return sfHttpRequest_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Destroy a HTTP request
--/
--/ @param httpRequest HTTP request to destroy
--/
--//////////////////////////////////////////////////////////
procedure destroy (httpRequest : sfHttpRequest_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Set the value of a header field of a HTTP request
--/
--/ The field is created if it doesn't exist. The name of
--/ the field is case insensitive.
--/ By default, a request doesn't contain any field (but the
--/ mandatory fields are added later by the HTTP client when
--/ sending the request).
--/
--/ @param httpRequest HTTP request
--/ @param field Name of the field to set
--/ @param value Value of the field
--/
--//////////////////////////////////////////////////////////
procedure setField
(httpRequest : sfHttpRequest_Ptr;
field : String;
value : String);
--//////////////////////////////////////////////////////////
--/ @brief Set a HTTP request method
--/
--/ See the sfHttpMethod enumeration for a complete list of all
--/ the availale methods.
--/ The method is sfHttpGet by default.
--/
--/ @param httpRequest HTTP request
--/ @param method Method to use for the request
--/
--//////////////////////////////////////////////////////////
procedure setMethod (httpRequest : sfHttpRequest_Ptr;
method : sfHttpMethod);
--//////////////////////////////////////////////////////////
--/ @brief Set a HTTP request URI
--/
--/ The URI is the resource (usually a web page or a file)
--/ that you want to get or post.
--/ The URI is "/" (the root page) by default.
--/
--/ @param httpRequest HTTP request
--/ @param uri URI to request, relative to the host
--/
--//////////////////////////////////////////////////////////
procedure setUri (httpRequest : sfHttpRequest_Ptr;
uri : String);
--//////////////////////////////////////////////////////////
--/ @brief Set the HTTP version of a HTTP request
--/
--/ The HTTP version is 1.0 by default.
--/
--/ @param httpRequest HTTP request
--/ @param major Major HTTP version number
--/ @param minor Minor HTTP version number
--/
--//////////////////////////////////////////////////////////
procedure setHttpVersion
(httpRequest : sfHttpRequest_Ptr;
major : sfUint32;
minor : sfUint32);
--//////////////////////////////////////////////////////////
--/ @brief Set the body of a HTTP request
--/
--/ The body of a request is optional and only makes sense
--/ for POST requests. It is ignored for all other methods.
--/ The body is empty by default.
--/
--/ @param httpRequest HTTP request
--/ @param httpBody Content of the body
--/
--//////////////////////////////////////////////////////////
procedure setBody (httpRequest : sfHttpRequest_Ptr;
httpBody : String);
private
pragma Import (C, create, "sfHttpRequest_create");
pragma Import (C, destroy, "sfHttpRequest_destroy");
pragma Import (C, setMethod, "sfHttpRequest_setMethod");
pragma Import (C, setHttpVersion, "sfHttpRequest_setHttpVersion");
end Request;
package Response is
--//////////////////////////////////////////////////////////
--/ @brief Destroy a HTTP response
--/
--/ @param httpResponse HTTP response to destroy
--/
--//////////////////////////////////////////////////////////
procedure destroy (httpResponse : sfHttpResponse_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Get the value of a field of a HTTP response
--/
--/ If the field @a field is not found in the response header,
--/ the empty string is returned. This function uses
--/ case-insensitive comparisons.
--/
--/ @param httpResponse HTTP response
--/ @param field Name of the field to get
--/
--/ @return Value of the field, or empty string if not found
--/
--//////////////////////////////////////////////////////////
function getField (httpResponse : sfHttpResponse_Ptr;
field : String) return String;
--//////////////////////////////////////////////////////////
--/ @brief Get the status code of a HTTP reponse
--/
--/ The status code should be the first thing to be checked
--/ after receiving a response, it defines whether it is a
--/ success, a failure or anything else (see the sfHttpStatus
--/ enumeration).
--/
--/ @param httpResponse HTTP response
--/
--/ @return Status code of the response
--/
--//////////////////////////////////////////////////////////
function getStatus (httpResponse : sfHttpResponse_Ptr) return sfHttpStatus;
--//////////////////////////////////////////////////////////
--/ @brief Get the major HTTP version number of a HTTP response
--/
--/ @param httpResponse HTTP response
--/
--/ @return Major HTTP version number
--/
--//////////////////////////////////////////////////////////
function getMajorVersion (httpResponse : sfHttpResponse_Ptr) return sfUint32;
--//////////////////////////////////////////////////////////
--/ @brief Get the minor HTTP version number of a HTTP response
--/
--/ @param httpResponse HTTP response
--/
--/ @return Minor HTTP version number
--/
--//////////////////////////////////////////////////////////
function getMinorVersion (httpResponse : sfHttpResponse_Ptr) return sfUint32;
--//////////////////////////////////////////////////////////
--/ @brief Get the body of a HTTP response
--/
--/ The body of a response may contain:
--/ @li the requested page (for GET requests)
--/ @li a response from the server (for POST requests)
--/ @li nothing (for HEAD requests)
--/ @li an error message (in case of an error)
--/
--/ @param httpResponse HTTP response
--/
--/ @return The response body
--/
--//////////////////////////////////////////////////////////
function getBody (httpResponse : sfHttpResponse_Ptr) return String;
private
pragma Import (C, destroy, "sfHttpResponse_destroy");
pragma Import (C, getStatus, "sfHttpResponse_getStatus");
pragma Import (C, getMajorVersion, "sfHttpResponse_getMajorVersion");
pragma Import (C, getMinorVersion, "sfHttpResponse_getMinorVersion");
end Response;
--//////////////////////////////////////////////////////////
--/ @brief Create a new Http object
--/
--/ @return A new sfHttp object
--/
--//////////////////////////////////////////////////////////
function create return sfHttp_Ptr;
--//////////////////////////////////////////////////////////
--/ @brief Destroy a Http object
--/
--/ @param http Http object to destroy
--/
--//////////////////////////////////////////////////////////
procedure destroy (http : sfHttp_Ptr);
--//////////////////////////////////////////////////////////
--/ @brief Set the target host of a HTTP object
--/
--/ This function just stores the host address and port, it
--/ doesn't actually connect to it until you send a request.
--/ If the port is 0, it means that the HTTP client will use
--/ the right port according to the protocol used
--/ (80 for HTTP, 443 for HTTPS). You should
--/ leave it like this unless you really need a port other
--/ than the standard one, or use an unknown protocol.
--/
--/ @param http Http object
--/ @param host Web server to connect to
--/ @param port Port to use for connection
--/
--//////////////////////////////////////////////////////////
procedure setHost
(http : sfHttp_Ptr;
host : String;
port : sfUint16);
--//////////////////////////////////////////////////////////
--/ @brief Send a HTTP request and return the server's response.
--/
--/ You must have a valid host before sending a request (see sfHttp_setHost).
--/ Any missing mandatory header field in the request will be added
--/ with an appropriate value.
--/ Warning: this function waits for the server's response and may
--/ not return instantly; use a thread if you don't want to block your
--/ application, or use a timeout to limit the time to wait. A value
--/ of 0 means that the client will use the system defaut timeout
--/ (which is usually pretty long).
--/
--/ @param http Http object
--/ @param request Request to send
--/ @param timeout Maximum time to wait
--/
--/ @return Server's response
--/
--//////////////////////////////////////////////////////////
function sendRequest
(http : sfHttp_Ptr;
request : sfHttpRequest_Ptr;
timeout : Sf.System.Time.sfTime) return sfHttpResponse_Ptr;
private
pragma Convention (C, sfHttpMethod);
pragma Import (C, create, "sfHttp_create");
pragma Import (C, destroy, "sfHttp_destroy");
pragma Import (C, sendRequest, "sfHttp_sendRequest");
end Sf.Network.Http;
|
with ObjectPack;
use ObjectPack;
package VisitablePackage is
type Visitable is interface and Object;
type VisitablePtr is access all Visitable'Class;
function getChildCount(v: access Visitable) return Integer is abstract;
function setChildren(v: access Visitable ; children : ObjectPtrArrayPtr) return VisitablePtr is abstract;
function getChildren(v: access Visitable) return ObjectPtrArrayPtr is abstract;
function getChildAt(v: access Visitable; i : Integer) return VisitablePtr is abstract;
function setChildAt(v: access Visitable; i: in Integer; child: in VisitablePtr) return VisitablePtr is abstract;
end VisitablePackage;
|
package Memory_Analyzer is
function Count (Size : Integer; File : String; Var : String) return Boolean;
end Memory_Analyzer;
|
-- Copyright (C) 2019 Thierry Rascle <thierr26@free.fr>
-- MIT license. Please refer to the LICENSE file.
with Apsepp.Test_Node_Class.Suite_Stub; use Apsepp.Test_Node_Class.Suite_Stub;
use Apsepp.Test_Node_Class;
package Apsepp.Abstract_Test_Suite is
subtype Test_Node_Array is Apsepp.Test_Node_Class.Test_Node_Array;
type Test_Suite is abstract limited new Test_Suite_Stub with private;
not overriding
function Child_Array (Obj : Test_Suite) return Test_Node_Array
is abstract;
overriding
function Child_Count (Obj : Test_Suite) return Test_Node_Count
is (Test_Suite'Class (Obj).Child_Array'Length);
overriding
function Child (Obj : Test_Suite;
K : Test_Node_Index) return Test_Node_Access
is (Test_Suite'Class (Obj).Child_Array (K));
overriding
function Routine (Obj : Test_Suite;
K : Test_Routine_Index) return Test_Routine;
procedure Run_Body (Obj : Test_Node_Interfa'Class;
Outcome : out Test_Outcome;
Kind : Run_Kind;
Cond : not null access function return Boolean)
renames Test_Node_Class.Suite_Stub.Run_Body;
private
type Test_Suite is abstract limited new Test_Suite_Stub with null record;
end Apsepp.Abstract_Test_Suite;
|
-- C85014A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT THE NUMBER OF FORMAL PARAMETERS IS USED TO DETERMINE
-- WHICH SUBPROGRAM OR ENTRY IS BEING RENAMED.
-- HISTORY:
-- JET 03/24/88 CREATED ORIGINAL TEST.
-- BCB 04/18/90 CORRECTED ERROR MESSAGE FOR ENTRY2.
WITH REPORT; USE REPORT;
PROCEDURE C85014A IS
TASK TYPE T1 IS
ENTRY ENTER (I1: IN OUT INTEGER);
ENTRY STOP;
END T1;
TASK TYPE T2 IS
ENTRY ENTER (I1, I2: IN OUT INTEGER);
ENTRY STOP;
END T2;
TASK1 : T1;
TASK2 : T2;
FUNCTION F RETURN T1 IS
BEGIN
RETURN TASK1;
END F;
FUNCTION F RETURN T2 IS
BEGIN
RETURN TASK2;
END F;
PROCEDURE PROC (I1: IN OUT INTEGER) IS
BEGIN
I1 := I1 + 1;
END PROC;
PROCEDURE PROC (I1, I2: IN OUT INTEGER) IS
BEGIN
I1 := I1 + 2;
I2 := I2 + 2;
END PROC;
TASK BODY T1 IS
ACCEPTING_ENTRIES : BOOLEAN := TRUE;
BEGIN
WHILE ACCEPTING_ENTRIES LOOP
SELECT
ACCEPT ENTER (I1 : IN OUT INTEGER) DO
I1 := I1 + 1;
END ENTER;
OR
ACCEPT STOP DO
ACCEPTING_ENTRIES := FALSE;
END STOP;
END SELECT;
END LOOP;
END T1;
TASK BODY T2 IS
ACCEPTING_ENTRIES : BOOLEAN := TRUE;
BEGIN
WHILE ACCEPTING_ENTRIES LOOP
SELECT
ACCEPT ENTER (I1, I2 : IN OUT INTEGER) DO
I1 := I1 + 2;
I2 := I2 + 2;
END ENTER;
OR
ACCEPT STOP DO
ACCEPTING_ENTRIES := FALSE;
END STOP;
END SELECT;
END LOOP;
END T2;
BEGIN
TEST ("C85014A", "CHECK THAT THE NUMBER OF FORMAL PARAMETERS IS " &
"USED TO DETERMINE WHICH SUBPROGRAM OR ENTRY " &
"IS BEING RENAMED");
DECLARE
PROCEDURE PROC1 (J1: IN OUT INTEGER) RENAMES PROC;
PROCEDURE PROC2 (J1, J2: IN OUT INTEGER) RENAMES PROC;
PROCEDURE ENTRY1 (J1: IN OUT INTEGER) RENAMES F.ENTER;
PROCEDURE ENTRY2 (J1, J2: IN OUT INTEGER) RENAMES F.ENTER;
K1, K2 : INTEGER := 0;
BEGIN
PROC1(K1);
IF K1 /= IDENT_INT(1) THEN
FAILED("INCORRECT RETURN VALUE FROM PROC1");
END IF;
ENTRY1(K2);
IF K2 /= IDENT_INT(1) THEN
FAILED("INCORRECT RETURN VALUE FROM ENTRY1");
END IF;
PROC2(K1, K2);
IF K1 /= IDENT_INT(3) OR K2 /= IDENT_INT(3) THEN
FAILED("INCORRECT RETURN VALUE FROM PROC2");
END IF;
ENTRY2(K1, K2);
IF K1 /= IDENT_INT(5) OR K2 /= IDENT_INT(5) THEN
FAILED("INCORRECT RETURN VALUE FROM ENTRY2");
END IF;
END;
TASK1.STOP;
TASK2.STOP;
RESULT;
END C85014A;
|
------------------------------------------------------------------------------
-- 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) $
with Macros;
with Ada.Characters.Handling;
with Symbols.Unicode;
function Regular_Expressions.Create
(Source : String)
return Expression
is
-- Full_Exp = Alter_Exp
--
-- Alter_Exp= Con_Exp {|Con_Exp}
-- Con_Exp = Item_Exp { Item_Exp }
-- Item_Exp = Base_Exp |
-- Base_Exp* |
-- Base_Exp+ |
-- Base_Exp?;
-- Base_Exp = (Alter_Exp) |
-- Symbol |
-- {Macro} |
-- Square
-- Square = [in_square]
I : Positive := Source'First;
Result : Expression;
procedure Next;
function Char return Character;
function Char_In (Set : String) return Boolean;
function Has_More return Boolean;
function Do_Alternative return Boolean;
function Do_Concatenate return Boolean;
function Do_Item return Boolean;
function Do_Base return Boolean;
function Do_Square return Boolean;
function Get_Literal return Expression;
procedure Read_Char (Read : out Symbol;
Success : out Boolean;
Slash : in Boolean := False);
procedure Next is
begin
I := I + 1;
end Next;
function Char return Character is
begin
return Source (I);
end Char;
function Has_More return Boolean is
begin
return I in Source'Range;
end Has_More;
function Char_In (Set : String) return Boolean is
begin
for J in Set'Range loop
if Source (I) = Set (J) then
return True;
end if;
end loop;
return False;
end;
function Get_Literal return Expression is
Success : Boolean;
To_Read : Symbol;
begin
if Char = ']' then
return null;
end if;
Read_Char (To_Read, Success);
return New_Literal (To_Range (To_Read));
end Get_Literal;
function "+" (Char : Character) return Symbol is
begin
return Symbol (Character'Pos (Char));
end "+";
function Do_Alternative return Boolean is
Left : Expression;
begin
if Do_Concatenate then
Left := Result;
while Has_More and then Char = '|'
loop
Next;
if Do_Concatenate then
Left := New_Alternative (Left, Result);
else
return False;
end if;
end loop;
Result := Left;
return True;
else
return False;
end if;
end Do_Alternative;
function Do_Concatenate return Boolean is
Left : Expression;
begin
if Do_Item then
Left := Result;
while Has_More and then Do_Item
loop
Left := New_Sequence (Left, Result);
end loop;
Result := Left;
return True;
else
return False;
end if;
end Do_Concatenate;
function Do_Item return Boolean is
begin
if Do_Base then
if Has_More then
case Char is
when '*' =>
Result := New_Iteration (Result);
Next;
when '+' =>
Result := New_Iteration (Result, Allow_Zero => False);
Next;
when '?' =>
Result := New_Optional (Result);
Next;
when others =>
null;
end case;
end if;
return True;
else
return False;
end if;
end Do_Item;
procedure Do_Name
(From, To : out Positive;
Success : out Boolean) is
begin
Success := True;
if not (Has_More and then Char = '{') then
Success := False;
return;
end if;
Next;
From := I;
while Has_More and then Char /= '}' loop
To := I;
Next;
end loop;
if Has_More and then Char = '}' then
Next;
else
Success := False;
end if;
end Do_Name;
function Do_Macro return Boolean is
From, To : Positive;
Success : Boolean;
begin
Do_Name (From, To, Success);
if Success then
Result := Macros.Find (Source (From .. To));
end if;
return Success;
end Do_Macro;
function Do_Base return Boolean is
begin
case Char is
when '[' =>
return Do_Square;
when '(' =>
Next;
if Do_Alternative and then Char = ')' then
Next;
return True;
else
return False;
end if;
when '{' =>
if Do_Macro then
Result := New_Apply (Result);
return True;
else
return False;
end if;
when ')' =>
return False;
when '|' =>
return False;
when others =>
Result := Get_Literal;
return Result /= null;
end case;
end Do_Base;
-- in_square = ^? ?] {-|base} (-[in_square]) ?
-- base = char | range | \p{category} | \m{macro}
-- range = char-char
-- char = \?a | \uXXXX
procedure Read_Char (Read : out Symbol;
Success : out Boolean;
Slash : Boolean := False)
is
use Ada.Characters.Handling;
function Hex (Char : Character) return Symbol is
Img : constant String := "16#" & Char & "#";
begin
return Symbol'Value (Img);
end Hex;
begin
Success := True;
if Slash or else Char = '\' then
if not Slash then
Next;
end if;
if not Has_More then
Success := False;
return;
end if;
case Char is
when 'f' =>
Read := +Ascii.FF;
Next;
when 'n' =>
Read := +Ascii.LF;
Next;
when 'r' =>
Read := +Ascii.CR;
Next;
when 't' =>
Read := +Ascii.HT;
Next;
when 'v' =>
Read := +Ascii.VT;
Next;
when 'u' =>
Read := 0;
Next;
Success := Has_More and then Is_Hexadecimal_Digit (Char);
while Has_More and then Is_Hexadecimal_Digit (Char) loop
Read := Read * 16 + Hex (Char);
Next;
end loop;
when others =>
Read := +Char;
Next;
end case;
-- elsif Char = ']' then
-- Success := False;
-- return;
else
Read := +Char;
Next;
end if;
end Read_Char;
-- base = char | range | \p{category} | \m{macro}
procedure In_Square_Base (Set : in out Symbol_Set;
Success : out Boolean) is
First : Symbol;
Second : Symbol;
Slash : Boolean := False;
From : Positive;
To : Positive;
begin
Success := True;
if Char = '\' then
Next;
if Char = 'p' then
Next;
Do_Name (From, To, Success);
if Success then
Set := Set or
Symbols.Unicode.General_Category (Source (From .. To));
end if;
return;
elsif Char = 'm' then
Next;
if Do_Macro then
if Result.Kind = Literal then
Set := Set or Result.Chars;
else
Success := False;
end if;
else
Success := False;
end if;
return;
else
Slash := True;
end if;
end if;
Read_Char (First, Success, Slash);
if not Success then
return;
end if;
if Has_More and then Char = '-' then
Next;
Read_Char (Second, Success);
if not Success then
return;
end if;
Set := Set or To_Range (First, Second);
else
Set := Set or To_Range (First);
end if;
end In_Square_Base;
-- in_square = ^? ?] {-|base} (-[in_square]) ?
procedure In_Square
(Set : out Symbol_Set;
Success : out Boolean)
is
Invert : Boolean := False;
begin
Success := True;
if Char = '^' then
Invert := True;
Next;
end if;
if Char = ']' then
Set := To_Range (+Char);
Next;
else
Set := Empty;
end if;
while Success and then Has_More and then Char /= ']' loop
if Char = '-' then
Next;
if not Has_More or else Char /= '[' then
Set := Set or To_Range (+'-');
Next;
else
-- charclass substraction
Next;
declare
Right : Symbol_Set;
begin
In_Square (Right, Success);
if Success then
Set := Set - Right;
if Has_More and then Char = ']' then
Next;
else
Success := False;
end if;
end if;
end;
exit;
end if;
else
In_Square_Base (Set, Success);
end if;
end loop;
if Success and Invert then
Set := To_Range (0, Not_A_Symbol - 1) - Set;
end if;
end In_Square;
function Do_Square return Boolean is
Set : Symbol_Set;
Success : Boolean;
begin
if Char /= '[' then
return False;
end if;
Next;
In_Square (Set, Success);
if not Success or else not Has_More or else Char /= ']' then
return False;
end if;
Next;
Result := New_Literal (Set);
return True;
end Do_Square;
begin
if Do_Alternative then
return Result;
else
raise Syntax_Error;
end if;
end Regular_Expressions.Create;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
pragma License (Unrestricted);
-- implementation unit
package Ada.Strings.Naked_Maps.Case_Mapping is
pragma Preelaborate;
function Lower_Case_Map return not null Character_Mapping_Access;
function Upper_Case_Map return not null Character_Mapping_Access;
end Ada.Strings.Naked_Maps.Case_Mapping;
|
pragma License (Unrestricted);
-- implementation unit
with Ada.IO_Exceptions;
with Ada.IO_Modes;
with System.Native_IO;
private with Ada.Tags;
package Ada.Streams.Naked_Stream_IO is
pragma Preelaborate;
-- the parameter Form
Default_Form : constant System.Native_IO.Packed_Form :=
(Shared => IO_Modes.By_Mode, Wait => False, Overwrite => True);
subtype Form_String is String (1 .. 256);
procedure Set (
Form : in out System.Native_IO.Packed_Form;
Keyword : String;
Item : String);
function Pack (Form : String) return System.Native_IO.Packed_Form;
procedure Unpack (
Form : System.Native_IO.Packed_Form;
Result : out Form_String;
Last : out Natural);
-- non-controlled
type Stream_Type (<>) is limited private;
type Non_Controlled_File_Type is access all Stream_Type;
-- Note: Non_Controlled_File_Type is pass-by-value whether in out or not,
-- and it's possible that Reset/Set_Mode may close the file.
-- So these functions have access mode.
procedure Create (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode := IO_Modes.Out_File;
Name : String := "";
Form : System.Native_IO.Packed_Form := Default_Form);
procedure Create (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.Inout_File_Mode := IO_Modes.Out_File;
Name : String := "";
Form : System.Native_IO.Packed_Form := Default_Form);
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Name : String;
Form : System.Native_IO.Packed_Form := Default_Form);
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.Inout_File_Mode;
Name : String;
Form : System.Native_IO.Packed_Form := Default_Form);
procedure Close (
File : aliased in out Non_Controlled_File_Type;
Raise_On_Error : Boolean := True);
procedure Delete (File : aliased in out Non_Controlled_File_Type);
procedure Reset (
File : aliased in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode);
procedure Reset (
File : aliased in out Non_Controlled_File_Type;
Mode : IO_Modes.Inout_File_Mode);
function Mode (File : not null Non_Controlled_File_Type)
return IO_Modes.File_Mode;
function Mode (File : not null Non_Controlled_File_Type)
return IO_Modes.Inout_File_Mode;
function Mode (File : not null Non_Controlled_File_Type)
return System.Native_IO.File_Mode;
function Name (File : not null Non_Controlled_File_Type) return String;
function Form (File : Non_Controlled_File_Type)
return System.Native_IO.Packed_Form;
pragma Inline (Mode);
pragma Inline (Form);
function Is_Open (File : Non_Controlled_File_Type) return Boolean;
function End_Of_File (File : not null Non_Controlled_File_Type)
return Boolean;
pragma Inline (Is_Open);
function Stream (File : not null Non_Controlled_File_Type)
return not null access Root_Stream_Type'Class;
procedure Read (
File : not null Non_Controlled_File_Type;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset);
procedure Write (
File : not null Non_Controlled_File_Type;
Item : Stream_Element_Array);
procedure Set_Index (
File : not null Non_Controlled_File_Type;
To : Stream_Element_Positive_Count);
function Index (File : not null Non_Controlled_File_Type)
return Stream_Element_Positive_Count;
function Size (File : not null Non_Controlled_File_Type)
return Stream_Element_Count;
procedure Set_Mode (
File : aliased in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode);
procedure Flush (File : not null Non_Controlled_File_Type);
-- write the buffer and synchronize with hardware
procedure Flush_Writing_Buffer (
File : not null Non_Controlled_File_Type;
Raise_On_Error : Boolean := True);
-- write the buffer only
-- handle for non-controlled
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.File_Mode;
Handle : System.Native_IO.Handle_Type;
Name : String := "";
Form : System.Native_IO.Packed_Form := Default_Form;
To_Close : Boolean := False);
procedure Open (
File : in out Non_Controlled_File_Type;
Mode : IO_Modes.Inout_File_Mode;
Handle : System.Native_IO.Handle_Type;
Name : String := "";
Form : System.Native_IO.Packed_Form := Default_Form;
To_Close : Boolean := False);
function Handle (File : not null Non_Controlled_File_Type)
return System.Native_IO.Handle_Type;
pragma Inline (Handle);
function Is_Standard (File : not null Non_Controlled_File_Type)
return Boolean;
pragma Inline (Is_Standard);
-- exceptions
Status_Error : exception
renames IO_Exceptions.Status_Error;
Mode_Error : exception
renames IO_Exceptions.Mode_Error;
Use_Error : exception
renames IO_Exceptions.Use_Error;
Device_Error : exception
renames IO_Exceptions.Device_Error;
End_Error : exception
renames IO_Exceptions.End_Error;
private
package Dispatchers is
type Root_Dispatcher is limited new Root_Stream_Type with record
File : Non_Controlled_File_Type;
end record;
pragma Suppress_Initialization (Root_Dispatcher);
for Root_Dispatcher'Size use Standard'Address_Size * 2; -- [gcc-7] ?
for Root_Dispatcher'Alignment use
Standard'Address_Size / Standard'Storage_Unit; -- [gcc-7] ? in x32
overriding procedure Read (
Stream : in out Root_Dispatcher;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset);
overriding procedure Write (
Stream : in out Root_Dispatcher;
Item : Stream_Element_Array);
type Seekable_Dispatcher is limited new Seekable_Stream_Type with record
File : Non_Controlled_File_Type;
end record;
pragma Suppress_Initialization (Seekable_Dispatcher);
for Seekable_Dispatcher'Size use Standard'Address_Size * 2; -- [gcc-7] ?
for Seekable_Dispatcher'Alignment use
Standard'Address_Size / Standard'Storage_Unit; -- [gcc-7] ? in x32
overriding procedure Read (
Stream : in out Seekable_Dispatcher;
Item : out Stream_Element_Array;
Last : out Stream_Element_Offset);
overriding procedure Write (
Stream : in out Seekable_Dispatcher;
Item : Stream_Element_Array);
overriding procedure Set_Index (
Stream : in out Seekable_Dispatcher;
To : Stream_Element_Positive_Count);
overriding function Index (Stream : Seekable_Dispatcher)
return Stream_Element_Positive_Count;
overriding function Size (Stream : Seekable_Dispatcher)
return Stream_Element_Count;
type Dispatcher is record
Tag : Tags.Tag := Tags.No_Tag;
File : Non_Controlled_File_Type := null;
end record;
pragma Suppress_Initialization (Dispatcher);
for Dispatcher'Size use Standard'Address_Size * 2; -- [gcc-7] ?
for Dispatcher'Alignment use
Standard'Address_Size / Standard'Storage_Unit;
pragma Compile_Time_Error (
Seekable_Dispatcher'Size /= Root_Dispatcher'Size
or else Dispatcher'Size /= Root_Dispatcher'Size,
"size mismatch");
pragma Compile_Time_Error (
Seekable_Dispatcher'Alignment /= Root_Dispatcher'Alignment
or else Dispatcher'Alignment /= Root_Dispatcher'Alignment,
"misaligned");
end Dispatchers;
type Stream_Kind is (
Ordinary,
Temporary,
External,
External_No_Close,
Standard_Handle);
pragma Discard_Names (Stream_Kind);
Uninitialized_Buffer : constant := -1;
type Close_Handler is access procedure (
Handle : System.Native_IO.Handle_Type;
Name : System.Native_IO.Name_Pointer;
Raise_On_Error : Boolean);
pragma Favor_Top_Level (Close_Handler);
type Stream_Type is record -- "limited" prevents No_Elaboration_Code
Handle : aliased System.Native_IO.Handle_Type; -- file descripter
Mode : System.Native_IO.File_Mode;
Name : System.Native_IO.Name_Pointer;
Form : System.Native_IO.Packed_Form;
Kind : Stream_Kind;
Has_Full_Name : Boolean;
Buffer_Inline : aliased Stream_Element;
Buffer : System.Address;
Buffer_Length : Stream_Element_Offset;
Buffer_Index : Stream_Element_Offset; -- Index (File) mod Buffer_Length
Reading_Index : Stream_Element_Offset;
Writing_Index : Stream_Element_Offset;
Closer : Close_Handler;
Dispatcher : aliased Dispatchers.Dispatcher :=
(Tag => Tags.No_Tag, File => null);
end record;
pragma Suppress_Initialization (Stream_Type);
end Ada.Streams.Naked_Stream_IO;
|
-- Used for all testcases for MySQL driver
with AdaBase.Driver.Base.PostgreSQL;
with AdaBase.Statement.Base.PostgreSQL;
package Connect is
-- All specific drivers renamed to "Database_Driver"
subtype Database_Driver is AdaBase.Driver.Base.PostgreSQL.PostgreSQL_Driver;
subtype Stmt_Type is AdaBase.Statement.Base.PostgreSQL.PostgreSQL_statement;
subtype Stmt_Type_access is
AdaBase.Statement.Base.PostgreSQL.PostgreSQL_statement_access;
DR : Database_Driver;
procedure connect_database;
end Connect;
|
--**********
--* Helen
--* Added some declarations here to agree with Ada95 manual
--********
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A D A . E X C E P T I O N S --
-- --
-- S p e c --
-- --
-- $Revision: 2 $ --
-- --
-- Copyright (c) 1992,1993,1994 NYU, All Rights Reserved --
-- --
-- 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, 675 Mass Ave, Cambridge, MA 02139, USA. --
-- --
------------------------------------------------------------------------------
package Ada.Exceptions is
type Exception_Id is private;
Null_Id : constant Exception_Id;
function Exception_Name(Id : Exception_Id) return String;
type Exception_Occurrence is private;
type Exception_Occurrence_Access is access all Exception_Occurrence;
Null_Occurrence : constant Exception_Occurrence;
procedure Raise_Exception (E : in Exception_Id; Message : in String := "");
function Exception_Message(X : Exception_Occurrence) return String;
procedure Reraise_Occurrence (X : Exception_Occurrence);
function Exception_Identity(X : Exception_Occurrence) return Exception_Id;
function Exception_Name (X : Exception_Occurrence) return String;
function Exception_Information (X : Exception_Occurrence) return String;
procedure Save_Occurrence(Target : out Exception_Occurrence;
Source : in Exception_Occurrence);
function Save_Occurrence(Source : Exception_Occurrence)
return Exception_Occurrence_Access;
private
-- Dummy definitions for now (body not implemented yet) ???
type Exception_Id is new Integer;
Null_Id : constant Exception_Id := 0;
type Exception_Occurrence is new Integer;
Null_Occurrence : constant Exception_Occurrence := 0;
end Ada.Exceptions;
|
with Text_IO;
package body Memory_Analyzer is
function Bytes_Required (Value : in Integer) return Integer is
Bytes_To_Long_Word : constant Integer := 4;
Offset_To_Byte_In_Bits : constant Integer := 8 - 1;
Offset_To_Long_Word_In_Bytes : Integer := Bytes_To_Long_Word - 1;
begin
return
((
(((Value + Offset_To_Byte_In_Bits) / 8) +
Offset_To_Long_Word_In_Bytes) /
Bytes_To_Long_Word) *
Bytes_To_Long_Word);
end Bytes_Required;
function Count
(Size : Integer;
File : String;
Var : String) return Boolean
is
begin
Text_IO.Put_Line
("local, " &
File &
", " &
Var &
", " &
Integer'Image (Bytes_Required (Size)));
return True;
end Count;
end Memory_Analyzer;
|
-- Abstract :
--
-- A generalized LR parser, with no error recovery, no semantic checks.
--
-- This allows wisi-generate (which uses the generated wisi_grammar)
-- to not depend on wisitoken-lr-mckenzie_recover, so editing that
-- does not cause everything to be regenerated/compiled.
--
-- Copyright (C) 2002, 2003, 2009, 2010, 2013 - 2015, 2017 - 2019 Free Software Foundation, Inc.
--
-- This file is part of the WisiToken package.
--
-- The WisiToken package is free software; you can redistribute it
-- and/or modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or
-- (at your option) any later version. This library is distributed in
-- the hope that it will be useful, but WITHOUT ANY WARRANTY; without
-- even the implied warranty of MERCHAN- TABILITY or FITNESS FOR A
-- PARTICULAR PURPOSE.
--
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with WisiToken.Lexer;
with WisiToken.Parse.LR.Parser_Lists;
with WisiToken.Syntax_Trees;
package WisiToken.Parse.LR.Parser_No_Recover is
Default_Max_Parallel : constant := 15;
type Parser is new WisiToken.Parse.Base_Parser with record
Table : Parse_Table_Ptr;
Shared_Tree : aliased Syntax_Trees.Base_Tree;
-- Each parser has its own branched syntax tree, all branched from
-- this tree.
--
-- See WisiToken.LR.Parser_Lists Parser_State for more discussion of
-- Shared_Tree.
Parsers : aliased Parser_Lists.List;
Max_Parallel : SAL.Base_Peek_Type;
First_Parser_Label : Integer;
Terminate_Same_State : Boolean;
end record;
overriding procedure Finalize (Object : in out LR.Parser_No_Recover.Parser);
-- Deep free Object.Table.
procedure New_Parser
(Parser : out LR.Parser_No_Recover.Parser;
Trace : not null access WisiToken.Trace'Class;
Lexer : in WisiToken.Lexer.Handle;
Table : in Parse_Table_Ptr;
User_Data : in Syntax_Trees.User_Data_Access;
Max_Parallel : in SAL.Base_Peek_Type := Default_Max_Parallel;
First_Parser_Label : in Integer := 1;
Terminate_Same_State : in Boolean := True);
overriding procedure Parse (Shared_Parser : aliased in out LR.Parser_No_Recover.Parser);
-- Attempt a parse. Calls Parser.Lexer.Reset, runs lexer to end of
-- input setting Shared_Parser.Terminals, then parses tokens.
--
-- If a parse error is encountered, raises Syntax_Error.
-- Parser.Lexer_Errors and Parsers(*).Errors contain information
-- about the errors.
--
-- For other errors, raises Parse_Error with an appropriate error
-- message.
overriding function Tree (Parser : in LR.Parser_No_Recover.Parser) return Syntax_Trees.Tree;
overriding function Any_Errors (Parser : in LR.Parser_No_Recover.Parser) return Boolean;
overriding procedure Put_Errors (Parser : in LR.Parser_No_Recover.Parser);
-- Put user-friendly error messages from the parse to
-- Ada.Text_IO.Current_Error.
overriding procedure Execute_Actions (Parser : in out LR.Parser_No_Recover.Parser);
-- Execute the grammar actions in Parser.
end WisiToken.Parse.LR.Parser_No_Recover;
|
with Ada.Unchecked_Deallocation;
with System.Address_To_Named_Access_Conversions;
with System.Storage_Pools.Overlaps;
package body System.Initialization is
pragma Suppress (All_Checks);
type Object_Access is access all Object;
for Object_Access'Storage_Pool use Storage_Pools.Overlaps.Pool.all;
procedure Free is
new Ada.Unchecked_Deallocation (Object, Object_Access);
package OA_Conv is
new Address_To_Named_Access_Conversions (Object, Object_Access);
-- implementation
function New_Object (Storage : not null access Object_Storage)
return Object_Pointer
is
type Storage_Access is access all Object_Storage; -- local type
for Storage_Access'Storage_Size use 0;
package SA_Conv is
new Address_To_Named_Access_Conversions (
Object_Storage,
Storage_Access);
begin
if Object'Has_Access_Values
or else Object'Has_Tagged_Values
or else Object'Size > Standard'Word_Size * 8 -- large object
then
Storage_Pools.Overlaps.Set_Address (
SA_Conv.To_Address (Storage_Access (Storage)));
return Object_Pointer (Object_Access'(new Object));
else
declare
Item : Object; -- default initialized
pragma Unmodified (Item);
Result : constant Object_Pointer :=
Object_Pointer (
OA_Conv.To_Pointer (
SA_Conv.To_Address (Storage_Access (Storage))));
begin
Result.all := Item;
return Result;
end;
end if;
end New_Object;
function New_Object (
Storage : not null access Object_Storage;
Value : Object)
return Object_Pointer
is
type Storage_Access is access all Object_Storage; -- local type
for Storage_Access'Storage_Size use 0;
package SA_Conv is
new Address_To_Named_Access_Conversions (
Object_Storage,
Storage_Access);
begin
if Object'Has_Access_Values or else Object'Has_Tagged_Values then
Storage_Pools.Overlaps.Set_Address (
SA_Conv.To_Address (Storage_Access (Storage)));
return Object_Pointer (Object_Access'(new Object'(Value)));
else
declare
Result : constant Object_Pointer :=
Object_Pointer (
OA_Conv.To_Pointer (
SA_Conv.To_Address (Storage_Access (Storage))));
begin
Result.all := Value;
return Result;
end;
end if;
end New_Object;
procedure Delete_Object (Storage : not null access Object_Storage) is
type Storage_Access is access all Object_Storage; -- local type
for Storage_Access'Storage_Size use 0;
package SA_Conv is
new Address_To_Named_Access_Conversions (
Object_Storage,
Storage_Access);
begin
if Object'Has_Access_Values or else Object'Has_Tagged_Values then
declare
A : constant Address :=
SA_Conv.To_Address (Storage_Access (Storage));
X : Object_Access := OA_Conv.To_Pointer (A);
begin
Storage_Pools.Overlaps.Set_Address (A);
Free (X);
end;
end if;
end Delete_Object;
end System.Initialization;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Range_Example is
type Range_2_Based is array (Positive range 2 .. 4) of Integer;
ARR : Range_2_Based := (3, 5, 7);
begin
<<example_1>>
Put_Line ("example 1");
for Index in 2 .. 4 loop
Put_Line (Integer'image (ARR (Index)));
end loop;
<<example_2>>
Put_Line ("example 2");
for Index in ARR'first .. ARR'last loop
Put_Line (Integer'image (ARR (Index)));
end loop;
<<example_3>>
Put_Line ("example 3");
for Index in ARR'range loop
Put_Line (Integer'image (ARR (Index)));
end loop;
end;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.