content stringlengths 23 1.05M |
|---|
-- 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 Ada.Strings.Unbounded;
package Orka.Strings is
pragma Preelaborate;
function Trim (Value : String) return String;
-- Return value with whitespace removed from both the start and end
function Strip_Line_Term (Value : String) return String;
-- Return the value without any LF and CR characters at the end
function Lines (Value : String) return Positive;
-- Return the number of lines that the string contains
package SU renames Ada.Strings.Unbounded;
function "+" (Value : String) return SU.Unbounded_String renames SU.To_Unbounded_String;
function "+" (Value : SU.Unbounded_String) return String renames SU.To_String;
type String_List is array (Positive range <>) of SU.Unbounded_String;
function Split
(Value : String;
Separator : String := " ";
Maximum : Natural := 0) return String_List;
function Join (List : String_List; Separator : String) return String;
end Orka.Strings;
|
with Varsize3_Pkg2;
with Varsize3_Pkg3;
package Varsize3_Pkg1 is
type Arr is array (Positive range 1 .. Varsize3_Pkg2.Last_Index) of Boolean;
package My_G is new Varsize3_Pkg3 (Arr);
type Object is new My_G.Object;
end Varsize3_Pkg1;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . T A S K _ P R I M I T I V E S . O P E R A T I O N S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- 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. 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/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This is the VxWorks version of this package
-- This package contains all the GNULL primitives that interface directly with
-- the underlying OS.
with Ada.Unchecked_Conversion;
with Interfaces.C;
with System.Multiprocessors;
with System.Tasking.Debug;
with System.Interrupt_Management;
with System.Float_Control;
with System.OS_Constants;
with System.Soft_Links;
-- We use System.Soft_Links instead of System.Tasking.Initialization
-- because the later is a higher level package that we shouldn't depend
-- on. For example when using the restricted run time, it is replaced by
-- System.Tasking.Restricted.Stages.
with System.Task_Info;
with System.VxWorks.Ext;
package body System.Task_Primitives.Operations is
package OSC renames System.OS_Constants;
package SSL renames System.Soft_Links;
use System.Tasking.Debug;
use System.Tasking;
use System.OS_Interface;
use System.Parameters;
use type System.VxWorks.Ext.t_id;
use type Interfaces.C.int;
use type System.OS_Interface.unsigned;
subtype int is System.OS_Interface.int;
subtype unsigned is System.OS_Interface.unsigned;
Relative : constant := 0;
----------------
-- Local Data --
----------------
-- The followings are logically constants, but need to be initialized at
-- run time.
Environment_Task_Id : Task_Id;
-- A variable to hold Task_Id for the environment task
-- The followings are internal configuration constants needed
Dispatching_Policy : Character;
pragma Import (C, Dispatching_Policy, "__gl_task_dispatching_policy");
Foreign_Task_Elaborated : aliased Boolean := True;
-- Used to identified fake tasks (i.e., non-Ada Threads)
Locking_Policy : Character;
pragma Import (C, Locking_Policy, "__gl_locking_policy");
Mutex_Protocol : Priority_Type;
Single_RTS_Lock : aliased RTS_Lock;
-- This is a lock to allow only one thread of control in the RTS at a
-- time; it is used to execute in mutual exclusion from all other tasks.
-- Used to protect All_Tasks_List
Time_Slice_Val : Integer;
pragma Import (C, Time_Slice_Val, "__gl_time_slice_val");
Null_Thread_Id : constant Thread_Id := 0;
-- Constant to indicate that the thread identifier has not yet been
-- initialized.
--------------------
-- Local Packages --
--------------------
package Specific is
procedure Initialize;
pragma Inline (Initialize);
-- Initialize task specific data
function Is_Valid_Task return Boolean;
pragma Inline (Is_Valid_Task);
-- Does executing thread have a TCB?
procedure Set (Self_Id : Task_Id);
pragma Inline (Set);
-- Set the self id for the current task, unless Self_Id is null, in
-- which case the task specific data is deleted.
function Self return Task_Id;
pragma Inline (Self);
-- Return a pointer to the Ada Task Control Block of the calling task
end Specific;
package body Specific is separate;
-- The body of this package is target specific
----------------------------------
-- ATCB allocation/deallocation --
----------------------------------
package body ATCB_Allocation is separate;
-- The body of this package is shared across several targets
---------------------------------
-- Support for foreign threads --
---------------------------------
function Register_Foreign_Thread
(Thread : Thread_Id;
Sec_Stack_Size : Size_Type := Unspecified_Size) return Task_Id;
-- Allocate and initialize a new ATCB for the current Thread. The size of
-- the secondary stack can be optionally specified.
function Register_Foreign_Thread
(Thread : Thread_Id;
Sec_Stack_Size : Size_Type := Unspecified_Size)
return Task_Id is separate;
-----------------------
-- Local Subprograms --
-----------------------
procedure Abort_Handler (signo : Signal);
-- Handler for the abort (SIGABRT) signal to handle asynchronous abort
procedure Install_Signal_Handlers;
-- Install the default signal handlers for the current task
function Is_Task_Context return Boolean;
-- This function returns True if the current execution is in the context of
-- a task, and False if it is an interrupt context.
type Set_Stack_Limit_Proc_Acc is access procedure;
pragma Convention (C, Set_Stack_Limit_Proc_Acc);
Set_Stack_Limit_Hook : Set_Stack_Limit_Proc_Acc;
pragma Import (C, Set_Stack_Limit_Hook, "__gnat_set_stack_limit_hook");
-- Procedure to be called when a task is created to set stack limit. Used
-- only for VxWorks 5 and VxWorks MILS guest OS.
function To_Address is
new Ada.Unchecked_Conversion (Task_Id, System.Address);
-------------------
-- Abort_Handler --
-------------------
procedure Abort_Handler (signo : Signal) is
pragma Unreferenced (signo);
-- Do not call Self at this point as we're in a signal handler
-- and it may not be available, in particular on targets where we
-- support ZCX and where we don't do anything here anyway.
Self_ID : Task_Id;
Old_Set : aliased sigset_t;
Unblocked_Mask : aliased sigset_t;
Result : int;
pragma Warnings (Off, Result);
use System.Interrupt_Management;
begin
-- It is not safe to raise an exception when using ZCX and the GCC
-- exception handling mechanism.
if ZCX_By_Default then
return;
end if;
Self_ID := Self;
if Self_ID.Deferral_Level = 0
and then Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
and then not Self_ID.Aborting
then
Self_ID.Aborting := True;
-- Make sure signals used for RTS internal purposes are unmasked
Result := sigemptyset (Unblocked_Mask'Access);
pragma Assert (Result = 0);
Result :=
sigaddset
(Unblocked_Mask'Access,
Signal (Abort_Task_Interrupt));
pragma Assert (Result = 0);
Result := sigaddset (Unblocked_Mask'Access, SIGBUS);
pragma Assert (Result = 0);
Result := sigaddset (Unblocked_Mask'Access, SIGFPE);
pragma Assert (Result = 0);
Result := sigaddset (Unblocked_Mask'Access, SIGILL);
pragma Assert (Result = 0);
Result := sigaddset (Unblocked_Mask'Access, SIGSEGV);
pragma Assert (Result = 0);
Result :=
pthread_sigmask
(SIG_UNBLOCK,
Unblocked_Mask'Access,
Old_Set'Access);
pragma Assert (Result = 0);
raise Standard'Abort_Signal;
end if;
end Abort_Handler;
-----------------
-- Stack_Guard --
-----------------
procedure Stack_Guard (T : ST.Task_Id; On : Boolean) is
pragma Unreferenced (T);
pragma Unreferenced (On);
begin
-- Nothing needed (why not???)
null;
end Stack_Guard;
-------------------
-- Get_Thread_Id --
-------------------
function Get_Thread_Id (T : ST.Task_Id) return OSI.Thread_Id is
begin
return T.Common.LL.Thread;
end Get_Thread_Id;
----------
-- Self --
----------
function Self return Task_Id renames Specific.Self;
-----------------------------
-- Install_Signal_Handlers --
-----------------------------
procedure Install_Signal_Handlers is
act : aliased struct_sigaction;
old_act : aliased struct_sigaction;
Tmp_Set : aliased sigset_t;
Result : int;
begin
act.sa_flags := 0;
act.sa_handler := Abort_Handler'Address;
Result := sigemptyset (Tmp_Set'Access);
pragma Assert (Result = 0);
act.sa_mask := Tmp_Set;
Result :=
sigaction
(Signal (Interrupt_Management.Abort_Task_Interrupt),
act'Unchecked_Access,
old_act'Unchecked_Access);
pragma Assert (Result = 0);
Interrupt_Management.Initialize_Interrupts;
end Install_Signal_Handlers;
---------------------
-- Initialize_Lock --
---------------------
procedure Initialize_Lock
(Prio : System.Any_Priority;
L : not null access Lock)
is
begin
L.Mutex := semMCreate (SEM_Q_PRIORITY + SEM_INVERSION_SAFE);
L.Prio_Ceiling := int (Prio);
L.Protocol := Mutex_Protocol;
pragma Assert (L.Mutex /= 0);
end Initialize_Lock;
procedure Initialize_Lock
(L : not null access RTS_Lock;
Level : Lock_Level)
is
pragma Unreferenced (Level);
begin
L.Mutex := semMCreate (SEM_Q_PRIORITY + SEM_INVERSION_SAFE);
L.Prio_Ceiling := int (System.Any_Priority'Last);
L.Protocol := Mutex_Protocol;
pragma Assert (L.Mutex /= 0);
end Initialize_Lock;
-------------------
-- Finalize_Lock --
-------------------
procedure Finalize_Lock (L : not null access Lock) is
Result : int;
begin
Result := semDelete (L.Mutex);
pragma Assert (Result = 0);
end Finalize_Lock;
procedure Finalize_Lock (L : not null access RTS_Lock) is
Result : int;
begin
Result := semDelete (L.Mutex);
pragma Assert (Result = 0);
end Finalize_Lock;
----------------
-- Write_Lock --
----------------
procedure Write_Lock
(L : not null access Lock;
Ceiling_Violation : out Boolean)
is
Result : int;
begin
if L.Protocol = Prio_Protect
and then int (Self.Common.Current_Priority) > L.Prio_Ceiling
then
Ceiling_Violation := True;
return;
else
Ceiling_Violation := False;
end if;
Result := semTake (L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
end Write_Lock;
procedure Write_Lock (L : not null access RTS_Lock) is
Result : int;
begin
Result := semTake (L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
end Write_Lock;
procedure Write_Lock (T : Task_Id) is
Result : int;
begin
Result := semTake (T.Common.LL.L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
end Write_Lock;
---------------
-- Read_Lock --
---------------
procedure Read_Lock
(L : not null access Lock;
Ceiling_Violation : out Boolean) is
begin
Write_Lock (L, Ceiling_Violation);
end Read_Lock;
------------
-- Unlock --
------------
procedure Unlock (L : not null access Lock) is
Result : int;
begin
Result := semGive (L.Mutex);
pragma Assert (Result = 0);
end Unlock;
procedure Unlock (L : not null access RTS_Lock) is
Result : int;
begin
Result := semGive (L.Mutex);
pragma Assert (Result = 0);
end Unlock;
procedure Unlock (T : Task_Id) is
Result : int;
begin
Result := semGive (T.Common.LL.L.Mutex);
pragma Assert (Result = 0);
end Unlock;
-----------------
-- Set_Ceiling --
-----------------
-- Dynamic priority ceilings are not supported by the underlying system
procedure Set_Ceiling
(L : not null access Lock;
Prio : System.Any_Priority)
is
pragma Unreferenced (L, Prio);
begin
null;
end Set_Ceiling;
-----------
-- Sleep --
-----------
procedure Sleep (Self_ID : Task_Id; Reason : System.Tasking.Task_States) is
pragma Unreferenced (Reason);
Result : int;
begin
pragma Assert (Self_ID = Self);
-- Release the mutex before sleeping
Result := semGive (Self_ID.Common.LL.L.Mutex);
pragma Assert (Result = 0);
-- Perform a blocking operation to take the CV semaphore. Note that a
-- blocking operation in VxWorks will reenable task scheduling. When we
-- are no longer blocked and control is returned, task scheduling will
-- again be disabled.
Result := semTake (Self_ID.Common.LL.CV, WAIT_FOREVER);
pragma Assert (Result = 0);
-- Take the mutex back
Result := semTake (Self_ID.Common.LL.L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
end Sleep;
-----------------
-- Timed_Sleep --
-----------------
-- This is for use within the run-time system, so abort is assumed to be
-- already deferred, and the caller should be holding its own ATCB lock.
procedure Timed_Sleep
(Self_ID : Task_Id;
Time : Duration;
Mode : ST.Delay_Modes;
Reason : System.Tasking.Task_States;
Timedout : out Boolean;
Yielded : out Boolean)
is
pragma Unreferenced (Reason);
Orig : constant Duration := Monotonic_Clock;
Absolute : Duration;
Ticks : int;
Result : int;
Wakeup : Boolean := False;
begin
Timedout := False;
Yielded := True;
if Mode = Relative then
Absolute := Orig + Time;
-- Systematically add one since the first tick will delay *at most*
-- 1 / Rate_Duration seconds, so we need to add one to be on the
-- safe side.
Ticks := To_Clock_Ticks (Time);
if Ticks > 0 and then Ticks < int'Last then
Ticks := Ticks + 1;
end if;
else
Absolute := Time;
Ticks := To_Clock_Ticks (Time - Monotonic_Clock);
end if;
if Ticks > 0 then
loop
-- Release the mutex before sleeping
Result := semGive (Self_ID.Common.LL.L.Mutex);
pragma Assert (Result = 0);
-- Perform a blocking operation to take the CV semaphore. Note
-- that a blocking operation in VxWorks will reenable task
-- scheduling. When we are no longer blocked and control is
-- returned, task scheduling will again be disabled.
Result := semTake (Self_ID.Common.LL.CV, Ticks);
if Result = 0 then
-- Somebody may have called Wakeup for us
Wakeup := True;
else
if errno /= S_objLib_OBJ_TIMEOUT then
Wakeup := True;
else
-- If Ticks = int'last, it was most probably truncated so
-- let's make another round after recomputing Ticks from
-- the absolute time.
if Ticks /= int'Last then
Timedout := True;
else
Ticks := To_Clock_Ticks (Absolute - Monotonic_Clock);
if Ticks < 0 then
Timedout := True;
end if;
end if;
end if;
end if;
-- Take the mutex back
Result := semTake (Self_ID.Common.LL.L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
exit when Timedout or Wakeup;
end loop;
else
Timedout := True;
-- Should never hold a lock while yielding
Result := semGive (Self_ID.Common.LL.L.Mutex);
Result := taskDelay (0);
Result := semTake (Self_ID.Common.LL.L.Mutex, WAIT_FOREVER);
end if;
end Timed_Sleep;
-----------------
-- Timed_Delay --
-----------------
-- This is for use in implementing delay statements, so we assume the
-- caller is holding no locks.
procedure Timed_Delay
(Self_ID : Task_Id;
Time : Duration;
Mode : ST.Delay_Modes)
is
Orig : constant Duration := Monotonic_Clock;
Absolute : Duration;
Ticks : int;
Timedout : Boolean;
Aborted : Boolean := False;
Result : int;
pragma Warnings (Off, Result);
begin
if Mode = Relative then
Absolute := Orig + Time;
Ticks := To_Clock_Ticks (Time);
if Ticks > 0 and then Ticks < int'Last then
-- First tick will delay anytime between 0 and 1 / sysClkRateGet
-- seconds, so we need to add one to be on the safe side.
Ticks := Ticks + 1;
end if;
else
Absolute := Time;
Ticks := To_Clock_Ticks (Time - Orig);
end if;
if Ticks > 0 then
-- Modifying State, locking the TCB
Result := semTake (Self_ID.Common.LL.L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
Self_ID.Common.State := Delay_Sleep;
Timedout := False;
loop
Aborted := Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level;
-- Release the TCB before sleeping
Result := semGive (Self_ID.Common.LL.L.Mutex);
pragma Assert (Result = 0);
exit when Aborted;
Result := semTake (Self_ID.Common.LL.CV, Ticks);
if Result /= 0 then
-- If Ticks = int'last, it was most probably truncated, so make
-- another round after recomputing Ticks from absolute time.
if errno = S_objLib_OBJ_TIMEOUT and then Ticks /= int'Last then
Timedout := True;
else
Ticks := To_Clock_Ticks (Absolute - Monotonic_Clock);
if Ticks < 0 then
Timedout := True;
end if;
end if;
end if;
-- Take back the lock after having slept, to protect further
-- access to Self_ID.
Result := semTake (Self_ID.Common.LL.L.Mutex, WAIT_FOREVER);
pragma Assert (Result = 0);
exit when Timedout;
end loop;
Self_ID.Common.State := Runnable;
Result := semGive (Self_ID.Common.LL.L.Mutex);
else
Result := taskDelay (0);
end if;
end Timed_Delay;
---------------------
-- Monotonic_Clock --
---------------------
function Monotonic_Clock return Duration is
TS : aliased timespec;
Result : int;
begin
Result := clock_gettime (OSC.CLOCK_RT_Ada, TS'Unchecked_Access);
pragma Assert (Result = 0);
return To_Duration (TS);
end Monotonic_Clock;
-------------------
-- RT_Resolution --
-------------------
function RT_Resolution return Duration is
begin
return 1.0 / Duration (sysClkRateGet);
end RT_Resolution;
------------
-- Wakeup --
------------
procedure Wakeup (T : Task_Id; Reason : System.Tasking.Task_States) is
pragma Unreferenced (Reason);
Result : int;
begin
Result := semGive (T.Common.LL.CV);
pragma Assert (Result = 0);
end Wakeup;
-----------
-- Yield --
-----------
procedure Yield (Do_Yield : Boolean := True) is
pragma Unreferenced (Do_Yield);
Result : int;
pragma Unreferenced (Result);
begin
Result := taskDelay (0);
end Yield;
------------------
-- Set_Priority --
------------------
procedure Set_Priority
(T : Task_Id;
Prio : System.Any_Priority;
Loss_Of_Inheritance : Boolean := False)
is
pragma Unreferenced (Loss_Of_Inheritance);
Result : int;
begin
Result :=
taskPrioritySet
(T.Common.LL.Thread, To_VxWorks_Priority (int (Prio)));
pragma Assert (Result = 0);
-- Note: in VxWorks 6.6 (or earlier), the task is placed at the end of
-- the priority queue instead of the head. This is not the behavior
-- required by Annex D (RM D.2.3(5/2)), but we consider it an acceptable
-- variation (RM 1.1.3(6)), given this is the built-in behavior of the
-- operating system. VxWorks versions starting from 6.7 implement the
-- required Annex D semantics.
-- In older versions we attempted to better approximate the Annex D
-- required behavior, but this simulation was not entirely accurate,
-- and it seems better to live with the standard VxWorks semantics.
T.Common.Current_Priority := Prio;
end Set_Priority;
------------------
-- Get_Priority --
------------------
function Get_Priority (T : Task_Id) return System.Any_Priority is
begin
return T.Common.Current_Priority;
end Get_Priority;
----------------
-- Enter_Task --
----------------
procedure Enter_Task (Self_ID : Task_Id) is
begin
-- Store the user-level task id in the Thread field (to be used
-- internally by the run-time system) and the kernel-level task id in
-- the LWP field (to be used by the debugger).
Self_ID.Common.LL.Thread := taskIdSelf;
Self_ID.Common.LL.LWP := getpid;
Specific.Set (Self_ID);
-- Properly initializes the FPU for PPC/MIPS systems
System.Float_Control.Reset;
-- Install the signal handlers
-- This is called for each task since there is no signal inheritance
-- between VxWorks tasks.
Install_Signal_Handlers;
-- If stack checking is enabled, set the stack limit for this task
if Set_Stack_Limit_Hook /= null then
Set_Stack_Limit_Hook.all;
end if;
end Enter_Task;
-------------------
-- Is_Valid_Task --
-------------------
function Is_Valid_Task return Boolean renames Specific.Is_Valid_Task;
-----------------------------
-- Register_Foreign_Thread --
-----------------------------
function Register_Foreign_Thread return Task_Id is
begin
if Is_Valid_Task then
return Self;
else
return Register_Foreign_Thread (taskIdSelf);
end if;
end Register_Foreign_Thread;
--------------------
-- Initialize_TCB --
--------------------
procedure Initialize_TCB (Self_ID : Task_Id; Succeeded : out Boolean) is
begin
Self_ID.Common.LL.CV := semBCreate (SEM_Q_PRIORITY, SEM_EMPTY);
Self_ID.Common.LL.Thread := Null_Thread_Id;
if Self_ID.Common.LL.CV = 0 then
Succeeded := False;
else
Succeeded := True;
Initialize_Lock (Self_ID.Common.LL.L'Access, ATCB_Level);
end if;
end Initialize_TCB;
-----------------
-- Create_Task --
-----------------
procedure Create_Task
(T : Task_Id;
Wrapper : System.Address;
Stack_Size : System.Parameters.Size_Type;
Priority : System.Any_Priority;
Succeeded : out Boolean)
is
Adjusted_Stack_Size : size_t;
use type System.Multiprocessors.CPU_Range;
begin
-- Check whether both Dispatching_Domain and CPU are specified for
-- the task, and the CPU value is not contained within the range of
-- processors for the domain.
if T.Common.Domain /= null
and then T.Common.Base_CPU /= System.Multiprocessors.Not_A_Specific_CPU
and then
(T.Common.Base_CPU not in T.Common.Domain'Range
or else not T.Common.Domain (T.Common.Base_CPU))
then
Succeeded := False;
return;
end if;
-- Ask for four extra bytes of stack space so that the ATCB pointer can
-- be stored below the stack limit, plus extra space for the frame of
-- Task_Wrapper. This is so the user gets the amount of stack requested
-- exclusive of the needs.
-- We also have to allocate n more bytes for the task name storage and
-- enough space for the Wind Task Control Block which is around 0x778
-- bytes. VxWorks also seems to carve out additional space, so use 2048
-- as a nice round number. We might want to increment to the nearest
-- page size in case we ever support VxVMI.
-- ??? - we should come back and visit this so we can set the task name
-- to something appropriate.
Adjusted_Stack_Size := size_t (Stack_Size) + 2048;
-- Since the initial signal mask of a thread is inherited from the
-- creator, and the Environment task has all its signals masked, we do
-- not need to manipulate caller's signal mask at this point. All tasks
-- in RTS will have All_Tasks_Mask initially.
-- We now compute the VxWorks task name and options, then spawn ...
declare
Name : aliased String (1 .. T.Common.Task_Image_Len + 1);
Name_Address : System.Address;
-- Task name we are going to hand down to VxWorks
function Get_Task_Options return int;
pragma Import (C, Get_Task_Options, "__gnat_get_task_options");
-- Function that returns the options to be set for the task that we
-- are creating. We fetch the options assigned to the current task,
-- so offering some user level control over the options for a task
-- hierarchy, and force VX_FP_TASK because it is almost always
-- required.
begin
-- If there is no Ada task name handy, let VxWorks choose one.
-- Otherwise, tell VxWorks what the Ada task name is.
if T.Common.Task_Image_Len = 0 then
Name_Address := System.Null_Address;
else
Name (1 .. Name'Last - 1) :=
T.Common.Task_Image (1 .. T.Common.Task_Image_Len);
Name (Name'Last) := ASCII.NUL;
Name_Address := Name'Address;
end if;
-- Now spawn the VxWorks task for real
T.Common.LL.Thread :=
taskSpawn
(Name_Address,
To_VxWorks_Priority (int (Priority)),
Get_Task_Options,
Adjusted_Stack_Size,
Wrapper,
To_Address (T));
end;
-- Set processor affinity
Set_Task_Affinity (T);
-- Only case of failure is if taskSpawn returned 0 (aka Null_Thread_Id)
if T.Common.LL.Thread = Null_Thread_Id then
Succeeded := False;
else
Succeeded := True;
Task_Creation_Hook (T.Common.LL.Thread);
Set_Priority (T, Priority);
end if;
end Create_Task;
------------------
-- Finalize_TCB --
------------------
procedure Finalize_TCB (T : Task_Id) is
Result : int;
begin
Result := semDelete (T.Common.LL.L.Mutex);
pragma Assert (Result = 0);
T.Common.LL.Thread := Null_Thread_Id;
Result := semDelete (T.Common.LL.CV);
pragma Assert (Result = 0);
if T.Known_Tasks_Index /= -1 then
Known_Tasks (T.Known_Tasks_Index) := null;
end if;
ATCB_Allocation.Free_ATCB (T);
end Finalize_TCB;
---------------
-- Exit_Task --
---------------
procedure Exit_Task is
begin
Specific.Set (null);
end Exit_Task;
----------------
-- Abort_Task --
----------------
procedure Abort_Task (T : Task_Id) is
Result : int;
begin
Result :=
kill
(T.Common.LL.Thread,
Signal (Interrupt_Management.Abort_Task_Interrupt));
pragma Assert (Result = 0);
end Abort_Task;
----------------
-- Initialize --
----------------
procedure Initialize (S : in out Suspension_Object) is
begin
-- Initialize internal state (always to False (RM D.10(6)))
S.State := False;
S.Waiting := False;
-- Initialize internal mutex
-- Use simpler binary semaphore instead of VxWorks mutual exclusion
-- semaphore, because we don't need the fancier semantics and their
-- overhead.
S.L := semBCreate (SEM_Q_FIFO, SEM_FULL);
-- Initialize internal condition variable
S.CV := semBCreate (SEM_Q_FIFO, SEM_EMPTY);
end Initialize;
--------------
-- Finalize --
--------------
procedure Finalize (S : in out Suspension_Object) is
pragma Unmodified (S);
-- S may be modified on other targets, but not on VxWorks
Result : STATUS;
begin
-- Destroy internal mutex
Result := semDelete (S.L);
pragma Assert (Result = OK);
-- Destroy internal condition variable
Result := semDelete (S.CV);
pragma Assert (Result = OK);
end Finalize;
-------------------
-- Current_State --
-------------------
function Current_State (S : Suspension_Object) return Boolean is
begin
-- We do not want to use lock on this read operation. State is marked
-- as Atomic so that we ensure that the value retrieved is correct.
return S.State;
end Current_State;
---------------
-- Set_False --
---------------
procedure Set_False (S : in out Suspension_Object) is
Result : STATUS;
begin
SSL.Abort_Defer.all;
Result := semTake (S.L, WAIT_FOREVER);
pragma Assert (Result = OK);
S.State := False;
Result := semGive (S.L);
pragma Assert (Result = OK);
SSL.Abort_Undefer.all;
end Set_False;
--------------
-- Set_True --
--------------
procedure Set_True (S : in out Suspension_Object) is
Result : STATUS;
begin
-- Set_True can be called from an interrupt context, in which case
-- Abort_Defer is undefined.
if Is_Task_Context then
SSL.Abort_Defer.all;
end if;
Result := semTake (S.L, WAIT_FOREVER);
pragma Assert (Result = OK);
-- If there is already a task waiting on this suspension object then we
-- resume it, leaving the state of the suspension object to False, as it
-- is specified in (RM D.10 (9)). Otherwise, it just leaves the state to
-- True.
if S.Waiting then
S.Waiting := False;
S.State := False;
Result := semGive (S.CV);
pragma Assert (Result = OK);
else
S.State := True;
end if;
Result := semGive (S.L);
pragma Assert (Result = OK);
-- Set_True can be called from an interrupt context, in which case
-- Abort_Undefer is undefined.
if Is_Task_Context then
SSL.Abort_Undefer.all;
end if;
end Set_True;
------------------------
-- Suspend_Until_True --
------------------------
procedure Suspend_Until_True (S : in out Suspension_Object) is
Result : STATUS;
begin
SSL.Abort_Defer.all;
Result := semTake (S.L, WAIT_FOREVER);
if S.Waiting then
-- Program_Error must be raised upon calling Suspend_Until_True
-- if another task is already waiting on that suspension object
-- (RM D.10(10)).
Result := semGive (S.L);
pragma Assert (Result = OK);
SSL.Abort_Undefer.all;
raise Program_Error;
else
-- Suspend the task if the state is False. Otherwise, the task
-- continues its execution, and the state of the suspension object
-- is set to False (RM D.10 (9)).
if S.State then
S.State := False;
Result := semGive (S.L);
pragma Assert (Result = 0);
SSL.Abort_Undefer.all;
else
S.Waiting := True;
-- Release the mutex before sleeping
Result := semGive (S.L);
pragma Assert (Result = OK);
SSL.Abort_Undefer.all;
Result := semTake (S.CV, WAIT_FOREVER);
pragma Assert (Result = 0);
end if;
end if;
end Suspend_Until_True;
----------------
-- Check_Exit --
----------------
-- Dummy version
function Check_Exit (Self_ID : ST.Task_Id) return Boolean is
pragma Unreferenced (Self_ID);
begin
return True;
end Check_Exit;
--------------------
-- Check_No_Locks --
--------------------
function Check_No_Locks (Self_ID : ST.Task_Id) return Boolean is
pragma Unreferenced (Self_ID);
begin
return True;
end Check_No_Locks;
----------------------
-- Environment_Task --
----------------------
function Environment_Task return Task_Id is
begin
return Environment_Task_Id;
end Environment_Task;
--------------
-- Lock_RTS --
--------------
procedure Lock_RTS is
begin
Write_Lock (Single_RTS_Lock'Access);
end Lock_RTS;
----------------
-- Unlock_RTS --
----------------
procedure Unlock_RTS is
begin
Unlock (Single_RTS_Lock'Access);
end Unlock_RTS;
------------------
-- Suspend_Task --
------------------
function Suspend_Task
(T : ST.Task_Id;
Thread_Self : Thread_Id) return Boolean
is
begin
if T.Common.LL.Thread /= Null_Thread_Id
and then T.Common.LL.Thread /= Thread_Self
then
return taskSuspend (T.Common.LL.Thread) = 0;
else
return True;
end if;
end Suspend_Task;
-----------------
-- Resume_Task --
-----------------
function Resume_Task
(T : ST.Task_Id;
Thread_Self : Thread_Id) return Boolean
is
begin
if T.Common.LL.Thread /= Null_Thread_Id
and then T.Common.LL.Thread /= Thread_Self
then
return taskResume (T.Common.LL.Thread) = 0;
else
return True;
end if;
end Resume_Task;
--------------------
-- Stop_All_Tasks --
--------------------
procedure Stop_All_Tasks
is
Thread_Self : constant Thread_Id := taskIdSelf;
C : Task_Id;
Dummy : int;
Old : int;
begin
Old := Int_Lock;
C := All_Tasks_List;
while C /= null loop
if C.Common.LL.Thread /= Null_Thread_Id
and then C.Common.LL.Thread /= Thread_Self
then
Dummy := Task_Stop (C.Common.LL.Thread);
end if;
C := C.Common.All_Tasks_Link;
end loop;
Dummy := Int_Unlock (Old);
end Stop_All_Tasks;
---------------
-- Stop_Task --
---------------
function Stop_Task (T : ST.Task_Id) return Boolean is
begin
if T.Common.LL.Thread /= Null_Thread_Id then
return Task_Stop (T.Common.LL.Thread) = 0;
else
return True;
end if;
end Stop_Task;
-------------------
-- Continue_Task --
-------------------
function Continue_Task (T : ST.Task_Id) return Boolean
is
begin
if T.Common.LL.Thread /= Null_Thread_Id then
return Task_Cont (T.Common.LL.Thread) = 0;
else
return True;
end if;
end Continue_Task;
---------------------
-- Is_Task_Context --
---------------------
function Is_Task_Context return Boolean is
begin
return System.OS_Interface.Interrupt_Context /= 1;
end Is_Task_Context;
----------------
-- Initialize --
----------------
procedure Initialize (Environment_Task : Task_Id) is
Result : int;
pragma Unreferenced (Result);
begin
Environment_Task_Id := Environment_Task;
Interrupt_Management.Initialize;
Specific.Initialize;
if Locking_Policy = 'C' then
Mutex_Protocol := Prio_Protect;
elsif Locking_Policy = 'I' then
Mutex_Protocol := Prio_Inherit;
else
Mutex_Protocol := Prio_None;
end if;
if Time_Slice_Val > 0 then
Result :=
Set_Time_Slice
(To_Clock_Ticks
(Duration (Time_Slice_Val) / Duration (1_000_000.0)));
elsif Dispatching_Policy = 'R' then
Result := Set_Time_Slice (To_Clock_Ticks (0.01));
end if;
-- Initialize the lock used to synchronize chain of all ATCBs
Initialize_Lock (Single_RTS_Lock'Access, RTS_Lock_Level);
-- Make environment task known here because it doesn't go through
-- Activate_Tasks, which does it for all other tasks.
Known_Tasks (Known_Tasks'First) := Environment_Task;
Environment_Task.Known_Tasks_Index := Known_Tasks'First;
Enter_Task (Environment_Task);
-- Set processor affinity
Set_Task_Affinity (Environment_Task);
end Initialize;
-----------------------
-- Set_Task_Affinity --
-----------------------
procedure Set_Task_Affinity (T : ST.Task_Id) is
Result : int := 0;
pragma Unreferenced (Result);
use System.Task_Info;
use type System.Multiprocessors.CPU_Range;
begin
-- Do nothing if the underlying thread has not yet been created. If the
-- thread has not yet been created then the proper affinity will be set
-- during its creation.
if T.Common.LL.Thread = Null_Thread_Id then
null;
-- pragma CPU
elsif T.Common.Base_CPU /= Multiprocessors.Not_A_Specific_CPU then
-- Ada 2012 pragma CPU uses CPU numbers starting from 1, while on
-- VxWorks the first CPU is identified by a 0, so we need to adjust.
Result :=
taskCpuAffinitySet
(T.Common.LL.Thread, int (T.Common.Base_CPU) - 1);
-- Task_Info
elsif T.Common.Task_Info /= Unspecified_Task_Info then
Result := taskCpuAffinitySet (T.Common.LL.Thread, T.Common.Task_Info);
-- Handle dispatching domains
elsif T.Common.Domain /= null
and then (T.Common.Domain /= ST.System_Domain
or else T.Common.Domain.all /=
(Multiprocessors.CPU'First ..
Multiprocessors.Number_Of_CPUs => True))
then
declare
CPU_Set : unsigned := 0;
begin
-- Set the affinity to all the processors belonging to the
-- dispatching domain.
for Proc in T.Common.Domain'Range loop
if T.Common.Domain (Proc) then
-- The thread affinity mask is a bit vector in which each
-- bit represents a logical processor.
CPU_Set := CPU_Set + 2 ** (Integer (Proc) - 1);
end if;
end loop;
Result := taskMaskAffinitySet (T.Common.LL.Thread, CPU_Set);
end;
end if;
end Set_Task_Affinity;
end System.Task_Primitives.Operations;
|
-----------------------------------------------------------------------
-- serialize-io-json-tests -- Unit tests for JSON parser
-- Copyright (C) 2011, 2016, 2017, 2020 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.Streams.Stream_IO;
with Ada.Characters.Wide_Wide_Latin_1;
with Ada.Calendar.Formatting;
with Util.Test_Caller;
with Util.Log.Loggers;
with Util.Streams.Files;
with Util.Beans.Objects.Readers;
package body Util.Serialize.IO.JSON.Tests is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.IO.JSON");
package Caller is new Util.Test_Caller (Test, "Serialize.IO.JSON");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse errors)",
Test_Parse_Error'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Parse (parse Ok)",
Test_Parser'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write",
Test_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write (Simple)",
Test_Simple_Output'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Write (Nullable)",
Test_Nullable'Access);
Caller.Add_Test (Suite, "Test Util.Serialize.IO.JSON.Read",
Test_Read'Access);
end Add_Tests;
-- ------------------------------
-- Check various JSON parsing errors.
-- ------------------------------
procedure Test_Parse_Error (T : in out Test) is
pragma Unreferenced (T);
procedure Check_Parse_Error (Content : in String);
procedure Check_Parse_Error (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
begin
P.Parse_String (Content, R);
Log.Error ("No exception raised for: {0}", Content);
exception
when Parse_Error =>
null;
end Check_Parse_Error;
begin
Check_Parse_Error ("{ ""person"":23");
Check_Parse_Error ("{ person: 23]");
Check_Parse_Error ("[ }");
Check_Parse_Error ("{[]}");
Check_Parse_Error ("{");
Check_Parse_Error ("{[");
Check_Parse_Error ("{ ""person");
Check_Parse_Error ("{ ""person"":");
Check_Parse_Error ("{ ""person"":""asf");
Check_Parse_Error ("{ ""person"":""asf""");
Check_Parse_Error ("{ ""person"":""asf"",");
Check_Parse_Error ("{ ""person"":""\uze""}");
Check_Parse_Error ("{ ""person"":""\u012-""}");
Check_Parse_Error ("{ ""person"":""\u012G""}");
end Test_Parse_Error;
-- ------------------------------
-- Check various (basic) JSON valid strings (no mapper).
-- ------------------------------
procedure Test_Parser (T : in out Test) is
procedure Check_Parse (Content : in String);
procedure Check_Parse (Content : in String) is
P : Parser;
R : Util.Beans.Objects.Readers.Reader;
Root : Util.Beans.Objects.Object;
begin
P.Parse_String (Content, R);
Root := R.Get_Root;
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Null result for " & Content);
exception
when Parse_Error =>
Log.Error ("Parse error for: " & Content);
raise;
end Check_Parse;
begin
Check_Parse ("{ ""person"":23}");
Check_Parse ("{ }");
Check_Parse ("{""person"":""asf""}");
Check_Parse ("{""person"":""asf"",""age"":""2""}");
Check_Parse ("{ ""person"":""\u0123""}");
Check_Parse ("{ ""person"":""\u4567""}");
Check_Parse ("{ ""person"":""\u89ab""}");
Check_Parse ("{ ""person"":""\ucdef""}");
Check_Parse ("{ ""person"":""\u1CDE""}");
Check_Parse ("{ ""person"":""\u2ABF""}");
Check_Parse ("[{ ""person"":""\u2ABF""}]");
Check_Parse ("""testt""");
Check_Parse ("""""");
Check_Parse ("123");
end Test_Parser;
-- ------------------------------
-- Generate some output stream for the test.
-- ------------------------------
procedure Write_Stream (Stream : in out Util.Serialize.IO.Output_Stream'Class) is
Name : Ada.Strings.Unbounded.Unbounded_String;
Wide : constant Wide_Wide_String :=
Ada.Characters.Wide_Wide_Latin_1.CR &
Ada.Characters.Wide_Wide_Latin_1.LF &
Ada.Characters.Wide_Wide_Latin_1.HT &
Wide_Wide_Character'Val (16#080#) &
Wide_Wide_Character'Val (16#1fC#) &
Wide_Wide_Character'Val (16#20AC#) & -- Euro sign
Wide_Wide_Character'Val (16#2acbf#);
T : constant Ada.Calendar.Time := Ada.Calendar.Formatting.Time_Of (2011, 11, 19, 23, 0, 0);
begin
Ada.Strings.Unbounded.Append (Name, "Katniss Everdeen");
Stream.Start_Document;
Stream.Start_Entity ("root");
Stream.Start_Entity ("person");
Stream.Write_Attribute ("id", 1);
Stream.Write_Attribute ("name", Name);
Stream.Write_Entity ("name", Name);
Stream.Write_Entity ("gender", "female");
Stream.Write_Entity ("volunteer", True);
Stream.Write_Entity ("age", 17);
Stream.Write_Entity ("date", T);
Stream.Write_Wide_Entity ("skin", "olive skin");
Stream.Start_Array ("badges");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "hunter");
Stream.End_Entity ("badge");
Stream.Start_Entity ("badge");
Stream.Write_Entity ("level", "gold");
Stream.Write_Entity ("name", "archery");
Stream.End_Entity ("badge");
Stream.End_Array ("badges");
Stream.Start_Entity ("district");
Stream.Write_Attribute ("id", 12);
Stream.Write_Wide_Attribute ("industry", "Coal mining");
Stream.Write_Attribute ("state", "<destroyed>");
Stream.Write_Long_Entity ("members", 10_000);
Stream.Write_Entity ("description", "<TBW>&""");
Stream.Write_Wide_Entity ("wescape", "'""<>&;,@!`~[]{}^%*()-+=");
Stream.Write_Entity ("escape", "'""<>&;,@!`~\[]{}^%*()-+=");
Stream.Write_Wide_Entity ("wide", Wide);
Stream.End_Entity ("district");
Stream.End_Entity ("person");
Stream.End_Entity ("root");
Stream.End_Document;
end Write_Stream;
-- ------------------------------
-- Test the JSON output stream generation.
-- ------------------------------
procedure Test_Output (T : in out Test) is
File : aliased Util.Streams.Files.File_Stream;
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
Expect : constant String := Util.Tests.Get_Path ("regtests/expect/test-stream.json");
Path : constant String := Util.Tests.Get_Test_Path ("regtests/result/test-stream.json");
begin
File.Create (Mode => Ada.Streams.Stream_IO.Out_File, Name => Path);
Buffer.Initialize (Output => File'Unchecked_Access, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Write_Stream (Stream);
Stream.Close;
Util.Tests.Assert_Equal_Files (T => T,
Expect => Expect,
Test => Path,
Message => "JSON output serialization");
end Test_Output;
-- ------------------------------
-- Test the JSON output stream generation (simple JSON documents).
-- ------------------------------
procedure Test_Simple_Output (T : in out Test) is
function Get_Array return String;
function Get_Struct return String;
function Get_Named_Struct return String;
function Get_Integer return String;
function Get_String return String;
function Get_Array return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Array ("");
Stream.Write_Entity ("", 23);
Stream.Write_Entity ("", 45);
Stream.End_Array ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Array;
function Get_Struct return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("");
Stream.Write_Entity ("age", 23);
Stream.Write_Entity ("id", 45);
Stream.End_Entity ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Struct;
function Get_Named_Struct return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("name");
Stream.Write_Entity ("age", 23);
Stream.Write_Entity ("id", 45);
Stream.End_Entity ("");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Named_Struct;
function Get_Integer return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Write_Entity ("", 23);
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_Integer;
function Get_String return String is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Write_Entity ("", "test");
Stream.End_Document;
Stream.Close;
return Util.Streams.Texts.To_String (Buffer);
end Get_String;
A1 : constant String := Get_Array;
S1 : constant String := Get_Struct;
S2 : constant String := Get_Named_Struct;
I1 : constant String := Get_Integer;
S3 : constant String := Get_String;
begin
Log.Error ("Array: {0}", A1);
Util.Tests.Assert_Equals (T, "[ 23, 45]", A1,
"Invalid JSON array");
Log.Error ("Struct: {0}", S1);
Util.Tests.Assert_Equals (T, "{""age"": 23,""id"": 45}", S1,
"Invalid JSON struct");
Log.Error ("Struct: {0}", S2);
Util.Tests.Assert_Equals (T, "{""name"":{""age"": 23,""id"": 45}}", S2,
"Invalid JSON struct");
Log.Error ("Struct: {0}", I1);
Util.Tests.Assert_Equals (T, " 23", I1,
"Invalid JSON struct");
Log.Error ("Struct: {0}", S3);
Util.Tests.Assert_Equals (T, """test""", S3,
"Invalid JSON struct");
end Test_Simple_Output;
-- ------------------------------
-- Test the JSON output stream generation and parsing for nullable basic types.
-- ------------------------------
procedure Test_Nullable (T : in out Test) is
Buffer : aliased Util.Streams.Texts.Print_Stream;
Stream : Util.Serialize.IO.JSON.Output_Stream;
S : Util.Nullables.Nullable_String;
B : Util.Nullables.Nullable_Boolean;
I : Util.Nullables.Nullable_Integer;
D : Util.Nullables.Nullable_Time;
begin
Buffer.Initialize (Output => null, Size => 10000);
Stream.Initialize (Output => Buffer'Unchecked_Access);
Stream.Start_Document;
Stream.Start_Entity ("");
Stream.Write_Entity ("string", S);
Stream.Write_Entity ("bool", B);
Stream.Write_Entity ("int", I);
Stream.Write_Entity ("date", D);
Stream.End_Entity ("");
Stream.End_Document;
Stream.Close;
declare
Data : constant String := Util.Streams.Texts.To_String (Buffer);
begin
Log.Error ("JSON: {0}", Data);
Util.Tests.Assert_Equals (T,
"{""string"":null,""bool"":null,""int"":null,""date"":null}",
Data,
"Invalid JSON for nullable values");
end;
end Test_Nullable;
-- ------------------------------
-- Test reading a JSON content into an Object tree.
-- ------------------------------
procedure Test_Read (T : in out Test) is
use Util.Beans.Objects;
Path : constant String := Util.Tests.Get_Test_Path ("regtests/files/pass01.json");
Root : Util.Beans.Objects.Object;
Value : Util.Beans.Objects.Object;
Item : Util.Beans.Objects.Object;
begin
Root := Read (Path);
T.Assert (not Util.Beans.Objects.Is_Null (Root), "Read should not return null object");
T.Assert (Util.Beans.Objects.Is_Array (Root), "Root object is an array");
Value := Util.Beans.Objects.Get_Value (Root, 1);
Util.Tests.Assert_Equals (T, "JSON Test Pattern pass1",
Util.Beans.Objects.To_String (Value), "Invalid first element");
Value := Util.Beans.Objects.Get_Value (Root, 4);
T.Assert (Util.Beans.Objects.Is_Array (Value), "Element 4 should be an empty array");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.Get_Count (Value), "Invalid array");
Value := Util.Beans.Objects.Get_Value (Root, 8);
T.Assert (Util.Beans.Objects.Is_Null (Value), "Element 8 should be null");
Value := Util.Beans.Objects.Get_Value (Root, 9);
T.Assert (not Util.Beans.Objects.Is_Null (Value), "Element 9 should not be null");
Item := Util.Beans.Objects.Get_Value (Value, "integer");
Util.Tests.Assert_Equals (T, 1234567890, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value");
Item := Util.Beans.Objects.Get_Value (Value, "zero");
Util.Tests.Assert_Equals (T, 0, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (0)");
Item := Util.Beans.Objects.Get_Value (Value, "one");
Util.Tests.Assert_Equals (T, 1, Util.Beans.Objects.To_Integer (Item),
"Invalid integer value (1)");
Item := Util.Beans.Objects.Get_Value (Value, "true");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value true should be a boolean");
T.Assert (Util.Beans.Objects.To_Boolean (Item),
"The value true should be... true!");
Item := Util.Beans.Objects.Get_Value (Value, "false");
T.Assert (Util.Beans.Objects.Get_Type (Item) = TYPE_BOOLEAN,
"The value false should be a boolean");
T.Assert (not Util.Beans.Objects.To_Boolean (Item),
"The value false should be... false!");
Item := Util.Beans.Objects.Get_Value (Value, " s p a c e d ");
T.Assert (Is_Array (Item), "The value should be an array");
for I in 1 .. 7 loop
Util.Tests.Assert_Equals (T, I, To_Integer (Get_Value (Item, I)),
"Invalid array value at " & Integer'Image (I));
end loop;
end Test_Read;
end Util.Serialize.IO.JSON.Tests;
|
package agar.gui.point is
type point_t is record
x : c.int;
y : c.int;
end record;
type point_access_t is access all point_t;
pragma convention (c, point_t);
pragma convention (c, point_access_t);
end agar.gui.point;
|
-- { dg-do run }
procedure Packed_Subtype is
subtype Ubyte is Integer range 0 .. 255;
type Packet (Id : Ubyte) is record
A, B : Ubyte;
end record;
pragma Pack (Packet);
subtype My_Packet is Packet (Id => 1);
MP : My_Packet;
begin
MP.A := 1;
MP.B := 2;
if MP.A /= 1 or else MP.B /= 2 then
raise Program_Error;
end if;
end;
|
-- convert UCD/UnicodeData.txt, UCD/CompositionExclusions.txt
-- bin/ucd_normalization -r $UCD/UnicodeData.txt $UCD/CompositionExclusions.txt > ../source/strings/a-ucdnor.ads
-- bin/ucd_normalization -u $UCD/UnicodeData.txt $UCD/CompositionExclusions.txt > ../source/strings/a-ucnoun.ads
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Ordered_Sets;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.Maps.Constants; use Ada.Strings.Maps.Constants;
with Ada.Strings.Wide_Wide_Unbounded; use Ada.Strings.Wide_Wide_Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
procedure ucd_normalization is
function Value (S : String) return Wide_Wide_Character is
Img : constant String := "Hex_" & (1 .. 8 - S'Length => '0') & S;
begin
return Wide_Wide_Character'Value (Img);
end Value;
procedure Put_16 (Item : Integer) is
begin
if Item >= 16#10000# then
Put (Item, Width => 1, Base => 16);
else
declare
S : String (1 .. 8); -- "16#XXXX#"
begin
Put (S, Item, Base => 16);
S (1) := '1';
S (2) := '6';
S (3) := '#';
for I in reverse 4 .. 6 loop
if S (I) = '#' then
S (4 .. I) := (others => '0');
exit;
end if;
end loop;
Put (S);
end;
end if;
end Put_16;
function NFS_Exclusion (C : Wide_Wide_Character) return Boolean is
begin
case Wide_Wide_Character'Pos (C) is
when 16#2000# .. 16#2FFF#
| 16#F900# .. 16#FAFF#
| 16#2F800# .. 16#2FAFF# =>
return True;
when others =>
return False;
end case;
end NFS_Exclusion;
package Decomposite_Maps is new Ada.Containers.Ordered_Maps (
Wide_Wide_Character,
Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String);
use Decomposite_Maps;
package WWC_Sets is new Ada.Containers.Ordered_Sets (
Wide_Wide_Character);
use WWC_Sets;
NFD : Decomposite_Maps.Map;
Exclusions : WWC_Sets.Set;
type Kind_Type is (Decomposition, Excluded, Singleton);
type Bit is (In_16, In_32);
function Get_Bit (C : Wide_Wide_Character) return Bit is
begin
if C > Wide_Wide_Character'Val (16#FFFF#) then
return In_32;
else
return In_16;
end if;
end Get_Bit;
function Get_Bit (S : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String) return Bit is
begin
for I in 1 .. Length (S) loop
if Get_Bit (Element (S, I)) = In_32 then
return In_32;
end if;
end loop;
return In_16;
end Get_Bit;
type Normalization is (D, C);
Total_Num : array (Boolean, Normalization) of Natural;
Num : array (Boolean, Kind_Type, Bit) of Natural;
type Output_Kind is (Reversible, Unreversible);
Output : Output_Kind;
begin
if Argument (1) = "-r" then
Output := Reversible;
elsif Argument (1) = "-u" then
Output := Unreversible;
else
raise Data_Error with "-r or -u";
end if;
declare
File : Ada.Text_IO.File_Type;
begin
Open (File, In_File, Argument (2));
while not End_Of_File (File) loop
declare
Line : constant String := Get_Line (File);
type Range_Type is record
First : Positive;
Last : Natural;
end record;
Fields : array (1 .. 14) of Range_Type;
P : Positive := Line'First;
N : Natural;
Token_First : Positive;
Token_Last : Natural;
Code : Wide_Wide_Character;
Alt : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String;
begin
for I in Fields'Range loop
N := P;
while N <= Line'Last and then Line (N) /= ';' loop
N := N + 1;
end loop;
if (N <= Line'Last) /= (I < Field'Last) then
raise Data_Error with Line & " -- 2A";
end if;
Fields (I).First := P;
Fields (I).Last := N - 1;
P := N + 1; -- skip ';'
end loop;
Code := Value (Line (Fields (1).First .. Fields (1).Last));
if Fields (6).First <= Fields (6).Last then -- normalization
if Line (Fields (6).First) = '<' then
null; -- skip NFKD
else -- NFD
Alt := Null_Unbounded_Wide_Wide_String;
P := Fields (6).First;
while P <= Fields (6).Last loop
Find_Token (
Line (P .. Fields (6).Last),
Hexadecimal_Digit_Set,
Inside,
Token_First,
Token_Last);
if Token_First /= P then
raise Data_Error with Line & " -- 2B";
end if;
Append (Alt, Value (Line (Token_First .. Token_Last)));
P := Token_Last + 1;
exit when P > Fields (6).Last;
N := Index_Non_Blank (Line (P .. Fields (6).Last));
if N = 0 then
raise Data_Error with Line & " -- 2C";
end if;
P := N;
end loop;
Insert (NFD, Code, Alt);
end if;
end if;
end;
end loop;
Close (File);
end;
declare
I : Decomposite_Maps.Cursor := First (NFD);
begin
while Has_Element (I) loop
if not NFS_Exclusion (Key (I)) then
declare
J : Decomposite_Maps.Cursor := Next (I);
begin
while Has_Element (J) loop
if Element (I) = Element (J) then
raise Data_Error with "dup";
end if;
J := Next (J);
end loop;
end;
end if;
I := Next (I);
end loop;
end;
declare
File : Ada.Text_IO.File_Type;
begin
Open (File, In_File, Argument (3));
while not End_Of_File (File) loop
declare
Line : constant String := Get_Line (File);
P : Positive := Line'First;
Token_First : Positive;
Token_Last : Natural;
First : Wide_Wide_Character;
begin
if Line'Length = 0 or else Line (P) = '#' then
null; -- comment
else
Find_Token (
Line (P .. Line'Last),
Hexadecimal_Digit_Set,
Inside,
Token_First,
Token_Last);
if Token_First /= P then
raise Data_Error with Line & " -- 3A";
end if;
First := Value (Line (Token_First .. Token_Last));
P := Token_Last + 1;
if Line (P) = '.' then
raise Data_Error with Line & " -- 3B";
end if;
if not Contains (NFD, First) then
raise Data_Error with Line & " -- 3C";
end if;
Insert (Exclusions, First);
end if;
end;
end loop;
Close (File);
end;
-- # (4) Non-Starter Decompositions
-- # 0344 COMBINING GREEK DIALYTIKA TONOS
-- # 0F73 TIBETAN VOWEL SIGN II
-- # 0F75 TIBETAN VOWEL SIGN UU
-- # 0F81 TIBETAN VOWEL SIGN REVERSED II
Insert (Exclusions, Wide_Wide_Character'Val (16#0344#));
Insert (Exclusions, Wide_Wide_Character'Val (16#0F73#));
Insert (Exclusions, Wide_Wide_Character'Val (16#0F75#));
Insert (Exclusions, Wide_Wide_Character'Val (16#0F81#));
-- count
for NFSE in Boolean loop
for K in Kind_Type loop
for B in Bit loop
Num (NFSE, K, B) := 0;
end loop;
end loop;
for N in Normalization loop
Total_Num (NFSE, N) := 0;
end loop;
end loop;
declare
I : Decomposite_Maps.Cursor := First (NFD);
begin
while Has_Element (I) loop
declare
NFSE : Boolean := NFS_Exclusion (Key (I));
B : Bit := Bit'Max (Get_Bit (Key (I)), Get_Bit (Element (I)));
K : Kind_Type;
begin
if Contains (Exclusions, Key (I)) then
K := Excluded;
elsif Length (Element (I)) > 1 then
K := Decomposition;
Total_Num (NFSE, C) := Total_Num (NFSE, C) + 1;
else
K := Singleton;
end if;
Num (NFSE, K, B) := Num (NFSE, K, B) + 1;
Total_Num (NFSE, D) := Total_Num (NFSE, D) + 1;
end;
I := Next (I);
end loop;
end;
-- output the Ada spec
case Output is
when Reversible =>
Put_Line ("pragma License (Unrestricted);");
Put_Line ("-- implementation unit,");
Put_Line ("-- translated from UnicodeData.txt (6), CompositionExclusions.txt");
Put_Line ("package Ada.UCD.Normalization is");
Put_Line (" pragma Pure;");
New_Line;
Put_Line (" -- excluding U+2000..U+2FFF, U+F900..U+FAFF, and U+2F800..U+2FAFF");
New_Line;
Put (" NFD_Total : constant := ");
Put (Total_Num (False, D), Width => 1);
Put (";");
New_Line;
Put (" NFC_Total : constant := ");
Put (Total_Num (False, C), Width => 1);
Put (";");
New_Line;
New_Line;
when Unreversible =>
Put_Line ("pragma License (Unrestricted);");
Put_Line ("-- implementation unit,");
Put_Line ("-- translated from UnicodeData.txt (6), CompositionExclusions.txt");
Put_Line ("package Ada.UCD.Normalization.Unreversible is");
Put_Line (" pragma Pure;");
New_Line;
Put_Line (" -- including U+2000..U+2FFF, U+F900..U+FAFF, and U+2F800..U+2FAFF");
New_Line;
Put (" NFD_Unreversible_Total : constant := ");
Put (Total_Num (True, D), Width => 1);
Put (";");
New_Line;
Put (" NFC_Unreversible_Total : constant := ");
Put (Total_Num (True, C), Width => 1);
Put (";");
New_Line;
New_Line;
end case;
declare
NFSE : constant Boolean := Output = Unreversible;
begin
for K in Kind_Type loop
for B in Bit loop
if Num (NFSE, K, B) /= 0 then
Put (" NFD_");
if NFSE then
Put ("Unreversible_");
end if;
case K is
when Decomposition => Put ("D_");
when Excluded => Put ("E_");
when Singleton => Put ("S_");
end case;
Put ("Table_");
case B is
when In_16 => Put ("XXXX");
when In_32 => Put ("XXXXXXXX");
end case;
Put (" : constant Map_");
case B is
when In_16 => Put ("16");
when In_32 => Put ("32");
end case;
Put ("x");
case K is
when Decomposition | Excluded => Put ("2");
when Singleton => Put ("1");
end case;
Put ("_Type (1 .. ");
Put (Num (NFSE, K, B), Width => 1);
Put (") := (");
New_Line;
declare
I : Decomposite_Maps.Cursor := First (NFD);
Second : Boolean := False;
begin
while Has_Element (I) loop
declare
Item_NFSE : Boolean := NFS_Exclusion (Key (I));
Item_B : Bit := Bit'Max (Get_Bit (Key (I)), Get_Bit (Element (I)));
Item_K : Kind_Type;
begin
if Contains (Exclusions, Key (I)) then
Item_K := Excluded;
elsif Length (Element (I)) > 1 then
Item_K := Decomposition;
else
Item_K := Singleton;
end if;
if Item_NFSE = NFSE
and then Item_K = K
and then Item_B = B
then
if Second then
Put (",");
New_Line;
end if;
Put (" ");
if Num (NFSE, K, B) = 1 then
Put ("1 => ");
end if;
Put ("(");
Put_16 (Wide_Wide_Character'Pos (Key (I)));
Put (", ");
if K = Singleton then
Put_16 (
Wide_Wide_Character'Pos (
Element (Element (I), 1)));
else
declare
E : Ada.Strings.Wide_Wide_Unbounded.Unbounded_Wide_Wide_String
renames Element (I);
begin
Put ("(");
for EI in 1 .. Length (E) loop
if EI > 1 then
Put (", ");
end if;
Put_16 (
Wide_Wide_Character'Pos (
Element (E, EI)));
end loop;
Put (")");
end;
end if;
Put (")");
Second := True;
end if;
end;
I := Next (I);
end loop;
Put (");");
New_Line;
end;
New_Line;
end if;
end loop;
end loop;
end;
case Output is
when Reversible =>
Put_Line ("end Ada.UCD.Normalization;");
when Unreversible =>
Put_Line ("end Ada.UCD.Normalization.Unreversible;");
end case;
end ucd_normalization;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- Copyright (C) 2013-2019, 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. --
-- --
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- This subprogram is called before elaboration
pragma Warnings (Off);
with System.SAMV71; use System.SAMV71;
pragma Warnings (On);
with Interfaces.SAM; use Interfaces.SAM;
with Interfaces.SAM.EFC; use Interfaces.SAM.EFC;
with Interfaces.SAM.PMC; use Interfaces.SAM.PMC;
with System.BB.Board_Parameters;
procedure Setup_Pll
is
Master_Clock : Natural;
FWS : EFC_EEFC_FMR_FWS_Field;
begin
-- Set FWS to max to handle clock changes below
EFC_Periph.EEFC_FMR := (FWS => 6,
CLOE => 1,
others => <>);
-- 31.17 Recommended Programming Sequence
-- 1. If the Main crystal oscillator is not required, the PLL and divider
-- can be directly configured (Step 6.) else this oscillator must be
-- started (Step 2.).
null;
-- 2. Enable the Main crystal oscillator by setting CKGR_MOR.MOSCXTEN.
-- The user can define a startup time. This can be done by configuring
-- the appropriate value in CKGR_MOR.MOSCXTST. Once this register has
-- been correctly configured, the user must wait for PMC_SR.MOSCXTS to
-- be set. This can be done either by polling PMC_SR.MOSCXTS, or by
-- waiting for the interrupt line to be raised if the associated
-- interrupt source (MOSCXTS) has been enabled in PMC_IER.
PMC_Periph.CKGR_MOR := (MOSCXTEN => 1,
MOSCRCEN => 1,
MOSCXTST => 8,
KEY => Passwd,
others => <>);
while PMC_Periph.PMC_SR.MOSCXTS = 0 loop
null;
end loop;
-- 3. Switch MAINCK to the Main crystal oscillator by setting
-- CKGR_MOR.MOSCSEL.
PMC_Periph.CKGR_MOR := (MOSCXTEN => 1,
MOSCRCEN => 1,
MOSCXTST => 8,
KEY => Passwd,
MOSCSEL => 1,
others => <>);
-- 4. Wait for PMC_SR.MOSCSELS to be set to ensure the switch is complete.
while PMC_Periph.PMC_SR.MOSCSELS = 0 loop
null;
end loop;
-- 5. Check MAINCK frequency:
-- This Frequency Can Be Measured Via CKGR_MCFR.
-- Read CKGR_MCFR until The MAINFRDY Field is Set, After Which The
-- User Can Read CKGR_MCFR.MAINF By Performing An Additional Read.
-- This Provides The Number of Main Clock Cycles That Have Been
-- Counted During A Period of 16 SLCK Cycles.
-- If MAINF = 0, switch MAINCK to the Main RC Oscillator by clearing
-- CKGR_MOR.MOSCSEL. If MAINF /= 0, proceed to Step 6
while PMC_Periph.CKGR_MCFR.MAINFRDY = 0 loop
null;
end loop;
if PMC_Periph.CKGR_MCFR.MAINF = 0 then
PMC_Periph.CKGR_MOR.MOSCSEL := 0;
end if;
-- 6. Set PLLA and Divider (if not required, proceed to Step 7.):
-- All parameters needed to configure PLLA and the divider are located
-- in CKGR_PLLAR.
-- CKGR_PLLAR.DIVA is used to control the divider. This parameter can be
-- Programmed Between 0 and 127. Divider Output is Divider Input Divided
-- By DIVA Parameter. By Default, DIVA Field is Cleared Which Means That
-- The Divider and PLLA Are Turned Off.
-- CKGR_PLLAR.MULA is The PLLA Multiplier Factor. This Parameter Can Be
-- Programmed Between 0 and 62. if MULA is Cleared, PLLA Will Be Turned
-- Off, Otherwise The PLLA Output Frequency is PLLA Input Frequency
-- Multiplied By (MULA + 1).
-- CKGR_PLLAR.PLLACOUNT specifies the number of SLCK cycles before
-- PMC_SR.LOCKA is set after CKGR_PLLAR has been written.
-- Once CKGR_PLLAR Has Been Written, The User Must Wait for PMC_SR.LOCKA
-- To Be Set. This Can Be Done Either By Polling PMC_SR.LOCKA or By
-- Waiting for The Interrupt Line To Be Raised if The Associated
-- Interrupt Source (LOCKA) Has Been Enabled in PMC_IER. all Fields in
-- CKGR_PLLAR Can Be Programmed in A Single Write Operation. if MULA or
-- DIVA is Modified, The LOCKA Bit Goes Low To Indicate That PLLA is not
-- Yet Ready. when PLLA is Locked, LOCKA is Set Again. The User Must Wait
-- for The LOCKA Bit To Be Set Before Using The PLLA Output Clock.
PMC_Periph.CKGR_PLLAR := (ONE => 1,
MULA => System.BB.Board_Parameters.PLL_MULA - 1,
DIVA => System.BB.Board_Parameters.PLL_DIVA,
PLLACOUNT => 16#3F#,
others => <>);
while PMC_Periph.PMC_SR.LOCKA = 0 loop
null;
end loop;
-- 7. Select MCK and HCLK:
-- MCK and HCLK are configurable via PMC_MCKR.
-- CSS is Used To select The Clock Source of MCK and HCLK. By Default, The
-- Selected Clock Source is MAINCK.
-- PRES is used to define the HCLK and MCK prescaler.s The user can choose
-- between different values (1, 2, 3, 4, 8, 16, 32, 64). Prescaler output
-- is the selected clock source frequency divided by the PRES value.
-- MDIV is used to define the MCK divider. It is possible to choose between
-- different values (0, 1, 2, 3). MCK output is the HCLK frequency
-- divided by 1, 2, 3 or 4, depending on the value programmed in MDIV.
-- By default, MDIV is cleared, which indicates that the HCLK is equal
-- to MCK.
-- Once the PMC_MCKR has been written, the user must wait for PMC_SR.MCKRDY
-- to be set. This can be done either by polling PMC_SR.MCKRDY or by
-- waiting for the interrupt line to be raised if the associated
-- interrupt source (MCKRDY) has been enabled in PMC_IER. PMC_MCKR
-- must not be programmed in a single write operation. The programming
-- sequence for PMC_MCKR is as follows :
-- If a new value for PMC_MCKR.CSS corresponds to any of the available
-- PLL clocks :
-- a. Program PMC_MCKR.PRES.
-- b. Wait for PMC_SR.MCKRDY to be set.
-- c. Program PMC_MCKR.MDIV.
-- d. Wait for PMC_SR.MCKRDY to be set.
-- e. Program PMC_MCKR.CSS.
-- f. Wait for PMC_SR.MCKRDY to be set.
-- If a new value for PMC_MCKR.CSS corresponds to MAINCK or SLCK:
-- a. Program PMC_MCKR.CSS.
-- b. Wait for PMC_SR.MCKRDY to be set.
-- c. Program PMC_MCKR.PRES.
-- d. Wait for PMC_SR.MCKRDY to be set.
-- If CSS, MDIV or PRES are modified at any stage, the MCKRDY bit goes
-- low to indicate that MCK and HCLK are not yet ready. The user
-- must wait for MCKRDY bit to be set again before using MCK and
-- HCLK.
-- MCK is MAINCK divided by 2.
PMC_Periph.PMC_MCKR.PRES := Clk_1;
while PMC_Periph.PMC_SR.MCKRDY = 0 loop
null;
end loop;
pragma Warnings (Off);
PMC_Periph.PMC_MCKR.MDIV :=
(if System.BB.Board_Parameters.Clock_Frequency > 150_000_000 then
PMC.Pck_Div2 else PMC.Eq_Pck);
pragma Warnings (On);
while PMC_Periph.PMC_SR.MCKRDY = 0 loop
null;
end loop;
PMC_Periph.PMC_MCKR.CSS := PMC.Plla_Clk;
while PMC_Periph.PMC_SR.MCKRDY = 0 loop
null;
end loop;
-- 8. Select the Programmable clocks (PCKx):
-- PCKx are controlled via registers PMC_SCER, PMC_SCDR and PMC_SCSR.
-- PCKx Can Be Enabled and / or Disabled Via PMC_SCER and PMC_SCDR.
-- Three PCKx Can Be Used. PMC_SCSR Indicates Which PCKx is Enabled.
-- By Default all PCKx Are Disabled.
-- PMC_PCKx Registers Are Used To Configure PCKx.
-- PMC_PCKx.CSS is used to select the PCKx divider source. Several clock
-- Options are available :
-- MAINCK, SLCK, MCK, PLLACK, UPLLCKDIV
-- SLCK is The Default Clock Source.
-- PMC_PCKx.PRES is Used To Control The PCKx Prescaler. It is Possible To
-- Choose Between Different Values (1 To 256). PCKx Output is Prescaler
-- Input Divided By PRES. By Default, The PRES Value is Cleared Which
-- Means That PCKx is Equal To Slow Clock.
-- Once PMC_PCKx Has Been Configured, The Corresponding PCKx Must Be
-- Enabled and The User Must Wait for PMC_SR.PCKRDYx To Be Set. This
-- Can Be Done Either By Polling PMC_SR.PCKRDYx or By Waiting for The
-- Interrupt Line To Be Raised if The Associated Interrupt Source
-- (PCKRDYx) Has Been Enabled in PMC_IER. all Parameters in PMC_PCKx
-- Can Be Programmed in A Single Write Operation.
-- If The PMC_PCKx.CSS and PMC_PCKx.PRES Parameters Are To Be Modified,
-- The Corresponding PCKx Must Be Disabled First. The Parameters Can
-- then Be Modified. Once This Has Been Done, The User Must Re - Enable
-- PCKx and Wait for The PCKRDYx Bit To Be Set.
null;
-- 9. Enable the peripheral clocks
-- Once all of The Previous Steps Have Been Completed, The Peripheral
-- Clocks Can Be Enabled and / or Disabled Via Registers PMC_PCERx and
-- PMC_PCDRx.
null;
case PMC_Periph.PMC_MCKR.MDIV is
when Eq_Pck =>
Master_Clock := System.BB.Board_Parameters.Clock_Frequency;
when Pck_Div2 =>
Master_Clock := System.BB.Board_Parameters.Clock_Frequency / 2;
when Pck_Div4 =>
Master_Clock := System.BB.Board_Parameters.Clock_Frequency / 4;
when Pck_Div3 =>
Master_Clock := System.BB.Board_Parameters.Clock_Frequency / 3;
end case;
if Master_Clock < 23_000_000 then
FWS := 0;
elsif Master_Clock < 46_000_000 then
FWS := 1;
elsif Master_Clock < 69_000_000 then
FWS := 2;
elsif Master_Clock < 92_000_000 then
FWS := 3;
elsif Master_Clock < 115_000_000 then
FWS := 4;
elsif Master_Clock < 138_000_000 then
FWS := 5;
else
FWS := 6;
end if;
EFC_Periph.EEFC_FMR := (FWS => FWS,
CLOE => 1,
others => <>);
end Setup_Pll;
|
function Palindrome (Text : String) return Boolean is
begin
for Offset in 0..Text'Length / 2 - 1 loop
if Text (Text'First + Offset) /= Text (Text'Last - Offset) then
return False;
end if;
end loop;
return True;
end Palindrome;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ V F P T --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1997-2000, 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 CStand; use CStand;
with Einfo; use Einfo;
with Opt; use Opt;
with Stand; use Stand;
with Targparm; use Targparm;
with Ttypef; use Ttypef;
with Uintp; use Uintp;
pragma Elaborate_All (Uintp);
package body Sem_VFpt is
T_Digits : constant Uint := UI_From_Int (IEEEL_Digits);
-- Digits for IEEE formats
-----------------
-- Set_D_Float --
-----------------
procedure Set_D_Float (E : Entity_Id) is
begin
Init_Size (Base_Type (E), 64);
Init_Alignment (Base_Type (E));
Init_Digits_Value (Base_Type (E), VAXDF_Digits);
Set_Vax_Float (Base_Type (E), True);
Set_Float_Bounds (Base_Type (E));
Init_Size (E, 64);
Init_Alignment (E);
Init_Digits_Value (E, VAXDF_Digits);
Set_Scalar_Range (E, Scalar_Range (Base_Type (E)));
end Set_D_Float;
-----------------
-- Set_F_Float --
-----------------
procedure Set_F_Float (E : Entity_Id) is
begin
Init_Size (Base_Type (E), 32);
Init_Alignment (Base_Type (E));
Init_Digits_Value (Base_Type (E), VAXFF_Digits);
Set_Vax_Float (Base_Type (E), True);
Set_Float_Bounds (Base_Type (E));
Init_Size (E, 32);
Init_Alignment (E);
Init_Digits_Value (E, VAXFF_Digits);
Set_Scalar_Range (E, Scalar_Range (Base_Type (E)));
end Set_F_Float;
-----------------
-- Set_G_Float --
-----------------
procedure Set_G_Float (E : Entity_Id) is
begin
Init_Size (Base_Type (E), 64);
Init_Alignment (Base_Type (E));
Init_Digits_Value (Base_Type (E), VAXGF_Digits);
Set_Vax_Float (Base_Type (E), True);
Set_Float_Bounds (Base_Type (E));
Init_Size (E, 64);
Init_Alignment (E);
Init_Digits_Value (E, VAXGF_Digits);
Set_Scalar_Range (E, Scalar_Range (Base_Type (E)));
end Set_G_Float;
-------------------
-- Set_IEEE_Long --
-------------------
procedure Set_IEEE_Long (E : Entity_Id) is
begin
Init_Size (Base_Type (E), 64);
Init_Alignment (Base_Type (E));
Init_Digits_Value (Base_Type (E), IEEEL_Digits);
Set_Vax_Float (Base_Type (E), False);
Set_Float_Bounds (Base_Type (E));
Init_Size (E, 64);
Init_Alignment (E);
Init_Digits_Value (E, IEEEL_Digits);
Set_Scalar_Range (E, Scalar_Range (Base_Type (E)));
end Set_IEEE_Long;
--------------------
-- Set_IEEE_Short --
--------------------
procedure Set_IEEE_Short (E : Entity_Id) is
begin
Init_Size (Base_Type (E), 32);
Init_Alignment (Base_Type (E));
Init_Digits_Value (Base_Type (E), IEEES_Digits);
Set_Vax_Float (Base_Type (E), False);
Set_Float_Bounds (Base_Type (E));
Init_Size (E, 32);
Init_Alignment (E);
Init_Digits_Value (E, IEEES_Digits);
Set_Scalar_Range (E, Scalar_Range (Base_Type (E)));
end Set_IEEE_Short;
------------------------------
-- Set_Standard_Fpt_Formats --
------------------------------
procedure Set_Standard_Fpt_Formats is
begin
-- IEEE case
if Opt.Float_Format = 'I' then
Set_IEEE_Short (Standard_Float);
Set_IEEE_Long (Standard_Long_Float);
Set_IEEE_Long (Standard_Long_Long_Float);
-- Vax float case
else
Set_F_Float (Standard_Float);
if Opt.Float_Format_Long = 'D' then
Set_D_Float (Standard_Long_Float);
else
Set_G_Float (Standard_Long_Float);
end if;
-- Note: Long_Long_Float gets set only in the real VMS case,
-- because this gives better results for testing out the use
-- of VAX float on non-VMS environments with the -gnatdm switch.
if OpenVMS_On_Target then
Set_G_Float (Standard_Long_Long_Float);
end if;
end if;
end Set_Standard_Fpt_Formats;
end Sem_VFpt;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Command_Line; use Ada.Command_Line;
with Ada.Environment_Variables;
with Ada.Directories;
with GNAT.OS_Lib;
with GNAT.Directory_Operations;
with GNAT.Regpat;
with Ada; use Ada;
procedure Startx is
-- XTerminal is a terminal bast in Xorg -- meant to be used as a login
-- terminal.
use GNAT.OS_Lib;
package Env renames Ada.Environment_Variables;
package Cl renames Ada.Command_Line;
package Files renames Ada.Directories;
package Os renames GNAT.OS_Lib;
package Os_Files renames GNAT.Directory_Operations;
package Regex renames GNAT.Regpat;
-- package OS renames gnat.os_lib;
-- Env, CL, and CLenv are just abbreviations for: Environment_Variables,
-- Command_Line, and Command_Line.Environment
-- xterm -bg black -fg white +sb +sm -fn 10x20 -sl 4000 -cr yellow
-- /usr/bin/Xnest :1 -geometry 1024x768+0+0 -ac -name Windowmaker & wmaker
-- -display :1
Empty_Argument_List : constant Os.String_List (1 .. 0) := (others => null);
Empty_List_Access : Os.String_List_Access :=
new Os.String_List'(Empty_Argument_List);
function Image (Num : Natural) return String is
N : Natural := Num;
S : String (1 .. 48) := (others => ' ');
L : Natural := 0;
procedure Image_Natural
(N : in Natural;
S : in out String;
L : in out Natural) is
begin
null;
if N >= 10 then
Image_Natural (N / 10, S, L);
L := L + 1;
S (L) := Character'Val (48 + (N rem 10));
else
L := L + 1;
S (L) := Character'Val (48 + (N rem 10));
end if;
end Image_Natural;
begin
null;
Image_Natural (N, S, L);
return S (1 .. L);
end Image;
function Create_Display_Number return String is
use Ada.Directories;
New_Number : Natural := 0;
begin
if Exists ("/tmp") then
loop
if Exists ("/tmp/.X" & Image (New_Number) & "-lock") then
New_Number := New_Number + 1;
else
return Image (New_Number);
end if;
end loop;
else
return "0";
end if;
end Create_Display_Number;
-- Using GNAT.Directory_Operations, make given filesystem path compatible
-- with the current Operating System: Path ("to/file") => "to\file"(windows)
function Path (Original : String) return String is
use Os_Files;
Result : Path_Name :=
Os_Files.Format_Pathname
(Path => Path_Name (Original),
Style => System_Default);
begin
return String (Result);
end Path;
-- Using GNAT.Directory_Operations, make given filesystem path compatible
-- with the current Operating System:
-- Path ("${HOME}/to/file") => "C:\msys\home\user\to\file" (windows)
function Expand_Path (Original : String) return String is
use Os_Files;
Result : Path_Name :=
Os_Files.Format_Pathname
(Path =>
Os_Files.Expand_Path (Path => Path_Name (Original), Mode => Both),
Style => System_Default);
begin
return String (Result);
end Expand_Path;
-- Using GNAT.Directory_Operations and GNAT.OS_LIB, make given filesystem
-- path compatible with the current Operating System, returning the full
-- path: Full_Path ("../to/file") => "C:\dir\dir\to\file" (windows)
function Full_Path (Original : String) return String is
use Os;
begin
return Os.Normalize_Pathname (Path (Original));
end Full_Path;
User_Clientrc : String := Expand_Path ("${HOME}/.xinitrc");
System_Clientrc : String := Path ("/etc/X11/xinit/xinitrc");
User_Serverrc : String := Expand_Path ("${HOME}/.xserverrc");
System_Serverrc : String := Path ("/etc/X11/xinit/xserverrc");
Default_Client : String := "xterm";
Default_Server : String := Path ("/usr/bin/X");
Default_Client_Arguments_Access : Os.String_List_Access :=
Os.Argument_String_To_List ("");
Default_Server_Arguments_Access : Os.String_List_Access :=
Os.Argument_String_To_List ("");
Default_Client_Arguments : Os.String_List :=
(if
Default_Client_Arguments_Access /= null
then
Default_Client_Arguments_Access.all
else Empty_List_Access.all);
Default_Server_Arguments : Os.String_List :=
(if
Default_Server_Arguments_Access /= null
then
Default_Server_Arguments_Access.all
else Empty_List_Access.all);
-- Defaultdisplay = ":0"
-- Clientargs = ""
-- Serverargs = ""
-- Vtarg = ""
-- Enable_Xauth = 1
Env_Display : String := Env.Value ("DISPLAY", "");
New_Display : String := ":" & Create_Display_Number;
Custom_Client_Access : Os.String_Access :=
(if
Ada.Command_Line.Argument_Count > 0
then
Os.Locate_Exec_On_Path (Ada.Command_Line.Argument (1))
else null);
Manager_Command_Access : Os.String_Access :=
Os.Locate_Exec_On_Path ("/usr/bin/dbus-launch");
Xterm_Command_Access : Os.String_Access :=
Os.Locate_Exec_On_Path ("/usr/bin/xterm");
Xnest_Command_Access : Os.String_Access :=
Os.Locate_Exec_On_Path ("/usr/bin/Xnest");
Xserver_Command_Access : Os.String_Access :=
Os.Locate_Exec_On_Path ("/usr/bin/Xserver");
Xinit_Command_Access : Os.String_Access := Os.Locate_Exec_On_Path ("xinit");
Xterm_Background : String := "black";
Xterm_Foreground : String := "white";
Xterm_Scrollbar : Boolean := False;
Xterm_Session_Management_Callbacks : Boolean := False;
Xterm_Loginshell : Boolean := False;
-- Xterm_Font : String := "adobe-source code pro*";
-- Xterm_Font : String := "gnu-unifont*";
Xterm_Font : String :=
"-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1";
Xterm_Font_Size : String := "9";
Xterm_Lineshistory : String := "4000";
Xterm_Cursorcolor : String := "yellow";
Xterm_Border : String := "256";
Xterm_Geometry : String := "200x50+-128+-128";
-- Xterm_Geometry : String := "260x70+-128+-128";
Xterm_Arguments : Os.Argument_List :=
(new String'("-bg"),
new String'(Xterm_Background),
new String'("-fg"),
new String'(Xterm_Foreground),
(if Xterm_Scrollbar then new String'("-sb") else new String'("+sb")),
(if Xterm_Session_Management_Callbacks then new String'("-sm")
else new String'("+sm")),
(if Xterm_Loginshell then new String'("-ls") else new String'("+ls")),
new String'("-fs"),
new String'(Xterm_Font_Size),
new String'("-fn"),
new String'
("-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1"),
new String'("-sl"),
new String'(Xterm_Lineshistory),
new String'("-cr"),
new String'(Xterm_Cursorcolor),
new String'("-geometry"),
new String'(Xterm_Geometry),
new String'("-b"),
new String'(Xterm_Border),
new String'("-xrm"),
new String'("*overrideRedirect: True"));
Xterm_Command_Arguments : Os.Argument_List :=
(new String'("--"), Xterm_Command_Access) & Xterm_Arguments;
Xnest_Title : String := "Graphical Session";
-- Xnest_Foreground : String := "white";
-- Xnest_Background : String := "black";
Xnest_Geometry : String := "1920x1080+-0+-0";
Xnest_Border : String := "64";
Empty_Arguments : GNAT.OS_Lib.Argument_List (1 .. 0) := (others => null);
Xnest_Arguments : GNAT.OS_Lib.Argument_List :=
(new String'(New_Display),
new String'("-display"),
new String'(Env_Display),
new String'("-geometry"),
new String'(Xnest_Geometry),
new String'("-name"),
new String'(Xnest_Title),
new String'("-reset"),
new String'("-terminate"),
new String'("-fn"),
new String'
("-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1"),
new String'("-bw"),
new String'(Xnest_Border));
Xserver_Arguments : GNAT.OS_Lib.Argument_List :=
(new String'(New_Display),
new String'("-display"),
new String'(Env_Display),
new String'("-geometry"),
new String'(Xnest_Geometry),
new String'("-name"),
new String'(Xnest_Title),
new String'("-reset"),
new String'("-terminate"),
new String'("-fn"),
new String'
("-gnu-unifont-medium-r-normal-sans-16-160-75-75-c-80-iso10646-1"),
new String'("-bw"),
new String'(Xnest_Border));
Launch_Status : Boolean := True;
-- The return status of the command + arguments
function Command_Arguments return GNAT.OS_Lib.Argument_List is
Command_Words : GNAT.OS_Lib.Argument_List (1 .. Argument_Count) :=
(others => null);
Xterm_Command_Words : Os.String_List := Xterm_Command_Arguments;
begin
for N in 1 .. Argument_Count loop
Command_Words (N) := new String'(Argument (N));
end loop;
if Command_Words'Length > 0 then
return Command_Words;
else
return Xterm_Command_Words;
end if;
end Command_Arguments;
procedure Launch
(Command : String;
Arguments : GNAT.OS_Lib.Argument_List) is
Launch_Arguments : GNAT.OS_Lib.Argument_List := Arguments;
begin
GNAT.OS_Lib.Spawn (Command, Launch_Arguments, Launch_Status);
end Launch;
Launch_Error_Count : Integer := 0;
begin
Env.Clear ("SESSION_MANAGER");
Env.Set ("DISPLAY", Env_Display);
declare
Arguments : Os.Argument_List := Command_Arguments;
Xnest : Os.Process_Id;
Xserver : Os.Process_Id;
Session_Manager : Os.Process_Id;
Process_With_Exit : Os.Process_Id;
-- Arguments => checked and tweaked argument list given at progam start
-- Xnest => The instance of Xnest or Xorg that will be monitored, Session_Manager
-- Xterm : OS.Process_Id;
begin
if Env_Display /= "" then
if Xnest_Command_Access /= null
and then Manager_Command_Access /= null
then
Xnest :=
Os.Non_Blocking_Spawn
(Xnest_Command_Access.all,
Xnest_Arguments);
Env.Set ("DISPLAY", New_Display);
delay 0.02;
Session_Manager :=
Os.Non_Blocking_Spawn (Manager_Command_Access.all, Arguments);
Os.Wait_Process (Process_With_Exit, Launch_Status);
else
Launch_Status := False;
Xnest := Os.Invalid_Pid;
Session_Manager := Invalid_Pid;
end if;
else
--- Remaining startx operations go here. ---
if Xserver_Command_Access /= null
and then Manager_Command_Access /= null
then
Xserver :=
Os.Non_Blocking_Spawn
(Xserver_Command_Access.all,
Xserver_Arguments);
Env.Set ("DISPLAY", New_Display);
delay 0.02;
Session_Manager :=
Os.Non_Blocking_Spawn (Manager_Command_Access.all, Arguments);
Os.Wait_Process (Process_With_Exit, Launch_Status);
else
Launch_Status := False;
Xnest := Os.Invalid_Pid;
Session_Manager := Invalid_Pid;
end if;
end if;
if not Launch_Status then
Launch_Error_Count := Launch_Error_Count + 1;
Set_Exit_Status (Failure);
else
Launch_Error_Count := 0;
Set_Exit_Status (Success);
end if;
--Give return status back to calling os/environment.
for I in Arguments'Range loop
Free (Arguments (I));
end loop;
end;
end Startx;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2017, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- Windows Service abstraction
with League.String_Vectors;
with League.Strings;
private with System;
private with Matreshka.Internals.Windows;
package Services is
pragma Preelaborate;
type Service_Status is
(Stopped,
Start_Pending,
Stop_Pending,
Running,
Continue_Pending,
Pause_Pending,
Paused);
type Status_Listener is tagged limited private;
type Status_Listener_Access is not null access all Status_Listener;
not overriding procedure Set_Status
(Self : in out Status_Listener;
Value : Service_Status);
type Service is abstract tagged limited private;
type Service_Access is access all Service'Class;
not overriding function Name (Self : Service)
return League.Strings.Universal_String is abstract;
not overriding procedure Run
(Self : in out Service;
Args : League.String_Vectors.Universal_String_Vector;
Status : Services.Status_Listener_Access) is abstract;
type Control_Kind is
(Continue, -- Notifies a paused service that it should resume.
Interrogate, -- Notifies a service to report its current status
-- information to the service control manager.
Pause, -- Notifies a service that it should pause.
Pre_Shutdown, -- Notifies a service that the system will be shutdown.
Shutdown, -- Notifies a service that the system is shutting down
-- so the service can perform cleanup tasks.
Stop); -- Notifies a service that it should stop.
not overriding procedure Control
(Self : in out Service;
Control : Services.Control_Kind;
Status : Services.Status_Listener_Access) is abstract;
-- The control handler function is intended to receive notification and
-- return immediately.
procedure Dispatch (Service : Service_Access);
private
type HANDLE is new System.Address;
subtype DWORD is Matreshka.Internals.Windows.DWORD;
SERVICE_FILE_SYSTEM_DRIVER : constant := 16#00000002#;
-- The service is a file system driver.
SERVICE_KERNEL_DRIVER : constant := 16#00000001#;
-- The service is a device driver.
SERVICE_WIN32_OWN_PROCESS : constant := 16#00000010#;
-- The service runs in its own process.
SERVICE_WIN32_SHARE_PROCESS : constant := 16#00000020#;
-- The service shares a process with other services.
SERVICE_USER_OWN_PROCESS : constant := 16#00000050#;
-- The service runs in its own process under the logged-on user account.
SERVICE_USER_SHARE_PROCESS : constant := 16#00000060#;
-- The service shares a process with one or more other services that run
-- under the logged-on user account.
SERVICE_CONTINUE_PENDING : constant := 16#00000005#;
-- The service continue is pending.
SERVICE_PAUSE_PENDING : constant := 16#00000006#;
-- The service pause is pending.
SERVICE_PAUSED : constant := 16#00000007#;
-- The service is paused.
SERVICE_RUNNING : constant := 16#00000004#;
-- The service is running.
SERVICE_START_PENDING : constant := 16#00000002#;
-- The service is starting.
SERVICE_STOP_PENDING : constant := 16#00000003#;
-- The service is stopping.
SERVICE_STOPPED : constant := 16#00000001#;
-- The service is not running.
SERVICE_CONTROL_CONTINUE : constant := 16#00000003#;
-- Notifies a paused service that it should resume.
SERVICE_CONTROL_INTERROGATE : constant := 16#00000004#;
-- Notifies a service to report its current status information to the
-- service control manager.
SERVICE_CONTROL_PAUSE : constant := 16#00000002#;
-- Notifies a service that it should pause.
SERVICE_CONTROL_PRESHUTDOWN : constant := 16#0000000F#;
-- Notifies a service that the system will be shutting down.
SERVICE_CONTROL_SHUTDOWN : constant := 16#00000005#;
-- Notifies a service that the system is shutting down so the service can
-- perform cleanup tasks.
SERVICE_CONTROL_STOP : constant := 16#00000001#;
-- Notifies a service that it should stop.
SERVICE_ACCEPT_PAUSE_CONTINUE : constant := 16#00000002#;
-- The service can be paused and continued.
-- This control code allows the service to receive SERVICE_CONTROL_PAUSE
-- and SERVICE_CONTROL_CONTINUE notifications.
SERVICE_ACCEPT_PRESHUTDOWN : constant := 16#00000100#;
-- The service can perform preshutdown tasks.
-- This control code enables the service to receive
-- SERVICE_CONTROL_PRESHUTDOWN notifications. Note that ControlService and
-- ControlServiceEx cannot send this notification; only the system can
-- send it.
-- Windows Server 2003 and Windows XP: This value is not supported.
SERVICE_ACCEPT_SHUTDOWN : constant := 16#00000004#;
-- The service is notified when system shutdown occurs.
-- This control code allows the service to receive SERVICE_CONTROL_SHUTDOWN
-- notifications. Note that ControlService and ControlServiceEx cannot send
-- this notification; only the system can send it.
SERVICE_ACCEPT_STOP : constant := 16#00000001#;
-- The service can be stopped.
-- This control code allows the service to receive SERVICE_CONTROL_STOP
-- notifications.
NO_ERROR : constant := 0;
type C_SERVICE_STATUS is record
dwServiceType : DWORD := SERVICE_WIN32_OWN_PROCESS;
dwCurrentState : DWORD := SERVICE_STOPPED;
dwControlsAccepted : DWORD := SERVICE_ACCEPT_STOP;
dwWin32ExitCode : DWORD := NO_ERROR;
dwServiceSpecificExitCode : DWORD := NO_ERROR;
dwCheckPoint : DWORD := 0;
dwWaitHint : DWORD := 0;
end record
with Convention => C;
type Status_Listener is tagged limited record
StatusHandle : HANDLE;
Status : aliased C_SERVICE_STATUS;
end record;
type Service is abstract tagged limited record
Listener : aliased Status_Listener;
end record;
end Services;
|
with impact.d2.orbs.Collision,
impact.d2.Math;
private with impact.d2.orbs.dynamic_Tree;
package impact.d2.orbs.Broadphase
--
-- The broad-phase is used for computing pairs and performing volume queries and ray casts.
-- This broad-phase does not persist pairs. Instead, this reports potentially new pairs.
-- It is up to the client to consume the new pairs and to track subsequent overlap.
--
is
use impact.d2.Math;
type b2Pair is
record
proxyIdA,
proxyIdB,
next : int32;
end record;
type b2Pairs is array (int32 range <>) of aliased b2Pair;
e_nullProxy : constant := -1;
type b2BroadPhase is tagged private;
function to_b2BroadPhase return b2BroadPhase;
procedure destruct (Self : in out b2BroadPhase);
-- Create a proxy with an initial AABB. Pairs are not reported until
-- UpdatePairs is called.
--
function CreateProxy (Self : access b2BroadPhase; aabb : in collision.b2AABB;
userData : access Any'Class) return int32;
-- Destroy a proxy. It is up to the client to remove any pairs.
--
procedure DestroyProxy (Self : in out b2BroadPhase; proxyId : in int32);
-- Call MoveProxy as many times as you like, then when you are done
-- call UpdatePairs to finalized the proxy pairs (for your time step).
--
procedure MoveProxy (Self : in out b2BroadPhase; proxyId : in int32;
aabb : in collision.b2AABB;
displacement : in b2Vec2);
-- Get the fat AABB for a proxy.
--
function GetFatAABB (Self : in b2BroadPhase; proxyId : in int32) return collision.b2AABB;
-- Get user data from a proxy. Returns NULL if the id is invalid.
--
function GetUserData (Self : in b2BroadPhase; proxyId : in int32) return access Any'Class;
-- Test overlap of fat AABBs.
--
function TestOverlap (Self : in b2BroadPhase; proxyIdA, proxyIdB : in int32) return Boolean;
-- Get the number of proxies.
--
function GetProxyCount (Self : in b2BroadPhase) return int32;
-- Update the pairs. This results in pair callbacks. This can only add pairs.
--
generic
type callback_t is private;
with procedure addPair (the_Callback : access callback_t;
userDataA,
userDataB : access Any'Class);
procedure UpdatePairs (Self : in out b2BroadPhase; the_Callback : access callback_t);
-- template <typename T>
-- void UpdatePairs(T* callback);
-- addPair (callback, userDataA, userDataB);
-- Query an AABB for overlapping proxies. The callback class
-- is called for each proxy that overlaps the supplied AABB.
--
generic
type callback_t is private;
with function QueryCallback (the_Callback : access callback_t ;
nodeId : in int32 ) return Boolean;
procedure Query (Self : in b2BroadPhase; the_Callback : access callback_t;
aabb : in collision.b2AABB);
-- template <typename T>
-- void Query(T* callback, const b2AABB& aabb) const;
-- Ray-cast against the proxies in the tree. This relies on the callback
-- to perform a exact ray-cast in the case were the proxy contains a shape.
-- The callback also performs the any collision filtering. This has performance
-- roughly equal to k * log(n), where k is the number of collisions and n is the
-- number of proxies in the tree.
-- 'input' the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1).
-- 'callback' a callback class that is called for each proxy that is hit by the ray.
--
generic
type callback_t is private;
with function RayCastCallback (the_Callback : access callback_t;
Input : in collision.b2RayCastInput;
nodeId : in int32 ) return float32;
procedure RayCast (Self : in b2BroadPhase; the_Callback : access callback_t;
input : in collision.b2RayCastInput);
-- template <typename T>
-- void RayCast(T* callback, const b2RayCastInput& input) const;
-- Compute the height of the embedded tree.
--
function ComputeHeight (Self : in b2BroadPhase) return int32;
private
type b2Pairs_view is access all b2Pairs;
type int32_array_view is access all int32_array;
type b2BroadPhase is tagged
record
m_tree : aliased dynamic_tree.b2DynamicTree := dynamic_tree.to_b2DynamicTree;
m_proxyCount : int32;
m_moveBuffer : int32_array_view;
m_moveCapacity : int32;
m_moveCount : int32;
m_pairBuffer : b2Pairs_view;
m_pairCapacity : int32;
m_pairCount : int32;
m_queryProxyId : int32;
end record;
procedure BufferMove (Self : in out b2BroadPhase; proxyId : in int32);
procedure unBufferMove (Self : in out b2BroadPhase; proxyId : in int32);
function QueryCallback (Self : access b2BroadPhase; proxyId : in int32) return Boolean;
end impact.d2.orbs.Broadphase;
|
-- This file is generated by SWIG. Please do *not* modify by hand.
--
with Interfaces.C;
with Interfaces.C.Strings;
with osmesa_c.Pointers;
with Swig;
with Swig.Pointers;
with Interfaces.C;
package osmesa_c.Binding is
function OSMesaCreateContext
(format : in osmesa_c.GLenum;
sharelist : in osmesa_c.OSMesaContext) return osmesa_c.OSMesaContext;
function OSMesaCreateContextExt
(format : in osmesa_c.GLenum;
depthBits : in osmesa_c.GLint;
stencilBits : in osmesa_c.GLint;
accumBits : in osmesa_c.GLint;
sharelist : in osmesa_c.OSMesaContext) return osmesa_c.OSMesaContext;
procedure OSMesaDestroyContext (ctx : in osmesa_c.OSMesaContext);
function OSMesaMakeCurrent
(ctx : in osmesa_c.OSMesaContext;
buffer : in Swig.void_ptr;
the_type : in osmesa_c.GLenum;
width : in osmesa_c.GLsizei;
height : in osmesa_c.GLsizei) return osmesa_c.GLboolean;
function OSMesaGetCurrentContext return osmesa_c.OSMesaContext;
procedure OSMesaPixelStore
(pname : in osmesa_c.GLint;
value : in osmesa_c.GLint);
procedure OSMesaGetIntegerv
(pname : in osmesa_c.GLint;
value : in osmesa_c.Pointers.GLint_Pointer);
function OSMesaGetDepthBuffer
(c : in osmesa_c.OSMesaContext;
width : in osmesa_c.Pointers.GLint_Pointer;
height : in osmesa_c.Pointers.GLint_Pointer;
bytesPerValue : in osmesa_c.Pointers.GLint_Pointer;
buffer : in Swig.Pointers.void_ptr_Pointer) return osmesa_c.GLboolean;
function OSMesaGetColorBuffer
(c : in osmesa_c.OSMesaContext;
width : in osmesa_c.Pointers.GLint_Pointer;
height : in osmesa_c.Pointers.GLint_Pointer;
format : in osmesa_c.Pointers.GLint_Pointer;
buffer : in Swig.Pointers.void_ptr_Pointer) return osmesa_c.GLboolean;
function OSMesaGetProcAddress
(funcName : in Interfaces.C.Strings.chars_ptr) return osmesa_c.OSMESAproc;
procedure OSMesaColorClamp (enable : in osmesa_c.GLboolean);
procedure OSMesaPostprocess
(osmesa : in osmesa_c.OSMesaContext;
filter : in Interfaces.C.Strings.chars_ptr;
enable_value : in Interfaces.C.unsigned);
private
pragma Import (C, OSMesaCreateContext, "Ada_OSMesaCreateContext");
pragma Import (C, OSMesaCreateContextExt, "Ada_OSMesaCreateContextExt");
pragma Import (C, OSMesaDestroyContext, "Ada_OSMesaDestroyContext");
pragma Import (C, OSMesaMakeCurrent, "Ada_OSMesaMakeCurrent");
pragma Import (C, OSMesaGetCurrentContext, "Ada_OSMesaGetCurrentContext");
pragma Import (C, OSMesaPixelStore, "Ada_OSMesaPixelStore");
pragma Import (C, OSMesaGetIntegerv, "Ada_OSMesaGetIntegerv");
pragma Import (C, OSMesaGetDepthBuffer, "Ada_OSMesaGetDepthBuffer");
pragma Import (C, OSMesaGetColorBuffer, "Ada_OSMesaGetColorBuffer");
pragma Import (C, OSMesaGetProcAddress, "Ada_OSMesaGetProcAddress");
pragma Import (C, OSMesaColorClamp, "Ada_OSMesaColorClamp");
pragma Import (C, OSMesaPostprocess, "Ada_OSMesaPostprocess");
end osmesa_c.Binding;
|
with Ada.Text_IO; use Ada.Text_IO;
with Account.Default_Account; use Account.Default_Account;
With Account.Vector; use Account.Vector;
package body Cocount is
procedure Main is
DA: Account.Default_Account.Instance;
AS: Account.Vector.Account_Stack;
begin
-- Set_Name(DA, "tom");
DA.Set_Name("Tom");
Add(AS, DA);
-- Put_Line("Cocount..." & Name(DA) & " , " & AS.Length'Image);
Put_Line("Delete...");
Delete(AS, DA);
AS.Delete(0); -- OK
-- Put_Line("Cocount..." & Name(DA) & " , " & AS.Length'Image);
end Main;
end Cocount;
|
with Ada.Assertions; use Ada.Assertions;
with Device; use Device;
package body Memory.RAM is
function Create_RAM(latency : Time_Type := 1;
burst : Time_Type := 0;
word_size : Positive := 8;
word_count : Natural := 65536) return RAM_Pointer is
result : constant RAM_Pointer := new RAM_Type;
begin
result.latency := latency;
result.burst := burst;
result.word_size := word_size;
result.word_count := word_count;
return result;
end Create_RAM;
function Clone(mem : RAM_Type) return Memory_Pointer is
result : constant RAM_Pointer := new RAM_Type'(mem);
begin
return Memory_Pointer(result);
end Clone;
procedure Reset(mem : in out RAM_Type;
context : in Natural) is
begin
Reset(Memory_Type(mem), context);
mem.writes := 0;
end Reset;
procedure Read(mem : in out RAM_Type;
address : in Address_Type;
size : in Positive) is
word : constant Address_Type := Address_Type(mem.word_size);
offset : constant Natural := Natural(address mod word);
count : constant Natural := (size + mem.word_size + offset - 1) /
mem.word_size;
begin
Assert(address < Address_Type(2) ** Get_Address_Bits,
"invalid address in Memory.RAM.Read");
if mem.burst = 0 then
Advance(mem, mem.latency * Time_Type(count));
else
Advance(mem, mem.latency);
Advance(mem, mem.burst * Time_Type(count - 1));
end if;
end Read;
procedure Write(mem : in out RAM_Type;
address : in Address_Type;
size : in Positive) is
word : constant Address_Type := Address_Type(mem.word_size);
offset : constant Natural := Natural(address mod word);
count : constant Natural := (size + mem.word_size + offset - 1) /
mem.word_size;
begin
Assert(address < Address_Type(2) ** Get_Address_Bits,
"invalid address in Memory.RAM.Write");
if mem.burst = 0 then
Advance(mem, mem.latency * Time_Type(count));
else
Advance(mem, mem.latency);
Advance(mem, mem.burst * Time_Type(count - 1));
end if;
mem.writes := mem.writes + 1;
end Write;
function To_String(mem : RAM_Type) return Unbounded_String is
result : Unbounded_String;
begin
Append(result, "(ram ");
Append(result, "(latency" & Time_Type'Image(mem.latency) & ")");
if mem.burst /= 0 then
Append(result, "(burst" & Time_Type'Image(mem.burst) & ")");
end if;
Append(result, "(word_size" & Positive'Image(mem.word_size) & ")");
Append(result, "(word_count" & Natural'Image(mem.word_count) & ")");
Append(result, ")");
return result;
end To_String;
function Get_Cost(mem : RAM_Type) return Cost_Type is
begin
return 0;
end Get_Cost;
function Get_Writes(mem : RAM_Type) return Long_Integer is
begin
return mem.writes;
end Get_Writes;
function Get_Word_Size(mem : RAM_Type) return Positive is
begin
return mem.word_size;
end Get_Word_Size;
function Get_Ports(mem : RAM_Type) return Port_Vector_Type is
result : Port_Vector_Type;
port : constant Port_Type := Get_Port(mem);
begin
-- Emit a port if we aren't creating a model.
if mem.word_count = 0 then
result.Append(port);
end if;
return result;
end Get_Ports;
procedure Generate(mem : in RAM_Type;
sigs : in out Unbounded_String;
code : in out Unbounded_String) is
name : constant String := "m" & To_String(Get_ID(mem));
pname : constant String := "p" & To_String(Get_ID(mem));
words : constant Natural := mem.word_count;
word_bits : constant Natural := 8 * Get_Word_Size(mem);
latency : constant Time_Type := mem.latency;
burst : constant Time_Type := mem.burst;
begin
Declare_Signals(sigs, name, word_bits);
if words > 0 then
-- Emit a memory model.
Line(code, name & "_inst : entity work.ram");
Line(code, " generic map (");
Line(code, " ADDR_WIDTH => ADDR_WIDTH,");
Line(code, " WORD_WIDTH => " & To_String(word_bits) & ",");
Line(code, " SIZE => " & To_String(words) & ",");
Line(code, " LATENCY => " & To_String(latency) & ",");
Line(code, " BURST => " & To_String(burst));
Line(code, " )");
Line(code, " port map (");
Line(code, " clk => clk,");
Line(code, " rst => rst,");
Line(code, " addr => " & name & "_addr,");
Line(code, " din => " & name & "_din,");
Line(code, " dout => " & name & "_dout,");
Line(code, " re => " & name & "_re,");
Line(code, " we => " & name & "_we,");
Line(code, " mask => " & name & "_mask,");
Line(code, " ready => " & name & "_ready");
Line(code, " );");
else
-- No model; wire up a port.
Declare_Signals(sigs, pname, word_bits);
Line(code, pname & "_addr <= " & name & "_addr;");
Line(code, pname & "_din <= " & name & "_din;");
Line(code, name & "_dout <= " & pname & "_dout;");
Line(code, pname & "_re <= " & name & "_re;");
Line(code, pname & "_we <= " & name & "_we;");
Line(code, pname & "_mask <= " & name & "_mask;");
Line(code, name & "_ready <= " & pname & "_ready;");
end if;
end Generate;
end Memory.RAM;
|
-- 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 Orka.Transforms.Doubles.Quaternions;
package body Orka.Cameras is
function Projection_Matrix (Object : Camera_Lens) return Transforms.Matrix4 is
Width : constant GL.Types.Single := GL.Types.Single (Object.Width);
Height : constant GL.Types.Single := GL.Types.Single (Object.Height);
use type GL.Types.Single;
begin
if Object.Reversed_Z then
return Transforms.Infinite_Perspective_Reversed_Z (Object.FOV, Width / Height, 0.1);
else
return Transforms.Infinite_Perspective (Object.FOV, Width / Height, 0.1);
end if;
end Projection_Matrix;
-----------------------------------------------------------------------------
procedure Set_Input_Scale
(Object : in out Camera;
X, Y, Z : GL.Types.Double) is
begin
Object.Scale := (X, Y, Z, 0.0);
end Set_Input_Scale;
procedure Set_Up_Direction
(Object : in out Camera;
Direction : Vector4) is
begin
Object.Up := Direction;
end Set_Up_Direction;
function Lens (Object : Camera) return Camera_Lens is (Object.Lens);
procedure Set_Lens (Object : in out Camera; Lens : Camera_Lens) is
begin
Object.Lens := Lens;
end Set_Lens;
procedure Set_Position
(Object : in out First_Person_Camera;
Position : Vector4) is
begin
Object.Position := Position;
end Set_Position;
overriding
procedure Look_At
(Object : in out Third_Person_Camera;
Target : Behaviors.Behavior_Ptr) is
begin
Object.Target := Target;
end Look_At;
-----------------------------------------------------------------------------
overriding
function View_Position (Object : First_Person_Camera) return Vector4 is
(Object.Position);
overriding
function Target_Position (Object : Third_Person_Camera) return Vector4 is
(Object.Target.Position);
-----------------------------------------------------------------------------
function Create_Lens
(Width, Height : Positive;
FOV : GL.Types.Single;
Context : Contexts.Context'Class) return Camera_Lens is
begin
return
(Width => Width,
Height => Height,
FOV => FOV,
Reversed_Z => Context.Enabled (Contexts.Reversed_Z));
end Create_Lens;
function Projection_Matrix (Object : Camera) return Transforms.Matrix4 is
(Projection_Matrix (Object.Lens));
function Look_At (Target, Camera, Up_World : Vector4) return Matrix4 is
use Orka.Transforms.Doubles.Vectors;
Forward : constant Vector4
:= Normalize ((Target - Camera));
Side : constant Vector4 := Normalize (Cross (Forward, Up_World));
Up : constant Vector4 := Cross (Side, Forward);
begin
return
((Side (X), Up (X), -Forward (X), 0.0),
(Side (Y), Up (Y), -Forward (Y), 0.0),
(Side (Z), Up (Z), -Forward (Z), 0.0),
(0.0, 0.0, 0.0, 1.0));
end Look_At;
function Rotate_To_Up (Object : Camera'Class) return Matrix4 is
package Quaternions renames Orka.Transforms.Doubles.Quaternions;
use Orka.Transforms.Doubles.Matrices;
begin
return R (Vector4 (Quaternions.R (Y_Axis, Object.Up)));
end Rotate_To_Up;
protected body Change_Updater is
procedure Set (Value : Vector4) is
use Orka.Transforms.Doubles.Vectors;
begin
Change := Change + Value;
Is_Set := True;
end Set;
procedure Get (Value : in out Vector4) is
use Orka.Transforms.Doubles.Vectors;
use type Vector4;
begin
Value (X) := Change (X);
Value (Y) := Change (Y);
Value (Z) := Change (Z);
Value (W) := Change (W);
if Is_Set then
Change := (0.0, 0.0, 0.0, 0.0);
end if;
end Get;
end Change_Updater;
end Orka.Cameras;
|
package P is
type T is private; -- No components visible
procedure F (X : in out T); -- The only visible operation
N : constant T; -- A constant, which value is hidden
private
type T is record -- The implementation, visible to children only
Component : Integer;
end record;
procedure V (X : in out T); -- Operation used only by children
N : constant T := (Component => 0); -- Constant implementation
end P;
|
------------------------------------------------------------------------------
-- --
-- Copyright (c) 2014-2021 Vitalii Bondarenko <vibondare@gmail.com> --
-- --
------------------------------------------------------------------------------
-- --
-- The MIT License (MIT) --
-- --
-- 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_Conversion;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
with Gtk.Main;
with Gtk.Enums; use Gtk.Enums;
use Gtk.Enums.String_List;
with Glib; use Glib;
with Glib.Values; use Glib.Values;
with Notify; use Notify;
with Notify.Notification; use Notify.Notification;
with Demo_Action_Callbacks; use Demo_Action_Callbacks;
with GPS_Utils; use GPS_Utils;
procedure Demo_Action is
Notification : Notify_Notification;
R : Boolean;
User_Data : String_Ptr :=
new UTF8_String'("String passed to the action callback");
package My_Action is new Add_Action_User_Data (String_Ptr);
begin
Restore_GPS_Startup_Values;
Gtk.Main.Init;
-- Init libnotify.
R := Notify_Init ("Notify_Ada");
-- Create new notification.
G_New
(Notification => Notification,
Summary => "Ada binding to the libnotify.",
Body_Text => "Add an action to the notification.",
Icon_Name => "");
Notification.Set_Timeout (NOTIFY_EXPIRES_DEFAULT);
-- Add action.
Notification.Add_Action
(Action => "default",
Label => "Press Me",
Callback => Action_Callback'Access);
-- Add action with user data.
My_Action.Add_Action
(Notification => Notification,
Action => "user_data_action",
Label => "Print Message",
Callback => Action_Callback_User_Data'Access,
User_Data => User_Data);
-- Sets the category of the Notification.
Notification.Set_Category ("presence.online");
-- Connect signal "closed" handler.
Notification.On_Closed (On_Closed_Callback'Access);
-- Show Notification on the screen.
R := Notification.Show;
Gtk.Main.Main;
Notify_Uninit;
end Demo_Action;
|
-----------------------------------------------------------------------
-- GtkAda - Ada95 binding for Gtk+/Gnome --
-- --
-- Copyright (C) 2011, AdaCore --
-- --
-- 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. --
-- --
-----------------------------------------------------------------------
with Interfaces.C.Strings; use Interfaces.C.Strings;
with System; use System;
with System.Assertions; use System.Assertions;
with Ada.Exceptions;
with Ada.Text_IO;
with Ada.Unchecked_Deallocation;
with Glib; use Glib;
with Gtk.Handlers; use Gtk.Handlers;
with Gtkada.Handlers; use Gtkada.Handlers;
package body Gtkada.Builder is
use Handlers_Map;
package Builder_Callback is new Gtk.Handlers.Callback
(Gtkada_Builder_Record);
package Builder_Return_Callback is new Gtk.Handlers.Return_Callback
(Gtkada_Builder_Record, Boolean);
procedure Wrapper_Callback
(C_Builder : System.Address;
C_Object : System.Address;
C_Signal_Name : Interfaces.C.Strings.chars_ptr;
C_Handler_Name : Interfaces.C.Strings.chars_ptr;
C_Connect_Object : System.Address;
Flags : Glib.G_Connect_Flags;
User_Data : System.Address);
pragma Convention (C, Wrapper_Callback);
-- Low-level subprogram to perform signal connections.
procedure Connect
(Handler_Name : String;
Handler : Universal_Marshaller;
Base_Object : GObject;
Signal : Glib.Signal_Name;
After : Boolean;
The_Builder : Gtkada_Builder;
Slot_Object : GObject);
-- Connect object to handler
procedure Free (Builder : access Gtkada_Builder_Record'Class);
-- Called when the Builder is destroyed
procedure On_Destroy
(Data : System.Address;
Builder_Addr : System.Address);
pragma Convention (C, On_Destroy);
-------------
-- Connect --
-------------
procedure Connect
(Handler_Name : String;
Handler : Universal_Marshaller;
Base_Object : GObject;
Signal : Glib.Signal_Name;
After : Boolean;
The_Builder : Gtkada_Builder;
Slot_Object : GObject) is
begin
-- Sanity checks
case Handler.T is
when Object | Object_Return =>
if Slot_Object = null then
Raise_Assert_Failure
("Error when connecting handler """ & Handler_Name & """:"
& ASCII.LF
& " attempting to connect a callback of type """ &
Handler_Type'Image (Handler.T)
& """, but no User_Data was specified in glade-3");
end if;
when Builder | Builder_Return =>
null;
end case;
-- Do the connect
case Handler.T is
when Object =>
Object_Callback.Object_Connect
(Widget => Base_Object,
Name => Signal,
Marsh => Object_Callback.To_Marshaller
(Object_Callback.Marshallers.Void_Marshaller.Handler
(Handler.The_Object_Handler)),
Slot_Object => Slot_Object,
After => After);
when Object_Return =>
Object_Return_Callback.Object_Connect
(Widget => Base_Object,
Name => Signal,
Marsh => Object_Return_Callback.To_Marshaller
(Object_Return_Callback.Marshallers.Void_Marshaller.Handler
(Handler.The_Object_Return_Handler)),
Slot_Object => Slot_Object,
After => After);
when Builder =>
Builder_Callback.Object_Connect
(Widget => Base_Object,
Name => Signal,
Marsh => Builder_Callback.To_Marshaller
(Builder_Callback.Marshallers.Void_Marshaller.Handler
(Handler.The_Builder_Handler)),
Slot_Object => The_Builder,
After => After);
when Builder_Return =>
Builder_Return_Callback.Object_Connect
(Widget => Base_Object,
Name => Signal,
Marsh => Builder_Return_Callback.To_Marshaller
(Builder_Return_Callback.Marshallers.Void_Marshaller.Handler
(Handler.The_Builder_Return_Handler)),
Slot_Object => The_Builder,
After => After);
end case;
end Connect;
----------------------
-- Wrapper_Callback --
----------------------
procedure Wrapper_Callback
(C_Builder : System.Address;
C_Object : System.Address;
C_Signal_Name : Interfaces.C.Strings.chars_ptr;
C_Handler_Name : Interfaces.C.Strings.chars_ptr;
C_Connect_Object : System.Address;
Flags : Glib.G_Connect_Flags;
User_Data : System.Address)
is
pragma Unreferenced (User_Data);
Object : constant GObject := Convert (C_Object);
Signal_Name : constant String := Value (C_Signal_Name);
After : constant Boolean := (Flags and G_Connect_After) /= 0;
Builder : constant Gtkada_Builder :=
Gtkada_Builder (Convert (C_Builder));
The_Marshaller : Universal_Marshaller_Access;
-- The universal marshaller
Handler_Name : constant String := Value (C_Handler_Name);
C : Cursor;
begin
-- Find the marshaller corresponding to the handler name.
C := Find (Builder.Handlers, To_Unbounded_String (Handler_Name));
if C = No_Element then
Raise_Assert_Failure
("Attempting to connect a callback to a handler ("""
& Handler_Name
& ")"" for which no callback has been registered.");
end if;
The_Marshaller := Element (C);
-- Now do the actual connect
Connect (Handler_Name => Handler_Name,
Handler => The_Marshaller.all,
Base_Object => Object,
Signal => Glib.Signal_Name (Signal_Name),
After => After,
The_Builder => Builder,
Slot_Object => Convert (C_Connect_Object));
end Wrapper_Callback;
----------------------
-- Register_Handler --
----------------------
procedure Register_Handler
(Builder : access Gtkada_Builder_Record'Class;
Handler_Name : String;
Handler : Object_Handler)
is
Item : Universal_Marshaller_Access;
begin
Item := new Universal_Marshaller (Object);
Item.The_Object_Handler := Handler;
Insert
(Builder.Handlers,
Key => To_Unbounded_String (Handler_Name),
New_Item => Item);
end Register_Handler;
----------------------
-- Register_Handler --
----------------------
procedure Register_Handler
(Builder : access Gtkada_Builder_Record'Class;
Handler_Name : String;
Handler : Object_Return_Handler)
is
Item : Universal_Marshaller_Access;
begin
Item := new Universal_Marshaller (Object_Return);
Item.The_Object_Return_Handler := Handler;
Insert
(Builder.Handlers,
Key => To_Unbounded_String (Handler_Name),
New_Item => Item);
end Register_Handler;
----------------------
-- Register_Handler --
----------------------
procedure Register_Handler
(Builder : access Gtkada_Builder_Record'Class;
Handler_Name : String;
Handler : Builder_Handler)
is
Item : Universal_Marshaller_Access;
begin
Item := new Universal_Marshaller (Gtkada.Builder.Builder);
Item.The_Builder_Handler := Handler;
Insert
(Builder.Handlers,
Key => To_Unbounded_String (Handler_Name),
New_Item => Item);
end Register_Handler;
----------------------
-- Register_Handler --
----------------------
procedure Register_Handler
(Builder : access Gtkada_Builder_Record'Class;
Handler_Name : String;
Handler : Builder_Return_Handler)
is
Item : Universal_Marshaller_Access;
begin
Item := new Universal_Marshaller (Builder_Return);
Item.The_Builder_Return_Handler := Handler;
Insert
(Builder.Handlers,
Key => To_Unbounded_String (Handler_Name),
New_Item => Item);
end Register_Handler;
----------------
-- Do_Connect --
----------------
procedure Do_Connect (Builder : access Gtkada_Builder_Record'Class) is
begin
Connect_Signals_Full
(Builder,
Wrapper_Callback'Access,
User_Data => Glib.Object.Get_Object (Builder));
end Do_Connect;
----------------
-- On_Destroy --
----------------
procedure Free (Builder : access Gtkada_Builder_Record'Class) is
C : Cursor;
E : Universal_Marshaller_Access;
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(Universal_Marshaller, Universal_Marshaller_Access);
begin
-- Free memory associated to handlers
C := First (Builder.Handlers);
while Has_Element (C) loop
E := Element (C);
Unchecked_Free (E);
Next (C);
end loop;
exception
when E : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Information (E));
end Free;
-------------
-- Gtk_New --
-------------
procedure Gtk_New (Builder : out Gtkada_Builder) is
begin
Builder := new Gtkada_Builder_Record;
Gtkada.Builder.Initialize (Builder);
end Gtk_New;
----------------
-- On_Destroy --
----------------
procedure On_Destroy
(Data : System.Address;
Builder_Addr : System.Address)
is
pragma Unreferenced (Data);
Stub : Gtkada_Builder_Record;
Builder : constant Gtkada_Builder := Gtkada_Builder
(Get_User_Data (Builder_Addr, Stub));
begin
Free (Builder);
end On_Destroy;
----------------
-- Initialize --
----------------
procedure Initialize (Builder : access Gtkada_Builder_Record'Class) is
begin
Gtk.Builder.Initialize (Builder);
Weak_Ref (Builder, On_Destroy'Access);
end Initialize;
end Gtkada.Builder;
|
-- { dg-do compile }
-- { dg-options "-fdump-tree-optimized" }
procedure Array24 (N : Natural) is
S : String (1 .. N);
pragma Volatile (S);
begin
S := (others => '0');
end;
-- { dg-final { scan-tree-dump-not "builtin_unwind_resume" "optimized" } }
|
------------------------------------------------------------------------------
-- --
-- GNAT RUNTIME COMPONENTS --
-- --
-- A D A . N U M E R I C S . A U X --
-- --
-- B o d y --
-- (Machine Version for x86) --
-- --
-- $Revision$
-- --
-- Copyright (C) 1998-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. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- File a-numaux.adb <- 86numaux.adb
-- This version of Numerics.Aux is for the IEEE Double Extended floating
-- point format on x86.
with System.Machine_Code; use System.Machine_Code;
package body Ada.Numerics.Aux is
NL : constant String := ASCII.LF & ASCII.HT;
type FPU_Stack_Pointer is range 0 .. 7;
for FPU_Stack_Pointer'Size use 3;
type FPU_Status_Word is record
B : Boolean; -- FPU Busy (for 8087 compatibility only)
ES : Boolean; -- Error Summary Status
SF : Boolean; -- Stack Fault
Top : FPU_Stack_Pointer;
-- Condition Code Flags
-- C2 is set by FPREM and FPREM1 to indicate incomplete reduction.
-- In case of successfull recorction, C0, C3 and C1 are set to the
-- three least significant bits of the result (resp. Q2, Q1 and Q0).
-- C2 is used by FPTAN, FSIN, FCOS, and FSINCOS to indicate that
-- that source operand is beyond the allowable range of
-- -2.0**63 .. 2.0**63.
C3 : Boolean;
C2 : Boolean;
C1 : Boolean;
C0 : Boolean;
-- Exception Flags
PE : Boolean; -- Precision
UE : Boolean; -- Underflow
OE : Boolean; -- Overflow
ZE : Boolean; -- Zero Divide
DE : Boolean; -- Denormalized Operand
IE : Boolean; -- Invalid Operation
end record;
for FPU_Status_Word use record
B at 0 range 15 .. 15;
C3 at 0 range 14 .. 14;
Top at 0 range 11 .. 13;
C2 at 0 range 10 .. 10;
C1 at 0 range 9 .. 9;
C0 at 0 range 8 .. 8;
ES at 0 range 7 .. 7;
SF at 0 range 6 .. 6;
PE at 0 range 5 .. 5;
UE at 0 range 4 .. 4;
OE at 0 range 3 .. 3;
ZE at 0 range 2 .. 2;
DE at 0 range 1 .. 1;
IE at 0 range 0 .. 0;
end record;
for FPU_Status_Word'Size use 16;
-----------------------
-- Local subprograms --
-----------------------
function Is_Nan (X : Double) return Boolean;
-- Return True iff X is a IEEE NaN value
function Logarithmic_Pow (X, Y : Double) return Double;
-- Implementation of X**Y using Exp and Log functions (binary base)
-- to calculate the exponentiation. This is used by Pow for values
-- for values of Y in the open interval (-0.25, 0.25)
function Reduce (X : Double) return Double;
-- Implement partial reduction of X by Pi in the x86.
-- Note that for the Sin, Cos and Tan functions completely accurate
-- reduction of the argument is done for arguments in the range of
-- -2.0**63 .. 2.0**63, using a 66-bit approximation of Pi.
pragma Inline (Is_Nan);
pragma Inline (Reduce);
---------------------------------
-- Basic Elementary Functions --
---------------------------------
-- This section implements a few elementary functions that are
-- used to build the more complex ones. This ordering enables
-- better inlining.
----------
-- Atan --
----------
function Atan (X : Double) return Double is
Result : Double;
begin
Asm (Template =>
"fld1" & NL
& "fpatan",
Outputs => Double'Asm_Output ("=t", Result),
Inputs => Double'Asm_Input ("0", X));
-- The result value is NaN iff input was invalid
if not (Result = Result) then
raise Argument_Error;
end if;
return Result;
end Atan;
---------
-- Exp --
---------
function Exp (X : Double) return Double is
Result : Double;
begin
Asm (Template =>
"fldl2e " & NL
& "fmulp %%st, %%st(1)" & NL -- X * log2 (E)
& "fld %%st(0) " & NL
& "frndint " & NL -- Integer (X * Log2 (E))
& "fsubr %%st, %%st(1)" & NL -- Fraction (X * Log2 (E))
& "fxch " & NL
& "f2xm1 " & NL -- 2**(...) - 1
& "fld1 " & NL
& "faddp %%st, %%st(1)" & NL -- 2**(Fraction (X * Log2 (E)))
& "fscale " & NL -- E ** X
& "fstp %%st(1) ",
Outputs => Double'Asm_Output ("=t", Result),
Inputs => Double'Asm_Input ("0", X));
return Result;
end Exp;
------------
-- Is_Nan --
------------
function Is_Nan (X : Double) return Boolean is
begin
-- The IEEE NaN values are the only ones that do not equal themselves
return not (X = X);
end Is_Nan;
---------
-- Log --
---------
function Log (X : Double) return Double is
Result : Double;
begin
Asm (Template =>
"fldln2 " & NL
& "fxch " & NL
& "fyl2x " & NL,
Outputs => Double'Asm_Output ("=t", Result),
Inputs => Double'Asm_Input ("0", X));
return Result;
end Log;
------------
-- Reduce --
------------
function Reduce (X : Double) return Double is
Result : Double;
begin
Asm
(Template =>
-- Partial argument reduction
"fldpi " & NL
& "fadd %%st(0), %%st" & NL
& "fxch %%st(1) " & NL
& "fprem1 " & NL
& "fstp %%st(1) ",
Outputs => Double'Asm_Output ("=t", Result),
Inputs => Double'Asm_Input ("0", X));
return Result;
end Reduce;
----------
-- Sqrt --
----------
function Sqrt (X : Double) return Double is
Result : Double;
begin
if X < 0.0 then
raise Argument_Error;
end if;
Asm (Template => "fsqrt",
Outputs => Double'Asm_Output ("=t", Result),
Inputs => Double'Asm_Input ("0", X));
return Result;
end Sqrt;
---------------------------------
-- Other Elementary Functions --
---------------------------------
-- These are built using the previously implemented basic functions
----------
-- Acos --
----------
function Acos (X : Double) return Double is
Result : Double;
begin
Result := 2.0 * Atan (Sqrt ((1.0 - X) / (1.0 + X)));
-- The result value is NaN iff input was invalid
if Is_Nan (Result) then
raise Argument_Error;
end if;
return Result;
end Acos;
----------
-- Asin --
----------
function Asin (X : Double) return Double is
Result : Double;
begin
Result := Atan (X / Sqrt ((1.0 - X) * (1.0 + X)));
-- The result value is NaN iff input was invalid
if Is_Nan (Result) then
raise Argument_Error;
end if;
return Result;
end Asin;
---------
-- Cos --
---------
function Cos (X : Double) return Double is
Reduced_X : Double := X;
Result : Double;
Status : FPU_Status_Word;
begin
loop
Asm
(Template =>
"fcos " & NL
& "xorl %%eax, %%eax " & NL
& "fnstsw %%ax ",
Outputs => (Double'Asm_Output ("=t", Result),
FPU_Status_Word'Asm_Output ("=a", Status)),
Inputs => Double'Asm_Input ("0", Reduced_X));
exit when not Status.C2;
-- Original argument was not in range and the result
-- is the unmodified argument.
Reduced_X := Reduce (Result);
end loop;
return Result;
end Cos;
---------------------
-- Logarithmic_Pow --
---------------------
function Logarithmic_Pow (X, Y : Double) return Double is
Result : Double;
begin
Asm (Template => "" -- X : Y
& "fyl2x " & NL -- Y * Log2 (X)
& "fst %%st(1) " & NL -- Y * Log2 (X) : Y * Log2 (X)
& "frndint " & NL -- Int (...) : Y * Log2 (X)
& "fsubr %%st, %%st(1)" & NL -- Int (...) : Fract (...)
& "fxch " & NL -- Fract (...) : Int (...)
& "f2xm1 " & NL -- 2**Fract (...) - 1 : Int (...)
& "fld1 " & NL -- 1 : 2**Fract (...) - 1 : Int (...)
& "faddp %%st, %%st(1)" & NL -- 2**Fract (...) : Int (...)
& "fscale " & NL -- 2**(Fract (...) + Int (...))
& "fstp %%st(1) ",
Outputs => Double'Asm_Output ("=t", Result),
Inputs =>
(Double'Asm_Input ("0", X),
Double'Asm_Input ("u", Y)));
return Result;
end Logarithmic_Pow;
---------
-- Pow --
---------
function Pow (X, Y : Double) return Double is
type Mantissa_Type is mod 2**Double'Machine_Mantissa;
-- Modular type that can hold all bits of the mantissa of Double
-- For negative exponents, a division is done
-- at the end of the processing.
Negative_Y : constant Boolean := Y < 0.0;
Abs_Y : constant Double := abs Y;
-- During this function the following invariant is kept:
-- X ** (abs Y) = Base**(Exp_High + Exp_Mid + Exp_Low) * Factor
Base : Double := X;
Exp_High : Double := Double'Floor (Abs_Y);
Exp_Mid : Double;
Exp_Low : Double;
Exp_Int : Mantissa_Type;
Factor : Double := 1.0;
begin
-- Select algorithm for calculating Pow:
-- integer cases fall through
if Exp_High >= 2.0**Double'Machine_Mantissa then
-- In case of Y that is IEEE infinity, just raise constraint error
if Exp_High > Double'Safe_Last then
raise Constraint_Error;
end if;
-- Large values of Y are even integers and will stay integer
-- after division by two.
loop
-- Exp_Mid and Exp_Low are zero, so
-- X**(abs Y) = Base ** Exp_High = (Base**2) ** (Exp_High / 2)
Exp_High := Exp_High / 2.0;
Base := Base * Base;
exit when Exp_High < 2.0**Double'Machine_Mantissa;
end loop;
elsif Exp_High /= Abs_Y then
Exp_Low := Abs_Y - Exp_High;
Factor := 1.0;
if Exp_Low /= 0.0 then
-- Exp_Low now is in interval (0.0, 1.0)
-- Exp_Mid := Double'Floor (Exp_Low * 4.0) / 4.0;
Exp_Mid := 0.0;
Exp_Low := Exp_Low - Exp_Mid;
if Exp_Low >= 0.5 then
Factor := Sqrt (X);
Exp_Low := Exp_Low - 0.5; -- exact
if Exp_Low >= 0.25 then
Factor := Factor * Sqrt (Factor);
Exp_Low := Exp_Low - 0.25; -- exact
end if;
elsif Exp_Low >= 0.25 then
Factor := Sqrt (Sqrt (X));
Exp_Low := Exp_Low - 0.25; -- exact
end if;
-- Exp_Low now is in interval (0.0, 0.25)
-- This means it is safe to call Logarithmic_Pow
-- for the remaining part.
Factor := Factor * Logarithmic_Pow (X, Exp_Low);
end if;
elsif X = 0.0 then
return 0.0;
end if;
-- Exp_High is non-zero integer smaller than 2**Double'Machine_Mantissa
Exp_Int := Mantissa_Type (Exp_High);
-- Standard way for processing integer powers > 0
while Exp_Int > 1 loop
if (Exp_Int and 1) = 1 then
-- Base**Y = Base**(Exp_Int - 1) * Exp_Int for Exp_Int > 0
Factor := Factor * Base;
end if;
-- Exp_Int is even and Exp_Int > 0, so
-- Base**Y = (Base**2)**(Exp_Int / 2)
Base := Base * Base;
Exp_Int := Exp_Int / 2;
end loop;
-- Exp_Int = 1 or Exp_Int = 0
if Exp_Int = 1 then
Factor := Base * Factor;
end if;
if Negative_Y then
Factor := 1.0 / Factor;
end if;
return Factor;
end Pow;
---------
-- Sin --
---------
function Sin (X : Double) return Double is
Reduced_X : Double := X;
Result : Double;
Status : FPU_Status_Word;
begin
loop
Asm
(Template =>
"fsin " & NL
& "xorl %%eax, %%eax " & NL
& "fnstsw %%ax ",
Outputs => (Double'Asm_Output ("=t", Result),
FPU_Status_Word'Asm_Output ("=a", Status)),
Inputs => Double'Asm_Input ("0", Reduced_X));
exit when not Status.C2;
-- Original argument was not in range and the result
-- is the unmodified argument.
Reduced_X := Reduce (Result);
end loop;
return Result;
end Sin;
---------
-- Tan --
---------
function Tan (X : Double) return Double is
Reduced_X : Double := X;
Result : Double;
Status : FPU_Status_Word;
begin
loop
Asm
(Template =>
"fptan " & NL
& "xorl %%eax, %%eax " & NL
& "fnstsw %%ax " & NL
& "ffree %%st(0) " & NL
& "fincstp ",
Outputs => (Double'Asm_Output ("=t", Result),
FPU_Status_Word'Asm_Output ("=a", Status)),
Inputs => Double'Asm_Input ("0", Reduced_X));
exit when not Status.C2;
-- Original argument was not in range and the result
-- is the unmodified argument.
Reduced_X := Reduce (Result);
end loop;
return Result;
end Tan;
----------
-- Sinh --
----------
function Sinh (X : Double) return Double is
begin
-- Mathematically Sinh (x) is defined to be (Exp (X) - Exp (-X)) / 2.0
if abs X < 25.0 then
return (Exp (X) - Exp (-X)) / 2.0;
else
return Exp (X) / 2.0;
end if;
end Sinh;
----------
-- Cosh --
----------
function Cosh (X : Double) return Double is
begin
-- Mathematically Cosh (X) is defined to be (Exp (X) + Exp (-X)) / 2.0
if abs X < 22.0 then
return (Exp (X) + Exp (-X)) / 2.0;
else
return Exp (X) / 2.0;
end if;
end Cosh;
----------
-- Tanh --
----------
function Tanh (X : Double) return Double is
begin
-- Return the Hyperbolic Tangent of x
--
-- x -x
-- e - e Sinh (X)
-- Tanh (X) is defined to be ----------- = --------
-- x -x Cosh (X)
-- e + e
if abs X > 23.0 then
return Double'Copy_Sign (1.0, X);
end if;
return 1.0 / (1.0 + Exp (-2.0 * X)) - 1.0 / (1.0 + Exp (2.0 * X));
end Tanh;
end Ada.Numerics.Aux;
|
package body Compute is
procedure Printf (String : in Interfaces.C.char_array);
pragma Import (C, Printf, "printf");
procedure Compute is
begin
Printf ("beep ");
end Compute;
end Compute;
|
-- C35003A.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT CONSTRAINT_ERROR IS RAISED FOR AN INTEGER OR
-- ENUMERATION SUBTYPE INDICATION WHEN THE LOWER OR UPPER BOUND
-- OF A NON-NULL RANGE LIES OUTSIDE THE RANGE OF THE TYPE MARK.
-- HISTORY:
-- JET 01/25/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C35003A IS
TYPE ENUM IS (ZERO, ONE, TWO, THREE);
SUBTYPE SUBENUM IS ENUM RANGE ONE..TWO;
TYPE INT IS RANGE 1..10;
SUBTYPE SUBINT IS INTEGER RANGE -10..10;
TYPE A1 IS ARRAY (0..11) OF INTEGER;
TYPE A2 IS ARRAY (INTEGER RANGE -11..10) OF INTEGER;
BEGIN
TEST ("C35003A", "CHECK THAT CONSTRAINT_ERROR IS RAISED FOR AN " &
"INTEGER OR ENUMERATION SUBTYPE INDICATION " &
"WHEN THE LOWER OR UPPER BOUND OF A NON-NULL " &
"RANGE LIES OUTSIDE THE RANGE OF THE TYPE MARK");
BEGIN
DECLARE
SUBTYPE SUBSUBENUM IS SUBENUM RANGE ZERO..TWO;
BEGIN
FAILED ("NO EXCEPTION RAISED (E1)");
DECLARE
Z : SUBSUBENUM := ONE;
BEGIN
IF NOT EQUAL(SUBSUBENUM'POS(Z),SUBSUBENUM'POS(Z))
THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (E1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (E1)");
END;
BEGIN
DECLARE
TYPE A IS ARRAY (SUBENUM RANGE ONE..THREE) OF INTEGER;
BEGIN
FAILED ("NO EXCEPTION RAISED (E2)");
DECLARE
Z : A := (OTHERS => 0);
BEGIN
IF NOT EQUAL(Z(ONE),Z(ONE)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (E2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (E2)");
END;
BEGIN
DECLARE
TYPE I IS ACCESS INT RANGE INT(IDENT_INT(0))..10;
BEGIN
FAILED ("NO EXCEPTION RAISED (I1)");
DECLARE
Z : I := NEW INT'(1);
BEGIN
IF NOT EQUAL(INTEGER(Z.ALL),INTEGER(Z.ALL)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (I1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (I1)");
END;
BEGIN
DECLARE
TYPE I IS NEW INT RANGE 1..INT'SUCC(10);
BEGIN
FAILED ("NO EXCEPTION RAISED (I2)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (I2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (I2)");
END;
BEGIN
DECLARE
TYPE R IS RECORD
A : SUBINT RANGE IDENT_INT(-11)..0;
END RECORD;
BEGIN
FAILED ("NO EXCEPTION RAISED (S1)");
DECLARE
Z : R := (A => 1);
BEGIN
IF NOT EQUAL(INTEGER(Z.A),INTEGER(Z.A)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (S1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (S1)");
END;
BEGIN
DECLARE
Z : SUBINT RANGE 0..IDENT_INT(11) := 0;
BEGIN
FAILED ("NO EXCEPTION RAISED (S2)");
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (S2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (S2)");
END;
BEGIN
DECLARE
SUBTYPE I IS SUBINT RANGE A1'RANGE;
BEGIN
FAILED ("NO EXCEPTION RAISED (R1)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (R1)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (R1)");
END;
BEGIN
DECLARE
SUBTYPE I IS SUBINT RANGE A2'RANGE;
BEGIN
FAILED ("NO EXCEPTION RAISED (R2)");
DECLARE
Z : I := 1;
BEGIN
IF NOT EQUAL(INTEGER(Z),INTEGER(Z)) THEN
COMMENT ("DON'T OPTIMIZE Z");
END IF;
END;
EXCEPTION
WHEN OTHERS =>
FAILED ("EXCEPTION RAISED IN WRONG PLACE (R2)");
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED (R2)");
END;
RESULT;
END C35003A;
|
with AWS.Server;
with Gprslaves.Nameserver.Server;
with AWS.Config;
procedure GPR_Tools.Gprslaves.Nameserver.Main is
Web_Server : AWS.Server.HTTP;
Config : AWS.Config.Object;
begin
AWS.Server.Start (Web_Server => Web_Server,
Callback => Server.Request'Access,
Config => Config);
end GPR_Tools.Gprslaves.Nameserver.Main;
|
-- part of AdaYaml, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "copying.txt"
with Ada.Text_IO;
with Ada.Command_Line;
with Yaml.Source.Text_IO;
with Yaml.Source.File;
with Yaml.Dom.Loading;
with Yaml.Dom.Node;
pragma Unreferenced (Yaml.Dom.Node);
procedure Yaml.To_Dom is
use type Dom.Node_Kind;
Input : Source.Pointer;
begin
if Ada.Command_Line.Argument_Count = 0 then
Input := Source.Text_IO.As_Source (Ada.Text_IO.Standard_Input);
else
Input := Source.File.As_Source (Ada.Command_Line.Argument (1));
end if;
declare
Document : constant Dom.Document_Reference :=
Dom.Loading.From_Source (Input);
Root_Node : constant not null access Dom.Node.Instance :=
Document.Root.Value.Data;
procedure Visit_Pair (Key, Value : not null access Dom.Node.Instance) is
begin
Ada.Text_IO.Put_Line ("Key: " & Key.Kind'Img);
if Key.Kind = Dom.Scalar then
Ada.Text_IO.Put_Line (" """ & Key.Content.Value.Data.all & """");
end if;
Ada.Text_IO.Put_Line ("Value: " & Value.Kind'Img);
if Value.Kind = Dom.Scalar then
Ada.Text_IO.Put_Line (" """ & Value.Content.Value.Data.all & """");
end if;
end Visit_Pair;
begin
Ada.Text_IO.Put_Line ("Root is " & Root_Node.Kind'Img);
if Root_Node.Kind = Dom.Mapping then
Root_Node.Pairs.Iterate (Visit_Pair'Access);
end if;
end;
end Yaml.To_Dom;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with AdaBase.Interfaces.Connection;
with AdaBase.Bindings.PostgreSQL;
with AdaBase.Results;
with Ada.Containers.Ordered_Maps;
with Ada.Containers.Vectors;
with Ada.Unchecked_Deallocation;
with Ada.Exceptions;
package AdaBase.Connection.Base.PostgreSQL is
package AIC renames AdaBase.Interfaces.Connection;
package BND renames AdaBase.Bindings.PostgreSQL;
package AR renames AdaBase.Results;
package EX renames Ada.Exceptions;
type PostgreSQL_Connection is new Base_Connection and AIC.iConnection
with private;
type PostgreSQL_Connection_Access is access all PostgreSQL_Connection;
type param_unit is record
payload : AR.Textual;
binary : Boolean;
is_null : Boolean;
end record;
type parameter_block is array (Positive range <>) of param_unit;
type postexec_status is (executed, returned_data, failed);
-----------------------------------------
-- SUBROUTINES REQUIRED BY INTERFACE --
-----------------------------------------
overriding
procedure connect (conn : out PostgreSQL_Connection;
database : String;
username : String := blankstring;
password : String := blankstring;
hostname : String := blankstring;
socket : String := blankstring;
port : Posix_Port := portless);
overriding
procedure setCompressed (conn : out PostgreSQL_Connection;
compressed : Boolean);
overriding
function compressed (conn : PostgreSQL_Connection) return Boolean;
overriding
procedure setUseBuffer (conn : out PostgreSQL_Connection;
buffered : Boolean);
overriding
function useBuffer (conn : PostgreSQL_Connection) return Boolean;
overriding
procedure setMultiQuery (conn : out PostgreSQL_Connection;
multiple : Boolean);
overriding
function multiquery (conn : PostgreSQL_Connection) return Boolean;
overriding
procedure setAutoCommit (conn : out PostgreSQL_Connection; auto : Boolean);
overriding
function description (conn : PostgreSQL_Connection) return String;
overriding
function SqlState (conn : PostgreSQL_Connection) return SQL_State;
overriding
function driverMessage (conn : PostgreSQL_Connection) return String;
overriding
function driverCode (conn : PostgreSQL_Connection) return Driver_Codes;
overriding
function lastInsertID (conn : PostgreSQL_Connection) return Trax_ID;
overriding
procedure commit (conn : out PostgreSQL_Connection);
overriding
procedure rollback (conn : out PostgreSQL_Connection);
overriding
procedure disconnect (conn : out PostgreSQL_Connection);
overriding
procedure execute (conn : out PostgreSQL_Connection; sql : String);
overriding
function rows_affected_by_execution (conn : PostgreSQL_Connection)
return Affected_Rows;
overriding
procedure setTransactionIsolation (conn : out PostgreSQL_Connection;
isolation : Trax_Isolation);
overriding
procedure set_character_set (conn : out PostgreSQL_Connection;
charset : String);
overriding
function character_set (conn : out PostgreSQL_Connection) return String;
---------------------------------------------------
-- SUBROUTINES PARTICULAR TO POSTGRESQL DRIVER --
---------------------------------------------------
function SqlState (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return SQL_State;
procedure discard_pgresult (conn : PostgreSQL_Connection;
res : out BND.PGresult_Access);
function rows_in_result (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return Affected_Rows;
function rows_impacted (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return Affected_Rows;
function field_data_is_binary (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return Boolean;
function prepare_statement (conn : PostgreSQL_Connection;
stmt : aliased out BND.PGresult_Access;
name : String;
sql : String) return Boolean;
function prepare_metadata (conn : PostgreSQL_Connection;
meta : aliased out BND.PGresult_Access;
name : String) return Boolean;
function destroy_statement (conn : out PostgreSQL_Connection;
name : String) return Boolean;
function direct_stmt_exec (conn : out PostgreSQL_Connection;
stmt : aliased out BND.PGresult_Access;
sql : String) return Boolean;
function fields_count (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Natural;
function field_is_null (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return Boolean;
function field_length (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return Natural;
function field_name (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return String;
function field_type (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return field_types;
function field_table (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return String;
function field_string (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return String;
function field_binary (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural;
max_length : Natural) return String;
function field_chain (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural;
max_length : Natural) return String;
function driverMessage (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return String;
function driverCode (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Driver_Codes;
function markers_found (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Natural;
function holds_refcursor (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return Boolean;
function execute_prepared_stmt (conn : PostgreSQL_Connection;
name : String;
data : parameter_block)
return BND.PGresult_Access;
function execute_prepared_stmt (conn : PostgreSQL_Connection;
name : String) return BND.PGresult_Access;
function examine_result (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return postexec_status;
function returned_id (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Trax_ID;
function select_last_val (conn : PostgreSQL_Connection) return Trax_ID;
procedure destroy_later (conn : out PostgreSQL_Connection;
identifier : Trax_ID);
------------------
-- EXCEPTIONS --
------------------
UNSUPPORTED_BY_PGSQL : exception;
NOT_WHILE_CONNECTED : exception;
DISCONNECT_FAILED : exception;
CONNECT_FAILED : exception;
AUTOCOMMIT_FAIL : exception;
TRAXISOL_FAIL : exception;
TRAX_BEGIN_FAIL : exception;
ROLLBACK_FAIL : exception;
COMMIT_FAIL : exception;
QUERY_FAIL : exception;
CHARSET_FAIL : exception;
METADATA_FAIL : exception;
STMT_NOT_VALID : exception;
STMT_RESET_FAIL : exception;
STMT_FETCH_FAIL : exception;
STORED_PROCEDURES : exception;
private
type table_cell is record
column_1 : CT.Text;
end record;
type data_type_rec is record
data_type : field_types;
end record;
package table_map is new Ada.Containers.Ordered_Maps
(Key_Type => Positive,
Element_Type => table_cell);
package type_map is new Ada.Containers.Ordered_Maps
(Key_Type => Positive,
Element_Type => data_type_rec);
package stmt_vector is new Ada.Containers.Vectors
(Index_Type => Natural,
Element_Type => Trax_ID);
type PostgreSQL_Connection is new Base_Connection and AIC.iConnection
with record
info_description : String (1 .. 29) := "PostgreSQL 9.1+ native driver";
prop_multiquery : Boolean := False;
dummy : Boolean := False;
handle : aliased BND.PGconn_Access := null;
cmd_sql_state : SQL_State := stateless;
cmd_rows_impact : Affected_Rows := 0;
-- For last insert id support using INSERT INTO ... RETURNING
cmd_insert_return : Boolean := False;
insert_return_val : Trax_ID := 0;
-- Upon connection, dump tables and data types and store them
tables : table_map.Map;
data_types : type_map.Map;
-- Upon commit and rollback, deallocate all prep stmts in map
stmts_to_destroy : stmt_vector.Vector;
end record;
subtype octet is String (1 .. 3);
subtype hexbyte is String (1 .. 2);
function convert_octet_to_char (before : octet) return Character;
function convert_hexbyte_to_char (before : hexbyte) return Character;
function is_ipv4_or_ipv6 (teststr : String) return Boolean;
function convert_version (pgsql_version : Natural) return CT.Text;
function get_library_version return Natural;
function convert_data_type (pg_type : String; category : Character;
typelen : Integer; encoded_utf8 : Boolean)
return field_types;
function refined_byte_type (byteX : field_types; constraint : String)
return field_types;
procedure Initialize (conn : in out PostgreSQL_Connection);
procedure private_execute (conn : out PostgreSQL_Connection; sql : String);
procedure begin_transaction (conn : out PostgreSQL_Connection);
procedure cache_table_names (conn : out PostgreSQL_Connection);
procedure cache_data_types (conn : out PostgreSQL_Connection);
function piped_tables (conn : PostgreSQL_Connection) return String;
function get_server_version (conn : PostgreSQL_Connection) return Natural;
function get_server_info (conn : PostgreSQL_Connection) return CT.Text;
function within_transaction (conn : PostgreSQL_Connection) return Boolean;
function connection_attempt_succeeded (conn : PostgreSQL_Connection)
return Boolean;
function private_select (conn : PostgreSQL_Connection; sql : String)
return BND.PGresult_Access;
procedure free_binary is new Ada.Unchecked_Deallocation
(BND.IC.char_array, BND.ICS.char_array_access);
procedure establish_uniform_encoding (conn : out PostgreSQL_Connection);
procedure retrieve_uniform_encoding (conn : out PostgreSQL_Connection);
overriding
procedure finalize (conn : in out PostgreSQL_Connection);
end AdaBase.Connection.Base.PostgreSQL;
|
with avtas.lmcp.object; use avtas.lmcp.object;
with avtas.lmcp.types; use avtas.lmcp.types;
package afrl.cmasi is
end afrl.cmasi;
|
with
ada.Containers,
ada.Streams;
package lace.Text
--
-- Models a string of text characters.
--
is
pragma Pure;
type Item (Capacity : Natural) is private;
function Image (Self : in Item) return String;
Error : exception;
--------------
-- Stock Items
--
subtype Item_2 is Item (Capacity => 2);
subtype Item_4 is Item (Capacity => 4);
subtype Item_8 is Item (Capacity => 8);
subtype Item_16 is Item (Capacity => 16);
subtype Item_32 is Item (Capacity => 32);
subtype Item_64 is Item (Capacity => 64);
subtype Item_128 is Item (Capacity => 128);
subtype Item_256 is Item (Capacity => 256);
subtype Item_512 is Item (Capacity => 512);
subtype Item_1k is Item (Capacity => 1024);
subtype Item_2k is Item (Capacity => 2 * 1024);
subtype Item_4k is Item (Capacity => 4 * 1024);
subtype Item_8k is Item (Capacity => 8 * 1024);
subtype Item_16k is Item (Capacity => 16 * 1024);
subtype Item_32k is Item (Capacity => 32 * 1024);
subtype Item_64k is Item (Capacity => 64 * 1024);
subtype Item_128k is Item (Capacity => 128 * 1024);
subtype Item_256k is Item (Capacity => 256 * 1024);
subtype Item_512k is Item (Capacity => 512 * 1024);
subtype Item_1m is Item (Capacity => 1024 * 1024);
subtype Item_2m is Item (Capacity => 2 * 1024 * 1024);
subtype Item_4m is Item (Capacity => 4 * 1024 * 1024);
subtype Item_8m is Item (Capacity => 8 * 1024 * 1024);
subtype Item_16m is Item (Capacity => 16 * 1024 * 1024);
subtype Item_32m is Item (Capacity => 32 * 1024 * 1024);
subtype Item_64m is Item (Capacity => 64 * 1024 * 1024);
subtype Item_128m is Item (Capacity => 128 * 1024 * 1024);
subtype Item_256m is Item (Capacity => 256 * 1024 * 1024);
subtype Item_512m is Item (Capacity => 512 * 1024 * 1024);
---------------
-- Stock Arrays
--
type Items_2 is array (Positive range <>) of aliased Item_2;
type Items_4 is array (Positive range <>) of aliased Item_4;
type Items_8 is array (Positive range <>) of aliased Item_8;
type Items_16 is array (Positive range <>) of aliased Item_16;
type Items_32 is array (Positive range <>) of aliased Item_32;
type Items_64 is array (Positive range <>) of aliased Item_64;
type Items_128 is array (Positive range <>) of aliased Item_128;
type Items_256 is array (Positive range <>) of aliased Item_256;
type Items_512 is array (Positive range <>) of aliased Item_512;
type Items_1k is array (Positive range <>) of aliased Item_1k;
type Items_2k is array (Positive range <>) of aliased Item_2k;
type Items_4k is array (Positive range <>) of aliased Item_4k;
type Items_8k is array (Positive range <>) of aliased Item_8k;
type Items_16k is array (Positive range <>) of aliased Item_16k;
type Items_32k is array (Positive range <>) of aliased Item_32k;
type Items_64k is array (Positive range <>) of aliased Item_64k;
type Items_128k is array (Positive range <>) of aliased Item_128k;
type Items_256k is array (Positive range <>) of aliased Item_256k;
type Items_512k is array (Positive range <>) of aliased Item_512k;
type Items_1m is array (Positive range <>) of aliased Item_1m;
type Items_2m is array (Positive range <>) of aliased Item_2m;
type Items_4m is array (Positive range <>) of aliased Item_4m;
type Items_8m is array (Positive range <>) of aliased Item_8m;
type Items_16m is array (Positive range <>) of aliased Item_16m;
type Items_32m is array (Positive range <>) of aliased Item_32m;
type Items_64m is array (Positive range <>) of aliased Item_64m;
type Items_128m is array (Positive range <>) of aliased Item_128m;
type Items_256m is array (Positive range <>) of aliased Item_256m;
type Items_512m is array (Positive range <>) of aliased Item_512m;
---------------
-- Construction
--
function to_Text (From : in String;
Trim : in Boolean := False) return Item;
function to_Text (From : in String;
Capacity : in Natural;
Trim : in Boolean := False) return Item;
function "+" (From : in String) return Item;
-------------
-- Attributes
--
procedure String_is (Self : in out Item; Now : in String);
function to_String (Self : in Item) return String;
function "+" (Self : in Item) return String renames to_String;
function is_Empty (Self : in Item) return Boolean;
function Length (Self : in Item) return Natural;
function Hashed (Self : in Item) return ada.Containers.Hash_type;
overriding
function "=" (Left, Right : in Item) return Boolean;
function to_Lowercase (Self : in Item) return Item;
function mono_Spaced (Self : in Item) return Item;
private
type Item (Capacity : Natural) is
record
Length : Natural := 0;
Data : String (1 .. Capacity);
end record;
----------
-- Streams
--
function Item_input (Stream : access ada.Streams.root_Stream_type'Class) return Item;
procedure Item_output (Stream : access ada.Streams.root_Stream_type'Class; the_Item : in Item);
procedure read (Stream : access ada.Streams.root_Stream_type'Class; Self : out Item);
procedure write (Stream : access ada.Streams.root_Stream_type'Class; Self : in Item);
for Item'input use Item_input;
for Item'output use Item_output;
for Item'write use write;
for Item'read use read;
end lace.Text;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Henge is
function Read
return Integer is
C : Character;
begin
Get(C);
if C = 'h' then
return 0;
else
for I in 1..4 loop
Get(C);
end loop;
return Read + 12;
end if;
end;
X: Integer;
begin
Put("Mata in namn: ");
X := Read;
Put("Det var "); Put(X,1); Put(" stenar.");
end;
|
pragma Warnings (Off);
-- Internal GNAT unit, non-portable!
-- But SocketCAN is only available on Linux anyways...
with GNAT.Sockets.Thin;
with GNAT.Sockets.Thin_Common;
pragma Warnings (On);
package body SocketCAN is
use type C.int;
package Socket_Defs is
-- socket.h
SOCK_RAW : constant := 3;
AF_CAN : constant := 29;
PF_CAN : constant := 29;
end Socket_Defs;
package Can_Defs is
-- can.h
CAN_RAW : constant := 1;
pragma Unreferenced (CAN_RAW);
type C_Raw_Sockaddr_In is record
Family : C.unsigned_short;
Index : C.int;
Fill : C.char_array (0 .. 15);
end record
with Size => 24 * 8;
pragma No_Component_Reordering (C_Raw_Sockaddr_In);
pragma Convention (C, C_Raw_Sockaddr_In);
for C_Raw_Sockaddr_In use record
Family at 0 range 0 .. 31;
Index at 0 range 32 .. 63;
end record;
type C_Can_Data is array (0 .. 7) of Interfaces.Unsigned_8;
for C_Can_Data'Alignment use 8;
type C_Can_Frame is record
Can_Id : Interfaces.Unsigned_32;
Can_Dlc : Interfaces.Unsigned_8;
Pad : Interfaces.Unsigned_8;
Res0 : Interfaces.Unsigned_8;
Res1 : Interfaces.Unsigned_8;
Data : C_Can_Data;
end record;
pragma No_Component_Reordering (C_Can_Frame);
pragma Convention (C, C_Can_Frame);
RTR_Flag : constant := 16#40000000#;
EFF_Flag : constant := 16#80000000#;
ERR_Flag : constant := 16#20000000#;
SFF_Mask : constant := 16#000007FF#;
EFF_Mask : constant := 16#1FFFFFFF#;
ERR_Mask : constant := 16#1FFFFFFF#;
pragma Unreferenced (EFF_Flag, ERR_Flag, EFF_Mask, ERR_Mask);
end Can_Defs;
function Convert (Frame : Can_Frame) return Can_Defs.C_Can_Frame;
function Convert (Frame : Can_Frame) return Can_Defs.C_Can_Frame
is
use Interfaces;
Id : constant Unsigned_32 := Unsigned_32 (Frame.Can_Id);
begin
return (Can_Id => (if Frame.Rtr then Id or Can_Defs.RTR_Flag else Id),
Can_Dlc => Unsigned_8 (Frame.Dlc),
Pad => 0,
Res0 => 0,
Res1 => 0,
Data => Can_Defs.C_Can_Data (Frame.Data));
end Convert;
function Convert (Frame : Can_Defs.C_Can_Frame) return Can_Frame;
function Convert (Frame : Can_Defs.C_Can_Frame) return Can_Frame
is
use Interfaces;
begin
return (Can_Id => Frame_Id_Type (Frame.Can_Id and Can_Defs.SFF_Mask),
Rtr => (Frame.Can_Id and Can_Defs.RTR_Flag) /= 0,
Dlc => Dlc_Type (Frame.Can_Dlc),
Data => Frame_Data (Frame.Data));
end Convert;
procedure Send_Socket
(Socket : in Socket_Type;
Frame : in Can_Frame)
is
Msg : aliased Can_Defs.C_Can_Frame := Convert (Frame);
Mtu : constant C.int := Msg'Size / 8;
Res : constant C.int := C_Write (C.int (Socket), Msg'Address, Mtu);
begin
if Res /= Mtu then
raise SocketCAN_Error with
"Failed to write message with id" & Msg.Can_Id'Img &
": write return value " & Res'Img;
end if;
end Send_Socket;
procedure Receive_Socket_Blocking
(Socket : in Socket_Type;
Frame : out Can_Frame)
is
Msg : aliased Can_Defs.C_Can_Frame;
Mtu : constant C.int := Msg'Size / 8;
Res : C.int;
begin
Res := C_Read (C.int (Socket), Msg'Address, Mtu);
if Res = GNAT.Sockets.Thin_Common.Failure then
raise SocketCAN_Error with
"Failed to read message: read return value " & Res'Img;
elsif Res /= Mtu then
raise SocketCAN_Error with
"Received frame size" & Mtu'Img & " not supported";
end if;
Frame := Convert (Msg);
end Receive_Socket_Blocking;
Protocols : constant array (Protocol_Type) of C.int :=
(RAW => 1,
BCM => 2,
TP16 => 3,
TP20 => 4,
MCNET => 5,
ISOTP => 6,
J1939 => 7,
NPROTO => 8);
function Create_Socket (Protocol : Protocol_Type := RAW) return Socket_Type
is
use GNAT.Sockets.Thin;
Res : constant C.int := C_Socket (Domain => Socket_Defs.PF_CAN,
Typ => Socket_Defs.SOCK_RAW,
Protocol => Protocols (Protocol));
begin
if Res = GNAT.Sockets.Thin_Common.Failure then
raise SocketCAN_Error with
"Failed to create socket: socket return value " & Res'Img;
end if;
return Socket_Type (Res);
end Create_Socket;
procedure Bind_Socket
(Socket : in Socket_Type;
Name : in String := "can0")
is
use GNAT.Sockets.Thin;
Index : constant C.int := C_Name_To_Index (C.To_C (Name));
begin
if Index = 0 then
raise SocketCAN_Error with
"Failed to get interface index of " & Name & " when binding socket";
end if;
declare
Sin : aliased Can_Defs.C_Raw_Sockaddr_In :=
(Family => Socket_Defs.AF_CAN,
Index => Index,
Fill => (others => C.char'First));
Res : constant C.int :=
C_Bind (C.int (Socket), Sin'Address, Sin'Size / 8);
begin
if Res = GNAT.Sockets.Thin_Common.Failure then
raise SocketCAN_Error with "Failed to bind " & Name;
end if;
end;
end Bind_Socket;
procedure Close_Socket
(Socket : in Socket_Type)
is
use GNAT.Sockets.Thin;
Res : C.int;
begin
Res := C_Close (C.int (Socket));
if Res = GNAT.Sockets.Thin_Common.Failure then
raise SocketCAN_Error with "Failed to close: return value" & Res'Img;
end if;
end Close_Socket;
function Is_Frame_Pending
(Socket : Socket_Type)
return Boolean
is
use type C.short;
POLLIN : constant C.short := 16#0001#;
Pfd : aliased Poll_Fd :=
(Fd => C.int (Socket),
Events => POLLIN,
Revents => 0);
Res : C.int;
begin
Res := C_Poll (Fds => Pfd'Address,
N_Fds => 1,
Timeout => 0);
if Res < 0 then
raise SocketCAN_Error with
"Polling error" & Res'Img & " (revents =" & Pfd.Revents'Img & ")";
end if;
return (Pfd.Revents = POLLIN);
end Is_Frame_Pending;
end SocketCAN;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . T A S K _ I N F O --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the definitions and routines associated with the
-- implementation and use of the Task_Info pragma. It is specialized
-- appropriately for targets that make use of this pragma.
-- Note: the compiler generates direct calls to this interface, via Rtsfind.
-- Any changes to this interface may require corresponding compiler changes.
-- This unit may be used directly from an application program by providing
-- an appropriate WITH, and the interface can be expected to remain stable.
-- This is the Solaris (native) version of this module.
with System.OS_Interface;
package System.Task_Info is
pragma Preelaborate;
pragma Elaborate_Body;
-- To ensure that a body is allowed
-----------------------------------------------------
-- Binding of Tasks to LWPs and LWPs to processors --
-----------------------------------------------------
-- The Solaris implementation of the GNU Low-Level Interface (GNULLI)
-- implements each Ada task as a Solaris thread. The Solaris thread
-- library distributes threads across one or more LWPs (Light Weight
-- Process) that are members of the same process. Solaris distributes
-- processes and LWPs across the available CPUs on a given machine. The
-- pragma Task_Info provides the mechanism to control the distribution
-- of tasks to LWPs, and LWPs to processors.
-- Each thread has a number of attributes that dictate it's scheduling.
-- These attributes are:
--
-- New_LWP: whether a new LWP is created for this thread.
--
-- Bound_To_LWP: whether the thread is bound to a specific LWP
-- for its entire lifetime.
--
-- CPU: the CPU number associated to the LWP
--
-- The Task_Info pragma:
-- pragma Task_Info (EXPRESSION);
-- allows the specification on a task by task basis of a value of type
-- System.Task_Info.Task_Info_Type to be passed to a task when it is
-- created. The specification of this type, and the effect on the task
-- that is created is target dependent.
-- The Task_Info pragma appears within a task definition (compare the
-- definition and implementation of pragma Priority). If no such pragma
-- appears, then the value Task_Info_Unspecified is passed. If a pragma
-- is present, then it supplies an alternative value. If the argument of
-- the pragma is a discriminant reference, then the value can be set on
-- a task by task basis by supplying the appropriate discriminant value.
-- Note that this means that the type used for Task_Info_Type must be
-- suitable for use as a discriminant (i.e. a scalar or access type).
-----------------------
-- Thread Attributes --
-----------------------
subtype CPU_Number is System.OS_Interface.processorid_t;
CPU_UNCHANGED : constant CPU_Number := System.OS_Interface.PBIND_QUERY;
-- Do not bind the LWP to a specific processor
ANY_CPU : constant CPU_Number := System.OS_Interface.PBIND_NONE;
-- Bind the LWP to any processor
Invalid_CPU_Number : exception;
type Thread_Attributes (New_LWP : Boolean) is record
Bound_To_LWP : Boolean := True;
case New_LWP is
when False =>
null;
when True =>
CPU : CPU_Number := CPU_UNCHANGED;
end case;
end record;
Default_Thread_Attributes : constant Thread_Attributes := (False, True);
function Unbound_Thread_Attributes
return Thread_Attributes;
function Bound_Thread_Attributes
return Thread_Attributes;
function Bound_Thread_Attributes (CPU : CPU_Number)
return Thread_Attributes;
type Task_Info_Type is access all Thread_Attributes;
function New_Unbound_Thread_Attributes
return Task_Info_Type;
function New_Bound_Thread_Attributes
return Task_Info_Type;
function New_Bound_Thread_Attributes (CPU : CPU_Number)
return Task_Info_Type;
Unspecified_Task_Info : constant Task_Info_Type := null;
end System.Task_Info;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2016-2018, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF51_SVD.GPIO; use NRF51_SVD.GPIO;
package body nRF51.GPIO is
overriding
function Mode (This : GPIO_Point) return HAL.GPIO.GPIO_Mode is
CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin);
begin
case CNF.DIR is
when Input => return HAL.GPIO.Input;
when Output => return HAL.GPIO.Output;
end case;
end Mode;
--------------
-- Set_Mode --
--------------
overriding
procedure Set_Mode (This : in out GPIO_Point;
Mode : HAL.GPIO.GPIO_Config_Mode)
is
CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin);
begin
CNF.DIR := (case Mode is
when HAL.GPIO.Input => Input,
when HAL.GPIO.Output => Output);
CNF.INPUT := (case Mode is
when HAL.GPIO.Input => Connect,
when HAL.GPIO.Output => Disconnect);
end Set_Mode;
---------
-- Set --
---------
overriding
function Set
(This : GPIO_Point)
return Boolean
is
begin
return GPIO_Periph.IN_k.Arr (This.Pin) = High;
end Set;
-------------------
-- Pull_Resistor --
-------------------
overriding
function Pull_Resistor (This : GPIO_Point)
return HAL.GPIO.GPIO_Pull_Resistor
is
begin
case GPIO_Periph.PIN_CNF (This.Pin).PULL is
when Disabled => return HAL.GPIO.Floating;
when Pulldown => return HAL.GPIO.Pull_Down;
when Pullup => return HAL.GPIO.Pull_Up;
end case;
end Pull_Resistor;
-----------------------
-- Set_Pull_Resistor --
-----------------------
overriding
procedure Set_Pull_Resistor (This : in out GPIO_Point;
Pull : HAL.GPIO.GPIO_Pull_Resistor)
is
begin
GPIO_Periph.PIN_CNF (This.Pin).PULL :=
(case Pull is
when HAL.GPIO.Floating => Disabled,
when HAL.GPIO.Pull_Down => Pulldown,
when HAL.GPIO.Pull_Up => Pullup);
end Set_Pull_Resistor;
---------
-- Set --
---------
overriding procedure Set
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := High;
end Set;
-----------
-- Clear --
-----------
overriding procedure Clear
(This : in out GPIO_Point)
is
begin
GPIO_Periph.OUT_k.Arr (This.Pin) := Low;
end Clear;
------------
-- Toggle --
------------
overriding procedure Toggle
(This : in out GPIO_Point)
is
begin
if This.Set then
This.Clear;
else
This.Set;
end if;
end Toggle;
------------------
-- Configure_IO --
------------------
procedure Configure_IO
(This : GPIO_Point;
Config : GPIO_Configuration)
is
CNF : PIN_CNF_Register renames GPIO_Periph.PIN_CNF (This.Pin);
begin
CNF.DIR := (case Config.Mode is
when Mode_In => Input,
when Mode_Out => Output);
CNF.INPUT := (case Config.Input_Buffer is
when Input_Buffer_Connect => Connect,
when Input_Buffer_Disconnect => Disconnect);
CNF.PULL := (case Config.Resistors is
when No_Pull => Disabled,
when Pull_Up => Pullup,
when Pull_Down => Pulldown);
CNF.DRIVE := (case Config.Drive is
when Drive_S0S1 => S0S1,
when Drive_H0S1 => H0S1,
when Drive_S0H1 => S0H1,
when Drive_H0H1 => H0H1,
when Drive_D0S1 => D0S1,
when Drive_D0H1 => D0H1,
when Drive_S0D1 => S0D1,
when Drive_H0D1 => H0D1);
CNF.SENSE := (case Config.Sense is
when Sense_Disabled => Disabled,
when Sense_For_High_Level => High,
when Sense_For_Low_Level => Low);
end Configure_IO;
end nRF51.GPIO;
|
with ada.text_io;
use ada.text_io;
package intro is
-------------------------------
-- Name: Jon Spohn
-- David Rogina
-- Game Intro Package Specification
-------------------------------
--read in and display title page
procedure title_page(file:in file_type);
end intro;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2018 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.
package GL.Enums.Internalformat is
pragma Preelaborate;
type Parameter is
(Samples,
Internalformat_Supported,
Internalformat_Preferred,
Internalformat_Red_Size,
Internalformat_Green_Size,
Internalformat_Blue_Size,
Internalformat_Alpha_Size,
Internalformat_Depth_Size,
Internalformat_Stencil_Size,
Internalformat_Shared_Size,
Internalformat_Red_Type,
Internalformat_Green_Type,
Internalformat_Blue_Type,
Internalformat_Alpha_Type,
Internalformat_Depth_Type,
Internalformat_Stencil_Type,
Max_Width,
Max_Height,
Max_Depth,
Max_Layers,
Max_Combined_Dimensions,
Color_Components,
Depth_Components,
Stencil_Components,
Color_Renderable,
Depth_Renderable,
Stencil_Renderable,
Framebuffer_Renderable,
Framebuffer_Renderable_Layered,
Framebuffer_Blend,
Texture_Image_Format,
Texture_Image_Type,
Get_Texture_Image_Format,
Get_Texture_Image_Type,
Mipmap,
Manual_Generate_Mipmap,
Auto_Generate_Mipmap,
Color_Encoding,
sRGB_Read,
sRGB_Write,
sRGB_Decode_ARB,
Filter,
Vertex_Texture,
Tess_Control_Texture,
Tess_Evaluation_Texture,
Geometry_Texture,
Fragment_Texture,
Compute_Texture,
Texture_Shadow,
Texture_Gather,
Texture_Gather_Shadow,
Shader_Image_Load,
Shader_Image_Store,
Shader_Image_Atomic,
Image_Texel_Size,
Image_Compatibility_Class,
Image_Pixel_Format,
Image_Pixel_Type,
Simultaneous_Texture_And_Depth_Test,
Simultaneous_Texture_And_Stencil_Test,
Simultaneous_Texture_And_Depth_Write,
Simultaneous_Texture_And_Stencil_Write,
Texture_Compressed_Block_Width,
Texture_Compressed_Block_Height,
Texture_Compressed_Block_Size,
Clear_Buffer,
Texture_View,
View_Compatibility_Class,
Texture_Compressed,
Image_Format_Compatibility_Type,
Num_Sample_Counts);
private
for Parameter use
(Samples => 16#80A9#,
Internalformat_Supported => 16#826F#,
Internalformat_Preferred => 16#8270#,
Internalformat_Red_Size => 16#8271#,
Internalformat_Green_Size => 16#8272#,
Internalformat_Blue_Size => 16#8273#,
Internalformat_Alpha_Size => 16#8274#,
Internalformat_Depth_Size => 16#8275#,
Internalformat_Stencil_Size => 16#8276#,
Internalformat_Shared_Size => 16#8277#,
Internalformat_Red_Type => 16#8278#,
Internalformat_Green_Type => 16#8279#,
Internalformat_Blue_Type => 16#827A#,
Internalformat_Alpha_Type => 16#827B#,
Internalformat_Depth_Type => 16#827C#,
Internalformat_Stencil_Type => 16#827D#,
Max_Width => 16#827E#,
Max_Height => 16#827F#,
Max_Depth => 16#8280#,
Max_Layers => 16#8281#,
Max_Combined_Dimensions => 16#8282#,
Color_Components => 16#8283#,
Depth_Components => 16#8284#,
Stencil_Components => 16#8285#,
Color_Renderable => 16#8286#,
Depth_Renderable => 16#8287#,
Stencil_Renderable => 16#8288#,
Framebuffer_Renderable => 16#8289#,
Framebuffer_Renderable_Layered => 16#828A#,
Framebuffer_Blend => 16#828B#,
Texture_Image_Format => 16#828F#,
Texture_Image_Type => 16#8290#,
Get_Texture_Image_Format => 16#8291#,
Get_Texture_Image_Type => 16#8292#,
Mipmap => 16#8293#,
Manual_Generate_Mipmap => 16#8294#,
Auto_Generate_Mipmap => 16#8295#,
Color_Encoding => 16#8296#,
sRGB_Read => 16#8297#,
sRGB_Write => 16#8298#,
sRGB_Decode_ARB => 16#8299#,
Filter => 16#829A#,
Vertex_Texture => 16#829B#,
Tess_Control_Texture => 16#829C#,
Tess_Evaluation_Texture => 16#829D#,
Geometry_Texture => 16#829E#,
Fragment_Texture => 16#829F#,
Compute_Texture => 16#82A0#,
Texture_Shadow => 16#82A1#,
Texture_Gather => 16#82A2#,
Texture_Gather_Shadow => 16#82A3#,
Shader_Image_Load => 16#82A4#,
Shader_Image_Store => 16#82A5#,
Shader_Image_Atomic => 16#82A6#,
Image_Texel_Size => 16#82A7#,
Image_Compatibility_Class => 16#82A8#,
Image_Pixel_Format => 16#82A9#,
Image_Pixel_Type => 16#82AA#,
Simultaneous_Texture_And_Depth_Test => 16#82AC#,
Simultaneous_Texture_And_Stencil_Test => 16#82AD#,
Simultaneous_Texture_And_Depth_Write => 16#82AE#,
Simultaneous_Texture_And_Stencil_Write => 16#82AF#,
Texture_Compressed_Block_Width => 16#82B1#,
Texture_Compressed_Block_Height => 16#82B2#,
Texture_Compressed_Block_Size => 16#82B3#,
Clear_Buffer => 16#82B4#,
Texture_View => 16#82B5#,
View_Compatibility_Class => 16#82B6#,
Texture_Compressed => 16#86A1#,
Image_Format_Compatibility_Type => 16#90C7#,
Num_Sample_Counts => 16#9380#);
for Parameter'Size use Low_Level.Enum'Size;
end GL.Enums.Internalformat;
|
pragma Ada_95;
with System;
package ada_main is
pragma Warnings (Off);
gnat_argc : Integer;
gnat_argv : System.Address;
gnat_envp : System.Address;
pragma Import (C, gnat_argc);
pragma Import (C, gnat_argv);
pragma Import (C, gnat_envp);
gnat_exit_status : Integer;
pragma Import (C, gnat_exit_status);
GNAT_Version : constant String :=
"GNAT Version: 5.3.0" & ASCII.NUL;
pragma Export (C, GNAT_Version, "__gnat_version");
Ada_Main_Program_Name : constant String := "_ada_main" & ASCII.NUL;
pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
procedure adainit;
pragma Export (C, adainit, "adainit");
procedure adafinal;
pragma Export (C, adafinal, "adafinal");
function main
(argc : Integer;
argv : System.Address;
envp : System.Address)
return Integer;
pragma Export (C, main, "main");
type Version_32 is mod 2 ** 32;
u00001 : constant Version_32 := 16#eaeed2ac#;
pragma Export (C, u00001, "mainB");
u00002 : constant Version_32 := 16#fbff4c67#;
pragma Export (C, u00002, "system__standard_libraryB");
u00003 : constant Version_32 := 16#1ec6fd90#;
pragma Export (C, u00003, "system__standard_libraryS");
u00004 : constant Version_32 := 16#3ffc8e18#;
pragma Export (C, u00004, "adaS");
u00005 : constant Version_32 := 16#9b14b3ac#;
pragma Export (C, u00005, "ada__command_lineB");
u00006 : constant Version_32 := 16#d59e21a4#;
pragma Export (C, u00006, "ada__command_lineS");
u00007 : constant Version_32 := 16#1d274481#;
pragma Export (C, u00007, "systemS");
u00008 : constant Version_32 := 16#b19b6653#;
pragma Export (C, u00008, "system__secondary_stackB");
u00009 : constant Version_32 := 16#b6468be8#;
pragma Export (C, u00009, "system__secondary_stackS");
u00010 : constant Version_32 := 16#b01dad17#;
pragma Export (C, u00010, "system__parametersB");
u00011 : constant Version_32 := 16#630d49fe#;
pragma Export (C, u00011, "system__parametersS");
u00012 : constant Version_32 := 16#a207fefe#;
pragma Export (C, u00012, "system__soft_linksB");
u00013 : constant Version_32 := 16#467d9556#;
pragma Export (C, u00013, "system__soft_linksS");
u00014 : constant Version_32 := 16#2c143749#;
pragma Export (C, u00014, "ada__exceptionsB");
u00015 : constant Version_32 := 16#f4f0cce8#;
pragma Export (C, u00015, "ada__exceptionsS");
u00016 : constant Version_32 := 16#a46739c0#;
pragma Export (C, u00016, "ada__exceptions__last_chance_handlerB");
u00017 : constant Version_32 := 16#3aac8c92#;
pragma Export (C, u00017, "ada__exceptions__last_chance_handlerS");
u00018 : constant Version_32 := 16#393398c1#;
pragma Export (C, u00018, "system__exception_tableB");
u00019 : constant Version_32 := 16#b33e2294#;
pragma Export (C, u00019, "system__exception_tableS");
u00020 : constant Version_32 := 16#ce4af020#;
pragma Export (C, u00020, "system__exceptionsB");
u00021 : constant Version_32 := 16#75442977#;
pragma Export (C, u00021, "system__exceptionsS");
u00022 : constant Version_32 := 16#37d758f1#;
pragma Export (C, u00022, "system__exceptions__machineS");
u00023 : constant Version_32 := 16#b895431d#;
pragma Export (C, u00023, "system__exceptions_debugB");
u00024 : constant Version_32 := 16#aec55d3f#;
pragma Export (C, u00024, "system__exceptions_debugS");
u00025 : constant Version_32 := 16#570325c8#;
pragma Export (C, u00025, "system__img_intB");
u00026 : constant Version_32 := 16#1ffca443#;
pragma Export (C, u00026, "system__img_intS");
u00027 : constant Version_32 := 16#39a03df9#;
pragma Export (C, u00027, "system__storage_elementsB");
u00028 : constant Version_32 := 16#30e40e85#;
pragma Export (C, u00028, "system__storage_elementsS");
u00029 : constant Version_32 := 16#b98c3e16#;
pragma Export (C, u00029, "system__tracebackB");
u00030 : constant Version_32 := 16#831a9d5a#;
pragma Export (C, u00030, "system__tracebackS");
u00031 : constant Version_32 := 16#9ed49525#;
pragma Export (C, u00031, "system__traceback_entriesB");
u00032 : constant Version_32 := 16#1d7cb2f1#;
pragma Export (C, u00032, "system__traceback_entriesS");
u00033 : constant Version_32 := 16#8c33a517#;
pragma Export (C, u00033, "system__wch_conB");
u00034 : constant Version_32 := 16#065a6653#;
pragma Export (C, u00034, "system__wch_conS");
u00035 : constant Version_32 := 16#9721e840#;
pragma Export (C, u00035, "system__wch_stwB");
u00036 : constant Version_32 := 16#2b4b4a52#;
pragma Export (C, u00036, "system__wch_stwS");
u00037 : constant Version_32 := 16#92b797cb#;
pragma Export (C, u00037, "system__wch_cnvB");
u00038 : constant Version_32 := 16#09eddca0#;
pragma Export (C, u00038, "system__wch_cnvS");
u00039 : constant Version_32 := 16#6033a23f#;
pragma Export (C, u00039, "interfacesS");
u00040 : constant Version_32 := 16#ece6fdb6#;
pragma Export (C, u00040, "system__wch_jisB");
u00041 : constant Version_32 := 16#899dc581#;
pragma Export (C, u00041, "system__wch_jisS");
u00042 : constant Version_32 := 16#41837d1e#;
pragma Export (C, u00042, "system__stack_checkingB");
u00043 : constant Version_32 := 16#93982f69#;
pragma Export (C, u00043, "system__stack_checkingS");
u00044 : constant Version_32 := 16#12c8cd7d#;
pragma Export (C, u00044, "ada__tagsB");
u00045 : constant Version_32 := 16#ce72c228#;
pragma Export (C, u00045, "ada__tagsS");
u00046 : constant Version_32 := 16#c3335bfd#;
pragma Export (C, u00046, "system__htableB");
u00047 : constant Version_32 := 16#99e5f76b#;
pragma Export (C, u00047, "system__htableS");
u00048 : constant Version_32 := 16#089f5cd0#;
pragma Export (C, u00048, "system__string_hashB");
u00049 : constant Version_32 := 16#3bbb9c15#;
pragma Export (C, u00049, "system__string_hashS");
u00050 : constant Version_32 := 16#807fe041#;
pragma Export (C, u00050, "system__unsigned_typesS");
u00051 : constant Version_32 := 16#06052bd0#;
pragma Export (C, u00051, "system__val_lluB");
u00052 : constant Version_32 := 16#fa8db733#;
pragma Export (C, u00052, "system__val_lluS");
u00053 : constant Version_32 := 16#27b600b2#;
pragma Export (C, u00053, "system__val_utilB");
u00054 : constant Version_32 := 16#b187f27f#;
pragma Export (C, u00054, "system__val_utilS");
u00055 : constant Version_32 := 16#d1060688#;
pragma Export (C, u00055, "system__case_utilB");
u00056 : constant Version_32 := 16#392e2d56#;
pragma Export (C, u00056, "system__case_utilS");
u00057 : constant Version_32 := 16#28f088c2#;
pragma Export (C, u00057, "ada__text_ioB");
u00058 : constant Version_32 := 16#f372c8ac#;
pragma Export (C, u00058, "ada__text_ioS");
u00059 : constant Version_32 := 16#10558b11#;
pragma Export (C, u00059, "ada__streamsB");
u00060 : constant Version_32 := 16#2e6701ab#;
pragma Export (C, u00060, "ada__streamsS");
u00061 : constant Version_32 := 16#db5c917c#;
pragma Export (C, u00061, "ada__io_exceptionsS");
u00062 : constant Version_32 := 16#84a27f0d#;
pragma Export (C, u00062, "interfaces__c_streamsB");
u00063 : constant Version_32 := 16#8bb5f2c0#;
pragma Export (C, u00063, "interfaces__c_streamsS");
u00064 : constant Version_32 := 16#6db6928f#;
pragma Export (C, u00064, "system__crtlS");
u00065 : constant Version_32 := 16#431faf3c#;
pragma Export (C, u00065, "system__file_ioB");
u00066 : constant Version_32 := 16#ba56a5e4#;
pragma Export (C, u00066, "system__file_ioS");
u00067 : constant Version_32 := 16#b7ab275c#;
pragma Export (C, u00067, "ada__finalizationB");
u00068 : constant Version_32 := 16#19f764ca#;
pragma Export (C, u00068, "ada__finalizationS");
u00069 : constant Version_32 := 16#95817ed8#;
pragma Export (C, u00069, "system__finalization_rootB");
u00070 : constant Version_32 := 16#52d53711#;
pragma Export (C, u00070, "system__finalization_rootS");
u00071 : constant Version_32 := 16#769e25e6#;
pragma Export (C, u00071, "interfaces__cB");
u00072 : constant Version_32 := 16#4a38bedb#;
pragma Export (C, u00072, "interfaces__cS");
u00073 : constant Version_32 := 16#07e6ee66#;
pragma Export (C, u00073, "system__os_libB");
u00074 : constant Version_32 := 16#d7b69782#;
pragma Export (C, u00074, "system__os_libS");
u00075 : constant Version_32 := 16#1a817b8e#;
pragma Export (C, u00075, "system__stringsB");
u00076 : constant Version_32 := 16#639855e7#;
pragma Export (C, u00076, "system__stringsS");
u00077 : constant Version_32 := 16#e0b8de29#;
pragma Export (C, u00077, "system__file_control_blockS");
u00078 : constant Version_32 := 16#0758d1fc#;
pragma Export (C, u00078, "courbesS");
u00079 : constant Version_32 := 16#d8cedace#;
pragma Export (C, u00079, "mathB");
u00080 : constant Version_32 := 16#70dc6f09#;
pragma Export (C, u00080, "mathS");
u00081 : constant Version_32 := 16#5e7381e4#;
pragma Export (C, u00081, "vecteursB");
u00082 : constant Version_32 := 16#adaf9663#;
pragma Export (C, u00082, "vecteursS");
u00083 : constant Version_32 := 16#608e2cd1#;
pragma Export (C, u00083, "system__concat_5B");
u00084 : constant Version_32 := 16#9a7907af#;
pragma Export (C, u00084, "system__concat_5S");
u00085 : constant Version_32 := 16#932a4690#;
pragma Export (C, u00085, "system__concat_4B");
u00086 : constant Version_32 := 16#63436fa1#;
pragma Export (C, u00086, "system__concat_4S");
u00087 : constant Version_32 := 16#2b70b149#;
pragma Export (C, u00087, "system__concat_3B");
u00088 : constant Version_32 := 16#16571824#;
pragma Export (C, u00088, "system__concat_3S");
u00089 : constant Version_32 := 16#fd83e873#;
pragma Export (C, u00089, "system__concat_2B");
u00090 : constant Version_32 := 16#1f879351#;
pragma Export (C, u00090, "system__concat_2S");
u00091 : constant Version_32 := 16#46899fd1#;
pragma Export (C, u00091, "system__concat_7B");
u00092 : constant Version_32 := 16#e1e01f9e#;
pragma Export (C, u00092, "system__concat_7S");
u00093 : constant Version_32 := 16#a83b7c85#;
pragma Export (C, u00093, "system__concat_6B");
u00094 : constant Version_32 := 16#cfe06933#;
pragma Export (C, u00094, "system__concat_6S");
u00095 : constant Version_32 := 16#f0df9003#;
pragma Export (C, u00095, "system__img_realB");
u00096 : constant Version_32 := 16#da8f1563#;
pragma Export (C, u00096, "system__img_realS");
u00097 : constant Version_32 := 16#19b0ff72#;
pragma Export (C, u00097, "system__fat_llfS");
u00098 : constant Version_32 := 16#1b28662b#;
pragma Export (C, u00098, "system__float_controlB");
u00099 : constant Version_32 := 16#fddb07bd#;
pragma Export (C, u00099, "system__float_controlS");
u00100 : constant Version_32 := 16#f1f88835#;
pragma Export (C, u00100, "system__img_lluB");
u00101 : constant Version_32 := 16#c9b6e082#;
pragma Export (C, u00101, "system__img_lluS");
u00102 : constant Version_32 := 16#eef535cd#;
pragma Export (C, u00102, "system__img_unsB");
u00103 : constant Version_32 := 16#1f8bdcb6#;
pragma Export (C, u00103, "system__img_unsS");
u00104 : constant Version_32 := 16#4d5722f6#;
pragma Export (C, u00104, "system__powten_tableS");
u00105 : constant Version_32 := 16#08ec0c09#;
pragma Export (C, u00105, "liste_generiqueB");
u00106 : constant Version_32 := 16#97c69cab#;
pragma Export (C, u00106, "liste_generiqueS");
u00107 : constant Version_32 := 16#ab2d7ed8#;
pragma Export (C, u00107, "courbes__droitesB");
u00108 : constant Version_32 := 16#cf757770#;
pragma Export (C, u00108, "courbes__droitesS");
u00109 : constant Version_32 := 16#6d4d969a#;
pragma Export (C, u00109, "system__storage_poolsB");
u00110 : constant Version_32 := 16#e87cc305#;
pragma Export (C, u00110, "system__storage_poolsS");
u00111 : constant Version_32 := 16#d8628a63#;
pragma Export (C, u00111, "normalisationB");
u00112 : constant Version_32 := 16#7121c556#;
pragma Export (C, u00112, "normalisationS");
u00113 : constant Version_32 := 16#7aa6c482#;
pragma Export (C, u00113, "parser_svgB");
u00114 : constant Version_32 := 16#b3ea5ce2#;
pragma Export (C, u00114, "parser_svgS");
u00115 : constant Version_32 := 16#12c24a43#;
pragma Export (C, u00115, "ada__charactersS");
u00116 : constant Version_32 := 16#8f637df8#;
pragma Export (C, u00116, "ada__characters__handlingB");
u00117 : constant Version_32 := 16#3b3f6154#;
pragma Export (C, u00117, "ada__characters__handlingS");
u00118 : constant Version_32 := 16#4b7bb96a#;
pragma Export (C, u00118, "ada__characters__latin_1S");
u00119 : constant Version_32 := 16#af50e98f#;
pragma Export (C, u00119, "ada__stringsS");
u00120 : constant Version_32 := 16#e2ea8656#;
pragma Export (C, u00120, "ada__strings__mapsB");
u00121 : constant Version_32 := 16#1e526bec#;
pragma Export (C, u00121, "ada__strings__mapsS");
u00122 : constant Version_32 := 16#a87ab9e2#;
pragma Export (C, u00122, "system__bit_opsB");
u00123 : constant Version_32 := 16#0765e3a3#;
pragma Export (C, u00123, "system__bit_opsS");
u00124 : constant Version_32 := 16#92f05f13#;
pragma Export (C, u00124, "ada__strings__maps__constantsS");
u00125 : constant Version_32 := 16#e18a47a0#;
pragma Export (C, u00125, "ada__float_text_ioB");
u00126 : constant Version_32 := 16#e61b3c6c#;
pragma Export (C, u00126, "ada__float_text_ioS");
u00127 : constant Version_32 := 16#d5f9759f#;
pragma Export (C, u00127, "ada__text_io__float_auxB");
u00128 : constant Version_32 := 16#f854caf5#;
pragma Export (C, u00128, "ada__text_io__float_auxS");
u00129 : constant Version_32 := 16#181dc502#;
pragma Export (C, u00129, "ada__text_io__generic_auxB");
u00130 : constant Version_32 := 16#a6c327d3#;
pragma Export (C, u00130, "ada__text_io__generic_auxS");
u00131 : constant Version_32 := 16#faa9a7b2#;
pragma Export (C, u00131, "system__val_realB");
u00132 : constant Version_32 := 16#e30e3390#;
pragma Export (C, u00132, "system__val_realS");
u00133 : constant Version_32 := 16#0be1b996#;
pragma Export (C, u00133, "system__exn_llfB");
u00134 : constant Version_32 := 16#9ca35a6e#;
pragma Export (C, u00134, "system__exn_llfS");
u00135 : constant Version_32 := 16#45525895#;
pragma Export (C, u00135, "system__fat_fltS");
u00136 : constant Version_32 := 16#e5480ede#;
pragma Export (C, u00136, "ada__strings__fixedB");
u00137 : constant Version_32 := 16#a86b22b3#;
pragma Export (C, u00137, "ada__strings__fixedS");
u00138 : constant Version_32 := 16#3bc8a117#;
pragma Export (C, u00138, "ada__strings__searchB");
u00139 : constant Version_32 := 16#c1ab8667#;
pragma Export (C, u00139, "ada__strings__searchS");
u00140 : constant Version_32 := 16#f78329ae#;
pragma Export (C, u00140, "ada__strings__unboundedB");
u00141 : constant Version_32 := 16#e303cf90#;
pragma Export (C, u00141, "ada__strings__unboundedS");
u00142 : constant Version_32 := 16#5b9edcc4#;
pragma Export (C, u00142, "system__compare_array_unsigned_8B");
u00143 : constant Version_32 := 16#b424350c#;
pragma Export (C, u00143, "system__compare_array_unsigned_8S");
u00144 : constant Version_32 := 16#5f72f755#;
pragma Export (C, u00144, "system__address_operationsB");
u00145 : constant Version_32 := 16#0e2bfab2#;
pragma Export (C, u00145, "system__address_operationsS");
u00146 : constant Version_32 := 16#6a859064#;
pragma Export (C, u00146, "system__storage_pools__subpoolsB");
u00147 : constant Version_32 := 16#e3b008dc#;
pragma Export (C, u00147, "system__storage_pools__subpoolsS");
u00148 : constant Version_32 := 16#57a37a42#;
pragma Export (C, u00148, "system__address_imageB");
u00149 : constant Version_32 := 16#bccbd9bb#;
pragma Export (C, u00149, "system__address_imageS");
u00150 : constant Version_32 := 16#b5b2aca1#;
pragma Export (C, u00150, "system__finalization_mastersB");
u00151 : constant Version_32 := 16#69316dc1#;
pragma Export (C, u00151, "system__finalization_mastersS");
u00152 : constant Version_32 := 16#7268f812#;
pragma Export (C, u00152, "system__img_boolB");
u00153 : constant Version_32 := 16#e8fe356a#;
pragma Export (C, u00153, "system__img_boolS");
u00154 : constant Version_32 := 16#d7aac20c#;
pragma Export (C, u00154, "system__ioB");
u00155 : constant Version_32 := 16#8365b3ce#;
pragma Export (C, u00155, "system__ioS");
u00156 : constant Version_32 := 16#63f11652#;
pragma Export (C, u00156, "system__storage_pools__subpools__finalizationB");
u00157 : constant Version_32 := 16#fe2f4b3a#;
pragma Export (C, u00157, "system__storage_pools__subpools__finalizationS");
u00158 : constant Version_32 := 16#afc64758#;
pragma Export (C, u00158, "system__atomic_countersB");
u00159 : constant Version_32 := 16#d05bd04b#;
pragma Export (C, u00159, "system__atomic_countersS");
u00160 : constant Version_32 := 16#f4e1c091#;
pragma Export (C, u00160, "system__stream_attributesB");
u00161 : constant Version_32 := 16#221dd20d#;
pragma Export (C, u00161, "system__stream_attributesS");
u00162 : constant Version_32 := 16#f08789ae#;
pragma Export (C, u00162, "ada__text_io__enumeration_auxB");
u00163 : constant Version_32 := 16#52f1e0af#;
pragma Export (C, u00163, "ada__text_io__enumeration_auxS");
u00164 : constant Version_32 := 16#d0432c8d#;
pragma Export (C, u00164, "system__img_enum_newB");
u00165 : constant Version_32 := 16#7c6b4241#;
pragma Export (C, u00165, "system__img_enum_newS");
u00166 : constant Version_32 := 16#4b37b589#;
pragma Export (C, u00166, "system__val_enumB");
u00167 : constant Version_32 := 16#a63d0614#;
pragma Export (C, u00167, "system__val_enumS");
u00168 : constant Version_32 := 16#2261c2e2#;
pragma Export (C, u00168, "stlB");
u00169 : constant Version_32 := 16#96280b15#;
pragma Export (C, u00169, "stlS");
u00170 : constant Version_32 := 16#84ad4a42#;
pragma Export (C, u00170, "ada__numericsS");
u00171 : constant Version_32 := 16#03e83d1c#;
pragma Export (C, u00171, "ada__numerics__elementary_functionsB");
u00172 : constant Version_32 := 16#00443200#;
pragma Export (C, u00172, "ada__numerics__elementary_functionsS");
u00173 : constant Version_32 := 16#3e0cf54d#;
pragma Export (C, u00173, "ada__numerics__auxB");
u00174 : constant Version_32 := 16#9f6e24ed#;
pragma Export (C, u00174, "ada__numerics__auxS");
u00175 : constant Version_32 := 16#129c3f4f#;
pragma Export (C, u00175, "system__machine_codeS");
u00176 : constant Version_32 := 16#9d39c675#;
pragma Export (C, u00176, "system__memoryB");
u00177 : constant Version_32 := 16#445a22b5#;
pragma Export (C, u00177, "system__memoryS");
-- BEGIN ELABORATION ORDER
-- ada%s
-- ada.characters%s
-- ada.characters.handling%s
-- ada.characters.latin_1%s
-- ada.command_line%s
-- interfaces%s
-- system%s
-- system.address_operations%s
-- system.address_operations%b
-- system.atomic_counters%s
-- system.atomic_counters%b
-- system.case_util%s
-- system.case_util%b
-- system.exn_llf%s
-- system.exn_llf%b
-- system.float_control%s
-- system.float_control%b
-- system.htable%s
-- system.img_bool%s
-- system.img_bool%b
-- system.img_enum_new%s
-- system.img_enum_new%b
-- system.img_int%s
-- system.img_int%b
-- system.img_real%s
-- system.io%s
-- system.io%b
-- system.machine_code%s
-- system.parameters%s
-- system.parameters%b
-- system.crtl%s
-- interfaces.c_streams%s
-- interfaces.c_streams%b
-- system.powten_table%s
-- system.standard_library%s
-- system.exceptions_debug%s
-- system.exceptions_debug%b
-- system.storage_elements%s
-- system.storage_elements%b
-- system.stack_checking%s
-- system.stack_checking%b
-- system.string_hash%s
-- system.string_hash%b
-- system.htable%b
-- system.strings%s
-- system.strings%b
-- system.os_lib%s
-- system.traceback_entries%s
-- system.traceback_entries%b
-- ada.exceptions%s
-- system.soft_links%s
-- system.unsigned_types%s
-- system.fat_flt%s
-- system.fat_llf%s
-- system.img_llu%s
-- system.img_llu%b
-- system.img_uns%s
-- system.img_uns%b
-- system.img_real%b
-- system.val_enum%s
-- system.val_llu%s
-- system.val_real%s
-- system.val_util%s
-- system.val_util%b
-- system.val_real%b
-- system.val_llu%b
-- system.val_enum%b
-- system.wch_con%s
-- system.wch_con%b
-- system.wch_cnv%s
-- system.wch_jis%s
-- system.wch_jis%b
-- system.wch_cnv%b
-- system.wch_stw%s
-- system.wch_stw%b
-- ada.exceptions.last_chance_handler%s
-- ada.exceptions.last_chance_handler%b
-- system.address_image%s
-- system.bit_ops%s
-- system.bit_ops%b
-- system.compare_array_unsigned_8%s
-- system.compare_array_unsigned_8%b
-- system.concat_2%s
-- system.concat_2%b
-- system.concat_3%s
-- system.concat_3%b
-- system.concat_4%s
-- system.concat_4%b
-- system.concat_5%s
-- system.concat_5%b
-- system.concat_6%s
-- system.concat_6%b
-- system.concat_7%s
-- system.concat_7%b
-- system.exception_table%s
-- system.exception_table%b
-- ada.io_exceptions%s
-- ada.numerics%s
-- ada.numerics.aux%s
-- ada.numerics.aux%b
-- ada.numerics.elementary_functions%s
-- ada.numerics.elementary_functions%b
-- ada.strings%s
-- ada.strings.maps%s
-- ada.strings.fixed%s
-- ada.strings.maps.constants%s
-- ada.strings.search%s
-- ada.strings.search%b
-- ada.tags%s
-- ada.streams%s
-- ada.streams%b
-- interfaces.c%s
-- system.exceptions%s
-- system.exceptions%b
-- system.exceptions.machine%s
-- system.file_control_block%s
-- system.file_io%s
-- system.finalization_root%s
-- system.finalization_root%b
-- ada.finalization%s
-- ada.finalization%b
-- system.storage_pools%s
-- system.storage_pools%b
-- system.finalization_masters%s
-- system.storage_pools.subpools%s
-- system.storage_pools.subpools.finalization%s
-- system.storage_pools.subpools.finalization%b
-- system.stream_attributes%s
-- system.stream_attributes%b
-- system.memory%s
-- system.memory%b
-- system.standard_library%b
-- system.secondary_stack%s
-- system.storage_pools.subpools%b
-- system.finalization_masters%b
-- system.file_io%b
-- interfaces.c%b
-- ada.tags%b
-- ada.strings.fixed%b
-- ada.strings.maps%b
-- system.soft_links%b
-- system.os_lib%b
-- ada.command_line%b
-- ada.characters.handling%b
-- system.secondary_stack%b
-- system.address_image%b
-- ada.strings.unbounded%s
-- ada.strings.unbounded%b
-- system.traceback%s
-- ada.exceptions%b
-- system.traceback%b
-- ada.text_io%s
-- ada.text_io%b
-- ada.text_io.enumeration_aux%s
-- ada.text_io.float_aux%s
-- ada.float_text_io%s
-- ada.float_text_io%b
-- ada.text_io.generic_aux%s
-- ada.text_io.generic_aux%b
-- ada.text_io.float_aux%b
-- ada.text_io.enumeration_aux%b
-- liste_generique%s
-- liste_generique%b
-- vecteurs%s
-- vecteurs%b
-- math%s
-- math%b
-- courbes%s
-- courbes.droites%s
-- courbes.droites%b
-- normalisation%s
-- normalisation%b
-- parser_svg%s
-- parser_svg%b
-- stl%s
-- stl%b
-- main%b
-- END ELABORATION ORDER
end ada_main;
|
#/bin/sh
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# script to change the system id in an object file from PA-RISC 2.0 to 1.1
adb -w $1 << EOF
?m 0 -1 0
0x0?X
0x0?W (@0x0&~0x40000)|(~@0x0&0x40000)
0?"change checksum"
0x7c?X
0x7c?W (@0x7c&~0x40000)|(~@0x7c&0x40000)
$q
EOF
exit 0
|
-- C48009D.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- FOR ALLOCATORS OF THE FORM "NEW T'(X)", CHECK THAT CONSTRAINT_ERROR
-- IS RAISED IF T IS AN UNCONSTRAINED ARRAY TYPE WITH INDEX SUBTYPE(S)
-- S,
-- 1) X HAS TOO MANY VALUES FOR S;
-- 2) A NAMED NON-NULL BOUND OF X LIES OUTSIDE S'S RANGE;
-- 3) THE BOUND'S OF X ARE NOT EQUAL TO BOUNDS SPECIFIED FOR THE
-- ALLOCATOR'S DESIGNATED BASE TYPE. (THEY ARE EQUAL TO THE BOUNDS
-- SPECIFIED FOR T).
-- RM 01/08/80
-- NL 10/13/81
-- SPS 10/26/82
-- JBG 03/03/83
-- EG 07/05/84
-- PWN 11/30/94 REMOVED TEST ILLEGAL IN ADA 9X.
-- KAS 11/14/95 FOR SLIDING ASSIGNMENT, CHANGED FAIL TO COMMENT ON LANGUAGE
-- KAS 12/02/95 INCLUDED SECOND CASE
-- PWN 05/03/96 Enforced Ada 95 sliding rules
WITH REPORT;
PROCEDURE C48009D IS
USE REPORT ;
BEGIN
TEST("C48009D","FOR ALLOCATORS OF THE FORM 'NEW T'(X)', CHECK " &
"THAT CONSTRAINT_ERROR IS RAISED WHEN " &
"APPROPRIATE - UNCONSTRAINED ARRAY TYPES");
DECLARE
SUBTYPE TWO IS INTEGER RANGE 1 .. 2;
SUBTYPE TWON IS INTEGER RANGE IDENT_INT(1) .. IDENT_INT(2);
TYPE UA IS ARRAY(INTEGER RANGE <>) OF INTEGER;
TYPE TD IS ARRAY(TWO RANGE <>) OF INTEGER RANGE 1 .. 7;
TYPE TDN IS ARRAY(TWON RANGE <>) OF INTEGER RANGE 1 .. 7;
TYPE ATD IS ACCESS TD;
TYPE ATDN IS ACCESS TDN;
TYPE A_UA IS ACCESS UA;
TYPE A_CA IS ACCESS UA(3 .. 4);
TYPE A_CAN IS ACCESS UA(4 .. 3);
VD : ATD;
VDN : ATDN;
V_A_CA : A_CA;
V_A_CAN : A_CAN;
BEGIN
BEGIN
VD := NEW TD'(3, 4, 5);
FAILED ("NO EXCEPTION RAISED - CASE 1A");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 1A");
END;
BEGIN
VDN := NEW TDN'(3, 4, 5);
FAILED ("NO EXCEPTION RAISED - CASE 1B");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 1B");
END;
BEGIN
VD := NEW TD'(IDENT_INT(0) .. 2 => 6);
FAILED ("NO EXCEPTION RAISED - CASE 2");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 2");
END;
BEGIN
V_A_CA := NEW UA'(2 .. 3 => 3);
COMMENT ("ADA 95 SLIDING ASSIGNMENT - CASE 3A");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("ADA 83 NON SLIDING ASSIGNMENT - CASE 3A");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3A");
END;
BEGIN
V_A_CAN := NEW UA'(IDENT_INT(3) .. IDENT_INT(2) => 3);
COMMENT ("ADA 95 SLIDING ASSIGNMENT - CASE 3B");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ("ADA 83 NON SLIDING ASSIGNMENT - CASE 3B");
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3B");
END;
END;
RESULT;
END C48009D;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ C H 3 --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2006, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Checks; use Checks;
with Einfo; use Einfo;
with Errout; use Errout;
with Exp_Aggr; use Exp_Aggr;
with Exp_Ch4; use Exp_Ch4;
with Exp_Ch7; use Exp_Ch7;
with Exp_Ch9; use Exp_Ch9;
with Exp_Ch11; use Exp_Ch11;
with Exp_Disp; use Exp_Disp;
with Exp_Dist; use Exp_Dist;
with Exp_Smem; use Exp_Smem;
with Exp_Strm; use Exp_Strm;
with Exp_Tss; use Exp_Tss;
with Exp_Util; use Exp_Util;
with Freeze; use Freeze;
with Hostparm; use Hostparm;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Attr; use Sem_Attr;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch8; use Sem_Ch8;
with Sem_Disp; use Sem_Disp;
with Sem_Eval; use Sem_Eval;
with Sem_Mech; use Sem_Mech;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Stand; use Stand;
with Snames; use Snames;
with Tbuild; use Tbuild;
with Ttypes; use Ttypes;
with Validsw; use Validsw;
package body Exp_Ch3 is
-----------------------
-- Local Subprograms --
-----------------------
procedure Adjust_Discriminants (Rtype : Entity_Id);
-- This is used when freezing a record type. It attempts to construct
-- more restrictive subtypes for discriminants so that the max size of
-- the record can be calculated more accurately. See the body of this
-- procedure for details.
procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id);
-- Build initialization procedure for given array type. Nod is a node
-- used for attachment of any actions required in its construction.
-- It also supplies the source location used for the procedure.
function Build_Discriminant_Formals
(Rec_Id : Entity_Id;
Use_Dl : Boolean) return List_Id;
-- This function uses the discriminants of a type to build a list of
-- formal parameters, used in the following function. If the flag Use_Dl
-- is set, the list is built using the already defined discriminals
-- of the type. Otherwise new identifiers are created, with the source
-- names of the discriminants.
procedure Build_Master_Renaming (N : Node_Id; T : Entity_Id);
-- If the designated type of an access type is a task type or contains
-- tasks, we make sure that a _Master variable is declared in the current
-- scope, and then declare a renaming for it:
--
-- atypeM : Master_Id renames _Master;
--
-- where atyp is the name of the access type. This declaration is
-- used when an allocator for the access type is expanded. The node N
-- is the full declaration of the designated type that contains tasks.
-- The renaming declaration is inserted before N, and after the Master
-- declaration.
procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id);
-- Build record initialization procedure. N is the type declaration
-- node, and Pe is the corresponding entity for the record type.
procedure Build_Slice_Assignment (Typ : Entity_Id);
-- Build assignment procedure for one-dimensional arrays of controlled
-- types. Other array and slice assignments are expanded in-line, but
-- the code expansion for controlled components (when control actions
-- are active) can lead to very large blocks that GCC3 handles poorly.
procedure Build_Variant_Record_Equality (Typ : Entity_Id);
-- Create An Equality function for the non-tagged variant record 'Typ'
-- and attach it to the TSS list
procedure Check_Stream_Attributes (Typ : Entity_Id);
-- Check that if a limited extension has a parent with user-defined
-- stream attributes, and does not itself have user-definer
-- stream-attributes, then any limited component of the extension also
-- has the corresponding user-defined stream attributes.
procedure Expand_Tagged_Root (T : Entity_Id);
-- Add a field _Tag at the beginning of the record. This field carries
-- the value of the access to the Dispatch table. This procedure is only
-- called on root (non CPP_Class) types, the _Tag field being inherited
-- by the descendants.
procedure Expand_Record_Controller (T : Entity_Id);
-- T must be a record type that Has_Controlled_Component. Add a field
-- _controller of type Record_Controller or Limited_Record_Controller
-- in the record T.
procedure Freeze_Array_Type (N : Node_Id);
-- Freeze an array type. Deals with building the initialization procedure,
-- creating the packed array type for a packed array and also with the
-- creation of the controlling procedures for the controlled case. The
-- argument N is the N_Freeze_Entity node for the type.
procedure Freeze_Enumeration_Type (N : Node_Id);
-- Freeze enumeration type with non-standard representation. Builds the
-- array and function needed to convert between enumeration pos and
-- enumeration representation values. N is the N_Freeze_Entity node
-- for the type.
procedure Freeze_Record_Type (N : Node_Id);
-- Freeze record type. Builds all necessary discriminant checking
-- and other ancillary functions, and builds dispatch tables where
-- needed. The argument N is the N_Freeze_Entity node. This processing
-- applies only to E_Record_Type entities, not to class wide types,
-- record subtypes, or private types.
procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id);
-- Treat user-defined stream operations as renaming_as_body if the
-- subprogram they rename is not frozen when the type is frozen.
function Init_Formals (Typ : Entity_Id) return List_Id;
-- This function builds the list of formals for an initialization routine.
-- The first formal is always _Init with the given type. For task value
-- record types and types containing tasks, three additional formals are
-- added:
--
-- _Master : Master_Id
-- _Chain : in out Activation_Chain
-- _Task_Name : String
--
-- The caller must append additional entries for discriminants if required.
function In_Runtime (E : Entity_Id) return Boolean;
-- Check if E is defined in the RTL (in a child of Ada or System). Used
-- to avoid to bring in the overhead of _Input, _Output for tagged types.
function Make_Eq_Case
(E : Entity_Id;
CL : Node_Id;
Discr : Entity_Id := Empty) return List_Id;
-- Building block for variant record equality. Defined to share the
-- code between the tagged and non-tagged case. Given a Component_List
-- node CL, it generates an 'if' followed by a 'case' statement that
-- compares all components of local temporaries named X and Y (that
-- are declared as formals at some upper level). E provides the Sloc to be
-- used for the generated code. Discr is used as the case statement switch
-- in the case of Unchecked_Union equality.
function Make_Eq_If
(E : Entity_Id;
L : List_Id) return Node_Id;
-- Building block for variant record equality. Defined to share the
-- code between the tagged and non-tagged case. Given the list of
-- components (or discriminants) L, it generates a return statement
-- that compares all components of local temporaries named X and Y
-- (that are declared as formals at some upper level). E provides the Sloc
-- to be used for the generated code.
procedure Make_Predefined_Primitive_Specs
(Tag_Typ : Entity_Id;
Predef_List : out List_Id;
Renamed_Eq : out Node_Id);
-- Create a list with the specs of the predefined primitive operations.
-- The following entries are present for all tagged types, and provide
-- the results of the corresponding attribute applied to the object.
-- Dispatching is required in general, since the result of the attribute
-- will vary with the actual object subtype.
--
-- _alignment provides result of 'Alignment attribute
-- _size provides result of 'Size attribute
-- typSR provides result of 'Read attribute
-- typSW provides result of 'Write attribute
-- typSI provides result of 'Input attribute
-- typSO provides result of 'Output attribute
--
-- The following entries are additionally present for non-limited
-- tagged types, and implement additional dispatching operations
-- for predefined operations:
--
-- _equality implements "=" operator
-- _assign implements assignment operation
-- typDF implements deep finalization
-- typDA implements deep adust
--
-- The latter two are empty procedures unless the type contains some
-- controlled components that require finalization actions (the deep
-- in the name refers to the fact that the action applies to components).
--
-- The list is returned in Predef_List. The Parameter Renamed_Eq
-- either returns the value Empty, or else the defining unit name
-- for the predefined equality function in the case where the type
-- has a primitive operation that is a renaming of predefined equality
-- (but only if there is also an overriding user-defined equality
-- function). The returned Renamed_Eq will be passed to the
-- corresponding parameter of Predefined_Primitive_Bodies.
function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean;
-- returns True if there are representation clauses for type T that
-- are not inherited. If the result is false, the init_proc and the
-- discriminant_checking functions of the parent can be reused by
-- a derived type.
procedure Make_Controlling_Function_Wrappers
(Tag_Typ : Entity_Id;
Decl_List : out List_Id;
Body_List : out List_Id);
-- Ada 2005 (AI-391): Makes specs and bodies for the wrapper functions
-- associated with inherited functions with controlling results which
-- are not overridden. The body of each wrapper function consists solely
-- of a return statement whose expression is an extension aggregate
-- invoking the inherited subprogram's parent subprogram and extended
-- with a null association list.
function Predef_Spec_Or_Body
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : Name_Id;
Profile : List_Id;
Ret_Type : Entity_Id := Empty;
For_Body : Boolean := False) return Node_Id;
-- This function generates the appropriate expansion for a predefined
-- primitive operation specified by its name, parameter profile and
-- return type (Empty means this is a procedure). If For_Body is false,
-- then the returned node is a subprogram declaration. If For_Body is
-- true, then the returned node is a empty subprogram body containing
-- no declarations and no statements.
function Predef_Stream_Attr_Spec
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : TSS_Name_Type;
For_Body : Boolean := False) return Node_Id;
-- Specialized version of Predef_Spec_Or_Body that apply to read, write,
-- input and output attribute whose specs are constructed in Exp_Strm.
function Predef_Deep_Spec
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : TSS_Name_Type;
For_Body : Boolean := False) return Node_Id;
-- Specialized version of Predef_Spec_Or_Body that apply to _deep_adjust
-- and _deep_finalize
function Predefined_Primitive_Bodies
(Tag_Typ : Entity_Id;
Renamed_Eq : Node_Id) return List_Id;
-- Create the bodies of the predefined primitives that are described in
-- Predefined_Primitive_Specs. When not empty, Renamed_Eq must denote
-- the defining unit name of the type's predefined equality as returned
-- by Make_Predefined_Primitive_Specs.
function Predefined_Primitive_Freeze (Tag_Typ : Entity_Id) return List_Id;
-- Freeze entities of all predefined primitive operations. This is needed
-- because the bodies of these operations do not normally do any freezeing.
function Stream_Operation_OK
(Typ : Entity_Id;
Operation : TSS_Name_Type) return Boolean;
-- Check whether the named stream operation must be emitted for a given
-- type. The rules for inheritance of stream attributes by type extensions
-- are enforced by this function. Furthermore, various restrictions prevent
-- the generation of these operations, as a useful optimization or for
-- certification purposes.
--------------------------
-- Adjust_Discriminants --
--------------------------
-- This procedure attempts to define subtypes for discriminants that
-- are more restrictive than those declared. Such a replacement is
-- possible if we can demonstrate that values outside the restricted
-- range would cause constraint errors in any case. The advantage of
-- restricting the discriminant types in this way is tha the maximum
-- size of the variant record can be calculated more conservatively.
-- An example of a situation in which we can perform this type of
-- restriction is the following:
-- subtype B is range 1 .. 10;
-- type Q is array (B range <>) of Integer;
-- type V (N : Natural) is record
-- C : Q (1 .. N);
-- end record;
-- In this situation, we can restrict the upper bound of N to 10, since
-- any larger value would cause a constraint error in any case.
-- There are many situations in which such restriction is possible, but
-- for now, we just look for cases like the above, where the component
-- in question is a one dimensional array whose upper bound is one of
-- the record discriminants. Also the component must not be part of
-- any variant part, since then the component does not always exist.
procedure Adjust_Discriminants (Rtype : Entity_Id) is
Loc : constant Source_Ptr := Sloc (Rtype);
Comp : Entity_Id;
Ctyp : Entity_Id;
Ityp : Entity_Id;
Lo : Node_Id;
Hi : Node_Id;
P : Node_Id;
Loval : Uint;
Discr : Entity_Id;
Dtyp : Entity_Id;
Dhi : Node_Id;
Dhiv : Uint;
Ahi : Node_Id;
Ahiv : Uint;
Tnn : Entity_Id;
begin
Comp := First_Component (Rtype);
while Present (Comp) loop
-- If our parent is a variant, quit, we do not look at components
-- that are in variant parts, because they may not always exist.
P := Parent (Comp); -- component declaration
P := Parent (P); -- component list
exit when Nkind (Parent (P)) = N_Variant;
-- We are looking for a one dimensional array type
Ctyp := Etype (Comp);
if not Is_Array_Type (Ctyp)
or else Number_Dimensions (Ctyp) > 1
then
goto Continue;
end if;
-- The lower bound must be constant, and the upper bound is a
-- discriminant (which is a discriminant of the current record).
Ityp := Etype (First_Index (Ctyp));
Lo := Type_Low_Bound (Ityp);
Hi := Type_High_Bound (Ityp);
if not Compile_Time_Known_Value (Lo)
or else Nkind (Hi) /= N_Identifier
or else No (Entity (Hi))
or else Ekind (Entity (Hi)) /= E_Discriminant
then
goto Continue;
end if;
-- We have an array with appropriate bounds
Loval := Expr_Value (Lo);
Discr := Entity (Hi);
Dtyp := Etype (Discr);
-- See if the discriminant has a known upper bound
Dhi := Type_High_Bound (Dtyp);
if not Compile_Time_Known_Value (Dhi) then
goto Continue;
end if;
Dhiv := Expr_Value (Dhi);
-- See if base type of component array has known upper bound
Ahi := Type_High_Bound (Etype (First_Index (Base_Type (Ctyp))));
if not Compile_Time_Known_Value (Ahi) then
goto Continue;
end if;
Ahiv := Expr_Value (Ahi);
-- The condition for doing the restriction is that the high bound
-- of the discriminant is greater than the low bound of the array,
-- and is also greater than the high bound of the base type index.
if Dhiv > Loval and then Dhiv > Ahiv then
-- We can reset the upper bound of the discriminant type to
-- whichever is larger, the low bound of the component, or
-- the high bound of the base type array index.
-- We build a subtype that is declared as
-- subtype Tnn is discr_type range discr_type'First .. max;
-- And insert this declaration into the tree. The type of the
-- discriminant is then reset to this more restricted subtype.
Tnn := Make_Defining_Identifier (Loc, New_Internal_Name ('T'));
Insert_Action (Declaration_Node (Rtype),
Make_Subtype_Declaration (Loc,
Defining_Identifier => Tnn,
Subtype_Indication =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (Dtyp, Loc),
Constraint =>
Make_Range_Constraint (Loc,
Range_Expression =>
Make_Range (Loc,
Low_Bound =>
Make_Attribute_Reference (Loc,
Attribute_Name => Name_First,
Prefix => New_Occurrence_Of (Dtyp, Loc)),
High_Bound =>
Make_Integer_Literal (Loc,
Intval => UI_Max (Loval, Ahiv)))))));
Set_Etype (Discr, Tnn);
end if;
<<Continue>>
Next_Component (Comp);
end loop;
end Adjust_Discriminants;
---------------------------
-- Build_Array_Init_Proc --
---------------------------
procedure Build_Array_Init_Proc (A_Type : Entity_Id; Nod : Node_Id) is
Loc : constant Source_Ptr := Sloc (Nod);
Comp_Type : constant Entity_Id := Component_Type (A_Type);
Index_List : List_Id;
Proc_Id : Entity_Id;
Body_Stmts : List_Id;
function Init_Component return List_Id;
-- Create one statement to initialize one array component, designated
-- by a full set of indices.
function Init_One_Dimension (N : Int) return List_Id;
-- Create loop to initialize one dimension of the array. The single
-- statement in the loop body initializes the inner dimensions if any,
-- or else the single component. Note that this procedure is called
-- recursively, with N being the dimension to be initialized. A call
-- with N greater than the number of dimensions simply generates the
-- component initialization, terminating the recursion.
--------------------
-- Init_Component --
--------------------
function Init_Component return List_Id is
Comp : Node_Id;
begin
Comp :=
Make_Indexed_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Expressions => Index_List);
if Needs_Simple_Initialization (Comp_Type) then
Set_Assignment_OK (Comp);
return New_List (
Make_Assignment_Statement (Loc,
Name => Comp,
Expression =>
Get_Simple_Init_Val
(Comp_Type, Loc, Component_Size (A_Type))));
else
return
Build_Initialization_Call (Loc, Comp, Comp_Type, True, A_Type);
end if;
end Init_Component;
------------------------
-- Init_One_Dimension --
------------------------
function Init_One_Dimension (N : Int) return List_Id is
Index : Entity_Id;
begin
-- If the component does not need initializing, then there is nothing
-- to do here, so we return a null body. This occurs when generating
-- the dummy Init_Proc needed for Initialize_Scalars processing.
if not Has_Non_Null_Base_Init_Proc (Comp_Type)
and then not Needs_Simple_Initialization (Comp_Type)
and then not Has_Task (Comp_Type)
then
return New_List (Make_Null_Statement (Loc));
-- If all dimensions dealt with, we simply initialize the component
elsif N > Number_Dimensions (A_Type) then
return Init_Component;
-- Here we generate the required loop
else
Index :=
Make_Defining_Identifier (Loc, New_External_Name ('J', N));
Append (New_Reference_To (Index, Loc), Index_List);
return New_List (
Make_Implicit_Loop_Statement (Nod,
Identifier => Empty,
Iteration_Scheme =>
Make_Iteration_Scheme (Loc,
Loop_Parameter_Specification =>
Make_Loop_Parameter_Specification (Loc,
Defining_Identifier => Index,
Discrete_Subtype_Definition =>
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Attribute_Name => Name_Range,
Expressions => New_List (
Make_Integer_Literal (Loc, N))))),
Statements => Init_One_Dimension (N + 1)));
end if;
end Init_One_Dimension;
-- Start of processing for Build_Array_Init_Proc
begin
if Suppress_Init_Proc (A_Type) then
return;
end if;
Index_List := New_List;
-- We need an initialization procedure if any of the following is true:
-- 1. The component type has an initialization procedure
-- 2. The component type needs simple initialization
-- 3. Tasks are present
-- 4. The type is marked as a publc entity
-- The reason for the public entity test is to deal properly with the
-- Initialize_Scalars pragma. This pragma can be set in the client and
-- not in the declaring package, this means the client will make a call
-- to the initialization procedure (because one of conditions 1-3 must
-- apply in this case), and we must generate a procedure (even if it is
-- null) to satisfy the call in this case.
-- Exception: do not build an array init_proc for a type whose root
-- type is Standard.String or Standard.Wide_[Wide_]String, since there
-- is no place to put the code, and in any case we handle initialization
-- of such types (in the Initialize_Scalars case, that's the only time
-- the issue arises) in a special manner anyway which does not need an
-- init_proc.
if Has_Non_Null_Base_Init_Proc (Comp_Type)
or else Needs_Simple_Initialization (Comp_Type)
or else Has_Task (Comp_Type)
or else (not Restriction_Active (No_Initialize_Scalars)
and then Is_Public (A_Type)
and then Root_Type (A_Type) /= Standard_String
and then Root_Type (A_Type) /= Standard_Wide_String
and then Root_Type (A_Type) /= Standard_Wide_Wide_String)
then
Proc_Id :=
Make_Defining_Identifier (Loc, Make_Init_Proc_Name (A_Type));
Body_Stmts := Init_One_Dimension (1);
Discard_Node (
Make_Subprogram_Body (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Proc_Id,
Parameter_Specifications => Init_Formals (A_Type)),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Body_Stmts)));
Set_Ekind (Proc_Id, E_Procedure);
Set_Is_Public (Proc_Id, Is_Public (A_Type));
Set_Is_Internal (Proc_Id);
Set_Has_Completion (Proc_Id);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Proc_Id);
end if;
-- Set inlined unless controlled stuff or tasks around, in which
-- case we do not want to inline, because nested stuff may cause
-- difficulties in interunit inlining, and furthermore there is
-- in any case no point in inlining such complex init procs.
if not Has_Task (Proc_Id)
and then not Controlled_Type (Proc_Id)
then
Set_Is_Inlined (Proc_Id);
end if;
-- Associate Init_Proc with type, and determine if the procedure
-- is null (happens because of the Initialize_Scalars pragma case,
-- where we have to generate a null procedure in case it is called
-- by a client with Initialize_Scalars set). Such procedures have
-- to be generated, but do not have to be called, so we mark them
-- as null to suppress the call.
Set_Init_Proc (A_Type, Proc_Id);
if List_Length (Body_Stmts) = 1
and then Nkind (First (Body_Stmts)) = N_Null_Statement
then
Set_Is_Null_Init_Proc (Proc_Id);
end if;
end if;
end Build_Array_Init_Proc;
-----------------------------
-- Build_Class_Wide_Master --
-----------------------------
procedure Build_Class_Wide_Master (T : Entity_Id) is
Loc : constant Source_Ptr := Sloc (T);
M_Id : Entity_Id;
Decl : Node_Id;
P : Node_Id;
Par : Node_Id;
begin
-- Nothing to do if there is no task hierarchy
if Restriction_Active (No_Task_Hierarchy) then
return;
end if;
-- Find declaration that created the access type: either a
-- type declaration, or an object declaration with an
-- access definition, in which case the type is anonymous.
if Is_Itype (T) then
P := Associated_Node_For_Itype (T);
else
P := Parent (T);
end if;
-- Nothing to do if we already built a master entity for this scope
if not Has_Master_Entity (Scope (T)) then
-- first build the master entity
-- _Master : constant Master_Id := Current_Master.all;
-- and insert it just before the current declaration
Decl :=
Make_Object_Declaration (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uMaster),
Constant_Present => True,
Object_Definition => New_Reference_To (Standard_Integer, Loc),
Expression =>
Make_Explicit_Dereference (Loc,
New_Reference_To (RTE (RE_Current_Master), Loc)));
Insert_Before (P, Decl);
Analyze (Decl);
Set_Has_Master_Entity (Scope (T));
-- Now mark the containing scope as a task master
Par := P;
while Nkind (Par) /= N_Compilation_Unit loop
Par := Parent (Par);
-- If we fall off the top, we are at the outer level, and the
-- environment task is our effective master, so nothing to mark.
if Nkind (Par) = N_Task_Body
or else Nkind (Par) = N_Block_Statement
or else Nkind (Par) = N_Subprogram_Body
then
Set_Is_Task_Master (Par, True);
exit;
end if;
end loop;
end if;
-- Now define the renaming of the master_id
M_Id :=
Make_Defining_Identifier (Loc,
New_External_Name (Chars (T), 'M'));
Decl :=
Make_Object_Renaming_Declaration (Loc,
Defining_Identifier => M_Id,
Subtype_Mark => New_Reference_To (Standard_Integer, Loc),
Name => Make_Identifier (Loc, Name_uMaster));
Insert_Before (P, Decl);
Analyze (Decl);
Set_Master_Id (T, M_Id);
exception
when RE_Not_Available =>
return;
end Build_Class_Wide_Master;
--------------------------------
-- Build_Discr_Checking_Funcs --
--------------------------------
procedure Build_Discr_Checking_Funcs (N : Node_Id) is
Rec_Id : Entity_Id;
Loc : Source_Ptr;
Enclosing_Func_Id : Entity_Id;
Sequence : Nat := 1;
Type_Def : Node_Id;
V : Node_Id;
function Build_Case_Statement
(Case_Id : Entity_Id;
Variant : Node_Id) return Node_Id;
-- Build a case statement containing only two alternatives. The
-- first alternative corresponds exactly to the discrete choices
-- given on the variant with contains the components that we are
-- generating the checks for. If the discriminant is one of these
-- return False. The second alternative is an OTHERS choice that
-- will return True indicating the discriminant did not match.
function Build_Dcheck_Function
(Case_Id : Entity_Id;
Variant : Node_Id) return Entity_Id;
-- Build the discriminant checking function for a given variant
procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id);
-- Builds the discriminant checking function for each variant of the
-- given variant part of the record type.
--------------------------
-- Build_Case_Statement --
--------------------------
function Build_Case_Statement
(Case_Id : Entity_Id;
Variant : Node_Id) return Node_Id
is
Alt_List : constant List_Id := New_List;
Actuals_List : List_Id;
Case_Node : Node_Id;
Case_Alt_Node : Node_Id;
Choice : Node_Id;
Choice_List : List_Id;
D : Entity_Id;
Return_Node : Node_Id;
begin
Case_Node := New_Node (N_Case_Statement, Loc);
-- Replace the discriminant which controls the variant, with the
-- name of the formal of the checking function.
Set_Expression (Case_Node,
Make_Identifier (Loc, Chars (Case_Id)));
Choice := First (Discrete_Choices (Variant));
if Nkind (Choice) = N_Others_Choice then
Choice_List := New_Copy_List (Others_Discrete_Choices (Choice));
else
Choice_List := New_Copy_List (Discrete_Choices (Variant));
end if;
if not Is_Empty_List (Choice_List) then
Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
Set_Discrete_Choices (Case_Alt_Node, Choice_List);
-- In case this is a nested variant, we need to return the result
-- of the discriminant checking function for the immediately
-- enclosing variant.
if Present (Enclosing_Func_Id) then
Actuals_List := New_List;
D := First_Discriminant (Rec_Id);
while Present (D) loop
Append (Make_Identifier (Loc, Chars (D)), Actuals_List);
Next_Discriminant (D);
end loop;
Return_Node :=
Make_Return_Statement (Loc,
Expression =>
Make_Function_Call (Loc,
Name =>
New_Reference_To (Enclosing_Func_Id, Loc),
Parameter_Associations =>
Actuals_List));
else
Return_Node :=
Make_Return_Statement (Loc,
Expression =>
New_Reference_To (Standard_False, Loc));
end if;
Set_Statements (Case_Alt_Node, New_List (Return_Node));
Append (Case_Alt_Node, Alt_List);
end if;
Case_Alt_Node := New_Node (N_Case_Statement_Alternative, Loc);
Choice_List := New_List (New_Node (N_Others_Choice, Loc));
Set_Discrete_Choices (Case_Alt_Node, Choice_List);
Return_Node :=
Make_Return_Statement (Loc,
Expression =>
New_Reference_To (Standard_True, Loc));
Set_Statements (Case_Alt_Node, New_List (Return_Node));
Append (Case_Alt_Node, Alt_List);
Set_Alternatives (Case_Node, Alt_List);
return Case_Node;
end Build_Case_Statement;
---------------------------
-- Build_Dcheck_Function --
---------------------------
function Build_Dcheck_Function
(Case_Id : Entity_Id;
Variant : Node_Id) return Entity_Id
is
Body_Node : Node_Id;
Func_Id : Entity_Id;
Parameter_List : List_Id;
Spec_Node : Node_Id;
begin
Body_Node := New_Node (N_Subprogram_Body, Loc);
Sequence := Sequence + 1;
Func_Id :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Rec_Id), 'D', Sequence));
Spec_Node := New_Node (N_Function_Specification, Loc);
Set_Defining_Unit_Name (Spec_Node, Func_Id);
Parameter_List := Build_Discriminant_Formals (Rec_Id, False);
Set_Parameter_Specifications (Spec_Node, Parameter_List);
Set_Result_Definition (Spec_Node,
New_Reference_To (Standard_Boolean, Loc));
Set_Specification (Body_Node, Spec_Node);
Set_Declarations (Body_Node, New_List);
Set_Handled_Statement_Sequence (Body_Node,
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (
Build_Case_Statement (Case_Id, Variant))));
Set_Ekind (Func_Id, E_Function);
Set_Mechanism (Func_Id, Default_Mechanism);
Set_Is_Inlined (Func_Id, True);
Set_Is_Pure (Func_Id, True);
Set_Is_Public (Func_Id, Is_Public (Rec_Id));
Set_Is_Internal (Func_Id, True);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Func_Id);
end if;
Analyze (Body_Node);
Append_Freeze_Action (Rec_Id, Body_Node);
Set_Dcheck_Function (Variant, Func_Id);
return Func_Id;
end Build_Dcheck_Function;
----------------------------
-- Build_Dcheck_Functions --
----------------------------
procedure Build_Dcheck_Functions (Variant_Part_Node : Node_Id) is
Component_List_Node : Node_Id;
Decl : Entity_Id;
Discr_Name : Entity_Id;
Func_Id : Entity_Id;
Variant : Node_Id;
Saved_Enclosing_Func_Id : Entity_Id;
begin
-- Build the discriminant checking function for each variant, label
-- all components of that variant with the function's name.
Discr_Name := Entity (Name (Variant_Part_Node));
Variant := First_Non_Pragma (Variants (Variant_Part_Node));
while Present (Variant) loop
Func_Id := Build_Dcheck_Function (Discr_Name, Variant);
Component_List_Node := Component_List (Variant);
if not Null_Present (Component_List_Node) then
Decl :=
First_Non_Pragma (Component_Items (Component_List_Node));
while Present (Decl) loop
Set_Discriminant_Checking_Func
(Defining_Identifier (Decl), Func_Id);
Next_Non_Pragma (Decl);
end loop;
if Present (Variant_Part (Component_List_Node)) then
Saved_Enclosing_Func_Id := Enclosing_Func_Id;
Enclosing_Func_Id := Func_Id;
Build_Dcheck_Functions (Variant_Part (Component_List_Node));
Enclosing_Func_Id := Saved_Enclosing_Func_Id;
end if;
end if;
Next_Non_Pragma (Variant);
end loop;
end Build_Dcheck_Functions;
-- Start of processing for Build_Discr_Checking_Funcs
begin
-- Only build if not done already
if not Discr_Check_Funcs_Built (N) then
Type_Def := Type_Definition (N);
if Nkind (Type_Def) = N_Record_Definition then
if No (Component_List (Type_Def)) then -- null record.
return;
else
V := Variant_Part (Component_List (Type_Def));
end if;
else pragma Assert (Nkind (Type_Def) = N_Derived_Type_Definition);
if No (Component_List (Record_Extension_Part (Type_Def))) then
return;
else
V := Variant_Part
(Component_List (Record_Extension_Part (Type_Def)));
end if;
end if;
Rec_Id := Defining_Identifier (N);
if Present (V) and then not Is_Unchecked_Union (Rec_Id) then
Loc := Sloc (N);
Enclosing_Func_Id := Empty;
Build_Dcheck_Functions (V);
end if;
Set_Discr_Check_Funcs_Built (N);
end if;
end Build_Discr_Checking_Funcs;
--------------------------------
-- Build_Discriminant_Formals --
--------------------------------
function Build_Discriminant_Formals
(Rec_Id : Entity_Id;
Use_Dl : Boolean) return List_Id
is
Loc : Source_Ptr := Sloc (Rec_Id);
Parameter_List : constant List_Id := New_List;
D : Entity_Id;
Formal : Entity_Id;
Param_Spec_Node : Node_Id;
begin
if Has_Discriminants (Rec_Id) then
D := First_Discriminant (Rec_Id);
while Present (D) loop
Loc := Sloc (D);
if Use_Dl then
Formal := Discriminal (D);
else
Formal := Make_Defining_Identifier (Loc, Chars (D));
end if;
Param_Spec_Node :=
Make_Parameter_Specification (Loc,
Defining_Identifier => Formal,
Parameter_Type =>
New_Reference_To (Etype (D), Loc));
Append (Param_Spec_Node, Parameter_List);
Next_Discriminant (D);
end loop;
end if;
return Parameter_List;
end Build_Discriminant_Formals;
-------------------------------
-- Build_Initialization_Call --
-------------------------------
-- References to a discriminant inside the record type declaration
-- can appear either in the subtype_indication to constrain a
-- record or an array, or as part of a larger expression given for
-- the initial value of a component. In both of these cases N appears
-- in the record initialization procedure and needs to be replaced by
-- the formal parameter of the initialization procedure which
-- corresponds to that discriminant.
-- In the example below, references to discriminants D1 and D2 in proc_1
-- are replaced by references to formals with the same name
-- (discriminals)
-- A similar replacement is done for calls to any record
-- initialization procedure for any components that are themselves
-- of a record type.
-- type R (D1, D2 : Integer) is record
-- X : Integer := F * D1;
-- Y : Integer := F * D2;
-- end record;
-- procedure proc_1 (Out_2 : out R; D1 : Integer; D2 : Integer) is
-- begin
-- Out_2.D1 := D1;
-- Out_2.D2 := D2;
-- Out_2.X := F * D1;
-- Out_2.Y := F * D2;
-- end;
function Build_Initialization_Call
(Loc : Source_Ptr;
Id_Ref : Node_Id;
Typ : Entity_Id;
In_Init_Proc : Boolean := False;
Enclos_Type : Entity_Id := Empty;
Discr_Map : Elist_Id := New_Elmt_List;
With_Default_Init : Boolean := False) return List_Id
is
First_Arg : Node_Id;
Args : List_Id;
Decls : List_Id;
Decl : Node_Id;
Discr : Entity_Id;
Arg : Node_Id;
Proc : constant Entity_Id := Base_Init_Proc (Typ);
Init_Type : constant Entity_Id := Etype (First_Formal (Proc));
Full_Init_Type : constant Entity_Id := Underlying_Type (Init_Type);
Res : constant List_Id := New_List;
Full_Type : Entity_Id := Typ;
Controller_Typ : Entity_Id;
begin
-- Nothing to do if the Init_Proc is null, unless Initialize_Scalars
-- is active (in which case we make the call anyway, since in the
-- actual compiled client it may be non null).
if Is_Null_Init_Proc (Proc) and then not Init_Or_Norm_Scalars then
return Empty_List;
end if;
-- Go to full view if private type. In the case of successive
-- private derivations, this can require more than one step.
while Is_Private_Type (Full_Type)
and then Present (Full_View (Full_Type))
loop
Full_Type := Full_View (Full_Type);
end loop;
-- If Typ is derived, the procedure is the initialization procedure for
-- the root type. Wrap the argument in an conversion to make it type
-- honest. Actually it isn't quite type honest, because there can be
-- conflicts of views in the private type case. That is why we set
-- Conversion_OK in the conversion node.
if (Is_Record_Type (Typ)
or else Is_Array_Type (Typ)
or else Is_Private_Type (Typ))
and then Init_Type /= Base_Type (Typ)
then
First_Arg := OK_Convert_To (Etype (Init_Type), Id_Ref);
Set_Etype (First_Arg, Init_Type);
else
First_Arg := Id_Ref;
end if;
Args := New_List (Convert_Concurrent (First_Arg, Typ));
-- In the tasks case, add _Master as the value of the _Master parameter
-- and _Chain as the value of the _Chain parameter. At the outer level,
-- these will be variables holding the corresponding values obtained
-- from GNARL. At inner levels, they will be the parameters passed down
-- through the outer routines.
if Has_Task (Full_Type) then
if Restriction_Active (No_Task_Hierarchy) then
-- See comments in System.Tasking.Initialization.Init_RTS
-- for the value 3 (should be rtsfindable constant ???)
Append_To (Args, Make_Integer_Literal (Loc, 3));
else
Append_To (Args, Make_Identifier (Loc, Name_uMaster));
end if;
Append_To (Args, Make_Identifier (Loc, Name_uChain));
-- Ada 2005 (AI-287): In case of default initialized components
-- with tasks, we generate a null string actual parameter.
-- This is just a workaround that must be improved later???
if With_Default_Init then
Append_To (Args,
Make_String_Literal (Loc,
Strval => ""));
else
Decls := Build_Task_Image_Decls (Loc, Id_Ref, Enclos_Type);
Decl := Last (Decls);
Append_To (Args,
New_Occurrence_Of (Defining_Identifier (Decl), Loc));
Append_List (Decls, Res);
end if;
else
Decls := No_List;
Decl := Empty;
end if;
-- Add discriminant values if discriminants are present
if Has_Discriminants (Full_Init_Type) then
Discr := First_Discriminant (Full_Init_Type);
while Present (Discr) loop
-- If this is a discriminated concurrent type, the init_proc
-- for the corresponding record is being called. Use that
-- type directly to find the discriminant value, to handle
-- properly intervening renamed discriminants.
declare
T : Entity_Id := Full_Type;
begin
if Is_Protected_Type (T) then
T := Corresponding_Record_Type (T);
elsif Is_Private_Type (T)
and then Present (Underlying_Full_View (T))
and then Is_Protected_Type (Underlying_Full_View (T))
then
T := Corresponding_Record_Type (Underlying_Full_View (T));
end if;
Arg :=
Get_Discriminant_Value (
Discr,
T,
Discriminant_Constraint (Full_Type));
end;
if In_Init_Proc then
-- Replace any possible references to the discriminant in the
-- call to the record initialization procedure with references
-- to the appropriate formal parameter.
if Nkind (Arg) = N_Identifier
and then Ekind (Entity (Arg)) = E_Discriminant
then
Arg := New_Reference_To (Discriminal (Entity (Arg)), Loc);
-- Case of access discriminants. We replace the reference
-- to the type by a reference to the actual object
elsif Nkind (Arg) = N_Attribute_Reference
and then Is_Access_Type (Etype (Arg))
and then Is_Entity_Name (Prefix (Arg))
and then Is_Type (Entity (Prefix (Arg)))
then
Arg :=
Make_Attribute_Reference (Loc,
Prefix => New_Copy (Prefix (Id_Ref)),
Attribute_Name => Name_Unrestricted_Access);
-- Otherwise make a copy of the default expression. Note
-- that we use the current Sloc for this, because we do not
-- want the call to appear to be at the declaration point.
-- Within the expression, replace discriminants with their
-- discriminals.
else
Arg :=
New_Copy_Tree (Arg, Map => Discr_Map, New_Sloc => Loc);
end if;
else
if Is_Constrained (Full_Type) then
Arg := Duplicate_Subexpr_No_Checks (Arg);
else
-- The constraints come from the discriminant default
-- exps, they must be reevaluated, so we use New_Copy_Tree
-- but we ensure the proper Sloc (for any embedded calls).
Arg := New_Copy_Tree (Arg, New_Sloc => Loc);
end if;
end if;
-- Ada 2005 (AI-287) In case of default initialized components,
-- we need to generate the corresponding selected component node
-- to access the discriminant value. In other cases this is not
-- required because we are inside the init proc and we use the
-- corresponding formal.
if With_Default_Init
and then Nkind (Id_Ref) = N_Selected_Component
and then Nkind (Arg) = N_Identifier
then
Append_To (Args,
Make_Selected_Component (Loc,
Prefix => New_Copy_Tree (Prefix (Id_Ref)),
Selector_Name => Arg));
else
Append_To (Args, Arg);
end if;
Next_Discriminant (Discr);
end loop;
end if;
-- If this is a call to initialize the parent component of a derived
-- tagged type, indicate that the tag should not be set in the parent.
if Is_Tagged_Type (Full_Init_Type)
and then not Is_CPP_Class (Full_Init_Type)
and then Nkind (Id_Ref) = N_Selected_Component
and then Chars (Selector_Name (Id_Ref)) = Name_uParent
then
Append_To (Args, New_Occurrence_Of (Standard_False, Loc));
end if;
Append_To (Res,
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Proc, Loc),
Parameter_Associations => Args));
if Controlled_Type (Typ)
and then Nkind (Id_Ref) = N_Selected_Component
then
if Chars (Selector_Name (Id_Ref)) /= Name_uParent then
Append_List_To (Res,
Make_Init_Call (
Ref => New_Copy_Tree (First_Arg),
Typ => Typ,
Flist_Ref =>
Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
With_Attach => Make_Integer_Literal (Loc, 1)));
-- If the enclosing type is an extension with new controlled
-- components, it has his own record controller. If the parent
-- also had a record controller, attach it to the new one.
-- Build_Init_Statements relies on the fact that in this specific
-- case the last statement of the result is the attach call to
-- the controller. If this is changed, it must be synchronized.
elsif Present (Enclos_Type)
and then Has_New_Controlled_Component (Enclos_Type)
and then Has_Controlled_Component (Typ)
then
if Is_Return_By_Reference_Type (Typ) then
Controller_Typ := RTE (RE_Limited_Record_Controller);
else
Controller_Typ := RTE (RE_Record_Controller);
end if;
Append_List_To (Res,
Make_Init_Call (
Ref =>
Make_Selected_Component (Loc,
Prefix => New_Copy_Tree (First_Arg),
Selector_Name => Make_Identifier (Loc, Name_uController)),
Typ => Controller_Typ,
Flist_Ref => Find_Final_List (Typ, New_Copy_Tree (First_Arg)),
With_Attach => Make_Integer_Literal (Loc, 1)));
end if;
end if;
return Res;
exception
when RE_Not_Available =>
return Empty_List;
end Build_Initialization_Call;
---------------------------
-- Build_Master_Renaming --
---------------------------
procedure Build_Master_Renaming (N : Node_Id; T : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
M_Id : Entity_Id;
Decl : Node_Id;
begin
-- Nothing to do if there is no task hierarchy
if Restriction_Active (No_Task_Hierarchy) then
return;
end if;
M_Id :=
Make_Defining_Identifier (Loc,
New_External_Name (Chars (T), 'M'));
Decl :=
Make_Object_Renaming_Declaration (Loc,
Defining_Identifier => M_Id,
Subtype_Mark => New_Reference_To (RTE (RE_Master_Id), Loc),
Name => Make_Identifier (Loc, Name_uMaster));
Insert_Before (N, Decl);
Analyze (Decl);
Set_Master_Id (T, M_Id);
exception
when RE_Not_Available =>
return;
end Build_Master_Renaming;
----------------------------
-- Build_Record_Init_Proc --
----------------------------
procedure Build_Record_Init_Proc (N : Node_Id; Pe : Entity_Id) is
Loc : Source_Ptr := Sloc (N);
Discr_Map : constant Elist_Id := New_Elmt_List;
Proc_Id : Entity_Id;
Rec_Type : Entity_Id;
Set_Tag : Entity_Id := Empty;
function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id;
-- Build a assignment statement node which assigns to record
-- component its default expression if defined. The left hand side
-- of the assignment is marked Assignment_OK so that initialization
-- of limited private records works correctly, Return also the
-- adjustment call for controlled objects
procedure Build_Discriminant_Assignments (Statement_List : List_Id);
-- If the record has discriminants, adds assignment statements to
-- statement list to initialize the discriminant values from the
-- arguments of the initialization procedure.
function Build_Init_Statements (Comp_List : Node_Id) return List_Id;
-- Build a list representing a sequence of statements which initialize
-- components of the given component list. This may involve building
-- case statements for the variant parts.
function Build_Init_Call_Thru (Parameters : List_Id) return List_Id;
-- Given a non-tagged type-derivation that declares discriminants,
-- such as
--
-- type R (R1, R2 : Integer) is record ... end record;
--
-- type D (D1 : Integer) is new R (1, D1);
--
-- we make the _init_proc of D be
--
-- procedure _init_proc(X : D; D1 : Integer) is
-- begin
-- _init_proc( R(X), 1, D1);
-- end _init_proc;
--
-- This function builds the call statement in this _init_proc.
procedure Build_Init_Procedure;
-- Build the tree corresponding to the procedure specification and body
-- of the initialization procedure (by calling all the preceding
-- auxiliary routines), and install it as the _init TSS.
procedure Build_Offset_To_Top_Functions;
-- Ada 2005 (AI-251): Build the tree corresponding to the procedure spec
-- and body of the Offset_To_Top function that is generated when the
-- parent of a type with discriminants has secondary dispatch tables.
procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id);
-- Add range checks to components of disciminated records. S is a
-- subtype indication of a record component. Check_List is a list
-- to which the check actions are appended.
function Component_Needs_Simple_Initialization
(T : Entity_Id) return Boolean;
-- Determines if a component needs simple initialization, given its type
-- T. This is the same as Needs_Simple_Initialization except for the
-- following difference: the types Tag, Interface_Tag, and Vtable_Ptr
-- which are access types which would normally require simple
-- initialization to null, do not require initialization as components,
-- since they are explicitly initialized by other means.
procedure Constrain_Array
(SI : Node_Id;
Check_List : List_Id);
-- Called from Build_Record_Checks.
-- Apply a list of index constraints to an unconstrained array type.
-- The first parameter is the entity for the resulting subtype.
-- Check_List is a list to which the check actions are appended.
procedure Constrain_Index
(Index : Node_Id;
S : Node_Id;
Check_List : List_Id);
-- Called from Build_Record_Checks.
-- Process an index constraint in a constrained array declaration.
-- The constraint can be a subtype name, or a range with or without
-- an explicit subtype mark. The index is the corresponding index of the
-- unconstrained array. S is the range expression. Check_List is a list
-- to which the check actions are appended.
function Parent_Subtype_Renaming_Discrims return Boolean;
-- Returns True for base types N that rename discriminants, else False
function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean;
-- Determines whether a record initialization procedure needs to be
-- generated for the given record type.
----------------------
-- Build_Assignment --
----------------------
function Build_Assignment (Id : Entity_Id; N : Node_Id) return List_Id is
Exp : Node_Id := N;
Lhs : Node_Id;
Typ : constant Entity_Id := Underlying_Type (Etype (Id));
Kind : Node_Kind := Nkind (N);
Res : List_Id;
begin
Loc := Sloc (N);
Lhs :=
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name => New_Occurrence_Of (Id, Loc));
Set_Assignment_OK (Lhs);
-- Case of an access attribute applied to the current instance.
-- Replace the reference to the type by a reference to the actual
-- object. (Note that this handles the case of the top level of
-- the expression being given by such an attribute, but does not
-- cover uses nested within an initial value expression. Nested
-- uses are unlikely to occur in practice, but are theoretically
-- possible. It is not clear how to handle them without fully
-- traversing the expression. ???
if Kind = N_Attribute_Reference
and then (Attribute_Name (N) = Name_Unchecked_Access
or else
Attribute_Name (N) = Name_Unrestricted_Access)
and then Is_Entity_Name (Prefix (N))
and then Is_Type (Entity (Prefix (N)))
and then Entity (Prefix (N)) = Rec_Type
then
Exp :=
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Attribute_Name => Name_Unrestricted_Access);
end if;
-- Ada 2005 (AI-231): Add the run-time check if required
if Ada_Version >= Ada_05
and then Can_Never_Be_Null (Etype (Id)) -- Lhs
then
if Nkind (Exp) = N_Null then
return New_List (
Make_Raise_Constraint_Error (Sloc (Exp),
Reason => CE_Null_Not_Allowed));
elsif Present (Etype (Exp))
and then not Can_Never_Be_Null (Etype (Exp))
then
Install_Null_Excluding_Check (Exp);
end if;
end if;
-- Take a copy of Exp to ensure that later copies of this
-- component_declaration in derived types see the original tree,
-- not a node rewritten during expansion of the init_proc.
Exp := New_Copy_Tree (Exp);
Res := New_List (
Make_Assignment_Statement (Loc,
Name => Lhs,
Expression => Exp));
Set_No_Ctrl_Actions (First (Res));
-- Adjust the tag if tagged (because of possible view conversions).
-- Suppress the tag adjustment when Java_VM because JVM tags are
-- represented implicitly in objects.
if Is_Tagged_Type (Typ) and then not Java_VM then
Append_To (Res,
Make_Assignment_Statement (Loc,
Name =>
Make_Selected_Component (Loc,
Prefix => New_Copy_Tree (Lhs),
Selector_Name =>
New_Reference_To (First_Tag_Component (Typ), Loc)),
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Reference_To
(Node (First_Elmt (Access_Disp_Table (Typ))), Loc))));
end if;
-- Adjust the component if controlled except if it is an
-- aggregate that will be expanded inline
if Kind = N_Qualified_Expression then
Kind := Nkind (Expression (N));
end if;
if Controlled_Type (Typ)
and then not (Kind = N_Aggregate or else Kind = N_Extension_Aggregate)
then
Append_List_To (Res,
Make_Adjust_Call (
Ref => New_Copy_Tree (Lhs),
Typ => Etype (Id),
Flist_Ref =>
Find_Final_List (Etype (Id), New_Copy_Tree (Lhs)),
With_Attach => Make_Integer_Literal (Loc, 1)));
end if;
return Res;
exception
when RE_Not_Available =>
return Empty_List;
end Build_Assignment;
------------------------------------
-- Build_Discriminant_Assignments --
------------------------------------
procedure Build_Discriminant_Assignments (Statement_List : List_Id) is
D : Entity_Id;
Is_Tagged : constant Boolean := Is_Tagged_Type (Rec_Type);
begin
if Has_Discriminants (Rec_Type)
and then not Is_Unchecked_Union (Rec_Type)
then
D := First_Discriminant (Rec_Type);
while Present (D) loop
-- Don't generate the assignment for discriminants in derived
-- tagged types if the discriminant is a renaming of some
-- ancestor discriminant. This initialization will be done
-- when initializing the _parent field of the derived record.
if Is_Tagged and then
Present (Corresponding_Discriminant (D))
then
null;
else
Loc := Sloc (D);
Append_List_To (Statement_List,
Build_Assignment (D,
New_Reference_To (Discriminal (D), Loc)));
end if;
Next_Discriminant (D);
end loop;
end if;
end Build_Discriminant_Assignments;
--------------------------
-- Build_Init_Call_Thru --
--------------------------
function Build_Init_Call_Thru (Parameters : List_Id) return List_Id is
Parent_Proc : constant Entity_Id :=
Base_Init_Proc (Etype (Rec_Type));
Parent_Type : constant Entity_Id :=
Etype (First_Formal (Parent_Proc));
Uparent_Type : constant Entity_Id :=
Underlying_Type (Parent_Type);
First_Discr_Param : Node_Id;
Parent_Discr : Entity_Id;
First_Arg : Node_Id;
Args : List_Id;
Arg : Node_Id;
Res : List_Id;
begin
-- First argument (_Init) is the object to be initialized.
-- ??? not sure where to get a reasonable Loc for First_Arg
First_Arg :=
OK_Convert_To (Parent_Type,
New_Reference_To (Defining_Identifier (First (Parameters)), Loc));
Set_Etype (First_Arg, Parent_Type);
Args := New_List (Convert_Concurrent (First_Arg, Rec_Type));
-- In the tasks case,
-- add _Master as the value of the _Master parameter
-- add _Chain as the value of the _Chain parameter.
-- add _Task_Name as the value of the _Task_Name parameter.
-- At the outer level, these will be variables holding the
-- corresponding values obtained from GNARL or the expander.
--
-- At inner levels, they will be the parameters passed down through
-- the outer routines.
First_Discr_Param := Next (First (Parameters));
if Has_Task (Rec_Type) then
if Restriction_Active (No_Task_Hierarchy) then
-- See comments in System.Tasking.Initialization.Init_RTS
-- for the value 3.
Append_To (Args, Make_Integer_Literal (Loc, 3));
else
Append_To (Args, Make_Identifier (Loc, Name_uMaster));
end if;
Append_To (Args, Make_Identifier (Loc, Name_uChain));
Append_To (Args, Make_Identifier (Loc, Name_uTask_Name));
First_Discr_Param := Next (Next (Next (First_Discr_Param)));
end if;
-- Append discriminant values
if Has_Discriminants (Uparent_Type) then
pragma Assert (not Is_Tagged_Type (Uparent_Type));
Parent_Discr := First_Discriminant (Uparent_Type);
while Present (Parent_Discr) loop
-- Get the initial value for this discriminant
-- ??? needs to be cleaned up to use parent_Discr_Constr
-- directly.
declare
Discr_Value : Elmt_Id :=
First_Elmt
(Stored_Constraint (Rec_Type));
Discr : Entity_Id :=
First_Stored_Discriminant (Uparent_Type);
begin
while Original_Record_Component (Parent_Discr) /= Discr loop
Next_Stored_Discriminant (Discr);
Next_Elmt (Discr_Value);
end loop;
Arg := Node (Discr_Value);
end;
-- Append it to the list
if Nkind (Arg) = N_Identifier
and then Ekind (Entity (Arg)) = E_Discriminant
then
Append_To (Args,
New_Reference_To (Discriminal (Entity (Arg)), Loc));
-- Case of access discriminants. We replace the reference
-- to the type by a reference to the actual object
-- ??? why is this code deleted without comment
-- elsif Nkind (Arg) = N_Attribute_Reference
-- and then Is_Entity_Name (Prefix (Arg))
-- and then Is_Type (Entity (Prefix (Arg)))
-- then
-- Append_To (Args,
-- Make_Attribute_Reference (Loc,
-- Prefix => New_Copy (Prefix (Id_Ref)),
-- Attribute_Name => Name_Unrestricted_Access));
else
Append_To (Args, New_Copy (Arg));
end if;
Next_Discriminant (Parent_Discr);
end loop;
end if;
Res :=
New_List (
Make_Procedure_Call_Statement (Loc,
Name => New_Occurrence_Of (Parent_Proc, Loc),
Parameter_Associations => Args));
return Res;
end Build_Init_Call_Thru;
-----------------------------------
-- Build_Offset_To_Top_Functions --
-----------------------------------
procedure Build_Offset_To_Top_Functions is
ADT : Elmt_Id;
Body_Node : Node_Id;
Func_Id : Entity_Id;
Spec_Node : Node_Id;
E : Entity_Id;
procedure Build_Offset_To_Top_Internal (Typ : Entity_Id);
-- Internal subprogram used to recursively traverse all the ancestors
----------------------------------
-- Build_Offset_To_Top_Internal --
----------------------------------
procedure Build_Offset_To_Top_Internal (Typ : Entity_Id) is
begin
-- Climb to the ancestor (if any) handling private types
if Present (Full_View (Etype (Typ))) then
if Full_View (Etype (Typ)) /= Typ then
Build_Offset_To_Top_Internal (Full_View (Etype (Typ)));
end if;
elsif Etype (Typ) /= Typ then
Build_Offset_To_Top_Internal (Etype (Typ));
end if;
if Present (Abstract_Interfaces (Typ))
and then not Is_Empty_Elmt_List (Abstract_Interfaces (Typ))
then
E := First_Entity (Typ);
while Present (E) loop
if Is_Tag (E)
and then Chars (E) /= Name_uTag
then
if Typ = Rec_Type then
Body_Node := New_Node (N_Subprogram_Body, Loc);
Func_Id := Make_Defining_Identifier (Loc,
New_Internal_Name ('F'));
Set_DT_Offset_To_Top_Func (E, Func_Id);
Spec_Node := New_Node (N_Function_Specification, Loc);
Set_Defining_Unit_Name (Spec_Node, Func_Id);
Set_Parameter_Specifications (Spec_Node, New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uO),
In_Present => True,
Parameter_Type => New_Reference_To (Typ, Loc))));
Set_Result_Definition (Spec_Node,
New_Reference_To (RTE (RE_Storage_Offset), Loc));
Set_Specification (Body_Node, Spec_Node);
Set_Declarations (Body_Node, New_List);
Set_Handled_Statement_Sequence (Body_Node,
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (
Make_Return_Statement (Loc,
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc,
Name_uO),
Selector_Name => New_Reference_To
(E, Loc)),
Attribute_Name => Name_Position)))));
Set_Ekind (Func_Id, E_Function);
Set_Mechanism (Func_Id, Default_Mechanism);
Set_Is_Internal (Func_Id, True);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Func_Id);
end if;
Analyze (Body_Node);
Append_Freeze_Action (Rec_Type, Body_Node);
end if;
Next_Elmt (ADT);
end if;
Next_Entity (E);
end loop;
end if;
end Build_Offset_To_Top_Internal;
-- Start of processing for Build_Offset_To_Top_Functions
begin
if Etype (Rec_Type) = Rec_Type
or else not Has_Discriminants (Etype (Rec_Type))
or else No (Abstract_Interfaces (Rec_Type))
or else Is_Empty_Elmt_List (Abstract_Interfaces (Rec_Type))
then
return;
end if;
-- Skip the first _Tag, which is the main tag of the
-- tagged type. Following tags correspond with abstract
-- interfaces.
ADT := Next_Elmt (First_Elmt (Access_Disp_Table (Rec_Type)));
-- Handle private types
if Present (Full_View (Rec_Type)) then
Build_Offset_To_Top_Internal (Full_View (Rec_Type));
else
Build_Offset_To_Top_Internal (Rec_Type);
end if;
end Build_Offset_To_Top_Functions;
--------------------------
-- Build_Init_Procedure --
--------------------------
procedure Build_Init_Procedure is
Body_Node : Node_Id;
Handled_Stmt_Node : Node_Id;
Parameters : List_Id;
Proc_Spec_Node : Node_Id;
Body_Stmts : List_Id;
Record_Extension_Node : Node_Id;
Init_Tag : Node_Id;
procedure Init_Secondary_Tags (Typ : Entity_Id);
-- Ada 2005 (AI-251): Initialize the tags of all the secondary
-- tables associated with abstract interface types
-------------------------
-- Init_Secondary_Tags --
-------------------------
procedure Init_Secondary_Tags (Typ : Entity_Id) is
ADT : Elmt_Id;
procedure Init_Secondary_Tags_Internal (Typ : Entity_Id);
-- Internal subprogram used to recursively climb to the root type
----------------------------------
-- Init_Secondary_Tags_Internal --
----------------------------------
procedure Init_Secondary_Tags_Internal (Typ : Entity_Id) is
Aux_N : Node_Id;
E : Entity_Id;
Iface : Entity_Id;
Prev_E : Entity_Id;
begin
-- Climb to the ancestor (if any) handling private types
if Present (Full_View (Etype (Typ))) then
if Full_View (Etype (Typ)) /= Typ then
Init_Secondary_Tags_Internal (Full_View (Etype (Typ)));
end if;
elsif Etype (Typ) /= Typ then
Init_Secondary_Tags_Internal (Etype (Typ));
end if;
if Present (Abstract_Interfaces (Typ))
and then not Is_Empty_Elmt_List (Abstract_Interfaces (Typ))
then
E := First_Entity (Typ);
while Present (E) loop
if Is_Tag (E)
and then Chars (E) /= Name_uTag
then
Aux_N := Node (ADT);
pragma Assert (Present (Aux_N));
Iface := Find_Interface (Typ, E);
-- Initialize the pointer to the secondary DT
-- associated with the interface
Append_To (Body_Stmts,
Make_Assignment_Statement (Loc,
Name =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name =>
New_Reference_To (E, Loc)),
Expression =>
New_Reference_To (Aux_N, Loc)));
-- Issue error if Set_Offset_To_Top is not available
-- in a configurable run-time environment.
if not RTE_Available (RE_Set_Offset_To_Top) then
Error_Msg_CRT ("abstract interface types", Typ);
return;
end if;
-- We generate a different call to Set_Offset_To_Top
-- when the parent of the type has discriminants
if Typ /= Etype (Typ)
and then Has_Discriminants (Etype (Typ))
then
pragma Assert (Present (DT_Offset_To_Top_Func (E)));
-- Generate:
-- Set_Offset_To_Top
-- (This => Init,
-- Interface_T => Iface'Tag,
-- Is_Constant => False,
-- Offset_Value => n,
-- Offset_Func => Fn'Address)
Append_To (Body_Stmts,
Make_Procedure_Call_Statement (Loc,
Name => New_Reference_To
(RTE (RE_Set_Offset_To_Top), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc,
Name_uInit),
Attribute_Name => Name_Address),
Unchecked_Convert_To (RTE (RE_Tag),
New_Reference_To
(Node (First_Elmt
(Access_Disp_Table (Iface))),
Loc)),
New_Occurrence_Of (Standard_False, Loc),
Unchecked_Convert_To (RTE (RE_Storage_Offset),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc,
Name_uInit),
Selector_Name => New_Reference_To
(E, Loc)),
Attribute_Name => Name_Position)),
Unchecked_Convert_To (RTE (RE_Address),
Make_Attribute_Reference (Loc,
Prefix => New_Reference_To
(DT_Offset_To_Top_Func (E),
Loc),
Attribute_Name =>
Name_Address)))));
-- In this case the next component stores the value
-- of the offset to the top
Prev_E := E;
Next_Entity (E);
pragma Assert (Present (E));
Append_To (Body_Stmts,
Make_Assignment_Statement (Loc,
Name =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc,
Name_uInit),
Selector_Name =>
New_Reference_To (E, Loc)),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc,
Name_uInit),
Selector_Name => New_Reference_To
(Prev_E, Loc)),
Attribute_Name => Name_Position)));
-- Normal case: No discriminants in the parent type
else
-- Generate:
-- Set_Offset_To_Top
-- (This => Init,
-- Interface_T => Iface'Tag,
-- Is_Constant => True,
-- Offset_Value => n,
-- Offset_Func => null);
Append_To (Body_Stmts,
Make_Procedure_Call_Statement (Loc,
Name => New_Reference_To
(RTE (RE_Set_Offset_To_Top), Loc),
Parameter_Associations => New_List (
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Attribute_Name => Name_Address),
Unchecked_Convert_To (RTE (RE_Tag),
New_Reference_To
(Node (First_Elmt
(Access_Disp_Table (Iface))),
Loc)),
New_Occurrence_Of (Standard_True, Loc),
Unchecked_Convert_To (RTE (RE_Storage_Offset),
Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc,
Name_uInit),
Selector_Name => New_Reference_To
(E, Loc)),
Attribute_Name => Name_Position)),
New_Reference_To
(RTE (RE_Null_Address), Loc))));
end if;
Next_Elmt (ADT);
end if;
Next_Entity (E);
end loop;
end if;
end Init_Secondary_Tags_Internal;
-- Start of processing for Init_Secondary_Tags
begin
-- Skip the first _Tag, which is the main tag of the
-- tagged type. Following tags correspond with abstract
-- interfaces.
ADT := Next_Elmt (First_Elmt (Access_Disp_Table (Typ)));
-- Handle private types
if Present (Full_View (Typ)) then
Init_Secondary_Tags_Internal (Full_View (Typ));
else
Init_Secondary_Tags_Internal (Typ);
end if;
end Init_Secondary_Tags;
-- Start of processing for Build_Init_Procedure
begin
Body_Stmts := New_List;
Body_Node := New_Node (N_Subprogram_Body, Loc);
Proc_Id :=
Make_Defining_Identifier (Loc,
Chars => Make_Init_Proc_Name (Rec_Type));
Set_Ekind (Proc_Id, E_Procedure);
Proc_Spec_Node := New_Node (N_Procedure_Specification, Loc);
Set_Defining_Unit_Name (Proc_Spec_Node, Proc_Id);
Parameters := Init_Formals (Rec_Type);
Append_List_To (Parameters,
Build_Discriminant_Formals (Rec_Type, True));
-- For tagged types, we add a flag to indicate whether the routine
-- is called to initialize a parent component in the init_proc of
-- a type extension. If the flag is false, we do not set the tag
-- because it has been set already in the extension.
if Is_Tagged_Type (Rec_Type)
and then not Is_CPP_Class (Rec_Type)
then
Set_Tag :=
Make_Defining_Identifier (Loc, New_Internal_Name ('P'));
Append_To (Parameters,
Make_Parameter_Specification (Loc,
Defining_Identifier => Set_Tag,
Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc),
Expression => New_Occurrence_Of (Standard_True, Loc)));
end if;
Set_Parameter_Specifications (Proc_Spec_Node, Parameters);
Set_Specification (Body_Node, Proc_Spec_Node);
Set_Declarations (Body_Node, New_List);
if Parent_Subtype_Renaming_Discrims then
-- N is a Derived_Type_Definition that renames the parameters
-- of the ancestor type. We initialize it by expanding our
-- discriminants and call the ancestor _init_proc with a
-- type-converted object
Append_List_To (Body_Stmts,
Build_Init_Call_Thru (Parameters));
elsif Nkind (Type_Definition (N)) = N_Record_Definition then
Build_Discriminant_Assignments (Body_Stmts);
if not Null_Present (Type_Definition (N)) then
Append_List_To (Body_Stmts,
Build_Init_Statements (
Component_List (Type_Definition (N))));
end if;
else
-- N is a Derived_Type_Definition with a possible non-empty
-- extension. The initialization of a type extension consists
-- in the initialization of the components in the extension.
Build_Discriminant_Assignments (Body_Stmts);
Record_Extension_Node :=
Record_Extension_Part (Type_Definition (N));
if not Null_Present (Record_Extension_Node) then
declare
Stmts : constant List_Id :=
Build_Init_Statements (
Component_List (Record_Extension_Node));
begin
-- The parent field must be initialized first because
-- the offset of the new discriminants may depend on it
Prepend_To (Body_Stmts, Remove_Head (Stmts));
Append_List_To (Body_Stmts, Stmts);
end;
end if;
end if;
-- Add here the assignment to instantiate the Tag
-- The assignement corresponds to the code:
-- _Init._Tag := Typ'Tag;
-- Suppress the tag assignment when Java_VM because JVM tags are
-- represented implicitly in objects. It is also suppressed in
-- case of CPP_Class types because in this case the tag is
-- initialized in the C++ side.
if Is_Tagged_Type (Rec_Type)
and then not Is_CPP_Class (Rec_Type)
and then not Java_VM
then
Init_Tag :=
Make_Assignment_Statement (Loc,
Name =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name =>
New_Reference_To (First_Tag_Component (Rec_Type), Loc)),
Expression =>
New_Reference_To
(Node (First_Elmt (Access_Disp_Table (Rec_Type))), Loc));
-- The tag must be inserted before the assignments to other
-- components, because the initial value of the component may
-- depend ot the tag (eg. through a dispatching operation on
-- an access to the current type). The tag assignment is not done
-- when initializing the parent component of a type extension,
-- because in that case the tag is set in the extension.
-- Extensions of imported C++ classes add a final complication,
-- because we cannot inhibit tag setting in the constructor for
-- the parent. In that case we insert the tag initialization
-- after the calls to initialize the parent.
Init_Tag :=
Make_If_Statement (Loc,
Condition => New_Occurrence_Of (Set_Tag, Loc),
Then_Statements => New_List (Init_Tag));
if not Is_CPP_Class (Etype (Rec_Type)) then
Prepend_To (Body_Stmts, Init_Tag);
-- Ada 2005 (AI-251): Initialization of all the tags
-- corresponding with abstract interfaces
if Ada_Version >= Ada_05
and then not Is_Interface (Rec_Type)
then
Init_Secondary_Tags (Rec_Type);
end if;
else
declare
Nod : Node_Id := First (Body_Stmts);
begin
-- We assume the first init_proc call is for the parent
while Present (Next (Nod))
and then (Nkind (Nod) /= N_Procedure_Call_Statement
or else not Is_Init_Proc (Name (Nod)))
loop
Nod := Next (Nod);
end loop;
Insert_After (Nod, Init_Tag);
end;
end if;
end if;
Handled_Stmt_Node := New_Node (N_Handled_Sequence_Of_Statements, Loc);
Set_Statements (Handled_Stmt_Node, Body_Stmts);
Set_Exception_Handlers (Handled_Stmt_Node, No_List);
Set_Handled_Statement_Sequence (Body_Node, Handled_Stmt_Node);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Proc_Id);
end if;
-- Associate Init_Proc with type, and determine if the procedure
-- is null (happens because of the Initialize_Scalars pragma case,
-- where we have to generate a null procedure in case it is called
-- by a client with Initialize_Scalars set). Such procedures have
-- to be generated, but do not have to be called, so we mark them
-- as null to suppress the call.
Set_Init_Proc (Rec_Type, Proc_Id);
if List_Length (Body_Stmts) = 1
and then Nkind (First (Body_Stmts)) = N_Null_Statement
then
Set_Is_Null_Init_Proc (Proc_Id);
end if;
end Build_Init_Procedure;
---------------------------
-- Build_Init_Statements --
---------------------------
function Build_Init_Statements (Comp_List : Node_Id) return List_Id is
Check_List : constant List_Id := New_List;
Alt_List : List_Id;
Statement_List : List_Id;
Stmts : List_Id;
Per_Object_Constraint_Components : Boolean;
Decl : Node_Id;
Variant : Node_Id;
Id : Entity_Id;
Typ : Entity_Id;
function Has_Access_Constraint (E : Entity_Id) return Boolean;
-- Components with access discriminants that depend on the current
-- instance must be initialized after all other components.
---------------------------
-- Has_Access_Constraint --
---------------------------
function Has_Access_Constraint (E : Entity_Id) return Boolean is
Disc : Entity_Id;
T : constant Entity_Id := Etype (E);
begin
if Has_Per_Object_Constraint (E)
and then Has_Discriminants (T)
then
Disc := First_Discriminant (T);
while Present (Disc) loop
if Is_Access_Type (Etype (Disc)) then
return True;
end if;
Next_Discriminant (Disc);
end loop;
return False;
else
return False;
end if;
end Has_Access_Constraint;
-- Start of processing for Build_Init_Statements
begin
if Null_Present (Comp_List) then
return New_List (Make_Null_Statement (Loc));
end if;
Statement_List := New_List;
-- Loop through components, skipping pragmas, in 2 steps. The first
-- step deals with regular components. The second step deals with
-- components have per object constraints, and no explicit initia-
-- lization.
Per_Object_Constraint_Components := False;
-- First step : regular components
Decl := First_Non_Pragma (Component_Items (Comp_List));
while Present (Decl) loop
Loc := Sloc (Decl);
Build_Record_Checks
(Subtype_Indication (Component_Definition (Decl)), Check_List);
Id := Defining_Identifier (Decl);
Typ := Etype (Id);
if Has_Access_Constraint (Id)
and then No (Expression (Decl))
then
-- Skip processing for now and ask for a second pass
Per_Object_Constraint_Components := True;
else
-- Case of explicit initialization
if Present (Expression (Decl)) then
Stmts := Build_Assignment (Id, Expression (Decl));
-- Case of composite component with its own Init_Proc
elsif not Is_Interface (Typ)
and then Has_Non_Null_Base_Init_Proc (Typ)
then
Stmts :=
Build_Initialization_Call
(Loc,
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name => New_Occurrence_Of (Id, Loc)),
Typ,
True,
Rec_Type,
Discr_Map => Discr_Map);
-- Case of component needing simple initialization
elsif Component_Needs_Simple_Initialization (Typ) then
Stmts :=
Build_Assignment
(Id, Get_Simple_Init_Val (Typ, Loc, Esize (Id)));
-- Nothing needed for this case
else
Stmts := No_List;
end if;
if Present (Check_List) then
Append_List_To (Statement_List, Check_List);
end if;
if Present (Stmts) then
-- Add the initialization of the record controller before
-- the _Parent field is attached to it when the attachment
-- can occur. It does not work to simply initialize the
-- controller first: it must be initialized after the parent
-- if the parent holds discriminants that can be used
-- to compute the offset of the controller. We assume here
-- that the last statement of the initialization call is the
-- attachement of the parent (see Build_Initialization_Call)
if Chars (Id) = Name_uController
and then Rec_Type /= Etype (Rec_Type)
and then Has_Controlled_Component (Etype (Rec_Type))
and then Has_New_Controlled_Component (Rec_Type)
then
Insert_List_Before (Last (Statement_List), Stmts);
else
Append_List_To (Statement_List, Stmts);
end if;
end if;
end if;
Next_Non_Pragma (Decl);
end loop;
if Per_Object_Constraint_Components then
-- Second pass: components with per-object constraints
Decl := First_Non_Pragma (Component_Items (Comp_List));
while Present (Decl) loop
Loc := Sloc (Decl);
Id := Defining_Identifier (Decl);
Typ := Etype (Id);
if Has_Access_Constraint (Id)
and then No (Expression (Decl))
then
if Has_Non_Null_Base_Init_Proc (Typ) then
Append_List_To (Statement_List,
Build_Initialization_Call (Loc,
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name => New_Occurrence_Of (Id, Loc)),
Typ, True, Rec_Type, Discr_Map => Discr_Map));
elsif Component_Needs_Simple_Initialization (Typ) then
Append_List_To (Statement_List,
Build_Assignment
(Id, Get_Simple_Init_Val (Typ, Loc, Esize (Id))));
end if;
end if;
Next_Non_Pragma (Decl);
end loop;
end if;
-- Process the variant part
if Present (Variant_Part (Comp_List)) then
Alt_List := New_List;
Variant := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
while Present (Variant) loop
Loc := Sloc (Variant);
Append_To (Alt_List,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices =>
New_Copy_List (Discrete_Choices (Variant)),
Statements =>
Build_Init_Statements (Component_List (Variant))));
Next_Non_Pragma (Variant);
end loop;
-- The expression of the case statement which is a reference
-- to one of the discriminants is replaced by the appropriate
-- formal parameter of the initialization procedure.
Append_To (Statement_List,
Make_Case_Statement (Loc,
Expression =>
New_Reference_To (Discriminal (
Entity (Name (Variant_Part (Comp_List)))), Loc),
Alternatives => Alt_List));
end if;
-- For a task record type, add the task create call and calls
-- to bind any interrupt (signal) entries.
if Is_Task_Record_Type (Rec_Type) then
-- In the case of the restricted run time the ATCB has already
-- been preallocated.
if Restricted_Profile then
Append_To (Statement_List,
Make_Assignment_Statement (Loc,
Name => Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name => Make_Identifier (Loc, Name_uTask_Id)),
Expression => Make_Attribute_Reference (Loc,
Prefix =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_uInit),
Selector_Name =>
Make_Identifier (Loc, Name_uATCB)),
Attribute_Name => Name_Unchecked_Access)));
end if;
Append_To (Statement_List, Make_Task_Create_Call (Rec_Type));
declare
Task_Type : constant Entity_Id :=
Corresponding_Concurrent_Type (Rec_Type);
Task_Decl : constant Node_Id := Parent (Task_Type);
Task_Def : constant Node_Id := Task_Definition (Task_Decl);
Vis_Decl : Node_Id;
Ent : Entity_Id;
begin
if Present (Task_Def) then
Vis_Decl := First (Visible_Declarations (Task_Def));
while Present (Vis_Decl) loop
Loc := Sloc (Vis_Decl);
if Nkind (Vis_Decl) = N_Attribute_Definition_Clause then
if Get_Attribute_Id (Chars (Vis_Decl)) =
Attribute_Address
then
Ent := Entity (Name (Vis_Decl));
if Ekind (Ent) = E_Entry then
Append_To (Statement_List,
Make_Procedure_Call_Statement (Loc,
Name => New_Reference_To (
RTE (RE_Bind_Interrupt_To_Entry), Loc),
Parameter_Associations => New_List (
Make_Selected_Component (Loc,
Prefix =>
Make_Identifier (Loc, Name_uInit),
Selector_Name =>
Make_Identifier (Loc, Name_uTask_Id)),
Entry_Index_Expression (
Loc, Ent, Empty, Task_Type),
Expression (Vis_Decl))));
end if;
end if;
end if;
Next (Vis_Decl);
end loop;
end if;
end;
end if;
-- For a protected type, add statements generated by
-- Make_Initialize_Protection.
if Is_Protected_Record_Type (Rec_Type) then
Append_List_To (Statement_List,
Make_Initialize_Protection (Rec_Type));
end if;
-- If no initializations when generated for component declarations
-- corresponding to this Statement_List, append a null statement
-- to the Statement_List to make it a valid Ada tree.
if Is_Empty_List (Statement_List) then
Append (New_Node (N_Null_Statement, Loc), Statement_List);
end if;
return Statement_List;
exception
when RE_Not_Available =>
return Empty_List;
end Build_Init_Statements;
-------------------------
-- Build_Record_Checks --
-------------------------
procedure Build_Record_Checks (S : Node_Id; Check_List : List_Id) is
Subtype_Mark_Id : Entity_Id;
begin
if Nkind (S) = N_Subtype_Indication then
Find_Type (Subtype_Mark (S));
Subtype_Mark_Id := Entity (Subtype_Mark (S));
-- Remaining processing depends on type
case Ekind (Subtype_Mark_Id) is
when Array_Kind =>
Constrain_Array (S, Check_List);
when others =>
null;
end case;
end if;
end Build_Record_Checks;
-------------------------------------------
-- Component_Needs_Simple_Initialization --
-------------------------------------------
function Component_Needs_Simple_Initialization
(T : Entity_Id) return Boolean
is
begin
return
Needs_Simple_Initialization (T)
and then not Is_RTE (T, RE_Tag)
and then not Is_RTE (T, RE_Vtable_Ptr)
-- Ada 2005 (AI-251): Check also the tag of abstract interfaces
and then not Is_RTE (T, RE_Interface_Tag);
end Component_Needs_Simple_Initialization;
---------------------
-- Constrain_Array --
---------------------
procedure Constrain_Array
(SI : Node_Id;
Check_List : List_Id)
is
C : constant Node_Id := Constraint (SI);
Number_Of_Constraints : Nat := 0;
Index : Node_Id;
S, T : Entity_Id;
begin
T := Entity (Subtype_Mark (SI));
if Ekind (T) in Access_Kind then
T := Designated_Type (T);
end if;
S := First (Constraints (C));
while Present (S) loop
Number_Of_Constraints := Number_Of_Constraints + 1;
Next (S);
end loop;
-- In either case, the index constraint must provide a discrete
-- range for each index of the array type and the type of each
-- discrete range must be the same as that of the corresponding
-- index. (RM 3.6.1)
S := First (Constraints (C));
Index := First_Index (T);
Analyze (Index);
-- Apply constraints to each index type
for J in 1 .. Number_Of_Constraints loop
Constrain_Index (Index, S, Check_List);
Next (Index);
Next (S);
end loop;
end Constrain_Array;
---------------------
-- Constrain_Index --
---------------------
procedure Constrain_Index
(Index : Node_Id;
S : Node_Id;
Check_List : List_Id)
is
T : constant Entity_Id := Etype (Index);
begin
if Nkind (S) = N_Range then
Process_Range_Expr_In_Decl (S, T, Check_List);
end if;
end Constrain_Index;
--------------------------------------
-- Parent_Subtype_Renaming_Discrims --
--------------------------------------
function Parent_Subtype_Renaming_Discrims return Boolean is
De : Entity_Id;
Dp : Entity_Id;
begin
if Base_Type (Pe) /= Pe then
return False;
end if;
if Etype (Pe) = Pe
or else not Has_Discriminants (Pe)
or else Is_Constrained (Pe)
or else Is_Tagged_Type (Pe)
then
return False;
end if;
-- If there are no explicit stored discriminants we have inherited
-- the root type discriminants so far, so no renamings occurred.
if First_Discriminant (Pe) = First_Stored_Discriminant (Pe) then
return False;
end if;
-- Check if we have done some trivial renaming of the parent
-- discriminants, i.e. someting like
--
-- type DT (X1,X2: int) is new PT (X1,X2);
De := First_Discriminant (Pe);
Dp := First_Discriminant (Etype (Pe));
while Present (De) loop
pragma Assert (Present (Dp));
if Corresponding_Discriminant (De) /= Dp then
return True;
end if;
Next_Discriminant (De);
Next_Discriminant (Dp);
end loop;
return Present (Dp);
end Parent_Subtype_Renaming_Discrims;
------------------------
-- Requires_Init_Proc --
------------------------
function Requires_Init_Proc (Rec_Id : Entity_Id) return Boolean is
Comp_Decl : Node_Id;
Id : Entity_Id;
Typ : Entity_Id;
begin
-- Definitely do not need one if specifically suppressed
if Suppress_Init_Proc (Rec_Id) then
return False;
end if;
-- If it is a type derived from a type with unknown discriminants,
-- we cannot build an initialization procedure for it.
if Has_Unknown_Discriminants (Rec_Id) then
return False;
end if;
-- Otherwise we need to generate an initialization procedure if
-- Is_CPP_Class is False and at least one of the following applies:
-- 1. Discriminants are present, since they need to be initialized
-- with the appropriate discriminant constraint expressions.
-- However, the discriminant of an unchecked union does not
-- count, since the discriminant is not present.
-- 2. The type is a tagged type, since the implicit Tag component
-- needs to be initialized with a pointer to the dispatch table.
-- 3. The type contains tasks
-- 4. One or more components has an initial value
-- 5. One or more components is for a type which itself requires
-- an initialization procedure.
-- 6. One or more components is a type that requires simple
-- initialization (see Needs_Simple_Initialization), except
-- that types Tag and Interface_Tag are excluded, since fields
-- of these types are initialized by other means.
-- 7. The type is the record type built for a task type (since at
-- the very least, Create_Task must be called)
-- 8. The type is the record type built for a protected type (since
-- at least Initialize_Protection must be called)
-- 9. The type is marked as a public entity. The reason we add this
-- case (even if none of the above apply) is to properly handle
-- Initialize_Scalars. If a package is compiled without an IS
-- pragma, and the client is compiled with an IS pragma, then
-- the client will think an initialization procedure is present
-- and call it, when in fact no such procedure is required, but
-- since the call is generated, there had better be a routine
-- at the other end of the call, even if it does nothing!)
-- Note: the reason we exclude the CPP_Class case is because in this
-- case the initialization is performed in the C++ side.
if Is_CPP_Class (Rec_Id) then
return False;
elsif not Restriction_Active (No_Initialize_Scalars)
and then Is_Public (Rec_Id)
then
return True;
elsif (Has_Discriminants (Rec_Id)
and then not Is_Unchecked_Union (Rec_Id))
or else Is_Tagged_Type (Rec_Id)
or else Is_Concurrent_Record_Type (Rec_Id)
or else Has_Task (Rec_Id)
then
return True;
end if;
Id := First_Component (Rec_Id);
while Present (Id) loop
Comp_Decl := Parent (Id);
Typ := Etype (Id);
if Present (Expression (Comp_Decl))
or else Has_Non_Null_Base_Init_Proc (Typ)
or else Component_Needs_Simple_Initialization (Typ)
then
return True;
end if;
Next_Component (Id);
end loop;
return False;
end Requires_Init_Proc;
-- Start of processing for Build_Record_Init_Proc
begin
Rec_Type := Defining_Identifier (N);
-- This may be full declaration of a private type, in which case
-- the visible entity is a record, and the private entity has been
-- exchanged with it in the private part of the current package.
-- The initialization procedure is built for the record type, which
-- is retrievable from the private entity.
if Is_Incomplete_Or_Private_Type (Rec_Type) then
Rec_Type := Underlying_Type (Rec_Type);
end if;
-- If there are discriminants, build the discriminant map to replace
-- discriminants by their discriminals in complex bound expressions.
-- These only arise for the corresponding records of protected types.
if Is_Concurrent_Record_Type (Rec_Type)
and then Has_Discriminants (Rec_Type)
then
declare
Disc : Entity_Id;
begin
Disc := First_Discriminant (Rec_Type);
while Present (Disc) loop
Append_Elmt (Disc, Discr_Map);
Append_Elmt (Discriminal (Disc), Discr_Map);
Next_Discriminant (Disc);
end loop;
end;
end if;
-- Derived types that have no type extension can use the initialization
-- procedure of their parent and do not need a procedure of their own.
-- This is only correct if there are no representation clauses for the
-- type or its parent, and if the parent has in fact been frozen so
-- that its initialization procedure exists.
if Is_Derived_Type (Rec_Type)
and then not Is_Tagged_Type (Rec_Type)
and then not Is_Unchecked_Union (Rec_Type)
and then not Has_New_Non_Standard_Rep (Rec_Type)
and then not Parent_Subtype_Renaming_Discrims
and then Has_Non_Null_Base_Init_Proc (Etype (Rec_Type))
then
Copy_TSS (Base_Init_Proc (Etype (Rec_Type)), Rec_Type);
-- Otherwise if we need an initialization procedure, then build one,
-- mark it as public and inlinable and as having a completion.
elsif Requires_Init_Proc (Rec_Type)
or else Is_Unchecked_Union (Rec_Type)
then
Build_Offset_To_Top_Functions;
Build_Init_Procedure;
Set_Is_Public (Proc_Id, Is_Public (Pe));
-- The initialization of protected records is not worth inlining.
-- In addition, when compiled for another unit for inlining purposes,
-- it may make reference to entities that have not been elaborated
-- yet. The initialization of controlled records contains a nested
-- clean-up procedure that makes it impractical to inline as well,
-- and leads to undefined symbols if inlined in a different unit.
-- Similar considerations apply to task types.
if not Is_Concurrent_Type (Rec_Type)
and then not Has_Task (Rec_Type)
and then not Controlled_Type (Rec_Type)
then
Set_Is_Inlined (Proc_Id);
end if;
Set_Is_Internal (Proc_Id);
Set_Has_Completion (Proc_Id);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Proc_Id);
end if;
end if;
end Build_Record_Init_Proc;
----------------------------
-- Build_Slice_Assignment --
----------------------------
-- Generates the following subprogram:
-- procedure Assign
-- (Source, Target : Array_Type,
-- Left_Lo, Left_Hi, Right_Lo, Right_Hi : Index;
-- Rev : Boolean)
-- is
-- Li1 : Index;
-- Ri1 : Index;
-- begin
-- if Rev then
-- Li1 := Left_Hi;
-- Ri1 := Right_Hi;
-- else
-- Li1 := Left_Lo;
-- Ri1 := Right_Lo;
-- end if;
-- loop
-- if Rev then
-- exit when Li1 < Left_Lo;
-- else
-- exit when Li1 > Left_Hi;
-- end if;
-- Target (Li1) := Source (Ri1);
-- if Rev then
-- Li1 := Index'pred (Li1);
-- Ri1 := Index'pred (Ri1);
-- else
-- Li1 := Index'succ (Li1);
-- Ri1 := Index'succ (Ri1);
-- end if;
-- end loop;
-- end Assign;
procedure Build_Slice_Assignment (Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (Typ);
Index : constant Entity_Id := Base_Type (Etype (First_Index (Typ)));
-- Build formal parameters of procedure
Larray : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('A'));
Rarray : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('R'));
Left_Lo : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('L'));
Left_Hi : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('L'));
Right_Lo : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('R'));
Right_Hi : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('R'));
Rev : constant Entity_Id :=
Make_Defining_Identifier
(Loc, Chars => New_Internal_Name ('D'));
Proc_Name : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => Make_TSS_Name (Typ, TSS_Slice_Assign));
Lnn : constant Entity_Id :=
Make_Defining_Identifier (Loc, New_Internal_Name ('L'));
Rnn : constant Entity_Id :=
Make_Defining_Identifier (Loc, New_Internal_Name ('R'));
-- Subscripts for left and right sides
Decls : List_Id;
Loops : Node_Id;
Stats : List_Id;
begin
-- Build declarations for indices
Decls := New_List;
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Lnn,
Object_Definition =>
New_Occurrence_Of (Index, Loc)));
Append_To (Decls,
Make_Object_Declaration (Loc,
Defining_Identifier => Rnn,
Object_Definition =>
New_Occurrence_Of (Index, Loc)));
Stats := New_List;
-- Build initializations for indices
declare
F_Init : constant List_Id := New_List;
B_Init : constant List_Id := New_List;
begin
Append_To (F_Init,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Lnn, Loc),
Expression => New_Occurrence_Of (Left_Lo, Loc)));
Append_To (F_Init,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Rnn, Loc),
Expression => New_Occurrence_Of (Right_Lo, Loc)));
Append_To (B_Init,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Lnn, Loc),
Expression => New_Occurrence_Of (Left_Hi, Loc)));
Append_To (B_Init,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Rnn, Loc),
Expression => New_Occurrence_Of (Right_Hi, Loc)));
Append_To (Stats,
Make_If_Statement (Loc,
Condition => New_Occurrence_Of (Rev, Loc),
Then_Statements => B_Init,
Else_Statements => F_Init));
end;
-- Now construct the assignment statement
Loops :=
Make_Loop_Statement (Loc,
Statements => New_List (
Make_Assignment_Statement (Loc,
Name =>
Make_Indexed_Component (Loc,
Prefix => New_Occurrence_Of (Larray, Loc),
Expressions => New_List (New_Occurrence_Of (Lnn, Loc))),
Expression =>
Make_Indexed_Component (Loc,
Prefix => New_Occurrence_Of (Rarray, Loc),
Expressions => New_List (New_Occurrence_Of (Rnn, Loc))))),
End_Label => Empty);
-- Build exit condition
declare
F_Ass : constant List_Id := New_List;
B_Ass : constant List_Id := New_List;
begin
Append_To (F_Ass,
Make_Exit_Statement (Loc,
Condition =>
Make_Op_Gt (Loc,
Left_Opnd => New_Occurrence_Of (Lnn, Loc),
Right_Opnd => New_Occurrence_Of (Left_Hi, Loc))));
Append_To (B_Ass,
Make_Exit_Statement (Loc,
Condition =>
Make_Op_Lt (Loc,
Left_Opnd => New_Occurrence_Of (Lnn, Loc),
Right_Opnd => New_Occurrence_Of (Left_Lo, Loc))));
Prepend_To (Statements (Loops),
Make_If_Statement (Loc,
Condition => New_Occurrence_Of (Rev, Loc),
Then_Statements => B_Ass,
Else_Statements => F_Ass));
end;
-- Build the increment/decrement statements
declare
F_Ass : constant List_Id := New_List;
B_Ass : constant List_Id := New_List;
begin
Append_To (F_Ass,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Lnn, Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Index, Loc),
Attribute_Name => Name_Succ,
Expressions => New_List (
New_Occurrence_Of (Lnn, Loc)))));
Append_To (F_Ass,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Rnn, Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Index, Loc),
Attribute_Name => Name_Succ,
Expressions => New_List (
New_Occurrence_Of (Rnn, Loc)))));
Append_To (B_Ass,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Lnn, Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Index, Loc),
Attribute_Name => Name_Pred,
Expressions => New_List (
New_Occurrence_Of (Lnn, Loc)))));
Append_To (B_Ass,
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Rnn, Loc),
Expression =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Index, Loc),
Attribute_Name => Name_Pred,
Expressions => New_List (
New_Occurrence_Of (Rnn, Loc)))));
Append_To (Statements (Loops),
Make_If_Statement (Loc,
Condition => New_Occurrence_Of (Rev, Loc),
Then_Statements => B_Ass,
Else_Statements => F_Ass));
end;
Append_To (Stats, Loops);
declare
Spec : Node_Id;
Formals : List_Id := New_List;
begin
Formals := New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Larray,
Out_Present => True,
Parameter_Type =>
New_Reference_To (Base_Type (Typ), Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Rarray,
Parameter_Type =>
New_Reference_To (Base_Type (Typ), Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Left_Lo,
Parameter_Type =>
New_Reference_To (Index, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Left_Hi,
Parameter_Type =>
New_Reference_To (Index, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Right_Lo,
Parameter_Type =>
New_Reference_To (Index, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Right_Hi,
Parameter_Type =>
New_Reference_To (Index, Loc)));
Append_To (Formals,
Make_Parameter_Specification (Loc,
Defining_Identifier => Rev,
Parameter_Type =>
New_Reference_To (Standard_Boolean, Loc)));
Spec :=
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Proc_Name,
Parameter_Specifications => Formals);
Discard_Node (
Make_Subprogram_Body (Loc,
Specification => Spec,
Declarations => Decls,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Stats)));
end;
Set_TSS (Typ, Proc_Name);
Set_Is_Pure (Proc_Name);
end Build_Slice_Assignment;
------------------------------------
-- Build_Variant_Record_Equality --
------------------------------------
-- Generates:
-- function _Equality (X, Y : T) return Boolean is
-- begin
-- -- Compare discriminants
-- if False or else X.D1 /= Y.D1 or else X.D2 /= Y.D2 then
-- return False;
-- end if;
-- -- Compare components
-- if False or else X.C1 /= Y.C1 or else X.C2 /= Y.C2 then
-- return False;
-- end if;
-- -- Compare variant part
-- case X.D1 is
-- when V1 =>
-- if False or else X.C2 /= Y.C2 or else X.C3 /= Y.C3 then
-- return False;
-- end if;
-- ...
-- when Vn =>
-- if False or else X.Cn /= Y.Cn then
-- return False;
-- end if;
-- end case;
-- return True;
-- end _Equality;
procedure Build_Variant_Record_Equality (Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (Typ);
F : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => Make_TSS_Name (Typ, TSS_Composite_Equality));
X : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => Name_X);
Y : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => Name_Y);
Def : constant Node_Id := Parent (Typ);
Comps : constant Node_Id := Component_List (Type_Definition (Def));
Stmts : constant List_Id := New_List;
Pspecs : constant List_Id := New_List;
begin
-- Derived Unchecked_Union types no longer inherit the equality function
-- of their parent.
if Is_Derived_Type (Typ)
and then not Is_Unchecked_Union (Typ)
and then not Has_New_Non_Standard_Rep (Typ)
then
declare
Parent_Eq : constant Entity_Id :=
TSS (Root_Type (Typ), TSS_Composite_Equality);
begin
if Present (Parent_Eq) then
Copy_TSS (Parent_Eq, Typ);
return;
end if;
end;
end if;
Discard_Node (
Make_Subprogram_Body (Loc,
Specification =>
Make_Function_Specification (Loc,
Defining_Unit_Name => F,
Parameter_Specifications => Pspecs,
Result_Definition => New_Reference_To (Standard_Boolean, Loc)),
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => Stmts)));
Append_To (Pspecs,
Make_Parameter_Specification (Loc,
Defining_Identifier => X,
Parameter_Type => New_Reference_To (Typ, Loc)));
Append_To (Pspecs,
Make_Parameter_Specification (Loc,
Defining_Identifier => Y,
Parameter_Type => New_Reference_To (Typ, Loc)));
-- Unchecked_Unions require additional machinery to support equality.
-- Two extra parameters (A and B) are added to the equality function
-- parameter list in order to capture the inferred values of the
-- discriminants in later calls.
if Is_Unchecked_Union (Typ) then
declare
Discr_Type : constant Node_Id := Etype (First_Discriminant (Typ));
A : constant Node_Id :=
Make_Defining_Identifier (Loc,
Chars => Name_A);
B : constant Node_Id :=
Make_Defining_Identifier (Loc,
Chars => Name_B);
begin
-- Add A and B to the parameter list
Append_To (Pspecs,
Make_Parameter_Specification (Loc,
Defining_Identifier => A,
Parameter_Type => New_Reference_To (Discr_Type, Loc)));
Append_To (Pspecs,
Make_Parameter_Specification (Loc,
Defining_Identifier => B,
Parameter_Type => New_Reference_To (Discr_Type, Loc)));
-- Generate the following header code to compare the inferred
-- discriminants:
-- if a /= b then
-- return False;
-- end if;
Append_To (Stmts,
Make_If_Statement (Loc,
Condition =>
Make_Op_Ne (Loc,
Left_Opnd => New_Reference_To (A, Loc),
Right_Opnd => New_Reference_To (B, Loc)),
Then_Statements => New_List (
Make_Return_Statement (Loc,
Expression => New_Occurrence_Of (Standard_False, Loc)))));
-- Generate component-by-component comparison. Note that we must
-- propagate one of the inferred discriminant formals to act as
-- the case statement switch.
Append_List_To (Stmts,
Make_Eq_Case (Typ, Comps, A));
end;
-- Normal case (not unchecked union)
else
Append_To (Stmts,
Make_Eq_If (Typ,
Discriminant_Specifications (Def)));
Append_List_To (Stmts,
Make_Eq_Case (Typ, Comps));
end if;
Append_To (Stmts,
Make_Return_Statement (Loc,
Expression => New_Reference_To (Standard_True, Loc)));
Set_TSS (Typ, F);
Set_Is_Pure (F);
if not Debug_Generated_Code then
Set_Debug_Info_Off (F);
end if;
end Build_Variant_Record_Equality;
-----------------------------
-- Check_Stream_Attributes --
-----------------------------
procedure Check_Stream_Attributes (Typ : Entity_Id) is
Comp : Entity_Id;
Par_Read : constant Boolean :=
Stream_Attribute_Available (Typ, TSS_Stream_Read)
and then not Has_Specified_Stream_Read (Typ);
Par_Write : constant Boolean :=
Stream_Attribute_Available (Typ, TSS_Stream_Write)
and then not Has_Specified_Stream_Write (Typ);
procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type);
-- Check that Comp has a user-specified Nam stream attribute
----------------
-- Check_Attr --
----------------
procedure Check_Attr (Nam : Name_Id; TSS_Nam : TSS_Name_Type) is
begin
if not Stream_Attribute_Available (Etype (Comp), TSS_Nam) then
Error_Msg_Name_1 := Nam;
Error_Msg_N
("|component& in limited extension must have% attribute", Comp);
end if;
end Check_Attr;
-- Start of processing for Check_Stream_Attributes
begin
if Par_Read or else Par_Write then
Comp := First_Component (Typ);
while Present (Comp) loop
if Comes_From_Source (Comp)
and then Original_Record_Component (Comp) = Comp
and then Is_Limited_Type (Etype (Comp))
then
if Par_Read then
Check_Attr (Name_Read, TSS_Stream_Read);
end if;
if Par_Write then
Check_Attr (Name_Write, TSS_Stream_Write);
end if;
end if;
Next_Component (Comp);
end loop;
end if;
end Check_Stream_Attributes;
-----------------------------
-- Expand_Record_Extension --
-----------------------------
-- Add a field _parent at the beginning of the record extension. This is
-- used to implement inheritance. Here are some examples of expansion:
-- 1. no discriminants
-- type T2 is new T1 with null record;
-- gives
-- type T2 is new T1 with record
-- _Parent : T1;
-- end record;
-- 2. renamed discriminants
-- type T2 (B, C : Int) is new T1 (A => B) with record
-- _Parent : T1 (A => B);
-- D : Int;
-- end;
-- 3. inherited discriminants
-- type T2 is new T1 with record -- discriminant A inherited
-- _Parent : T1 (A);
-- D : Int;
-- end;
procedure Expand_Record_Extension (T : Entity_Id; Def : Node_Id) is
Indic : constant Node_Id := Subtype_Indication (Def);
Loc : constant Source_Ptr := Sloc (Def);
Rec_Ext_Part : Node_Id := Record_Extension_Part (Def);
Par_Subtype : Entity_Id;
Comp_List : Node_Id;
Comp_Decl : Node_Id;
Parent_N : Node_Id;
D : Entity_Id;
List_Constr : constant List_Id := New_List;
begin
-- Expand_Record_Extension is called directly from the semantics, so
-- we must check to see whether expansion is active before proceeding
if not Expander_Active then
return;
end if;
-- This may be a derivation of an untagged private type whose full
-- view is tagged, in which case the Derived_Type_Definition has no
-- extension part. Build an empty one now.
if No (Rec_Ext_Part) then
Rec_Ext_Part :=
Make_Record_Definition (Loc,
End_Label => Empty,
Component_List => Empty,
Null_Present => True);
Set_Record_Extension_Part (Def, Rec_Ext_Part);
Mark_Rewrite_Insertion (Rec_Ext_Part);
end if;
Comp_List := Component_List (Rec_Ext_Part);
Parent_N := Make_Defining_Identifier (Loc, Name_uParent);
-- If the derived type inherits its discriminants the type of the
-- _parent field must be constrained by the inherited discriminants
if Has_Discriminants (T)
and then Nkind (Indic) /= N_Subtype_Indication
and then not Is_Constrained (Entity (Indic))
then
D := First_Discriminant (T);
while Present (D) loop
Append_To (List_Constr, New_Occurrence_Of (D, Loc));
Next_Discriminant (D);
end loop;
Par_Subtype :=
Process_Subtype (
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Reference_To (Entity (Indic), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => List_Constr)),
Def);
-- Otherwise the original subtype_indication is just what is needed
else
Par_Subtype := Process_Subtype (New_Copy_Tree (Indic), Def);
end if;
Set_Parent_Subtype (T, Par_Subtype);
Comp_Decl :=
Make_Component_Declaration (Loc,
Defining_Identifier => Parent_N,
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication => New_Reference_To (Par_Subtype, Loc)));
if Null_Present (Rec_Ext_Part) then
Set_Component_List (Rec_Ext_Part,
Make_Component_List (Loc,
Component_Items => New_List (Comp_Decl),
Variant_Part => Empty,
Null_Present => False));
Set_Null_Present (Rec_Ext_Part, False);
elsif Null_Present (Comp_List)
or else Is_Empty_List (Component_Items (Comp_List))
then
Set_Component_Items (Comp_List, New_List (Comp_Decl));
Set_Null_Present (Comp_List, False);
else
Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
end if;
Analyze (Comp_Decl);
end Expand_Record_Extension;
------------------------------------
-- Expand_N_Full_Type_Declaration --
------------------------------------
procedure Expand_N_Full_Type_Declaration (N : Node_Id) is
Def_Id : constant Entity_Id := Defining_Identifier (N);
B_Id : constant Entity_Id := Base_Type (Def_Id);
Par_Id : Entity_Id;
FN : Node_Id;
begin
if Is_Access_Type (Def_Id) then
-- Anonymous access types are created for the components of the
-- record parameter for an entry declaration. No master is created
-- for such a type.
if Has_Task (Designated_Type (Def_Id))
and then Comes_From_Source (N)
then
Build_Master_Entity (Def_Id);
Build_Master_Renaming (Parent (Def_Id), Def_Id);
-- Create a class-wide master because a Master_Id must be generated
-- for access-to-limited-class-wide types whose root may be extended
-- with task components, and for access-to-limited-interfaces because
-- they can be used to reference tasks implementing such interface.
elsif Is_Class_Wide_Type (Designated_Type (Def_Id))
and then (Is_Limited_Type (Designated_Type (Def_Id))
or else
(Is_Interface (Designated_Type (Def_Id))
and then
Is_Limited_Interface (Designated_Type (Def_Id))))
and then Tasking_Allowed
-- Do not create a class-wide master for types whose convention is
-- Java since these types cannot embed Ada tasks anyway. Note that
-- the following test cannot catch the following case:
-- package java.lang.Object is
-- type Typ is tagged limited private;
-- type Ref is access all Typ'Class;
-- private
-- type Typ is tagged limited ...;
-- pragma Convention (Typ, Java)
-- end;
-- Because the convention appears after we have done the
-- processing for type Ref.
and then Convention (Designated_Type (Def_Id)) /= Convention_Java
then
Build_Class_Wide_Master (Def_Id);
elsif Ekind (Def_Id) = E_Access_Protected_Subprogram_Type then
Expand_Access_Protected_Subprogram_Type (N);
end if;
elsif Has_Task (Def_Id) then
Expand_Previous_Access_Type (Def_Id);
end if;
Par_Id := Etype (B_Id);
-- The parent type is private then we need to inherit
-- any TSS operations from the full view.
if Ekind (Par_Id) in Private_Kind
and then Present (Full_View (Par_Id))
then
Par_Id := Base_Type (Full_View (Par_Id));
end if;
if Nkind (Type_Definition (Original_Node (N)))
= N_Derived_Type_Definition
and then not Is_Tagged_Type (Def_Id)
and then Present (Freeze_Node (Par_Id))
and then Present (TSS_Elist (Freeze_Node (Par_Id)))
then
Ensure_Freeze_Node (B_Id);
FN := Freeze_Node (B_Id);
if No (TSS_Elist (FN)) then
Set_TSS_Elist (FN, New_Elmt_List);
end if;
declare
T_E : constant Elist_Id := TSS_Elist (FN);
Elmt : Elmt_Id;
begin
Elmt := First_Elmt (TSS_Elist (Freeze_Node (Par_Id)));
while Present (Elmt) loop
if Chars (Node (Elmt)) /= Name_uInit then
Append_Elmt (Node (Elmt), T_E);
end if;
Next_Elmt (Elmt);
end loop;
-- If the derived type itself is private with a full view, then
-- associate the full view with the inherited TSS_Elist as well.
if Ekind (B_Id) in Private_Kind
and then Present (Full_View (B_Id))
then
Ensure_Freeze_Node (Base_Type (Full_View (B_Id)));
Set_TSS_Elist
(Freeze_Node (Base_Type (Full_View (B_Id))), TSS_Elist (FN));
end if;
end;
end if;
end Expand_N_Full_Type_Declaration;
---------------------------------
-- Expand_N_Object_Declaration --
---------------------------------
-- First we do special processing for objects of a tagged type where this
-- is the point at which the type is frozen. The creation of the dispatch
-- table and the initialization procedure have to be deferred to this
-- point, since we reference previously declared primitive subprograms.
-- For all types, we call an initialization procedure if there is one
procedure Expand_N_Object_Declaration (N : Node_Id) is
Def_Id : constant Entity_Id := Defining_Identifier (N);
Typ : constant Entity_Id := Etype (Def_Id);
Loc : constant Source_Ptr := Sloc (N);
Expr : constant Node_Id := Expression (N);
New_Ref : Node_Id;
Id_Ref : Node_Id;
Expr_Q : Node_Id;
begin
-- Don't do anything for deferred constants. All proper actions will
-- be expanded during the full declaration.
if No (Expr) and Constant_Present (N) then
return;
end if;
-- Make shared memory routines for shared passive variable
if Is_Shared_Passive (Def_Id) then
Make_Shared_Var_Procs (N);
end if;
-- If tasks being declared, make sure we have an activation chain
-- defined for the tasks (has no effect if we already have one), and
-- also that a Master variable is established and that the appropriate
-- enclosing construct is established as a task master.
if Has_Task (Typ) then
Build_Activation_Chain_Entity (N);
Build_Master_Entity (Def_Id);
end if;
-- Default initialization required, and no expression present
if No (Expr) then
-- Expand Initialize call for controlled objects. One may wonder why
-- the Initialize Call is not done in the regular Init procedure
-- attached to the record type. That's because the init procedure is
-- recursively called on each component, including _Parent, thus the
-- Init call for a controlled object would generate not only one
-- Initialize call as it is required but one for each ancestor of
-- its type. This processing is suppressed if No_Initialization set.
if not Controlled_Type (Typ)
or else No_Initialization (N)
then
null;
elsif not Abort_Allowed
or else not Comes_From_Source (N)
then
Insert_Actions_After (N,
Make_Init_Call (
Ref => New_Occurrence_Of (Def_Id, Loc),
Typ => Base_Type (Typ),
Flist_Ref => Find_Final_List (Def_Id),
With_Attach => Make_Integer_Literal (Loc, 1)));
-- Abort allowed
else
-- We need to protect the initialize call
-- begin
-- Defer_Abort.all;
-- Initialize (...);
-- at end
-- Undefer_Abort.all;
-- end;
-- ??? this won't protect the initialize call for controlled
-- components which are part of the init proc, so this block
-- should probably also contain the call to _init_proc but this
-- requires some code reorganization...
declare
L : constant List_Id :=
Make_Init_Call (
Ref => New_Occurrence_Of (Def_Id, Loc),
Typ => Base_Type (Typ),
Flist_Ref => Find_Final_List (Def_Id),
With_Attach => Make_Integer_Literal (Loc, 1));
Blk : constant Node_Id :=
Make_Block_Statement (Loc,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc, L));
begin
Prepend_To (L, Build_Runtime_Call (Loc, RE_Abort_Defer));
Set_At_End_Proc (Handled_Statement_Sequence (Blk),
New_Occurrence_Of (RTE (RE_Abort_Undefer_Direct), Loc));
Insert_Actions_After (N, New_List (Blk));
Expand_At_End_Handler
(Handled_Statement_Sequence (Blk), Entity (Identifier (Blk)));
end;
end if;
-- Call type initialization procedure if there is one. We build the
-- call and put it immediately after the object declaration, so that
-- it will be expanded in the usual manner. Note that this will
-- result in proper handling of defaulted discriminants. The call
-- to the Init_Proc is suppressed if No_Initialization is set.
if Has_Non_Null_Base_Init_Proc (Typ)
and then not No_Initialization (N)
then
-- The call to the initialization procedure does NOT freeze
-- the object being initialized. This is because the call is
-- not a source level call. This works fine, because the only
-- possible statements depending on freeze status that can
-- appear after the _Init call are rep clauses which can
-- safely appear after actual references to the object.
Id_Ref := New_Reference_To (Def_Id, Loc);
Set_Must_Not_Freeze (Id_Ref);
Set_Assignment_OK (Id_Ref);
Insert_Actions_After (N,
Build_Initialization_Call (Loc, Id_Ref, Typ));
-- If simple initialization is required, then set an appropriate
-- simple initialization expression in place. This special
-- initialization is required even though No_Init_Flag is present.
-- An internally generated temporary needs no initialization because
-- it will be assigned subsequently. In particular, there is no
-- point in applying Initialize_Scalars to such a temporary.
elsif Needs_Simple_Initialization (Typ)
and then not Is_Internal (Def_Id)
then
Set_No_Initialization (N, False);
Set_Expression (N, Get_Simple_Init_Val (Typ, Loc, Esize (Def_Id)));
Analyze_And_Resolve (Expression (N), Typ);
end if;
-- Generate attribute for Persistent_BSS if needed
if Persistent_BSS_Mode
and then Comes_From_Source (N)
and then Is_Potentially_Persistent_Type (Typ)
and then Is_Library_Level_Entity (Def_Id)
then
declare
Prag : Node_Id;
begin
Prag :=
Make_Linker_Section_Pragma
(Def_Id, Sloc (N), ".persistent.bss");
Insert_After (N, Prag);
Analyze (Prag);
end;
end if;
-- If access type, then we know it is null if not initialized
if Is_Access_Type (Typ) then
Set_Is_Known_Null (Def_Id);
end if;
-- Explicit initialization present
else
-- Obtain actual expression from qualified expression
if Nkind (Expr) = N_Qualified_Expression then
Expr_Q := Expression (Expr);
else
Expr_Q := Expr;
end if;
-- When we have the appropriate type of aggregate in the expression
-- (it has been determined during analysis of the aggregate by
-- setting the delay flag), let's perform in place assignment and
-- thus avoid creating a temporary.
if Is_Delayed_Aggregate (Expr_Q) then
Convert_Aggr_In_Object_Decl (N);
else
-- In most cases, we must check that the initial value meets any
-- constraint imposed by the declared type. However, there is one
-- very important exception to this rule. If the entity has an
-- unconstrained nominal subtype, then it acquired its constraints
-- from the expression in the first place, and not only does this
-- mean that the constraint check is not needed, but an attempt to
-- perform the constraint check can cause order order of
-- elaboration problems.
if not Is_Constr_Subt_For_U_Nominal (Typ) then
-- If this is an allocator for an aggregate that has been
-- allocated in place, delay checks until assignments are
-- made, because the discriminants are not initialized.
if Nkind (Expr) = N_Allocator
and then No_Initialization (Expr)
then
null;
else
Apply_Constraint_Check (Expr, Typ);
end if;
end if;
-- If the type is controlled we attach the object to the final
-- list and adjust the target after the copy. This
-- ??? incomplete sentence
if Controlled_Type (Typ) then
declare
Flist : Node_Id;
F : Entity_Id;
begin
-- Attach the result to a dummy final list which will never
-- be finalized if Delay_Finalize_Attachis set. It is
-- important to attach to a dummy final list rather than not
-- attaching at all in order to reset the pointers coming
-- from the initial value. Equivalent code exists in the
-- sec-stack case in Exp_Ch4.Expand_N_Allocator.
if Delay_Finalize_Attach (N) then
F :=
Make_Defining_Identifier (Loc, New_Internal_Name ('F'));
Insert_Action (N,
Make_Object_Declaration (Loc,
Defining_Identifier => F,
Object_Definition =>
New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
Flist := New_Reference_To (F, Loc);
else
Flist := Find_Final_List (Def_Id);
end if;
Insert_Actions_After (N,
Make_Adjust_Call (
Ref => New_Reference_To (Def_Id, Loc),
Typ => Base_Type (Typ),
Flist_Ref => Flist,
With_Attach => Make_Integer_Literal (Loc, 1)));
end;
end if;
-- For tagged types, when an init value is given, the tag has to
-- be re-initialized separately in order to avoid the propagation
-- of a wrong tag coming from a view conversion unless the type
-- is class wide (in this case the tag comes from the init value).
-- Suppress the tag assignment when Java_VM because JVM tags are
-- represented implicitly in objects. Ditto for types that are
-- CPP_CLASS, and for initializations that are aggregates, because
-- they have to have the right tag.
if Is_Tagged_Type (Typ)
and then not Is_Class_Wide_Type (Typ)
and then not Is_CPP_Class (Typ)
and then not Java_VM
and then Nkind (Expr) /= N_Aggregate
then
-- The re-assignment of the tag has to be done even if the
-- object is a constant.
New_Ref :=
Make_Selected_Component (Loc,
Prefix => New_Reference_To (Def_Id, Loc),
Selector_Name =>
New_Reference_To (First_Tag_Component (Typ), Loc));
Set_Assignment_OK (New_Ref);
Insert_After (N,
Make_Assignment_Statement (Loc,
Name => New_Ref,
Expression =>
Unchecked_Convert_To (RTE (RE_Tag),
New_Reference_To
(Node
(First_Elmt
(Access_Disp_Table (Base_Type (Typ)))),
Loc))));
-- For discrete types, set the Is_Known_Valid flag if the
-- initializing value is known to be valid.
elsif Is_Discrete_Type (Typ) and then Expr_Known_Valid (Expr) then
Set_Is_Known_Valid (Def_Id);
elsif Is_Access_Type (Typ) then
-- For access types set the Is_Known_Non_Null flag if the
-- initializing value is known to be non-null. We can also set
-- Can_Never_Be_Null if this is a constant.
if Known_Non_Null (Expr) then
Set_Is_Known_Non_Null (Def_Id, True);
if Constant_Present (N) then
Set_Can_Never_Be_Null (Def_Id);
end if;
end if;
end if;
-- If validity checking on copies, validate initial expression
if Validity_Checks_On
and then Validity_Check_Copies
then
Ensure_Valid (Expr);
Set_Is_Known_Valid (Def_Id);
end if;
end if;
-- Cases where the back end cannot handle the initialization directly
-- In such cases, we expand an assignment that will be appropriately
-- handled by Expand_N_Assignment_Statement.
-- The exclusion of the unconstrained case is wrong, but for now it
-- is too much trouble ???
if (Is_Possibly_Unaligned_Slice (Expr)
or else (Is_Possibly_Unaligned_Object (Expr)
and then not Represented_As_Scalar (Etype (Expr))))
-- The exclusion of the unconstrained case is wrong, but for now
-- it is too much trouble ???
and then not (Is_Array_Type (Etype (Expr))
and then not Is_Constrained (Etype (Expr)))
then
declare
Stat : constant Node_Id :=
Make_Assignment_Statement (Loc,
Name => New_Reference_To (Def_Id, Loc),
Expression => Relocate_Node (Expr));
begin
Set_Expression (N, Empty);
Set_No_Initialization (N);
Set_Assignment_OK (Name (Stat));
Set_No_Ctrl_Actions (Stat);
Insert_After (N, Stat);
Analyze (Stat);
end;
end if;
end if;
-- For array type, check for size too large
-- We really need this for record types too???
if Is_Array_Type (Typ) then
Apply_Array_Size_Check (N, Typ);
end if;
exception
when RE_Not_Available =>
return;
end Expand_N_Object_Declaration;
---------------------------------
-- Expand_N_Subtype_Indication --
---------------------------------
-- Add a check on the range of the subtype. The static case is partially
-- duplicated by Process_Range_Expr_In_Decl in Sem_Ch3, but we still need
-- to check here for the static case in order to avoid generating
-- extraneous expanded code.
procedure Expand_N_Subtype_Indication (N : Node_Id) is
Ran : constant Node_Id := Range_Expression (Constraint (N));
Typ : constant Entity_Id := Entity (Subtype_Mark (N));
begin
if Nkind (Parent (N)) = N_Constrained_Array_Definition or else
Nkind (Parent (N)) = N_Slice
then
Resolve (Ran, Typ);
Apply_Range_Check (Ran, Typ);
end if;
end Expand_N_Subtype_Indication;
---------------------------
-- Expand_N_Variant_Part --
---------------------------
-- If the last variant does not contain the Others choice, replace it with
-- an N_Others_Choice node since Gigi always wants an Others. Note that we
-- do not bother to call Analyze on the modified variant part, since it's
-- only effect would be to compute the contents of the
-- Others_Discrete_Choices node laboriously, and of course we already know
-- the list of choices that corresponds to the others choice (it's the
-- list we are replacing!)
procedure Expand_N_Variant_Part (N : Node_Id) is
Last_Var : constant Node_Id := Last_Non_Pragma (Variants (N));
Others_Node : Node_Id;
begin
if Nkind (First (Discrete_Choices (Last_Var))) /= N_Others_Choice then
Others_Node := Make_Others_Choice (Sloc (Last_Var));
Set_Others_Discrete_Choices
(Others_Node, Discrete_Choices (Last_Var));
Set_Discrete_Choices (Last_Var, New_List (Others_Node));
end if;
end Expand_N_Variant_Part;
---------------------------------
-- Expand_Previous_Access_Type --
---------------------------------
procedure Expand_Previous_Access_Type (Def_Id : Entity_Id) is
T : Entity_Id := First_Entity (Current_Scope);
begin
-- Find all access types declared in the current scope, whose
-- designated type is Def_Id.
while Present (T) loop
if Is_Access_Type (T)
and then Designated_Type (T) = Def_Id
then
Build_Master_Entity (Def_Id);
Build_Master_Renaming (Parent (Def_Id), T);
end if;
Next_Entity (T);
end loop;
end Expand_Previous_Access_Type;
------------------------------
-- Expand_Record_Controller --
------------------------------
procedure Expand_Record_Controller (T : Entity_Id) is
Def : Node_Id := Type_Definition (Parent (T));
Comp_List : Node_Id;
Comp_Decl : Node_Id;
Loc : Source_Ptr;
First_Comp : Node_Id;
Controller_Type : Entity_Id;
Ent : Entity_Id;
begin
if Nkind (Def) = N_Derived_Type_Definition then
Def := Record_Extension_Part (Def);
end if;
if Null_Present (Def) then
Set_Component_List (Def,
Make_Component_List (Sloc (Def),
Component_Items => Empty_List,
Variant_Part => Empty,
Null_Present => True));
end if;
Comp_List := Component_List (Def);
if Null_Present (Comp_List)
or else Is_Empty_List (Component_Items (Comp_List))
then
Loc := Sloc (Comp_List);
else
Loc := Sloc (First (Component_Items (Comp_List)));
end if;
if Is_Return_By_Reference_Type (T) then
Controller_Type := RTE (RE_Limited_Record_Controller);
else
Controller_Type := RTE (RE_Record_Controller);
end if;
Ent := Make_Defining_Identifier (Loc, Name_uController);
Comp_Decl :=
Make_Component_Declaration (Loc,
Defining_Identifier => Ent,
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication => New_Reference_To (Controller_Type, Loc)));
if Null_Present (Comp_List)
or else Is_Empty_List (Component_Items (Comp_List))
then
Set_Component_Items (Comp_List, New_List (Comp_Decl));
Set_Null_Present (Comp_List, False);
else
-- The controller cannot be placed before the _Parent field since
-- gigi lays out field in order and _parent must be first to
-- preserve the polymorphism of tagged types.
First_Comp := First (Component_Items (Comp_List));
if Chars (Defining_Identifier (First_Comp)) /= Name_uParent
and then Chars (Defining_Identifier (First_Comp)) /= Name_uTag
then
Insert_Before (First_Comp, Comp_Decl);
else
Insert_After (First_Comp, Comp_Decl);
end if;
end if;
New_Scope (T);
Analyze (Comp_Decl);
Set_Ekind (Ent, E_Component);
Init_Component_Location (Ent);
-- Move the _controller entity ahead in the list of internal entities
-- of the enclosing record so that it is selected instead of a
-- potentially inherited one.
declare
E : constant Entity_Id := Last_Entity (T);
Comp : Entity_Id;
begin
pragma Assert (Chars (E) = Name_uController);
Set_Next_Entity (E, First_Entity (T));
Set_First_Entity (T, E);
Comp := Next_Entity (E);
while Next_Entity (Comp) /= E loop
Next_Entity (Comp);
end loop;
Set_Next_Entity (Comp, Empty);
Set_Last_Entity (T, Comp);
end;
End_Scope;
exception
when RE_Not_Available =>
return;
end Expand_Record_Controller;
------------------------
-- Expand_Tagged_Root --
------------------------
procedure Expand_Tagged_Root (T : Entity_Id) is
Def : constant Node_Id := Type_Definition (Parent (T));
Comp_List : Node_Id;
Comp_Decl : Node_Id;
Sloc_N : Source_Ptr;
begin
if Null_Present (Def) then
Set_Component_List (Def,
Make_Component_List (Sloc (Def),
Component_Items => Empty_List,
Variant_Part => Empty,
Null_Present => True));
end if;
Comp_List := Component_List (Def);
if Null_Present (Comp_List)
or else Is_Empty_List (Component_Items (Comp_List))
then
Sloc_N := Sloc (Comp_List);
else
Sloc_N := Sloc (First (Component_Items (Comp_List)));
end if;
Comp_Decl :=
Make_Component_Declaration (Sloc_N,
Defining_Identifier => First_Tag_Component (T),
Component_Definition =>
Make_Component_Definition (Sloc_N,
Aliased_Present => False,
Subtype_Indication => New_Reference_To (RTE (RE_Tag), Sloc_N)));
if Null_Present (Comp_List)
or else Is_Empty_List (Component_Items (Comp_List))
then
Set_Component_Items (Comp_List, New_List (Comp_Decl));
Set_Null_Present (Comp_List, False);
else
Insert_Before (First (Component_Items (Comp_List)), Comp_Decl);
end if;
-- We don't Analyze the whole expansion because the tag component has
-- already been analyzed previously. Here we just insure that the tree
-- is coherent with the semantic decoration
Find_Type (Subtype_Indication (Component_Definition (Comp_Decl)));
exception
when RE_Not_Available =>
return;
end Expand_Tagged_Root;
-----------------------
-- Freeze_Array_Type --
-----------------------
procedure Freeze_Array_Type (N : Node_Id) is
Typ : constant Entity_Id := Entity (N);
Base : constant Entity_Id := Base_Type (Typ);
begin
if not Is_Bit_Packed_Array (Typ) then
-- If the component contains tasks, so does the array type. This may
-- not be indicated in the array type because the component may have
-- been a private type at the point of definition. Same if component
-- type is controlled.
Set_Has_Task (Base, Has_Task (Component_Type (Typ)));
Set_Has_Controlled_Component (Base,
Has_Controlled_Component (Component_Type (Typ))
or else Is_Controlled (Component_Type (Typ)));
if No (Init_Proc (Base)) then
-- If this is an anonymous array created for a declaration with
-- an initial value, its init_proc will never be called. The
-- initial value itself may have been expanded into assign-
-- ments, in which case the object declaration is carries the
-- No_Initialization flag.
if Is_Itype (Base)
and then Nkind (Associated_Node_For_Itype (Base)) =
N_Object_Declaration
and then (Present (Expression (Associated_Node_For_Itype (Base)))
or else
No_Initialization (Associated_Node_For_Itype (Base)))
then
null;
-- We do not need an init proc for string or wide [wide] string,
-- since the only time these need initialization in normalize or
-- initialize scalars mode, and these types are treated specially
-- and do not need initialization procedures.
elsif Root_Type (Base) = Standard_String
or else Root_Type (Base) = Standard_Wide_String
or else Root_Type (Base) = Standard_Wide_Wide_String
then
null;
-- Otherwise we have to build an init proc for the subtype
else
Build_Array_Init_Proc (Base, N);
end if;
end if;
if Typ = Base and then Has_Controlled_Component (Base) then
Build_Controlling_Procs (Base);
if not Is_Limited_Type (Component_Type (Typ))
and then Number_Dimensions (Typ) = 1
then
Build_Slice_Assignment (Typ);
end if;
end if;
-- For packed case, there is a default initialization, except if the
-- component type is itself a packed structure with an initialization
-- procedure.
elsif Present (Init_Proc (Component_Type (Base)))
and then No (Base_Init_Proc (Base))
then
Build_Array_Init_Proc (Base, N);
end if;
end Freeze_Array_Type;
-----------------------------
-- Freeze_Enumeration_Type --
-----------------------------
procedure Freeze_Enumeration_Type (N : Node_Id) is
Typ : constant Entity_Id := Entity (N);
Loc : constant Source_Ptr := Sloc (Typ);
Ent : Entity_Id;
Lst : List_Id;
Num : Nat;
Arr : Entity_Id;
Fent : Entity_Id;
Ityp : Entity_Id;
Is_Contiguous : Boolean;
Pos_Expr : Node_Id;
Last_Repval : Uint;
Func : Entity_Id;
pragma Warnings (Off, Func);
begin
-- Various optimization are possible if the given representation is
-- contiguous.
Is_Contiguous := True;
Ent := First_Literal (Typ);
Last_Repval := Enumeration_Rep (Ent);
Next_Literal (Ent);
while Present (Ent) loop
if Enumeration_Rep (Ent) - Last_Repval /= 1 then
Is_Contiguous := False;
exit;
else
Last_Repval := Enumeration_Rep (Ent);
end if;
Next_Literal (Ent);
end loop;
if Is_Contiguous then
Set_Has_Contiguous_Rep (Typ);
Ent := First_Literal (Typ);
Num := 1;
Lst := New_List (New_Reference_To (Ent, Sloc (Ent)));
else
-- Build list of literal references
Lst := New_List;
Num := 0;
Ent := First_Literal (Typ);
while Present (Ent) loop
Append_To (Lst, New_Reference_To (Ent, Sloc (Ent)));
Num := Num + 1;
Next_Literal (Ent);
end loop;
end if;
-- Now build an array declaration
-- typA : array (Natural range 0 .. num - 1) of ctype :=
-- (v, v, v, v, v, ....)
-- where ctype is the corresponding integer type. If the representation
-- is contiguous, we only keep the first literal, which provides the
-- offset for Pos_To_Rep computations.
Arr :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Typ), 'A'));
Append_Freeze_Action (Typ,
Make_Object_Declaration (Loc,
Defining_Identifier => Arr,
Constant_Present => True,
Object_Definition =>
Make_Constrained_Array_Definition (Loc,
Discrete_Subtype_Definitions => New_List (
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Reference_To (Standard_Natural, Loc),
Constraint =>
Make_Range_Constraint (Loc,
Range_Expression =>
Make_Range (Loc,
Low_Bound =>
Make_Integer_Literal (Loc, 0),
High_Bound =>
Make_Integer_Literal (Loc, Num - 1))))),
Component_Definition =>
Make_Component_Definition (Loc,
Aliased_Present => False,
Subtype_Indication => New_Reference_To (Typ, Loc))),
Expression =>
Make_Aggregate (Loc,
Expressions => Lst)));
Set_Enum_Pos_To_Rep (Typ, Arr);
-- Now we build the function that converts representation values to
-- position values. This function has the form:
-- function _Rep_To_Pos (A : etype; F : Boolean) return Integer is
-- begin
-- case ityp!(A) is
-- when enum-lit'Enum_Rep => return posval;
-- when enum-lit'Enum_Rep => return posval;
-- ...
-- when others =>
-- [raise Constraint_Error when F "invalid data"]
-- return -1;
-- end case;
-- end;
-- Note: the F parameter determines whether the others case (no valid
-- representation) raises Constraint_Error or returns a unique value
-- of minus one. The latter case is used, e.g. in 'Valid code.
-- Note: the reason we use Enum_Rep values in the case here is to avoid
-- the code generator making inappropriate assumptions about the range
-- of the values in the case where the value is invalid. ityp is a
-- signed or unsigned integer type of appropriate width.
-- Note: if exceptions are not supported, then we suppress the raise
-- and return -1 unconditionally (this is an erroneous program in any
-- case and there is no obligation to raise Constraint_Error here!) We
-- also do this if pragma Restrictions (No_Exceptions) is active.
-- Representations are signed
if Enumeration_Rep (First_Literal (Typ)) < 0 then
-- The underlying type is signed. Reset the Is_Unsigned_Type
-- explicitly, because it might have been inherited from
-- parent type.
Set_Is_Unsigned_Type (Typ, False);
if Esize (Typ) <= Standard_Integer_Size then
Ityp := Standard_Integer;
else
Ityp := Universal_Integer;
end if;
-- Representations are unsigned
else
if Esize (Typ) <= Standard_Integer_Size then
Ityp := RTE (RE_Unsigned);
else
Ityp := RTE (RE_Long_Long_Unsigned);
end if;
end if;
-- The body of the function is a case statement. First collect case
-- alternatives, or optimize the contiguous case.
Lst := New_List;
-- If representation is contiguous, Pos is computed by subtracting
-- the representation of the first literal.
if Is_Contiguous then
Ent := First_Literal (Typ);
if Enumeration_Rep (Ent) = Last_Repval then
-- Another special case: for a single literal, Pos is zero
Pos_Expr := Make_Integer_Literal (Loc, Uint_0);
else
Pos_Expr :=
Convert_To (Standard_Integer,
Make_Op_Subtract (Loc,
Left_Opnd =>
Unchecked_Convert_To (Ityp,
Make_Identifier (Loc, Name_uA)),
Right_Opnd =>
Make_Integer_Literal (Loc,
Intval =>
Enumeration_Rep (First_Literal (Typ)))));
end if;
Append_To (Lst,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices => New_List (
Make_Range (Sloc (Enumeration_Rep_Expr (Ent)),
Low_Bound =>
Make_Integer_Literal (Loc,
Intval => Enumeration_Rep (Ent)),
High_Bound =>
Make_Integer_Literal (Loc, Intval => Last_Repval))),
Statements => New_List (
Make_Return_Statement (Loc,
Expression => Pos_Expr))));
else
Ent := First_Literal (Typ);
while Present (Ent) loop
Append_To (Lst,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices => New_List (
Make_Integer_Literal (Sloc (Enumeration_Rep_Expr (Ent)),
Intval => Enumeration_Rep (Ent))),
Statements => New_List (
Make_Return_Statement (Loc,
Expression =>
Make_Integer_Literal (Loc,
Intval => Enumeration_Pos (Ent))))));
Next_Literal (Ent);
end loop;
end if;
-- In normal mode, add the others clause with the test
if not Restriction_Active (No_Exception_Handlers) then
Append_To (Lst,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices => New_List (Make_Others_Choice (Loc)),
Statements => New_List (
Make_Raise_Constraint_Error (Loc,
Condition => Make_Identifier (Loc, Name_uF),
Reason => CE_Invalid_Data),
Make_Return_Statement (Loc,
Expression =>
Make_Integer_Literal (Loc, -1)))));
-- If Restriction (No_Exceptions_Handlers) is active then we always
-- return -1 (since we cannot usefully raise Constraint_Error in
-- this case). See description above for further details.
else
Append_To (Lst,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices => New_List (Make_Others_Choice (Loc)),
Statements => New_List (
Make_Return_Statement (Loc,
Expression =>
Make_Integer_Literal (Loc, -1)))));
end if;
-- Now we can build the function body
Fent :=
Make_Defining_Identifier (Loc, Make_TSS_Name (Typ, TSS_Rep_To_Pos));
Func :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Function_Specification (Loc,
Defining_Unit_Name => Fent,
Parameter_Specifications => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uA),
Parameter_Type => New_Reference_To (Typ, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uF),
Parameter_Type => New_Reference_To (Standard_Boolean, Loc))),
Result_Definition => New_Reference_To (Standard_Integer, Loc)),
Declarations => Empty_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (
Make_Case_Statement (Loc,
Expression =>
Unchecked_Convert_To (Ityp,
Make_Identifier (Loc, Name_uA)),
Alternatives => Lst))));
Set_TSS (Typ, Fent);
Set_Is_Pure (Fent);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Fent);
end if;
exception
when RE_Not_Available =>
return;
end Freeze_Enumeration_Type;
------------------------
-- Freeze_Record_Type --
------------------------
procedure Freeze_Record_Type (N : Node_Id) is
Comp : Entity_Id;
Def_Id : constant Node_Id := Entity (N);
Predef_List : List_Id;
Type_Decl : constant Node_Id := Parent (Def_Id);
Renamed_Eq : Node_Id := Empty;
-- Could use some comments ???
Wrapper_Decl_List : List_Id := No_List;
Wrapper_Body_List : List_Id := No_List;
begin
-- Build discriminant checking functions if not a derived type (for
-- derived types that are not tagged types, we always use the
-- discriminant checking functions of the parent type). However, for
-- untagged types the derivation may have taken place before the
-- parent was frozen, so we copy explicitly the discriminant checking
-- functions from the parent into the components of the derived type.
if not Is_Derived_Type (Def_Id)
or else Has_New_Non_Standard_Rep (Def_Id)
or else Is_Tagged_Type (Def_Id)
then
Build_Discr_Checking_Funcs (Type_Decl);
elsif Is_Derived_Type (Def_Id)
and then not Is_Tagged_Type (Def_Id)
-- If we have a derived Unchecked_Union, we do not inherit the
-- discriminant checking functions from the parent type since the
-- discriminants are non existent.
and then not Is_Unchecked_Union (Def_Id)
and then Has_Discriminants (Def_Id)
then
declare
Old_Comp : Entity_Id;
begin
Old_Comp :=
First_Component (Base_Type (Underlying_Type (Etype (Def_Id))));
Comp := First_Component (Def_Id);
while Present (Comp) loop
if Ekind (Comp) = E_Component
and then Chars (Comp) = Chars (Old_Comp)
then
Set_Discriminant_Checking_Func (Comp,
Discriminant_Checking_Func (Old_Comp));
end if;
Next_Component (Old_Comp);
Next_Component (Comp);
end loop;
end;
end if;
if Is_Derived_Type (Def_Id)
and then Is_Limited_Type (Def_Id)
and then Is_Tagged_Type (Def_Id)
then
Check_Stream_Attributes (Def_Id);
end if;
-- Update task and controlled component flags, because some of the
-- component types may have been private at the point of the record
-- declaration.
Comp := First_Component (Def_Id);
while Present (Comp) loop
if Has_Task (Etype (Comp)) then
Set_Has_Task (Def_Id);
elsif Has_Controlled_Component (Etype (Comp))
or else (Chars (Comp) /= Name_uParent
and then Is_Controlled (Etype (Comp)))
then
Set_Has_Controlled_Component (Def_Id);
end if;
Next_Component (Comp);
end loop;
-- Creation of the Dispatch Table. Note that a Dispatch Table is
-- created for regular tagged types as well as for Ada types deriving
-- from a C++ Class, but not for tagged types directly corresponding to
-- the C++ classes. In the later case we assume that the Vtable is
-- created in the C++ side and we just use it.
if Is_Tagged_Type (Def_Id) then
if Is_CPP_Class (Def_Id) then
-- Because of the new C++ ABI compatibility we now allow the
-- programer to use the Ada tag (and in this case we must do
-- the normal expansion of the tag)
if Etype (First_Component (Def_Id)) = RTE (RE_Tag)
and then Underlying_Type (Etype (Def_Id)) = Def_Id
then
Expand_Tagged_Root (Def_Id);
end if;
Set_All_DT_Position (Def_Id);
Set_Default_Constructor (Def_Id);
else
-- Usually inherited primitives are not delayed but the first Ada
-- extension of a CPP_Class is an exception since the address of
-- the inherited subprogram has to be inserted in the new Ada
-- Dispatch Table and this is a freezing action (usually the
-- inherited primitive address is inserted in the DT by
-- Inherit_DT)
-- Similarly, if this is an inherited operation whose parent is
-- not frozen yet, it is not in the DT of the parent, and we
-- generate an explicit freeze node for the inherited operation,
-- so that it is properly inserted in the DT of the current type.
declare
Elmt : Elmt_Id := First_Elmt (Primitive_Operations (Def_Id));
Subp : Entity_Id;
begin
while Present (Elmt) loop
Subp := Node (Elmt);
if Present (Alias (Subp)) then
if Is_CPP_Class (Etype (Def_Id)) then
Set_Has_Delayed_Freeze (Subp);
elsif Has_Delayed_Freeze (Alias (Subp))
and then not Is_Frozen (Alias (Subp))
then
Set_Is_Frozen (Subp, False);
Set_Has_Delayed_Freeze (Subp);
end if;
end if;
Next_Elmt (Elmt);
end loop;
end;
if Underlying_Type (Etype (Def_Id)) = Def_Id then
Expand_Tagged_Root (Def_Id);
end if;
-- Unfreeze momentarily the type to add the predefined primitives
-- operations. The reason we unfreeze is so that these predefined
-- operations will indeed end up as primitive operations (which
-- must be before the freeze point).
Set_Is_Frozen (Def_Id, False);
Make_Predefined_Primitive_Specs
(Def_Id, Predef_List, Renamed_Eq);
Insert_List_Before_And_Analyze (N, Predef_List);
-- Ada 2005 (AI-391): For a nonabstract null extension, create
-- wrapper functions for each nonoverridden inherited function
-- with a controlling result of the type. The wrapper for such
-- a function returns an extension aggregate that invokes the
-- the parent function.
if Ada_Version >= Ada_05
and then not Is_Abstract (Def_Id)
and then Is_Null_Extension (Def_Id)
then
Make_Controlling_Function_Wrappers
(Def_Id, Wrapper_Decl_List, Wrapper_Body_List);
Insert_List_Before_And_Analyze (N, Wrapper_Decl_List);
end if;
Set_Is_Frozen (Def_Id, True);
Set_All_DT_Position (Def_Id);
-- Add the controlled component before the freezing actions
-- referenced in those actions.
if Has_New_Controlled_Component (Def_Id) then
Expand_Record_Controller (Def_Id);
end if;
-- Suppress creation of a dispatch table when Java_VM because the
-- dispatching mechanism is handled internally by the JVM.
if not Java_VM then
-- Ada 2005 (AI-251): Build the secondary dispatch tables
declare
ADT : Elist_Id := Access_Disp_Table (Def_Id);
procedure Add_Secondary_Tables (Typ : Entity_Id);
-- Internal subprogram, recursively climb to the ancestors
--------------------------
-- Add_Secondary_Tables --
--------------------------
procedure Add_Secondary_Tables (Typ : Entity_Id) is
E : Entity_Id;
Iface : Elmt_Id;
Result : List_Id;
Suffix_Index : Int;
begin
-- Climb to the ancestor (if any) handling private types
if Present (Full_View (Etype (Typ))) then
if Full_View (Etype (Typ)) /= Typ then
Add_Secondary_Tables (Full_View (Etype (Typ)));
end if;
elsif Etype (Typ) /= Typ then
Add_Secondary_Tables (Etype (Typ));
end if;
if Present (Abstract_Interfaces (Typ))
and then
not Is_Empty_Elmt_List (Abstract_Interfaces (Typ))
then
Iface := First_Elmt (Abstract_Interfaces (Typ));
Suffix_Index := 0;
E := First_Entity (Typ);
while Present (E) loop
if Is_Tag (E) and then Chars (E) /= Name_uTag then
Make_Secondary_DT
(Typ => Def_Id,
Ancestor_Typ => Typ,
Suffix_Index => Suffix_Index,
Iface => Node (Iface),
AI_Tag => E,
Acc_Disp_Tables => ADT,
Result => Result);
Append_Freeze_Actions (Def_Id, Result);
Suffix_Index := Suffix_Index + 1;
Next_Elmt (Iface);
end if;
Next_Entity (E);
end loop;
end if;
end Add_Secondary_Tables;
-- Start of processing to build secondary dispatch tables
begin
-- Handle private types
if Present (Full_View (Def_Id)) then
Add_Secondary_Tables (Full_View (Def_Id));
else
Add_Secondary_Tables (Def_Id);
end if;
Set_Access_Disp_Table (Def_Id, ADT);
Append_Freeze_Actions (Def_Id, Make_DT (Def_Id));
end;
end if;
-- Make sure that the primitives Initialize, Adjust and Finalize
-- are Frozen before other TSS subprograms. We don't want them
-- Frozen inside.
if Is_Controlled (Def_Id) then
if not Is_Limited_Type (Def_Id) then
Append_Freeze_Actions (Def_Id,
Freeze_Entity
(Find_Prim_Op (Def_Id, Name_Adjust), Sloc (Def_Id)));
end if;
Append_Freeze_Actions (Def_Id,
Freeze_Entity
(Find_Prim_Op (Def_Id, Name_Initialize), Sloc (Def_Id)));
Append_Freeze_Actions (Def_Id,
Freeze_Entity
(Find_Prim_Op (Def_Id, Name_Finalize), Sloc (Def_Id)));
end if;
-- Freeze rest of primitive operations
Append_Freeze_Actions
(Def_Id, Predefined_Primitive_Freeze (Def_Id));
Append_Freeze_Actions
(Def_Id, Init_Predefined_Interface_Primitives (Def_Id));
end if;
-- In the non-tagged case, an equality function is provided only for
-- variant records (that are not unchecked unions).
elsif Has_Discriminants (Def_Id)
and then not Is_Limited_Type (Def_Id)
then
declare
Comps : constant Node_Id :=
Component_List (Type_Definition (Type_Decl));
begin
if Present (Comps)
and then Present (Variant_Part (Comps))
then
Build_Variant_Record_Equality (Def_Id);
end if;
end;
end if;
-- Before building the record initialization procedure, if we are
-- dealing with a concurrent record value type, then we must go through
-- the discriminants, exchanging discriminals between the concurrent
-- type and the concurrent record value type. See the section "Handling
-- of Discriminants" in the Einfo spec for details.
if Is_Concurrent_Record_Type (Def_Id)
and then Has_Discriminants (Def_Id)
then
declare
Ctyp : constant Entity_Id :=
Corresponding_Concurrent_Type (Def_Id);
Conc_Discr : Entity_Id;
Rec_Discr : Entity_Id;
Temp : Entity_Id;
begin
Conc_Discr := First_Discriminant (Ctyp);
Rec_Discr := First_Discriminant (Def_Id);
while Present (Conc_Discr) loop
Temp := Discriminal (Conc_Discr);
Set_Discriminal (Conc_Discr, Discriminal (Rec_Discr));
Set_Discriminal (Rec_Discr, Temp);
Set_Discriminal_Link (Discriminal (Conc_Discr), Conc_Discr);
Set_Discriminal_Link (Discriminal (Rec_Discr), Rec_Discr);
Next_Discriminant (Conc_Discr);
Next_Discriminant (Rec_Discr);
end loop;
end;
end if;
if Has_Controlled_Component (Def_Id) then
if No (Controller_Component (Def_Id)) then
Expand_Record_Controller (Def_Id);
end if;
Build_Controlling_Procs (Def_Id);
end if;
Adjust_Discriminants (Def_Id);
Build_Record_Init_Proc (Type_Decl, Def_Id);
-- For tagged type, build bodies of primitive operations. Note that we
-- do this after building the record initialization experiment, since
-- the primitive operations may need the initialization routine
if Is_Tagged_Type (Def_Id) then
Predef_List := Predefined_Primitive_Bodies (Def_Id, Renamed_Eq);
Append_Freeze_Actions (Def_Id, Predef_List);
-- Ada 2005 (AI-391): If any wrappers were created for nonoverridden
-- inherited functions, then add their bodies to the freeze actions.
if Present (Wrapper_Body_List) then
Append_Freeze_Actions (Def_Id, Wrapper_Body_List);
end if;
-- Populate the two auxiliary tables used for dispatching
-- asynchronous, conditional and timed selects for synchronized
-- types that implement a limited interface.
if Ada_Version >= Ada_05
and then not Restriction_Active (No_Dispatching_Calls)
and then Is_Concurrent_Record_Type (Def_Id)
and then Implements_Interface (
Typ => Def_Id,
Kind => Any_Limited_Interface,
Check_Parent => True)
then
Append_Freeze_Actions (Def_Id,
Make_Select_Specific_Data_Table (Def_Id));
end if;
end if;
end Freeze_Record_Type;
------------------------------
-- Freeze_Stream_Operations --
------------------------------
procedure Freeze_Stream_Operations (N : Node_Id; Typ : Entity_Id) is
Names : constant array (1 .. 4) of TSS_Name_Type :=
(TSS_Stream_Input,
TSS_Stream_Output,
TSS_Stream_Read,
TSS_Stream_Write);
Stream_Op : Entity_Id;
begin
-- Primitive operations of tagged types are frozen when the dispatch
-- table is constructed.
if not Comes_From_Source (Typ)
or else Is_Tagged_Type (Typ)
then
return;
end if;
for J in Names'Range loop
Stream_Op := TSS (Typ, Names (J));
if Present (Stream_Op)
and then Is_Subprogram (Stream_Op)
and then Nkind (Unit_Declaration_Node (Stream_Op)) =
N_Subprogram_Declaration
and then not Is_Frozen (Stream_Op)
then
Append_Freeze_Actions
(Typ, Freeze_Entity (Stream_Op, Sloc (N)));
end if;
end loop;
end Freeze_Stream_Operations;
-----------------
-- Freeze_Type --
-----------------
-- Full type declarations are expanded at the point at which the type is
-- frozen. The formal N is the Freeze_Node for the type. Any statements or
-- declarations generated by the freezing (e.g. the procedure generated
-- for initialization) are chained in the Actions field list of the freeze
-- node using Append_Freeze_Actions.
function Freeze_Type (N : Node_Id) return Boolean is
Def_Id : constant Entity_Id := Entity (N);
RACW_Seen : Boolean := False;
Result : Boolean := False;
begin
-- Process associated access types needing special processing
if Present (Access_Types_To_Process (N)) then
declare
E : Elmt_Id := First_Elmt (Access_Types_To_Process (N));
begin
while Present (E) loop
if Is_Remote_Access_To_Class_Wide_Type (Node (E)) then
RACW_Seen := True;
end if;
E := Next_Elmt (E);
end loop;
end;
if RACW_Seen then
-- If there are RACWs designating this type, make stubs now
Remote_Types_Tagged_Full_View_Encountered (Def_Id);
end if;
end if;
-- Freeze processing for record types
if Is_Record_Type (Def_Id) then
if Ekind (Def_Id) = E_Record_Type then
Freeze_Record_Type (N);
-- The subtype may have been declared before the type was frozen. If
-- the type has controlled components it is necessary to create the
-- entity for the controller explicitly because it did not exist at
-- the point of the subtype declaration. Only the entity is needed,
-- the back-end will obtain the layout from the type. This is only
-- necessary if this is constrained subtype whose component list is
-- not shared with the base type.
elsif Ekind (Def_Id) = E_Record_Subtype
and then Has_Discriminants (Def_Id)
and then Last_Entity (Def_Id) /= Last_Entity (Base_Type (Def_Id))
and then Present (Controller_Component (Def_Id))
then
declare
Old_C : constant Entity_Id := Controller_Component (Def_Id);
New_C : Entity_Id;
begin
if Scope (Old_C) = Base_Type (Def_Id) then
-- The entity is the one in the parent. Create new one
New_C := New_Copy (Old_C);
Set_Parent (New_C, Parent (Old_C));
New_Scope (Def_Id);
Enter_Name (New_C);
End_Scope;
end if;
end;
if Is_Itype (Def_Id)
and then Is_Record_Type (Underlying_Type (Scope (Def_Id)))
then
-- The freeze node is only used to introduce the controller,
-- the back-end has no use for it for a discriminated
-- component.
Set_Freeze_Node (Def_Id, Empty);
Set_Has_Delayed_Freeze (Def_Id, False);
Result := True;
end if;
-- Similar process if the controller of the subtype is not present
-- but the parent has it. This can happen with constrained
-- record components where the subtype is an itype.
elsif Ekind (Def_Id) = E_Record_Subtype
and then Is_Itype (Def_Id)
and then No (Controller_Component (Def_Id))
and then Present (Controller_Component (Etype (Def_Id)))
then
declare
Old_C : constant Entity_Id :=
Controller_Component (Etype (Def_Id));
New_C : constant Entity_Id := New_Copy (Old_C);
begin
Set_Next_Entity (New_C, First_Entity (Def_Id));
Set_First_Entity (Def_Id, New_C);
-- The freeze node is only used to introduce the controller,
-- the back-end has no use for it for a discriminated
-- component.
Set_Freeze_Node (Def_Id, Empty);
Set_Has_Delayed_Freeze (Def_Id, False);
Result := True;
end;
end if;
-- Freeze processing for array types
elsif Is_Array_Type (Def_Id) then
Freeze_Array_Type (N);
-- Freeze processing for access types
-- For pool-specific access types, find out the pool object used for
-- this type, needs actual expansion of it in some cases. Here are the
-- different cases :
-- 1. Rep Clause "for Def_Id'Storage_Size use 0;"
-- ---> don't use any storage pool
-- 2. Rep Clause : for Def_Id'Storage_Size use Expr.
-- Expand:
-- Def_Id__Pool : Stack_Bounded_Pool (Expr, DT'Size, DT'Alignment);
-- 3. Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
-- ---> Storage Pool is the specified one
-- See GNAT Pool packages in the Run-Time for more details
elsif Ekind (Def_Id) = E_Access_Type
or else Ekind (Def_Id) = E_General_Access_Type
then
declare
Loc : constant Source_Ptr := Sloc (N);
Desig_Type : constant Entity_Id := Designated_Type (Def_Id);
Pool_Object : Entity_Id;
Siz_Exp : Node_Id;
Freeze_Action_Typ : Entity_Id;
begin
if Has_Storage_Size_Clause (Def_Id) then
Siz_Exp := Expression (Parent (Storage_Size_Variable (Def_Id)));
else
Siz_Exp := Empty;
end if;
-- Case 1
-- Rep Clause "for Def_Id'Storage_Size use 0;"
-- ---> don't use any storage pool
if Has_Storage_Size_Clause (Def_Id)
and then Compile_Time_Known_Value (Siz_Exp)
and then Expr_Value (Siz_Exp) = 0
then
null;
-- Case 2
-- Rep Clause : for Def_Id'Storage_Size use Expr.
-- ---> Expand:
-- Def_Id__Pool : Stack_Bounded_Pool
-- (Expr, DT'Size, DT'Alignment);
elsif Has_Storage_Size_Clause (Def_Id) then
declare
DT_Size : Node_Id;
DT_Align : Node_Id;
begin
-- For unconstrained composite types we give a size of zero
-- so that the pool knows that it needs a special algorithm
-- for variable size object allocation.
if Is_Composite_Type (Desig_Type)
and then not Is_Constrained (Desig_Type)
then
DT_Size :=
Make_Integer_Literal (Loc, 0);
DT_Align :=
Make_Integer_Literal (Loc, Maximum_Alignment);
else
DT_Size :=
Make_Attribute_Reference (Loc,
Prefix => New_Reference_To (Desig_Type, Loc),
Attribute_Name => Name_Max_Size_In_Storage_Elements);
DT_Align :=
Make_Attribute_Reference (Loc,
Prefix => New_Reference_To (Desig_Type, Loc),
Attribute_Name => Name_Alignment);
end if;
Pool_Object :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Def_Id), 'P'));
-- We put the code associated with the pools in the entity
-- that has the later freeze node, usually the acces type
-- but it can also be the designated_type; because the pool
-- code requires both those types to be frozen
if Is_Frozen (Desig_Type)
and then (No (Freeze_Node (Desig_Type))
or else Analyzed (Freeze_Node (Desig_Type)))
then
Freeze_Action_Typ := Def_Id;
-- A Taft amendment type cannot get the freeze actions
-- since the full view is not there.
elsif Is_Incomplete_Or_Private_Type (Desig_Type)
and then No (Full_View (Desig_Type))
then
Freeze_Action_Typ := Def_Id;
else
Freeze_Action_Typ := Desig_Type;
end if;
Append_Freeze_Action (Freeze_Action_Typ,
Make_Object_Declaration (Loc,
Defining_Identifier => Pool_Object,
Object_Definition =>
Make_Subtype_Indication (Loc,
Subtype_Mark =>
New_Reference_To
(RTE (RE_Stack_Bounded_Pool), Loc),
Constraint =>
Make_Index_Or_Discriminant_Constraint (Loc,
Constraints => New_List (
-- First discriminant is the Pool Size
New_Reference_To (
Storage_Size_Variable (Def_Id), Loc),
-- Second discriminant is the element size
DT_Size,
-- Third discriminant is the alignment
DT_Align)))));
end;
Set_Associated_Storage_Pool (Def_Id, Pool_Object);
-- Case 3
-- Rep Clause "for Def_Id'Storage_Pool use a_Pool_Object"
-- ---> Storage Pool is the specified one
elsif Present (Associated_Storage_Pool (Def_Id)) then
-- Nothing to do the associated storage pool has been attached
-- when analyzing the rep. clause
null;
end if;
-- For access-to-controlled types (including class-wide types and
-- Taft-amendment types which potentially have controlled
-- components), expand the list controller object that will store
-- the dynamically allocated objects. Do not do this
-- transformation for expander-generated access types, but do it
-- for types that are the full view of types derived from other
-- private types. Also suppress the list controller in the case
-- of a designated type with convention Java, since this is used
-- when binding to Java API specs, where there's no equivalent of
-- a finalization list and we don't want to pull in the
-- finalization support if not needed.
if not Comes_From_Source (Def_Id)
and then not Has_Private_Declaration (Def_Id)
then
null;
elsif (Controlled_Type (Desig_Type)
and then Convention (Desig_Type) /= Convention_Java)
or else
(Is_Incomplete_Or_Private_Type (Desig_Type)
and then No (Full_View (Desig_Type))
-- An exception is made for types defined in the run-time
-- because Ada.Tags.Tag itself is such a type and cannot
-- afford this unnecessary overhead that would generates a
-- loop in the expansion scheme...
and then not In_Runtime (Def_Id)
-- Another exception is if Restrictions (No_Finalization)
-- is active, since then we know nothing is controlled.
and then not Restriction_Active (No_Finalization))
-- If the designated type is not frozen yet, its controlled
-- status must be retrieved explicitly.
or else (Is_Array_Type (Desig_Type)
and then not Is_Frozen (Desig_Type)
and then Controlled_Type (Component_Type (Desig_Type)))
then
Set_Associated_Final_Chain (Def_Id,
Make_Defining_Identifier (Loc,
New_External_Name (Chars (Def_Id), 'L')));
Append_Freeze_Action (Def_Id,
Make_Object_Declaration (Loc,
Defining_Identifier => Associated_Final_Chain (Def_Id),
Object_Definition =>
New_Reference_To (RTE (RE_List_Controller), Loc)));
end if;
end;
-- Freeze processing for enumeration types
elsif Ekind (Def_Id) = E_Enumeration_Type then
-- We only have something to do if we have a non-standard
-- representation (i.e. at least one literal whose pos value
-- is not the same as its representation)
if Has_Non_Standard_Rep (Def_Id) then
Freeze_Enumeration_Type (N);
end if;
-- Private types that are completed by a derivation from a private
-- type have an internally generated full view, that needs to be
-- frozen. This must be done explicitly because the two views share
-- the freeze node, and the underlying full view is not visible when
-- the freeze node is analyzed.
elsif Is_Private_Type (Def_Id)
and then Is_Derived_Type (Def_Id)
and then Present (Full_View (Def_Id))
and then Is_Itype (Full_View (Def_Id))
and then Has_Private_Declaration (Full_View (Def_Id))
and then Freeze_Node (Full_View (Def_Id)) = N
then
Set_Entity (N, Full_View (Def_Id));
Result := Freeze_Type (N);
Set_Entity (N, Def_Id);
-- All other types require no expander action. There are such cases
-- (e.g. task types and protected types). In such cases, the freeze
-- nodes are there for use by Gigi.
end if;
Freeze_Stream_Operations (N, Def_Id);
return Result;
exception
when RE_Not_Available =>
return False;
end Freeze_Type;
-------------------------
-- Get_Simple_Init_Val --
-------------------------
function Get_Simple_Init_Val
(T : Entity_Id;
Loc : Source_Ptr;
Size : Uint := No_Uint) return Node_Id
is
Val : Node_Id;
Result : Node_Id;
Val_RE : RE_Id;
Size_To_Use : Uint;
-- This is the size to be used for computation of the appropriate
-- initial value for the Normalize_Scalars and Initialize_Scalars case.
Lo_Bound : Uint;
Hi_Bound : Uint;
-- These are the values computed by the procedure Check_Subtype_Bounds
procedure Check_Subtype_Bounds;
-- This procedure examines the subtype T, and its ancestor subtypes and
-- derived types to determine the best known information about the
-- bounds of the subtype. After the call Lo_Bound is set either to
-- No_Uint if no information can be determined, or to a value which
-- represents a known low bound, i.e. a valid value of the subtype can
-- not be less than this value. Hi_Bound is similarly set to a known
-- high bound (valid value cannot be greater than this).
--------------------------
-- Check_Subtype_Bounds --
--------------------------
procedure Check_Subtype_Bounds is
ST1 : Entity_Id;
ST2 : Entity_Id;
Lo : Node_Id;
Hi : Node_Id;
Loval : Uint;
Hival : Uint;
begin
Lo_Bound := No_Uint;
Hi_Bound := No_Uint;
-- Loop to climb ancestor subtypes and derived types
ST1 := T;
loop
if not Is_Discrete_Type (ST1) then
return;
end if;
Lo := Type_Low_Bound (ST1);
Hi := Type_High_Bound (ST1);
if Compile_Time_Known_Value (Lo) then
Loval := Expr_Value (Lo);
if Lo_Bound = No_Uint or else Lo_Bound < Loval then
Lo_Bound := Loval;
end if;
end if;
if Compile_Time_Known_Value (Hi) then
Hival := Expr_Value (Hi);
if Hi_Bound = No_Uint or else Hi_Bound > Hival then
Hi_Bound := Hival;
end if;
end if;
ST2 := Ancestor_Subtype (ST1);
if No (ST2) then
ST2 := Etype (ST1);
end if;
exit when ST1 = ST2;
ST1 := ST2;
end loop;
end Check_Subtype_Bounds;
-- Start of processing for Get_Simple_Init_Val
begin
-- For a private type, we should always have an underlying type
-- (because this was already checked in Needs_Simple_Initialization).
-- What we do is to get the value for the underlying type and then do
-- an Unchecked_Convert to the private type.
if Is_Private_Type (T) then
Val := Get_Simple_Init_Val (Underlying_Type (T), Loc, Size);
-- A special case, if the underlying value is null, then qualify it
-- with the underlying type, so that the null is properly typed
-- Similarly, if it is an aggregate it must be qualified, because an
-- unchecked conversion does not provide a context for it.
if Nkind (Val) = N_Null
or else Nkind (Val) = N_Aggregate
then
Val :=
Make_Qualified_Expression (Loc,
Subtype_Mark =>
New_Occurrence_Of (Underlying_Type (T), Loc),
Expression => Val);
end if;
Result := Unchecked_Convert_To (T, Val);
-- Don't truncate result (important for Initialize/Normalize_Scalars)
if Nkind (Result) = N_Unchecked_Type_Conversion
and then Is_Scalar_Type (Underlying_Type (T))
then
Set_No_Truncation (Result);
end if;
return Result;
-- For scalars, we must have normalize/initialize scalars case
elsif Is_Scalar_Type (T) then
pragma Assert (Init_Or_Norm_Scalars);
-- Compute size of object. If it is given by the caller, we can use
-- it directly, otherwise we use Esize (T) as an estimate. As far as
-- we know this covers all cases correctly.
if Size = No_Uint or else Size <= Uint_0 then
Size_To_Use := UI_Max (Uint_1, Esize (T));
else
Size_To_Use := Size;
end if;
-- Maximum size to use is 64 bits, since we will create values
-- of type Unsigned_64 and the range must fit this type.
if Size_To_Use /= No_Uint and then Size_To_Use > Uint_64 then
Size_To_Use := Uint_64;
end if;
-- Check known bounds of subtype
Check_Subtype_Bounds;
-- Processing for Normalize_Scalars case
if Normalize_Scalars then
-- If zero is invalid, it is a convenient value to use that is
-- for sure an appropriate invalid value in all situations.
if Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
Val := Make_Integer_Literal (Loc, 0);
-- Cases where all one bits is the appropriate invalid value
-- For modular types, all 1 bits is either invalid or valid. If
-- it is valid, then there is nothing that can be done since there
-- are no invalid values (we ruled out zero already).
-- For signed integer types that have no negative values, either
-- there is room for negative values, or there is not. If there
-- is, then all 1 bits may be interpretecd as minus one, which is
-- certainly invalid. Alternatively it is treated as the largest
-- positive value, in which case the observation for modular types
-- still applies.
-- For float types, all 1-bits is a NaN (not a number), which is
-- certainly an appropriately invalid value.
elsif Is_Unsigned_Type (T)
or else Is_Floating_Point_Type (T)
or else Is_Enumeration_Type (T)
then
Val := Make_Integer_Literal (Loc, 2 ** Size_To_Use - 1);
-- Resolve as Unsigned_64, because the largest number we
-- can generate is out of range of universal integer.
Analyze_And_Resolve (Val, RTE (RE_Unsigned_64));
-- Case of signed types
else
declare
Signed_Size : constant Uint :=
UI_Min (Uint_63, Size_To_Use - 1);
begin
-- Normally we like to use the most negative number. The
-- one exception is when this number is in the known
-- subtype range and the largest positive number is not in
-- the known subtype range.
-- For this exceptional case, use largest positive value
if Lo_Bound /= No_Uint and then Hi_Bound /= No_Uint
and then Lo_Bound <= (-(2 ** Signed_Size))
and then Hi_Bound < 2 ** Signed_Size
then
Val := Make_Integer_Literal (Loc, 2 ** Signed_Size - 1);
-- Normal case of largest negative value
else
Val := Make_Integer_Literal (Loc, -(2 ** Signed_Size));
end if;
end;
end if;
-- Here for Initialize_Scalars case
else
-- For float types, use float values from System.Scalar_Values
if Is_Floating_Point_Type (T) then
if Root_Type (T) = Standard_Short_Float then
Val_RE := RE_IS_Isf;
elsif Root_Type (T) = Standard_Float then
Val_RE := RE_IS_Ifl;
elsif Root_Type (T) = Standard_Long_Float then
Val_RE := RE_IS_Ilf;
else pragma Assert (Root_Type (T) = Standard_Long_Long_Float);
Val_RE := RE_IS_Ill;
end if;
-- If zero is invalid, use zero values from System.Scalar_Values
elsif Lo_Bound /= No_Uint and then Lo_Bound > Uint_0 then
if Size_To_Use <= 8 then
Val_RE := RE_IS_Iz1;
elsif Size_To_Use <= 16 then
Val_RE := RE_IS_Iz2;
elsif Size_To_Use <= 32 then
Val_RE := RE_IS_Iz4;
else
Val_RE := RE_IS_Iz8;
end if;
-- For unsigned, use unsigned values from System.Scalar_Values
elsif Is_Unsigned_Type (T) then
if Size_To_Use <= 8 then
Val_RE := RE_IS_Iu1;
elsif Size_To_Use <= 16 then
Val_RE := RE_IS_Iu2;
elsif Size_To_Use <= 32 then
Val_RE := RE_IS_Iu4;
else
Val_RE := RE_IS_Iu8;
end if;
-- For signed, use signed values from System.Scalar_Values
else
if Size_To_Use <= 8 then
Val_RE := RE_IS_Is1;
elsif Size_To_Use <= 16 then
Val_RE := RE_IS_Is2;
elsif Size_To_Use <= 32 then
Val_RE := RE_IS_Is4;
else
Val_RE := RE_IS_Is8;
end if;
end if;
Val := New_Occurrence_Of (RTE (Val_RE), Loc);
end if;
-- The final expression is obtained by doing an unchecked conversion
-- of this result to the base type of the required subtype. We use
-- the base type to avoid the unchecked conversion from chopping
-- bits, and then we set Kill_Range_Check to preserve the "bad"
-- value.
Result := Unchecked_Convert_To (Base_Type (T), Val);
-- Ensure result is not truncated, since we want the "bad" bits
-- and also kill range check on result.
if Nkind (Result) = N_Unchecked_Type_Conversion then
Set_No_Truncation (Result);
Set_Kill_Range_Check (Result, True);
end if;
return Result;
-- String or Wide_[Wide]_String (must have Initialize_Scalars set)
elsif Root_Type (T) = Standard_String
or else
Root_Type (T) = Standard_Wide_String
or else
Root_Type (T) = Standard_Wide_Wide_String
then
pragma Assert (Init_Or_Norm_Scalars);
return
Make_Aggregate (Loc,
Component_Associations => New_List (
Make_Component_Association (Loc,
Choices => New_List (
Make_Others_Choice (Loc)),
Expression =>
Get_Simple_Init_Val
(Component_Type (T), Loc, Esize (Root_Type (T))))));
-- Access type is initialized to null
elsif Is_Access_Type (T) then
return
Make_Null (Loc);
-- No other possibilities should arise, since we should only be
-- calling Get_Simple_Init_Val if Needs_Simple_Initialization
-- returned True, indicating one of the above cases held.
else
raise Program_Error;
end if;
exception
when RE_Not_Available =>
return Empty;
end Get_Simple_Init_Val;
------------------------------
-- Has_New_Non_Standard_Rep --
------------------------------
function Has_New_Non_Standard_Rep (T : Entity_Id) return Boolean is
begin
if not Is_Derived_Type (T) then
return Has_Non_Standard_Rep (T)
or else Has_Non_Standard_Rep (Root_Type (T));
-- If Has_Non_Standard_Rep is not set on the derived type, the
-- representation is fully inherited.
elsif not Has_Non_Standard_Rep (T) then
return False;
else
return First_Rep_Item (T) /= First_Rep_Item (Root_Type (T));
-- May need a more precise check here: the First_Rep_Item may
-- be a stream attribute, which does not affect the representation
-- of the type ???
end if;
end Has_New_Non_Standard_Rep;
----------------
-- In_Runtime --
----------------
function In_Runtime (E : Entity_Id) return Boolean is
S1 : Entity_Id := Scope (E);
begin
while Scope (S1) /= Standard_Standard loop
S1 := Scope (S1);
end loop;
return Chars (S1) = Name_System or else Chars (S1) = Name_Ada;
end In_Runtime;
------------------
-- Init_Formals --
------------------
function Init_Formals (Typ : Entity_Id) return List_Id is
Loc : constant Source_Ptr := Sloc (Typ);
Formals : List_Id;
begin
-- First parameter is always _Init : in out typ. Note that we need
-- this to be in/out because in the case of the task record value,
-- there are default record fields (_Priority, _Size, -Task_Info)
-- that may be referenced in the generated initialization routine.
Formals := New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uInit),
In_Present => True,
Out_Present => True,
Parameter_Type => New_Reference_To (Typ, Loc)));
-- For task record value, or type that contains tasks, add two more
-- formals, _Master : Master_Id and _Chain : in out Activation_Chain
-- We also add these parameters for the task record type case.
if Has_Task (Typ)
or else (Is_Record_Type (Typ) and then Is_Task_Record_Type (Typ))
then
Append_To (Formals,
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uMaster),
Parameter_Type => New_Reference_To (RTE (RE_Master_Id), Loc)));
Append_To (Formals,
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uChain),
In_Present => True,
Out_Present => True,
Parameter_Type =>
New_Reference_To (RTE (RE_Activation_Chain), Loc)));
Append_To (Formals,
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_uTask_Name),
In_Present => True,
Parameter_Type =>
New_Reference_To (Standard_String, Loc)));
end if;
return Formals;
exception
when RE_Not_Available =>
return Empty_List;
end Init_Formals;
-------------------------------------
-- Make_Predefined_Primitive_Specs --
-------------------------------------
procedure Make_Controlling_Function_Wrappers
(Tag_Typ : Entity_Id;
Decl_List : out List_Id;
Body_List : out List_Id)
is
Loc : constant Source_Ptr := Sloc (Tag_Typ);
Prim_Elmt : Elmt_Id;
Subp : Entity_Id;
Actual_List : List_Id;
Formal_List : List_Id;
Formal : Entity_Id;
Par_Formal : Entity_Id;
Formal_Node : Node_Id;
Func_Spec : Node_Id;
Func_Decl : Node_Id;
Func_Body : Node_Id;
Return_Stmt : Node_Id;
begin
Decl_List := New_List;
Body_List := New_List;
Prim_Elmt := First_Elmt (Primitive_Operations (Tag_Typ));
while Present (Prim_Elmt) loop
Subp := Node (Prim_Elmt);
-- If a primitive function with a controlling result of the type has
-- not been overridden by the user, then we must create a wrapper
-- function here that effectively overrides it and invokes the
-- abstract inherited function's nonabstract parent. This can only
-- occur for a null extension. Note that functions with anonymous
-- controlling access results don't qualify and must be overridden.
-- We also exclude Input attributes, since each type will have its
-- own version of Input constructed by the expander. The test for
-- Comes_From_Source is needed to distinguish inherited operations
-- from renamings (which also have Alias set).
if Is_Abstract (Subp)
and then Present (Alias (Subp))
and then not Comes_From_Source (Subp)
and then Ekind (Subp) = E_Function
and then Has_Controlling_Result (Subp)
and then not Is_Access_Type (Etype (Subp))
and then not Is_TSS (Subp, TSS_Stream_Input)
then
Formal_List := No_List;
Formal := First_Formal (Subp);
if Present (Formal) then
Formal_List := New_List;
while Present (Formal) loop
Append
(Make_Parameter_Specification
(Loc,
Defining_Identifier =>
Make_Defining_Identifier (Sloc (Formal),
Chars => Chars (Formal)),
In_Present => In_Present (Parent (Formal)),
Out_Present => Out_Present (Parent (Formal)),
Parameter_Type =>
New_Reference_To (Etype (Formal), Loc),
Expression =>
New_Copy_Tree (Expression (Parent (Formal)))),
Formal_List);
Next_Formal (Formal);
end loop;
end if;
Func_Spec :=
Make_Function_Specification (Loc,
Defining_Unit_Name =>
Make_Defining_Identifier (Loc, Chars (Subp)),
Parameter_Specifications =>
Formal_List,
Result_Definition =>
New_Reference_To (Etype (Subp), Loc));
Func_Decl := Make_Subprogram_Declaration (Loc, Func_Spec);
Append_To (Decl_List, Func_Decl);
-- Build a wrapper body that calls the parent function. The body
-- contains a single return statement that returns an extension
-- aggregate whose ancestor part is a call to the parent function,
-- passing the formals as actuals (with any controlling arguments
-- converted to the types of the corresponding formals of the
-- parent function, which might be anonymous access types), and
-- having a null extension.
Formal := First_Formal (Subp);
Par_Formal := First_Formal (Alias (Subp));
Formal_Node := First (Formal_List);
if Present (Formal) then
Actual_List := New_List;
else
Actual_List := No_List;
end if;
while Present (Formal) loop
if Is_Controlling_Formal (Formal) then
Append_To (Actual_List,
Make_Type_Conversion (Loc,
Subtype_Mark =>
New_Occurrence_Of (Etype (Par_Formal), Loc),
Expression =>
New_Reference_To
(Defining_Identifier (Formal_Node), Loc)));
else
Append_To
(Actual_List,
New_Reference_To
(Defining_Identifier (Formal_Node), Loc));
end if;
Next_Formal (Formal);
Next_Formal (Par_Formal);
Next (Formal_Node);
end loop;
Return_Stmt :=
Make_Return_Statement (Loc,
Expression =>
Make_Extension_Aggregate (Loc,
Ancestor_Part =>
Make_Function_Call (Loc,
Name => New_Reference_To (Alias (Subp), Loc),
Parameter_Associations => Actual_List),
Null_Record_Present => True));
Func_Body :=
Make_Subprogram_Body (Loc,
Specification => New_Copy_Tree (Func_Spec),
Declarations => Empty_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (Return_Stmt)));
Set_Defining_Unit_Name
(Specification (Func_Body),
Make_Defining_Identifier (Loc, Chars (Subp)));
Append_To (Body_List, Func_Body);
-- Replace the inherited function with the wrapper function
-- in the primitive operations list.
Override_Dispatching_Operation
(Tag_Typ, Subp, New_Op => Defining_Unit_Name (Func_Spec));
end if;
Next_Elmt (Prim_Elmt);
end loop;
end Make_Controlling_Function_Wrappers;
------------------
-- Make_Eq_Case --
------------------
-- <Make_Eq_if shared components>
-- case X.D1 is
-- when V1 => <Make_Eq_Case> on subcomponents
-- ...
-- when Vn => <Make_Eq_Case> on subcomponents
-- end case;
function Make_Eq_Case
(E : Entity_Id;
CL : Node_Id;
Discr : Entity_Id := Empty) return List_Id
is
Loc : constant Source_Ptr := Sloc (E);
Result : constant List_Id := New_List;
Variant : Node_Id;
Alt_List : List_Id;
begin
Append_To (Result, Make_Eq_If (E, Component_Items (CL)));
if No (Variant_Part (CL)) then
return Result;
end if;
Variant := First_Non_Pragma (Variants (Variant_Part (CL)));
if No (Variant) then
return Result;
end if;
Alt_List := New_List;
while Present (Variant) loop
Append_To (Alt_List,
Make_Case_Statement_Alternative (Loc,
Discrete_Choices => New_Copy_List (Discrete_Choices (Variant)),
Statements => Make_Eq_Case (E, Component_List (Variant))));
Next_Non_Pragma (Variant);
end loop;
-- If we have an Unchecked_Union, use one of the parameters that
-- captures the discriminants.
if Is_Unchecked_Union (E) then
Append_To (Result,
Make_Case_Statement (Loc,
Expression => New_Reference_To (Discr, Loc),
Alternatives => Alt_List));
else
Append_To (Result,
Make_Case_Statement (Loc,
Expression =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_X),
Selector_Name => New_Copy (Name (Variant_Part (CL)))),
Alternatives => Alt_List));
end if;
return Result;
end Make_Eq_Case;
----------------
-- Make_Eq_If --
----------------
-- Generates:
-- if
-- X.C1 /= Y.C1
-- or else
-- X.C2 /= Y.C2
-- ...
-- then
-- return False;
-- end if;
-- or a null statement if the list L is empty
function Make_Eq_If
(E : Entity_Id;
L : List_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (E);
C : Node_Id;
Field_Name : Name_Id;
Cond : Node_Id;
begin
if No (L) then
return Make_Null_Statement (Loc);
else
Cond := Empty;
C := First_Non_Pragma (L);
while Present (C) loop
Field_Name := Chars (Defining_Identifier (C));
-- The tags must not be compared they are not part of the value.
-- Note also that in the following, we use Make_Identifier for
-- the component names. Use of New_Reference_To to identify the
-- components would be incorrect because the wrong entities for
-- discriminants could be picked up in the private type case.
if Field_Name /= Name_uTag then
Evolve_Or_Else (Cond,
Make_Op_Ne (Loc,
Left_Opnd =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_X),
Selector_Name =>
Make_Identifier (Loc, Field_Name)),
Right_Opnd =>
Make_Selected_Component (Loc,
Prefix => Make_Identifier (Loc, Name_Y),
Selector_Name =>
Make_Identifier (Loc, Field_Name))));
end if;
Next_Non_Pragma (C);
end loop;
if No (Cond) then
return Make_Null_Statement (Loc);
else
return
Make_Implicit_If_Statement (E,
Condition => Cond,
Then_Statements => New_List (
Make_Return_Statement (Loc,
Expression => New_Occurrence_Of (Standard_False, Loc))));
end if;
end if;
end Make_Eq_If;
-------------------------------------
-- Make_Predefined_Primitive_Specs --
-------------------------------------
procedure Make_Predefined_Primitive_Specs
(Tag_Typ : Entity_Id;
Predef_List : out List_Id;
Renamed_Eq : out Node_Id)
is
Loc : constant Source_Ptr := Sloc (Tag_Typ);
Res : constant List_Id := New_List;
Prim : Elmt_Id;
Eq_Needed : Boolean;
Eq_Spec : Node_Id;
Eq_Name : Name_Id := Name_Op_Eq;
function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean;
-- Returns true if Prim is a renaming of an unresolved predefined
-- equality operation.
-------------------------------
-- Is_Predefined_Eq_Renaming --
-------------------------------
function Is_Predefined_Eq_Renaming (Prim : Node_Id) return Boolean is
begin
return Chars (Prim) /= Name_Op_Eq
and then Present (Alias (Prim))
and then Comes_From_Source (Prim)
and then Is_Intrinsic_Subprogram (Alias (Prim))
and then Chars (Alias (Prim)) = Name_Op_Eq;
end Is_Predefined_Eq_Renaming;
-- Start of processing for Make_Predefined_Primitive_Specs
begin
Renamed_Eq := Empty;
-- Spec of _Size
Append_To (Res, Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uSize,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Long_Long_Integer));
-- Spec of _Alignment
Append_To (Res, Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uAlignment,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Integer));
-- Specs for dispatching stream attributes
declare
Stream_Op_TSS_Names :
constant array (Integer range <>) of TSS_Name_Type :=
(TSS_Stream_Read,
TSS_Stream_Write,
TSS_Stream_Input,
TSS_Stream_Output);
begin
for Op in Stream_Op_TSS_Names'Range loop
if Stream_Operation_OK (Tag_Typ, Stream_Op_TSS_Names (Op)) then
Append_To (Res,
Predef_Stream_Attr_Spec (Loc, Tag_Typ,
Stream_Op_TSS_Names (Op)));
end if;
end loop;
end;
-- Spec of "=" if expanded if the type is not limited and if a
-- user defined "=" was not already declared for the non-full
-- view of a private extension
if not Is_Limited_Type (Tag_Typ) then
Eq_Needed := True;
Prim := First_Elmt (Primitive_Operations (Tag_Typ));
while Present (Prim) loop
-- If a primitive is encountered that renames the predefined
-- equality operator before reaching any explicit equality
-- primitive, then we still need to create a predefined
-- equality function, because calls to it can occur via
-- the renaming. A new name is created for the equality
-- to avoid conflicting with any user-defined equality.
-- (Note that this doesn't account for renamings of
-- equality nested within subpackages???)
if Is_Predefined_Eq_Renaming (Node (Prim)) then
Eq_Name := New_External_Name (Chars (Node (Prim)), 'E');
elsif Chars (Node (Prim)) = Name_Op_Eq
and then (No (Alias (Node (Prim)))
or else Nkind (Unit_Declaration_Node (Node (Prim))) =
N_Subprogram_Renaming_Declaration)
and then Etype (First_Formal (Node (Prim))) =
Etype (Next_Formal (First_Formal (Node (Prim))))
and then Base_Type (Etype (Node (Prim))) = Standard_Boolean
then
Eq_Needed := False;
exit;
-- If the parent equality is abstract, the inherited equality is
-- abstract as well, and no body can be created for for it.
elsif Chars (Node (Prim)) = Name_Op_Eq
and then Present (Alias (Node (Prim)))
and then Is_Abstract (Alias (Node (Prim)))
then
Eq_Needed := False;
exit;
end if;
Next_Elmt (Prim);
end loop;
-- If a renaming of predefined equality was found
-- but there was no user-defined equality (so Eq_Needed
-- is still true), then set the name back to Name_Op_Eq.
-- But in the case where a user-defined equality was
-- located after such a renaming, then the predefined
-- equality function is still needed, so Eq_Needed must
-- be set back to True.
if Eq_Name /= Name_Op_Eq then
if Eq_Needed then
Eq_Name := Name_Op_Eq;
else
Eq_Needed := True;
end if;
end if;
if Eq_Needed then
Eq_Spec := Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Eq_Name,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_Y),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Boolean);
Append_To (Res, Eq_Spec);
if Eq_Name /= Name_Op_Eq then
Renamed_Eq := Defining_Unit_Name (Specification (Eq_Spec));
Prim := First_Elmt (Primitive_Operations (Tag_Typ));
while Present (Prim) loop
-- Any renamings of equality that appeared before an
-- overriding equality must be updated to refer to
-- the entity for the predefined equality, otherwise
-- calls via the renaming would get incorrectly
-- resolved to call the user-defined equality function.
if Is_Predefined_Eq_Renaming (Node (Prim)) then
Set_Alias (Node (Prim), Renamed_Eq);
-- Exit upon encountering a user-defined equality
elsif Chars (Node (Prim)) = Name_Op_Eq
and then No (Alias (Node (Prim)))
then
exit;
end if;
Next_Elmt (Prim);
end loop;
end if;
end if;
-- Spec for dispatching assignment
Append_To (Res, Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uAssign,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Out_Present => True,
Parameter_Type => New_Reference_To (Tag_Typ, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
Parameter_Type => New_Reference_To (Tag_Typ, Loc)))));
end if;
-- Generate the declarations for the following primitive operations:
-- disp_asynchronous_select
-- disp_conditional_select
-- disp_get_prim_op_kind
-- disp_get_task_id
-- disp_timed_select
-- for limited interfaces and synchronized types that implement a
-- limited interface.
if Ada_Version >= Ada_05
and then
((Is_Interface (Tag_Typ) and then Is_Limited_Record (Tag_Typ))
or else
(Is_Concurrent_Record_Type (Tag_Typ)
and then Implements_Interface (
Typ => Tag_Typ,
Kind => Any_Limited_Interface,
Check_Parent => True)))
then
Append_To (Res,
Make_Subprogram_Declaration (Loc,
Specification =>
Make_Disp_Asynchronous_Select_Spec (Tag_Typ)));
Append_To (Res,
Make_Subprogram_Declaration (Loc,
Specification =>
Make_Disp_Conditional_Select_Spec (Tag_Typ)));
Append_To (Res,
Make_Subprogram_Declaration (Loc,
Specification =>
Make_Disp_Get_Prim_Op_Kind_Spec (Tag_Typ)));
Append_To (Res,
Make_Subprogram_Declaration (Loc,
Specification =>
Make_Disp_Get_Task_Id_Spec (Tag_Typ)));
Append_To (Res,
Make_Subprogram_Declaration (Loc,
Specification =>
Make_Disp_Timed_Select_Spec (Tag_Typ)));
end if;
-- Specs for finalization actions that may be required in case a
-- future extension contain a controlled element. We generate those
-- only for root tagged types where they will get dummy bodies or
-- when the type has controlled components and their body must be
-- generated. It is also impossible to provide those for tagged
-- types defined within s-finimp since it would involve circularity
-- problems
if In_Finalization_Root (Tag_Typ) then
null;
-- We also skip these if finalization is not available
elsif Restriction_Active (No_Finalization) then
null;
elsif Etype (Tag_Typ) = Tag_Typ or else Controlled_Type (Tag_Typ) then
if not Is_Limited_Type (Tag_Typ) then
Append_To (Res,
Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust));
end if;
Append_To (Res, Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize));
end if;
Predef_List := Res;
end Make_Predefined_Primitive_Specs;
---------------------------------
-- Needs_Simple_Initialization --
---------------------------------
function Needs_Simple_Initialization (T : Entity_Id) return Boolean is
begin
-- Check for private type, in which case test applies to the
-- underlying type of the private type.
if Is_Private_Type (T) then
declare
RT : constant Entity_Id := Underlying_Type (T);
begin
if Present (RT) then
return Needs_Simple_Initialization (RT);
else
return False;
end if;
end;
-- Cases needing simple initialization are access types, and, if pragma
-- Normalize_Scalars or Initialize_Scalars is in effect, then all scalar
-- types.
elsif Is_Access_Type (T)
or else (Init_Or_Norm_Scalars and then (Is_Scalar_Type (T)))
then
return True;
-- If Initialize/Normalize_Scalars is in effect, string objects also
-- need initialization, unless they are created in the course of
-- expanding an aggregate (since in the latter case they will be
-- filled with appropriate initializing values before they are used).
elsif Init_Or_Norm_Scalars
and then
(Root_Type (T) = Standard_String
or else Root_Type (T) = Standard_Wide_String
or else Root_Type (T) = Standard_Wide_Wide_String)
and then
(not Is_Itype (T)
or else Nkind (Associated_Node_For_Itype (T)) /= N_Aggregate)
then
return True;
else
return False;
end if;
end Needs_Simple_Initialization;
----------------------
-- Predef_Deep_Spec --
----------------------
function Predef_Deep_Spec
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : TSS_Name_Type;
For_Body : Boolean := False) return Node_Id
is
Prof : List_Id;
Type_B : Entity_Id;
begin
if Name = TSS_Deep_Finalize then
Prof := New_List;
Type_B := Standard_Boolean;
else
Prof := New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_L),
In_Present => True,
Out_Present => True,
Parameter_Type =>
New_Reference_To (RTE (RE_Finalizable_Ptr), Loc)));
Type_B := Standard_Short_Short_Integer;
end if;
Append_To (Prof,
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_V),
In_Present => True,
Out_Present => True,
Parameter_Type => New_Reference_To (Tag_Typ, Loc)));
Append_To (Prof,
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_B),
Parameter_Type => New_Reference_To (Type_B, Loc)));
return Predef_Spec_Or_Body (Loc,
Name => Make_TSS_Name (Tag_Typ, Name),
Tag_Typ => Tag_Typ,
Profile => Prof,
For_Body => For_Body);
exception
when RE_Not_Available =>
return Empty;
end Predef_Deep_Spec;
-------------------------
-- Predef_Spec_Or_Body --
-------------------------
function Predef_Spec_Or_Body
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : Name_Id;
Profile : List_Id;
Ret_Type : Entity_Id := Empty;
For_Body : Boolean := False) return Node_Id
is
Id : constant Entity_Id := Make_Defining_Identifier (Loc, Name);
Spec : Node_Id;
begin
Set_Is_Public (Id, Is_Public (Tag_Typ));
-- The internal flag is set to mark these declarations because
-- they have specific properties. First they are primitives even
-- if they are not defined in the type scope (the freezing point
-- is not necessarily in the same scope), furthermore the
-- predefined equality can be overridden by a user-defined
-- equality, no body will be generated in this case.
Set_Is_Internal (Id);
if not Debug_Generated_Code then
Set_Debug_Info_Off (Id);
end if;
if No (Ret_Type) then
Spec :=
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Id,
Parameter_Specifications => Profile);
else
Spec :=
Make_Function_Specification (Loc,
Defining_Unit_Name => Id,
Parameter_Specifications => Profile,
Result_Definition =>
New_Reference_To (Ret_Type, Loc));
end if;
-- If body case, return empty subprogram body. Note that this is
-- ill-formed, because there is not even a null statement, and
-- certainly not a return in the function case. The caller is
-- expected to do surgery on the body to add the appropriate stuff.
if For_Body then
return Make_Subprogram_Body (Loc, Spec, Empty_List, Empty);
-- For the case of Input/Output attributes applied to an abstract type,
-- generate abstract specifications. These will never be called,
-- but we need the slots allocated in the dispatching table so
-- that typ'Class'Input and typ'Class'Output will work properly.
elsif (Is_TSS (Name, TSS_Stream_Input)
or else
Is_TSS (Name, TSS_Stream_Output))
and then Is_Abstract (Tag_Typ)
then
return Make_Abstract_Subprogram_Declaration (Loc, Spec);
-- Normal spec case, where we return a subprogram declaration
else
return Make_Subprogram_Declaration (Loc, Spec);
end if;
end Predef_Spec_Or_Body;
-----------------------------
-- Predef_Stream_Attr_Spec --
-----------------------------
function Predef_Stream_Attr_Spec
(Loc : Source_Ptr;
Tag_Typ : Entity_Id;
Name : TSS_Name_Type;
For_Body : Boolean := False) return Node_Id
is
Ret_Type : Entity_Id;
begin
if Name = TSS_Stream_Input then
Ret_Type := Tag_Typ;
else
Ret_Type := Empty;
end if;
return Predef_Spec_Or_Body (Loc,
Name => Make_TSS_Name (Tag_Typ, Name),
Tag_Typ => Tag_Typ,
Profile => Build_Stream_Attr_Profile (Loc, Tag_Typ, Name),
Ret_Type => Ret_Type,
For_Body => For_Body);
end Predef_Stream_Attr_Spec;
---------------------------------
-- Predefined_Primitive_Bodies --
---------------------------------
function Predefined_Primitive_Bodies
(Tag_Typ : Entity_Id;
Renamed_Eq : Node_Id) return List_Id
is
Loc : constant Source_Ptr := Sloc (Tag_Typ);
Res : constant List_Id := New_List;
Decl : Node_Id;
Prim : Elmt_Id;
Eq_Needed : Boolean;
Eq_Name : Name_Id;
Ent : Entity_Id;
begin
-- See if we have a predefined "=" operator
if Present (Renamed_Eq) then
Eq_Needed := True;
Eq_Name := Chars (Renamed_Eq);
else
Eq_Needed := False;
Eq_Name := No_Name;
Prim := First_Elmt (Primitive_Operations (Tag_Typ));
while Present (Prim) loop
if Chars (Node (Prim)) = Name_Op_Eq
and then Is_Internal (Node (Prim))
then
Eq_Needed := True;
Eq_Name := Name_Op_Eq;
end if;
Next_Elmt (Prim);
end loop;
end if;
-- Body of _Alignment
Decl := Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uAlignment,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Integer,
For_Body => True);
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, New_List (
Make_Return_Statement (Loc,
Expression =>
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_X),
Attribute_Name => Name_Alignment)))));
Append_To (Res, Decl);
-- Body of _Size
Decl := Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uSize,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Long_Long_Integer,
For_Body => True);
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, New_List (
Make_Return_Statement (Loc,
Expression =>
Make_Attribute_Reference (Loc,
Prefix => Make_Identifier (Loc, Name_X),
Attribute_Name => Name_Size)))));
Append_To (Res, Decl);
-- Bodies for Dispatching stream IO routines. We need these only for
-- non-limited types (in the limited case there is no dispatching).
-- We also skip them if dispatching or finalization are not available.
if Stream_Operation_OK (Tag_Typ, TSS_Stream_Read)
and then No (TSS (Tag_Typ, TSS_Stream_Read))
then
Build_Record_Read_Procedure (Loc, Tag_Typ, Decl, Ent);
Append_To (Res, Decl);
end if;
if Stream_Operation_OK (Tag_Typ, TSS_Stream_Write)
and then No (TSS (Tag_Typ, TSS_Stream_Write))
then
Build_Record_Write_Procedure (Loc, Tag_Typ, Decl, Ent);
Append_To (Res, Decl);
end if;
-- Skip bodies of _Input and _Output for the abstract case, since
-- the corresponding specs are abstract (see Predef_Spec_Or_Body)
if not Is_Abstract (Tag_Typ) then
if Stream_Operation_OK (Tag_Typ, TSS_Stream_Input)
and then No (TSS (Tag_Typ, TSS_Stream_Input))
then
Build_Record_Or_Elementary_Input_Function
(Loc, Tag_Typ, Decl, Ent);
Append_To (Res, Decl);
end if;
if Stream_Operation_OK (Tag_Typ, TSS_Stream_Output)
and then No (TSS (Tag_Typ, TSS_Stream_Output))
then
Build_Record_Or_Elementary_Output_Procedure
(Loc, Tag_Typ, Decl, Ent);
Append_To (Res, Decl);
end if;
end if;
-- Generate the bodies for the following primitive operations:
-- disp_asynchronous_select
-- disp_conditional_select
-- disp_get_prim_op_kind
-- disp_get_task_id
-- disp_timed_select
-- for limited interfaces and synchronized types that implement a
-- limited interface. The interface versions will have null bodies.
if Ada_Version >= Ada_05
and then
not Restriction_Active (No_Dispatching_Calls)
and then
((Is_Interface (Tag_Typ) and then Is_Limited_Record (Tag_Typ))
or else
(Is_Concurrent_Record_Type (Tag_Typ)
and then Implements_Interface (
Typ => Tag_Typ,
Kind => Any_Limited_Interface,
Check_Parent => True)))
then
Append_To (Res, Make_Disp_Asynchronous_Select_Body (Tag_Typ));
Append_To (Res, Make_Disp_Conditional_Select_Body (Tag_Typ));
Append_To (Res, Make_Disp_Get_Prim_Op_Kind_Body (Tag_Typ));
Append_To (Res, Make_Disp_Get_Task_Id_Body (Tag_Typ));
Append_To (Res, Make_Disp_Timed_Select_Body (Tag_Typ));
end if;
if not Is_Limited_Type (Tag_Typ) then
-- Body for equality
if Eq_Needed then
Decl :=
Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Eq_Name,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_X),
Parameter_Type => New_Reference_To (Tag_Typ, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier =>
Make_Defining_Identifier (Loc, Name_Y),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
Ret_Type => Standard_Boolean,
For_Body => True);
declare
Def : constant Node_Id := Parent (Tag_Typ);
Stmts : constant List_Id := New_List;
Variant_Case : Boolean := Has_Discriminants (Tag_Typ);
Comps : Node_Id := Empty;
Typ_Def : Node_Id := Type_Definition (Def);
begin
if Variant_Case then
if Nkind (Typ_Def) = N_Derived_Type_Definition then
Typ_Def := Record_Extension_Part (Typ_Def);
end if;
if Present (Typ_Def) then
Comps := Component_List (Typ_Def);
end if;
Variant_Case := Present (Comps)
and then Present (Variant_Part (Comps));
end if;
if Variant_Case then
Append_To (Stmts,
Make_Eq_If (Tag_Typ, Discriminant_Specifications (Def)));
Append_List_To (Stmts, Make_Eq_Case (Tag_Typ, Comps));
Append_To (Stmts,
Make_Return_Statement (Loc,
Expression => New_Reference_To (Standard_True, Loc)));
else
Append_To (Stmts,
Make_Return_Statement (Loc,
Expression =>
Expand_Record_Equality (Tag_Typ,
Typ => Tag_Typ,
Lhs => Make_Identifier (Loc, Name_X),
Rhs => Make_Identifier (Loc, Name_Y),
Bodies => Declarations (Decl))));
end if;
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, Stmts));
end;
Append_To (Res, Decl);
end if;
-- Body for dispatching assignment
Decl :=
Predef_Spec_Or_Body (Loc,
Tag_Typ => Tag_Typ,
Name => Name_uAssign,
Profile => New_List (
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_X),
Out_Present => True,
Parameter_Type => New_Reference_To (Tag_Typ, Loc)),
Make_Parameter_Specification (Loc,
Defining_Identifier => Make_Defining_Identifier (Loc, Name_Y),
Parameter_Type => New_Reference_To (Tag_Typ, Loc))),
For_Body => True);
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, New_List (
Make_Assignment_Statement (Loc,
Name => Make_Identifier (Loc, Name_X),
Expression => Make_Identifier (Loc, Name_Y)))));
Append_To (Res, Decl);
end if;
-- Generate dummy bodies for finalization actions of types that have
-- no controlled components.
-- Skip this processing if we are in the finalization routine in the
-- runtime itself, otherwise we get hopelessly circularly confused!
if In_Finalization_Root (Tag_Typ) then
null;
-- Skip this if finalization is not available
elsif Restriction_Active (No_Finalization) then
null;
elsif (Etype (Tag_Typ) = Tag_Typ or else Is_Controlled (Tag_Typ))
and then not Has_Controlled_Component (Tag_Typ)
then
if not Is_Limited_Type (Tag_Typ) then
Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Adjust, True);
if Is_Controlled (Tag_Typ) then
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc,
Make_Adjust_Call (
Ref => Make_Identifier (Loc, Name_V),
Typ => Tag_Typ,
Flist_Ref => Make_Identifier (Loc, Name_L),
With_Attach => Make_Identifier (Loc, Name_B))));
else
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, New_List (
Make_Null_Statement (Loc))));
end if;
Append_To (Res, Decl);
end if;
Decl := Predef_Deep_Spec (Loc, Tag_Typ, TSS_Deep_Finalize, True);
if Is_Controlled (Tag_Typ) then
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc,
Make_Final_Call (
Ref => Make_Identifier (Loc, Name_V),
Typ => Tag_Typ,
With_Detach => Make_Identifier (Loc, Name_B))));
else
Set_Handled_Statement_Sequence (Decl,
Make_Handled_Sequence_Of_Statements (Loc, New_List (
Make_Null_Statement (Loc))));
end if;
Append_To (Res, Decl);
end if;
return Res;
end Predefined_Primitive_Bodies;
---------------------------------
-- Predefined_Primitive_Freeze --
---------------------------------
function Predefined_Primitive_Freeze
(Tag_Typ : Entity_Id) return List_Id
is
Loc : constant Source_Ptr := Sloc (Tag_Typ);
Res : constant List_Id := New_List;
Prim : Elmt_Id;
Frnodes : List_Id;
begin
Prim := First_Elmt (Primitive_Operations (Tag_Typ));
while Present (Prim) loop
if Is_Internal (Node (Prim)) then
Frnodes := Freeze_Entity (Node (Prim), Loc);
if Present (Frnodes) then
Append_List_To (Res, Frnodes);
end if;
end if;
Next_Elmt (Prim);
end loop;
return Res;
end Predefined_Primitive_Freeze;
-------------------------
-- Stream_Operation_OK --
-------------------------
function Stream_Operation_OK
(Typ : Entity_Id;
Operation : TSS_Name_Type) return Boolean
is
Has_Inheritable_Stream_Attribute : Boolean := False;
begin
if Is_Limited_Type (Typ)
and then Is_Tagged_Type (Typ)
and then Is_Derived_Type (Typ)
then
-- Special case of a limited type extension: a default implementation
-- of the stream attributes Read and Write exists if the attribute
-- has been specified for an ancestor type.
Has_Inheritable_Stream_Attribute :=
Present (Find_Inherited_TSS (Base_Type (Etype (Typ)), Operation));
end if;
return
not (Is_Limited_Type (Typ)
and then not Has_Inheritable_Stream_Attribute)
and then not Has_Unknown_Discriminants (Typ)
and then RTE_Available (RE_Tag)
and then RTE_Available (RE_Root_Stream_Type)
and then not Restriction_Active (No_Dispatch)
and then not Restriction_Active (No_Streams);
end Stream_Operation_OK;
end Exp_Ch3;
|
pragma Style_Checks (Off);
package Mat.Expressions.Parser_Goto is
type Small_Integer is range -32_000 .. 32_000;
type Goto_Entry is record
Nonterm : Small_Integer;
Newstate : Small_Integer;
end record;
--pragma suppress(index_check);
subtype Row is Integer range -1 .. Integer'Last;
type Goto_Parse_Table is array (Row range <>) of Goto_Entry;
Goto_Matrix : constant Goto_Parse_Table :=
((-1,-1) -- Dummy Entry.
-- State 0
,(-6,15),(-5,22),(-3,1),(-2,26)
-- State 2
,(-6,15),(-5,22),(-3,29)
-- State 3
,(-6,15),(-5,22),(-3,30)
-- State 4
,(-4,32)
-- State 5
,(-4,33)
-- State 6
,(-7,36)
-- State 7
,(-7,37)
-- State 8
,(-7,38)
-- State 9
,(-5,39)
-- State 10
,(-8,46)
-- State 11
,(-8,47)
-- State 12
,(-6,48)
-- State 13
,(-8,49)
-- State 14
,(-8,50)
-- State 16
,(-8,52)
-- State 27
,(-6,15),(-5,22),(-3,54)
-- State 28
,(-6,15),(-5,22),(-3,55)
-- State 32
,(-5,57)
-- State 33
,(-6,59),(-5,58)
-- State 40
,(-6,61)
-- State 41
,(-6,62)
-- State 42
,(-6,63)
-- State 43
,(-6,64)
-- State 44
,(-6,65)
-- State 45
,(-6,66)
-- State 51
,(-6,67)
-- State 60
,(-7,68)
-- State 69
,(-6,70)
);
-- The offset vector
GOTO_OFFSET : array (0.. 70) of Integer :=
(0,
4,4,7,10,11,12,13,14,15,16,17,18,19,20,21,21,22,
22,22,22,22,22,22,22,22,22,22,25,28,28,28,28,29,31,
31,31,31,31,31,31,32,33,34,35,36,37,37,37,37,37,37,
38,38,38,38,38,38,38,38,38,39,39,39,39,39,39,39,39,
39, 40);
subtype Rule is Natural;
subtype Nonterminal is Integer;
Rule_Length : array (Rule range 0 .. 41) of Natural := (2,
1,3,2,3,3,3,3,3,4,2,2,2,2,2,2,2,2,3,2,1,1,1,1,1,1,2,2,2,2,4,2,2,1,1,0,1,1,
1,1,0,1);
Get_LHS_Rule: array (Rule range 0 .. 41) of Nonterminal := (-1,
-2,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,
-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-3,-8,-8,-8,
-8,-8,-8,-8,-5,-5,-9,-9,-6,-7,-7,-4,-4);
end Mat.Expressions.Parser_Goto;
|
with Ada.Assertions; use Ada.Assertions;
package body Memory.Arbiter is
function Create_Arbiter(next : access Memory_Type'Class)
return Arbiter_Pointer is
result : constant Arbiter_Pointer := new Arbiter_Type;
begin
Set_Memory(result.all, next);
return result;
end Create_Arbiter;
function Clone(mem : Arbiter_Type) return Memory_Pointer is
result : constant Arbiter_Pointer := new Arbiter_Type'(mem);
begin
return Memory_Pointer(result);
end Clone;
procedure Reset(mem : in out Arbiter_Type;
context : in Natural) is
begin
Reset(Container_Type(mem), context);
end Reset;
procedure Set_Port(mem : in out Arbiter_Type;
port : in Natural;
ready : out Boolean) is
begin
mem.port := port;
ready := True;
end Set_Port;
function Get_Next_Time(mem : Arbiter_Type) return Time_Type is
begin
if mem.port > mem.pending.Last_Index then
return 0;
else
return mem.pending.Element(mem.port);
end if;
end Get_Next_Time;
procedure Read(mem : in out Arbiter_Type;
address : in Address_Type;
size : in Positive) is
begin
Read(Container_Type(mem), address, size);
end Read;
procedure Write(mem : in out Arbiter_Type;
address : in Address_Type;
size : in Positive) is
begin
Write(Container_Type(mem), address, size);
end Write;
procedure Idle(mem : in out Arbiter_Type;
cycles : in Time_Type) is
begin
Assert(False, "Memory.Arbiter.Idle not implemented");
end Idle;
function To_String(mem : Arbiter_Type) return Unbounded_String is
result : Unbounded_String;
begin
Append(result, "(arbiter ");
Append(result, "(memory ");
Append(result, To_String(Get_Memory(mem).all));
Append(result, ")");
Append(result, ")");
return result;
end To_String;
end Memory.Arbiter;
|
package estado_casillero is
type t_estado_casillero is (Limpio,Sucio);
function random_estado return t_estado_casillero;
procedure put_estado_casillero (c : in t_estado_casillero);
end estado_casillero;
|
-- FILE: oedipus-elementary_functions.ads LICENSE: MIT © 2021 Mae Morella
with Oedipus; use Oedipus;
package Oedipus.Elementary_Functions is
Div_By_Zero : exception;
function "+" (C : in Complex) return Complex;
-- PRECOND: none
-- POSTCOND: positive C is returned
function "-" (C : in Complex) return Complex;
-- PRECOND: none
-- POSTCOND: negative of C is returned
function "+" (C1, C2 : in Complex) return Complex;
-- PRECOND: none
-- POSTCOND: sum of C1 & C2 is returned
function "-" (C1, C2 : in Complex) return Complex;
-- PRECOND: none
-- POSTCOND: difference of C1 & C2 is returned
function "*" (C1, C2 : in Complex) return Complex;
-- PRECOND: none
-- POSTCOND: product of C1 & C2 is returned
function "/" (C1, C2 : in Complex) return Complex;
-- PRECOND: C2 is not 0+0i. POSTCOND: quotient of C1 & C2 is returned
-- exceptions: Div_By_Zero is raised if precondition fails
end Oedipus.Elementary_Functions;
|
-- C48009B.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- FOR ALLOCATORS OF THE FORM "NEW T'(X)", CHECK THAT CONSTRAINT_ERROR
-- IS RAISED IF T IS AN UNCONSTRAINED RECORD OR PRIVATE TYPE, (X) IS AN
-- AGGREGATE OR A VALUE OF TYPE T, AND ONE OF THE DISCRIMINANT VALUES IN
-- X:
-- 1) DOES NOT SATISFY THE RANGE CONSTRAINT FOR THE CORRESPONDING
-- DISCRIMINANT OF T.
-- 2) DOES NOT EQUAL THE DISCRIMINANT VALUE SPECIFIED IN THE
-- DECLARATION OF THE ALLOCATOR'S BASE TYPE.
-- 3) A DISCRIMINANT VALUE IS COMPATIBLE WITH A DISCRIMINANT'S SUBTYPE
-- BUT DOES NOT PROVIDE A COMPATIBLE INDEX OR DISCRIMINANT
-- CONSTRAINT FOR A SUBCOMPONENT DEPENDENT ON THE DISCRIMINANT.
-- RM 01/08/80
-- NL 10/13/81
-- SPS 10/26/82
-- JBG 03/02/83
-- EG 07/05/84
WITH REPORT;
PROCEDURE C48009B IS
USE REPORT;
BEGIN
TEST( "C48009B" , "FOR ALLOCATORS OF THE FORM 'NEW T '(X)', " &
"CHECK THAT CONSTRAINT_ERROR IS RAISED WHEN " &
"APPROPRIATE - UNCONSTRAINED RECORD AND " &
"PRIVATE TYPES");
DECLARE
SUBTYPE I1_7 IS INTEGER RANGE IDENT_INT(1)..IDENT_INT(7);
SUBTYPE I1_10 IS INTEGER RANGE IDENT_INT(1)..IDENT_INT(10);
SUBTYPE I2_9 IS INTEGER RANGE IDENT_INT(2)..IDENT_INT(9);
TYPE REC (A : I2_9) IS
RECORD
NULL;
END RECORD;
TYPE ARR IS ARRAY (I2_9 RANGE <>) OF INTEGER;
TYPE T_REC (C : I1_10) IS
RECORD
D : REC(C);
END RECORD;
TYPE T_ARR (C : I1_10) IS
RECORD
D : ARR(2..C);
E : ARR(C..9);
END RECORD;
TYPE T_REC_REC (A : I1_10) IS
RECORD
B : T_REC(A);
END RECORD;
TYPE T_REC_ARR (A : I1_10) IS
RECORD
B : T_ARR(A);
END RECORD;
TYPE TB ( A : I1_7 ) IS
RECORD
R : INTEGER;
END RECORD;
TYPE A_T_REC_REC IS ACCESS T_REC_REC;
TYPE A_T_REC_ARR IS ACCESS T_REC_ARR;
TYPE ATB IS ACCESS TB;
TYPE ACTB IS ACCESS TB(3);
VA_T_REC_REC : A_T_REC_REC;
VA_T_REC_ARR : A_T_REC_ARR;
VB : ATB;
VCB : ACTB;
PACKAGE P IS
TYPE PRIV( A : I1_10 ) IS PRIVATE;
CONS_PRIV : CONSTANT PRIV;
PRIVATE
TYPE PRIV( A : I1_10 ) IS
RECORD
R : INTEGER;
END RECORD;
CONS_PRIV : CONSTANT PRIV := (2, 3);
END P;
USE P;
TYPE A_PRIV IS ACCESS P.PRIV;
TYPE A_CPRIV IS ACCESS P.PRIV (3);
VP : A_PRIV;
VCP : A_CPRIV;
FUNCTION ALLOC1(X : P.PRIV) RETURN A_CPRIV IS
BEGIN
IF EQUAL(1, 1) THEN
RETURN NEW P.PRIV'(X);
ELSE
RETURN NULL;
END IF;
END ALLOC1;
FUNCTION ALLOC2(X : TB) RETURN ACTB IS
BEGIN
IF EQUAL(1, 1) THEN
RETURN NEW TB'(X);
ELSE
RETURN NULL;
END IF;
END ALLOC2;
BEGIN
BEGIN -- B1
VB := NEW TB'(A => IDENT_INT(0), R => 1);
FAILED ("NO EXCEPTION RAISED - CASE 1A");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED( "WRONG EXCEPTION RAISED - CASE 1A" );
END;
BEGIN
VB := NEW TB'(A => 8, R => 1);
FAILED ("NO EXCEPTION RAISED - CASE 1B");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED( "WRONG EXCEPTION RAISED - CASE 1B");
END; -- B1
BEGIN -- B2
VCB := NEW TB'(2, 3);
FAILED ("NO EXCEPTION RAISED - CASE 2A");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 2A");
END;
BEGIN
IF ALLOC2((IDENT_INT(4), 3)) = NULL THEN
FAILED ("IMPOSSIBLE - CASE 2B");
END IF;
FAILED ("NO EXCEPTION RAISED - CASE 2B");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 2B");
END;
BEGIN
IF ALLOC1(CONS_PRIV) = NULL THEN
FAILED ("IMPOSSIBLE - CASE 2C");
END IF;
FAILED ("NO EXCEPTION RAISED - CASE 2C");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 2C");
END; -- B2
BEGIN -- B3
VA_T_REC_REC := NEW T_REC_REC'(1, (1, (A => 1)));
FAILED ("NO EXCEPTION RAISED - CASE 3A");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3A");
END;
BEGIN
VA_T_REC_REC := NEW T_REC_REC'(10,
(10, (A => 10)));
FAILED ("NO EXCEPTION RAISED - CASE 3B");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3B");
END;
BEGIN
VA_T_REC_ARR := NEW T_REC_ARR'(1, (1, (OTHERS => 1),
(OTHERS => 2)));
FAILED ("NO EXCEPTION RAISED - CASE 3C");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3C");
END;
BEGIN
VA_T_REC_ARR := NEW T_REC_ARR'(10, (10, (OTHERS => 1),
(OTHERS => 2)));
FAILED ("NO EXCEPTION RAISED - CASE 3D");
EXCEPTION
WHEN CONSTRAINT_ERROR => NULL;
WHEN OTHERS =>
FAILED ("WRONG EXCEPTION RAISED - CASE 3D");
END;
END;
RESULT;
END C48009B;
|
-----------------------------------------------------------------------
-- Util.Beans.Objects.Discretes -- Unit tests for concurrency package
-- Copyright (C) 2009, 2010, 2020 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.Calendar.Formatting;
with Util.Beans.Objects;
with Util.Beans.Objects.Enums;
with Util.Beans.Objects.Time;
with Util.Beans.Objects.Discrete_Tests;
package body Util.Beans.Objects.Discretes is
use Ada.Calendar;
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time;
function Time_Value (S : String) return Ada.Calendar.Time;
function "-" (Left, Right : Boolean) return Boolean;
function "+" (Left, Right : Boolean) return Boolean;
package Test_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Integer,
To_Type => Util.Beans.Objects.To_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Integer'Value,
Test_Name => "Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Duration is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Duration,
To_Type => Util.Beans.Objects.To_Duration,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Duration'Value,
Test_Name => "Duration",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Integer'Value,
Test_Name => "Long_Integer",
Test_Values => "-100,1,0,1,1000");
package Test_Long_Long_Integer is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Integer,
To_Type => Util.Beans.Objects.To_Long_Long_Integer,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Integer'Value,
Test_Name => "Long_Long_Integer",
Test_Values => "-10000000000000,1,0,1,1000_000_000_000");
function "-" (Left, Right : Boolean) return Boolean is
begin
return Left and Right;
end "-";
function "+" (Left, Right : Boolean) return Boolean is
begin
return Left or Right;
end "+";
package Test_Boolean is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Boolean,
To_Type => Util.Beans.Objects.To_Boolean,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Boolean'Value,
Test_Name => "Boolean",
Test_Values => "false,true");
type Color is (WHITE, BLACK, RED, GREEN, BLUE, YELLOW);
package Color_Object is new Util.Beans.Objects.Enums (Color, ROUND_VALUE => True);
function "-" (Left, Right : Color) return Color;
function "+" (Left, Right : Color) return Color;
function "-" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) - Color'Pos (Right);
begin
if N >= 0 then
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
else
return Color'Val ((Color'Pos (WHITE) - N) mod 6);
end if;
end "-";
function "+" (Left, Right : Color) return Color is
N : constant Integer := Color'Pos (Left) + Color'Pos (Right);
begin
return Color'Val ((Color'Pos (WHITE) + N) mod 6);
end "+";
package Test_Enum is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Color,
To_Type => Color_Object.To_Value,
To_Object_Test => Color_Object.To_Object,
Value => Color'Value,
Test_Name => "Color",
Test_Values => "BLACK,RED,GREEN,BLUE,YELLOW");
Epoch : constant Ada.Calendar.Time :=
Ada.Calendar.Time_Of (Year => Year_Number'First,
Month => 1,
Day => 1,
Seconds => 12 * 3600.0);
function Time_Value (S : String) return Ada.Calendar.Time is
begin
return Ada.Calendar.Formatting.Value (S);
end Time_Value;
-- For the purpose of the time unit test, we need Time + Time operation even
-- if this does not really makes sense.
function "+" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 + T2) + Epoch;
end "+";
function "-" (Left, Right : Ada.Calendar.Time) return Ada.Calendar.Time is
T1 : constant Duration := Left - Epoch;
T2 : constant Duration := Right - Epoch;
begin
return (T1 - T2) + Epoch;
end "-";
package Test_Time is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Ada.Calendar.Time,
To_Type => Util.Beans.Objects.Time.To_Time,
To_Object_Test => Util.Beans.Objects.Time.To_Object,
Value => Time_Value,
Test_Name => "Time",
Test_Values => "1970-03-04 12:12:00,1975-05-04 13:13:10");
package Test_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Float,
To_Type => Util.Beans.Objects.To_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Float'Value,
Test_Name => "Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Float,
To_Type => Util.Beans.Objects.To_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Float'Value,
Test_Name => "Long_Float",
Test_Values => "1.2,3.3,-3.3");
package Test_Long_Long_Float is new
Util.Beans.Objects.Discrete_Tests (Test_Type => Long_Long_Float,
To_Type => Util.Beans.Objects.To_Long_Long_Float,
To_Object_Test => Util.Beans.Objects.To_Object,
Value => Long_Long_Float'Value,
Test_Name => "Long_Long_Float",
Test_Values => "1.2,3.3,-3.3");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Test_Boolean.Add_Tests (Suite);
Test_Integer.Add_Tests (Suite);
Test_Long_Integer.Add_Tests (Suite);
Test_Duration.Add_Tests (Suite);
Test_Long_Long_Integer.Add_Tests (Suite);
Test_Time.Add_Tests (Suite);
Test_Float.Add_Tests (Suite);
Test_Long_Float.Add_Tests (Suite);
Test_Long_Long_Float.Add_Tests (Suite);
Test_Enum.Add_Tests (Suite);
end Add_Tests;
end Util.Beans.Objects.Discretes;
|
with Ada.Text_IO;
use Ada.Text_IO;
procedure AdaHelloWorld is
begin
Put_Line ("Hello World");
end AdaHelloWorld; |
with Ada.Text_IO; use Ada.Text_IO;
procedure Test is
type R is record A, B: Character; end record;
X: R;
function F return R is
begin
return X;
end;
procedure Update(C: in out Character) is
begin
C := '0';
end;
begin
update(F.A);
end Test;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package body Bit_Fields is
type Convert_8 (As_Array : Boolean := False) is record
case As_Array is
when False =>
Value : UInt8;
when True =>
Bits : Bit_Field (0 .. 7);
end case;
end record with Unchecked_Union, Size => 8;
for Convert_8 use record
Value at 0 range 0 .. 7;
Bits at 0 range 0 .. 7;
end record;
type Convert_16 (As_Array : Boolean := False) is record
case As_Array is
when False =>
Value : UInt16;
when True =>
Bits : Bit_Field (0 .. 15);
end case;
end record with Unchecked_Union, Size => 16;
for Convert_16 use record
Value at 0 range 0 .. 15;
Bits at 0 range 0 .. 15;
end record;
type Convert_32 (As_Array : Boolean := False) is record
case As_Array is
when False =>
Value : UInt32;
when True =>
Bits : Bit_Field (0 .. 31);
end case;
end record with Unchecked_Union, Size => 32;
for Convert_32 use record
Value at 0 range 0 .. 31;
Bits at 0 range 0 .. 31;
end record;
-------------
-- To_Word --
-------------
function To_Word (Bits : Bit_Field) return UInt32 is
Tmp : Convert_32;
begin
Tmp.Bits := Bits;
return Tmp.Value;
end To_Word;
--------------
-- To_UInt16 --
--------------
function To_UInt16 (Bits : Bit_Field) return UInt16 is
Tmp : Convert_16;
begin
Tmp.Bits := Bits;
return Tmp.Value;
end To_UInt16;
-------------
-- To_UInt8 --
-------------
function To_UInt8 (Bits : Bit_Field) return UInt8 is
Tmp : Convert_8;
begin
Tmp.Bits := Bits;
return Tmp.Value;
end To_UInt8;
------------------
-- To_Bit_Field --
------------------
function To_Bit_Field (Value : UInt32) return Bit_Field is
Tmp : Convert_32;
begin
Tmp.Value := Value;
return Tmp.Bits;
end To_Bit_Field;
------------------
-- To_Bit_Field --
------------------
function To_Bit_Field (Value : UInt16) return Bit_Field is
Tmp : Convert_16;
begin
Tmp.Value := Value;
return Tmp.Bits;
end To_Bit_Field;
------------------
-- To_Bit_Field --
------------------
function To_Bit_Field (Value : UInt8) return Bit_Field is
Tmp : Convert_8;
begin
Tmp.Value := Value;
return Tmp.Bits;
end To_Bit_Field;
end Bit_Fields;
|
-- This spec has been automatically generated from STM32F105xx.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
with System;
package STM32.FLASH is
pragma Preelaborate;
---------------
-- Registers --
---------------
------------------
-- ACR_Register --
------------------
subtype ACR_LATENCY_Field is STM32.UInt3;
subtype ACR_HLFCYA_Field is STM32.Bit;
subtype ACR_PRFTBE_Field is STM32.Bit;
subtype ACR_PRFTBS_Field is STM32.Bit;
-- Flash access control register
type ACR_Register is record
-- Latency
LATENCY : ACR_LATENCY_Field := 16#0#;
-- Flash half cycle access enable
HLFCYA : ACR_HLFCYA_Field := 16#0#;
-- Prefetch buffer enable
PRFTBE : ACR_PRFTBE_Field := 16#1#;
-- Read-only. Prefetch buffer status
PRFTBS : ACR_PRFTBS_Field := 16#1#;
-- unspecified
Reserved_6_31 : STM32.UInt26 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for ACR_Register use record
LATENCY at 0 range 0 .. 2;
HLFCYA at 0 range 3 .. 3;
PRFTBE at 0 range 4 .. 4;
PRFTBS at 0 range 5 .. 5;
Reserved_6_31 at 0 range 6 .. 31;
end record;
-----------------
-- SR_Register --
-----------------
subtype SR_BSY_Field is STM32.Bit;
subtype SR_PGERR_Field is STM32.Bit;
subtype SR_WRPRTERR_Field is STM32.Bit;
subtype SR_EOP_Field is STM32.Bit;
-- Status register
type SR_Register is record
-- Read-only. Busy
BSY : SR_BSY_Field := 16#0#;
-- unspecified
Reserved_1_1 : STM32.Bit := 16#0#;
-- Programming error
PGERR : SR_PGERR_Field := 16#0#;
-- unspecified
Reserved_3_3 : STM32.Bit := 16#0#;
-- Write protection error
WRPRTERR : SR_WRPRTERR_Field := 16#0#;
-- End of operation
EOP : SR_EOP_Field := 16#0#;
-- unspecified
Reserved_6_31 : STM32.UInt26 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for SR_Register use record
BSY at 0 range 0 .. 0;
Reserved_1_1 at 0 range 1 .. 1;
PGERR at 0 range 2 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
WRPRTERR at 0 range 4 .. 4;
EOP at 0 range 5 .. 5;
Reserved_6_31 at 0 range 6 .. 31;
end record;
-----------------
-- CR_Register --
-----------------
subtype CR_PG_Field is STM32.Bit;
subtype CR_PER_Field is STM32.Bit;
subtype CR_MER_Field is STM32.Bit;
subtype CR_OPTPG_Field is STM32.Bit;
subtype CR_OPTER_Field is STM32.Bit;
subtype CR_STRT_Field is STM32.Bit;
subtype CR_LOCK_Field is STM32.Bit;
subtype CR_OPTWRE_Field is STM32.Bit;
subtype CR_ERRIE_Field is STM32.Bit;
subtype CR_EOPIE_Field is STM32.Bit;
-- Control register
type CR_Register is record
-- Programming
PG : CR_PG_Field := 16#0#;
-- Page Erase
PER : CR_PER_Field := 16#0#;
-- Mass Erase
MER : CR_MER_Field := 16#0#;
-- unspecified
Reserved_3_3 : STM32.Bit := 16#0#;
-- Option byte programming
OPTPG : CR_OPTPG_Field := 16#0#;
-- Option byte erase
OPTER : CR_OPTER_Field := 16#0#;
-- Start
STRT : CR_STRT_Field := 16#0#;
-- Lock
LOCK : CR_LOCK_Field := 16#1#;
-- unspecified
Reserved_8_8 : STM32.Bit := 16#0#;
-- Option bytes write enable
OPTWRE : CR_OPTWRE_Field := 16#0#;
-- Error interrupt enable
ERRIE : CR_ERRIE_Field := 16#0#;
-- unspecified
Reserved_11_11 : STM32.Bit := 16#0#;
-- End of operation interrupt enable
EOPIE : CR_EOPIE_Field := 16#0#;
-- unspecified
Reserved_13_31 : STM32.UInt19 := 16#0#;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for CR_Register use record
PG at 0 range 0 .. 0;
PER at 0 range 1 .. 1;
MER at 0 range 2 .. 2;
Reserved_3_3 at 0 range 3 .. 3;
OPTPG at 0 range 4 .. 4;
OPTER at 0 range 5 .. 5;
STRT at 0 range 6 .. 6;
LOCK at 0 range 7 .. 7;
Reserved_8_8 at 0 range 8 .. 8;
OPTWRE at 0 range 9 .. 9;
ERRIE at 0 range 10 .. 10;
Reserved_11_11 at 0 range 11 .. 11;
EOPIE at 0 range 12 .. 12;
Reserved_13_31 at 0 range 13 .. 31;
end record;
------------------
-- OBR_Register --
------------------
subtype OBR_OPTERR_Field is STM32.Bit;
subtype OBR_RDPRT_Field is STM32.Bit;
subtype OBR_WDG_SW_Field is STM32.Bit;
subtype OBR_nRST_STOP_Field is STM32.Bit;
subtype OBR_nRST_STDBY_Field is STM32.Bit;
--------------
-- OBR.Data --
--------------
-- OBR_Data array element
subtype OBR_Data_Element is STM32.Byte;
-- OBR_Data array
type OBR_Data_Field_Array is array (0 .. 1) of OBR_Data_Element
with Component_Size => 8, Size => 16;
-- Type definition for OBR_Data
type OBR_Data_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- Data as a value
Val : STM32.Short;
when True =>
-- Data as an array
Arr : OBR_Data_Field_Array;
end case;
end record
with Unchecked_Union, Size => 16;
for OBR_Data_Field use record
Val at 0 range 0 .. 15;
Arr at 0 range 0 .. 15;
end record;
-- Option byte register
type OBR_Register is record
-- Read-only. Option byte error
OPTERR : OBR_OPTERR_Field;
-- Read-only. Read protection
RDPRT : OBR_RDPRT_Field;
-- Read-only. WDG_SW
WDG_SW : OBR_WDG_SW_Field;
-- Read-only. nRST_STOP
nRST_STOP : OBR_nRST_STOP_Field;
-- Read-only. nRST_STDBY
nRST_STDBY : OBR_nRST_STDBY_Field;
-- unspecified
Reserved_5_9 : STM32.UInt5;
-- Read-only. Data0
Data : OBR_Data_Field;
-- unspecified
Reserved_26_31 : STM32.UInt6;
end record
with Volatile_Full_Access, Size => 32,
Bit_Order => System.Low_Order_First;
for OBR_Register use record
OPTERR at 0 range 0 .. 0;
RDPRT at 0 range 1 .. 1;
WDG_SW at 0 range 2 .. 2;
nRST_STOP at 0 range 3 .. 3;
nRST_STDBY at 0 range 4 .. 4;
Reserved_5_9 at 0 range 5 .. 9;
Data at 0 range 10 .. 25;
Reserved_26_31 at 0 range 26 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- FLASH
type FLASH_Peripheral is record
-- Flash access control register
ACR : ACR_Register;
-- Flash key register
KEYR : STM32.Word;
-- Flash option key register
OPTKEYR : STM32.Word;
-- Status register
SR : SR_Register;
-- Control register
CR : CR_Register;
-- Flash address register
AR : STM32.Word;
-- Option byte register
OBR : OBR_Register;
-- Write protection register
WRPR : STM32.Word;
end record
with Volatile;
for FLASH_Peripheral use record
ACR at 0 range 0 .. 31;
KEYR at 4 range 0 .. 31;
OPTKEYR at 8 range 0 .. 31;
SR at 12 range 0 .. 31;
CR at 16 range 0 .. 31;
AR at 20 range 0 .. 31;
OBR at 28 range 0 .. 31;
WRPR at 32 range 0 .. 31;
end record;
-- FLASH
FLASH_Periph : aliased FLASH_Peripheral
with Import, Address => FLASH_Base;
end STM32.FLASH;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . S T R I N G S . F I X E D --
-- --
-- S p e c --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. In accordance with the copyright of that document, you can freely --
-- copy and modify this specification, provided that if you redistribute a --
-- modified version, any changes that you have made are clearly indicated. --
-- --
------------------------------------------------------------------------------
with Ada.Strings.Maps; use Ada.Strings.Maps;
with Ada.Strings; use Ada.Strings;
package String_Fixed with
SPARK_Mode
is
pragma Preelaborate;
------------------------
-- Search Subprograms --
------------------------
function Index
(Source : String;
Set : Maps.Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward)
return Natural with
Pre => Source'Length = 0 or else From in Source'Range,
Post => Index'Result in 0 | Source'Range,
Contract_Cases =>
((for all I in Source'Range =>
(if I = From or else (I > From) = (Going = Forward) then
(Test = Inside) /= Is_In (Source (I), Set))) =>
Index'Result = 0,
others =>
Index'Result in Source'Range
and then
(Index'Result = From
or else (Index'Result > From) = (Going = Forward))
and then (Test = Inside) = Is_In (Source (Index'Result), Set)
and then
(for all I in Source'Range =>
(if
I /= Index'Result
and then (I < Index'Result) = (Going = Forward)
and then (I = From or else (I > From) = (Going = Forward))
then (Test = Inside) /= Is_In (Source (I), Set))));
-- Index searches for the first or last occurrence of any of a set of
-- characters (when Test=Inside), or any of the complement of a set
-- of characters (when Test=Outside). If Source is the null string,
-- Index returns 0; otherwise, if From is not in Source'Range, then
-- Index_Error is propagated. Otherwise, it returns the smallest index
-- I >= From (if Going=Forward) or the largest index I <= From (if
-- Going=Backward) such that Source(I) satisfies the Test condition with
-- respect to Set; it returns 0 if there is no such Character in Source.
function Any_In_Set
(Source : String;
Set : Maps.Character_Set)
return Boolean is (for some C of Source => Is_In (C, Set)) with
Ghost;
function Is_Valid_Inside_Forward
(Source : String;
Set : Maps.Character_Set;
Result : Natural)
return Boolean is
(if Result = 0 then not Any_In_Set (Source, Set)
elsif Result not in Source'Range then Result = 0
elsif Result = Source'First then Is_In (Source (Result), Set)
else Is_In (Source (Result), Set) and then not Any_In_Set (Source
(Source'First .. Result - 1), Set)) with
Ghost;
function Is_Valid_Inside_Backward
(Source : String;
Set : Maps.Character_Set;
Result : Natural)
return Boolean is
(if Result = 0 then not Any_In_Set (Source, Set)
elsif Result not in Source'Range then Result = 0
elsif Result = Source'Last then Is_In (Source (Result), Set)
else Is_In (Source (Result), Set) and then not Any_In_Set (Source
(Result + 1 .. Source'Last), Set)) with
Ghost;
function All_In_Set
(Source : String;
Set : Maps.Character_Set)
return Boolean is (for all C of Source => Is_In (C, Set)) with
Ghost;
function Is_Valid_Outside_Forward
(Source : String;
Set : Maps.Character_Set;
Result : Natural)
return Boolean is
(if Result = 0 then All_In_Set (Source, Set)
elsif Result not in Source'Range then Result = 0
elsif Result = Source'First then not Is_In (Source (Result), Set)
else not Is_In (Source (Result), Set) and then All_In_Set (Source
(Source'First .. Result - 1), Set)) with
Ghost;
function Is_Valid_Outside_Backward
(Source : String;
Set : Maps.Character_Set;
Result : Natural)
return Boolean is
(if Result = 0 then All_In_Set (Source, Set)
elsif Result not in Source'Range then Result = 0
elsif Result = Source'Last then not Is_In (Source (Result), Set)
else not Is_In (Source (Result), Set) and then All_In_Set (Source
(Result + 1 .. Source'Last), Set)) with
Ghost;
function Index
(Source : String;
Set : Maps.Character_Set;
Test : Membership := Inside;
Going : Direction := Forward)
return Natural with
Post =>
(if Source'Length = 0 then Index'Result = 0
elsif Test = Inside and Going = Forward then
Is_Valid_Inside_Forward (Source, Set, Index'Result)
elsif Test = Inside and Going = Backward then
Is_Valid_Inside_Backward (Source, Set, Index'Result)
elsif Test = Outside and Going = Forward then
Is_Valid_Outside_Forward (Source, Set, Index'Result)
elsif Test = Outside and Going = Backward then
Is_Valid_Outside_Backward (Source, Set, Index'Result)
else False);
-- If Going = Forward,
-- returns Index (Source, Set, Source'First, Test, Forward); otherwise,
-- returns Index (Source, Set, Source'Last, Test, Backward);
function Index_Non_Blank
(Source : String;
From : Positive;
Going : Direction := Forward)
return Natural with
Pre => Source'Length = 0 or else From in Source'Range,
Post => Index_Non_Blank'Result in 0 | Source'Range,
Contract_Cases =>
((for all I in Source'Range =>
(if I = From or else (I > From) = (Going = Forward) then
Source (I) = ' ')) =>
Index_Non_Blank'Result = 0,
others =>
Index_Non_Blank'Result in Source'Range
and then
(Index_Non_Blank'Result = From
or else (Index_Non_Blank'Result > From) = (Going = Forward))
and then Source (Index_Non_Blank'Result) /= ' '
and then
(for all I in Source'Range =>
(if
I /= Index_Non_Blank'Result
and then (I < Index_Non_Blank'Result) = (Going = Forward)
and then (I = From or else (I > From) = (Going = Forward))
then Source (I) = ' ')));
-- Returns Index (Source, Maps.To_Set(Space), From, Outside, Going);
function Index_Non_Blank
(Source : String;
Going : Direction := Forward)
return Natural with
Post => Index_Non_Blank'Result in 0 | Source'Range,
Contract_Cases =>
((for all C of Source => C = ' ') => Index_Non_Blank'Result = 0,
others =>
Index_Non_Blank'Result in Source'Range
and then Source (Index_Non_Blank'Result) /= ' '
and then
(for all I in Source'Range =>
(if
I /= Index_Non_Blank'Result
and then (I < Index_Non_Blank'Result) = (Going = Forward)
then Source (I) = ' ')));
-- Returns Index(Source, Maps.To_Set(Space), Outside, Going)
---------------------------------------
-- String Transformation Subprograms --
---------------------------------------
function Insert
(Source : String;
Before : Positive;
New_Item : String)
return String with
Pre => Before >= Source'First
and then (Source'Last = Integer'Last or else Before <= Source'Last + 1)
and then New_Item'Length <= Integer'Last - Source'Length
and then Source'First = 1 and then New_Item'First = 1,
Post => Insert'Result'First = 1 and then Insert'Result = Source
(Source'First .. Before - 1) & New_Item & Source
(Before .. Source'Last);
-- Propagates Index_Error if Before is not in Source'First ..
-- Source'Last+1; otherwise, returns Source(Source'First..Before-1)
-- & New_Item & Source(Before..Source'Last), but with lower bound 1.
-- Beware of the overflow of the string length !
function Overwrite
(Source : String;
Position : Positive;
New_Item : String)
return String with
Pre => Position >= Source'First
and then (Source'Last = Integer'Last or else Position <= Source'Last + 1)
and then New_Item'Length <= Integer'Last - (Position - Source'First + 1)
and then Source'First = 1 and then New_Item'First = 1,
Post => Overwrite'Result'First = 1 and then Overwrite'Result = Source
(1 .. Position - 1) & New_Item &
(if New_Item'Length > Source'Last - Position then "" else Source
(Position + New_Item'Length .. Source'Last));
-- Propagates Index_Error if Position is not in Source'First ..
-- Source'Last+1; otherwise, returns the string obtained from Source
-- by consecutively replacing characters starting at Position with
-- corresponding characters from New_Item with lower bound 1. If the end
-- of Source is reached before the characters in New_Item are exhausted,
-- the remaining characters from New_Item are appended to the string.
-- Beware of the overflow of the string length !
function Delete
(Source : String;
From : Positive;
Through : Natural)
return String with
Pre => From > Through
or else (From in Source'Range and then Through <= Source'Last),
Post => Delete'Result'First = 1,
Contract_Cases => (From > Through => Delete'Result = Source,
others => Delete'Result = Source
(Source'First .. From - 1) & (if Through < Source'Last then Source
(Through + 1 .. Source'Last) else ""));
-- If From > Through, the returned string is Source with lower bound
-- 1. If From not in Source'Range, or Through > Source'Last, then
-- Index_Error is propagated. Otherwise, the returned string comprises
-- Source(Source'First..From - 1) & Source(Through+1..Source'Last), but
-- with lower bound 1.
---------------------------------
-- String Selector Subprograms --
---------------------------------
function Trim
(Source : String;
Left : Maps.Character_Set;
Right : Maps.Character_Set)
return String with
Post =>
(if
(for all K in Source'Range => Is_In (Source (K), Left)) or
(for all K in Source'Range => Is_In (Source (K), Right))
then Trim'Result = ""
else
(for some Low in Source'Range =>
(for some High in Source'Range =>
Trim'Result = Source (Low .. High)
and then not Is_In (Source (Low), Left)
and then not Is_In (Source (High), Right)
and then
(for all K in Source'Range =>
(if K < Low then Is_In (Source (K), Left))
and then (if K > High then Is_In (Source (K), Right))))));
-- Returns the string obtained by removing from Source all leading
-- characters in Left and all trailing characters in Right.
function Trim
(Source : String;
Side : Trim_End)
return String with
Post =>
(if (for all K in Source'Range => Source (K) = ' ') then Trim'Result = ""
else
(for some Low in Source'Range =>
(for some High in Source'Range =>
Trim'Result = Source (Low .. High)
and then
(if Side = Left then High = Source'Last
else Source (High) /= ' ')
and then
(if Side = Right then Low = Source'First
else Source (Low) /= ' ')
and then
(for all K in Source'Range =>
(if K < Low then Source (K) = ' ')
and then (if K > High then Source (K) = ' ')))));
-- Returns the string obtained by removing from Source all leading Space
-- characters (if Side = Left), all trailing Space characters (if Side
-- = Right), or all leading and trailing Space characters (if Side =
-- Both).
function Head
(Source : String;
Count : Natural;
Pad : Character := Space)
return String with
Pre => Source'First = 1,
Post => Head'Result'Length = Count,
Contract_Cases => (Count <= Source'Length => Head'Result = Source
(Source'First .. Count),
others => Head'Result = Source & (1 .. Count - Source'Length => Pad));
-- Returns a string of length Count. If Count <= Source'Length, the
-- string comprises the first Count characters of Source. Otherwise,
-- its contents are Source concatenated with Count-Source'Length Pad
-- characters.
function Tail
(Source : String;
Count : Natural;
Pad : Character := Space)
return String with
Pre => Source'First = 1,
Post => Tail'Result'Length = Count,
Contract_Cases => (Count = 0 => Tail'Result = "",
(Count in 1 .. Source'Length) => Tail'Result = Source
(Source'Last - Count + 1 .. Source'Last),
others => Tail'Result = (1 .. Count - Source'Length => Pad) & Source);
-- Returns a string of length Count. If Count <= Source'Length, the
-- string comprises the last Count characters of Source. Otherwise, its
-- contents are Count-Source'Length Pad characters concatenated with
-- Source.
----------------------------------
-- String Constructor Functions --
----------------------------------
function "*"
(Left : Natural;
Right : Character)
return String with
Post => "*"'Result'Length = Left
and then (for all E of "*"'Result => E = Right);
-- This function replicates a character a specified number of times. It
-- returns a string whose length is Left and each of whose elements is
-- Right.
end String_Fixed;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M --
-- --
-- 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 Debug; use Debug;
with Debug_A; use Debug_A;
with Einfo; use Einfo;
with Errout; use Errout;
with Expander; use Expander;
with Fname; use Fname;
with HLO; use HLO;
with Lib; use Lib;
with Lib.Load; use Lib.Load;
with Nlists; use Nlists;
with Opt; use Opt;
with Sem_Attr; use Sem_Attr;
with Sem_Ch2; use Sem_Ch2;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch4; use Sem_Ch4;
with Sem_Ch5; use Sem_Ch5;
with Sem_Ch6; use Sem_Ch6;
with Sem_Ch7; use Sem_Ch7;
with Sem_Ch8; use Sem_Ch8;
with Sem_Ch9; use Sem_Ch9;
with Sem_Ch10; use Sem_Ch10;
with Sem_Ch11; use Sem_Ch11;
with Sem_Ch12; use Sem_Ch12;
with Sem_Ch13; use Sem_Ch13;
with Sem_Prag; use Sem_Prag;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Stand; use Stand;
with Uintp; use Uintp;
pragma Warnings (Off, Sem_Util);
-- Suppress warnings of unused with for Sem_Util (used only in asserts)
package body Sem is
Outer_Generic_Scope : Entity_Id := Empty;
-- Global reference to the outer scope that is generic. In a non
-- generic context, it is empty. At the moment, it is only used
-- for avoiding freezing of external references in generics.
-------------
-- Analyze --
-------------
procedure Analyze (N : Node_Id) is
begin
Debug_A_Entry ("analyzing ", N);
-- Immediate return if already analyzed
if Analyzed (N) then
Debug_A_Exit ("analyzing ", N, " (done, analyzed already)");
return;
end if;
Current_Error_Node := N;
-- Otherwise processing depends on the node kind
case Nkind (N) is
when N_Abort_Statement =>
Analyze_Abort_Statement (N);
when N_Abstract_Subprogram_Declaration =>
Analyze_Abstract_Subprogram_Declaration (N);
when N_Accept_Alternative =>
Analyze_Accept_Alternative (N);
when N_Accept_Statement =>
Analyze_Accept_Statement (N);
when N_Aggregate =>
Analyze_Aggregate (N);
when N_Allocator =>
Analyze_Allocator (N);
when N_And_Then =>
Analyze_Short_Circuit (N);
when N_Assignment_Statement =>
Analyze_Assignment (N);
when N_Asynchronous_Select =>
Analyze_Asynchronous_Select (N);
when N_At_Clause =>
Analyze_At_Clause (N);
when N_Attribute_Reference =>
Analyze_Attribute (N);
when N_Attribute_Definition_Clause =>
Analyze_Attribute_Definition_Clause (N);
when N_Block_Statement =>
Analyze_Block_Statement (N);
when N_Case_Statement =>
Analyze_Case_Statement (N);
when N_Character_Literal =>
Analyze_Character_Literal (N);
when N_Code_Statement =>
Analyze_Code_Statement (N);
when N_Compilation_Unit =>
Analyze_Compilation_Unit (N);
when N_Component_Declaration =>
Analyze_Component_Declaration (N);
when N_Conditional_Expression =>
Analyze_Conditional_Expression (N);
when N_Conditional_Entry_Call =>
Analyze_Conditional_Entry_Call (N);
when N_Delay_Alternative =>
Analyze_Delay_Alternative (N);
when N_Delay_Relative_Statement =>
Analyze_Delay_Relative (N);
when N_Delay_Until_Statement =>
Analyze_Delay_Until (N);
when N_Entry_Body =>
Analyze_Entry_Body (N);
when N_Entry_Body_Formal_Part =>
Analyze_Entry_Body_Formal_Part (N);
when N_Entry_Call_Alternative =>
Analyze_Entry_Call_Alternative (N);
when N_Entry_Declaration =>
Analyze_Entry_Declaration (N);
when N_Entry_Index_Specification =>
Analyze_Entry_Index_Specification (N);
when N_Enumeration_Representation_Clause =>
Analyze_Enumeration_Representation_Clause (N);
when N_Exception_Declaration =>
Analyze_Exception_Declaration (N);
when N_Exception_Renaming_Declaration =>
Analyze_Exception_Renaming (N);
when N_Exit_Statement =>
Analyze_Exit_Statement (N);
when N_Expanded_Name =>
Analyze_Expanded_Name (N);
when N_Explicit_Dereference =>
Analyze_Explicit_Dereference (N);
when N_Extension_Aggregate =>
Analyze_Aggregate (N);
when N_Formal_Object_Declaration =>
Analyze_Formal_Object_Declaration (N);
when N_Formal_Package_Declaration =>
Analyze_Formal_Package (N);
when N_Formal_Subprogram_Declaration =>
Analyze_Formal_Subprogram (N);
when N_Formal_Type_Declaration =>
Analyze_Formal_Type_Declaration (N);
when N_Free_Statement =>
Analyze_Free_Statement (N);
when N_Freeze_Entity =>
null; -- no semantic processing required
when N_Full_Type_Declaration =>
Analyze_Type_Declaration (N);
when N_Function_Call =>
Analyze_Function_Call (N);
when N_Function_Instantiation =>
Analyze_Function_Instantiation (N);
when N_Generic_Function_Renaming_Declaration =>
Analyze_Generic_Function_Renaming (N);
when N_Generic_Package_Declaration =>
Analyze_Generic_Package_Declaration (N);
when N_Generic_Package_Renaming_Declaration =>
Analyze_Generic_Package_Renaming (N);
when N_Generic_Procedure_Renaming_Declaration =>
Analyze_Generic_Procedure_Renaming (N);
when N_Generic_Subprogram_Declaration =>
Analyze_Generic_Subprogram_Declaration (N);
when N_Goto_Statement =>
Analyze_Goto_Statement (N);
when N_Handled_Sequence_Of_Statements =>
Analyze_Handled_Statements (N);
when N_Identifier =>
Analyze_Identifier (N);
when N_If_Statement =>
Analyze_If_Statement (N);
when N_Implicit_Label_Declaration =>
Analyze_Implicit_Label_Declaration (N);
when N_In =>
Analyze_Membership_Op (N);
when N_Incomplete_Type_Declaration =>
Analyze_Incomplete_Type_Decl (N);
when N_Indexed_Component =>
Analyze_Indexed_Component_Form (N);
when N_Integer_Literal =>
Analyze_Integer_Literal (N);
when N_Itype_Reference =>
Analyze_Itype_Reference (N);
when N_Label =>
Analyze_Label (N);
when N_Loop_Statement =>
Analyze_Loop_Statement (N);
when N_Not_In =>
Analyze_Membership_Op (N);
when N_Null =>
Analyze_Null (N);
when N_Null_Statement =>
Analyze_Null_Statement (N);
when N_Number_Declaration =>
Analyze_Number_Declaration (N);
when N_Object_Declaration =>
Analyze_Object_Declaration (N);
when N_Object_Renaming_Declaration =>
Analyze_Object_Renaming (N);
when N_Operator_Symbol =>
Analyze_Operator_Symbol (N);
when N_Op_Abs =>
Analyze_Unary_Op (N);
when N_Op_Add =>
Analyze_Arithmetic_Op (N);
when N_Op_And =>
Analyze_Logical_Op (N);
when N_Op_Concat =>
Analyze_Concatenation (N);
when N_Op_Divide =>
Analyze_Arithmetic_Op (N);
when N_Op_Eq =>
Analyze_Equality_Op (N);
when N_Op_Expon =>
Analyze_Arithmetic_Op (N);
when N_Op_Ge =>
Analyze_Comparison_Op (N);
when N_Op_Gt =>
Analyze_Comparison_Op (N);
when N_Op_Le =>
Analyze_Comparison_Op (N);
when N_Op_Lt =>
Analyze_Comparison_Op (N);
when N_Op_Minus =>
Analyze_Unary_Op (N);
when N_Op_Mod =>
Analyze_Arithmetic_Op (N);
when N_Op_Multiply =>
Analyze_Arithmetic_Op (N);
when N_Op_Ne =>
Analyze_Equality_Op (N);
when N_Op_Not =>
Analyze_Negation (N);
when N_Op_Or =>
Analyze_Logical_Op (N);
when N_Op_Plus =>
Analyze_Unary_Op (N);
when N_Op_Rem =>
Analyze_Arithmetic_Op (N);
when N_Op_Rotate_Left =>
Analyze_Arithmetic_Op (N);
when N_Op_Rotate_Right =>
Analyze_Arithmetic_Op (N);
when N_Op_Shift_Left =>
Analyze_Arithmetic_Op (N);
when N_Op_Shift_Right =>
Analyze_Arithmetic_Op (N);
when N_Op_Shift_Right_Arithmetic =>
Analyze_Arithmetic_Op (N);
when N_Op_Subtract =>
Analyze_Arithmetic_Op (N);
when N_Op_Xor =>
Analyze_Logical_Op (N);
when N_Or_Else =>
Analyze_Short_Circuit (N);
when N_Others_Choice =>
Analyze_Others_Choice (N);
when N_Package_Body =>
Analyze_Package_Body (N);
when N_Package_Body_Stub =>
Analyze_Package_Body_Stub (N);
when N_Package_Declaration =>
Analyze_Package_Declaration (N);
when N_Package_Instantiation =>
Analyze_Package_Instantiation (N);
when N_Package_Renaming_Declaration =>
Analyze_Package_Renaming (N);
when N_Package_Specification =>
Analyze_Package_Specification (N);
when N_Parameter_Association =>
Analyze_Parameter_Association (N);
when N_Pragma =>
Analyze_Pragma (N);
when N_Private_Extension_Declaration =>
Analyze_Private_Extension_Declaration (N);
when N_Private_Type_Declaration =>
Analyze_Private_Type_Declaration (N);
when N_Procedure_Call_Statement =>
Analyze_Procedure_Call (N);
when N_Procedure_Instantiation =>
Analyze_Procedure_Instantiation (N);
when N_Protected_Body =>
Analyze_Protected_Body (N);
when N_Protected_Body_Stub =>
Analyze_Protected_Body_Stub (N);
when N_Protected_Definition =>
Analyze_Protected_Definition (N);
when N_Protected_Type_Declaration =>
Analyze_Protected_Type (N);
when N_Qualified_Expression =>
Analyze_Qualified_Expression (N);
when N_Raise_Statement =>
Analyze_Raise_Statement (N);
when N_Raise_xxx_Error =>
Analyze_Raise_xxx_Error (N);
when N_Range =>
Analyze_Range (N);
when N_Range_Constraint =>
Analyze_Range (Range_Expression (N));
when N_Real_Literal =>
Analyze_Real_Literal (N);
when N_Record_Representation_Clause =>
Analyze_Record_Representation_Clause (N);
when N_Reference =>
Analyze_Reference (N);
when N_Requeue_Statement =>
Analyze_Requeue (N);
when N_Return_Statement =>
Analyze_Return_Statement (N);
when N_Selected_Component =>
Find_Selected_Component (N);
-- ??? why not Analyze_Selected_Component, needs comments
when N_Selective_Accept =>
Analyze_Selective_Accept (N);
when N_Single_Protected_Declaration =>
Analyze_Single_Protected (N);
when N_Single_Task_Declaration =>
Analyze_Single_Task (N);
when N_Slice =>
Analyze_Slice (N);
when N_String_Literal =>
Analyze_String_Literal (N);
when N_Subprogram_Body =>
Analyze_Subprogram_Body (N);
when N_Subprogram_Body_Stub =>
Analyze_Subprogram_Body_Stub (N);
when N_Subprogram_Declaration =>
Analyze_Subprogram_Declaration (N);
when N_Subprogram_Info =>
Analyze_Subprogram_Info (N);
when N_Subprogram_Renaming_Declaration =>
Analyze_Subprogram_Renaming (N);
when N_Subtype_Declaration =>
Analyze_Subtype_Declaration (N);
when N_Subtype_Indication =>
Analyze_Subtype_Indication (N);
when N_Subunit =>
Analyze_Subunit (N);
when N_Task_Body =>
Analyze_Task_Body (N);
when N_Task_Body_Stub =>
Analyze_Task_Body_Stub (N);
when N_Task_Definition =>
Analyze_Task_Definition (N);
when N_Task_Type_Declaration =>
Analyze_Task_Type (N);
when N_Terminate_Alternative =>
Analyze_Terminate_Alternative (N);
when N_Timed_Entry_Call =>
Analyze_Timed_Entry_Call (N);
when N_Triggering_Alternative =>
Analyze_Triggering_Alternative (N);
when N_Type_Conversion =>
Analyze_Type_Conversion (N);
when N_Unchecked_Expression =>
Analyze_Unchecked_Expression (N);
when N_Unchecked_Type_Conversion =>
Analyze_Unchecked_Type_Conversion (N);
when N_Use_Package_Clause =>
Analyze_Use_Package (N);
when N_Use_Type_Clause =>
Analyze_Use_Type (N);
when N_Validate_Unchecked_Conversion =>
null;
when N_Variant_Part =>
Analyze_Variant_Part (N);
when N_With_Clause =>
Analyze_With_Clause (N);
when N_With_Type_Clause =>
Analyze_With_Type_Clause (N);
-- A call to analyze the Empty node is an error, but most likely
-- it is an error caused by an attempt to analyze a malformed
-- piece of tree caused by some other error, so if there have
-- been any other errors, we just ignore it, otherwise it is
-- a real internal error which we complain about.
when N_Empty =>
pragma Assert (Errors_Detected /= 0);
null;
-- A call to analyze the error node is simply ignored, to avoid
-- causing cascaded errors (happens of course only in error cases)
when N_Error =>
null;
-- For the remaining node types, we generate compiler abort, because
-- these nodes are always analyzed within the Sem_Chn routines and
-- there should never be a case of making a call to the main Analyze
-- routine for these node kinds. For example, an N_Access_Definition
-- node appears only in the context of a type declaration, and is
-- processed by the analyze routine for type declarations.
when
N_Abortable_Part |
N_Access_Definition |
N_Access_Function_Definition |
N_Access_Procedure_Definition |
N_Access_To_Object_Definition |
N_Case_Statement_Alternative |
N_Compilation_Unit_Aux |
N_Component_Association |
N_Component_Clause |
N_Component_List |
N_Constrained_Array_Definition |
N_Decimal_Fixed_Point_Definition |
N_Defining_Character_Literal |
N_Defining_Identifier |
N_Defining_Operator_Symbol |
N_Defining_Program_Unit_Name |
N_Delta_Constraint |
N_Derived_Type_Definition |
N_Designator |
N_Digits_Constraint |
N_Discriminant_Association |
N_Discriminant_Specification |
N_Elsif_Part |
N_Entry_Call_Statement |
N_Enumeration_Type_Definition |
N_Exception_Handler |
N_Floating_Point_Definition |
N_Formal_Decimal_Fixed_Point_Definition |
N_Formal_Derived_Type_Definition |
N_Formal_Discrete_Type_Definition |
N_Formal_Floating_Point_Definition |
N_Formal_Modular_Type_Definition |
N_Formal_Ordinary_Fixed_Point_Definition |
N_Formal_Private_Type_Definition |
N_Formal_Signed_Integer_Type_Definition |
N_Function_Specification |
N_Generic_Association |
N_Index_Or_Discriminant_Constraint |
N_Iteration_Scheme |
N_Loop_Parameter_Specification |
N_Mod_Clause |
N_Modular_Type_Definition |
N_Ordinary_Fixed_Point_Definition |
N_Parameter_Specification |
N_Pragma_Argument_Association |
N_Procedure_Specification |
N_Real_Range_Specification |
N_Record_Definition |
N_Signed_Integer_Type_Definition |
N_Unconstrained_Array_Definition |
N_Unused_At_Start |
N_Unused_At_End |
N_Variant =>
raise Program_Error;
end case;
Debug_A_Exit ("analyzing ", N, " (done)");
-- Now that we have analyzed the node, we call the expander to
-- perform possible expansion. This is done only for nodes that
-- are not subexpressions, because in the case of subexpressions,
-- we don't have the type yet, and the expander will need to know
-- the type before it can do its job. For subexpression nodes, the
-- call to the expander happens in the Sem_Res.Resolve.
-- The Analyzed flag is also set at this point for non-subexpression
-- nodes (in the case of subexpression nodes, we can't set the flag
-- yet, since resolution and expansion have not yet been completed)
if Nkind (N) not in N_Subexpr then
Expand (N);
end if;
end Analyze;
-- Version with check(s) suppressed
procedure Analyze (N : Node_Id; Suppress : Check_Id) is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Analyze (N);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Analyze (N);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Analyze;
------------------
-- Analyze_List --
------------------
procedure Analyze_List (L : List_Id) is
Node : Node_Id;
begin
Node := First (L);
while Present (Node) loop
Analyze (Node);
Next (Node);
end loop;
end Analyze_List;
-- Version with check(s) suppressed
procedure Analyze_List (L : List_Id; Suppress : Check_Id) is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Analyze_List (L);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Analyze_List (L);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Analyze_List;
-------------------------
-- Enter_Generic_Scope --
-------------------------
procedure Enter_Generic_Scope (S : Entity_Id) is
begin
if No (Outer_Generic_Scope) then
Outer_Generic_Scope := S;
end if;
end Enter_Generic_Scope;
------------------------
-- Exit_Generic_Scope --
------------------------
procedure Exit_Generic_Scope (S : Entity_Id) is
begin
if S = Outer_Generic_Scope then
Outer_Generic_Scope := Empty;
end if;
end Exit_Generic_Scope;
-----------------------------
-- External_Ref_In_Generic --
-----------------------------
function External_Ref_In_Generic (E : Entity_Id) return Boolean is
begin
-- Entity is global if defined outside of current outer_generic_scope:
-- Either the entity has a smaller depth that the outer generic, or it
-- is in a different compilation unit.
return Present (Outer_Generic_Scope)
and then (Scope_Depth (Scope (E)) < Scope_Depth (Outer_Generic_Scope)
or else not In_Same_Source_Unit (E, Outer_Generic_Scope));
end External_Ref_In_Generic;
------------------------
-- Get_Scope_Suppress --
------------------------
function Get_Scope_Suppress (C : Check_Id) return Boolean is
S : Suppress_Record renames Scope_Suppress;
begin
case C is
when Access_Check => return S.Access_Checks;
when Accessibility_Check => return S.Accessibility_Checks;
when Discriminant_Check => return S.Discriminant_Checks;
when Division_Check => return S.Division_Checks;
when Elaboration_Check => return S.Discriminant_Checks;
when Index_Check => return S.Elaboration_Checks;
when Length_Check => return S.Discriminant_Checks;
when Overflow_Check => return S.Overflow_Checks;
when Range_Check => return S.Range_Checks;
when Storage_Check => return S.Storage_Checks;
when Tag_Check => return S.Tag_Checks;
when All_Checks =>
raise Program_Error;
end case;
end Get_Scope_Suppress;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
Entity_Suppress.Init;
Scope_Stack.Init;
Unloaded_Subunits := False;
end Initialize;
------------------------------
-- Insert_After_And_Analyze --
------------------------------
procedure Insert_After_And_Analyze (N : Node_Id; M : Node_Id) is
Node : Node_Id;
begin
if Present (M) then
-- If we are not at the end of the list, then the easiest
-- coding is simply to insert before our successor
if Present (Next (N)) then
Insert_Before_And_Analyze (Next (N), M);
-- Case of inserting at the end of the list
else
-- Capture the Node_Id of the node to be inserted. This Node_Id
-- will still be the same after the insert operation.
Node := M;
Insert_After (N, M);
-- Now just analyze from the inserted node to the end of
-- the new list (note that this properly handles the case
-- where any of the analyze calls result in the insertion of
-- nodes after the analyzed node, expecting analysis).
while Present (Node) loop
Analyze (Node);
Mark_Rewrite_Insertion (Node);
Next (Node);
end loop;
end if;
end if;
end Insert_After_And_Analyze;
-- Version with check(s) suppressed
procedure Insert_After_And_Analyze
(N : Node_Id; M : Node_Id; Suppress : Check_Id)
is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Insert_After_And_Analyze (N, M);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Insert_After_And_Analyze (N, M);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Insert_After_And_Analyze;
-------------------------------
-- Insert_Before_And_Analyze --
-------------------------------
procedure Insert_Before_And_Analyze (N : Node_Id; M : Node_Id) is
Node : Node_Id;
begin
if Present (M) then
-- Capture the Node_Id of the first list node to be inserted.
-- This will still be the first node after the insert operation,
-- since Insert_List_After does not modify the Node_Id values.
Node := M;
Insert_Before (N, M);
-- The insertion does not change the Id's of any of the nodes in
-- the list, and they are still linked, so we can simply loop from
-- the original first node until we meet the node before which the
-- insertion is occurring. Note that this properly handles the case
-- where any of the analyzed nodes insert nodes after themselves,
-- expecting them to get analyzed.
while Node /= N loop
Analyze (Node);
Mark_Rewrite_Insertion (Node);
Next (Node);
end loop;
end if;
end Insert_Before_And_Analyze;
-- Version with check(s) suppressed
procedure Insert_Before_And_Analyze
(N : Node_Id; M : Node_Id; Suppress : Check_Id)
is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Insert_Before_And_Analyze (N, M);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Insert_Before_And_Analyze (N, M);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Insert_Before_And_Analyze;
-----------------------------------
-- Insert_List_After_And_Analyze --
-----------------------------------
procedure Insert_List_After_And_Analyze (N : Node_Id; L : List_Id) is
After : constant Node_Id := Next (N);
Node : Node_Id;
begin
if Is_Non_Empty_List (L) then
-- Capture the Node_Id of the first list node to be inserted.
-- This will still be the first node after the insert operation,
-- since Insert_List_After does not modify the Node_Id values.
Node := First (L);
Insert_List_After (N, L);
-- Now just analyze from the original first node until we get to
-- the successor of the original insertion point (which may be
-- Empty if the insertion point was at the end of the list). Note
-- that this properly handles the case where any of the analyze
-- calls result in the insertion of nodes after the analyzed
-- node (possibly calling this routine recursively).
while Node /= After loop
Analyze (Node);
Mark_Rewrite_Insertion (Node);
Next (Node);
end loop;
end if;
end Insert_List_After_And_Analyze;
-- Version with check(s) suppressed
procedure Insert_List_After_And_Analyze
(N : Node_Id; L : List_Id; Suppress : Check_Id)
is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Insert_List_After_And_Analyze (N, L);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Insert_List_After_And_Analyze (N, L);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Insert_List_After_And_Analyze;
------------------------------------
-- Insert_List_Before_And_Analyze --
------------------------------------
procedure Insert_List_Before_And_Analyze (N : Node_Id; L : List_Id) is
Node : Node_Id;
begin
if Is_Non_Empty_List (L) then
-- Capture the Node_Id of the first list node to be inserted.
-- This will still be the first node after the insert operation,
-- since Insert_List_After does not modify the Node_Id values.
Node := First (L);
Insert_List_Before (N, L);
-- The insertion does not change the Id's of any of the nodes in
-- the list, and they are still linked, so we can simply loop from
-- the original first node until we meet the node before which the
-- insertion is occurring. Note that this properly handles the case
-- where any of the analyzed nodes insert nodes after themselves,
-- expecting them to get analyzed.
while Node /= N loop
Analyze (Node);
Mark_Rewrite_Insertion (Node);
Next (Node);
end loop;
end if;
end Insert_List_Before_And_Analyze;
-- Version with check(s) suppressed
procedure Insert_List_Before_And_Analyze
(N : Node_Id; L : List_Id; Suppress : Check_Id)
is
begin
if Suppress = All_Checks then
declare
Svg : constant Suppress_Record := Scope_Suppress;
begin
Scope_Suppress := (others => True);
Insert_List_Before_And_Analyze (N, L);
Scope_Suppress := Svg;
end;
else
declare
Svg : constant Boolean := Get_Scope_Suppress (Suppress);
begin
Set_Scope_Suppress (Suppress, True);
Insert_List_Before_And_Analyze (N, L);
Set_Scope_Suppress (Suppress, Svg);
end;
end if;
end Insert_List_Before_And_Analyze;
----------
-- Lock --
----------
procedure Lock is
begin
Entity_Suppress.Locked := True;
Scope_Stack.Locked := True;
Entity_Suppress.Release;
Scope_Stack.Release;
end Lock;
---------------
-- Semantics --
---------------
procedure Semantics (Comp_Unit : Node_Id) is
-- The following locations save the corresponding global flags and
-- variables so that they can be restored on completion. This is
-- needed so that calls to Rtsfind start with the proper default
-- values for these variables, and also that such calls do not
-- disturb the settings for units being analyzed at a higher level.
S_Full_Analysis : constant Boolean := Full_Analysis;
S_In_Default_Expr : constant Boolean := In_Default_Expression;
S_Inside_A_Generic : constant Boolean := Inside_A_Generic;
S_New_Nodes_OK : constant Int := New_Nodes_OK;
S_Outer_Gen_Scope : constant Entity_Id := Outer_Generic_Scope;
S_Sem_Unit : constant Unit_Number_Type := Current_Sem_Unit;
Save_Config_Switches : Config_Switches_Type;
-- Variable used to save values of config switches while we analyze
-- the new unit, to be restored on exit for proper recursive behavior.
procedure Do_Analyze;
-- Procedure to analyze the compilation unit. This is called more
-- than once when the high level optimizer is activated.
procedure Do_Analyze is
begin
Save_Scope_Stack;
New_Scope (Standard_Standard);
Scope_Suppress := Suppress_Options;
Scope_Stack.Table
(Scope_Stack.Last).Component_Alignment_Default := Calign_Default;
Scope_Stack.Table
(Scope_Stack.Last).Is_Active_Stack_Base := True;
Outer_Generic_Scope := Empty;
-- Now analyze the top level compilation unit node
Analyze (Comp_Unit);
-- Check for scope mismatch on exit from compilation
pragma Assert (Current_Scope = Standard_Standard
or else Comp_Unit = Cunit (Main_Unit));
-- Then pop entry for Standard, and pop implicit types
Pop_Scope;
Restore_Scope_Stack;
end Do_Analyze;
-- Start of processing for Sem
begin
Compiler_State := Analyzing;
Current_Sem_Unit := Get_Cunit_Unit_Number (Comp_Unit);
Expander_Mode_Save_And_Set
(Operating_Mode = Generate_Code or Debug_Flag_X);
Full_Analysis := True;
Inside_A_Generic := False;
In_Default_Expression := False;
Set_Comes_From_Source_Default (False);
Save_Opt_Config_Switches (Save_Config_Switches);
Set_Opt_Config_Switches
(Is_Internal_File_Name (Unit_File_Name (Current_Sem_Unit)));
-- Only do analysis of unit that has not already been analyzed
if not Analyzed (Comp_Unit) then
Initialize_Version (Current_Sem_Unit);
if HLO_Active then
Expander_Mode_Save_And_Set (False);
New_Nodes_OK := 1;
Do_Analyze;
Reset_Analyzed_Flags (Comp_Unit);
Expander_Mode_Restore;
High_Level_Optimize (Comp_Unit);
New_Nodes_OK := 0;
end if;
Do_Analyze;
end if;
-- Save indication of dynamic elaboration checks for ALI file
Set_Dynamic_Elab (Current_Sem_Unit, Dynamic_Elaboration_Checks);
-- Restore settings of saved switches to entry values
Current_Sem_Unit := S_Sem_Unit;
Full_Analysis := S_Full_Analysis;
In_Default_Expression := S_In_Default_Expr;
Inside_A_Generic := S_Inside_A_Generic;
New_Nodes_OK := S_New_Nodes_OK;
Outer_Generic_Scope := S_Outer_Gen_Scope;
Restore_Opt_Config_Switches (Save_Config_Switches);
Expander_Mode_Restore;
end Semantics;
------------------------
-- Set_Scope_Suppress --
------------------------
procedure Set_Scope_Suppress (C : Check_Id; B : Boolean) is
S : Suppress_Record renames Scope_Suppress;
begin
case C is
when Access_Check => S.Access_Checks := B;
when Accessibility_Check => S.Accessibility_Checks := B;
when Discriminant_Check => S.Discriminant_Checks := B;
when Division_Check => S.Division_Checks := B;
when Elaboration_Check => S.Discriminant_Checks := B;
when Index_Check => S.Elaboration_Checks := B;
when Length_Check => S.Discriminant_Checks := B;
when Overflow_Check => S.Overflow_Checks := B;
when Range_Check => S.Range_Checks := B;
when Storage_Check => S.Storage_Checks := B;
when Tag_Check => S.Tag_Checks := B;
when All_Checks =>
raise Program_Error;
end case;
end Set_Scope_Suppress;
end Sem;
|
with Ada.Streams.Naked_Stream_IO.Standard_Files;
package body Ada.Streams.Stream_IO.Standard_Files is
Standard_Input_Object : aliased File_Type;
Standard_Output_Object : aliased File_Type;
Standard_Error_Object : aliased File_Type;
-- implementation
function Standard_Input return not null access constant File_Type is
begin
return Standard_Input_Object'Access;
end Standard_Input;
function Standard_Output return not null access constant File_Type is
begin
return Standard_Output_Object'Access;
end Standard_Output;
function Standard_Error return not null access constant File_Type is
begin
return Standard_Error_Object'Access;
end Standard_Error;
begin
Controlled.Reference (Standard_Input_Object).all :=
Naked_Stream_IO.Standard_Files.Standard_Input;
Controlled.Reference (Standard_Output_Object).all :=
Naked_Stream_IO.Standard_Files.Standard_Output;
Controlled.Reference (Standard_Error_Object).all :=
Naked_Stream_IO.Standard_Files.Standard_Error;
end Ada.Streams.Stream_IO.Standard_Files;
|
with ada.characters.latin_1;
with logger;
use logger;
package body box_parts is
function get_parts(box_info : box_info_t) return box_parts_t is
lower_halfbox : halfbox_t;
inner_halfbox : halfbox_t;
upper_halfbox : halfbox_t;
begin
debug("Génération de la boîte");
-- Demi boite inférieure
lower_halfbox := get_halfbox(
box_info.width,
box_info.length,
-- On gère la parité ici et fait ajoute le "surplus"
-- sur la boîte du bas
box_info.height / 2 + box_info.height mod 2,
box_info.thickness,
box_info.queue_length);
-- Demi boite du millieu
inner_halfbox := get_halfbox(
box_info.width - 2 * box_info.thickness,
box_info.length - 2 * box_info.thickness,
box_info.inner_height,
box_info.thickness,
box_info.queue_length);
-- Demi boite du haut
upper_halfbox := get_halfbox(
box_info.width,
box_info.length,
box_info.height / 2,
box_info.thickness,
box_info.queue_length);
return (lower_halfbox => lower_halfbox,
inner_halfbox => inner_halfbox,
upper_halfbox => upper_halfbox);
end;
procedure destroy(parts : in out box_parts_t) is
begin
destroy(parts.lower_halfbox);
destroy(parts.inner_halfbox);
destroy(parts.upper_halfbox);
end;
function to_string(box_parts : box_parts_t) return string is
tab : constant character := ada.characters.latin_1.HT;
lf : constant character := ada.characters.latin_1.LF;
begin
return "[" & lf
& tab & "upper_halfbox: " & to_string(box_parts.upper_halfbox) & lf
& tab & "inner_halfbox: " & to_string(box_parts.inner_halfbox) & lf
& tab & "lower_halfbox: " & to_string(box_parts.lower_halfbox) & lf
& "]";
end;
end box_parts;
|
with Ada.Containers.Generic_Array_Access_Types;
with Ada.Unchecked_Deallocation;
procedure cntnr_array_sorting is
type SA is access String;
procedure Free is new Ada.Unchecked_Deallocation (String, SA);
Data : SA := null;
Comp_Count : Natural;
Swap_Count : Natural;
procedure Setup (Source : String) is
begin
Free (Data);
Data := new String'(Source);
Comp_Count := 0;
Swap_Count := 0;
end Setup;
procedure Report (
Message : String;
Source_Location : String := Ada.Debug.Source_Location;
Enclosing_Entity : String := Ada.Debug.Enclosing_Entity) is
begin
Ada.Debug.Put (
Message & Natural'Image (Comp_Count) & Natural'Image (Swap_Count),
Source_Location => Source_Location,
Enclosing_Entity => Enclosing_Entity);
end Report;
procedure Increment (X : in out Natural) is
begin
X := X + 1;
end Increment;
function LT (Left, Right : Character) return Boolean is
pragma Debug (Increment (Comp_Count));
begin
return Left < Right;
end LT;
procedure Swap (Data : in out SA; Left, Right : Integer) is
pragma Debug (Increment (Swap_Count));
Temp : Character := Data (Left);
begin
Data (Left) := Data (Right);
Data (Right) := Temp;
end Swap;
package SA_Op is
new Ada.Containers.Generic_Array_Access_Types (
Positive,
Character,
String,
SA);
package SA_Reversing is new SA_Op.Generic_Reversing (Swap);
package SA_Sorting is new SA_Op.Generic_Sorting (LT, Swap);
begin
-- Is_Sorted
begin
Setup ("");
pragma Assert (SA_Sorting.Is_Sorted (Data));
Setup ("ABCDEF");
pragma Assert (SA_Sorting.Is_Sorted (Data));
Setup ("ABCCDD");
pragma Assert (SA_Sorting.Is_Sorted (Data));
Setup ("ABCBA");
pragma Assert (not SA_Sorting.Is_Sorted (Data));
end;
-- In_Place_Reverse
begin
Setup ("");
SA_Reversing.Reverse_Elements (Data);
pragma Assert (Data.all = "");
pragma Assert (Swap_Count = 0);
Setup ("A");
SA_Reversing.Reverse_Elements (Data);
pragma Assert (Data.all = "A");
pragma Assert (Swap_Count = 0);
Setup ("BA");
SA_Reversing.Reverse_Elements (Data);
pragma Assert (Data.all = "AB");
pragma Assert (Swap_Count = 1);
Setup ("CBA");
SA_Reversing.Reverse_Elements (Data);
pragma Assert (Data.all = "ABC");
pragma Assert (Swap_Count = 1);
Setup ("DCBA");
SA_Reversing.Reverse_Elements (Data);
pragma Assert (Data.all = "ABCD");
pragma Assert (Swap_Count = 2);
end;
-- rotate an empty data
declare
Source : constant String := "";
Middle : constant Integer := 0;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "");
pragma Assert (Swap_Count = 0);
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "");
pragma Assert (Swap_Count = 0);
end;
-- rotate 1
declare
Source : constant String := "A";
Middle : constant Integer := 1;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "A");
pragma Assert (Swap_Count = 0);
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "A");
pragma Assert (Swap_Count = 0);
end;
-- rotate 2
declare
Source : constant String := "BA";
Middle : constant Integer := 1;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "AB");
pragma Assert (Swap_Count = 1);
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "AB");
pragma Assert (Swap_Count = 1);
end;
-- rotate 3-1
declare
Source : constant String := "CAB";
Middle : constant Integer := 1;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABC");
pragma Debug (Report ("R3-1 rev"));
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABC");
pragma Debug (Report ("R3-1 jug"));
end;
-- rotate 3-2
declare
Source : constant String := "BCA";
Middle : constant Integer := 2;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABC");
pragma Debug (Report ("R3-2 rev"));
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABC");
pragma Debug (Report ("R3-2 jug"));
end;
-- rotate 4-1
declare
Source : constant String := "DABC";
Middle : constant Integer := 1;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-1 rev"));
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-1 jug"));
end;
-- rotate 4-2
declare
Source : constant String := "CDAB";
Middle : constant Integer := 2;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-2 rev"));
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-2 jug"));
end;
-- rotate 4-3
declare
Source : constant String := "BCDA";
Middle : constant Integer := 3;
begin
Setup (Source);
SA_Reversing.Reverse_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-3 rev"));
Setup (Source);
SA_Reversing.Juggling_Rotate_Elements (Data, Before => Middle + 1);
pragma Assert (Data.all = "ABCD");
pragma Debug (Report ("R4-3 jug"));
end;
-- sort a sorted data
declare
Source : constant String := "ABBCDDEFFG";
begin
Setup (Source);
SA_Sorting.Insertion_Sort (Data);
pragma Assert (Data.all = "ABBCDDEFFG");
pragma Assert (Swap_Count = 0);
pragma Debug (Report ("S1 ins"));
Setup (Source);
SA_Sorting.Merge_Sort (Data);
pragma Assert (Data.all = "ABBCDDEFFG");
pragma Assert (Swap_Count = 0);
pragma Debug (Report ("S1 ipm"));
end;
-- sort a random data
declare
Source : constant String := "DBFGHIECJA";
begin
Setup (Source);
SA_Sorting.Insertion_Sort (Data);
pragma Assert (Data.all = "ABCDEFGHIJ");
pragma Debug (Report ("S2 ins"));
Setup (Source);
SA_Sorting.Merge_Sort (Data);
pragma Assert (Data.all = "ABCDEFGHIJ");
pragma Debug (Report ("S2 ipm"));
end;
-- sort a random long data
declare
Source : constant String := "LOOOOOOOOOONGDATA";
begin
Setup (Source);
SA_Sorting.Insertion_Sort (Data);
pragma Assert (Data.all = "AADGLNOOOOOOOOOOT");
pragma Debug (Report ("S3 ins"));
Setup (Source);
SA_Sorting.Merge_Sort (Data);
pragma Assert (Data.all = "AADGLNOOOOOOOOOOT");
pragma Debug (Report ("S3 ipm"));
end;
-- sort a keyboard
declare
Source : constant String := "ASDFGHJKL";
begin
Setup (Source);
SA_Sorting.Insertion_Sort (Data);
pragma Assert (Data.all = "ADFGHJKLS");
pragma Debug (Report ("S4 ins"));
Setup (Source);
SA_Sorting.Merge_Sort (Data);
pragma Assert (Data.all = "ADFGHJKLS");
pragma Debug (Report ("S4 ipm"));
end;
Free (Data);
pragma Debug (Ada.Debug.Put ("OK"));
end cntnr_array_sorting;
|
-- MIT License
--
-- Copyright (c) 2020 Max Reznik
--
-- 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 PB_Support.Integer_32_Vectors;
with Compiler.Enum_Descriptors;
with Compiler.Field_Descriptors;
package body Compiler.Descriptors is
F : Ada_Pretty.Factory renames Compiler.Context.Factory;
use type Ada_Pretty.Node_Access;
use type League.Strings.Universal_String;
function "+" (Text : Wide_Wide_String)
return League.Strings.Universal_String
renames League.Strings.To_Universal_String;
function Type_Name
(Self : Google.Protobuf.Descriptor.Descriptor_Proto)
return League.Strings.Universal_String;
-- Return Ada type (simple) name
function Check_Dependency
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Done : Compiler.Context.String_Sets.Set;
Force : Natural;
Fake : in out Compiler.Context.String_Sets.Set) return Boolean;
function Public_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access;
function Read_Subprogram
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access;
function Write_Subprogram
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access;
procedure One_Of_Declaration
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Index : Positive;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set;
Types : in out Ada_Pretty.Node_Access;
Component : in out Ada_Pretty.Node_Access);
function Is_One_Of
(Value : PB_Support.Integer_32_Vectors.Option;
Index : Positive) return Boolean;
function Indexing_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Prefix : League.Strings.Universal_String;
Variable : Boolean) return Ada_Pretty.Node_Access;
function Indexing_Body
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Prefix : League.Strings.Universal_String;
Variable : Boolean) return Ada_Pretty.Node_Access;
----------------
-- Enum_Types --
----------------
function Enum_Types
(Self : Google.Protobuf.Descriptor.Descriptor_Proto)
return Ada_Pretty.Node_Access
is
Result : Ada_Pretty.Node_Access;
Item : Ada_Pretty.Node_Access;
begin
for J in 1 .. Self.Enum_Type.Length loop
Item := Compiler.Enum_Descriptors.Public_Spec (Self.Enum_Type (J));
Result := F.New_List (Result, Item);
end loop;
for J in 1 .. Self.Nested_Type.Length loop
Item := Enum_Types (Self.Nested_Type (J));
if Item /= null then
Result := F.New_List (Result, Item);
end if;
end loop;
return Result;
end Enum_Types;
----------------------
-- Check_Dependency --
----------------------
function Check_Dependency
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Done : Compiler.Context.String_Sets.Set;
Force : Natural;
Fake : in out Compiler.Context.String_Sets.Set) return Boolean
is
Required : Compiler.Context.String_Sets.Set;
Tipe : constant League.Strings.Universal_String := Type_Name (Self);
begin
for J in 1 .. Self.Field.Length loop
declare
use all type Google.Protobuf.Descriptor.Label;
Field : constant Google.Protobuf.Descriptor.Field_Descriptor_Proto
:= Self.Field (J);
Type_Name : League.Strings.Universal_String;
Named_Type : Compiler.Context.Named_Type;
begin
if Field.Type_Name.Is_Set then
Type_Name := Field.Type_Name.Value;
end if;
if not Compiler.Context.Named_Types.Contains (Type_Name) then
null;
else
Named_Type := Compiler.Context.Named_Types (Type_Name);
if not (Done.Contains (Named_Type.Ada_Type.Type_Name)
or else Named_Type.Is_Enumeration
or else Named_Type.Ada_Type.Package_Name /= Pkg
or else
(Field.Label.Is_Set
and then Field.Label.Value = LABEL_REPEATED))
then
Required.Insert
(Compiler.Field_Descriptors.Unique_Id
(Field, Pkg, Tipe));
end if;
end if;
end;
end loop;
if Natural (Required.Length) <= Force then
Fake.Union (Required);
return True;
else
return False;
end if;
end Check_Dependency;
----------------
-- Dependency --
----------------
procedure Dependency
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Result : in out Compiler.Context.String_Sets.Set)
is
begin
Result.Include (+"Ada.Finalization");
Result.Include (+"Ada.Streams");
if Self.Enum_Type.Length > 0 then
Result.Include (+"PB_Support.Vectors");
end if;
for J in 1 .. Self.Field.Length loop
Compiler.Field_Descriptors.Dependency (Self.Field (J), Result);
end loop;
for J in 1 .. Self.Nested_Type.Length loop
Dependency (Self.Nested_Type (J), Result);
end loop;
end Dependency;
--------------------
-- Get_Used_Types --
--------------------
procedure Get_Used_Types
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Result : in out Compiler.Context.String_Sets.Set) is
begin
for J in 1 .. Self.Field.Length loop
Compiler.Field_Descriptors.Get_Used_Types (Self.Field (J), Result);
end loop;
for J in 1 .. Self.Nested_Type.Length loop
Get_Used_Types (Self.Nested_Type (J), Result);
end loop;
end Get_Used_Types;
-------------------
-- Indexing_Body --
-------------------
function Indexing_Body
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Prefix : League.Strings.Universal_String;
Variable : Boolean) return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Ref_Name : constant League.Strings.Universal_String :=
My_Name & "_" & Prefix & "_Reference";
Result : Ada_Pretty.Node_Access;
begin
Result := F.New_Subprogram_Body
(Specification =>
F.New_Subprogram_Specification
(Name => F.New_Name ("Get_" & Ref_Name),
Is_Overriding => Ada_Pretty.False,
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (My_Name & "_Vector"),
Is_In => Variable,
Is_Out => Variable,
Is_Aliased => True),
F.New_Parameter
(Name => F.New_Name (+"Index"),
Type_Definition => F.New_Name (+"Positive"))),
Result => F.New_Name (Ref_Name)),
Statements => F.New_Return
(F.New_Parentheses
(F.New_Argument_Association
(Value => F.New_Name (+"Self.Data (Index)'Access"),
Choice => F.New_Name (+"Element")))));
return Result;
end Indexing_Body;
-------------------
-- Indexing_Spec --
-------------------
function Indexing_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Prefix : League.Strings.Universal_String;
Variable : Boolean) return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Ref_Name : constant League.Strings.Universal_String :=
My_Name & "_" & Prefix & "_Reference";
Map : constant array (Boolean) of Ada_Pretty.Access_Modifier :=
(True => Ada_Pretty.Unspecified,
False => Ada_Pretty.Access_Constant);
Result : Ada_Pretty.Node_Access;
begin
Result := F.New_Type
(Name => F.New_Name (Ref_Name),
Discriminants => F.New_Parameter
(Name => F.New_Name (+"Element"),
Type_Definition => F.New_Null_Exclusion
(F.New_Access
(Target => F.New_Name (My_Name),
Modifier => Map (Variable)))),
Definition => F.New_Record,
Aspects => F.New_Argument_Association
(Choice => F.New_Name (+"Implicit_Dereference"),
Value => F.New_Name (+"Element")));
Result := F.New_List
(Result,
F.New_Subprogram_Declaration
(Specification =>
F.New_Subprogram_Specification
(Name => F.New_Name ("Get_" & Ref_Name),
Is_Overriding => Ada_Pretty.False,
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (My_Name & "_Vector"),
Is_In => Variable,
Is_Out => Variable,
Is_Aliased => True),
F.New_Parameter
(Name => F.New_Name (+"Index"),
Type_Definition => F.New_Name (+"Positive"))),
Result => F.New_Name (Ref_Name)),
Aspects => F.New_Name (+"Inline")));
return Result;
end Indexing_Spec;
---------------
-- Is_One_Of --
---------------
function Is_One_Of
(Value : PB_Support.Integer_32_Vectors.Option;
Index : Positive) return Boolean
is
begin
return Value.Is_Set and then Natural (Value.Value) + 1 = Index;
end Is_One_Of;
------------------------
-- One_Of_Declaration --
------------------------
procedure One_Of_Declaration
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Index : Positive;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set;
Types : in out Ada_Pretty.Node_Access;
Component : in out Ada_Pretty.Node_Access)
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Item_Name : constant League.Strings.Universal_String :=
Compiler.Context.To_Ada_Name (Self.Oneof_Decl (Index).Name.Value);
Next : Ada_Pretty.Node_Access;
Name : constant League.Strings.Universal_String :=
My_Name & "_Variant";
Choices : Ada_Pretty.Node_Access;
begin
Next := F.New_Name (Item_Name & "_Not_Set");
Choices :=
F.New_Case_Path
(Next,
F.New_Statement);
for J in 1 .. Self.Field.Length loop
declare
Field : constant Google.Protobuf.Descriptor.Field_Descriptor_Proto
:= Self.Field (J);
Literal : League.Strings.Universal_String;
begin
if Is_One_Of (Field.Oneof_Index, Index) then
Literal := Compiler.Context.To_Ada_Name (Field.Name.Value) &
"_Kind";
Next := F.New_List
(Next,
F.New_Argument_Association (F.New_Name (Literal)));
Choices := F.New_List
(Choices,
F.New_Case_Path
(F.New_Name (Literal),
Compiler.Field_Descriptors.Component
(Field, Pkg, My_Name, Fake)));
end if;
end;
end loop;
Types := F.New_List
(Types,
F.New_Type
(Name => F.New_Name (Name & "_Kind"),
Definition => F.New_Parentheses (Next)));
Types := F.New_List
(Types,
F.New_Type
(Name => F.New_Name (Name),
Discriminants =>
F.New_Parameter
(Name => F.New_Name (Item_Name),
Type_Definition => F.New_Name (Name & "_Kind"),
Initialization => F.New_Name (Item_Name & "_Not_Set")),
Definition => F.New_Record
(Components =>
F.New_Case
(Expression => F.New_Name (Item_Name),
List => Choices))));
Component := F.New_List
(Component,
F.New_Variable
(Name => F.New_Name (+"Variant"),
Type_Definition => F.New_Name (Name)));
end One_Of_Declaration;
--------------------------
-- Populate_Named_Types --
--------------------------
procedure Populate_Named_Types
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
PB_Prefix : League.Strings.Universal_String;
Ada_Package : League.Strings.Universal_String;
Map : in out Compiler.Context.Named_Type_Maps.Map)
is
Name : constant League.Strings.Universal_String := Type_Name (Self);
Key : League.Strings.Universal_String := PB_Prefix;
Value : constant Compiler.Context.Named_Type :=
(Is_Enumeration => False,
Ada_Type =>
(Package_Name => Ada_Package,
Type_Name => Name));
begin
Key.Append (".");
if Self.Name.Is_Set then
Key.Append (Self.Name.Value);
end if;
Map.Insert (Key, Value);
for J in 1 .. Self.Nested_Type.Length loop
Populate_Named_Types
(Self => Self.Nested_Type (J),
PB_Prefix => Key,
Ada_Package => Ada_Package,
Map => Map);
end loop;
for J in 1 .. Self.Enum_Type.Length loop
Compiler.Enum_Descriptors.Populate_Named_Types
(Self => Self.Enum_Type (J),
PB_Prefix => Key,
Ada_Package => Ada_Package,
Map => Map);
end loop;
end Populate_Named_Types;
------------------
-- Private_Spec --
------------------
function Private_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto)
return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
T_Array : Ada_Pretty.Node_Access;
Array_Access : Ada_Pretty.Node_Access;
Result : Ada_Pretty.Node_Access;
Item : Ada_Pretty.Node_Access;
Read : Ada_Pretty.Node_Access;
Write : Ada_Pretty.Node_Access;
Use_R : Ada_Pretty.Node_Access;
Use_W : Ada_Pretty.Node_Access;
Adjust : Ada_Pretty.Node_Access;
Final : Ada_Pretty.Node_Access;
begin
for J in 1 .. Self.Nested_Type.Length loop
Item := Private_Spec (Self.Nested_Type (J));
Result := F.New_List (Result, Item);
end loop;
Read := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Name => F.New_Name ("Read_" & My_Name),
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Stream"),
Type_Definition => F.New_Selected_Name
(+"access Ada.Streams.Root_Stream_Type'Class")),
F.New_Parameter
(Name => F.New_Name (+"V"),
Type_Definition => F.New_Name (My_Name),
Is_Out => True))));
Write := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Name => F.New_Name ("Write_" & My_Name),
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Stream"),
Type_Definition => F.New_Selected_Name
(+"access Ada.Streams.Root_Stream_Type'Class")),
F.New_Parameter
(Name => F.New_Name (+"V"),
Type_Definition => F.New_Name (My_Name)))));
Use_R := F.New_Statement
(F.New_Name ("for " & My_Name & "'Read use Read_" & My_Name));
Use_W := F.New_Statement
(F.New_Name ("for " & My_Name & "'Write use Write_" & My_Name));
T_Array := F.New_Type
(Name => F.New_Name (My_Name & "_Array"),
Definition => F.New_Array
(Indexes => F.New_Name (+"Positive range <>"),
Component => F.New_Name ("aliased " & My_Name)));
Array_Access := F.New_Type
(Name => F.New_Name (My_Name & "_Array_Access"),
Definition => F.New_Access
(Target => F.New_Name (My_Name & "_Array")));
Item := F.New_Type
(F.New_Name (Type_Name (Self) & "_Vector"),
Definition => F.New_Record
(Parent => F.New_Selected_Name
(+"Ada.Finalization.Controlled"),
Components => F.New_List
(F.New_Variable
(Name => F.New_Name (+"Data"),
Type_Definition => F.New_Name (My_Name & "_Array_Access")),
F.New_Variable
(Name => F.New_Name (+"Length"),
Type_Definition => F.New_Name (+"Natural"),
Initialization => F.New_Literal (0)))));
Adjust := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Is_Overriding => Ada_Pretty.True,
Name => F.New_Name (+"Adjust"),
Parameters => F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (Type_Name (Self) & "_Vector"),
Is_In => True,
Is_Out => True)));
Final := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Is_Overriding => Ada_Pretty.True,
Name => F.New_Name (+"Finalize"),
Parameters => F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (Type_Name (Self) & "_Vector"),
Is_In => True,
Is_Out => True)));
Result := F.New_List
(Result,
F.New_List
((Read, Write, Use_R, Use_W,
T_Array, Array_Access, Item, Adjust, Final)));
return Result;
end Private_Spec;
-----------------
-- Public_Spec --
-----------------
function Public_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Me : constant Ada_Pretty.Node_Access := F.New_Name (My_Name);
V_Name : Ada_Pretty.Node_Access;
P_Self : Ada_Pretty.Node_Access;
Is_Set : Ada_Pretty.Node_Access;
Count : Ada_Pretty.Node_Access;
Clear : Ada_Pretty.Node_Access;
Append : Ada_Pretty.Node_Access;
Option : Ada_Pretty.Node_Access;
Result : Ada_Pretty.Node_Access;
Item : Ada_Pretty.Node_Access;
One_Of : Ada_Pretty.Node_Access;
Indexing : Ada_Pretty.Node_Access;
begin
for J in 1 .. Self.Field.Length loop
if not Self.Field (J).Oneof_Index.Is_Set then
Item := Compiler.Field_Descriptors.Component
(Self.Field (J), Pkg, My_Name, Fake);
Result := F.New_List (Result, Item);
end if;
end loop;
for J in 1 .. Self.Oneof_Decl.Length loop
One_Of_Declaration (Self, J, Pkg, Fake, One_Of, Result);
end loop;
Result := F.New_List
(One_Of,
F.New_Type
(F.New_Name (My_Name),
Definition => F.New_Record (Components => Result)));
Is_Set := F.New_Name (+"Is_Set");
Option := F.New_Type
(Name => F.New_Name ("Optional_" & My_Name),
Discriminants => F.New_Parameter
(Name => Is_Set,
Type_Definition => F.New_Name (+"Boolean"),
Initialization => F.New_Name (+"False")),
Definition => F.New_Record
(Components => F.New_Case
(Expression => Is_Set,
List => F.New_List
(F.New_Case_Path
(Choice => F.New_Name (+"True"),
List => F.New_Variable
(Name => F.New_Name (+"Value"),
Type_Definition =>
F.New_Selected_Name
(Compiler.Context.Relative_Name
(Pkg & "." & My_Name, Pkg)))),
F.New_Case_Path
(Choice => F.New_Name (+"False"),
List => F.New_Statement)))));
V_Name := F.New_Name (My_Name & "_Vector");
P_Self := F.New_Name (+"Self");
Count := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Length"),
Parameters => F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name),
Result => F.New_Name (+"Natural")));
Clear := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Clear"),
Parameters => F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name,
Is_In => True,
Is_Out => True)));
Append := F.New_Subprogram_Declaration
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Append"),
Parameters => F.New_List
(F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name,
Is_In => True,
Is_Out => True),
F.New_Parameter
(F.New_Name (+"V"), Me))));
Indexing := F.New_List
(Indexing_Spec (Self, +"Variable", True),
Indexing_Spec (Self, +"Constant", False));
Result := F.New_List ((Result, Option, Count, Clear, Append, Indexing));
return Result;
end Public_Spec;
-----------------
-- Public_Spec --
-----------------
procedure Public_Spec
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Result : out Ada_Pretty.Node_Access;
Again : in out Boolean;
Done : in out Compiler.Context.String_Sets.Set;
Force : in out Natural)
is
Name : constant League.Strings.Universal_String := Type_Name (Self);
Item : Ada_Pretty.Node_Access;
Fake : Compiler.Context.String_Sets.Set renames
Compiler.Context.Fake;
begin
Result := null;
for J in 1 .. Self.Nested_Type.Length loop
Public_Spec (Self.Nested_Type (J), Pkg, Item, Again, Done, Force);
if Item /= null then
Result := F.New_List (Result, Item);
Force := 0;
end if;
end loop;
if not Done.Contains (Name) then
if Check_Dependency (Self, Pkg, Done, Force, Fake) then
Result := F.New_List (Result, Public_Spec (Self, Pkg, Fake));
Done.Insert (Name);
else
Again := True;
end if;
end if;
end Public_Spec;
---------------------
-- Read_Subprogram --
---------------------
function Read_Subprogram
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access
is
function Oneof_Name
(Field : Google.Protobuf.Descriptor.Field_Descriptor_Proto)
return League.Strings.Universal_String;
function Oneof_Name
(Field : Google.Protobuf.Descriptor.Field_Descriptor_Proto)
return League.Strings.Universal_String is
begin
if Field.Oneof_Index.Is_Set then
return Compiler.Context.To_Ada_Name
(Self.Oneof_Decl
(Natural (Field.Oneof_Index.Value) + 1).Name.Value);
else
return League.Strings.Empty_Universal_String;
end if;
end Oneof_Name;
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Key : Ada_Pretty.Node_Access;
Result : Ada_Pretty.Node_Access;
Field : Ada_Pretty.Node_Access;
begin
Key := F.New_Variable
(Name => F.New_Name (+"Key"),
Type_Definition => F.New_Selected_Name (+"PB_Support.IO.Key"),
Is_Aliased => True);
for J in 1 .. Self.Field.Length loop
Field := Compiler.Field_Descriptors.Read_Case
(Self.Field (J),
Pkg,
My_Name,
Fake,
Oneof_Name (Self.Field (J)));
Result := F.New_List (Result, Field);
end loop;
Result := F.New_List
(Result,
F.New_Case_Path
(Choice => F.New_Name (+"others"),
List => F.New_Statement
(F.New_Apply
(Prefix => F.New_Selected_Name
(+"PB_Support.IO.Unknown_Field"),
Arguments => F.New_List
(F.New_Argument_Association (F.New_Name (+"Stream")),
F.New_Argument_Association
(F.New_Selected_Name (+"Key.Encoding")))))));
Result := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Name => F.New_Name ("Read_" & My_Name),
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Stream"),
Type_Definition => F.New_Selected_Name
(+"access Ada.Streams.Root_Stream_Type'Class")),
F.New_Parameter
(Name => F.New_Name (+"V"),
Type_Definition => F.New_Name (My_Name),
Is_Out => True))),
Declarations => Key,
Statements => F.New_Loop
(Condition => F.New_Apply
(Prefix => F.New_Selected_Name
(+"PB_Support.IO.Read_Key"),
Arguments => F.New_List
(F.New_Argument_Association
(F.New_Name (+"Stream")),
F.New_Argument_Association
(F.New_Name (+"Key'Access")))),
Statements => F.New_Case
(Expression => F.New_Selected_Name (+"Key.Field"),
List => Result)));
return Result;
end Read_Subprogram;
-----------------
-- Subprograms --
-----------------
function Subprograms
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String)
return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Me : constant Ada_Pretty.Node_Access := F.New_Name (My_Name);
V_Name : Ada_Pretty.Node_Access;
P_Self : Ada_Pretty.Node_Access;
Free : Ada_Pretty.Node_Access;
Count : Ada_Pretty.Node_Access;
Clear : Ada_Pretty.Node_Access;
Append : Ada_Pretty.Node_Access;
Adjust : Ada_Pretty.Node_Access;
Final : Ada_Pretty.Node_Access;
Read : Ada_Pretty.Node_Access;
Write : Ada_Pretty.Node_Access;
Ref : Ada_Pretty.Node_Access;
Result : Ada_Pretty.Node_Access;
begin
V_Name := F.New_Name (My_Name & "_Vector");
P_Self := F.New_Name (+"Self");
Count := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Length"),
Parameters => F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name),
Result => F.New_Name (+"Natural")),
Statements => F.New_Return
(F.New_Selected_Name (+"Self.Length")));
Clear := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Clear"),
Parameters => F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name,
Is_In => True,
Is_Out => True)),
Statements => F.New_Assignment
(Left => F.New_Selected_Name (+"Self.Length"),
Right => F.New_Literal (0)));
Free := F.New_Statement
(F.New_Apply
(F.New_Name (+"procedure Free is new Ada.Unchecked_Deallocation"),
F.New_List
(F.New_Argument_Association
(F.New_Name (My_Name & "_Array")),
F.New_Argument_Association
(F.New_Name (My_Name & "_Array_Access")))));
Append := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Name => F.New_Name (+"Append"),
Parameters => F.New_List
(F.New_Parameter
(Name => P_Self,
Type_Definition => V_Name,
Is_In => True,
Is_Out => True),
F.New_Parameter
(F.New_Name (+"V"), Me))),
Declarations => F.New_Variable
(Name => F.New_Name (+"Init_Length"),
Type_Definition => F.New_Name (+"Positive"),
Is_Constant => True,
Initialization => F.New_Apply
(Prefix => F.New_Selected_Name (+"Positive'Max"),
Arguments => F.New_List
(F.New_Argument_Association (F.New_Literal (1)),
F.New_Argument_Association
(F.New_List
(F.New_Literal (256),
F.New_Infix
(+"/",
F.New_Selected_Name (My_Name & "'Size"))))))),
Statements => F.New_List
((F.New_If
(Condition => F.New_Selected_Name (+"Self.Length = 0"),
Then_Path => F.New_Assignment
(F.New_Selected_Name (+"Self.Data"),
F.New_Infix
(Operator => +"new",
Left => F.New_Apply
(F.New_Selected_Name (My_Name & "_Array"),
F.New_Selected_Name (+"1 .. Init_Length")))),
Elsif_List => F.New_Elsif
(Condition => F.New_List
(F.New_Selected_Name (+"Self.Length"),
F.New_Infix
(+"=",
F.New_Selected_Name (+"Self.Data'Last"))),
List => F.New_Assignment
(F.New_Selected_Name (+"Self.Data"),
F.New_Qualified_Expession
(F.New_Selected_Name ("new " & My_Name & "_Array"),
F.New_List
(F.New_Selected_Name (+"Self.Data.all"),
F.New_Infix
(+"&",
F.New_Qualified_Expession
(F.New_Selected_Name (My_Name & "_Array"),
F.New_Selected_Name
(+"1 .. Self.Length => <>"))
)))))),
F.New_Assignment
(F.New_Selected_Name (+"Self.Length"),
F.New_List
(F.New_Selected_Name (+"Self.Length"),
F.New_Infix (+"+", F.New_Literal (1)))),
F.New_Assignment
(F.New_Apply
(F.New_Selected_Name (+"Self.Data"),
F.New_Selected_Name (+"Self.Length")),
F.New_Name (+"V")))));
Adjust := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Is_Overriding => Ada_Pretty.True,
Name => F.New_Name (+"Adjust"),
Parameters => F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (Type_Name (Self) & "_Vector"),
Is_In => True,
Is_Out => True)),
Statements => F.New_If
(Condition => F.New_Name (+"Self.Length > 0"),
Then_Path => F.New_Assignment
(F.New_Selected_Name (+"Self.Data"),
F.New_Qualified_Expession
(F.New_Name ("new " & My_Name & "_Array"),
F.New_Apply
(F.New_Selected_Name (+"Self.Data"),
F.New_List
(F.New_Literal (1),
F.New_Infix
(+"..",
F.New_Selected_Name (+"Self.Length"))))))));
Final := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Is_Overriding => Ada_Pretty.True,
Name => F.New_Name (+"Finalize"),
Parameters => F.New_Parameter
(Name => F.New_Name (+"Self"),
Type_Definition => F.New_Name (Type_Name (Self) & "_Vector"),
Is_In => True,
Is_Out => True)),
Statements => F.New_If
(Condition => F.New_Name (+"Self.Data /= null"),
Then_Path => F.New_Statement
(F.New_Apply
(F.New_Name (+"Free"),
F.New_Selected_Name (+"Self.Data")))));
Read := Read_Subprogram (Self, Pkg, Compiler.Context.Fake);
Write := Write_Subprogram (Self, Pkg, Compiler.Context.Fake);
Ref := F.New_List
(Indexing_Body (Self, +"Variable", True),
Indexing_Body (Self, +"Constant", False));
Result := F.New_List
((Count, Clear, Free, Append, Adjust, Final, Ref, Read, Write));
for J in 1 .. Self.Nested_Type.Length loop
Result := F.New_List
(Result, Subprograms (Self.Nested_Type (J), Pkg));
end loop;
return Result;
end Subprograms;
---------------
-- Type_Name --
---------------
function Type_Name
(Self : Google.Protobuf.Descriptor.Descriptor_Proto)
return League.Strings.Universal_String is
begin
if Self.Name.Is_Set then
return Compiler.Context.To_Ada_Name (Self.Name.Value);
else
return +"Message";
end if;
end Type_Name;
-------------------------
-- Vector_Declarations --
-------------------------
function Vector_Declarations
(Self : Google.Protobuf.Descriptor.Descriptor_Proto)
return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Result : Ada_Pretty.Node_Access;
Item : Ada_Pretty.Node_Access;
begin
Result := F.New_List
(Result,
F.New_Type
(Name => F.New_Name (My_Name & "_Vector"),
Definition => F.New_Private_Record
(Is_Tagged => True),
Aspects => F.New_List
(F.New_Argument_Association
(F.New_Name ("Get_" & My_Name & "_Variable_Reference"),
F.New_Name (+"Variable_Indexing")),
F.New_Argument_Association
(F.New_Name ("Get_" & My_Name & "_Constant_Reference"),
F.New_Name (+"Constant_Indexing")))));
for J in 1 .. Self.Nested_Type.Length loop
Item := Vector_Declarations (Self.Nested_Type (J));
Result := F.New_List (Result, Item);
end loop;
return Result;
end Vector_Declarations;
----------------------
-- Write_Subprogram --
----------------------
function Write_Subprogram
(Self : Google.Protobuf.Descriptor.Descriptor_Proto;
Pkg : League.Strings.Universal_String;
Fake : Compiler.Context.String_Sets.Set)
return Ada_Pretty.Node_Access
is
My_Name : constant League.Strings.Universal_String := Type_Name (Self);
Result : Ada_Pretty.Node_Access;
If_Stmt : Ada_Pretty.Node_Access;
Decl : Ada_Pretty.Node_Access;
Stream : constant Ada_Pretty.Node_Access :=
F.New_Selected_Name (+"PB_Support.Internal.Stream");
Stmts : Ada_Pretty.Node_Access;
begin
If_Stmt := F.New_If
(F.New_List
(F.New_Selected_Name (+"Stream.all"),
F.New_Infix
(+"not in",
F.New_Selected_Name (+"PB_Support.Internal.Stream"))),
F.New_Block
(Declarations => F.New_Variable
(Name => F.New_Name (+"WS"),
Type_Definition => F.New_Apply
(Stream,
F.New_Name (+"Stream")),
Is_Aliased => True),
Statements => F.New_List
(F.New_Statement
(F.New_Apply
(F.New_Name ("Write_" & My_Name),
F.New_List
(F.New_Argument_Association
(F.New_Name (+"WS'Access")),
F.New_Argument_Association
(F.New_Name (+"V"))))),
F.New_Return)));
Stmts := F.New_Statement (F.New_Selected_Name (+"WS.Start_Message"));
for J in 1 .. Self.Field.Length loop
if not Self.Field (J).Oneof_Index.Is_Set then
Stmts := F.New_List
(Stmts,
Compiler.Field_Descriptors.Write_Call
(Self.Field (J), Pkg, My_Name, Fake));
end if;
end loop;
for K in 1 .. Self.Oneof_Decl.Length loop
declare
Name : constant League.Strings.Universal_String :=
Compiler.Context.To_Ada_Name (Self.Oneof_Decl (K).Name.Value);
Cases : Ada_Pretty.Node_Access;
begin
for J in 1 .. Self.Field.Length loop
if Is_One_Of (Self.Field (J).Oneof_Index, K) then
Cases := F.New_List
(Cases,
Compiler.Field_Descriptors.Case_Path
(Self.Field (J), Pkg, My_Name, Fake));
end if;
end loop;
Cases := F.New_List
(Cases,
F.New_Case_Path
(F.New_Name (Name & "_Not_Set"),
F.New_Statement));
Stmts := F.New_List
(Stmts,
F.New_Case
(F.New_Selected_Name ("V.Variant." & Name),
Cases));
end;
end loop;
Stmts := F.New_List
(Stmts,
F.New_If
(F.New_Selected_Name (+"WS.End_Message"),
F.New_Statement
(F.New_Apply
(F.New_Name ("Write_" & My_Name),
F.New_List
(F.New_Argument_Association
(F.New_Name (+"WS'Access")),
F.New_Argument_Association
(F.New_Name (+"V")))))));
Decl := F.New_Block
(Declarations =>
F.New_Variable
(Name => F.New_Name (+"WS"),
Type_Definition => Stream,
Rename =>
F.New_Apply
(Stream,
F.New_Argument_Association
(F.New_Selected_Name (+"Stream.all")))),
Statements => Stmts);
Result := F.New_Subprogram_Body
(F.New_Subprogram_Specification
(Name => F.New_Name ("Write_" & My_Name),
Parameters => F.New_List
(F.New_Parameter
(Name => F.New_Name (+"Stream"),
Type_Definition => F.New_Selected_Name
(+"access Ada.Streams.Root_Stream_Type'Class")),
F.New_Parameter
(Name => F.New_Name (+"V"),
Type_Definition => F.New_Name (My_Name)))),
Statements => F.New_List (If_Stmt, Decl));
return Result;
end Write_Subprogram;
end Compiler.Descriptors;
|
-- Copyright ©2021,2022 Steve 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 Cairo;
with Gdk.Event;
with Glib; use Glib;
with Glib.Main; use Glib.Main;
with Gtk.Drawing_Area;
with Gtk.Widget;
with BDF_Font;
package Crt is
package Blink_Timeout is new Glib.Main.Generic_Sources (Gtk.Drawing_Area.Gtk_Drawing_Area);
package Redraw_Timeout is new Glib.Main.Generic_Sources (Gtk.Drawing_Area.Gtk_Drawing_Area);
Font_Filename : constant String := "D410-b-12.bdf";
Blink_Period_MS : constant Guint := 500;
type Crt_T is record
DA : Gtk.Drawing_Area.Gtk_Drawing_Area;
Zoom : BDF_Font.Zoom_T;
Blink_State : Boolean;
-- Timeout_ID : Glib.Main.G_Source_ID := 0;
end record;
Tube : Crt_T;
surface : Cairo.Cairo_Surface;
Blink_TO, Redraw_TO : Glib.Main.G_Source_ID;
procedure Init (Zoom : in BDF_Font.Zoom_T);
function Configure_Event_CB
(Self : access Gtk.Widget.Gtk_Widget_Record'Class;
Event : Gdk.Event.Gdk_Event_Configure)
return Boolean;
function Draw_CB
(Self : access Gtk.Widget.Gtk_Widget_Record'Class;
Cr : Cairo.Cairo_Context)
return Boolean;
Unloaded_Character : exception;
end Crt; |
-- Copyright (c) 2013, Nordic Semiconductor ASA
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * 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 Nordic Semiconductor ASA nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- 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.
--
-- This spec has been automatically generated from nrf51.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with HAL;
with System;
package NRF51_SVD.AMLI is
pragma Preelaborate;
---------------
-- Registers --
---------------
-------------------------------------
-- AMLI_RAMPRI cluster's Registers --
-------------------------------------
-- Configuration field for RAM block 0.
type CPU0_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for CPU0_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- CPU0_RAMPRI_RAM array
type CPU0_RAMPRI_RAM_Field_Array is array (0 .. 7) of CPU0_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for CPU0.
type CPU0_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : CPU0_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for CPU0_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Configuration field for RAM block 0.
type SPIS1_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for SPIS1_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- SPIS1_RAMPRI_RAM array
type SPIS1_RAMPRI_RAM_Field_Array is array (0 .. 7) of SPIS1_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for SPIS1.
type SPIS1_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : SPIS1_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for SPIS1_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Configuration field for RAM block 0.
type RADIO_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for RADIO_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- RADIO_RAMPRI_RAM array
type RADIO_RAMPRI_RAM_Field_Array is array (0 .. 7) of RADIO_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for RADIO.
type RADIO_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : RADIO_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for RADIO_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Configuration field for RAM block 0.
type ECB_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for ECB_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- ECB_RAMPRI_RAM array
type ECB_RAMPRI_RAM_Field_Array is array (0 .. 7) of ECB_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for ECB.
type ECB_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : ECB_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for ECB_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Configuration field for RAM block 0.
type CCM_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for CCM_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- CCM_RAMPRI_RAM array
type CCM_RAMPRI_RAM_Field_Array is array (0 .. 7) of CCM_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for CCM.
type CCM_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : CCM_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for CCM_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- Configuration field for RAM block 0.
type AAR_RAM0_Field is
(
-- Priority 0.
Pri0,
-- Priority 2.
Pri2,
-- Priority 4.
Pri4,
-- Priority 6.
Pri6,
-- Priority 8.
Pri8,
-- Priority 10.
Pri10,
-- Priority 12.
Pri12,
-- Priority 14.
Pri14)
with Size => 4;
for AAR_RAM0_Field use
(Pri0 => 0,
Pri2 => 2,
Pri4 => 4,
Pri6 => 6,
Pri8 => 8,
Pri10 => 10,
Pri12 => 12,
Pri14 => 14);
-- AAR_RAMPRI_RAM array
type AAR_RAMPRI_RAM_Field_Array is array (0 .. 7) of AAR_RAM0_Field
with Component_Size => 4, Size => 32;
-- Configurable priority configuration register for AAR.
type AAR_RAMPRI_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RAM as a value
Val : HAL.UInt32;
when True =>
-- RAM as an array
Arr : AAR_RAMPRI_RAM_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access,
Bit_Order => System.Low_Order_First;
for AAR_RAMPRI_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- RAM configurable priority configuration structure.
type AMLI_RAMPRI_Cluster is record
-- Configurable priority configuration register for CPU0.
CPU0 : aliased CPU0_RAMPRI_Register;
-- Configurable priority configuration register for SPIS1.
SPIS1 : aliased SPIS1_RAMPRI_Register;
-- Configurable priority configuration register for RADIO.
RADIO : aliased RADIO_RAMPRI_Register;
-- Configurable priority configuration register for ECB.
ECB : aliased ECB_RAMPRI_Register;
-- Configurable priority configuration register for CCM.
CCM : aliased CCM_RAMPRI_Register;
-- Configurable priority configuration register for AAR.
AAR : aliased AAR_RAMPRI_Register;
end record
with Volatile, Size => 192;
for AMLI_RAMPRI_Cluster use record
CPU0 at 16#0# range 0 .. 31;
SPIS1 at 16#4# range 0 .. 31;
RADIO at 16#8# range 0 .. 31;
ECB at 16#C# range 0 .. 31;
CCM at 16#10# range 0 .. 31;
AAR at 16#14# range 0 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- AHB Multi-Layer Interface.
type AMLI_Peripheral is record
-- RAM configurable priority configuration structure.
RAMPRI : aliased AMLI_RAMPRI_Cluster;
end record
with Volatile;
for AMLI_Peripheral use record
RAMPRI at 16#E00# range 0 .. 191;
end record;
-- AHB Multi-Layer Interface.
AMLI_Periph : aliased AMLI_Peripheral
with Import, Address => System'To_Address (16#40000000#);
end NRF51_SVD.AMLI;
|
with STM32.RNG.Interrupts; use STM32.RNG.Interrupts;
with STM32.Board; use STM32.Board;
with HAL; use HAL;
package body Utils is
procedure Clear(Update : Boolean; Color : Bitmap_Color := BG) is
begin
Display.Hidden_Buffer(1).Set_Source(Color);
Display.Hidden_Buffer(1).Fill;
if Update then
Display.Update_Layer(1, Copy_Back => False);
end if;
end Clear;
function GetRandomFloat return Float is
begin
return Float(Random) / Float(UInt32'Last);
end GetRandomFloat;
end Utils;
|
-----------------------------------------------------------------------
-- asf-locales -- Locale support
-- Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2017, 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 Util.Strings.Vectors;
with ASF.Contexts.Faces;
with Ada.Strings.Unbounded;
package body ASF.Locales is
use Util.Properties.Bundles;
type Locale_Binding (Len : Natural) is new ASF.Beans.Class_Binding with record
Loader : Loader_Access;
Scope : ASF.Beans.Scope_Type;
Name : String (1 .. Len);
end record;
type Locale_Binding_Access is access all Locale_Binding;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access);
-- ------------------------------
-- Initialize the locale support by using the configuration properties.
-- Properties matching the pattern: <b>bundle</b>.<i>var-name</i>=<i>bundle-name</i>
-- are used to register bindings linking a facelet variable <i>var-name</i>
-- to the resource bundle <i>bundle-name</i>.
-- ------------------------------
procedure Initialize (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Config : in Util.Properties.Manager'Class) is
Names : Util.Strings.Vectors.Vector;
Dir : constant String := Config.Get ("bundle.dir", "bundles");
begin
Config.Get_Names (Names, "bundle.var.");
Util.Properties.Bundles.Initialize (Fac.Factory, Dir);
for Name of Names loop -- I in Names'Range loop
declare
Value : constant String := Config.Get (Name);
begin
Register (Fac, Beans, Name (Name'First + 11 .. Name'Last), Value);
end;
end loop;
end Initialize;
-- ------------------------------
-- Compute the locale that must be used according to the <b>Accept-Language</b> request
-- header and the application supported locales.
-- ------------------------------
function Calculate_Locale (Fac : in Factory;
Req : in ASF.Requests.Request'Class)
return Util.Locales.Locale is
use Util.Locales;
use type ASF.Requests.Quality_Type;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type);
Found_Locale : Util.Locales.Locale := Fac.Default_Locale;
Found_Quality : ASF.Requests.Quality_Type := 0.0;
procedure Process_Locales (Locale : in Util.Locales.Locale;
Quality : in ASF.Requests.Quality_Type) is
begin
if Found_Quality >= Quality then
return;
end if;
for I in 1 .. Fac.Nb_Locales loop
-- We need a match on the language. The variant/country can be ignored and will
-- be honored by the resource bundle.
if Fac.Locales (I) = Locale
or Get_Language (Fac.Locales (I)) = Get_Language (Locale)
then
Found_Locale := Locale;
Found_Quality := Quality;
return;
end if;
end loop;
end Process_Locales;
begin
if Fac.Nb_Locales > 0 then
Req.Accept_Locales (Process_Locales'Access);
end if;
return Found_Locale;
end Calculate_Locale;
procedure Register (Fac : in out Factory;
Beans : in out ASF.Beans.Bean_Factory;
Name : in String;
Bundle : in String) is
L : constant Locale_Binding_Access := new Locale_Binding (Len => Bundle'Length);
P : ASF.Beans.Parameter_Bean_Ref.Ref;
begin
L.Loader := Fac.Factory'Unchecked_Access;
L.Scope := ASF.Beans.REQUEST_SCOPE;
L.Name := Bundle;
ASF.Beans.Register (Beans, Name, L.all'Access, P);
end Register;
-- Load the resource bundle identified by the <b>Name</b> and for the given
-- <b>Locale</b>.
procedure Load_Bundle (Fac : in out Factory;
Name : in String;
Locale : in String;
Result : out Bundle) is
begin
Load_Bundle (Factory => Fac.Factory,
Locale => Locale,
Name => Name,
Bundle => Result);
end Load_Bundle;
-- ------------------------------
-- Get the list of supported locales for this application.
-- ------------------------------
function Get_Supported_Locales (From : in Factory)
return Util.Locales.Locale_Array is
begin
return From.Locales (1 .. From.Nb_Locales);
end Get_Supported_Locales;
-- ------------------------------
-- Add the locale to the list of supported locales.
-- ------------------------------
procedure Add_Supported_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Nb_Locales := Into.Nb_Locales + 1;
Into.Locales (Into.Nb_Locales) := Locale;
end Add_Supported_Locale;
-- ------------------------------
-- Get the default locale defined by the application.
-- ------------------------------
function Get_Default_Locale (From : in Factory) return Util.Locales.Locale is
begin
return From.Default_Locale;
end Get_Default_Locale;
-- ------------------------------
-- Set the default locale defined by the application.
-- ------------------------------
procedure Set_Default_Locale (Into : in out Factory;
Locale : in Util.Locales.Locale) is
begin
Into.Default_Locale := Locale;
end Set_Default_Locale;
procedure Create (Factory : in Locale_Binding;
Name : in Ada.Strings.Unbounded.Unbounded_String;
Result : out Util.Beans.Basic.Readonly_Bean_Access) is
pragma Unreferenced (Name);
use type ASF.Contexts.Faces.Faces_Context_Access;
Context : constant ASF.Contexts.Faces.Faces_Context_Access := ASF.Contexts.Faces.Current;
B : constant Bundle_Access := new Bundle;
begin
if Context = null then
Load_Bundle (Factory => Factory.Loader.all,
Locale => "en",
Name => Factory.Name,
Bundle => B.all);
else
Load_Bundle (Factory => Factory.Loader.all,
Locale => Util.Locales.To_String (Context.Get_Locale),
Name => Factory.Name,
Bundle => B.all);
end if;
Result := B.all'Access;
end Create;
end ASF.Locales;
|
with Ada.Text_IO, Generic_Root; use Generic_Root;
procedure Multiplicative_Root is
procedure Compute is new Compute_Root("*"); -- "*" for multiplicative roots
package TIO renames Ada.Text_IO;
package NIO is new TIO.Integer_IO(Number);
procedure Print_Numbers(Target_Root: Number; How_Many: Natural) is
Current: Number := 0;
Root, Pers: Number;
begin
for I in 1 .. How_Many loop
loop
Compute(Current, Root, Pers);
exit when Root = Target_Root;
Current := Current + 1;
end loop;
NIO.Put(Current, Width => 6);
if I < How_Many then
TIO.Put(",");
end if;
Current := Current + 1;
end loop;
end Print_Numbers;
Inputs: Number_Array := (123321, 7739, 893, 899998);
Root, Pers: Number;
begin
TIO.Put_Line(" Number MDR MP");
for I in Inputs'Range loop
Compute(Inputs(I), Root, Pers);
NIO.Put(Inputs(I), Width => 8);
NIO.Put(Root, Width => 6);
NIO.Put(Pers, Width => 6);
TIO.New_Line;
end loop;
TIO.New_Line;
TIO.Put_Line(" MDR first_five_numbers_with_that_MDR");
for I in 0 .. 9 loop
TIO.Put(" " & Integer'Image(I) & " ");
Print_Numbers(Target_Root => Number(I), How_Many => 5);
TIO.New_Line;
end loop;
end Multiplicative_Root;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2016, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System.Machine_Code; use System.Machine_Code;
with Ada.Unchecked_Conversion;
with Interfaces; use Interfaces;
with HAL; use HAL;
with Cortex_M_SVD.SCB; use Cortex_M_SVD.SCB;
with Cortex_M_SVD.PF; use Cortex_M_SVD.PF;
with Cortex_M_SVD.Cache; use Cortex_M_SVD.Cache;
package body Cortex_M.Cache is
Data_Cache_Line_Size : constant UInt32 :=
2 ** Natural (PF_Periph.CCSIDR.LineSize + 2);
procedure DSB with Inline_Always;
-- Data Stored Barrier
procedure ISB with Inline_Always;
-- Instruction Stored Barrier
generic
Reg_Address : System.Address;
procedure Cache_Maintenance
(Start : System.Address;
Len : Natural) with Inline_Always;
---------
-- DSB --
---------
procedure DSB is
begin
Asm ("dsb", Volatile => True);
end DSB;
---------
-- ISB --
---------
procedure ISB is
begin
Asm ("isb", Volatile => True);
end ISB;
-----------------------
-- Cache_Maintenance --
-----------------------
procedure Cache_Maintenance
(Start : System.Address;
Len : Natural)
is
begin
if not D_Cache_Enabled then
return;
end if;
declare
function To_U32 is new Ada.Unchecked_Conversion
(System.Address, UInt32);
Op_Size : Integer_32 := Integer_32 (Len);
Op_Addr : UInt32 := To_U32 (Start);
Reg : UInt32 with Volatile, Address => Reg_Address;
begin
DSB;
while Op_Size > 0 loop
Reg := Op_Addr;
Op_Addr := Op_Addr + Data_Cache_Line_Size;
Op_Size := Op_Size - Integer_32 (Data_Cache_Line_Size);
end loop;
DSB;
ISB;
end;
end Cache_Maintenance;
--------------------
-- Enable_I_Cache --
--------------------
procedure Enable_I_Cache
is
begin
DSB;
ISB;
Cortex_M_SVD.Cache.Cache_Periph.ICIALLU := 0; -- Invalidate I-Cache
Cortex_M_SVD.SCB.SCB_Periph.CCR.IC := True; -- Enable I-Cache
DSB;
ISB;
end Enable_I_Cache;
---------------------
-- Disable_I_Cache --
---------------------
procedure Disable_I_Cache
is
begin
DSB;
ISB;
Cortex_M_SVD.SCB.SCB_Periph.CCR.IC := False; -- Disable I-Cache
Cortex_M_SVD.Cache.Cache_Periph.ICIALLU := 0; -- Invalidate I-Cache
DSB;
ISB;
end Disable_I_Cache;
--------------------
-- Enable_D_Cache --
--------------------
procedure Enable_D_Cache
is
CCSIDR : CCSIDR_Register;
begin
PF_Periph.CSSELR := (InD => Data_Cache,
Level => Level_1,
others => <>);
DSB;
CCSIDR := PF_Periph.CCSIDR;
for S in reverse 0 .. CCSIDR.NumSets loop
for W in reverse 0 .. CCSIDR.Associativity loop
Cache_Periph.DCISW :=
(Set => UInt9 (S),
Way => UInt2 (W),
others => <>);
end loop;
end loop;
DSB;
SCB_Periph.CCR.DC := True; -- Enable D-Cache
DSB;
ISB;
end Enable_D_Cache;
---------------------
-- Disable_D_Cache --
---------------------
procedure Disable_D_Cache
is
Sets : DCISW_Set_Field;
Ways : DCISW_Way_Field;
begin
PF_Periph.CSSELR := (InD => Data_Cache,
Level => Level_1,
others => <>);
DSB;
-- Clean & Invalidate D-Cache
Sets := DCISW_Set_Field (PF_Periph.CCSIDR.NumSets);
Ways := DCISW_Way_Field (PF_Periph.CCSIDR.Associativity);
for S in 0 .. Sets loop
for W in 0 .. Ways loop
Cache_Periph.DCCISW :=
(Set => S,
Way => W,
others => <>);
end loop;
end loop;
SCB_Periph.CCR.DC := False; -- Disable D-Cache
DSB;
ISB;
end Disable_D_Cache;
---------------------
-- I_Cache_Enabled --
---------------------
function I_Cache_Enabled return Boolean
is
begin
return SCB_Periph.CCR.IC;
end I_Cache_Enabled;
---------------------
-- D_Cache_Enabled --
---------------------
function D_Cache_Enabled return Boolean
is
begin
return SCB_Periph.CCR.DC;
end D_Cache_Enabled;
------------------
-- Clean_DCache --
------------------
procedure Int_Clean_DCache is
new Cache_Maintenance (Cache_Periph.DCCMVAC'Address);
procedure Clean_DCache
(Start : System.Address;
Len : Natural)
renames Int_Clean_DCache;
-----------------------
-- Invalidate_DCache --
-----------------------
procedure Int_Invalidate_DCache is
new Cache_Maintenance (Cache_Periph.DCIMVAC'Address);
procedure Invalidate_DCache
(Start : System.Address;
Len : Natural)
renames Int_Invalidate_DCache;
-----------------------------
-- Clean_Invalidate_DCache --
-----------------------------
procedure Int_Clean_Invalidate_DCache is
new Cache_Maintenance (Cache_Periph.DCCIMVAC'Address);
procedure Clean_Invalidate_DCache
(Start : System.Address;
Len : Natural)
renames Int_Clean_Invalidate_DCache;
end Cortex_M.Cache;
|
-- { dg-do compile }
-- { dg-options "-O2" }
with Aggr10_Pkg; use Aggr10_Pkg;
procedure Aggr10 is
No_Name_Location : constant Name_Location :=
(Name => Name_Id'First,
Location => Int'First,
Source => Source_Id'First,
Except => False,
Found => False);
Name_Loc : Name_Location;
begin
Name_Loc := Get;
if Name_Loc = No_Name_Location then -- { dg-bogus "comparison always false" }
raise Program_Error;
end if;
Set (Name_Loc);
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- A S P E C T S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2010-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. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Atree; use Atree;
with Einfo; use Einfo;
with Nlists; use Nlists;
with Sinfo; use Sinfo;
with GNAT.HTable;
package body Aspects is
-- The following array indicates aspects that a subtype inherits from its
-- base type. True means that the subtype inherits the aspect from its base
-- type. False means it is not inherited.
Base_Aspect : constant array (Aspect_Id) of Boolean :=
(Aspect_Atomic => True,
Aspect_Atomic_Components => True,
Aspect_Constant_Indexing => True,
Aspect_Default_Iterator => True,
Aspect_Discard_Names => True,
Aspect_Independent_Components => True,
Aspect_Iterator_Element => True,
Aspect_Type_Invariant => True,
Aspect_Unchecked_Union => True,
Aspect_Variable_Indexing => True,
Aspect_Volatile => True,
Aspect_Volatile_Full_Access => True,
others => False);
-- The following array indicates type aspects that are inherited and apply
-- to the class-wide type as well.
Inherited_Aspect : constant array (Aspect_Id) of Boolean :=
(Aspect_Constant_Indexing => True,
Aspect_Default_Iterator => True,
Aspect_Implicit_Dereference => True,
Aspect_Iterator_Element => True,
Aspect_Remote_Types => True,
Aspect_Variable_Indexing => True,
others => False);
------------------------------------------
-- Hash Table for Aspect Specifications --
------------------------------------------
type AS_Hash_Range is range 0 .. 510;
-- Size of hash table headers
function AS_Hash (F : Node_Id) return AS_Hash_Range;
-- Hash function for hash table
function AS_Hash (F : Node_Id) return AS_Hash_Range is
begin
return AS_Hash_Range (F mod 511);
end AS_Hash;
package Aspect_Specifications_Hash_Table is new
GNAT.HTable.Simple_HTable
(Header_Num => AS_Hash_Range,
Element => List_Id,
No_Element => No_List,
Key => Node_Id,
Hash => AS_Hash,
Equal => "=");
-------------------------------------
-- Hash Table for Aspect Id Values --
-------------------------------------
type AI_Hash_Range is range 0 .. 112;
-- Size of hash table headers
function AI_Hash (F : Name_Id) return AI_Hash_Range;
-- Hash function for hash table
function AI_Hash (F : Name_Id) return AI_Hash_Range is
begin
return AI_Hash_Range (F mod 113);
end AI_Hash;
package Aspect_Id_Hash_Table is new
GNAT.HTable.Simple_HTable
(Header_Num => AI_Hash_Range,
Element => Aspect_Id,
No_Element => No_Aspect,
Key => Name_Id,
Hash => AI_Hash,
Equal => "=");
---------------------------
-- Aspect_Specifications --
---------------------------
function Aspect_Specifications (N : Node_Id) return List_Id is
begin
if Has_Aspects (N) then
return Aspect_Specifications_Hash_Table.Get (N);
else
return No_List;
end if;
end Aspect_Specifications;
--------------------------------
-- Aspects_On_Body_Or_Stub_OK --
--------------------------------
function Aspects_On_Body_Or_Stub_OK (N : Node_Id) return Boolean is
Aspect : Node_Id;
Aspects : List_Id;
begin
-- The routine should be invoked on a body [stub] with aspects
pragma Assert (Has_Aspects (N));
pragma Assert
(Nkind (N) in N_Body_Stub | N_Entry_Body | N_Package_Body |
N_Protected_Body | N_Subprogram_Body | N_Task_Body);
-- Look through all aspects and see whether they can be applied to a
-- body [stub].
Aspects := Aspect_Specifications (N);
Aspect := First (Aspects);
while Present (Aspect) loop
if not Aspect_On_Body_Or_Stub_OK (Get_Aspect_Id (Aspect)) then
return False;
end if;
Next (Aspect);
end loop;
return True;
end Aspects_On_Body_Or_Stub_OK;
----------------------
-- Exchange_Aspects --
----------------------
procedure Exchange_Aspects (N1 : Node_Id; N2 : Node_Id) is
begin
pragma Assert
(Permits_Aspect_Specifications (N1)
and then Permits_Aspect_Specifications (N2));
-- Perform the exchange only when both nodes have lists to be swapped
if Has_Aspects (N1) and then Has_Aspects (N2) then
declare
L1 : constant List_Id := Aspect_Specifications (N1);
L2 : constant List_Id := Aspect_Specifications (N2);
begin
Set_Parent (L1, N2);
Set_Parent (L2, N1);
Aspect_Specifications_Hash_Table.Set (N1, L2);
Aspect_Specifications_Hash_Table.Set (N2, L1);
end;
end if;
end Exchange_Aspects;
-----------------
-- Find_Aspect --
-----------------
function Find_Aspect (Id : Entity_Id; A : Aspect_Id) return Node_Id is
Decl : Node_Id;
Item : Node_Id;
Owner : Entity_Id;
Spec : Node_Id;
begin
Owner := Id;
-- Handle various cases of base or inherited aspects for types
if Is_Type (Id) then
if Base_Aspect (A) then
Owner := Base_Type (Owner);
end if;
if Is_Class_Wide_Type (Owner) and then Inherited_Aspect (A) then
Owner := Root_Type (Owner);
end if;
if Is_Private_Type (Owner)
and then Present (Full_View (Owner))
and then not Operational_Aspect (A)
then
Owner := Full_View (Owner);
end if;
end if;
-- Search the representation items for the desired aspect
Item := First_Rep_Item (Owner);
while Present (Item) loop
if Nkind (Item) = N_Aspect_Specification
and then Get_Aspect_Id (Item) = A
then
return Item;
end if;
Next_Rep_Item (Item);
end loop;
-- Note that not all aspects are added to the chain of representation
-- items. In such cases, search the list of aspect specifications. First
-- find the declaration node where the aspects reside. This is usually
-- the parent or the parent of the parent.
Decl := Parent (Owner);
if not Permits_Aspect_Specifications (Decl) then
Decl := Parent (Decl);
end if;
-- Search the list of aspect specifications for the desired aspect
if Permits_Aspect_Specifications (Decl) then
Spec := First (Aspect_Specifications (Decl));
while Present (Spec) loop
if Get_Aspect_Id (Spec) = A then
return Spec;
end if;
Next (Spec);
end loop;
end if;
-- The entity does not carry any aspects or the desired aspect was not
-- found.
return Empty;
end Find_Aspect;
--------------------------
-- Find_Value_Of_Aspect --
--------------------------
function Find_Value_Of_Aspect
(Id : Entity_Id;
A : Aspect_Id) return Node_Id
is
Spec : constant Node_Id := Find_Aspect (Id, A);
begin
if Present (Spec) then
if A = Aspect_Default_Iterator then
return Expression (Aspect_Rep_Item (Spec));
else
return Expression (Spec);
end if;
end if;
return Empty;
end Find_Value_Of_Aspect;
-------------------
-- Get_Aspect_Id --
-------------------
function Get_Aspect_Id (Name : Name_Id) return Aspect_Id is
begin
return Aspect_Id_Hash_Table.Get (Name);
end Get_Aspect_Id;
function Get_Aspect_Id (Aspect : Node_Id) return Aspect_Id is
begin
pragma Assert (Nkind (Aspect) = N_Aspect_Specification);
return Aspect_Id_Hash_Table.Get (Chars (Identifier (Aspect)));
end Get_Aspect_Id;
----------------
-- Has_Aspect --
----------------
function Has_Aspect (Id : Entity_Id; A : Aspect_Id) return Boolean is
begin
return Present (Find_Aspect (Id, A));
end Has_Aspect;
------------------
-- Move_Aspects --
------------------
procedure Move_Aspects (From : Node_Id; To : Node_Id) is
pragma Assert (not Has_Aspects (To));
begin
if Has_Aspects (From) then
Set_Aspect_Specifications (To, Aspect_Specifications (From));
Aspect_Specifications_Hash_Table.Remove (From);
Set_Has_Aspects (From, False);
end if;
end Move_Aspects;
---------------------------
-- Move_Or_Merge_Aspects --
---------------------------
procedure Move_Or_Merge_Aspects (From : Node_Id; To : Node_Id) is
procedure Relocate_Aspect (Asp : Node_Id);
-- Move aspect specification Asp to the aspect specifications of node To
---------------------
-- Relocate_Aspect --
---------------------
procedure Relocate_Aspect (Asp : Node_Id) is
Asps : List_Id;
begin
if Has_Aspects (To) then
Asps := Aspect_Specifications (To);
-- Create a new aspect specification list for node To
else
Asps := New_List;
Set_Aspect_Specifications (To, Asps);
Set_Has_Aspects (To);
end if;
-- Remove the aspect from its original owner and relocate it to node
-- To.
Remove (Asp);
Append (Asp, Asps);
end Relocate_Aspect;
-- Local variables
Asp : Node_Id;
Asp_Id : Aspect_Id;
Next_Asp : Node_Id;
-- Start of processing for Move_Or_Merge_Aspects
begin
if Has_Aspects (From) then
Asp := First (Aspect_Specifications (From));
while Present (Asp) loop
-- Store the next aspect now as a potential relocation will alter
-- the contents of the list.
Next_Asp := Next (Asp);
-- When moving or merging aspects from a subprogram body stub that
-- also acts as a spec, relocate only those aspects that may apply
-- to a body [stub]. Note that a precondition must also be moved
-- to the proper body as the pre/post machinery expects it to be
-- there.
if Nkind (From) = N_Subprogram_Body_Stub
and then No (Corresponding_Spec_Of_Stub (From))
then
Asp_Id := Get_Aspect_Id (Asp);
if Aspect_On_Body_Or_Stub_OK (Asp_Id)
or else Asp_Id = Aspect_Pre
or else Asp_Id = Aspect_Precondition
then
Relocate_Aspect (Asp);
end if;
-- When moving or merging aspects from a single concurrent type
-- declaration, relocate only those aspects that may apply to the
-- anonymous object created for the type.
-- Note: It is better to use Is_Single_Concurrent_Type_Declaration
-- here, but Aspects and Sem_Util have incompatible licenses.
elsif Nkind (Original_Node (From)) in
N_Single_Protected_Declaration | N_Single_Task_Declaration
then
Asp_Id := Get_Aspect_Id (Asp);
if Aspect_On_Anonymous_Object_OK (Asp_Id) then
Relocate_Aspect (Asp);
end if;
-- Default case - relocate the aspect to its new owner
else
Relocate_Aspect (Asp);
end if;
Asp := Next_Asp;
end loop;
-- The relocations may have left node From's aspect specifications
-- list empty. If this is the case, simply remove the aspects.
if Is_Empty_List (Aspect_Specifications (From)) then
Remove_Aspects (From);
end if;
end if;
end Move_Or_Merge_Aspects;
-----------------------------------
-- Permits_Aspect_Specifications --
-----------------------------------
Has_Aspect_Specifications_Flag : constant array (Node_Kind) of Boolean :=
(N_Abstract_Subprogram_Declaration => True,
N_Component_Declaration => True,
N_Entry_Body => True,
N_Entry_Declaration => True,
N_Exception_Declaration => True,
N_Exception_Renaming_Declaration => True,
N_Expression_Function => True,
N_Formal_Abstract_Subprogram_Declaration => True,
N_Formal_Concrete_Subprogram_Declaration => True,
N_Formal_Object_Declaration => True,
N_Formal_Package_Declaration => True,
N_Formal_Type_Declaration => True,
N_Full_Type_Declaration => True,
N_Function_Instantiation => True,
N_Generic_Package_Declaration => True,
N_Generic_Renaming_Declaration => True,
N_Generic_Subprogram_Declaration => True,
N_Object_Declaration => True,
N_Object_Renaming_Declaration => True,
N_Package_Body => True,
N_Package_Body_Stub => True,
N_Package_Declaration => True,
N_Package_Instantiation => True,
N_Package_Specification => True,
N_Package_Renaming_Declaration => True,
N_Parameter_Specification => True,
N_Private_Extension_Declaration => True,
N_Private_Type_Declaration => True,
N_Procedure_Instantiation => True,
N_Protected_Body => True,
N_Protected_Body_Stub => True,
N_Protected_Type_Declaration => True,
N_Single_Protected_Declaration => True,
N_Single_Task_Declaration => True,
N_Subprogram_Body => True,
N_Subprogram_Body_Stub => True,
N_Subprogram_Declaration => True,
N_Subprogram_Renaming_Declaration => True,
N_Subtype_Declaration => True,
N_Task_Body => True,
N_Task_Body_Stub => True,
N_Task_Type_Declaration => True,
others => False);
function Permits_Aspect_Specifications (N : Node_Id) return Boolean is
begin
return Has_Aspect_Specifications_Flag (Nkind (N));
end Permits_Aspect_Specifications;
--------------------
-- Remove_Aspects --
--------------------
procedure Remove_Aspects (N : Node_Id) is
begin
if Has_Aspects (N) then
Aspect_Specifications_Hash_Table.Remove (N);
Set_Has_Aspects (N, False);
end if;
end Remove_Aspects;
-----------------
-- Same_Aspect --
-----------------
-- Table used for Same_Aspect, maps aspect to canonical aspect
type Aspect_To_Aspect_Mapping is array (Aspect_Id) of Aspect_Id;
function Init_Canonical_Aspect return Aspect_To_Aspect_Mapping;
-- Initialize the Canonical_Aspect mapping below
function Init_Canonical_Aspect return Aspect_To_Aspect_Mapping is
Result : Aspect_To_Aspect_Mapping;
begin
-- They all map to themselves...
for Aspect in Aspect_Id loop
Result (Aspect) := Aspect;
end loop;
-- ...except for these:
Result (Aspect_Dynamic_Predicate) := Aspect_Predicate;
Result (Aspect_Inline_Always) := Aspect_Inline;
Result (Aspect_Interrupt_Priority) := Aspect_Priority;
Result (Aspect_Postcondition) := Aspect_Post;
Result (Aspect_Precondition) := Aspect_Pre;
Result (Aspect_Shared) := Aspect_Atomic;
Result (Aspect_Static_Predicate) := Aspect_Predicate;
Result (Aspect_Type_Invariant) := Aspect_Invariant;
return Result;
end Init_Canonical_Aspect;
Canonical_Aspect : constant Aspect_To_Aspect_Mapping :=
Init_Canonical_Aspect;
function Same_Aspect (A1 : Aspect_Id; A2 : Aspect_Id) return Boolean is
begin
return Canonical_Aspect (A1) = Canonical_Aspect (A2);
end Same_Aspect;
-------------------------------
-- Set_Aspect_Specifications --
-------------------------------
procedure Set_Aspect_Specifications (N : Node_Id; L : List_Id) is
begin
pragma Assert (Permits_Aspect_Specifications (N));
pragma Assert (not Has_Aspects (N));
pragma Assert (L /= No_List);
Set_Has_Aspects (N);
Set_Parent (L, N);
Aspect_Specifications_Hash_Table.Set (N, L);
end Set_Aspect_Specifications;
-- Package initialization sets up Aspect Id hash table
begin
for J in Aspect_Id loop
Aspect_Id_Hash_Table.Set (Aspect_Names (J), J);
end loop;
end Aspects;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Program.Elements.Type_Definitions;
package Program.Elements.Root_Types is
pragma Pure (Program.Elements.Root_Types);
type Root_Type is
limited interface and Program.Elements.Type_Definitions.Type_Definition;
type Root_Type_Access is access all Root_Type'Class with Storage_Size => 0;
type Root_Type_Text is limited interface;
type Root_Type_Text_Access is access all Root_Type_Text'Class
with Storage_Size => 0;
not overriding function To_Root_Type_Text
(Self : in out Root_Type)
return Root_Type_Text_Access is abstract;
end Program.Elements.Root_Types;
|
with GDB_Remote.Agent;
package GDB_Remote.Target is
subtype Address is Unsigned_64;
subtype Register is Unsigned_32;
package Parent renames Agent;
type Instance (Buffer_Size : Buffer_Lenght_Type := 256)
is abstract limited new Parent.Instance
with private;
subtype Class is Instance'Class;
type Ptr is access all Class;
procedure From_Host (This : in out Instance;
C : Character);
procedure Detach (This : in out Instance)
is abstract;
procedure Set_Thread (This : in out Instance;
Id : Integer)
is abstract;
procedure Read_Memory (This : in out Instance;
Addr : Address;
Data : out Unsigned_8;
Success : out Boolean)
is abstract;
procedure Write_Memory (This : in out Instance;
Addr : Address;
Data : Unsigned_8;
Success : out Boolean)
is abstract;
function Last_General_Register (This : Instance) return Natural
is abstract;
procedure Read_Register (This : in out Instance;
Id : Natural;
Data : out Register;
Success : out Boolean)
is abstract;
procedure Write_Register (This : in out Instance;
Id : Natural;
Data : Register;
Success : out Boolean)
is abstract;
procedure Continue (This : in out Instance;
Single_Step : Boolean := False)
is abstract;
procedure Continue_At (This : in out Instance;
Addr : Address;
Single_Step : Boolean := False)
is abstract;
procedure Halt (This : in out Instance)
is abstract;
function Supported (This : Instance;
B_Type : Breakpoint_Type)
return Boolean
is abstract;
procedure Insert_Breakpoint (This : in out Instance;
B_Type : Breakpoint_Type;
Addr : Address;
Kind : Natural)
is abstract;
procedure Remove_Breakpoint (This : in out Instance;
B_Type : Breakpoint_Type;
Addr : Address;
Kind : Natural)
is abstract;
private
type Instance (Buffer_Size : Buffer_Lenght_Type := 256)
is abstract limited new Parent.Instance (Buffer_Size)
with null record;
procedure Push_Register is new Agent.Push_Mod (Register);
end GDB_Remote.Target;
|
with AAA.Strings;
package CLIC.User_Input is
-------------------
-- Interactivity --
-------------------
Not_Interactive : aliased Boolean := False;
-- When not Interactive, instead of asking the user something, use default.
User_Interrupt : exception;
-- Raised when the user hits Ctrl-D and no further input can be obtained as
-- stdin is closed.
type Answer_Kind is (Yes, No, Always);
type Answer_Set is array (Answer_Kind) of Boolean;
function Query (Question : String;
Valid : Answer_Set;
Default : Answer_Kind)
return Answer_Kind;
-- If interactive, ask the user for one of the valid answer.
-- Otherwise return the Default answer.
function Query_Multi (Question : String;
Choices : AAA.Strings.Vector;
Page_Size : Positive := 10)
return Positive
with Pre => Page_Size >= 2 and then Page_Size < 36;
-- Present the Choices in a numbered list 1-9-0-a-z, with paging if
-- Choices.Length > Page_Size. Default is always First of Choices.
type Answer_With_Input (Length : Natural) is record
Input : String (1 .. Length);
Answer : Answer_Kind;
end record;
function Validated_Input
(Question : String;
Prompt : String;
Valid : Answer_Set;
Default : access function (User_Input : String) return Answer_Kind;
Confirm : String := "Is this information correct?";
Is_Valid : access function (User_Input : String) return Boolean)
return Answer_With_Input;
-- Interactive prompt for information from the user, with confirmation:
-- Put_Line (Question)
-- loop
-- Put (Prompt); Get_Line (User_Input);
-- if Is_Valid (User_Input) then
-- exit when Query (Confirm, Valid, Default (User_Input)) /= No;
-- end if;
-- end loop
function Img (Kind : Answer_Kind) return String;
type String_Validation_Access is
access function (Str : String) return Boolean;
function Query_String (Question : String;
Default : String;
Validation : String_Validation_Access)
return String
with Pre => Validation = null or else Validation (Default);
-- If interactive, ask the user to provide a valid string.
-- Otherwise return the Default value.
--
-- If Validation is null, any input is accepted.
--
-- The Default value has to be a valid input.
procedure Continue_Or_Abort;
-- If interactive, ask the user to press Enter or Ctrl-C to stop.
-- Output a log trace otherwise and continue.
end CLIC.User_Input;
|
-- C32001D.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- CHECK THAT IN MULTIPLE OBJECT DECLARATIONS FOR ACCESS TYPES, THE
-- SUBTYPE INDICATION AND THE INITIALIZATION EXPRESSIONS ARE EVALUATED
-- ONCE FOR EACH NAMED OBJECT THAT IS DECLARED AND THE SUBTYPE
-- INDICATION IS EVALUATED FIRST. ALSO, CHECK THAT THE EVALUATIONS
-- YIELD THE SAME RESULT AS A SEQUENCE OF SINGLE OBJECT DECLARATIONS.
-- RJW 7/16/86
WITH REPORT; USE REPORT;
PROCEDURE C32001D IS
TYPE ARR IS ARRAY (1 .. 2) OF INTEGER;
BUMP : ARR := (0, 0);
F1 : ARR;
FUNCTION F (I : INTEGER) RETURN INTEGER IS
BEGIN
BUMP (I) := BUMP (I) + 1;
F1 (I) := BUMP (I);
RETURN BUMP (I);
END F;
FUNCTION G (I : INTEGER) RETURN INTEGER IS
BEGIN
BUMP (I) := BUMP (I) + 1;
RETURN BUMP (I);
END G;
BEGIN
TEST ("C32001D", "CHECK THAT IN MULTIPLE OBJECT DECLARATIONS " &
"FOR ACCESS TYPES, THE SUBTYPE INDICATION " &
"AND THE INITIALIZATION EXPRESSIONS ARE " &
"EVALUATED ONCE FOR EACH NAMED OBJECT THAT " &
"IS DECLARED AND THE SUBTYPE INDICATION IS " &
"EVALUATED FIRST. ALSO, CHECK THAT THE " &
"EVALUATIONS YIELD THE SAME RESULT AS A " &
"SEQUENCE OF SINGLE OBJECT DECLARATIONS" );
DECLARE
TYPE CELL (SIZE : INTEGER) IS
RECORD
VALUE : INTEGER;
END RECORD;
TYPE LINK IS ACCESS CELL;
L1, L2 : LINK (F (1)) := NEW CELL'(F1 (1), G (1));
CL1, CL2 : CONSTANT LINK (F (2)) := NEW CELL'(F1 (2), G (2));
PROCEDURE CHECK (L : LINK; V1, V2 : INTEGER; S : STRING) IS
BEGIN
IF L.SIZE /= V1 THEN
FAILED ( S & ".SIZE INITIALIZED INCORRECTLY TO " &
INTEGER'IMAGE (L.SIZE));
END IF;
IF L.VALUE /= V2 THEN
FAILED ( S & ".VALUE INITIALIZED INCORRECTLY TO " &
INTEGER'IMAGE (L.VALUE));
END IF;
END CHECK;
BEGIN
CHECK (L1, 1, 2, "L1");
CHECK (L2, 3, 4, "L2");
CHECK (CL1, 1, 2, "CL1");
CHECK (CL2, 3, 4, "CL2");
END;
RESULT;
END C32001D;
|
with System.Runtime_Context;
package body System.Secondary_Stack is
pragma Suppress (All_Checks);
use type Storage_Elements.Storage_Offset;
type Unsigned is mod 2 ** Integer'Size;
function clz (X : Unsigned) return Unsigned
with Import, Convention => Intrinsic, External_Name => "__builtin_clz";
procedure unreachable
with Import,
Convention => Intrinsic, External_Name => "__builtin_unreachable";
pragma No_Return (unreachable);
-- implementation
procedure SS_Allocate (
Addr : out Address;
Storage_Size : Storage_Elements.Storage_Count)
is
TLS : constant not null Runtime_Context.Task_Local_Storage_Access :=
Runtime_Context.Get_Task_Local_Storage;
Alignment : Storage_Elements.Storage_Count;
begin
-- alignment
if Storage_Size <= Standard'Maximum_Alignment / 2 then
declare
H : constant Integer :=
Integer (
clz (Unsigned (Storage_Size) * 2 - 1)
xor (Unsigned'Size - 1)); -- cancel wordy xor
begin
if H not in 0 .. Standard'Address_Size - 1 then
unreachable; -- assume H is in address-width
end if;
Alignment := Storage_Elements.Storage_Offset (
Storage_Elements.Integer_Address'(
Storage_Elements.Shift_Left (1, H)));
end;
else
Alignment := Standard'Maximum_Alignment;
end if;
Unbounded_Stack_Allocators.Allocate (
TLS.Secondary_Stack,
Addr,
Storage_Size,
Alignment);
end SS_Allocate;
function SS_Mark return Mark_Id is
TLS : constant not null Runtime_Context.Task_Local_Storage_Access :=
Runtime_Context.Get_Task_Local_Storage;
begin
return Unbounded_Stack_Allocators.Mark (TLS.Secondary_Stack);
end SS_Mark;
procedure SS_Release (M : Mark_Id) is
TLS : constant not null Runtime_Context.Task_Local_Storage_Access :=
Runtime_Context.Get_Task_Local_Storage;
begin
Unbounded_Stack_Allocators.Release (TLS.Secondary_Stack, M);
end SS_Release;
end System.Secondary_Stack;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- SQL Database Access --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2013, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This package is low level bindings to SQLite3 library.
------------------------------------------------------------------------------
with Interfaces.C;
with Matreshka.Internals.Strings.C;
with Matreshka.Internals.Utf16;
package Matreshka.Internals.SQL_Drivers.SQLite3 is
pragma Preelaborate;
----------------
-- Data types --
----------------
type sqlite3 is limited private;
type sqlite3_Access is access all sqlite3;
pragma Convention (C, sqlite3_Access);
type sqlite3_stmt is limited private;
type sqlite3_stmt_Access is access all sqlite3_stmt;
pragma Convention (C, sqlite3_stmt_Access);
type Utf16_Code_Unit_Access_Destructor is
access procedure
(Text : Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access);
pragma Convention (C, Utf16_Code_Unit_Access_Destructor);
---------------
-- Constants --
---------------
SQLITE_OK : constant := 0; -- Successful result
--#define SQLITE_ERROR 1 /* SQL error or missing database */
--#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
--#define SQLITE_PERM 3 /* Access permission denied */
--#define SQLITE_ABORT 4 /* Callback routine requested an abort */
--#define SQLITE_BUSY 5 /* The database file is locked */
--#define SQLITE_LOCKED 6 /* A table in the database is locked */
--#define SQLITE_NOMEM 7 /* A malloc() failed */
--#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
--#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
--#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
--#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
--#define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
--#define SQLITE_FULL 13 /* Insertion failed because database is full */
--#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
--#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
--#define SQLITE_EMPTY 16 /* Database is empty */
--#define SQLITE_SCHEMA 17 /* The database schema changed */
--#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
--#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
--#define SQLITE_MISMATCH 20 /* Data type mismatch */
--#define SQLITE_MISUSE 21 /* Library used incorrectly */
--#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
--#define SQLITE_AUTH 23 /* Authorization denied */
--#define SQLITE_FORMAT 24 /* Auxiliary database format error */
--#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
--#define SQLITE_NOTADB 26 /* File opened that is not a database file */
SQLITE_ROW : constant := 100; -- sqlite3_step() has another row
-- ready
SQLITE_DONE : constant := 101; -- sqlite3_step() has finished
-- executing
SQLITE_CONFIG_SINGLETHREAD : constant := 1; -- nil
SQLITE_CONFIG_MULTITHREAD : constant := 2; -- nil
SQLITE_CONFIG_SERIALIZED : constant := 3; -- nil
--#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
--#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
--#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
--#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
--#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
--#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
--#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
--#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
--/* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
--#define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
--#define SQLITE_CONFIG_PCACHE 14 /* sqlite3_pcache_methods* */
--#define SQLITE_CONFIG_GETPCACHE 15 /* sqlite3_pcache_methods* */
--#define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
SQLITE_INTEGER : constant := 1;
SQLITE_FLOAT : constant := 2;
SQLITE_TEXT : constant := 3;
SQLITE_BLOB : constant := 4;
SQLITE_NULL : constant := 5;
---------------
-- Functions --
---------------
function sqlite3_bind_double
(Handle : sqlite3_stmt_Access;
Index : Interfaces.C.int;
Value : Interfaces.C.double) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_double);
function sqlite3_bind_int64
(Handle : sqlite3_stmt_Access;
Index : Interfaces.C.int;
Value : Interfaces.Integer_64) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_int64);
function sqlite3_bind_null
(Handle : sqlite3_stmt_Access;
Index : Interfaces.C.int) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_null);
function sqlite3_bind_parameter_count
(Handle : sqlite3_stmt_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_parameter_count);
function sqlite3_bind_parameter_index
(Handle : sqlite3_stmt_Access;
Name : Interfaces.C.char_array) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_parameter_index);
function sqlite3_bind_text16
(Handle : sqlite3_stmt_Access;
Index : Interfaces.C.int;
Text : Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access;
nBytes : Interfaces.C.int;
Destructor : Utf16_Code_Unit_Access_Destructor) return Interfaces.C.int;
pragma Import (C, sqlite3_bind_text16);
function sqlite3_close (Handle : sqlite3_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_close);
function sqlite3_column_bytes16
(Handle : sqlite3_stmt_Access;
iCol : Interfaces.C.int) return Interfaces.C.int;
pragma Import (C, sqlite3_column_bytes16);
function sqlite3_column_double
(Handle : sqlite3_stmt_Access;
iCol : Interfaces.C.int) return Interfaces.C.double;
pragma Import (C, sqlite3_column_double);
function sqlite3_column_int64
(Handle : sqlite3_stmt_Access;
iCol : Interfaces.C.int) return Interfaces.Integer_64;
pragma Import (C, sqlite3_column_int64);
function sqlite3_column_text16
(Handle : sqlite3_stmt_Access;
iCol : Interfaces.C.int)
return Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access;
pragma Import (C, sqlite3_column_text16);
function sqlite3_column_type
(Handle : sqlite3_stmt_Access;
iCol : Interfaces.C.int) return Interfaces.C.int;
pragma Import (C, sqlite3_column_type);
function sqlite3_config (Option : Interfaces.C.int) return Interfaces.C.int;
pragma Import (C, sqlite3_config);
function sqlite3_errmsg16
(db : sqlite3_Access)
return Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access;
pragma Import (C, sqlite3_errmsg16);
function sqlite3_finalize
(Handle : sqlite3_stmt_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_finalize);
function sqlite3_last_insert_rowid
(Handle : sqlite3_Access) return Interfaces.Integer_64;
pragma Import (C, sqlite3_last_insert_rowid);
function sqlite3_open16
(File_Name : Matreshka.Internals.Utf16.Utf16_String;
-- Handle : out sqlite3_Access) return Interfaces.C.int;
Handle : not null access sqlite3_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_open16);
function sqlite3_prepare16_v2
(db : sqlite3_Access;
zSql : Matreshka.Internals.Utf16.Utf16_String;
nByte : Interfaces.C.int;
-- ppStmt : out sqlite3_stmt_Access;
-- pzTail : out Utf16_Code_Unit_Access) return Interfaces.C.int;
ppStmt : not null access sqlite3_stmt_Access;
pzTail :
not null access Matreshka.Internals.Strings.C.Utf16_Code_Unit_Access)
return Interfaces.C.int;
pragma Import (C, sqlite3_prepare16_v2);
function sqlite3_reset
(pStmt : sqlite3_stmt_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_reset);
function sqlite3_step
(Handle : sqlite3_stmt_Access) return Interfaces.C.int;
pragma Import (C, sqlite3_step);
private
type sqlite3 is limited null record;
type sqlite3_stmt is limited null record;
end Matreshka.Internals.SQL_Drivers.SQLite3;
|
-----------------------------------------------------------------------
-- util-commands-consoles-text -- Text console interface
-- Copyright (C) 2014, 2017, 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
generic
package Util.Commands.Consoles.Text is
type Console_Type is new Util.Commands.Consoles.Console_Type with private;
-- Report an error message.
overriding
procedure Error (Console : in out Console_Type;
Message : in String);
-- Report a notice message.
overriding
procedure Notice (Console : in out Console_Type;
Kind : in Notice_Type;
Message : in String);
-- Print the field value for the given field.
overriding
procedure Print_Field (Console : in out Console_Type;
Field : in Field_Type;
Value : in String;
Justify : in Justify_Type := J_LEFT);
-- Print the title for the given field.
overriding
procedure Print_Title (Console : in out Console_Type;
Field : in Field_Type;
Title : in String);
-- Start a new title in a report.
overriding
procedure Start_Title (Console : in out Console_Type);
-- Finish a new title in a report.
procedure End_Title (Console : in out Console_Type);
-- Start a new row in a report.
overriding
procedure Start_Row (Console : in out Console_Type);
-- Finish a new row in a report.
overriding
procedure End_Row (Console : in out Console_Type);
private
type Console_Type is new Util.Commands.Consoles.Console_Type with record
File : Ada.Text_IO.File_Type;
end record;
end Util.Commands.Consoles.Text;
|
with Screen_Interface; use Screen_Interface;
with Drawing; use Drawing;
with Ada.Real_Time; use Ada.Real_Time;
procedure Test is
Period : constant Time_Span := Milliseconds (500);
Next_Start : Time := Clock + Seconds (1);
begin
Screen_Interface.Initialize;
Fill_Screen (Black);
Circle (Center => (100, 100),
Radius => 50,
Col => Green,
Fill => True);
loop
Next_Start := Next_Start + Period;
delay until Next_Start;
end loop;
end Test;
|
-- Copyright ©2022 Steve 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.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Dasher_Codes; use Dasher_Codes;
with Logging; use Logging;
with Redirector;
package body Mini_Expect is
-- protected body Runner is
procedure Prepare (Filename : in String) is
begin
if Expecting then
raise Already_Expecting with "Cannot run mini-Expect script while another is still active";
end if;
Open (File => Expect_File, Mode => In_File, Name => Filename);
Log (TRACE, "mini-Expect script opened: " & Filename);
Runner_Task := new Runner_T;
end Prepare;
function Convert_Line (Script_Line : in String) return String is
-- Remove leading and trailing double-quotes, convert \n to Dasher NL
Src_Start : constant Positive := Index (Script_Line, """", Forward) + 1;
Src_End : constant Positive := Index (Script_Line, """", Backward);
Result : String (1 .. Src_End-Src_Start);
In_Ix : Positive := Src_Start;
Out_Ix : Positive := 1;
Changed : Boolean := False;
begin
Log (TRACE, "Convert_Line called with: " & Script_Line);
Log (TRACE, "... Src_Start set to" & Src_Start'Image & ", Src_End set to" & Src_End'Image);
Log (TRACE, "... Max result length set to" & Result'Length'Image);
while In_Ix < Src_End loop
Changed := False;
if In_Ix < Src_End then
if Script_Line(In_Ix) = '\' then
if Script_Line(In_Ix + 1) = 'n' then
Result(Out_Ix) := Dasher_NL;
In_Ix := In_Ix + 2; -- skip over a character
Out_Ix := Out_Ix + 1;
Changed := True;
end if;
end if;
end if;
if not Changed then
Result(Out_Ix) := Script_Line(In_Ix);
In_Ix := In_Ix + 1;
Out_Ix := Out_Ix + 1;
end if;
end loop;
Log (TRACE, "Convert_Line returning: " & Result(1 .. Out_Ix-1));
return Result(1 .. Out_Ix-1);
end Convert_Line;
procedure Handle_Char (Ch : in Character; Done : out Boolean) is
begin
if Ch = Dasher_NL or Ch = Dasher_CR then
-- Reset the search on every new line
Host_Str := Null_Unbounded_String;
else
Host_Str := Host_Str & Ch;
Log (TRACE, "... so far we have: " & To_String (Host_Str));
if Length (Host_Str) >= Length (Search_Str) then
Log (TRACE, "... Handle_Char comparing '" & To_String (Tail(Host_Str, Length (Search_Str)))
& "' with '" & To_String (Search_Str));
if Tail(Host_Str, Length (Search_Str)) = Search_Str then
Expecting := False;
Log (TRACE, "... MATCHED!");
end if;
end if;
end if;
Done := not Expecting;
end Handle_Char;
task body Runner_T is
Expect_Line : String(1..132);
Expect_Line_Length : Natural;
begin
Expecting := False;
while not End_Of_File (Expect_File) loop
Get_Line (Expect_File, Expect_Line, Expect_Line_Length);
Log (TRACE, "Expect script line: " & Expect_Line (1 .. Expect_Line_Length));
if Expect_Line_Length = 0 then
-- empty line
Log (TRACE, "... Skipping empty line");
elsif Expect_Line(1) = '#' then
-- comment line
Log (TRACE, "... Skipping comment line");
elsif Expect_Line(1..6) = "expect" then
-- expect string from host command, no timeout
Expecting := True;
Log (TRACE, "... Processing 'expect' command");
-- delay 0.2;
Search_Str := To_Unbounded_String (Convert_Line (Expect_Line(8..Expect_Line_Length)));
Log (TRACE, "... the search sting is '" & To_String (Search_Str) & "'");
Host_Str := Null_Unbounded_String;
while Expecting loop
Log (TRACE, "Mini_Expect waiting for match");
delay 0.1;
end loop;
Log (TRACE, "... found Expect string: " & To_String (Search_Str));
delay 0.2;
elsif Expect_Line(1..4) = "send" then
-- send line to host command
Log (TRACE, "... Processing 'send' command");
declare
Converted : constant String := Convert_Line (Expect_Line(6..Expect_Line_Length));
begin
Redirector.Router.Send_Data (Converted);
end;
elsif Expect_Line(1..4) = "exit" then
-- exit script command
exit;
else
Log (WARNING, "Cannot parse mini-Expect command - aborting script");
exit;
end if;
end loop;
Close (Expect_File);
Log (TRACE, "Mini-Expect script ***completed***");
end Runner_T;
end Mini_Expect; |
with agar.core.types;
package agar.gui.widget.progress_bar is
use type c.unsigned;
type type_t is (PROGRESS_BAR_HORIZ, PROGRESS_BAR_VERT);
for type_t use (PROGRESS_BAR_HORIZ => 0, PROGRESS_BAR_VERT => 1);
for type_t'size use c.unsigned'size;
pragma convention (c, type_t);
type flags_t is new c.unsigned;
PROGRESS_BAR_HFILL : constant flags_t := 16#01#;
PROGRESS_BAR_VFILL : constant flags_t := 16#02#;
PROGRESS_BAR_SHOW_PCT : constant flags_t := 16#04#;
PROGRESS_BAR_EXPAND : constant flags_t := PROGRESS_BAR_HFILL or PROGRESS_BAR_VFILL;
type progress_bar_t is limited private;
type progress_bar_access_t is access all progress_bar_t;
pragma convention (c, progress_bar_access_t);
type percent_t is new c.int range 0 .. 100;
type percent_access_t is access all percent_t;
pragma convention (c, percent_t);
pragma convention (c, percent_access_t);
-- API
function allocate
(parent : widget_access_t;
bar_type : type_t;
flags : flags_t) return progress_bar_access_t;
pragma import (c, allocate, "AG_ProgressBarNew");
function allocate_horizontal
(parent : widget_access_t;
flags : flags_t) return progress_bar_access_t;
pragma import (c, allocate_horizontal, "AG_ProgressBarNewHoriz");
function allocate_vertical
(parent : widget_access_t;
flags : flags_t) return progress_bar_access_t;
pragma import (c, allocate_vertical, "AG_ProgressBarNewVert");
procedure set_width
(bar : progress_bar_access_t;
width : natural);
pragma inline (set_width);
function percent (bar : progress_bar_access_t) return percent_t;
pragma import (c, percent, "AG_ProgressBarPercent");
function widget (bar : progress_bar_access_t) return widget_access_t;
pragma inline (widget);
private
type progress_bar_t is record
widget : aliased widget_t;
flags : flags_t;
value : c.int;
min : c.int;
max : c.int;
bar_type : type_t;
width : c.int;
pad : c.int;
cache : agar.core.types.void_ptr_t; -- XXX: ag_text_cache *
end record;
pragma convention (c, progress_bar_t);
end agar.gui.widget.progress_bar;
|
-----------------------------------------------------------------------
-- util-streams-raw -- Raw streams (OS specific)
-- Copyright (C) 2011, 2016, 2018, 2019 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.IO_Exceptions;
with Interfaces.C;
package body Util.Streams.Raw is
use Util.Systems.Os;
use type Util.Systems.Types.File_Type;
-- GNAT 2018 issues a warning due to the use type Interfaces.C.int clause.
-- But gcc 7.3 and older fails to compile and requires this use clause.
pragma Warnings (Off);
use type Interfaces.C.int;
pragma Warnings (On);
-- -----------------------
-- Initialize the raw stream to read and write on the given file descriptor.
-- -----------------------
procedure Initialize (Stream : in out Raw_Stream;
File : in File_Type) is
begin
if Stream.File /= NO_FILE then
raise Ada.IO_Exceptions.Status_Error;
end if;
Stream.File := File;
end Initialize;
-- -----------------------
-- Get the file descriptor associated with the stream.
-- -----------------------
function Get_File (Stream : in Raw_Stream) return Util.Systems.Os.File_Type is
begin
return Stream.File;
end Get_File;
-- -----------------------
-- Set the file descriptor to be used by the stream.
-- -----------------------
procedure Set_File (Stream : in out Raw_Stream;
File : in Util.Systems.Os.File_Type) is
begin
Stream.File := File;
end Set_File;
-- -----------------------
-- Close the stream.
-- -----------------------
overriding
procedure Close (Stream : in out Raw_Stream) is
begin
if Stream.File /= NO_FILE then
if Close (Stream.File) /= 0 then
raise Ada.IO_Exceptions.Device_Error;
end if;
Stream.File := NO_FILE;
end if;
end Close;
-- -----------------------
-- Write the buffer array to the output stream.
-- -----------------------
procedure Write (Stream : in out Raw_Stream;
Buffer : in Ada.Streams.Stream_Element_Array) is
begin
if Write (Stream.File, Buffer'Address, Buffer'Length) < 0 then
raise Ada.IO_Exceptions.Device_Error;
end if;
end Write;
-- -----------------------
-- Read into the buffer as many bytes as possible and return in
-- <b>last</b> the position of the last byte read.
-- -----------------------
procedure Read (Stream : in out Raw_Stream;
Into : out Ada.Streams.Stream_Element_Array;
Last : out Ada.Streams.Stream_Element_Offset) is
Res : Ssize_T;
begin
Res := Read (Stream.File, Into'Address, Into'Length);
if Res < 0 then
raise Ada.IO_Exceptions.Device_Error;
end if;
Last := Into'First + Ada.Streams.Stream_Element_Offset (Res) - 1;
end Read;
-- -----------------------
-- Reposition the read/write file offset.
-- -----------------------
procedure Seek (Stream : in out Raw_Stream;
Pos : in Util.Systems.Types.off_t;
Mode : in Util.Systems.Types.Seek_Mode) is
-- use type Util.Systems.Types.off_t;
Res : Util.Systems.Types.off_t;
begin
Res := Sys_Lseek (Stream.File, Pos, Mode);
if Res < 0 then
raise Ada.IO_Exceptions.Device_Error;
end if;
end Seek;
-- -----------------------
-- Flush the stream and release the buffer.
-- -----------------------
procedure Finalize (Object : in out Raw_Stream) is
begin
Close (Object);
end Finalize;
end Util.Streams.Raw;
|
-- Copyright © by Jeff Foley 2020-2022. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
-- SPDX-License-Identifier: Apache-2.0
local json = require("json")
name = "Censys"
type = "cert"
function start()
set_rate_limit(3)
end
function vertical(ctx, domain)
local c
local cfg = datasrc_config()
if cfg ~= nil then
c = cfg.credentials
end
if (c == nil or c.key == nil or c.key == "" or c.secret == nil or c.secret == "") then
return
end
api_query(ctx, cfg, domain)
end
function api_query(ctx, cfg, domain)
local p = 1
while(true) do
local err, body, resp
body, err = json.encode({
['query']="parsed.names: " .. domain,
['page']=p,
['fields']={"parsed.names"},
})
if (err ~= nil and err ~= "") then
return
end
resp, err = request(ctx, {
method="POST",
data=body,
['url']="https://www.censys.io/api/v1/search/certificates",
headers={['Content-Type']="application/json"},
id=cfg["credentials"].key,
pass=cfg["credentials"].secret,
})
if (err ~= nil and err ~= "") then
log(ctx, "vertical request to service failed: " .. err)
return
end
local d = json.decode(resp)
if (d == nil or d.status ~= "ok" or #(d.results) == 0) then
return
end
for _, r in pairs(d.results) do
for _, v in pairs(r["parsed.names"]) do
new_name(ctx, v)
end
end
if d["metadata"].page >= d["metadata"].pages then
return
end
p = p + 1
end
end
|
------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding Samples --
-- --
-- Sample.Menu_Demo.Aux --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998,2006 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: 2006/06/25 14:30:22 $
-- Binding Version 01.00
------------------------------------------------------------------------------
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Sample.Manifest; use Sample.Manifest;
with Sample.Helpers; use Sample.Helpers;
with Sample.Keyboard_Handler; use Sample.Keyboard_Handler;
with Sample.Explanation; use Sample.Explanation;
package body Sample.Menu_Demo.Aux is
procedure Geometry (M : in Menu;
L : out Line_Count;
C : out Column_Count;
Y : out Line_Position;
X : out Column_Position;
Fy : out Line_Position;
Fx : out Column_Position);
procedure Geometry (M : in Menu;
L : out Line_Count; -- Lines used for menu
C : out Column_Count; -- Columns used for menu
Y : out Line_Position; -- Proposed Line for menu
X : out Column_Position; -- Proposed Column for menu
Fy : out Line_Position; -- Vertical inner frame
Fx : out Column_Position) -- Horiz. inner frame
is
Spc_Desc : Column_Position; -- spaces between description and item
begin
Set_Mark (M, Menu_Marker);
Spacing (M, Spc_Desc, Fy, Fx);
Scale (M, L, C);
Fx := Fx + Column_Position (Fy - 1); -- looks a bit nicer
L := L + 2 * Fy; -- count for frame at top and bottom
C := C + 2 * Fx; -- "
-- Calculate horizontal coordinate at the screen center
X := (Columns - C) / 2;
Y := 1; -- always startin line 1
end Geometry;
procedure Geometry (M : in Menu;
L : out Line_Count; -- Lines used for menu
C : out Column_Count; -- Columns used for menu
Y : out Line_Position; -- Proposed Line for menu
X : out Column_Position) -- Proposed Column for menu
is
Fy : Line_Position;
Fx : Column_Position;
begin
Geometry (M, L, C, Y, X, Fy, Fx);
end Geometry;
function Create (M : Menu;
Title : String;
Lin : Line_Position;
Col : Column_Position) return Panel
is
W, S : Window;
L : Line_Count;
C : Column_Count;
Y, Fy : Line_Position;
X, Fx : Column_Position;
Pan : Panel;
begin
Geometry (M, L, C, Y, X, Fy, Fx);
W := New_Window (L, C, Lin, Col);
Set_Meta_Mode (W);
Set_KeyPad_Mode (W);
if Has_Colors then
Set_Background (Win => W,
Ch => (Ch => ' ',
Color => Menu_Back_Color,
Attr => Normal_Video));
Set_Foreground (Men => M, Color => Menu_Fore_Color);
Set_Background (Men => M, Color => Menu_Back_Color);
Set_Grey (Men => M, Color => Menu_Grey_Color);
Erase (W);
end if;
S := Derived_Window (W, L - Fy, C - Fx, Fy, Fx);
Set_Meta_Mode (S);
Set_KeyPad_Mode (S);
Box (W);
Set_Window (M, W);
Set_Sub_Window (M, S);
if Title'Length > 0 then
Window_Title (W, Title);
end if;
Pan := New_Panel (W);
Post (M);
return Pan;
end Create;
procedure Destroy (M : in Menu;
P : in out Panel)
is
W, S : Window;
begin
W := Get_Window (M);
S := Get_Sub_Window (M);
Post (M, False);
Erase (W);
Delete (P);
Set_Window (M, Null_Window);
Set_Sub_Window (M, Null_Window);
Delete (S);
Delete (W);
Update_Panels;
end Destroy;
function Get_Request (M : Menu; P : Panel) return Key_Code
is
W : constant Window := Get_Window (M);
K : Real_Key_Code;
Ch : Character;
begin
Top (P);
loop
K := Get_Key (W);
if K in Special_Key_Code'Range then
case K is
when HELP_CODE => Explain_Context;
when EXPLAIN_CODE => Explain ("MENUKEYS");
when Key_Home => return REQ_FIRST_ITEM;
when QUIT_CODE => return QUIT;
when Key_Cursor_Down => return REQ_DOWN_ITEM;
when Key_Cursor_Up => return REQ_UP_ITEM;
when Key_Cursor_Left => return REQ_LEFT_ITEM;
when Key_Cursor_Right => return REQ_RIGHT_ITEM;
when Key_End => return REQ_LAST_ITEM;
when Key_Backspace => return REQ_BACK_PATTERN;
when Key_Next_Page => return REQ_SCR_DPAGE;
when Key_Previous_Page => return REQ_SCR_UPAGE;
when others => return K;
end case;
elsif K in Normal_Key_Code'Range then
Ch := Character'Val (K);
case Ch is
when CAN => return QUIT; -- CTRL-X
when SO => return REQ_NEXT_ITEM; -- CTRL-N
when DLE => return REQ_PREV_ITEM; -- CTRL-P
when NAK => return REQ_SCR_ULINE; -- CTRL-U
when EOT => return REQ_SCR_DLINE; -- CTRL-D
when ACK => return REQ_SCR_DPAGE; -- CTRL-F
when STX => return REQ_SCR_UPAGE; -- CTRL-B
when EM => return REQ_CLEAR_PATTERN; -- CTRL-Y
when BS => return REQ_BACK_PATTERN; -- CTRL-H
when SOH => return REQ_NEXT_MATCH; -- CTRL-A
when ENQ => return REQ_PREV_MATCH; -- CTRL-E
when DC4 => return REQ_TOGGLE_ITEM; -- CTRL-T
when CR | LF => return SELECT_ITEM;
when others => return K;
end case;
else
return K;
end if;
end loop;
end Get_Request;
end Sample.Menu_Demo.Aux;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Unchecked_Conversion;
with GL.API;
with GL.Enums.Getter;
package body GL.Objects.Renderbuffers is
function Hash (Key : Low_Level.Enums.Renderbuffer_Kind)
return Ada.Containers.Hash_Type is
function Value is new Ada.Unchecked_Conversion
(Source => Low_Level.Enums.Renderbuffer_Kind, Target => Low_Level.Enum);
begin
return Ada.Containers.Hash_Type (Value (Key));
end Hash;
package Renderbuffer_Maps is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => Low_Level.Enums.Renderbuffer_Kind,
Element_Type => Renderbuffer'Class,
Hash => Hash,
Equivalent_Keys => Low_Level.Enums."=");
use type Renderbuffer_Maps.Cursor;
Current_Renderbuffers : Renderbuffer_Maps.Map;
procedure Allocate (Object : Renderbuffer_Target;
Format : Pixels.Internal_Format;
Width, Height : Size;
Samples : Size := 0) is
begin
if Samples = 0 then
API.Renderbuffer_Storage (Object.Kind, Format, Width, Height);
Raise_Exception_On_OpenGL_Error;
else
API.Renderbuffer_Storage_Multisample (Object.Kind, Samples, Format,
Width, Height);
end if;
end Allocate;
function Width (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Width, Value);
return Value;
end Width;
function Height (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Height, Value);
return Value;
end Height;
function Internal_Format (Object : Renderbuffer_Target)
return Pixels.Internal_Format is
Value : Pixels.Internal_Format := Pixels.Internal_Format'First;
begin
API.Get_Renderbuffer_Parameter_Internal_Format
(Object.Kind, Enums.Getter.Internal_Format, Value);
return Value;
end Internal_Format;
function Red_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Green_Size, Value);
return Value;
end Red_Size;
function Green_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Green_Size, Value);
return Value;
end Green_Size;
function Blue_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Blue_Size, Value);
return Value;
end Blue_Size;
function Alpha_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Alpha_Size, Value);
return Value;
end Alpha_Size;
function Depth_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int
(Object.Kind, Enums.Getter.Depth_Size, Value);
return Value;
end Depth_Size;
function Stencil_Size (Object : Renderbuffer_Target) return Size is
Value : Int := 0;
begin
API.Get_Renderbuffer_Parameter_Int (Object.Kind,
Enums.Getter.Stencil_Size,
Value);
return Value;
end Stencil_Size;
function Raw_Kind (Object : Renderbuffer_Target)
return Low_Level.Enums.Renderbuffer_Kind is
begin
return Object.Kind;
end Raw_Kind;
procedure Bind (Target : Renderbuffer_Target; Object : Renderbuffer'Class) is
Cursor : constant Renderbuffer_Maps.Cursor
:= Current_Renderbuffers.Find (Target.Kind);
begin
if Cursor = Renderbuffer_Maps.No_Element or else
Renderbuffer_Maps.Element
(Cursor).Reference.GL_Id /= Object.Reference.GL_Id
then
API.Bind_Renderbuffer (Target.Kind, Object.Reference.GL_Id);
Raise_Exception_On_OpenGL_Error;
if Cursor = Renderbuffer_Maps.No_Element then
Current_Renderbuffers.Insert (Target.Kind, Object);
else
Current_Renderbuffers.Replace_Element (Cursor, Object);
end if;
end if;
end Bind;
function Current (Target : Renderbuffer_Target) return Renderbuffer'Class is
Cursor : constant Renderbuffer_Maps.Cursor
:= Current_Renderbuffers.Find (Target.Kind);
begin
if Cursor = Renderbuffer_Maps.No_Element then
raise No_Object_Bound_Exception with Target.Kind'Img;
else
return Renderbuffer_Maps.Element (Cursor);
end if;
end Current;
overriding
procedure Internal_Create_Id (Object : Renderbuffer; Id : out UInt) is
pragma Unreferenced (Object);
begin
API.Gen_Renderbuffers (1, Id);
Raise_Exception_On_OpenGL_Error;
end Internal_Create_Id;
overriding
procedure Internal_Release_Id (Object : Renderbuffer; Id : UInt) is
pragma Unreferenced (Object);
begin
API.Delete_Renderbuffers (1, (1 => Id));
Raise_Exception_On_OpenGL_Error;
end Internal_Release_Id;
end GL.Objects.Renderbuffers;
|
-- Ascon.Load_Store
-- Functions to load and store 64-bit words from Storage_Array in Big Endian
-- format. Currently these are not optimised for the case where the machine
-- itself is BE or has dedicated assembly instructions that can perform the
-- conversion. Some compilers may have a peephole optimisation for these
-- routines.
-- Copyright (c) 2016-2017, James Humphry - see LICENSE file for details
-- Note that all the Unsigned_xx types count as Implementation_Identifiers
pragma Restrictions(No_Implementation_Attributes,
No_Implementation_Units,
No_Obsolescent_Features);
with System.Storage_Elements;
use System.Storage_Elements;
with Interfaces;
use Interfaces;
private generic package Ascon.Load_Store
with SPARK_Mode => On is
subtype E is Storage_Element;
function Check_Storage_Array_Length_8 (X : in Storage_Array) return Boolean
is
(
if X'Last < X'First then
False
elsif X'First < 0 then
(
(Long_Long_Integer (X'Last) < Long_Long_Integer'Last +
Long_Long_Integer (X'First))
and then
X'Last - X'First = 7)
else
X'Last - X'First = 7
)
with Ghost;
function Storage_Array_To_Unsigned_64 (S : in Storage_Array)
return Unsigned_64 is
(Shift_Left(Unsigned_64(S(S'First)), 56) or
Shift_Left(Unsigned_64(S(S'First + 1)), 48) or
Shift_Left(Unsigned_64(S(S'First + 2)), 40) or
Shift_Left(Unsigned_64(S(S'First + 3)), 32) or
Shift_Left(Unsigned_64(S(S'First + 4)), 24) or
Shift_Left(Unsigned_64(S(S'First + 5)), 16) or
Shift_Left(Unsigned_64(S(S'First + 6)), 8) or
Unsigned_64(S(S'First + 7)))
with Inline, Pre => (Check_Storage_Array_Length_8(S));
function Unsigned_64_To_Storage_Array (W : in Unsigned_64)
return Storage_Array is
(Storage_Array'(E(Shift_Right(W, 56) mod 16#100#),
E(Shift_Right(W, 48) mod 16#100#),
E(Shift_Right(W, 40) mod 16#100#),
E(Shift_Right(W, 32) mod 16#100#),
E(Shift_Right(W, 24) mod 16#100#),
E(Shift_Right(W, 16) mod 16#100#),
E(Shift_Right(W, 8) mod 16#100#),
E(W mod 16#100#)))
with Inline, Post => (Unsigned_64_To_Storage_Array'Result'Length = 8);
end Ascon.Load_Store;
|
with
ada.Strings.fixed;
package body openGL.Program.lit.textured_skinned
is
overriding
procedure define (Self : in out Item; use_vertex_Shader : in Shader.view;
use_fragment_Shader : in Shader.view)
is
use ada.Strings,
ada.Strings.fixed;
begin
openGL.Program.lit.item (Self).define (use_vertex_Shader,
use_fragment_Shader); -- Define base class.
for i in Self.bone_transform_Uniforms'Range
loop
Self.bone_transform_Uniforms (i).define (Self'Access,
"bone_Matrices[" & Trim (Integer'Image (i - 1), Left) & "]");
end loop;
end define;
overriding
procedure set_Uniforms (Self : in Item)
is
begin
openGL.Program.lit.item (Self).set_Uniforms;
-- Texture
--
declare
sampler_Uniform : constant Variable.uniform.int := Self.uniform_Variable ("sTexture");
begin
sampler_Uniform.Value_is (0);
end;
end set_Uniforms;
procedure bone_Transform_is (Self : in Item; Which : in Integer;
Now : in Matrix_4x4)
is
begin
Self.bone_transform_Uniforms (Which).Value_is (Now);
end bone_Transform_is;
end openGL.Program.lit.textured_skinned;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Slim.Message_Visiters;
package body Slim.Messages.STAT is
List : constant Field_Description_Array :=
((Uint_8_Field, 4), -- Event Code (a 4 byte string)
(Uint_8_Field, 1), -- Number of headers
(Uint_8_Field, 1), -- MAS Initalized - 'm' or 'p'
(Uint_8_Field, 1), -- MAS Mode - serdes mode?
(Uint_32_Field, 1), -- buffer size - in bytes, of the player's buffer
(Uint_32_Field, 1), -- fullness - data bytes in the player's buffer
(Uint_64_Field, 1), -- Bytes Recieved
(Uint_16_Field, 1), -- Wireless Signal Strength (0-100)
(Uint_32_Field, 1), -- jiffies - a timestamp from the player (@1kHz)
(Uint_32_Field, 1), -- output buffer size - the decoded audio data
(Uint_32_Field, 1), -- output buffer fullness - in decoded audio data
(Uint_32_Field, 1), -- elapsed seconds - of the current stream
(Uint_16_Field, 1), -- Voltage
(Uint_32_Field, 1), -- elapsed milliseconds - of the current stream
(Uint_32_Field, 1), -- server timestamp - reflected from an strm-t cmd
(Uint_16_Field, 1)); -- error code - used with STMn
---------------------
-- Elapsed_Seconds --
---------------------
not overriding function Elapsed_Seconds
(Self : STAT_Message) return Natural is
begin
return Natural (Self.Data_32 (6));
end Elapsed_Seconds;
-----------
-- Event --
-----------
not overriding function Event (Self : STAT_Message) return Event_Kind is
begin
return (Character'Val (Self.Data_8 (1)),
Character'Val (Self.Data_8 (2)),
Character'Val (Self.Data_8 (3)),
Character'Val (Self.Data_8 (4)));
end Event;
----------
-- Read --
----------
overriding function Read
(Data : not null access
League.Stream_Element_Vectors.Stream_Element_Vector)
return STAT_Message is
begin
return Result : STAT_Message do
Read_Fields (Result, List, Data.all);
end return;
end Read;
-----------
-- Visit --
-----------
overriding procedure Visit
(Self : not null access STAT_Message;
Visiter : in out Slim.Message_Visiters.Visiter'Class) is
begin
Visiter.STAT (Self);
end Visit;
----------------
-- WiFi_Level --
----------------
not overriding function WiFi_Level (Self : STAT_Message) return Natural is
begin
return Natural (Self.Data_16 (1));
end WiFi_Level;
-----------
-- Write --
-----------
overriding procedure Write
(Self : STAT_Message;
Tag : out Message_Tag;
Data : out League.Stream_Element_Vectors.Stream_Element_Vector) is
begin
Tag := "STAT";
Write_Fields (Self, List, Data);
end Write;
end Slim.Messages.STAT;
|
with Ada.Containers.Ordered_Maps;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO;
procedure Associative_Array is
-- Instantiate the generic package Ada.Containers.Ordered_Maps
package Associative_Int is new Ada.Containers.Ordered_Maps(Unbounded_String, Integer);
use Associative_Int;
Color_Map : Map;
Color_Cursor : Cursor;
Success : Boolean;
Value : Integer;
begin
-- Add values to the ordered map
Color_Map.Insert(To_Unbounded_String("Red"), 10, Color_Cursor, Success);
Color_Map.Insert(To_Unbounded_String("Blue"), 20, Color_Cursor, Success);
Color_Map.Insert(To_Unbounded_String("Yellow"), 5, Color_Cursor, Success);
-- retrieve values from the ordered map and print the value and key
-- to the screen
Value := Color_Map.Element(To_Unbounded_String("Red"));
Ada.Text_Io.Put_Line("Red:" & Integer'Image(Value));
Value := Color_Map.Element(To_Unbounded_String("Blue"));
Ada.Text_IO.Put_Line("Blue:" & Integer'Image(Value));
Value := Color_Map.Element(To_Unbounded_String("Yellow"));
Ada.Text_IO.Put_Line("Yellow:" & Integer'Image(Value));
end Associative_Array;
|
--
-- Copyright 2021 (C) Holger Rodriguez
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with HAL.UART;
with RP.GPIO;
with RP.UART;
with ItsyBitsy;
package body Transport.Serial is
UART_TX : RP.GPIO.GPIO_Point renames ItsyBitsy.TX;
UART_RX : RP.GPIO.GPIO_Point renames ItsyBitsy.RX;
Port : RP.UART.UART_Port renames ItsyBitsy.UART;
Initialized : Boolean := False;
--------------------------------------------------------------------------
-- Gets a character from the serial line.
-- If the timeout is > 0, and no character received inside the
-- time range defined, it will return
-- ASCII.NUL
-- This enables the caller to not being blocked
--------------------------------------------------------------------------
function Get (Timeout : Natural := 0) return Character;
procedure Initialize is
Console_Config : constant RP.UART.UART_Configuration
:= (Baud => 115_200, others => <>);
begin
if Initialized then
return;
end if;
UART_TX.Configure (Mode => RP.GPIO.Output,
Pull => RP.GPIO.Pull_Up,
Func => RP.GPIO.UART);
UART_RX.Configure (Mode => RP.GPIO.Input,
Pull => RP.GPIO.Floating,
Func => RP.GPIO.UART);
Port.Configure (Config => Console_Config);
Initialized := True;
end Initialize;
function Get_Area_Selector return Area_Selector is
Selector : constant Character := Get (100);
begin
if Selector = 'L' then
return Transport.Led;
elsif Selector = 'M' then
return Transport.Matrix;
else
return Transport.None;
end if;
end Get_Area_Selector;
function Get_LED_Instruction return Evaluate.LEDs.LED_Instruction is
RetVal : Evaluate.LEDs.LED_Instruction;
begin
for I in RetVal'First .. RetVal'Last loop
RetVal (I) := Get;
end loop;
return RetVal;
end Get_LED_Instruction;
function Get_Matrix_Instruction
return Evaluate.Matrices.Matrix_Instruction is
RetVal : Evaluate.Matrices.Matrix_Instruction;
begin
-- Get Block
RetVal (1) := Get;
-- Get Size
RetVal (2) := Get;
-- Get Position
RetVal (3) := Get;
-- Get the first two chars representing a byte
RetVal (4) := Get;
RetVal (5) := Get;
-- Check for Word/Double Word Size
if RetVal (2) = 'W' or RetVal (2) = 'D' then
-- Get the next two chars representing the last byte of the word
RetVal (6) := Get;
RetVal (7) := Get;
if RetVal (2) = 'D' then
-- Check for Double Word Size
-- Get the next four chars representing the
-- least significant word of the double word
RetVal (8) := Get;
RetVal (9) := Get;
RetVal (10) := Get;
RetVal (11) := Get;
end if;
end if;
return RetVal;
end Get_Matrix_Instruction;
function Get (Timeout : Natural := 0) return Character is
use HAL.UART;
Data : UART_Data_8b (1 .. 1);
Status : UART_Status;
begin
Port.Receive (Data, Status, Timeout => Timeout);
case Status is
when Ok =>
return Character'Val (Data (1));
when Err_Error | Err_Timeout | Busy =>
return ASCII.NUL;
end case;
end Get;
end Transport.Serial;
|
package Opt1 is
type Dimention_Length is array (1 .. 16) of Natural;
type Dimension_Indexes is array (Positive range <>) of Positive;
function De_Linear_Index
(Index : Natural;
D : Natural;
Ind_Lengths : Dimention_Length)
return Dimension_Indexes;
end Opt1;
|
with Ada.Containers.Indefinite_Vectors;
package Nutrition is
type Food is interface;
procedure Eat (Object : in out Food) is abstract;
end Nutrition;
with Ada.Containers;
with Nutrition;
generic
type New_Food is new Nutrition.Food;
package Food_Boxes is
package Food_Vectors is
new Ada.Containers.Indefinite_Vectors
( Index_Type => Positive,
Element_Type => New_Food
);
subtype Food_Box is Food_Vectors.Vector;
end Food_Boxes;
|
package Dse_Step is
type Counter is record
Value : Natural;
Step : Natural;
end record;
pragma Suppress_Initialization (Counter);
procedure Do_Step (This : in out Counter);
pragma Inline (Do_Step);
type My_Counter is new Counter;
pragma Suppress_Initialization (My_Counter);
procedure Step_From (Start : in My_Counter);
Nsteps : Natural := 12;
Mv : Natural;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- ADA.CONTAINERS.RED_BLACK_TREES.GENERIC_OPERATIONS --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-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/>. --
-- --
-- This unit was originally developed by Matthew J Heaney. --
------------------------------------------------------------------------------
-- The references below to "CLR" refer to the following book, from which
-- several of the algorithms here were adapted:
-- Introduction to Algorithms
-- by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest
-- Publisher: The MIT Press (June 18, 1990)
-- ISBN: 0262031418
with System; use type System.Address;
package body Ada.Containers.Red_Black_Trees.Generic_Operations is
pragma Warnings (Off, "variable ""Busy*"" is not referenced");
pragma Warnings (Off, "variable ""Lock*"" is not referenced");
-- See comment in Ada.Containers.Helpers
-----------------------
-- Local Subprograms --
-----------------------
procedure Delete_Fixup (Tree : in out Tree_Type; Node : Node_Access);
procedure Delete_Swap (Tree : in out Tree_Type; Z, Y : Node_Access);
procedure Left_Rotate (Tree : in out Tree_Type; X : Node_Access);
procedure Right_Rotate (Tree : in out Tree_Type; Y : Node_Access);
-- Why is all the following code commented out ???
-- ---------------------
-- -- Check_Invariant --
-- ---------------------
-- procedure Check_Invariant (Tree : Tree_Type) is
-- Root : constant Node_Access := Tree.Root;
--
-- function Check (Node : Node_Access) return Natural;
--
-- -----------
-- -- Check --
-- -----------
--
-- function Check (Node : Node_Access) return Natural is
-- begin
-- if Node = null then
-- return 0;
-- end if;
--
-- if Color (Node) = Red then
-- declare
-- L : constant Node_Access := Left (Node);
-- begin
-- pragma Assert (L = null or else Color (L) = Black);
-- null;
-- end;
--
-- declare
-- R : constant Node_Access := Right (Node);
-- begin
-- pragma Assert (R = null or else Color (R) = Black);
-- null;
-- end;
--
-- declare
-- NL : constant Natural := Check (Left (Node));
-- NR : constant Natural := Check (Right (Node));
-- begin
-- pragma Assert (NL = NR);
-- return NL;
-- end;
-- end if;
--
-- declare
-- NL : constant Natural := Check (Left (Node));
-- NR : constant Natural := Check (Right (Node));
-- begin
-- pragma Assert (NL = NR);
-- return NL + 1;
-- end;
-- end Check;
--
-- -- Start of processing for Check_Invariant
--
-- begin
-- if Root = null then
-- pragma Assert (Tree.First = null);
-- pragma Assert (Tree.Last = null);
-- pragma Assert (Tree.Length = 0);
-- null;
--
-- else
-- pragma Assert (Color (Root) = Black);
-- pragma Assert (Tree.Length > 0);
-- pragma Assert (Tree.Root /= null);
-- pragma Assert (Tree.First /= null);
-- pragma Assert (Tree.Last /= null);
-- pragma Assert (Parent (Tree.Root) = null);
-- pragma Assert ((Tree.Length > 1)
-- or else (Tree.First = Tree.Last
-- and Tree.First = Tree.Root));
-- pragma Assert (Left (Tree.First) = null);
-- pragma Assert (Right (Tree.Last) = null);
--
-- declare
-- L : constant Node_Access := Left (Root);
-- R : constant Node_Access := Right (Root);
-- NL : constant Natural := Check (L);
-- NR : constant Natural := Check (R);
-- begin
-- pragma Assert (NL = NR);
-- null;
-- end;
-- end if;
-- end Check_Invariant;
------------------
-- Delete_Fixup --
------------------
procedure Delete_Fixup (Tree : in out Tree_Type; Node : Node_Access) is
-- CLR p274
X : Node_Access := Node;
W : Node_Access;
begin
while X /= Tree.Root
and then Color (X) = Black
loop
if X = Left (Parent (X)) then
W := Right (Parent (X));
if Color (W) = Red then
Set_Color (W, Black);
Set_Color (Parent (X), Red);
Left_Rotate (Tree, Parent (X));
W := Right (Parent (X));
end if;
if (Left (W) = null or else Color (Left (W)) = Black)
and then
(Right (W) = null or else Color (Right (W)) = Black)
then
Set_Color (W, Red);
X := Parent (X);
else
if Right (W) = null
or else Color (Right (W)) = Black
then
-- As a condition for setting the color of the left child to
-- black, the left child access value must be non-null. A
-- truth table analysis shows that if we arrive here, that
-- condition holds, so there's no need for an explicit test.
-- The assertion is here to document what we know is true.
pragma Assert (Left (W) /= null);
Set_Color (Left (W), Black);
Set_Color (W, Red);
Right_Rotate (Tree, W);
W := Right (Parent (X));
end if;
Set_Color (W, Color (Parent (X)));
Set_Color (Parent (X), Black);
Set_Color (Right (W), Black);
Left_Rotate (Tree, Parent (X));
X := Tree.Root;
end if;
else
pragma Assert (X = Right (Parent (X)));
W := Left (Parent (X));
if Color (W) = Red then
Set_Color (W, Black);
Set_Color (Parent (X), Red);
Right_Rotate (Tree, Parent (X));
W := Left (Parent (X));
end if;
if (Left (W) = null or else Color (Left (W)) = Black)
and then
(Right (W) = null or else Color (Right (W)) = Black)
then
Set_Color (W, Red);
X := Parent (X);
else
if Left (W) = null or else Color (Left (W)) = Black then
-- As a condition for setting the color of the right child
-- to black, the right child access value must be non-null.
-- A truth table analysis shows that if we arrive here, that
-- condition holds, so there's no need for an explicit test.
-- The assertion is here to document what we know is true.
pragma Assert (Right (W) /= null);
Set_Color (Right (W), Black);
Set_Color (W, Red);
Left_Rotate (Tree, W);
W := Left (Parent (X));
end if;
Set_Color (W, Color (Parent (X)));
Set_Color (Parent (X), Black);
Set_Color (Left (W), Black);
Right_Rotate (Tree, Parent (X));
X := Tree.Root;
end if;
end if;
end loop;
Set_Color (X, Black);
end Delete_Fixup;
---------------------------
-- Delete_Node_Sans_Free --
---------------------------
procedure Delete_Node_Sans_Free
(Tree : in out Tree_Type;
Node : Node_Access)
is
-- CLR p273
X, Y : Node_Access;
Z : constant Node_Access := Node;
pragma Assert (Z /= null);
begin
TC_Check (Tree.TC);
-- Why are these all commented out ???
-- pragma Assert (Tree.Length > 0);
-- pragma Assert (Tree.Root /= null);
-- pragma Assert (Tree.First /= null);
-- pragma Assert (Tree.Last /= null);
-- pragma Assert (Parent (Tree.Root) = null);
-- pragma Assert ((Tree.Length > 1)
-- or else (Tree.First = Tree.Last
-- and then Tree.First = Tree.Root));
-- pragma Assert ((Left (Node) = null)
-- or else (Parent (Left (Node)) = Node));
-- pragma Assert ((Right (Node) = null)
-- or else (Parent (Right (Node)) = Node));
-- pragma Assert (((Parent (Node) = null) and then (Tree.Root = Node))
-- or else ((Parent (Node) /= null) and then
-- ((Left (Parent (Node)) = Node)
-- or else (Right (Parent (Node)) = Node))));
if Left (Z) = null then
if Right (Z) = null then
if Z = Tree.First then
Tree.First := Parent (Z);
end if;
if Z = Tree.Last then
Tree.Last := Parent (Z);
end if;
if Color (Z) = Black then
Delete_Fixup (Tree, Z);
end if;
pragma Assert (Left (Z) = null);
pragma Assert (Right (Z) = null);
if Z = Tree.Root then
pragma Assert (Tree.Length = 1);
pragma Assert (Parent (Z) = null);
Tree.Root := null;
elsif Z = Left (Parent (Z)) then
Set_Left (Parent (Z), null);
else
pragma Assert (Z = Right (Parent (Z)));
Set_Right (Parent (Z), null);
end if;
else
pragma Assert (Z /= Tree.Last);
X := Right (Z);
if Z = Tree.First then
Tree.First := Min (X);
end if;
if Z = Tree.Root then
Tree.Root := X;
elsif Z = Left (Parent (Z)) then
Set_Left (Parent (Z), X);
else
pragma Assert (Z = Right (Parent (Z)));
Set_Right (Parent (Z), X);
end if;
Set_Parent (X, Parent (Z));
if Color (Z) = Black then
Delete_Fixup (Tree, X);
end if;
end if;
elsif Right (Z) = null then
pragma Assert (Z /= Tree.First);
X := Left (Z);
if Z = Tree.Last then
Tree.Last := Max (X);
end if;
if Z = Tree.Root then
Tree.Root := X;
elsif Z = Left (Parent (Z)) then
Set_Left (Parent (Z), X);
else
pragma Assert (Z = Right (Parent (Z)));
Set_Right (Parent (Z), X);
end if;
Set_Parent (X, Parent (Z));
if Color (Z) = Black then
Delete_Fixup (Tree, X);
end if;
else
pragma Assert (Z /= Tree.First);
pragma Assert (Z /= Tree.Last);
Y := Next (Z);
pragma Assert (Left (Y) = null);
X := Right (Y);
if X = null then
if Y = Left (Parent (Y)) then
pragma Assert (Parent (Y) /= Z);
Delete_Swap (Tree, Z, Y);
Set_Left (Parent (Z), Z);
else
pragma Assert (Y = Right (Parent (Y)));
pragma Assert (Parent (Y) = Z);
Set_Parent (Y, Parent (Z));
if Z = Tree.Root then
Tree.Root := Y;
elsif Z = Left (Parent (Z)) then
Set_Left (Parent (Z), Y);
else
pragma Assert (Z = Right (Parent (Z)));
Set_Right (Parent (Z), Y);
end if;
Set_Left (Y, Left (Z));
Set_Parent (Left (Y), Y);
Set_Right (Y, Z);
Set_Parent (Z, Y);
Set_Left (Z, null);
Set_Right (Z, null);
declare
Y_Color : constant Color_Type := Color (Y);
begin
Set_Color (Y, Color (Z));
Set_Color (Z, Y_Color);
end;
end if;
if Color (Z) = Black then
Delete_Fixup (Tree, Z);
end if;
pragma Assert (Left (Z) = null);
pragma Assert (Right (Z) = null);
if Z = Right (Parent (Z)) then
Set_Right (Parent (Z), null);
else
pragma Assert (Z = Left (Parent (Z)));
Set_Left (Parent (Z), null);
end if;
else
if Y = Left (Parent (Y)) then
pragma Assert (Parent (Y) /= Z);
Delete_Swap (Tree, Z, Y);
Set_Left (Parent (Z), X);
Set_Parent (X, Parent (Z));
else
pragma Assert (Y = Right (Parent (Y)));
pragma Assert (Parent (Y) = Z);
Set_Parent (Y, Parent (Z));
if Z = Tree.Root then
Tree.Root := Y;
elsif Z = Left (Parent (Z)) then
Set_Left (Parent (Z), Y);
else
pragma Assert (Z = Right (Parent (Z)));
Set_Right (Parent (Z), Y);
end if;
Set_Left (Y, Left (Z));
Set_Parent (Left (Y), Y);
declare
Y_Color : constant Color_Type := Color (Y);
begin
Set_Color (Y, Color (Z));
Set_Color (Z, Y_Color);
end;
end if;
if Color (Z) = Black then
Delete_Fixup (Tree, X);
end if;
end if;
end if;
Tree.Length := Tree.Length - 1;
end Delete_Node_Sans_Free;
-----------------
-- Delete_Swap --
-----------------
procedure Delete_Swap
(Tree : in out Tree_Type;
Z, Y : Node_Access)
is
pragma Assert (Z /= Y);
pragma Assert (Parent (Y) /= Z);
Y_Parent : constant Node_Access := Parent (Y);
Y_Color : constant Color_Type := Color (Y);
begin
Set_Parent (Y, Parent (Z));
Set_Left (Y, Left (Z));
Set_Right (Y, Right (Z));
Set_Color (Y, Color (Z));
if Tree.Root = Z then
Tree.Root := Y;
elsif Right (Parent (Y)) = Z then
Set_Right (Parent (Y), Y);
else
pragma Assert (Left (Parent (Y)) = Z);
Set_Left (Parent (Y), Y);
end if;
if Right (Y) /= null then
Set_Parent (Right (Y), Y);
end if;
if Left (Y) /= null then
Set_Parent (Left (Y), Y);
end if;
Set_Parent (Z, Y_Parent);
Set_Color (Z, Y_Color);
Set_Left (Z, null);
Set_Right (Z, null);
end Delete_Swap;
--------------------
-- Generic_Adjust --
--------------------
procedure Generic_Adjust (Tree : in out Tree_Type) is
N : constant Count_Type := Tree.Length;
Root : constant Node_Access := Tree.Root;
use type Helpers.Tamper_Counts;
begin
-- If the counts are nonzero, execution is technically erroneous, but
-- it seems friendly to allow things like concurrent "=" on shared
-- constants.
Zero_Counts (Tree.TC);
if N = 0 then
pragma Assert (Root = null);
return;
end if;
Tree.Root := null;
Tree.First := null;
Tree.Last := null;
Tree.Length := 0;
Tree.Root := Copy_Tree (Root);
Tree.First := Min (Tree.Root);
Tree.Last := Max (Tree.Root);
Tree.Length := N;
end Generic_Adjust;
-------------------
-- Generic_Clear --
-------------------
procedure Generic_Clear (Tree : in out Tree_Type) is
Root : Node_Access := Tree.Root;
begin
TC_Check (Tree.TC);
Tree := (First => null,
Last => null,
Root => null,
Length => 0,
TC => <>);
Delete_Tree (Root);
end Generic_Clear;
-----------------------
-- Generic_Copy_Tree --
-----------------------
function Generic_Copy_Tree (Source_Root : Node_Access) return Node_Access is
Target_Root : Node_Access := Copy_Node (Source_Root);
P, X : Node_Access;
begin
if Right (Source_Root) /= null then
Set_Right
(Node => Target_Root,
Right => Generic_Copy_Tree (Right (Source_Root)));
Set_Parent
(Node => Right (Target_Root),
Parent => Target_Root);
end if;
P := Target_Root;
X := Left (Source_Root);
while X /= null loop
declare
Y : constant Node_Access := Copy_Node (X);
begin
Set_Left (Node => P, Left => Y);
Set_Parent (Node => Y, Parent => P);
if Right (X) /= null then
Set_Right
(Node => Y,
Right => Generic_Copy_Tree (Right (X)));
Set_Parent
(Node => Right (Y),
Parent => Y);
end if;
P := Y;
X := Left (X);
end;
end loop;
return Target_Root;
exception
when others =>
Delete_Tree (Target_Root);
raise;
end Generic_Copy_Tree;
-------------------------
-- Generic_Delete_Tree --
-------------------------
procedure Generic_Delete_Tree (X : in out Node_Access) is
Y : Node_Access;
pragma Warnings (Off, Y);
begin
while X /= null loop
Y := Right (X);
Generic_Delete_Tree (Y);
Y := Left (X);
Free (X);
X := Y;
end loop;
end Generic_Delete_Tree;
-------------------
-- Generic_Equal --
-------------------
function Generic_Equal (Left, Right : Tree_Type) return Boolean is
begin
if Left.Length /= Right.Length then
return False;
end if;
-- If the containers are empty, return a result immediately, so as to
-- not manipulate the tamper bits unnecessarily.
if Left.Length = 0 then
return True;
end if;
declare
Lock_Left : With_Lock (Left.TC'Unrestricted_Access);
Lock_Right : With_Lock (Right.TC'Unrestricted_Access);
L_Node : Node_Access := Left.First;
R_Node : Node_Access := Right.First;
begin
while L_Node /= null loop
if not Is_Equal (L_Node, R_Node) then
return False;
end if;
L_Node := Next (L_Node);
R_Node := Next (R_Node);
end loop;
end;
return True;
end Generic_Equal;
-----------------------
-- Generic_Iteration --
-----------------------
procedure Generic_Iteration (Tree : Tree_Type) is
procedure Iterate (P : Node_Access);
-------------
-- Iterate --
-------------
procedure Iterate (P : Node_Access) is
X : Node_Access := P;
begin
while X /= null loop
Iterate (Left (X));
Process (X);
X := Right (X);
end loop;
end Iterate;
-- Start of processing for Generic_Iteration
begin
Iterate (Tree.Root);
end Generic_Iteration;
------------------
-- Generic_Move --
------------------
procedure Generic_Move (Target, Source : in out Tree_Type) is
begin
if Target'Address = Source'Address then
return;
end if;
TC_Check (Source.TC);
Clear (Target);
Target := Source;
Source := (First => null,
Last => null,
Root => null,
Length => 0,
TC => <>);
end Generic_Move;
------------------
-- Generic_Read --
------------------
procedure Generic_Read
(Stream : not null access Root_Stream_Type'Class;
Tree : in out Tree_Type)
is
N : Count_Type'Base;
Node, Last_Node : Node_Access;
begin
Clear (Tree);
Count_Type'Base'Read (Stream, N);
pragma Assert (N >= 0);
if N = 0 then
return;
end if;
Node := Read_Node (Stream);
pragma Assert (Node /= null);
pragma Assert (Color (Node) = Red);
Set_Color (Node, Black);
Tree.Root := Node;
Tree.First := Node;
Tree.Last := Node;
Tree.Length := 1;
for J in Count_Type range 2 .. N loop
Last_Node := Node;
pragma Assert (Last_Node = Tree.Last);
Node := Read_Node (Stream);
pragma Assert (Node /= null);
pragma Assert (Color (Node) = Red);
Set_Right (Node => Last_Node, Right => Node);
Tree.Last := Node;
Set_Parent (Node => Node, Parent => Last_Node);
Rebalance_For_Insert (Tree, Node);
Tree.Length := Tree.Length + 1;
end loop;
end Generic_Read;
-------------------------------
-- Generic_Reverse_Iteration --
-------------------------------
procedure Generic_Reverse_Iteration (Tree : Tree_Type)
is
procedure Iterate (P : Node_Access);
-------------
-- Iterate --
-------------
procedure Iterate (P : Node_Access) is
X : Node_Access := P;
begin
while X /= null loop
Iterate (Right (X));
Process (X);
X := Left (X);
end loop;
end Iterate;
-- Start of processing for Generic_Reverse_Iteration
begin
Iterate (Tree.Root);
end Generic_Reverse_Iteration;
-------------------
-- Generic_Write --
-------------------
procedure Generic_Write
(Stream : not null access Root_Stream_Type'Class;
Tree : Tree_Type)
is
procedure Process (Node : Node_Access);
pragma Inline (Process);
procedure Iterate is
new Generic_Iteration (Process);
-------------
-- Process --
-------------
procedure Process (Node : Node_Access) is
begin
Write_Node (Stream, Node);
end Process;
-- Start of processing for Generic_Write
begin
Count_Type'Base'Write (Stream, Tree.Length);
Iterate (Tree);
end Generic_Write;
-----------------
-- Left_Rotate --
-----------------
procedure Left_Rotate (Tree : in out Tree_Type; X : Node_Access) is
-- CLR p266
Y : constant Node_Access := Right (X);
pragma Assert (Y /= null);
begin
Set_Right (X, Left (Y));
if Left (Y) /= null then
Set_Parent (Left (Y), X);
end if;
Set_Parent (Y, Parent (X));
if X = Tree.Root then
Tree.Root := Y;
elsif X = Left (Parent (X)) then
Set_Left (Parent (X), Y);
else
pragma Assert (X = Right (Parent (X)));
Set_Right (Parent (X), Y);
end if;
Set_Left (Y, X);
Set_Parent (X, Y);
end Left_Rotate;
---------
-- Max --
---------
function Max (Node : Node_Access) return Node_Access is
-- CLR p248
X : Node_Access := Node;
Y : Node_Access;
begin
loop
Y := Right (X);
if Y = null then
return X;
end if;
X := Y;
end loop;
end Max;
---------
-- Min --
---------
function Min (Node : Node_Access) return Node_Access is
-- CLR p248
X : Node_Access := Node;
Y : Node_Access;
begin
loop
Y := Left (X);
if Y = null then
return X;
end if;
X := Y;
end loop;
end Min;
----------
-- Next --
----------
function Next (Node : Node_Access) return Node_Access is
begin
-- CLR p249
if Node = null then
return null;
end if;
if Right (Node) /= null then
return Min (Right (Node));
end if;
declare
X : Node_Access := Node;
Y : Node_Access := Parent (Node);
begin
while Y /= null
and then X = Right (Y)
loop
X := Y;
Y := Parent (Y);
end loop;
return Y;
end;
end Next;
--------------
-- Previous --
--------------
function Previous (Node : Node_Access) return Node_Access is
begin
if Node = null then
return null;
end if;
if Left (Node) /= null then
return Max (Left (Node));
end if;
declare
X : Node_Access := Node;
Y : Node_Access := Parent (Node);
begin
while Y /= null
and then X = Left (Y)
loop
X := Y;
Y := Parent (Y);
end loop;
return Y;
end;
end Previous;
--------------------------
-- Rebalance_For_Insert --
--------------------------
procedure Rebalance_For_Insert
(Tree : in out Tree_Type;
Node : Node_Access)
is
-- CLR p.268
X : Node_Access := Node;
pragma Assert (X /= null);
pragma Assert (Color (X) = Red);
Y : Node_Access;
begin
while X /= Tree.Root and then Color (Parent (X)) = Red loop
if Parent (X) = Left (Parent (Parent (X))) then
Y := Right (Parent (Parent (X)));
if Y /= null and then Color (Y) = Red then
Set_Color (Parent (X), Black);
Set_Color (Y, Black);
Set_Color (Parent (Parent (X)), Red);
X := Parent (Parent (X));
else
if X = Right (Parent (X)) then
X := Parent (X);
Left_Rotate (Tree, X);
end if;
Set_Color (Parent (X), Black);
Set_Color (Parent (Parent (X)), Red);
Right_Rotate (Tree, Parent (Parent (X)));
end if;
else
pragma Assert (Parent (X) = Right (Parent (Parent (X))));
Y := Left (Parent (Parent (X)));
if Y /= null and then Color (Y) = Red then
Set_Color (Parent (X), Black);
Set_Color (Y, Black);
Set_Color (Parent (Parent (X)), Red);
X := Parent (Parent (X));
else
if X = Left (Parent (X)) then
X := Parent (X);
Right_Rotate (Tree, X);
end if;
Set_Color (Parent (X), Black);
Set_Color (Parent (Parent (X)), Red);
Left_Rotate (Tree, Parent (Parent (X)));
end if;
end if;
end loop;
Set_Color (Tree.Root, Black);
end Rebalance_For_Insert;
------------------
-- Right_Rotate --
------------------
procedure Right_Rotate (Tree : in out Tree_Type; Y : Node_Access) is
X : constant Node_Access := Left (Y);
pragma Assert (X /= null);
begin
Set_Left (Y, Right (X));
if Right (X) /= null then
Set_Parent (Right (X), Y);
end if;
Set_Parent (X, Parent (Y));
if Y = Tree.Root then
Tree.Root := X;
elsif Y = Left (Parent (Y)) then
Set_Left (Parent (Y), X);
else
pragma Assert (Y = Right (Parent (Y)));
Set_Right (Parent (Y), X);
end if;
Set_Right (X, Y);
Set_Parent (Y, X);
end Right_Rotate;
---------
-- Vet --
---------
function Vet (Tree : Tree_Type; Node : Node_Access) return Boolean is
begin
if Node = null then
return True;
end if;
if Parent (Node) = Node
or else Left (Node) = Node
or else Right (Node) = Node
then
return False;
end if;
if Tree.Length = 0
or else Tree.Root = null
or else Tree.First = null
or else Tree.Last = null
then
return False;
end if;
if Parent (Tree.Root) /= null then
return False;
end if;
if Left (Tree.First) /= null then
return False;
end if;
if Right (Tree.Last) /= null then
return False;
end if;
if Tree.Length = 1 then
if Tree.First /= Tree.Last
or else Tree.First /= Tree.Root
then
return False;
end if;
if Node /= Tree.First then
return False;
end if;
if Parent (Node) /= null
or else Left (Node) /= null
or else Right (Node) /= null
then
return False;
end if;
return True;
end if;
if Tree.First = Tree.Last then
return False;
end if;
if Tree.Length = 2 then
if Tree.First /= Tree.Root
and then Tree.Last /= Tree.Root
then
return False;
end if;
if Tree.First /= Node
and then Tree.Last /= Node
then
return False;
end if;
end if;
if Left (Node) /= null
and then Parent (Left (Node)) /= Node
then
return False;
end if;
if Right (Node) /= null
and then Parent (Right (Node)) /= Node
then
return False;
end if;
if Parent (Node) = null then
if Tree.Root /= Node then
return False;
end if;
elsif Left (Parent (Node)) /= Node
and then Right (Parent (Node)) /= Node
then
return False;
end if;
return True;
end Vet;
end Ada.Containers.Red_Black_Trees.Generic_Operations;
|
with Ada.Text_Io; use Ada.Text_Io;
procedure Roots_Of_Function is
package Real_Io is new Ada.Text_Io.Float_Io(Long_Float);
use Real_Io;
function F(X : Long_Float) return Long_Float is
begin
return (X**3 - 3.0*X*X + 2.0*X);
end F;
Step : constant Long_Float := 1.0E-6;
Start : constant Long_Float := -1.0;
Stop : constant Long_Float := 3.0;
Value : Long_Float := F(Start);
Sign : Boolean := Value > 0.0;
X : Long_Float := Start + Step;
begin
if Value = 0.0 then
Put("Root found at ");
Put(Item => Start, Fore => 1, Aft => 6, Exp => 0);
New_Line;
end if;
while X <= Stop loop
Value := F(X);
if (Value > 0.0) /= Sign then
Put("Root found near ");
Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
New_Line;
elsif Value = 0.0 then
Put("Root found at ");
Put(Item => X, Fore => 1, Aft => 6, Exp => 0);
New_Line;
end if;
Sign := Value > 0.0;
X := X + Step;
end loop;
end Roots_Of_Function;
|
-- AoC 2020, Day 13
with Ada.Text_IO;
with GNAT.String_Split;
use GNAT;
package body Day is
package TIO renames Ada.Text_IO;
function load_file(filename : in String) return Schedule is
file : TIO.File_Type;
earliest : Long_Long_Integer;
departs : Depart_Vectors.Vector := Empty_Vector;
offsets : Depart_Vectors.Vector := Empty_Vector;
subs : String_Split.Slice_Set;
seps : constant String := ",";
begin
TIO.open(File => file, Mode => TIO.In_File, Name => filename);
earliest := Long_Long_Integer'Value(TIO.get_line(file));
String_Split.Create (S => subs, From => TIO.get_line(file), Separators => seps, Mode => String_Split.Multiple);
TIO.close(file);
for i in 1 .. String_Split.Slice_Count(subs) loop
declare
sub : constant String := String_Split.Slice(subs, i);
begin
if sub /= "x" then
departs.append(Long_Long_Integer'Value(sub));
offsets.append(Long_Long_Integer(i) - 1);
end if;
end;
end loop;
return Schedule'(earliest => earliest, departures => departs, offsets => offsets);
end load_file;
function bus_mult(s : in Schedule) return Long_Long_Integer is
offset : Long_Long_Integer := 0;
begin
loop
declare
leave : constant Long_Long_Integer := s.earliest + offset;
begin
for d of s.departures loop
if (leave mod d) = 0 then
return offset * d;
end if;
end loop;
offset := offset + 1;
end;
end loop;
end bus_mult;
function earliest_matching_iterative(s : in Schedule) return Long_Long_Integer is
t : Long_Long_Integer := 1;
begin
main_loop:
loop
declare
match : Boolean := true;
base : constant Long_Long_Integer := Long_Long_Integer(s.departures.first_element) * t;
begin
for i in s.departures.first_index+1 .. s.departures.last_index loop
declare
long_offset : constant Long_Long_Integer := s.offsets(i);
long_depart : constant Long_Long_Integer := s.departures(i);
offset : constant Long_Long_Integer := base + long_offset;
begin
if (offset mod long_depart) /= 0 then
match := false;
exit;
end if;
end;
end loop;
if match then
return base;
end if;
t := t+1;
end;
end loop main_loop;
end earliest_matching_iterative;
function bus_intersect(start : in Long_Long_Integer; step : in Long_Long_Integer;
bus : in Long_Long_Integer; offset : in Long_Long_Integer) return Long_Long_Integer is
t : Long_Long_Integer := start;
offset_t : Long_Long_Integer;
begin
loop
offset_t := t + offset;
if offset_t mod bus = 0 then
exit;
end if;
t := t + step;
end loop;
return t;
end bus_intersect;
function earliest_matching(s : in Schedule) return Long_Long_Integer is
t : Long_Long_Integer := 0;
step : Long_Long_Integer := s.departures.first_element;
begin
for i in s.departures.first_index+1 .. s.departures.last_index loop
t := bus_intersect(t, step, s.departures(i), s.offsets(i));
step := step * s.departures(i);
end loop;
return t;
end earliest_matching;
end Day;
|
-- Copyright (c) 2020-2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Strings.Hash;
-- ****h* Themes/Themes
-- FUNCTION
-- Provide code for read and set the game UI themes
-- SOURCE
package Themes is
-- ****
-- ****t* Themes/Themes.FontTypes
-- FUNCTION
-- Types of font available in game
-- SOURCE
type Font_Types is (HELPFONT, MAPFONT, INTERFACEFONT, ALLFONTS);
-- ****
-- ****d* Themes/Themes.All_Fonts
-- FUNCTION
-- Default value for FontTypes, all fonts
-- SOURCE
All_Fonts: constant Font_Types := ALLFONTS;
-- ****
-- ****t* Themes/Themes.Theme_Record
-- FUNCTION
-- Data structure for themes settings
-- PARAMETERS
-- Name - Name of theme
-- File_Name - Name of .tcl file of theme
-- Enemy_Ship_Icon - Icon used for Enemy Ship event
-- Attack_On_Base_Icon - Icon used for Attack on Base event
-- Disease_Icon - Icon used for Disease event
-- Double_PriceIcon - Icon used for Double Price event
-- Full_Docks_Icon - Icon used for Full Docks event
-- Enemy_Patrol_Icon - Icon used for Enemy Patrol event
-- Trader_Icon - Icon used for Trader event
-- Friendly_Ship_Icon - Icon used for Friendly Ship event
-- Deliver_Icon - Icon used for Deliver Item mission
-- Destroy_Icon - Icon used for Destroy Ship mission
-- Patrol_Icon - Icon used for Patrol Area mission
-- Explore_Icon - Icon used for Explore Area mission
-- Passenger_Icon - Icon used for Transport Passenger mission
-- Pilot_Icon - Icon used for Pilot info
-- Engineer_Icon - Icon used for Engineer info
-- Gunner_Icon - Icon used for Gunners info
-- Crew_Trader_Icon - Icon used for Trader info
-- Repair_Icon - Icon used for Repairs info
-- Upgrade_Icon - Icon used for Upgrade info
-- Clean_Icon - Icon used for Clean Ship info
-- Manufacture_Icon - Icon used for Manufacturing info
-- Move_Map_Up_Icon - Icon used for move map up button
-- Move_Map_Down_Icon - Icon used for move map down button
-- Move_Map_Left_Icon - Icon used for move map left button
-- Move_Map_Right_Icon - Icon used for move map right button
-- No_Fuel_Icon - Icon used for show warning about no fuel
-- No_Food_Icon - Icon used for show warning about no food
-- No_Drinks_Icon - Icon used for show warning about no drinks
-- Not_Visited_Base_Icon - Icon used for show not visited bases on map
-- Player_Ship_Icon - Icon used for show player ship on map
-- Empty_Map_Icon - Icon used for empty map fields
-- Target_Icon - Icon used for player selected target on map
-- Story_Icon - Icon used for show story event location on map
-- Overloaded_Icon - Icon used for show warning about overloaded ship
-- SOURCE
type Theme_Record is record
Name: Unbounded_String;
File_Name: Unbounded_String;
Enemy_Ship_Icon: Wide_Character;
Attack_On_Base_Icon: Wide_Character;
Disease_Icon: Wide_Character;
Double_Price_Icon: Wide_Character;
Full_Docks_Icon: Wide_Character;
Enemy_Patrol_Icon: Wide_Character;
Trader_Icon: Wide_Character;
Friendly_Ship_Icon: Wide_Character;
Deliver_Icon: Wide_Character;
Destroy_Icon: Wide_Character;
Patrol_Icon: Wide_Character;
Explore_Icon: Wide_Character;
Passenger_Icon: Wide_Character;
Pilot_Icon: Wide_Character;
Engineer_Icon: Wide_Character;
Gunner_Icon: Wide_Character;
Crew_Trader_Icon: Wide_Character;
Repair_Icon: Wide_Character;
Upgrade_Icon: Wide_Character;
Clean_Icon: Wide_Character;
Manufacture_Icon: Wide_Character;
Move_Map_Up_Icon: Wide_Character;
Move_Map_Down_Icon: Wide_Character;
Move_Map_Left_Icon: Wide_Character;
Move_Map_Right_Icon: Wide_Character;
No_Fuel_Icon: Wide_Character;
No_Food_Icon: Wide_Character;
No_Drinks_Icon: Wide_Character;
Not_Visited_Base_Icon: Wide_Character;
Player_Ship_Icon: Wide_Character;
Empty_Map_Icon: Wide_Character;
Target_Icon: Wide_Character;
Story_Icon: Wide_Character;
Overloaded_Icon: Wide_Character;
end record;
-- ****
-- ****d* Themes/Themes.Default_Theme
-- FUNCTION
-- Default the game theme
-- SOURCE
Default_Theme: constant Theme_Record :=
(Name => Null_Unbounded_String, File_Name => Null_Unbounded_String,
Enemy_Ship_Icon => Wide_Character'Val(16#f51c#),
Attack_On_Base_Icon => Wide_Character'Val(16#f543#),
Disease_Icon => Wide_Character'Val(16#f5a6#),
Double_Price_Icon => Wide_Character'Val(16#f0d6#),
Full_Docks_Icon => Wide_Character'Val(16#f057#),
Enemy_Patrol_Icon => Wide_Character'Val(16#f51b#),
Trader_Icon => Wide_Character'Val(16#f197#),
Friendly_Ship_Icon => Wide_Character'Val(16#f197#),
Deliver_Icon => Wide_Character'Val(16#f53b#),
Destroy_Icon => Wide_Character'Val(16#fc6a#),
Patrol_Icon => Wide_Character'Val(16#f540#),
Explore_Icon => Wide_Character'Val(16#f707#),
Passenger_Icon => Wide_Character'Val(16#f183#),
Pilot_Icon => Wide_Character'Val(16#f655#),
Engineer_Icon => Wide_Character'Val(16#f013#),
Gunner_Icon => Wide_Character'Val(16#f4fb#),
Crew_Trader_Icon => Wide_Character'Val(16#f651#),
Repair_Icon => Wide_Character'Val(16#f54a#),
Upgrade_Icon => Wide_Character'Val(16#f6e3#),
Clean_Icon => Wide_Character'Val(16#f458#),
Manufacture_Icon => Wide_Character'Val(16#f0e3#),
Move_Map_Up_Icon => Wide_Character'Val(16#2191#),
Move_Map_Down_Icon => Wide_Character'Val(16#2193#),
Move_Map_Left_Icon => Wide_Character'Val(16#2190#),
Move_Map_Right_Icon => Wide_Character'Val(16#2192#),
No_Fuel_Icon => Wide_Character'Val(16#f2ca#),
No_Food_Icon => Wide_Character'Val(16#f787#),
No_Drinks_Icon => Wide_Character'Val(16#f72f#),
Not_Visited_Base_Icon => Wide_Character'Val(16#229b#),
Player_Ship_Icon => Wide_Character'Val(16#f135#),
Empty_Map_Icon => Wide_Character'Val(16#f0c8#),
Target_Icon => Wide_Character'Val(16#f05b#),
Story_Icon => Wide_Character'Val(16#f059#),
Overloaded_Icon => Wide_Character'Val(16#f55b#));
-- ****
-- ****t* Themes/Themes.Themes_Container
-- FUNCTION
-- Used to store themes data
-- SOURCE
package Themes_Container is new Ada.Containers.Indefinite_Hashed_Maps
(Key_Type => String, Element_Type => Theme_Record,
Hash => Ada.Strings.Hash, Equivalent_Keys => "=");
-- ****
-- ****v* Themes/Themes.Themes_List
-- FUNCTION
-- List of all available themes
-- SOURCE
Themes_List: Themes_Container.Map;
-- ****
-- ****f* Themes/Themes.Load_Themes
-- FUNCTION
-- Load data for all themes
-- SOURCE
procedure Load_Themes;
-- ****
-- ****f* Themes/Themes.Set_Theme
-- FUNCTION
-- Set values for the current theme
-- SOURCE
procedure Set_Theme;
-- ****
end Themes;
|
-----------------------------------------------------------------------
-- util-processes-os -- System specific and low level operations
-- Copyright (C) 2011, 2012, 2018, 2019 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 System;
with Ada.Unchecked_Deallocation;
with Ada.Characters.Conversions;
with Ada.Directories;
with Util.Log.Loggers;
package body Util.Processes.Os is
use type Interfaces.C.size_t;
use type Util.Systems.Os.HANDLE;
use type Ada.Directories.File_Kind;
use type System.Address;
-- The logger
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Processes.Os");
procedure Free is
new Ada.Unchecked_Deallocation (Object => Interfaces.C.wchar_array,
Name => Wchar_Ptr);
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class);
procedure Redirect_Output (Path : in Wchar_Ptr;
Append : in Boolean;
Output : out HANDLE);
procedure Redirect_Input (Path : in Wchar_Ptr;
Input : out HANDLE);
-- ------------------------------
-- Wait for the process to exit.
-- ------------------------------
overriding
procedure Wait (Sys : in out System_Process;
Proc : in out Process'Class;
Timeout : in Duration) is
use type Util.Streams.Output_Stream_Access;
Result : DWORD;
T : DWORD;
Code : aliased DWORD;
Status : BOOL;
begin
-- Close the input stream pipe if there is one.
if Proc.Input /= null then
Util.Streams.Raw.Raw_Stream'Class (Proc.Input.all).Close;
end if;
if Timeout < 0.0 then
T := DWORD'Last;
else
T := DWORD (Timeout * 1000.0);
Log.Debug ("Waiting {0} ms", DWORD'Image (T));
end if;
Result := Wait_For_Single_Object (H => Sys.Process_Info.hProcess,
Time => T);
Log.Debug ("Status {0}", DWORD'Image (Result));
Status := Get_Exit_Code_Process (Proc => Sys.Process_Info.hProcess,
Code => Code'Unchecked_Access);
if Status = 0 then
Log.Error ("Process is still running. Error {0}", Integer'Image (Get_Last_Error));
end if;
Proc.Exit_Value := Integer (Code);
Log.Debug ("Process exit is: {0}", Integer'Image (Proc.Exit_Value));
end Wait;
-- ------------------------------
-- Terminate the process by sending a signal on Unix and exiting the process on Windows.
-- This operation is not portable and has a different behavior between Unix and Windows.
-- Its intent is to stop the process.
-- ------------------------------
overriding
procedure Stop (Sys : in out System_Process;
Proc : in out Process'Class;
Signal : in Positive := 15) is
pragma Unreferenced (Proc);
Result : Integer;
pragma Unreferenced (Result);
begin
Result := Terminate_Process (Sys.Process_Info.hProcess, DWORD (Signal));
end Stop;
procedure Prepare_Working_Directory (Sys : in out System_Process;
Proc : in out Process'Class) is
Dir : constant String := Ada.Strings.Unbounded.To_String (Proc.Dir);
begin
Free (Sys.Dir);
if Dir'Length > 0 then
if not Ada.Directories.Exists (Dir)
or else Ada.Directories.Kind (Dir) /= Ada.Directories.Directory
then
raise Ada.Directories.Name_Error with "Invalid directory: " & Dir;
end if;
Sys.Dir := To_WSTR (Dir);
end if;
end Prepare_Working_Directory;
procedure Redirect_Output (Path : in Wchar_Ptr;
Append : in Boolean;
Output : out HANDLE) is
Sec : aliased Security_Attributes;
begin
Sec.Length := Security_Attributes'Size / 8;
Sec.Security_Descriptor := System.Null_Address;
Sec.Inherit := 1;
Output := Create_File (Path.all'Address,
(if Append then FILE_APPEND_DATA else GENERIC_WRITE),
FILE_SHARE_WRITE + FILE_SHARE_READ,
Sec'Unchecked_Access,
(if Append then OPEN_ALWAYS else CREATE_ALWAYS),
FILE_ATTRIBUTE_NORMAL,
NO_FILE);
if Output = INVALID_HANDLE_VALUE then
Log.Error ("Cannot create process output file: {0}", Integer'Image (Get_Last_Error));
raise Process_Error with "Cannot create process output file";
end if;
end Redirect_Output;
procedure Redirect_Input (Path : in Wchar_Ptr;
Input : out HANDLE) is
Sec : aliased Security_Attributes;
begin
Sec.Length := Security_Attributes'Size / 8;
Sec.Security_Descriptor := System.Null_Address;
Sec.Inherit := 1;
Input := Create_File (Path.all'Address,
GENERIC_READ,
FILE_SHARE_READ,
Sec'Unchecked_Access,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NO_FILE);
if Input = INVALID_HANDLE_VALUE then
Log.Error ("Cannot open process input file: {0}", Integer'Image (Get_Last_Error));
raise Process_Error with "Cannot open process input file";
end if;
end Redirect_Input;
-- ------------------------------
-- Spawn a new process.
-- ------------------------------
overriding
procedure Spawn (Sys : in out System_Process;
Proc : in out Process'Class;
Mode : in Pipe_Mode := NONE) is
use Interfaces.C;
Result : Integer;
Startup : aliased Startup_Info;
R : BOOL with Unreferenced;
begin
Sys.Prepare_Working_Directory (Proc);
-- Since checks are disabled, verify by hand that the argv table is correct.
if Sys.Command = null or else Sys.Command'Length < 1 then
raise Program_Error with "Invalid process argument list";
end if;
Startup.cb := Startup'Size / 8;
Startup.hStdInput := Get_Std_Handle (STD_INPUT_HANDLE);
Startup.hStdOutput := Get_Std_Handle (STD_OUTPUT_HANDLE);
Startup.hStdError := Get_Std_Handle (STD_ERROR_HANDLE);
if Sys.Out_File /= null then
Redirect_Output (Sys.Out_File, Sys.Out_Append, Startup.hStdOutput);
Startup.dwFlags := 16#100#;
end if;
if Sys.Err_File /= null then
Redirect_Output (Sys.Err_File, Sys.Err_Append, Startup.hStdError);
Startup.dwFlags := 16#100#;
end if;
if Sys.In_File /= null then
Redirect_Input (Sys.In_File, Startup.hStdInput);
Startup.dwFlags := 16#100#;
end if;
if Mode = WRITE or Mode = READ_WRITE or Mode = READ_WRITE_ALL then
Build_Input_Pipe (Sys, Proc, Startup);
end if;
if Mode = READ or Mode = READ_WRITE or Mode = READ_ALL or Mode = READ_WRITE_ALL then
Build_Output_Pipe (Sys, Proc, Startup, Mode);
end if;
-- Start the child process.
if Sys.Dir /= null then
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
1,
16#0#,
System.Null_Address,
Sys.Dir.all'Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
else
Result := Create_Process (System.Null_Address,
Sys.Command.all'Address,
null,
null,
1,
16#0#,
System.Null_Address,
System.Null_Address,
Startup'Unchecked_Access,
Sys.Process_Info'Unchecked_Access);
end if;
-- Close the handles which are not necessary.
if Startup.hStdInput /= Get_Std_Handle (STD_INPUT_HANDLE) then
R := Close_Handle (Startup.hStdInput);
end if;
if Startup.hStdOutput /= Get_Std_Handle (STD_OUTPUT_HANDLE) then
R := Close_Handle (Startup.hStdOutput);
end if;
if Startup.hStdError /= Get_Std_Handle (STD_ERROR_HANDLE) then
R := Close_Handle (Startup.hStdError);
end if;
if Result /= 1 then
Result := Get_Last_Error;
Log.Error ("Process creation failed: {0}", Integer'Image (Result));
raise Process_Error with "Cannot create process " & Integer'Image (Result);
end if;
Proc.Pid := Process_Identifier (Sys.Process_Info.dwProcessId);
end Spawn;
-- ------------------------------
-- Create the output stream to read/write on the process input/output.
-- Setup the file to be closed on exec.
-- ------------------------------
function Create_Stream (File : in Util.Streams.Raw.File_Type)
return Util.Streams.Raw.Raw_Stream_Access is
Stream : constant Util.Streams.Raw.Raw_Stream_Access := new Util.Streams.Raw.Raw_Stream;
begin
Stream.Initialize (File);
return Stream;
end Create_Stream;
-- ------------------------------
-- Build the output pipe redirection to read the process output.
-- ------------------------------
procedure Build_Output_Pipe (Sys : in out System_Process;
Proc : in out Process'Class;
Into : in out Startup_Info;
Mode : in Pipe_Mode) is
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Read_Pipe_Handle : aliased HANDLE;
Error_Handle : aliased HANDLE;
Result : BOOL;
R : BOOL with Unreferenced;
Current_Proc : constant HANDLE := Get_Current_Process;
Redirect_Error : constant Boolean := Mode = READ_ALL or Mode = READ_WRITE_ALL;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := 1;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Read_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Read_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
R := Close_Handle (Read_Handle);
if Redirect_Error and Sys.Out_File = null and Sys.Err_File = null then
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Error_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 1,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
elsif Sys.Out_File /= null then
Error_Handle := Write_Handle;
end if;
Into.dwFlags := 16#100#;
if Sys.Out_File = null then
Into.hStdOutput := Write_Handle;
end if;
if Redirect_Error and Sys.Err_File = null then
Into.hStdError := Error_Handle;
end if;
Proc.Output := Create_Stream (Read_Pipe_Handle).all'Access;
end Build_Output_Pipe;
-- ------------------------------
-- Build the input pipe redirection to write the process standard input.
-- ------------------------------
procedure Build_Input_Pipe (Sys : in out System_Process;
Proc : in out Process'Class;
Into : in out Startup_Info) is
pragma Unreferenced (Sys);
Sec : aliased Security_Attributes;
Read_Handle : aliased HANDLE;
Write_Handle : aliased HANDLE;
Write_Pipe_Handle : aliased HANDLE;
Result : BOOL;
R : BOOL with Unreferenced;
Current_Proc : constant HANDLE := Get_Current_Process;
begin
Sec.Length := Sec'Size / 8;
Sec.Inherit := 1;
Sec.Security_Descriptor := System.Null_Address;
Result := Create_Pipe (Read_Handle => Read_Handle'Unchecked_Access,
Write_Handle => Write_Handle'Unchecked_Access,
Attributes => Sec'Unchecked_Access,
Buf_Size => 0);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
Result := Duplicate_Handle (SourceProcessHandle => Current_Proc,
SourceHandle => Write_Handle,
TargetProcessHandle => Current_Proc,
TargetHandle => Write_Pipe_Handle'Unchecked_Access,
DesiredAccess => 0,
InheritHandle => 0,
Options => 2);
if Result = 0 then
Log.Error ("Cannot create pipe: {0}", Integer'Image (Get_Last_Error));
raise Program_Error with "Cannot create pipe";
end if;
R := Close_Handle (Write_Handle);
Into.dwFlags := 16#100#;
Into.hStdInput := Read_Handle;
Proc.Input := Create_Stream (Write_Pipe_Handle).all'Access;
end Build_Input_Pipe;
-- ------------------------------
-- Append the argument to the process argument list.
-- ------------------------------
overriding
procedure Append_Argument (Sys : in out System_Process;
Arg : in String) is
Len : Interfaces.C.size_t := Arg'Length;
begin
if Sys.Command /= null then
Len := Len + Sys.Command'Length + 2;
declare
S : constant Wchar_Ptr := new Interfaces.C.wchar_array (0 .. Len);
begin
S (Sys.Command'Range) := Sys.Command.all;
Free (Sys.Command);
Sys.Command := S;
end;
Sys.Command (Sys.Pos) := Interfaces.C.To_C (' ');
Sys.Pos := Sys.Pos + 1;
else
Sys.Command := new Interfaces.C.wchar_array (0 .. Len + 1);
Sys.Pos := 0;
end if;
for I in Arg'Range loop
Sys.Command (Sys.Pos)
:= Interfaces.C.To_C (Ada.Characters.Conversions.To_Wide_Character (Arg (I)));
Sys.Pos := Sys.Pos + 1;
end loop;
Sys.Command (Sys.Pos) := Interfaces.C.wide_nul;
end Append_Argument;
-- ------------------------------
-- Set the process input, output and error streams to redirect and use specified files.
-- ------------------------------
overriding
procedure Set_Streams (Sys : in out System_Process;
Input : in String;
Output : in String;
Error : in String;
Append_Output : in Boolean;
Append_Error : in Boolean;
To_Close : in File_Type_Array_Access) is
begin
if Input'Length > 0 then
Log.Info ("Redirect input {0}", Input);
Sys.In_File := To_WSTR (Input);
end if;
if Output'Length > 0 then
Log.Info ("Redirect output {0}", Output);
Sys.Out_File := To_WSTR (Output);
Sys.Out_Append := Append_Output;
end if;
if Error'Length > 0 then
Sys.Err_File := To_WSTR (Error);
Sys.Err_Append := Append_Error;
end if;
Sys.To_Close := To_Close;
end Set_Streams;
-- ------------------------------
-- Deletes the storage held by the system process.
-- ------------------------------
overriding
procedure Finalize (Sys : in out System_Process) is
Result : BOOL;
pragma Unreferenced (Result);
begin
if Sys.Process_Info.hProcess /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hProcess);
Sys.Process_Info.hProcess := NO_FILE;
end if;
if Sys.Process_Info.hThread /= NO_FILE then
Result := Close_Handle (Sys.Process_Info.hThread);
Sys.Process_Info.hThread := NO_FILE;
end if;
Free (Sys.In_File);
Free (Sys.Out_File);
Free (Sys.Err_File);
Free (Sys.Dir);
Free (Sys.Command);
end Finalize;
end Util.Processes.Os;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . M E M O R Y _ C O P Y --
-- --
-- S p e c --
-- --
-- Copyright (C) 2001-2014, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package provides general block copy mechanisms analogous to those
-- provided by the C routines memcpy and memmove allowing for copies with
-- and without possible overlap of the operands.
-- The idea is to allow a configurable run-time to provide this capability
-- for use by the compiler without dragging in C-run time routines.
with System.CRTL;
-- The above with is contrary to the intent ???
package System.Memory_Copy is
pragma Preelaborate;
procedure memcpy (S1 : Address; S2 : Address; N : System.CRTL.size_t)
renames System.CRTL.memcpy;
-- Copies N storage units from area starting at S2 to area starting
-- at S1 without any check for buffer overflow. The memory areas
-- must not overlap, or the result of this call is undefined.
procedure memmove (S1 : Address; S2 : Address; N : System.CRTL.size_t)
renames System.CRTL.memmove;
-- Copies N storage units from area starting at S2 to area starting
-- at S1 without any check for buffer overflow. The difference between
-- this memmove and memcpy is that with memmove, the storage areas may
-- overlap (forwards or backwards) and the result is correct (i.e. it
-- is as if S2 is first moved to a temporary area, and then this area
-- is copied to S1 in a separate step).
-- In the standard library, these are just interfaced to the C routines.
-- But in the HI-E (high integrity version) they may be reprogrammed to
-- meet certification requirements (and marked High_Integrity).
-- Note that in high integrity mode these routines are by default not
-- available, and the HI-E compiler will as a result generate implicit
-- loops (which will violate the restriction No_Implicit_Loops).
end System.Memory_Copy;
|
with Ada.Streams;
with Ada.Finalization;
with Interfaces;
with kv.avm.Actor_References;
with kv.avm.Actor_References.Sets;
with kv.avm.Registers;
with kv.avm.Tuples;
package kv.avm.Messages is
use Interfaces;
use kv.avm.Registers;
use kv.avm.Tuples;
type Message_Type is tagged private;
procedure Initialize
(Self : in out Message_Type);
procedure Adjust
(Self : in out Message_Type);
procedure Finalize
(Self : in out Message_Type);
procedure Initialize
(Self : in out Message_Type;
Source : in kv.avm.Actor_References.Actor_Reference_Type;
Reply_To : in kv.avm.Actor_References.Actor_Reference_Type;
Destination : in kv.avm.Actor_References.Actor_Reference_Type;
Message_Name : in String;
Data : in kv.avm.Tuples.Tuple_Type;
Future : in Interfaces.Unsigned_32);
function Get_Name(Self : Message_Type) return String;
function Get_Source(Self : Message_Type) return kv.avm.Actor_References.Actor_Reference_Type;
function Get_Reply_To(Self : Message_Type) return kv.avm.Actor_References.Actor_Reference_Type;
function Get_Destination(Self : Message_Type) return kv.avm.Actor_References.Actor_Reference_Type;
function Get_Data(Self : Message_Type) return kv.avm.Tuples.Tuple_Type;
function Get_Future(Self : Message_Type) return Interfaces.Unsigned_32;
function Image(Self : Message_Type) return String;
function Debug(Self : Message_Type) return String;
function Reachable(Self : Message_Type) return kv.avm.Actor_References.Sets.Set;
function "="(L, R: Message_Type) return Boolean;
procedure Message_Write(Stream : not null access Ada.Streams.Root_Stream_Type'CLASS; Item : in Message_Type);
for Message_Type'WRITE use Message_Write;
procedure Message_Read(Stream : not null access Ada.Streams.Root_Stream_Type'CLASS; Item : out Message_Type);
for Message_Type'READ use Message_Read;
private
type Reference_Counted_Message_Type;
type Reference_Counted_Message_Access is access all Reference_Counted_Message_Type;
type Message_Type is new Ada.Finalization.Controlled with
record
Ref : Reference_Counted_Message_Access;
end record;
end kv.avm.Messages;
|
-- Copyright (c) 2020 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Streams;
with Ada.Containers.Hashed_Maps;
with Fuse.Main;
with League.Stream_Element_Vectors;
with League.Strings.Hash;
package Photo_Files is
type Element_Array is
array (Positive range <>) of Ada.Streams.Stream_Element;
type File is record
Id : League.Strings.Universal_String;
Base_URL : League.Strings.Universal_String;
end record;
package File_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => League.Strings.Universal_String, -- Name
Element_Type => File,
Hash => League.Strings.Hash,
Equivalent_Keys => League.Strings."=");
type Album is record
Id : League.Strings.Universal_String;
Files : File_Maps.Map;
end record;
package Album_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => League.Strings.Universal_String, -- Name
Element_Type => Album,
Hash => League.Strings.Hash,
Equivalent_Keys => League.Strings."=");
type Context is record
Access_Token : League.Strings.Universal_String;
Albums : Album_Maps.Map;
Cached_File : League.Strings.Universal_String;
Cached_Data : League.Stream_Element_Vectors.Stream_Element_Vector;
end record;
type Context_Access is access all Context;
pragma Warnings (Off);
package Photos is new Fuse.Main
(Element_Type => Ada.Streams.Stream_Element,
Element_Array => Element_Array,
User_Data_Type => Context_Access);
pragma Warnings (On);
function GetAttr
(Path : in String;
St_Buf : access Photos.System.Stat_Type)
return Photos.System.Error_Type;
function Open
(Path : in String;
Fi : access Photos.System.File_Info_Type)
return Photos.System.Error_Type;
function Read
(Path : in String;
Buffer : access Photos.Buffer_Type;
Size : in out Natural;
Offset : in Natural;
Fi : access Photos.System.File_Info_Type)
return Photos.System.Error_Type;
function ReadDir
(Path : in String;
Filler : access procedure
(Name : String;
St_Buf : Photos.System.Stat_Access;
Offset : Natural);
Offset : in Natural;
Fi : access Photos.System.File_Info_Type)
return Photos.System.Error_Type;
package Hello_GetAttr is new Photos.GetAttr;
package Hello_Open is new Photos.Open;
package Hello_Read is new Photos.Read;
package Hello_ReadDir is new Photos.ReadDir;
end Photo_Files;
|
with Ada.Integer_Text_IO;
with Ada.Unchecked_Deallocation;
procedure Euler14 is
Max_Start: constant Positive := 999_999;
subtype Start_Type is Positive range 1 .. Max_Start;
type Memo is array (Start_Type) of Natural;
type Memo_Ptr is access Memo;
procedure Free is new Ada.Unchecked_Deallocation(Memo, Memo_Ptr);
Collatz: Memo_Ptr := new Memo'(1 => 1, others => 0);
type Intermediate is range 1 .. 2 ** 60;
function Chain_Length(Start: Intermediate) return Positive is
Next: constant Intermediate
:= (if Start mod 2 = 0 then Start / 2 else 3 * Start + 1);
begin
if Start <= Intermediate(Start_Type'Last) then
declare
S: constant Start_Type := Start_Type(Start);
begin
if Collatz(S) = 0 then
Collatz(S) := 1 + Chain_Length(Next);
end if;
return Collatz(S);
end;
else
return 1 + Chain_Length(Next);
end if;
end Chain_Length;
Max, Curr: Natural := 0;
Best: Start_Type;
begin
for I in Start_Type'Range loop
Curr := Chain_Length(Intermediate(I));
if Curr > Max then
Max := Curr;
Best := I;
end if;
end loop;
Ada.Integer_Text_IO.Put(Best);
Free(Collatz);
end Euler14;
|
with Ada.Containers.Generic_Constrained_Array_Sort;
package body Genetic is
-- Determine the sum of each gene's fitness within the gene pool.
function Total_Fitness (P : in Pool) return Float is
-- We will add up each gene's individual fitness.
Result : Float := 0.0;
begin
-- For each gene in the pool
for I in P'Range loop
-- Add that gene's fitness.
Result := Result + Fitness_Of (P (I).G);
end loop;
-- Return the sum.
return Result;
end Total_Fitness;
-- Create a pool full of random genes. It will not be sorted yet.
procedure Randomize (P : out Pool) is
begin
-- For each gene in the pool
for I in P'Range loop
-- Create a random gene.
P (I).G := Random_Gene;
-- Since we have yet to evaluate the fitness of this gene, mark that
-- it is not cached.
P (I).Cached := False;
end loop;
end Randomize;
-- Get the most fit gene from the pool. The pool must be sorted before
-- calling this.
function Best_Gene (P : in Pool) return Gene is
-- Simply return the first element in the pool. Since the pool is
-- required to be sorted before calling this function, the first element
-- will be the most fit gene.
(P (P'First).G);
-- Compare the fitness of two genes. This function is used for sorting the
-- gene pool.
function Gene_Compare (Left, Right : in Fit_Gene) return Boolean is
-- Simply compare the two genes' fitness.
(Left.Fitness > Right.Fitness);
-- Sort a gene pool by the fitness of each gene. We use Ada's built-in
-- sorting procedure.
procedure Pool_Sort is new Ada.Containers.Generic_Constrained_Array_Sort (
Index_Type => Pool_Index,
Element_Type => Fit_Gene,
Array_Type => Pool,
"<" => Gene_Compare);
-- Advance the evolution of the genes. This first sorts the genes from most
-- to least fit, then replaces the least fit genes with mutations of fit
-- genes or random new genes.
procedure Evolve (P : in out Pool) is
-- The last part of the pool, called the foreign space, gets replaced
-- with new random genes. This is the first index of that part.
Foreign_Space : Natural := P'Last - (P'Length / 10);
-- The second half of the pool (not including the foreign space) gets
-- replaced with mutations of the most fit genes. This is the first index
-- of that part.
Halfway : Natural := (P'First + Foreign_Space) / 2;
-- The last index of the part of the pool being replaced by mutated
-- genes. We will use this index when copying and mutating the most fit
-- genes.
Other_End : Natural := Foreign_Space - 1;
begin
-- First, we must get the fitness of each gene in the pool and sort.
-- For each gene in the pool
for I in P'Range loop
-- Unless we already know the gene's fitness
if not P (I).Cached then
-- Calculate the gene's fitness.
P (I).Fitness := Fitness_Of (P (I).G);
-- Mark that we know this gene's fitness now.
P (I).Cached := True;
end if;
end loop;
-- Sort the gene pool so the most fit genes are at the front.
Pool_Sort (P);
-- Next, we will mutate the most fit genes.
-- For each of the most fit genes
for I in P'First .. Halfway loop
-- Copy the gene over into the second half. `Other_End` is the index
-- into which we copy the gene.
P (Other_End) := P (I);
-- Mutate the gene.
Mutate (P (Other_End).G);
-- Because we have changed the gene, its fitness will change too. Mark
-- that we no longer know its fitness.
P (Other_End).Cached := False;
-- Move the other end index to the next position.
Other_End := Other_End - 1;
end loop;
-- Finally, we will introduce some new random genes at the end of the
-- pool.
-- For each gene in the foreign space
for I in Foreign_Space .. P'Last loop
-- Replace the gene with a random new one.
P (I).G := Random_Gene;
-- Since this is a completely new gene, we don't know its fitness yet.
P (I).Cached := False;
end loop;
end Evolve;
end Genetic;
|
--
-- CDDL HEADER START
--
-- The contents of this file are subject to the terms of the
-- Common Development and Distribution License (the "License").
-- You may not use this file except in compliance with the License.
--
-- See LICENSE.txt included in this distribution for the specific
-- language governing permissions and limitations under the License.
--
-- When distributing Covered Code, include this CDDL HEADER in each
-- file and include the License file at LICENSE.txt.
-- If applicable, add the following below this CDDL HEADER, with the
-- fields enclosed by brackets "[]" replaced with your own identifying
-- information: Portions Copyright [yyyy] [name of copyright owner]
--
-- CDDL HEADER END
--
--
-- Copyright (c) 2017, Chris Fraire <cfraire@me.com>.
--
with Ada.Text_IO; use Ada.Text_IO;
procedure Hello is
begin
Put_Line("Hello, world!");
Put_Line("""
Hello?""");
Put_Line('?');
Put_Line('
');
Put(0);
Put(12);
Put(123_456);
Put(3.14159_26);
Put(2#1111_1111#);
Put(16#E#E1);
Put(16#F.FF#E+2);
Put_Line();
Put_Line("Archimedes said ""Εύρηκα""");
end Hello;
-- Test a URL that is not matched fully by a rule using just {URIChar} and
-- {FnameChar}:
-- https://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx
|
--PRÁCTICA 3: CÉSAR BORAO MORATINOS (Maps_G_Array.adb)
with Ada.Text_IO;
with Ada.Strings.Unbounded;
package body Maps_G is
package ASU renames Ada.Strings.Unbounded;
procedure Put (M: in out Map;
Key: Key_Type;
Value: Value_Type) is
Position: Natural := 1;
Found: Boolean;
begin
Found := False;
if M.P_Array = null then
M.P_Array := new Cell_Array;
M.P_Array(1) := (Key,Value,True);
M.Length := 1;
Found := True;
else
while not Found and Position <= M.Length loop
if M.P_Array(Position).Key = Key then
M.P_Array(Position).Value := Value;
Found := True;
end if;
Position := Position+1;
end loop;
if not Found then
if M.Length >= Max_Clients then
raise Full_Map;
end if;
M.P_Array(Position) := (Key,Value,True);
M.Length := M.Length + 1;
end if;
end if;
end Put;
procedure Get (M: Map;
Key: in Key_Type;
Value: out Value_Type;
Success: out Boolean) is
Position: Natural := 1;
begin
if M.P_Array = null then
Success := False;
else
Success := False;
while not Success and Position <= M.Length loop
if M.P_Array(Position).Key = Key then
Value := M.P_Array(Position).Value;
Success := True;
end if;
Position := Position + 1;
end loop;
end if;
end Get;
procedure Delete (M: in out Map;
Key: in Key_Type;
Success: out Boolean) is
Position: Natural := 1;
begin
Success := False;
while not Success and Position <= M.Length loop
if M.P_Array(Position).Key = Key then
Success := True;
for I in Position..M.Length-1 loop
M.P_Array(I) := M.P_Array(I+1);
end loop;
end if;
Position := Position + 1;
end loop;
M.Length := M.Length - 1;
end Delete;
function Map_Length (M: Map) return Natural is
begin
return M.Length;
end Map_Length;
function First (M: Map) return Cursor is
C: Cursor;
begin
C.M := M;
C.Position := 1;
return C;
end First;
procedure Next (C: in out Cursor) is
begin
C.Position := C.Position + 1;
end;
function Has_Element (C: Cursor) return Boolean is
begin
if C.Position > C.M.Length then
return False;
else
return C.M.P_Array(C.Position).Full;
end if;
end Has_Element;
function Element (C: Cursor) return Element_Type is
Element: Element_Type;
begin
if Has_Element (C) then
Element.Key := C.M.P_Array(C.Position).Key;
Element.Value := C.M.P_Array(C.Position).Value;
else
raise No_Element;
end if;
return Element;
end Element;
end Maps_G;
|
with System.Long_Long_Integer_Types;
with System.Unwind.Raising;
pragma Warnings (Off, System.Unwind.Raising); -- break "pure" rule
package body System.Exponentiations is
pragma Suppress (All_Checks);
use type Long_Long_Integer_Types.Long_Long_Unsigned;
subtype Long_Long_Unsigned is Long_Long_Integer_Types.Long_Long_Unsigned;
procedure unreachable
with Import,
Convention => Intrinsic, External_Name => "__builtin_unreachable";
pragma No_Return (unreachable);
-- implementation
function Generic_Exp_Integer (Left : Integer_Type; Right : Natural)
return Integer_Type is
begin
if Left = 2 then
if Right >= Integer_Type'Size then
Unwind.Raising.Overflow;
else
declare
function Shift_Left (Value : Integer_Type; Amount : Natural)
return Integer_Type
with Import, Convention => Intrinsic;
begin
return Shift_Left (1, Right);
end;
end if;
elsif Left = 0 then
if Right > 0 then
return 0;
else -- Right = 0
return 1;
end if;
else
declare
function mul_overflow (
a, b : Integer;
res : not null access Integer)
return Boolean
with Import,
Convention => Intrinsic,
External_Name => "__builtin_smul_overflow";
function mul_overflow (
a, b : Long_Long_Integer;
res : not null access Long_Long_Integer)
return Boolean
with Import,
Convention => Intrinsic,
External_Name => "__builtin_smulll_overflow";
Result : Integer_Type := 1;
Factor : Integer_Type := Left;
Exponent : Natural := Right;
begin
if Factor < 0 then
Factor := -Factor;
if Exponent rem 2 /= 0 then
Result := -1;
end if;
end if;
loop
if Exponent rem 2 /= 0 then
declare
Overflow : Boolean;
begin
if Integer_Type'Size > Integer'Size then
declare
R : aliased Long_Long_Integer;
begin
Overflow := mul_overflow (
Long_Long_Integer (Result),
Long_Long_Integer (Factor),
R'Access);
Result := Integer_Type (R);
end;
else
declare
R : aliased Integer;
begin
Overflow := mul_overflow (
Integer (Result),
Integer (Factor),
R'Access);
Result := Integer_Type (R);
end;
end if;
if Overflow then
Unwind.Raising.Overflow;
end if;
end;
end if;
Exponent := Exponent / 2;
exit when Exponent = 0;
if Exponent rem 2 /= 0 then
declare
Overflow : Boolean;
begin
if Integer_Type'Size > Integer'Size then
declare
Factor_Squared : aliased Long_Long_Integer;
begin
Overflow := mul_overflow (
Long_Long_Integer (Factor),
Long_Long_Integer (Factor),
Factor_Squared'Access);
Factor := Integer_Type (Factor_Squared);
end;
else
declare
Factor_Squared : aliased Integer;
begin
Overflow := mul_overflow (
Integer (Factor),
Integer (Factor),
Factor_Squared'Access);
Factor := Integer_Type (Factor_Squared);
end;
end if;
if Overflow then
Unwind.Raising.Overflow;
end if;
end;
end if;
end loop;
return Result;
end;
end if;
end Generic_Exp_Integer;
function Generic_Exp_Integer_No_Check (Left : Integer_Type; Right : Natural)
return Integer_Type is
begin
if Left = 2 then
if Right >= Integer_Type'Size then
return 0;
else
declare
function Shift_Left (Value : Integer_Type; Amount : Natural)
return Integer_Type
with Import, Convention => Intrinsic;
begin
return Shift_Left (1, Right);
end;
end if;
else
declare
Result : Integer_Type := 1;
Factor : Integer_Type := Left;
Exponent : Natural := Right;
begin
loop
if Exponent rem 2 /= 0 then
Result := Result * Factor;
end if;
Exponent := Exponent / 2;
exit when Exponent = 0;
Factor := Factor * Factor;
end loop;
return Result;
end;
end if;
end Generic_Exp_Integer_No_Check;
function Generic_Exp_Unsigned (Left : Unsigned_Type; Right : Natural)
return Unsigned_Type is
begin
if Left = 2 then
if Right >= Unsigned_Type'Size then
return 0;
else
return Shift_Left (1, Right);
end if;
else
declare
Result : Unsigned_Type := 1;
Factor : Unsigned_Type := Left;
Exponent : Natural := Right;
begin
loop
if Exponent rem 2 /= 0 then
Result := Result * Factor;
end if;
Exponent := Exponent / 2;
exit when Exponent = 0;
Factor := Factor * Factor;
end loop;
return Result;
end;
end if;
end Generic_Exp_Unsigned;
function Generic_Exp_Modular (
Left : Unsigned_Type;
Modulus : Unsigned_Type;
Right : Natural)
return Unsigned_Type is
begin
if Modulus <= 0 then
unreachable; -- T'Modulus > 0
end if;
if Left = 2 and then Right < Unsigned_Type'Size then
return Shift_Left (1, Right) mod Modulus;
else
declare
Result : Unsigned_Type := 1;
Factor : Unsigned_Type := Left;
Exponent : Natural := Right;
begin
loop
if Exponent rem 2 /= 0 then
Result := Unsigned_Type'Mod (
Long_Long_Unsigned'Mod (Result)
* Long_Long_Unsigned'Mod (Factor)
mod Long_Long_Unsigned'Mod (Modulus));
end if;
Exponent := Exponent / 2;
exit when Exponent = 0;
Factor := Unsigned_Type'Mod (
Long_Long_Unsigned'Mod (Factor)
* Long_Long_Unsigned'Mod (Factor)
mod Long_Long_Unsigned'Mod (Modulus));
end loop;
return Result;
end;
end if;
end Generic_Exp_Modular;
end System.Exponentiations;
|
with STM32_SVD; use STM32_SVD;
generic
Filename : String;
package STM32GD.USART.Peripheral is
pragma Preelaborate;
procedure Transmit (Data : in Byte);
end STM32GD.USART.Peripheral;
|
package Entry_Declaration is
task type Task_With_Entry is
entry First_Entry;
end Task_With_Entry;
end Entry_Declaration;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.