content stringlengths 23 1.05M |
|---|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . T A S K I N G . E N T R Y _ C A L L S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2019, 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. --
-- --
------------------------------------------------------------------------------
with System.Task_Primitives.Operations;
with System.Tasking.Initialization;
with System.Tasking.Protected_Objects.Entries;
with System.Tasking.Protected_Objects.Operations;
with System.Tasking.Queuing;
with System.Tasking.Utilities;
with System.Parameters;
package body System.Tasking.Entry_Calls is
package STPO renames System.Task_Primitives.Operations;
use Parameters;
use Protected_Objects.Entries;
use Protected_Objects.Operations;
-- DO NOT use Protected_Objects.Lock or Protected_Objects.Unlock
-- internally. Those operations will raise Program_Error, which
-- we are not prepared to handle inside the RTS. Instead, use
-- System.Task_Primitives lock operations directly on Protection.L.
-----------------------
-- Local Subprograms --
-----------------------
procedure Lock_Server (Entry_Call : Entry_Call_Link);
-- This locks the server targeted by Entry_Call
--
-- This may be a task or a protected object, depending on the target of the
-- original call or any subsequent requeues.
--
-- This routine is needed because the field specifying the server for this
-- call must be protected by the server's mutex. If it were protected by
-- the caller's mutex, accessing the server's queues would require locking
-- the caller to get the server, locking the server, and then accessing the
-- queues. This involves holding two ATCB locks at once, something which we
-- can guarantee that it will always be done in the same order, or locking
-- a protected object while we hold an ATCB lock, something which is not
-- permitted. Since the server cannot be obtained reliably, it must be
-- obtained unreliably and then checked again once it has been locked.
--
-- If Single_Lock and server is a PO, release RTS_Lock
--
-- This should only be called by the Entry_Call.Self.
-- It should be holding no other ATCB locks at the time.
procedure Unlock_Server (Entry_Call : Entry_Call_Link);
-- STPO.Unlock the server targeted by Entry_Call. The server must
-- be locked before calling this.
--
-- If Single_Lock and server is a PO, take RTS_Lock on exit.
procedure Unlock_And_Update_Server
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link);
-- Similar to Unlock_Server, but services entry calls if the
-- server is a protected object.
--
-- If Single_Lock and server is a PO, take RTS_Lock on exit.
procedure Check_Pending_Actions_For_Entry_Call
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link);
-- This procedure performs priority change of a queued call and dequeuing
-- of an entry call when the call is cancelled. If the call is dequeued the
-- state should be set to Cancelled. Call only with abort deferred and
-- holding lock of Self_ID. This is a bit of common code for all entry
-- calls. The effect is to do any deferred base priority change operation,
-- in case some other task called STPO.Set_Priority while the current task
-- had abort deferred, and to dequeue the call if the call has been
-- aborted.
procedure Poll_Base_Priority_Change_At_Entry_Call
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link);
pragma Inline (Poll_Base_Priority_Change_At_Entry_Call);
-- A specialized version of Poll_Base_Priority_Change, that does the
-- optional entry queue reordering. Has to be called with the Self_ID's
-- ATCB write-locked. May temporarily release the lock.
---------------------
-- Check_Exception --
---------------------
procedure Check_Exception
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link)
is
pragma Warnings (Off, Self_ID);
use type Ada.Exceptions.Exception_Id;
procedure Internal_Raise (X : Ada.Exceptions.Exception_Id);
pragma Import (C, Internal_Raise, "__gnat_raise_with_msg");
E : constant Ada.Exceptions.Exception_Id :=
Entry_Call.Exception_To_Raise;
begin
-- pragma Assert (Self_ID.Deferral_Level = 0);
-- The above may be useful for debugging, but the Florist packages
-- contain critical sections that defer abort and then do entry calls,
-- which causes the above Assert to trip.
if E /= Ada.Exceptions.Null_Id then
Internal_Raise (E);
end if;
end Check_Exception;
------------------------------------------
-- Check_Pending_Actions_For_Entry_Call --
------------------------------------------
procedure Check_Pending_Actions_For_Entry_Call
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link)
is
begin
pragma Assert (Self_ID = Entry_Call.Self);
Poll_Base_Priority_Change_At_Entry_Call (Self_ID, Entry_Call);
if Self_ID.Pending_ATC_Level < Self_ID.ATC_Nesting_Level
and then Entry_Call.State = Now_Abortable
then
STPO.Unlock (Self_ID);
Lock_Server (Entry_Call);
if Queuing.Onqueue (Entry_Call)
and then Entry_Call.State = Now_Abortable
then
Queuing.Dequeue_Call (Entry_Call);
Entry_Call.State :=
(if Entry_Call.Cancellation_Attempted then Cancelled else Done);
Unlock_And_Update_Server (Self_ID, Entry_Call);
else
Unlock_Server (Entry_Call);
end if;
STPO.Write_Lock (Self_ID);
end if;
end Check_Pending_Actions_For_Entry_Call;
-----------------
-- Lock_Server --
-----------------
procedure Lock_Server (Entry_Call : Entry_Call_Link) is
Test_Task : Task_Id;
Test_PO : Protection_Entries_Access;
Ceiling_Violation : Boolean;
Failures : Integer := 0;
begin
Test_Task := Entry_Call.Called_Task;
loop
if Test_Task = null then
-- Entry_Call was queued on a protected object, or in transition,
-- when we last fetched Test_Task.
Test_PO := To_Protection (Entry_Call.Called_PO);
if Test_PO = null then
-- We had very bad luck, interleaving with TWO different
-- requeue operations. Go around the loop and try again.
if Single_Lock then
STPO.Unlock_RTS;
STPO.Yield;
STPO.Lock_RTS;
else
STPO.Yield;
end if;
else
if Single_Lock then
STPO.Unlock_RTS;
end if;
Lock_Entries_With_Status (Test_PO, Ceiling_Violation);
-- ???
-- The following code allows Lock_Server to be called when
-- cancelling a call, to allow for the possibility that the
-- priority of the caller has been raised beyond that of the
-- protected entry call by Ada.Dynamic_Priorities.Set_Priority.
-- If the current task has a higher priority than the ceiling
-- of the protected object, temporarily lower it. It will
-- be reset in Unlock.
if Ceiling_Violation then
declare
Current_Task : constant Task_Id := STPO.Self;
Old_Base_Priority : System.Any_Priority;
begin
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Current_Task);
Old_Base_Priority := Current_Task.Common.Base_Priority;
Current_Task.New_Base_Priority := Test_PO.Ceiling;
System.Tasking.Initialization.Change_Base_Priority
(Current_Task);
STPO.Unlock (Current_Task);
if Single_Lock then
STPO.Unlock_RTS;
end if;
-- Following lock should not fail
Lock_Entries (Test_PO);
Test_PO.Old_Base_Priority := Old_Base_Priority;
Test_PO.Pending_Action := True;
end;
end if;
exit when To_Address (Test_PO) = Entry_Call.Called_PO;
Unlock_Entries (Test_PO);
if Single_Lock then
STPO.Lock_RTS;
end if;
end if;
else
STPO.Write_Lock (Test_Task);
exit when Test_Task = Entry_Call.Called_Task;
STPO.Unlock (Test_Task);
end if;
Test_Task := Entry_Call.Called_Task;
Failures := Failures + 1;
pragma Assert (Failures <= 5);
end loop;
end Lock_Server;
---------------------------------------------
-- Poll_Base_Priority_Change_At_Entry_Call --
---------------------------------------------
procedure Poll_Base_Priority_Change_At_Entry_Call
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link)
is
begin
if Self_ID.Pending_Priority_Change then
-- Check for ceiling violations ???
Self_ID.Pending_Priority_Change := False;
-- Requeue the entry call at the new priority. We need to requeue
-- even if the new priority is the same than the previous (see ACATS
-- test cxd4006).
STPO.Unlock (Self_ID);
Lock_Server (Entry_Call);
Queuing.Requeue_Call_With_New_Prio
(Entry_Call, STPO.Get_Priority (Self_ID));
Unlock_And_Update_Server (Self_ID, Entry_Call);
STPO.Write_Lock (Self_ID);
end if;
end Poll_Base_Priority_Change_At_Entry_Call;
--------------------
-- Reset_Priority --
--------------------
procedure Reset_Priority
(Acceptor : Task_Id;
Acceptor_Prev_Priority : Rendezvous_Priority)
is
begin
pragma Assert (Acceptor = STPO.Self);
-- Since we limit this kind of "active" priority change to be done
-- by the task for itself, we don't need to lock Acceptor.
if Acceptor_Prev_Priority /= Priority_Not_Boosted then
STPO.Set_Priority (Acceptor, Acceptor_Prev_Priority,
Loss_Of_Inheritance => True);
end if;
end Reset_Priority;
------------------------------
-- Try_To_Cancel_Entry_Call --
------------------------------
procedure Try_To_Cancel_Entry_Call (Succeeded : out Boolean) is
Entry_Call : Entry_Call_Link;
Self_ID : constant Task_Id := STPO.Self;
use type Ada.Exceptions.Exception_Id;
begin
Entry_Call := Self_ID.Entry_Calls (Self_ID.ATC_Nesting_Level)'Access;
-- Experimentation has shown that abort is sometimes (but not
-- always) already deferred when Cancel_xxx_Entry_Call is called.
-- That may indicate an error. Find out what is going on. ???
pragma Assert (Entry_Call.Mode = Asynchronous_Call);
Initialization.Defer_Abort_Nestable (Self_ID);
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Self_ID);
Entry_Call.Cancellation_Attempted := True;
if Self_ID.Pending_ATC_Level >= Entry_Call.Level then
Self_ID.Pending_ATC_Level := Entry_Call.Level - 1;
end if;
Entry_Calls.Wait_For_Completion (Entry_Call);
STPO.Unlock (Self_ID);
if Single_Lock then
STPO.Unlock_RTS;
end if;
Succeeded := Entry_Call.State = Cancelled;
Initialization.Undefer_Abort_Nestable (Self_ID);
-- Ideally, abort should no longer be deferred at this point, so we
-- should be able to call Check_Exception. The loop below should be
-- considered temporary, to work around the possibility that abort
-- may be deferred more than one level deep ???
if Entry_Call.Exception_To_Raise /= Ada.Exceptions.Null_Id then
while Self_ID.Deferral_Level > 0 loop
System.Tasking.Initialization.Undefer_Abort_Nestable (Self_ID);
end loop;
Entry_Calls.Check_Exception (Self_ID, Entry_Call);
end if;
end Try_To_Cancel_Entry_Call;
------------------------------
-- Unlock_And_Update_Server --
------------------------------
procedure Unlock_And_Update_Server
(Self_ID : Task_Id;
Entry_Call : Entry_Call_Link)
is
Called_PO : Protection_Entries_Access;
Caller : Task_Id;
begin
if Entry_Call.Called_Task /= null then
STPO.Unlock (Entry_Call.Called_Task);
else
Called_PO := To_Protection (Entry_Call.Called_PO);
PO_Service_Entries (Self_ID, Called_PO, False);
if Called_PO.Pending_Action then
Called_PO.Pending_Action := False;
Caller := STPO.Self;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Caller);
Caller.New_Base_Priority := Called_PO.Old_Base_Priority;
Initialization.Change_Base_Priority (Caller);
STPO.Unlock (Caller);
if Single_Lock then
STPO.Unlock_RTS;
end if;
end if;
Unlock_Entries (Called_PO);
if Single_Lock then
STPO.Lock_RTS;
end if;
end if;
end Unlock_And_Update_Server;
-------------------
-- Unlock_Server --
-------------------
procedure Unlock_Server (Entry_Call : Entry_Call_Link) is
Caller : Task_Id;
Called_PO : Protection_Entries_Access;
begin
if Entry_Call.Called_Task /= null then
STPO.Unlock (Entry_Call.Called_Task);
else
Called_PO := To_Protection (Entry_Call.Called_PO);
if Called_PO.Pending_Action then
Called_PO.Pending_Action := False;
Caller := STPO.Self;
if Single_Lock then
STPO.Lock_RTS;
end if;
STPO.Write_Lock (Caller);
Caller.New_Base_Priority := Called_PO.Old_Base_Priority;
Initialization.Change_Base_Priority (Caller);
STPO.Unlock (Caller);
if Single_Lock then
STPO.Unlock_RTS;
end if;
end if;
Unlock_Entries (Called_PO);
if Single_Lock then
STPO.Lock_RTS;
end if;
end if;
end Unlock_Server;
-------------------------
-- Wait_For_Completion --
-------------------------
procedure Wait_For_Completion (Entry_Call : Entry_Call_Link) is
Self_Id : constant Task_Id := Entry_Call.Self;
begin
-- If this is a conditional call, it should be cancelled when it
-- becomes abortable. This is checked in the loop below.
Self_Id.Common.State := Entry_Caller_Sleep;
-- Try to remove calls to Sleep in the loop below by letting the caller
-- a chance of getting ready immediately, using Unlock & Yield.
-- See similar action in Wait_For_Call & Timed_Selective_Wait.
if Single_Lock then
STPO.Unlock_RTS;
else
STPO.Unlock (Self_Id);
end if;
if Entry_Call.State < Done then
STPO.Yield;
end if;
if Single_Lock then
STPO.Lock_RTS;
else
STPO.Write_Lock (Self_Id);
end if;
loop
Check_Pending_Actions_For_Entry_Call (Self_Id, Entry_Call);
exit when Entry_Call.State >= Done;
STPO.Sleep (Self_Id, Entry_Caller_Sleep);
end loop;
Self_Id.Common.State := Runnable;
Utilities.Exit_One_ATC_Level (Self_Id);
end Wait_For_Completion;
--------------------------------------
-- Wait_For_Completion_With_Timeout --
--------------------------------------
procedure Wait_For_Completion_With_Timeout
(Entry_Call : Entry_Call_Link;
Wakeup_Time : Duration;
Mode : Delay_Modes;
Yielded : out Boolean)
is
Self_Id : constant Task_Id := Entry_Call.Self;
Timedout : Boolean := False;
begin
-- This procedure waits for the entry call to be served, with a timeout.
-- It tries to cancel the call if the timeout expires before the call is
-- served.
-- If we wake up from the timed sleep operation here, it may be for
-- several possible reasons:
-- 1) The entry call is done being served.
-- 2) There is an abort or priority change to be served.
-- 3) The timeout has expired (Timedout = True)
-- 4) There has been a spurious wakeup.
-- Once the timeout has expired we may need to continue to wait if the
-- call is already being serviced. In that case, we want to go back to
-- sleep, but without any timeout. The variable Timedout is used to
-- control this. If the Timedout flag is set, we do not need to
-- STPO.Sleep with a timeout. We just sleep until we get a wakeup for
-- some status change.
-- The original call may have become abortable after waking up. We want
-- to check Check_Pending_Actions_For_Entry_Call again in any case.
pragma Assert (Entry_Call.Mode = Timed_Call);
Yielded := False;
Self_Id.Common.State := Entry_Caller_Sleep;
-- Looping is necessary in case the task wakes up early from the timed
-- sleep, due to a "spurious wakeup". Spurious wakeups are a weakness of
-- POSIX condition variables. A thread waiting for a condition variable
-- is allowed to wake up at any time, not just when the condition is
-- signaled. See same loop in the ordinary Wait_For_Completion, above.
loop
Check_Pending_Actions_For_Entry_Call (Self_Id, Entry_Call);
exit when Entry_Call.State >= Done;
STPO.Timed_Sleep (Self_Id, Wakeup_Time, Mode,
Entry_Caller_Sleep, Timedout, Yielded);
if Timedout then
-- Try to cancel the call (see Try_To_Cancel_Entry_Call for
-- corresponding code in the ATC case).
Entry_Call.Cancellation_Attempted := True;
-- Reset Entry_Call.State so that the call is marked as cancelled
-- by Check_Pending_Actions_For_Entry_Call below.
if Entry_Call.State < Was_Abortable then
Entry_Call.State := Now_Abortable;
end if;
if Self_Id.Pending_ATC_Level >= Entry_Call.Level then
Self_Id.Pending_ATC_Level := Entry_Call.Level - 1;
end if;
-- The following loop is the same as the loop and exit code
-- from the ordinary Wait_For_Completion. If we get here, we
-- have timed out but we need to keep waiting until the call
-- has actually completed or been cancelled successfully.
loop
Check_Pending_Actions_For_Entry_Call (Self_Id, Entry_Call);
exit when Entry_Call.State >= Done;
STPO.Sleep (Self_Id, Entry_Caller_Sleep);
end loop;
Self_Id.Common.State := Runnable;
Utilities.Exit_One_ATC_Level (Self_Id);
return;
end if;
end loop;
-- This last part is the same as ordinary Wait_For_Completion,
-- and is only executed if the call completed without timing out.
Self_Id.Common.State := Runnable;
Utilities.Exit_One_ATC_Level (Self_Id);
end Wait_For_Completion_With_Timeout;
--------------------------
-- Wait_Until_Abortable --
--------------------------
procedure Wait_Until_Abortable
(Self_ID : Task_Id;
Call : Entry_Call_Link)
is
begin
pragma Assert (Self_ID.ATC_Nesting_Level > Level_No_ATC_Occurring);
pragma Assert (Call.Mode = Asynchronous_Call);
STPO.Write_Lock (Self_ID);
Self_ID.Common.State := Entry_Caller_Sleep;
loop
Check_Pending_Actions_For_Entry_Call (Self_ID, Call);
exit when Call.State >= Was_Abortable;
STPO.Sleep (Self_ID, Async_Select_Sleep);
end loop;
Self_ID.Common.State := Runnable;
STPO.Unlock (Self_ID);
end Wait_Until_Abortable;
end System.Tasking.Entry_Calls;
|
-----------------------------------------------------------------------
-- contexts-facelets -- Contexts for facelets
-- Copyright (C) 2009, 2010, 2011, 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 Util.Strings;
with EL.Objects;
with EL.Contexts;
with EL.Expressions;
with EL.Functions;
with ASF.Components.Base;
with ASF.Converters;
with ASF.Validators;
with Ada.Strings.Unbounded;
with Ada.Containers.Vectors;
limited with ASF.Views.Nodes.Facelets;
package ASF.Contexts.Facelets is
use ASF.Components;
use Ada.Strings.Unbounded;
-- ------------------------------
-- Facelet context
-- ------------------------------
-- The <b>Facelet_Context</b> defines a context used exclusively when
-- building the component tree from the facelet nodes. It allows to
-- compose the component tree by using other facelet fragments.
type Facelet_Context is abstract tagged private;
type Facelet_Context_Access is access all Facelet_Context'Class;
-- Get the EL context for evaluating expressions.
function Get_ELContext (Context : in Facelet_Context)
return EL.Contexts.ELContext_Access;
-- Set the EL context for evaluating expressions.
procedure Set_ELContext (Context : in out Facelet_Context;
ELContext : in EL.Contexts.ELContext_Access);
-- Get the function mapper associated with the EL context.
function Get_Function_Mapper (Context : in Facelet_Context)
return EL.Functions.Function_Mapper_Access;
-- Set the attribute having given name with the value.
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in String;
Value : in EL.Objects.Object);
-- Set the attribute having given name with the value.
procedure Set_Attribute (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Objects.Object);
-- Set the attribute having given name with the expression.
procedure Set_Variable (Context : in out Facelet_Context;
Name : in Unbounded_String;
Value : in EL.Expressions.Expression);
-- Set the attribute having given name with the expression.
procedure Set_Variable (Context : in out Facelet_Context;
Name : in String;
Value : in EL.Expressions.Expression);
-- Include the facelet from the given source file.
-- The included views appended to the parent component tree.
procedure Include_Facelet (Context : in out Facelet_Context;
Source : in String;
Parent : in Base.UIComponent_Access);
-- Include the definition having the given name.
procedure Include_Definition (Context : in out Facelet_Context;
Name : in Unbounded_String;
Parent : in Base.UIComponent_Access;
Found : out Boolean);
-- Push into the current facelet context the <ui:define> nodes contained in
-- the composition/decorate tag.
procedure Push_Defines (Context : in out Facelet_Context;
Node : access ASF.Views.Nodes.Facelets.Composition_Tag_Node);
-- Pop from the current facelet context the <ui:define> nodes.
procedure Pop_Defines (Context : in out Facelet_Context);
-- Set the path to resolve relative facelet paths and get the previous path.
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in String;
Previous : out Unbounded_String);
-- Set the path to resolve relative facelet paths.
procedure Set_Relative_Path (Context : in out Facelet_Context;
Path : in Unbounded_String);
-- Resolve the facelet relative path
function Resolve_Path (Context : Facelet_Context;
Path : String) return String;
-- Get a converter from a name.
-- Returns the converter object or null if there is no converter.
function Get_Converter (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Converters.Converter_Access is abstract;
-- Get a validator from a name.
-- Returns the validator object or null if there is no validator.
function Get_Validator (Context : in Facelet_Context;
Name : in EL.Objects.Object)
return ASF.Validators.Validator_Access is abstract;
private
type Composition_Tag_Node is access all ASF.Views.Nodes.Facelets.Composition_Tag_Node'Class;
package Defines_Vector is
new Ada.Containers.Vectors (Index_Type => Natural,
Element_Type => Composition_Tag_Node);
type Facelet_Context is abstract tagged record
-- The expression context;
Context : EL.Contexts.ELContext_Access := null;
Defines : Defines_Vector.Vector;
Path : Unbounded_String;
Inserts : Util.Strings.String_Set.Set;
end record;
end ASF.Contexts.Facelets;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Test is Put('a'); end Test;
|
-----------------------------------------------------------------------
-- css-tools-messages -- CSS tools messages
-- Copyright (C) 2017 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.Finalization;
with CSS.Core.Errors;
private with Util.Log.Locations;
private with Ada.Containers.Ordered_Maps;
package CSS.Tools.Messages is
-- The message severity.
type Severity_Type is (MSG_ERROR, MSG_WARNING, MSG_INFO);
-- The list of messages for each source location.
type Message_List is limited new Ada.Finalization.Limited_Controlled
and CSS.Core.Errors.Error_Handler with private;
-- Report an error message at the given CSS source position.
overriding
procedure Error (Handler : in out Message_List;
Loc : in CSS.Core.Location;
Message : in String);
-- Report a warning message at the given CSS source position.
overriding
procedure Warning (Handler : in out Message_List;
Loc : in CSS.Core.Location;
Message : in String);
-- Get the number of errors collected.
function Get_Error_Count (Handler : in Message_List) return Natural;
-- Get the number of warnings collected.
function Get_Warning_Count (Handler : in Message_List) return Natural;
-- Iterate over the list of message in the line order.
procedure Iterate (List : in Message_List;
Process : not null access procedure (Severity : in Severity_Type;
Loc : in CSS.Core.Location;
Message : in String));
private
type Message_Type;
type Message_Type_Access is access Message_Type;
type Message_Type (Len : Natural) is limited record
Next : Message_Type_Access;
Kind : Severity_Type := MSG_ERROR;
Message : String (1 .. Len);
end record;
package Message_Sets is
new Ada.Containers.Ordered_Maps (Key_Type => CSS.Core.Location,
Element_Type => Message_Type_Access,
"<" => Util.Log.Locations."<",
"=" => "=");
-- The message list is a ordered map of message list. The map is sorted on the
-- line number.
type Message_List is limited new Ada.Finalization.Limited_Controlled
and CSS.Core.Errors.Error_Handler with record
List : Message_Sets.Map;
Error_Count : Natural := 0;
Warning_Count : Natural := 0;
end record;
-- Add a message for the given source location.
procedure Add (Handler : in out Message_List;
Loc : in CSS.Core.Location;
Message : in Message_Type_Access);
-- Release the list of messages.
overriding
procedure Finalize (List : in out Message_List);
end CSS.Tools.Messages;
|
with ${self.flavor};
package ${self.name} is new ${self.flavor};
|
with Ada.Real_Time; use Ada.Real_Time;
with Text_IO; use Text_IO;
procedure trabalho05 is
canal: array(1..6) of Integer:=(-1,-1,-1,-1,-1,-1);
type vetor is array(1..3) of Integer;
comparacao: vetor;
-- função de envio assíncrono
procedure send (buf: in Integer; c: in Integer) is
begin
canal(c) := buf; -- valor do buffer é copiado na posição c do vetor canal
--Put_Line("send" & Integer'Image(canal(c)));
end send;
-- função de recebimento
procedure receive (buf: out Integer; c: in Integer) is
begin
while canal(c) = -1 loop
null;
end loop;
buf:=canal(c);
--Put_Line("receive" & Integer'Image(buf));
canal(c):=-1;
end receive;
task type threadA;
task body threadA is
voto : Integer := 10; -- mudar voto para obter saída diferente
status : Integer;
begin
send(voto,1); -- primeiro canal para send
receive(status,4); -- primeiro canal para receive
--Put_Line("status A:" & Integer'Image(status));
if status = 0 then -- status de falha
Put_Line("A versao A falhou. Finalizando."); -- mostra e depois finaliza
else
Put_Line("A versao A continua executando."); -- continua executando
while true loop
null;
end loop;
end if;
end threadA;
task type threadB;
task body threadB is
voto : Integer := 10; -- mudar voto para obter saída diferente
status : Integer;
begin
send(voto,2); -- segundo canal para send
receive(status,5); -- segundo canal para receive
--Put_Line("status B:" & Integer'Image(status));
if status = 0 then -- status de falha
Put_Line("A versao B falhou. Finalizando."); -- mostra e depois finaliza
else
Put_Line("A versao B continua executando."); -- continua executando
while true loop
null;
end loop;
end if;
end threadB;
task type threadC;
task body threadC is
voto : Integer := 10; -- mudar voto para obter saída diferente
status : Integer;
begin
send(voto,3); -- terceiro canal para send
receive(status,6); -- teceiro canal para receive
--Put_Line("status C:" & Integer'Image(status));
if status = 0 then -- status de falha
Put_Line("A versao C falhou. Finalizando."); -- mostra e depois finaliza
else
Put_Line("A versao C continua executando."); -- continua executando
while true loop
null;
end loop;
end if;
end threadC;
-- função de compraração dos votos
function compara(comparacao: in vetor) return Integer is
versaoErrada: Integer;
begin
if comparacao(1) = comparacao(2) and comparacao(2) = comparacao(3) then -- a = b = c
Put_Line("Nenhuma versao falhou.");
Put_Line("Voto majoritario:" & Integer'Image(comparacao(1)));
versaoErrada := 0; -- todas são iguais
elsif comparacao(1) = comparacao(2) then -- somente a = b
Put_Line("Versao C falhou.");
Put_Line("Voto majoritario:" & Integer'Image(comparacao(1)));
Put_Line("Voto minoritario:" & Integer'Image(comparacao(3)));
versaoErrada := 3; -- c é diferente
elsif comparacao(2) = comparacao(3) then -- somente b = c
Put_Line("Versao A falhou.");
Put_Line("Voto majoritario:" & Integer'Image(comparacao(2)));
Put_Line("Voto minoritario:" & Integer'Image(comparacao(1)));
versaoErrada := 1; -- a é diferente
else -- somente a = c
Put_Line("Versao B falhou.");
Put_Line("Voto majoritario:" & Integer'Image(comparacao(1)));
Put_Line("Voto minoritario:" & Integer'Image(comparacao(2)));
versaoErrada := 2; -- b é diferente
end if;
return versaoErrada;
end compara;
task type threadDriver;
task body threadDriver is
versaoErrada: Integer;
begin
receive(comparacao(1),1);
--Put_Line("driver - A:" & Integer'Image(comparacao(1)));
receive(comparacao(2),2);
--Put_Line("driver - B:" & Integer'Image(comparacao(2)));
receive(comparacao(3),3);
--Put_Line("driver - C:" & Integer'Image(comparacao(3)));
versaoErrada := compara(comparacao);
if versaoErrada = 0 then -- todas ok
send(1,4); -- A
send(1,5); -- B
send(1,6); -- C
elsif versaoErrada = 1 then -- A falhou
send(0,4); -- A
send(1,5); -- B
send(1,6); -- C
elsif versaoErrada = 2 then -- B falhou
send(1,4); -- A
send(0,5); -- B
send(1,6); -- C
else -- C falhou
send(1,4); -- A
send(1,5); -- B
send(0,6); -- C
end if;
end threadDriver;
-- inicialização de threads
A : threadA;
B : threadB;
C : threadC;
D : threadDriver;
begin
null;
end trabalho05;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ T S S --
-- --
-- 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 Einfo; use Einfo;
with Elists; use Elists;
with Exp_Util; use Exp_Util;
with Lib; use Lib;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Snames; use Snames;
package body Exp_Tss is
--------------------
-- Base_Init_Proc --
--------------------
function Base_Init_Proc (Typ : Entity_Id) return Entity_Id is
Full_Type : E;
Proc : Entity_Id;
begin
pragma Assert (Ekind (Typ) in Type_Kind);
if Is_Private_Type (Typ) then
Full_Type := Underlying_Type (Base_Type (Typ));
else
Full_Type := Typ;
end if;
if No (Full_Type) then
return Empty;
elsif Is_Concurrent_Type (Full_Type)
and then Present (Corresponding_Record_Type (Base_Type (Full_Type)))
then
return Init_Proc (Corresponding_Record_Type (Base_Type (Full_Type)));
else
Proc := Init_Proc (Base_Type (Full_Type));
if No (Proc)
and then Is_Composite_Type (Full_Type)
and then Is_Derived_Type (Full_Type)
then
return Init_Proc (Root_Type (Full_Type));
else
return Proc;
end if;
end if;
end Base_Init_Proc;
--------------
-- Copy_TSS --
--------------
-- Note: internally this routine is also used to initially set up
-- a TSS entry for a new type (case of being called from Set_TSS)
procedure Copy_TSS (TSS : Entity_Id; Typ : Entity_Id) is
FN : Node_Id;
begin
Ensure_Freeze_Node (Typ);
FN := Freeze_Node (Typ);
if No (TSS_Elist (FN)) then
Set_TSS_Elist (FN, New_Elmt_List);
end if;
-- We prepend here, so that a second call overrides the first, it
-- is not clear that this is required, but it seems reasonable.
Prepend_Elmt (TSS, TSS_Elist (FN));
end Copy_TSS;
---------------------------------
-- Has_Non_Null_Base_Init_Proc --
---------------------------------
function Has_Non_Null_Base_Init_Proc (Typ : Entity_Id) return Boolean is
BIP : constant Entity_Id := Base_Init_Proc (Typ);
begin
return Present (BIP) and then not Is_Null_Init_Proc (BIP);
end Has_Non_Null_Base_Init_Proc;
---------------
-- Init_Proc --
---------------
function Init_Proc (Typ : Entity_Id) return Entity_Id is
begin
return TSS (Typ, Name_uInit_Proc);
end Init_Proc;
-------------------
-- Set_Init_Proc --
-------------------
procedure Set_Init_Proc (Typ : Entity_Id; Init : Entity_Id) is
begin
Set_TSS (Typ, Init);
end Set_Init_Proc;
-------------
-- Set_TSS --
-------------
procedure Set_TSS (Typ : Entity_Id; TSS : Entity_Id) is
Subprog_Body : constant Node_Id := Unit_Declaration_Node (TSS);
begin
-- Case of insertion location is in unit defining the type
if In_Same_Code_Unit (Typ, TSS) then
Append_Freeze_Action (Typ, Subprog_Body);
-- Otherwise, we are using an already existing TSS in another unit
else
null;
end if;
Copy_TSS (TSS, Typ);
end Set_TSS;
---------
-- TSS --
---------
function TSS (Typ : Entity_Id; Nam : Name_Id) return Entity_Id is
FN : constant Node_Id := Freeze_Node (Typ);
Elmt : Elmt_Id;
Subp : Entity_Id;
begin
if No (FN) then
return Empty;
elsif No (TSS_Elist (FN)) then
return Empty;
else
Elmt := First_Elmt (TSS_Elist (FN));
while Present (Elmt) loop
if Chars (Node (Elmt)) = Nam then
Subp := Node (Elmt);
-- For stream subprograms, the TSS entity may be a renaming-
-- as-body of an already generated entity. Use that one rather
-- the one introduced by the renaming, which is an artifact of
-- current stream handling.
if Nkind (Parent (Parent (Subp))) =
N_Subprogram_Renaming_Declaration
and then
Present (Corresponding_Spec (Parent (Parent (Subp))))
then
return Corresponding_Spec (Parent (Parent (Subp)));
else
return Subp;
end if;
else
Next_Elmt (Elmt);
end if;
end loop;
end if;
return Empty;
end TSS;
end Exp_Tss;
|
-- Copyright 2015 Steven Stewart-Gallus
--
-- 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 Interfaces.C; use Interfaces.C;
with Libc.Stdint;
with XCB;
with XKB;
package XKB.X11 is
pragma Preelaborate;
pragma Link_With ("-lxkbcommon-x11");
XKB_X11_MIN_MAJOR_XKB_VERSION : constant := 1;
XKB_X11_MIN_MINOR_XKB_VERSION : constant := 0;
type xkb_x11_setup_xkb_extension_flags is
(XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS);
pragma Convention
(C,
xkb_x11_setup_xkb_extension_flags); -- /usr/include/xkbcommon/xkbcommon-x11.h:58
function xkb_x11_setup_xkb_extension
(connection : XCB.xcb_connection_t_access;
major_xkb_version : Libc.Stdint.uint16_t;
minor_xkb_version : Libc.Stdint.uint16_t;
flags : xkb_x11_setup_xkb_extension_flags;
major_xkb_version_out : access Libc.Stdint.uint16_t;
minor_xkb_version_out : access Libc.Stdint.uint16_t;
base_event_out : access Libc.Stdint.uint8_t;
base_error_out : access Libc.Stdint.uint8_t)
return int; -- /usr/include/xkbcommon/xkbcommon-x11.h:98
pragma Import
(C,
xkb_x11_setup_xkb_extension,
"xkb_x11_setup_xkb_extension");
function xkb_x11_get_core_keyboard_device_id
(connection : XCB.xcb_connection_t)
return Libc.Stdint.int32_t; -- /usr/include/xkbcommon/xkbcommon-x11.h:116
pragma Import
(C,
xkb_x11_get_core_keyboard_device_id,
"xkb_x11_get_core_keyboard_device_id");
function xkb_x11_keymap_new_from_device
(context : XKB.xkb_context_access;
connection : XCB.xcb_connection_t_access;
device_id : Libc.Stdint.int32_t;
flags : XKB.xkb_keymap_compile_flags)
return XKB
.xkb_keymap_access; -- /usr/include/xkbcommon/xkbcommon-x11.h:140
pragma Import
(C,
xkb_x11_keymap_new_from_device,
"xkb_x11_keymap_new_from_device");
function xkb_x11_state_new_from_device
(keymap : XKB.xkb_keymap_access;
connection : XCB.xcb_connection_t_access;
device_id : Libc.Stdint.int32_t)
return XKB
.xkb_state_access; -- /usr/include/xkbcommon/xkbcommon-x11.h:164
pragma Import
(C,
xkb_x11_state_new_from_device,
"xkb_x11_state_new_from_device");
end XKB.X11;
|
with AUnit; use AUnit;
with AUnit.Reporter.Text; use AUnit.Reporter.Text;
with AUnit.Run; use AUnit.Run;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Workshop_Suite; use Workshop_Suite;
procedure Tests_Workshop is
function Runner is new Test_Runner_With_Status (Suite);
Reporter : Text_Reporter;
begin
if Runner (Reporter) /= Success then
OS_Exit (1);
end if;
end Tests_Workshop; |
-- C46044B.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 CONSTRAINT ERROR IS RAISED FOR CONVERSION TO A
-- CONSTRAINED ARRAY TYPE IF THE TARGET TYPE IS NON-NULL AND
-- CORRESPONDING DIMENSIONS OF THE TARGET AND OPERAND DO NOT HAVE
-- THE SAME LENGTH. ALSO, CHECK THAT CONSTRAINT_ERROR IS RAISED IF
-- THE TARGET TYPE IS NULL AND THE OPERAND TYPE IS NON-NULL.
-- R.WILLIAMS 9/8/86
WITH REPORT; USE REPORT;
PROCEDURE C46044B IS
TYPE ARR1 IS ARRAY (INTEGER RANGE <>) OF INTEGER;
SUBTYPE CARR1A IS ARR1 (IDENT_INT (1) .. IDENT_INT (6));
C1A : CARR1A := (CARR1A'RANGE => 0);
SUBTYPE CARR1B IS ARR1 (IDENT_INT (2) .. IDENT_INT (5));
C1B : CARR1B := (CARR1B'RANGE => 0);
SUBTYPE CARR1N IS ARR1 (IDENT_INT (1) .. IDENT_INT (0));
C1N : CARR1N := (CARR1N'RANGE => 0);
TYPE ARR2 IS ARRAY (INTEGER RANGE <>, INTEGER RANGE <>) OF
INTEGER;
SUBTYPE CARR2A IS ARR2 (IDENT_INT (1) .. IDENT_INT (2),
IDENT_INT (1) .. IDENT_INT (2));
C2A : CARR2A := (CARR2A'RANGE (1) => (CARR2A'RANGE (2) => 0));
SUBTYPE CARR2B IS ARR2 (IDENT_INT (0) .. IDENT_INT (2),
IDENT_INT (0) .. IDENT_INT (2));
C2B : CARR2B := (CARR2B'RANGE (1) => (CARR2B'RANGE (2) => 0));
SUBTYPE CARR2N IS ARR2 (IDENT_INT (2) .. IDENT_INT (1),
IDENT_INT (1) .. IDENT_INT (2));
C2N : CARR2N := (CARR2N'RANGE (1) => (CARR2N'RANGE (2) => 0));
PROCEDURE CHECK1 (A : ARR1; STR : STRING) IS
BEGIN
FAILED ( "NO EXCEPTION RAISED - " & STR );
END CHECK1;
PROCEDURE CHECK2 (A : ARR2; STR : STRING) IS
BEGIN
FAILED ( "NO EXCEPTION RAISED - " & STR );
END CHECK2;
BEGIN
TEST ( "C46044B", "CHECK THAT CONSTRAINT ERROR IS RAISED FOR " &
"CONVERSION TO A CONSTRAINED ARRAY TYPE " &
"IF THE TARGET TYPE IS NON-NULL AND " &
"CORRESPONDING DIMENSIONS OF THE TARGET AND " &
"OPERAND DO NOT HAVE THE SAME LENGTH. " &
"ALSO, CHECK THAT CONSTRAINT_ERROR IS " &
"RAISED IF THE TARGET TYPE IS NULL AND " &
"THE OPERAND TYPE IS NON-NULL" );
BEGIN -- (A).
C1A := C1B;
CHECK1 (C1A, "(A)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (A)" );
END;
BEGIN -- (B).
CHECK1 (CARR1A (C1B), "(B)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (B)" );
END;
BEGIN -- (C).
C1B := C1A;
CHECK1 (C1B, "(C)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (C)" );
END;
BEGIN -- (D).
CHECK1 (CARR1B (C1A), "(D)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (D)" );
END;
BEGIN -- (E).
C1A := C1N;
CHECK1 (C1A, "(E)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (E)" );
END;
BEGIN -- (F).
CHECK1 (CARR1A (C1N), "(F)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (F)" );
END;
BEGIN -- (G).
C2A := C2B;
CHECK2 (C2A, "(G)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (G)" );
END;
BEGIN -- (H).
CHECK2 (CARR2A (C2B), "(H)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (H)" );
END;
BEGIN -- (I).
C2B := C2A;
CHECK2 (C2B, "(I)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (I)" );
END;
BEGIN -- (J).
CHECK2 (CARR2A (C2B), "(J)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (J)" );
END;
BEGIN -- (K).
C2A := C2N;
CHECK2 (C2A, "(K)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (K)" );
END;
BEGIN -- (L).
CHECK2 (CARR2A (C2N), "(L)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (L)" );
END;
BEGIN -- (M).
C1N := C1A;
CHECK1 (C1N, "(M)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (M)" );
END;
BEGIN -- (N).
CHECK1 (CARR1N (C1A), "(N)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (N)" );
END;
BEGIN -- (O).
C2N := C2A;
CHECK2 (C2N, "(O)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (O)" );
END;
BEGIN -- (P).
CHECK2 (CARR2N (C2A), "(P)");
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED - (P)" );
END;
RESULT;
END C46044B;
|
separate (Numerics.Sparse_Matrices)
function N_Row (Mat : in Sparse_Matrix) return Pos is
begin
return Mat.N_Row;
end N_Row;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E T _ T A R G --
-- --
-- B o d y --
-- --
-- Copyright (C) 2013-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Debug; use Debug;
with Get_Targ; use Get_Targ;
with Opt; use Opt;
with Output; use Output;
with System; use System;
with System.OS_Lib; use System.OS_Lib;
with Unchecked_Conversion;
package body Set_Targ is
--------------------------------------------------------
-- Data Used to Read/Write Target Dependent Info File --
--------------------------------------------------------
-- Table of string names written to file
subtype Str is String;
S_Bits_BE : constant Str := "Bits_BE";
S_Bits_Per_Unit : constant Str := "Bits_Per_Unit";
S_Bits_Per_Word : constant Str := "Bits_Per_Word";
S_Bytes_BE : constant Str := "Bytes_BE";
S_Char_Size : constant Str := "Char_Size";
S_Double_Float_Alignment : constant Str := "Double_Float_Alignment";
S_Double_Scalar_Alignment : constant Str := "Double_Scalar_Alignment";
S_Double_Size : constant Str := "Double_Size";
S_Float_Size : constant Str := "Float_Size";
S_Float_Words_BE : constant Str := "Float_Words_BE";
S_Int_Size : constant Str := "Int_Size";
S_Long_Double_Size : constant Str := "Long_Double_Size";
S_Long_Long_Size : constant Str := "Long_Long_Size";
S_Long_Size : constant Str := "Long_Size";
S_Maximum_Alignment : constant Str := "Maximum_Alignment";
S_Max_Unaligned_Field : constant Str := "Max_Unaligned_Field";
S_Pointer_Size : constant Str := "Pointer_Size";
S_Short_Enums : constant Str := "Short_Enums";
S_Short_Size : constant Str := "Short_Size";
S_Strict_Alignment : constant Str := "Strict_Alignment";
S_System_Allocator_Alignment : constant Str := "System_Allocator_Alignment";
S_Wchar_T_Size : constant Str := "Wchar_T_Size";
S_Words_BE : constant Str := "Words_BE";
-- Table of names
type AStr is access all String;
DTN : constant array (Nat range <>) of AStr := (
S_Bits_BE 'Unrestricted_Access,
S_Bits_Per_Unit 'Unrestricted_Access,
S_Bits_Per_Word 'Unrestricted_Access,
S_Bytes_BE 'Unrestricted_Access,
S_Char_Size 'Unrestricted_Access,
S_Double_Float_Alignment 'Unrestricted_Access,
S_Double_Scalar_Alignment 'Unrestricted_Access,
S_Double_Size 'Unrestricted_Access,
S_Float_Size 'Unrestricted_Access,
S_Float_Words_BE 'Unrestricted_Access,
S_Int_Size 'Unrestricted_Access,
S_Long_Double_Size 'Unrestricted_Access,
S_Long_Long_Size 'Unrestricted_Access,
S_Long_Size 'Unrestricted_Access,
S_Maximum_Alignment 'Unrestricted_Access,
S_Max_Unaligned_Field 'Unrestricted_Access,
S_Pointer_Size 'Unrestricted_Access,
S_Short_Enums 'Unrestricted_Access,
S_Short_Size 'Unrestricted_Access,
S_Strict_Alignment 'Unrestricted_Access,
S_System_Allocator_Alignment 'Unrestricted_Access,
S_Wchar_T_Size 'Unrestricted_Access,
S_Words_BE 'Unrestricted_Access);
-- Table of corresponding value pointers
DTV : constant array (Nat range <>) of System.Address := (
Bits_BE 'Address,
Bits_Per_Unit 'Address,
Bits_Per_Word 'Address,
Bytes_BE 'Address,
Char_Size 'Address,
Double_Float_Alignment 'Address,
Double_Scalar_Alignment 'Address,
Double_Size 'Address,
Float_Size 'Address,
Float_Words_BE 'Address,
Int_Size 'Address,
Long_Double_Size 'Address,
Long_Long_Size 'Address,
Long_Size 'Address,
Maximum_Alignment 'Address,
Max_Unaligned_Field 'Address,
Pointer_Size 'Address,
Short_Enums 'Address,
Short_Size 'Address,
Strict_Alignment 'Address,
System_Allocator_Alignment 'Address,
Wchar_T_Size 'Address,
Words_BE 'Address);
DTR : array (Nat range DTV'Range) of Boolean := (others => False);
-- Table of flags used to validate that all values are present in file
-----------------------
-- Local Subprograms --
-----------------------
procedure Read_Target_Dependent_Values (File_Name : String);
-- Read target dependent values from File_Name, and set the target
-- dependent values (global variables) declared in this package.
procedure Fail (E : String);
pragma No_Return (Fail);
-- Terminate program with fatal error message passed as parameter
procedure Register_Float_Type
(Name : C_String;
Digs : Natural;
Complex : Boolean;
Count : Natural;
Float_Rep : Float_Rep_Kind;
Precision : Positive;
Size : Positive;
Alignment : Natural);
pragma Convention (C, Register_Float_Type);
-- Call back to allow the back end to register available types. This call
-- back makes entries in the FPT_Mode_Table for any floating point types
-- reported by the back end. Name is the name of the type as a normal
-- format Null-terminated string. Digs is the number of digits, where 0
-- means it is not a fpt type (ignored during registration). Complex is
-- non-zero if the type has real and imaginary parts (also ignored during
-- registration). Count is the number of elements in a vector type (zero =
-- not a vector, registration ignores vectors). Float_Rep shows the kind of
-- floating-point type, and Precision, Size and Alignment are the precision
-- size and alignment in bits.
--
-- The only types that are actually registered have Digs non-zero, Complex
-- zero (false), and Count zero (not a vector). The Long_Double_Index
-- variable below is updated to indicate the index at which a "long double"
-- type can be found if it gets registered at all.
Long_Double_Index : Integer := -1;
-- Once all the floating point types have been registered, the index in
-- FPT_Mode_Table at which "long double" can be found, if anywhere. A
-- negative value means that no "long double" has been registered. This
-- is useful to know whether we have a "long double" available at all and
-- get at it's characteristics without having to search the FPT_Mode_Table
-- when we need to decide which C type should be used as the basis for
-- Long_Long_Float in Ada.
function FPT_Mode_Index_For (Name : String) return Natural;
-- Return the index in FPT_Mode_Table that designates the entry
-- corresponding to the C type named Name. Raise Program_Error if
-- there is no such entry.
function FPT_Mode_Index_For (T : S_Float_Types) return Natural;
-- Return the index in FPT_Mode_Table that designates the entry for
-- a back-end type suitable as a basis to construct the standard Ada
-- floating point type identified by T.
----------------
-- C_Type_For --
----------------
function C_Type_For (T : S_Float_Types) return String is
-- ??? For now, we don't have a good way to tell the widest float
-- type with hardware support. Basically, GCC knows the size of that
-- type, but on x86-64 there often are two or three 128-bit types,
-- one double extended that has 18 decimal digits, a 128-bit quad
-- precision type with 33 digits and possibly a 128-bit decimal float
-- type with 34 digits. As a workaround, we define Long_Long_Float as
-- C's "long double" if that type exists and has at most 18 digits,
-- or otherwise the same as Long_Float.
Max_HW_Digs : constant := 18;
-- Maximum hardware digits supported
begin
case T is
when S_Float
| S_Short_Float
=>
return "float";
when S_Long_Float =>
return "double";
when S_Long_Long_Float =>
if Long_Double_Index >= 0
and then FPT_Mode_Table (Long_Double_Index).DIGS <= Max_HW_Digs
then
return "long double";
else
return "double";
end if;
end case;
end C_Type_For;
----------
-- Fail --
----------
procedure Fail (E : String) is
E_Fatal : constant := 4;
-- Code for fatal error
begin
Write_Str (E);
Write_Eol;
OS_Exit (E_Fatal);
end Fail;
------------------------
-- FPT_Mode_Index_For --
------------------------
function FPT_Mode_Index_For (Name : String) return Natural is
begin
for J in FPT_Mode_Table'First .. Num_FPT_Modes loop
if FPT_Mode_Table (J).NAME.all = Name then
return J;
end if;
end loop;
raise Program_Error;
end FPT_Mode_Index_For;
function FPT_Mode_Index_For (T : S_Float_Types) return Natural is
begin
return FPT_Mode_Index_For (C_Type_For (T));
end FPT_Mode_Index_For;
-------------------------
-- Register_Float_Type --
-------------------------
procedure Register_Float_Type
(Name : C_String;
Digs : Natural;
Complex : Boolean;
Count : Natural;
Float_Rep : Float_Rep_Kind;
Precision : Positive;
Size : Positive;
Alignment : Natural)
is
T : String (1 .. Name'Length);
Last : Natural := 0;
procedure Dump;
-- Dump information given by the back end for the type to register
----------
-- Dump --
----------
procedure Dump is
begin
Write_Str ("type " & T (1 .. Last) & " is ");
if Count > 0 then
Write_Str ("array (1 .. ");
Write_Int (Int (Count));
if Complex then
Write_Str (", 1 .. 2");
end if;
Write_Str (") of ");
elsif Complex then
Write_Str ("array (1 .. 2) of ");
end if;
if Digs > 0 then
Write_Str ("digits ");
Write_Int (Int (Digs));
Write_Line (";");
Write_Str ("pragma Float_Representation (");
case Float_Rep is
when AAMP => Write_Str ("AAMP");
when IEEE_Binary => Write_Str ("IEEE");
end case;
Write_Line (", " & T (1 .. Last) & ");");
else
Write_Str ("mod 2**");
Write_Int (Int (Precision / Positive'Max (1, Count)));
Write_Line (";");
end if;
if Precision = Size then
Write_Str ("for " & T (1 .. Last) & "'Size use ");
Write_Int (Int (Size));
Write_Line (";");
else
Write_Str ("for " & T (1 .. Last) & "'Value_Size use ");
Write_Int (Int (Precision));
Write_Line (";");
Write_Str ("for " & T (1 .. Last) & "'Object_Size use ");
Write_Int (Int (Size));
Write_Line (";");
end if;
Write_Str ("for " & T (1 .. Last) & "'Alignment use ");
Write_Int (Int (Alignment / 8));
Write_Line (";");
Write_Eol;
end Dump;
-- Start of processing for Register_Float_Type
begin
-- Acquire name
for J in T'Range loop
T (J) := Name (Name'First + J - 1);
if T (J) = ASCII.NUL then
Last := J - 1;
exit;
end if;
end loop;
-- Dump info if debug flag set
if Debug_Flag_Dot_B then
Dump;
end if;
-- Acquire entry if non-vector non-complex fpt type (digits non-zero)
if Digs > 0 and then not Complex and then Count = 0 then
declare
This_Name : constant String := T (1 .. Last);
begin
Num_FPT_Modes := Num_FPT_Modes + 1;
FPT_Mode_Table (Num_FPT_Modes) :=
(NAME => new String'(This_Name),
DIGS => Digs,
FLOAT_REP => Float_Rep,
PRECISION => Precision,
SIZE => Size,
ALIGNMENT => Alignment);
if Long_Double_Index < 0 and then This_Name = "long double" then
Long_Double_Index := Num_FPT_Modes;
end if;
end;
end if;
end Register_Float_Type;
-----------------------------------
-- Write_Target_Dependent_Values --
-----------------------------------
-- We do this at the System.Os_Lib level, since we have to do the read at
-- that level anyway, so it is easier and more consistent to follow the
-- same path for the write.
procedure Write_Target_Dependent_Values is
Fdesc : File_Descriptor;
OK : Boolean;
Buffer : String (1 .. 80);
Buflen : Natural;
-- Buffer used to build line one of file
type ANat is access all Natural;
-- Pointer to Nat or Pos value (it is harmless to treat Pos values and
-- Nat values as Natural via Unchecked_Conversion).
function To_ANat is new Unchecked_Conversion (Address, ANat);
procedure AddC (C : Character);
-- Add one character to buffer
procedure AddN (N : Natural);
-- Add representation of integer N to Buffer, updating Buflen. N
-- must be less than 1000, and output is 3 characters with leading
-- spaces as needed.
procedure Write_Line;
-- Output contents of Buffer (1 .. Buflen) followed by a New_Line,
-- and set Buflen back to zero, ready to write next line.
----------
-- AddC --
----------
procedure AddC (C : Character) is
begin
Buflen := Buflen + 1;
Buffer (Buflen) := C;
end AddC;
----------
-- AddN --
----------
procedure AddN (N : Natural) is
begin
if N > 999 then
raise Program_Error;
end if;
if N > 99 then
AddC (Character'Val (48 + N / 100));
else
AddC (' ');
end if;
if N > 9 then
AddC (Character'Val (48 + N / 10 mod 10));
else
AddC (' ');
end if;
AddC (Character'Val (48 + N mod 10));
end AddN;
----------------
-- Write_Line --
----------------
procedure Write_Line is
begin
AddC (ASCII.LF);
if Buflen /= Write (Fdesc, Buffer'Address, Buflen) then
Delete_File (Target_Dependent_Info_Write_Name.all, OK);
Fail ("disk full writing file "
& Target_Dependent_Info_Write_Name.all);
end if;
Buflen := 0;
end Write_Line;
-- Start of processing for Write_Target_Dependent_Values
begin
Fdesc :=
Create_File (Target_Dependent_Info_Write_Name.all, Text);
if Fdesc = Invalid_FD then
Fail ("cannot create file " & Target_Dependent_Info_Write_Name.all);
end if;
-- Loop through values
for J in DTN'Range loop
-- Output name
Buflen := DTN (J)'Length;
Buffer (1 .. Buflen) := DTN (J).all;
-- Line up values
while Buflen < 26 loop
AddC (' ');
end loop;
AddC (' ');
AddC (' ');
-- Output value and write line
AddN (To_ANat (DTV (J)).all);
Write_Line;
end loop;
-- Blank line to separate sections
Write_Line;
-- Write lines for registered FPT types
for J in 1 .. Num_FPT_Modes loop
declare
E : FPT_Mode_Entry renames FPT_Mode_Table (J);
begin
Buflen := E.NAME'Last;
Buffer (1 .. Buflen) := E.NAME.all;
-- Pad out to line up values
while Buflen < 11 loop
AddC (' ');
end loop;
AddC (' ');
AddC (' ');
AddN (E.DIGS);
AddC (' ');
AddC (' ');
case E.FLOAT_REP is
when AAMP => AddC ('A');
when IEEE_Binary => AddC ('I');
end case;
AddC (' ');
AddN (E.PRECISION);
AddC (' ');
AddN (E.ALIGNMENT);
Write_Line;
end;
end loop;
-- Close file
Close (Fdesc, OK);
if not OK then
Fail ("disk full writing file "
& Target_Dependent_Info_Write_Name.all);
end if;
end Write_Target_Dependent_Values;
----------------------------------
-- Read_Target_Dependent_Values --
----------------------------------
procedure Read_Target_Dependent_Values (File_Name : String) is
File_Desc : File_Descriptor;
N : Natural;
type ANat is access all Natural;
-- Pointer to Nat or Pos value (it is harmless to treat Pos values
-- as Nat via Unchecked_Conversion).
function To_ANat is new Unchecked_Conversion (Address, ANat);
VP : ANat;
Buffer : String (1 .. 2000);
Buflen : Natural;
-- File information and length (2000 easily enough)
Nam_Buf : String (1 .. 40);
Nam_Len : Natural;
procedure Check_Spaces;
-- Checks that we have one or more spaces and skips them
procedure FailN (S : String);
pragma No_Return (FailN);
-- Calls Fail adding " name in file xxx", where name is the currently
-- gathered name in Nam_Buf, surrounded by quotes, and xxx is the
-- name of the file.
procedure Get_Name;
-- Scan out name, leaving it in Nam_Buf with Nam_Len set. Calls
-- Skip_Spaces to skip any following spaces. Note that the name is
-- terminated by a sequence of at least two spaces.
function Get_Nat return Natural;
-- N on entry points to decimal integer, scan out decimal integer
-- and return it, leaving N pointing to following space or LF.
procedure Skip_Spaces;
-- Skip past spaces
------------------
-- Check_Spaces --
------------------
procedure Check_Spaces is
begin
if N > Buflen or else Buffer (N) /= ' ' then
FailN ("missing space for");
end if;
Skip_Spaces;
return;
end Check_Spaces;
-----------
-- FailN --
-----------
procedure FailN (S : String) is
begin
Fail (S & " """ & Nam_Buf (1 .. Nam_Len) & """ in file "
& File_Name);
end FailN;
--------------
-- Get_Name --
--------------
procedure Get_Name is
begin
Nam_Len := 0;
-- Scan out name and put it in Nam_Buf
loop
if N > Buflen or else Buffer (N) = ASCII.LF then
FailN ("incorrectly formatted line for");
end if;
-- Name is terminated by two blanks
exit when N < Buflen and then Buffer (N .. N + 1) = " ";
Nam_Len := Nam_Len + 1;
if Nam_Len > Nam_Buf'Last then
Fail ("name too long");
end if;
Nam_Buf (Nam_Len) := Buffer (N);
N := N + 1;
end loop;
Check_Spaces;
end Get_Name;
-------------
-- Get_Nat --
-------------
function Get_Nat return Natural is
Result : Natural := 0;
begin
loop
if N > Buflen
or else Buffer (N) not in '0' .. '9'
or else Result > 999
then
FailN ("bad value for");
end if;
Result := Result * 10 + (Character'Pos (Buffer (N)) - 48);
N := N + 1;
exit when N <= Buflen
and then (Buffer (N) = ASCII.LF or else Buffer (N) = ' ');
end loop;
return Result;
end Get_Nat;
-----------------
-- Skip_Spaces --
-----------------
procedure Skip_Spaces is
begin
while N <= Buflen and Buffer (N) = ' ' loop
N := N + 1;
end loop;
end Skip_Spaces;
-- Start of processing for Read_Target_Dependent_Values
begin
File_Desc := Open_Read (File_Name, Text);
if File_Desc = Invalid_FD then
Fail ("cannot read file " & File_Name);
end if;
Buflen := Read (File_Desc, Buffer'Address, Buffer'Length);
Close (File_Desc);
if Buflen = Buffer'Length then
Fail ("file is too long: " & File_Name);
end if;
-- Scan through file for properly formatted entries in first section
N := 1;
while N <= Buflen and then Buffer (N) /= ASCII.LF loop
Get_Name;
-- Validate name and get corresponding value pointer
VP := null;
for J in DTN'Range loop
if DTN (J).all = Nam_Buf (1 .. Nam_Len) then
VP := To_ANat (DTV (J));
DTR (J) := True;
exit;
end if;
end loop;
if VP = null then
FailN ("unrecognized name");
end if;
-- Scan out value
VP.all := Get_Nat;
if N > Buflen or else Buffer (N) /= ASCII.LF then
FailN ("misformatted line for");
end if;
N := N + 1; -- skip LF
end loop;
-- Fall through this loop when all lines in first section read.
-- Check that values have been supplied for all entries.
for J in DTR'Range loop
if not DTR (J) then
Fail ("missing entry for " & DTN (J).all & " in file "
& File_Name);
end if;
end loop;
-- Now acquire FPT entries
if N >= Buflen then
Fail ("missing entries for FPT modes in file " & File_Name);
end if;
if Buffer (N) = ASCII.LF then
N := N + 1;
else
Fail ("missing blank line in file " & File_Name);
end if;
Num_FPT_Modes := 0;
while N <= Buflen loop
Get_Name;
Num_FPT_Modes := Num_FPT_Modes + 1;
declare
E : FPT_Mode_Entry renames FPT_Mode_Table (Num_FPT_Modes);
begin
E.NAME := new String'(Nam_Buf (1 .. Nam_Len));
if Long_Double_Index < 0 and then E.NAME.all = "long double" then
Long_Double_Index := Num_FPT_Modes;
end if;
E.DIGS := Get_Nat;
Check_Spaces;
case Buffer (N) is
when 'I' =>
E.FLOAT_REP := IEEE_Binary;
when 'A' =>
E.FLOAT_REP := AAMP;
when others =>
FailN ("bad float rep field for");
end case;
N := N + 1;
Check_Spaces;
E.PRECISION := Get_Nat;
Check_Spaces;
E.ALIGNMENT := Get_Nat;
if Buffer (N) /= ASCII.LF then
FailN ("junk at end of line for");
end if;
-- ??? We do not read E.SIZE, see Write_Target_Dependent_Values
E.SIZE :=
(E.PRECISION + E.ALIGNMENT - 1) / E.ALIGNMENT * E.ALIGNMENT;
N := N + 1;
end;
end loop;
end Read_Target_Dependent_Values;
-- Package Initialization, set target dependent values. This must be done
-- early on, before we start accessing various compiler packages, since
-- these values are used all over the place.
begin
-- First step: see if the -gnateT switch is present. As we have noted,
-- this has to be done very early, so cannot depend on the normal circuit
-- for reading switches and setting switches in Opt. The following code
-- will set Opt.Target_Dependent_Info_Read_Name if the switch -gnateT=name
-- is present in the options string.
declare
type Arg_Array is array (Nat) of Big_String_Ptr;
type Arg_Array_Ptr is access Arg_Array;
-- Types to access compiler arguments
save_argc : Nat;
pragma Import (C, save_argc);
-- Saved value of argc (number of arguments), imported from misc.c
save_argv : Arg_Array_Ptr;
pragma Import (C, save_argv);
-- Saved value of argv (argument pointers), imported from misc.c
gnat_argc : Nat;
gnat_argv : Arg_Array_Ptr;
pragma Import (C, gnat_argc);
pragma Import (C, gnat_argv);
-- If save_argv is not set, default to gnat_argc/argv
argc : Nat;
argv : Arg_Array_Ptr;
function Len_Arg (Arg : Big_String_Ptr) return Nat;
-- Determine length of argument Arg (a nul terminated C string).
-------------
-- Len_Arg --
-------------
function Len_Arg (Arg : Big_String_Ptr) return Nat is
begin
for J in 1 .. Nat'Last loop
if Arg (Natural (J)) = ASCII.NUL then
return J - 1;
end if;
end loop;
raise Program_Error;
end Len_Arg;
begin
if save_argv /= null then
argv := save_argv;
argc := save_argc;
else
-- Case of a non gcc compiler, e.g. gnat2why or gnat2scil
argv := gnat_argv;
argc := gnat_argc;
end if;
-- Loop through arguments looking for -gnateT, also look for -gnatd.b
for Arg in 1 .. argc - 1 loop
declare
Argv_Ptr : constant Big_String_Ptr := argv (Arg);
Argv_Len : constant Nat := Len_Arg (Argv_Ptr);
begin
if Argv_Len > 8
and then Argv_Ptr (1 .. 8) = "-gnateT="
then
Opt.Target_Dependent_Info_Read_Name :=
new String'(Argv_Ptr (9 .. Natural (Argv_Len)));
elsif Argv_Len >= 8
and then Argv_Ptr (1 .. 8) = "-gnatd.b"
then
Debug_Flag_Dot_B := True;
end if;
end;
end loop;
end;
-- Case of reading the target dependent values from file
-- This is bit more complex than might be expected, because it has to be
-- done very early. All kinds of packages depend on these values, and we
-- can't wait till the normal processing of reading command line switches
-- etc to read the file. We do this at the System.OS_Lib level since it is
-- too early to be using Osint directly.
if Opt.Target_Dependent_Info_Read_Name /= null then
Read_Target_Dependent_Values (Target_Dependent_Info_Read_Name.all);
else
-- If the back-end comes with a target config file, then use it
-- to set the values
declare
Back_End_Config_File : constant String_Ptr :=
Get_Back_End_Config_File;
begin
if Back_End_Config_File /= null then
pragma Gnat_Annotate
(CodePeer, Intentional, "test always false",
"some variant body will return non null");
Read_Target_Dependent_Values (Back_End_Config_File.all);
-- Otherwise we get all values from the back end directly
else
Bits_BE := Get_Bits_BE;
Bits_Per_Unit := Get_Bits_Per_Unit;
Bits_Per_Word := Get_Bits_Per_Word;
Bytes_BE := Get_Bytes_BE;
Char_Size := Get_Char_Size;
Double_Float_Alignment := Get_Double_Float_Alignment;
Double_Scalar_Alignment := Get_Double_Scalar_Alignment;
Float_Words_BE := Get_Float_Words_BE;
Int_Size := Get_Int_Size;
Long_Long_Size := Get_Long_Long_Size;
Long_Size := Get_Long_Size;
Maximum_Alignment := Get_Maximum_Alignment;
Max_Unaligned_Field := Get_Max_Unaligned_Field;
Pointer_Size := Get_Pointer_Size;
Short_Enums := Get_Short_Enums;
Short_Size := Get_Short_Size;
Strict_Alignment := Get_Strict_Alignment;
System_Allocator_Alignment := Get_System_Allocator_Alignment;
Wchar_T_Size := Get_Wchar_T_Size;
Words_BE := Get_Words_BE;
-- Let the back-end register its floating point types and compute
-- the sizes of our standard types from there:
Num_FPT_Modes := 0;
Register_Back_End_Types (Register_Float_Type'Access);
declare
T : FPT_Mode_Entry renames
FPT_Mode_Table (FPT_Mode_Index_For (S_Float));
begin
Float_Size := Pos (T.SIZE);
end;
declare
T : FPT_Mode_Entry renames
FPT_Mode_Table (FPT_Mode_Index_For (S_Long_Float));
begin
Double_Size := Pos (T.SIZE);
end;
declare
T : FPT_Mode_Entry renames
FPT_Mode_Table (FPT_Mode_Index_For (S_Long_Long_Float));
begin
Long_Double_Size := Pos (T.SIZE);
end;
end if;
end;
end if;
end Set_Targ;
|
-- Abstract :
--
-- See spec.
--
-- Copyright (C) 2017 - 2019 Free Software Foundation, Inc.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
package body SAL.Gen_Bounded_Definite_Vectors
with Spark_Mode
is
pragma Suppress (All_Checks);
function Length (Container : in Vector) return Ada.Containers.Count_Type
is (Ada.Containers.Count_Type (To_Peek_Index (Container.Last)));
function Is_Full (Container : in Vector) return Boolean
is begin
return Length (Container) = Capacity;
end Is_Full;
procedure Clear (Container : in out Vector)
is begin
Container.Last := No_Index;
end Clear;
function Element (Container : Vector; Index : Index_Type) return Element_Type
is (Container.Elements (Peek_Type (Index - Index_Type'First + 1)));
procedure Replace_Element
(Container : in out Vector;
Index : in Index_Type;
New_Item : in Element_Type)
is begin
Container.Elements (To_Peek_Index (Index)) := New_Item;
end Replace_Element;
function Last_Index (Container : Vector) return Extended_Index
is (Container.Last);
procedure Append (Container : in out Vector; New_Item : in Element_Type)
is
J : constant Peek_Type := To_Peek_Index (Container.Last + 1);
begin
Container.Elements (J) := New_Item;
Container.Last := Container.Last + 1;
end Append;
procedure Prepend (Container : in out Vector; New_Item : in Element_Type)
is
J : constant Peek_Type := Peek_Type (Container.Last + 1 - Index_Type'First + 1);
begin
Container.Elements (2 .. J) := Container.Elements (1 .. J - 1);
Container.Elements (1) := New_Item;
Container.Last := Container.Last + 1;
end Prepend;
procedure Insert
(Container : in out Vector;
New_Item : in Element_Type;
Before : in Extended_Index)
is
J : constant Peek_Type := To_Peek_Index ((if Before = No_Index then Container.Last + 1 else Before));
K : constant Base_Peek_Type := To_Peek_Index (Container.Last);
begin
Container.Elements (J + 1 .. K + 1) := Container.Elements (J .. K);
Container.Elements (J) := New_Item;
Container.Last := Container.Last + 1;
end Insert;
function "+" (Item : in Element_Type) return Vector
is begin
return Result : Vector do
Append (Result, Item);
end return;
end "+";
function "&" (Left : in Vector; Right : in Element_Type) return Vector
is begin
-- WORKAROUND: If init Result with ":= Left", GNAT Community 2019
-- checks Default_Initial_Condition (which fails when Left is not
-- empty)! That is only supposed to be checked when initialized by
-- default. Reported to AdaCore as ticket S724-042.
return Result : Vector do
Result := Left;
Append (Result, Right);
end return;
end "&";
procedure Delete_First (Container : in out Vector; Count : in Ada.Containers.Count_Type := 1)
is
use Ada.Containers;
begin
if Count = 0 then
return;
end if;
declare
New_Last : constant Extended_Index := Extended_Index (Integer (Container.Last) - Integer (Count));
J : constant Base_Peek_Type := Base_Peek_Type (Count);
K : constant Peek_Type := To_Peek_Index (Container.Last);
begin
-- Delete items 1 .. J, shift remaining down.
Container.Elements (1 .. K - J) := Container.Elements (J + 1 .. K);
Container.Last := New_Last;
end;
end Delete_First;
end SAL.Gen_Bounded_Definite_Vectors;
|
-----------------------------------------------------------------------
-- awa-events-queues-fifos -- Fifo event queues (memory based)
-- Copyright (C) 2012 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Log.Loggers;
package body AWA.Events.Queues.Fifos is
use Util.Log;
Log : constant Loggers.Logger := Loggers.Create ("AWA.Events.Queues.Fifos");
procedure Free is
new Ada.Unchecked_Deallocation (Object => AWA.Events.Module_Event'Class,
Name => AWA.Events.Module_Event_Access);
-- ------------------------------
-- Get the queue name.
-- ------------------------------
overriding
function Get_Name (From : in Fifo_Queue) return String is
begin
return From.Name;
end Get_Name;
-- ------------------------------
-- Get the model queue reference object.
-- Returns a null object if the queue is not persistent.
-- ------------------------------
overriding
function Get_Queue (From : in Fifo_Queue) return AWA.Events.Models.Queue_Ref is
pragma Unreferenced (From);
begin
return AWA.Events.Models.Null_Queue;
end Get_Queue;
-- ------------------------------
-- Queue the event.
-- ------------------------------
procedure Enqueue (Into : in out Fifo_Queue;
Event : in AWA.Events.Module_Event'Class) is
E : constant Module_Event_Access := Copy (Event);
begin
Log.Debug ("Enqueue event on queue {0}", Into.Name);
E.Set_Event_Kind (Event.Get_Event_Kind);
Into.Fifo.Enqueue (E);
end Enqueue;
-- ------------------------------
-- Dequeue an event and process it with the <b>Process</b> procedure.
-- ------------------------------
procedure Dequeue (From : in out Fifo_Queue;
Process : access procedure (Event : in Module_Event'Class)) is
E : Module_Event_Access;
begin
Log.Debug ("Dequeue event queue {0}", From.Name);
From.Fifo.Dequeue (E, 0.0);
begin
Process (E.all);
exception
when E : others =>
Log.Error ("Exception when processing event", E);
end;
Free (E);
exception
when Fifo_Protected_Queue.Timeout =>
null;
end Dequeue;
-- ------------------------------
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
-- ------------------------------
overriding
function Get_Value (From : in Fifo_Queue;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
-- ------------------------------
-- Set the value identified by the name.
-- If the name cannot be found, the method should raise the No_Value
-- exception.
-- ------------------------------
overriding
procedure Set_Value (From : in out Fifo_Queue;
Name : in String;
Value : in Util.Beans.Objects.Object) is
begin
if Name = "size" then
From.Fifo.Set_Size (Util.Beans.Objects.To_Integer (Value));
end if;
end Set_Value;
-- ------------------------------
-- Release the queue storage.
-- ------------------------------
overriding
procedure Finalize (From : in out Fifo_Queue) is
begin
while From.Fifo.Get_Count > 0 loop
declare
E : Module_Event_Access;
begin
From.Fifo.Dequeue (E);
Free (E);
end;
end loop;
end Finalize;
-- ------------------------------
-- Create the queue associated with the given name and configure it by using
-- the configuration properties.
-- ------------------------------
function Create_Queue (Name : in String;
Props : in EL.Beans.Param_Vectors.Vector;
Context : in EL.Contexts.ELContext'Class) return Queue_Access is
Result : constant Fifo_Queue_Access := new Fifo_Queue '(Name_Length => Name'Length,
Name => Name,
others => <>);
begin
EL.Beans.Initialize (Result.all, Props, Context);
return Result.all'Access;
end Create_Queue;
end AWA.Events.Queues.Fifos;
|
with System;
with STM32_SVD; use STM32_SVD;
with STM32_SVD.RCC; use STM32_SVD.RCC;
with STM32GD.Board; use STM32GD.Board;
with STM32GD.GPIO; use STM32GD.GPIO;
package body Peripherals is
procedure Init is
begin
RCC.RCC_Periph.APB1ENR.I2C1EN := 1;
RCC.RCC_Periph.APB2ENR.USART1EN := 1;
RCC.RCC_Periph.APB2ENR.ADCEN := 1;
SCL_OUT.Init;
for I in Integer range 0 .. 10 loop
-- SCL_OUT.Toggle;
for J in Integer range 0 .. 1000 loop null; end loop;
end loop;
SCL.Init;
SDA.Init;
I2C.Init;
RX.Init;
TX.Init;
USART.Init;
end Init;
end Peripherals;
|
-- CC1221D.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:
-- FOR A FORMAL INTEGER TYPE, CHECK THAT THE FOLLOWING BASIC
-- OPERATIONS ARE IMPLICITLY DECLARED AND ARE THEREFORE AVAILABLE
-- WITHIN THE GENERIC UNIT: EXPLICIT CONVERSION TO AND FROM REAL
-- TYPES AND IMPLICIT CONVERSION FROM INTEGER LITERALS.
-- HISTORY:
-- BCB 11/12/87 CREATED ORIGINAL TEST FROM SPLIT OF CC1221A.ADA
WITH SYSTEM; USE SYSTEM;
WITH REPORT; USE REPORT;
PROCEDURE CC1221D IS
SUBTYPE SUBINT IS INTEGER RANGE -100 .. 100;
TYPE INT IS RANGE -300 .. 300;
SUBTYPE SINT1 IS INT
RANGE INT (IDENT_INT (-4)) .. INT (IDENT_INT (4));
TYPE INT1 IS RANGE -6 .. 6;
BEGIN
TEST ( "CC1221D", "FOR A FORMAL INTEGER TYPE, CHECK THAT THE " &
"FOLLOWING BASIC OPERATIONS ARE IMPLICITLY " &
"DECLARED AND ARE THEREFORE AVAILABLE " &
"WITHIN THE GENERIC UNIT: EXPLICIT " &
"CONVERSION TO AND FROM REAL TYPES AND " &
"IMPLICIT CONVERSION FROM INTEGER LITERALS");
DECLARE -- (D) CHECKS FOR EXPLICIT CONVERSION TO AND FROM OTHER
-- NUMERIC TYPES, AND IMPLICIT CONVERSION FROM
-- INTEGER LITERALS.
GENERIC
TYPE T IS RANGE <>;
PROCEDURE P (STR : STRING);
PROCEDURE P (STR : STRING) IS
TYPE FIXED IS DELTA 0.1 RANGE -100.0 .. 100.0;
FI0 : FIXED := 0.0;
FI2 : FIXED := 2.0;
FIN2 : FIXED := -2.0;
FL0 : FLOAT := 0.0;
FL2 : FLOAT := 2.0;
FLN2 : FLOAT := -2.0;
T0 : T := 0;
T2 : T := 2;
TN2 : T := -2;
FUNCTION IDENT (X : T) RETURN T IS
BEGIN
IF EQUAL (3, 3) THEN
RETURN X;
ELSE
RETURN T'FIRST;
END IF;
END IDENT;
BEGIN
IF T0 + 1 /= 1 THEN
FAILED ( "INCORRECT RESULTS FOR IMPLICIT " &
"CONVERSION WITH TYPE " & STR & " - 1" );
END IF;
IF T2 + 1 /= 3 THEN
FAILED ( "INCORRECT RESULTS FOR IMPLICIT " &
"CONVERSION WITH TYPE " & STR & " - 2" );
END IF;
IF TN2 + 1 /= -1 THEN
FAILED ( "INCORRECT RESULTS FOR IMPLICIT " &
"CONVERSION WITH TYPE " & STR & " - 3" );
END IF;
IF T (FI0) /= T0 THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FIXED VALUE 0.0 WITH TYPE " & STR);
END IF;
IF T (FI2) /= IDENT (T2) THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FIXED VALUE 2.0 WITH TYPE " & STR);
END IF;
IF T (FIN2) /= TN2 THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FIXED VALUE -2.0 WITH TYPE " & STR);
END IF;
IF T (FL0) /= IDENT (T0) THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FLOAT VALUE 0.0 WITH TYPE " & STR);
END IF;
IF T (FL2) /= T2 THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FLOAT VALUE 2.0 WITH TYPE " & STR);
END IF;
IF T (FLN2) /= IDENT (TN2) THEN
FAILED ( "INCORRECT CONVERSION FROM " &
"FLOAT VALUE -2.0 WITH TYPE " & STR);
END IF;
IF FIXED (T0) /= FI0 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FIXED VALUE 0.0 WITH TYPE " & STR);
END IF;
IF FIXED (IDENT (T2)) /= FI2 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FIXED VALUE 2.0 WITH TYPE " & STR);
END IF;
IF FIXED (TN2) /= FIN2 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FIXED VALUE -2.0 WITH TYPE " & STR);
END IF;
IF FLOAT (IDENT (T0)) /= FL0 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FLOAT VALUE 0.0 WITH TYPE " & STR);
END IF;
IF FLOAT (T2) /= FL2 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FLOAT VALUE 2.0 WITH TYPE " & STR);
END IF;
IF FLOAT (IDENT (TN2)) /= FLN2 THEN
FAILED ( "INCORRECT CONVERSION TO " &
"FLOAT VALUE -2.0 WITH TYPE " & STR);
END IF;
END P;
PROCEDURE P1 IS NEW P (SUBINT);
PROCEDURE P2 IS NEW P (SINT1);
PROCEDURE P3 IS NEW P (INT1);
BEGIN
P1 ( "SUBINT" );
P2 ( "SINT" );
P3 ( "INT1" );
END; -- (D).
RESULT;
END CC1221D;
|
package Datos is
type Nodo;
type Lista is access Nodo;
type Nodo is record
Info : Integer;
Sig : Lista;
end record;
end Datos; |
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . B B . C P U _ P R I M I T I V E S --
-- --
-- B o d y --
-- --
-- Copyright (C) 1999-2002 Universidad Politecnica de Madrid --
-- Copyright (C) 2003-2005 The European Space Agency --
-- Copyright (C) 2003-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. --
-- --
-- The port of GNARL to bare board targets was initially developed by the --
-- Real-Time Systems Group at the Technical University of Madrid. --
-- --
------------------------------------------------------------------------------
-- This package implements RISC-V architecture specific support for the GNAT
-- Ravenscar run time.
with System.Multiprocessors;
with System.BB.Threads.Queues;
with System.BB.Board_Support;
with System.BB.CPU_Specific; use System.BB.CPU_Specific;
package body System.BB.CPU_Primitives is
package SSE renames System.Storage_Elements;
use type SSE.Integer_Address;
use type SSE.Storage_Offset;
type Context_Switch_Params is record
Running_Thread_Address : Address;
-- Address of the running thread entry for the current cpu
First_Thread_Address : Address;
-- Address of the first read thread for the current cpu
end record;
pragma Convention (C, Context_Switch_Params);
pragma Suppress_Initialization (Context_Switch_Params);
-- This record describe data that are passed from Pre_Context_Switch
-- to Context_Switch. In the assembly code we take advantage of the ABI
-- so that the data returned are in the registers of the incoming call.
-- So there is no need to copy or to move the data between both calls.
function Pre_Context_Switch return Context_Switch_Params;
pragma Export (Asm, Pre_Context_Switch, "__gnat_pre_context_switch");
-- The full context switch is split in 2 stages:
-- - Pre_Context_Switch: adjust the current priority (but don't modify
-- the MSTATUS.MIE bit), and return the running and first thread queue
-- addresses.
-- - The assembly routine (context_switch) which does the real context
-- switch.
-- When called from interrupt handler, the stack pointer is saved before
-- and restore after the context switch. Therefore the context switch
-- cannot allocate a frame but only assembly code can guarantee that. We
-- also take advantage of this two stage call to extract queue pointers
-- in the Ada code.
------------------------
-- Pre_Context_Switch --
------------------------
function Pre_Context_Switch return Context_Switch_Params is
use System.BB.Threads.Queues;
use System.BB.Threads;
CPU_Id : constant System.Multiprocessors.CPU :=
Board_Support.Multiprocessors.Current_CPU;
New_Priority : constant Integer :=
First_Thread_Table (CPU_Id).Active_Priority;
begin
-- Called with interrupts disabled
-- Set interrupt priority. Unlike the SPARC implementation, the
-- interrupt priority is not part of the context (not in a register).
-- However full interrupt disabling is part of the context switch.
if New_Priority < Interrupt_Priority'Last then
Board_Support.Interrupts.Set_Current_Priority (New_Priority);
end if;
return (Running_Thread_Table (CPU_Id)'Address,
First_Thread_Table (CPU_Id)'Address);
end Pre_Context_Switch;
--------------------
-- Context_Switch --
--------------------
procedure Context_Switch is
procedure Context_Switch_Asm
(Running_Thread_Table_Element_Address : System.Address;
Ready_Thread_Table_Element_Address : System.Address);
pragma Import (Asm, Context_Switch_Asm, "__gnat_context_switch");
-- Real context switch in assembly code
Params : Context_Switch_Params;
begin
-- First set priority and get pointers
Params := Pre_Context_Switch;
-- Then the real context switch
Context_Switch_Asm (Params.Running_Thread_Address,
Params.First_Thread_Address);
end Context_Switch;
------------------------
-- Disable_Interrupts --
------------------------
procedure Disable_Interrupts is
begin
-- Clear the Machine Interrupt Enable (MIE) bit of the mstatus register
Clear_Mstatus_Bits (Mstatus_MIE);
end Disable_Interrupts;
-----------------------
-- Enable_Interrupts --
-----------------------
procedure Enable_Interrupts (Level : Integer) is
begin
if Level /= System.Interrupt_Priority'Last then
Board_Support.Interrupts.Set_Current_Priority (Level);
-- Really enable interrupts
-- Set the Machine Interrupt Enable (MIE) bit of the mstatus register
Set_Mstatus_Bits (Mstatus_MIE);
end if;
end Enable_Interrupts;
----------------------
-- Initialize_Stack --
----------------------
procedure Initialize_Stack
(Base : Address;
Size : Storage_Elements.Storage_Offset;
Stack_Pointer : out Address)
is
use System.Storage_Elements;
Minimum_Stack_Size_In_Bytes : constant Integer_Address :=
CPU_Specific.Stack_Alignment;
Initial_SP : constant System.Address :=
To_Address
(To_Integer (Base + Size) -
Minimum_Stack_Size_In_Bytes);
begin
Stack_Pointer := Initial_SP;
end Initialize_Stack;
------------------------
-- Initialize_Context --
------------------------
procedure Initialize_Context
(Buffer : not null access Context_Buffer;
Program_Counter : System.Address;
Argument : System.Address;
Stack_Pointer : System.Address)
is
procedure Start_Thread_Asm;
pragma Import (Asm, Start_Thread_Asm, "__gnat_start_thread");
Initial_SP : Address;
begin
-- No need to initialize the context of the environment task
if Program_Counter = Null_Address then
return;
end if;
-- We cheat as we don't know the stack size nor the stack base
Initialize_Stack (Stack_Pointer, 0, Initial_SP);
Buffer.RA := Start_Thread_Asm'Address;
Buffer.SP := Initial_SP;
-- Use callee saved registers to make sure the values are loaded during
-- the first context_switch.
Buffer.S1 := Argument;
Buffer.S2 := Program_Counter;
end Initialize_Context;
--------------------
-- Initialize_CPU --
--------------------
procedure Initialize_CPU is
begin
null;
end Initialize_CPU;
----------------------------
-- Install_Error_Handlers --
----------------------------
procedure Install_Error_Handlers is
begin
null;
end Install_Error_Handlers;
end System.BB.CPU_Primitives;
|
package Date is
type T_Mois is
(Janvier, Fevrier, Mars, Avril, Mai, Juin, Juillet, Aout, Septembre,
Octobre, Novembre, Decembre);
type T_Date is record
Jour : Integer; -- {entre 1 et 31}
Mois : T_Mois;
Annee : Integer; -- {positif}
end record;
Date_Incorrecte : exception;
-- Retourne Vrai si D1 < D2.
-- Paramètres :
-- D1 : T_Date
-- D2 : T_Date
-- Assure :
-- retourne Vrai si la relation est vraie et faux sinon.
function D1_Inf_D2 (Date1 : T_Date; Date2 : T_Date) return Boolean;
-- Retourne Vrai si D1 = D2.
-- Paramètres :
-- D1 : T_Date
-- D2 : T_Date
-- Assure :
-- retourne Vrai si la relation est vraie et faux sinon.
function D1_Egal_D2 (Date1 : T_Date; Date2 : T_Date) return Boolean;
-- Crée une date correspondant aux entiers Jour, Mois et Annee donnés.
function Creer_Date
(Jour : Integer; Mois : Integer; Annee : Integer) return T_Date;
end Date;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- C H E C K S --
-- --
-- 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 Debug; use Debug;
with Einfo; use Einfo;
with Errout; use Errout;
with Exp_Ch2; use Exp_Ch2;
with Exp_Pakd; use Exp_Pakd;
with Exp_Util; use Exp_Util;
with Elists; use Elists;
with Eval_Fat; use Eval_Fat;
with Freeze; use Freeze;
with Lib; use Lib;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Output; use Output;
with Restrict; use Restrict;
with Rident; use Rident;
with Rtsfind; use Rtsfind;
with Sem; use Sem;
with Sem_Eval; use Sem_Eval;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch8; use Sem_Ch8;
with Sem_Res; use Sem_Res;
with Sem_Util; use Sem_Util;
with Sem_Warn; use Sem_Warn;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames; use Snames;
with Sprint; use Sprint;
with Stand; use Stand;
with Targparm; use Targparm;
with Tbuild; use Tbuild;
with Ttypes; use Ttypes;
with Urealp; use Urealp;
with Validsw; use Validsw;
package body Checks is
-- General note: many of these routines are concerned with generating
-- checking code to make sure that constraint error is raised at runtime.
-- Clearly this code is only needed if the expander is active, since
-- otherwise we will not be generating code or going into the runtime
-- execution anyway.
-- We therefore disconnect most of these checks if the expander is
-- inactive. This has the additional benefit that we do not need to
-- worry about the tree being messed up by previous errors (since errors
-- turn off expansion anyway).
-- There are a few exceptions to the above rule. For instance routines
-- such as Apply_Scalar_Range_Check that do not insert any code can be
-- safely called even when the Expander is inactive (but Errors_Detected
-- is 0). The benefit of executing this code when expansion is off, is
-- the ability to emit constraint error warning for static expressions
-- even when we are not generating code.
-------------------------------------
-- Suppression of Redundant Checks --
-------------------------------------
-- This unit implements a limited circuit for removal of redundant
-- checks. The processing is based on a tracing of simple sequential
-- flow. For any sequence of statements, we save expressions that are
-- marked to be checked, and then if the same expression appears later
-- with the same check, then under certain circumstances, the second
-- check can be suppressed.
-- Basically, we can suppress the check if we know for certain that
-- the previous expression has been elaborated (together with its
-- check), and we know that the exception frame is the same, and that
-- nothing has happened to change the result of the exception.
-- Let us examine each of these three conditions in turn to describe
-- how we ensure that this condition is met.
-- First, we need to know for certain that the previous expression has
-- been executed. This is done principly by the mechanism of calling
-- Conditional_Statements_Begin at the start of any statement sequence
-- and Conditional_Statements_End at the end. The End call causes all
-- checks remembered since the Begin call to be discarded. This does
-- miss a few cases, notably the case of a nested BEGIN-END block with
-- no exception handlers. But the important thing is to be conservative.
-- The other protection is that all checks are discarded if a label
-- is encountered, since then the assumption of sequential execution
-- is violated, and we don't know enough about the flow.
-- Second, we need to know that the exception frame is the same. We
-- do this by killing all remembered checks when we enter a new frame.
-- Again, that's over-conservative, but generally the cases we can help
-- with are pretty local anyway (like the body of a loop for example).
-- Third, we must be sure to forget any checks which are no longer valid.
-- This is done by two mechanisms, first the Kill_Checks_Variable call is
-- used to note any changes to local variables. We only attempt to deal
-- with checks involving local variables, so we do not need to worry
-- about global variables. Second, a call to any non-global procedure
-- causes us to abandon all stored checks, since such a all may affect
-- the values of any local variables.
-- The following define the data structures used to deal with remembering
-- checks so that redundant checks can be eliminated as described above.
-- Right now, the only expressions that we deal with are of the form of
-- simple local objects (either declared locally, or IN parameters) or
-- such objects plus/minus a compile time known constant. We can do
-- more later on if it seems worthwhile, but this catches many simple
-- cases in practice.
-- The following record type reflects a single saved check. An entry
-- is made in the stack of saved checks if and only if the expression
-- has been elaborated with the indicated checks.
type Saved_Check is record
Killed : Boolean;
-- Set True if entry is killed by Kill_Checks
Entity : Entity_Id;
-- The entity involved in the expression that is checked
Offset : Uint;
-- A compile time value indicating the result of adding or
-- subtracting a compile time value. This value is to be
-- added to the value of the Entity. A value of zero is
-- used for the case of a simple entity reference.
Check_Type : Character;
-- This is set to 'R' for a range check (in which case Target_Type
-- is set to the target type for the range check) or to 'O' for an
-- overflow check (in which case Target_Type is set to Empty).
Target_Type : Entity_Id;
-- Used only if Do_Range_Check is set. Records the target type for
-- the check. We need this, because a check is a duplicate only if
-- it has a the same target type (or more accurately one with a
-- range that is smaller or equal to the stored target type of a
-- saved check).
end record;
-- The following table keeps track of saved checks. Rather than use an
-- extensible table. We just use a table of fixed size, and we discard
-- any saved checks that do not fit. That's very unlikely to happen and
-- this is only an optimization in any case.
Saved_Checks : array (Int range 1 .. 200) of Saved_Check;
-- Array of saved checks
Num_Saved_Checks : Nat := 0;
-- Number of saved checks
-- The following stack keeps track of statement ranges. It is treated
-- as a stack. When Conditional_Statements_Begin is called, an entry
-- is pushed onto this stack containing the value of Num_Saved_Checks
-- at the time of the call. Then when Conditional_Statements_End is
-- called, this value is popped off and used to reset Num_Saved_Checks.
-- Note: again, this is a fixed length stack with a size that should
-- always be fine. If the value of the stack pointer goes above the
-- limit, then we just forget all saved checks.
Saved_Checks_Stack : array (Int range 1 .. 100) of Nat;
Saved_Checks_TOS : Nat := 0;
-----------------------
-- Local Subprograms --
-----------------------
procedure Apply_Float_Conversion_Check
(Ck_Node : Node_Id;
Target_Typ : Entity_Id);
-- The checks on a conversion from a floating-point type to an integer
-- type are delicate. They have to be performed before conversion, they
-- have to raise an exception when the operand is a NaN, and rounding must
-- be taken into account to determine the safe bounds of the operand.
procedure Apply_Selected_Length_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Do_Static : Boolean);
-- This is the subprogram that does all the work for Apply_Length_Check
-- and Apply_Static_Length_Check. Expr, Target_Typ and Source_Typ are as
-- described for the above routines. The Do_Static flag indicates that
-- only a static check is to be done.
procedure Apply_Selected_Range_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Do_Static : Boolean);
-- This is the subprogram that does all the work for Apply_Range_Check.
-- Expr, Target_Typ and Source_Typ are as described for the above
-- routine. The Do_Static flag indicates that only a static check is
-- to be done.
type Check_Type is (Access_Check, Division_Check);
function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean;
-- This function is used to see if an access or division by zero check is
-- needed. The check is to be applied to a single variable appearing in the
-- source, and N is the node for the reference. If N is not of this form,
-- True is returned with no further processing. If N is of the right form,
-- then further processing determines if the given Check is needed.
--
-- The particular circuit is to see if we have the case of a check that is
-- not needed because it appears in the right operand of a short circuited
-- conditional where the left operand guards the check. For example:
--
-- if Var = 0 or else Q / Var > 12 then
-- ...
-- end if;
--
-- In this example, the division check is not required. At the same time
-- we can issue warnings for suspicious use of non-short-circuited forms,
-- such as:
--
-- if Var = 0 or Q / Var > 12 then
-- ...
-- end if;
procedure Find_Check
(Expr : Node_Id;
Check_Type : Character;
Target_Type : Entity_Id;
Entry_OK : out Boolean;
Check_Num : out Nat;
Ent : out Entity_Id;
Ofs : out Uint);
-- This routine is used by Enable_Range_Check and Enable_Overflow_Check
-- to see if a check is of the form for optimization, and if so, to see
-- if it has already been performed. Expr is the expression to check,
-- and Check_Type is 'R' for a range check, 'O' for an overflow check.
-- Target_Type is the target type for a range check, and Empty for an
-- overflow check. If the entry is not of the form for optimization,
-- then Entry_OK is set to False, and the remaining out parameters
-- are undefined. If the entry is OK, then Ent/Ofs are set to the
-- entity and offset from the expression. Check_Num is the number of
-- a matching saved entry in Saved_Checks, or zero if no such entry
-- is located.
function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id;
-- If a discriminal is used in constraining a prival, Return reference
-- to the discriminal of the protected body (which renames the parameter
-- of the enclosing protected operation). This clumsy transformation is
-- needed because privals are created too late and their actual subtypes
-- are not available when analysing the bodies of the protected operations.
-- To be cleaned up???
function Guard_Access
(Cond : Node_Id;
Loc : Source_Ptr;
Ck_Node : Node_Id) return Node_Id;
-- In the access type case, guard the test with a test to ensure
-- that the access value is non-null, since the checks do not
-- not apply to null access values.
procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr);
-- Called by Apply_{Length,Range}_Checks to rewrite the tree with the
-- Constraint_Error node.
function Selected_Length_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Warn_Node : Node_Id) return Check_Result;
-- Like Apply_Selected_Length_Checks, except it doesn't modify
-- anything, just returns a list of nodes as described in the spec of
-- this package for the Range_Check function.
function Selected_Range_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Warn_Node : Node_Id) return Check_Result;
-- Like Apply_Selected_Range_Checks, except it doesn't modify anything,
-- just returns a list of nodes as described in the spec of this package
-- for the Range_Check function.
------------------------------
-- Access_Checks_Suppressed --
------------------------------
function Access_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Access_Check);
else
return Scope_Suppress (Access_Check);
end if;
end Access_Checks_Suppressed;
-------------------------------------
-- Accessibility_Checks_Suppressed --
-------------------------------------
function Accessibility_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Accessibility_Check);
else
return Scope_Suppress (Accessibility_Check);
end if;
end Accessibility_Checks_Suppressed;
-------------------------
-- Append_Range_Checks --
-------------------------
procedure Append_Range_Checks
(Checks : Check_Result;
Stmts : List_Id;
Suppress_Typ : Entity_Id;
Static_Sloc : Source_Ptr;
Flag_Node : Node_Id)
is
Internal_Flag_Node : constant Node_Id := Flag_Node;
Internal_Static_Sloc : constant Source_Ptr := Static_Sloc;
Checks_On : constant Boolean :=
(not Index_Checks_Suppressed (Suppress_Typ))
or else
(not Range_Checks_Suppressed (Suppress_Typ));
begin
-- For now we just return if Checks_On is false, however this should
-- be enhanced to check for an always True value in the condition
-- and to generate a compilation warning???
if not Checks_On then
return;
end if;
for J in 1 .. 2 loop
exit when No (Checks (J));
if Nkind (Checks (J)) = N_Raise_Constraint_Error
and then Present (Condition (Checks (J)))
then
if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
Append_To (Stmts, Checks (J));
Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
end if;
else
Append_To
(Stmts,
Make_Raise_Constraint_Error (Internal_Static_Sloc,
Reason => CE_Range_Check_Failed));
end if;
end loop;
end Append_Range_Checks;
------------------------
-- Apply_Access_Check --
------------------------
procedure Apply_Access_Check (N : Node_Id) is
P : constant Node_Id := Prefix (N);
begin
-- We do not need checks if we are not generating code (i.e. the
-- expander is not active). This is not just an optimization, there
-- are cases (e.g. with pragma Debug) where generating the checks
-- can cause real trouble).
if not Expander_Active then
return;
end if;
-- No check if short circuiting makes check unnecessary
if not Check_Needed (P, Access_Check) then
return;
end if;
-- Otherwise go ahead and install the check
Install_Null_Excluding_Check (P);
end Apply_Access_Check;
-------------------------------
-- Apply_Accessibility_Check --
-------------------------------
procedure Apply_Accessibility_Check (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
Param_Ent : constant Entity_Id := Param_Entity (N);
Param_Level : Node_Id;
Type_Level : Node_Id;
begin
if Inside_A_Generic then
return;
-- Only apply the run-time check if the access parameter
-- has an associated extra access level parameter and
-- when the level of the type is less deep than the level
-- of the access parameter.
elsif Present (Param_Ent)
and then Present (Extra_Accessibility (Param_Ent))
and then UI_Gt (Object_Access_Level (N),
Type_Access_Level (Typ))
and then not Accessibility_Checks_Suppressed (Param_Ent)
and then not Accessibility_Checks_Suppressed (Typ)
then
Param_Level :=
New_Occurrence_Of (Extra_Accessibility (Param_Ent), Loc);
Type_Level :=
Make_Integer_Literal (Loc, Type_Access_Level (Typ));
-- Raise Program_Error if the accessibility level of the the access
-- parameter is deeper than the level of the target access type.
Insert_Action (N,
Make_Raise_Program_Error (Loc,
Condition =>
Make_Op_Gt (Loc,
Left_Opnd => Param_Level,
Right_Opnd => Type_Level),
Reason => PE_Accessibility_Check_Failed));
Analyze_And_Resolve (N);
end if;
end Apply_Accessibility_Check;
---------------------------
-- Apply_Alignment_Check --
---------------------------
procedure Apply_Alignment_Check (E : Entity_Id; N : Node_Id) is
AC : constant Node_Id := Address_Clause (E);
Typ : constant Entity_Id := Etype (E);
Expr : Node_Id;
Loc : Source_Ptr;
Alignment_Required : constant Boolean := Maximum_Alignment > 1;
-- Constant to show whether target requires alignment checks
begin
-- See if check needed. Note that we never need a check if the
-- maximum alignment is one, since the check will always succeed
if No (AC)
or else not Check_Address_Alignment (AC)
or else not Alignment_Required
then
return;
end if;
Loc := Sloc (AC);
Expr := Expression (AC);
if Nkind (Expr) = N_Unchecked_Type_Conversion then
Expr := Expression (Expr);
elsif Nkind (Expr) = N_Function_Call
and then Is_Entity_Name (Name (Expr))
and then Is_RTE (Entity (Name (Expr)), RE_To_Address)
then
Expr := First (Parameter_Associations (Expr));
if Nkind (Expr) = N_Parameter_Association then
Expr := Explicit_Actual_Parameter (Expr);
end if;
end if;
-- Here Expr is the address value. See if we know that the
-- value is unacceptable at compile time.
if Compile_Time_Known_Value (Expr)
and then (Known_Alignment (E) or else Known_Alignment (Typ))
then
declare
AL : Uint := Alignment (Typ);
begin
-- The object alignment might be more restrictive than the
-- type alignment.
if Known_Alignment (E) then
AL := Alignment (E);
end if;
if Expr_Value (Expr) mod AL /= 0 then
Insert_Action (N,
Make_Raise_Program_Error (Loc,
Reason => PE_Misaligned_Address_Value));
Error_Msg_NE
("?specified address for& not " &
"consistent with alignment ('R'M 13.3(27))", Expr, E);
end if;
end;
-- Here we do not know if the value is acceptable, generate
-- code to raise PE if alignment is inappropriate.
else
-- Skip generation of this code if we don't want elab code
if not Restriction_Active (No_Elaboration_Code) then
Insert_After_And_Analyze (N,
Make_Raise_Program_Error (Loc,
Condition =>
Make_Op_Ne (Loc,
Left_Opnd =>
Make_Op_Mod (Loc,
Left_Opnd =>
Unchecked_Convert_To
(RTE (RE_Integer_Address),
Duplicate_Subexpr_No_Checks (Expr)),
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (E, Loc),
Attribute_Name => Name_Alignment)),
Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
Reason => PE_Misaligned_Address_Value),
Suppress => All_Checks);
end if;
end if;
return;
exception
when RE_Not_Available =>
return;
end Apply_Alignment_Check;
-------------------------------------
-- Apply_Arithmetic_Overflow_Check --
-------------------------------------
-- This routine is called only if the type is an integer type, and
-- a software arithmetic overflow check must be performed for op
-- (add, subtract, multiply). The check is performed only if
-- Software_Overflow_Checking is enabled and Do_Overflow_Check
-- is set. In this case we expand the operation into a more complex
-- sequence of tests that ensures that overflow is properly caught.
procedure Apply_Arithmetic_Overflow_Check (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
Rtyp : constant Entity_Id := Root_Type (Typ);
Siz : constant Int := UI_To_Int (Esize (Rtyp));
Dsiz : constant Int := Siz * 2;
Opnod : Node_Id;
Ctyp : Entity_Id;
Opnd : Node_Id;
Cent : RE_Id;
begin
-- Skip this if overflow checks are done in back end, or the overflow
-- flag is not set anyway, or we are not doing code expansion.
if Backend_Overflow_Checks_On_Target
or else not Do_Overflow_Check (N)
or else not Expander_Active
then
return;
end if;
-- Otherwise, we generate the full general code for front end overflow
-- detection, which works by doing arithmetic in a larger type:
-- x op y
-- is expanded into
-- Typ (Checktyp (x) op Checktyp (y));
-- where Typ is the type of the original expression, and Checktyp is
-- an integer type of sufficient length to hold the largest possible
-- result.
-- In the case where check type exceeds the size of Long_Long_Integer,
-- we use a different approach, expanding to:
-- typ (xxx_With_Ovflo_Check (Integer_64 (x), Integer (y)))
-- where xxx is Add, Multiply or Subtract as appropriate
-- Find check type if one exists
if Dsiz <= Standard_Integer_Size then
Ctyp := Standard_Integer;
elsif Dsiz <= Standard_Long_Long_Integer_Size then
Ctyp := Standard_Long_Long_Integer;
-- No check type exists, use runtime call
else
if Nkind (N) = N_Op_Add then
Cent := RE_Add_With_Ovflo_Check;
elsif Nkind (N) = N_Op_Multiply then
Cent := RE_Multiply_With_Ovflo_Check;
else
pragma Assert (Nkind (N) = N_Op_Subtract);
Cent := RE_Subtract_With_Ovflo_Check;
end if;
Rewrite (N,
OK_Convert_To (Typ,
Make_Function_Call (Loc,
Name => New_Reference_To (RTE (Cent), Loc),
Parameter_Associations => New_List (
OK_Convert_To (RTE (RE_Integer_64), Left_Opnd (N)),
OK_Convert_To (RTE (RE_Integer_64), Right_Opnd (N))))));
Analyze_And_Resolve (N, Typ);
return;
end if;
-- If we fall through, we have the case where we do the arithmetic in
-- the next higher type and get the check by conversion. In these cases
-- Ctyp is set to the type to be used as the check type.
Opnod := Relocate_Node (N);
Opnd := OK_Convert_To (Ctyp, Left_Opnd (Opnod));
Analyze (Opnd);
Set_Etype (Opnd, Ctyp);
Set_Analyzed (Opnd, True);
Set_Left_Opnd (Opnod, Opnd);
Opnd := OK_Convert_To (Ctyp, Right_Opnd (Opnod));
Analyze (Opnd);
Set_Etype (Opnd, Ctyp);
Set_Analyzed (Opnd, True);
Set_Right_Opnd (Opnod, Opnd);
-- The type of the operation changes to the base type of the check
-- type, and we reset the overflow check indication, since clearly
-- no overflow is possible now that we are using a double length
-- type. We also set the Analyzed flag to avoid a recursive attempt
-- to expand the node.
Set_Etype (Opnod, Base_Type (Ctyp));
Set_Do_Overflow_Check (Opnod, False);
Set_Analyzed (Opnod, True);
-- Now build the outer conversion
Opnd := OK_Convert_To (Typ, Opnod);
Analyze (Opnd);
Set_Etype (Opnd, Typ);
-- In the discrete type case, we directly generate the range check
-- for the outer operand. This range check will implement the required
-- overflow check.
if Is_Discrete_Type (Typ) then
Rewrite (N, Opnd);
Generate_Range_Check (Expression (N), Typ, CE_Overflow_Check_Failed);
-- For other types, we enable overflow checking on the conversion,
-- after setting the node as analyzed to prevent recursive attempts
-- to expand the conversion node.
else
Set_Analyzed (Opnd, True);
Enable_Overflow_Check (Opnd);
Rewrite (N, Opnd);
end if;
exception
when RE_Not_Available =>
return;
end Apply_Arithmetic_Overflow_Check;
----------------------------
-- Apply_Array_Size_Check --
----------------------------
-- The situation is as follows. In GNAT 3 (GCC 2.x), the size in bits
-- is computed in 32 bits without an overflow check. That's a real
-- problem for Ada. So what we do in GNAT 3 is to approximate the
-- size of an array by manually multiplying the element size by the
-- number of elements, and comparing that against the allowed limits.
-- In GNAT 5, the size in byte is still computed in 32 bits without
-- an overflow check in the dynamic case, but the size in bits is
-- computed in 64 bits. We assume that's good enough, and we do not
-- bother to generate any front end test.
procedure Apply_Array_Size_Check (N : Node_Id; Typ : Entity_Id) is
Loc : constant Source_Ptr := Sloc (N);
Ctyp : constant Entity_Id := Component_Type (Typ);
Ent : constant Entity_Id := Defining_Identifier (N);
Decl : Node_Id;
Lo : Node_Id;
Hi : Node_Id;
Lob : Uint;
Hib : Uint;
Siz : Uint;
Xtyp : Entity_Id;
Indx : Node_Id;
Sizx : Node_Id;
Code : Node_Id;
Static : Boolean := True;
-- Set false if any index subtye bound is non-static
Umark : constant Uintp.Save_Mark := Uintp.Mark;
-- We can throw away all the Uint computations here, since they are
-- done only to generate boolean test results.
Check_Siz : Uint;
-- Size to check against
function Is_Address_Or_Import (Decl : Node_Id) return Boolean;
-- Determines if Decl is an address clause or Import/Interface pragma
-- that references the defining identifier of the current declaration.
--------------------------
-- Is_Address_Or_Import --
--------------------------
function Is_Address_Or_Import (Decl : Node_Id) return Boolean is
begin
if Nkind (Decl) = N_At_Clause then
return Chars (Identifier (Decl)) = Chars (Ent);
elsif Nkind (Decl) = N_Attribute_Definition_Clause then
return
Chars (Decl) = Name_Address
and then
Nkind (Name (Decl)) = N_Identifier
and then
Chars (Name (Decl)) = Chars (Ent);
elsif Nkind (Decl) = N_Pragma then
if (Chars (Decl) = Name_Import
or else
Chars (Decl) = Name_Interface)
and then Present (Pragma_Argument_Associations (Decl))
then
declare
F : constant Node_Id :=
First (Pragma_Argument_Associations (Decl));
begin
return
Present (F)
and then
Present (Next (F))
and then
Nkind (Expression (Next (F))) = N_Identifier
and then
Chars (Expression (Next (F))) = Chars (Ent);
end;
else
return False;
end if;
else
return False;
end if;
end Is_Address_Or_Import;
-- Start of processing for Apply_Array_Size_Check
begin
-- Do size check on local arrays. We only need this in the GCC 2
-- case, since in GCC 3, we expect the back end to properly handle
-- things. This routine can be removed when we baseline GNAT 3.
if Opt.GCC_Version >= 3 then
return;
end if;
-- No need for a check if not expanding
if not Expander_Active then
return;
end if;
-- No need for a check if checks are suppressed
if Storage_Checks_Suppressed (Typ) then
return;
end if;
-- It is pointless to insert this check inside an init proc, because
-- that's too late, we have already built the object to be the right
-- size, and if it's too large, too bad!
if Inside_Init_Proc then
return;
end if;
-- Look head for pragma interface/import or address clause applying
-- to this entity. If found, we suppress the check entirely. For now
-- we only look ahead 20 declarations to stop this becoming too slow
-- Note that eventually this whole routine gets moved to gigi.
Decl := N;
for Ctr in 1 .. 20 loop
Next (Decl);
exit when No (Decl);
if Is_Address_Or_Import (Decl) then
return;
end if;
end loop;
-- First step is to calculate the maximum number of elements. For
-- this calculation, we use the actual size of the subtype if it is
-- static, and if a bound of a subtype is non-static, we go to the
-- bound of the base type.
Siz := Uint_1;
Indx := First_Index (Typ);
while Present (Indx) loop
Xtyp := Etype (Indx);
Lo := Type_Low_Bound (Xtyp);
Hi := Type_High_Bound (Xtyp);
-- If any bound raises constraint error, we will never get this
-- far, so there is no need to generate any kind of check.
if Raises_Constraint_Error (Lo)
or else
Raises_Constraint_Error (Hi)
then
Uintp.Release (Umark);
return;
end if;
-- Otherwise get bounds values
if Is_Static_Expression (Lo) then
Lob := Expr_Value (Lo);
else
Lob := Expr_Value (Type_Low_Bound (Base_Type (Xtyp)));
Static := False;
end if;
if Is_Static_Expression (Hi) then
Hib := Expr_Value (Hi);
else
Hib := Expr_Value (Type_High_Bound (Base_Type (Xtyp)));
Static := False;
end if;
Siz := Siz * UI_Max (Hib - Lob + 1, Uint_0);
Next_Index (Indx);
end loop;
-- Compute the limit against which we want to check. For subprograms,
-- where the array will go on the stack, we use 8*2**24, which (in
-- bits) is the size of a 16 megabyte array.
if Is_Subprogram (Scope (Ent)) then
Check_Siz := Uint_2 ** 27;
else
Check_Siz := Uint_2 ** 31;
end if;
-- If we have all static bounds and Siz is too large, then we know
-- we know we have a storage error right now, so generate message
if Static and then Siz >= Check_Siz then
Insert_Action (N,
Make_Raise_Storage_Error (Loc,
Reason => SE_Object_Too_Large));
Error_Msg_N ("?Storage_Error will be raised at run-time", N);
Uintp.Release (Umark);
return;
end if;
-- Case of component size known at compile time. If the array
-- size is definitely in range, then we do not need a check.
if Known_Esize (Ctyp)
and then Siz * Esize (Ctyp) < Check_Siz
then
Uintp.Release (Umark);
return;
end if;
-- Here if a dynamic check is required
-- What we do is to build an expression for the size of the array,
-- which is computed as the 'Size of the array component, times
-- the size of each dimension.
Uintp.Release (Umark);
Sizx :=
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Ctyp, Loc),
Attribute_Name => Name_Size);
Indx := First_Index (Typ);
for J in 1 .. Number_Dimensions (Typ) loop
if Sloc (Etype (Indx)) = Sloc (N) then
Ensure_Defined (Etype (Indx), N);
end if;
Sizx :=
Make_Op_Multiply (Loc,
Left_Opnd => Sizx,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Typ, Loc),
Attribute_Name => Name_Length,
Expressions => New_List (
Make_Integer_Literal (Loc, J))));
Next_Index (Indx);
end loop;
-- Emit the check
Code :=
Make_Raise_Storage_Error (Loc,
Condition =>
Make_Op_Ge (Loc,
Left_Opnd => Sizx,
Right_Opnd =>
Make_Integer_Literal (Loc,
Intval => Check_Siz)),
Reason => SE_Object_Too_Large);
Set_Size_Check_Code (Defining_Identifier (N), Code);
Insert_Action (N, Code, Suppress => All_Checks);
end Apply_Array_Size_Check;
----------------------------
-- Apply_Constraint_Check --
----------------------------
procedure Apply_Constraint_Check
(N : Node_Id;
Typ : Entity_Id;
No_Sliding : Boolean := False)
is
Desig_Typ : Entity_Id;
begin
if Inside_A_Generic then
return;
elsif Is_Scalar_Type (Typ) then
Apply_Scalar_Range_Check (N, Typ);
elsif Is_Array_Type (Typ) then
-- A useful optimization: an aggregate with only an others clause
-- always has the right bounds.
if Nkind (N) = N_Aggregate
and then No (Expressions (N))
and then Nkind
(First (Choices (First (Component_Associations (N)))))
= N_Others_Choice
then
return;
end if;
if Is_Constrained (Typ) then
Apply_Length_Check (N, Typ);
if No_Sliding then
Apply_Range_Check (N, Typ);
end if;
else
Apply_Range_Check (N, Typ);
end if;
elsif (Is_Record_Type (Typ)
or else Is_Private_Type (Typ))
and then Has_Discriminants (Base_Type (Typ))
and then Is_Constrained (Typ)
then
Apply_Discriminant_Check (N, Typ);
elsif Is_Access_Type (Typ) then
Desig_Typ := Designated_Type (Typ);
-- No checks necessary if expression statically null
if Nkind (N) = N_Null then
null;
-- No sliding possible on access to arrays
elsif Is_Array_Type (Desig_Typ) then
if Is_Constrained (Desig_Typ) then
Apply_Length_Check (N, Typ);
end if;
Apply_Range_Check (N, Typ);
elsif Has_Discriminants (Base_Type (Desig_Typ))
and then Is_Constrained (Desig_Typ)
then
Apply_Discriminant_Check (N, Typ);
end if;
if Can_Never_Be_Null (Typ)
and then not Can_Never_Be_Null (Etype (N))
then
Install_Null_Excluding_Check (N);
end if;
end if;
end Apply_Constraint_Check;
------------------------------
-- Apply_Discriminant_Check --
------------------------------
procedure Apply_Discriminant_Check
(N : Node_Id;
Typ : Entity_Id;
Lhs : Node_Id := Empty)
is
Loc : constant Source_Ptr := Sloc (N);
Do_Access : constant Boolean := Is_Access_Type (Typ);
S_Typ : Entity_Id := Etype (N);
Cond : Node_Id;
T_Typ : Entity_Id;
function Is_Aliased_Unconstrained_Component return Boolean;
-- It is possible for an aliased component to have a nominal
-- unconstrained subtype (through instantiation). If this is a
-- discriminated component assigned in the expansion of an aggregate
-- in an initialization, the check must be suppressed. This unusual
-- situation requires a predicate of its own (see 7503-008).
----------------------------------------
-- Is_Aliased_Unconstrained_Component --
----------------------------------------
function Is_Aliased_Unconstrained_Component return Boolean is
Comp : Entity_Id;
Pref : Node_Id;
begin
if Nkind (Lhs) /= N_Selected_Component then
return False;
else
Comp := Entity (Selector_Name (Lhs));
Pref := Prefix (Lhs);
end if;
if Ekind (Comp) /= E_Component
or else not Is_Aliased (Comp)
then
return False;
end if;
return not Comes_From_Source (Pref)
and then In_Instance
and then not Is_Constrained (Etype (Comp));
end Is_Aliased_Unconstrained_Component;
-- Start of processing for Apply_Discriminant_Check
begin
if Do_Access then
T_Typ := Designated_Type (Typ);
else
T_Typ := Typ;
end if;
-- Nothing to do if discriminant checks are suppressed or else no code
-- is to be generated
if not Expander_Active
or else Discriminant_Checks_Suppressed (T_Typ)
then
return;
end if;
-- No discriminant checks necessary for an access when expression
-- is statically Null. This is not only an optimization, this is
-- fundamental because otherwise discriminant checks may be generated
-- in init procs for types containing an access to a not-yet-frozen
-- record, causing a deadly forward reference.
-- Also, if the expression is of an access type whose designated
-- type is incomplete, then the access value must be null and
-- we suppress the check.
if Nkind (N) = N_Null then
return;
elsif Is_Access_Type (S_Typ) then
S_Typ := Designated_Type (S_Typ);
if Ekind (S_Typ) = E_Incomplete_Type then
return;
end if;
end if;
-- If an assignment target is present, then we need to generate
-- the actual subtype if the target is a parameter or aliased
-- object with an unconstrained nominal subtype.
if Present (Lhs)
and then (Present (Param_Entity (Lhs))
or else (not Is_Constrained (T_Typ)
and then Is_Aliased_View (Lhs)
and then not Is_Aliased_Unconstrained_Component))
then
T_Typ := Get_Actual_Subtype (Lhs);
end if;
-- Nothing to do if the type is unconstrained (this is the case
-- where the actual subtype in the RM sense of N is unconstrained
-- and no check is required).
if not Is_Constrained (T_Typ) then
return;
-- Ada 2005: nothing to do if the type is one for which there is a
-- partial view that is constrained.
elsif Ada_Version >= Ada_05
and then Has_Constrained_Partial_View (Base_Type (T_Typ))
then
return;
end if;
-- Nothing to do if the type is an Unchecked_Union
if Is_Unchecked_Union (Base_Type (T_Typ)) then
return;
end if;
-- Suppress checks if the subtypes are the same.
-- the check must be preserved in an assignment to a formal, because
-- the constraint is given by the actual.
if Nkind (Original_Node (N)) /= N_Allocator
and then (No (Lhs)
or else not Is_Entity_Name (Lhs)
or else No (Param_Entity (Lhs)))
then
if (Etype (N) = Typ
or else (Do_Access and then Designated_Type (Typ) = S_Typ))
and then not Is_Aliased_View (Lhs)
then
return;
end if;
-- We can also eliminate checks on allocators with a subtype mark
-- that coincides with the context type. The context type may be a
-- subtype without a constraint (common case, a generic actual).
elsif Nkind (Original_Node (N)) = N_Allocator
and then Is_Entity_Name (Expression (Original_Node (N)))
then
declare
Alloc_Typ : constant Entity_Id :=
Entity (Expression (Original_Node (N)));
begin
if Alloc_Typ = T_Typ
or else (Nkind (Parent (T_Typ)) = N_Subtype_Declaration
and then Is_Entity_Name (
Subtype_Indication (Parent (T_Typ)))
and then Alloc_Typ = Base_Type (T_Typ))
then
return;
end if;
end;
end if;
-- See if we have a case where the types are both constrained, and
-- all the constraints are constants. In this case, we can do the
-- check successfully at compile time.
-- We skip this check for the case where the node is a rewritten`
-- allocator, because it already carries the context subtype, and
-- extracting the discriminants from the aggregate is messy.
if Is_Constrained (S_Typ)
and then Nkind (Original_Node (N)) /= N_Allocator
then
declare
DconT : Elmt_Id;
Discr : Entity_Id;
DconS : Elmt_Id;
ItemS : Node_Id;
ItemT : Node_Id;
begin
-- S_Typ may not have discriminants in the case where it is a
-- private type completed by a default discriminated type. In
-- that case, we need to get the constraints from the
-- underlying_type. If the underlying type is unconstrained (i.e.
-- has no default discriminants) no check is needed.
if Has_Discriminants (S_Typ) then
Discr := First_Discriminant (S_Typ);
DconS := First_Elmt (Discriminant_Constraint (S_Typ));
else
Discr := First_Discriminant (Underlying_Type (S_Typ));
DconS :=
First_Elmt
(Discriminant_Constraint (Underlying_Type (S_Typ)));
if No (DconS) then
return;
end if;
-- A further optimization: if T_Typ is derived from S_Typ
-- without imposing a constraint, no check is needed.
if Nkind (Original_Node (Parent (T_Typ))) =
N_Full_Type_Declaration
then
declare
Type_Def : constant Node_Id :=
Type_Definition
(Original_Node (Parent (T_Typ)));
begin
if Nkind (Type_Def) = N_Derived_Type_Definition
and then Is_Entity_Name (Subtype_Indication (Type_Def))
and then Entity (Subtype_Indication (Type_Def)) = S_Typ
then
return;
end if;
end;
end if;
end if;
DconT := First_Elmt (Discriminant_Constraint (T_Typ));
while Present (Discr) loop
ItemS := Node (DconS);
ItemT := Node (DconT);
exit when
not Is_OK_Static_Expression (ItemS)
or else
not Is_OK_Static_Expression (ItemT);
if Expr_Value (ItemS) /= Expr_Value (ItemT) then
if Do_Access then -- needs run-time check.
exit;
else
Apply_Compile_Time_Constraint_Error
(N, "incorrect value for discriminant&?",
CE_Discriminant_Check_Failed, Ent => Discr);
return;
end if;
end if;
Next_Elmt (DconS);
Next_Elmt (DconT);
Next_Discriminant (Discr);
end loop;
if No (Discr) then
return;
end if;
end;
end if;
-- Here we need a discriminant check. First build the expression
-- for the comparisons of the discriminants:
-- (n.disc1 /= typ.disc1) or else
-- (n.disc2 /= typ.disc2) or else
-- ...
-- (n.discn /= typ.discn)
Cond := Build_Discriminant_Checks (N, T_Typ);
-- If Lhs is set and is a parameter, then the condition is
-- guarded by: lhs'constrained and then (condition built above)
if Present (Param_Entity (Lhs)) then
Cond :=
Make_And_Then (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Param_Entity (Lhs), Loc),
Attribute_Name => Name_Constrained),
Right_Opnd => Cond);
end if;
if Do_Access then
Cond := Guard_Access (Cond, Loc, N);
end if;
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition => Cond,
Reason => CE_Discriminant_Check_Failed));
end Apply_Discriminant_Check;
------------------------
-- Apply_Divide_Check --
------------------------
procedure Apply_Divide_Check (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
Left : constant Node_Id := Left_Opnd (N);
Right : constant Node_Id := Right_Opnd (N);
LLB : Uint;
Llo : Uint;
Lhi : Uint;
LOK : Boolean;
Rlo : Uint;
Rhi : Uint;
ROK : Boolean;
begin
if Expander_Active
and then not Backend_Divide_Checks_On_Target
and then Check_Needed (Right, Division_Check)
then
Determine_Range (Right, ROK, Rlo, Rhi);
-- See if division by zero possible, and if so generate test. This
-- part of the test is not controlled by the -gnato switch.
if Do_Division_Check (N) then
if (not ROK) or else (Rlo <= 0 and then 0 <= Rhi) then
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Op_Eq (Loc,
Left_Opnd => Duplicate_Subexpr_Move_Checks (Right),
Right_Opnd => Make_Integer_Literal (Loc, 0)),
Reason => CE_Divide_By_Zero));
end if;
end if;
-- Test for extremely annoying case of xxx'First divided by -1
if Do_Overflow_Check (N) then
if Nkind (N) = N_Op_Divide
and then Is_Signed_Integer_Type (Typ)
then
Determine_Range (Left, LOK, Llo, Lhi);
LLB := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
if ((not ROK) or else (Rlo <= (-1) and then (-1) <= Rhi))
and then
((not LOK) or else (Llo = LLB))
then
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_And_Then (Loc,
Make_Op_Eq (Loc,
Left_Opnd =>
Duplicate_Subexpr_Move_Checks (Left),
Right_Opnd => Make_Integer_Literal (Loc, LLB)),
Make_Op_Eq (Loc,
Left_Opnd =>
Duplicate_Subexpr (Right),
Right_Opnd =>
Make_Integer_Literal (Loc, -1))),
Reason => CE_Overflow_Check_Failed));
end if;
end if;
end if;
end if;
end Apply_Divide_Check;
----------------------------------
-- Apply_Float_Conversion_Check --
----------------------------------
-- Let F and I be the source and target types of the conversion.
-- The Ada standard specifies that a floating-point value X is rounded
-- to the nearest integer, with halfway cases being rounded away from
-- zero. The rounded value of X is checked against I'Range.
-- The catch in the above paragraph is that there is no good way
-- to know whether the round-to-integer operation resulted in
-- overflow. A remedy is to perform a range check in the floating-point
-- domain instead, however:
-- (1) The bounds may not be known at compile time
-- (2) The check must take into account possible rounding.
-- (3) The range of type I may not be exactly representable in F.
-- (4) The end-points I'First - 0.5 and I'Last + 0.5 may or may
-- not be in range, depending on the sign of I'First and I'Last.
-- (5) X may be a NaN, which will fail any comparison
-- The following steps take care of these issues converting X:
-- (1) If either I'First or I'Last is not known at compile time, use
-- I'Base instead of I in the next three steps and perform a
-- regular range check against I'Range after conversion.
-- (2) If I'First - 0.5 is representable in F then let Lo be that
-- value and define Lo_OK as (I'First > 0). Otherwise, let Lo be
-- F'Machine (T) and let Lo_OK be (Lo >= I'First). In other words,
-- take one of the closest floating-point numbers to T, and see if
-- it is in range or not.
-- (3) If I'Last + 0.5 is representable in F then let Hi be that value
-- and define Hi_OK as (I'Last < 0). Otherwise, let Hi be
-- F'Rounding (T) and let Hi_OK be (Hi <= I'Last).
-- (4) Raise CE when (Lo_OK and X < Lo) or (not Lo_OK and X <= Lo)
-- or (Hi_OK and X > Hi) or (not Hi_OK and X >= Hi)
procedure Apply_Float_Conversion_Check
(Ck_Node : Node_Id;
Target_Typ : Entity_Id)
is
LB : constant Node_Id := Type_Low_Bound (Target_Typ);
HB : constant Node_Id := Type_High_Bound (Target_Typ);
Loc : constant Source_Ptr := Sloc (Ck_Node);
Expr_Type : constant Entity_Id := Base_Type (Etype (Ck_Node));
Target_Base : constant Entity_Id := Implementation_Base_Type
(Target_Typ);
Max_Bound : constant Uint := UI_Expon
(Machine_Radix (Expr_Type),
Machine_Mantissa (Expr_Type) - 1) - 1;
-- Largest bound, so bound plus or minus half is a machine number of F
Ifirst,
Ilast : Uint; -- Bounds of integer type
Lo, Hi : Ureal; -- Bounds to check in floating-point domain
Lo_OK,
Hi_OK : Boolean; -- True iff Lo resp. Hi belongs to I'Range
Lo_Chk,
Hi_Chk : Node_Id; -- Expressions that are False iff check fails
Reason : RT_Exception_Code;
begin
if not Compile_Time_Known_Value (LB)
or not Compile_Time_Known_Value (HB)
then
declare
-- First check that the value falls in the range of the base
-- type, to prevent overflow during conversion and then
-- perform a regular range check against the (dynamic) bounds.
Par : constant Node_Id := Parent (Ck_Node);
pragma Assert (Target_Base /= Target_Typ);
pragma Assert (Nkind (Par) = N_Type_Conversion);
Temp : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => New_Internal_Name ('T'));
begin
Apply_Float_Conversion_Check (Ck_Node, Target_Base);
Set_Etype (Temp, Target_Base);
Insert_Action (Parent (Par),
Make_Object_Declaration (Loc,
Defining_Identifier => Temp,
Object_Definition => New_Occurrence_Of (Target_Typ, Loc),
Expression => New_Copy_Tree (Par)),
Suppress => All_Checks);
Insert_Action (Par,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Not_In (Loc,
Left_Opnd => New_Occurrence_Of (Temp, Loc),
Right_Opnd => New_Occurrence_Of (Target_Typ, Loc)),
Reason => CE_Range_Check_Failed));
Rewrite (Par, New_Occurrence_Of (Temp, Loc));
return;
end;
end if;
-- Get the bounds of the target type
Ifirst := Expr_Value (LB);
Ilast := Expr_Value (HB);
-- Check against lower bound
if abs (Ifirst) < Max_Bound then
Lo := UR_From_Uint (Ifirst) - Ureal_Half;
Lo_OK := (Ifirst > 0);
else
Lo := Machine (Expr_Type, UR_From_Uint (Ifirst), Round_Even, Ck_Node);
Lo_OK := (Lo >= UR_From_Uint (Ifirst));
end if;
if Lo_OK then
-- Lo_Chk := (X >= Lo)
Lo_Chk := Make_Op_Ge (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
Right_Opnd => Make_Real_Literal (Loc, Lo));
else
-- Lo_Chk := (X > Lo)
Lo_Chk := Make_Op_Gt (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
Right_Opnd => Make_Real_Literal (Loc, Lo));
end if;
-- Check against higher bound
if abs (Ilast) < Max_Bound then
Hi := UR_From_Uint (Ilast) + Ureal_Half;
Hi_OK := (Ilast < 0);
else
Hi := Machine (Expr_Type, UR_From_Uint (Ilast), Round_Even, Ck_Node);
Hi_OK := (Hi <= UR_From_Uint (Ilast));
end if;
if Hi_OK then
-- Hi_Chk := (X <= Hi)
Hi_Chk := Make_Op_Le (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
Right_Opnd => Make_Real_Literal (Loc, Hi));
else
-- Hi_Chk := (X < Hi)
Hi_Chk := Make_Op_Lt (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
Right_Opnd => Make_Real_Literal (Loc, Hi));
end if;
-- If the bounds of the target type are the same as those of the
-- base type, the check is an overflow check as a range check is
-- not performed in these cases.
if Expr_Value (Type_Low_Bound (Target_Base)) = Ifirst
and then Expr_Value (Type_High_Bound (Target_Base)) = Ilast
then
Reason := CE_Overflow_Check_Failed;
else
Reason := CE_Range_Check_Failed;
end if;
-- Raise CE if either conditions does not hold
Insert_Action (Ck_Node,
Make_Raise_Constraint_Error (Loc,
Condition => Make_Op_Not (Loc, Make_And_Then (Loc, Lo_Chk, Hi_Chk)),
Reason => Reason));
end Apply_Float_Conversion_Check;
------------------------
-- Apply_Length_Check --
------------------------
procedure Apply_Length_Check
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id := Empty)
is
begin
Apply_Selected_Length_Checks
(Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
end Apply_Length_Check;
-----------------------
-- Apply_Range_Check --
-----------------------
procedure Apply_Range_Check
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id := Empty)
is
begin
Apply_Selected_Range_Checks
(Ck_Node, Target_Typ, Source_Typ, Do_Static => False);
end Apply_Range_Check;
------------------------------
-- Apply_Scalar_Range_Check --
------------------------------
-- Note that Apply_Scalar_Range_Check never turns the Do_Range_Check
-- flag off if it is already set on.
procedure Apply_Scalar_Range_Check
(Expr : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id := Empty;
Fixed_Int : Boolean := False)
is
Parnt : constant Node_Id := Parent (Expr);
S_Typ : Entity_Id;
Arr : Node_Id := Empty; -- initialize to prevent warning
Arr_Typ : Entity_Id := Empty; -- initialize to prevent warning
OK : Boolean;
Is_Subscr_Ref : Boolean;
-- Set true if Expr is a subscript
Is_Unconstrained_Subscr_Ref : Boolean;
-- Set true if Expr is a subscript of an unconstrained array. In this
-- case we do not attempt to do an analysis of the value against the
-- range of the subscript, since we don't know the actual subtype.
Int_Real : Boolean;
-- Set to True if Expr should be regarded as a real value
-- even though the type of Expr might be discrete.
procedure Bad_Value;
-- Procedure called if value is determined to be out of range
---------------
-- Bad_Value --
---------------
procedure Bad_Value is
begin
Apply_Compile_Time_Constraint_Error
(Expr, "value not in range of}?", CE_Range_Check_Failed,
Ent => Target_Typ,
Typ => Target_Typ);
end Bad_Value;
-- Start of processing for Apply_Scalar_Range_Check
begin
if Inside_A_Generic then
return;
-- Return if check obviously not needed. Note that we do not check
-- for the expander being inactive, since this routine does not
-- insert any code, but it does generate useful warnings sometimes,
-- which we would like even if we are in semantics only mode.
elsif Target_Typ = Any_Type
or else not Is_Scalar_Type (Target_Typ)
or else Raises_Constraint_Error (Expr)
then
return;
end if;
-- Now, see if checks are suppressed
Is_Subscr_Ref :=
Is_List_Member (Expr) and then Nkind (Parnt) = N_Indexed_Component;
if Is_Subscr_Ref then
Arr := Prefix (Parnt);
Arr_Typ := Get_Actual_Subtype_If_Available (Arr);
end if;
if not Do_Range_Check (Expr) then
-- Subscript reference. Check for Index_Checks suppressed
if Is_Subscr_Ref then
-- Check array type and its base type
if Index_Checks_Suppressed (Arr_Typ)
or else Index_Checks_Suppressed (Base_Type (Arr_Typ))
then
return;
-- Check array itself if it is an entity name
elsif Is_Entity_Name (Arr)
and then Index_Checks_Suppressed (Entity (Arr))
then
return;
-- Check expression itself if it is an entity name
elsif Is_Entity_Name (Expr)
and then Index_Checks_Suppressed (Entity (Expr))
then
return;
end if;
-- All other cases, check for Range_Checks suppressed
else
-- Check target type and its base type
if Range_Checks_Suppressed (Target_Typ)
or else Range_Checks_Suppressed (Base_Type (Target_Typ))
then
return;
-- Check expression itself if it is an entity name
elsif Is_Entity_Name (Expr)
and then Range_Checks_Suppressed (Entity (Expr))
then
return;
-- If Expr is part of an assignment statement, then check
-- left side of assignment if it is an entity name.
elsif Nkind (Parnt) = N_Assignment_Statement
and then Is_Entity_Name (Name (Parnt))
and then Range_Checks_Suppressed (Entity (Name (Parnt)))
then
return;
end if;
end if;
end if;
-- Do not set range checks if they are killed
if Nkind (Expr) = N_Unchecked_Type_Conversion
and then Kill_Range_Check (Expr)
then
return;
end if;
-- Do not set range checks for any values from System.Scalar_Values
-- since the whole idea of such values is to avoid checking them!
if Is_Entity_Name (Expr)
and then Is_RTU (Scope (Entity (Expr)), System_Scalar_Values)
then
return;
end if;
-- Now see if we need a check
if No (Source_Typ) then
S_Typ := Etype (Expr);
else
S_Typ := Source_Typ;
end if;
if not Is_Scalar_Type (S_Typ) or else S_Typ = Any_Type then
return;
end if;
Is_Unconstrained_Subscr_Ref :=
Is_Subscr_Ref and then not Is_Constrained (Arr_Typ);
-- Always do a range check if the source type includes infinities
-- and the target type does not include infinities. We do not do
-- this if range checks are killed.
if Is_Floating_Point_Type (S_Typ)
and then Has_Infinities (S_Typ)
and then not Has_Infinities (Target_Typ)
then
Enable_Range_Check (Expr);
end if;
-- Return if we know expression is definitely in the range of
-- the target type as determined by Determine_Range. Right now
-- we only do this for discrete types, and not fixed-point or
-- floating-point types.
-- The additional less-precise tests below catch these cases
-- Note: skip this if we are given a source_typ, since the point
-- of supplying a Source_Typ is to stop us looking at the expression.
-- could sharpen this test to be out parameters only ???
if Is_Discrete_Type (Target_Typ)
and then Is_Discrete_Type (Etype (Expr))
and then not Is_Unconstrained_Subscr_Ref
and then No (Source_Typ)
then
declare
Tlo : constant Node_Id := Type_Low_Bound (Target_Typ);
Thi : constant Node_Id := Type_High_Bound (Target_Typ);
Lo : Uint;
Hi : Uint;
begin
if Compile_Time_Known_Value (Tlo)
and then Compile_Time_Known_Value (Thi)
then
declare
Lov : constant Uint := Expr_Value (Tlo);
Hiv : constant Uint := Expr_Value (Thi);
begin
-- If range is null, we for sure have a constraint error
-- (we don't even need to look at the value involved,
-- since all possible values will raise CE).
if Lov > Hiv then
Bad_Value;
return;
end if;
-- Otherwise determine range of value
Determine_Range (Expr, OK, Lo, Hi);
if OK then
-- If definitely in range, all OK
if Lo >= Lov and then Hi <= Hiv then
return;
-- If definitely not in range, warn
elsif Lov > Hi or else Hiv < Lo then
Bad_Value;
return;
-- Otherwise we don't know
else
null;
end if;
end if;
end;
end if;
end;
end if;
Int_Real :=
Is_Floating_Point_Type (S_Typ)
or else (Is_Fixed_Point_Type (S_Typ) and then not Fixed_Int);
-- Check if we can determine at compile time whether Expr is in the
-- range of the target type. Note that if S_Typ is within the bounds
-- of Target_Typ then this must be the case. This check is meaningful
-- only if this is not a conversion between integer and real types.
if not Is_Unconstrained_Subscr_Ref
and then
Is_Discrete_Type (S_Typ) = Is_Discrete_Type (Target_Typ)
and then
(In_Subrange_Of (S_Typ, Target_Typ, Fixed_Int)
or else
Is_In_Range (Expr, Target_Typ, Fixed_Int, Int_Real))
then
return;
elsif Is_Out_Of_Range (Expr, Target_Typ, Fixed_Int, Int_Real) then
Bad_Value;
return;
-- In the floating-point case, we only do range checks if the
-- type is constrained. We definitely do NOT want range checks
-- for unconstrained types, since we want to have infinities
elsif Is_Floating_Point_Type (S_Typ) then
if Is_Constrained (S_Typ) then
Enable_Range_Check (Expr);
end if;
-- For all other cases we enable a range check unconditionally
else
Enable_Range_Check (Expr);
return;
end if;
end Apply_Scalar_Range_Check;
----------------------------------
-- Apply_Selected_Length_Checks --
----------------------------------
procedure Apply_Selected_Length_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Do_Static : Boolean)
is
Cond : Node_Id;
R_Result : Check_Result;
R_Cno : Node_Id;
Loc : constant Source_Ptr := Sloc (Ck_Node);
Checks_On : constant Boolean :=
(not Index_Checks_Suppressed (Target_Typ))
or else
(not Length_Checks_Suppressed (Target_Typ));
begin
if not Expander_Active then
return;
end if;
R_Result :=
Selected_Length_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
for J in 1 .. 2 loop
R_Cno := R_Result (J);
exit when No (R_Cno);
-- A length check may mention an Itype which is attached to a
-- subsequent node. At the top level in a package this can cause
-- an order-of-elaboration problem, so we make sure that the itype
-- is referenced now.
if Ekind (Current_Scope) = E_Package
and then Is_Compilation_Unit (Current_Scope)
then
Ensure_Defined (Target_Typ, Ck_Node);
if Present (Source_Typ) then
Ensure_Defined (Source_Typ, Ck_Node);
elsif Is_Itype (Etype (Ck_Node)) then
Ensure_Defined (Etype (Ck_Node), Ck_Node);
end if;
end if;
-- If the item is a conditional raise of constraint error,
-- then have a look at what check is being performed and
-- ???
if Nkind (R_Cno) = N_Raise_Constraint_Error
and then Present (Condition (R_Cno))
then
Cond := Condition (R_Cno);
if not Has_Dynamic_Length_Check (Ck_Node)
and then Checks_On
then
Insert_Action (Ck_Node, R_Cno);
if not Do_Static then
Set_Has_Dynamic_Length_Check (Ck_Node);
end if;
end if;
-- Output a warning if the condition is known to be True
if Is_Entity_Name (Cond)
and then Entity (Cond) = Standard_True
then
Apply_Compile_Time_Constraint_Error
(Ck_Node, "wrong length for array of}?",
CE_Length_Check_Failed,
Ent => Target_Typ,
Typ => Target_Typ);
-- If we were only doing a static check, or if checks are not
-- on, then we want to delete the check, since it is not needed.
-- We do this by replacing the if statement by a null statement
elsif Do_Static or else not Checks_On then
Rewrite (R_Cno, Make_Null_Statement (Loc));
end if;
else
Install_Static_Check (R_Cno, Loc);
end if;
end loop;
end Apply_Selected_Length_Checks;
---------------------------------
-- Apply_Selected_Range_Checks --
---------------------------------
procedure Apply_Selected_Range_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Do_Static : Boolean)
is
Cond : Node_Id;
R_Result : Check_Result;
R_Cno : Node_Id;
Loc : constant Source_Ptr := Sloc (Ck_Node);
Checks_On : constant Boolean :=
(not Index_Checks_Suppressed (Target_Typ))
or else
(not Range_Checks_Suppressed (Target_Typ));
begin
if not Expander_Active or else not Checks_On then
return;
end if;
R_Result :=
Selected_Range_Checks (Ck_Node, Target_Typ, Source_Typ, Empty);
for J in 1 .. 2 loop
R_Cno := R_Result (J);
exit when No (R_Cno);
-- If the item is a conditional raise of constraint error,
-- then have a look at what check is being performed and
-- ???
if Nkind (R_Cno) = N_Raise_Constraint_Error
and then Present (Condition (R_Cno))
then
Cond := Condition (R_Cno);
if not Has_Dynamic_Range_Check (Ck_Node) then
Insert_Action (Ck_Node, R_Cno);
if not Do_Static then
Set_Has_Dynamic_Range_Check (Ck_Node);
end if;
end if;
-- Output a warning if the condition is known to be True
if Is_Entity_Name (Cond)
and then Entity (Cond) = Standard_True
then
-- Since an N_Range is technically not an expression, we
-- have to set one of the bounds to C_E and then just flag
-- the N_Range. The warning message will point to the
-- lower bound and complain about a range, which seems OK.
if Nkind (Ck_Node) = N_Range then
Apply_Compile_Time_Constraint_Error
(Low_Bound (Ck_Node), "static range out of bounds of}?",
CE_Range_Check_Failed,
Ent => Target_Typ,
Typ => Target_Typ);
Set_Raises_Constraint_Error (Ck_Node);
else
Apply_Compile_Time_Constraint_Error
(Ck_Node, "static value out of range of}?",
CE_Range_Check_Failed,
Ent => Target_Typ,
Typ => Target_Typ);
end if;
-- If we were only doing a static check, or if checks are not
-- on, then we want to delete the check, since it is not needed.
-- We do this by replacing the if statement by a null statement
elsif Do_Static or else not Checks_On then
Rewrite (R_Cno, Make_Null_Statement (Loc));
end if;
else
Install_Static_Check (R_Cno, Loc);
end if;
end loop;
end Apply_Selected_Range_Checks;
-------------------------------
-- Apply_Static_Length_Check --
-------------------------------
procedure Apply_Static_Length_Check
(Expr : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id := Empty)
is
begin
Apply_Selected_Length_Checks
(Expr, Target_Typ, Source_Typ, Do_Static => True);
end Apply_Static_Length_Check;
-------------------------------------
-- Apply_Subscript_Validity_Checks --
-------------------------------------
procedure Apply_Subscript_Validity_Checks (Expr : Node_Id) is
Sub : Node_Id;
begin
pragma Assert (Nkind (Expr) = N_Indexed_Component);
-- Loop through subscripts
Sub := First (Expressions (Expr));
while Present (Sub) loop
-- Check one subscript. Note that we do not worry about
-- enumeration type with holes, since we will convert the
-- value to a Pos value for the subscript, and that convert
-- will do the necessary validity check.
Ensure_Valid (Sub, Holes_OK => True);
-- Move to next subscript
Sub := Next (Sub);
end loop;
end Apply_Subscript_Validity_Checks;
----------------------------------
-- Apply_Type_Conversion_Checks --
----------------------------------
procedure Apply_Type_Conversion_Checks (N : Node_Id) is
Target_Type : constant Entity_Id := Etype (N);
Target_Base : constant Entity_Id := Base_Type (Target_Type);
Expr : constant Node_Id := Expression (N);
Expr_Type : constant Entity_Id := Etype (Expr);
begin
if Inside_A_Generic then
return;
-- Skip these checks if serious errors detected, there are some nasty
-- situations of incomplete trees that blow things up.
elsif Serious_Errors_Detected > 0 then
return;
-- Scalar type conversions of the form Target_Type (Expr) require
-- a range check if we cannot be sure that Expr is in the base type
-- of Target_Typ and also that Expr is in the range of Target_Typ.
-- These are not quite the same condition from an implementation
-- point of view, but clearly the second includes the first.
elsif Is_Scalar_Type (Target_Type) then
declare
Conv_OK : constant Boolean := Conversion_OK (N);
-- If the Conversion_OK flag on the type conversion is set
-- and no floating point type is involved in the type conversion
-- then fixed point values must be read as integral values.
Float_To_Int : constant Boolean :=
Is_Floating_Point_Type (Expr_Type)
and then Is_Integer_Type (Target_Type);
begin
if not Overflow_Checks_Suppressed (Target_Base)
and then not In_Subrange_Of (Expr_Type, Target_Base, Conv_OK)
and then not Float_To_Int
then
Set_Do_Overflow_Check (N);
end if;
if not Range_Checks_Suppressed (Target_Type)
and then not Range_Checks_Suppressed (Expr_Type)
then
if Float_To_Int then
Apply_Float_Conversion_Check (Expr, Target_Type);
else
Apply_Scalar_Range_Check
(Expr, Target_Type, Fixed_Int => Conv_OK);
end if;
end if;
end;
elsif Comes_From_Source (N)
and then Is_Record_Type (Target_Type)
and then Is_Derived_Type (Target_Type)
and then not Is_Tagged_Type (Target_Type)
and then not Is_Constrained (Target_Type)
and then Present (Stored_Constraint (Target_Type))
then
-- An unconstrained derived type may have inherited discriminant
-- Build an actual discriminant constraint list using the stored
-- constraint, to verify that the expression of the parent type
-- satisfies the constraints imposed by the (unconstrained!)
-- derived type. This applies to value conversions, not to view
-- conversions of tagged types.
declare
Loc : constant Source_Ptr := Sloc (N);
Cond : Node_Id;
Constraint : Elmt_Id;
Discr_Value : Node_Id;
Discr : Entity_Id;
New_Constraints : constant Elist_Id := New_Elmt_List;
Old_Constraints : constant Elist_Id :=
Discriminant_Constraint (Expr_Type);
begin
Constraint := First_Elmt (Stored_Constraint (Target_Type));
while Present (Constraint) loop
Discr_Value := Node (Constraint);
if Is_Entity_Name (Discr_Value)
and then Ekind (Entity (Discr_Value)) = E_Discriminant
then
Discr := Corresponding_Discriminant (Entity (Discr_Value));
if Present (Discr)
and then Scope (Discr) = Base_Type (Expr_Type)
then
-- Parent is constrained by new discriminant. Obtain
-- Value of original discriminant in expression. If
-- the new discriminant has been used to constrain more
-- than one of the stored discriminants, this will
-- provide the required consistency check.
Append_Elmt (
Make_Selected_Component (Loc,
Prefix =>
Duplicate_Subexpr_No_Checks
(Expr, Name_Req => True),
Selector_Name =>
Make_Identifier (Loc, Chars (Discr))),
New_Constraints);
else
-- Discriminant of more remote ancestor ???
return;
end if;
-- Derived type definition has an explicit value for
-- this stored discriminant.
else
Append_Elmt
(Duplicate_Subexpr_No_Checks (Discr_Value),
New_Constraints);
end if;
Next_Elmt (Constraint);
end loop;
-- Use the unconstrained expression type to retrieve the
-- discriminants of the parent, and apply momentarily the
-- discriminant constraint synthesized above.
Set_Discriminant_Constraint (Expr_Type, New_Constraints);
Cond := Build_Discriminant_Checks (Expr, Expr_Type);
Set_Discriminant_Constraint (Expr_Type, Old_Constraints);
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition => Cond,
Reason => CE_Discriminant_Check_Failed));
end;
-- For arrays, conversions are applied during expansion, to take
-- into accounts changes of representation. The checks become range
-- checks on the base type or length checks on the subtype, depending
-- on whether the target type is unconstrained or constrained.
else
null;
end if;
end Apply_Type_Conversion_Checks;
----------------------------------------------
-- Apply_Universal_Integer_Attribute_Checks --
----------------------------------------------
procedure Apply_Universal_Integer_Attribute_Checks (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
begin
if Inside_A_Generic then
return;
-- Nothing to do if checks are suppressed
elsif Range_Checks_Suppressed (Typ)
and then Overflow_Checks_Suppressed (Typ)
then
return;
-- Nothing to do if the attribute does not come from source. The
-- internal attributes we generate of this type do not need checks,
-- and furthermore the attempt to check them causes some circular
-- elaboration orders when dealing with packed types.
elsif not Comes_From_Source (N) then
return;
-- If the prefix is a selected component that depends on a discriminant
-- the check may improperly expose a discriminant instead of using
-- the bounds of the object itself. Set the type of the attribute to
-- the base type of the context, so that a check will be imposed when
-- needed (e.g. if the node appears as an index).
elsif Nkind (Prefix (N)) = N_Selected_Component
and then Ekind (Typ) = E_Signed_Integer_Subtype
and then Depends_On_Discriminant (Scalar_Range (Typ))
then
Set_Etype (N, Base_Type (Typ));
-- Otherwise, replace the attribute node with a type conversion
-- node whose expression is the attribute, retyped to universal
-- integer, and whose subtype mark is the target type. The call
-- to analyze this conversion will set range and overflow checks
-- as required for proper detection of an out of range value.
else
Set_Etype (N, Universal_Integer);
Set_Analyzed (N, True);
Rewrite (N,
Make_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Expression => Relocate_Node (N)));
Analyze_And_Resolve (N, Typ);
return;
end if;
end Apply_Universal_Integer_Attribute_Checks;
-------------------------------
-- Build_Discriminant_Checks --
-------------------------------
function Build_Discriminant_Checks
(N : Node_Id;
T_Typ : Entity_Id) return Node_Id
is
Loc : constant Source_Ptr := Sloc (N);
Cond : Node_Id;
Disc : Elmt_Id;
Disc_Ent : Entity_Id;
Dref : Node_Id;
Dval : Node_Id;
function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id;
----------------------------------
-- Aggregate_Discriminant_Value --
----------------------------------
function Aggregate_Discriminant_Val (Disc : Entity_Id) return Node_Id is
Assoc : Node_Id;
begin
-- The aggregate has been normalized with named associations. We
-- use the Chars field to locate the discriminant to take into
-- account discriminants in derived types, which carry the same
-- name as those in the parent.
Assoc := First (Component_Associations (N));
while Present (Assoc) loop
if Chars (First (Choices (Assoc))) = Chars (Disc) then
return Expression (Assoc);
else
Next (Assoc);
end if;
end loop;
-- Discriminant must have been found in the loop above
raise Program_Error;
end Aggregate_Discriminant_Val;
-- Start of processing for Build_Discriminant_Checks
begin
-- Loop through discriminants evolving the condition
Cond := Empty;
Disc := First_Elmt (Discriminant_Constraint (T_Typ));
-- For a fully private type, use the discriminants of the parent type
if Is_Private_Type (T_Typ)
and then No (Full_View (T_Typ))
then
Disc_Ent := First_Discriminant (Etype (Base_Type (T_Typ)));
else
Disc_Ent := First_Discriminant (T_Typ);
end if;
while Present (Disc) loop
Dval := Node (Disc);
if Nkind (Dval) = N_Identifier
and then Ekind (Entity (Dval)) = E_Discriminant
then
Dval := New_Occurrence_Of (Discriminal (Entity (Dval)), Loc);
else
Dval := Duplicate_Subexpr_No_Checks (Dval);
end if;
-- If we have an Unchecked_Union node, we can infer the discriminants
-- of the node.
if Is_Unchecked_Union (Base_Type (T_Typ)) then
Dref := New_Copy (
Get_Discriminant_Value (
First_Discriminant (T_Typ),
T_Typ,
Stored_Constraint (T_Typ)));
elsif Nkind (N) = N_Aggregate then
Dref :=
Duplicate_Subexpr_No_Checks
(Aggregate_Discriminant_Val (Disc_Ent));
else
Dref :=
Make_Selected_Component (Loc,
Prefix =>
Duplicate_Subexpr_No_Checks (N, Name_Req => True),
Selector_Name =>
Make_Identifier (Loc, Chars (Disc_Ent)));
Set_Is_In_Discriminant_Check (Dref);
end if;
Evolve_Or_Else (Cond,
Make_Op_Ne (Loc,
Left_Opnd => Dref,
Right_Opnd => Dval));
Next_Elmt (Disc);
Next_Discriminant (Disc_Ent);
end loop;
return Cond;
end Build_Discriminant_Checks;
------------------
-- Check_Needed --
------------------
function Check_Needed (Nod : Node_Id; Check : Check_Type) return Boolean is
N : Node_Id;
P : Node_Id;
K : Node_Kind;
L : Node_Id;
R : Node_Id;
begin
-- Always check if not simple entity
if Nkind (Nod) not in N_Has_Entity
or else not Comes_From_Source (Nod)
then
return True;
end if;
-- Look up tree for short circuit
N := Nod;
loop
P := Parent (N);
K := Nkind (P);
if K not in N_Subexpr then
return True;
-- Or/Or Else case, left operand must be equality test
elsif K = N_Op_Or or else K = N_Or_Else then
exit when N = Right_Opnd (P)
and then Nkind (Left_Opnd (P)) = N_Op_Eq;
-- And/And then case, left operand must be inequality test
elsif K = N_Op_And or else K = N_And_Then then
exit when N = Right_Opnd (P)
and then Nkind (Left_Opnd (P)) = N_Op_Ne;
end if;
N := P;
end loop;
-- If we fall through the loop, then we have a conditional with an
-- appropriate test as its left operand. So test further.
L := Left_Opnd (P);
if Nkind (L) = N_Op_Not then
L := Right_Opnd (L);
end if;
R := Right_Opnd (L);
L := Left_Opnd (L);
-- Left operand of test must match original variable
if Nkind (L) not in N_Has_Entity
or else Entity (L) /= Entity (Nod)
then
return True;
end if;
-- Right operand of test mus be key value (zero or null)
case Check is
when Access_Check =>
if Nkind (R) /= N_Null then
return True;
end if;
when Division_Check =>
if not Compile_Time_Known_Value (R)
or else Expr_Value (R) /= Uint_0
then
return True;
end if;
end case;
-- Here we have the optimizable case, warn if not short-circuited
if K = N_Op_And or else K = N_Op_Or then
case Check is
when Access_Check =>
Error_Msg_N
("Constraint_Error may be raised (access check)?",
Parent (Nod));
when Division_Check =>
Error_Msg_N
("Constraint_Error may be raised (zero divide)?",
Parent (Nod));
end case;
if K = N_Op_And then
Error_Msg_N ("use `AND THEN` instead of AND?", P);
else
Error_Msg_N ("use `OR ELSE` instead of OR?", P);
end if;
-- If not short-circuited, we need the ckeck
return True;
-- If short-circuited, we can omit the check
else
return False;
end if;
end Check_Needed;
-----------------------------------
-- Check_Valid_Lvalue_Subscripts --
-----------------------------------
procedure Check_Valid_Lvalue_Subscripts (Expr : Node_Id) is
begin
-- Skip this if range checks are suppressed
if Range_Checks_Suppressed (Etype (Expr)) then
return;
-- Only do this check for expressions that come from source. We
-- assume that expander generated assignments explicitly include
-- any necessary checks. Note that this is not just an optimization,
-- it avoids infinite recursions!
elsif not Comes_From_Source (Expr) then
return;
-- For a selected component, check the prefix
elsif Nkind (Expr) = N_Selected_Component then
Check_Valid_Lvalue_Subscripts (Prefix (Expr));
return;
-- Case of indexed component
elsif Nkind (Expr) = N_Indexed_Component then
Apply_Subscript_Validity_Checks (Expr);
-- Prefix may itself be or contain an indexed component, and
-- these subscripts need checking as well
Check_Valid_Lvalue_Subscripts (Prefix (Expr));
end if;
end Check_Valid_Lvalue_Subscripts;
----------------------------------
-- Null_Exclusion_Static_Checks --
----------------------------------
procedure Null_Exclusion_Static_Checks (N : Node_Id) is
K : constant Node_Kind := Nkind (N);
Typ : Entity_Id;
Related_Nod : Node_Id;
Has_Null_Exclusion : Boolean := False;
begin
pragma Assert (K = N_Parameter_Specification
or else K = N_Object_Declaration
or else K = N_Discriminant_Specification
or else K = N_Component_Declaration);
Typ := Etype (Defining_Identifier (N));
pragma Assert (Is_Access_Type (Typ)
or else (K = N_Object_Declaration and then Is_Array_Type (Typ)));
case K is
when N_Parameter_Specification =>
Related_Nod := Parameter_Type (N);
Has_Null_Exclusion := Null_Exclusion_Present (N);
when N_Object_Declaration =>
Related_Nod := Object_Definition (N);
Has_Null_Exclusion := Null_Exclusion_Present (N);
when N_Discriminant_Specification =>
Related_Nod := Discriminant_Type (N);
Has_Null_Exclusion := Null_Exclusion_Present (N);
when N_Component_Declaration =>
if Present (Access_Definition (Component_Definition (N))) then
Related_Nod := Component_Definition (N);
Has_Null_Exclusion :=
Null_Exclusion_Present
(Access_Definition (Component_Definition (N)));
else
Related_Nod :=
Subtype_Indication (Component_Definition (N));
Has_Null_Exclusion :=
Null_Exclusion_Present (Component_Definition (N));
end if;
when others =>
raise Program_Error;
end case;
-- Enforce legality rule 3.10 (14/1): A null_exclusion is only allowed
-- of the access subtype does not exclude null.
if Has_Null_Exclusion
and then Can_Never_Be_Null (Typ)
-- No need to check itypes that have the null-excluding attribute
-- because they were checked at their point of creation
and then not Is_Itype (Typ)
then
Error_Msg_N
("(Ada 2005) already a null-excluding type", Related_Nod);
end if;
-- Check that null-excluding objects are always initialized
if K = N_Object_Declaration
and then No (Expression (N))
then
-- Add a an expression that assignates null. This node is needed
-- by Apply_Compile_Time_Constraint_Error, that will replace this
-- node by a Constraint_Error node.
Set_Expression (N, Make_Null (Sloc (N)));
Set_Etype (Expression (N), Etype (Defining_Identifier (N)));
Apply_Compile_Time_Constraint_Error
(N => Expression (N),
Msg => "(Ada 2005) null-excluding objects must be initialized?",
Reason => CE_Null_Not_Allowed);
end if;
-- Check that the null value is not used as a single expression to
-- assignate a value to a null-excluding component, formal or object;
-- otherwise generate a warning message at the sloc of Related_Nod and
-- replace Expression (N) by an N_Contraint_Error node.
declare
Expr : constant Node_Id := Expression (N);
begin
if Present (Expr)
and then Nkind (Expr) = N_Null
then
case K is
when N_Discriminant_Specification |
N_Component_Declaration =>
Apply_Compile_Time_Constraint_Error
(N => Expr,
Msg => "(Ada 2005) NULL not allowed in"
& " null-excluding components?",
Reason => CE_Null_Not_Allowed);
when N_Parameter_Specification =>
Apply_Compile_Time_Constraint_Error
(N => Expr,
Msg => "(Ada 2005) NULL not allowed in"
& " null-excluding formals?",
Reason => CE_Null_Not_Allowed);
when N_Object_Declaration =>
Apply_Compile_Time_Constraint_Error
(N => Expr,
Msg => "(Ada 2005) NULL not allowed in"
& " null-excluding objects?",
Reason => CE_Null_Not_Allowed);
when others =>
null;
end case;
end if;
end;
end Null_Exclusion_Static_Checks;
----------------------------------
-- Conditional_Statements_Begin --
----------------------------------
procedure Conditional_Statements_Begin is
begin
Saved_Checks_TOS := Saved_Checks_TOS + 1;
-- If stack overflows, kill all checks, that way we know to
-- simply reset the number of saved checks to zero on return.
-- This should never occur in practice.
if Saved_Checks_TOS > Saved_Checks_Stack'Last then
Kill_All_Checks;
-- In the normal case, we just make a new stack entry saving
-- the current number of saved checks for a later restore.
else
Saved_Checks_Stack (Saved_Checks_TOS) := Num_Saved_Checks;
if Debug_Flag_CC then
w ("Conditional_Statements_Begin: Num_Saved_Checks = ",
Num_Saved_Checks);
end if;
end if;
end Conditional_Statements_Begin;
--------------------------------
-- Conditional_Statements_End --
--------------------------------
procedure Conditional_Statements_End is
begin
pragma Assert (Saved_Checks_TOS > 0);
-- If the saved checks stack overflowed, then we killed all
-- checks, so setting the number of saved checks back to
-- zero is correct. This should never occur in practice.
if Saved_Checks_TOS > Saved_Checks_Stack'Last then
Num_Saved_Checks := 0;
-- In the normal case, restore the number of saved checks
-- from the top stack entry.
else
Num_Saved_Checks := Saved_Checks_Stack (Saved_Checks_TOS);
if Debug_Flag_CC then
w ("Conditional_Statements_End: Num_Saved_Checks = ",
Num_Saved_Checks);
end if;
end if;
Saved_Checks_TOS := Saved_Checks_TOS - 1;
end Conditional_Statements_End;
---------------------
-- Determine_Range --
---------------------
Cache_Size : constant := 2 ** 10;
type Cache_Index is range 0 .. Cache_Size - 1;
-- Determine size of below cache (power of 2 is more efficient!)
Determine_Range_Cache_N : array (Cache_Index) of Node_Id;
Determine_Range_Cache_Lo : array (Cache_Index) of Uint;
Determine_Range_Cache_Hi : array (Cache_Index) of Uint;
-- The above arrays are used to implement a small direct cache
-- for Determine_Range calls. Because of the way Determine_Range
-- recursively traces subexpressions, and because overflow checking
-- calls the routine on the way up the tree, a quadratic behavior
-- can otherwise be encountered in large expressions. The cache
-- entry for node N is stored in the (N mod Cache_Size) entry, and
-- can be validated by checking the actual node value stored there.
procedure Determine_Range
(N : Node_Id;
OK : out Boolean;
Lo : out Uint;
Hi : out Uint)
is
Typ : constant Entity_Id := Etype (N);
Lo_Left : Uint;
Hi_Left : Uint;
-- Lo and Hi bounds of left operand
Lo_Right : Uint;
Hi_Right : Uint;
-- Lo and Hi bounds of right (or only) operand
Bound : Node_Id;
-- Temp variable used to hold a bound node
Hbound : Uint;
-- High bound of base type of expression
Lor : Uint;
Hir : Uint;
-- Refined values for low and high bounds, after tightening
OK1 : Boolean;
-- Used in lower level calls to indicate if call succeeded
Cindex : Cache_Index;
-- Used to search cache
function OK_Operands return Boolean;
-- Used for binary operators. Determines the ranges of the left and
-- right operands, and if they are both OK, returns True, and puts
-- the results in Lo_Right, Hi_Right, Lo_Left, Hi_Left
-----------------
-- OK_Operands --
-----------------
function OK_Operands return Boolean is
begin
Determine_Range (Left_Opnd (N), OK1, Lo_Left, Hi_Left);
if not OK1 then
return False;
end if;
Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
return OK1;
end OK_Operands;
-- Start of processing for Determine_Range
begin
-- Prevent junk warnings by initializing range variables
Lo := No_Uint;
Hi := No_Uint;
Lor := No_Uint;
Hir := No_Uint;
-- If the type is not discrete, or is undefined, then we can't
-- do anything about determining the range.
if No (Typ) or else not Is_Discrete_Type (Typ)
or else Error_Posted (N)
then
OK := False;
return;
end if;
-- For all other cases, we can determine the range
OK := True;
-- If value is compile time known, then the possible range is the
-- one value that we know this expression definitely has!
if Compile_Time_Known_Value (N) then
Lo := Expr_Value (N);
Hi := Lo;
return;
end if;
-- Return if already in the cache
Cindex := Cache_Index (N mod Cache_Size);
if Determine_Range_Cache_N (Cindex) = N then
Lo := Determine_Range_Cache_Lo (Cindex);
Hi := Determine_Range_Cache_Hi (Cindex);
return;
end if;
-- Otherwise, start by finding the bounds of the type of the
-- expression, the value cannot be outside this range (if it
-- is, then we have an overflow situation, which is a separate
-- check, we are talking here only about the expression value).
-- We use the actual bound unless it is dynamic, in which case
-- use the corresponding base type bound if possible. If we can't
-- get a bound then we figure we can't determine the range (a
-- peculiar case, that perhaps cannot happen, but there is no
-- point in bombing in this optimization circuit.
-- First the low bound
Bound := Type_Low_Bound (Typ);
if Compile_Time_Known_Value (Bound) then
Lo := Expr_Value (Bound);
elsif Compile_Time_Known_Value (Type_Low_Bound (Base_Type (Typ))) then
Lo := Expr_Value (Type_Low_Bound (Base_Type (Typ)));
else
OK := False;
return;
end if;
-- Now the high bound
Bound := Type_High_Bound (Typ);
-- We need the high bound of the base type later on, and this should
-- always be compile time known. Again, it is not clear that this
-- can ever be false, but no point in bombing.
if Compile_Time_Known_Value (Type_High_Bound (Base_Type (Typ))) then
Hbound := Expr_Value (Type_High_Bound (Base_Type (Typ)));
Hi := Hbound;
else
OK := False;
return;
end if;
-- If we have a static subtype, then that may have a tighter bound
-- so use the upper bound of the subtype instead in this case.
if Compile_Time_Known_Value (Bound) then
Hi := Expr_Value (Bound);
end if;
-- We may be able to refine this value in certain situations. If
-- refinement is possible, then Lor and Hir are set to possibly
-- tighter bounds, and OK1 is set to True.
case Nkind (N) is
-- For unary plus, result is limited by range of operand
when N_Op_Plus =>
Determine_Range (Right_Opnd (N), OK1, Lor, Hir);
-- For unary minus, determine range of operand, and negate it
when N_Op_Minus =>
Determine_Range (Right_Opnd (N), OK1, Lo_Right, Hi_Right);
if OK1 then
Lor := -Hi_Right;
Hir := -Lo_Right;
end if;
-- For binary addition, get range of each operand and do the
-- addition to get the result range.
when N_Op_Add =>
if OK_Operands then
Lor := Lo_Left + Lo_Right;
Hir := Hi_Left + Hi_Right;
end if;
-- Division is tricky. The only case we consider is where the
-- right operand is a positive constant, and in this case we
-- simply divide the bounds of the left operand
when N_Op_Divide =>
if OK_Operands then
if Lo_Right = Hi_Right
and then Lo_Right > 0
then
Lor := Lo_Left / Lo_Right;
Hir := Hi_Left / Lo_Right;
else
OK1 := False;
end if;
end if;
-- For binary subtraction, get range of each operand and do
-- the worst case subtraction to get the result range.
when N_Op_Subtract =>
if OK_Operands then
Lor := Lo_Left - Hi_Right;
Hir := Hi_Left - Lo_Right;
end if;
-- For MOD, if right operand is a positive constant, then
-- result must be in the allowable range of mod results.
when N_Op_Mod =>
if OK_Operands then
if Lo_Right = Hi_Right
and then Lo_Right /= 0
then
if Lo_Right > 0 then
Lor := Uint_0;
Hir := Lo_Right - 1;
else -- Lo_Right < 0
Lor := Lo_Right + 1;
Hir := Uint_0;
end if;
else
OK1 := False;
end if;
end if;
-- For REM, if right operand is a positive constant, then
-- result must be in the allowable range of mod results.
when N_Op_Rem =>
if OK_Operands then
if Lo_Right = Hi_Right
and then Lo_Right /= 0
then
declare
Dval : constant Uint := (abs Lo_Right) - 1;
begin
-- The sign of the result depends on the sign of the
-- dividend (but not on the sign of the divisor, hence
-- the abs operation above).
if Lo_Left < 0 then
Lor := -Dval;
else
Lor := Uint_0;
end if;
if Hi_Left < 0 then
Hir := Uint_0;
else
Hir := Dval;
end if;
end;
else
OK1 := False;
end if;
end if;
-- Attribute reference cases
when N_Attribute_Reference =>
case Attribute_Name (N) is
-- For Pos/Val attributes, we can refine the range using the
-- possible range of values of the attribute expression
when Name_Pos | Name_Val =>
Determine_Range (First (Expressions (N)), OK1, Lor, Hir);
-- For Length attribute, use the bounds of the corresponding
-- index type to refine the range.
when Name_Length =>
declare
Atyp : Entity_Id := Etype (Prefix (N));
Inum : Nat;
Indx : Node_Id;
LL, LU : Uint;
UL, UU : Uint;
begin
if Is_Access_Type (Atyp) then
Atyp := Designated_Type (Atyp);
end if;
-- For string literal, we know exact value
if Ekind (Atyp) = E_String_Literal_Subtype then
OK := True;
Lo := String_Literal_Length (Atyp);
Hi := String_Literal_Length (Atyp);
return;
end if;
-- Otherwise check for expression given
if No (Expressions (N)) then
Inum := 1;
else
Inum :=
UI_To_Int (Expr_Value (First (Expressions (N))));
end if;
Indx := First_Index (Atyp);
for J in 2 .. Inum loop
Indx := Next_Index (Indx);
end loop;
Determine_Range
(Type_Low_Bound (Etype (Indx)), OK1, LL, LU);
if OK1 then
Determine_Range
(Type_High_Bound (Etype (Indx)), OK1, UL, UU);
if OK1 then
-- The maximum value for Length is the biggest
-- possible gap between the values of the bounds.
-- But of course, this value cannot be negative.
Hir := UI_Max (Uint_0, UU - LL);
-- For constrained arrays, the minimum value for
-- Length is taken from the actual value of the
-- bounds, since the index will be exactly of
-- this subtype.
if Is_Constrained (Atyp) then
Lor := UI_Max (Uint_0, UL - LU);
-- For an unconstrained array, the minimum value
-- for length is always zero.
else
Lor := Uint_0;
end if;
end if;
end if;
end;
-- No special handling for other attributes
-- Probably more opportunities exist here ???
when others =>
OK1 := False;
end case;
-- For type conversion from one discrete type to another, we
-- can refine the range using the converted value.
when N_Type_Conversion =>
Determine_Range (Expression (N), OK1, Lor, Hir);
-- Nothing special to do for all other expression kinds
when others =>
OK1 := False;
Lor := No_Uint;
Hir := No_Uint;
end case;
-- At this stage, if OK1 is true, then we know that the actual
-- result of the computed expression is in the range Lor .. Hir.
-- We can use this to restrict the possible range of results.
if OK1 then
-- If the refined value of the low bound is greater than the
-- type high bound, then reset it to the more restrictive
-- value. However, we do NOT do this for the case of a modular
-- type where the possible upper bound on the value is above the
-- base type high bound, because that means the result could wrap.
if Lor > Lo
and then not (Is_Modular_Integer_Type (Typ)
and then Hir > Hbound)
then
Lo := Lor;
end if;
-- Similarly, if the refined value of the high bound is less
-- than the value so far, then reset it to the more restrictive
-- value. Again, we do not do this if the refined low bound is
-- negative for a modular type, since this would wrap.
if Hir < Hi
and then not (Is_Modular_Integer_Type (Typ)
and then Lor < Uint_0)
then
Hi := Hir;
end if;
end if;
-- Set cache entry for future call and we are all done
Determine_Range_Cache_N (Cindex) := N;
Determine_Range_Cache_Lo (Cindex) := Lo;
Determine_Range_Cache_Hi (Cindex) := Hi;
return;
-- If any exception occurs, it means that we have some bug in the compiler
-- possibly triggered by a previous error, or by some unforseen peculiar
-- occurrence. However, this is only an optimization attempt, so there is
-- really no point in crashing the compiler. Instead we just decide, too
-- bad, we can't figure out a range in this case after all.
exception
when others =>
-- Debug flag K disables this behavior (useful for debugging)
if Debug_Flag_K then
raise;
else
OK := False;
Lo := No_Uint;
Hi := No_Uint;
return;
end if;
end Determine_Range;
------------------------------------
-- Discriminant_Checks_Suppressed --
------------------------------------
function Discriminant_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) then
if Is_Unchecked_Union (E) then
return True;
elsif Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Discriminant_Check);
end if;
end if;
return Scope_Suppress (Discriminant_Check);
end Discriminant_Checks_Suppressed;
--------------------------------
-- Division_Checks_Suppressed --
--------------------------------
function Division_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Division_Check);
else
return Scope_Suppress (Division_Check);
end if;
end Division_Checks_Suppressed;
-----------------------------------
-- Elaboration_Checks_Suppressed --
-----------------------------------
function Elaboration_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
-- The complication in this routine is that if we are in the dynamic
-- model of elaboration, we also check All_Checks, since All_Checks
-- does not set Elaboration_Check explicitly.
if Present (E) then
if Kill_Elaboration_Checks (E) then
return True;
elsif Checks_May_Be_Suppressed (E) then
if Is_Check_Suppressed (E, Elaboration_Check) then
return True;
elsif Dynamic_Elaboration_Checks then
return Is_Check_Suppressed (E, All_Checks);
else
return False;
end if;
end if;
end if;
if Scope_Suppress (Elaboration_Check) then
return True;
elsif Dynamic_Elaboration_Checks then
return Scope_Suppress (All_Checks);
else
return False;
end if;
end Elaboration_Checks_Suppressed;
---------------------------
-- Enable_Overflow_Check --
---------------------------
procedure Enable_Overflow_Check (N : Node_Id) is
Typ : constant Entity_Id := Base_Type (Etype (N));
Chk : Nat;
OK : Boolean;
Ent : Entity_Id;
Ofs : Uint;
Lo : Uint;
Hi : Uint;
begin
if Debug_Flag_CC then
w ("Enable_Overflow_Check for node ", Int (N));
Write_Str (" Source location = ");
wl (Sloc (N));
pg (N);
end if;
-- Nothing to do if the range of the result is known OK. We skip
-- this for conversions, since the caller already did the check,
-- and in any case the condition for deleting the check for a
-- type conversion is different in any case.
if Nkind (N) /= N_Type_Conversion then
Determine_Range (N, OK, Lo, Hi);
-- Note in the test below that we assume that if a bound of the
-- range is equal to that of the type. That's not quite accurate
-- but we do this for the following reasons:
-- a) The way that Determine_Range works, it will typically report
-- the bounds of the value as being equal to the bounds of the
-- type, because it either can't tell anything more precise, or
-- does not think it is worth the effort to be more precise.
-- b) It is very unusual to have a situation in which this would
-- generate an unnecessary overflow check (an example would be
-- a subtype with a range 0 .. Integer'Last - 1 to which the
-- literal value one is added.
-- c) The alternative is a lot of special casing in this routine
-- which would partially duplicate Determine_Range processing.
if OK
and then Lo > Expr_Value (Type_Low_Bound (Typ))
and then Hi < Expr_Value (Type_High_Bound (Typ))
then
if Debug_Flag_CC then
w ("No overflow check required");
end if;
return;
end if;
end if;
-- If not in optimizing mode, set flag and we are done. We are also
-- done (and just set the flag) if the type is not a discrete type,
-- since it is not worth the effort to eliminate checks for other
-- than discrete types. In addition, we take this same path if we
-- have stored the maximum number of checks possible already (a
-- very unlikely situation, but we do not want to blow up!)
if Optimization_Level = 0
or else not Is_Discrete_Type (Etype (N))
or else Num_Saved_Checks = Saved_Checks'Last
then
Set_Do_Overflow_Check (N, True);
if Debug_Flag_CC then
w ("Optimization off");
end if;
return;
end if;
-- Otherwise evaluate and check the expression
Find_Check
(Expr => N,
Check_Type => 'O',
Target_Type => Empty,
Entry_OK => OK,
Check_Num => Chk,
Ent => Ent,
Ofs => Ofs);
if Debug_Flag_CC then
w ("Called Find_Check");
w (" OK = ", OK);
if OK then
w (" Check_Num = ", Chk);
w (" Ent = ", Int (Ent));
Write_Str (" Ofs = ");
pid (Ofs);
end if;
end if;
-- If check is not of form to optimize, then set flag and we are done
if not OK then
Set_Do_Overflow_Check (N, True);
return;
end if;
-- If check is already performed, then return without setting flag
if Chk /= 0 then
if Debug_Flag_CC then
w ("Check suppressed!");
end if;
return;
end if;
-- Here we will make a new entry for the new check
Set_Do_Overflow_Check (N, True);
Num_Saved_Checks := Num_Saved_Checks + 1;
Saved_Checks (Num_Saved_Checks) :=
(Killed => False,
Entity => Ent,
Offset => Ofs,
Check_Type => 'O',
Target_Type => Empty);
if Debug_Flag_CC then
w ("Make new entry, check number = ", Num_Saved_Checks);
w (" Entity = ", Int (Ent));
Write_Str (" Offset = ");
pid (Ofs);
w (" Check_Type = O");
w (" Target_Type = Empty");
end if;
-- If we get an exception, then something went wrong, probably because
-- of an error in the structure of the tree due to an incorrect program.
-- Or it may be a bug in the optimization circuit. In either case the
-- safest thing is simply to set the check flag unconditionally.
exception
when others =>
Set_Do_Overflow_Check (N, True);
if Debug_Flag_CC then
w (" exception occurred, overflow flag set");
end if;
return;
end Enable_Overflow_Check;
------------------------
-- Enable_Range_Check --
------------------------
procedure Enable_Range_Check (N : Node_Id) is
Chk : Nat;
OK : Boolean;
Ent : Entity_Id;
Ofs : Uint;
Ttyp : Entity_Id;
P : Node_Id;
begin
-- Return if unchecked type conversion with range check killed.
-- In this case we never set the flag (that's what Kill_Range_Check
-- is all about!)
if Nkind (N) = N_Unchecked_Type_Conversion
and then Kill_Range_Check (N)
then
return;
end if;
-- Debug trace output
if Debug_Flag_CC then
w ("Enable_Range_Check for node ", Int (N));
Write_Str (" Source location = ");
wl (Sloc (N));
pg (N);
end if;
-- If not in optimizing mode, set flag and we are done. We are also
-- done (and just set the flag) if the type is not a discrete type,
-- since it is not worth the effort to eliminate checks for other
-- than discrete types. In addition, we take this same path if we
-- have stored the maximum number of checks possible already (a
-- very unlikely situation, but we do not want to blow up!)
if Optimization_Level = 0
or else No (Etype (N))
or else not Is_Discrete_Type (Etype (N))
or else Num_Saved_Checks = Saved_Checks'Last
then
Set_Do_Range_Check (N, True);
if Debug_Flag_CC then
w ("Optimization off");
end if;
return;
end if;
-- Otherwise find out the target type
P := Parent (N);
-- For assignment, use left side subtype
if Nkind (P) = N_Assignment_Statement
and then Expression (P) = N
then
Ttyp := Etype (Name (P));
-- For indexed component, use subscript subtype
elsif Nkind (P) = N_Indexed_Component then
declare
Atyp : Entity_Id;
Indx : Node_Id;
Subs : Node_Id;
begin
Atyp := Etype (Prefix (P));
if Is_Access_Type (Atyp) then
Atyp := Designated_Type (Atyp);
-- If the prefix is an access to an unconstrained array,
-- perform check unconditionally: it depends on the bounds
-- of an object and we cannot currently recognize whether
-- the test may be redundant.
if not Is_Constrained (Atyp) then
Set_Do_Range_Check (N, True);
return;
end if;
-- Ditto if the prefix is an explicit dereference whose
-- designated type is unconstrained.
elsif Nkind (Prefix (P)) = N_Explicit_Dereference
and then not Is_Constrained (Atyp)
then
Set_Do_Range_Check (N, True);
return;
end if;
Indx := First_Index (Atyp);
Subs := First (Expressions (P));
loop
if Subs = N then
Ttyp := Etype (Indx);
exit;
end if;
Next_Index (Indx);
Next (Subs);
end loop;
end;
-- For now, ignore all other cases, they are not so interesting
else
if Debug_Flag_CC then
w (" target type not found, flag set");
end if;
Set_Do_Range_Check (N, True);
return;
end if;
-- Evaluate and check the expression
Find_Check
(Expr => N,
Check_Type => 'R',
Target_Type => Ttyp,
Entry_OK => OK,
Check_Num => Chk,
Ent => Ent,
Ofs => Ofs);
if Debug_Flag_CC then
w ("Called Find_Check");
w ("Target_Typ = ", Int (Ttyp));
w (" OK = ", OK);
if OK then
w (" Check_Num = ", Chk);
w (" Ent = ", Int (Ent));
Write_Str (" Ofs = ");
pid (Ofs);
end if;
end if;
-- If check is not of form to optimize, then set flag and we are done
if not OK then
if Debug_Flag_CC then
w (" expression not of optimizable type, flag set");
end if;
Set_Do_Range_Check (N, True);
return;
end if;
-- If check is already performed, then return without setting flag
if Chk /= 0 then
if Debug_Flag_CC then
w ("Check suppressed!");
end if;
return;
end if;
-- Here we will make a new entry for the new check
Set_Do_Range_Check (N, True);
Num_Saved_Checks := Num_Saved_Checks + 1;
Saved_Checks (Num_Saved_Checks) :=
(Killed => False,
Entity => Ent,
Offset => Ofs,
Check_Type => 'R',
Target_Type => Ttyp);
if Debug_Flag_CC then
w ("Make new entry, check number = ", Num_Saved_Checks);
w (" Entity = ", Int (Ent));
Write_Str (" Offset = ");
pid (Ofs);
w (" Check_Type = R");
w (" Target_Type = ", Int (Ttyp));
pg (Ttyp);
end if;
-- If we get an exception, then something went wrong, probably because
-- of an error in the structure of the tree due to an incorrect program.
-- Or it may be a bug in the optimization circuit. In either case the
-- safest thing is simply to set the check flag unconditionally.
exception
when others =>
Set_Do_Range_Check (N, True);
if Debug_Flag_CC then
w (" exception occurred, range flag set");
end if;
return;
end Enable_Range_Check;
------------------
-- Ensure_Valid --
------------------
procedure Ensure_Valid (Expr : Node_Id; Holes_OK : Boolean := False) is
Typ : constant Entity_Id := Etype (Expr);
begin
-- Ignore call if we are not doing any validity checking
if not Validity_Checks_On then
return;
-- Ignore call if range checks suppressed on entity in question
elsif Is_Entity_Name (Expr)
and then Range_Checks_Suppressed (Entity (Expr))
then
return;
-- No check required if expression is from the expander, we assume
-- the expander will generate whatever checks are needed. Note that
-- this is not just an optimization, it avoids infinite recursions!
-- Unchecked conversions must be checked, unless they are initialized
-- scalar values, as in a component assignment in an init proc.
-- In addition, we force a check if Force_Validity_Checks is set
elsif not Comes_From_Source (Expr)
and then not Force_Validity_Checks
and then (Nkind (Expr) /= N_Unchecked_Type_Conversion
or else Kill_Range_Check (Expr))
then
return;
-- No check required if expression is known to have valid value
elsif Expr_Known_Valid (Expr) then
return;
-- No check required if checks off
elsif Range_Checks_Suppressed (Typ) then
return;
-- Ignore case of enumeration with holes where the flag is set not
-- to worry about holes, since no special validity check is needed
elsif Is_Enumeration_Type (Typ)
and then Has_Non_Standard_Rep (Typ)
and then Holes_OK
then
return;
-- No check required on the left-hand side of an assignment
elsif Nkind (Parent (Expr)) = N_Assignment_Statement
and then Expr = Name (Parent (Expr))
then
return;
-- No check on a univeral real constant. The context will eventually
-- convert it to a machine number for some target type, or report an
-- illegality.
elsif Nkind (Expr) = N_Real_Literal
and then Etype (Expr) = Universal_Real
then
return;
-- An annoying special case. If this is an out parameter of a scalar
-- type, then the value is not going to be accessed, therefore it is
-- inappropriate to do any validity check at the call site.
else
-- Only need to worry about scalar types
if Is_Scalar_Type (Typ) then
declare
P : Node_Id;
N : Node_Id;
E : Entity_Id;
F : Entity_Id;
A : Node_Id;
L : List_Id;
begin
-- Find actual argument (which may be a parameter association)
-- and the parent of the actual argument (the call statement)
N := Expr;
P := Parent (Expr);
if Nkind (P) = N_Parameter_Association then
N := P;
P := Parent (N);
end if;
-- Only need to worry if we are argument of a procedure
-- call since functions don't have out parameters. If this
-- is an indirect or dispatching call, get signature from
-- the subprogram type.
if Nkind (P) = N_Procedure_Call_Statement then
L := Parameter_Associations (P);
if Is_Entity_Name (Name (P)) then
E := Entity (Name (P));
else
pragma Assert (Nkind (Name (P)) = N_Explicit_Dereference);
E := Etype (Name (P));
end if;
-- Only need to worry if there are indeed actuals, and
-- if this could be a procedure call, otherwise we cannot
-- get a match (either we are not an argument, or the
-- mode of the formal is not OUT). This test also filters
-- out the generic case.
if Is_Non_Empty_List (L)
and then Is_Subprogram (E)
then
-- This is the loop through parameters, looking to
-- see if there is an OUT parameter for which we are
-- the argument.
F := First_Formal (E);
A := First (L);
while Present (F) loop
if Ekind (F) = E_Out_Parameter and then A = N then
return;
end if;
Next_Formal (F);
Next (A);
end loop;
end if;
end if;
end;
end if;
end if;
-- If we fall through, a validity check is required. Note that it would
-- not be good to set Do_Range_Check, even in contexts where this is
-- permissible, since this flag causes checking against the target type,
-- not the source type in contexts such as assignments
Insert_Valid_Check (Expr);
end Ensure_Valid;
----------------------
-- Expr_Known_Valid --
----------------------
function Expr_Known_Valid (Expr : Node_Id) return Boolean is
Typ : constant Entity_Id := Etype (Expr);
begin
-- Non-scalar types are always considered valid, since they never
-- give rise to the issues of erroneous or bounded error behavior
-- that are the concern. In formal reference manual terms the
-- notion of validity only applies to scalar types. Note that
-- even when packed arrays are represented using modular types,
-- they are still arrays semantically, so they are also always
-- valid (in particular, the unused bits can be random rubbish
-- without affecting the validity of the array value).
if not Is_Scalar_Type (Typ) or else Is_Packed_Array_Type (Typ) then
return True;
-- If no validity checking, then everything is considered valid
elsif not Validity_Checks_On then
return True;
-- Floating-point types are considered valid unless floating-point
-- validity checks have been specifically turned on.
elsif Is_Floating_Point_Type (Typ)
and then not Validity_Check_Floating_Point
then
return True;
-- If the expression is the value of an object that is known to
-- be valid, then clearly the expression value itself is valid.
elsif Is_Entity_Name (Expr)
and then Is_Known_Valid (Entity (Expr))
then
return True;
-- If the type is one for which all values are known valid, then
-- we are sure that the value is valid except in the slightly odd
-- case where the expression is a reference to a variable whose size
-- has been explicitly set to a value greater than the object size.
elsif Is_Known_Valid (Typ) then
if Is_Entity_Name (Expr)
and then Ekind (Entity (Expr)) = E_Variable
and then Esize (Entity (Expr)) > Esize (Typ)
then
return False;
else
return True;
end if;
-- Integer and character literals always have valid values, where
-- appropriate these will be range checked in any case.
elsif Nkind (Expr) = N_Integer_Literal
or else
Nkind (Expr) = N_Character_Literal
then
return True;
-- If we have a type conversion or a qualification of a known valid
-- value, then the result will always be valid.
elsif Nkind (Expr) = N_Type_Conversion
or else
Nkind (Expr) = N_Qualified_Expression
then
return Expr_Known_Valid (Expression (Expr));
-- The result of any operator is always considered valid, since we
-- assume the necessary checks are done by the operator. For operators
-- on floating-point operations, we must also check when the operation
-- is the right-hand side of an assignment, or is an actual in a call.
elsif
Nkind (Expr) in N_Binary_Op or else Nkind (Expr) in N_Unary_Op
then
if Is_Floating_Point_Type (Typ)
and then Validity_Check_Floating_Point
and then
(Nkind (Parent (Expr)) = N_Assignment_Statement
or else Nkind (Parent (Expr)) = N_Function_Call
or else Nkind (Parent (Expr)) = N_Parameter_Association)
then
return False;
else
return True;
end if;
-- For all other cases, we do not know the expression is valid
else
return False;
end if;
end Expr_Known_Valid;
----------------
-- Find_Check --
----------------
procedure Find_Check
(Expr : Node_Id;
Check_Type : Character;
Target_Type : Entity_Id;
Entry_OK : out Boolean;
Check_Num : out Nat;
Ent : out Entity_Id;
Ofs : out Uint)
is
function Within_Range_Of
(Target_Type : Entity_Id;
Check_Type : Entity_Id) return Boolean;
-- Given a requirement for checking a range against Target_Type, and
-- and a range Check_Type against which a check has already been made,
-- determines if the check against check type is sufficient to ensure
-- that no check against Target_Type is required.
---------------------
-- Within_Range_Of --
---------------------
function Within_Range_Of
(Target_Type : Entity_Id;
Check_Type : Entity_Id) return Boolean
is
begin
if Target_Type = Check_Type then
return True;
else
declare
Tlo : constant Node_Id := Type_Low_Bound (Target_Type);
Thi : constant Node_Id := Type_High_Bound (Target_Type);
Clo : constant Node_Id := Type_Low_Bound (Check_Type);
Chi : constant Node_Id := Type_High_Bound (Check_Type);
begin
if (Tlo = Clo
or else (Compile_Time_Known_Value (Tlo)
and then
Compile_Time_Known_Value (Clo)
and then
Expr_Value (Clo) >= Expr_Value (Tlo)))
and then
(Thi = Chi
or else (Compile_Time_Known_Value (Thi)
and then
Compile_Time_Known_Value (Chi)
and then
Expr_Value (Chi) <= Expr_Value (Clo)))
then
return True;
else
return False;
end if;
end;
end if;
end Within_Range_Of;
-- Start of processing for Find_Check
begin
-- Establish default, to avoid warnings from GCC
Check_Num := 0;
-- Case of expression is simple entity reference
if Is_Entity_Name (Expr) then
Ent := Entity (Expr);
Ofs := Uint_0;
-- Case of expression is entity + known constant
elsif Nkind (Expr) = N_Op_Add
and then Compile_Time_Known_Value (Right_Opnd (Expr))
and then Is_Entity_Name (Left_Opnd (Expr))
then
Ent := Entity (Left_Opnd (Expr));
Ofs := Expr_Value (Right_Opnd (Expr));
-- Case of expression is entity - known constant
elsif Nkind (Expr) = N_Op_Subtract
and then Compile_Time_Known_Value (Right_Opnd (Expr))
and then Is_Entity_Name (Left_Opnd (Expr))
then
Ent := Entity (Left_Opnd (Expr));
Ofs := UI_Negate (Expr_Value (Right_Opnd (Expr)));
-- Any other expression is not of the right form
else
Ent := Empty;
Ofs := Uint_0;
Entry_OK := False;
return;
end if;
-- Come here with expression of appropriate form, check if
-- entity is an appropriate one for our purposes.
if (Ekind (Ent) = E_Variable
or else
Ekind (Ent) = E_Constant
or else
Ekind (Ent) = E_Loop_Parameter
or else
Ekind (Ent) = E_In_Parameter)
and then not Is_Library_Level_Entity (Ent)
then
Entry_OK := True;
else
Entry_OK := False;
return;
end if;
-- See if there is matching check already
for J in reverse 1 .. Num_Saved_Checks loop
declare
SC : Saved_Check renames Saved_Checks (J);
begin
if SC.Killed = False
and then SC.Entity = Ent
and then SC.Offset = Ofs
and then SC.Check_Type = Check_Type
and then Within_Range_Of (Target_Type, SC.Target_Type)
then
Check_Num := J;
return;
end if;
end;
end loop;
-- If we fall through entry was not found
Check_Num := 0;
return;
end Find_Check;
---------------------------------
-- Generate_Discriminant_Check --
---------------------------------
-- Note: the code for this procedure is derived from the
-- emit_discriminant_check routine a-trans.c v1.659.
procedure Generate_Discriminant_Check (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Pref : constant Node_Id := Prefix (N);
Sel : constant Node_Id := Selector_Name (N);
Orig_Comp : constant Entity_Id :=
Original_Record_Component (Entity (Sel));
-- The original component to be checked
Discr_Fct : constant Entity_Id :=
Discriminant_Checking_Func (Orig_Comp);
-- The discriminant checking function
Discr : Entity_Id;
-- One discriminant to be checked in the type
Real_Discr : Entity_Id;
-- Actual discriminant in the call
Pref_Type : Entity_Id;
-- Type of relevant prefix (ignoring private/access stuff)
Args : List_Id;
-- List of arguments for function call
Formal : Entity_Id;
-- Keep track of the formal corresponding to the actual we build
-- for each discriminant, in order to be able to perform the
-- necessary type conversions.
Scomp : Node_Id;
-- Selected component reference for checking function argument
begin
Pref_Type := Etype (Pref);
-- Force evaluation of the prefix, so that it does not get evaluated
-- twice (once for the check, once for the actual reference). Such a
-- double evaluation is always a potential source of inefficiency,
-- and is functionally incorrect in the volatile case, or when the
-- prefix may have side-effects. An entity or a component of an
-- entity requires no evaluation.
if Is_Entity_Name (Pref) then
if Treat_As_Volatile (Entity (Pref)) then
Force_Evaluation (Pref, Name_Req => True);
end if;
elsif Treat_As_Volatile (Etype (Pref)) then
Force_Evaluation (Pref, Name_Req => True);
elsif Nkind (Pref) = N_Selected_Component
and then Is_Entity_Name (Prefix (Pref))
then
null;
else
Force_Evaluation (Pref, Name_Req => True);
end if;
-- For a tagged type, use the scope of the original component to
-- obtain the type, because ???
if Is_Tagged_Type (Scope (Orig_Comp)) then
Pref_Type := Scope (Orig_Comp);
-- For an untagged derived type, use the discriminants of the
-- parent which have been renamed in the derivation, possibly
-- by a one-to-many discriminant constraint.
-- For non-tagged type, initially get the Etype of the prefix
else
if Is_Derived_Type (Pref_Type)
and then Number_Discriminants (Pref_Type) /=
Number_Discriminants (Etype (Base_Type (Pref_Type)))
then
Pref_Type := Etype (Base_Type (Pref_Type));
end if;
end if;
-- We definitely should have a checking function, This routine should
-- not be called if no discriminant checking function is present.
pragma Assert (Present (Discr_Fct));
-- Create the list of the actual parameters for the call. This list
-- is the list of the discriminant fields of the record expression to
-- be discriminant checked.
Args := New_List;
Formal := First_Formal (Discr_Fct);
Discr := First_Discriminant (Pref_Type);
while Present (Discr) loop
-- If we have a corresponding discriminant field, and a parent
-- subtype is present, then we want to use the corresponding
-- discriminant since this is the one with the useful value.
if Present (Corresponding_Discriminant (Discr))
and then Ekind (Pref_Type) = E_Record_Type
and then Present (Parent_Subtype (Pref_Type))
then
Real_Discr := Corresponding_Discriminant (Discr);
else
Real_Discr := Discr;
end if;
-- Construct the reference to the discriminant
Scomp :=
Make_Selected_Component (Loc,
Prefix =>
Unchecked_Convert_To (Pref_Type,
Duplicate_Subexpr (Pref)),
Selector_Name => New_Occurrence_Of (Real_Discr, Loc));
-- Manually analyze and resolve this selected component. We really
-- want it just as it appears above, and do not want the expander
-- playing discriminal games etc with this reference. Then we
-- append the argument to the list we are gathering.
Set_Etype (Scomp, Etype (Real_Discr));
Set_Analyzed (Scomp, True);
Append_To (Args, Convert_To (Etype (Formal), Scomp));
Next_Formal_With_Extras (Formal);
Next_Discriminant (Discr);
end loop;
-- Now build and insert the call
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Function_Call (Loc,
Name => New_Occurrence_Of (Discr_Fct, Loc),
Parameter_Associations => Args),
Reason => CE_Discriminant_Check_Failed));
end Generate_Discriminant_Check;
---------------------------
-- Generate_Index_Checks --
---------------------------
procedure Generate_Index_Checks (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
A : constant Node_Id := Prefix (N);
Sub : Node_Id;
Ind : Nat;
Num : List_Id;
begin
Sub := First (Expressions (N));
Ind := 1;
while Present (Sub) loop
if Do_Range_Check (Sub) then
Set_Do_Range_Check (Sub, False);
-- Force evaluation except for the case of a simple name of
-- a non-volatile entity.
if not Is_Entity_Name (Sub)
or else Treat_As_Volatile (Entity (Sub))
then
Force_Evaluation (Sub);
end if;
-- Generate a raise of constraint error with the appropriate
-- reason and a condition of the form:
-- Base_Type(Sub) not in array'range (subscript)
-- Note that the reason we generate the conversion to the
-- base type here is that we definitely want the range check
-- to take place, even if it looks like the subtype is OK.
-- Optimization considerations that allow us to omit the
-- check have already been taken into account in the setting
-- of the Do_Range_Check flag earlier on.
if Ind = 1 then
Num := No_List;
else
Num := New_List (Make_Integer_Literal (Loc, Ind));
end if;
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Not_In (Loc,
Left_Opnd =>
Convert_To (Base_Type (Etype (Sub)),
Duplicate_Subexpr_Move_Checks (Sub)),
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => Duplicate_Subexpr_Move_Checks (A),
Attribute_Name => Name_Range,
Expressions => Num)),
Reason => CE_Index_Check_Failed));
end if;
Ind := Ind + 1;
Next (Sub);
end loop;
end Generate_Index_Checks;
--------------------------
-- Generate_Range_Check --
--------------------------
procedure Generate_Range_Check
(N : Node_Id;
Target_Type : Entity_Id;
Reason : RT_Exception_Code)
is
Loc : constant Source_Ptr := Sloc (N);
Source_Type : constant Entity_Id := Etype (N);
Source_Base_Type : constant Entity_Id := Base_Type (Source_Type);
Target_Base_Type : constant Entity_Id := Base_Type (Target_Type);
begin
-- First special case, if the source type is already within the
-- range of the target type, then no check is needed (probably we
-- should have stopped Do_Range_Check from being set in the first
-- place, but better late than later in preventing junk code!
-- We do NOT apply this if the source node is a literal, since in
-- this case the literal has already been labeled as having the
-- subtype of the target.
if In_Subrange_Of (Source_Type, Target_Type)
and then not
(Nkind (N) = N_Integer_Literal
or else
Nkind (N) = N_Real_Literal
or else
Nkind (N) = N_Character_Literal
or else
(Is_Entity_Name (N)
and then Ekind (Entity (N)) = E_Enumeration_Literal))
then
return;
end if;
-- We need a check, so force evaluation of the node, so that it does
-- not get evaluated twice (once for the check, once for the actual
-- reference). Such a double evaluation is always a potential source
-- of inefficiency, and is functionally incorrect in the volatile case.
if not Is_Entity_Name (N)
or else Treat_As_Volatile (Entity (N))
then
Force_Evaluation (N);
end if;
-- The easiest case is when Source_Base_Type and Target_Base_Type
-- are the same since in this case we can simply do a direct
-- check of the value of N against the bounds of Target_Type.
-- [constraint_error when N not in Target_Type]
-- Note: this is by far the most common case, for example all cases of
-- checks on the RHS of assignments are in this category, but not all
-- cases are like this. Notably conversions can involve two types.
if Source_Base_Type = Target_Base_Type then
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Not_In (Loc,
Left_Opnd => Duplicate_Subexpr (N),
Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
Reason => Reason));
-- Next test for the case where the target type is within the bounds
-- of the base type of the source type, since in this case we can
-- simply convert these bounds to the base type of T to do the test.
-- [constraint_error when N not in
-- Source_Base_Type (Target_Type'First)
-- ..
-- Source_Base_Type(Target_Type'Last))]
-- The conversions will always work and need no check
elsif In_Subrange_Of (Target_Type, Source_Base_Type) then
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Not_In (Loc,
Left_Opnd => Duplicate_Subexpr (N),
Right_Opnd =>
Make_Range (Loc,
Low_Bound =>
Convert_To (Source_Base_Type,
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_First)),
High_Bound =>
Convert_To (Source_Base_Type,
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_Last)))),
Reason => Reason));
-- Note that at this stage we now that the Target_Base_Type is
-- not in the range of the Source_Base_Type (since even the
-- Target_Type itself is not in this range). It could still be
-- the case that the Source_Type is in range of the target base
-- type, since we have not checked that case.
-- If that is the case, we can freely convert the source to the
-- target, and then test the target result against the bounds.
elsif In_Subrange_Of (Source_Type, Target_Base_Type) then
-- We make a temporary to hold the value of the converted
-- value (converted to the base type), and then we will
-- do the test against this temporary.
-- Tnn : constant Target_Base_Type := Target_Base_Type (N);
-- [constraint_error when Tnn not in Target_Type]
-- Then the conversion itself is replaced by an occurrence of Tnn
declare
Tnn : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => New_Internal_Name ('T'));
begin
Insert_Actions (N, New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Tnn,
Object_Definition =>
New_Occurrence_Of (Target_Base_Type, Loc),
Constant_Present => True,
Expression =>
Make_Type_Conversion (Loc,
Subtype_Mark => New_Occurrence_Of (Target_Base_Type, Loc),
Expression => Duplicate_Subexpr (N))),
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Not_In (Loc,
Left_Opnd => New_Occurrence_Of (Tnn, Loc),
Right_Opnd => New_Occurrence_Of (Target_Type, Loc)),
Reason => Reason)));
Rewrite (N, New_Occurrence_Of (Tnn, Loc));
end;
-- At this stage, we know that we have two scalar types, which are
-- directly convertible, and where neither scalar type has a base
-- range that is in the range of the other scalar type.
-- The only way this can happen is with a signed and unsigned type.
-- So test for these two cases:
else
-- Case of the source is unsigned and the target is signed
if Is_Unsigned_Type (Source_Base_Type)
and then not Is_Unsigned_Type (Target_Base_Type)
then
-- If the source is unsigned and the target is signed, then we
-- know that the source is not shorter than the target (otherwise
-- the source base type would be in the target base type range).
-- In other words, the unsigned type is either the same size
-- as the target, or it is larger. It cannot be smaller.
pragma Assert
(Esize (Source_Base_Type) >= Esize (Target_Base_Type));
-- We only need to check the low bound if the low bound of the
-- target type is non-negative. If the low bound of the target
-- type is negative, then we know that we will fit fine.
-- If the high bound of the target type is negative, then we
-- know we have a constraint error, since we can't possibly
-- have a negative source.
-- With these two checks out of the way, we can do the check
-- using the source type safely
-- This is definitely the most annoying case!
-- [constraint_error
-- when (Target_Type'First >= 0
-- and then
-- N < Source_Base_Type (Target_Type'First))
-- or else Target_Type'Last < 0
-- or else N > Source_Base_Type (Target_Type'Last)];
-- We turn off all checks since we know that the conversions
-- will work fine, given the guards for negative values.
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Or_Else (Loc,
Make_Or_Else (Loc,
Left_Opnd =>
Make_And_Then (Loc,
Left_Opnd => Make_Op_Ge (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_First),
Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
Right_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd => Duplicate_Subexpr (N),
Right_Opnd =>
Convert_To (Source_Base_Type,
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_First)))),
Right_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_Last),
Right_Opnd => Make_Integer_Literal (Loc, Uint_0))),
Right_Opnd =>
Make_Op_Gt (Loc,
Left_Opnd => Duplicate_Subexpr (N),
Right_Opnd =>
Convert_To (Source_Base_Type,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Target_Type, Loc),
Attribute_Name => Name_Last)))),
Reason => Reason),
Suppress => All_Checks);
-- Only remaining possibility is that the source is signed and
-- the target is unsigned
else
pragma Assert (not Is_Unsigned_Type (Source_Base_Type)
and then Is_Unsigned_Type (Target_Base_Type));
-- If the source is signed and the target is unsigned, then
-- we know that the target is not shorter than the source
-- (otherwise the target base type would be in the source
-- base type range).
-- In other words, the unsigned type is either the same size
-- as the target, or it is larger. It cannot be smaller.
-- Clearly we have an error if the source value is negative
-- since no unsigned type can have negative values. If the
-- source type is non-negative, then the check can be done
-- using the target type.
-- Tnn : constant Target_Base_Type (N) := Target_Type;
-- [constraint_error
-- when N < 0 or else Tnn not in Target_Type];
-- We turn off all checks for the conversion of N to the
-- target base type, since we generate the explicit check
-- to ensure that the value is non-negative
declare
Tnn : constant Entity_Id :=
Make_Defining_Identifier (Loc,
Chars => New_Internal_Name ('T'));
begin
Insert_Actions (N, New_List (
Make_Object_Declaration (Loc,
Defining_Identifier => Tnn,
Object_Definition =>
New_Occurrence_Of (Target_Base_Type, Loc),
Constant_Present => True,
Expression =>
Make_Type_Conversion (Loc,
Subtype_Mark =>
New_Occurrence_Of (Target_Base_Type, Loc),
Expression => Duplicate_Subexpr (N))),
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd => Duplicate_Subexpr (N),
Right_Opnd => Make_Integer_Literal (Loc, Uint_0)),
Right_Opnd =>
Make_Not_In (Loc,
Left_Opnd => New_Occurrence_Of (Tnn, Loc),
Right_Opnd =>
New_Occurrence_Of (Target_Type, Loc))),
Reason => Reason)),
Suppress => All_Checks);
-- Set the Etype explicitly, because Insert_Actions may
-- have placed the declaration in the freeze list for an
-- enclosing construct, and thus it is not analyzed yet.
Set_Etype (Tnn, Target_Base_Type);
Rewrite (N, New_Occurrence_Of (Tnn, Loc));
end;
end if;
end if;
end Generate_Range_Check;
---------------------
-- Get_Discriminal --
---------------------
function Get_Discriminal (E : Entity_Id; Bound : Node_Id) return Node_Id is
Loc : constant Source_Ptr := Sloc (E);
D : Entity_Id;
Sc : Entity_Id;
begin
-- The entity E is the type of a private component of the protected
-- type, or the type of a renaming of that component within a protected
-- operation of that type.
Sc := Scope (E);
if Ekind (Sc) /= E_Protected_Type then
Sc := Scope (Sc);
if Ekind (Sc) /= E_Protected_Type then
return Bound;
end if;
end if;
D := First_Discriminant (Sc);
while Present (D)
and then Chars (D) /= Chars (Bound)
loop
Next_Discriminant (D);
end loop;
return New_Occurrence_Of (Discriminal (D), Loc);
end Get_Discriminal;
------------------
-- Guard_Access --
------------------
function Guard_Access
(Cond : Node_Id;
Loc : Source_Ptr;
Ck_Node : Node_Id) return Node_Id
is
begin
if Nkind (Cond) = N_Or_Else then
Set_Paren_Count (Cond, 1);
end if;
if Nkind (Ck_Node) = N_Allocator then
return Cond;
else
return
Make_And_Then (Loc,
Left_Opnd =>
Make_Op_Ne (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (Ck_Node),
Right_Opnd => Make_Null (Loc)),
Right_Opnd => Cond);
end if;
end Guard_Access;
-----------------------------
-- Index_Checks_Suppressed --
-----------------------------
function Index_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Index_Check);
else
return Scope_Suppress (Index_Check);
end if;
end Index_Checks_Suppressed;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
for J in Determine_Range_Cache_N'Range loop
Determine_Range_Cache_N (J) := Empty;
end loop;
end Initialize;
-------------------------
-- Insert_Range_Checks --
-------------------------
procedure Insert_Range_Checks
(Checks : Check_Result;
Node : Node_Id;
Suppress_Typ : Entity_Id;
Static_Sloc : Source_Ptr := No_Location;
Flag_Node : Node_Id := Empty;
Do_Before : Boolean := False)
is
Internal_Flag_Node : Node_Id := Flag_Node;
Internal_Static_Sloc : Source_Ptr := Static_Sloc;
Check_Node : Node_Id;
Checks_On : constant Boolean :=
(not Index_Checks_Suppressed (Suppress_Typ))
or else
(not Range_Checks_Suppressed (Suppress_Typ));
begin
-- For now we just return if Checks_On is false, however this should
-- be enhanced to check for an always True value in the condition
-- and to generate a compilation warning???
if not Expander_Active or else not Checks_On then
return;
end if;
if Static_Sloc = No_Location then
Internal_Static_Sloc := Sloc (Node);
end if;
if No (Flag_Node) then
Internal_Flag_Node := Node;
end if;
for J in 1 .. 2 loop
exit when No (Checks (J));
if Nkind (Checks (J)) = N_Raise_Constraint_Error
and then Present (Condition (Checks (J)))
then
if not Has_Dynamic_Range_Check (Internal_Flag_Node) then
Check_Node := Checks (J);
Mark_Rewrite_Insertion (Check_Node);
if Do_Before then
Insert_Before_And_Analyze (Node, Check_Node);
else
Insert_After_And_Analyze (Node, Check_Node);
end if;
Set_Has_Dynamic_Range_Check (Internal_Flag_Node);
end if;
else
Check_Node :=
Make_Raise_Constraint_Error (Internal_Static_Sloc,
Reason => CE_Range_Check_Failed);
Mark_Rewrite_Insertion (Check_Node);
if Do_Before then
Insert_Before_And_Analyze (Node, Check_Node);
else
Insert_After_And_Analyze (Node, Check_Node);
end if;
end if;
end loop;
end Insert_Range_Checks;
------------------------
-- Insert_Valid_Check --
------------------------
procedure Insert_Valid_Check (Expr : Node_Id) is
Loc : constant Source_Ptr := Sloc (Expr);
Exp : Node_Id;
begin
-- Do not insert if checks off, or if not checking validity
if Range_Checks_Suppressed (Etype (Expr))
or else (not Validity_Checks_On)
then
return;
end if;
-- If we have a checked conversion, then validity check applies to
-- the expression inside the conversion, not the result, since if
-- the expression inside is valid, then so is the conversion result.
Exp := Expr;
while Nkind (Exp) = N_Type_Conversion loop
Exp := Expression (Exp);
end loop;
-- Insert the validity check. Note that we do this with validity
-- checks turned off, to avoid recursion, we do not want validity
-- checks on the validity checking code itself!
Validity_Checks_On := False;
Insert_Action
(Expr,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Op_Not (Loc,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix =>
Duplicate_Subexpr_No_Checks (Exp, Name_Req => True),
Attribute_Name => Name_Valid)),
Reason => CE_Invalid_Data),
Suppress => All_Checks);
-- If the expression is a a reference to an element of a bit-packed
-- array, it is rewritten as a renaming declaration. If the expression
-- is an actual in a call, it has not been expanded, waiting for the
-- proper point at which to do it. The same happens with renamings, so
-- that we have to force the expansion now. This non-local complication
-- is due to code in exp_ch2,adb, exp_ch4.adb and exp_ch6.adb.
if Is_Entity_Name (Exp)
and then Nkind (Parent (Entity (Exp))) = N_Object_Renaming_Declaration
then
declare
Old_Exp : constant Node_Id := Name (Parent (Entity (Exp)));
begin
if Nkind (Old_Exp) = N_Indexed_Component
and then Is_Bit_Packed_Array (Etype (Prefix (Old_Exp)))
then
Expand_Packed_Element_Reference (Old_Exp);
end if;
end;
end if;
Validity_Checks_On := True;
end Insert_Valid_Check;
----------------------------------
-- Install_Null_Excluding_Check --
----------------------------------
procedure Install_Null_Excluding_Check (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Typ : constant Entity_Id := Etype (N);
procedure Mark_Non_Null;
-- After installation of check, marks node as non-null if entity
-------------------
-- Mark_Non_Null --
-------------------
procedure Mark_Non_Null is
begin
if Is_Entity_Name (N) then
Set_Is_Known_Null (Entity (N), False);
if Safe_To_Capture_Value (N, Entity (N)) then
Set_Is_Known_Non_Null (Entity (N), True);
end if;
end if;
end Mark_Non_Null;
-- Start of processing for Install_Null_Excluding_Check
begin
pragma Assert (Is_Access_Type (Typ));
-- No check inside a generic (why not???)
if Inside_A_Generic then
return;
end if;
-- No check needed if known to be non-null
if Known_Non_Null (N) then
return;
end if;
-- If known to be null, here is where we generate a compile time check
if Known_Null (N) then
Apply_Compile_Time_Constraint_Error
(N,
"null value not allowed here?",
CE_Access_Check_Failed);
Mark_Non_Null;
return;
end if;
-- If entity is never assigned, for sure a warning is appropriate
if Is_Entity_Name (N) then
Check_Unset_Reference (N);
end if;
-- No check needed if checks are suppressed on the range. Note that we
-- don't set Is_Known_Non_Null in this case (we could legitimately do
-- so, since the program is erroneous, but we don't like to casually
-- propagate such conclusions from erroneosity).
if Access_Checks_Suppressed (Typ) then
return;
end if;
-- Otherwise install access check
Insert_Action (N,
Make_Raise_Constraint_Error (Loc,
Condition =>
Make_Op_Eq (Loc,
Left_Opnd => Duplicate_Subexpr_Move_Checks (N),
Right_Opnd => Make_Null (Loc)),
Reason => CE_Access_Check_Failed));
Mark_Non_Null;
end Install_Null_Excluding_Check;
--------------------------
-- Install_Static_Check --
--------------------------
procedure Install_Static_Check (R_Cno : Node_Id; Loc : Source_Ptr) is
Stat : constant Boolean := Is_Static_Expression (R_Cno);
Typ : constant Entity_Id := Etype (R_Cno);
begin
Rewrite (R_Cno,
Make_Raise_Constraint_Error (Loc,
Reason => CE_Range_Check_Failed));
Set_Analyzed (R_Cno);
Set_Etype (R_Cno, Typ);
Set_Raises_Constraint_Error (R_Cno);
Set_Is_Static_Expression (R_Cno, Stat);
end Install_Static_Check;
---------------------
-- Kill_All_Checks --
---------------------
procedure Kill_All_Checks is
begin
if Debug_Flag_CC then
w ("Kill_All_Checks");
end if;
-- We reset the number of saved checks to zero, and also modify
-- all stack entries for statement ranges to indicate that the
-- number of checks at each level is now zero.
Num_Saved_Checks := 0;
for J in 1 .. Saved_Checks_TOS loop
Saved_Checks_Stack (J) := 0;
end loop;
end Kill_All_Checks;
-----------------
-- Kill_Checks --
-----------------
procedure Kill_Checks (V : Entity_Id) is
begin
if Debug_Flag_CC then
w ("Kill_Checks for entity", Int (V));
end if;
for J in 1 .. Num_Saved_Checks loop
if Saved_Checks (J).Entity = V then
if Debug_Flag_CC then
w (" Checks killed for saved check ", J);
end if;
Saved_Checks (J).Killed := True;
end if;
end loop;
end Kill_Checks;
------------------------------
-- Length_Checks_Suppressed --
------------------------------
function Length_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Length_Check);
else
return Scope_Suppress (Length_Check);
end if;
end Length_Checks_Suppressed;
--------------------------------
-- Overflow_Checks_Suppressed --
--------------------------------
function Overflow_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Overflow_Check);
else
return Scope_Suppress (Overflow_Check);
end if;
end Overflow_Checks_Suppressed;
-----------------
-- Range_Check --
-----------------
function Range_Check
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id := Empty;
Warn_Node : Node_Id := Empty) return Check_Result
is
begin
return Selected_Range_Checks
(Ck_Node, Target_Typ, Source_Typ, Warn_Node);
end Range_Check;
-----------------------------
-- Range_Checks_Suppressed --
-----------------------------
function Range_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) then
-- Note: for now we always suppress range checks on Vax float types,
-- since Gigi does not know how to generate these checks.
if Vax_Float (E) then
return True;
elsif Kill_Range_Checks (E) then
return True;
elsif Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Range_Check);
end if;
end if;
return Scope_Suppress (Range_Check);
end Range_Checks_Suppressed;
-------------------
-- Remove_Checks --
-------------------
procedure Remove_Checks (Expr : Node_Id) is
Discard : Traverse_Result;
pragma Warnings (Off, Discard);
function Process (N : Node_Id) return Traverse_Result;
-- Process a single node during the traversal
function Traverse is new Traverse_Func (Process);
-- The traversal function itself
-------------
-- Process --
-------------
function Process (N : Node_Id) return Traverse_Result is
begin
if Nkind (N) not in N_Subexpr then
return Skip;
end if;
Set_Do_Range_Check (N, False);
case Nkind (N) is
when N_And_Then =>
Discard := Traverse (Left_Opnd (N));
return Skip;
when N_Attribute_Reference =>
Set_Do_Overflow_Check (N, False);
when N_Function_Call =>
Set_Do_Tag_Check (N, False);
when N_Op =>
Set_Do_Overflow_Check (N, False);
case Nkind (N) is
when N_Op_Divide =>
Set_Do_Division_Check (N, False);
when N_Op_And =>
Set_Do_Length_Check (N, False);
when N_Op_Mod =>
Set_Do_Division_Check (N, False);
when N_Op_Or =>
Set_Do_Length_Check (N, False);
when N_Op_Rem =>
Set_Do_Division_Check (N, False);
when N_Op_Xor =>
Set_Do_Length_Check (N, False);
when others =>
null;
end case;
when N_Or_Else =>
Discard := Traverse (Left_Opnd (N));
return Skip;
when N_Selected_Component =>
Set_Do_Discriminant_Check (N, False);
when N_Type_Conversion =>
Set_Do_Length_Check (N, False);
Set_Do_Tag_Check (N, False);
Set_Do_Overflow_Check (N, False);
when others =>
null;
end case;
return OK;
end Process;
-- Start of processing for Remove_Checks
begin
Discard := Traverse (Expr);
end Remove_Checks;
----------------------------
-- Selected_Length_Checks --
----------------------------
function Selected_Length_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Warn_Node : Node_Id) return Check_Result
is
Loc : constant Source_Ptr := Sloc (Ck_Node);
S_Typ : Entity_Id;
T_Typ : Entity_Id;
Expr_Actual : Node_Id;
Exptyp : Entity_Id;
Cond : Node_Id := Empty;
Do_Access : Boolean := False;
Wnode : Node_Id := Warn_Node;
Ret_Result : Check_Result := (Empty, Empty);
Num_Checks : Natural := 0;
procedure Add_Check (N : Node_Id);
-- Adds the action given to Ret_Result if N is non-Empty
function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id;
function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id;
-- Comments required ???
function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean;
-- True for equal literals and for nodes that denote the same constant
-- entity, even if its value is not a static constant. This includes the
-- case of a discriminal reference within an init proc. Removes some
-- obviously superfluous checks.
function Length_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id;
-- Returns expression to compute:
-- Typ'Length /= Exptyp'Length
function Length_N_Cond
(Expr : Node_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id;
-- Returns expression to compute:
-- Typ'Length /= Expr'Length
---------------
-- Add_Check --
---------------
procedure Add_Check (N : Node_Id) is
begin
if Present (N) then
-- For now, ignore attempt to place more than 2 checks ???
if Num_Checks = 2 then
return;
end if;
pragma Assert (Num_Checks <= 1);
Num_Checks := Num_Checks + 1;
Ret_Result (Num_Checks) := N;
end if;
end Add_Check;
------------------
-- Get_E_Length --
------------------
function Get_E_Length (E : Entity_Id; Indx : Nat) return Node_Id is
Pt : constant Entity_Id := Scope (Scope (E));
N : Node_Id;
E1 : Entity_Id := E;
begin
if Ekind (Scope (E)) = E_Record_Type
and then Has_Discriminants (Scope (E))
then
N := Build_Discriminal_Subtype_Of_Component (E);
if Present (N) then
Insert_Action (Ck_Node, N);
E1 := Defining_Identifier (N);
end if;
end if;
if Ekind (E1) = E_String_Literal_Subtype then
return
Make_Integer_Literal (Loc,
Intval => String_Literal_Length (E1));
elsif Ekind (Pt) = E_Protected_Type
and then Has_Discriminants (Pt)
and then Has_Completion (Pt)
and then not Inside_Init_Proc
then
-- If the type whose length is needed is a private component
-- constrained by a discriminant, we must expand the 'Length
-- attribute into an explicit computation, using the discriminal
-- of the current protected operation. This is because the actual
-- type of the prival is constructed after the protected opera-
-- tion has been fully expanded.
declare
Indx_Type : Node_Id;
Lo : Node_Id;
Hi : Node_Id;
Do_Expand : Boolean := False;
begin
Indx_Type := First_Index (E);
for J in 1 .. Indx - 1 loop
Next_Index (Indx_Type);
end loop;
Get_Index_Bounds (Indx_Type, Lo, Hi);
if Nkind (Lo) = N_Identifier
and then Ekind (Entity (Lo)) = E_In_Parameter
then
Lo := Get_Discriminal (E, Lo);
Do_Expand := True;
end if;
if Nkind (Hi) = N_Identifier
and then Ekind (Entity (Hi)) = E_In_Parameter
then
Hi := Get_Discriminal (E, Hi);
Do_Expand := True;
end if;
if Do_Expand then
if not Is_Entity_Name (Lo) then
Lo := Duplicate_Subexpr_No_Checks (Lo);
end if;
if not Is_Entity_Name (Hi) then
Lo := Duplicate_Subexpr_No_Checks (Hi);
end if;
N :=
Make_Op_Add (Loc,
Left_Opnd =>
Make_Op_Subtract (Loc,
Left_Opnd => Hi,
Right_Opnd => Lo),
Right_Opnd => Make_Integer_Literal (Loc, 1));
return N;
else
N :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Length,
Prefix =>
New_Occurrence_Of (E1, Loc));
if Indx > 1 then
Set_Expressions (N, New_List (
Make_Integer_Literal (Loc, Indx)));
end if;
return N;
end if;
end;
else
N :=
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Length,
Prefix =>
New_Occurrence_Of (E1, Loc));
if Indx > 1 then
Set_Expressions (N, New_List (
Make_Integer_Literal (Loc, Indx)));
end if;
return N;
end if;
end Get_E_Length;
------------------
-- Get_N_Length --
------------------
function Get_N_Length (N : Node_Id; Indx : Nat) return Node_Id is
begin
return
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Length,
Prefix =>
Duplicate_Subexpr_No_Checks (N, Name_Req => True),
Expressions => New_List (
Make_Integer_Literal (Loc, Indx)));
end Get_N_Length;
-------------------
-- Length_E_Cond --
-------------------
function Length_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id
is
begin
return
Make_Op_Ne (Loc,
Left_Opnd => Get_E_Length (Typ, Indx),
Right_Opnd => Get_E_Length (Exptyp, Indx));
end Length_E_Cond;
-------------------
-- Length_N_Cond --
-------------------
function Length_N_Cond
(Expr : Node_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id
is
begin
return
Make_Op_Ne (Loc,
Left_Opnd => Get_E_Length (Typ, Indx),
Right_Opnd => Get_N_Length (Expr, Indx));
end Length_N_Cond;
function Same_Bounds (L : Node_Id; R : Node_Id) return Boolean is
begin
return
(Nkind (L) = N_Integer_Literal
and then Nkind (R) = N_Integer_Literal
and then Intval (L) = Intval (R))
or else
(Is_Entity_Name (L)
and then Ekind (Entity (L)) = E_Constant
and then ((Is_Entity_Name (R)
and then Entity (L) = Entity (R))
or else
(Nkind (R) = N_Type_Conversion
and then Is_Entity_Name (Expression (R))
and then Entity (L) = Entity (Expression (R)))))
or else
(Is_Entity_Name (R)
and then Ekind (Entity (R)) = E_Constant
and then Nkind (L) = N_Type_Conversion
and then Is_Entity_Name (Expression (L))
and then Entity (R) = Entity (Expression (L)))
or else
(Is_Entity_Name (L)
and then Is_Entity_Name (R)
and then Entity (L) = Entity (R)
and then Ekind (Entity (L)) = E_In_Parameter
and then Inside_Init_Proc);
end Same_Bounds;
-- Start of processing for Selected_Length_Checks
begin
if not Expander_Active then
return Ret_Result;
end if;
if Target_Typ = Any_Type
or else Target_Typ = Any_Composite
or else Raises_Constraint_Error (Ck_Node)
then
return Ret_Result;
end if;
if No (Wnode) then
Wnode := Ck_Node;
end if;
T_Typ := Target_Typ;
if No (Source_Typ) then
S_Typ := Etype (Ck_Node);
else
S_Typ := Source_Typ;
end if;
if S_Typ = Any_Type or else S_Typ = Any_Composite then
return Ret_Result;
end if;
if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
S_Typ := Designated_Type (S_Typ);
T_Typ := Designated_Type (T_Typ);
Do_Access := True;
-- A simple optimization
if Nkind (Ck_Node) = N_Null then
return Ret_Result;
end if;
end if;
if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
if Is_Constrained (T_Typ) then
-- The checking code to be generated will freeze the
-- corresponding array type. However, we must freeze the
-- type now, so that the freeze node does not appear within
-- the generated condional expression, but ahead of it.
Freeze_Before (Ck_Node, T_Typ);
Expr_Actual := Get_Referenced_Object (Ck_Node);
Exptyp := Get_Actual_Subtype (Ck_Node);
if Is_Access_Type (Exptyp) then
Exptyp := Designated_Type (Exptyp);
end if;
-- String_Literal case. This needs to be handled specially be-
-- cause no index types are available for string literals. The
-- condition is simply:
-- T_Typ'Length = string-literal-length
if Nkind (Expr_Actual) = N_String_Literal
and then Ekind (Etype (Expr_Actual)) = E_String_Literal_Subtype
then
Cond :=
Make_Op_Ne (Loc,
Left_Opnd => Get_E_Length (T_Typ, 1),
Right_Opnd =>
Make_Integer_Literal (Loc,
Intval =>
String_Literal_Length (Etype (Expr_Actual))));
-- General array case. Here we have a usable actual subtype for
-- the expression, and the condition is built from the two types
-- (Do_Length):
-- T_Typ'Length /= Exptyp'Length or else
-- T_Typ'Length (2) /= Exptyp'Length (2) or else
-- T_Typ'Length (3) /= Exptyp'Length (3) or else
-- ...
elsif Is_Constrained (Exptyp) then
declare
Ndims : constant Nat := Number_Dimensions (T_Typ);
L_Index : Node_Id;
R_Index : Node_Id;
L_Low : Node_Id;
L_High : Node_Id;
R_Low : Node_Id;
R_High : Node_Id;
L_Length : Uint;
R_Length : Uint;
Ref_Node : Node_Id;
begin
-- At the library level, we need to ensure that the
-- type of the object is elaborated before the check
-- itself is emitted. This is only done if the object
-- is in the current compilation unit, otherwise the
-- type is frozen and elaborated in its unit.
if Is_Itype (Exptyp)
and then
Ekind (Cunit_Entity (Current_Sem_Unit)) = E_Package
and then
not In_Package_Body (Cunit_Entity (Current_Sem_Unit))
and then In_Open_Scopes (Scope (Exptyp))
then
Ref_Node := Make_Itype_Reference (Sloc (Ck_Node));
Set_Itype (Ref_Node, Exptyp);
Insert_Action (Ck_Node, Ref_Node);
end if;
L_Index := First_Index (T_Typ);
R_Index := First_Index (Exptyp);
for Indx in 1 .. Ndims loop
if not (Nkind (L_Index) = N_Raise_Constraint_Error
or else
Nkind (R_Index) = N_Raise_Constraint_Error)
then
Get_Index_Bounds (L_Index, L_Low, L_High);
Get_Index_Bounds (R_Index, R_Low, R_High);
-- Deal with compile time length check. Note that we
-- skip this in the access case, because the access
-- value may be null, so we cannot know statically.
if not Do_Access
and then Compile_Time_Known_Value (L_Low)
and then Compile_Time_Known_Value (L_High)
and then Compile_Time_Known_Value (R_Low)
and then Compile_Time_Known_Value (R_High)
then
if Expr_Value (L_High) >= Expr_Value (L_Low) then
L_Length := Expr_Value (L_High) -
Expr_Value (L_Low) + 1;
else
L_Length := UI_From_Int (0);
end if;
if Expr_Value (R_High) >= Expr_Value (R_Low) then
R_Length := Expr_Value (R_High) -
Expr_Value (R_Low) + 1;
else
R_Length := UI_From_Int (0);
end if;
if L_Length > R_Length then
Add_Check
(Compile_Time_Constraint_Error
(Wnode, "too few elements for}?", T_Typ));
elsif L_Length < R_Length then
Add_Check
(Compile_Time_Constraint_Error
(Wnode, "too many elements for}?", T_Typ));
end if;
-- The comparison for an individual index subtype
-- is omitted if the corresponding index subtypes
-- statically match, since the result is known to
-- be true. Note that this test is worth while even
-- though we do static evaluation, because non-static
-- subtypes can statically match.
elsif not
Subtypes_Statically_Match
(Etype (L_Index), Etype (R_Index))
and then not
(Same_Bounds (L_Low, R_Low)
and then Same_Bounds (L_High, R_High))
then
Evolve_Or_Else
(Cond, Length_E_Cond (Exptyp, T_Typ, Indx));
end if;
Next (L_Index);
Next (R_Index);
end if;
end loop;
end;
-- Handle cases where we do not get a usable actual subtype that
-- is constrained. This happens for example in the function call
-- and explicit dereference cases. In these cases, we have to get
-- the length or range from the expression itself, making sure we
-- do not evaluate it more than once.
-- Here Ck_Node is the original expression, or more properly the
-- result of applying Duplicate_Expr to the original tree,
-- forcing the result to be a name.
else
declare
Ndims : constant Nat := Number_Dimensions (T_Typ);
begin
-- Build the condition for the explicit dereference case
for Indx in 1 .. Ndims loop
Evolve_Or_Else
(Cond, Length_N_Cond (Ck_Node, T_Typ, Indx));
end loop;
end;
end if;
end if;
end if;
-- Construct the test and insert into the tree
if Present (Cond) then
if Do_Access then
Cond := Guard_Access (Cond, Loc, Ck_Node);
end if;
Add_Check
(Make_Raise_Constraint_Error (Loc,
Condition => Cond,
Reason => CE_Length_Check_Failed));
end if;
return Ret_Result;
end Selected_Length_Checks;
---------------------------
-- Selected_Range_Checks --
---------------------------
function Selected_Range_Checks
(Ck_Node : Node_Id;
Target_Typ : Entity_Id;
Source_Typ : Entity_Id;
Warn_Node : Node_Id) return Check_Result
is
Loc : constant Source_Ptr := Sloc (Ck_Node);
S_Typ : Entity_Id;
T_Typ : Entity_Id;
Expr_Actual : Node_Id;
Exptyp : Entity_Id;
Cond : Node_Id := Empty;
Do_Access : Boolean := False;
Wnode : Node_Id := Warn_Node;
Ret_Result : Check_Result := (Empty, Empty);
Num_Checks : Integer := 0;
procedure Add_Check (N : Node_Id);
-- Adds the action given to Ret_Result if N is non-Empty
function Discrete_Range_Cond
(Expr : Node_Id;
Typ : Entity_Id) return Node_Id;
-- Returns expression to compute:
-- Low_Bound (Expr) < Typ'First
-- or else
-- High_Bound (Expr) > Typ'Last
function Discrete_Expr_Cond
(Expr : Node_Id;
Typ : Entity_Id) return Node_Id;
-- Returns expression to compute:
-- Expr < Typ'First
-- or else
-- Expr > Typ'Last
function Get_E_First_Or_Last
(E : Entity_Id;
Indx : Nat;
Nam : Name_Id) return Node_Id;
-- Returns expression to compute:
-- E'First or E'Last
function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id;
function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id;
-- Returns expression to compute:
-- N'First or N'Last using Duplicate_Subexpr_No_Checks
function Range_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat)
return Node_Id;
-- Returns expression to compute:
-- Exptyp'First < Typ'First or else Exptyp'Last > Typ'Last
function Range_Equal_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id;
-- Returns expression to compute:
-- Exptyp'First /= Typ'First or else Exptyp'Last /= Typ'Last
function Range_N_Cond
(Expr : Node_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id;
-- Return expression to compute:
-- Expr'First < Typ'First or else Expr'Last > Typ'Last
---------------
-- Add_Check --
---------------
procedure Add_Check (N : Node_Id) is
begin
if Present (N) then
-- For now, ignore attempt to place more than 2 checks ???
if Num_Checks = 2 then
return;
end if;
pragma Assert (Num_Checks <= 1);
Num_Checks := Num_Checks + 1;
Ret_Result (Num_Checks) := N;
end if;
end Add_Check;
-------------------------
-- Discrete_Expr_Cond --
-------------------------
function Discrete_Expr_Cond
(Expr : Node_Id;
Typ : Entity_Id) return Node_Id
is
begin
return
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd =>
Convert_To (Base_Type (Typ),
Duplicate_Subexpr_No_Checks (Expr)),
Right_Opnd =>
Convert_To (Base_Type (Typ),
Get_E_First_Or_Last (Typ, 0, Name_First))),
Right_Opnd =>
Make_Op_Gt (Loc,
Left_Opnd =>
Convert_To (Base_Type (Typ),
Duplicate_Subexpr_No_Checks (Expr)),
Right_Opnd =>
Convert_To
(Base_Type (Typ),
Get_E_First_Or_Last (Typ, 0, Name_Last))));
end Discrete_Expr_Cond;
-------------------------
-- Discrete_Range_Cond --
-------------------------
function Discrete_Range_Cond
(Expr : Node_Id;
Typ : Entity_Id) return Node_Id
is
LB : Node_Id := Low_Bound (Expr);
HB : Node_Id := High_Bound (Expr);
Left_Opnd : Node_Id;
Right_Opnd : Node_Id;
begin
if Nkind (LB) = N_Identifier
and then Ekind (Entity (LB)) = E_Discriminant then
LB := New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
end if;
if Nkind (HB) = N_Identifier
and then Ekind (Entity (HB)) = E_Discriminant then
HB := New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
end if;
Left_Opnd :=
Make_Op_Lt (Loc,
Left_Opnd =>
Convert_To
(Base_Type (Typ), Duplicate_Subexpr_No_Checks (LB)),
Right_Opnd =>
Convert_To
(Base_Type (Typ), Get_E_First_Or_Last (Typ, 0, Name_First)));
if Base_Type (Typ) = Typ then
return Left_Opnd;
elsif Compile_Time_Known_Value (High_Bound (Scalar_Range (Typ)))
and then
Compile_Time_Known_Value (High_Bound (Scalar_Range
(Base_Type (Typ))))
then
if Is_Floating_Point_Type (Typ) then
if Expr_Value_R (High_Bound (Scalar_Range (Typ))) =
Expr_Value_R (High_Bound (Scalar_Range (Base_Type (Typ))))
then
return Left_Opnd;
end if;
else
if Expr_Value (High_Bound (Scalar_Range (Typ))) =
Expr_Value (High_Bound (Scalar_Range (Base_Type (Typ))))
then
return Left_Opnd;
end if;
end if;
end if;
Right_Opnd :=
Make_Op_Gt (Loc,
Left_Opnd =>
Convert_To
(Base_Type (Typ), Duplicate_Subexpr_No_Checks (HB)),
Right_Opnd =>
Convert_To
(Base_Type (Typ),
Get_E_First_Or_Last (Typ, 0, Name_Last)));
return Make_Or_Else (Loc, Left_Opnd, Right_Opnd);
end Discrete_Range_Cond;
-------------------------
-- Get_E_First_Or_Last --
-------------------------
function Get_E_First_Or_Last
(E : Entity_Id;
Indx : Nat;
Nam : Name_Id) return Node_Id
is
N : Node_Id;
LB : Node_Id;
HB : Node_Id;
Bound : Node_Id;
begin
if Is_Array_Type (E) then
N := First_Index (E);
for J in 2 .. Indx loop
Next_Index (N);
end loop;
else
N := Scalar_Range (E);
end if;
if Nkind (N) = N_Subtype_Indication then
LB := Low_Bound (Range_Expression (Constraint (N)));
HB := High_Bound (Range_Expression (Constraint (N)));
elsif Is_Entity_Name (N) then
LB := Type_Low_Bound (Etype (N));
HB := Type_High_Bound (Etype (N));
else
LB := Low_Bound (N);
HB := High_Bound (N);
end if;
if Nam = Name_First then
Bound := LB;
else
Bound := HB;
end if;
if Nkind (Bound) = N_Identifier
and then Ekind (Entity (Bound)) = E_Discriminant
then
-- If this is a task discriminant, and we are the body, we must
-- retrieve the corresponding body discriminal. This is another
-- consequence of the early creation of discriminals, and the
-- need to generate constraint checks before their declarations
-- are made visible.
if Is_Concurrent_Record_Type (Scope (Entity (Bound))) then
declare
Tsk : constant Entity_Id :=
Corresponding_Concurrent_Type
(Scope (Entity (Bound)));
Disc : Entity_Id;
begin
if In_Open_Scopes (Tsk)
and then Has_Completion (Tsk)
then
-- Find discriminant of original task, and use its
-- current discriminal, which is the renaming within
-- the task body.
Disc := First_Discriminant (Tsk);
while Present (Disc) loop
if Chars (Disc) = Chars (Entity (Bound)) then
Set_Scope (Discriminal (Disc), Tsk);
return New_Occurrence_Of (Discriminal (Disc), Loc);
end if;
Next_Discriminant (Disc);
end loop;
-- That loop should always succeed in finding a matching
-- entry and returning. Fatal error if not.
raise Program_Error;
else
return
New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
end if;
end;
else
return New_Occurrence_Of (Discriminal (Entity (Bound)), Loc);
end if;
elsif Nkind (Bound) = N_Identifier
and then Ekind (Entity (Bound)) = E_In_Parameter
and then not Inside_Init_Proc
then
return Get_Discriminal (E, Bound);
elsif Nkind (Bound) = N_Integer_Literal then
return Make_Integer_Literal (Loc, Intval (Bound));
-- Case of a bound that has been rewritten to an
-- N_Raise_Constraint_Error node because it is an out-of-range
-- value. We may not call Duplicate_Subexpr on this node because
-- an N_Raise_Constraint_Error is not side effect free, and we may
-- not assume that we are in the proper context to remove side
-- effects on it at the point of reference.
elsif Nkind (Bound) = N_Raise_Constraint_Error then
return New_Copy_Tree (Bound);
else
return Duplicate_Subexpr_No_Checks (Bound);
end if;
end Get_E_First_Or_Last;
-----------------
-- Get_N_First --
-----------------
function Get_N_First (N : Node_Id; Indx : Nat) return Node_Id is
begin
return
Make_Attribute_Reference (Loc,
Attribute_Name => Name_First,
Prefix =>
Duplicate_Subexpr_No_Checks (N, Name_Req => True),
Expressions => New_List (
Make_Integer_Literal (Loc, Indx)));
end Get_N_First;
----------------
-- Get_N_Last --
----------------
function Get_N_Last (N : Node_Id; Indx : Nat) return Node_Id is
begin
return
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Last,
Prefix =>
Duplicate_Subexpr_No_Checks (N, Name_Req => True),
Expressions => New_List (
Make_Integer_Literal (Loc, Indx)));
end Get_N_Last;
------------------
-- Range_E_Cond --
------------------
function Range_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id
is
begin
return
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
Right_Opnd =>
Make_Op_Gt (Loc,
Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
end Range_E_Cond;
------------------------
-- Range_Equal_E_Cond --
------------------------
function Range_Equal_E_Cond
(Exptyp : Entity_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id
is
begin
return
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Ne (Loc,
Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_First),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
Right_Opnd =>
Make_Op_Ne (Loc,
Left_Opnd => Get_E_First_Or_Last (Exptyp, Indx, Name_Last),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
end Range_Equal_E_Cond;
------------------
-- Range_N_Cond --
------------------
function Range_N_Cond
(Expr : Node_Id;
Typ : Entity_Id;
Indx : Nat) return Node_Id
is
begin
return
Make_Or_Else (Loc,
Left_Opnd =>
Make_Op_Lt (Loc,
Left_Opnd => Get_N_First (Expr, Indx),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_First)),
Right_Opnd =>
Make_Op_Gt (Loc,
Left_Opnd => Get_N_Last (Expr, Indx),
Right_Opnd => Get_E_First_Or_Last (Typ, Indx, Name_Last)));
end Range_N_Cond;
-- Start of processing for Selected_Range_Checks
begin
if not Expander_Active then
return Ret_Result;
end if;
if Target_Typ = Any_Type
or else Target_Typ = Any_Composite
or else Raises_Constraint_Error (Ck_Node)
then
return Ret_Result;
end if;
if No (Wnode) then
Wnode := Ck_Node;
end if;
T_Typ := Target_Typ;
if No (Source_Typ) then
S_Typ := Etype (Ck_Node);
else
S_Typ := Source_Typ;
end if;
if S_Typ = Any_Type or else S_Typ = Any_Composite then
return Ret_Result;
end if;
-- The order of evaluating T_Typ before S_Typ seems to be critical
-- because S_Typ can be derived from Etype (Ck_Node), if it's not passed
-- in, and since Node can be an N_Range node, it might be invalid.
-- Should there be an assert check somewhere for taking the Etype of
-- an N_Range node ???
if Is_Access_Type (T_Typ) and then Is_Access_Type (S_Typ) then
S_Typ := Designated_Type (S_Typ);
T_Typ := Designated_Type (T_Typ);
Do_Access := True;
-- A simple optimization
if Nkind (Ck_Node) = N_Null then
return Ret_Result;
end if;
end if;
-- For an N_Range Node, check for a null range and then if not
-- null generate a range check action.
if Nkind (Ck_Node) = N_Range then
-- There's no point in checking a range against itself
if Ck_Node = Scalar_Range (T_Typ) then
return Ret_Result;
end if;
declare
T_LB : constant Node_Id := Type_Low_Bound (T_Typ);
T_HB : constant Node_Id := Type_High_Bound (T_Typ);
LB : constant Node_Id := Low_Bound (Ck_Node);
HB : constant Node_Id := High_Bound (Ck_Node);
Null_Range : Boolean;
Out_Of_Range_L : Boolean;
Out_Of_Range_H : Boolean;
begin
-- Check for case where everything is static and we can
-- do the check at compile time. This is skipped if we
-- have an access type, since the access value may be null.
-- ??? This code can be improved since you only need to know
-- that the two respective bounds (LB & T_LB or HB & T_HB)
-- are known at compile time to emit pertinent messages.
if Compile_Time_Known_Value (LB)
and then Compile_Time_Known_Value (HB)
and then Compile_Time_Known_Value (T_LB)
and then Compile_Time_Known_Value (T_HB)
and then not Do_Access
then
-- Floating-point case
if Is_Floating_Point_Type (S_Typ) then
Null_Range := Expr_Value_R (HB) < Expr_Value_R (LB);
Out_Of_Range_L :=
(Expr_Value_R (LB) < Expr_Value_R (T_LB))
or else
(Expr_Value_R (LB) > Expr_Value_R (T_HB));
Out_Of_Range_H :=
(Expr_Value_R (HB) > Expr_Value_R (T_HB))
or else
(Expr_Value_R (HB) < Expr_Value_R (T_LB));
-- Fixed or discrete type case
else
Null_Range := Expr_Value (HB) < Expr_Value (LB);
Out_Of_Range_L :=
(Expr_Value (LB) < Expr_Value (T_LB))
or else
(Expr_Value (LB) > Expr_Value (T_HB));
Out_Of_Range_H :=
(Expr_Value (HB) > Expr_Value (T_HB))
or else
(Expr_Value (HB) < Expr_Value (T_LB));
end if;
if not Null_Range then
if Out_Of_Range_L then
if No (Warn_Node) then
Add_Check
(Compile_Time_Constraint_Error
(Low_Bound (Ck_Node),
"static value out of range of}?", T_Typ));
else
Add_Check
(Compile_Time_Constraint_Error
(Wnode,
"static range out of bounds of}?", T_Typ));
end if;
end if;
if Out_Of_Range_H then
if No (Warn_Node) then
Add_Check
(Compile_Time_Constraint_Error
(High_Bound (Ck_Node),
"static value out of range of}?", T_Typ));
else
Add_Check
(Compile_Time_Constraint_Error
(Wnode,
"static range out of bounds of}?", T_Typ));
end if;
end if;
end if;
else
declare
LB : Node_Id := Low_Bound (Ck_Node);
HB : Node_Id := High_Bound (Ck_Node);
begin
-- If either bound is a discriminant and we are within
-- the record declaration, it is a use of the discriminant
-- in a constraint of a component, and nothing can be
-- checked here. The check will be emitted within the
-- init proc. Before then, the discriminal has no real
-- meaning.
if Nkind (LB) = N_Identifier
and then Ekind (Entity (LB)) = E_Discriminant
then
if Current_Scope = Scope (Entity (LB)) then
return Ret_Result;
else
LB :=
New_Occurrence_Of (Discriminal (Entity (LB)), Loc);
end if;
end if;
if Nkind (HB) = N_Identifier
and then Ekind (Entity (HB)) = E_Discriminant
then
if Current_Scope = Scope (Entity (HB)) then
return Ret_Result;
else
HB :=
New_Occurrence_Of (Discriminal (Entity (HB)), Loc);
end if;
end if;
Cond := Discrete_Range_Cond (Ck_Node, T_Typ);
Set_Paren_Count (Cond, 1);
Cond :=
Make_And_Then (Loc,
Left_Opnd =>
Make_Op_Ge (Loc,
Left_Opnd => Duplicate_Subexpr_No_Checks (HB),
Right_Opnd => Duplicate_Subexpr_No_Checks (LB)),
Right_Opnd => Cond);
end;
end if;
end;
elsif Is_Scalar_Type (S_Typ) then
-- This somewhat duplicates what Apply_Scalar_Range_Check does,
-- except the above simply sets a flag in the node and lets
-- gigi generate the check base on the Etype of the expression.
-- Sometimes, however we want to do a dynamic check against an
-- arbitrary target type, so we do that here.
if Ekind (Base_Type (S_Typ)) /= Ekind (Base_Type (T_Typ)) then
Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
-- For literals, we can tell if the constraint error will be
-- raised at compile time, so we never need a dynamic check, but
-- if the exception will be raised, then post the usual warning,
-- and replace the literal with a raise constraint error
-- expression. As usual, skip this for access types
elsif Compile_Time_Known_Value (Ck_Node)
and then not Do_Access
then
declare
LB : constant Node_Id := Type_Low_Bound (T_Typ);
UB : constant Node_Id := Type_High_Bound (T_Typ);
Out_Of_Range : Boolean;
Static_Bounds : constant Boolean :=
Compile_Time_Known_Value (LB)
and Compile_Time_Known_Value (UB);
begin
-- Following range tests should use Sem_Eval routine ???
if Static_Bounds then
if Is_Floating_Point_Type (S_Typ) then
Out_Of_Range :=
(Expr_Value_R (Ck_Node) < Expr_Value_R (LB))
or else
(Expr_Value_R (Ck_Node) > Expr_Value_R (UB));
else -- fixed or discrete type
Out_Of_Range :=
Expr_Value (Ck_Node) < Expr_Value (LB)
or else
Expr_Value (Ck_Node) > Expr_Value (UB);
end if;
-- Bounds of the type are static and the literal is
-- out of range so make a warning message.
if Out_Of_Range then
if No (Warn_Node) then
Add_Check
(Compile_Time_Constraint_Error
(Ck_Node,
"static value out of range of}?", T_Typ));
else
Add_Check
(Compile_Time_Constraint_Error
(Wnode,
"static value out of range of}?", T_Typ));
end if;
end if;
else
Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
end if;
end;
-- Here for the case of a non-static expression, we need a runtime
-- check unless the source type range is guaranteed to be in the
-- range of the target type.
else
if not In_Subrange_Of (S_Typ, T_Typ) then
Cond := Discrete_Expr_Cond (Ck_Node, T_Typ);
end if;
end if;
end if;
if Is_Array_Type (T_Typ) and then Is_Array_Type (S_Typ) then
if Is_Constrained (T_Typ) then
Expr_Actual := Get_Referenced_Object (Ck_Node);
Exptyp := Get_Actual_Subtype (Expr_Actual);
if Is_Access_Type (Exptyp) then
Exptyp := Designated_Type (Exptyp);
end if;
-- String_Literal case. This needs to be handled specially be-
-- cause no index types are available for string literals. The
-- condition is simply:
-- T_Typ'Length = string-literal-length
if Nkind (Expr_Actual) = N_String_Literal then
null;
-- General array case. Here we have a usable actual subtype for
-- the expression, and the condition is built from the two types
-- T_Typ'First < Exptyp'First or else
-- T_Typ'Last > Exptyp'Last or else
-- T_Typ'First(1) < Exptyp'First(1) or else
-- T_Typ'Last(1) > Exptyp'Last(1) or else
-- ...
elsif Is_Constrained (Exptyp) then
declare
Ndims : constant Nat := Number_Dimensions (T_Typ);
L_Index : Node_Id;
R_Index : Node_Id;
L_Low : Node_Id;
L_High : Node_Id;
R_Low : Node_Id;
R_High : Node_Id;
begin
L_Index := First_Index (T_Typ);
R_Index := First_Index (Exptyp);
for Indx in 1 .. Ndims loop
if not (Nkind (L_Index) = N_Raise_Constraint_Error
or else
Nkind (R_Index) = N_Raise_Constraint_Error)
then
Get_Index_Bounds (L_Index, L_Low, L_High);
Get_Index_Bounds (R_Index, R_Low, R_High);
-- Deal with compile time length check. Note that we
-- skip this in the access case, because the access
-- value may be null, so we cannot know statically.
if not
Subtypes_Statically_Match
(Etype (L_Index), Etype (R_Index))
then
-- If the target type is constrained then we
-- have to check for exact equality of bounds
-- (required for qualified expressions).
if Is_Constrained (T_Typ) then
Evolve_Or_Else
(Cond,
Range_Equal_E_Cond (Exptyp, T_Typ, Indx));
else
Evolve_Or_Else
(Cond, Range_E_Cond (Exptyp, T_Typ, Indx));
end if;
end if;
Next (L_Index);
Next (R_Index);
end if;
end loop;
end;
-- Handle cases where we do not get a usable actual subtype that
-- is constrained. This happens for example in the function call
-- and explicit dereference cases. In these cases, we have to get
-- the length or range from the expression itself, making sure we
-- do not evaluate it more than once.
-- Here Ck_Node is the original expression, or more properly the
-- result of applying Duplicate_Expr to the original tree,
-- forcing the result to be a name.
else
declare
Ndims : constant Nat := Number_Dimensions (T_Typ);
begin
-- Build the condition for the explicit dereference case
for Indx in 1 .. Ndims loop
Evolve_Or_Else
(Cond, Range_N_Cond (Ck_Node, T_Typ, Indx));
end loop;
end;
end if;
else
-- Generate an Action to check that the bounds of the
-- source value are within the constraints imposed by the
-- target type for a conversion to an unconstrained type.
-- Rule is 4.6(38).
if Nkind (Parent (Ck_Node)) = N_Type_Conversion then
declare
Opnd_Index : Node_Id;
Targ_Index : Node_Id;
begin
Opnd_Index
:= First_Index (Get_Actual_Subtype (Ck_Node));
Targ_Index := First_Index (T_Typ);
while Opnd_Index /= Empty loop
if Nkind (Opnd_Index) = N_Range then
if Is_In_Range
(Low_Bound (Opnd_Index), Etype (Targ_Index))
and then
Is_In_Range
(High_Bound (Opnd_Index), Etype (Targ_Index))
then
null;
-- If null range, no check needed
elsif
Compile_Time_Known_Value (High_Bound (Opnd_Index))
and then
Compile_Time_Known_Value (Low_Bound (Opnd_Index))
and then
Expr_Value (High_Bound (Opnd_Index)) <
Expr_Value (Low_Bound (Opnd_Index))
then
null;
elsif Is_Out_Of_Range
(Low_Bound (Opnd_Index), Etype (Targ_Index))
or else
Is_Out_Of_Range
(High_Bound (Opnd_Index), Etype (Targ_Index))
then
Add_Check
(Compile_Time_Constraint_Error
(Wnode, "value out of range of}?", T_Typ));
else
Evolve_Or_Else
(Cond,
Discrete_Range_Cond
(Opnd_Index, Etype (Targ_Index)));
end if;
end if;
Next_Index (Opnd_Index);
Next_Index (Targ_Index);
end loop;
end;
end if;
end if;
end if;
-- Construct the test and insert into the tree
if Present (Cond) then
if Do_Access then
Cond := Guard_Access (Cond, Loc, Ck_Node);
end if;
Add_Check
(Make_Raise_Constraint_Error (Loc,
Condition => Cond,
Reason => CE_Range_Check_Failed));
end if;
return Ret_Result;
end Selected_Range_Checks;
-------------------------------
-- Storage_Checks_Suppressed --
-------------------------------
function Storage_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) and then Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Storage_Check);
else
return Scope_Suppress (Storage_Check);
end if;
end Storage_Checks_Suppressed;
---------------------------
-- Tag_Checks_Suppressed --
---------------------------
function Tag_Checks_Suppressed (E : Entity_Id) return Boolean is
begin
if Present (E) then
if Kill_Tag_Checks (E) then
return True;
elsif Checks_May_Be_Suppressed (E) then
return Is_Check_Suppressed (E, Tag_Check);
end if;
end if;
return Scope_Suppress (Tag_Check);
end Tag_Checks_Suppressed;
end Checks;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . W I D E _ W I D E _ T E X T _ I O . M O D U L A R _ A U X --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2019, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Wide_Wide_Text_IO.Generic_Aux; use Ada.Wide_Wide_Text_IO.Generic_Aux;
with System.Img_BIU; use System.Img_BIU;
with System.Img_Uns; use System.Img_Uns;
with System.Img_LLB; use System.Img_LLB;
with System.Img_LLU; use System.Img_LLU;
with System.Img_LLW; use System.Img_LLW;
with System.Img_WIU; use System.Img_WIU;
with System.Val_Uns; use System.Val_Uns;
with System.Val_LLU; use System.Val_LLU;
package body Ada.Wide_Wide_Text_IO.Modular_Aux is
use System.Unsigned_Types;
-----------------------
-- Local Subprograms --
-----------------------
procedure Load_Modular
(File : File_Type;
Buf : out String;
Ptr : in out Natural);
-- This is an auxiliary routine that is used to load an possibly signed
-- modular literal value from the input file into Buf, starting at Ptr + 1.
-- Ptr is left set to the last character stored.
-------------
-- Get_LLU --
-------------
procedure Get_LLU
(File : File_Type;
Item : out Long_Long_Unsigned;
Width : Field)
is
Buf : String (1 .. Field'Last);
Stop : Integer := 0;
Ptr : aliased Integer := 1;
begin
if Width /= 0 then
Load_Width (File, Width, Buf, Stop);
String_Skip (Buf, Ptr);
else
Load_Modular (File, Buf, Stop);
end if;
Item := Scan_Long_Long_Unsigned (Buf, Ptr'Access, Stop);
Check_End_Of_Field (Buf, Stop, Ptr, Width);
end Get_LLU;
-------------
-- Get_Uns --
-------------
procedure Get_Uns
(File : File_Type;
Item : out Unsigned;
Width : Field)
is
Buf : String (1 .. Field'Last);
Stop : Integer := 0;
Ptr : aliased Integer := 1;
begin
if Width /= 0 then
Load_Width (File, Width, Buf, Stop);
String_Skip (Buf, Ptr);
else
Load_Modular (File, Buf, Stop);
end if;
Item := Scan_Unsigned (Buf, Ptr'Access, Stop);
Check_End_Of_Field (Buf, Stop, Ptr, Width);
end Get_Uns;
--------------
-- Gets_LLU --
--------------
procedure Gets_LLU
(From : String;
Item : out Long_Long_Unsigned;
Last : out Positive)
is
Pos : aliased Integer;
begin
String_Skip (From, Pos);
Item := Scan_Long_Long_Unsigned (From, Pos'Access, From'Last);
Last := Pos - 1;
exception
when Constraint_Error =>
raise Data_Error;
end Gets_LLU;
--------------
-- Gets_Uns --
--------------
procedure Gets_Uns
(From : String;
Item : out Unsigned;
Last : out Positive)
is
Pos : aliased Integer;
begin
String_Skip (From, Pos);
Item := Scan_Unsigned (From, Pos'Access, From'Last);
Last := Pos - 1;
exception
when Constraint_Error =>
raise Data_Error;
end Gets_Uns;
------------------
-- Load_Modular --
------------------
procedure Load_Modular
(File : File_Type;
Buf : out String;
Ptr : in out Natural)
is
Hash_Loc : Natural;
Loaded : Boolean;
begin
Load_Skip (File);
-- Note: it is a bit strange to allow a minus sign here, but it seems
-- consistent with the general behavior expected by the ACVC tests
-- which is to scan past junk and then signal data error, see ACVC
-- test CE3704F, case (6), which is for signed integer exponents,
-- which seems a similar case.
Load (File, Buf, Ptr, '+', '-');
Load_Digits (File, Buf, Ptr, Loaded);
if Loaded then
-- Deal with based case. We recognize either the standard '#' or the
-- allowed alternative replacement ':' (see RM J.2(3)).
Load (File, Buf, Ptr, '#', ':', Loaded);
if Loaded then
Hash_Loc := Ptr;
Load_Extended_Digits (File, Buf, Ptr);
Load (File, Buf, Ptr, Buf (Hash_Loc));
end if;
Load (File, Buf, Ptr, 'E', 'e', Loaded);
if Loaded then
-- Note: it is strange to allow a minus sign, since the syntax
-- does not, but that is what ACVC test CE3704F, case (6) wants
-- for the signed case, and there seems no good reason to treat
-- exponents differently for the signed and unsigned cases.
Load (File, Buf, Ptr, '+', '-');
Load_Digits (File, Buf, Ptr);
end if;
end if;
end Load_Modular;
-------------
-- Put_LLU --
-------------
procedure Put_LLU
(File : File_Type;
Item : Long_Long_Unsigned;
Width : Field;
Base : Number_Base)
is
Buf : String (1 .. Field'Last);
Ptr : Natural := 0;
begin
if Base = 10 and then Width = 0 then
Set_Image_Long_Long_Unsigned (Item, Buf, Ptr);
elsif Base = 10 then
Set_Image_Width_Long_Long_Unsigned (Item, Width, Buf, Ptr);
else
Set_Image_Based_Long_Long_Unsigned (Item, Base, Width, Buf, Ptr);
end if;
Put_Item (File, Buf (1 .. Ptr));
end Put_LLU;
-------------
-- Put_Uns --
-------------
procedure Put_Uns
(File : File_Type;
Item : Unsigned;
Width : Field;
Base : Number_Base)
is
Buf : String (1 .. Field'Last);
Ptr : Natural := 0;
begin
if Base = 10 and then Width = 0 then
Set_Image_Unsigned (Item, Buf, Ptr);
elsif Base = 10 then
Set_Image_Width_Unsigned (Item, Width, Buf, Ptr);
else
Set_Image_Based_Unsigned (Item, Base, Width, Buf, Ptr);
end if;
Put_Item (File, Buf (1 .. Ptr));
end Put_Uns;
--------------
-- Puts_LLU --
--------------
procedure Puts_LLU
(To : out String;
Item : Long_Long_Unsigned;
Base : Number_Base)
is
Buf : String (1 .. Field'Last);
Ptr : Natural := 0;
begin
if Base = 10 then
Set_Image_Width_Long_Long_Unsigned (Item, To'Length, Buf, Ptr);
else
Set_Image_Based_Long_Long_Unsigned (Item, Base, To'Length, Buf, Ptr);
end if;
if Ptr > To'Length then
raise Layout_Error;
else
To (To'First .. To'First + Ptr - 1) := Buf (1 .. Ptr);
end if;
end Puts_LLU;
--------------
-- Puts_Uns --
--------------
procedure Puts_Uns
(To : out String;
Item : Unsigned;
Base : Number_Base)
is
Buf : String (1 .. Field'Last);
Ptr : Natural := 0;
begin
if Base = 10 then
Set_Image_Width_Unsigned (Item, To'Length, Buf, Ptr);
else
Set_Image_Based_Unsigned (Item, Base, To'Length, Buf, Ptr);
end if;
if Ptr > To'Length then
raise Layout_Error;
else
To (To'First .. To'First + Ptr - 1) := Buf (1 .. Ptr);
end if;
end Puts_Uns;
end Ada.Wide_Wide_Text_IO.Modular_Aux;
|
with HAL;
generic
with package Chip_Select is new HAL.Pin (<>);
with package Chip_Enable is new HAL.Pin (<>);
with package IRQ is new HAL.Pin (<>);
with package SPI is new HAL.SPI (<>);
with package Clock is new HAL.Clock (<>);
package Drivers.NRF24 is
pragma Preelaborate;
type Raw_Register_Array is array (0 .. 16#1D#) of Unsigned_8;
subtype Channel_Type is Unsigned_8 range 0 .. 127;
type Address_Type is array (1 .. 5) of Unsigned_8;
type Packet_Type is array (Positive range <>) of Unsigned_8;
procedure Init;
procedure Set_Channel (Channel : Channel_Type);
procedure Set_RX_Address (Address : Address_Type);
procedure Set_TX_Address (Address : Address_Type);
procedure TX_Mode;
procedure RX_Mode;
procedure TX (Packet: Packet_Type);
function Wait_For_RX return Boolean;
procedure RX (Packet : out Packet_Type);
procedure Power_Down;
procedure Cancel;
procedure Read_Registers (Registers : out Raw_Register_Array);
generic
with procedure Put_Line (Line: in string);
procedure Print_Registers;
end Drivers.NRF24;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
package body Program.Nodes.Task_Body_Stubs is
function Create
(Task_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Body_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Name : not null Program.Elements.Defining_Identifiers
.Defining_Identifier_Access;
Is_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Separate_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
With_Token : Program.Lexical_Elements.Lexical_Element_Access;
Aspects : Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Task_Body_Stub is
begin
return Result : Task_Body_Stub :=
(Task_Token => Task_Token, Body_Token => Body_Token, Name => Name,
Is_Token => Is_Token, Separate_Token => Separate_Token,
With_Token => With_Token, Aspects => Aspects,
Semicolon_Token => Semicolon_Token, Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
function Create
(Name : not null Program.Elements.Defining_Identifiers
.Defining_Identifier_Access;
Aspects : Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access;
Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Task_Body_Stub is
begin
return Result : Implicit_Task_Body_Stub :=
(Name => Name, Aspects => Aspects,
Is_Part_Of_Implicit => Is_Part_Of_Implicit,
Is_Part_Of_Inherited => Is_Part_Of_Inherited,
Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
overriding function Name
(Self : Base_Task_Body_Stub)
return not null Program.Elements.Defining_Identifiers
.Defining_Identifier_Access is
begin
return Self.Name;
end Name;
overriding function Aspects
(Self : Base_Task_Body_Stub)
return Program.Elements.Aspect_Specifications
.Aspect_Specification_Vector_Access is
begin
return Self.Aspects;
end Aspects;
overriding function Task_Token
(Self : Task_Body_Stub)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Task_Token;
end Task_Token;
overriding function Body_Token
(Self : Task_Body_Stub)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Body_Token;
end Body_Token;
overriding function Is_Token
(Self : Task_Body_Stub)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Is_Token;
end Is_Token;
overriding function Separate_Token
(Self : Task_Body_Stub)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Separate_Token;
end Separate_Token;
overriding function With_Token
(Self : Task_Body_Stub)
return Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.With_Token;
end With_Token;
overriding function Semicolon_Token
(Self : Task_Body_Stub)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Semicolon_Token;
end Semicolon_Token;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Task_Body_Stub)
return Boolean is
begin
return Self.Is_Part_Of_Implicit;
end Is_Part_Of_Implicit;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Task_Body_Stub)
return Boolean is
begin
return Self.Is_Part_Of_Inherited;
end Is_Part_Of_Inherited;
overriding function Is_Part_Of_Instance
(Self : Implicit_Task_Body_Stub)
return Boolean is
begin
return Self.Is_Part_Of_Instance;
end Is_Part_Of_Instance;
procedure Initialize (Self : in out Base_Task_Body_Stub'Class) is
begin
Set_Enclosing_Element (Self.Name, Self'Unchecked_Access);
for Item in Self.Aspects.Each_Element loop
Set_Enclosing_Element (Item.Element, Self'Unchecked_Access);
end loop;
null;
end Initialize;
overriding function Is_Task_Body_Stub
(Self : Base_Task_Body_Stub)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Task_Body_Stub;
overriding function Is_Declaration
(Self : Base_Task_Body_Stub)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Declaration;
overriding procedure Visit
(Self : not null access Base_Task_Body_Stub;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is
begin
Visitor.Task_Body_Stub (Self);
end Visit;
overriding function To_Task_Body_Stub_Text
(Self : in out Task_Body_Stub)
return Program.Elements.Task_Body_Stubs.Task_Body_Stub_Text_Access is
begin
return Self'Unchecked_Access;
end To_Task_Body_Stub_Text;
overriding function To_Task_Body_Stub_Text
(Self : in out Implicit_Task_Body_Stub)
return Program.Elements.Task_Body_Stubs.Task_Body_Stub_Text_Access is
pragma Unreferenced (Self);
begin
return null;
end To_Task_Body_Stub_Text;
end Program.Nodes.Task_Body_Stubs;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Aux; use Ada.Numerics.Aux;
with Prime_Ada; use Prime_Ada;
procedure Main is
begin
declare
n : Integer;
begin
for i in 1 .. 6 loop
n := Integer (Pow (Double (10), Double (i)));
Put ("n = ");
Put_Line (Integer'Image (n));
Get_Prime (n);
Put (Integer'Image (cnt));
Put_Line (" prime numbers found.");
end loop;
end;
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- I T Y P E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2010, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains declarations for handling of implicit types
with Einfo; use Einfo;
with Sem_Util; use Sem_Util;
with Types; use Types;
package Itypes is
--------------------
-- Implicit Types --
--------------------
-- Implicit types (Itypes) are types and subtypes created by the semantic
-- phase or the expander to reflect the underlying semantics. These could
-- be generated by building trees for corresponding declarations and then
-- analyzing these trees, but there are three reasons for not doing this
-- in some cases:
-- 1. The declarations would require more tree nodes
-- 2. In some cases, the elaboration of these types is associated
-- with internal nodes in the tree.
-- 3. For some types, notably class wide types, there is no Ada
-- declaration that would correspond to the desired entity.
-- So instead, implicit types are constructed by simply creating an
-- appropriate entity with the help of routines in this package. These
-- entities are fully decorated, as described in Einfo (just as though
-- they had been created by the normal analysis procedure).
-- The type declaration declaring an Itype must be analyzed with checks
-- off because this declaration has not been inserted in the tree (if it
-- has been then it is not an Itype), and hence checks that would be
-- generated during the analysis cannot be inserted in the tree. At any
-- rate, Itype analysis should always be done with checks off, otherwise
-- duplicate checks will most likely be emitted.
-- Unlike types declared explicitly, implicit types are defined on first
-- use, which means that Gigi detects the use of such types, and defines
-- them at the point of the first use automatically.
-- Although Itypes are not explicitly declared, they are associated with
-- a specific node in the tree (roughly the node that caused them to be
-- created), via the Associated_Node_For_Itype field. This association is
-- used particularly by New_Copy_Tree, which uses it to determine whether
-- or not to copy a referenced Itype. If the associated node is part of
-- the tree to be copied by New_Copy_Tree, then (since the idea of the
-- call to New_Copy_Tree is to create a complete duplicate of a tree,
-- as though it had appeared separately in the source), the Itype in
-- question is duplicated as part of the New_Copy_Tree processing.
-- As a consequence of this copying mechanism, the association between
-- Itypes and associated nodes must be one-to-one: several Itypes must
-- not share an associated node. For example, the semantic decoration
-- of an array aggregate generates several Itypes: for each index subtype
-- and for the array subtype. The associated node of each index subtype
-- is the corresponding range expression.
-- Notes on the use of the Parent field of an Itype
-- In some cases, we do create a declaration node for an itype, and in
-- such cases, the Parent field of the Itype points to this declaration
-- in the normal manner. This case can be detected by checking for a
-- non-empty Parent field referencing a declaration whose Defining_Entity
-- is the Itype in question.
-- In some other cases, where we don't generate such a declaration, as
-- described above, the Itype is attached to the tree implicitly by being
-- referenced elsewhere, e.g. as the Etype of some object. In this case
-- the Parent field may be Empty.
-- In other cases where we don't generate a declaration for the Itype,
-- the Itype may be attached to an arbitrary node in the tree, using
-- the Parent field. This Parent field may even reference a declaration
-- for a related different entity (hence the description of the tests
-- needed for the case where a declaration for the Itype is created).
------------------
-- Create_Itype --
------------------
function Create_Itype
(Ekind : Entity_Kind;
Related_Nod : Node_Id;
Related_Id : Entity_Id := Empty;
Suffix : Character := ' ';
Suffix_Index : Nat := 0;
Scope_Id : Entity_Id := Current_Scope) return Entity_Id;
-- Used to create a new Itype
--
-- Related_Nod is the node for which this Itype was created. It is
-- set as the Associated_Node_For_Itype of the new Itype. The Sloc of
-- the new Itype is that of this node.
--
-- Related_Id is present only if the implicit type name may be referenced
-- as a public symbol, and thus needs a unique external name. The name
-- is created by a call to:
--
-- New_External_Name (Chars (Related_Id), Suffix, Suffix_Index, 'T')
--
-- If the implicit type does not need an external name, then the
-- Related_Id parameter is omitted (and hence Empty). In this case
-- Suffix and Suffix_Index are ignored and the implicit type name is
-- created by a call to Make_Temporary.
--
-- Note that in all cases, the name starts with "T". This is used
-- to identify implicit types in the error message handling circuits.
--
-- The Scope_Id parameter specifies the scope of the created type, and
-- is normally the Current_Scope as shown, but can be set otherwise.
--
-- The size/align fields are initialized to unknown (Uint_0).
--
-- If Ekind is in Access_Subprogram_Kind, Can_Use_Internal_Rep is set True,
-- unless Always_Compatible_Rep_On_Target is True.
---------------------------------
-- Create_Null_Excluding_Itype --
---------------------------------
function Create_Null_Excluding_Itype
(T : Entity_Id;
Related_Nod : Node_Id;
Scope_Id : Entity_Id := Current_Scope) return Entity_Id;
-- Ada 2005 (AI-231): T is an access type and this subprogram creates and
-- returns an internal access-subtype declaration of T that has the null
-- exclusion attribute set to True.
--
-- Usage of null-excluding Itypes
-- ------------------------------
--
-- type T1 is access ...
-- type T2 is not null T1;
--
-- type Rec is record
-- Comp : not null T1;
-- end record;
--
-- type Arr is array (...) of not null T1;
--
-- Instead of associating the not-null attribute with the defining ids of
-- these declarations, we generate an internal subtype declaration of T1
-- that has the null exclusion attribute set to true.
end Itypes;
|
package body Opt46_Pkg is
function Last (T : Instance) return Table_Index_Type is
begin
return Table_Index_Type (T.P.Last_Val);
end Last;
end Opt46_Pkg;
|
-- Abstract :
--
-- See spec
--
-- Copyright (C) 2012, 2013, 2015, 2017, 2018 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or
-- modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or (at
-- your option) any later version. This 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
-- distributed with this program; see file COPYING. If not, write to
-- the Free Software Foundation, 51 Franklin Street, Suite 500, Boston,
-- MA 02110-1335, USA.
pragma License (GPL);
package body WisiToken.BNF.Utils is
function Strip_Quotes (Item : in String) return String
is begin
if Item'Length < 2 then
return Item;
else
return Item
((if Item (Item'First) = '"' then Item'First + 1 else Item'First) ..
(if Item (Item'Last) = '"' then Item'Last - 1 else Item'Last));
end if;
end Strip_Quotes;
function Strip_Parens (Item : in String) return String
is begin
if Item'Length < 2 then
return Item;
else
return Item
((if Item (Item'First) = '(' then Item'First + 1 else Item'First) ..
(if Item (Item'Last) = ')' then Item'Last - 1 else Item'Last));
end if;
end Strip_Parens;
end WisiToken.BNF.Utils;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Command_Line; use Ada.Command_Line;
package body regge.io is
package Real_IO is new Ada.Text_IO.Float_IO (Real); use Real_IO;
package Integer_IO is new Ada.Text_IO.Integer_IO (Integer); use Integer_IO;
function str (source : in Integer;
width : in Integer := 0) return string is
result : string(1..width);
wide_result : string(1..Integer'width);
begin
if width = 0 then
Put(wide_result,source);
return trim(wide_result,left); -- flush left, returns a string just large enough to contain the integer
else
Put(result,source);
return result;
end if;
end str;
function str (source : in Real;
width : in Integer := 10) return string is
result : string(1..width);
begin
-- 4932 = largest exponent for 18 dec. digits
-- so may need up to 4 digits in the exponent + 1 for the sign = 5
if source = 0.0 then
Put (result,source,width-7,3);
elsif abs (source) < 1.0 then
if abs (source) >= 1.0e-99 then
Put (result,source,width-7,3);
elsif abs (source) >= 1.0e-999 then
Put (result,source,width-8,4);
else
Put (result,source,width-9,5);
end if;
else
if abs (source) < 1.0e100 then
Put (result,source,width-7,3);
elsif abs (source) < 1.0e1000 then
Put (result,source,width-8,4);
else
Put (result,source,width-9,5);
end if;
end if;
return result;
end str;
function read_command_arg (the_arg : Integer) return Integer is
last : Integer;
the_arg_value : Integer;
begin
get (Ada.Command_Line.Argument (the_arg),the_arg_value,last);
return the_arg;
end read_command_arg;
procedure read_lattice
is
txt : File_Type;
tmp : Integer;
bone : Integer;
begin
Open (txt,In_file,"data/lattice/simp12.txt");
Get (txt,n_simp2); skip_line (txt);
for a in 1..n_simp2 loop
Get (txt,bone); skip_line (txt);
Get (txt,n_loop02(bone)); skip_line (txt);
Get (txt,n_simp12(bone)); skip_line (txt);
for b in 1..n_simp12(bone) loop
Get (txt,tmp);
Get (txt,simp12(bone)(tmp));
end loop;
end loop;
Close (txt);
Open (txt,In_file,"data/lsq/data-0"&str(num,1)&".txt");
Get (txt,n_simp1);
skip_line (txt); -- skip trailing text on first line
skip_line (txt); -- skip second line
for i in 1 .. n_simp1 loop
Get (txt, simp01(i)(1));
Get (txt, simp01(i)(2));
Get (txt, lsq(i));
end loop;
Close (txt);
end read_lattice;
end regge.io;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2021, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with System; use System;
with System.Storage_Elements; use System.Storage_Elements;
with BBqueue; use BBqueue;
with BBqueue.Buffers; use BBqueue.Buffers;
with USB.Utils;
package body USB.Device.Serial is
Bulk_Buffer_Size : constant := 64;
----------------
-- Initialize --
----------------
overriding
function Initialize (This : in out Default_Serial_Class;
Dev : in out USB_Device_Stack'Class;
Base_Interface_Index : Interface_Id)
return Init_Result
is
begin
-- Request Interrupt EP --
if not Dev.Request_Endpoint (Interrupt, This.Int_EP) then
return Not_Enough_EPs;
end if;
This.Int_Buf := Dev.Request_Buffer ((This.Int_EP, EP_In),
Bulk_Buffer_Size);
if This.Int_Buf = System.Null_Address then
return Not_Enough_EP_Buffer;
end if;
-- Request Bulk EPs --
if not Dev.Request_Endpoint (Bulk, This.Bulk_EP) then
return Not_Enough_EPs;
end if;
This.Bulk_Out_Buf := Dev.Request_Buffer ((This.Bulk_EP, EP_Out),
Bulk_Buffer_Size);
if This.Bulk_Out_Buf = System.Null_Address then
return Not_Enough_EP_Buffer;
end if;
This.Bulk_In_Buf := Dev.Request_Buffer ((This.Bulk_EP, EP_In),
Bulk_Buffer_Size);
if This.Bulk_In_Buf = System.Null_Address then
return Not_Enough_EP_Buffer;
end if;
-- Interface --
This.Interface_Index := Base_Interface_Index;
This.Iface_Str := Dev.Register_String
(USB.To_USB_String ("Serial Test iface name"));
-- Default line coding
This.Coding.Bitrate := 115_200;
This.Coding.Stop_Bit := 0;
This.Coding.Parity := 0;
This.Coding.Data_Bits := 8;
return Ok;
end Initialize;
--------------------
-- Get_Class_Info --
--------------------
overriding
procedure Get_Class_Info
(This : in out Default_Serial_Class;
Number_Of_Interfaces : out Interface_Id;
Config_Descriptor_Length : out Natural)
is
pragma Unreferenced (This);
begin
Number_Of_Interfaces := 2;
Config_Descriptor_Length := 66;
end Get_Class_Info;
----------------------------
-- Fill_Config_Descriptor --
----------------------------
overriding
procedure Fill_Config_Descriptor (This : in out Default_Serial_Class;
Data : out UInt8_Array)
is
F : constant Natural := Data'First;
USB_DESC_TYPE_INTERFACE : constant := 4;
USB_DESC_TYPE_ENDPOINT : constant := 5;
USB_DESC_CS_INTERFACE : constant := 16#24#;
USB_CLASS_CDC : constant := 2;
USB_CLASS_CDC_DATA : constant := 10;
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL : constant := 2;
CDC_FUNC_DESC_HEADER : constant := 0;
CDC_FUNC_DESC_CALL_MANAGEMENT : constant := 1;
CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT : constant := 2;
CDC_FUNC_DESC_UNION : constant := 6;
begin
Data (F + 0 .. F + 65) :=
(
-- Interface Associate --
8, -- bLength
16#0B#, -- bDescriptorType 0x0B
UInt8 (This.Interface_Index), -- bFirstInterface
2, -- bInterfaceCount
USB_CLASS_CDC, -- bFunctionClass
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, -- bFunctionSubClass
0, -- bFunctionProtocol
0, -- iFunction
-- CDC Control Interface --
9, -- bLength
USB_DESC_TYPE_INTERFACE, -- bDescriptorType
UInt8 (This.Interface_Index), -- bInterfaceNumber
0, -- bAlternateSetting
1, -- bNumEndpoints
USB_CLASS_CDC, -- bInterfaceClass
CDC_COMM_SUBCLASS_ABSTRACT_CONTROL_MODEL, -- bInterfaceSubClass
0, -- bInterfaceProtocol
UInt8 (This.Iface_Str), -- iInterface (String index)
-- CDC Header --
5,
USB_DESC_CS_INTERFACE,
CDC_FUNC_DESC_HEADER,
16#20#,
16#01#,
-- CDC Call --
5,
USB_DESC_CS_INTERFACE,
CDC_FUNC_DESC_CALL_MANAGEMENT,
0,
UInt8 (This.Interface_Index + 1),
-- CDC ACM: support line request --
4,
USB_DESC_CS_INTERFACE,
CDC_FUNC_DESC_ABSTRACT_CONTROL_MANAGEMENT,
2,
-- CDC Union --
5,
USB_DESC_CS_INTERFACE,
CDC_FUNC_DESC_UNION,
UInt8 (This.Interface_Index),
UInt8 (This.Interface_Index + 1),
-- Endpoint Notification --
7,
USB_DESC_TYPE_ENDPOINT,
16#80# or UInt8 (This.Int_EP), -- In EP
3, -- Interrupt EP
16#40#, 0, -- TODO: Max packet size
16, -- Polling interval
-- CDC Control Interface --
9, -- bLength
USB_DESC_TYPE_INTERFACE, -- bDescriptorType
UInt8 (This.Interface_Index + 1), -- bInterfaceNumber
0, -- bAlternateSetting
2, -- bNumEndpoints
USB_CLASS_CDC_DATA, -- bInterfaceClass
0, -- bInterfaceSubClass
0, -- bInterfaceProtocol
0, -- iInterface (String index)
-- Endpoint Data out --
7,
USB_DESC_TYPE_ENDPOINT,
UInt8 (This.Bulk_EP), -- Out EP
2, -- Bulk EP
16#40#, 0, -- TODO: Max packet size
0, -- Polling interval
-- Endpoint Data in --
7,
USB_DESC_TYPE_ENDPOINT,
16#80# or UInt8 (This.Bulk_EP), -- In EP
2, -- Bulk EP
16#40#, 0, -- TODO: Max packet size
0
);
end Fill_Config_Descriptor;
---------------
-- Configure --
---------------
overriding
function Configure
(This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class;
Index : UInt16)
return Setup_Request_Answer
is
begin
if Index = 1 then
UDC.EP_Setup (EP => (This.Int_EP, EP_In),
Typ => Interrupt,
Max_Size => 64);
UDC.EP_Setup (EP => (This.Bulk_EP, EP_In),
Typ => Bulk,
Max_Size => 64);
UDC.EP_Setup (EP => (This.Bulk_EP, EP_Out),
Typ => Bulk,
Max_Size => 64);
This.Setup_RX (UDC);
return Handled;
else
return Not_Supported;
end if;
end Configure;
-------------------
-- Setup_Request --
-------------------
overriding
function Setup_Read_Request (This : in out Default_Serial_Class;
Req : Setup_Data;
Buf : out System.Address;
Len : out Buffer_Len)
return Setup_Request_Answer
is
begin
Buf := System.Null_Address;
Len := 0;
if Req.RType.Typ = Class and then Req.RType.Recipient = Iface then
case Req.Request is
when 16#21# => -- GET_LINE_CODING
Buf := This.Coding'Address;
Len := This.Coding'Size / 8;
return Handled;
when others =>
raise Program_Error with "Unknown Serial request";
end case;
end if;
return Next_Callback;
end Setup_Read_Request;
-------------------------
-- Setup_Write_Request --
-------------------------
overriding
function Setup_Write_Request (This : in out Default_Serial_Class;
Req : Setup_Data;
Data : UInt8_Array)
return Setup_Request_Answer
is
begin
if Req.RType.Typ = Class and then Req.RType.Recipient = Iface then
case Req.Request is
when 16#20# => -- SET_LINE_CODING
if Data'Length = (This.Coding'Size / 8) then
declare
Dst : UInt8_Array (1 .. This.Coding'Size / 8)
with Address => This.Coding'Address;
begin
Dst := Data;
return Handled;
end;
else
return Not_Supported;
end if;
when 16#22# => -- SET_CONTROL_LINE_STATE
This.State.DTE_Is_Present := (Req.Value and 1) /= 0;
This.State.Half_Duplex_Carrier_control := (Req.Value and 2) /= 0;
return Handled;
when 16#23# => -- SEND_BREAK
-- TODO: Break are ignored for now...
return Handled;
when others =>
raise Program_Error with "Unknown Serial request";
end case;
end if;
return Next_Callback;
end Setup_Write_Request;
-----------------------
-- Transfer_Complete --
-----------------------
overriding
procedure Transfer_Complete (This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class;
EP : EP_Addr;
CNT : UInt11)
is
begin
if EP = (This.Bulk_EP, EP_Out) then
-- Move OUT data to the RX queue
declare
WG : BBqueue.Buffers.Write_Grant;
begin
Grant (This.RX_Queue, WG, BBqueue.Count (CNT));
if State (WG) = Valid then
USB.Utils.Copy (Src => This.Bulk_Out_Buf,
Dst => Slice (WG).Addr,
Count => CNT);
Commit (This.RX_Queue, WG, BBqueue.Count (CNT));
end if;
end;
This.Setup_RX (UDC);
elsif EP = (This.Bulk_EP, EP_In) then
This.TX_In_Progress := False;
This.Setup_TX (UDC);
else
raise Program_Error with "Not expecting transfer on EP";
end if;
end Transfer_Complete;
--------------
-- Setup_RX --
--------------
procedure Setup_RX (This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class)
is
begin
UDC.EP_Ready_For_Data (EP => This.Bulk_EP,
Addr => This.Bulk_Out_Buf,
Max_Len => Bulk_Buffer_Size,
Ready => True);
end Setup_RX;
--------------
-- Setup_TX --
--------------
procedure Setup_TX (This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class)
is
RG : BBqueue.Buffers.Read_Grant;
begin
if This.TX_In_Progress then
return;
end if;
Read (This.TX_Queue, RG, Bulk_Buffer_Size);
if State (RG) = Valid then
-- Copy into IN buffer
USB.Utils.Copy (Src => Slice (RG).Addr,
Dst => This.Bulk_In_Buf,
Count => Natural (Slice (RG).Length));
This.TX_In_Progress := True;
-- Send IN buffer
UDC.EP_Write_Packet (Ep => This.Bulk_EP,
Addr => This.Bulk_In_Buf,
Len => UInt32 (Slice (RG).Length));
Release (This.TX_Queue, RG);
end if;
end Setup_TX;
-----------------
-- Line_Coding --
-----------------
function Line_Coding (This : Default_Serial_Class)
return CDC_Line_Coding
is (This.Coding);
---------------------
-- List_Ctrl_State --
---------------------
function List_Ctrl_State (This : Default_Serial_Class)
return CDC_Line_Control_State
is (This.State);
----------
-- Read --
----------
procedure Read (This : in out Default_Serial_Class;
Buf : System.Address;
Len : in out UInt32)
is
RG : BBqueue.Buffers.Read_Grant;
begin
Read (This.RX_Queue, RG, Count (Len));
if State (RG) = Valid then
Len := UInt32 (Slice (RG).Length);
USB.Utils.Copy (Src => Slice (RG).Addr,
Dst => Buf,
Count => Len);
Release (This.RX_Queue, RG);
else
Len := 0;
end if;
end Read;
----------
-- Read --
----------
procedure Read (This : in out Default_Serial_Class;
Str : out String;
Len : out UInt32)
is
begin
Len := Str'Length;
This.Read (Str'Address, Len);
end Read;
-----------
-- Write --
-----------
procedure Write (This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class;
Buf : System.Address;
Len : in out UInt32)
is
WG : BBqueue.Buffers.Write_Grant;
begin
Grant (This.TX_Queue, WG, Count (Len));
if State (WG) = Valid then
Len := UInt32'Min (Len, UInt32 (Slice (WG).Length));
USB.Utils.Copy (Src => Buf,
Dst => Slice (WG).Addr,
Count => Len);
Commit (This.TX_Queue, WG);
This.Setup_TX (UDC);
else
Len := 0;
end if;
end Write;
-----------
-- Write --
-----------
procedure Write (This : in out Default_Serial_Class;
UDC : in out USB_Device_Controller'Class;
Str : String;
Len : out UInt32)
is
begin
Len := Str'Length;
This.Write (UDC, Str'Address, Len);
end Write;
end USB.Device.Serial;
|
-- MIT License
-- Copyright (c) 2021 Stephen Merrony
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
-- BEWARE: DO NOT FALL INTO THE TRAP OF TRYING TO RESOLVE ADDRESSES HERE - DECODE ONLY!
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Interfaces; use Interfaces;
with CPU_Instructions; use CPU_Instructions;
with Devices;
with DG_Types; use DG_Types;
with Memory; use Memory;
package Decoder is
type Carry_T is (None, Z, O, C);
type Mode_Num_T is new Word_T range 0 .. 3;
type Mode_T is (Absolute, PC, AC2, AC3);
type Shift_T is (None, L, R, S);
type Skip_T is (None, SKP, SZC, SNC, SZR, SNR, SEZ, SBN);
type Decoded_Instr_T is record
Instruction : Instr_Mnemonic_T;
Mnemonic : Unbounded_String;
Format : Instr_Format_T;
Instr_Type : Instr_Class_T;
Instr_Len : Positive;
Disp_Offset : Natural;
Disassembly : Unbounded_String;
-- Instruction Parameters
Mode : Mode_T;
Ind : Boolean;
Disp_8 : Integer_8; -- signed 8-bit displacement
Disp_15 : Integer_16; -- signed 15-bit displacement
Disp_31 : Integer_32; -- signed 31-bit displacement
Disp_32 : Unsigned_32;
Imm_S16 : Integer_16; -- signed 16-bit immediate
Imm_U16 : Unsigned_16;
Imm_DW : Dword_T;
Arg_Count : Integer;
Ac, Acs, Acd : AC_ID; -- single, src, dest ACs
Word_2 : Word_T; -- 2nd word of instruction
Word_3 : Word_T; -- 3rd word of instruction
IO_Dir : IO_Dir_T;
IO_Reg : IO_Reg_T; -- A/B/C I/O
IO_Flag : IO_Flag_T;
IO_Dev : Dev_Num_T;
IO_Test : IO_Test_T;
Sh : Shift_T;
Carry : Carry_T;
No_Load : Boolean;
Skip : Skip_T;
Bit_Number : Natural;
Low_Byte : Boolean;
end record;
type Opcode_Rec is record
Exists : Boolean;
Mnem : Instr_Mnemonic_T;
end record;
type Opcode_Lookup_T is array (0 .. 65_535) of Opcode_Rec;
procedure Match_Instruction
(Opcode : in Word_T; Mnem : out Instr_Mnemonic_T; Found : out Boolean);
function Generate_All_Possible_Opcodes return Opcode_Lookup_T;
function Instruction_Decode
(Opcode : in Word_T; PC : Phys_Addr_T; LEF_Mode : Boolean;
IO_On : Boolean; ATU_On : Boolean; Disassemble : Boolean;
Radix : Number_Base_T) return Decoded_Instr_T;
procedure Init;
Decode_Failed : exception;
private
Opcode_Lookup_Arr : Opcode_Lookup_T;
end Decoder;
|
------------------------------------------------------------------------------
-- Copyright (c) 2014-2016, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Ada.Command_Line;
with Ada.Text_IO;
with AWS.Config;
with AWS.Server;
with Syslog.Guess.App_Name;
with Syslog.Guess.Hostname;
with Syslog.Transport.Send_Task;
with Syslog.Transport.UDP;
with Simple_Webapps.Append_Servers;
procedure Append_Server is
WS : AWS.Server.HTTP;
Handler : Simple_Webapps.Append_Servers.Handler;
Debug : constant Boolean := Ada.Command_Line.Argument_Count >= 2;
begin
if Debug then
Simple_Webapps.Append_Servers.Log := Ada.Text_IO.Put_Line'Access;
else
Syslog.Guess.App_Name;
Syslog.Guess.Hostname;
Syslog.Transport.UDP.Connect ("127.0.0.1");
Syslog.Transport.Send_Task.Set_Backend (Syslog.Transport.UDP.Transport);
Syslog.Set_Transport (Syslog.Transport.Send_Task.Transport);
Syslog.Set_Default_Facility (Syslog.Facilities.Daemon);
Syslog.Set_Default_Severity (Syslog.Severities.Notice);
Simple_Webapps.Append_Servers.Log := Syslog.Log'Access;
end if;
if Ada.Command_Line.Argument_Count >= 1 then
Handler.Reset (Ada.Command_Line.Argument (1));
else
Handler.Reset ("append.sx");
end if;
AWS.Server.Start (WS, Handler, AWS.Config.Get_Current);
if Debug then
Ada.Text_IO.Put_Line ("Websever started");
AWS.Server.Wait (AWS.Server.Q_Key_Pressed);
else
AWS.Server.Wait;
end if;
AWS.Server.Shutdown (WS);
end Append_Server;
|
------------------------------------------------------------------------------
-- --
-- AFORTH COMPONENTS --
-- --
-- F O R T H . I N T E R P R E T E R --
-- --
-- B o d y --
-- --
-- Copyright (C) 2006-2011 Samuel Tardieu <sam@rfc1149.net> --
-- --
-- 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/>. --
-- --
-- The main repository for this software is located at: --
-- http://git.rfc1149.net/aforth.git --
-- --
------------------------------------------------------------------------------
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Exceptions; use Ada.Exceptions;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
with Forth.Builtins;
with Readline.Completion;
with Readline.Variables;
package body Forth.Interpreter is
-- Notes:
-- - the compilation stack is the data stack
TIB_Length : constant := 1024;
Stack_Marker : constant := -1;
Forward_Reference : constant := -100;
Backward_Reference : constant := -101;
Do_Loop_Reference : constant := -102;
Definition_Reference : constant := -103;
use Dictionaries, Compilation_Buffers;
procedure Initialize (I : IT);
-- Register builtin words (Ada and Forth primitives)
procedure Register (I : IT;
Name : String;
Action : Action_Type);
function Find (I : IT; Name : String) return Action_Type;
-- May raise Word_Not_Found
procedure Add_To_Compilation_Buffer (I : IT; Action : Action_Type);
function Next_Index (V : Compilation_Buffers.Vector)
return Natural_Cell;
package Cell_IO is new Ada.Text_IO.Integer_IO (Cell);
use Cell_IO;
pragma Warnings (Off);
function To_Cell_Access is
new Ada.Unchecked_Conversion (Byte_Access, Cell_Access);
pragma Warnings (On);
function To_Unsigned_32 is
new Ada.Unchecked_Conversion (Cell, Unsigned_32);
function To_Cell is
new Ada.Unchecked_Conversion (Unsigned_32, Cell);
function To_Unsigned_64 is
new Ada.Unchecked_Conversion (Integer_64, Unsigned_64);
function To_Integer_64 is
new Ada.Unchecked_Conversion (Unsigned_64, Integer_64);
Forth_Exit : constant Action_Type := (Kind => Forth_Word,
Immediate => True,
Inline => False,
Forth_Proc => -1);
procedure Remember_Variable
(I : IT;
Name : String;
Var : out Cell_Access);
procedure Remember_Variable
(I : IT;
Name : String;
Var : out Cell);
procedure Start_Definition (I : IT; Name : String := "");
function To_String (I : IT) return String;
procedure Execute_Action (I : IT; Action : Action_Type);
procedure Execute_Forth_Word (I : IT; Addr : Cell);
procedure Main_Loop (I : IT);
function Word (I : IT) return String;
procedure Jump (I : IT);
procedure Jump_If_False (I : IT);
procedure Patch_Jump (I : IT; To_Patch : Cell; Target : Cell);
procedure Add_To_Compilation_Buffer (I : IT; Ada_Proc : Ada_Word_Access);
procedure Add_To_Compilation_Buffer (I : IT; Value : Cell);
procedure DoDoes (I : IT);
procedure Refill_Line (I : IT; Buffer : String);
procedure Check_Compile_Only (I : IT);
procedure Tick (I : IT; Name : String);
procedure Check_Control_Structure (I : IT; Reference : Cell);
function Is_Blank (C : Character) return Boolean;
function Parse_Number (I : IT; S : String) return Cell;
-- Parse a number given the current base. This will raise Constraint_Error
-- if the number cannot be parsed.
function Peek (I : IT) return Cell;
-------------------------------
-- Add_To_Compilation_Buffer --
-------------------------------
procedure Add_To_Compilation_Buffer (I : IT; Action : Action_Type) is
begin
Check_Compile_Only (I);
-- Call or inline words
if Action.Kind = Forth_Word and then Action.Inline then
declare
Index : Cell := Action.Forth_Proc;
begin
while Element (I.Compilation_Buffer, Index) /= Forth_Exit loop
Add_To_Compilation_Buffer
(I, Element (I.Compilation_Buffer, Index));
Index := Index + 1;
end loop;
end;
else
Append (I.Compilation_Buffer, Action);
end if;
end Add_To_Compilation_Buffer;
-------------------------------
-- Add_To_Compilation_Buffer --
-------------------------------
procedure Add_To_Compilation_Buffer (I : IT; Ada_Proc : Ada_Word_Access) is
begin
Add_To_Compilation_Buffer
(I,
Action_Type'(Kind => Ada_Word,
Immediate => True,
Ada_Proc => Ada_Proc));
end Add_To_Compilation_Buffer;
-------------------------------
-- Add_To_Compilation_Buffer --
-------------------------------
procedure Add_To_Compilation_Buffer (I : IT; Value : Cell) is
begin
Add_To_Compilation_Buffer
(I,
Action_Type'(Kind => Number,
Immediate => True,
Value => Value));
end Add_To_Compilation_Buffer;
-----------
-- Again --
-----------
procedure Again (I : IT) is
begin
Check_Control_Structure (I, Backward_Reference);
Literal (I);
Add_To_Compilation_Buffer (I, Jump'Access);
Check_Control_Structure (I, Stack_Marker);
end Again;
-----------
-- Ahead --
-----------
procedure Ahead (I : IT) is
-- The compilation stack contains the index of the address to
-- patch when the AHEAD is resolved by a THEN.
begin
Push (I, Next_Index (I.Compilation_Buffer));
Push (I, Forward_Reference);
Add_To_Compilation_Buffer (I, 0);
Add_To_Compilation_Buffer (I, Jump'Access);
end Ahead;
-----------
-- Align --
-----------
procedure Align (I : IT) is
begin
if I.Here.all mod 4 /= 0 then
I.Here.all := I.Here.all + (4 - (I.Here.all mod 4));
end if;
end Align;
---------
-- Bye --
---------
procedure Bye (I : IT) is
begin
raise Bye_Exception;
end Bye;
------------
-- Cfetch --
------------
procedure Cfetch (I : IT) is
begin
Push (I, Cell (I.Memory (Pop (I))));
end Cfetch;
------------
-- Cfetch --
------------
function Cfetch (I : IT; Addr : Cell) return Cell is
begin
Push (I, Addr);
Cfetch (I);
return Pop (I);
end Cfetch;
------------------------
-- Check_Compile_Only --
------------------------
procedure Check_Compile_Only (I : IT) is
begin
if I.State.all /= 1 then
raise Compile_Only;
end if;
end Check_Compile_Only;
-----------------------------
-- Check_Control_Structure --
-----------------------------
procedure Check_Control_Structure (I : IT; Reference : Cell) is
begin
Check_Compile_Only (I);
if Pop (I) /= Reference then
raise Unbalanced_Control_Structure;
end if;
end Check_Control_Structure;
-----------
-- Colon --
-----------
procedure Colon (I : IT) is
begin
Start_Definition (I, Word (I));
end Colon;
------------------
-- Colon_Noname --
------------------
procedure Colon_Noname (I : IT) is
begin
Push (I, Next_Index (I.Compilation_Buffer));
Start_Definition (I);
end Colon_Noname;
-------------------
-- Compile_Comma --
-------------------
procedure Compile_Comma (I : IT) is
begin
Add_To_Compilation_Buffer (I, Pop (I));
Add_To_Compilation_Buffer (I, Execute'Access);
end Compile_Comma;
------------------
-- Compile_Exit --
------------------
procedure Compile_Exit (I : IT) is
begin
Add_To_Compilation_Buffer (I, Forth_Exit);
end Compile_Exit;
------------------
-- Compile_Mode --
------------------
procedure Compile_Mode (I : IT) is
begin
I.State.all := 1;
end Compile_Mode;
-----------
-- Count --
-----------
procedure Count (I : IT) is
Start : constant Cell := Pop (I);
begin
Push (I, Start + 1);
Push (I, Cell (I.Memory (Start)));
end Count;
--------
-- Cr --
--------
procedure Cr (I : IT) is
begin
Push (I, 13);
Emit (I);
Push (I, 10);
Emit (I);
end Cr;
------------
-- Cstore --
------------
procedure Cstore (I : IT) is
Addr : constant Cell := Pop (I);
begin
I.Memory (Addr) := Unsigned_8 (Pop (I));
end Cstore;
-----------
-- D_Abs --
-----------
procedure D_Abs (I : IT) is
begin
Push_64 (I, abs (Pop_64 (I)));
end D_Abs;
-------------
-- D_Equal --
-------------
procedure D_Equal (I : IT) is
begin
Push (I, Pop_64 (I) = Pop_64 (I));
end D_Equal;
-----------
-- D_Max --
-----------
procedure D_Max (I : IT) is
begin
Push_64 (I, Integer_64'Max (Pop_64 (I), Pop_64 (I)));
end D_Max;
-----------
-- D_Min --
-----------
procedure D_Min (I : IT) is
begin
Push_64 (I, Integer_64'Min (Pop_64 (I), Pop_64 (I)));
end D_Min;
-------------
-- D_Minus --
-------------
procedure D_Minus (I : IT) is
X : constant Integer_64 := Pop_64 (I);
begin
Push_64 (I, Pop_64 (I) - X);
end D_Minus;
------------
-- D_Plus --
------------
procedure D_Plus (I : IT) is
begin
Push_64 (I, Pop_64 (I) + Pop_64 (I));
end D_Plus;
---------------
-- D_Smaller --
---------------
procedure D_Smaller (I : IT) is
X : constant Integer_64 := Pop_64 (I);
begin
Push (I, Pop_64 (I) < X);
end D_Smaller;
---------------
-- D_Two_Div --
---------------
procedure D_Two_Div (I : IT) is
A : constant Integer_64 := Pop_64 (I);
B : Unsigned_64 := To_Unsigned_64 (A) / 2;
begin
if A < 0 then
B := B or (2 ** 63);
end if;
Push_Unsigned_64 (I, B);
end D_Two_Div;
-----------------
-- D_Two_Times --
-----------------
procedure D_Two_Times (I : IT) is
begin
Push_Unsigned_64 (I, Pop_Unsigned_64 (I) * 2);
end D_Two_Times;
-----------
-- Depth --
-----------
procedure Depth (I : IT) is
begin
Push (I, Cell (Length (I.Data_Stack)));
end Depth;
------------
-- DivMod --
------------
procedure DivMod (I : IT) is
B : constant Cell := Pop (I);
A : constant Cell := Pop (I);
begin
Push (I, A rem B);
Push (I, A / B);
end DivMod;
------------
-- DoDoes --
------------
procedure DoDoes (I : IT) is
begin
-- Patch the latest exit by inserting a call to the current
-- action.
pragma Assert (Last_Element (I.Compilation_Buffer) = Forth_Exit);
Insert (I.Compilation_Buffer,
Last_Index (I.Compilation_Buffer),
Action_Type'(Kind => Forth_Word,
Immediate => True,
Inline => False,
Forth_Proc => Pop (I)));
end DoDoes;
----------
-- Does --
----------
procedure Does (I : IT) is
-- Terminate current word after asking to patch the latest created
-- one. Compilation buffer after index, call to DoDoes and exit
-- is Compilation_Index + 3.
Does_Part : constant Cell := Last_Index (I.Compilation_Buffer) + 4;
begin
Add_To_Compilation_Buffer (I, Does_Part);
Add_To_Compilation_Buffer (I, DoDoes'Access);
Semicolon (I);
-- Start an unnamed word corresponding to the DOES> part
Start_Definition (I);
pragma Assert (Next_Index (I.Compilation_Buffer) = Does_Part);
end Does;
----------
-- Drop --
----------
procedure Drop (I : IT) is
Value : constant Cell := Pop (I);
pragma Unreferenced (Value);
begin
null;
end Drop;
---------
-- Dup --
---------
procedure Dup (I : IT) is
begin
Push (I, Peek (I.Data_Stack));
end Dup;
----------
-- Emit --
----------
procedure Emit (I : IT) is
begin
Put (Character'Val (Pop (I)));
end Emit;
-----------
-- Equal --
-----------
procedure Equal (I : IT) is
begin
Push (I, Pop (I) = Pop (I));
end Equal;
--------------
-- Evaluate --
--------------
procedure Evaluate (I : IT) is
begin
Interpret_Line (I, To_String (I));
end Evaluate;
-------------
-- Execute --
-------------
procedure Execute (I : IT) is
begin
Execute_Forth_Word (I, Pop (I));
end Execute;
--------------------
-- Execute_Action --
--------------------
procedure Execute_Action (I : IT; Action : Action_Type) is
begin
case Action.Kind is
when Ada_Word =>
Action.Ada_Proc.all (I);
when Forth_Word =>
Execute_Forth_Word (I, Action.Forth_Proc);
when Number =>
Push (I, Action.Value);
end case;
end Execute_Action;
------------------------
-- Execute_Forth_Word --
------------------------
procedure Execute_Forth_Word (I : IT; Addr : Cell) is
begin
Push (I.Return_Stack, I.Current_IP);
I.Current_IP := Addr;
while not I.Interrupt loop
declare
Current_Action : constant Action_Type :=
Element (I.Compilation_Buffer, I.Current_IP);
begin
I.Current_IP := I.Current_IP + 1;
if Current_Action = Forth_Exit then
I.Current_IP := Pop (I.Return_Stack);
return;
end if;
Execute_Action (I, Current_Action);
end;
end loop;
end Execute_Forth_Word;
-----------
-- Fetch --
-----------
procedure Fetch (I : IT) is
pragma Warnings (Off);
Addr : constant Cell_Access :=
To_Cell_Access (I.Memory (Pop (I))'Access);
pragma Warnings (On);
begin
Push (I, Addr.all);
end Fetch;
-----------
-- Fetch --
-----------
function Fetch (I : IT; Addr : Cell) return Cell is
begin
Push (I, Addr);
Fetch (I);
return Pop (I);
end Fetch;
----------
-- Find --
----------
procedure Find (I : IT) is
C : constant Cell := Peek (I);
A : Action_Type;
begin
Count (I);
A := Find (I, To_String (I));
Push (I, A.Forth_Proc);
if A.Immediate then
Push (I, 1);
else
Push (I, -1);
end if;
exception
when Word_Not_Found =>
Push (I, C);
Push (I, 0);
end Find;
----------
-- Find --
----------
function Find (I : IT; Name : String) return Action_Type
is
Lower_Name : constant String := To_Lower (Name);
begin
for J in reverse First_Index (I.Dict) .. Last_Index (I.Dict) loop
declare
Current : Dictionary_Entry renames Element (I.Dict, J);
begin
if To_Lower (To_String (Current.Name)) = Lower_Name then
pragma Assert (Current.Action.Kind = Forth_Word);
return Current.Action;
end if;
end;
end loop;
Raise_Word_Not_Found (Name);
end Find;
------------------
-- Fm_Slash_Mod --
------------------
procedure Fm_Slash_Mod (I : IT) is
Divisor : constant Integer_64 := Integer_64 (Pop (I));
Dividend : constant Integer_64 := Pop_64 (I);
Remainder : constant Integer_64 := Dividend mod Divisor;
Quotient : constant Integer_64 := (Dividend - Remainder) / Divisor;
begin
Push (I, Cell (Remainder));
Push_64 (I, Quotient);
Drop (I);
end Fm_Slash_Mod;
---------------
-- Forth_And --
---------------
procedure Forth_And (I : IT) is
begin
Push_Unsigned (I, Pop_Unsigned (I) and Pop_Unsigned (I));
end Forth_And;
-----------------
-- Forth_Begin --
-----------------
procedure Forth_Begin (I : IT) is
-- The structure of the BEGIN/WHILE/REPEAT loop on the compilation
-- stack is:
-- Stack_Marker
-- addr of first WHILE to patch
-- addr of second WHILE to patch
-- ...
-- addr of the beginning of the loop
-- Backward_Reference
begin
Push (I, Stack_Marker);
Push (I, Next_Index (I.Compilation_Buffer));
Push (I, Backward_Reference);
end Forth_Begin;
--------------
-- Forth_Do --
--------------
procedure Forth_Do (I : IT) is
-- The structure of a DO - LOOP/+LOOP on the compilation stack
-- is:
-- Stack_Marker
-- addr of the first DO/LEAVE
-- addr of the second LEAVE
-- addr of the third LEAVE
-- ...
-- addr of the beginning of the loop
-- Do_Loop_Reference
-- At run-time, on the return stack, we have:
-- Loop_Limit
-- Loop_Index
begin
Add_To_Compilation_Buffer (I, Two_To_R'Access);
Push (I, Stack_Marker);
Push (I, Next_Index (I.Compilation_Buffer));
Push (I, Do_Loop_Reference);
end Forth_Do;
--------------
-- Forth_If --
--------------
procedure Forth_If (I : IT) is
begin
Push (I, Next_Index (I.Compilation_Buffer));
Push (I, Forward_Reference);
Add_To_Compilation_Buffer (I, 0);
Add_To_Compilation_Buffer (I, Jump_If_False'Access);
end Forth_If;
--------------
-- Forth_Or --
--------------
procedure Forth_Or (I : IT) is
begin
Push_Unsigned (I, Pop_Unsigned (I) or Pop_Unsigned (I));
end Forth_Or;
----------------
-- Forth_Then --
----------------
procedure Forth_Then (I : IT) is
begin
Check_Control_Structure (I, Forward_Reference);
Patch_Jump (I,
To_Patch => Pop (I),
Target => Next_Index (I.Compilation_Buffer));
end Forth_Then;
-----------------
-- Forth_While --
-----------------
procedure Forth_While (I : IT) is
begin
Check_Control_Structure (I, Backward_Reference);
Push (I, Next_Index (I.Compilation_Buffer));
Swap (I);
Add_To_Compilation_Buffer (I, 0);
Add_To_Compilation_Buffer (I, Jump_If_False'Access);
Push (I, Backward_Reference);
end Forth_While;
---------------
-- Forth_Xor --
---------------
procedure Forth_Xor (I : IT) is
begin
Push_Unsigned (I, Pop_Unsigned (I) xor Pop_Unsigned (I));
end Forth_Xor;
----------------------
-- Free_Interpreter --
----------------------
procedure Free_Interpreter (I : in out IT) is
procedure Free is
new Ada.Unchecked_Deallocation (Interpreter_Body, Interpreter_Type);
begin
Free (I);
end Free_Interpreter;
------------
-- From_R --
------------
procedure From_R (I : IT) is
begin
Push (I, Pop (I.Return_Stack));
end From_R;
------------------
-- Greaterequal --
------------------
procedure Greaterequal (I : IT) is
B : constant Cell := Pop (I);
begin
Push (I, Pop (I) >= B);
end Greaterequal;
-------------
-- Include --
-------------
procedure Include (I : IT) is
begin
Include_File (I, Word (I));
end Include;
------------------
-- Include_File --
------------------
procedure Include_File (I : IT; File_Name : String)
is
Previous_Input : constant File_Access := Current_Input;
File : File_Type;
Old_TIB_Count : constant Cell := I.TIB_Count.all;
Old_IN_Ptr : constant Cell := I.IN_Ptr.all;
Old_TIB : constant Byte_Array :=
I.Memory (I.TIB .. I.TIB + Old_TIB_Count - 1);
Old_Use_RL : constant Boolean := I.Use_RL;
begin
begin
Open (File, In_File, File_Name);
exception
when Name_Error =>
Put_Line ("*** File not found: " & File_Name);
raise;
end;
Set_Input (File);
I.Use_RL := False;
begin
Main_Loop (I);
exception
when End_Error =>
Close (File);
Set_Input (Previous_Input.all);
I.Memory (I.TIB .. I.TIB + Old_TIB_Count - 1) := Old_TIB;
I.TIB_Count.all := Old_TIB_Count;
I.IN_Ptr.all := Old_IN_Ptr;
I.Use_RL := Old_Use_RL;
when others =>
Close (File);
Set_Input (Previous_Input.all);
I.Use_RL := Old_Use_RL;
raise;
end;
end Include_File;
----------------
-- Initialize --
----------------
procedure Initialize (I : IT) is
begin
-- Store and register HERE at position 0
-- Bootstrap STATE at position 4
pragma Warnings (Off);
I.State := To_Cell_Access (I.Memory (4)'Access);
pragma Warnings (On);
Store (I, 0, 4);
Start_Definition (I, "(HERE)");
Add_To_Compilation_Buffer (I, 0);
Semicolon (I);
Remember_Variable (I, "(HERE)", I.Here);
Make_And_Remember_Variable (I, "STATE", I.State);
-- Default existing variables
Make_And_Remember_Variable (I, "BASE", I.Base, Initial_Value => 10);
Make_And_Remember_Variable (I, "TIB", I.TIB, Size => 1024);
Make_And_Remember_Variable (I, "TIB#", I.TIB_Count);
Make_And_Remember_Variable (I, ">IN", I.IN_Ptr);
-- Default Ada words
Register_Ada_Word (I, "AGAIN", Again'Access, Immediate => True);
Register_Ada_Word (I, "AHEAD", Ahead'Access, Immediate => True);
Register_Ada_Word (I, "ALIGN", Align'Access);
Register_Ada_Word (I, "BYE", Bye'Access);
Register_Ada_Word (I, "C@", Cfetch'Access);
Register_Ada_Word (I, "COMPILE,", Compile_Comma'Access);
Register_Ada_Word (I, "COUNT", Count'Access);
Register_Ada_Word (I, "C!", Cstore'Access);
Register_Ada_Word (I, ":", Colon'Access);
Register_Ada_Word (I, ":NONAME", Colon_Noname'Access);
Register_Ada_Word (I, "]", Compile_Mode'Access);
Register_Ada_Word (I, "CR", Cr'Access);
Register_Ada_Word (I, "DABS", D_Abs'Access);
Register_Ada_Word (I, "D=", D_Equal'Access);
Register_Ada_Word (I, "DMAX", D_Max'Access);
Register_Ada_Word (I, "DMIN", D_Min'Access);
Register_Ada_Word (I, "D-", D_Minus'Access);
Register_Ada_Word (I, "D+", D_Plus'Access);
Register_Ada_Word (I, "D<", D_Smaller'Access);
Register_Ada_Word (I, "D2/", D_Two_Div'Access);
Register_Ada_Word (I, "D2*", D_Two_Times'Access);
Register_Ada_Word (I, "DEPTH", Depth'Access);
Register_Ada_Word (I, "/MOD", DivMod'Access);
Register_Ada_Word (I, "DOES>", Does'Access, Immediate => True);
Register_Ada_Word (I, "DROP", Drop'Access);
Register_Ada_Word (I, "DUP", Dup'Access);
Register_Ada_Word (I, "EMIT", Emit'Access);
Register_Ada_Word (I, "=", Equal'Access);
Register_Ada_Word (I, "EVALUATE", Evaluate'Access);
Register_Ada_Word (I, "EXECUTE", Execute'Access);
Register_Ada_Word (I, "@", Fetch'Access);
Register_Ada_Word (I, "FIND", Find'Access);
Register_Ada_Word (I, "FM/MOD", Fm_Slash_Mod'Access);
Register_Ada_Word (I, "AND", Forth_And'Access);
Register_Ada_Word (I, "BEGIN", Forth_Begin'Access, Immediate => True);
Register_Ada_Word (I, "DO", Forth_Do'Access, Immediate => True);
Register_Ada_Word (I, "EXIT", Compile_Exit'Access, Immediate => True);
Register_Ada_Word (I, "IF", Forth_If'Access, Immediate => True);
Register_Ada_Word (I, "OR", Forth_Or'Access);
Register_Ada_Word (I, "THEN", Forth_Then'Access, Immediate => True);
Register_Ada_Word (I, "WHILE", Forth_While'Access, Immediate => True);
Register_Ada_Word (I, "XOR", Forth_Xor'Access);
Register_Ada_Word (I, "R>", From_R'Access);
Register_Ada_Word (I, ">=", Greaterequal'Access);
Register_Ada_Word (I, "J", J'Access);
Register_Ada_Word (I, "INCLUDE", Include'Access);
Register_Ada_Word (I, "[", Interpret_Mode'Access, Immediate => True);
Register_Ada_Word (I, "LEAVE", Leave'Access, Immediate => True);
Register_Ada_Word (I, "LITERAL", Literal'Access, Immediate => True);
Register_Ada_Word (I, "LSHIFT", Lshift'Access);
Register_Ada_Word (I, "KEY", Key'Access);
Register_Ada_Word (I, "MS", MS'Access);
Register_Ada_Word (I, "M*", Mstar'Access);
Register_Ada_Word (I, "0<", Negative'Access);
Register_Ada_Word (I, "PARSE", Parse'Access);
Register_Ada_Word (I, "PARSE-WORD", Parse_Word'Access);
Register_Ada_Word (I, "PICK", Pick'Access);
Register_Ada_Word (I, "+", Plus'Access);
Register_Ada_Word (I, "+LOOP", Plus_Loop'Access, Immediate => True);
Register_Ada_Word (I, "POSTPONE", Postpone'Access, Immediate => True);
Register_Ada_Word (I, "QUIT", Quit'Access);
Register_Ada_Word (I, "R@", R_At'Access);
Register_Ada_Word (I, "RECURSE", Recurse'Access, Immediate => True);
Register_Ada_Word (I, "REFILL", Refill'Access);
Register_Ada_Word (I, "REPEAT", Repeat'Access, Immediate => True);
Register_Ada_Word (I, "ROLL", Roll'Access);
Register_Ada_Word (I, "RSHIFT", Rshift'Access);
Register_Ada_Word (I, "S>D", S_To_D'Access);
Register_Ada_Word (I, "*/MOD", ScaleMod'Access);
Register_Ada_Word (I, "SEE", See'Access);
Register_Ada_Word (I, ";", Semicolon'Access, Immediate => True);
Register_Ada_Word (I, "IMMEDIATE", Set_Immediate'Access);
Register_Ada_Word (I, "INLINE", Set_Inline'Access);
Register_Ada_Word (I, "SKIP-BLANKS", Skip_Blanks'Access);
Register_Ada_Word (I, "SM/REM", Sm_Slash_Rem'Access);
Register_Ada_Word (I, "SWAP", Swap'Access);
Register_Ada_Word (I, "!", Store'Access);
Register_Ada_Word (I, "'", Tick'Access);
Register_Ada_Word (I, "*", Times'Access);
Register_Ada_Word (I, ">BODY", To_Body'Access);
Register_Ada_Word (I, ">R", To_R'Access);
Register_Ada_Word (I, "2/", Two_Div'Access);
Register_Ada_Word (I, "2DUP", Two_Dup'Access);
Register_Ada_Word (I, "2R@", Two_R_At'Access);
Register_Ada_Word (I, "2>R", Two_To_R'Access);
Register_Ada_Word (I, "U<", U_Smaller'Access);
Register_Ada_Word (I, "UM/MOD", Um_Slash_Mod'Access);
Register_Ada_Word (I, "UM*", Um_Star'Access);
Register_Ada_Word (I, "UNLOOP", Unloop'Access);
Register_Ada_Word (I, "UNUSED", Unused'Access);
Register_Ada_Word (I, "WORD", Word'Access);
Register_Ada_Word (I, "WORDS", Words'Access);
for J in Forth.Builtins.Builtins'Range loop
Interpret_Line (I, Forth.Builtins.Builtins (J) .all);
end loop;
Readline.Variables.Variable_Bind ("completion-ignore-case", "on");
end Initialize;
--------------
-- Is_Blank --
--------------
function Is_Blank (C : Character) return Boolean is
begin
return C <= ' ';
end Is_Blank;
---------------
-- Interpret --
---------------
procedure Interpret (I : IT) is
begin
while not I.Interrupt loop
declare
W : constant String := Word (I);
A : Action_Type;
C : Cell;
begin
if W'Length = 0 then
exit;
end if;
if I.State.all = 0 then
begin
A := Find (I, W);
A.Immediate := True;
Execute_Action (I, A);
exception
when NF : Word_Not_Found =>
begin
C := Parse_Number (I, W);
exception
when Constraint_Error =>
Reraise_Occurrence (NF);
end;
Push (I, C);
when Compile_Only =>
raise Compile_Only with W;
end;
else
begin
A := Find (I, W);
if A.Immediate then
Execute_Action (I, A);
else
Add_To_Compilation_Buffer (I, A);
end if;
exception
when NF : Word_Not_Found =>
begin
C := Parse_Number (I, W);
exception
when Constraint_Error =>
Reraise_Occurrence (NF);
end;
Add_To_Compilation_Buffer (I, C);
when Compile_Only =>
raise Compile_Only with W;
end;
end if;
end;
end loop;
end Interpret;
--------------------
-- Interpret_Line --
--------------------
procedure Interpret_Line (I : IT; Line : String) is
Saved_Count : constant Cell := I.TIB_Count.all;
Saved_Content : constant Byte_Array (1 .. TIB_Length) :=
I.Memory (I.TIB .. I.TIB + TIB_Length - 1);
Saved_Ptr : constant Cell := I.IN_Ptr.all;
begin
I.Interrupt := False;
Refill_Line (I, Line);
Interpret (I);
I.Memory (I.TIB .. I.TIB + TIB_Length - 1) := Saved_Content;
I.TIB_Count.all := Saved_Count;
I.IN_Ptr.all := Saved_Ptr;
end Interpret_Line;
--------------------
-- Interpret_Mode --
--------------------
procedure Interpret_Mode (I : IT) is
begin
I.State.all := 0;
end Interpret_Mode;
---------------
-- Interrupt --
---------------
procedure Interrupt (I : IT) is
begin
I.Interrupt := True;
end Interrupt;
-------
-- J --
-------
procedure J (I : IT) is
begin
if Length (I.Return_Stack) < 3 then
raise Stack_Underflow;
end if;
Push (I, Element (I.Return_Stack, Length (I.Return_Stack) - 2));
end J;
----------
-- Jump --
----------
procedure Jump (I : IT) is
begin
I.Current_IP := Pop (I);
end Jump;
-------------------
-- Jump_If_False --
-------------------
procedure Jump_If_False (I : IT) is
Target : constant Cell := Pop (I);
begin
if Pop (I) = 0 then
I.Current_IP := Target;
end if;
end Jump_If_False;
---------
-- Key --
---------
procedure Key (I : IT) is
C : Character;
begin
Get_Immediate (C);
Push (I, Cell (Character'Pos (C)));
end Key;
-----------
-- Leave --
-----------
procedure Leave (I : IT) is
begin
-- Look for Do_Loop_Reference on the stack
for J in reverse 1 .. Length (I.Data_Stack) loop
if Element (I.Data_Stack, J) = Do_Loop_Reference then
-- Insert the leave information at the proper place
Insert (I.Data_Stack, J - 1, Next_Index (I.Compilation_Buffer));
Add_To_Compilation_Buffer (I, 0);
Add_To_Compilation_Buffer (I, Jump'Access);
return;
end if;
end loop;
raise Unbalanced_Control_Structure;
end Leave;
-------------
-- Literal --
-------------
procedure Literal (I : IT) is
begin
Add_To_Compilation_Buffer (I, Pop (I));
end Literal;
------------
-- Lshift --
------------
procedure Lshift (I : IT) is
U : constant Natural := Natural (Pop_Unsigned (I));
begin
Push (I, Pop (I) * 2 ** U);
end Lshift;
---------------
-- Main_Loop --
---------------
procedure Main_Loop (I : IT) is
begin
loop
Refill (I);
Interpret (I);
end loop;
end Main_Loop;
--------------------------------
-- Make_And_Remember_Variable --
--------------------------------
procedure Make_And_Remember_Variable
(I : IT;
Name : String;
Var : out Cell_Access;
Size : Cell := 4;
Initial_Value : Cell := 0)
is
begin
Make_Variable (I, Name, Size, Initial_Value);
Remember_Variable (I, Name, Var);
end Make_And_Remember_Variable;
--------------------------------
-- Make_And_Remember_Variable --
--------------------------------
procedure Make_And_Remember_Variable
(I : IT;
Name : String;
Var : out Cell;
Size : Cell := 4;
Initial_Value : Cell := 0)
is
begin
Make_Variable (I, Name, Size, Initial_Value);
Remember_Variable (I, Name, Var);
end Make_And_Remember_Variable;
-------------------
-- Make_Variable --
-------------------
procedure Make_Variable
(I : IT;
Name : String;
Size : Cell := 4;
Initial_Value : Cell := 0)
is
begin
if Size = 4 then
Align (I);
Store (I, I.Here.all, Initial_Value);
elsif Initial_Value /= 0 then
raise Program_Error;
end if;
Start_Definition (I, Name);
Add_To_Compilation_Buffer (I, I.Here.all);
Semicolon (I);
I.Here.all := I.Here.all + Size;
end Make_Variable;
--------
-- MS --
--------
procedure MS (I : IT) is
begin
delay until Clock + Milliseconds (Integer (Pop (I)));
end MS;
-----------
-- Mstar --
-----------
procedure Mstar (I : IT) is
begin
Push_64 (I, Integer_64 (Pop (I)) * Integer_64 (Pop (I)));
end Mstar;
--------------
-- Negative --
--------------
procedure Negative (I : IT) is
begin
Push (I, Pop (I) < 0);
end Negative;
----------------
-- Next_Index --
----------------
function Next_Index (V : Compilation_Buffers.Vector) return Natural_Cell is
begin
return Last_Index (V) + 1;
end Next_Index;
---------------------
-- New_Interpreter --
---------------------
function New_Interpreter
(Memory_Size : Cell := 65536;
Stack_Size : Cell := 256)
return IT is
begin
return I : constant IT := new Interpreter_Body (Memory_Size - 1) do
New_Stack (I.Data_Stack, Stack_Size);
New_Stack (I.Return_Stack, Stack_Size);
Initialize (I);
end return;
end New_Interpreter;
-----------
-- Parse --
-----------
procedure Parse (I : IT)
is
Char : constant Unsigned_8 := Unsigned_8 (Pop (I));
begin
Push (I, I.TIB + I.IN_Ptr.all);
for J in I.IN_Ptr.all .. I.TIB_Count.all - 1 loop
if I.Memory (I.TIB + J) = Char then
Push (I, J - I.IN_Ptr.all);
I.IN_Ptr.all := J + 1;
return;
end if;
end loop;
Push (I, I.TIB_Count.all - I.IN_Ptr.all);
I.IN_Ptr.all := I.TIB_Count.all;
end Parse;
------------------
-- Parse_Number --
------------------
function Parse_Number (I : IT; S : String) return Cell
is
B : constant Unsigned_32 := Unsigned_32 (I.Base.all);
Negative : Boolean := False;
Sign_Parsed : Boolean := False;
Result : Unsigned_32 := 0;
begin
for I in S'Range loop
declare
C : Character renames S (I);
begin
if C = '+' then
if Sign_Parsed then
raise Constraint_Error;
end if;
elsif C = '-' then
if Sign_Parsed then
raise Constraint_Error;
end if;
Negative := not Negative;
else
declare
Digit : Unsigned_32;
begin
Sign_Parsed := True;
if C >= '0' and C <= '9' then
Digit := Character'Pos (C) - Character'Pos ('0');
elsif C >= 'A' and C <= 'Z' then
Digit := 10 + Character'Pos (C) - Character'Pos ('A');
elsif C >= 'a' and C <= 'z' then
Digit := 10 + Character'Pos (C) - Character'Pos ('a');
else
raise Constraint_Error;
end if;
if Digit >= B then
raise Constraint_Error;
end if;
Result := Result * B + Digit;
end;
end if;
end;
end loop;
if Negative then
return -To_Cell (Result);
else
return To_Cell (Result);
end if;
end Parse_Number;
----------------
-- Parse_Word --
----------------
procedure Parse_Word (I : IT) is
Origin : Cell;
begin
Skip_Blanks (I);
Origin := I.IN_Ptr.all;
Push (I, I.TIB + Origin);
while I.IN_Ptr.all < I.TIB_Count.all loop
declare
C : constant Character :=
Character'Val (I.Memory (I.TIB + I.IN_Ptr.all));
begin
I.IN_Ptr.all := I.IN_Ptr.all + 1;
if Is_Blank (C) then
Push (I, I.IN_Ptr.all - Origin - 1);
return;
end if;
end;
end loop;
Push (I, I.IN_Ptr.all - Origin);
end Parse_Word;
----------------
-- Patch_Jump --
----------------
procedure Patch_Jump (I : IT; To_Patch : Cell; Target : Cell) is
pragma Assert (To_Patch < Next_Index (I.Compilation_Buffer));
pragma Assert (Target <= Next_Index (I.Compilation_Buffer));
Current : Action_Type := Element (I.Compilation_Buffer, To_Patch);
begin
Current.Value := Target;
Replace_Element (I.Compilation_Buffer, To_Patch, Current);
end Patch_Jump;
----------
-- Peek --
-----------
function Peek (I : IT) return Cell is
begin
return Peek (I.Data_Stack);
end Peek;
----------
-- Pick --
----------
procedure Pick (I : IT) is
How_Deep : constant Integer := Integer (Pop (I));
begin
if How_Deep >= Length (I.Data_Stack) then
raise Stack_Underflow;
end if;
Push (I, Element (I.Data_Stack, Length (I.Data_Stack) - How_Deep));
end Pick;
----------
-- Plus --
----------
procedure Plus (I : IT) is
begin
Push (I, Pop (I) + Pop (I));
end Plus;
---------------
-- Plus_Loop --
---------------
procedure Plus_Loop (I : IT) is
To_Patch : Cell;
begin
Check_Control_Structure (I, Do_Loop_Reference);
-- The standard says: "Add n to the loop index. If the loop
-- index did not cross the boundary between the loop limit
-- minus one and the loop limit, continue execution at the
-- beginning of the loop. Otherwise, discard the current loop
-- control parameters and continue execution immediately
-- following the loop."
--
-- In Forth, that is:
-- dup >r + >r 2dup >r >r >= swap 0< xor
-- not if [beginning] then unloop
Add_To_Compilation_Buffer (I, Dup'Access);
Add_To_Compilation_Buffer (I, From_R'Access);
Add_To_Compilation_Buffer (I, Plus'Access);
Add_To_Compilation_Buffer (I, From_R'Access);
Add_To_Compilation_Buffer (I, Two_Dup'Access);
Add_To_Compilation_Buffer (I, To_R'Access);
Add_To_Compilation_Buffer (I, To_R'Access);
Add_To_Compilation_Buffer (I, Greaterequal'Access);
Add_To_Compilation_Buffer (I, Swap'Access);
Add_To_Compilation_Buffer (I, Negative'Access);
Add_To_Compilation_Buffer (I, Forth_Xor'Access);
Add_To_Compilation_Buffer (I, Pop (I));
Add_To_Compilation_Buffer (I, Jump_If_False'Access);
Add_To_Compilation_Buffer (I, Unloop'Access);
-- Resolve forward references
loop
To_Patch := Pop (I);
exit when To_Patch = Stack_Marker;
Patch_Jump (I,
To_Patch => To_Patch,
Target => Next_Index (I.Compilation_Buffer));
end loop;
end Plus_Loop;
---------
-- Pop --
---------
function Pop (I : IT) return Cell is
begin
return Pop (I.Data_Stack);
end Pop;
------------
-- Pop_64 --
------------
function Pop_64 (I : IT) return Integer_64 is
begin
return To_Integer_64 (Pop_Unsigned_64 (I));
end Pop_64;
------------------
-- Pop_Unsigned --
------------------
function Pop_Unsigned (I : IT) return Unsigned_32 is
begin
return To_Unsigned_32 (Pop (I));
end Pop_Unsigned;
---------------------
-- Pop_Unsigned_64 --
---------------------
function Pop_Unsigned_64 (I : IT) return Unsigned_64 is
High : constant Unsigned_64 := Unsigned_64 (Pop_Unsigned (I)) * 2 ** 32;
begin
return High + Unsigned_64 (Pop_Unsigned (I));
end Pop_Unsigned_64;
--------------
-- Postpone --
--------------
procedure Postpone (I : IT) is
W : constant String := Word (I);
Action : Action_Type;
begin
Action := Find (I, W);
if Action.Immediate then
Add_To_Compilation_Buffer (I, Action);
else
Add_To_Compilation_Buffer (I, Action.Forth_Proc);
Add_To_Compilation_Buffer (I, Compile_Comma'Access);
end if;
exception
when Word_Not_Found =>
begin
Add_To_Compilation_Buffer (I, Parse_Number (I, W));
exception
when Constraint_Error =>
Raise_Word_Not_Found (W);
end;
end Postpone;
----------
-- Push --
----------
procedure Push (I : IT; X : Cell) is
begin
Push (I.Data_Stack, X);
end Push;
----------
-- Push --
----------
procedure Push (I : IT; B : Boolean) is
begin
if B then
Push (I, -1);
else
Push (I, 0);
end if;
end Push;
-------------
-- Push_64 --
-------------
procedure Push_64 (I : IT; X : Integer_64) is
begin
Push_Unsigned_64 (I, To_Unsigned_64 (X));
end Push_64;
-------------------
-- Push_Unsigned --
-------------------
procedure Push_Unsigned (I : IT; X : Unsigned_32) is
begin
Push (I, To_Cell (X));
end Push_Unsigned;
----------------------
-- Push_Unsigned_64 --
----------------------
procedure Push_Unsigned_64 (I : IT; X : Unsigned_64) is
begin
Push_Unsigned (I, Unsigned_32 (X mod (2 ** 32)));
Push_Unsigned (I, Unsigned_32 (X / 2 ** 32));
end Push_Unsigned_64;
----------
-- Quit --
----------
procedure Quit (I : IT) is
begin
loop
Clear (I.Data_Stack);
Clear (I.Return_Stack);
Interpret_Mode (I);
begin
Main_Loop (I);
exception
when Bye_Exception =>
return;
when End_Error =>
return;
when NF : Word_Not_Found =>
Put_Line ("*** Word not found: " & Exception_Message (NF));
when Stack_Overflow =>
Put_Line ("*** Stack overflow");
when Stack_Underflow =>
Put_Line ("*** Stack underflow");
when CO : Compile_Only =>
Put_Line ("*** Compile only: " & Exception_Message (CO));
when Name_Error =>
-- This exception has already been handled and is getting
-- reraised.
null;
when E : others =>
Put_Line ("*** Exception " & Exception_Name (E) &
" with message " &
Exception_Message (E));
end;
end loop;
end Quit;
----------
-- R_At --
----------
procedure R_At (I : IT) is
begin
Push (I, Peek (I.Return_Stack));
end R_At;
-------------
-- Recurse --
-------------
procedure Recurse (I : IT) is
begin
Add_To_Compilation_Buffer (I, I.Current_Action);
end Recurse;
------------
-- Refill --
------------
procedure Refill (I : IT) is
begin
if I.Use_RL then
if I.State.all = 0 then
Cr (I);
Refill_Line (I, Readline.Read_Line ("ok> "));
else
Refill_Line (I, Readline.Read_Line ("] "));
end if;
else
declare
Buffer : String (1 .. TIB_Length);
Last : Natural;
begin
Get_Line (Buffer, Last);
Refill_Line (I, Buffer (1 .. Last));
end;
end if;
end Refill;
-----------------
-- Refill_Line --
-----------------
procedure Refill_Line (I : IT; Buffer : String) is
Last : constant Natural := Natural'Min (Buffer'Length, TIB_Length);
begin
for J in 1 .. Integer'Min (Buffer'Length, TIB_Length) loop
I.Memory (I.TIB + Cell (J) - 1) := Character'Pos (Buffer (J));
end loop;
I.TIB_Count.all := Cell (Last);
I.IN_Ptr.all := 0;
end Refill_Line;
--------------
-- Register --
--------------
procedure Register
(I : IT;
Name : String;
Action : Action_Type)
is
begin
Append (I.Dict, (Name => To_Unbounded_String (Name),
Action => Action));
Readline.Completion.Add_Word (Name);
end Register;
-----------------------
-- Register_Ada_Word --
-----------------------
procedure Register_Ada_Word
(I : IT;
Name : String;
Word : Ada_Word_Access;
Immediate : Boolean := False)
is
begin
-- Create a Forth wrapper around an Ada word so that its address
-- can be taken and passed to EXECUTE.
Start_Definition (I, Name);
Add_To_Compilation_Buffer (I, Word);
Semicolon (I);
if Immediate then
Set_Immediate (I);
end if;
Set_Inline (I);
end Register_Ada_Word;
-----------------------
-- Register_Constant --
-----------------------
procedure Register_Constant
(I : IT;
Name : String;
Value : Cell)
is
begin
Start_Definition (I, Name);
Add_To_Compilation_Buffer (I, Value);
Semicolon (I);
end Register_Constant;
-----------------------
-- Remember_Variable --
-----------------------
procedure Remember_Variable
(I : IT;
Name : String;
Var : out Cell_Access)
is
begin
Tick (I, Name);
To_Body (I);
pragma Warnings (Off);
Var := To_Cell_Access (I.Memory (Pop (I)) 'Access);
pragma Warnings (On);
end Remember_Variable;
-----------------------
-- Remember_Variable --
-----------------------
procedure Remember_Variable
(I : IT;
Name : String;
Var : out Cell)
is
begin
Tick (I, Name);
To_Body (I);
Var := Pop (I);
end Remember_Variable;
------------
-- Repeat --
------------
procedure Repeat (I : IT) is
begin
Check_Control_Structure (I, Backward_Reference);
Literal (I);
Add_To_Compilation_Buffer (I, Jump'Access);
loop
declare
To_Fix : constant Cell := Pop (I);
begin
exit when To_Fix = Stack_Marker;
Patch_Jump (I, To_Fix, Next_Index (I.Compilation_Buffer));
end;
end loop;
end Repeat;
----------
-- Roll --
----------
procedure Roll (I : IT) is
Offset : constant Integer := Integer (Pop (I));
Index : constant Positive := Length (I.Data_Stack) - Offset;
begin
Push (I.Data_Stack, Element (I.Data_Stack, Index));
Delete (I.Data_Stack, Index);
end Roll;
------------
-- Rshift --
------------
procedure Rshift (I : IT) is
U : constant Natural := Natural (Pop_Unsigned (I));
begin
Push_Unsigned (I, Pop_Unsigned (I) / 2 ** U);
end Rshift;
------------
-- S_To_D --
------------
procedure S_To_D (I : IT) is
begin
Push_64 (I, Integer_64 (Pop (I)));
end S_To_D;
--------------
-- ScaleMod --
--------------
procedure ScaleMod (I : IT) is
begin
To_R (I);
Mstar (I);
From_R (I);
Sm_Slash_Rem (I);
end ScaleMod;
---------
-- See --
---------
procedure See (I : IT) is
Index : Cell;
Action : Action_Type;
Found : Boolean;
begin
Tick (I);
Index := Pop (I);
loop
Found := False;
Put (Cell'Image (Index) & ": ");
Action := Element (I.Compilation_Buffer, Index);
if Action = Forth_Exit then
Put_Line ("EXIT");
exit;
end if;
case Action.Kind is
when Number =>
declare
S : constant String := Cell'Image (Action.Value);
begin
Found := True;
if Action.Value >= 0 then
Put_Line (S (2 .. S'Last));
else
Put_Line (S);
end if;
end;
when Forth_Word =>
for J in
reverse First_Index (I.Dict) .. Last_Index (I.Dict) loop
declare
Current : Dictionary_Entry renames Element (I.Dict, J);
begin
if Current.Action.Kind = Forth_Word and then
Current.Action.Forth_Proc = Action.Forth_Proc
then
Found := True;
Put_Line (To_String (Current.Name));
exit;
end if;
end;
end loop;
when Ada_Word =>
if Action.Ada_Proc = Jump'Access then
Found := True;
Put_Line ("<JUMP>");
elsif Action.Ada_Proc = Jump_If_False'Access then
Found := True;
Put_Line ("<JUMP IF FALSE>");
elsif Action.Ada_Proc = DoDoes'Access then
Found := True;
Put_Line ("<DO DOES>");
else
for J in
reverse First_Index (I.Dict) .. Last_Index (I.Dict) loop
declare
Current : Dictionary_Entry renames Element (I.Dict, J);
begin
if Current.Action.Kind = Forth_Word then
declare
Idx : constant Cell :=
Current.Action.Forth_Proc;
A : constant Action_Type :=
Element (I.Compilation_Buffer, Idx);
begin
if A.Kind = Ada_Word and then
A.Ada_Proc = Action.Ada_Proc and then
Element (I.Compilation_Buffer, Idx + 1) =
Forth_Exit
then
Found := True;
Put_Line (To_String (Current.Name) &
" <Ada primitive>");
exit;
end if;
end;
end if;
end;
end loop;
end if;
end case;
if not Found then
Put_Line ("<unknown control word>");
end if;
Index := Index + 1;
end loop;
end See;
---------------
-- Semicolon --
---------------
procedure Semicolon (I : IT) is
begin
Check_Control_Structure (I, Definition_Reference);
Add_To_Compilation_Buffer (I, Forth_Exit);
-- Current_Name can be null during definition or completion of
-- a DOES> prefix.
if I.Current_Name /= "" then
Register (I, To_String (I.Current_Name), I.Current_Action);
I.Current_Name := To_Unbounded_String ("");
end if;
Interpret_Mode (I);
end Semicolon;
-------------------
-- Set_Immediate --
-------------------
procedure Set_Immediate (I : IT) is
Current : Dictionary_Entry := Last_Element (I.Dict);
begin
Current.Action.Immediate := True;
Replace_Element (I.Dict, Last_Index (I.Dict), Current);
end Set_Immediate;
----------------
-- Set_Inline --
----------------
procedure Set_Inline (I : IT) is
Current : Dictionary_Entry := Last_Element (I.Dict);
begin
Current.Action.Inline := True;
Replace_Element (I.Dict, Last_Index (I.Dict), Current);
end Set_Inline;
-----------------
-- Skip_Blanks --
-----------------
procedure Skip_Blanks (I : IT) is
begin
while I.IN_Ptr.all < I.TIB_Count.all loop
exit when
not Is_Blank (Character'Val (I.Memory (I.TIB + I.IN_Ptr.all)));
I.IN_Ptr.all := I.IN_Ptr.all + 1;
end loop;
end Skip_Blanks;
------------------
-- Sm_Slash_Rem --
------------------
procedure Sm_Slash_Rem (I : IT) is
N : constant Integer_64 := Integer_64 (Pop (I));
D : constant Integer_64 := Pop_64 (I);
R : constant Integer_64 := D rem N;
begin
Push (I, Cell (R));
Push_64 (I, (D - R) / N);
Drop (I);
end Sm_Slash_Rem;
----------------------
-- Start_Definition --
----------------------
procedure Start_Definition (I : IT; Name : String := "") is
begin
if Name /= "" then
I.Current_Name := To_Unbounded_String (Name);
end if;
I.Current_Action.Immediate := False;
I.Current_Action.Forth_Proc := Next_Index (I.Compilation_Buffer);
Compile_Mode (I);
Push (I, Definition_Reference);
end Start_Definition;
-----------
-- Store --
-----------
procedure Store (I : IT)
is
pragma Warnings (Off);
Addr : constant Cell_Access :=
To_Cell_Access (I.Memory (Pop (I))'Access);
pragma Warnings (On);
begin
Addr.all := Pop (I);
end Store;
-----------
-- Store --
-----------
procedure Store (I : IT; Addr : Cell; Value : Cell) is
begin
Push (I, Value);
Push (I, Addr);
Store (I);
end Store;
----------
-- Swap --
----------
procedure Swap (I : IT)
is
A : constant Cell := Pop (I);
B : constant Cell := Pop (I);
begin
Push (I, A);
Push (I, B);
end Swap;
----------
-- Tick --
----------
procedure Tick (I : IT; Name : String) is
A : constant Action_Type := Find (I, Name);
begin
Push (I, A.Forth_Proc);
end Tick;
----------
-- Tick --
----------
procedure Tick (I : IT) is
begin
Tick (I, Word (I));
end Tick;
-----------
-- Times --
-----------
procedure Times (I : IT) is
begin
Push (I, Pop (I) * Pop (I));
end Times;
-------------
-- To_Body --
-------------
procedure To_Body (I : IT) is
begin
Push (I, Element (I.Compilation_Buffer, Pop (I)) .Value);
end To_Body;
----------
-- To_R --
----------
procedure To_R (I : IT) is
begin
Push (I.Return_Stack, Pop (I));
end To_R;
---------------
-- To_String --
---------------
function To_String (I : IT) return String is
Length : constant Natural := Natural (Pop (I));
Addr : Cell := Pop (I);
Result : String (1 .. Length);
begin
for J in Result'Range loop
Result (J) := Character'Val (Cfetch (I, Addr));
Addr := Addr + 1;
end loop;
return Result;
end To_String;
-------------
-- Two_Div --
-------------
procedure Two_Div (I : IT) is
A : constant Cell := Pop (I);
B : Unsigned_32 := To_Unsigned_32 (A) / 2;
begin
if A < 0 then
B := B or (2 ** 31);
end if;
Push_Unsigned (I, B);
end Two_Div;
-------------
-- Two_Dup --
-------------
procedure Two_Dup (I : IT) is
A : constant Cell := Pop (I);
B : constant Cell := Pop (I);
begin
Push (I, B);
Push (I, A);
Push (I, B);
Push (I, A);
end Two_Dup;
--------------
-- Two_R_At --
--------------
procedure Two_R_At (I : IT) is
begin
Push (I, Element (I.Return_Stack, Length (I.Return_Stack) - 1));
Push (I, Peek (I.Return_Stack));
end Two_R_At;
--------------
-- Two_To_R --
--------------
procedure Two_To_R (I : IT) is
begin
Swap (I);
To_R (I);
To_R (I);
end Two_To_R;
---------------
-- U_Smaller --
---------------
procedure U_Smaller (I : IT) is
R : constant Unsigned_32 := Pop_Unsigned (I);
begin
Push (I, Pop_Unsigned (I) < R);
end U_Smaller;
------------------
-- Um_Slash_Mod --
------------------
procedure Um_Slash_Mod (I : IT) is
N : constant Unsigned_64 := Unsigned_64 (Pop_Unsigned (I));
D : constant Unsigned_64 := Pop_Unsigned_64 (I);
begin
Push_Unsigned (I, Unsigned_32 (D mod N));
Push_Unsigned_64 (I, D / N);
Drop (I);
end Um_Slash_Mod;
-------------
-- Um_Star --
-------------
procedure Um_Star (I : IT) is
begin
Push_Unsigned_64 (I, Unsigned_64 (Pop_Unsigned (I)) *
Unsigned_64 (Pop_Unsigned (I)));
end Um_Star;
------------
-- Unloop --
------------
procedure Unloop (I : IT) is
begin
Delete_Last (I.Return_Stack);
Delete_Last (I.Return_Stack);
end Unloop;
------------
-- Unused --
------------
procedure Unused (I : IT) is
begin
Push (I, I.Memory'Last - I.Here.all + 1);
end Unused;
----------
-- Word --
----------
procedure Word (I : IT) is
Length : Cell;
Addr : Cell;
begin
Parse (I);
Length := Pop (I);
Addr := Pop (I);
I.Memory (Addr - 1) := Unsigned_8 (Length);
Push (I, Addr - 1);
end Word;
----------
-- Word --
----------
function Word (I : IT) return String is
begin
Parse_Word (I);
return To_String (I);
end Word;
-----------
-- Words --
-----------
procedure Words (I : IT) is
Len : Natural := 0;
begin
for J in First_Index (I.Dict) .. Last_Index (I.Dict) loop
declare
Current : Dictionary_Entry renames Element (I.Dict, J);
begin
Len := Len + Length (Current.Name) + 1;
if Len > 75 then
New_Line;
Len := Length (Current.Name);
elsif J /= First_Index (I.Dict) then
Put (' ');
end if;
Put (To_String (Current.Name));
end;
end loop;
end Words;
end Forth.Interpreter;
|
with Ada.Numerics.Generic_Elementary_Functions;
package body Planets is
package EF is new Ada.Numerics.Generic_Elementary_Functions (Orka.Float_64);
function Get_Vector
(Latitude, Longitude : Orka.Float_64) return Matrices.Vectors.Vector4
is
Lon_Rad : constant Orka.Float_64 := Matrices.Vectors.To_Radians (Longitude);
Lat_Rad : constant Orka.Float_64 := Matrices.Vectors.To_Radians (Latitude);
XY : constant Orka.Float_64 := EF.Cos (Lat_Rad);
X : constant Orka.Float_64 := XY * EF.Cos (Lon_Rad);
Y : constant Orka.Float_64 := XY * EF.Sin (Lon_Rad);
Z : constant Orka.Float_64 := EF.Sin (Lat_Rad);
begin
pragma Assert (Matrices.Vectors.Normalized ((X, Y, Z, 0.0)));
return (X, Y, Z, 1.0);
end Get_Vector;
function Flattened_Vector
(Planet : Planet_Characteristics;
Direction : Matrices.Vector4;
Altitude : Orka.Float_64) return Matrices.Vectors.Vector4
is
E2 : constant Orka.Float_64 := 2.0 * Planet.Flattening - Planet.Flattening**2;
N : constant Orka.Float_64 := Planet.Semi_Major_Axis /
EF.Sqrt (1.0 - E2 * Direction (Orka.Z)**2);
begin
return
(Direction (Orka.X) * (N + Altitude),
Direction (Orka.Y) * (N + Altitude),
Direction (Orka.Z) * (N * (1.0 - E2) + Altitude),
1.0);
end Flattened_Vector;
function Geodetic_To_ECEF
(Planet : Planet_Characteristics;
Latitude, Longitude, Altitude : Orka.Float_64) return Matrices.Vector4 is
begin
return Flattened_Vector (Planet, Get_Vector (Latitude, Longitude), Altitude);
end Geodetic_To_ECEF;
function Radius
(Planet : Planet_Characteristics;
Direction : Matrices.Vector4) return Orka.Float_64 is
begin
return Matrices.Vectors.Length (Flattened_Vector (Planet, Direction, 0.0));
end Radius;
function Radius
(Planet : Planet_Characteristics;
Latitude, Longitude : Orka.Float_64) return Orka.Float_64 is
begin
return Radius (Planet, Get_Vector (Latitude, Longitude));
end Radius;
end Planets;
|
-- SPDX-FileCopyrightText: 2021-2022 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
---------------------------------------------------------------------
with Ada.Real_Time;
with Ada.Streams;
with Ada.Unchecked_Conversion;
with Interfaces;
with System;
with ESP32.GPIO;
with ESP32.DPort;
with ESP32.SPI;
with Lora;
with Ints;
with Locations;
procedure Main
with No_Return
is
use type Ada.Real_Time.Time;
Environment_Task_Storage_Size : constant Natural := 4096
with
Export,
Convention => Ada,
External_Name => "_environment_task_storage_size";
-- Increase stack size for environment task
procedure puts
(data : String)
with Import, Convention => C, External_Name => "puts";
procedure Read
(Address : Interfaces.Unsigned_8;
Value : out Interfaces.Unsigned_8);
-- Read a byte from LoRa module
procedure Write
(Address : Interfaces.Unsigned_8;
Value : Interfaces.Unsigned_8);
-- Write a byte to LoRa module
----------
-- Read --
----------
procedure Read
(Address : Interfaces.Unsigned_8;
Value : out Interfaces.Unsigned_8)
is
Buffer : ESP32.SPI.Data_Array (1 .. 1);
begin
ESP32.SPI.Half_Duplex_Transfer
(Host => ESP32.SPI.SPI_2,
Address => (8, Interfaces.Unsigned_16 (Address)),
MISO => Buffer);
Value := Interfaces.Unsigned_8 (Buffer (1));
end Read;
-----------
-- Write --
-----------
procedure Write
(Address : Interfaces.Unsigned_8;
Value : Interfaces.Unsigned_8)
is
Buffer : constant ESP32.SPI.Data_Array (1 .. 1) :=
(1 => Ada.Streams.Stream_Element (Value));
begin
ESP32.SPI.Half_Duplex_Transfer
(Host => ESP32.SPI.SPI_2,
Address => (8, Interfaces.Unsigned_16 (Address)),
MOSI => Buffer);
end Write;
package Lora_SPI is new Lora (Read, Write);
Button : constant := 0; -- Button pad
LED : constant := 25; -- LED pad
LoRa_Reset : constant := 14;
begin
ESP32.DPort.Set_Active (ESP32.DPort.SPI2, True);
ESP32.GPIO.Configure_All
(((Pad => LED,
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Output,
Output => ESP32.GPIO.GPIO_OUT),
(Pad => 5, -- SPI CLK
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Output,
Output => ESP32.GPIO.HSPICLK),
(Pad => 18, -- SPI CS0 -> LoRa NSS
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Output,
Output => ESP32.GPIO.HSPICS0),
(Pad => 27, -- SPI MOSI
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Output,
Output => ESP32.GPIO.HSPID),
(Pad => 19, -- SPI MISO
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Input,
Interrupt => ESP32.GPIO.Disabled,
Input => ESP32.GPIO.HSPIQ),
(Pad => 26, -- <-- LoRa DIO0
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Input,
Interrupt => ESP32.GPIO.Rising_Edge,
Input => ESP32.GPIO.None),
(Pad => 35, -- <-- LoRa DIO1
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Input,
Interrupt => ESP32.GPIO.Rising_Edge,
Input => ESP32.GPIO.None),
(Pad => 34, -- <-- LoRa DIO2
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Input,
Interrupt => ESP32.GPIO.Disabled,
Input => ESP32.GPIO.None),
(Pad => LoRa_Reset, -- --> LoRa_Reset
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Output,
Output => ESP32.GPIO.GPIO_OUT),
(Pad => Button,
IO_MUX => ESP32.GPIO.GPIO_Matrix,
Direction => ESP32.GPIO.Input,
Interrupt => ESP32.GPIO.Disabled,
Input => ESP32.GPIO.None)));
ESP32.GPIO.Set_Level (LoRa_Reset, False);
delay until Ada.Real_Time.Clock + Ada.Real_Time.Milliseconds (20);
ESP32.GPIO.Set_Level (LoRa_Reset, True);
delay until Ada.Real_Time.Clock + Ada.Real_Time.Milliseconds (50);
ESP32.GPIO.Set_Level (18, True); -- SS
ESP32.SPI.Configure
(Host => ESP32.SPI.SPI_2,
Bit_Order => System.High_Order_First,
Byte_Order => System.Low_Order_First,
Frequency => 8_000_000,
CP_Mode => ESP32.SPI.Mode0);
ESP32.GPIO.Set_Level (LED, True);
LoRa_SPI.Initialize (433_375_000);
LoRa_SPI.Receive;
loop
declare
use type Ada.Streams.Stream_Element;
use type Ada.Streams.Stream_Element_Count;
use type Interfaces.Unsigned_16;
use type Interfaces.Integer_32;
Image : Ada.Streams.Stream_Element_Array (1 .. 2 + 2 * 4 + 7);
Index : Ada.Streams.Stream_Element_Count;
-- Next free byte in Image
subtype Word is Ada.Streams.Stream_Element_Array (1 .. 4);
function Cast is new Ada.Unchecked_Conversion
(Interfaces.Integer_32, Word);
procedure Append (Data : Ada.Streams.Stream_Element_Array);
-- Append Data to Image
------------
-- Append --
------------
procedure Append (Data : Ada.Streams.Stream_Element_Array) is
begin
Image (Index .. Index + Data'Length - 1) := Data;
Index := Index + Data'Length;
end Append;
type Packet is record
Lat : Interfaces.Integer_32;
Lng : Interfaces.Integer_32;
Tm_Sat : Interfaces.Unsigned_16;
Power : Interfaces.Unsigned_8;
end record;
RX_Done : Boolean;
RX_Timeout : Boolean;
Data : Packet;
Last : Ada.Streams.Stream_Element_Count;
Buffer : Ada.Streams.Stream_Element_Array (1 .. 12)
with Import, Address => Data'Address;
Present : constant :=
Locations.Location_Present + Locations.UTC_Time_Present;
Year_1 : constant := 2022 rem 256;
Year_2 : constant := 2022 / 256;
Month : constant := 6;
Day : constant := 1;
begin
Ints.Signal.Wait (RX_Done, RX_Timeout);
if RX_Done then
Lora_SPI.On_DIO_0_Raise (Buffer, Last);
if Last = Buffer'Last then
Index := 1;
Append ((Present, 0));
Append (Cast (Data.Lat / 5 * 9));
Append (Cast (Data.Lng / 5 * 9));
Append ((Year_1, Year_2, Month, Day)); -- year, month, day
Append
((0, -- hh
Ada.Streams.Stream_Element (Data.Tm_Sat / 16 / 60), -- mi
Ada.Streams.Stream_Element (Data.Tm_Sat / 16 mod 60))); -- s
Locations.Peripheral_Device.Write
(Locations.Location_and_Speed, Image);
Locations.Peripheral_Device.Write
(Locations.Battery_Level,
(1 => Ada.Streams.Stream_Element (Data.Power)));
end if;
end if;
end;
end loop;
end Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ C H 5 --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Aspects; use Aspects;
with Atree; use Atree;
with Checks; use Checks;
with Einfo; use Einfo;
with Errout; use Errout;
with Expander; use Expander;
with Exp_Ch6; use Exp_Ch6;
with Exp_Util; use Exp_Util;
with Freeze; use Freeze;
with Ghost; use Ghost;
with Lib; use Lib;
with Lib.Xref; use Lib.Xref;
with Namet; use Namet;
with Nlists; use Nlists;
with Nmake; use Nmake;
with Opt; use Opt;
with Restrict; use Restrict;
with Rident; use Rident;
with Sem; use Sem;
with Sem_Aux; use Sem_Aux;
with Sem_Case; use Sem_Case;
with Sem_Ch3; use Sem_Ch3;
with Sem_Ch6; use Sem_Ch6;
with Sem_Ch8; use Sem_Ch8;
with Sem_Dim; use Sem_Dim;
with Sem_Disp; use Sem_Disp;
with Sem_Elab; use Sem_Elab;
with Sem_Eval; use Sem_Eval;
with Sem_Res; use Sem_Res;
with Sem_Type; use Sem_Type;
with Sem_Util; use Sem_Util;
with Sem_Warn; use Sem_Warn;
with Snames; use Snames;
with Stand; use Stand;
with Sinfo; use Sinfo;
with Targparm; use Targparm;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
package body Sem_Ch5 is
Current_LHS : Node_Id := Empty;
-- Holds the left-hand side of the assignment statement being analyzed.
-- Used to determine the type of a target_name appearing on the RHS, for
-- AI12-0125 and the use of '@' as an abbreviation for the LHS.
Unblocked_Exit_Count : Nat := 0;
-- This variable is used when processing if statements, case statements,
-- and block statements. It counts the number of exit points that are not
-- blocked by unconditional transfer instructions: for IF and CASE, these
-- are the branches of the conditional; for a block, they are the statement
-- sequence of the block, and the statement sequences of any exception
-- handlers that are part of the block. When processing is complete, if
-- this count is zero, it means that control cannot fall through the IF,
-- CASE or block statement. This is used for the generation of warning
-- messages. This variable is recursively saved on entry to processing the
-- construct, and restored on exit.
procedure Preanalyze_Range (R_Copy : Node_Id);
-- Determine expected type of range or domain of iteration of Ada 2012
-- loop by analyzing separate copy. Do the analysis and resolution of the
-- copy of the bound(s) with expansion disabled, to prevent the generation
-- of finalization actions. This prevents memory leaks when the bounds
-- contain calls to functions returning controlled arrays or when the
-- domain of iteration is a container.
------------------------
-- Analyze_Assignment --
------------------------
-- WARNING: This routine manages Ghost regions. Return statements must be
-- replaced by gotos which jump to the end of the routine and restore the
-- Ghost mode.
procedure Analyze_Assignment (N : Node_Id) is
Lhs : constant Node_Id := Name (N);
Rhs : constant Node_Id := Expression (N);
T1 : Entity_Id;
T2 : Entity_Id;
Decl : Node_Id;
procedure Diagnose_Non_Variable_Lhs (N : Node_Id);
-- N is the node for the left hand side of an assignment, and it is not
-- a variable. This routine issues an appropriate diagnostic.
procedure Kill_Lhs;
-- This is called to kill current value settings of a simple variable
-- on the left hand side. We call it if we find any error in analyzing
-- the assignment, and at the end of processing before setting any new
-- current values in place.
procedure Set_Assignment_Type
(Opnd : Node_Id;
Opnd_Type : in out Entity_Id);
-- Opnd is either the Lhs or Rhs of the assignment, and Opnd_Type is the
-- nominal subtype. This procedure is used to deal with cases where the
-- nominal subtype must be replaced by the actual subtype.
-------------------------------
-- Diagnose_Non_Variable_Lhs --
-------------------------------
procedure Diagnose_Non_Variable_Lhs (N : Node_Id) is
begin
-- Not worth posting another error if left hand side already flagged
-- as being illegal in some respect.
if Error_Posted (N) then
return;
-- Some special bad cases of entity names
elsif Is_Entity_Name (N) then
declare
Ent : constant Entity_Id := Entity (N);
begin
if Ekind (Ent) = E_In_Parameter then
Error_Msg_N
("assignment to IN mode parameter not allowed", N);
return;
-- Renamings of protected private components are turned into
-- constants when compiling a protected function. In the case
-- of single protected types, the private component appears
-- directly.
elsif (Is_Prival (Ent)
and then
(Ekind (Current_Scope) = E_Function
or else Ekind (Enclosing_Dynamic_Scope
(Current_Scope)) = E_Function))
or else
(Ekind (Ent) = E_Component
and then Is_Protected_Type (Scope (Ent)))
then
Error_Msg_N
("protected function cannot modify protected object", N);
return;
elsif Ekind (Ent) = E_Loop_Parameter then
Error_Msg_N ("assignment to loop parameter not allowed", N);
return;
end if;
end;
-- For indexed components, test prefix if it is in array. We do not
-- want to recurse for cases where the prefix is a pointer, since we
-- may get a message confusing the pointer and what it references.
elsif Nkind (N) = N_Indexed_Component
and then Is_Array_Type (Etype (Prefix (N)))
then
Diagnose_Non_Variable_Lhs (Prefix (N));
return;
-- Another special case for assignment to discriminant
elsif Nkind (N) = N_Selected_Component then
if Present (Entity (Selector_Name (N)))
and then Ekind (Entity (Selector_Name (N))) = E_Discriminant
then
Error_Msg_N ("assignment to discriminant not allowed", N);
return;
-- For selection from record, diagnose prefix, but note that again
-- we only do this for a record, not e.g. for a pointer.
elsif Is_Record_Type (Etype (Prefix (N))) then
Diagnose_Non_Variable_Lhs (Prefix (N));
return;
end if;
end if;
-- If we fall through, we have no special message to issue
Error_Msg_N ("left hand side of assignment must be a variable", N);
end Diagnose_Non_Variable_Lhs;
--------------
-- Kill_Lhs --
--------------
procedure Kill_Lhs is
begin
if Is_Entity_Name (Lhs) then
declare
Ent : constant Entity_Id := Entity (Lhs);
begin
if Present (Ent) then
Kill_Current_Values (Ent);
end if;
end;
end if;
end Kill_Lhs;
-------------------------
-- Set_Assignment_Type --
-------------------------
procedure Set_Assignment_Type
(Opnd : Node_Id;
Opnd_Type : in out Entity_Id)
is
begin
Require_Entity (Opnd);
-- If the assignment operand is an in-out or out parameter, then we
-- get the actual subtype (needed for the unconstrained case). If the
-- operand is the actual in an entry declaration, then within the
-- accept statement it is replaced with a local renaming, which may
-- also have an actual subtype.
if Is_Entity_Name (Opnd)
and then (Ekind (Entity (Opnd)) = E_Out_Parameter
or else Ekind_In (Entity (Opnd),
E_In_Out_Parameter,
E_Generic_In_Out_Parameter)
or else
(Ekind (Entity (Opnd)) = E_Variable
and then Nkind (Parent (Entity (Opnd))) =
N_Object_Renaming_Declaration
and then Nkind (Parent (Parent (Entity (Opnd)))) =
N_Accept_Statement))
then
Opnd_Type := Get_Actual_Subtype (Opnd);
-- If assignment operand is a component reference, then we get the
-- actual subtype of the component for the unconstrained case.
elsif Nkind_In (Opnd, N_Selected_Component, N_Explicit_Dereference)
and then not Is_Unchecked_Union (Opnd_Type)
then
Decl := Build_Actual_Subtype_Of_Component (Opnd_Type, Opnd);
if Present (Decl) then
Insert_Action (N, Decl);
Mark_Rewrite_Insertion (Decl);
Analyze (Decl);
Opnd_Type := Defining_Identifier (Decl);
Set_Etype (Opnd, Opnd_Type);
Freeze_Itype (Opnd_Type, N);
elsif Is_Constrained (Etype (Opnd)) then
Opnd_Type := Etype (Opnd);
end if;
-- For slice, use the constrained subtype created for the slice
elsif Nkind (Opnd) = N_Slice then
Opnd_Type := Etype (Opnd);
end if;
end Set_Assignment_Type;
-- Local variables
Mode : Ghost_Mode_Type;
-- Start of processing for Analyze_Assignment
begin
-- Save LHS for use in target names (AI12-125)
Current_LHS := Lhs;
Mark_Coextensions (N, Rhs);
-- Analyze the target of the assignment first in case the expression
-- contains references to Ghost entities. The checks that verify the
-- proper use of a Ghost entity need to know the enclosing context.
Analyze (Lhs);
-- An assignment statement is Ghost when the left hand side denotes a
-- Ghost entity. Set the mode now to ensure that any nodes generated
-- during analysis and expansion are properly marked as Ghost.
Mark_And_Set_Ghost_Assignment (N, Mode);
Analyze (Rhs);
-- Ensure that we never do an assignment on a variable marked as
-- as Safe_To_Reevaluate.
pragma Assert (not Is_Entity_Name (Lhs)
or else Ekind (Entity (Lhs)) /= E_Variable
or else not Is_Safe_To_Reevaluate (Entity (Lhs)));
-- Start type analysis for assignment
T1 := Etype (Lhs);
-- In the most general case, both Lhs and Rhs can be overloaded, and we
-- must compute the intersection of the possible types on each side.
if Is_Overloaded (Lhs) then
declare
I : Interp_Index;
It : Interp;
begin
T1 := Any_Type;
Get_First_Interp (Lhs, I, It);
while Present (It.Typ) loop
-- An indexed component with generalized indexing is always
-- overloaded with the corresponding dereference. Discard the
-- interpretation that yields a reference type, which is not
-- assignable.
if Nkind (Lhs) = N_Indexed_Component
and then Present (Generalized_Indexing (Lhs))
and then Has_Implicit_Dereference (It.Typ)
then
null;
-- This may be a call to a parameterless function through an
-- implicit dereference, so discard interpretation as well.
elsif Is_Entity_Name (Lhs)
and then Has_Implicit_Dereference (It.Typ)
then
null;
elsif Has_Compatible_Type (Rhs, It.Typ) then
if T1 /= Any_Type then
-- An explicit dereference is overloaded if the prefix
-- is. Try to remove the ambiguity on the prefix, the
-- error will be posted there if the ambiguity is real.
if Nkind (Lhs) = N_Explicit_Dereference then
declare
PI : Interp_Index;
PI1 : Interp_Index := 0;
PIt : Interp;
Found : Boolean;
begin
Found := False;
Get_First_Interp (Prefix (Lhs), PI, PIt);
while Present (PIt.Typ) loop
if Is_Access_Type (PIt.Typ)
and then Has_Compatible_Type
(Rhs, Designated_Type (PIt.Typ))
then
if Found then
PIt :=
Disambiguate (Prefix (Lhs),
PI1, PI, Any_Type);
if PIt = No_Interp then
Error_Msg_N
("ambiguous left-hand side in "
& "assignment", Lhs);
exit;
else
Resolve (Prefix (Lhs), PIt.Typ);
end if;
exit;
else
Found := True;
PI1 := PI;
end if;
end if;
Get_Next_Interp (PI, PIt);
end loop;
end;
else
Error_Msg_N
("ambiguous left-hand side in assignment", Lhs);
exit;
end if;
else
T1 := It.Typ;
end if;
end if;
Get_Next_Interp (I, It);
end loop;
end;
if T1 = Any_Type then
Error_Msg_N
("no valid types for left-hand side for assignment", Lhs);
Kill_Lhs;
goto Leave;
end if;
end if;
-- The resulting assignment type is T1, so now we will resolve the left
-- hand side of the assignment using this determined type.
Resolve (Lhs, T1);
-- Cases where Lhs is not a variable
-- Cases where Lhs is not a variable. In an instance or an inlined body
-- no need for further check because assignment was legal in template.
if In_Inlined_Body then
null;
elsif not Is_Variable (Lhs) then
-- Ada 2005 (AI-327): Check assignment to the attribute Priority of a
-- protected object.
declare
Ent : Entity_Id;
S : Entity_Id;
begin
if Ada_Version >= Ada_2005 then
-- Handle chains of renamings
Ent := Lhs;
while Nkind (Ent) in N_Has_Entity
and then Present (Entity (Ent))
and then Present (Renamed_Object (Entity (Ent)))
loop
Ent := Renamed_Object (Entity (Ent));
end loop;
if (Nkind (Ent) = N_Attribute_Reference
and then Attribute_Name (Ent) = Name_Priority)
-- Renamings of the attribute Priority applied to protected
-- objects have been previously expanded into calls to the
-- Get_Ceiling run-time subprogram.
or else Is_Expanded_Priority_Attribute (Ent)
then
-- The enclosing subprogram cannot be a protected function
S := Current_Scope;
while not (Is_Subprogram (S)
and then Convention (S) = Convention_Protected)
and then S /= Standard_Standard
loop
S := Scope (S);
end loop;
if Ekind (S) = E_Function
and then Convention (S) = Convention_Protected
then
Error_Msg_N
("protected function cannot modify protected object",
Lhs);
end if;
-- Changes of the ceiling priority of the protected object
-- are only effective if the Ceiling_Locking policy is in
-- effect (AARM D.5.2 (5/2)).
if Locking_Policy /= 'C' then
Error_Msg_N
("assignment to the attribute PRIORITY has no effect??",
Lhs);
Error_Msg_N
("\since no Locking_Policy has been specified??", Lhs);
end if;
goto Leave;
end if;
end if;
end;
Diagnose_Non_Variable_Lhs (Lhs);
goto Leave;
-- Error of assigning to limited type. We do however allow this in
-- certain cases where the front end generates the assignments.
elsif Is_Limited_Type (T1)
and then not Assignment_OK (Lhs)
and then not Assignment_OK (Original_Node (Lhs))
then
-- CPP constructors can only be called in declarations
if Is_CPP_Constructor_Call (Rhs) then
Error_Msg_N ("invalid use of 'C'P'P constructor", Rhs);
else
Error_Msg_N
("left hand of assignment must not be limited type", Lhs);
Explain_Limited_Type (T1, Lhs);
end if;
goto Leave;
-- A class-wide type may be a limited view. This illegal case is not
-- caught by previous checks.
elsif Ekind (T1) = E_Class_Wide_Type and then From_Limited_With (T1) then
Error_Msg_NE ("invalid use of limited view of&", Lhs, T1);
goto Leave;
-- Enforce RM 3.9.3 (8): the target of an assignment operation cannot be
-- abstract. This is only checked when the assignment Comes_From_Source,
-- because in some cases the expander generates such assignments (such
-- in the _assign operation for an abstract type).
elsif Is_Abstract_Type (T1) and then Comes_From_Source (N) then
Error_Msg_N
("target of assignment operation must not be abstract", Lhs);
end if;
-- Resolution may have updated the subtype, in case the left-hand side
-- is a private protected component. Use the correct subtype to avoid
-- scoping issues in the back-end.
T1 := Etype (Lhs);
-- Ada 2005 (AI-50217, AI-326): Check wrong dereference of incomplete
-- type. For example:
-- limited with P;
-- package Pkg is
-- type Acc is access P.T;
-- end Pkg;
-- with Pkg; use Acc;
-- procedure Example is
-- A, B : Acc;
-- begin
-- A.all := B.all; -- ERROR
-- end Example;
if Nkind (Lhs) = N_Explicit_Dereference
and then Ekind (T1) = E_Incomplete_Type
then
Error_Msg_N ("invalid use of incomplete type", Lhs);
Kill_Lhs;
goto Leave;
end if;
-- Now we can complete the resolution of the right hand side
Set_Assignment_Type (Lhs, T1);
Resolve (Rhs, T1);
-- If the right-hand side contains target names, expansion has been
-- disabled to prevent expansion that might move target names out of
-- the context of the assignment statement. Restore the expander mode
-- now so that assignment statement can be properly expanded.
if Nkind (N) = N_Assignment_Statement and then Has_Target_Names (N) then
Expander_Mode_Restore;
end if;
-- This is the point at which we check for an unset reference
Check_Unset_Reference (Rhs);
Check_Unprotected_Access (Lhs, Rhs);
-- Remaining steps are skipped if Rhs was syntactically in error
if Rhs = Error then
Kill_Lhs;
goto Leave;
end if;
T2 := Etype (Rhs);
if not Covers (T1, T2) then
Wrong_Type (Rhs, Etype (Lhs));
Kill_Lhs;
goto Leave;
end if;
-- Ada 2005 (AI-326): In case of explicit dereference of incomplete
-- types, use the non-limited view if available
if Nkind (Rhs) = N_Explicit_Dereference
and then Is_Tagged_Type (T2)
and then Has_Non_Limited_View (T2)
then
T2 := Non_Limited_View (T2);
end if;
Set_Assignment_Type (Rhs, T2);
if Total_Errors_Detected /= 0 then
if No (T1) then
T1 := Any_Type;
end if;
if No (T2) then
T2 := Any_Type;
end if;
end if;
if T1 = Any_Type or else T2 = Any_Type then
Kill_Lhs;
goto Leave;
end if;
-- If the rhs is class-wide or dynamically tagged, then require the lhs
-- to be class-wide. The case where the rhs is a dynamically tagged call
-- to a dispatching operation with a controlling access result is
-- excluded from this check, since the target has an access type (and
-- no tag propagation occurs in that case).
if (Is_Class_Wide_Type (T2)
or else (Is_Dynamically_Tagged (Rhs)
and then not Is_Access_Type (T1)))
and then not Is_Class_Wide_Type (T1)
then
Error_Msg_N ("dynamically tagged expression not allowed!", Rhs);
elsif Is_Class_Wide_Type (T1)
and then not Is_Class_Wide_Type (T2)
and then not Is_Tag_Indeterminate (Rhs)
and then not Is_Dynamically_Tagged (Rhs)
then
Error_Msg_N ("dynamically tagged expression required!", Rhs);
end if;
-- Propagate the tag from a class-wide target to the rhs when the rhs
-- is a tag-indeterminate call.
if Is_Tag_Indeterminate (Rhs) then
if Is_Class_Wide_Type (T1) then
Propagate_Tag (Lhs, Rhs);
elsif Nkind (Rhs) = N_Function_Call
and then Is_Entity_Name (Name (Rhs))
and then Is_Abstract_Subprogram (Entity (Name (Rhs)))
then
Error_Msg_N
("call to abstract function must be dispatching", Name (Rhs));
elsif Nkind (Rhs) = N_Qualified_Expression
and then Nkind (Expression (Rhs)) = N_Function_Call
and then Is_Entity_Name (Name (Expression (Rhs)))
and then
Is_Abstract_Subprogram (Entity (Name (Expression (Rhs))))
then
Error_Msg_N
("call to abstract function must be dispatching",
Name (Expression (Rhs)));
end if;
end if;
-- Ada 2005 (AI-385): When the lhs type is an anonymous access type,
-- apply an implicit conversion of the rhs to that type to force
-- appropriate static and run-time accessibility checks. This applies
-- as well to anonymous access-to-subprogram types that are component
-- subtypes or formal parameters.
if Ada_Version >= Ada_2005 and then Is_Access_Type (T1) then
if Is_Local_Anonymous_Access (T1)
or else Ekind (T2) = E_Anonymous_Access_Subprogram_Type
-- Handle assignment to an Ada 2012 stand-alone object
-- of an anonymous access type.
or else (Ekind (T1) = E_Anonymous_Access_Type
and then Nkind (Associated_Node_For_Itype (T1)) =
N_Object_Declaration)
then
Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
Analyze_And_Resolve (Rhs, T1);
end if;
end if;
-- Ada 2005 (AI-231): Assignment to not null variable
if Ada_Version >= Ada_2005
and then Can_Never_Be_Null (T1)
and then not Assignment_OK (Lhs)
then
-- Case where we know the right hand side is null
if Known_Null (Rhs) then
Apply_Compile_Time_Constraint_Error
(N => Rhs,
Msg =>
"(Ada 2005) null not allowed in null-excluding objects??",
Reason => CE_Null_Not_Allowed);
-- We still mark this as a possible modification, that's necessary
-- to reset Is_True_Constant, and desirable for xref purposes.
Note_Possible_Modification (Lhs, Sure => True);
goto Leave;
-- If we know the right hand side is non-null, then we convert to the
-- target type, since we don't need a run time check in that case.
elsif not Can_Never_Be_Null (T2) then
Rewrite (Rhs, Convert_To (T1, Relocate_Node (Rhs)));
Analyze_And_Resolve (Rhs, T1);
end if;
end if;
if Is_Scalar_Type (T1) then
Apply_Scalar_Range_Check (Rhs, Etype (Lhs));
-- For array types, verify that lengths match. If the right hand side
-- is a function call that has been inlined, the assignment has been
-- rewritten as a block, and the constraint check will be applied to the
-- assignment within the block.
elsif Is_Array_Type (T1)
and then (Nkind (Rhs) /= N_Type_Conversion
or else Is_Constrained (Etype (Rhs)))
and then (Nkind (Rhs) /= N_Function_Call
or else Nkind (N) /= N_Block_Statement)
then
-- Assignment verifies that the length of the Lsh and Rhs are equal,
-- but of course the indexes do not have to match. If the right-hand
-- side is a type conversion to an unconstrained type, a length check
-- is performed on the expression itself during expansion. In rare
-- cases, the redundant length check is computed on an index type
-- with a different representation, triggering incorrect code in the
-- back end.
Apply_Length_Check (Rhs, Etype (Lhs));
else
-- Discriminant checks are applied in the course of expansion
null;
end if;
-- Note: modifications of the Lhs may only be recorded after
-- checks have been applied.
Note_Possible_Modification (Lhs, Sure => True);
-- ??? a real accessibility check is needed when ???
-- Post warning for redundant assignment or variable to itself
if Warn_On_Redundant_Constructs
-- We only warn for source constructs
and then Comes_From_Source (N)
-- Where the object is the same on both sides
and then Same_Object (Lhs, Original_Node (Rhs))
-- But exclude the case where the right side was an operation that
-- got rewritten (e.g. JUNK + K, where K was known to be zero). We
-- don't want to warn in such a case, since it is reasonable to write
-- such expressions especially when K is defined symbolically in some
-- other package.
and then Nkind (Original_Node (Rhs)) not in N_Op
then
if Nkind (Lhs) in N_Has_Entity then
Error_Msg_NE -- CODEFIX
("?r?useless assignment of & to itself!", N, Entity (Lhs));
else
Error_Msg_N -- CODEFIX
("?r?useless assignment of object to itself!", N);
end if;
end if;
-- Check for non-allowed composite assignment
if not Support_Composite_Assign_On_Target
and then (Is_Array_Type (T1) or else Is_Record_Type (T1))
and then (not Has_Size_Clause (T1) or else Esize (T1) > 64)
then
Error_Msg_CRT ("composite assignment", N);
end if;
-- Check elaboration warning for left side if not in elab code
if not In_Subprogram_Or_Concurrent_Unit then
Check_Elab_Assign (Lhs);
end if;
-- Set Referenced_As_LHS if appropriate. We only set this flag if the
-- assignment is a source assignment in the extended main source unit.
-- We are not interested in any reference information outside this
-- context, or in compiler generated assignment statements.
if Comes_From_Source (N)
and then In_Extended_Main_Source_Unit (Lhs)
then
Set_Referenced_Modified (Lhs, Out_Param => False);
end if;
-- RM 7.3.2 (12/3): An assignment to a view conversion (from a type
-- to one of its ancestors) requires an invariant check. Apply check
-- only if expression comes from source, otherwise it will be applied
-- when value is assigned to source entity.
if Nkind (Lhs) = N_Type_Conversion
and then Has_Invariants (Etype (Expression (Lhs)))
and then Comes_From_Source (Expression (Lhs))
then
Insert_After (N, Make_Invariant_Call (Expression (Lhs)));
end if;
-- Final step. If left side is an entity, then we may be able to reset
-- the current tracked values to new safe values. We only have something
-- to do if the left side is an entity name, and expansion has not
-- modified the node into something other than an assignment, and of
-- course we only capture values if it is safe to do so.
if Is_Entity_Name (Lhs)
and then Nkind (N) = N_Assignment_Statement
then
declare
Ent : constant Entity_Id := Entity (Lhs);
begin
if Safe_To_Capture_Value (N, Ent) then
-- If simple variable on left side, warn if this assignment
-- blots out another one (rendering it useless). We only do
-- this for source assignments, otherwise we can generate bogus
-- warnings when an assignment is rewritten as another
-- assignment, and gets tied up with itself.
-- There may have been a previous reference to a component of
-- the variable, which in general removes the Last_Assignment
-- field of the variable to indicate a relevant use of the
-- previous assignment. However, if the assignment is to a
-- subcomponent the reference may not have registered, because
-- it is not possible to determine whether the context is an
-- assignment. In those cases we generate a Deferred_Reference,
-- to be used at the end of compilation to generate the right
-- kind of reference, and we suppress a potential warning for
-- a useless assignment, which might be premature. This may
-- lose a warning in rare cases, but seems preferable to a
-- misleading warning.
if Warn_On_Modified_Unread
and then Is_Assignable (Ent)
and then Comes_From_Source (N)
and then In_Extended_Main_Source_Unit (Ent)
and then not Has_Deferred_Reference (Ent)
then
Warn_On_Useless_Assignment (Ent, N);
end if;
-- If we are assigning an access type and the left side is an
-- entity, then make sure that the Is_Known_[Non_]Null flags
-- properly reflect the state of the entity after assignment.
if Is_Access_Type (T1) then
if Known_Non_Null (Rhs) then
Set_Is_Known_Non_Null (Ent, True);
elsif Known_Null (Rhs)
and then not Can_Never_Be_Null (Ent)
then
Set_Is_Known_Null (Ent, True);
else
Set_Is_Known_Null (Ent, False);
if not Can_Never_Be_Null (Ent) then
Set_Is_Known_Non_Null (Ent, False);
end if;
end if;
-- For discrete types, we may be able to set the current value
-- if the value is known at compile time.
elsif Is_Discrete_Type (T1)
and then Compile_Time_Known_Value (Rhs)
then
Set_Current_Value (Ent, Rhs);
else
Set_Current_Value (Ent, Empty);
end if;
-- If not safe to capture values, kill them
else
Kill_Lhs;
end if;
end;
end if;
-- If assigning to an object in whole or in part, note location of
-- assignment in case no one references value. We only do this for
-- source assignments, otherwise we can generate bogus warnings when an
-- assignment is rewritten as another assignment, and gets tied up with
-- itself.
declare
Ent : constant Entity_Id := Get_Enclosing_Object (Lhs);
begin
if Present (Ent)
and then Safe_To_Capture_Value (N, Ent)
and then Nkind (N) = N_Assignment_Statement
and then Warn_On_Modified_Unread
and then Is_Assignable (Ent)
and then Comes_From_Source (N)
and then In_Extended_Main_Source_Unit (Ent)
then
Set_Last_Assignment (Ent, Lhs);
end if;
end;
Analyze_Dimension (N);
<<Leave>>
Current_LHS := Empty;
Restore_Ghost_Mode (Mode);
end Analyze_Assignment;
-----------------------------
-- Analyze_Block_Statement --
-----------------------------
procedure Analyze_Block_Statement (N : Node_Id) is
procedure Install_Return_Entities (Scop : Entity_Id);
-- Install all entities of return statement scope Scop in the visibility
-- chain except for the return object since its entity is reused in a
-- renaming.
-----------------------------
-- Install_Return_Entities --
-----------------------------
procedure Install_Return_Entities (Scop : Entity_Id) is
Id : Entity_Id;
begin
Id := First_Entity (Scop);
while Present (Id) loop
-- Do not install the return object
if not Ekind_In (Id, E_Constant, E_Variable)
or else not Is_Return_Object (Id)
then
Install_Entity (Id);
end if;
Next_Entity (Id);
end loop;
end Install_Return_Entities;
-- Local constants and variables
Decls : constant List_Id := Declarations (N);
Id : constant Node_Id := Identifier (N);
HSS : constant Node_Id := Handled_Statement_Sequence (N);
Is_BIP_Return_Statement : Boolean;
-- Start of processing for Analyze_Block_Statement
begin
-- In SPARK mode, we reject block statements. Note that the case of
-- block statements generated by the expander is fine.
if Nkind (Original_Node (N)) = N_Block_Statement then
Check_SPARK_05_Restriction ("block statement is not allowed", N);
end if;
-- If no handled statement sequence is present, things are really messed
-- up, and we just return immediately (defence against previous errors).
if No (HSS) then
Check_Error_Detected;
return;
end if;
-- Detect whether the block is actually a rewritten return statement of
-- a build-in-place function.
Is_BIP_Return_Statement :=
Present (Id)
and then Present (Entity (Id))
and then Ekind (Entity (Id)) = E_Return_Statement
and then Is_Build_In_Place_Function
(Return_Applies_To (Entity (Id)));
-- Normal processing with HSS present
declare
EH : constant List_Id := Exception_Handlers (HSS);
Ent : Entity_Id := Empty;
S : Entity_Id;
Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
-- Recursively save value of this global, will be restored on exit
begin
-- Initialize unblocked exit count for statements of begin block
-- plus one for each exception handler that is present.
Unblocked_Exit_Count := 1;
if Present (EH) then
Unblocked_Exit_Count := Unblocked_Exit_Count + List_Length (EH);
end if;
-- If a label is present analyze it and mark it as referenced
if Present (Id) then
Analyze (Id);
Ent := Entity (Id);
-- An error defense. If we have an identifier, but no entity, then
-- something is wrong. If previous errors, then just remove the
-- identifier and continue, otherwise raise an exception.
if No (Ent) then
Check_Error_Detected;
Set_Identifier (N, Empty);
else
Set_Ekind (Ent, E_Block);
Generate_Reference (Ent, N, ' ');
Generate_Definition (Ent);
if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
Set_Label_Construct (Parent (Ent), N);
end if;
end if;
end if;
-- If no entity set, create a label entity
if No (Ent) then
Ent := New_Internal_Entity (E_Block, Current_Scope, Sloc (N), 'B');
Set_Identifier (N, New_Occurrence_Of (Ent, Sloc (N)));
Set_Parent (Ent, N);
end if;
Set_Etype (Ent, Standard_Void_Type);
Set_Block_Node (Ent, Identifier (N));
Push_Scope (Ent);
-- The block served as an extended return statement. Ensure that any
-- entities created during the analysis and expansion of the return
-- object declaration are once again visible.
if Is_BIP_Return_Statement then
Install_Return_Entities (Ent);
end if;
if Present (Decls) then
Analyze_Declarations (Decls);
Check_Completion;
Inspect_Deferred_Constant_Completion (Decls);
end if;
Analyze (HSS);
Process_End_Label (HSS, 'e', Ent);
-- If exception handlers are present, then we indicate that enclosing
-- scopes contain a block with handlers. We only need to mark non-
-- generic scopes.
if Present (EH) then
S := Scope (Ent);
loop
Set_Has_Nested_Block_With_Handler (S);
exit when Is_Overloadable (S)
or else Ekind (S) = E_Package
or else Is_Generic_Unit (S);
S := Scope (S);
end loop;
end if;
Check_References (Ent);
End_Scope;
if Unblocked_Exit_Count = 0 then
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
Check_Unreachable_Code (N);
else
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
end if;
end;
end Analyze_Block_Statement;
--------------------------------
-- Analyze_Compound_Statement --
--------------------------------
procedure Analyze_Compound_Statement (N : Node_Id) is
begin
Analyze_List (Actions (N));
end Analyze_Compound_Statement;
----------------------------
-- Analyze_Case_Statement --
----------------------------
procedure Analyze_Case_Statement (N : Node_Id) is
Exp : Node_Id;
Exp_Type : Entity_Id;
Exp_Btype : Entity_Id;
Last_Choice : Nat;
Others_Present : Boolean;
-- Indicates if Others was present
pragma Warnings (Off, Last_Choice);
-- Don't care about assigned value
Statements_Analyzed : Boolean := False;
-- Set True if at least some statement sequences get analyzed. If False
-- on exit, means we had a serious error that prevented full analysis of
-- the case statement, and as a result it is not a good idea to output
-- warning messages about unreachable code.
Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
-- Recursively save value of this global, will be restored on exit
procedure Non_Static_Choice_Error (Choice : Node_Id);
-- Error routine invoked by the generic instantiation below when the
-- case statement has a non static choice.
procedure Process_Statements (Alternative : Node_Id);
-- Analyzes the statements associated with a case alternative. Needed
-- by instantiation below.
package Analyze_Case_Choices is new
Generic_Analyze_Choices
(Process_Associated_Node => Process_Statements);
use Analyze_Case_Choices;
-- Instantiation of the generic choice analysis package
package Check_Case_Choices is new
Generic_Check_Choices
(Process_Empty_Choice => No_OP,
Process_Non_Static_Choice => Non_Static_Choice_Error,
Process_Associated_Node => No_OP);
use Check_Case_Choices;
-- Instantiation of the generic choice processing package
-----------------------------
-- Non_Static_Choice_Error --
-----------------------------
procedure Non_Static_Choice_Error (Choice : Node_Id) is
begin
Flag_Non_Static_Expr
("choice given in case statement is not static!", Choice);
end Non_Static_Choice_Error;
------------------------
-- Process_Statements --
------------------------
procedure Process_Statements (Alternative : Node_Id) is
Choices : constant List_Id := Discrete_Choices (Alternative);
Ent : Entity_Id;
begin
Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
Statements_Analyzed := True;
-- An interesting optimization. If the case statement expression
-- is a simple entity, then we can set the current value within an
-- alternative if the alternative has one possible value.
-- case N is
-- when 1 => alpha
-- when 2 | 3 => beta
-- when others => gamma
-- Here we know that N is initially 1 within alpha, but for beta and
-- gamma, we do not know anything more about the initial value.
if Is_Entity_Name (Exp) then
Ent := Entity (Exp);
if Ekind_In (Ent, E_Variable,
E_In_Out_Parameter,
E_Out_Parameter)
then
if List_Length (Choices) = 1
and then Nkind (First (Choices)) in N_Subexpr
and then Compile_Time_Known_Value (First (Choices))
then
Set_Current_Value (Entity (Exp), First (Choices));
end if;
Analyze_Statements (Statements (Alternative));
-- After analyzing the case, set the current value to empty
-- since we won't know what it is for the next alternative
-- (unless reset by this same circuit), or after the case.
Set_Current_Value (Entity (Exp), Empty);
return;
end if;
end if;
-- Case where expression is not an entity name of a variable
Analyze_Statements (Statements (Alternative));
end Process_Statements;
-- Start of processing for Analyze_Case_Statement
begin
Unblocked_Exit_Count := 0;
Exp := Expression (N);
Analyze (Exp);
-- The expression must be of any discrete type. In rare cases, the
-- expander constructs a case statement whose expression has a private
-- type whose full view is discrete. This can happen when generating
-- a stream operation for a variant type after the type is frozen,
-- when the partial of view of the type of the discriminant is private.
-- In that case, use the full view to analyze case alternatives.
if not Is_Overloaded (Exp)
and then not Comes_From_Source (N)
and then Is_Private_Type (Etype (Exp))
and then Present (Full_View (Etype (Exp)))
and then Is_Discrete_Type (Full_View (Etype (Exp)))
then
Resolve (Exp, Etype (Exp));
Exp_Type := Full_View (Etype (Exp));
else
Analyze_And_Resolve (Exp, Any_Discrete);
Exp_Type := Etype (Exp);
end if;
Check_Unset_Reference (Exp);
Exp_Btype := Base_Type (Exp_Type);
-- The expression must be of a discrete type which must be determinable
-- independently of the context in which the expression occurs, but
-- using the fact that the expression must be of a discrete type.
-- Moreover, the type this expression must not be a character literal
-- (which is always ambiguous) or, for Ada-83, a generic formal type.
-- If error already reported by Resolve, nothing more to do
if Exp_Btype = Any_Discrete or else Exp_Btype = Any_Type then
return;
elsif Exp_Btype = Any_Character then
Error_Msg_N
("character literal as case expression is ambiguous", Exp);
return;
elsif Ada_Version = Ada_83
and then (Is_Generic_Type (Exp_Btype)
or else Is_Generic_Type (Root_Type (Exp_Btype)))
then
Error_Msg_N
("(Ada 83) case expression cannot be of a generic type", Exp);
return;
end if;
-- If the case expression is a formal object of mode in out, then treat
-- it as having a nonstatic subtype by forcing use of the base type
-- (which has to get passed to Check_Case_Choices below). Also use base
-- type when the case expression is parenthesized.
if Paren_Count (Exp) > 0
or else (Is_Entity_Name (Exp)
and then Ekind (Entity (Exp)) = E_Generic_In_Out_Parameter)
then
Exp_Type := Exp_Btype;
end if;
-- Call instantiated procedures to analyzwe and check discrete choices
Analyze_Choices (Alternatives (N), Exp_Type);
Check_Choices (N, Alternatives (N), Exp_Type, Others_Present);
-- Case statement with single OTHERS alternative not allowed in SPARK
if Others_Present and then List_Length (Alternatives (N)) = 1 then
Check_SPARK_05_Restriction
("OTHERS as unique case alternative is not allowed", N);
end if;
if Exp_Type = Universal_Integer and then not Others_Present then
Error_Msg_N ("case on universal integer requires OTHERS choice", Exp);
end if;
-- If all our exits were blocked by unconditional transfers of control,
-- then the entire CASE statement acts as an unconditional transfer of
-- control, so treat it like one, and check unreachable code. Skip this
-- test if we had serious errors preventing any statement analysis.
if Unblocked_Exit_Count = 0 and then Statements_Analyzed then
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
Check_Unreachable_Code (N);
else
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
end if;
-- If the expander is active it will detect the case of a statically
-- determined single alternative and remove warnings for the case, but
-- if we are not doing expansion, that circuit won't be active. Here we
-- duplicate the effect of removing warnings in the same way, so that
-- we will get the same set of warnings in -gnatc mode.
if not Expander_Active
and then Compile_Time_Known_Value (Expression (N))
and then Serious_Errors_Detected = 0
then
declare
Chosen : constant Node_Id := Find_Static_Alternative (N);
Alt : Node_Id;
begin
Alt := First (Alternatives (N));
while Present (Alt) loop
if Alt /= Chosen then
Remove_Warning_Messages (Statements (Alt));
end if;
Next (Alt);
end loop;
end;
end if;
end Analyze_Case_Statement;
----------------------------
-- Analyze_Exit_Statement --
----------------------------
-- If the exit includes a name, it must be the name of a currently open
-- loop. Otherwise there must be an innermost open loop on the stack, to
-- which the statement implicitly refers.
-- Additionally, in SPARK mode:
-- The exit can only name the closest enclosing loop;
-- An exit with a when clause must be directly contained in a loop;
-- An exit without a when clause must be directly contained in an
-- if-statement with no elsif or else, which is itself directly contained
-- in a loop. The exit must be the last statement in the if-statement.
procedure Analyze_Exit_Statement (N : Node_Id) is
Target : constant Node_Id := Name (N);
Cond : constant Node_Id := Condition (N);
Scope_Id : Entity_Id;
U_Name : Entity_Id;
Kind : Entity_Kind;
begin
if No (Cond) then
Check_Unreachable_Code (N);
end if;
if Present (Target) then
Analyze (Target);
U_Name := Entity (Target);
if not In_Open_Scopes (U_Name) or else Ekind (U_Name) /= E_Loop then
Error_Msg_N ("invalid loop name in exit statement", N);
return;
else
if Has_Loop_In_Inner_Open_Scopes (U_Name) then
Check_SPARK_05_Restriction
("exit label must name the closest enclosing loop", N);
end if;
Set_Has_Exit (U_Name);
end if;
else
U_Name := Empty;
end if;
for J in reverse 0 .. Scope_Stack.Last loop
Scope_Id := Scope_Stack.Table (J).Entity;
Kind := Ekind (Scope_Id);
if Kind = E_Loop and then (No (Target) or else Scope_Id = U_Name) then
Set_Has_Exit (Scope_Id);
exit;
elsif Kind = E_Block
or else Kind = E_Loop
or else Kind = E_Return_Statement
then
null;
else
Error_Msg_N
("cannot exit from program unit or accept statement", N);
return;
end if;
end loop;
-- Verify that if present the condition is a Boolean expression
if Present (Cond) then
Analyze_And_Resolve (Cond, Any_Boolean);
Check_Unset_Reference (Cond);
end if;
-- In SPARK mode, verify that the exit statement respects the SPARK
-- restrictions.
if Present (Cond) then
if Nkind (Parent (N)) /= N_Loop_Statement then
Check_SPARK_05_Restriction
("exit with when clause must be directly in loop", N);
end if;
else
if Nkind (Parent (N)) /= N_If_Statement then
if Nkind (Parent (N)) = N_Elsif_Part then
Check_SPARK_05_Restriction
("exit must be in IF without ELSIF", N);
else
Check_SPARK_05_Restriction ("exit must be directly in IF", N);
end if;
elsif Nkind (Parent (Parent (N))) /= N_Loop_Statement then
Check_SPARK_05_Restriction
("exit must be in IF directly in loop", N);
-- First test the presence of ELSE, so that an exit in an ELSE leads
-- to an error mentioning the ELSE.
elsif Present (Else_Statements (Parent (N))) then
Check_SPARK_05_Restriction ("exit must be in IF without ELSE", N);
-- An exit in an ELSIF does not reach here, as it would have been
-- detected in the case (Nkind (Parent (N)) /= N_If_Statement).
elsif Present (Elsif_Parts (Parent (N))) then
Check_SPARK_05_Restriction ("exit must be in IF without ELSIF", N);
end if;
end if;
-- Chain exit statement to associated loop entity
Set_Next_Exit_Statement (N, First_Exit_Statement (Scope_Id));
Set_First_Exit_Statement (Scope_Id, N);
-- Since the exit may take us out of a loop, any previous assignment
-- statement is not useless, so clear last assignment indications. It
-- is OK to keep other current values, since if the exit statement
-- does not exit, then the current values are still valid.
Kill_Current_Values (Last_Assignment_Only => True);
end Analyze_Exit_Statement;
----------------------------
-- Analyze_Goto_Statement --
----------------------------
procedure Analyze_Goto_Statement (N : Node_Id) is
Label : constant Node_Id := Name (N);
Scope_Id : Entity_Id;
Label_Scope : Entity_Id;
Label_Ent : Entity_Id;
begin
Check_SPARK_05_Restriction ("goto statement is not allowed", N);
-- Actual semantic checks
Check_Unreachable_Code (N);
Kill_Current_Values (Last_Assignment_Only => True);
Analyze (Label);
Label_Ent := Entity (Label);
-- Ignore previous error
if Label_Ent = Any_Id then
Check_Error_Detected;
return;
-- We just have a label as the target of a goto
elsif Ekind (Label_Ent) /= E_Label then
Error_Msg_N ("target of goto statement must be a label", Label);
return;
-- Check that the target of the goto is reachable according to Ada
-- scoping rules. Note: the special gotos we generate for optimizing
-- local handling of exceptions would violate these rules, but we mark
-- such gotos as analyzed when built, so this code is never entered.
elsif not Reachable (Label_Ent) then
Error_Msg_N ("target of goto statement is not reachable", Label);
return;
end if;
-- Here if goto passes initial validity checks
Label_Scope := Enclosing_Scope (Label_Ent);
for J in reverse 0 .. Scope_Stack.Last loop
Scope_Id := Scope_Stack.Table (J).Entity;
if Label_Scope = Scope_Id
or else not Ekind_In (Scope_Id, E_Block, E_Loop, E_Return_Statement)
then
if Scope_Id /= Label_Scope then
Error_Msg_N
("cannot exit from program unit or accept statement", N);
end if;
return;
end if;
end loop;
raise Program_Error;
end Analyze_Goto_Statement;
--------------------------
-- Analyze_If_Statement --
--------------------------
-- A special complication arises in the analysis of if statements
-- The expander has circuitry to completely delete code that it can tell
-- will not be executed (as a result of compile time known conditions). In
-- the analyzer, we ensure that code that will be deleted in this manner
-- is analyzed but not expanded. This is obviously more efficient, but
-- more significantly, difficulties arise if code is expanded and then
-- eliminated (e.g. exception table entries disappear). Similarly, itypes
-- generated in deleted code must be frozen from start, because the nodes
-- on which they depend will not be available at the freeze point.
procedure Analyze_If_Statement (N : Node_Id) is
E : Node_Id;
Save_Unblocked_Exit_Count : constant Nat := Unblocked_Exit_Count;
-- Recursively save value of this global, will be restored on exit
Save_In_Deleted_Code : Boolean;
Del : Boolean := False;
-- This flag gets set True if a True condition has been found, which
-- means that remaining ELSE/ELSIF parts are deleted.
procedure Analyze_Cond_Then (Cnode : Node_Id);
-- This is applied to either the N_If_Statement node itself or to an
-- N_Elsif_Part node. It deals with analyzing the condition and the THEN
-- statements associated with it.
-----------------------
-- Analyze_Cond_Then --
-----------------------
procedure Analyze_Cond_Then (Cnode : Node_Id) is
Cond : constant Node_Id := Condition (Cnode);
Tstm : constant List_Id := Then_Statements (Cnode);
begin
Unblocked_Exit_Count := Unblocked_Exit_Count + 1;
Analyze_And_Resolve (Cond, Any_Boolean);
Check_Unset_Reference (Cond);
Set_Current_Value_Condition (Cnode);
-- If already deleting, then just analyze then statements
if Del then
Analyze_Statements (Tstm);
-- Compile time known value, not deleting yet
elsif Compile_Time_Known_Value (Cond) then
Save_In_Deleted_Code := In_Deleted_Code;
-- If condition is True, then analyze the THEN statements and set
-- no expansion for ELSE and ELSIF parts.
if Is_True (Expr_Value (Cond)) then
Analyze_Statements (Tstm);
Del := True;
Expander_Mode_Save_And_Set (False);
In_Deleted_Code := True;
-- If condition is False, analyze THEN with expansion off
else -- Is_False (Expr_Value (Cond))
Expander_Mode_Save_And_Set (False);
In_Deleted_Code := True;
Analyze_Statements (Tstm);
Expander_Mode_Restore;
In_Deleted_Code := Save_In_Deleted_Code;
end if;
-- Not known at compile time, not deleting, normal analysis
else
Analyze_Statements (Tstm);
end if;
end Analyze_Cond_Then;
-- Start of processing for Analyze_If_Statement
begin
-- Initialize exit count for else statements. If there is no else part,
-- this count will stay non-zero reflecting the fact that the uncovered
-- else case is an unblocked exit.
Unblocked_Exit_Count := 1;
Analyze_Cond_Then (N);
-- Now to analyze the elsif parts if any are present
if Present (Elsif_Parts (N)) then
E := First (Elsif_Parts (N));
while Present (E) loop
Analyze_Cond_Then (E);
Next (E);
end loop;
end if;
if Present (Else_Statements (N)) then
Analyze_Statements (Else_Statements (N));
end if;
-- If all our exits were blocked by unconditional transfers of control,
-- then the entire IF statement acts as an unconditional transfer of
-- control, so treat it like one, and check unreachable code.
if Unblocked_Exit_Count = 0 then
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
Check_Unreachable_Code (N);
else
Unblocked_Exit_Count := Save_Unblocked_Exit_Count;
end if;
if Del then
Expander_Mode_Restore;
In_Deleted_Code := Save_In_Deleted_Code;
end if;
if not Expander_Active
and then Compile_Time_Known_Value (Condition (N))
and then Serious_Errors_Detected = 0
then
if Is_True (Expr_Value (Condition (N))) then
Remove_Warning_Messages (Else_Statements (N));
if Present (Elsif_Parts (N)) then
E := First (Elsif_Parts (N));
while Present (E) loop
Remove_Warning_Messages (Then_Statements (E));
Next (E);
end loop;
end if;
else
Remove_Warning_Messages (Then_Statements (N));
end if;
end if;
-- Warn on redundant if statement that has no effect
-- Note, we could also check empty ELSIF parts ???
if Warn_On_Redundant_Constructs
-- If statement must be from source
and then Comes_From_Source (N)
-- Condition must not have obvious side effect
and then Has_No_Obvious_Side_Effects (Condition (N))
-- No elsif parts of else part
and then No (Elsif_Parts (N))
and then No (Else_Statements (N))
-- Then must be a single null statement
and then List_Length (Then_Statements (N)) = 1
then
-- Go to original node, since we may have rewritten something as
-- a null statement (e.g. a case we could figure the outcome of).
declare
T : constant Node_Id := First (Then_Statements (N));
S : constant Node_Id := Original_Node (T);
begin
if Comes_From_Source (S) and then Nkind (S) = N_Null_Statement then
Error_Msg_N ("if statement has no effect?r?", N);
end if;
end;
end if;
end Analyze_If_Statement;
----------------------------------------
-- Analyze_Implicit_Label_Declaration --
----------------------------------------
-- An implicit label declaration is generated in the innermost enclosing
-- declarative part. This is done for labels, and block and loop names.
-- Note: any changes in this routine may need to be reflected in
-- Analyze_Label_Entity.
procedure Analyze_Implicit_Label_Declaration (N : Node_Id) is
Id : constant Node_Id := Defining_Identifier (N);
begin
Enter_Name (Id);
Set_Ekind (Id, E_Label);
Set_Etype (Id, Standard_Void_Type);
Set_Enclosing_Scope (Id, Current_Scope);
end Analyze_Implicit_Label_Declaration;
------------------------------
-- Analyze_Iteration_Scheme --
------------------------------
procedure Analyze_Iteration_Scheme (N : Node_Id) is
Cond : Node_Id;
Iter_Spec : Node_Id;
Loop_Spec : Node_Id;
begin
-- For an infinite loop, there is no iteration scheme
if No (N) then
return;
end if;
Cond := Condition (N);
Iter_Spec := Iterator_Specification (N);
Loop_Spec := Loop_Parameter_Specification (N);
if Present (Cond) then
Analyze_And_Resolve (Cond, Any_Boolean);
Check_Unset_Reference (Cond);
Set_Current_Value_Condition (N);
elsif Present (Iter_Spec) then
Analyze_Iterator_Specification (Iter_Spec);
else
Analyze_Loop_Parameter_Specification (Loop_Spec);
end if;
end Analyze_Iteration_Scheme;
------------------------------------
-- Analyze_Iterator_Specification --
------------------------------------
procedure Analyze_Iterator_Specification (N : Node_Id) is
procedure Check_Reverse_Iteration (Typ : Entity_Id);
-- For an iteration over a container, if the loop carries the Reverse
-- indicator, verify that the container type has an Iterate aspect that
-- implements the reversible iterator interface.
function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id;
-- For containers with Iterator and related aspects, the cursor is
-- obtained by locating an entity with the proper name in the scope
-- of the type.
-----------------------------
-- Check_Reverse_Iteration --
-----------------------------
procedure Check_Reverse_Iteration (Typ : Entity_Id) is
begin
if Reverse_Present (N)
and then not Is_Array_Type (Typ)
and then not Is_Reversible_Iterator (Typ)
then
Error_Msg_NE
("container type does not support reverse iteration", N, Typ);
end if;
end Check_Reverse_Iteration;
---------------------
-- Get_Cursor_Type --
---------------------
function Get_Cursor_Type (Typ : Entity_Id) return Entity_Id is
Ent : Entity_Id;
begin
-- If iterator type is derived, the cursor is declared in the scope
-- of the parent type.
if Is_Derived_Type (Typ) then
Ent := First_Entity (Scope (Etype (Typ)));
else
Ent := First_Entity (Scope (Typ));
end if;
while Present (Ent) loop
exit when Chars (Ent) = Name_Cursor;
Next_Entity (Ent);
end loop;
if No (Ent) then
return Any_Type;
end if;
-- The cursor is the target of generated assignments in the
-- loop, and cannot have a limited type.
if Is_Limited_Type (Etype (Ent)) then
Error_Msg_N ("cursor type cannot be limited", N);
end if;
return Etype (Ent);
end Get_Cursor_Type;
-- Local variables
Def_Id : constant Node_Id := Defining_Identifier (N);
Iter_Name : constant Node_Id := Name (N);
Loc : constant Source_Ptr := Sloc (N);
Subt : constant Node_Id := Subtype_Indication (N);
Bas : Entity_Id;
Typ : Entity_Id;
-- Start of processing for Analyze_Iterator_Specification
begin
Enter_Name (Def_Id);
-- AI12-0151 specifies that when the subtype indication is present, it
-- must statically match the type of the array or container element.
-- To simplify this check, we introduce a subtype declaration with the
-- given subtype indication when it carries a constraint, and rewrite
-- the original as a reference to the created subtype entity.
if Present (Subt) then
if Nkind (Subt) = N_Subtype_Indication then
declare
S : constant Entity_Id := Make_Temporary (Sloc (Subt), 'S');
Decl : constant Node_Id :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => S,
Subtype_Indication => New_Copy_Tree (Subt));
begin
Insert_Before (Parent (Parent (N)), Decl);
Analyze (Decl);
Rewrite (Subt, New_Occurrence_Of (S, Sloc (Subt)));
end;
else
Analyze (Subt);
end if;
-- Save entity of subtype indication for subsequent check
Bas := Entity (Subt);
end if;
Preanalyze_Range (Iter_Name);
-- Set the kind of the loop variable, which is not visible within
-- the iterator name.
Set_Ekind (Def_Id, E_Variable);
-- Provide a link between the iterator variable and the container, for
-- subsequent use in cross-reference and modification information.
if Of_Present (N) then
Set_Related_Expression (Def_Id, Iter_Name);
-- For a container, the iterator is specified through the aspect
if not Is_Array_Type (Etype (Iter_Name)) then
declare
Iterator : constant Entity_Id :=
Find_Value_Of_Aspect
(Etype (Iter_Name), Aspect_Default_Iterator);
I : Interp_Index;
It : Interp;
begin
if No (Iterator) then
null; -- error reported below.
elsif not Is_Overloaded (Iterator) then
Check_Reverse_Iteration (Etype (Iterator));
-- If Iterator is overloaded, use reversible iterator if
-- one is available.
elsif Is_Overloaded (Iterator) then
Get_First_Interp (Iterator, I, It);
while Present (It.Nam) loop
if Ekind (It.Nam) = E_Function
and then Is_Reversible_Iterator (Etype (It.Nam))
then
Set_Etype (Iterator, It.Typ);
Set_Entity (Iterator, It.Nam);
exit;
end if;
Get_Next_Interp (I, It);
end loop;
Check_Reverse_Iteration (Etype (Iterator));
end if;
end;
end if;
end if;
-- If the domain of iteration is an expression, create a declaration for
-- it, so that finalization actions are introduced outside of the loop.
-- The declaration must be a renaming because the body of the loop may
-- assign to elements.
if not Is_Entity_Name (Iter_Name)
-- When the context is a quantified expression, the renaming
-- declaration is delayed until the expansion phase if we are
-- doing expansion.
and then (Nkind (Parent (N)) /= N_Quantified_Expression
or else Operating_Mode = Check_Semantics)
-- Do not perform this expansion for ASIS and when expansion is
-- disabled, where the temporary may hide the transformation of a
-- selected component into a prefixed function call, and references
-- need to see the original expression.
and then Expander_Active
then
declare
Id : constant Entity_Id := Make_Temporary (Loc, 'R', Iter_Name);
Decl : Node_Id;
Act_S : Node_Id;
begin
-- If the domain of iteration is an array component that depends
-- on a discriminant, create actual subtype for it. Pre-analysis
-- does not generate the actual subtype of a selected component.
if Nkind (Iter_Name) = N_Selected_Component
and then Is_Array_Type (Etype (Iter_Name))
then
Act_S :=
Build_Actual_Subtype_Of_Component
(Etype (Selector_Name (Iter_Name)), Iter_Name);
Insert_Action (N, Act_S);
if Present (Act_S) then
Typ := Defining_Identifier (Act_S);
else
Typ := Etype (Iter_Name);
end if;
else
Typ := Etype (Iter_Name);
-- Verify that the expression produces an iterator
if not Of_Present (N) and then not Is_Iterator (Typ)
and then not Is_Array_Type (Typ)
and then No (Find_Aspect (Typ, Aspect_Iterable))
then
Error_Msg_N
("expect object that implements iterator interface",
Iter_Name);
end if;
end if;
-- Protect against malformed iterator
if Typ = Any_Type then
Error_Msg_N ("invalid expression in loop iterator", Iter_Name);
return;
end if;
if not Of_Present (N) then
Check_Reverse_Iteration (Typ);
end if;
-- The name in the renaming declaration may be a function call.
-- Indicate that it does not come from source, to suppress
-- spurious warnings on renamings of parameterless functions,
-- a common enough idiom in user-defined iterators.
Decl :=
Make_Object_Renaming_Declaration (Loc,
Defining_Identifier => Id,
Subtype_Mark => New_Occurrence_Of (Typ, Loc),
Name =>
New_Copy_Tree (Iter_Name, New_Sloc => Loc));
Insert_Actions (Parent (Parent (N)), New_List (Decl));
Rewrite (Name (N), New_Occurrence_Of (Id, Loc));
Set_Etype (Id, Typ);
Set_Etype (Name (N), Typ);
end;
-- Container is an entity or an array with uncontrolled components, or
-- else it is a container iterator given by a function call, typically
-- called Iterate in the case of predefined containers, even though
-- Iterate is not a reserved name. What matters is that the return type
-- of the function is an iterator type.
elsif Is_Entity_Name (Iter_Name) then
Analyze (Iter_Name);
if Nkind (Iter_Name) = N_Function_Call then
declare
C : constant Node_Id := Name (Iter_Name);
I : Interp_Index;
It : Interp;
begin
if not Is_Overloaded (Iter_Name) then
Resolve (Iter_Name, Etype (C));
else
Get_First_Interp (C, I, It);
while It.Typ /= Empty loop
if Reverse_Present (N) then
if Is_Reversible_Iterator (It.Typ) then
Resolve (Iter_Name, It.Typ);
exit;
end if;
elsif Is_Iterator (It.Typ) then
Resolve (Iter_Name, It.Typ);
exit;
end if;
Get_Next_Interp (I, It);
end loop;
end if;
end;
-- Domain of iteration is not overloaded
else
Resolve (Iter_Name, Etype (Iter_Name));
end if;
if not Of_Present (N) then
Check_Reverse_Iteration (Etype (Iter_Name));
end if;
end if;
-- Get base type of container, for proper retrieval of Cursor type
-- and primitive operations.
Typ := Base_Type (Etype (Iter_Name));
if Is_Array_Type (Typ) then
if Of_Present (N) then
Set_Etype (Def_Id, Component_Type (Typ));
-- The loop variable is aliased if the array components are
-- aliased.
Set_Is_Aliased (Def_Id, Has_Aliased_Components (Typ));
-- AI12-0047 stipulates that the domain (array or container)
-- cannot be a component that depends on a discriminant if the
-- enclosing object is mutable, to prevent a modification of the
-- dowmain of iteration in the course of an iteration.
-- If the object is an expression it has been captured in a
-- temporary, so examine original node.
if Nkind (Original_Node (Iter_Name)) = N_Selected_Component
and then Is_Dependent_Component_Of_Mutable_Object
(Original_Node (Iter_Name))
then
Error_Msg_N
("iterable name cannot be a discriminant-dependent "
& "component of a mutable object", N);
end if;
if Present (Subt)
and then
(Base_Type (Bas) /= Base_Type (Component_Type (Typ))
or else
not Subtypes_Statically_Match (Bas, Component_Type (Typ)))
then
Error_Msg_N
("subtype indication does not match component type", Subt);
end if;
-- Here we have a missing Range attribute
else
Error_Msg_N
("missing Range attribute in iteration over an array", N);
-- In Ada 2012 mode, this may be an attempt at an iterator
if Ada_Version >= Ada_2012 then
Error_Msg_NE
("\if& is meant to designate an element of the array, use OF",
N, Def_Id);
end if;
-- Prevent cascaded errors
Set_Ekind (Def_Id, E_Loop_Parameter);
Set_Etype (Def_Id, Etype (First_Index (Typ)));
end if;
-- Check for type error in iterator
elsif Typ = Any_Type then
return;
-- Iteration over a container
else
Set_Ekind (Def_Id, E_Loop_Parameter);
Error_Msg_Ada_2012_Feature ("container iterator", Sloc (N));
-- OF present
if Of_Present (N) then
if Has_Aspect (Typ, Aspect_Iterable) then
declare
Elt : constant Entity_Id :=
Get_Iterable_Type_Primitive (Typ, Name_Element);
begin
if No (Elt) then
Error_Msg_N
("missing Element primitive for iteration", N);
else
Set_Etype (Def_Id, Etype (Elt));
end if;
end;
-- For a predefined container, The type of the loop variable is
-- the Iterator_Element aspect of the container type.
else
declare
Element : constant Entity_Id :=
Find_Value_Of_Aspect
(Typ, Aspect_Iterator_Element);
Iterator : constant Entity_Id :=
Find_Value_Of_Aspect
(Typ, Aspect_Default_Iterator);
Orig_Iter_Name : constant Node_Id :=
Original_Node (Iter_Name);
Cursor_Type : Entity_Id;
begin
if No (Element) then
Error_Msg_NE ("cannot iterate over&", N, Typ);
return;
else
Set_Etype (Def_Id, Entity (Element));
Cursor_Type := Get_Cursor_Type (Typ);
pragma Assert (Present (Cursor_Type));
-- If subtype indication was given, verify that it covers
-- the element type of the container.
if Present (Subt)
and then (not Covers (Bas, Etype (Def_Id))
or else not Subtypes_Statically_Match
(Bas, Etype (Def_Id)))
then
Error_Msg_N
("subtype indication does not match element type",
Subt);
end if;
-- If the container has a variable indexing aspect, the
-- element is a variable and is modifiable in the loop.
if Has_Aspect (Typ, Aspect_Variable_Indexing) then
Set_Ekind (Def_Id, E_Variable);
end if;
-- If the container is a constant, iterating over it
-- requires a Constant_Indexing operation.
if not Is_Variable (Iter_Name)
and then not Has_Aspect (Typ, Aspect_Constant_Indexing)
then
Error_Msg_N
("iteration over constant container require "
& "constant_indexing aspect", N);
-- The Iterate function may have an in_out parameter,
-- and a constant container is thus illegal.
elsif Present (Iterator)
and then Ekind (Entity (Iterator)) = E_Function
and then Ekind (First_Formal (Entity (Iterator))) /=
E_In_Parameter
and then not Is_Variable (Iter_Name)
then
Error_Msg_N ("variable container expected", N);
end if;
-- Detect a case where the iterator denotes a component
-- of a mutable object which depends on a discriminant.
-- Note that the iterator may denote a function call in
-- qualified form, in which case this check should not
-- be performed.
if Nkind (Orig_Iter_Name) = N_Selected_Component
and then
Present (Entity (Selector_Name (Orig_Iter_Name)))
and then Ekind_In
(Entity (Selector_Name (Orig_Iter_Name)),
E_Component,
E_Discriminant)
and then Is_Dependent_Component_Of_Mutable_Object
(Orig_Iter_Name)
then
Error_Msg_N
("container cannot be a discriminant-dependent "
& "component of a mutable object", N);
end if;
end if;
end;
end if;
-- IN iterator, domain is a range, or a call to Iterate function
else
-- For an iteration of the form IN, the name must denote an
-- iterator, typically the result of a call to Iterate. Give a
-- useful error message when the name is a container by itself.
-- The type may be a formal container type, which has to have
-- an Iterable aspect detailing the required primitives.
if Is_Entity_Name (Original_Node (Name (N)))
and then not Is_Iterator (Typ)
then
if Has_Aspect (Typ, Aspect_Iterable) then
null;
elsif not Has_Aspect (Typ, Aspect_Iterator_Element) then
Error_Msg_NE
("cannot iterate over&", Name (N), Typ);
else
Error_Msg_N
("name must be an iterator, not a container", Name (N));
end if;
if Has_Aspect (Typ, Aspect_Iterable) then
null;
else
Error_Msg_NE
("\to iterate directly over the elements of a container, "
& "write `of &`", Name (N), Original_Node (Name (N)));
-- No point in continuing analysis of iterator spec
return;
end if;
end if;
-- If the name is a call (typically prefixed) to some Iterate
-- function, it has been rewritten as an object declaration.
-- If that object is a selected component, verify that it is not
-- a component of an unconstrained mutable object.
if Nkind (Iter_Name) = N_Identifier
or else (not Expander_Active and Comes_From_Source (Iter_Name))
then
declare
Orig_Node : constant Node_Id := Original_Node (Iter_Name);
Iter_Kind : constant Node_Kind := Nkind (Orig_Node);
Obj : Node_Id;
begin
if Iter_Kind = N_Selected_Component then
Obj := Prefix (Orig_Node);
elsif Iter_Kind = N_Function_Call then
Obj := First_Actual (Orig_Node);
-- If neither, the name comes from source
else
Obj := Iter_Name;
end if;
if Nkind (Obj) = N_Selected_Component
and then Is_Dependent_Component_Of_Mutable_Object (Obj)
then
Error_Msg_N
("container cannot be a discriminant-dependent "
& "component of a mutable object", N);
end if;
end;
end if;
-- The result type of Iterate function is the classwide type of
-- the interface parent. We need the specific Cursor type defined
-- in the container package. We obtain it by name for a predefined
-- container, or through the Iterable aspect for a formal one.
if Has_Aspect (Typ, Aspect_Iterable) then
Set_Etype (Def_Id,
Get_Cursor_Type
(Parent (Find_Value_Of_Aspect (Typ, Aspect_Iterable)),
Typ));
else
Set_Etype (Def_Id, Get_Cursor_Type (Typ));
Check_Reverse_Iteration (Etype (Iter_Name));
end if;
end if;
end if;
end Analyze_Iterator_Specification;
-------------------
-- Analyze_Label --
-------------------
-- Note: the semantic work required for analyzing labels (setting them as
-- reachable) was done in a prepass through the statements in the block,
-- so that forward gotos would be properly handled. See Analyze_Statements
-- for further details. The only processing required here is to deal with
-- optimizations that depend on an assumption of sequential control flow,
-- since of course the occurrence of a label breaks this assumption.
procedure Analyze_Label (N : Node_Id) is
pragma Warnings (Off, N);
begin
Kill_Current_Values;
end Analyze_Label;
--------------------------
-- Analyze_Label_Entity --
--------------------------
procedure Analyze_Label_Entity (E : Entity_Id) is
begin
Set_Ekind (E, E_Label);
Set_Etype (E, Standard_Void_Type);
Set_Enclosing_Scope (E, Current_Scope);
Set_Reachable (E, True);
end Analyze_Label_Entity;
------------------------------------------
-- Analyze_Loop_Parameter_Specification --
------------------------------------------
procedure Analyze_Loop_Parameter_Specification (N : Node_Id) is
Loop_Nod : constant Node_Id := Parent (Parent (N));
procedure Check_Controlled_Array_Attribute (DS : Node_Id);
-- If the bounds are given by a 'Range reference on a function call
-- that returns a controlled array, introduce an explicit declaration
-- to capture the bounds, so that the function result can be finalized
-- in timely fashion.
procedure Check_Predicate_Use (T : Entity_Id);
-- Diagnose Attempt to iterate through non-static predicate. Note that
-- a type with inherited predicates may have both static and dynamic
-- forms. In this case it is not sufficent to check the static predicate
-- function only, look for a dynamic predicate aspect as well.
function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean;
-- N is the node for an arbitrary construct. This function searches the
-- construct N to see if any expressions within it contain function
-- calls that use the secondary stack, returning True if any such call
-- is found, and False otherwise.
procedure Process_Bounds (R : Node_Id);
-- If the iteration is given by a range, create temporaries and
-- assignment statements block to capture the bounds and perform
-- required finalization actions in case a bound includes a function
-- call that uses the temporary stack. We first pre-analyze a copy of
-- the range in order to determine the expected type, and analyze and
-- resolve the original bounds.
--------------------------------------
-- Check_Controlled_Array_Attribute --
--------------------------------------
procedure Check_Controlled_Array_Attribute (DS : Node_Id) is
begin
if Nkind (DS) = N_Attribute_Reference
and then Is_Entity_Name (Prefix (DS))
and then Ekind (Entity (Prefix (DS))) = E_Function
and then Is_Array_Type (Etype (Entity (Prefix (DS))))
and then
Is_Controlled (Component_Type (Etype (Entity (Prefix (DS)))))
and then Expander_Active
then
declare
Loc : constant Source_Ptr := Sloc (N);
Arr : constant Entity_Id := Etype (Entity (Prefix (DS)));
Indx : constant Entity_Id :=
Base_Type (Etype (First_Index (Arr)));
Subt : constant Entity_Id := Make_Temporary (Loc, 'S');
Decl : Node_Id;
begin
Decl :=
Make_Subtype_Declaration (Loc,
Defining_Identifier => Subt,
Subtype_Indication =>
Make_Subtype_Indication (Loc,
Subtype_Mark => New_Occurrence_Of (Indx, Loc),
Constraint =>
Make_Range_Constraint (Loc, Relocate_Node (DS))));
Insert_Before (Loop_Nod, Decl);
Analyze (Decl);
Rewrite (DS,
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Subt, Loc),
Attribute_Name => Attribute_Name (DS)));
Analyze (DS);
end;
end if;
end Check_Controlled_Array_Attribute;
-------------------------
-- Check_Predicate_Use --
-------------------------
procedure Check_Predicate_Use (T : Entity_Id) is
begin
-- A predicated subtype is illegal in loops and related constructs
-- if the predicate is not static, or if it is a non-static subtype
-- of a statically predicated subtype.
if Is_Discrete_Type (T)
and then Has_Predicates (T)
and then (not Has_Static_Predicate (T)
or else not Is_Static_Subtype (T)
or else Has_Dynamic_Predicate_Aspect (T))
then
-- Seems a confusing message for the case of a static predicate
-- with a non-static subtype???
Bad_Predicated_Subtype_Use
("cannot use subtype& with non-static predicate for loop "
& "iteration", Discrete_Subtype_Definition (N),
T, Suggest_Static => True);
elsif Inside_A_Generic and then Is_Generic_Formal (T) then
Set_No_Dynamic_Predicate_On_Actual (T);
end if;
end Check_Predicate_Use;
------------------------------------
-- Has_Call_Using_Secondary_Stack --
------------------------------------
function Has_Call_Using_Secondary_Stack (N : Node_Id) return Boolean is
function Check_Call (N : Node_Id) return Traverse_Result;
-- Check if N is a function call which uses the secondary stack
----------------
-- Check_Call --
----------------
function Check_Call (N : Node_Id) return Traverse_Result is
Nam : Node_Id;
Subp : Entity_Id;
Return_Typ : Entity_Id;
begin
if Nkind (N) = N_Function_Call then
Nam := Name (N);
-- Call using access to subprogram with explicit dereference
if Nkind (Nam) = N_Explicit_Dereference then
Subp := Etype (Nam);
-- Call using a selected component notation or Ada 2005 object
-- operation notation
elsif Nkind (Nam) = N_Selected_Component then
Subp := Entity (Selector_Name (Nam));
-- Common case
else
Subp := Entity (Nam);
end if;
Return_Typ := Etype (Subp);
if Is_Composite_Type (Return_Typ)
and then not Is_Constrained (Return_Typ)
then
return Abandon;
elsif Sec_Stack_Needed_For_Return (Subp) then
return Abandon;
end if;
end if;
-- Continue traversing the tree
return OK;
end Check_Call;
function Check_Calls is new Traverse_Func (Check_Call);
-- Start of processing for Has_Call_Using_Secondary_Stack
begin
return Check_Calls (N) = Abandon;
end Has_Call_Using_Secondary_Stack;
--------------------
-- Process_Bounds --
--------------------
procedure Process_Bounds (R : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
function One_Bound
(Original_Bound : Node_Id;
Analyzed_Bound : Node_Id;
Typ : Entity_Id) return Node_Id;
-- Capture value of bound and return captured value
---------------
-- One_Bound --
---------------
function One_Bound
(Original_Bound : Node_Id;
Analyzed_Bound : Node_Id;
Typ : Entity_Id) return Node_Id
is
Assign : Node_Id;
Decl : Node_Id;
Id : Entity_Id;
begin
-- If the bound is a constant or an object, no need for a separate
-- declaration. If the bound is the result of previous expansion
-- it is already analyzed and should not be modified. Note that
-- the Bound will be resolved later, if needed, as part of the
-- call to Make_Index (literal bounds may need to be resolved to
-- type Integer).
if Analyzed (Original_Bound) then
return Original_Bound;
elsif Nkind_In (Analyzed_Bound, N_Integer_Literal,
N_Character_Literal)
or else Is_Entity_Name (Analyzed_Bound)
then
Analyze_And_Resolve (Original_Bound, Typ);
return Original_Bound;
end if;
-- Normally, the best approach is simply to generate a constant
-- declaration that captures the bound. However, there is a nasty
-- case where this is wrong. If the bound is complex, and has a
-- possible use of the secondary stack, we need to generate a
-- separate assignment statement to ensure the creation of a block
-- which will release the secondary stack.
-- We prefer the constant declaration, since it leaves us with a
-- proper trace of the value, useful in optimizations that get rid
-- of junk range checks.
if not Has_Call_Using_Secondary_Stack (Analyzed_Bound) then
Analyze_And_Resolve (Original_Bound, Typ);
-- Ensure that the bound is valid. This check should not be
-- generated when the range belongs to a quantified expression
-- as the construct is still not expanded into its final form.
if Nkind (Parent (R)) /= N_Loop_Parameter_Specification
or else Nkind (Parent (Parent (R))) /= N_Quantified_Expression
then
Ensure_Valid (Original_Bound);
end if;
Force_Evaluation (Original_Bound);
return Original_Bound;
end if;
Id := Make_Temporary (Loc, 'R', Original_Bound);
-- Here we make a declaration with a separate assignment
-- statement, and insert before loop header.
Decl :=
Make_Object_Declaration (Loc,
Defining_Identifier => Id,
Object_Definition => New_Occurrence_Of (Typ, Loc));
Assign :=
Make_Assignment_Statement (Loc,
Name => New_Occurrence_Of (Id, Loc),
Expression => Relocate_Node (Original_Bound));
Insert_Actions (Loop_Nod, New_List (Decl, Assign));
-- Now that this temporary variable is initialized we decorate it
-- as safe-to-reevaluate to inform to the backend that no further
-- asignment will be issued and hence it can be handled as side
-- effect free. Note that this decoration must be done when the
-- assignment has been analyzed because otherwise it will be
-- rejected (see Analyze_Assignment).
Set_Is_Safe_To_Reevaluate (Id);
Rewrite (Original_Bound, New_Occurrence_Of (Id, Loc));
if Nkind (Assign) = N_Assignment_Statement then
return Expression (Assign);
else
return Original_Bound;
end if;
end One_Bound;
Hi : constant Node_Id := High_Bound (R);
Lo : constant Node_Id := Low_Bound (R);
R_Copy : constant Node_Id := New_Copy_Tree (R);
New_Hi : Node_Id;
New_Lo : Node_Id;
Typ : Entity_Id;
-- Start of processing for Process_Bounds
begin
Set_Parent (R_Copy, Parent (R));
Preanalyze_Range (R_Copy);
Typ := Etype (R_Copy);
-- If the type of the discrete range is Universal_Integer, then the
-- bound's type must be resolved to Integer, and any object used to
-- hold the bound must also have type Integer, unless the literal
-- bounds are constant-folded expressions with a user-defined type.
if Typ = Universal_Integer then
if Nkind (Lo) = N_Integer_Literal
and then Present (Etype (Lo))
and then Scope (Etype (Lo)) /= Standard_Standard
then
Typ := Etype (Lo);
elsif Nkind (Hi) = N_Integer_Literal
and then Present (Etype (Hi))
and then Scope (Etype (Hi)) /= Standard_Standard
then
Typ := Etype (Hi);
else
Typ := Standard_Integer;
end if;
end if;
Set_Etype (R, Typ);
New_Lo := One_Bound (Lo, Low_Bound (R_Copy), Typ);
New_Hi := One_Bound (Hi, High_Bound (R_Copy), Typ);
-- Propagate staticness to loop range itself, in case the
-- corresponding subtype is static.
if New_Lo /= Lo and then Is_OK_Static_Expression (New_Lo) then
Rewrite (Low_Bound (R), New_Copy (New_Lo));
end if;
if New_Hi /= Hi and then Is_OK_Static_Expression (New_Hi) then
Rewrite (High_Bound (R), New_Copy (New_Hi));
end if;
end Process_Bounds;
-- Local variables
DS : constant Node_Id := Discrete_Subtype_Definition (N);
Id : constant Entity_Id := Defining_Identifier (N);
DS_Copy : Node_Id;
-- Start of processing for Analyze_Loop_Parameter_Specification
begin
Enter_Name (Id);
-- We always consider the loop variable to be referenced, since the loop
-- may be used just for counting purposes.
Generate_Reference (Id, N, ' ');
-- Check for the case of loop variable hiding a local variable (used
-- later on to give a nice warning if the hidden variable is never
-- assigned).
declare
H : constant Entity_Id := Homonym (Id);
begin
if Present (H)
and then Ekind (H) = E_Variable
and then Is_Discrete_Type (Etype (H))
and then Enclosing_Dynamic_Scope (H) = Enclosing_Dynamic_Scope (Id)
then
Set_Hiding_Loop_Variable (H, Id);
end if;
end;
-- Loop parameter specification must include subtype mark in SPARK
if Nkind (DS) = N_Range then
Check_SPARK_05_Restriction
("loop parameter specification must include subtype mark", N);
end if;
-- Analyze the subtype definition and create temporaries for the bounds.
-- Do not evaluate the range when preanalyzing a quantified expression
-- because bounds expressed as function calls with side effects will be
-- incorrectly replicated.
if Nkind (DS) = N_Range
and then Expander_Active
and then Nkind (Parent (N)) /= N_Quantified_Expression
then
Process_Bounds (DS);
-- Either the expander not active or the range of iteration is a subtype
-- indication, an entity, or a function call that yields an aggregate or
-- a container.
else
DS_Copy := New_Copy_Tree (DS);
Set_Parent (DS_Copy, Parent (DS));
Preanalyze_Range (DS_Copy);
-- Ada 2012: If the domain of iteration is:
-- a) a function call,
-- b) an identifier that is not a type,
-- c) an attribute reference 'Old (within a postcondition),
-- d) an unchecked conversion or a qualified expression with
-- the proper iterator type.
-- then it is an iteration over a container. It was classified as
-- a loop specification by the parser, and must be rewritten now
-- to activate container iteration. The last case will occur within
-- an expanded inlined call, where the expansion wraps an actual in
-- an unchecked conversion when needed. The expression of the
-- conversion is always an object.
if Nkind (DS_Copy) = N_Function_Call
or else (Is_Entity_Name (DS_Copy)
and then not Is_Type (Entity (DS_Copy)))
or else (Nkind (DS_Copy) = N_Attribute_Reference
and then Nam_In (Attribute_Name (DS_Copy),
Name_Loop_Entry, Name_Old))
or else Has_Aspect (Etype (DS_Copy), Aspect_Iterable)
or else Nkind (DS_Copy) = N_Unchecked_Type_Conversion
or else (Nkind (DS_Copy) = N_Qualified_Expression
and then Is_Iterator (Etype (DS_Copy)))
then
-- This is an iterator specification. Rewrite it as such and
-- analyze it to capture function calls that may require
-- finalization actions.
declare
I_Spec : constant Node_Id :=
Make_Iterator_Specification (Sloc (N),
Defining_Identifier => Relocate_Node (Id),
Name => DS_Copy,
Subtype_Indication => Empty,
Reverse_Present => Reverse_Present (N));
Scheme : constant Node_Id := Parent (N);
begin
Set_Iterator_Specification (Scheme, I_Spec);
Set_Loop_Parameter_Specification (Scheme, Empty);
Analyze_Iterator_Specification (I_Spec);
-- In a generic context, analyze the original domain of
-- iteration, for name capture.
if not Expander_Active then
Analyze (DS);
end if;
-- Set kind of loop parameter, which may be used in the
-- subsequent analysis of the condition in a quantified
-- expression.
Set_Ekind (Id, E_Loop_Parameter);
return;
end;
-- Domain of iteration is not a function call, and is side-effect
-- free.
else
-- A quantified expression that appears in a pre/post condition
-- is pre-analyzed several times. If the range is given by an
-- attribute reference it is rewritten as a range, and this is
-- done even with expansion disabled. If the type is already set
-- do not reanalyze, because a range with static bounds may be
-- typed Integer by default.
if Nkind (Parent (N)) = N_Quantified_Expression
and then Present (Etype (DS))
then
null;
else
Analyze (DS);
end if;
end if;
end if;
if DS = Error then
return;
end if;
-- Some additional checks if we are iterating through a type
if Is_Entity_Name (DS)
and then Present (Entity (DS))
and then Is_Type (Entity (DS))
then
-- The subtype indication may denote the completion of an incomplete
-- type declaration.
if Ekind (Entity (DS)) = E_Incomplete_Type then
Set_Entity (DS, Get_Full_View (Entity (DS)));
Set_Etype (DS, Entity (DS));
end if;
Check_Predicate_Use (Entity (DS));
end if;
-- Error if not discrete type
if not Is_Discrete_Type (Etype (DS)) then
Wrong_Type (DS, Any_Discrete);
Set_Etype (DS, Any_Type);
end if;
Check_Controlled_Array_Attribute (DS);
if Nkind (DS) = N_Subtype_Indication then
Check_Predicate_Use (Entity (Subtype_Mark (DS)));
end if;
Make_Index (DS, N, In_Iter_Schm => True);
Set_Ekind (Id, E_Loop_Parameter);
-- A quantified expression which appears in a pre- or post-condition may
-- be analyzed multiple times. The analysis of the range creates several
-- itypes which reside in different scopes depending on whether the pre-
-- or post-condition has been expanded. Update the type of the loop
-- variable to reflect the proper itype at each stage of analysis.
if No (Etype (Id))
or else Etype (Id) = Any_Type
or else
(Present (Etype (Id))
and then Is_Itype (Etype (Id))
and then Nkind (Parent (Loop_Nod)) = N_Expression_With_Actions
and then Nkind (Original_Node (Parent (Loop_Nod))) =
N_Quantified_Expression)
then
Set_Etype (Id, Etype (DS));
end if;
-- Treat a range as an implicit reference to the type, to inhibit
-- spurious warnings.
Generate_Reference (Base_Type (Etype (DS)), N, ' ');
Set_Is_Known_Valid (Id, True);
-- The loop is not a declarative part, so the loop variable must be
-- frozen explicitly. Do not freeze while preanalyzing a quantified
-- expression because the freeze node will not be inserted into the
-- tree due to flag Is_Spec_Expression being set.
if Nkind (Parent (N)) /= N_Quantified_Expression then
declare
Flist : constant List_Id := Freeze_Entity (Id, N);
begin
if Is_Non_Empty_List (Flist) then
Insert_Actions (N, Flist);
end if;
end;
end if;
-- Case where we have a range or a subtype, get type bounds
if Nkind_In (DS, N_Range, N_Subtype_Indication)
and then not Error_Posted (DS)
and then Etype (DS) /= Any_Type
and then Is_Discrete_Type (Etype (DS))
then
declare
L : Node_Id;
H : Node_Id;
begin
if Nkind (DS) = N_Range then
L := Low_Bound (DS);
H := High_Bound (DS);
else
L :=
Type_Low_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
H :=
Type_High_Bound (Underlying_Type (Etype (Subtype_Mark (DS))));
end if;
-- Check for null or possibly null range and issue warning. We
-- suppress such messages in generic templates and instances,
-- because in practice they tend to be dubious in these cases. The
-- check applies as well to rewritten array element loops where a
-- null range may be detected statically.
if Compile_Time_Compare (L, H, Assume_Valid => True) = GT then
-- Suppress the warning if inside a generic template or
-- instance, since in practice they tend to be dubious in these
-- cases since they can result from intended parameterization.
if not Inside_A_Generic and then not In_Instance then
-- Specialize msg if invalid values could make the loop
-- non-null after all.
if Compile_Time_Compare
(L, H, Assume_Valid => False) = GT
then
-- Since we know the range of the loop is null, set the
-- appropriate flag to remove the loop entirely during
-- expansion.
Set_Is_Null_Loop (Loop_Nod);
if Comes_From_Source (N) then
Error_Msg_N
("??loop range is null, loop will not execute", DS);
end if;
-- Here is where the loop could execute because of
-- invalid values, so issue appropriate message and in
-- this case we do not set the Is_Null_Loop flag since
-- the loop may execute.
elsif Comes_From_Source (N) then
Error_Msg_N
("??loop range may be null, loop may not execute",
DS);
Error_Msg_N
("??can only execute if invalid values are present",
DS);
end if;
end if;
-- In either case, suppress warnings in the body of the loop,
-- since it is likely that these warnings will be inappropriate
-- if the loop never actually executes, which is likely.
Set_Suppress_Loop_Warnings (Loop_Nod);
-- The other case for a warning is a reverse loop where the
-- upper bound is the integer literal zero or one, and the
-- lower bound may exceed this value.
-- For example, we have
-- for J in reverse N .. 1 loop
-- In practice, this is very likely to be a case of reversing
-- the bounds incorrectly in the range.
elsif Reverse_Present (N)
and then Nkind (Original_Node (H)) = N_Integer_Literal
and then
(Intval (Original_Node (H)) = Uint_0
or else
Intval (Original_Node (H)) = Uint_1)
then
-- Lower bound may in fact be known and known not to exceed
-- upper bound (e.g. reverse 0 .. 1) and that's OK.
if Compile_Time_Known_Value (L)
and then Expr_Value (L) <= Expr_Value (H)
then
null;
-- Otherwise warning is warranted
else
Error_Msg_N ("??loop range may be null", DS);
Error_Msg_N ("\??bounds may be wrong way round", DS);
end if;
end if;
-- Check if either bound is known to be outside the range of the
-- loop parameter type, this is e.g. the case of a loop from
-- 20..X where the type is 1..19.
-- Such a loop is dubious since either it raises CE or it executes
-- zero times, and that cannot be useful!
if Etype (DS) /= Any_Type
and then not Error_Posted (DS)
and then Nkind (DS) = N_Subtype_Indication
and then Nkind (Constraint (DS)) = N_Range_Constraint
then
declare
LLo : constant Node_Id :=
Low_Bound (Range_Expression (Constraint (DS)));
LHi : constant Node_Id :=
High_Bound (Range_Expression (Constraint (DS)));
Bad_Bound : Node_Id := Empty;
-- Suspicious loop bound
begin
-- At this stage L, H are the bounds of the type, and LLo
-- Lhi are the low bound and high bound of the loop.
if Compile_Time_Compare (LLo, L, Assume_Valid => True) = LT
or else
Compile_Time_Compare (LLo, H, Assume_Valid => True) = GT
then
Bad_Bound := LLo;
end if;
if Compile_Time_Compare (LHi, L, Assume_Valid => True) = LT
or else
Compile_Time_Compare (LHi, H, Assume_Valid => True) = GT
then
Bad_Bound := LHi;
end if;
if Present (Bad_Bound) then
Error_Msg_N
("suspicious loop bound out of range of "
& "loop subtype??", Bad_Bound);
Error_Msg_N
("\loop executes zero times or raises "
& "Constraint_Error??", Bad_Bound);
end if;
end;
end if;
-- This declare block is about warnings, if we get an exception while
-- testing for warnings, we simply abandon the attempt silently. This
-- most likely occurs as the result of a previous error, but might
-- just be an obscure case we have missed. In either case, not giving
-- the warning is perfectly acceptable.
exception
when others => null;
end;
end if;
-- A loop parameter cannot be effectively volatile (SPARK RM 7.1.3(4)).
-- This check is relevant only when SPARK_Mode is on as it is not a
-- standard Ada legality check.
if SPARK_Mode = On and then Is_Effectively_Volatile (Id) then
Error_Msg_N ("loop parameter cannot be volatile", Id);
end if;
end Analyze_Loop_Parameter_Specification;
----------------------------
-- Analyze_Loop_Statement --
----------------------------
procedure Analyze_Loop_Statement (N : Node_Id) is
function Is_Container_Iterator (Iter : Node_Id) return Boolean;
-- Given a loop iteration scheme, determine whether it is an Ada 2012
-- container iteration.
function Is_Wrapped_In_Block (N : Node_Id) return Boolean;
-- Determine whether loop statement N has been wrapped in a block to
-- capture finalization actions that may be generated for container
-- iterators. Prevents infinite recursion when block is analyzed.
-- Routine is a noop if loop is single statement within source block.
---------------------------
-- Is_Container_Iterator --
---------------------------
function Is_Container_Iterator (Iter : Node_Id) return Boolean is
begin
-- Infinite loop
if No (Iter) then
return False;
-- While loop
elsif Present (Condition (Iter)) then
return False;
-- for Def_Id in [reverse] Name loop
-- for Def_Id [: Subtype_Indication] of [reverse] Name loop
elsif Present (Iterator_Specification (Iter)) then
declare
Nam : constant Node_Id := Name (Iterator_Specification (Iter));
Nam_Copy : Node_Id;
begin
Nam_Copy := New_Copy_Tree (Nam);
Set_Parent (Nam_Copy, Parent (Nam));
Preanalyze_Range (Nam_Copy);
-- The only two options here are iteration over a container or
-- an array.
return not Is_Array_Type (Etype (Nam_Copy));
end;
-- for Def_Id in [reverse] Discrete_Subtype_Definition loop
else
declare
LP : constant Node_Id := Loop_Parameter_Specification (Iter);
DS : constant Node_Id := Discrete_Subtype_Definition (LP);
DS_Copy : Node_Id;
begin
DS_Copy := New_Copy_Tree (DS);
Set_Parent (DS_Copy, Parent (DS));
Preanalyze_Range (DS_Copy);
-- Check for a call to Iterate () or an expression with
-- an iterator type.
return
(Nkind (DS_Copy) = N_Function_Call
and then Needs_Finalization (Etype (DS_Copy)))
or else Is_Iterator (Etype (DS_Copy));
end;
end if;
end Is_Container_Iterator;
-------------------------
-- Is_Wrapped_In_Block --
-------------------------
function Is_Wrapped_In_Block (N : Node_Id) return Boolean is
HSS : Node_Id;
Stat : Node_Id;
begin
-- Check if current scope is a block that is not a transient block.
if Ekind (Current_Scope) /= E_Block
or else No (Block_Node (Current_Scope))
then
return False;
else
HSS :=
Handled_Statement_Sequence (Parent (Block_Node (Current_Scope)));
-- Skip leading pragmas that may be introduced for invariant and
-- predicate checks.
Stat := First (Statements (HSS));
while Present (Stat) and then Nkind (Stat) = N_Pragma loop
Stat := Next (Stat);
end loop;
return Stat = N and then No (Next (Stat));
end if;
end Is_Wrapped_In_Block;
-- Local declarations
Id : constant Node_Id := Identifier (N);
Iter : constant Node_Id := Iteration_Scheme (N);
Loc : constant Source_Ptr := Sloc (N);
Ent : Entity_Id;
Stmt : Node_Id;
-- Start of processing for Analyze_Loop_Statement
begin
if Present (Id) then
-- Make name visible, e.g. for use in exit statements. Loop labels
-- are always considered to be referenced.
Analyze (Id);
Ent := Entity (Id);
-- Guard against serious error (typically, a scope mismatch when
-- semantic analysis is requested) by creating loop entity to
-- continue analysis.
if No (Ent) then
if Total_Errors_Detected /= 0 then
Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
else
raise Program_Error;
end if;
-- Verify that the loop name is hot hidden by an unrelated
-- declaration in an inner scope.
elsif Ekind (Ent) /= E_Label and then Ekind (Ent) /= E_Loop then
Error_Msg_Sloc := Sloc (Ent);
Error_Msg_N ("implicit label declaration for & is hidden#", Id);
if Present (Homonym (Ent))
and then Ekind (Homonym (Ent)) = E_Label
then
Set_Entity (Id, Ent);
Set_Ekind (Ent, E_Loop);
end if;
else
Generate_Reference (Ent, N, ' ');
Generate_Definition (Ent);
-- If we found a label, mark its type. If not, ignore it, since it
-- means we have a conflicting declaration, which would already
-- have been diagnosed at declaration time. Set Label_Construct
-- of the implicit label declaration, which is not created by the
-- parser for generic units.
if Ekind (Ent) = E_Label then
Set_Ekind (Ent, E_Loop);
if Nkind (Parent (Ent)) = N_Implicit_Label_Declaration then
Set_Label_Construct (Parent (Ent), N);
end if;
end if;
end if;
-- Case of no identifier present. Create one and attach it to the
-- loop statement for use as a scope and as a reference for later
-- expansions. Indicate that the label does not come from source,
-- and attach it to the loop statement so it is part of the tree,
-- even without a full declaration.
else
Ent := New_Internal_Entity (E_Loop, Current_Scope, Loc, 'L');
Set_Etype (Ent, Standard_Void_Type);
Set_Identifier (N, New_Occurrence_Of (Ent, Loc));
Set_Parent (Ent, N);
Set_Has_Created_Identifier (N);
end if;
-- If the iterator specification has a syntactic error, transform
-- construct into an infinite loop to prevent a crash and perform
-- some analysis.
if Present (Iter)
and then Present (Iterator_Specification (Iter))
and then Error_Posted (Iterator_Specification (Iter))
then
Set_Iteration_Scheme (N, Empty);
Analyze (N);
return;
end if;
-- Iteration over a container in Ada 2012 involves the creation of a
-- controlled iterator object. Wrap the loop in a block to ensure the
-- timely finalization of the iterator and release of container locks.
-- The same applies to the use of secondary stack when obtaining an
-- iterator.
if Ada_Version >= Ada_2012
and then Is_Container_Iterator (Iter)
and then not Is_Wrapped_In_Block (N)
then
declare
Block_Nod : Node_Id;
Block_Id : Entity_Id;
begin
Block_Nod :=
Make_Block_Statement (Loc,
Declarations => New_List,
Handled_Statement_Sequence =>
Make_Handled_Sequence_Of_Statements (Loc,
Statements => New_List (Relocate_Node (N))));
Add_Block_Identifier (Block_Nod, Block_Id);
-- The expansion of iterator loops generates an iterator in order
-- to traverse the elements of a container:
-- Iter : <iterator type> := Iterate (Container)'reference;
-- The iterator is controlled and returned on the secondary stack.
-- The analysis of the call to Iterate establishes a transient
-- scope to deal with the secondary stack management, but never
-- really creates a physical block as this would kill the iterator
-- too early (see Wrap_Transient_Declaration). To address this
-- case, mark the generated block as needing secondary stack
-- management.
Set_Uses_Sec_Stack (Block_Id);
Rewrite (N, Block_Nod);
Analyze (N);
return;
end;
end if;
-- Kill current values on entry to loop, since statements in the body of
-- the loop may have been executed before the loop is entered. Similarly
-- we kill values after the loop, since we do not know that the body of
-- the loop was executed.
Kill_Current_Values;
Push_Scope (Ent);
Analyze_Iteration_Scheme (Iter);
-- Check for following case which merits a warning if the type E of is
-- a multi-dimensional array (and no explicit subscript ranges present).
-- for J in E'Range
-- for K in E'Range
if Present (Iter)
and then Present (Loop_Parameter_Specification (Iter))
then
declare
LPS : constant Node_Id := Loop_Parameter_Specification (Iter);
DSD : constant Node_Id :=
Original_Node (Discrete_Subtype_Definition (LPS));
begin
if Nkind (DSD) = N_Attribute_Reference
and then Attribute_Name (DSD) = Name_Range
and then No (Expressions (DSD))
then
declare
Typ : constant Entity_Id := Etype (Prefix (DSD));
begin
if Is_Array_Type (Typ)
and then Number_Dimensions (Typ) > 1
and then Nkind (Parent (N)) = N_Loop_Statement
and then Present (Iteration_Scheme (Parent (N)))
then
declare
OIter : constant Node_Id :=
Iteration_Scheme (Parent (N));
OLPS : constant Node_Id :=
Loop_Parameter_Specification (OIter);
ODSD : constant Node_Id :=
Original_Node (Discrete_Subtype_Definition (OLPS));
begin
if Nkind (ODSD) = N_Attribute_Reference
and then Attribute_Name (ODSD) = Name_Range
and then No (Expressions (ODSD))
and then Etype (Prefix (ODSD)) = Typ
then
Error_Msg_Sloc := Sloc (ODSD);
Error_Msg_N
("inner range same as outer range#??", DSD);
end if;
end;
end if;
end;
end if;
end;
end if;
-- Analyze the statements of the body except in the case of an Ada 2012
-- iterator with the expander active. In this case the expander will do
-- a rewrite of the loop into a while loop. We will then analyze the
-- loop body when we analyze this while loop.
-- We need to do this delay because if the container is for indefinite
-- types the actual subtype of the components will only be determined
-- when the cursor declaration is analyzed.
-- If the expander is not active then we want to analyze the loop body
-- now even in the Ada 2012 iterator case, since the rewriting will not
-- be done. Insert the loop variable in the current scope, if not done
-- when analysing the iteration scheme. Set its kind properly to detect
-- improper uses in the loop body.
-- In GNATprove mode, we do one of the above depending on the kind of
-- loop. If it is an iterator over an array, then we do not analyze the
-- loop now. We will analyze it after it has been rewritten by the
-- special SPARK expansion which is activated in GNATprove mode. We need
-- to do this so that other expansions that should occur in GNATprove
-- mode take into account the specificities of the rewritten loop, in
-- particular the introduction of a renaming (which needs to be
-- expanded).
-- In other cases in GNATprove mode then we want to analyze the loop
-- body now, since no rewriting will occur. Within a generic the
-- GNATprove mode is irrelevant, we must analyze the generic for
-- non-local name capture.
if Present (Iter)
and then Present (Iterator_Specification (Iter))
then
if GNATprove_Mode
and then Is_Iterator_Over_Array (Iterator_Specification (Iter))
and then not Inside_A_Generic
then
null;
elsif not Expander_Active then
declare
I_Spec : constant Node_Id := Iterator_Specification (Iter);
Id : constant Entity_Id := Defining_Identifier (I_Spec);
begin
if Scope (Id) /= Current_Scope then
Enter_Name (Id);
end if;
-- In an element iterator, The loop parameter is a variable if
-- the domain of iteration (container or array) is a variable.
if not Of_Present (I_Spec)
or else not Is_Variable (Name (I_Spec))
then
Set_Ekind (Id, E_Loop_Parameter);
end if;
end;
Analyze_Statements (Statements (N));
end if;
else
-- Pre-Ada2012 for-loops and while loops.
Analyze_Statements (Statements (N));
end if;
-- When the iteration scheme of a loop contains attribute 'Loop_Entry,
-- the loop is transformed into a conditional block. Retrieve the loop.
Stmt := N;
if Subject_To_Loop_Entry_Attributes (Stmt) then
Stmt := Find_Loop_In_Conditional_Block (Stmt);
end if;
-- Finish up processing for the loop. We kill all current values, since
-- in general we don't know if the statements in the loop have been
-- executed. We could do a bit better than this with a loop that we
-- know will execute at least once, but it's not worth the trouble and
-- the front end is not in the business of flow tracing.
Process_End_Label (Stmt, 'e', Ent);
End_Scope;
Kill_Current_Values;
-- Check for infinite loop. Skip check for generated code, since it
-- justs waste time and makes debugging the routine called harder.
-- Note that we have to wait till the body of the loop is fully analyzed
-- before making this call, since Check_Infinite_Loop_Warning relies on
-- being able to use semantic visibility information to find references.
if Comes_From_Source (Stmt) then
Check_Infinite_Loop_Warning (Stmt);
end if;
-- Code after loop is unreachable if the loop has no WHILE or FOR and
-- contains no EXIT statements within the body of the loop.
if No (Iter) and then not Has_Exit (Ent) then
Check_Unreachable_Code (Stmt);
end if;
end Analyze_Loop_Statement;
----------------------------
-- Analyze_Null_Statement --
----------------------------
-- Note: the semantics of the null statement is implemented by a single
-- null statement, too bad everything isn't as simple as this.
procedure Analyze_Null_Statement (N : Node_Id) is
pragma Warnings (Off, N);
begin
null;
end Analyze_Null_Statement;
-------------------------
-- Analyze_Target_Name --
-------------------------
procedure Analyze_Target_Name (N : Node_Id) is
begin
if No (Current_LHS) then
Error_Msg_N ("target name can only appear within an assignment", N);
Set_Etype (N, Any_Type);
else
Set_Has_Target_Names (Parent (Current_LHS));
Set_Etype (N, Etype (Current_LHS));
-- Disable expansion for the rest of the analysis of the current
-- right-hand side. The enclosing assignment statement will be
-- rewritten during expansion, together with occurrences of the
-- target name.
if Expander_Active then
Expander_Mode_Save_And_Set (False);
end if;
end if;
end Analyze_Target_Name;
------------------------
-- Analyze_Statements --
------------------------
procedure Analyze_Statements (L : List_Id) is
S : Node_Id;
Lab : Entity_Id;
begin
-- The labels declared in the statement list are reachable from
-- statements in the list. We do this as a prepass so that any goto
-- statement will be properly flagged if its target is not reachable.
-- This is not required, but is nice behavior.
S := First (L);
while Present (S) loop
if Nkind (S) = N_Label then
Analyze (Identifier (S));
Lab := Entity (Identifier (S));
-- If we found a label mark it as reachable
if Ekind (Lab) = E_Label then
Generate_Definition (Lab);
Set_Reachable (Lab);
if Nkind (Parent (Lab)) = N_Implicit_Label_Declaration then
Set_Label_Construct (Parent (Lab), S);
end if;
-- If we failed to find a label, it means the implicit declaration
-- of the label was hidden. A for-loop parameter can do this to
-- a label with the same name inside the loop, since the implicit
-- label declaration is in the innermost enclosing body or block
-- statement.
else
Error_Msg_Sloc := Sloc (Lab);
Error_Msg_N
("implicit label declaration for & is hidden#",
Identifier (S));
end if;
end if;
Next (S);
end loop;
-- Perform semantic analysis on all statements
Conditional_Statements_Begin;
S := First (L);
while Present (S) loop
Analyze (S);
-- Remove dimension in all statements
Remove_Dimension_In_Statement (S);
Next (S);
end loop;
Conditional_Statements_End;
-- Make labels unreachable. Visibility is not sufficient, because labels
-- in one if-branch for example are not reachable from the other branch,
-- even though their declarations are in the enclosing declarative part.
S := First (L);
while Present (S) loop
if Nkind (S) = N_Label then
Set_Reachable (Entity (Identifier (S)), False);
end if;
Next (S);
end loop;
end Analyze_Statements;
----------------------------
-- Check_Unreachable_Code --
----------------------------
procedure Check_Unreachable_Code (N : Node_Id) is
Error_Node : Node_Id;
P : Node_Id;
begin
if Is_List_Member (N) and then Comes_From_Source (N) then
declare
Nxt : Node_Id;
begin
Nxt := Original_Node (Next (N));
-- Skip past pragmas
while Nkind (Nxt) = N_Pragma loop
Nxt := Original_Node (Next (Nxt));
end loop;
-- If a label follows us, then we never have dead code, since
-- someone could branch to the label, so we just ignore it, unless
-- we are in formal mode where goto statements are not allowed.
if Nkind (Nxt) = N_Label
and then not Restriction_Check_Required (SPARK_05)
then
return;
-- Otherwise see if we have a real statement following us
elsif Present (Nxt)
and then Comes_From_Source (Nxt)
and then Is_Statement (Nxt)
then
-- Special very annoying exception. If we have a return that
-- follows a raise, then we allow it without a warning, since
-- the Ada RM annoyingly requires a useless return here.
if Nkind (Original_Node (N)) /= N_Raise_Statement
or else Nkind (Nxt) /= N_Simple_Return_Statement
then
-- The rather strange shenanigans with the warning message
-- here reflects the fact that Kill_Dead_Code is very good
-- at removing warnings in deleted code, and this is one
-- warning we would prefer NOT to have removed.
Error_Node := Nxt;
-- If we have unreachable code, analyze and remove the
-- unreachable code, since it is useless and we don't
-- want to generate junk warnings.
-- We skip this step if we are not in code generation mode
-- or CodePeer mode.
-- This is the one case where we remove dead code in the
-- semantics as opposed to the expander, and we do not want
-- to remove code if we are not in code generation mode,
-- since this messes up the ASIS trees or loses useful
-- information in the CodePeer tree.
-- Note that one might react by moving the whole circuit to
-- exp_ch5, but then we lose the warning in -gnatc mode.
if Operating_Mode = Generate_Code
and then not CodePeer_Mode
then
loop
Nxt := Next (N);
-- Quit deleting when we have nothing more to delete
-- or if we hit a label (since someone could transfer
-- control to a label, so we should not delete it).
exit when No (Nxt) or else Nkind (Nxt) = N_Label;
-- Statement/declaration is to be deleted
Analyze (Nxt);
Remove (Nxt);
Kill_Dead_Code (Nxt);
end loop;
end if;
-- Now issue the warning (or error in formal mode)
if Restriction_Check_Required (SPARK_05) then
Check_SPARK_05_Restriction
("unreachable code is not allowed", Error_Node);
else
Error_Msg ("??unreachable code!", Sloc (Error_Node));
end if;
end if;
-- If the unconditional transfer of control instruction is the
-- last statement of a sequence, then see if our parent is one of
-- the constructs for which we count unblocked exits, and if so,
-- adjust the count.
else
P := Parent (N);
-- Statements in THEN part or ELSE part of IF statement
if Nkind (P) = N_If_Statement then
null;
-- Statements in ELSIF part of an IF statement
elsif Nkind (P) = N_Elsif_Part then
P := Parent (P);
pragma Assert (Nkind (P) = N_If_Statement);
-- Statements in CASE statement alternative
elsif Nkind (P) = N_Case_Statement_Alternative then
P := Parent (P);
pragma Assert (Nkind (P) = N_Case_Statement);
-- Statements in body of block
elsif Nkind (P) = N_Handled_Sequence_Of_Statements
and then Nkind (Parent (P)) = N_Block_Statement
then
-- The original loop is now placed inside a block statement
-- due to the expansion of attribute 'Loop_Entry. Return as
-- this is not a "real" block for the purposes of exit
-- counting.
if Nkind (N) = N_Loop_Statement
and then Subject_To_Loop_Entry_Attributes (N)
then
return;
end if;
-- Statements in exception handler in a block
elsif Nkind (P) = N_Exception_Handler
and then Nkind (Parent (P)) = N_Handled_Sequence_Of_Statements
and then Nkind (Parent (Parent (P))) = N_Block_Statement
then
null;
-- None of these cases, so return
else
return;
end if;
-- This was one of the cases we are looking for (i.e. the
-- parent construct was IF, CASE or block) so decrement count.
Unblocked_Exit_Count := Unblocked_Exit_Count - 1;
end if;
end;
end if;
end Check_Unreachable_Code;
----------------------
-- Preanalyze_Range --
----------------------
procedure Preanalyze_Range (R_Copy : Node_Id) is
Save_Analysis : constant Boolean := Full_Analysis;
Typ : Entity_Id;
begin
Full_Analysis := False;
Expander_Mode_Save_And_Set (False);
Analyze (R_Copy);
if Nkind (R_Copy) in N_Subexpr and then Is_Overloaded (R_Copy) then
-- Apply preference rules for range of predefined integer types, or
-- diagnose true ambiguity.
declare
I : Interp_Index;
It : Interp;
Found : Entity_Id := Empty;
begin
Get_First_Interp (R_Copy, I, It);
while Present (It.Typ) loop
if Is_Discrete_Type (It.Typ) then
if No (Found) then
Found := It.Typ;
else
if Scope (Found) = Standard_Standard then
null;
elsif Scope (It.Typ) = Standard_Standard then
Found := It.Typ;
else
-- Both of them are user-defined
Error_Msg_N
("ambiguous bounds in range of iteration", R_Copy);
Error_Msg_N ("\possible interpretations:", R_Copy);
Error_Msg_NE ("\\} ", R_Copy, Found);
Error_Msg_NE ("\\} ", R_Copy, It.Typ);
exit;
end if;
end if;
end if;
Get_Next_Interp (I, It);
end loop;
end;
end if;
-- Subtype mark in iteration scheme
if Is_Entity_Name (R_Copy) and then Is_Type (Entity (R_Copy)) then
null;
-- Expression in range, or Ada 2012 iterator
elsif Nkind (R_Copy) in N_Subexpr then
Resolve (R_Copy);
Typ := Etype (R_Copy);
if Is_Discrete_Type (Typ) then
null;
-- Check that the resulting object is an iterable container
elsif Has_Aspect (Typ, Aspect_Iterator_Element)
or else Has_Aspect (Typ, Aspect_Constant_Indexing)
or else Has_Aspect (Typ, Aspect_Variable_Indexing)
then
null;
-- The expression may yield an implicit reference to an iterable
-- container. Insert explicit dereference so that proper type is
-- visible in the loop.
elsif Has_Implicit_Dereference (Etype (R_Copy)) then
declare
Disc : Entity_Id;
begin
Disc := First_Discriminant (Typ);
while Present (Disc) loop
if Has_Implicit_Dereference (Disc) then
Build_Explicit_Dereference (R_Copy, Disc);
exit;
end if;
Next_Discriminant (Disc);
end loop;
end;
end if;
end if;
Expander_Mode_Restore;
Full_Analysis := Save_Analysis;
end Preanalyze_Range;
end Sem_Ch5;
|
-- { dg-do run }
-- { dg-options "-gnatws" }
procedure discr4 is
package Pkg is
type Rec_Comp (D : access Integer) is record
Data : Integer;
end record;
--
type I is interface;
procedure Test (Obj : I) is abstract;
--
Num : aliased Integer := 10;
--
type Root (D : access Integer) is tagged record
C1 : Rec_Comp (D); -- test
end record;
--
type DT is new Root and I with null record;
--
procedure Dummy (Obj : DT);
procedure Test (Obj : DT);
end;
--
package body Pkg is
procedure Dummy (Obj : DT) is
begin
raise Program_Error;
end;
--
procedure Test (Obj : DT) is
begin
null;
end;
end;
--
use Pkg;
--
procedure CW_Test (Obj : I'Class) is
begin
Obj.Test;
end;
--
Obj : DT (Num'Access);
begin
CW_Test (Obj);
end;
|
generic
Size: Positive;
-- determines the size of the square
with function Represent(N: Natural) return String;
-- this turns a number into a string to be printed
-- the length of the output should not change
-- e.g., Represent(N) may return " #" if N is a prime
-- and " " else
with procedure Put_String(S: String);
-- outputs a string, no new line
with procedure New_Line;
-- the name says all
package Generic_Ulam is
procedure Print_Spiral;
-- calls Put_String(Represent(I)) N^2 times
-- and New_Line N times
end Generic_Ulam;
|
with agar.core.event;
with agar.core.event_types;
with agar.core.tail_queue;
with agar.core.timeout;
with agar.core.types;
with agar.gui.surface;
with agar.gui.widget.label;
with agar.gui.widget.menu;
with agar.gui.widget.scrollbar;
with agar.gui.window;
package agar.gui.widget.tlist is
use type c.unsigned;
type popup_t is limited private;
type popup_access_t is access all popup_t;
pragma convention (c, popup_access_t);
type item_t is limited private;
type item_access_t is access all item_t;
pragma convention (c, item_access_t);
type tlist_t is limited private;
type tlist_access_t is access all tlist_t;
pragma convention (c, tlist_access_t);
package popup_tail_queue is new agar.core.tail_queue
(entry_type => popup_access_t);
package item_tail_queue is new agar.core.tail_queue
(entry_type => item_access_t);
package tlist_tail_queue is new agar.core.tail_queue
(entry_type => tlist_access_t);
type flags_t is new c.unsigned;
TLIST_MULTI : constant flags_t := 16#001#;
TLIST_MULTITOGGLE : constant flags_t := 16#002#;
TLIST_POLL : constant flags_t := 16#004#;
TLIST_TREE : constant flags_t := 16#010#;
TLIST_HFILL : constant flags_t := 16#020#;
TLIST_VFILL : constant flags_t := 16#040#;
TLIST_NOSELSTATE : constant flags_t := 16#100#;
TLIST_EXPAND : constant flags_t := TLIST_HFILL or TLIST_VFILL;
-- API
function allocate
(parent : widget_access_t;
flags : flags_t) return tlist_access_t;
pragma import (c, allocate, "AG_TlistNew");
function allocate_polled
(parent : widget_access_t;
flags : flags_t;
callback : agar.core.event.callback_t) return tlist_access_t;
pragma import (c, allocate_polled, "AG_TlistNewPolled");
procedure set_item_height
(tlist : tlist_access_t;
height : natural);
pragma inline (set_item_height);
procedure set_icon
(tlist : tlist_access_t;
item : item_access_t;
icon : agar.gui.surface.surface_access_t);
pragma import (c, set_icon, "AG_TlistSetIcon");
procedure size_hint
(tlist : tlist_access_t;
text : string;
num_items : natural);
pragma inline (size_hint);
procedure size_hint_pixels
(tlist : tlist_access_t;
width : natural;
num_items : natural);
pragma inline (size_hint_pixels);
procedure size_hint_largest
(tlist : tlist_access_t;
num_items : natural);
pragma inline (size_hint_largest);
procedure set_double_click_callback
(tlist : tlist_access_t;
callback : agar.core.event.callback_t);
pragma inline (set_double_click_callback);
procedure set_changed_callback
(tlist : tlist_access_t;
callback : agar.core.event.callback_t);
pragma inline (set_changed_callback);
-- manipulating items
procedure delete
(tlist : tlist_access_t;
item : item_access_t);
pragma import (c, delete, "AG_TlistDel");
procedure list_begin (tlist : tlist_access_t);
pragma import (c, list_begin, "AG_TlistClear");
procedure list_end (tlist : tlist_access_t);
pragma import (c, list_end, "AG_TlistRestore");
procedure list_select
(tlist : tlist_access_t;
item : item_access_t);
pragma import (c, list_select, "AG_TlistSelect");
procedure list_select_all (tlist : tlist_access_t);
pragma import (c, list_select_all, "AG_TlistSelectAll");
procedure list_deselect
(tlist : tlist_access_t;
item : item_access_t);
pragma import (c, list_deselect, "AG_TlistDeselect");
procedure list_deselect_all (tlist : tlist_access_t);
pragma import (c, list_deselect_all, "AG_TlistDeselectAll");
function list_select_pointer
(tlist : tlist_access_t;
pointer : agar.core.types.void_ptr_t) return item_access_t;
pragma import (c, list_select_pointer, "AG_TlistSelectPtr");
function list_select_text
(tlist : tlist_access_t;
text : string) return item_access_t;
pragma inline (list_select_text);
function list_find_by_index
(tlist : tlist_access_t;
index : integer) return item_access_t;
pragma inline (list_find_by_index);
function list_selected_item (tlist : tlist_access_t) return item_access_t;
pragma import (c, list_selected_item, "AG_TlistSelectedItem");
function list_selected_item_pointer (tlist : tlist_access_t) return agar.core.types.void_ptr_t;
pragma import (c, list_selected_item_pointer, "AG_TlistSelectedItemPtr");
function list_first (tlist : tlist_access_t) return item_access_t;
pragma import (c, list_first, "AG_TlistFirstItem");
function list_last (tlist : tlist_access_t) return item_access_t;
pragma import (c, list_last, "AG_TlistLastItem");
-- popup menus
function set_popup_callback
(tlist : tlist_access_t;
callback : agar.core.event.callback_t) return agar.gui.widget.menu.item_access_t;
pragma inline (set_popup_callback);
function set_popup
(tlist : tlist_access_t;
category : string) return agar.gui.widget.menu.item_access_t;
pragma inline (set_popup);
--
function widget (tlist : tlist_access_t) return widget_access_t;
pragma inline (widget);
private
type popup_t is record
class : cs.chars_ptr;
menu : agar.gui.widget.menu.menu_access_t;
item : agar.gui.widget.menu.item_access_t;
panel : agar.gui.window.window_access_t;
popups : popup_tail_queue.entry_t;
end record;
pragma convention (c, popup_t);
type item_label_t is array (1 .. agar.gui.widget.label.max) of aliased c.char;
pragma convention (c, item_label_t);
type item_argv_t is array (1 .. 8) of aliased agar.core.event_types.arg_t;
pragma convention (c, item_argv_t);
type item_t is record
selected : c.int;
icon_source : agar.gui.surface.surface_access_t;
icon : c.int;
ptr : agar.core.types.void_ptr_t;
category : cs.chars_ptr;
text : item_label_t;
label : c.int;
argv : item_argv_t;
argc : c.int;
depth : agar.core.types.uint8_t;
flags : agar.core.types.uint8_t;
items : item_tail_queue.entry_t;
selitems : item_tail_queue.entry_t;
end record;
pragma convention (c, item_t);
type tlist_t is record
widget : aliased widget_t;
flags : flags_t;
selected : agar.core.types.void_ptr_t;
hint_width : c.int;
hint_height : c.int;
space : c.int;
item_height : c.int;
icon_width : c.int;
double_clicked : agar.core.types.void_ptr_t;
items : item_tail_queue.head_t;
selitems : item_tail_queue.head_t;
num_items : c.int;
visible_items : c.int;
sbar : agar.gui.widget.scrollbar.scrollbar_access_t;
popups : item_tail_queue.head_t;
compare_func : access function (a, b : item_access_t) return c.int;
popup_ev : access agar.core.event.event_t;
changed_ev : access agar.core.event.event_t;
double_click_ev : access agar.core.event.event_t;
inc_to : agar.core.timeout.timeout_t;
dec_to : agar.core.timeout.timeout_t;
wheel_ticks : agar.core.types.uint32_t;
row_width : c.int;
r : agar.gui.rect.rect_t;
end record;
pragma convention (c, tlist_t);
end agar.gui.widget.tlist;
|
with Asis;
with League.Strings;
package Documentation_Generator.Database is
type Module_Information is tagged limited private;
type Module_Access is access all Module_Information;
type Compilation_Unit_Information is tagged limited private;
type Compilation_Unit_Access is access all Compilation_Unit_Information;
type Type_Information is tagged limited private;
type Type_Access is access all Type_Information;
------------------------
-- Module_Information --
------------------------
function Name
(Self : Module_Information'Class) return League.Strings.Universal_String;
-- Returns name of the module.
function Short_Description
(Self : Module_Information'Class) return League.Strings.Universal_String;
-- Returns short description of the module.
----------------------------------
-- Compilation_Unit_Information --
----------------------------------
function Name
(Self : Compilation_Unit_Information'Class)
return League.Strings.Universal_String;
-- Returns full name of the compilation unit.
----------------------
-- Type_Information --
----------------------
function Name
(Self : Type_Information'Class) return League.Strings.Universal_String;
-- Returns name of the type.
function Compilation_Unit
(Self : Type_Information'Class) return Compilation_Unit_Access;
-- Returns compilation unit in which type is declared.
function Module (Self : Type_Information'Class) return Module_Access;
-- Returns module to which specified type belongs.
function Description
(Self : Type_Information'Class) return League.Strings.Universal_String;
-- Returns description of the type.
------------------------
-- Global Supbrograms --
------------------------
function Create
(Name : League.Strings.Universal_String;
Short_Description : League.Strings.Universal_String) return Module_Access;
-- Creates new module.
function Create
(Unit : Asis.Compilation_Unit;
Module : not null Module_Access) return Compilation_Unit_Access;
-- Creates compilation unit and associate it with the specified module.
function Lookup
(Unit : Asis.Compilation_Unit) return Compilation_Unit_Access;
-- Lookup for compilation unit with the specified name. Creates new one if
-- not present.
function Lookup (Declaration : Asis.Element) return Type_Access;
-- Lookup for type declaration. Creates new one if not present.
procedure Iterate
(Process : not null access procedure (Module : not null Module_Access));
-- Iterate over all modules.
procedure Iterate
(Process : not null access procedure (The_Type : not null Type_Access));
-- Iterate over all type declarations.
private
type Module_Information is tagged limited record
Name : League.Strings.Universal_String;
Short_Description : League.Strings.Universal_String;
end record;
type Compilation_Unit_Information is tagged limited record
Module : Module_Access;
Unit : Asis.Compilation_Unit;
end record;
type Type_Information is tagged limited record
Element : Asis.Element;
end record;
end Documentation_Generator.Database;
|
-- { dg-do compile }
procedure pointer_array is
type Node;
type Node_Ptr is access Node;
type Node is array (1..10) of Node_Ptr;
procedure Process (N : Node_Ptr) is
begin
null;
end;
begin
null;
end;
|
with Ada.Directories,
Ada.Direct_IO,
Ada.Text_IO;
procedure Whole_File is
File_Name : String := "whole_file.adb";
File_Size : Natural := Natural (Ada.Directories.Size (File_Name));
subtype File_String is String (1 .. File_Size);
package File_String_IO is new Ada.Direct_IO (File_String);
File : File_String_IO.File_Type;
Contents : File_String;
begin
File_String_IO.Open (File, Mode => File_String_IO.In_File,
Name => File_Name);
File_String_IO.Read (File, Item => Contents);
File_String_IO.Close (File);
Ada.Text_IO.Put (Contents);
end Whole_File;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with GL.API;
package body GL.Fixed.Matrix is
procedure Apply_Frustum (Stack : Matrix_Stack;
Left, Right, Bottom, Top, Near, Far : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Frustum (Left, Right, Bottom, Top, Near, Far);
Raise_Exception_On_OpenGL_Error;
end Apply_Frustum;
procedure Apply_Orthogonal (Stack : Matrix_Stack;
Left, Right, Bottom, Top, Near, Far : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Ortho (Left, Right, Bottom, Top, Near, Far);
Raise_Exception_On_OpenGL_Error;
end Apply_Orthogonal;
procedure Load_Identity (Stack : Matrix_Stack) is
begin
API.Matrix_Mode (Stack.Mode);
API.Load_Identity;
Raise_Exception_On_OpenGL_Error;
end Load_Identity;
procedure Load_Matrix (Stack : Matrix_Stack; Value : Matrix4) is
begin
API.Matrix_Mode (Stack.Mode);
API.Load_Matrix (Value);
Raise_Exception_On_OpenGL_Error;
end Load_Matrix;
procedure Apply_Multiplication (Stack : Matrix_Stack; Factor : Matrix4) is
begin
API.Matrix_Mode (Stack.Mode);
API.Mult_Matrix (Factor);
Raise_Exception_On_OpenGL_Error;
end Apply_Multiplication;
procedure Apply_Multiplication (Stack : Matrix_Stack; Factor : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Mult_Matrix (Identity4 * Factor);
Raise_Exception_On_OpenGL_Error;
end Apply_Multiplication;
procedure Push (Stack : Matrix_Stack) is
begin
API.Matrix_Mode (Stack.Mode);
API.Push_Matrix;
Raise_Exception_On_OpenGL_Error;
end Push;
procedure Pop (Stack : Matrix_Stack) is
begin
API.Matrix_Mode (Stack.Mode);
API.Pop_Matrix;
Raise_Exception_On_OpenGL_Error;
end Pop;
procedure Apply_Rotation (Stack : Matrix_Stack; Angle : Double;
Axis : Vector3) is
begin
API.Matrix_Mode (Stack.Mode);
API.Rotate (Angle, Axis (X), Axis (Y), Axis (Z));
Raise_Exception_On_OpenGL_Error;
end Apply_Rotation;
procedure Apply_Rotation (Stack : Matrix_Stack; Angle, X, Y, Z : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Rotate (Angle, X, Y, Z);
Raise_Exception_On_OpenGL_Error;
end Apply_Rotation;
procedure Apply_Scaling (Stack : Matrix_Stack; X, Y, Z : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Scale (X, Y, Z);
Raise_Exception_On_OpenGL_Error;
end Apply_Scaling;
procedure Apply_Translation (Stack : Matrix_Stack; Along : Vector3) is
begin
API.Matrix_Mode (Stack.Mode);
API.Translate (Along (X), Along (Y), Along (Z));
Raise_Exception_On_OpenGL_Error;
end Apply_Translation;
procedure Apply_Translation (Stack : Matrix_Stack; X, Y, Z : Double) is
begin
API.Matrix_Mode (Stack.Mode);
API.Translate (X, Y, Z);
Raise_Exception_On_OpenGL_Error;
end Apply_Translation;
end GL.Fixed.Matrix;
|
-----------------------------------------------------------------------
-- awa-mail-clients-files -- Mail client dump/file implementation
-- Copyright (C) 2012, 2014, 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.Strings.Unbounded;
with Util.Properties;
with Util.Concurrent.Counters;
-- The <b>AWA.Mail.Clients.Files</b> package provides a dump implementation of the
-- mail client interfaces on top of raw system files.
package AWA.Mail.Clients.Files is
NAME : constant String := "file";
-- ------------------------------
-- Mail Message
-- ------------------------------
-- The <b>File_Mail_Message</b> represents a mail message that is written on a file in
-- in specific directory.
type File_Mail_Message is new Mail_Message with private;
type File_Mail_Message_Access is access all File_Mail_Message'Class;
-- Set the <tt>From</tt> part of the message.
overriding
procedure Set_From (Message : in out File_Mail_Message;
Name : in String;
Address : in String);
-- Add a recipient for the message.
overriding
procedure Add_Recipient (Message : in out File_Mail_Message;
Kind : in Recipient_Type;
Name : in String;
Address : in String);
-- Set the subject of the message.
overriding
procedure Set_Subject (Message : in out File_Mail_Message;
Subject : in String);
-- Set the body of the message.
overriding
procedure Set_Body (Message : in out File_Mail_Message;
Content : in Unbounded_String;
Alternative : in Unbounded_String;
Content_Type : in String);
-- Add an attachment with the given content.
overriding
procedure Add_Attachment (Message : in out File_Mail_Message;
Content : in Unbounded_String;
Content_Id : in String;
Content_Type : in String);
overriding
procedure Add_File_Attachment (Message : in out File_Mail_Message;
Filename : in String;
Content_Id : in String;
Content_Type : in String);
-- Send the email message.
overriding
procedure Send (Message : in out File_Mail_Message);
-- ------------------------------
-- Mail Manager
-- ------------------------------
-- The <b>Mail_Manager</b> is the entry point to create a new mail message
-- and be able to send it.
type File_Mail_Manager is limited new Mail_Manager with private;
type File_Mail_Manager_Access is access all File_Mail_Manager'Class;
-- Create a file based mail manager and configure it according to the properties.
function Create_Manager (Props : in Util.Properties.Manager'Class) return Mail_Manager_Access;
-- Create a new mail message.
overriding
function Create_Message (Manager : in File_Mail_Manager) return Mail_Message_Access;
private
type File_Mail_Message is new Mail_Message with record
Manager : File_Mail_Manager_Access;
From : Ada.Strings.Unbounded.Unbounded_String;
To : Ada.Strings.Unbounded.Unbounded_String;
Cc : Ada.Strings.Unbounded.Unbounded_String;
Bcc : Ada.Strings.Unbounded.Unbounded_String;
Subject : Ada.Strings.Unbounded.Unbounded_String;
Message : Ada.Strings.Unbounded.Unbounded_String;
Html : Ada.Strings.Unbounded.Unbounded_String;
Attachments : Ada.Strings.Unbounded.Unbounded_String;
end record;
type File_Mail_Manager is limited new Mail_Manager with record
Self : File_Mail_Manager_Access;
Path : Ada.Strings.Unbounded.Unbounded_String;
Index : Util.Concurrent.Counters.Counter;
end record;
end AWA.Mail.Clients.Files;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2019, Daniel King
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * The name of the copyright holder may not be used to endorse or promote
-- Products derived from this software without specific prior written
-- permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with Keccak.Keccak_1600.Rounds_12;
with Keccak.Generic_Parallel_Sponge;
with Keccak.Padding;
pragma Elaborate_All (Keccak.Generic_Parallel_Sponge);
package Keccak.Parallel_Keccak_1600.Rounds_12
with SPARK_Mode => On
is
procedure Permute_All_P2 is new KeccakF_1600_P2.Permute_All
(First_Round => 12,
Num_Rounds => 12);
procedure Permute_All_P4 is new KeccakF_1600_P4.Permute_All
(Permute_All_P2);
procedure Permute_All_P8 is new KeccakF_1600_P8.Permute_All
(Permute_All_P2);
package Parallel_Sponge_P2 is new Keccak.Generic_Parallel_Sponge
(State_Size => 1600,
State_Type => KeccakF_1600_P2.Parallel_State,
Parallelism => 2,
Init => KeccakF_1600_P2.Init,
Permute_All => Permute_All_P2,
XOR_Bits_Into_State_Separate => KeccakF_1600_P2.XOR_Bits_Into_State_Separate,
XOR_Bits_Into_State_All => KeccakF_1600_P2.XOR_Bits_Into_State_All,
Extract_Bytes => KeccakF_1600_P2.Extract_Bytes,
Pad => Keccak.Padding.Pad101_Single_Block,
Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits);
package Parallel_Sponge_P4 is new Keccak.Generic_Parallel_Sponge
(State_Size => 1600,
State_Type => KeccakF_1600_P4.Parallel_State,
Parallelism => 4,
Init => KeccakF_1600_P4.Init,
Permute_All => Permute_All_P4,
XOR_Bits_Into_State_Separate => KeccakF_1600_P4.XOR_Bits_Into_State_Separate,
XOR_Bits_Into_State_All => KeccakF_1600_P4.XOR_Bits_Into_State_All,
Extract_Bytes => KeccakF_1600_P4.Extract_Bytes,
Pad => Keccak.Padding.Pad101_Single_Block,
Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits);
package Parallel_Sponge_P8 is new Keccak.Generic_Parallel_Sponge
(State_Size => 1600,
State_Type => KeccakF_1600_P8.Parallel_State,
Parallelism => 8,
Init => KeccakF_1600_P8.Init,
Permute_All => Permute_All_P8,
XOR_Bits_Into_State_Separate => KeccakF_1600_P8.XOR_Bits_Into_State_Separate,
XOR_Bits_Into_State_All => KeccakF_1600_P8.XOR_Bits_Into_State_All,
Extract_Bytes => KeccakF_1600_P8.Extract_Bytes,
Pad => Keccak.Padding.Pad101_Single_Block,
Min_Padding_Bits => Keccak.Padding.Pad101_Min_Bits);
end Keccak.Parallel_Keccak_1600.Rounds_12;
|
with Interfaces; use Interfaces;
with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
with STM32.USARTs; use STM32.USARTs;
with Ringbuffers;
package Serial_IO is
package FIFO_Package is new Ringbuffers (256, Unsigned_8);
subtype FIFO is FIFO_Package.Ringbuffer;
protected type Serial_Port_Controller
is
procedure Init (Baud_Rate : Baud_Rates);
function Available return Boolean;
procedure Read (Result : out Unsigned_8);
-- function Read return Unsigned_8;
procedure Write (Data : Unsigned_8);
private
procedure Interrupt_Handler;
pragma Attach_Handler (Interrupt_Handler, USART1_Interrupt);
Input : FIFO;
Output : FIFO;
Initialized : Boolean := False;
end Serial_Port_Controller;
Serial : Serial_Port_Controller;
end Serial_IO;
|
pragma License (Unrestricted);
-- optional runtime unit specialized for Windows
package System.Wide_Startup is
pragma Preelaborate;
pragma Linker_Options ("-municode");
wargc : Integer
with Export, Convention => C, External_Name => "__drake_wargc";
wargv : Address
with Export, Convention => C, External_Name => "__drake_wargv";
wenvp : Address
with Export, Convention => C, External_Name => "__drake_wenvp";
function wmain (argc : Integer; argv : Address; envp : Address)
return Integer
with Export, Convention => C, External_Name => "wmain";
end System.Wide_Startup;
|
procedure Hello is
begin
Put_Line ("Hello, world!");
end Hello;
|
-- This spec has been automatically generated from out.svd
pragma Restrictions (No_Elaboration_Code);
pragma Ada_2012;
pragma Style_Checks (Off);
with System;
package MSP430_SVD.INTERRUPTS is
pragma Preelaborate;
-----------------
-- Peripherals --
-----------------
type INTERRUPTS_Peripheral is record
end record
with Volatile;
for INTERRUPTS_Peripheral use record
end record;
INTERRUPTS_Periph : aliased _INTERRUPTS_Peripheral
with Import, Address => _INTERRUPTS_Base;
end MSP430_SVD.INTERRUPTS;
|
with GNAT.Command_Line; use GNAT.Command_Line;
with GNAT.IO; use GNAT.IO;
with GNAT.Traceback.Symbolic;
with Ada.Exceptions;
with Ada.Command_Line;
with Ada.Text_IO;
with Babel;
with Babel.Files;
with Ada.Directories;
with Ada.Strings.Unbounded;
with Util.Encoders;
with Util.Encoders.Base16;
with Util.Log.Loggers;
with Babel.Filters;
with Babel.Files.Buffers;
with Babel.Files.Queues;
with Babel.Stores.Local;
with Babel.Strategies.Default;
with Babel.Strategies.Workers;
with Babel.Base.Text;
with Babel.Base.Users;
with Babel.Streams;
with Babel.Streams.XZ;
with Babel.Streams.Cached;
with Babel.Streams.Files;
with Tar;
procedure babel_main is
use Ada.Strings.Unbounded;
Out_Dir : Ada.Strings.Unbounded.Unbounded_String;
Dir : Babel.Files.Directory_Type;
Hex_Encoder : Util.Encoders.Base16.Encoder;
Exclude : aliased Babel.Filters.Exclude_Directory_Filter_Type;
Local : aliased Babel.Stores.Local.Local_Store_Type;
Backup : aliased Babel.Strategies.Default.Default_Strategy_Type;
Buffers : aliased Babel.Files.Buffers.Buffer_Pool;
Store : aliased Babel.Stores.Local.Local_Store_Type;
Database : aliased Babel.Base.Text.Text_Database;
Queue : aliased Babel.Files.Queues.File_Queue;
Debug : Boolean := False;
Task_Count : Positive := 2;
--
-- procedure Print_Sha (Path : in String;
-- File : in out Babel.Files.File) is
-- Sha : constant String := Hex_Encoder.Transform (File.SHA1);
-- begin
-- Put_Line (Path & "/" & To_String (File.Name) & " => " & Sha);
-- end Print_Sha;
procedure Usage is
begin
Ada.Text_IO.Put_Line ("babel [-d] [-t count] {command} [options]");
Ada.Text_IO.Put_Line (" -d Debug mode");
Ada.Text_IO.Put_Line (" -t count Number of tasks to create");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("Commands:");
Ada.Text_IO.Put_Line (" copy <dst-dir> <src-dir>");
Ada.Text_IO.Put_Line (" scan <src-dir>");
Ada.Command_Line.Set_Exit_Status (2);
end Usage;
package Backup_Workers is
new Babel.Strategies.Workers (Babel.Strategies.Default.Default_Strategy_Type);
procedure Do_Backup (Count : in Positive) is
Workers : Backup_Workers.Worker_Type (Count);
Container : Babel.Files.Default_Container;
Dir_Queue : Babel.Files.Queues.Directory_Queue;
procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is
begin
Strategy.Set_Filters (Exclude'Unchecked_Access);
Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => Store'Unchecked_Access);
Strategy.Set_Buffers (Buffers'Unchecked_Access);
Strategy.Set_Queue (Queue'Unchecked_Access);
end Configure;
begin
Babel.Files.Queues.Add_Directory (Dir_Queue, Dir);
Configure (Backup);
Backup_Workers.Configure (Workers, Configure'Access);
Backup_Workers.Start (Workers);
Backup.Scan (Dir_Queue, Container);
Backup_Workers.Finish (Workers, Database);
end Do_Backup;
procedure Do_Copy is
Dst : constant String := GNAT.Command_Line.Get_Argument;
Src : constant String := GNAT.Command_Line.Get_Argument;
begin
Dir := Babel.Files.Allocate (Name => Src,
Dir => Babel.Files.NO_DIRECTORY);
Store.Set_Root_Directory (Dst);
Local.Set_Root_Directory ("");
Do_Backup (Task_Count);
Database.Save ("database.txt");
end Do_Copy;
procedure Do_Scan is
Src : constant String := GNAT.Command_Line.Get_Argument;
Workers : Backup_Workers.Worker_Type (Task_Count);
Container : Babel.Files.Default_Container;
Dir_Queue : Babel.Files.Queues.Directory_Queue;
procedure Configure (Strategy : in out Babel.Strategies.Default.Default_Strategy_Type) is
begin
Strategy.Set_Filters (Exclude'Unchecked_Access);
Strategy.Set_Stores (Read => Local'Unchecked_Access, Write => null);
Strategy.Set_Buffers (Buffers'Unchecked_Access);
Strategy.Set_Queue (Queue'Unchecked_Access);
end Configure;
begin
Dir := Babel.Files.Allocate (Name => Src,
Dir => Babel.Files.NO_DIRECTORY);
Local.Set_Root_Directory ("");
Babel.Files.Queues.Add_Directory (Dir_Queue, Dir);
Configure (Backup);
Backup_Workers.Configure (Workers, Configure'Access);
Backup_Workers.Start (Workers);
Backup.Scan (Dir_Queue, Container);
Backup_Workers.Finish (Workers, Database);
Database.Save ("database-scan.txt");
end Do_Scan;
begin
Util.Log.Loggers.Initialize ("babel.properties");
Initialize_Option_Scan (Stop_At_First_Non_Switch => True, Section_Delimiters => "targs");
-- Parse the command line
loop
case Getopt ("* v o: t:") is
when ASCII.NUL =>
exit;
when 'o' =>
Out_Dir := To_Unbounded_String (Parameter & "/");
when 'd' =>
Debug := True;
when 't' =>
Task_Count := Positive'Value (Parameter);
when '*' =>
exit;
when others =>
null;
end case;
end loop;
if Ada.Command_Line.Argument_Count = 0 then
Usage;
return;
end if;
Babel.Files.Buffers.Create_Pool (Into => Buffers, Count => 100, Size => 64 * 1024);
Store.Set_Buffers (Buffers'Unchecked_Access);
Local.Set_Buffers (Buffers'Unchecked_Access);
declare
Cmd_Name : constant String := Full_Switch;
begin
if Cmd_Name = "copy" then
Do_Copy;
elsif Cmd_Name = "scan" then
Do_Scan;
else
Usage;
end if;
end;
exception
when E : Invalid_Switch =>
Ada.Text_IO.Put_Line ("Invalid option: " & Ada.Exceptions.Exception_Message (E));
Usage;
when E : others =>
Ada.Text_IO.Put_Line (Ada.Exceptions.Exception_Message (E));
Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
Ada.Command_Line.Set_Exit_Status (1);
end babel_main;
|
with Ada.Text_IO;
with Ada.Exceptions;
with Text_IO; -- Old style
with Vole_Tokens;
with Vole_Goto;
with Vole_Shift_Reduce;
with vole_lex_dfa;
with kv.avm.Vole_Lex;
with kv.avm.Vole_Tree;
with kv.avm.Instructions;
with kv.avm.Registers;
use Ada.Text_IO;
use Ada.Exceptions;
use Text_IO; -- Old style
use Vole_Tokens;
use Vole_Goto;
use Vole_Shift_Reduce;
use vole_lex_dfa;
use kv.avm.Vole_Lex;
use kv.avm.Vole_Tree;
use kv.avm.Instructions;
use kv.avm.Registers;
package body kv.avm.vole_parser is
procedure YYError(Text : in String) is
begin
New_Line;
Put_Line("PARSE ERROR on line"&Positive'IMAGE(kv.avm.Vole_Lex.Line_Number)&" parsing '"&vole_lex_dfa.yytext&"'");
end YYError;
procedure YYParse is
-- Rename User Defined Packages to Internal Names.
package yy_goto_tables renames
Vole_Goto;
package yy_shift_reduce_tables renames
Vole_Shift_Reduce;
package yy_tokens renames
Vole_Tokens;
use yy_tokens, yy_goto_tables, yy_shift_reduce_tables;
procedure yyerrok;
procedure yyclearin;
package yy is
-- the size of the value and state stacks
stack_size : constant Natural := 300;
-- subtype rule is natural;
subtype parse_state is natural;
-- subtype nonterminal is integer;
-- encryption constants
default : constant := -1;
first_shift_entry : constant := 0;
accept_code : constant := -3001;
error_code : constant := -3000;
-- stack data used by the parser
tos : natural := 0;
value_stack : array(0..stack_size) of yy_tokens.yystype;
state_stack : array(0..stack_size) of parse_state;
-- current input symbol and action the parser is on
action : integer;
rule_id : rule;
input_symbol : yy_tokens.token;
-- error recovery flag
error_flag : natural := 0;
-- indicates 3 - (number of valid shifts after an error occurs)
look_ahead : boolean := true;
index : integer;
-- Is Debugging option on or off
DEBUG : boolean renames Verbose;
end yy;
function goto_state
(state : yy.parse_state;
sym : nonterminal) return yy.parse_state;
function parse_action
(state : yy.parse_state;
t : yy_tokens.token) return integer;
pragma inline(goto_state, parse_action);
function goto_state(state : yy.parse_state;
sym : nonterminal) return yy.parse_state is
index : integer;
begin
index := goto_offset(state);
while integer(goto_matrix(index).nonterm) /= sym loop
index := index + 1;
end loop;
return integer(goto_matrix(index).newstate);
end goto_state;
function parse_action(state : yy.parse_state;
t : yy_tokens.token) return integer is
index : integer;
tok_pos : integer;
default : constant integer := -1;
begin
tok_pos := yy_tokens.token'pos(t);
index := shift_reduce_offset(state);
while integer(shift_reduce_matrix(index).t) /= tok_pos and then
integer(shift_reduce_matrix(index).t) /= default
loop
index := index + 1;
end loop;
return integer(shift_reduce_matrix(index).act);
end parse_action;
-- error recovery stuff
procedure handle_error is
temp_action : integer;
begin
if yy.error_flag = 3 then -- no shift yet, clobber input.
if yy.debug then
text_io.put_line("Ayacc.YYParse: Error Recovery Clobbers " &
yy_tokens.token'image(yy.input_symbol));
end if;
if yy.input_symbol = yy_tokens.end_of_input then -- don't discard,
if yy.debug then
text_io.put_line("Ayacc.YYParse: Can't discard END_OF_INPUT, quiting...");
end if;
raise yy_tokens.syntax_error;
end if;
yy.look_ahead := true; -- get next token
return; -- and try again...
end if;
if yy.error_flag = 0 then -- brand new error
yyerror("Syntax Error");
end if;
yy.error_flag := 3;
-- find state on stack where error is a valid shift --
if yy.debug then
text_io.put_line("Ayacc.YYParse: Looking for state with error as valid shift");
end if;
loop
if yy.debug then
text_io.put_line("Ayacc.YYParse: Examining State " &
yy.parse_state'image(yy.state_stack(yy.tos)));
end if;
temp_action := parse_action(yy.state_stack(yy.tos), error);
if temp_action >= yy.first_shift_entry then
if yy.tos = yy.stack_size then
text_io.put_line(" Stack size exceeded on state_stack");
raise yy_Tokens.syntax_error;
end if;
yy.tos := yy.tos + 1;
yy.state_stack(yy.tos) := temp_action;
exit;
end if;
Decrement_Stack_Pointer :
begin
yy.tos := yy.tos - 1;
exception
when Constraint_Error =>
yy.tos := 0;
end Decrement_Stack_Pointer;
if yy.tos = 0 then
if yy.debug then
text_io.put_line("Ayacc.YYParse: Error recovery popped entire stack, aborting...");
end if;
raise yy_tokens.syntax_error;
end if;
end loop;
if yy.debug then
text_io.put_line("Ayacc.YYParse: Shifted error token in state " &
yy.parse_state'image(yy.state_stack(yy.tos)));
end if;
end handle_error;
-- print debugging information for a shift operation
procedure shift_debug(state_id: yy.parse_state; lexeme: yy_tokens.token) is
begin
text_io.put_line("Ayacc.YYParse: Shift "& yy.parse_state'image(state_id)&" on input symbol "&
yy_tokens.token'image(lexeme) );
end;
-- print debugging information for a reduce operation
procedure reduce_debug(rule_id: rule; state_id: yy.parse_state) is
begin
text_io.put_line("Ayacc.YYParse: Reduce by rule "&rule'image(rule_id)&" goto state "&
yy.parse_state'image(state_id));
end;
-- make the parser believe that 3 valid shifts have occured.
-- used for error recovery.
procedure yyerrok is
begin
yy.error_flag := 0;
end yyerrok;
-- called to clear input symbol that caused an error.
procedure yyclearin is
begin
-- yy.input_symbol := yylex;
yy.look_ahead := true;
end yyclearin;
begin
-- initialize by pushing state 0 and getting the first input symbol
yy.state_stack(yy.tos) := 0;
loop
yy.index := shift_reduce_offset(yy.state_stack(yy.tos));
if integer(shift_reduce_matrix(yy.index).t) = yy.default then
yy.action := integer(shift_reduce_matrix(yy.index).act);
else
if yy.look_ahead then
yy.look_ahead := false;
yy.input_symbol := yylex;
end if;
yy.action :=
parse_action(yy.state_stack(yy.tos), yy.input_symbol);
end if;
if yy.action >= yy.first_shift_entry then -- SHIFT
if yy.debug then
shift_debug(yy.action, yy.input_symbol);
end if;
-- Enter new state
if yy.tos = yy.stack_size then
text_io.put_line(" Stack size exceeded on state_stack");
raise yy_Tokens.syntax_error;
end if;
yy.tos := yy.tos + 1;
yy.state_stack(yy.tos) := yy.action;
yy.value_stack(yy.tos) := yylval;
if yy.error_flag > 0 then -- indicate a valid shift
yy.error_flag := yy.error_flag - 1;
end if;
-- Advance lookahead
yy.look_ahead := true;
elsif yy.action = yy.error_code then -- ERROR
handle_error;
elsif yy.action = yy.accept_code then
if yy.debug then
text_io.put_line("Ayacc.YYParse: Accepting Grammar...");
end if;
exit;
else -- Reduce Action
-- Convert action into a rule
yy.rule_id := -1 * yy.action;
-- Execute User Action
-- user_action(yy.rule_id);
case yy.rule_id is
when 1 =>
--#line 64
Build_Program(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
Save_Program(
yyval.Node);
when 4 =>
--#line 76
Put_Line("unimp 01");
when 5 =>
--#line 80
Put_Line("unimp 02");
when 6 =>
--#line 84
Put_Line("unimp 03");
when 7 =>
--#line 89
yyval.Node :=
yy.value_stack(yy.tos-2).Node; -- Copy up
yy.value_stack(yy.tos-2).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 8 =>
--#line 97
yyval.Node := null;
when 9 =>
--#line 98
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 10 =>
--#line 103
Build_Actor_Node(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-4).Node,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos-1).Node);
when 11 =>
--#line 105
Build_Actor_Node(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-6).Node,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos-4).Node);
when 12 =>
--#line 109
yyval.Node := null;
when 13 =>
--#line 110
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 14 =>
--#line 115
yyval.Node :=
yy.value_stack(yy.tos-1).Node; -- Copy up
yy.value_stack(yy.tos-1).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 15 =>
--#line 123
Build_Attribute(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node);
when 16 =>
--#line 124
Build_Attribute(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 17 =>
--#line 128
Build_Kind(
yyval.Node, Line_Number, Bit_Or_Boolean);
when 18 =>
--#line 129
Build_Kind(
yyval.Node, Line_Number, Bit_Or_Boolean,
yy.value_stack(yy.tos-1).Node);
when 19 =>
--#line 133
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 20 =>
--#line 134
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 21 =>
--#line 135
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 22 =>
--#line 136
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 23 =>
--#line 137
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 24 =>
--#line 138
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 25 =>
--#line 139
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 26 =>
--#line 144
Build_Kind(
yyval.Node, Line_Number, Signed_Integer);
when 27 =>
--#line 146
Build_Kind(
yyval.Node, Line_Number, Signed_Integer,
yy.value_stack(yy.tos).Node);
when 28 =>
--#line 151
Build_Kind(
yyval.Node, Line_Number, Unsigned_Integer);
when 29 =>
--#line 153
Build_Kind(
yyval.Node, Line_Number, Unsigned_Integer,
yy.value_stack(yy.tos).Node);
when 30 =>
--#line 157
Put_Line("unimp 06");
when 31 =>
--#line 158
Put_Line("unimp 07");
when 32 =>
--#line 162
Put_Line("unimp 08");
when 33 =>
--#line 163
Build_Kind(
yyval.Node, Line_Number, Immutable_String,
yy.value_stack(yy.tos).Node);
when 34 =>
--#line 168
Build_Kind(
yyval.Node, Line_Number, Actor_Definition);
when 35 =>
--#line 170
Build_Kind(
yyval.Node, Line_Number, Actor_Definition,
yy.value_stack(yy.tos).Node);
when 36 =>
--#line 172
Build_Kind(
yyval.Node, Line_Number, Actor_Definition, New_Constructor_Send(
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node));
when 37 =>
--#line 176
Put_Line("unimp 10");
when 38 =>
--#line 177
Put_Line("unimp 11");
when 39 =>
--#line 182
Build_Kind(
yyval.Node, Line_Number, Bit_Or_Boolean);
when 40 =>
--#line 184
Build_Kind(
yyval.Node, Line_Number, Bit_Or_Boolean,
yy.value_stack(yy.tos).Node);
when 41 =>
--#line 190
Build_Kind(
yyval.Node, Line_Number, Signed_Integer);
when 42 =>
--#line 192
Build_Kind(
yyval.Node, Line_Number, Unsigned_Integer);
when 43 =>
--#line 194
Build_Kind(
yyval.Node, Line_Number, Floatingpoint);
when 44 =>
--#line 196
Build_Kind(
yyval.Node, Line_Number, Actor_Definition);
when 45 =>
--#line 198
Build_Kind(
yyval.Node, Line_Number, Tuple);
when 46 =>
--#line 200
Build_Kind(
yyval.Node, Line_Number, Immutable_String);
when 47 =>
--#line 205
yyval.Node :=
yy.value_stack(yy.tos-2).Node; -- Copy up
yy.value_stack(yy.tos-2).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 48 =>
--#line 213
yyval.Node := null;
when 49 =>
--#line 214
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 50 =>
--#line 219
Build_Message(
yyval.Node, Line_Number, True,
yy.value_stack(yy.tos-4).Node,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node, null);
when 51 =>
--#line 221
Build_Message(
yyval.Node, Line_Number, True,
yy.value_stack(yy.tos-4).Node,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node,
yy.value_stack(yy.tos-6).Node);
when 52 =>
--#line 223
Build_Message(
yyval.Node, Line_Number, False,
yy.value_stack(yy.tos-4).Node,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node, null);
when 53 =>
--#line 225
Build_Constructor(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 54 =>
--#line 230
yyval.Node :=
yy.value_stack(yy.tos-1).Node;
when 55 =>
--#line 234
yyval.Node := null;
when 56 =>
--#line 235
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 57 =>
--#line 240
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 58 =>
--#line 242
yyval.Node :=
yy.value_stack(yy.tos-2).Node; -- Copy up
yy.value_stack(yy.tos-2).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 59 =>
--#line 251
Build_Arg(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 60 =>
--#line 256
Build_Id_Node(
yyval.Node, Line_Number, yytext);
when 61 =>
--#line 260
yyval.Node :=
yy.value_stack(yy.tos-1).Node;
when 62 =>
--#line 264
yyval.Node := null;
when 63 =>
--#line 265
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 64 =>
--#line 270
yyval.Node :=
yy.value_stack(yy.tos-2).Node; -- Copy up
yy.value_stack(yy.tos-2).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 65 =>
--#line 278
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 66 =>
--#line 279
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 67 =>
--#line 280
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 68 =>
--#line 281
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 69 =>
--#line 282
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 70 =>
--#line 283
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 71 =>
--#line 284
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 72 =>
--#line 285
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 73 =>
--#line 289
Build_While(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 74 =>
--#line 290
Build_While(
yyval.Node, Line_Number, null,
yy.value_stack(yy.tos).Node);
when 75 =>
--#line 294
Build_Assert(
yyval.Node, Line_Number,
yy.value_stack(yy.tos).Node);
when 76 =>
--#line 298
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 77 =>
--#line 302
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 78 =>
--#line 303
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 79 =>
--#line 307
Build_If(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-4).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 80 =>
--#line 311
yyval.Node := null;
when 81 =>
--#line 312
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 82 =>
--#line 313
Build_If(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-5).Node,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos-1).Node);
when 83 =>
--#line 317
Build_Return(
yyval.Node, Line_Number,
yy.value_stack(yy.tos).Node);
when 84 =>
--#line 321
yyval.Node := null;
when 85 =>
--#line 322
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 86 =>
--#line 323
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 87 =>
--#line 324
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 88 =>
--#line 325
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 89 =>
--#line 326
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 90 =>
--#line 331
yyval.Node :=
yy.value_stack(yy.tos-1).Node;
when 91 =>
--#line 335
Put_Line("unimp 30");
when 92 =>
--#line 340
Put_Line("unimp 29");
when 93 =>
--#line 344
Build_Send_Statement(
yyval.Node, Line_Number, Self, null,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 94 =>
--#line 348
Build_Send_Statement(
yyval.Node, Line_Number, Actor,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 95 =>
--#line 352
Build_Call_Statement(
yyval.Node, Line_Number, Self, null,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 96 =>
--#line 356
Build_Call_Statement(
yyval.Node, Line_Number, Super, null,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 97 =>
--#line 360
Build_Call_Statement(
yyval.Node, Line_Number, Actor,
yy.value_stack(yy.tos-3).Node,
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node);
when 98 =>
--#line 364
Build_Assignment(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 99 =>
--#line 365
Raise_Exception(Unimplemented_Error'IDENTITY, "Rule statement_assign (tuple)");
when 100 =>
--#line 369
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 101 =>
--#line 370
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 102 =>
--#line 371
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 103 =>
--#line 372
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 104 =>
--#line 376
Build_Op_Expression(
yyval.Node, Line_Number, Op_Pos, null,
yy.value_stack(yy.tos).Node);
when 105 =>
--#line 380
Build_Kind(
yyval.Node, Line_Number, Actor_Definition, New_Constructor_Send(
yy.value_stack(yy.tos-1).Node,
yy.value_stack(yy.tos).Node));
when 106 =>
--#line 385
Build_Var_Expression(
yyval.Node, Line_Number, True,
yy.value_stack(yy.tos).Node);
when 107 =>
--#line 387
Build_Var_Expression(
yyval.Node, Line_Number, False,
yy.value_stack(yy.tos).Node);
when 108 =>
--#line 391
Put_Line("unimp 35");
when 109 =>
--#line 392
Put_Line("unimp 36");
when 110 =>
--#line 393
Put_Line("unimp 37");
when 111 =>
--#line 394
Put_Line("unimp 38");
when 112 =>
--#line 398
yyval.Node := null;
when 113 =>
--#line 400
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 114 =>
--#line 405
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 115 =>
--#line 407
yyval.Node :=
yy.value_stack(yy.tos-2).Node; -- Copy up
yy.value_stack(yy.tos-2).Node := null; -- Only keep one reference to this node.
Add_Next(
yyval.Node,
yy.value_stack(yy.tos).Node);
when 116 =>
--#line 415
Build_Op_Expression(
yyval.Node, Line_Number, Add,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 117 =>
--#line 416
Build_Op_Expression(
yyval.Node, Line_Number, Sub,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 118 =>
--#line 417
Build_Op_Expression(
yyval.Node, Line_Number, Mul,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 119 =>
--#line 418
Build_Op_Expression(
yyval.Node, Line_Number, Div,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 120 =>
--#line 419
Build_Op_Expression(
yyval.Node, Line_Number, Modulo,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 121 =>
--#line 420
Build_Op_Expression(
yyval.Node, Line_Number, Exp,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 122 =>
--#line 421
Build_Op_Expression(
yyval.Node, Line_Number, Eq,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 123 =>
--#line 422
Build_Op_Expression(
yyval.Node, Line_Number, Neq,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 124 =>
--#line 423
Build_Op_Expression(
yyval.Node, Line_Number, L_t,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 125 =>
--#line 424
Build_Op_Expression(
yyval.Node, Line_Number, Lte,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 126 =>
--#line 425
Build_Op_Expression(
yyval.Node, Line_Number, G_t,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 127 =>
--#line 426
Build_Op_Expression(
yyval.Node, Line_Number, Gte,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 128 =>
--#line 427
Build_Op_Expression(
yyval.Node, Line_Number, Shift_Left,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 129 =>
--#line 428
Build_Op_Expression(
yyval.Node, Line_Number, Shift_Right,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 130 =>
--#line 429
Build_Op_Expression(
yyval.Node, Line_Number, B_And,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 131 =>
--#line 430
Build_Op_Expression(
yyval.Node, Line_Number, B_Or ,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 132 =>
--#line 431
Build_Op_Expression(
yyval.Node, Line_Number, B_Xor,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 133 =>
--#line 432
yyval.Node :=
yy.value_stack(yy.tos-1).Node;
when 134 =>
--#line 433
Build_Op_Expression(
yyval.Node, Line_Number, Negate,
yy.value_stack(yy.tos).Node);
when 135 =>
--#line 434
Build_Op_Expression(
yyval.Node, Line_Number, Op_Neg,
yy.value_stack(yy.tos).Node);
when 136 =>
--#line 435
Build_Op_Expression(
yyval.Node, Line_Number, Op_Pos,
yy.value_stack(yy.tos).Node);
when 137 =>
--#line 436
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 138 =>
--#line 437
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 139 =>
--#line 441
Build_Literal_Expression(
yyval.Node, Line_Number, Signed_Integer, yytext);
when 140 =>
--#line 442
Build_Literal_Expression(
yyval.Node, Line_Number, Floatingpoint, yytext);
when 141 =>
--#line 443
Build_Literal_Expression(
yyval.Node, Line_Number, Immutable_String, yytext);
when 142 =>
--#line 444
yyval.Node :=
yy.value_stack(yy.tos).Node;
when 143 =>
--#line 448
Build_Literal_Expression(
yyval.Node, Line_Number, Bit_Or_Boolean, yytext);
when 144 =>
--#line 449
Build_Literal_Expression(
yyval.Node, Line_Number, Bit_Or_Boolean, yytext);
when 145 =>
--#line 454
Build_Var_Def(
yyval.Node, Line_Number,
yy.value_stack(yy.tos-2).Node,
yy.value_stack(yy.tos).Node);
when 146 =>
--#line 458
Build_Emit(
yyval.Node, Line_Number,
yy.value_stack(yy.tos).Node);
when others => null;
end case;
-- Pop RHS states and goto next state
yy.tos := yy.tos - rule_length(yy.rule_id) + 1;
if yy.tos > yy.stack_size then
text_io.put_line(" Stack size exceeded on state_stack");
raise yy_Tokens.syntax_error;
end if;
yy.state_stack(yy.tos) := goto_state(yy.state_stack(yy.tos-1) ,
get_lhs_rule(yy.rule_id));
yy.value_stack(yy.tos) := yyval;
if yy.debug then
reduce_debug(yy.rule_id,
goto_state(yy.state_stack(yy.tos - 1),
get_lhs_rule(yy.rule_id)));
end if;
end if;
end loop;
end yyparse;
end kv.avm.vole_parser;
|
-----------------------------------------------------------------------
-- awa-tags-modules-tests -- Unit tests for tags module
-- Copyright (C) 2013, 2018 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Util.Test_Caller;
with Util.Beans.Basic;
with Util.Beans.Objects;
with Security.Contexts;
with AWA.Users.Models;
with AWA.Services.Contexts;
with AWA.Tests.Helpers.Users;
with AWA.Tags.Beans;
package body AWA.Tags.Modules.Tests is
package Caller is new Util.Test_Caller (Test, "Tags.Modules");
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access;
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Add_Tag",
Test_Add_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Remove_Tag",
Test_Remove_Tag'Access);
Caller.Add_Test (Suite, "Test AWA.Tags.Modules.Update_Tags",
Test_Remove_Tag'Access);
end Add_Tests;
function Create_Tag_List_Bean (Module : in Tag_Module_Access)
return AWA.Tags.Beans.Tag_List_Bean_Access is
Bean : constant Util.Beans.Basic.Readonly_Bean_Access
:= AWA.Tags.Beans.Create_Tag_List_Bean (Module);
begin
return AWA.Tags.Beans.Tag_List_Bean'Class (Bean.all)'Access;
end Create_Tag_List_Bean;
-- ------------------------------
-- Test tag creation.
-- ------------------------------
procedure Test_Add_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-add-tag@test.com");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
-- Create a tag.
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Add_Tag;
-- ------------------------------
-- Test tag removal.
-- ------------------------------
procedure Test_Remove_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-tag@test.com");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Add_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-3");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-2");
Tag_Manager.Remove_Tag (User.Get_Id, "awa_user", "workspaces-create", "user-tag-1");
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Remove_Tag;
-- ------------------------------
-- Test tag creation and removal.
-- ------------------------------
procedure Test_Update_Tag (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-tag@test.com");
declare
Tag_Manager : constant Tag_Module_Access := Get_Tag_Module;
User : constant AWA.Users.Models.User_Ref := Context.Get_User;
List : AWA.Tags.Beans.Tag_List_Bean_Access;
Cleanup : Util.Beans.Objects.Object;
Tags : Util.Strings.Vectors.Vector;
begin
T.Assert (Tag_Manager /= null, "There is no tag module");
List := Create_Tag_List_Bean (Tag_Manager);
Cleanup := Util.Beans.Objects.To_Object (List.all'Access);
List.Set_Value ("entity_type", Util.Beans.Objects.To_Object (String '("awa_user")));
List.Set_Value ("permission",
Util.Beans.Objects.To_Object (String '("workspace-create")));
-- Add 3 tags.
Tags.Append ("user-tag-1");
Tags.Append ("user-tag-2");
Tags.Append ("user-tag-3");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- Load the list.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 3, Integer (List.Get_Count), "Invalid number of tags");
-- Remove a tag that was not created.
Tags.Append ("user-tag-4");
List.Set_Deleted (Tags);
Tags.Clear;
Tags.Append ("user-tag-5");
List.Set_Added (Tags);
List.Update_Tags (User.Get_Id);
-- 'user-tag-5' is the only tag that should exist now.
List.Load_Tags (Tag_Manager.Get_Session, User.Get_Id);
Util.Tests.Assert_Equals (T, 1, Integer (List.Get_Count), "Invalid number of tags");
T.Assert (not Util.Beans.Objects.Is_Null (Cleanup), "Cleanup instance is null");
end;
end Test_Update_Tag;
end AWA.Tags.Modules.Tests;
|
pragma Ada_2012;
pragma Style_Checks (Off);
pragma Warnings ("U");
with Interfaces.C; use Interfaces.C;
with arm_math_types_h;
with sys_ustdint_h;
package quaternion_math_functions_h is
procedure arm_quaternion_norm_f32
(pInputQuaternions : access arm_math_types_h.float32_t;
pNorms : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:60
with Import => True,
Convention => C,
External_Name => "arm_quaternion_norm_f32";
procedure arm_quaternion_inverse_f32
(pInputQuaternions : access arm_math_types_h.float32_t;
pInverseQuaternions : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:73
with Import => True,
Convention => C,
External_Name => "arm_quaternion_inverse_f32";
procedure arm_quaternion_conjugate_f32
(inputQuaternions : access arm_math_types_h.float32_t;
pConjugateQuaternions : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:84
with Import => True,
Convention => C,
External_Name => "arm_quaternion_conjugate_f32";
procedure arm_quaternion_normalize_f32
(inputQuaternions : access arm_math_types_h.float32_t;
pNormalizedQuaternions : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:95
with Import => True,
Convention => C,
External_Name => "arm_quaternion_normalize_f32";
procedure arm_quaternion_product_single_f32
(qa : access arm_math_types_h.float32_t;
qb : access arm_math_types_h.float32_t;
r : access arm_math_types_h.float32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:107
with Import => True,
Convention => C,
External_Name => "arm_quaternion_product_single_f32";
procedure arm_quaternion_product_f32
(qa : access arm_math_types_h.float32_t;
qb : access arm_math_types_h.float32_t;
r : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:119
with Import => True,
Convention => C,
External_Name => "arm_quaternion_product_f32";
procedure arm_quaternion2rotation_f32
(pInputQuaternions : access arm_math_types_h.float32_t;
pOutputRotations : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:140
with Import => True,
Convention => C,
External_Name => "arm_quaternion2rotation_f32";
procedure arm_rotation2quaternion_f32
(pInputRotations : access arm_math_types_h.float32_t;
pOutputQuaternions : access arm_math_types_h.float32_t;
nbQuaternions : sys_ustdint_h.uint32_t) -- ../CMSIS_5/CMSIS/DSP/Include/dsp/quaternion_math_functions.h:151
with Import => True,
Convention => C,
External_Name => "arm_rotation2quaternion_f32";
end quaternion_math_functions_h;
|
-------------------------------------------------------------------------------
-- Copyright 2021, The Septum Developers (see AUTHORS file)
-- 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 body SP.Contexts is
function From
(File_Name : String; Line : Natural; Num_Lines : Natural; Context_Width : Natural) return Context_Match is
Minimum : constant Positive :=
(if Context_Width > Num_Lines or else Line - Context_Width < 1 then 1 else Line - Context_Width);
Maximum : constant Positive :=
(if Context_Width > Num_Lines or else Line + Context_Width > Num_Lines then Num_Lines
else Line + Context_Width);
begin
return C : Context_Match do
C.File_Name := Ada.Strings.Unbounded.To_Unbounded_String (File_Name);
C.Internal_Matches.Insert (Line);
C.Minimum := Minimum;
C.Maximum := Maximum;
end return;
end From;
function Is_Valid (C : Context_Match) return Boolean is
begin
return
(C.Minimum <= C.Maximum and then not C.Internal_Matches.Is_Empty
and then C.Minimum <= C.Internal_Matches.First_Element
and then C.Internal_Matches.Last_Element <= C.Maximum);
end Is_Valid;
function Real_Min (C : Context_Match) return Positive is (C.Internal_Matches.First_Element);
function Real_Max (C : Context_Match) return Positive is (C.Internal_Matches.Last_Element);
function Overlap (A, B : Context_Match) return Boolean is
A_To_Left_Of_B : constant Boolean := A.Maximum < B.Minimum;
A_To_Right_Of_B : constant Boolean := B.Maximum < A.Minimum;
New_Min : constant Positive := Positive'Max (A.Minimum, B.Minimum);
New_Max : constant Positive := Positive'Min (A.Maximum, B.Maximum);
use Ada.Strings.Unbounded;
begin
return
A.File_Name = B.File_Name and then not (A_To_Left_Of_B or else A_To_Right_Of_B)
and then
(New_Min <= Real_Min (A) and then New_Min <= Real_Min (B) and then Real_Max (A) <= New_Max
and then Real_Max (B) <= New_Max);
end Overlap;
function Contains (A : Context_Match; Line_Num : Positive) return Boolean is
begin
return A.Minimum <= Line_Num and then Line_Num <= A.Maximum;
end Contains;
function Contains (A, B : Context_Match) return Boolean is
-- Does A fully contain B?
use type Ada.Strings.Unbounded.Unbounded_String;
begin
return A.File_Name = B.File_Name and then A.Minimum <= B.Minimum and then B.Maximum <= A.Maximum;
end Contains;
function Merge (A, B : Context_Match) return Context_Match is
use Line_Matches;
begin
return C : Context_Match do
C.File_Name := A.File_Name;
C.Internal_Matches := A.Internal_Matches or B.Internal_Matches;
C.Minimum := Positive'Max (A.Minimum, B.Minimum);
C.Maximum := Positive'Min (A.Maximum, B.Maximum);
end return;
end Merge;
function Image (A : Context_Match) return String is
use Ada.Strings.Unbounded;
begin
return
To_String
(A.File_Name & ": " & A.Minimum'Image & " -> " & A.Maximum'Image & " " &
A.Internal_Matches.Length'Image & " matches");
end Image;
overriding
function "=" (A, B : Context_Match) return Boolean is
use Ada.Strings.Unbounded;
use SP.Contexts.Line_Matches;
begin
return
A.File_Name = B.File_Name and then A.Minimum = B.Minimum and then B.Maximum = A.Maximum
and then A.Internal_Matches = B.Internal_Matches;
end "=";
function Files_In (V : Context_Vectors.Vector) return SP.Strings.String_Sets.Set is
begin
return Files : SP.Strings.String_Sets.Set do
for Context of V loop
if not Files.Contains (Context.File_Name) then
Files.Insert (Context.File_Name);
end if;
end loop;
end return;
end Files_In;
end SP.Contexts;
|
with Ada.Calendar.Formatting;
package Printable_Calendar is
subtype String20 is String(1 .. 20);
type Month_Rep_Type is array (Ada.Calendar.Month_Number) of String20;
type Description is record
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
-- for internationalization, you only need to define a new description
Default_Description: constant Description :=
(Weekday_Rep =>
"Mo Tu We Th Fr Sa So",
Month_Rep =>
(" January ", " February ", " March ",
" April ", " May ", " June ",
" July ", " August ", " September ",
" October ", " November ", " December "));
type Calendar (<>) is tagged private;
-- Initialize a calendar for devices with 80- or 132-characters per row
function Init_80(Des: Description := Default_Description) return Calendar;
function Init_132(Des: Description := Default_Description) return Calendar;
-- the following procedures output to standard IO; override if neccessary
procedure New_Line(Cal: Calendar);
procedure Put_String(Cal: Calendar; S: String);
-- the following procedures do the real stuff
procedure Print_Line_Centered(Cal: Calendar'Class; Line: String);
procedure Print(Cal: Calendar'Class;
Year: Ada.Calendar.Year_Number;
Year_String: String); -- this is the main Thing
private
type Calendar is tagged record
Columns, Rows, Space_Between_Columns: Positive;
Left_Space: Natural;
Weekday_Rep: String20;
Month_Rep: Month_Rep_Type;
end record;
end Printable_Calendar;
|
with Ada.Text_IO; use Ada.Text_IO;
with GL.Types;
-- with Multivector_Analyze_E2GA;
with Multivector_Analyze_C3GA;
with Utilities;
package body Multivector_Analyze is
-- --------------------------------------------------------------------------
-- procedure Analyze (theAnalysis : in out MV_Analysis; MV : Multivectors.Multivector;
-- Flags : Flag_Type := (Flag_Invalid, False);
-- Epsilon : float := Default_Epsilon) is
-- begin
-- Multivector_Analyze_E2GA.Analyze (theAnalysis, MV, Flags, Epsilon);
-- end Analyze;
-- --------------------------------------------------------------------------
function Analyze (MV : Multivectors.Multivector;
Probe : Multivectors.Normalized_Point :=
C3GA.Probe (Blade_Types.C3_no);
Flags : Flag_Type := (Flag_Invalid, False);
Epsilon : float := Default_Epsilon) return MV_Analysis is
begin
return Multivector_Analyze_C3GA.Analyze (MV, Probe, Flags, Epsilon);
end Analyze;
-- -------------------------------------------------------------------------
function Blade_Subclass (A : MV_Analysis) return Blade_Subclass_Type is
begin
return A.M_Type.Blade_Subclass;
end Blade_Subclass;
-- --------------------------------------------------------------------------
function isValid (A : MV_Analysis) return Boolean is
begin
return A.M_Flags.Valid = Flag_Valid;
end isValid;
-- --------------------------------------------------------------------------
function isDual (A : MV_Analysis) return Boolean is
begin
return A.M_Flags.Dual;
end isDual;
-- --------------------------------------------------------------------------
function isBlade (A : MV_Analysis) return Boolean is
begin
-- return A.M_Type.Multivector_Kind
return A.M_Type.Blade_Class /= Non_Blade;
end isBlade;
-- --------------------------------------------------------------------------
function isVersor (A : MV_Analysis) return Boolean is
begin
return A.Versor_Kind /= Not_A_Versor;
end isVersor;
-- --------------------------------------------------------------------------
function isNull (A : MV_Analysis) return Boolean is
-- {return ((type() == BLADE) && (bladeClass() == ZERO));}
begin
return isBlade (A) and A.M_Type.Blade_Class = Zero_Blade;
end isNull;
-- --------------------------------------------------------------------------
function isZero (A : MV_Analysis) return Boolean is
-- {return ((type() == BLADE) && (bladeClass() == ZERO));}
begin
return isBlade (A) and A.M_Type.Blade_Class = Zero_Blade;
end isZero;
-- --------------------------------------------------------------------------
function Num_Points return integer is
begin
return Max_Points;
end Num_Points;
-- --------------------------------------------------------------------------
function Num_Vectors return integer is
begin
return Max_Vectors;
end Num_Vectors;
-- --------------------------------------------------------------------------
function Num_Scalars return integer is
begin
return Max_Scalars;
end Num_Scalars;
-- --------------------------------------------------------------------------
procedure Print_E3_Vector_Array (Name : String; anArray : E3_Vector_Array) is
begin
Put_Line (Name & ": ");
for Index in anArray'First .. anArray'Last loop
Utilities.Print_Vector ("", anArray (Index));
end loop;
New_Line;
end Print_E3_Vector_Array;
-- ------------------------------------------------------------------------
procedure Print_Analysis (Name : String; Analysis : MV_Analysis) is
use GL.Types;
use Multivector_Type;
begin
Put_Line (Name & " Analysis");
Put_Line ("Valid Flag " & boolean'Image (Analysis.M_Flags.Valid));
Put_Line ("Dual Flag " & boolean'Image (Analysis.M_Flags.Dual));
Print_Multivector_Info (Name & " M_MV_Type data", Analysis.M_MV_Type);
Put_Line ("Model Type " &
Model_Type'Image (Analysis.M_Type.Model_Kind));
Put_Line ("Multivector_Kind " &
Multivector_Type_Base.Object_Type'Image (Analysis.M_Type.Multivector_Kind));
Put_Line ("Epsilon " & Float'Image (Analysis.Epsilon));
Put_Line ("Pseudo_Scalar " & boolean'Image (Analysis.Pseudo_Scalar));
Put_Line ("Versor_Kind " & Versor_Subclass_Type'Image (Analysis.Versor_Kind));
Put_Line ("Blade_Subclass " & Blade_Subclass_Type'Image (Analysis.M_Type.Blade_Subclass));
Put_Line ("Points array:");
for index in Analysis.Points'Range loop
Put_Line (Single'Image (Analysis.Points (index) (GL.X)) & " " &
Single'Image (Analysis.Points (index) (GL.Y)) & " " &
Single'Image (Analysis.Points (index) (GL.Z)));
end loop;
exception
when others =>
Put_Line ("An exception occurred in Multivector_Analyze.Print_Analysis.");
raise;
end Print_Analysis;
-- ------------------------------------------------------------------------
procedure Print_Analysis_M_Vectors (Name : String; Analysis : MV_Analysis) is
use GL.Types;
begin
Put_Line (Name & " Analysis M_Vectors");
for index in Analysis.M_Vectors'Range loop
Put_Line (GL.Types.Single'Image (Analysis.M_Vectors (index) (GL.X)) & " " &
GL.Types.Single'Image (Analysis.M_Vectors (index) (GL.Y)) & " " &
GL.Types.Single'Image (Analysis.M_Vectors (index) (GL.Z)));
end loop;
exception
when others =>
Put_Line ("An exception occurred in Multivector_Analyze.Print_Analysis_M_Vectors.");
raise;
end Print_Analysis_M_Vectors;
-- ------------------------------------------------------------------------
procedure Print_Analysis_Points (Name : String; Analysis : MV_Analysis) is
use GL.Types;
begin
Put_Line (Name & " Analysis Points");
for index in 1 .. Multivector_Analyze.Max_Points loop
Put_Line (GL.Types.Single'Image (Analysis.Points (index) (GL.X))
& " " &
GL.Types.Single'Image (Analysis.Points (index) (GL.Y))
& " " &
GL.Types.Single'Image (Analysis.Points (index) (GL.Z)));
end loop;
exception
when others =>
Put_Line ("An exception occurred in Multivector_Analyze.Print_Analysis_Points.");
raise;
end Print_Analysis_Points;
-- ------------------------------------------------------------------------
function Versor_Subclass (A : MV_Analysis) return Blade_Subclass_Type is
begin
return Blade_Subclass (A);
end Versor_Subclass;
-- --------------------------------------------------------------------------
end Multivector_Analyze;
|
package SomeClass is
type SomeClass is record
someAttribute : Integer := 1;
end record;
type SomeClass2 is tagged record
someAttribute2 : Integer := 2;
end record;
type SomeClass3 is record
someAttribute3 : Integer := 3;
end record;
rogueVariable : Integer := 4;
function someFunction (Self : in SomeClass) return Integer;
procedure someProcedure (Self : in SomeClass);
procedure someUnrelatedProcedure;
end SomeClass;
|
-- { dg-do compile }
package cpp1 is
type Root_Interface is interface;
type Typ is new Root_Interface with record
TOTO : Integer;
pragma CPP_Vtable (TOTO);
end record;
end cpp1;
|
------------------------------------------------------------------------------
-- Copyright (c) 2019, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
with Natools.S_Expressions.Atom_Ref_Constructors;
with Natools.S_Expressions.File_Readers;
package body Natools.Web.Simple_Pages.Multipages is
procedure Build_And_Register
(Builder : in out Sites.Site_Builder;
Expression : in out S_Expressions.Lockable.Descriptor'Class;
Defaults : in Default_Data;
Root_Path : in S_Expressions.Atom;
Path_Spec : in S_Expressions.Atom);
function Key_Path (Path, Spec : S_Expressions.Atom)
return S_Expressions.Atom;
function Web_Path (Path, Spec : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference;
------------------------------
-- Local Helper Subprograms --
------------------------------
procedure Build_And_Register
(Builder : in out Sites.Site_Builder;
Expression : in out S_Expressions.Lockable.Descriptor'Class;
Defaults : in Default_Data;
Root_Path : in S_Expressions.Atom;
Path_Spec : in S_Expressions.Atom)
is
use type S_Expressions.Offset;
Name : constant S_Expressions.Atom
:= (if Path_Spec (Path_Spec'First) in
Character'Pos ('+') | Character'Pos ('-') | Character'Pos ('#')
then Path_Spec (Path_Spec'First + 1 .. Path_Spec'Last)
else Path_Spec);
Page : constant Page_Ref := Create (Expression, Defaults.Template, Name);
begin
declare
Mutator : constant Data_Refs.Mutator := Page.Ref.Update;
begin
Mutator.File_Path := Defaults.File_Path;
Mutator.Web_Path := Web_Path (Root_Path, Path_Spec);
end;
Register (Page, Builder, Key_Path (Root_Path, Path_Spec));
end Build_And_Register;
function Key_Path (Path, Spec : S_Expressions.Atom)
return S_Expressions.Atom
is
use type S_Expressions.Atom;
use type S_Expressions.Offset;
begin
case Spec (Spec'First) is
when Character'Pos ('+') =>
return Path & Spec (Spec'First + 1 .. Spec'Last);
when Character'Pos ('-') | Character'Pos ('#') =>
return S_Expressions.Null_Atom;
when others =>
return Spec;
end case;
end Key_Path;
function Web_Path (Path, Spec : S_Expressions.Atom)
return S_Expressions.Atom_Refs.Immutable_Reference
is
use type S_Expressions.Atom;
use type S_Expressions.Offset;
begin
case Spec (Spec'First) is
when Character'Pos ('+') | Character'Pos ('#') =>
return S_Expressions.Atom_Ref_Constructors.Create
(Path & Spec (Spec'First + 1 .. Spec'Last));
when Character'Pos ('-') =>
return S_Expressions.Atom_Ref_Constructors.Create
(Spec (Spec'First + 1 .. Spec'Last));
when others =>
return S_Expressions.Atom_Ref_Constructors.Create (Spec);
end case;
end Web_Path;
----------------------
-- Public Interface --
----------------------
function Create (File : in S_Expressions.Atom)
return Sites.Page_Loader'Class is
begin
return Loader'(File_Path
=> S_Expressions.Atom_Ref_Constructors.Create (File));
end Create;
overriding procedure Load
(Object : in out Loader;
Builder : in out Sites.Site_Builder;
Path : in S_Expressions.Atom)
is
use type S_Expressions.Events.Event;
Reader : Natools.S_Expressions.File_Readers.S_Reader
:= Natools.S_Expressions.File_Readers.Reader
(S_Expressions.To_String (Object.File_Path.Query));
Defaults : Default_Data;
Lock : S_Expressions.Lockable.Lock_State;
Event : S_Expressions.Events.Event := Reader.Current_Event;
begin
while Event = S_Expressions.Events.Open_List loop
Reader.Lock (Lock);
Reader.Next (Event);
if Event = S_Expressions.Events.Add_Atom then
declare
Path_Spec : constant S_Expressions.Atom := Reader.Current_Atom;
begin
if Path_Spec'Length = 0 then
Update (Defaults.Template, Reader);
else
Build_And_Register
(Builder, Reader, Defaults, Path, Path_Spec);
end if;
end;
end if;
Reader.Unlock (Lock);
Reader.Next (Event);
end loop;
end Load;
end Natools.Web.Simple_Pages.Multipages;
|
-----------------------------------------------------------------------
-- properties.hash -- Hash-based property implementation
-- Copyright (C) 2001, 2002, 2003, 2006, 2008, 2009, 2010 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.Unbounded;
with Ada.Containers;
with Ada.Containers.Hashed_Maps;
with Ada.Strings.Unbounded.Hash;
private package Util.Properties.Hash is
type Manager is new Util.Properties.Interface_P.Manager with private;
type Manager_Access is access all Manager'Class;
-- Returns TRUE if the property exists.
function Exists (Self : in Manager; Name : in Value)
return Boolean;
-- Returns the property value. Raises an exception if not found.
function Get (Self : in Manager; Name : in Value)
return Value;
procedure Insert (Self : in out Manager; Name : in Value;
Item : in Value);
-- Set the value of the property. The property is created if it
-- does not exists.
procedure Set (Self : in out Manager; Name : in Value;
Item : in Value);
-- Remove the property given its name.
procedure Remove (Self : in out Manager; Name : in Value);
-- Iterate over the properties and execute the given procedure passing the
-- property name and its value.
procedure Iterate (Self : in Manager;
Process : access procedure (Name, Item : Value));
-- Deep copy of properties stored in 'From' to 'To'.
function Create_Copy (Self : in Manager) return Interface_P.Manager_Access;
procedure Delete (Self : in Manager; Obj : in out Interface_P.Manager_Access);
function Get_Names (Self : in Manager;
Prefix : in String) return Name_Array;
private
function Equivalent_Keys (Left : Value; Right : Value)
return Boolean;
package PropertyMap is
new Ada.Containers.Hashed_Maps
(Element_Type => Value,
Key_Type => Value,
Hash => Ada.Strings.Unbounded.Hash,
Equivalent_Keys => Equivalent_Keys,
"=" => Ada.Strings.Unbounded."=");
type Manager is new Util.Properties.Interface_P.Manager with record
Content : PropertyMap.Map;
end record;
end Util.Properties.Hash;
|
-- This package is intended to set up and tear down the test environment.
-- Once created by GNATtest, this package will never be overwritten
-- automatically. Contents of this package can be modified in any way
-- except for sections surrounded by a 'read only' marker.
with Ada.Environment_Variables; use Ada.Environment_Variables;
package body Tk.TopLevel.TopLevel_Create_Options_Test_Data is
Local_TopLevel_Create_Options: aliased GNATtest_Generated.GNATtest_Standard
.Tk
.TopLevel
.TopLevel_Create_Options;
procedure Set_Up(Gnattest_T: in out Test_TopLevel_Create_Options) is
begin
GNATtest_Generated.GNATtest_Standard.Tk.TopLevel
.TopLevel_Options_Test_Data
.TopLevel_Options_Tests
.Set_Up
(GNATtest_Generated.GNATtest_Standard.Tk.TopLevel
.TopLevel_Options_Test_Data
.TopLevel_Options_Tests
.Test_TopLevel_Options
(Gnattest_T));
Gnattest_T.Fixture := Local_TopLevel_Create_Options'Access;
end Set_Up;
procedure Tear_Down(Gnattest_T: in out Test_TopLevel_Create_Options) is
TopLevel: Tk_Toplevel;
begin
GNATtest_Generated.GNATtest_Standard.Tk.TopLevel
.TopLevel_Options_Test_Data
.TopLevel_Options_Tests
.Tear_Down
(GNATtest_Generated.GNATtest_Standard.Tk.TopLevel
.TopLevel_Options_Test_Data
.TopLevel_Options_Tests
.Test_TopLevel_Options
(Gnattest_T));
if Value("DISPLAY", "")'Length = 0 then
return;
end if;
TopLevel := Get_Widget(".mydialog");
if TopLevel /= Null_Widget then
Destroy(TopLevel);
end if;
end Tear_Down;
end Tk.TopLevel.TopLevel_Create_Options_Test_Data;
|
-- { dg-do compile }
package body Incomplete5 is
function Get (O: Base_Object) return Integer is
begin
return Get_Handle(O).I;
end;
end Incomplete5;
|
pragma No_Run_Time;
with APEX;
use APEX;
with APEX.Timing;
use APEX.Timing;
with Interfaces.C;
package Activity is
procedure Thr1_Job;
end Activity;
|
package TLSF.Config
with SPARK_Mode, Pure, Preelaborate is
Max_Block_Size_Log2 : constant := 29; -- max Block is about 512Mb
SL_Index_Count_Log2 : constant := 6;
Align_Size_Log2 : constant := 3; -- for 32bit system: 2
FL_Index_Max : constant := Max_Block_Size_Log2 - 1;
Align_Size : constant := 2 ** Align_Size_Log2;
SL_Index_Count : constant := 2 ** SL_Index_Count_Log2;
FL_Index_Shift : constant := SL_Index_Count_Log2;
FL_Index_Count : constant := FL_Index_Max - FL_Index_Shift + 1;
Small_Block_Size : constant := 2 ** FL_Index_Shift;
end TLSF.Config;
|
------------------------------------------------------------------------------
-- Copyright (c) 2013, Natacha Porté --
-- --
-- Permission to use, copy, modify, and distribute this software for any --
-- purpose with or without fee is hereby granted, provided that the above --
-- copyright notice and this permission notice appear in all copies. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES --
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF --
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR --
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES --
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN --
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF --
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --
------------------------------------------------------------------------------
procedure Natools.Chunked_Strings.Tests.Memory
(Report : in out Natools.Tests.Reporter'Class)
is
function Allocated_Size (Source : in Chunked_String) return Natural;
-- Return the number of allocated characters in Source
function Allocated_Size (Source : in Chunked_String) return Natural is
begin
if Source.Data = null or else Source.Data'Last < 1 then
return 0;
end if;
return (Source.Data'Last - 1) * Source.Chunk_Size
+ Source.Data (Source.Data'Last)'Last;
end Allocated_Size;
package NT renames Natools.Tests;
begin
NT.Section (Report, "Extra tests for memory usage");
declare
Name : constant String := "Procedure Preallocate";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Memory_Ref := Allocated_Size (CS);
for I in 1 .. Repeats loop
Append (CS, Name);
end loop;
if Memory_Ref /= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory after preallocation:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after insertions:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Free_Extra_Memory";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Append (CS, Name);
Memory_Ref := Allocated_Size (CS);
Free_Extra_Memory (CS);
if Memory_Ref <= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory before:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
declare
Name : constant String := "Procedure Free_Extra_Memory (empty)";
CS : Chunked_String;
Memory_Ref : Natural;
Repeats : constant Positive := 50;
begin
Preallocate (CS, Repeats * Name'Length);
Memory_Ref := Allocated_Size (CS);
Free_Extra_Memory (CS);
if Memory_Ref <= Allocated_Size (CS) then
NT.Item (Report, Name, NT.Fail);
NT.Info (Report, "Memory before:"
& Natural'Image (Memory_Ref));
NT.Info (Report, "Memory after:"
& Natural'Image (Allocated_Size (CS)));
else
NT.Item (Report, Name, NT.Success);
end if;
exception
when Error : others => NT.Report_Exception (Report, Name, Error);
end;
Natools.Tests.End_Section (Report);
end Natools.Chunked_Strings.Tests.Memory;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
--
-- REPL is abbreviation for "Read, Execute, Print Loop", a kind of an
-- interactive programming environment.
--
-- This package provides a support for building REPL.
with Program.Contexts;
with Program.Compilation_Unit_Vectors;
package Program.REPL_Contexts is
type REPL_Context is new Program.Contexts.Context with private;
-- Context for REPL environment.
--
-- Context contains user input as sequence of cells. Each cell is
-- a declaration, a statement or an expression. Sequence of cells is
-- converted to corresponding Ada code. This code is wrapped into a main
-- subprogram - a library level procedure. Compilation unit for main
-- and any its dependency are available through OASIS Context API.
procedure Initialize
(Self : in out REPL_Context'Class;
Main_Name : Program.Text := "Main");
-- Initialize the context. Use Main_Name for the top level procedure.
-- This procedure will contain a code corresponding to the input.
function Cell_Count (Self : REPL_Context'Class) return Natural;
-- Total number of cells in the context.
function Is_Valid_Cell
(Self : REPL_Context'Class;
Index : Positive) return Boolean;
-- Return status of the cell with given index. Invalid cells have no
-- corresponding Ada code.
procedure Append_Cell
(Self : in out REPL_Context'Class;
Text : Program.Text);
-- Create new cell and append it to cell list as last element.
procedure Update_Cell
(Self : in out REPL_Context'Class;
Index : Positive;
Text : Program.Text);
-- Replace text of the cell with given index.
procedure Delete_Cell
(Self : in out REPL_Context'Class;
Index : Positive);
-- Drop the cell with given index from cell list.
private
type REPL_Context is new Program.Contexts.Context with null record;
overriding function Library_Unit_Declarations (Self : REPL_Context)
return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access;
overriding function Compilation_Unit_Bodies (Self : REPL_Context)
return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access;
end Program.REPL_Contexts;
|
-- Copyright (c) 2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- 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 Tcl.Lists; use Tcl.Lists;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
package body Tk.TtkEntry is
-- ****if* TtkEntry/TtkEntry.Widget_Command
-- FUNCTION
-- Used to get Natural result from the selected Tcl widget command
-- PARAMETERS
-- Widgt - Tk widget on which the command will be executed
-- Command_Name - Tk command which will be executed
-- Options - Option for the selected Tk command
-- RESULT
-- Natural type with the result of the Tk widget command
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
function Widget_Command is new Generic_Scalar_Execute_Widget_Command
(Result_Type => Natural);
-- ****
-- ****if* TtkEntry/TtkEntry.Options_To_String
-- FUNCTION
-- Convert Ada structure to Tcl command
-- PARAMETERS
-- Options - Ada Ttk_Entry_Options to convert
-- RESULT
-- String with Tcl command options
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
function Options_To_String(Options: Ttk_Entry_Options) return String is
-- ****
use Ada.Strings.Unbounded;
Options_String: Unbounded_String := Null_Unbounded_String;
begin
Option_Image
(Name => "class", Value => Options.Class,
Options_String => Options_String);
Option_Image
(Name => "cursor", Value => Options.Cursor,
Options_String => Options_String);
Option_Image
(Name => "exportselection", Value => Options.Export_Selection,
Options_String => Options_String);
Option_Image
(Name => "invalidcommand", Value => Options.Invalid_Command,
Options_String => Options_String);
Option_Image
(Name => "justify", Value => Options.Justify,
Options_String => Options_String);
Option_Image
(Name => "show", Value => Options.Show,
Options_String => Options_String);
if Options.State /= NONE then
Append
(Source => Options_String,
New_Item =>
" -state " &
To_Lower(Item => Entry_State_Type'Image(Options.State)));
end if;
Option_Image
(Name => "style", Value => Options.Style,
Options_String => Options_String);
Option_Image
(Name => "takefocus", Value => Options.Take_Focus,
Options_String => Options_String);
Option_Image
(Name => "textvariable", Value => Options.Text_Variable,
Options_String => Options_String);
if Options.Validation /= EMPTY then
Append
(Source => Options_String,
New_Item =>
" -validate " &
To_Lower(Item => Validate_Type'Image(Options.Validation)));
end if;
Option_Image
(Name => "validatecommand", Value => Options.Validate_Command,
Options_String => Options_String);
Option_Image
(Name => "width", Value => Options.Width,
Options_String => Options_String);
Option_Image
(Name => "xscrollcommand", Value => Options.X_Scroll_Command,
Options_String => Options_String);
return To_String(Source => Options_String);
end Options_To_String;
function Create
(Path_Name: Tk_Path_String; Options: Ttk_Entry_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) return Ttk_Entry is
begin
Tcl_Eval
(Tcl_Script =>
"ttk::entry " & Path_Name & " " &
Options_To_String(Options => Options),
Interpreter => Interpreter);
return Get_Widget(Path_Name => Path_Name, Interpreter => Interpreter);
end Create;
procedure Create
(Entry_Widget: out Ttk_Entry; Path_Name: Tk_Path_String;
Options: Ttk_Entry_Options;
Interpreter: Tcl_Interpreter := Get_Interpreter) is
begin
Entry_Widget :=
Create
(Path_Name => Path_Name, Options => Options,
Interpreter => Interpreter);
end Create;
function Get_Options(Entry_Widget: Ttk_Entry) return Ttk_Entry_Options is
begin
return Options: Ttk_Entry_Options := Default_Ttk_Entry_Options do
Options.Class := Option_Value(Widgt => Entry_Widget, Name => "class");
Options.Cursor :=
Option_Value(Widgt => Entry_Widget, Name => "cursor");
Options.Export_Selection :=
Option_Value(Widgt => Entry_Widget, Name => "exportselection");
Options.Invalid_Command :=
Option_Value(Widgt => Entry_Widget, Name => "invalidcommand");
Options.Justify :=
Option_Value(Widgt => Entry_Widget, Name => "justify");
Options.Show := Option_Value(Widgt => Entry_Widget, Name => "show");
Options.Style := Option_Value(Widgt => Entry_Widget, Name => "style");
Options.State :=
Entry_State_Type'Value
(Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "cget",
Options => "-state")
.Result);
Options.Take_Focus :=
Option_Value(Widgt => Entry_Widget, Name => "takefocus");
Options.Text_Variable :=
Option_Value(Widgt => Entry_Widget, Name => "textvariable");
Options.Validation :=
Validate_Type'Value
(Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "cget",
Options => "-validate")
.Result);
Options.Validate_Command :=
Option_Value(Widgt => Entry_Widget, Name => "validatecommand");
Options.Width := Option_Value(Widgt => Entry_Widget, Name => "width");
Options.X_Scroll_Command :=
Option_Value(Widgt => Entry_Widget, Name => "xscrollcommand");
end return;
end Get_Options;
procedure Configure(Entry_Widget: Ttk_Entry; Options: Ttk_Entry_Options) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "configure",
Options => Options_To_String(Options => Options));
end Configure;
-- ****if* TtkEntry/TtkEntry.Index_To_String_(numerical)
-- FUNCTION
-- Convert numeric index in ttk::entry to String
-- PARAMETERS
-- Index - The index to convert to String
-- Is_Index - If True, the Index is numerical index of character to convert,
-- otherwise it is X coordinate in ttk::entry
-- RESULT
-- String with converted Index or, if it is X coordinate, with added "@"
-- sign before number
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
function Index_To_String(Index: Natural; Is_Index: Boolean) return String is
-- ****
use Ada.Strings.Fixed;
begin
if Is_Index then
return Trim(Source => Natural'Image(Index), Side => Left);
end if;
return "@" & Trim(Source => Natural'Image(Index), Side => Left);
end Index_To_String;
-- ****if* TtkEntry/TtkEntry.Index_To_String_(Entry_Index_Type)
-- FUNCTION
-- Convert Entry_Index_Type index in ttk::entry to String
-- PARAMETERS
-- Index - The index to convert to String
-- RESULT
-- String with converted Index
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
function Index_To_String(Index: Entry_Index_Type) return String is
-- ****
begin
case Index is
when LASTCHARACTER =>
return "end";
when INSERT =>
return "insert";
when SELECTIONFIRST =>
return "sel.first";
when SELECTIONLAST =>
return "sel.last";
when NONE =>
return "";
end case;
end Index_To_String;
function Get_Bounding_Box
(Entry_Widget: Ttk_Entry; Index: Natural; Is_Index: Boolean := True)
return Bbox_Data is
Interpreter: constant Tcl_Interpreter :=
Tk_Interp(Widgt => Entry_Widget);
Result_List: constant Array_List :=
Split_List
(List =>
Tcl_Eval
(Tcl_Script =>
Tk_Path_Name(Widgt => Entry_Widget) & " bbox " &
Index_To_String(Index => Index, Is_Index => Is_Index),
Interpreter => Interpreter)
.Result,
Interpreter => Interpreter);
begin
return Coords: Bbox_Data := Empty_Bbox_Data do
Coords.Start_X :=
Natural'Value(To_Ada_String(Source => Result_List(1)));
Coords.Start_Y :=
Natural'Value(To_Ada_String(Source => Result_List(2)));
Coords.Width :=
Natural'Value(To_Ada_String(Source => Result_List(3)));
Coords.Height :=
Natural'Value(To_Ada_String(Source => Result_List(4)));
end return;
end Get_Bounding_Box;
function Get_Bounding_Box
(Entry_Widget: Ttk_Entry; Index: Entry_Index_Type) return Bbox_Data is
Interpreter: constant Tcl_Interpreter :=
Tk_Interp(Widgt => Entry_Widget);
Result_List: constant Array_List :=
Split_List
(List =>
Tcl_Eval
(Tcl_Script =>
Tk_Path_Name(Widgt => Entry_Widget) & " bbox " &
Index_To_String(Index => Index),
Interpreter => Interpreter)
.Result,
Interpreter => Interpreter);
begin
return Coords: Bbox_Data := Empty_Bbox_Data do
Coords.Start_X :=
Natural'Value(To_Ada_String(Source => Result_List(1)));
Coords.Start_Y :=
Natural'Value(To_Ada_String(Source => Result_List(2)));
Coords.Width :=
Natural'Value(To_Ada_String(Source => Result_List(3)));
Coords.Height :=
Natural'Value(To_Ada_String(Source => Result_List(4)));
end return;
end Get_Bounding_Box;
procedure Delete
(Entry_Widget: Ttk_Entry; First: Natural; Last: Natural := 0;
Is_First_Index, Is_Last_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "delete",
Options =>
Index_To_String(Index => First, Is_Index => Is_First_Index) &
(if Last > 0 then
" " & Index_To_String(Index => Last, Is_Index => Is_Last_Index)
else ""));
end Delete;
procedure Delete
(Entry_Widget: Ttk_Entry; First: Entry_Index_Type;
Last: Entry_Index_Type := NONE) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "delete",
Options =>
Index_To_String(Index => First) &
(if Last = NONE then "" else " " & Index_To_String(Index => Last)));
end Delete;
procedure Delete
(Entry_Widget: Ttk_Entry; First: Natural; Last: Entry_Index_Type := NONE;
Is_First_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "delete",
Options =>
Index_To_String(Index => First, Is_Index => Is_First_Index) &
(if Last = NONE then "" else " " & Index_To_String(Index => Last)));
end Delete;
procedure Delete
(Entry_Widget: Ttk_Entry; First: Entry_Index_Type; Last: Natural := 0;
Is_Last_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "delete",
Options =>
Index_To_String(Index => First) &
(if Last > 0 then
" " & Index_To_String(Index => Last, Is_Index => Is_Last_Index)
else ""));
end Delete;
function Get_Text(Entry_Widget: Ttk_Entry) return String is
begin
return
Execute_Widget_Command(Widgt => Entry_Widget, Command_Name => "get")
.Result;
end Get_Text;
procedure Set_Insert_Cursor
(Entry_Widget: Ttk_Entry; Index: Natural; Is_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "icursor",
Options => Index_To_String(Index => Index, Is_Index => Is_Index));
end Set_Insert_Cursor;
procedure Set_Insert_Cursor
(Entry_Widget: Ttk_Entry; Index: Entry_Index_Type) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "icursor",
Options => Index_To_String(Index => Index));
end Set_Insert_Cursor;
function Get_Index(Entry_Widget: Ttk_Entry; X: Natural) return Natural is
begin
return
Widget_Command
(Widgt => Entry_Widget, Command_Name => "index",
Options => Index_To_String(Index => X, Is_Index => False));
end Get_Index;
function Get_Index
(Entry_Widget: Ttk_Entry; Index: Entry_Index_Type) return Natural is
begin
return
Widget_Command
(Widgt => Entry_Widget, Command_Name => "index",
Options => Index_To_String(Index => Index));
end Get_Index;
procedure Insert_Text
(Entry_Widget: Ttk_Entry; Index: Natural; Text: Tcl_String;
Is_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "insert",
Options =>
Index_To_String(Index => Index, Is_Index => Is_Index) & " " &
To_String(Source => Text));
end Insert_Text;
procedure Insert_Text
(Entry_Widget: Ttk_Entry; Index: Entry_Index_Type; Text: Tcl_String) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "insert",
Options =>
Index_To_String(Index => Index) & " " & To_String(Source => Text));
end Insert_Text;
procedure Selection_Clear(Entry_Widget: Ttk_Entry) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options => "clear");
end Selection_Clear;
function Selection_Present(Entry_Widget: Ttk_Entry) return Boolean is
begin
return
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options => "present")
.Result;
end Selection_Present;
procedure Selection_Range
(Entry_Widget: Ttk_Entry; Start_Index, End_Index: Natural;
Is_Start_Index, Is_End_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options =>
"range " &
Index_To_String(Index => Start_Index, Is_Index => Is_Start_Index) &
" " &
Index_To_String(Index => End_Index, Is_Index => Is_End_Index));
end Selection_Range;
procedure Selection_Range
(Entry_Widget: Ttk_Entry; Start_Index, End_Index: Entry_Index_Type) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options =>
"range " & Index_To_String(Index => Start_Index) & " " &
Index_To_String(Index => End_Index));
end Selection_Range;
procedure Selection_Range
(Entry_Widget: Ttk_Entry; Start_Index: Natural;
End_Index: Entry_Index_Type; Is_Start_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options =>
"range " &
Index_To_String(Index => Start_Index, Is_Index => Is_Start_Index) &
" " & Index_To_String(Index => End_Index));
end Selection_Range;
procedure Selection_Range
(Entry_Widget: Ttk_Entry; Start_Index: Entry_Index_Type;
End_Index: Natural; Is_End_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "selection",
Options =>
"range " & Index_To_String(Index => Start_Index) & " " &
Index_To_String(Index => End_Index, Is_Index => Is_End_Index));
end Selection_Range;
function Validate(Entry_Widget: Ttk_Entry) return Boolean is
begin
return
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "validate")
.Result;
end Validate;
function X_View(Entry_Widget: Ttk_Entry) return Fractions_Array is
Interpreter: constant Tcl_Interpreter :=
Tk_Interp(Widgt => Entry_Widget);
Result_List: constant Array_List :=
Split_List
(List =>
Tcl_Eval
(Tcl_Script => Tk_Path_Name(Widgt => Entry_Widget) & " xview",
Interpreter => Interpreter)
.Result,
Interpreter => Interpreter);
begin
return Fractions: Fractions_Array := Default_Fractions_Array do
Fractions(1) :=
Fraction_Type'Value(To_Ada_String(Source => Result_List(1)));
Fractions(2) :=
Fraction_Type'Value(To_Ada_String(Source => Result_List(2)));
end return;
end X_View;
procedure X_View_Adjust
(Entry_Widget: Ttk_Entry; Index: Natural; Is_Index: Boolean := True) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "xview",
Options => Index_To_String(Index => Index, Is_Index => Is_Index));
end X_View_Adjust;
procedure X_View_Adjust(Entry_Widget: Ttk_Entry; Index: Entry_Index_Type) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "xview",
Options => Index_To_String(Index => Index));
end X_View_Adjust;
procedure X_View_Move_To
(Entry_Widget: Ttk_Entry; Fraction: Fraction_Type) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "xview",
Options => "moveto " & Fraction_Type'Image(Fraction));
end X_View_Move_To;
procedure X_View_Scroll
(Entry_Widget: Ttk_Entry; Number: Integer; What: Scroll_Unit_Type) is
begin
Execute_Widget_Command
(Widgt => Entry_Widget, Command_Name => "xview",
Options =>
"scroll " & Integer'Image(Number) & " " &
To_Lower(Item => Scroll_Unit_Type'Image(What)));
end X_View_Scroll;
end Tk.TtkEntry;
|
-- This file cannot be processed by the SPARK Examiner.
with Ada.Numerics,
Ada.Numerics.Long_Elementary_Functions;
package body PP_LF_Elementary is
function Pi return Long_Float is
begin
return Ada.Numerics.Pi;
end Pi;
function Sqrt (X : Long_Float) return Long_Float
renames Ada.Numerics.Long_Elementary_Functions.Sqrt;
function Exp (X : Long_Float) return Long_Float
renames Ada.Numerics.Long_Elementary_Functions.Exp;
end PP_LF_Elementary;
|
package GESTE_Fonts.FreeMonoBoldOblique5pt7b is
Font : constant Bitmap_Font_Ref;
private
FreeMonoBoldOblique5pt7bBitmaps : aliased constant Font_Bitmap := (
16#00#, 16#00#, 16#00#, 16#C1#, 16#82#, 16#04#, 16#00#, 16#30#, 16#00#,
16#00#, 16#00#, 16#00#, 16#A2#, 16#85#, 16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#50#, 16#A3#, 16#C5#, 16#0A#, 16#3E#, 16#30#, 16#A0#,
16#00#, 16#00#, 16#00#, 16#E2#, 16#47#, 16#03#, 16#24#, 16#70#, 16#40#,
16#00#, 16#00#, 16#41#, 16#42#, 16#87#, 16#9E#, 16#14#, 16#18#, 16#00#,
16#00#, 16#00#, 16#00#, 16#C2#, 16#04#, 16#1C#, 16#2C#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#41#, 16#02#, 16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#20#, 16#81#, 16#04#, 16#08#, 16#10#, 16#30#,
16#00#, 16#00#, 16#01#, 16#81#, 16#02#, 16#04#, 16#08#, 16#20#, 16#C0#,
16#00#, 16#00#, 16#00#, 16#43#, 16#C3#, 16#0A#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#01#, 16#02#, 16#1F#, 16#08#, 16#10#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#20#, 16#40#,
16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#1F#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#30#, 16#00#,
16#00#, 16#00#, 16#08#, 16#20#, 16#83#, 16#04#, 16#10#, 16#60#, 16#80#,
16#00#, 16#00#, 16#00#, 16#E2#, 16#44#, 16#91#, 16#24#, 16#30#, 16#00#,
16#00#, 16#00#, 16#01#, 16#C1#, 16#02#, 16#04#, 16#08#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#E2#, 16#40#, 16#86#, 16#18#, 16#78#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E0#, 16#43#, 16#01#, 16#06#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#, 16#C3#, 16#0A#, 16#3C#, 16#18#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E2#, 16#07#, 16#09#, 16#06#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#71#, 16#07#, 16#09#, 16#12#, 16#38#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E0#, 16#41#, 16#02#, 16#08#, 16#10#, 16#00#,
16#00#, 16#00#, 16#00#, 16#E2#, 16#47#, 16#13#, 16#24#, 16#38#, 16#00#,
16#00#, 16#00#, 16#00#, 16#E2#, 16#44#, 16#8F#, 16#04#, 16#70#, 16#00#,
16#00#, 16#00#, 16#00#, 16#01#, 16#80#, 16#00#, 16#00#, 16#30#, 16#00#,
16#00#, 16#00#, 16#00#, 16#01#, 16#00#, 16#00#, 16#00#, 16#20#, 16#80#,
16#00#, 16#00#, 16#00#, 16#00#, 16#43#, 16#0C#, 16#0C#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#, 16#0F#, 16#80#, 16#3E#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#02#, 16#03#, 16#03#, 16#38#, 16#00#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E2#, 16#41#, 16#84#, 16#00#, 16#30#, 16#00#,
16#00#, 16#00#, 16#00#, 16#C2#, 16#4B#, 16#9A#, 16#2C#, 16#40#, 16#80#,
16#00#, 16#00#, 16#01#, 16#C1#, 16#85#, 16#0E#, 16#22#, 16#EC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E2#, 16#44#, 16#9F#, 16#22#, 16#F8#, 16#00#,
16#00#, 16#00#, 16#00#, 16#F6#, 16#48#, 16#10#, 16#22#, 16#78#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E2#, 16#48#, 16#91#, 16#26#, 16#F8#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E3#, 16#46#, 16#14#, 16#22#, 16#FC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E3#, 16#4E#, 16#14#, 16#20#, 16#F0#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E6#, 16#48#, 16#17#, 16#22#, 16#78#, 16#00#,
16#00#, 16#00#, 16#03#, 16#F2#, 16#4F#, 16#92#, 16#24#, 16#FC#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E1#, 16#02#, 16#04#, 16#08#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#F0#, 16#81#, 16#02#, 16#4C#, 16#F0#, 16#00#,
16#00#, 16#00#, 16#03#, 16#F2#, 16#8A#, 16#1E#, 16#24#, 16#EC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#C2#, 16#04#, 16#08#, 16#12#, 16#FC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#36#, 16#6D#, 16#97#, 16#2A#, 16#EC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#73#, 16#4A#, 16#95#, 16#26#, 16#E8#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E6#, 16#48#, 16#91#, 16#26#, 16#70#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E2#, 16#44#, 16#9E#, 16#20#, 16#F0#, 16#00#,
16#00#, 16#00#, 16#01#, 16#C6#, 16#48#, 16#91#, 16#26#, 16#70#, 16#F0#,
16#00#, 16#00#, 16#03#, 16#E2#, 16#4C#, 16#9E#, 16#24#, 16#EC#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E2#, 16#44#, 16#07#, 16#26#, 16#78#, 16#00#,
16#00#, 16#00#, 16#03#, 16#E5#, 16#42#, 16#04#, 16#10#, 16#78#, 16#00#,
16#00#, 16#00#, 16#03#, 16#F4#, 16#48#, 16#91#, 16#24#, 16#70#, 16#00#,
16#00#, 16#00#, 16#07#, 16#74#, 16#49#, 16#1E#, 16#18#, 16#20#, 16#00#,
16#00#, 16#00#, 16#03#, 16#75#, 16#4E#, 16#9E#, 16#2C#, 16#58#, 16#00#,
16#00#, 16#00#, 16#03#, 16#72#, 16#C3#, 16#0C#, 16#24#, 16#DC#, 16#00#,
16#00#, 16#00#, 16#03#, 16#62#, 16#86#, 16#04#, 16#10#, 16#70#, 16#00#,
16#00#, 16#00#, 16#01#, 16#E2#, 16#82#, 16#08#, 16#24#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#61#, 16#82#, 16#04#, 16#08#, 16#10#, 16#70#,
16#00#, 16#00#, 16#81#, 16#01#, 16#02#, 16#04#, 16#0C#, 16#08#, 16#10#,
16#00#, 16#00#, 16#01#, 16#C1#, 16#02#, 16#04#, 16#08#, 16#10#, 16#C0#,
16#00#, 16#00#, 16#00#, 16#41#, 16#84#, 16#80#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#80#, 16#00#, 16#00#, 16#00#, 16#00#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#80#, 16#8E#, 16#24#, 16#7C#, 16#00#,
16#00#, 16#00#, 16#03#, 16#03#, 16#C4#, 16#91#, 16#22#, 16#F8#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#C8#, 16#90#, 16#20#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#33#, 16#C8#, 16#91#, 16#26#, 16#7C#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#88#, 16#9F#, 16#20#, 16#7C#, 16#00#,
16#00#, 16#00#, 16#00#, 16#F3#, 16#C2#, 16#08#, 16#10#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#E9#, 16#92#, 16#24#, 16#78#, 16#10#,
16#00#, 16#00#, 16#03#, 16#03#, 16#84#, 16#89#, 16#24#, 16#FC#, 16#00#,
16#00#, 16#00#, 16#00#, 16#C3#, 16#02#, 16#04#, 16#08#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#43#, 16#C1#, 16#02#, 16#04#, 16#08#, 16#10#,
16#00#, 16#00#, 16#01#, 16#02#, 16#C6#, 16#0C#, 16#2C#, 16#DC#, 16#00#,
16#00#, 16#00#, 16#01#, 16#C1#, 16#02#, 16#04#, 16#08#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#07#, 16#CA#, 16#95#, 16#2A#, 16#D4#, 16#00#,
16#00#, 16#00#, 16#00#, 16#07#, 16#8C#, 16#91#, 16#24#, 16#EC#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#88#, 16#91#, 16#26#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#07#, 16#CC#, 16#91#, 16#22#, 16#78#, 16#80#,
16#00#, 16#00#, 16#00#, 16#03#, 16#E9#, 16#92#, 16#64#, 16#78#, 16#10#,
16#00#, 16#00#, 16#00#, 16#06#, 16#C6#, 16#08#, 16#10#, 16#F8#, 16#00#,
16#00#, 16#00#, 16#00#, 16#03#, 16#C4#, 16#8E#, 16#26#, 16#78#, 16#00#,
16#00#, 16#00#, 16#01#, 16#07#, 16#84#, 16#08#, 16#20#, 16#38#, 16#00#,
16#00#, 16#00#, 16#00#, 16#06#, 16#C4#, 16#91#, 16#24#, 16#7C#, 16#00#,
16#00#, 16#00#, 16#00#, 16#06#, 16#ED#, 16#0A#, 16#18#, 16#30#, 16#00#,
16#00#, 16#00#, 16#00#, 16#06#, 16#EA#, 16#9E#, 16#3C#, 16#58#, 16#00#,
16#00#, 16#00#, 16#00#, 16#06#, 16#C7#, 16#0C#, 16#34#, 16#FC#, 16#00#,
16#00#, 16#00#, 16#00#, 16#06#, 16#ED#, 16#8A#, 16#18#, 16#30#, 16#40#,
16#00#, 16#00#, 16#00#, 16#03#, 16#C1#, 16#04#, 16#10#, 16#78#, 16#00#,
16#00#, 16#00#, 16#00#, 16#61#, 16#02#, 16#08#, 16#08#, 16#10#, 16#40#,
16#00#, 16#00#, 16#00#, 16#41#, 16#02#, 16#04#, 16#08#, 16#10#, 16#40#,
16#00#, 16#00#, 16#00#, 16#81#, 16#02#, 16#02#, 16#08#, 16#10#, 16#40#,
16#00#, 16#00#, 16#00#, 16#00#, 16#0E#, 16#07#, 16#00#, 16#00#, 16#00#);
Font_D : aliased constant Bitmap_Font :=
(
Bytes_Per_Glyph => 9,
Glyph_Width => 7,
Glyph_Height => 10,
Data => FreeMonoBoldOblique5pt7bBitmaps'Access);
Font : constant Bitmap_Font_Ref := Font_D'Access;
end GESTE_Fonts.FreeMonoBoldOblique5pt7b;
|
-----------------------------------------------------------------------
-- asf-navigations-redirect -- Navigator to redirect to another page
-- Copyright (C) 2010, 2011 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with EL.Expressions;
with EL.Contexts;
package ASF.Navigations.Redirect is
-- ------------------------------
-- Redirect page navigator
-- ------------------------------
-- The <b>Redirect_Navigator</b> handles the redirection rule for the navigation.
-- The redirection view can contain EL expressions that will be evaluated when the
-- redirect rule is executed.
type Redirect_Navigator is new Navigation_Case with private;
type Redirect_Navigator_Access is access all Redirect_Navigator'Class;
-- Get the redirection view. Evaluate the EL expressions used in the view name.
function Get_Redirection (Controller : in Redirect_Navigator;
Context : in ASF.Contexts.Faces.Faces_Context'Class)
return String;
-- Navigate to the next page or action according to the controller's navigator.
-- The navigator controller redirects the user to another page.
overriding
procedure Navigate (Controller : in Redirect_Navigator;
Context : in out ASF.Contexts.Faces.Faces_Context'Class);
-- Create a navigation case to redirect to another page.
function Create_Redirect_Navigator (To_View : in String;
Context : in EL.Contexts.ELContext'Class)
return Navigation_Access;
private
type Redirect_Navigator is new Navigation_Case with record
View_Expr : EL.Expressions.Expression;
end record;
end ASF.Navigations.Redirect;
|
pragma Ada_95;
pragma Warnings (Off);
pragma Source_File_Name (testmain, Spec_File_Name => "b__test.ads");
pragma Source_File_Name (testmain, Body_File_Name => "b__test.adb");
pragma Suppress (Overflow_Check);
with Ada.Exceptions;
package body testmain is
E103 : Short_Integer; pragma Import (Ada, E103, "system__os_lib_E");
E014 : Short_Integer; pragma Import (Ada, E014, "system__soft_links_E");
E024 : Short_Integer; pragma Import (Ada, E024, "system__exception_table_E");
E088 : Short_Integer; pragma Import (Ada, E088, "ada__io_exceptions_E");
E047 : Short_Integer; pragma Import (Ada, E047, "ada__strings_E");
E049 : Short_Integer; pragma Import (Ada, E049, "ada__strings__maps_E");
E053 : Short_Integer; pragma Import (Ada, E053, "ada__strings__maps__constants_E");
E090 : Short_Integer; pragma Import (Ada, E090, "ada__tags_E");
E087 : Short_Integer; pragma Import (Ada, E087, "ada__streams_E");
E064 : Short_Integer; pragma Import (Ada, E064, "interfaces__c_E");
E026 : Short_Integer; pragma Import (Ada, E026, "system__exceptions_E");
E106 : Short_Integer; pragma Import (Ada, E106, "system__file_control_block_E");
E098 : Short_Integer; pragma Import (Ada, E098, "system__file_io_E");
E101 : Short_Integer; pragma Import (Ada, E101, "system__finalization_root_E");
E099 : Short_Integer; pragma Import (Ada, E099, "ada__finalization_E");
E062 : Short_Integer; pragma Import (Ada, E062, "system__object_reader_E");
E042 : Short_Integer; pragma Import (Ada, E042, "system__dwarf_lines_E");
E018 : Short_Integer; pragma Import (Ada, E018, "system__secondary_stack_E");
E037 : Short_Integer; pragma Import (Ada, E037, "system__traceback__symbolic_E");
E007 : Short_Integer; pragma Import (Ada, E007, "ada__text_io_E");
E002 : Short_Integer; pragma Import (Ada, E002, "my_lib_E");
Local_Priority_Specific_Dispatching : constant String := "";
Local_Interrupt_States : constant String := "";
Is_Elaborated : Boolean := False;
procedure finalize_library is
begin
E007 := E007 - 1;
declare
procedure F1;
pragma Import (Ada, F1, "ada__text_io__finalize_spec");
begin
if E007 = 0 then
F1;
end if;
end;
declare
procedure F2;
pragma Import (Ada, F2, "system__file_io__finalize_body");
begin
E098 := E098 - 1;
if E098 = 0 then
F2;
end if;
end;
declare
procedure Reraise_Library_Exception_If_Any;
pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
begin
Reraise_Library_Exception_If_Any;
end;
end finalize_library;
procedure testfinal is
procedure Runtime_Finalize;
pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
begin
if not Is_Elaborated then
return;
end if;
Is_Elaborated := False;
Runtime_Finalize;
finalize_library;
end testfinal;
type No_Param_Proc is access procedure;
procedure testinit is
Main_Priority : Integer;
pragma Import (C, Main_Priority, "__gl_main_priority");
Time_Slice_Value : Integer;
pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
WC_Encoding : Character;
pragma Import (C, WC_Encoding, "__gl_wc_encoding");
Locking_Policy : Character;
pragma Import (C, Locking_Policy, "__gl_locking_policy");
Queuing_Policy : Character;
pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
Task_Dispatching_Policy : Character;
pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
Priority_Specific_Dispatching : System.Address;
pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
Num_Specific_Dispatching : Integer;
pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
Main_CPU : Integer;
pragma Import (C, Main_CPU, "__gl_main_cpu");
Interrupt_States : System.Address;
pragma Import (C, Interrupt_States, "__gl_interrupt_states");
Num_Interrupt_States : Integer;
pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
Unreserve_All_Interrupts : Integer;
pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
Detect_Blocking : Integer;
pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
Default_Stack_Size : Integer;
pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
Leap_Seconds_Support : Integer;
pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
Bind_Env_Addr : System.Address;
pragma Import (C, Bind_Env_Addr, "__gl_bind_env_addr");
procedure Runtime_Initialize (Install_Handler : Integer);
pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
Finalize_Library_Objects : No_Param_Proc;
pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
begin
if Is_Elaborated then
return;
end if;
Is_Elaborated := True;
Main_Priority := -1;
Time_Slice_Value := -1;
WC_Encoding := 'b';
Locking_Policy := ' ';
Queuing_Policy := ' ';
Task_Dispatching_Policy := ' ';
Priority_Specific_Dispatching :=
Local_Priority_Specific_Dispatching'Address;
Num_Specific_Dispatching := 0;
Main_CPU := -1;
Interrupt_States := Local_Interrupt_States'Address;
Num_Interrupt_States := 0;
Unreserve_All_Interrupts := 0;
Detect_Blocking := 0;
Default_Stack_Size := -1;
Leap_Seconds_Support := 0;
Runtime_Initialize (1);
if E014 = 0 then
System.Soft_Links'Elab_Spec;
end if;
if E024 = 0 then
System.Exception_Table'Elab_Body;
end if;
E024 := E024 + 1;
if E088 = 0 then
Ada.Io_Exceptions'Elab_Spec;
end if;
E088 := E088 + 1;
if E047 = 0 then
Ada.Strings'Elab_Spec;
end if;
E047 := E047 + 1;
if E049 = 0 then
Ada.Strings.Maps'Elab_Spec;
end if;
if E053 = 0 then
Ada.Strings.Maps.Constants'Elab_Spec;
end if;
E053 := E053 + 1;
if E090 = 0 then
Ada.Tags'Elab_Spec;
end if;
if E087 = 0 then
Ada.Streams'Elab_Spec;
end if;
E087 := E087 + 1;
if E064 = 0 then
Interfaces.C'Elab_Spec;
end if;
if E026 = 0 then
System.Exceptions'Elab_Spec;
end if;
E026 := E026 + 1;
if E106 = 0 then
System.File_Control_Block'Elab_Spec;
end if;
E106 := E106 + 1;
if E101 = 0 then
System.Finalization_Root'Elab_Spec;
end if;
E101 := E101 + 1;
if E099 = 0 then
Ada.Finalization'Elab_Spec;
end if;
E099 := E099 + 1;
if E062 = 0 then
System.Object_Reader'Elab_Spec;
end if;
if E042 = 0 then
System.Dwarf_Lines'Elab_Spec;
end if;
if E098 = 0 then
System.File_Io'Elab_Body;
end if;
E098 := E098 + 1;
E064 := E064 + 1;
if E090 = 0 then
Ada.Tags'Elab_Body;
end if;
E090 := E090 + 1;
E049 := E049 + 1;
if E014 = 0 then
System.Soft_Links'Elab_Body;
end if;
E014 := E014 + 1;
if E103 = 0 then
System.Os_Lib'Elab_Body;
end if;
E103 := E103 + 1;
if E018 = 0 then
System.Secondary_Stack'Elab_Body;
end if;
E018 := E018 + 1;
E042 := E042 + 1;
E062 := E062 + 1;
if E037 = 0 then
System.Traceback.Symbolic'Elab_Body;
end if;
E037 := E037 + 1;
if E007 = 0 then
Ada.Text_Io'Elab_Spec;
end if;
if E007 = 0 then
Ada.Text_Io'Elab_Body;
end if;
E007 := E007 + 1;
E002 := E002 + 1;
end testinit;
-- BEGIN Object file/option list
-- C:\Users\sloyd3\Documents\src\Ada_Libraries\test_libraries\obj\my_lib.o
-- -LC:\Users\sloyd3\Documents\src\Ada_Libraries\test_libraries\obj\
-- -LC:/gnat/2016/lib/gcc/i686-pc-mingw32/4.9.4/adalib/
-- -static
-- -lgnat
-- -Wl,--stack=0x2000000
-- END Object file/option list
end testmain;
|
with BTree;
procedure launch is
begin
BTree.main;
end launch;
|
with Ada.Streams.Stream_IO;
with Interfaces; use Interfaces;
with Zip.Headers, UnZip.Decompress;
with Zip_Streams;
package body UnZip is
use Ada.Streams, Ada.Strings.Unbounded;
--------------------------------------------------
-- *The* internal 1 - file unzipping procedure. --
-- Input must be _open_ and won't be _closed_ ! --
--------------------------------------------------
procedure UnZipFile (
zip_file : Zip_Streams.Zipstream_Class;
out_name : String;
name_from_header : Boolean;
header_index : in out Positive;
hint_comp_size : File_size_type; -- Added 2007 for .ODS files
feedback : Zip.Feedback_proc;
help_the_file_exists : Resolve_conflict_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set;
password : in out Unbounded_String;
file_system_routines : FS_routines_type
)
is
work_index : Positive := header_index;
local_header : Zip.Headers.Local_File_Header;
data_descriptor_after_data : Boolean;
method : PKZip_method;
skip_this_file : Boolean := False;
bin_text_mode : constant array (Boolean) of Write_mode :=
(write_to_binary_file, write_to_text_file);
mode : constant array (Boolean) of Write_mode :=
(bin_text_mode (options (extract_as_text)), just_test);
actual_mode : Write_mode := mode (options (test_only));
true_packed_size : File_size_type; -- encryption adds 12 to packed size
the_output_name : Unbounded_String;
-- 27 - Jun - 2001 : possibility of trashing directory part of a name
-- e.g. : unzipada\uza_src\unzip.ads - > unzip.ads
function Maybe_trash_dir (n : String) return String is
idx : Integer := n'First - 1;
begin
if options (junk_directories) then
for i in n'Range loop
if n (i) = '/' or else n (i) = '\' then
idx := i;
end if;
end loop;
-- idx points on the index just before the interesting part
return n (idx + 1 .. n'Last);
else
return n;
end if;
end Maybe_trash_dir;
procedure Set_definitively_named_outfile (composed_name : String) is
idx : Integer := composed_name'First - 1;
first_in_name : Integer;
begin
for i in composed_name'Range loop
if composed_name (i) = '/' or else composed_name (i) = '\' then
idx := i;
end if;
end loop;
-- idx points on the index just before the name part
if idx >= composed_name'First and then
actual_mode in Write_to_file and then
file_system_routines.Create_Path /= null
then
-- Not only the name, also a path.
-- In that case, we may need to create parts of the path.
declare
Directory_Separator : constant Character := '/';
-- The '/' separator is also recognized by Windows' routines,
-- so we can just use it as a standard. See the discussion started
-- in July 2010 in the Ada Comment mailing list about it
-- for the 2012 standard.
path : String := composed_name (composed_name'First .. idx - 1);
begin
-- Set the file separator recognized by the O.S.
for i in path'Range loop
if path (i) = '\' or else path (i) = '/' then
path (i) := Directory_Separator;
end if;
end loop;
file_system_routines.Create_Path (path);
end;
end if;
-- Now we can create the file itself.
first_in_name := composed_name'First;
--
the_output_name :=
To_Unbounded_String (composed_name (first_in_name .. composed_name'Last));
end Set_definitively_named_outfile;
function Full_Path_Name (Archive_File_Name : String) return String is
begin
if file_system_routines.Compose_File_Name = null then
return Archive_File_Name;
else
return file_system_routines.Compose_File_Name.all (Archive_File_Name);
end if;
end Full_Path_Name;
procedure Set_outfile (long_not_composed_name : String) is
-- Eventually trash the archived directory structure, then
-- eventually add/modify/ .. . another one:
name : constant String :=
Full_Path_Name (Maybe_trash_dir (long_not_composed_name));
begin
Set_definitively_named_outfile (name);
end Set_outfile;
procedure Set_outfile_interactive (long_not_composed_possible_name : String) is
-- Eventually trash the archived directory structure, then
-- eventually add/modify/ .. . another one:
possible_name : constant String :=
Full_Path_Name (Maybe_trash_dir (long_not_composed_possible_name));
new_name : String (1 .. 1024);
new_name_length : Natural;
begin
if help_the_file_exists /= null and then Zip.Exists (possible_name) then
loop
case current_user_attitude is
when yes | no | rename_it => -- then ask for this name too
help_the_file_exists (
possible_name,
current_user_attitude,
new_name, new_name_length
);
when yes_to_all | none | abort_now =>
exit; -- nothing to decide : previous decision was definitive
end case;
exit when not (
current_user_attitude = rename_it and then -- new name exists too!
Zip.Exists (new_name (1 .. new_name_length))
);
end loop;
-- User has decided.
case current_user_attitude is
when yes | yes_to_all =>
skip_this_file := False;
Set_definitively_named_outfile (possible_name);
when no | none =>
skip_this_file := True;
when rename_it =>
skip_this_file := False;
Set_definitively_named_outfile (new_name (1 .. new_name_length));
when abort_now =>
raise User_abort;
end case;
else -- no name conflict or non - interactive (help_the_file_exists=null)
skip_this_file := False;
Set_definitively_named_outfile (possible_name);
end if;
end Set_outfile_interactive;
procedure Inform_User (
name : String;
comp, uncomp : File_size_type
)
is
begin
if tell_data /= null then
tell_data (name, comp, uncomp, method);
end if;
end Inform_User;
the_name : String (1 .. 1000);
the_name_len : Natural;
use Zip, Zip_Streams;
actual_feedback : Zip.Feedback_proc;
dummy : p_Stream_Element_Array;
encrypted, dummy_bool : Boolean;
begin
begin
Set_Index (zip_file, work_index);
declare
TempStream : constant Zipstream_Class := zip_file;
begin
Zip.Headers.Read_and_check (TempStream, local_header);
end;
exception
when Zip.Headers.bad_local_header =>
raise;
when others =>
raise Read_Error;
end;
method := Zip.Method_from_code (local_header.zip_type);
if method = unknown then
raise Unsupported_method;
end if;
-- calculate offset of data
work_index :=
work_index + Positive (Ada.Streams.Stream_IO.Count (
local_header.filename_length +
local_header.extra_field_length +
Zip.Headers.local_header_length)
);
data_descriptor_after_data := (local_header.bit_flag and 8) /= 0;
if data_descriptor_after_data then
-- Sizes and CRC are stored after the data
-- We set size to avoid getting a sudden Zip_EOF !
local_header.dd.crc_32 := 0;
local_header.dd.compressed_size := hint_comp_size;
local_header.dd.uncompressed_size := File_size_type'Last;
actual_feedback := null; -- no feedback possible : unknown sizes
else
-- Sizes and CRC are stored before the data, inside the local header
actual_feedback := feedback; -- use the given feedback procedure
end if;
encrypted := (local_header.bit_flag and 1) /= 0;
-- 13 - Dec - 2002
true_packed_size := File_size_type (local_header.dd.compressed_size);
if encrypted then
true_packed_size := true_packed_size - 12;
end if;
if name_from_header then -- Name from local header is used as output name
the_name_len := Natural (local_header.filename_length);
String'Read (zip_file, the_name (1 .. the_name_len));
if not data_descriptor_after_data then
Inform_User (
the_name (1 .. the_name_len),
true_packed_size,
File_size_type (local_header.dd.uncompressed_size)
);
end if;
if the_name_len = 0 or else
(the_name (the_name_len) = '/' or else
the_name (the_name_len) = '\')
then
-- This is a directory name (12 - feb - 2000)
skip_this_file := True;
elsif actual_mode in Write_to_file then
Set_outfile_interactive (the_name (1 .. the_name_len));
else -- only informational, no need for interaction
Set_outfile (the_name (1 .. the_name_len));
end if;
else -- Output name is given : out_name
if not data_descriptor_after_data then
Inform_User (
out_name,
true_packed_size,
File_size_type (local_header.dd.uncompressed_size)
);
end if;
if out_name'Length = 0 or else
(out_name (out_name'Last) = '/' or else
out_name (out_name'Last) = '\')
then
-- This is a directory name, so do not write anything (30 - Jan - 2012).
skip_this_file := True;
elsif actual_mode in Write_to_file then
Set_outfile_interactive (out_name);
else -- only informational, no need for interaction
Set_outfile (out_name);
end if;
end if;
if skip_this_file then
actual_mode := just_test;
end if;
if skip_this_file and not data_descriptor_after_data then
-- We can skip actually since sizes are known.
if feedback /= null then
feedback (
percents_done => 0,
entry_skipped => True,
user_abort => dummy_bool
);
end if;
else
begin
Set_Index (zip_file, work_index); -- eventually skips the file name
exception
when others => raise Read_Error;
end;
UnZip.Decompress.Decompress_data (
zip_file => zip_file,
format => method,
mode => actual_mode,
output_file_name => To_String (the_output_name),
output_memory_access => dummy,
feedback => actual_feedback,
explode_literal_tree => (local_header.bit_flag and 4) /= 0,
explode_slide_8KB => (local_header.bit_flag and 2) /= 0,
end_data_descriptor => data_descriptor_after_data,
encrypted => encrypted,
password => password,
get_new_password => get_pwd,
hint => local_header.dd
);
if actual_mode /= just_test then
if file_system_routines.Set_Time_Stamp /= null then
file_system_routines.Set_Time_Stamp (
To_String (the_output_name),
Convert (local_header.file_timedate)
);
elsif file_system_routines.Set_ZTime_Stamp /= null then
file_system_routines.Set_ZTime_Stamp (
To_String (the_output_name),
local_header.file_timedate
);
end if;
end if;
if data_descriptor_after_data then -- Sizes and CRC at the end
-- Inform after decompression
Inform_User (
To_String (the_output_name),
local_header.dd.compressed_size,
local_header.dd.uncompressed_size
);
end if;
end if; -- not (skip_this_file and not data_descriptor)
-- Set the offset on the next zipped file
header_index := header_index + Positive (
Ada.Streams.Stream_IO.Count (
File_size_type (
local_header.filename_length +
local_header.extra_field_length +
Zip.Headers.local_header_length
) +
local_header.dd.compressed_size
));
if data_descriptor_after_data then
header_index :=
header_index + Positive (
Ada.Streams.Stream_IO.Count (Zip.Headers.data_descriptor_length));
end if;
end UnZipFile;
----------------------------------
-- Simple extraction procedures --
----------------------------------
-- Extract all files from an archive (from)
procedure Extract (from : String;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, null, null, null, null,
options, password, file_system_routines);
end Extract;
procedure Extract (from : String;
what : String;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, what, null, null, null, null,
options, password, file_system_routines);
end Extract;
procedure Extract (from : String;
what : String;
rename : String;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, what, rename, null, null, null,
options, password, file_system_routines);
end Extract;
procedure Extract (from : Zip.Zip_info;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, null, null, null, null,
options, password, file_system_routines);
end Extract;
procedure Extract (from : Zip.Zip_info;
what : String;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, what, null, null, null, null,
options, password, file_system_routines);
end Extract;
procedure Extract (from : Zip.Zip_info;
what : String;
rename : String;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
begin
Extract (from, what, rename, null, null, null,
options, password, file_system_routines);
end Extract;
-- All previous extract call the following ones, with bogus UI arguments
------------------------------------------------------------
-- All previous extraction procedures, for user interface --
------------------------------------------------------------
use Ada.Streams.Stream_IO;
-- Extract one precise file (what) from an archive (from)
procedure Extract (from : String;
what : String;
feedback : Zip.Feedback_proc;
help_the_file_exists : Resolve_conflict_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines) is
use Zip, Zip_Streams;
MyStream : aliased File_Zipstream;
-- was Unbounded_Stream & file - >buffer copy in v.26
zip_file : constant Zipstream_Class := MyStream'Unchecked_Access;
header_index : Positive;
comp_size : File_size_type;
uncomp_size : File_size_type;
work_password : Unbounded_String := To_Unbounded_String (password);
begin
if feedback = null then
current_user_attitude := yes_to_all; -- non - interactive
end if;
Set_Name (zip_file, from);
Open (MyStream, In_File);
Zip.Find_offset (zip_file,
what, options (case_sensitive_match),
header_index,
comp_size,
uncomp_size);
pragma Unreferenced (uncomp_size);
UnZipFile (zip_file,
what, False,
header_index,
comp_size,
feedback, help_the_file_exists, tell_data, get_pwd,
options,
work_password,
file_system_routines);
pragma Unreferenced (header_index, work_password);
Close (MyStream);
end Extract;
-- Extract one precise file (what) from an archive (from),
-- but save under a new name (rename)
procedure Extract (from : String;
what : String;
rename : String;
feedback : Zip.Feedback_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
)
is
use Zip, Zip_Streams;
MyStream : aliased File_Zipstream;
-- was Unbounded_Stream & file - >buffer copy in v.26
zip_file : constant Zipstream_Class := MyStream'Unchecked_Access;
header_index : Positive;
comp_size : File_size_type;
uncomp_size : File_size_type;
work_password : Unbounded_String := To_Unbounded_String (password);
begin
if feedback = null then
current_user_attitude := yes_to_all; -- non - interactive
end if;
Set_Name (zip_file, from);
Open (MyStream, In_File);
Zip.Find_offset (zip_file,
what, options (case_sensitive_match),
header_index,
comp_size,
uncomp_size);
pragma Unreferenced (uncomp_size);
UnZipFile (zip_file,
rename, False,
header_index,
comp_size,
feedback, null, tell_data, get_pwd,
options,
work_password,
file_system_routines);
pragma Unreferenced (header_index, work_password);
Close (MyStream);
end Extract;
-- Extract all files from an archive (from)
procedure Extract (from : String;
feedback : Zip.Feedback_proc;
help_the_file_exists : Resolve_conflict_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
)
is
use Zip, Zip_Streams;
MyStream : aliased File_Zipstream;
-- was Unbounded_Stream & file - >buffer copy in v.26
zip_file : constant Zipstream_Class := MyStream'Unchecked_Access;
header_index : Positive;
work_password : Unbounded_String := To_Unbounded_String (password);
begin
if feedback = null then
current_user_attitude := yes_to_all; -- non - interactive
end if;
Set_Name (zip_file, from);
Open (MyStream, In_File);
Zip.Find_first_offset (zip_file, header_index); -- >= 13 - May - 2001
-- We simply unzip everything sequentially, until the end:
all_files : loop
UnZipFile (
zip_file,
"", True,
header_index,
File_size_type'Last,
-- ^ no better hint available if comp_size is 0 in local header
feedback, help_the_file_exists, tell_data, get_pwd,
options,
work_password,
file_system_routines
);
end loop all_files;
exception
when Zip.Headers.bad_local_header =>
Close (MyStream); -- normal case : end was hit
when Zip.Zip_file_open_Error =>
raise; -- couldn't open zip file
when others =>
Close (MyStream);
raise; -- something else wrong
end Extract;
-- Extract all files from an archive (from)
-- Needs Zip.Load (from, . .. ) prior to the extraction
procedure Extract (from : Zip.Zip_info;
feedback : Zip.Feedback_proc;
help_the_file_exists : Resolve_conflict_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
)
is
procedure Extract_1_file (name : String) is
begin
Extract (from => from,
what => name,
feedback => feedback,
help_the_file_exists => help_the_file_exists,
tell_data => tell_data,
get_pwd => get_pwd,
options => options,
password => password,
file_system_routines => file_system_routines
);
end Extract_1_file;
--
procedure Extract_all_files is new Zip.Traverse (Extract_1_file);
--
begin
Extract_all_files (from);
end Extract;
-- Extract one precise file (what) from an archive (from)
-- Needs Zip.Load (from, . .. ) prior to the extraction
procedure Extract (from : Zip.Zip_info;
what : String;
feedback : Zip.Feedback_proc;
help_the_file_exists : Resolve_conflict_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
header_index : Positive;
comp_size : File_size_type;
uncomp_size : File_size_type;
work_password : Unbounded_String := To_Unbounded_String (password);
use Zip, Zip_Streams;
MyStream : aliased File_Zipstream;
input_stream : Zipstream_Class;
use_a_file : constant Boolean := Zip.Zip_Stream (from) = null;
begin
if use_a_file then
input_stream := MyStream'Unchecked_Access;
Set_Name (input_stream, Zip.Zip_name (from));
Open (MyStream, Ada.Streams.Stream_IO.In_File);
else -- use the given stream
input_stream := Zip.Zip_Stream (from);
end if;
if feedback = null then
current_user_attitude := yes_to_all; -- non - interactive
end if;
Zip.Find_offset (from, what, options (case_sensitive_match),
Ada.Streams.Stream_IO.Positive_Count (header_index),
comp_size,
uncomp_size);
pragma Unreferenced (uncomp_size);
UnZipFile (input_stream,
what, False,
header_index,
comp_size,
feedback, help_the_file_exists, tell_data, get_pwd,
options,
work_password,
file_system_routines);
pragma Unreferenced (header_index, work_password);
if use_a_file then
Close (MyStream);
end if;
end Extract;
-- Extract one precise file (what) from an archive (from)
-- but save under a new name (rename)
-- Needs Zip.Load (from, . .. ) prior to the extraction
procedure Extract (from : Zip.Zip_info;
what : String;
rename : String;
feedback : Zip.Feedback_proc;
tell_data : Tell_data_proc;
get_pwd : Get_password_proc;
options : Option_set := no_option;
password : String := "";
file_system_routines : FS_routines_type := null_routines
) is
header_index : Positive;
comp_size : File_size_type;
uncomp_size : File_size_type;
work_password : Unbounded_String := To_Unbounded_String (password);
use Zip, Zip_Streams;
MyStream : aliased File_Zipstream;
input_stream : Zipstream_Class;
use_a_file : constant Boolean := Zip.Zip_Stream (from) = null;
begin
if use_a_file then
input_stream := MyStream'Unchecked_Access;
Set_Name (input_stream, Zip.Zip_name (from));
Open (MyStream, Ada.Streams.Stream_IO.In_File);
else -- use the given stream
input_stream := Zip.Zip_Stream (from);
end if;
if feedback = null then
current_user_attitude := yes_to_all; -- non - interactive
end if;
Zip.Find_offset (from, what, options (case_sensitive_match),
Ada.Streams.Stream_IO.Positive_Count (header_index),
comp_size,
uncomp_size);
pragma Unreferenced (uncomp_size);
UnZipFile (input_stream,
rename,
False,
header_index,
comp_size,
feedback, null, tell_data, get_pwd,
options,
work_password,
file_system_routines);
pragma Unreferenced (header_index, work_password);
if use_a_file then
Close (MyStream);
end if;
end Extract;
end UnZip;
|
with Multiply_Proof; use Multiply_Proof;
package body Curve25519_Mult with
SPARK_Mode
is
--------------
-- Multiply --
--------------
function Multiply (X, Y : Integer_255) return Product_Integer is
Product : Product_Integer := (others => 0);
begin
for J in Index_Type loop
for K in Index_Type loop
Product (J + K) :=
Product (J + K)
+ X (J) * Y (K) * (if J mod 2 = 1 and then K mod 2 = 1 then 2 else 1);
Partial_Product_Def (X, Y, J, K);
-- Reminding definition of Partial_Product
pragma Loop_Invariant ((for all L in 0 .. J - 1 =>
Product (L) = Product'Loop_Entry (L))
and then
(for all L in J + K + 1 .. 18 =>
Product (L) = Product'Loop_Entry (L)));
-- To signify at which indexes content has not been changed
pragma Loop_Invariant (for all L in J .. J + K =>
Product (L) = Partial_Product (X, Y, J, L - J));
-- Increasingly proving the value of Product (L)
end loop;
pragma Loop_Invariant (for all L in J + 10 .. 18 =>
Product (L) = Product'Loop_Entry (L));
-- To signify at which indexes content has not been changed
pragma Loop_Invariant (for all L in Product_Index_Type =>
Product (L) in
(-2) * Long_Long_Integer (J + 1) * (2**27 - 1)**2
..
2 * Long_Long_Integer (J + 1) * (2**27 - 1)**2);
-- To prove overflow checks
pragma Loop_Invariant (for all L in 0 .. J + 9 =>
Product (L) = Array_Step_J (X, Y, J) (L));
-- Product is partially equal to Array_Step_J (X, Y, J);
end loop;
Prove_Multiply (X, Y, Product);
return Product;
end Multiply;
end Curve25519_Mult;
|
--===========================================================================
--
-- This package is the slave configuration for the Pico
-- use cases:
-- 1: Master Pico -> Slave Pico
-- 3: Master ItsyBitsy -> Slave Pico
--
--===========================================================================
--
-- Copyright 2022 (C) Holger Rodriguez
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with HAL.SPI;
with RP.Device;
with RP.GPIO;
with RP.SPI;
with Pico;
package SPI_Slave_Pico is
-----------------------------------------------------------------------
-- Slave section
SPI : RP.SPI.SPI_Port renames RP.Device.SPI_0;
SCK : RP.GPIO.GPIO_Point renames Pico.GP18;
NSS : RP.GPIO.GPIO_Point renames Pico.GP17;
MOSI : RP.GPIO.GPIO_Point renames Pico.GP16;
MISO : RP.GPIO.GPIO_Point renames Pico.GP19;
-----------------------------------------------------------------------
-- Configuration for the slave part for the Pico
Config : constant RP.SPI.SPI_Configuration
:= (Role => RP.SPI.Slave,
Baud => 10_000_000,
Data_Size => HAL.SPI.Data_Size_16b,
others => <>);
-----------------------------------------------------------------------
-- Initializes the Pico as slave
procedure Initialize;
end SPI_Slave_Pico;
|
pragma License (Unrestricted);
-- extended unit
with Ada.References.Wide_Wide_Strings;
with Ada.Streams.Block_Transmission.Wide_Wide_Strings;
with Ada.Strings.Generic_Bounded;
package Ada.Strings.Bounded_Wide_Wide_Strings is
new Generic_Bounded (
Wide_Wide_Character,
Wide_Wide_String,
Streams.Block_Transmission.Wide_Wide_Strings.Read,
Streams.Block_Transmission.Wide_Wide_Strings.Write,
References.Wide_Wide_Strings.Slicing);
pragma Preelaborate (Ada.Strings.Bounded_Wide_Wide_Strings);
|
-- Abstract:
--
-- An unbounded queue of definite non-limited elements.
--
-- Copyright (C) 2017 - 2019 Free Software Foundation, Inc.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with SAL.Gen_Definite_Doubly_Linked_Lists;
generic
type Element_Type is private;
package SAL.Gen_Unbounded_Definite_Queues is
package Pkg renames SAL.Gen_Unbounded_Definite_Queues;
type Queue is tagged private;
Empty_Queue : constant Queue;
procedure Clear (Queue : in out Pkg.Queue);
-- Empty Queue.
function Count (Queue : in Pkg.Queue) return Base_Peek_Type;
-- Return count of items in the Queue
function Length (Queue : in Pkg.Queue) return Base_Peek_Type renames Count;
function Is_Empty (Queue : in Pkg.Queue) return Boolean;
-- Return true if no items are in Queue.
function Is_Full (Queue : in Pkg.Queue) return Boolean is (False);
-- Return true if Queue is full.
function Remove (Queue : in out Pkg.Queue) return Element_Type;
-- Remove head/front item from Queue, return it.
--
-- Raise Container_Empty if Is_Empty.
function Get (Queue : in out Pkg.Queue) return Element_Type renames Remove;
procedure Drop (Queue : in out Pkg.Queue);
-- Remove head/front item from Queue, discard it.
--
-- Raise Container_Empty if Is_Empty.
type Constant_Reference_Type (Element : not null access constant Element_Type) is private
with
Implicit_Dereference => Element;
function Peek (Queue : in Pkg.Queue; N : Peek_Type := 1) return Constant_Reference_Type;
pragma Inline (Peek);
-- Return a constant reference to a queue item. N = 1 is the queue
-- head.
--
-- Raise Parameter_Error if N > Count
type Variable_Reference_Type (Element : not null access Element_Type) is private
with Implicit_Dereference => Element;
function Variable_Peek (Queue : in out Pkg.Queue; N : Peek_Type := 1) return Variable_Reference_Type;
pragma Inline (Variable_Peek);
-- Return a variable reference to a queue item. N = 1 is the queue
-- head.
--
-- Raises Parameter_Error if N > Count
procedure Add (Queue : in out Pkg.Queue; Item : in Element_Type);
-- Add Element to the tail/back of Queue.
procedure Put (Queue : in out Pkg.Queue; Item : in Element_Type) renames Add;
procedure Add_To_Head (Queue : in out Pkg.Queue; Item : in Element_Type);
-- Add Element to the head/front of Queue.
private
package Element_Lists is new SAL.Gen_Definite_Doubly_Linked_Lists (Element_Type);
-- We don't provide cursors or write access to queue elements, so we
-- don't need any tampering checks.
type Queue is tagged record
Data : Element_Lists.List;
-- Add at Tail/Back = Last, remove at Head/Front = First.
end record;
type Constant_Reference_Type (Element : not null access constant Element_Type) is
record
Dummy : Integer := raise Program_Error with "uninitialized reference";
end record;
type Variable_Reference_Type (Element : not null access Element_Type) is
record
Dummy : Integer := raise Program_Error with "uninitialized reference";
end record;
Empty_Queue : constant Queue := (Data => Element_Lists.Empty_List);
end SAL.Gen_Unbounded_Definite_Queues;
|
with Ada.Finalization;
generic
type Data_Type is private;
type Data_Access is access Data_Type;
package kv.Ref_Counting_Mixin is
type Control_Type is
record
Count : Natural := 0;
Data : Data_Access;
end record;
type Control_Access is access Control_Type;
type Ref_Type is new Ada.Finalization.Controlled with
record
Control : Control_Access;
end record;
overriding procedure Initialize(Self : in out Ref_Type);
overriding procedure Adjust(Self : in out Ref_Type);
overriding procedure Finalize(Self : in out Ref_Type);
procedure Set(Self : in out Ref_Type; Data : in Data_Access);
function Get(Self : Ref_Type) return Data_Access;
end kv.Ref_Counting_Mixin;
|
with Agar.Core.Thin;
with C_String;
with Interfaces.C;
package body Agar.Core.Error is
package C renames Interfaces.C;
procedure Set_Error (Message : in String) is
Ch_Message : aliased C.char_array := C.To_C (Message);
Ch_Format : aliased C.char_array := C.To_C ("%s");
begin
Thin.Error.Set_Error
(Format => C_String.To_C_String (Ch_Format'Unchecked_Access),
Data => C_String.To_C_String (Ch_Message'Unchecked_Access));
end Set_Error;
procedure Fatal_Error (Message : in String) is
Ch_Message : aliased C.char_array := C.To_C (Message);
Ch_Format : aliased C.char_array := C.To_C ("%s");
begin
Thin.Error.Fatal_Error
(Format => C_String.To_C_String (Ch_Format'Unchecked_Access),
Data => C_String.To_C_String (Ch_Message'Unchecked_Access));
end Fatal_Error;
--
-- Proxy procedure to call error callback from C code.
--
Error_Callback : Error_Callback_t := null;
procedure Caller (Message : C_String.String_Not_Null_Ptr_t);
pragma Convention (C, Caller);
procedure Caller (Message : in C_String.String_Not_Null_Ptr_t) is
begin
if Error_Callback /= null then
Error_Callback.all (C_String.To_String (Message));
end if;
end Caller;
procedure Set_Fatal_Callback
(Callback : Error_Callback_Not_Null_t) is
begin
Error_Callback := Callback;
Thin.Error.Set_Fatal_Callback (Caller'Access);
end Set_Fatal_Callback;
end Agar.Core.Error;
|
Put_Line ("Mary had a " & New_Str & " lamb.");
|
--
-- Copyright (C) 2015-2016 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
package HW.GFX.GMA.Display_Probing
is
type Port_List_Range is range 0 .. 7;
type Port_List is array (Port_List_Range) of Port_Type;
All_Ports : constant Port_List :=
(DP1, DP2, DP3, HDMI1, HDMI2, HDMI3, Analog, Internal);
procedure Scan_Ports
(Configs : out Pipe_Configs;
Ports : in Port_List := All_Ports;
Max_Pipe : in Pipe_Index := Pipe_Index'Last;
Keep_Power : in Boolean := False);
end HW.GFX.GMA.Display_Probing;
|
with ada.text_io, ada.integer_text_io, sacar_ficha, lanzar_dado;
use ada.text_io, ada.integer_text_io;
procedure prueba_parchis is
dado, intentos:integer:=0;
begin
loop exit when intentos=4 or dado=5;
dado:=lanzar_dado(dado);
intentos:=intentos+1;
put("Dado: ");
put(dado); -- Aunque no sea necesario lo he utilizado para verificar el funcionamiento del programa.
new_line;
end loop;
if dado=5 then
sacar_ficha;
else if intentos=4 then
put("Limite de intentos superados");
end if;
end if;
new_line;
put("Intentos utilizados:"); -- Aunque no sea necesario lo he utilizado para verificar el funcionamiento del programa.
put(intentos);
end prueba_parchis;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Latin_1;
procedure Bell is
begin
Put(Ada.Characters.Latin_1.BEL);
end Bell;
|
------------------------------------------------------------------------------
-- A d a r u n - t i m e s p e c i f i c a t i o n --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of ada.ads file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $
with Ada.Task_Identification; use Ada.Task_Identification;
generic
type Attribute is private;
Initial_Value : in Attribute;
package Ada.Task_Attributes is
type Attribute_Handle is access all Attribute;
function Value (T : Task_Id := Current_Task) return Attribute;
function Reference (T : Task_Id := Current_Task) return Attribute_Handle;
procedure Set_Value (Val : in Attribute;
T : in Task_Id := Current_Task);
procedure Reinitialize (T : in Task_Id := Current_Task);
end Ada.Task_Attributes;
|
-- Abstract :
--
-- See spec.
--
-- Copyright (C) 2018 - 2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or
-- modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or (at
-- your option) any later version. This 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
-- distributed with this program; see file COPYING. If not, write to
-- the Free Software Foundation, 51 Franklin Street, Suite 500, Boston,
-- MA 02110-1335, USA.
pragma License (GPL);
with Ada.Command_Line;
with Ada.Directories;
with Ada.Exceptions;
with Ada.Strings.Fixed;
with Ada.Text_IO;
with GNAT.OS_Lib;
with GNAT.Traceback.Symbolic;
with SAL;
with System.Multiprocessors;
with System.Storage_Elements;
with WisiToken.Lexer;
package body Emacs_Wisi_Common_Parse is
procedure Usage (Name : in String)
is
use Ada.Text_IO;
begin
Put_Line ("usage: " & Name & "[--recover-log <file-name>]");
Put_Line ("enters a loop waiting for commands:");
Put_Line ("Prompt is '" & Prompt & "'");
Put_Line ("commands are case sensitive");
Put_Line ("See wisi-process-parse.el *--send-parse, *--send-noop for arguments.");
end Usage;
procedure Read_Input (A : System.Address; N : Integer)
is
use System.Storage_Elements;
B : System.Address := A;
Remaining : Integer := N;
Read : Integer;
begin
-- We use GNAT.OS_Lib because it does not buffer input, so it runs
-- under Emacs nicely; GNAT Text_IO does not return text until
-- some fairly large buffer is filled.
--
-- With GNAT GPL 2016, GNAT.OS_Lib.Read does _not_ wait for all N
-- bytes or EOF; it returns as soon as it gets some bytes.
loop
Read := GNAT.OS_Lib.Read (GNAT.OS_Lib.Standin, B, Remaining);
if Read = 0 then
-- Pipe closed; probably parent Emacs crashed. Force exit.
raise SAL.Programmer_Error with "input pipe closed";
end if;
Remaining := Remaining - Read;
exit when Remaining <= 0;
B := B + Storage_Offset (Read);
end loop;
end Read_Input;
function Get_Command_Length return Integer
is
Temp : aliased String (1 .. 3) := (others => ' '); -- initialize for error message
begin
Read_Input (Temp'Address, Temp'Length);
return Integer'Value (Temp);
exception
when Constraint_Error =>
-- From Integer'Value
raise Protocol_Error with "invalid command byte count; '" & Temp & "'";
end Get_Command_Length;
function Get_String
(Source : in String;
Last : in out Integer)
return String
is
use Ada.Strings.Fixed;
First : constant Integer := Index
(Source => Source,
Pattern => """",
From => Last + 1);
begin
Last := Index
(Source => Source,
Pattern => """",
From => First + 1);
if First = 0 or Last = 0 then
raise Protocol_Error with "no '""' found for string";
end if;
return Source (First + 1 .. Last - 1);
end Get_String;
function Get_Integer
(Source : in String;
Last : in out Integer)
return Integer
is
use Ada.Strings.Fixed;
First : constant Integer := Last + 2; -- final char of previous item, space
begin
Last := Index
(Source => Source,
Pattern => " ",
From => First);
if Last = 0 then
Last := Source'Last;
else
Last := Last - 1;
end if;
return Integer'Value (Source (First .. Last));
exception
when others =>
Ada.Text_IO.Put_Line ("bad integer '" & Source (First .. Source'Last) & "'");
raise;
end Get_Integer;
function Get_Process_Start_Params return Process_Start_Params
is
use Ada.Command_Line;
procedure Put_Usage
is
use Ada.Text_IO;
begin
Put_Line (Standard_Error, "process start args:");
Put_Line (Standard_Error, "--help : put this help");
Put_Line (Standard_Error, "--recover-log <file_name> : log recover actions to file");
end Put_Usage;
Next_Arg : Integer := 1;
begin
return Result : Process_Start_Params do
loop
exit when Next_Arg > Argument_Count;
if Next_Arg <= Argument_Count and then Argument (Next_Arg) = "--help" then
Put_Usage;
raise Finish;
elsif Next_Arg + 1 <= Argument_Count and then Argument (Next_Arg) = "--recover-log" then
Result.Recover_Log_File_Name := Ada.Strings.Unbounded.To_Unbounded_String (Argument (Next_Arg + 1));
Next_Arg := Next_Arg + 2;
end if;
end loop;
end return;
end Get_Process_Start_Params;
function Get_Parse_Params (Command_Line : in String; Last : in out Integer) return Parse_Params
is
use WisiToken;
begin
return Result : Parse_Params do
-- We don't use an aggregate, to enforce execution order.
-- Match wisi-process-parse.el wisi-process--send-parse
Result.Post_Parse_Action := Wisi.Post_Parse_Action_Type'Val (Get_Integer (Command_Line, Last));
Result.Source_File_Name := +Get_String (Command_Line, Last);
Result.Begin_Byte_Pos := Get_Integer (Command_Line, Last);
-- Emacs end is after last char.
Result.End_Byte_Pos := Get_Integer (Command_Line, Last) - 1;
Result.Goal_Byte_Pos := Get_Integer (Command_Line, Last);
Result.Begin_Char_Pos := WisiToken.Buffer_Pos (Get_Integer (Command_Line, Last));
Result.Begin_Line := WisiToken.Line_Number_Type (Get_Integer (Command_Line, Last));
Result.End_Line := WisiToken.Line_Number_Type (Get_Integer (Command_Line, Last));
Result.Begin_Indent := Get_Integer (Command_Line, Last);
Result.Partial_Parse_Active := 1 = Get_Integer (Command_Line, Last);
Result.Debug_Mode := 1 = Get_Integer (Command_Line, Last);
Result.Parse_Verbosity := Get_Integer (Command_Line, Last);
Result.McKenzie_Verbosity := Get_Integer (Command_Line, Last);
Result.Action_Verbosity := Get_Integer (Command_Line, Last);
Result.McKenzie_Disable := Get_Integer (Command_Line, Last);
Result.Task_Count := Get_Integer (Command_Line, Last);
Result.Check_Limit := Get_Integer (Command_Line, Last);
Result.Enqueue_Limit := Get_Integer (Command_Line, Last);
Result.Max_Parallel := Get_Integer (Command_Line, Last);
Result.Byte_Count := Get_Integer (Command_Line, Last);
end return;
end Get_Parse_Params;
function Get_Refactor_Params (Command_Line : in String; Last : in out Integer) return Refactor_Params
is
use WisiToken;
begin
return Result : Refactor_Params do
-- We don't use an aggregate, to enforce execution order.
-- Match wisi-process-parse.el wisi-process--send-refactor
Result.Refactor_Action := Get_Integer (Command_Line, Last);
Result.Source_File_Name := +Get_String (Command_Line, Last);
Result.Parse_Region.First := WisiToken.Buffer_Pos (Get_Integer (Command_Line, Last));
Result.Parse_Region.Last := WisiToken.Buffer_Pos (Get_Integer (Command_Line, Last) - 1);
Result.Edit_Begin := WisiToken.Buffer_Pos (Get_Integer (Command_Line, Last));
Result.Parse_Begin_Char_Pos := WisiToken.Buffer_Pos (Get_Integer (Command_Line, Last));
Result.Parse_Begin_Line := WisiToken.Line_Number_Type (Get_Integer (Command_Line, Last));
Result.Parse_End_Line := WisiToken.Line_Number_Type (Get_Integer (Command_Line, Last));
Result.Debug_Mode := 1 = Get_Integer (Command_Line, Last);
Result.Parse_Verbosity := Get_Integer (Command_Line, Last);
Result.Action_Verbosity := Get_Integer (Command_Line, Last);
Result.Max_Parallel := Get_Integer (Command_Line, Last);
Result.Byte_Count := Get_Integer (Command_Line, Last);
end return;
end Get_Refactor_Params;
procedure Process_Stream
(Name : in String;
Language_Protocol_Version : in String;
Partial_Parse_Active : in out Boolean;
Params : in Process_Start_Params;
Parser : in out WisiToken.Parse.LR.Parser.Parser;
Parse_Data : in out Wisi.Parse_Data_Type'Class;
Descriptor : in WisiToken.Descriptor)
is
use Ada.Text_IO;
use WisiToken; -- "+", "-" Unbounded_string
procedure Cleanup
is begin
if Is_Open (Parser.Recover_Log_File) then
Close (Parser.Recover_Log_File);
end if;
end Cleanup;
begin
declare
use Ada.Directories;
use Ada.Strings.Unbounded;
begin
if Length (Params.Recover_Log_File_Name) > 0 then
Put_Line (";; logging to '" & (-Params.Recover_Log_File_Name) & "'");
-- to Current_Output, visible from Emacs
if Exists (-Params.Recover_Log_File_Name) then
Open (Parser.Recover_Log_File, Append_File, -Params.Recover_Log_File_Name);
else
Create (Parser.Recover_Log_File, Out_File, -Params.Recover_Log_File_Name);
end if;
end if;
end;
Parser.Trace.Set_Prefix (";; "); -- so debug messages don't confuse Emacs.
Put_Line
(Name & " protocol: process version " & Protocol_Version & " language version " & Language_Protocol_Version);
-- Read commands and tokens from standard_input via GNAT.OS_Lib,
-- send results to standard_output.
loop
Put (Prompt); Flush;
declare
Command_Length : constant Integer := Get_Command_Length;
Command_Line : aliased String (1 .. Command_Length);
Last : Integer;
function Match (Target : in String) return Boolean
is begin
Last := Command_Line'First + Target'Length - 1;
return Last <= Command_Line'Last and then Command_Line (Command_Line'First .. Last) = Target;
end Match;
begin
Read_Input (Command_Line'Address, Command_Length);
Put_Line (";; " & Command_Line);
if Match ("parse") then
-- Args: see wisi-process-parse.el wisi-process-parse--send-parse
-- Input: <source text>
-- Response:
-- [response elisp vector]...
-- [elisp error form]...
-- prompt
declare
Params : constant Parse_Params := Get_Parse_Params (Command_Line, Last);
Buffer : Ada.Strings.Unbounded.String_Access;
procedure Clean_Up
is
use all type SAL.Base_Peek_Type;
begin
Parser.Lexer.Discard_Rest_Of_Input;
if Parser.Parsers.Count > 0 then
Parse_Data.Put
(Parser.Lexer.Errors,
Parser.Parsers.First.State_Ref.Errors,
Parser.Parsers.First.State_Ref.Tree);
end if;
Ada.Strings.Unbounded.Free (Buffer);
end Clean_Up;
begin
Trace_Parse := Params.Parse_Verbosity;
Trace_McKenzie := Params.McKenzie_Verbosity;
Trace_Action := Params.Action_Verbosity;
Debug_Mode := Params.Debug_Mode;
Partial_Parse_Active := Params.Partial_Parse_Active;
if WisiToken.Parse.LR.McKenzie_Defaulted (Parser.Table.all) then
-- There is no McKenzie information; don't override that.
null;
elsif Params.McKenzie_Disable = -1 then
-- Use default
Parser.Enable_McKenzie_Recover := True;
else
Parser.Enable_McKenzie_Recover := Params.McKenzie_Disable = 0;
end if;
Parse_Data.Initialize
(Post_Parse_Action => Params.Post_Parse_Action,
Lexer => Parser.Lexer,
Descriptor => Descriptor'Unrestricted_Access,
Base_Terminals => Parser.Terminals'Unrestricted_Access,
Begin_Line => Params.Begin_Line,
End_Line => Params.End_Line,
Begin_Indent => Params.Begin_Indent,
Params => Command_Line (Last + 2 .. Command_Line'Last));
if Params.Task_Count > 0 then
Parser.Table.McKenzie_Param.Task_Count := System.Multiprocessors.CPU_Range (Params.Task_Count);
end if;
if Params.Check_Limit > 0 then
Parser.Table.McKenzie_Param.Check_Limit := Base_Token_Index (Params.Check_Limit);
end if;
if Params.Enqueue_Limit > 0 then
Parser.Table.McKenzie_Param.Enqueue_Limit := Params.Enqueue_Limit;
end if;
if Params.Max_Parallel > 0 then
Parser.Max_Parallel := SAL.Base_Peek_Type (Params.Max_Parallel);
end if;
Buffer := new String (Params.Begin_Byte_Pos .. Params.End_Byte_Pos);
Read_Input (Buffer (Params.Begin_Byte_Pos)'Address, Params.Byte_Count);
Parser.Lexer.Reset_With_String_Access
(Buffer, Params.Source_File_Name, Params.Begin_Char_Pos, Params.Begin_Line);
begin
Parser.Parse;
exception
when WisiToken.Partial_Parse =>
null;
end;
Parser.Execute_Actions;
Parse_Data.Put (Parser);
Clean_Up;
exception
when Syntax_Error =>
Clean_Up;
Put_Line ("(parse_error)");
when E : Parse_Error =>
Clean_Up;
Put_Line ("(parse_error """ & Ada.Exceptions.Exception_Message (E) & """)");
when E : Fatal_Error =>
Clean_Up;
Put_Line ("(error """ & Ada.Exceptions.Exception_Message (E) & """)");
end;
elsif Match ("refactor") then
-- Args: see wisi-process-parse.el wisi-process-parse--send-refactor
-- Input: <source text>
-- Response:
-- [edit elisp vector]...
-- prompt
declare
Params : constant Refactor_Params := Get_Refactor_Params (Command_Line, Last);
Buffer : Ada.Strings.Unbounded.String_Access;
procedure Clean_Up
is
use all type SAL.Base_Peek_Type;
begin
Parser.Lexer.Discard_Rest_Of_Input;
if Parser.Parsers.Count > 0 then
Parse_Data.Put
(Parser.Lexer.Errors,
Parser.Parsers.First.State_Ref.Errors,
Parser.Parsers.First.State_Ref.Tree);
end if;
Ada.Strings.Unbounded.Free (Buffer);
end Clean_Up;
begin
Trace_Parse := Params.Parse_Verbosity;
Trace_Action := Params.Action_Verbosity;
Debug_Mode := Params.Debug_Mode;
Partial_Parse_Active := True;
Parse_Data.Initialize
(Post_Parse_Action => Wisi.Navigate, -- mostly ignored
Lexer => Parser.Lexer,
Descriptor => Descriptor'Unrestricted_Access,
Base_Terminals => Parser.Terminals'Unrestricted_Access,
Begin_Line => Params.Parse_Begin_Line,
End_Line => Params.Parse_End_Line,
Begin_Indent => 0,
Params => "");
if Params.Max_Parallel > 0 then
Parser.Max_Parallel := SAL.Base_Peek_Type (Params.Max_Parallel);
end if;
Buffer := new String (Integer (Params.Parse_Region.First) .. Integer (Params.Parse_Region.Last));
Read_Input (Buffer (Buffer'First)'Address, Params.Byte_Count);
Parser.Lexer.Reset_With_String_Access
(Buffer, Params.Source_File_Name, Params.Parse_Begin_Char_Pos, Params.Parse_Begin_Line);
begin
Parser.Parse;
exception
when WisiToken.Partial_Parse =>
null;
end;
Parser.Execute_Actions;
Parse_Data.Refactor (Parser.Parsers.First_State_Ref.Tree, Params.Refactor_Action, Params.Edit_Begin);
Clean_Up;
exception
when Syntax_Error =>
Clean_Up;
Put_Line ("(parse_error ""refactor " & Params.Parse_Region.First'Image &
Params.Parse_Region.Last'Image & ": syntax error"")");
when E : Parse_Error =>
Clean_Up;
Put_Line ("(parse_error ""refactor " & Params.Parse_Region.First'Image &
Params.Parse_Region.Last'Image & ": " & Ada.Exceptions.Exception_Message (E) & """)");
when E : others => -- includes Fatal_Error
Clean_Up;
Put_Line ("(error """ & Ada.Exceptions.Exception_Message (E) & """)");
end;
elsif Match ("noop") then
-- Args: <source byte count>
-- Input: <source text>
-- Response: prompt
declare
Byte_Count : constant Integer := Get_Integer (Command_Line, Last);
Buffer : constant Ada.Strings.Unbounded.String_Access := new String (1 .. Byte_Count);
Token : Base_Token;
Lexer_Error : Boolean;
pragma Unreferenced (Lexer_Error);
begin
Token.ID := Invalid_Token_ID;
Read_Input (Buffer (1)'Address, Byte_Count);
Parser.Lexer.Reset_With_String_Access (Buffer, +"");
loop
exit when Token.ID = Parser.Trace.Descriptor.EOI_ID;
Lexer_Error := Parser.Lexer.Find_Next (Token);
end loop;
exception
when Syntax_Error =>
Parser.Lexer.Discard_Rest_Of_Input;
end;
elsif Match ("quit") then
exit;
else
Put_Line ("(error ""bad command: '" & Command_Line & "'"")");
end if;
exception
when E : Protocol_Error =>
-- don't exit the loop; allow debugging bad elisp
Put_Line ("(error ""protocol error "": " & Ada.Exceptions.Exception_Message (E) & """)");
end;
end loop;
Cleanup;
exception
when Finish =>
null;
when E : others =>
Cleanup;
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
New_Line (2);
Put_Line
("(error ""unhandled exception: " & Ada.Exceptions.Exception_Name (E) & ": " &
Ada.Exceptions.Exception_Message (E) & """)");
Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
end Process_Stream;
end Emacs_Wisi_Common_Parse;
|
-- flyweights-untracked_lists.adb
-- A package of singly-linked lists for the Flyweights packages without resource
-- tracking or release
-- Copyright (c) 2016, James Humphry
--
-- Permission to use, copy, modify, and/or distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
-- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
-- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
-- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
-- PERFORMANCE OF THIS SOFTWARE.
pragma Profile (No_Implementation_Extensions);
with Ada.Unchecked_Deallocation;
package body Flyweights.Untracked_Lists is
procedure Deallocate_Element is
new Ada.Unchecked_Deallocation(Object => Element,
Name => Element_Access);
procedure Insert (L : in out List;
E : in out Element_Access) is
Node_Ptr : Node_Access := L;
begin
if Node_Ptr = null then
-- List is empty:
-- Create a new node as the first list element
L := new Node'(Next => null,
Data => E);
else
-- List is not empty
-- Check for existing element
loop
if E = Node_Ptr.Data then
-- E is already a pointer to inside the FlyWeight
exit;
elsif E.all = Node_Ptr.Data.all then
-- E's value is a copy of a value already in the FlyWeight
Deallocate_Element(E);
E := Node_Ptr.Data;
exit;
end if;
if Node_Ptr.Next = null then
-- List not empty but element not already present. Add to the end of
-- the list.
Node_Ptr.Next := new Node'(Next => null,
Data => E);
else
Node_Ptr := Node_Ptr.Next;
end if;
end loop;
end if;
end Insert;
procedure Increment (L : in out List;
E : in Element_Access) is
begin
raise Program_Error
with "Attempting to adjust a use-count in an untracked list!";
end Increment;
procedure Remove (L : in out List;
Data_Ptr : in Element_Access) is
begin
raise Program_Error
with "Attempting to free element in an untracked list!";
end Remove;
end Flyweights.Untracked_Lists;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Ada.Command_Line;
with Ada.Text_IO;
with Anagram.Grammars;
with Anagram.Grammars.Reader;
with Anagram.Grammars_Convertors;
with Anagram.Grammars.Rule_Templates;
with Anagram.Grammars_Debug;
with Anagram.Grammars.LR_Tables;
with Anagram.Grammars.LR.LALR;
with Anagram.Grammars.Constructors;
with Anagram.Grammars.Conflicts;
with Writers; use Writers;
with League.String_Vectors;
with League.Strings;
procedure Ada_LARL is
use type Anagram.Grammars.Rule_Count;
use type Anagram.Grammars.LR.State_Count;
procedure Put_Proc_Decl
(Output : in out Writer;
Suffix : Wide_Wide_String);
procedure Put_Piece
(Piece : in out Writer;
From : Anagram.Grammars.Production_Index;
To : Anagram.Grammars.Production_Index);
procedure Put_Rule
(Output : in out Writer;
Prod : Anagram.Grammars.Production;
Rule : Anagram.Grammars.Rule);
function Image (X : Integer) return Wide_Wide_String;
procedure Print_Go_To;
procedure Print_Action;
File : constant String := Ada.Command_Line.Argument (1);
G : constant Anagram.Grammars.Grammar :=
Anagram.Grammars.Reader.Read (File);
Plain : constant Anagram.Grammars.Grammar :=
Anagram.Grammars_Convertors.Convert (G, Left => False);
AG : constant Anagram.Grammars.Grammar :=
Anagram.Grammars.Constructors.To_Augmented (Plain);
Table : constant Anagram.Grammars.LR_Tables.Table_Access :=
Anagram.Grammars.LR.LALR.Build
(Input => AG,
Right_Nulled => False);
Resolver : Anagram.Grammars.Conflicts.Resolver;
Output : Writer;
-----------
-- Image --
-----------
function Image (X : Integer) return Wide_Wide_String is
Img : constant Wide_Wide_String := Integer'Wide_Wide_Image (X);
begin
return Img (2 .. Img'Last);
end Image;
------------------
-- Print_Action --
------------------
procedure Print_Action is
use type Anagram.Grammars.Production_Count;
use type Anagram.Grammars.Part_Count;
type Action_Code is mod 2 ** 16;
Count : Natural;
Code : Action_Code;
begin
Output.P (" type Action_Code is mod 2 ** 16;");
Output.P (" for Action_Code'Size use 16;");
Output.P;
Output.P (" Action_Table : constant array");
Output.N (" (State_Index range 1 .. ");
Output.N (Natural (Anagram.Grammars.LR_Tables.Last_State (Table.all)));
Output.P (",");
Output.N (" Anagram.Grammars.Terminal_Count range 0 .. ");
Output.N (Natural (Plain.Last_Terminal));
Output.P (") of Action_Code :=");
for State in 1 .. Anagram.Grammars.LR_Tables.Last_State (Table.all) loop
if State = 1 then
Output.N (" (");
else
Output.P (",");
Output.N (" ");
end if;
Output.N (Natural (State));
Output.P (" =>");
Output.N (" (");
Count := 0;
for T in 0 .. Plain.Last_Terminal loop
declare
use Anagram.Grammars.LR_Tables;
S : constant Anagram.Grammars.LR.State_Count :=
Shift (Table.all, State, T);
R : constant Reduce_Iterator := Reduce (Table.all, State, T);
begin
if S /= 0 then
Code := Action_Code (S) + 16#80_00#;
elsif not Is_Empty (R) then
Code := Action_Code (Production (R));
else
Code := 0;
end if;
if Code /= 0 then
Output.N (Natural (T));
Output.N (" => ");
Output.N (Natural (Code));
Count := Count + 1;
if Count < 4 then
Output.N (", ");
else
Count := 0;
Output.P (",");
Output.N (" ");
end if;
end if;
end;
end loop;
Output.N ("others => 0)");
end loop;
Output.P (");");
Output.P;
Output.P (" type Production_Record is record");
Output.P (" NT : Anagram.Grammars.Non_Terminal_Index;");
Output.P (" Parts : Natural;");
Output.P (" end record;");
Output.P;
Output.N (" Prods : constant array (Action_Code range 1 .. ");
Output.N (Natural (Plain.Last_Production));
Output.P (") of");
Output.P (" Production_Record :=");
Count := 0;
for J in 1 .. Plain.Last_Production loop
if J = 1 then
Output.N (" (");
elsif Count > 5 then
Count := 0;
Output.P (",");
Output.N (" ");
else
Output.N (", ");
end if;
Output.N ("(");
Output.N (Natural (Plain.Production (J).Parent));
Output.N (", ");
Output.N (Natural (Plain.Production (J).Last
- Plain.Production (J).First + 1));
Output.N (")");
Count := Count + 1;
end loop;
Output.P (");");
Output.P;
Output.P (" procedure Next_Action");
Output.P (" (State : Anagram.Grammars.LR_Parsers.State_Index;");
Output.P (" Token : Anagram.Grammars.Terminal_Count;");
Output.P (" Value : out Anagram.Grammars.LR_Parsers.Action)");
Output.P (" is");
Output.P (" Code : constant Action_Code := " &
"Action_Table (State, Token);");
Output.P (" begin");
Output.P (" if (Code and 16#80_00#) /= 0 then");
Output.P (" Value := (Kind => Shift, " &
"State => State_Index (Code and 16#7F_FF#));");
Output.P (" elsif Code /= 0 then");
Output.P (" Value := (Kind => Reduce,");
Output.P (" Prod => " &
"Anagram.Grammars.Production_Index (Code),");
Output.P (" NT => Prods (Code).NT,");
Output.P (" Parts => Prods (Code).Parts);");
for State in 1 .. Anagram.Grammars.LR_Tables.Last_State (Table.all) loop
if Anagram.Grammars.LR_Tables.Finish (Table.all, State) then
Output.N (" elsif State = ");
Output.N (Natural (State));
Output.P (" then");
Output.P (" Value := (Kind => Finish);");
end if;
end loop;
Output.P (" else");
Output.P (" Value := (Kind => Error);");
Output.P (" end if;");
Output.P (" end Next_Action;");
Output.P;
end Print_Action;
-----------------
-- Print_Go_To --
-----------------
procedure Print_Go_To is
Count : Natural;
begin
Output.P (" Go_To_Table : constant array");
Output.N (" (Anagram.Grammars.LR_Parsers.State_Index range 1 .. ");
Output.N (Natural (Anagram.Grammars.LR_Tables.Last_State (Table.all)));
Output.P (",");
Output.N (" Anagram.Grammars.Non_Terminal_Index range 1 .. ");
Output.N (Natural (Plain.Last_Non_Terminal));
Output.P (") of State_Index :=");
for State in 1 .. Anagram.Grammars.LR_Tables.Last_State (Table.all) loop
if State = 1 then
Output.N (" (");
else
Output.P (",");
Output.N (" ");
end if;
Output.N (Natural (State));
Output.P (" =>");
Output.N (" (");
Count := 0;
for NT in 1 .. Plain.Last_Non_Terminal loop
declare
use Anagram.Grammars.LR;
Next : constant State_Count :=
Anagram.Grammars.LR_Tables.Shift (Table.all, State, NT);
begin
if Next /= 0 then
Output.N (Natural (NT));
Output.N (" => ");
Output.N (Natural (Next));
Count := Count + 1;
if Count < 4 then
Output.N (", ");
else
Count := 0;
Output.P (",");
Output.N (" ");
end if;
end if;
end;
end loop;
Output.N ("others => 0)");
end loop;
Output.P (");");
Output.P;
Output.P (" function Go_To");
Output.P (" (State : Anagram.Grammars.LR_Parsers.State_Index;");
Output.P (" NT : Anagram.Grammars.Non_Terminal_Index)");
Output.P (" return Anagram.Grammars.LR_Parsers.State_Index");
Output.P (" is");
Output.P (" begin");
Output.P (" return Go_To_Table (State, NT);");
Output.P (" end Go_To;");
Output.P;
end Print_Go_To;
--------------
-- Put_Rule --
--------------
procedure Put_Rule
(Output : in out Writer;
Prod : Anagram.Grammars.Production;
Rule : Anagram.Grammars.Rule)
is
use Anagram.Grammars.Rule_Templates;
use type League.Strings.Universal_String;
Template : constant Rule_Template := Create (Rule.Text);
Args : League.String_Vectors.Universal_String_Vector;
Value : League.Strings.Universal_String;
begin
for J in 1 .. Template.Count loop
Value.Clear;
if Plain.Non_Terminal (Prod.Parent).Name = Template.Part_Name (J) then
Value.Append ("Nodes (1)");
else
declare
Index : Positive := 1;
begin
for Part of Plain.Part (Prod.First .. Prod.Last) loop
if Part.Name = Template.Part_Name (J) then
Value.Append ("Nodes (");
Value.Append (Image (Index));
Value.Append (")");
end if;
Index := Index + 1;
end loop;
if Value.Is_Empty then
if Template.Has_Default (J) then
Value := Template.Default (J);
else
Ada.Text_IO.Put_Line
("Wrong part " &
Template.Part_Name (J).To_UTF_8_String &
" in rule for production " &
Plain.Non_Terminal (Prod.Parent).Name.To_UTF_8_String
& "." & Prod.Name.To_UTF_8_String);
Ada.Text_IO.Put_Line (Rule.Text.To_UTF_8_String);
raise Constraint_Error;
end if;
end if;
end;
end if;
Args.Append (Value);
end loop;
Output.P (Template.Substitute (Args));
end Put_Rule;
procedure Put_Proc_Decl
(Output : in out Writer;
Suffix : Wide_Wide_String) is
begin
Output.N ("procedure Program.Parsers.On_Reduce");
Output.P (Suffix);
Output.P (" (Self : access Parse_Context;");
Output.P (" Prod : Anagram.Grammars.Production_Index;");
Output.N (" Nodes : in out " &
"Program.Parsers.Nodes.Node_Array)");
end Put_Proc_Decl;
procedure Put_Piece
(Piece : in out Writer;
From : Anagram.Grammars.Production_Index;
To : Anagram.Grammars.Production_Index)
is
Suffix : Wide_Wide_String :=
Anagram.Grammars.Production_Index'Wide_Wide_Image (From);
begin
Suffix (1) := '_';
Piece.P ("with Anagram.Grammars;");
Piece.P ("with Program.Parsers.Nodes;");
Piece.N ("private ");
Put_Proc_Decl (Piece, Suffix);
Piece.P (";");
Piece.N ("pragma Preelaborate (Program.Parsers.On_Reduce");
Piece.N (Suffix);
Piece.P (");");
Piece.P;
-- Piece.P ("pragma Warnings (""U"");");
Piece.P ("with Program.Parsers.Nodes;");
Piece.P ("use Program.Parsers.Nodes;");
Piece.P ("pragma Style_Checks (""N"");");
Put_Proc_Decl (Piece, Suffix);
Piece.P (" is");
Piece.P ("begin");
Piece.P (" case Prod is");
for Prod of Plain.Production (From .. To) loop
Piece.N (" when");
Piece.N
(Anagram.Grammars.Production_Index'Wide_Wide_Image (Prod.Index));
Piece.P (" =>");
for Rule of Plain.Rule (Prod.First_Rule .. Prod.Last_Rule) loop
Put_Rule (Piece, Prod, Rule);
end loop;
if Prod.First_Rule > Prod.Last_Rule then
Piece.P (" null;");
end if;
end loop;
Piece.P (" when others =>");
Piece.P (" raise Constraint_Error;");
Piece.P (" end case;");
Piece.N ("end Program.Parsers.On_Reduce");
Piece.N (Suffix);
Piece.P (";");
end Put_Piece;
use type Anagram.Grammars.Production_Count;
Piece_Length : constant Anagram.Grammars.Production_Count := 500;
Piece : Writer;
begin
Resolver.Resolve (AG, Table.all);
Output.P ("with Anagram.Grammars;");
Output.P ("with Anagram.Grammars.LR_Parsers;");
Output.P;
Output.P ("package Program.Parsers.Data is");
Output.P (" pragma Preelaborate;");
Output.P;
Output.P (" procedure Next_Action");
Output.P (" (State : Anagram.Grammars.LR_Parsers.State_Index;");
Output.P (" Token : Anagram.Grammars.Terminal_Count;");
Output.P (" Value : out Anagram.Grammars.LR_Parsers.Action);");
Output.P;
Output.P (" function Go_To");
Output.P (" (State : Anagram.Grammars.LR_Parsers.State_Index;");
Output.P (" NT : Anagram.Grammars.Non_Terminal_Index)");
Output.P (" return Anagram.Grammars.LR_Parsers.State_Index;");
Output.P;
Output.P ("end Program.Parsers.Data;");
Output.P;
Output.P ("package body Program.Parsers.Data is");
Output.P (" use Anagram.Grammars.LR_Parsers;");
Output.P;
Print_Go_To;
Print_Action;
Output.P ("end Program.Parsers.Data;");
Output.P;
Output.P ("with Anagram.Grammars;");
Output.P ("with Program.Parsers.Nodes;");
Output.N ("private ");
Put_Proc_Decl (Output, "");
Output.P (";");
Output.P ("pragma Preelaborate (Program.Parsers.On_Reduce);");
Output.P;
for Piece_Index in 0 .. (Plain.Last_Production - 1) / Piece_Length loop
declare
From : constant Anagram.Grammars.Production_Index :=
Piece_Index * Piece_Length + 1;
begin
Output.N ("with Program.Parsers.On_Reduce_");
Output.N (Natural (From));
Output.P (";");
end;
end loop;
Put_Proc_Decl (Output, "");
Output.P (" is");
Output.P ("begin");
Output.P (" case Prod is");
for Piece_Index in 0 .. (Plain.Last_Production - 1) / Piece_Length loop
declare
From : constant Anagram.Grammars.Production_Index :=
Piece_Index * Piece_Length + 1;
To : constant Anagram.Grammars.Production_Index :=
Anagram.Grammars.Production_Index'Min
(Plain.Last_Production, (Piece_Index + 1) * Piece_Length);
begin
Output.N (" when ");
Output.N (Natural (From));
Output.N (" .. ");
Output.N (Natural (To));
Output.P (" =>");
Output.N (" On_Reduce_");
Output.N (Natural (From));
Output.P (" (Self, Prod, Nodes);");
Put_Piece
(Piece => Piece,
From => From,
To => To);
end;
end loop;
Output.P (" when others =>");
Output.P (" raise Constraint_Error;");
Output.P (" end case;");
Output.P ("end Program.Parsers.On_Reduce;");
Ada.Text_IO.Put_Line (Output.Text.To_UTF_8_String);
Ada.Text_IO.Put_Line (Piece.Text.To_UTF_8_String);
Anagram.Grammars_Debug.Print_Conflicts (AG, Table.all);
if Ada.Command_Line.Argument_Count > 1 then
Anagram.Grammars_Debug.Print (G);
end if;
end Ada_LARL;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2019 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.Characters.Latin_1;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Orka.Containers.Ring_Buffers;
with Orka.Loggers.Formatting;
with Orka.Loggers.Terminal;
with Orka.OS;
package body Orka.Loggers.Location is
package L renames Ada.Characters.Latin_1;
package SU renames Ada.Strings.Unbounded;
type Log_Request is record
Path : SU.Unbounded_String;
Message : SU.Unbounded_String;
end record;
package Buffers is new Orka.Containers.Ring_Buffers (Log_Request);
protected Queue is
procedure Enqueue
(Path : SU.Unbounded_String;
From : Source;
Kind : Message_Type;
Level : Severity;
Message : String);
entry Dequeue (Request : out Log_Request; Stop : out Boolean);
procedure Shutdown;
private
Messages : Buffers.Buffer (Capacity_Queue);
Should_Stop : Boolean := False;
Has_Stopped : Boolean := False;
end Queue;
protected body Queue is
procedure Enqueue
(Path : SU.Unbounded_String;
From : Source;
Kind : Message_Type;
Level : Severity;
Message : String) is
begin
if not Messages.Is_Full and not Has_Stopped then
Messages.Add_Last
((Path => Path,
Message => SU.To_Unbounded_String
(Formatting.Format_Message_No_Color (From, Kind, Level, Message) & L.LF)));
else
Orka.Loggers.Terminal.Logger.Log (From, Kind, Level, Message);
end if;
end Enqueue;
entry Dequeue
(Request : out Log_Request;
Stop : out Boolean) when not Messages.Is_Empty or else Should_Stop is
begin
Stop := Should_Stop and Messages.Is_Empty;
if Stop then
Has_Stopped := True;
return;
end if;
Request := Messages.Remove_First;
end Dequeue;
procedure Shutdown is
begin
Should_Stop := True;
end Shutdown;
end Queue;
procedure Shutdown is
begin
Queue.Shutdown;
end Shutdown;
task Logger_Task;
task body Logger_Task is
Name : String renames Task_Name;
Request : Log_Request;
Stop : Boolean;
begin
Orka.OS.Set_Task_Name (Name);
loop
Queue.Dequeue (Request, Stop);
exit when Stop;
Location.Append_Data
(Path => SU.To_String (Request.Path),
Data => Orka.Resources.Convert (SU.To_String (Request.Message)));
end loop;
exception
when Error : others =>
Orka.OS.Put_Line (Name & ": " & Ada.Exceptions.Exception_Information (Error));
end Logger_Task;
protected type Location_Logger (Min_Level : Severity) is new Logger with
overriding
procedure Log
(From : Source;
Kind : Message_Type;
Level : Severity;
Message : String);
procedure Set_Path (Path : String);
private
File_Path : SU.Unbounded_String;
end Location_Logger;
protected body Location_Logger is
procedure Log
(From : Source;
Kind : Message_Type;
Level : Severity;
Message : String) is
begin
if Level <= Min_Level then
Queue.Enqueue (File_Path, From, Kind, Level, Message);
end if;
end Log;
procedure Set_Path (Path : String) is
begin
File_Path := SU.To_Unbounded_String (Path);
end Set_Path;
end Location_Logger;
function Create_Logger (Path : String; Level : Severity := Debug) return Logger_Ptr is
begin
return Result : constant Logger_Ptr := new Location_Logger (Min_Level => Level) do
Location_Logger (Result.all).Set_Path (Path);
end return;
end Create_Logger;
end Orka.Loggers.Location;
|
-----------------------------------------------------------------------
-- awa-votes-modules -- Module votes
-- Copyright (C) 2013, 2016 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.Log.Loggers;
with Security.Permissions;
with AWA.Modules.Beans;
with AWA.Modules.Get;
with AWA.Votes.Beans;
with AWA.Permissions;
with AWA.Services.Contexts;
with AWA.Votes.Models;
with ADO.SQL;
with ADO.Sessions;
with ADO.Sessions.Entities;
package body AWA.Votes.Modules is
use AWA.Services;
use ADO.Sessions;
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("AWA.Votes.Module");
package Register is new AWA.Modules.Beans (Module => Vote_Module,
Module_Access => Vote_Module_Access);
-- ------------------------------
-- Initialize the votes module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Vote_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the votes module");
-- Register here any bean class, servlet, filter.
Register.Register (Plugin => Plugin,
Name => "AWA.Votes.Beans.Votes_Bean",
Handler => AWA.Votes.Beans.Create_Vote_Bean'Access);
AWA.Modules.Module (Plugin).Initialize (App, Props);
-- Add here the creation of manager instances.
end Initialize;
-- ------------------------------
-- Get the votes module.
-- ------------------------------
function Get_Vote_Module return Vote_Module_Access is
function Get is new AWA.Modules.Get (Vote_Module, Vote_Module_Access, NAME);
begin
return Get;
end Get_Vote_Module;
-- ------------------------------
-- Vote for the given element and return the total vote for that element.
-- ------------------------------
procedure Vote_For (Model : in Vote_Module;
Id : in ADO.Identifier;
Entity_Type : in String;
Permission : in String;
Value : in Integer;
Total : out Integer) is
pragma Unreferenced (Model);
Ctx : constant Contexts.Service_Context_Access := AWA.Services.Contexts.Current;
User : constant ADO.Identifier := Ctx.Get_User_Identifier;
DB : Master_Session := AWA.Services.Contexts.Get_Master_Session (Ctx);
Kind : ADO.Entity_Type;
Rating : AWA.Votes.Models.Rating_Ref;
Vote : AWA.Votes.Models.Vote_Ref;
Query : ADO.SQL.Query;
Found : Boolean;
Ident : constant String := Entity_Type & ADO.Identifier'Image (Id);
begin
-- Check that the user has the vote permission on the given object.
AWA.Permissions.Check (Permission => Security.Permissions.Get_Permission_Index (Permission),
Entity => Id);
Log.Info ("User {0} votes for {1} rating {2}",
ADO.Identifier'Image (User), Ident,
Integer'Image (Value));
Ctx.Start;
Kind := ADO.Sessions.Entities.Find_Entity_Type (DB, Entity_Type);
-- Get the vote associated with the object for the user.
Query.Set_Join ("INNER JOIN awa_rating r ON r.id = o.entity_id");
Query.Set_Filter ("r.for_entity_id = :id and r.for_entity_type = :type "
& "and o.user_id = :user_id");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Query.Bind_Param ("user_id", User);
Vote.Find (DB, Query, Found);
if not Found then
Query.Clear;
-- Get the rating associated with the object.
Query.Set_Filter ("for_entity_id = :id and for_entity_type = :type");
Query.Bind_Param ("id", Id);
Query.Bind_Param ("type", Kind);
Rating.Find (DB, Query, Found);
-- Create it if it does not exist.
if not Found then
Log.Info ("Creating rating for {0}", Ident);
Rating.Set_For_Entity_Id (Id);
Rating.Set_For_Entity_Type (Kind);
Rating.Set_Rating (Value);
Rating.Set_Vote_Count (1);
else
Rating.Set_Vote_Count (Rating.Get_Vote_Count + 1);
Rating.Set_Rating (Value + Rating.Get_Rating);
end if;
Rating.Save (DB);
Vote.Set_User_Id (User);
Vote.Set_Entity (Rating);
else
Rating := AWA.Votes.Models.Rating_Ref (Vote.Get_Entity);
Rating.Set_Rating (Rating.Get_Rating + Value - Vote.Get_Rating);
Rating.Save (DB);
end if;
Vote.Set_Rating (Value);
Vote.Save (DB);
-- Return the total rating for the element.
Total := Rating.Get_Rating;
Ctx.Commit;
end Vote_For;
end AWA.Votes.Modules;
|
-- Abstract :
--
-- Base utilities for McKenzie_Recover
--
-- Copyright (C) 2018, 2019 Free Software Foundation, Inc.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with GNAT.Traceback.Symbolic;
package body WisiToken.Parse.LR.McKenzie_Recover.Base is
function Get_Barrier
(Parsers : not null access Parser_Lists.List;
Parser_Status : in Parser_Status_Array;
Min_Success_Check_Count : in Natural;
Total_Enqueue_Count : in Natural;
Check_Delta_Limit : in Natural;
Enqueue_Limit : in Natural)
return Boolean
is
Done_Count : SAL.Base_Peek_Type := 0;
begin
-- Return True if all parsers are done, or if any parser has a config
-- available to check.
for P_Status of Parser_Status loop
case P_Status.Recover_State is
when Active | Ready =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 then
if P_Status.Parser_State.Recover.Check_Count - Check_Delta_Limit >= Min_Success_Check_Count then
-- fail; another parser succeeded, this one taking too long.
Done_Count := Done_Count + 1;
elsif Total_Enqueue_Count + P_Status.Parser_State.Recover.Config_Full_Count >= Enqueue_Limit then
-- fail
Done_Count := Done_Count + 1;
end if;
end if;
case P_Status.Recover_State is
when Active =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 then
-- Still working
return True;
else
if P_Status.Active_Workers = 0 then
-- fail; no configs left to check.
Done_Count := Done_Count + 1;
end if;
end if;
when Ready =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 and then
P_Status.Parser_State.Recover.Config_Heap.Min_Key <= P_Status.Parser_State.Recover.Results.Min_Key
then
-- Still more to check.
return True;
elsif P_Status.Active_Workers = 0 then
Done_Count := Done_Count + 1;
end if;
when others =>
null;
end case;
when Success | Fail =>
Done_Count := Done_Count + 1;
end case;
end loop;
return Done_Count = Parsers.Count;
end Get_Barrier;
protected body Supervisor is
procedure Initialize
(Parsers : not null access Parser_Lists.List;
Terminals : not null access constant Base_Token_Arrays.Vector)
is
Index : SAL.Peek_Type := 1;
begin
Supervisor.Parsers := Parsers;
Supervisor.Terminals := Terminals;
All_Parsers_Done := False;
Success_Counter := 0;
Min_Success_Check_Count := Natural'Last;
Total_Enqueue_Count := 0;
Fatal_Called := False;
Result := Recover_Status'First;
Error_ID := Ada.Exceptions.Null_Id;
for I in Parsers.Iterate loop
if Parsers.Reference (I).Recover_Insert_Delete.Length > 0 then
-- Previous error recovery resume not finished; this is supposed to
-- be checked in Parser.
raise SAL.Programmer_Error;
end if;
Parser_Status (Index) :=
(Recover_State => Active,
Parser_State => Parser_Lists.Persistent_State_Ref (I),
Fail_Mode => Success,
Active_Workers => 0);
declare
Data : McKenzie_Data renames Parsers.Reference (I).Recover;
begin
Data.Config_Heap.Clear;
Data.Results.Clear;
Data.Enqueue_Count := 0;
Data.Check_Count := 0;
Data.Success := False;
end;
Index := Index + 1;
end loop;
end Initialize;
entry Get
(Parser_Index : out SAL.Base_Peek_Type;
Config : out Configuration;
Status : out Config_Status)
when (Fatal_Called or All_Parsers_Done) or else Get_Barrier
(Parsers, Parser_Status, Min_Success_Check_Count, Total_Enqueue_Count, Check_Delta_Limit, Enqueue_Limit)
is
Done_Count : SAL.Base_Peek_Type := 0;
Min_Cost : Integer := Integer'Last;
Min_Cost_Index : SAL.Base_Peek_Type;
procedure Set_Outputs (I : in SAL.Peek_Type)
is begin
Parser_Index := I;
Config := Parser_Status (I).Parser_State.Recover.Config_Heap.Remove;
Status := Valid;
Parser_Status (I).Parser_State.Recover.Check_Count :=
Parser_Status (I).Parser_State.Recover.Check_Count + 1;
Parser_Status (I).Active_Workers := Parser_Status (I).Active_Workers + 1;
end Set_Outputs;
procedure Set_All_Done
is begin
Parser_Index := SAL.Base_Peek_Type'First;
Config := (others => <>);
Status := All_Done;
end Set_All_Done;
begin
if Fatal_Called or All_Parsers_Done then
Set_All_Done;
return;
end if;
-- Same logic as in Get_Barrier, but different actions.
--
-- No task_id in outline trace messages, because they may appear in
-- .parse_good
for I in Parser_Status'Range loop
declare
P_Status : Base.Parser_Status renames Parser_Status (I);
begin
case P_Status.Recover_State is
when Active | Ready =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 then
if P_Status.Parser_State.Recover.Check_Count - Check_Delta_Limit >= Min_Success_Check_Count then
if Trace_McKenzie > Outline then
Put_Line
(Trace.all,
P_Status.Parser_State.Label, "fail; check delta (limit" &
Integer'Image (Min_Success_Check_Count + Check_Delta_Limit) & ")",
Task_ID => False);
end if;
P_Status.Recover_State := Fail;
P_Status.Fail_Mode := Fail_Check_Delta;
Done_Count := Done_Count + 1;
elsif Total_Enqueue_Count + P_Status.Parser_State.Recover.Config_Full_Count >= Enqueue_Limit then
if Trace_McKenzie > Outline then
Put_Line
(Trace.all,
P_Status.Parser_State.Label, "fail; total enqueue limit (" &
Enqueue_Limit'Image & " cost" &
P_Status.Parser_State.Recover.Config_Heap.Min_Key'Image & ")",
Task_ID => False);
end if;
P_Status.Recover_State := Fail;
P_Status.Fail_Mode := Fail_Enqueue_Limit;
Done_Count := Done_Count + 1;
end if;
end if;
case P_Status.Recover_State is
when Active =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 then
if P_Status.Parser_State.Recover.Config_Heap.Min_Key < Min_Cost then
Min_Cost := P_Status.Parser_State.Recover.Config_Heap.Min_Key;
Min_Cost_Index := I;
-- not done
end if;
else
if P_Status.Active_Workers = 0 then
-- No configs left to check (rarely happens with real languages).
if Trace_McKenzie > Outline then
Put_Line
(Trace.all, P_Status.Parser_State.Label, "fail; no configs left", Task_ID => False);
end if;
P_Status.Recover_State := Fail;
P_Status.Fail_Mode := Fail_No_Configs_Left;
Done_Count := Done_Count + 1;
end if;
end if;
when Ready =>
if P_Status.Parser_State.Recover.Config_Heap.Count > 0 and then
P_Status.Parser_State.Recover.Config_Heap.Min_Key <=
P_Status.Parser_State.Recover.Results.Min_Key
then
-- Still more to check. We don't check Min_Cost here so this parser
-- can finish quickly.
Set_Outputs (I);
return;
elsif P_Status.Active_Workers = 0 then
P_Status.Recover_State := Success;
Done_Count := Done_Count + 1;
end if;
when others =>
null;
end case;
when Success | Fail =>
Done_Count := Done_Count + 1;
end case;
end;
end loop;
if Min_Cost /= Integer'Last then
Set_Outputs (Min_Cost_Index);
elsif Done_Count = Parsers.Count then
if Trace_McKenzie > Extra then
Trace.Put_Line ("Supervisor: done, " & (if Success_Counter > 0 then "succeed" else "fail"));
end if;
Set_All_Done;
All_Parsers_Done := True;
else
raise SAL.Programmer_Error with "Get_Barrier and Get logic do not match";
end if;
end Get;
procedure Success
(Parser_Index : in SAL.Peek_Type;
Config : in Configuration;
Configs : in out Config_Heaps.Heap_Type)
is
Data : McKenzie_Data renames Parser_Status (Parser_Index).Parser_State.Recover;
begin
Put (Parser_Index, Configs); -- Decrements Active_Worker_Count.
if Trace_McKenzie > Detail then
Put
("succeed: enqueue" & Integer'Image (Data.Enqueue_Count) & ", check " & Integer'Image (Data.Check_Count),
Trace.all, Parser_Status (Parser_Index).Parser_State.Label, Terminals.all, Config);
end if;
if Force_Full_Explore then
return;
end if;
Success_Counter := Success_Counter + 1;
Result := Success;
Data.Success := True;
if Data.Check_Count < Min_Success_Check_Count then
Min_Success_Check_Count := Data.Check_Count;
end if;
if Force_High_Cost_Solutions then
Data.Results.Add (Config);
if Data.Results.Count > 3 then
Parser_Status (Parser_Index).Recover_State := Ready;
end if;
else
if Data.Results.Count = 0 then
Data.Results.Add (Config);
Parser_Status (Parser_Index).Recover_State := Ready;
elsif Config.Cost < Data.Results.Min_Key then
-- delete higher cost configs from Results
loop
Data.Results.Drop;
exit when Data.Results.Count = 0 or else
Config.Cost >= Data.Results.Min_Key;
end loop;
Data.Results.Add (Config);
elsif Config.Cost = Data.Results.Min_Key then
Data.Results.Add (Config);
else
-- Config.Cost > Results.Min_Key
null;
end if;
end if;
end Success;
procedure Put (Parser_Index : in SAL.Peek_Type; Configs : in out Config_Heaps.Heap_Type)
is
Configs_Count : constant SAL.Base_Peek_Type := Configs.Count; -- Before it is emptied, for Trace.
P_Status : Base.Parser_Status renames Parser_Status (Parser_Index);
Data : McKenzie_Data renames P_Status.Parser_State.Recover;
begin
P_Status.Active_Workers := P_Status.Active_Workers - 1;
Total_Enqueue_Count := Total_Enqueue_Count + Integer (Configs_Count);
Data.Enqueue_Count := Data.Enqueue_Count + Integer (Configs_Count);
loop
exit when Configs.Count = 0;
-- [1] has a check for duplicate configs here; that only happens with
-- higher costs, which take too long for our application.
Data.Config_Heap.Add (Configs.Remove);
end loop;
if Trace_McKenzie > Detail then
Put_Line
(Trace.all, P_Status.Parser_State.Label,
"enqueue:" & SAL.Base_Peek_Type'Image (Configs_Count) &
"/" & SAL.Base_Peek_Type'Image (Data.Config_Heap.Count) &
"/" & Trimmed_Image (Total_Enqueue_Count) &
"/" & Trimmed_Image (Data.Check_Count) &
", min cost:" &
(if Data.Config_Heap.Count > 0
then Integer'Image (Data.Config_Heap.Min_Key)
else " ? ") &
", active workers:" & Integer'Image (P_Status.Active_Workers));
end if;
end Put;
procedure Config_Full (Prefix : in String; Parser_Index : in SAL.Peek_Type)
is
P_Status : Base.Parser_Status renames Parser_Status (Parser_Index);
Data : McKenzie_Data renames P_Status.Parser_State.Recover;
begin
Data.Config_Full_Count := Data.Config_Full_Count + 1;
if Trace_McKenzie > Outline then
Put_Line (Trace.all, Label (Parser_Index), Prefix & ": config.ops is full; " &
Data.Config_Full_Count'Image);
end if;
end Config_Full;
function Recover_Result return Recover_Status
is
Temp : Recover_Status := Result;
begin
if Result = Success then
return Success;
else
for S of Parser_Status loop
Temp := Recover_Status'Max (Result, S.Fail_Mode);
end loop;
return Temp;
end if;
end Recover_Result;
procedure Fatal (E : in Ada.Exceptions.Exception_Occurrence)
is
use Ada.Exceptions;
begin
if Trace_McKenzie > Outline then
Trace.Put_Line ("task " & Task_Attributes.Value'Image & " Supervisor: Error");
end if;
Fatal_Called := True;
Error_ID := Exception_Identity (E);
Error_Message := +Exception_Message (E);
if Debug_Mode then
Trace.Put_Line (Exception_Name (E) & ": " & Exception_Message (E));
Trace.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
end if;
end Fatal;
entry Done (Error_ID : out Ada.Exceptions.Exception_Id; Message : out Ada.Strings.Unbounded.Unbounded_String)
when All_Parsers_Done or Fatal_Called
is begin
Error_ID := Supervisor.Error_ID;
Message := Error_Message;
if Trace_McKenzie > Detail then
Trace.New_Line;
Trace.Put_Line ("Supervisor: Done");
end if;
end Done;
function Parser_State (Parser_Index : in SAL.Peek_Type) return Parser_Lists.Constant_Reference_Type
is begin
return (Element => Parser_Status (Parser_Index).Parser_State);
end Parser_State;
function Label (Parser_Index : in SAL.Peek_Type) return Natural
is begin
return Parser_Status (Parser_Index).Parser_State.Label;
end Label;
end Supervisor;
procedure Put
(Message : in String;
Super : not null access Base.Supervisor;
Shared : not null access Base.Shared;
Parser_Index : in SAL.Peek_Type;
Config : in Configuration;
Task_ID : in Boolean := True)
is begin
Put (Message, Super.Trace.all, Super.Parser_State (Parser_Index).Label,
Shared.Terminals.all, Config, Task_ID);
end Put;
end WisiToken.Parse.LR.McKenzie_Recover.Base;
|
with Ada.Containers.Vectors;
-- #include "impact.d3.Vector.h"
-- #include "btAlignedObjectArray.h"
package Impact.d3.graham_scan_2d_convex_Hull
--
--
--
is
type GrahamVector2 is record
Vector : Math.Vector_3;
m_angle : Math.Real;
m_orgIndex : Integer;
-- m_anchor : math.Vector_3; -- Only for sorting.
end record;
function to_GrahamVector2
(org : in Math.Vector_3;
orgIndex : in Integer)
return GrahamVector2;
-- GrahamVector2(const impact.d3.Vector& org, int orgIndex)
-- :impact.d3.Vector(org),
-- m_orgIndex(orgIndex)
-- {
-- }
-- type btAngleCompareFunc is
-- record
-- m_anchor : math.Vector_3;
-- end record;
--
--
--
-- function to_btAngleCompareFunc (anchor : in math.Vector_3) return
--btAngleCompareFunc;
-- btAngleCompareFunc(const impact.d3.Vector& anchor)
-- : m_anchor(anchor)
-- {
-- }
-- function "<" (a, b : in GrahamVector2) return Boolean;
-- function equivalent (Self : in btAngleCompareFunc; a, b : in
--GrahamVector2) return Boolean;
-- bool operator()(const GrahamVector2& a, const GrahamVector2& b)
--{
-- if (a.m_angle != b.m_angle)
-- return a.m_angle < b.m_angle;
-- else
-- {
-- impact.d3.Scalar al = (a-m_anchor).length2();
-- impact.d3.Scalar bl = (b-m_anchor).length2();
-- if (al != bl)
-- return al < bl;
-- else
-- {
-- return a.m_orgIndex < b.m_orgIndex;
-- }
-- }
-- }
package GrahamVector2_Vectors is new Ada.Containers.Vectors (
Positive,
GrahamVector2);
subtype GrahamVector2_Vector is GrahamVector2_Vectors.Vector;
procedure GrahamScanConvexHull2D
(originalPoints : in out GrahamVector2_Vector;
hull : in out GrahamVector2_Vector);
-- inline void GrahamScanConvexHull2D(btAlignedObjectArray<GrahamVector2>&
--originalPoints, btAlignedObjectArray<GrahamVector2>& hull)
-- {
-- if (originalPoints.size()<=1)
-- {
-- for (int i=0;i<originalPoints.size();i++)
-- hull.push_back(originalPoints[0]);
-- return;
-- }
-- //step1 : find anchor point with smallest x/y and move it to
--first location
-- //also precompute angles
-- for (int i=0;i<originalPoints.size();i++)
-- {
-- const impact.d3.Vector& left = originalPoints[i];
-- const impact.d3.Vector& right = originalPoints[0];
-- if (left.x() < right.x() || !(right.x() < left.x()) &&
--left.y() < right.y())
-- {
-- originalPoints.swap(0,i);
-- }
-- }
--
-- for (int i=0;i<originalPoints.size();i++)
-- {
-- impact.d3.Vector xvec(1,0,0);
-- impact.d3.Vector ar =
--originalPoints[i]-originalPoints[0];
-- originalPoints[i].m_angle = btCross(xvec,
--ar).dot(impact.d3.Vector(0,0,1)) / ar.length();
-- }
--
-- //step 2: sort all points, based on 'angle' with this anchor
-- btAngleCompareFunc comp(originalPoints[0]);
-- originalPoints.quickSortInternal(comp,1,originalPoints.size()-1)
--;
--
-- int i;
-- for (i = 0; i<2; i++)
-- hull.push_back(originalPoints[i]);
--
-- //step 3: keep all 'convex' points and discard concave points
--(using back tracking)
-- for (; i != originalPoints.size(); i++)
-- {
-- bool isConvex = false;
-- while (!isConvex&& hull.size()>1) {
-- impact.d3.Vector& a = hull[hull.size()-2];
-- impact.d3.Vector& b = hull[hull.size()-1];
-- isConvex =
--btCross(a-b,a-originalPoints[i]).dot(impact.d3.Vector(0,0,1))> 0;
-- if (!isConvex)
-- hull.pop_back();
-- else
-- hull.push_back(originalPoints[i]);
-- }
-- }
-- }
end Impact.d3.graham_scan_2d_convex_Hull;
|
separate (Numerics.Sparse_Matrices)
-- function Cumulative_Sum (Item : in Int_Array) return Int_Array is
-- Result : Int_Array (Item'Range);
-- Tmp : Int := 1;
-- begin
-- for I in Item'Range loop
-- Result (I) := Tmp;
-- Tmp := Tmp + Item (I);
-- end loop;
-- return Result;
-- end Cumulative_Sum;
procedure Cumulative_Sum (Item : in out Int_Array) is
use Ada.Text_IO;
N : Pos := 1;
M : Pos;
begin
for I in Item'Range loop
M := Item (I);
Item (I) := N;
N := N + M;
end loop;
end Cumulative_Sum;
|
------------------------------------------------------------------------------
-- --
-- ASIS-for-GNAT IMPLEMENTATION COMPONENTS --
-- --
-- A 4 G . E N C L _ E L --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2012, Free Software Foundation, Inc. --
-- --
-- ASIS-for-GNAT is free software; you can redistribute it and/or modify it --
-- under terms of the GNU General Public License as published by the Free --
-- Software Foundation; either version 2, or (at your option) any later --
-- version. ASIS-for-GNAT is distributed in the hope that it will be use- --
-- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- --
-- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General --
-- Public License for more details. You should have received a copy of the --
-- GNU General Public License distributed with ASIS-for-GNAT; see file --
-- COPYING. If not, write to the Free Software Foundation, 51 Franklin --
-- Street, Fifth Floor, Boston, MA 02110-1301, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by AdaCore --
-- (http://www.adacore.com). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with Asis.Declarations; use Asis.Declarations;
with Asis.Elements; use Asis.Elements;
with Asis.Extensions;
with Asis.Set_Get; use Asis.Set_Get;
with A4G.A_Sem; use A4G.A_Sem;
with A4G.A_Types; use A4G.A_Types;
with A4G.Int_Knds; use A4G.Int_Knds;
with A4G.Mapping; use A4G.Mapping;
with A4G.Queries; use A4G.Queries;
with A4G.Vcheck; use A4G.Vcheck;
with Atree; use Atree;
with Einfo; use Einfo;
with Namet; use Namet;
with Nlists; use Nlists;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames;
with Stand; use Stand;
with Types; use Types;
package body A4G.Encl_El is
------------------------------------------------
-- The general approach to the implementation --
-- of the Enclosing_Element query --
------------------------------------------------
-- There are important differences in the ways how an Enclosing_Element
-- is retrieved for explicit and implicit Elements, and for the elements
-- from expanded generics. For explicit Elements, the general way to get
-- the enclosing Element is to do the necessary bottom-up tree traversing,
-- for most of the cases all what we need if one step up the front-end
-- tree, but sometimes the differences between front-end and ASIS trees
-- require some non-trivial traversing.
--
-- For implicit Elements, there is a semantic link between a top Element
-- of an ASIS implicit sub-hierarchy and some explicit Element that
-- "generates" this subhierarchy. For example, an implicit declaration of
-- an inherited supprogram is "generated" by some derived type definition,
-- so inside the implicit subhierarchy we use the same approach for
-- retrieving the enclosing Element as for explicit Elements, but the
-- enclosing Element for subhierarchy is the construct that "generates" the
-- subhierarchy, and to get to this construct, the link stored as a part
-- of implicit elements structure is used.
--
-- For Elements from generic instantiations, we do bottom-up traversing of
-- the ASIS/front-end tree structure corresponding to the expanded code
-- in the same way as for explicit Elements, but when we are at the top of
-- an expanded spec or body, the next Enclosing_Element step should go
-- to the corresponding instantiation, so here we also do something
-- different that bottom-up tree traversing
--
-- But for most of the cases the way to get the enclosing Element is to
-- map the bottom-up traversing of the compiler tree onto the ASIS Elements
-- hierarchy. This is performed by Enclosing_Element_For_Explicit function,
-- and all the other routines defined in this package detect and process
-- various special cases. For implicit Elements and for Elements that are
-- components of expanded generic structure the first thing is to check if
-- this Element can be processed as if it is a usual explicit Element, and
-- then correct result, if needed.
---------------------------------------------------------------------
-- Mapping the bottom-up traversing of the compiler tree onto ASIS --
---------------------------------------------------------------------
-- Each ASIS Element contains the reference to the tree node it has been
-- built from. In many cases the enclosing Element should be built on
-- the parent node. In some cases the enclosing Element may be built on the
-- same node. And there are some cases when we have to do some traversing
-- that is specific to this particular Element to get to the compiler tree
-- node corresponding to its enclosing Element.
-- The way of getting the enclosing Element is implemented on the base of
-- two look-up tables (switches). The first table defines if for the given
-- element (that is, for the given Element kind, and the internal flat
-- Element classification is used here) some regular way of constructing
-- enclosing Element should be used, or some non-trivial traversing is
-- needed. This non-trivial traversing is specific to the Element kind, and
-- the corresponding routine is defined by the second look-up table.
-------------------------------------------------
-- The general structure of this package body --
-------------------------------------------------
-- The rest of this package body has the following structure:
--
-- Section 1 - definition of the first Enclosing_Element switch (makes
-- the difference between trivial and non-trivial cases of
-- mapping the bottom up compiler tree traversing onto ASIS
--
-- Section 2 - declarations of routines implementing various cases of
-- non-trivial bottom up compiler tree traversing
--
-- Section 3 - definition of the second Enclosing_Element switch (maps
-- Element kind requiring non-trivial actions onto
-- corresponding routines
--
-- Section 4 - (general-purpose) local subprograms
--
-- Section 5 - bodies of the routines declared in Section 2
--
-- Section 6 - bodies of the routines declared in the package spec
---------------------------------------------------------------------
-- Section 1 - Enclosing_Element first switch, separating trivial --
-- and non-trivial cases --
---------------------------------------------------------------------
-- This switch maps each value of the Internal_Element_Kinds onto one
-- of the following values of the same type, and this mapping has the
-- following meaning:
-- Not_An_Element => Asis.Nil_Element should be returned as
-- Enclosed Element;
--
-- Trivial_Mapping => A standard Enclosing_Element constructor should
-- be used, it is implemented by General_Encl_Elem
-- function
--
-- No_Mapping => is set for the special values added to the
-- Internal_Element_Kinds literals to organize the
-- Node_to_Element and Enclosing Element switches.
--
-- Non_Trivial_Mapping => a special function is needed for this Element
-- kind to get the Enclosing Element. This function
-- is selected by second switch,
--
-- Not_Implemented_Mapping => it means what is sounds
--
-- any the other value => the Enclosing Element for the Element of the
-- corresponding kind is based on the same node, but
-- is of the specified kind
Enclosing_Element_For_Explicits_First_Switch : constant
array (Internal_Element_Kinds) of Internal_Element_Kinds :=
(
-- type Internal_Element_Kinds is (
--
Not_An_Element => Not_An_Element,
-- Asis.Nil_Element should be returned as the
-- Enclosing for the Asis.Nil_Element, should not it???
--
------------------------------------------------------------------------------
--
-- -- A_Pragma, -- Asis.Elements
--
------------------------------------------------------------------------------
--
An_All_Calls_Remote_Pragma ..
-- An_Asynchronous_Pragma,
-- An_Atomic_Pragma,
-- An_Atomic_Components_Pragma,
-- An_Attach_Handler_Pragma,
-- A_Controlled_Pragma,
-- A_Convention_Pragma,
-- A_Discard_Names_Pragma,
-- An_Elaborate_Pragma,
-- An_Elaborate_All_Pragma,
-- An_Elaborate_Body_Pragma,
-- An_Export_Pragma,
-- An_Import_Pragma,
-- An_Inline_Pragma,
-- An_Inspection_Point_Pragma,
-- An_Interrupt_Handler_Pragma,
-- An_Interrupt_Priority_Pragma,
-- A_Linker_Options_Pragma
-- A_List_Pragma,
-- A_Locking_Policy_Pragma,
-- A_Normalize_Scalars_Pragma,
-- An_Optimize_Pragma,
-- A_Pack_Pragma,
-- A_Page_Pragma,
-- A_Preelaborate_Pragma,
-- A_Priority_Pragma,
-- A_Pure_Pragma,
-- A_Queuing_Policy_Pragma,
-- A_Remote_Call_Interface_Pragma,
-- A_Remote_Types_Pragma,
-- A_Restrictions_Pragma,
-- A_Reviewable_Pragma,
-- A_Shared_Passive_Pragma,
-- A_Storage_Size_Pragma,
-- A_Suppress_Pragma,
-- A_Task_Dispatching_Policy_Pragma,
-- A_Volatile_Pragma,
-- A_Volatile_Components_Pragma,
--
-- An_Implementation_Defined_Pragma,
--
An_Unknown_Pragma => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
--
-- -- A_Defining_Name, -- Asis.Declarations
--
------------------------------------------------------------------------------
--
A_Defining_Identifier => Non_Trivial_Mapping,
A_Defining_Character_Literal => An_Enumeration_Literal_Specification,
A_Defining_Enumeration_Literal => An_Enumeration_Literal_Specification,
--
-- -- A_Defining_Operator_Symbol => Non_Trivial_Mapping
--
A_Defining_And_Operator ..
-- A_Defining_Or_Operator,
-- A_Defining_Xor_Operator,
-- A_Defining_Equal_Operator,
-- A_Defining_Not_Equal_Operator,
-- A_Defining_Less_Than_Operator,
-- A_Defining_Less_Than_Or_Equal_Operator,
-- A_Defining_Greater_Than_Operator,
-- A_Defining_Greater_Than_Or_Equal_Operator,
-- A_Defining_Plus_Operator,
-- A_Defining_Minus_Operator,
-- A_Defining_Concatenate_Operator,
-- A_Defining_Unary_Plus_Operator,
-- A_Defining_Unary_Minus_Operator,
-- A_Defining_Multiply_Operator,
-- A_Defining_Divide_Operator,
-- A_Defining_Mod_Operator,
-- A_Defining_Rem_Operator,
-- A_Defining_Exponentiate_Operator,
-- A_Defining_Abs_Operator,
A_Defining_Not_Operator => Non_Trivial_Mapping,
A_Defining_Expanded_Name => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
--
-- -- A_Declaration, -- Asis.Declarations
--
------------------------------------------------------------------------------
--
An_Ordinary_Type_Declaration ..
-- A_Task_Type_Declaration,
-- A_Protected_Type_Declaration,
-- An_Incomplete_Type_Declaration,
-- A_Private_Type_Declaration,
-- A_Private_Extension_Declaration,
-- A_Subtype_Declaration,
A_Variable_Declaration => Trivial_Mapping,
A_Constant_Declaration => Trivial_Mapping,
A_Deferred_Constant_Declaration ..
-- A_Single_Task_Declaration,
-- A_Single_Protected_Declaration,
--
-- An_Integer_Number_Declaration,
A_Real_Number_Declaration => Trivial_Mapping,
--
An_Enumeration_Literal_Specification => Non_Trivial_Mapping,
-- is it really so?
--
A_Discriminant_Specification => Non_Trivial_Mapping,
A_Component_Declaration => Non_Trivial_Mapping,
A_Loop_Parameter_Specification ..
-- A_Generalized_Iterator_Specification,
An_Element_Iterator_Specification => Non_Trivial_Mapping,
A_Procedure_Declaration => Non_Trivial_Mapping,
A_Function_Declaration => Non_Trivial_Mapping,
--
A_Parameter_Specification => Non_Trivial_Mapping,
--
A_Procedure_Body_Declaration => Non_Trivial_Mapping,
A_Function_Body_Declaration => Non_Trivial_Mapping,
A_Return_Variable_Specification => Trivial_Mapping,
A_Return_Constant_Specification => Trivial_Mapping,
A_Null_Procedure_Declaration => Trivial_Mapping,
An_Expression_Function_Declaration => Trivial_Mapping,
A_Package_Declaration => Non_Trivial_Mapping,
A_Package_Body_Declaration => Non_Trivial_Mapping,
An_Object_Renaming_Declaration => Trivial_Mapping,
An_Exception_Renaming_Declaration => Trivial_Mapping,
A_Package_Renaming_Declaration => Non_Trivial_Mapping,
A_Procedure_Renaming_Declaration => Non_Trivial_Mapping,
A_Function_Renaming_Declaration => Non_Trivial_Mapping,
A_Generic_Package_Renaming_Declaration => Non_Trivial_Mapping,
A_Generic_Procedure_Renaming_Declaration => Non_Trivial_Mapping,
A_Generic_Function_Renaming_Declaration => Non_Trivial_Mapping,
A_Task_Body_Declaration => Non_Trivial_Mapping,
A_Protected_Body_Declaration => Non_Trivial_Mapping,
An_Entry_Declaration => Non_Trivial_Mapping,
An_Entry_Body_Declaration => Trivial_Mapping,
An_Entry_Index_Specification => Trivial_Mapping,
A_Procedure_Body_Stub => Trivial_Mapping,
A_Function_Body_Stub => Trivial_Mapping,
A_Package_Body_Stub => Trivial_Mapping,
A_Task_Body_Stub => Trivial_Mapping,
A_Protected_Body_Stub => Trivial_Mapping,
An_Exception_Declaration => Trivial_Mapping,
A_Choice_Parameter_Specification => Trivial_Mapping,
--
A_Generic_Procedure_Declaration => Non_Trivial_Mapping,
A_Generic_Function_Declaration => Non_Trivial_Mapping,
A_Generic_Package_Declaration => Non_Trivial_Mapping,
A_Package_Instantiation => Non_Trivial_Mapping,
A_Procedure_Instantiation => Non_Trivial_Mapping,
A_Function_Instantiation => Non_Trivial_Mapping,
A_Formal_Object_Declaration => Trivial_Mapping,
A_Formal_Type_Declaration => Trivial_Mapping,
A_Formal_Incomplete_Type_Declaration => Trivial_Mapping,
A_Formal_Procedure_Declaration => Trivial_Mapping,
A_Formal_Function_Declaration => Trivial_Mapping,
A_Formal_Package_Declaration => Trivial_Mapping,
A_Formal_Package_Declaration_With_Box => Trivial_Mapping,
------------------------------------------------------------------------------
--
-- -- A_Definition, -- Asis.Definitions
--
------------------------------------------------------------------------------
--
-- -- A_Type_Definition,
--
A_Derived_Type_Definition => Trivial_Mapping,
A_Derived_Record_Extension_Definition => Trivial_Mapping,
--
An_Enumeration_Type_Definition => Non_Trivial_Mapping,
--
A_Signed_Integer_Type_Definition => Trivial_Mapping,
A_Modular_Type_Definition => Trivial_Mapping,
--
-- -- A_Root_Type_Definition, ----- #########
--
-- A_Root_Integer_Definition, ----- #########
-- A_Root_Real_Definition, ----- #########
-- A_Root_Fixed_Definition, ----- #########
--
-- A_Universal_Integer_Definition, ----- #########
-- A_Universal_Real_Definition, ----- #########
-- A_Universal_Fixed_Definition, ----- #########
--
--
A_Floating_Point_Definition => Trivial_Mapping,
--
An_Ordinary_Fixed_Point_Definition => Trivial_Mapping,
A_Decimal_Fixed_Point_Definition => Trivial_Mapping,
--
An_Unconstrained_Array_Definition => Trivial_Mapping,
A_Constrained_Array_Definition => Trivial_Mapping,
--
A_Record_Type_Definition => Trivial_Mapping, -- ???
A_Tagged_Record_Type_Definition => Trivial_Mapping, -- ???
-- --|A2005 start
-- An_Interface_Type_Definition,
An_Ordinary_Interface ..
-- A_Limited_Interface,
-- A_Task_Interface,
-- A_Protected_Interface,
A_Synchronized_Interface => Trivial_Mapping,
-- --|A2005 end
-- -- An_Access_Type_Definition,
--
A_Pool_Specific_Access_To_Variable => Trivial_Mapping,
An_Access_To_Variable => Trivial_Mapping,
An_Access_To_Constant => Trivial_Mapping,
--
An_Access_To_Procedure => Trivial_Mapping,
An_Access_To_Protected_Procedure => Trivial_Mapping,
An_Access_To_Function => Trivial_Mapping,
An_Access_To_Protected_Function => Trivial_Mapping,
--
--
A_Subtype_Indication => Non_Trivial_Mapping,
--
-- -- A_Constraint,
--
A_Range_Attribute_Reference => Non_Trivial_Mapping, -- ???
A_Simple_Expression_Range => Non_Trivial_Mapping,
A_Digits_Constraint => Trivial_Mapping,
A_Delta_Constraint => Trivial_Mapping,
An_Index_Constraint => Non_Trivial_Mapping,
A_Discriminant_Constraint => Non_Trivial_Mapping,
--
A_Component_Definition => Trivial_Mapping,
--
-- -- A_Discrete_Subtype_Definition,
--
A_Discrete_Subtype_Indication_As_Subtype_Definition => Trivial_Mapping,
A_Discrete_Range_Attribute_Reference_As_Subtype_Definition => Trivial_Mapping,
A_Discrete_Simple_Expression_Range_As_Subtype_Definition => Trivial_Mapping,
--
-- -- A_Discrete_Range,
--
A_Discrete_Subtype_Indication => Non_Trivial_Mapping,
A_Discrete_Range_Attribute_Reference => Non_Trivial_Mapping,
A_Discrete_Simple_Expression_Range => Non_Trivial_Mapping,
--
--
An_Unknown_Discriminant_Part => Non_Trivial_Mapping,
A_Known_Discriminant_Part => Non_Trivial_Mapping,
--
A_Record_Definition => Non_Trivial_Mapping,
A_Null_Record_Definition => Non_Trivial_Mapping,
--
A_Null_Component => Non_Trivial_Mapping,
A_Variant_Part => Non_Trivial_Mapping,
A_Variant => Trivial_Mapping,
An_Others_Choice => Non_Trivial_Mapping,
-- --|A2005 start
An_Anonymous_Access_To_Variable ..
-- An_Anonymous_Access_To_Constant
-- An_Anonymous_Access_To_Procedure
-- An_Anonymous_Access_To_Protected_Procedure
-- An_Anonymous_Access_To_Function
An_Anonymous_Access_To_Protected_Function => Trivial_Mapping,
-- --|A2005 end
A_Private_Type_Definition => A_Private_Type_Declaration,
A_Tagged_Private_Type_Definition => A_Private_Type_Declaration,
A_Private_Extension_Definition => A_Private_Extension_Declaration,
--
A_Task_Definition => Trivial_Mapping,
A_Protected_Definition => Non_Trivial_Mapping,
--
-- -- A_Formal_Type_Definition,
--
A_Formal_Private_Type_Definition ..
-- A_Formal_Tagged_Private_Type_Definition,
--
-- A_Formal_Derived_Type_Definition,
--
-- A_Formal_Discrete_Type_Definition,
--
-- A_Formal_Signed_Integer_Type_Definition,
-- A_Formal_Modular_Type_Definition,
--
-- A_Formal_Floating_Point_Definition,
--
-- A_Formal_Ordinary_Fixed_Point_Definition,
-- A_Formal_Decimal_Fixed_Point_Definition,
--
-- A_Formal_Unconstrained_Array_Definition,
-- A_Formal_Constrained_Array_Definition,
--
-- -- A_Formal_Access_Type_Definition,
--
-- A_Formal_Pool_Specific_Access_To_Variable,
-- A_Formal_Access_To_Variable,
-- A_Formal_Access_To_Constant,
--
-- A_Formal_Access_To_Procedure,
-- A_Formal_Access_To_Protected_Procedure,
-- A_Formal_Access_To_Function,
-- A_Formal_Access_To_Protected_Function
An_Aspect_Specification => Trivial_Mapping,
--
------------------------------------------------------------------------------
--
-- -- An_Expression, -- Asis.Expressions --##########
--
------------------------------------------------------------------------------
--
An_Integer_Literal => Non_Trivial_Mapping,
A_Real_Literal => Non_Trivial_Mapping,
A_String_Literal => Non_Trivial_Mapping,
An_Identifier => Non_Trivial_Mapping,
--
-- -- An_Operator_Symbol,
--
An_And_Operator ..
-- An_Or_Operator,
-- An_Xor_Operator,
-- An_Equal_Operator,
-- A_Not_Equal_Operator,
-- A_Less_Than_Operator,
-- A_Less_Than_Or_Equal_Operator,
-- A_Greater_Than_Operator,
-- A_Greater_Than_Or_Equal_Operator,
-- A_Plus_Operator,
-- A_Minus_Operator,
-- A_Concatenate_Operator,
-- A_Unary_Plus_Operator,
-- A_Unary_Minus_Operator,
-- A_Multiply_Operator,
-- A_Divide_Operator,
-- A_Mod_Operator,
-- A_Rem_Operator,
-- An_Exponentiate_Operator,
-- An_Abs_Operator,
-- A_Not_Operator => A_Function_Call,
A_Not_Operator => Non_Trivial_Mapping,
--
-- A_Character_Literal ..
-- -- An_Enumeration_Literal,
-- An_Explicit_Dereference => Trivial_Mapping,
--
-- A_Function_Call => Non_Trivial_Mapping,
-- --
-- An_Indexed_Component ..
-- A_Slice => Trivial_Mapping,
-- A_Selected_Component => Non_Trivial_Mapping,
-- --
-- -- -- ??? Not_An_Attribute,
-- -- -- An_Attribute_Reference => Non_Trivial_Mapping,
-- --
-- An_Access_Attribute ..
-- -- An_Address_Attribute,
-- -- An_Adjacent_Attribute,
-- -- An_Aft_Attribute,
-- -- An_Alignment_Attribute,
-- -- A_Base_Attribute,
-- -- A_Bit_Order_Attribute,
-- -- A_Body_Version_Attribute,
-- -- A_Callable_Attribute,
-- -- A_Caller_Attribute,
-- -- A_Ceiling_Attribute,
-- -- A_Class_Attribute,
-- -- A_Component_Size_Attribute,
-- -- A_Compose_Attribute,
-- -- A_Constrained_Attribute,
-- -- A_Copy_Sign_Attribute,
-- -- A_Count_Attribute,
-- -- A_Definite_Attribute,
-- -- A_Delta_Attribute,
-- -- A_Denorm_Attribute,
-- -- A_Digits_Attribute,
-- -- An_Exponent_Attribute,
-- -- An_External_Tag_Attribute,
-- -- A_First_Attribute,
-- -- A_First_Bit_Attribute,
-- -- A_Floor_Attribute,
-- -- A_Fore_Attribute,
-- -- A_Fraction_Attribute,
-- -- An_Identity_Attribute,
-- -- An_Image_Attribute,
-- -- An_Input_Attribute,
-- -- A_Last_Attribute,
-- -- A_Last_Bit_Attribute,
-- -- A_Leading_Part_Attribute,
-- -- A_Length_Attribute,
-- -- A_Machine_Attribute,
-- -- A_Machine_Emax_Attribute,
-- -- A_Machine_Emin_Attribute,
-- -- A_Machine_Mantissa_Attribute,
-- -- A_Machine_Overflows_Attribute,
-- -- A_Machine_Radix_Attribute,
-- -- A_Machine_Rounds_Attribute,
-- -- A_Max_Attribute,
-- -- A_Max_Size_In_Storage_Elements_Attribute,
-- -- A_Min_Attribute,
-- -- A_Model_Attribute,
-- -- A_Model_Emin_Attribute,
-- -- A_Model_Epsilon_Attribute,
-- -- A_Model_Mantissa_Attribute,
-- -- A_Model_Small_Attribute,
-- -- A_Modulus_Attribute,
-- -- An_Output_Attribute,
-- -- A_Partition_ID_Attribute,
-- -- A_Pos_Attribute,
-- -- A_Position_Attribute,
-- -- A_Pred_Attribute,
-- -- A_Range_Attribute,
-- -- A_Read_Attribute,
-- -- A_Remainder_Attribute,
-- -- A_Round_Attribute,
-- -- A_Rounding_Attribute,
-- -- A_Safe_First_Attribute,
-- -- A_Safe_Last_Attribute,
-- -- A_Scale_Attribute,
-- -- A_Scaling_Attribute,
-- -- A_Signed_Zeros_Attribute,
-- -- A_Size_Attribute,
-- -- A_Small_Attribute,
-- -- A_Storage_Pool_Attribute,
-- -- A_Storage_Size_Attribute,
-- --
-- -- A_Succ_Attribute,
-- -- A_Tag_Attribute,
-- -- A_Terminated_Attribute,
-- -- A_Truncation_Attribute,
-- -- An_Unbiased_Rounding_Attribute,
-- -- An_Unchecked_Access_Attribute,
-- -- A_Val_Attribute,
-- -- A_Valid_Attribute,
-- -- A_Value_Attribute,
-- -- A_Version_Attribute,
-- -- A_Wide_Image_Attribute,
-- -- A_Wide_Value_Attribute,
-- -- A_Wide_Width_Attribute,
-- -- A_Width_Attribute,
-- -- A_Write_Attribute,
-- --
-- -- An_Implementation_Defined_Attribute, -- Vendor Annex M
-- An_Unknown_Attribute => Non_Trivial_Mapping,
--
-- -- A_Record_Aggregate,
-- -- An_Extension_Aggregate,
-- -- A_Positional_Array_Aggregate,
-- -- A_Named_Array_Aggregate,
-- --
-- -- An_And_Then_Short_Circuit,
-- -- An_Or_Else_Short_Circuit,
-- --
-- -- An_In_Range_Membership_Test,
-- -- A_Not_In_Range_Membership_Test,
-- -- An_In_Type_Membership_Test,
-- -- A_Not_In_Type_Membership_Test,
-- --
-- -- A_Null_Literal,
-- -- A_Parenthesized_Expression,
-- --
-- -- A_Type_Conversion,
-- -- A_Qualified_Expression,
-- --
-- -- An_Allocation_From_Subtype,
-- An_Allocation_From_Qualified_Expression,
-- A_Case_Expression, -- Ada 2012
-- An_If_Expression, -- Ada 2012
-- A_For_All_Quantified_Expression, -- Ada 2012
-- A_For_Some_Quantified_Expression); -- Ada 2012
A_Character_Literal ..
A_For_Some_Quantified_Expression => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
--
-- -- An_Association, -- Asis.Expressions
--
------------------------------------------------------------------------------
--
A_Pragma_Argument_Association => Trivial_Mapping,
A_Discriminant_Association => Non_Trivial_Mapping,
A_Record_Component_Association => Trivial_Mapping,
An_Array_Component_Association => Non_Trivial_Mapping,
A_Parameter_Association => Non_Trivial_Mapping,
A_Generic_Association => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
--
-- -- A_Statement, -- Asis.Statements
--
-- All subordinates of A_Statement kind require non trivial processing,
-- this processing is the same for all of them except
-- A_Terminate_Alternative_Statement
------------------------------------------------------------------------------
--
A_Null_Statement ..
-- An_Assignment_Statement,
-- An_If_Statement,
-- A_Case_Statement,
--
-- A_Loop_Statement,
-- A_While_Loop_Statement,
-- A_For_Loop_Statement,
--
-- A_Block_Statement,
-- An_Exit_Statement,
-- A_Goto_Statement,
--
-- A_Procedure_Call_Statement,
-- A_Return_Statement,
--
-- An_Accept_Statement,
-- An_Entry_Call_Statement,
--
-- A_Requeue_Statement,
-- A_Requeue_Statement_With_Abort,
--
-- A_Delay_Until_Statement,
-- A_Delay_Relative_Statement,
--
-- A_Terminate_Alternative_Statement,
-- A_Selective_Accept_Statement,
-- A_Timed_Entry_Call_Statement,
-- A_Conditional_Entry_Call_Statement,
-- An_Asynchronous_Select_Statement,
--
-- An_Abort_Statement,
-- A_Raise_Statement,
A_Code_Statement => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
-- Path_Kinds
-- Literals -- Ada RM 95
--
-- Detailed classification for
-- ASIS_Element_Kinds.Element_Kinds(A_Path) literal
-- corresponds to subtype Internal_Path_Kinds
------------------------------------------------------------------------------
An_If_Path => An_If_Statement,
An_Elsif_Path => Trivial_Mapping,
An_Else_Path => Non_Trivial_Mapping,
A_Case_Path => Trivial_Mapping,
A_Select_Path => Trivial_Mapping,
An_Or_Path => Trivial_Mapping,
A_Then_Abort_Path => Trivial_Mapping,
--
------------------------------------------------------------
-- An_Expression_Path, -- Asis.Expressions Ada 2015
-- Detailed classification for Asis.Element_Kinds (An_Expression_Path)
-- literal corresponds to subtype Internal_Expression_Path_Kinds
------------------------------------------------------------
An_If_Expression_Path ..
-- An_Elsif_Expression_Path,
An_Else_Expression_Path => Non_Trivial_Mapping,
------------------------------------------------------------------------
--
-- -- A_Clause, -- Asis.Clauses
--
------------------------------------------------------------------------------
--
A_Use_Package_Clause => Non_Trivial_Mapping,
A_Use_Type_Clause => Non_Trivial_Mapping,
A_Use_All_Type_Clause => Non_Trivial_Mapping,
A_With_Clause => Not_An_Element,
--
-- -- A_Representation_Clause,
--
An_Attribute_Definition_Clause => Non_Trivial_Mapping,
An_Enumeration_Representation_Clause => Trivial_Mapping,
A_Record_Representation_Clause => Trivial_Mapping,
An_At_Clause => Trivial_Mapping,
--
--
A_Component_Clause => Trivial_Mapping,
--
------------------------------------------------------------------------------
--
An_Exception_Handler => Non_Trivial_Mapping,
--
------------------------------------------------------------------------------
-- Special values added for Node -> Element and
-- Element -> Enclosing Element switching,
------------------------------------------------------------------------------
Non_Trivial_Mapping => No_Mapping,
Not_Implemented_Mapping => No_Mapping,
Trivial_Mapping => No_Mapping,
No_Mapping => No_Mapping,
others => Not_Implemented_Mapping
);
-------------------------------------------------------------------------
-- Section 2 - declarations of routines implementing various cases of --
-- non-trivial bottom up compiler tree traversing and --
-- accessed though the second switch --
-------------------------------------------------------------------------
function Not_Implemented_Enclosing_Element_Construction
(Element : Asis.Element) return Asis.Element;
-- Placeholders for "others" choice
-- The functions below computes Enclosing_Elememnt for specific Element
-- kinds; the corresponding situations cannot be covered by
-- General_Encl_Elem
function A_Pragma_Enclosing (Element : Asis.Element) return Asis.Element;
function A_Defining_Expanded_Name_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Defining_Identifier_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Defining_Operator_Symbol_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Constant_Declaration_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Enumeration_Literal_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Discriminant_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Loop_Parameter_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Parameter_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Enumeration_Type_Definition_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Subtype_Indication_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Range_Attribute_Reference_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Simple_Expression_Range_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Discrete_Range_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Discriminant_Part_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Record_Definition_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Null_Component_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Variant_Part_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Others_Choice_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Statement_Enclosing
(Element : Asis.Element)
return Asis.Element;
function A_Terminate_Alternative_Statement_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Else_Path_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Attribute_Definition_Clause_Enclosing
(Element : Asis.Element)
return Asis.Element;
function An_Exception_Handler_Enclosing
(Element : Asis.Element)
return Asis.Element;
function Possible_C_U_Enclosing
(Element : Asis.Element)
return Asis.Element;
-- Called in a situation when Enclosing_Element may have to be Nil_Element,
-- because we may reach the very top of the Element hierarchy of an ASIS
-- Compilation_Unit, so logically the next step up should be from Elements
-- into enclosing unit.
function An_Association_Enclosing
(Element : Asis.Element)
return Asis.Element;
-- Computes the Enclosing Element for parameter associations. The main
-- difference with An_Expression_Enclosing is that here we may have to deal
-- with normalized associations
function An_Expression_Enclosing
(Element : Asis.Element)
return Asis.Element;
-- This function implements the part of the semantic of the
-- Asis.Elements.Enclosing_Element function corresponding to the
-- enclosing element retrieving for elements representing Ada explicit
-- constructs. It deals only with expressions - the hardest part
-- for Enclosing_Element.
--------------------------------------------------------------------
-- Section 3 - definition of the second Enclosing_Element switch --
-- (maps Element kind requiring non-trivial actions --
-- onto corresponding routines --
--------------------------------------------------------------------
type Enclosing_Element_Construction_For_Explicits_Items is access
function (Element : Asis.Element) return Asis.Element;
-- access to the local items of the constructing the Enclosing Elements
-- for Explicit constructs
Enclosing_Element_For_Explicits_Second_Switch : constant
array (Internal_Element_Kinds)
of Enclosing_Element_Construction_For_Explicits_Items :=
(
-- type Internal_Element_Kinds is (
--
-- Not_An_Element, -- Asis.Nil_Element
--
------------------------------------------------------------------------------
-- A_Pragma, -- Asis.Elements
------------------------------------------------------------------------------
An_All_Calls_Remote_Pragma ..
-- An_Asynchronous_Pragma,
-- An_Atomic_Pragma,
-- An_Atomic_Components_Pragma,
-- An_Attach_Handler_Pragma,
-- A_Controlled_Pragma,
-- A_Convention_Pragma,
-- A_Discard_Names_Pragma,
-- An_Elaborate_Pragma,
-- An_Elaborate_All_Pragma,
-- An_Elaborate_Body_Pragma,
-- An_Export_Pragma,
-- An_Import_Pragma,
-- An_Inline_Pragma,
-- An_Inspection_Point_Pragma,
-- An_Interrupt_Handler_Pragma,
-- An_Interrupt_Priority_Pragma,
-- A_Linker_Options_Pragma
-- A_List_Pragma,
-- A_Locking_Policy_Pragma,
-- A_Normalize_Scalars_Pragma,
-- An_Optimize_Pragma,
-- A_Pack_Pragma,
-- A_Page_Pragma,
-- A_Preelaborate_Pragma,
-- A_Priority_Pragma,
-- A_Pure_Pragma,
-- A_Queuing_Policy_Pragma,
-- A_Remote_Call_Interface_Pragma,
-- A_Remote_Types_Pragma,
-- A_Restrictions_Pragma,
-- A_Reviewable_Pragma,
-- A_Shared_Passive_Pragma,
-- A_Storage_Size_Pragma,
-- A_Suppress_Pragma,
-- A_Task_Dispatching_Policy_Pragma,
-- A_Volatile_Pragma,
-- A_Volatile_Components_Pragma,
--
-- An_Implementation_Defined_Pragma,
--
An_Unknown_Pragma => A_Pragma_Enclosing'Access,
------------------------------------------------------------------------------
-- A_Defining_Name, -- Asis.Declarations
------------------------------------------------------------------------------
A_Defining_Identifier => A_Defining_Identifier_Enclosing'Access,
-- A_Defining_Character_Literal, -- an Enclosing Element is based
-- A_Defining_Enumeration_Literal, -- on the same Node
--
-- -- A_Defining_Operator_Symbol
--
A_Defining_And_Operator ..
-- A_Defining_Or_Operator,
-- A_Defining_Xor_Operator,
-- A_Defining_Equal_Operator,
-- A_Defining_Not_Equal_Operator,
-- A_Defining_Less_Than_Operator,
-- A_Defining_Less_Than_Or_Equal_Operator,
-- A_Defining_Greater_Than_Operator,
-- A_Defining_Greater_Than_Or_Equal_Operator,
-- A_Defining_Plus_Operator,
-- A_Defining_Minus_Operator,
-- A_Defining_Concatenate_Operator,
-- A_Defining_Unary_Plus_Operator,
-- A_Defining_Unary_Minus_Operator,
-- A_Defining_Multiply_Operator,
-- A_Defining_Divide_Operator,
-- A_Defining_Mod_Operator,
-- A_Defining_Rem_Operator,
-- A_Defining_Exponentiate_Operator,
-- A_Defining_Abs_Operator,
A_Defining_Not_Operator => A_Defining_Operator_Symbol_Enclosing'Access,
A_Defining_Expanded_Name => A_Defining_Expanded_Name_Enclosing'Access,
--
-------------------------------------------------------------------------------
--
-- -- A_Declaration, -- Asis.Declarations
--
-------------------------------------------------------------------------------
--
-- An_Ordinary_Type_Declaration, -- 3.2.1
-- A_Task_Type_Declaration, -- 3.2.1
-- A_Protected_Type_Declaration, -- 3.2.1
-- An_Incomplete_Type_Declaration, -- 3.2.1
-- A_Private_Type_Declaration, -- 3.2.1
-- A_Private_Extension_Declaration, -- 3.2.1
--
-- A_Subtype_Declaration, -- 3.2.2
--
-- A_Variable_Declaration, -- 3.3.1 -> Trait_Kinds
A_Constant_Declaration => A_Constant_Declaration_Enclosing'Access,
-- This is turned off, see G416-009
-- A_Deferred_Constant_Declaration, -- 3.3.1 -> Trait_Kinds
-- A_Single_Task_Declaration, -- 3.3.1
-- A_Single_Protected_Declaration, -- 3.3.1
--
-- An_Integer_Number_Declaration, -- 3.3.2
-- A_Real_Number_Declaration, -- 3.3.2
--
An_Enumeration_Literal_Specification =>
An_Enumeration_Literal_Specification_Enclosing'Access,
--
A_Discriminant_Specification => A_Discriminant_Specification_Enclosing'Access,
--
-- A_Component_Declaration => A_Component_Declaration_Enclosing'Access,
A_Component_Declaration => An_Expression_Enclosing'Access,
--
A_Loop_Parameter_Specification =>
A_Loop_Parameter_Specification_Enclosing'Access,
A_Generalized_Iterator_Specification ..
An_Element_Iterator_Specification =>
A_Loop_Parameter_Specification_Enclosing'Access,
--
A_Procedure_Declaration => Possible_C_U_Enclosing'Access,
A_Function_Declaration => Possible_C_U_Enclosing'Access,
--
A_Parameter_Specification => A_Parameter_Specification_Enclosing'Access,
A_Procedure_Body_Declaration => Possible_C_U_Enclosing'Access,
A_Function_Body_Declaration => Possible_C_U_Enclosing'Access,
--
A_Package_Declaration => Possible_C_U_Enclosing'Access,
A_Package_Body_Declaration => Possible_C_U_Enclosing'Access,
--
-- An_Object_Renaming_Declaration, -- 8.5.1
-- An_Exception_Renaming_Declaration, -- 8.5.2
A_Package_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Procedure_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Function_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Generic_Package_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Generic_Procedure_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Generic_Function_Renaming_Declaration => Possible_C_U_Enclosing'Access,
A_Task_Body_Declaration => Possible_C_U_Enclosing'Access,
A_Protected_Body_Declaration => Possible_C_U_Enclosing'Access,
--
An_Entry_Declaration => An_Expression_Enclosing'Access,
-- for entry declarations, the problem is for single task declarations
-- rewritten as anonymous task type declaration and task object declaration,
-- that's why we have to use An_Expression_Enclosing
-- An_Entry_Body_Declaration, -- 9.5.2
-- An_Entry_Index_Specification, -- 9.5.2
--
-- A_Procedure_Body_Stub, -- 10.1.3
-- A_Function_Body_Stub, -- 10.1.3
-- A_Package_Body_Stub, -- 10.1.3
-- A_Task_Body_Stub, -- 10.1.3
-- A_Protected_Body_Stub, -- 10.1.3
--
-- An_Exception_Declaration, -- 11.1
-- A_Choice_Parameter_Specification, -- 11.2
--
A_Generic_Procedure_Declaration => Possible_C_U_Enclosing'Access,
A_Generic_Function_Declaration => Possible_C_U_Enclosing'Access,
A_Generic_Package_Declaration => Possible_C_U_Enclosing'Access,
A_Package_Instantiation => Possible_C_U_Enclosing'Access,
A_Procedure_Instantiation => Possible_C_U_Enclosing'Access,
A_Function_Instantiation => Possible_C_U_Enclosing'Access,
--
-- A_Formal_Object_Declaration, -- 12.4 -> Mode_Kinds
--
-- A_Formal_Type_Declaration, -- 12.5
-- A_Formal_Procedure_Declaration, -- 12.6 -> Default_Kinds
--
-- A_Formal_Function_Declaration, -- 12.6 -> Default_Kinds
--
-- A_Formal_Package_Declaration, -- 12.7
-- A_Formal_Package_Declaration_With_Box, -- 12.7
--
-------------------------------------------------------------------------------
--
-- -- A_Definition, -- Asis.Definitions
--
-------------------------------------------------------------------------------
--
-- -- A_Type_Definition, -- 3.2.1 -> Type_Kinds
--
-- A_Derived_Type_Definition, -- 3.4 -> Trait_Kinds
-- A_Derived_Record_Extension_Definition, -- 3.4 -> Trait_Kinds
--
An_Enumeration_Type_Definition =>
An_Enumeration_Type_Definition_Enclosing'Access,
--
-- A_Signed_Integer_Type_Definition, -- 3.5.4
-- A_Modular_Type_Definition, -- 3.5.4
--
-- -- A_Root_Type_Definition, -- 3.5.4(10), 3.5.6(4)
-- -- -> Root_Type_Kinds
-- A_Root_Integer_Definition, -- 3.5.4(9)
-- A_Root_Real_Definition, -- 3.5.6(2)
-- A_Root_Fixed_Definition, -- 3.5.6(2)
--
-- A_Universal_Integer_Definition, -- 3.5.4(10)
-- A_Universal_Real_Definition, -- 3.5.6(4)
-- A_Universal_Fixed_Definition, -- 3.5.6(4)
--
--
-- A_Floating_Point_Definition, -- 3.5.7
--
-- An_Ordinary_Fixed_Point_Definition, -- 3.5.9
-- A_Decimal_Fixed_Point_Definition, -- 3.5.9
--
-- An_Unconstrained_Array_Definition, -- 3.6
-- A_Constrained_Array_Definition, -- 3.6
--
-- A_Record_Type_Definition, -- 3.8 -> Trait_Kinds
-- A_Tagged_Record_Type_Definition, -- 3.8 -> Trait_Kinds
--
-- -- An_Access_Type_Definition, -- 3.10 -> Access_Type_Kinds
--
-- A_Pool_Specific_Access_To_Variable,
-- An_Access_To_Variable,
-- An_Access_To_Constant,
--
-- An_Access_To_Procedure,
-- An_Access_To_Protected_Procedure,
-- An_Access_To_Function,
-- An_Access_To_Protected_Function,
--
--
A_Subtype_Indication => A_Subtype_Indication_Enclosing'Access,
--
-- -- A_Constraint, -- 3.2.2 -> Constraint_Kinds
--
A_Range_Attribute_Reference => A_Range_Attribute_Reference_Enclosing'Access,
A_Simple_Expression_Range => A_Simple_Expression_Range_Enclosing'Access,
-- A_Digits_Constraint, -- 3.2.2, 3.5.9
-- A_Delta_Constraint, -- 3.2.2, N.3
-- An_Index_Constraint => An_Index_Constraint_Enclosing'Access,
An_Index_Constraint => An_Expression_Enclosing'Access,
A_Discriminant_Constraint => An_Expression_Enclosing'Access,
--
-- A_Component_Definition, -- 3.6
--
-- -- A_Discrete_Subtype_Definition, -- 3.6 -> Discrete_Range_Kinds
--
-- A_Discrete_Subtype_Indication_As_Subtype_Definition,
-- A_Discrete_Range_Attribute_Reference_As_Subtype_Definition,
-- A_Discrete_Simple_Expression_Range_As_Subtype_Definition,
--
-- -- A_Discrete_Range, -- 3.6.1 -> Discrete_Range_Kinds
--
A_Discrete_Subtype_Indication => A_Discrete_Range_Enclosing'Access,
A_Discrete_Range_Attribute_Reference => A_Discrete_Range_Enclosing'Access,
A_Discrete_Simple_Expression_Range => A_Discrete_Range_Enclosing'Access,
--
--
An_Unknown_Discriminant_Part => A_Discriminant_Part_Enclosing'Access,
A_Known_Discriminant_Part => A_Discriminant_Part_Enclosing'Access,
--
A_Record_Definition => A_Record_Definition_Enclosing'Access,
A_Null_Record_Definition => A_Record_Definition_Enclosing'Access,
--
A_Null_Component => A_Null_Component_Enclosing'Access,
A_Variant_Part => A_Variant_Part_Enclosing'Access,
-- A_Variant, -- 3.8
--
An_Others_Choice => An_Others_Choice_Enclosing'Access,
-- A_Private_Type_Definition, -- 7.3 -> Trait_Kinds
-- A_Tagged_Private_Type_Definition, -- 7.3 -> Trait_Kinds
-- A_Private_Extension_Definition, -- 7.3 -> Trait_Kinds
--
-- A_Task_Definition, -- 9.1
A_Protected_Definition => An_Expression_Enclosing'Access,
--
-- -- A_Formal_Type_Definition, -- 12.5 -> Formal_Type_Kinds
--
-- A_Formal_Private_Type_Definition, -- 12.5.1 -> Trait_Kinds
-- A_Formal_Tagged_Private_Type_Definition, -- 12.5.1 -> Trait_Kinds
--
-- A_Formal_Derived_Type_Definition, -- 12.5.1 -> Trait_Kinds
--
-- A_Formal_Discrete_Type_Definition, -- 12.5.2
--
-- A_Formal_Signed_Integer_Type_Definition, -- 12.5.2
-- A_Formal_Modular_Type_Definition, -- 12.5.2
--
-- A_Formal_Floating_Point_Definition, -- 12.5.2
--
-- A_Formal_Ordinary_Fixed_Point_Definition, -- 12.5.2
-- A_Formal_Decimal_Fixed_Point_Definition, -- 12.5.2
--
-- A_Formal_Unconstrained_Array_Definition, -- 12.5.3
-- A_Formal_Constrained_Array_Definition, -- 12.5.3
--
-- -- A_Formal_Access_Type_Definition,
--
-- A_Formal_Pool_Specific_Access_To_Variable,
-- A_Formal_Access_To_Variable,
-- A_Formal_Access_To_Constant,
--
-- A_Formal_Access_To_Procedure,
-- A_Formal_Access_To_Protected_Procedure,
-- A_Formal_Access_To_Function,
-- A_Formal_Access_To_Protected_Function,
--
-------------------------------------------------------------------------------
--
-- -- An_Expression, -- Asis.Expressions
--
-------------------------------------------------------------------------------
-- --
An_Integer_Literal ..
-- -- A_Real_Literal, -- 2.4.1
-- A_String_Literal => A_Literal_Enclosing'Access,
-- --
An_Identifier => An_Expression_Enclosing'Access,
-- An_Identifier => An_Identifier_Enclosing'Access,
-- --
-- ---- An_Operator_Symbol, -- 4.1
-- --
An_And_Operator ..
-- -- An_Or_Operator, -- or
-- -- An_Xor_Operator, -- xor
-- -- An_Equal_Operator, -- =
-- -- A_Not_Equal_Operator, -- /=
-- -- A_Less_Than_Operator, -- <
-- -- A_Less_Than_Or_Equal_Operator, -- <=
-- -- A_Greater_Than_Operator, -- >
-- -- A_Greater_Than_Or_Equal_Operator, -- >=
-- -- A_Plus_Operator, -- +
-- -- A_Minus_Operator, -- -
-- -- A_Concatenate_Operator, -- &
-- -- A_Unary_Plus_Operator, -- +
-- -- A_Unary_Minus_Operator, -- -
-- -- A_Multiply_Operator, -- *
-- -- A_Divide_Operator, -- /
-- -- A_Mod_Operator, -- mod
-- -- A_Rem_Operator, -- rem
-- -- An_Exponentiate_Operator, -- **
-- -- An_Abs_Operator, -- abs
-- A_Not_Operator => An_Operator_Symbol_Enclosing'Access,
-- ??? Do we need An_Operator_Symbol_Enclosing???
A_Not_Operator => An_Expression_Enclosing'Access,
-- --
A_Character_Literal ..
-- -- An_Enumeration_Literal, -- 4.1
-- -- An_Explicit_Dereference, -- 4.1
--
-- A_Function_Call => A_Function_Call_Enclosing'Access,
-- --
-- -- An_Indexed_Component, -- 4.1.1
-- -- A_Slice, -- 4.1.2
-- A_Selected_Component => An_Identifier_Enclosing'Access,
-- --
-- -- An_Attribute_Reference, -- 4.1.4 -> Attribute_Kinds
-- --
-- An_Access_Attribute ..
-- -- An_Address_Attribute,
-- -- An_Adjacent_Attribute,
-- -- An_Aft_Attribute,
-- -- An_Alignment_Attribute,
-- -- A_Base_Attribute,
-- -- A_Bit_Order_Attribute,
-- -- A_Body_Version_Attribute,
-- -- A_Callable_Attribute,
-- -- A_Caller_Attribute,
-- -- A_Ceiling_Attribute,
-- -- A_Class_Attribute,
-- -- A_Component_Size_Attribute,
-- -- A_Compose_Attribute,
-- -- A_Constrained_Attribute,
-- -- A_Copy_Sign_Attribute,
-- -- A_Count_Attribute,
-- -- A_Definite_Attribute,
-- -- A_Delta_Attribute,
-- -- A_Denorm_Attribute,
-- -- A_Digits_Attribute,
-- -- An_Exponent_Attribute,
-- -- An_External_Tag_Attribute,
-- -- A_First_Attribute,
-- -- A_First_Bit_Attribute,
-- -- A_Floor_Attribute,
-- -- A_Fore_Attribute,
-- -- A_Fraction_Attribute,
-- -- An_Identity_Attribute,
-- -- An_Image_Attribute,
-- -- An_Input_Attribute,
-- -- A_Last_Attribute,
-- -- A_Last_Bit_Attribute,
-- -- A_Leading_Part_Attribute,
-- -- A_Length_Attribute,
-- -- A_Machine_Attribute,
-- -- A_Machine_Emax_Attribute,
-- -- A_Machine_Emin_Attribute,
-- -- A_Machine_Mantissa_Attribute,
-- -- A_Machine_Overflows_Attribute,
-- -- A_Machine_Radix_Attribute,
-- -- A_Machine_Rounds_Attribute,
-- -- A_Max_Attribute,
-- -- A_Max_Size_In_Storage_Elements_Attribute,
-- -- A_Min_Attribute,
-- -- A_Model_Attribute,
-- -- A_Model_Emin_Attribute,
-- -- A_Model_Epsilon_Attribute,
-- -- A_Model_Mantissa_Attribute,
-- -- A_Model_Small_Attribute,
-- -- A_Modulus_Attribute,
-- -- An_Output_Attribute,
-- -- A_Partition_ID_Attribute,
-- -- A_Pos_Attribute,
-- -- A_Position_Attribute,
-- A_Pred_Attribute => An_Attribute_Reference_Enclosing'Access,
--
-- A_Range_Attribute => A_Range_Attribute_Enclosing'Access,
--
-- A_Read_Attribute ..
-- -- A_Remainder_Attribute,
-- -- A_Round_Attribute,
-- -- A_Rounding_Attribute,
-- -- A_Safe_First_Attribute,
-- -- A_Safe_Last_Attribute,
-- -- A_Scale_Attribute,
-- -- A_Scaling_Attribute,
-- -- A_Signed_Zeros_Attribute,
-- -- A_Size_Attribute,
-- -- A_Small_Attribute,
-- -- A_Storage_Pool_Attribute,
-- -- A_Storage_Size_Attribute,
-- --
-- -- A_Succ_Attribute,
-- -- A_Tag_Attribute,
-- -- A_Terminated_Attribute,
-- -- A_Truncation_Attribute,
-- -- An_Unbiased_Rounding_Attribute,
-- -- An_Unchecked_Access_Attribute,
-- -- A_Val_Attribute,
-- -- A_Valid_Attribute,
-- -- A_Value_Attribute,
-- -- A_Version_Attribute,
-- -- A_Wide_Image_Attribute,
-- -- A_Wide_Value_Attribute,
-- -- A_Wide_Width_Attribute,
-- -- A_Width_Attribute,
-- -- A_Write_Attribute,
-- --
-- -- An_Implementation_Defined_Attribute, -- Vendor Annex M
-- An_Unknown_Attribute => An_Attribute_Reference_Enclosing'Access,
-- --
-- -- A_Record_Aggregate, -- 4.3
-- -- An_Extension_Aggregate, -- 4.3
-- -- A_Positional_Array_Aggregate, -- 4.3
-- -- A_Named_Array_Aggregate, -- 4.3
-- --
-- -- An_And_Then_Short_Circuit, -- 4.4
-- -- An_Or_Else_Short_Circuit, -- 4.4
-- --
-- -- An_In_Range_Membership_Test, -- 4.4
-- -- A_Not_In_Range_Membership_Test, -- 4.4
-- -- An_In_Type_Membership_Test, -- 4.4
-- -- A_Not_In_Type_Membership_Test, -- 4.4
-- --
-- -- A_Null_Literal, -- 4.4
-- -- A_Parenthesized_Expression, -- 4.4
-- --
-- -- A_Type_Conversion, -- 4.6
-- -- A_Qualified_Expression, -- 4.7
-- --
-- -- An_Allocation_From_Subtype, -- 4.8
-- -- An_Allocation_From_Qualified_Expression, -- 4.8
-- A_Case_Expression, -- Ada 2012
-- An_If_Expression, -- Ada 2012
-- A_For_All_Quantified_Expression, -- Ada 2012
-- A_For_Some_Quantified_Expression); -- Ada 2012
A_For_Some_Quantified_Expression => An_Expression_Enclosing'Access,
-------------------------------------------------------------------------------
--
-- -- An_Association, -- Asis.Expressions
--
-------------------------------------------------------------------------------
--
-- A_Pragma_Argument_Association, -- 2.8
A_Discriminant_Association => An_Expression_Enclosing'Access,
-- A_Record_Component_Association, -- 4.3.1
An_Array_Component_Association => An_Expression_Enclosing'Access,
A_Parameter_Association .. A_Generic_Association =>
An_Association_Enclosing'Access,
--
-------------------------------------------------------------------------------
--
-- -- A_Statement, -- Asis.Statements
--
-------------------------------------------------------------------------------
--
A_Null_Statement ..
-- An_Assignment_Statement, -- 5.2
-- An_If_Statement, -- 5.3
-- A_Case_Statement, -- 5.4
--
-- A_Loop_Statement, -- 5.5
-- A_While_Loop_Statement, -- 5.5
-- A_For_Loop_Statement, -- 5.5
--
-- A_Block_Statement, -- 5.6
-- An_Exit_Statement, -- 5.7
-- A_Goto_Statement, -- 5.8
--
-- A_Procedure_Call_Statement, -- 6.4
-- A_Return_Statement, -- 6.5
--
-- An_Accept_Statement, -- 9.5.2
-- An_Entry_Call_Statement, -- 9.5.3
--
-- A_Requeue_Statement, -- 9.5.4
-- A_Requeue_Statement_With_Abort, -- 9.5.4
--
-- A_Delay_Until_Statement, -- 9.6
A_Delay_Relative_Statement => A_Statement_Enclosing'Access,
--
A_Terminate_Alternative_Statement =>
A_Terminate_Alternative_Statement_Enclosing'Access,
--
A_Selective_Accept_Statement ..
-- A_Timed_Entry_Call_Statement, -- 9.7.3
-- A_Conditional_Entry_Call_Statement, -- 9.7.3
-- An_Asynchronous_Select_Statement, -- 9.7.4
--
-- An_Abort_Statement, -- 9.8
-- A_Raise_Statement, -- 11.3
A_Code_Statement => A_Statement_Enclosing'Access,
--
-------------------------------------------------------------------------------
-- Path_Kinds
-- Literals -- RM 95
------------------------------------------------------------------------------
--
-- An_If_Path,
-- An_Elsif_Path,
--
An_Else_Path => An_Else_Path_Enclosing'Access,
--
-- A_Case_Path,
-- -- when discrete_choice_list =>
-- -- sequence_of_statements
--
-- A_Select_Path,
-- -- select [guard] select_alternative
-- -- 9.7.2, 9.7.3:
-- -- select entry_call_alternative
-- -- 9.7.4:
-- -- select triggering_alternative
--
-- An_Or_Path,
-- -- or [guard] select_alternative 9.7.2:
-- -- or delay_alternative
--
-- A_Then_Abort_Path, -- 9.7.4
-- -- then abort sequence_of_statements
--
--
------------------------------------------------------------
-- An_Expression_Path, -- Asis.Expressions Ada 2015
------------------------------------------------------------
An_If_Expression_Path ..
-- An_Elsif_Expression_Path,
An_Else_Expression_Path => An_Expression_Enclosing'Access,
-------------------------------------------------------------------------------
--
-- -- A_Clause, -- Asis.Clauses
--
-------------------------------------------------------------------------------
--
A_Use_Package_Clause => Possible_C_U_Enclosing'Access, -- 8.4
A_Use_Type_Clause => Possible_C_U_Enclosing'Access, -- 8.4
A_Use_All_Type_Clause => Possible_C_U_Enclosing'Access, -- 8.4 Ada 2012
--
-- A_With_Clause, -- 10.1.2
--
-- -- A_Representation_Clause, -- 13.1 -> Representation_Clause_Kinds
--
An_Attribute_Definition_Clause =>
An_Attribute_Definition_Clause_Enclosing'Access,
-- An_Enumeration_Representation_Clause, -- 13.4
-- A_Record_Representation_Clause, -- 13.5.3
-- An_At_Clause, -- N.7
--
--
-- A_Component_Clause, -- 13.5.3
--
-------------------------------------------------------------------------------
--
An_Exception_Handler => An_Exception_Handler_Enclosing'Access,
--
-------------------------------------------------------------------------------
-- -- Special values added for Node -> Element switching,
-- -- see Asis_Vendor_Primitives.GNAT_to_Asis_Mapping body for
-- -- more details
-------------------------------------------------------------------------------
--
-- Non_Trivial_Mapping,
-- Not_Implemented_Mapping,
-- No_Mapping
--
others => Not_Implemented_Enclosing_Element_Construction'Access);
------------------------------------------------------
-- Section 4 - (general-purpose) local subprograms --
------------------------------------------------------
procedure Skip_Implicit_Subtype (Constr : in out Node_Id);
-- Supposing that Constr is a constraint, this procedure checks if the
-- parent node for it points to implicit subtype created in case if
-- this constraint is used directly in object declaration, and if
-- so, resets Constr to point to the constraint from the object
-- declaration
function Parent (Node : Node_Id) return Node_Id;
-- this function is the modification of Atree.Parent. It is able
-- to deal in the "ASIS mode" with the sequences of one-identifier
-- declarations/with clauses resulting from the normalization of
-- multi-name declarations/with clauses which is done by the
-- compiler
function General_Encl_Elem (Element : Asis.Element) return Asis.Element;
-- Computes Enclosing_Element for most common cases
procedure No_Enclosing_Element (Element_Kind : Internal_Element_Kinds);
-- Should be called only in erroneous situations, when no Enclosing_Element
-- can correspond to a given Element. Raises ASIS_Failed with the
-- corresponding Diagnosis
procedure Not_Implemented_Enclosing_Element_Construction
(Element : Asis.Element);
-- Generates Element-specific diagnosis about non-implemented case
function Is_Top_Of_Expanded_Generic (N : Node_Id) return Boolean;
-- Checks if N is the top node of the tree structure corresponding to
-- expanded generic spec or body
function Get_Rough_Enclosing_Node (Element : Asis.Element) return Node_Id;
-- This function finds the node, which is the base for a "rough"
-- enclosing element for the argument Element. Starting from the
-- argument R_Node, we go up through the chain of Parent nodes
-- till the first node, which is a member of some Node_List or to the node
-- representing the unit declaration in a compilation unit
function Get_Enclosing
(Approximation : Asis.Element;
Element : Asis.Element)
return Asis.Element;
-- This function finds the Enclosing Element for Element by traversing
-- Approximation which is considered as a rough estimation for
-- enclosing element.
procedure Skip_Normalized_Declarations_Back (Node : in out Node_Id);
-- this procedure is applied in case when the compiler may normalize a
-- multi-identifier declaration (or multi-name with clause) in a set of
-- equivalent one-identifier (one-name) declarations (clauses). It is
-- intended to be called for Node representing any declaration
-- (clause) in this normalized sequence, and it resets its parameter
-- to point to the first declaration (clause) in this sequence
--
-- There is no harm to call this procedure for Node which does not
-- represent a normalized declaration (or even which does not represent
-- any declaration at all), or for Node which represents the first
-- declaration in a normalized chain - the procedure simply leaves
-- its parameter intact.
--
-- (In some sense this procedure may be considered as an "inversion
-- of the local procedure Skip_Normalized_Declarations defined in
-- the body of the A4G.Mapping package)
---------------------------------------------------------------
-- Section 5 - bodies of the routines declared in Section 2 --
---------------------------------------------------------------
--------------------------------------
-- A_Constant_Declaration_Enclosing --
--------------------------------------
function A_Constant_Declaration_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result : Asis.Element := General_Encl_Elem (Element);
Res_Node : Node_Id;
begin
-- The problem with constant declarations exists for a declarations
-- created by the front-end to pass the actual expressions for generic
-- IN parameters, see EC16-004 and EC22-007
Res_Node := Node (Element);
if Present (Corresponding_Generic_Association (Res_Node)) then
Res_Node := Parent (Res_Node);
if No (Generic_Parent (Res_Node)) then
-- This IF statement prevents us from doing this special
-- processing for expanded package declarations, we have to do it
-- only for wrapper packages created for subprogram instantiation
Res_Node := Parent (Res_Node);
Res_Node := Corresponding_Body (Res_Node);
Res_Node := Parent (Res_Node);
Res_Node := First (Sinfo.Declarations (Res_Node));
while Nkind (Res_Node) /= N_Subprogram_Body loop
Res_Node := Next (Res_Node);
end loop;
Result := Node_To_Element_New (Node => Res_Node,
Starting_Element => Element);
end if;
end if;
return Result;
end A_Constant_Declaration_Enclosing;
----------------------------------------
-- A_Defining_Expanded_Name_Enclosing --
---------------------------------------
function A_Defining_Expanded_Name_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id := Parent (R_Node (Element));
Parent_Node_Kind : constant Node_Kind := Nkind (Parent_Node);
begin
if Parent_Node_Kind = N_Function_Specification or else
Parent_Node_Kind = N_Procedure_Specification or else
Parent_Node_Kind = N_Package_Specification
then -- one more step up required
Parent_Node := Parent (Parent_Node);
end if;
return Node_To_Element_New (Node => Parent_Node,
Starting_Element => Element);
end A_Defining_Expanded_Name_Enclosing;
-------------------------------------
-- A_Defining_Identifier_Enclosing --
-------------------------------------
function A_Defining_Identifier_Enclosing
(Element : Asis.Element)
return Asis.Element
is
-- A_Defining_Identifier may be processed just in the same way as
-- A_Defining_Expanded_Name, except the following cases:
-- - A_Defining_Identifier obtained as the child of
-- A_Choice_Parameter_Specification element (by means of Names
-- query) - both these elements are based on the same
-- N_Defining_Identifier node
--
-- - A_Defining_Identifier representing a statement label, it is
-- obtained by means of Label_Names query, and it is based on
-- N_Label node which is the member of the node list representing
-- the corresponding statement sequence (or it can be based on
-- N_Identifier node in case if the front-end rewrites a sequence of
-- statement implementing the infinite loop by goto into
-- N_Loop_Statement node. The Enclosing_Element of such
-- A_Defining_Name element will be the statement labeled by it, see
-- Asis_Statements.Label_Names.
--
-- - A_Defining_Identifier representing a statement identifier, it is
-- obtained by means of Statement_Identifier query, and it is based
-- on N_Identifier node. The Enclosing_Element of the name is the
-- named statement, see Asis_Statements.Statement_Identifier. But
-- there is no difference in computing the Enclosing Element
-- (compared to A_Defining_Expanded_Name) in this case.
--
-- - A special processing is needed for a formal package defining name
--
-- - A_Defining_Identifier is from a single task/protected declaration
Parent_Node : Node_Id := Parent (R_Node (Element));
Parent_Node_Kind : constant Node_Kind := Nkind (Parent_Node);
Result_Kind : Internal_Element_Kinds := Not_An_Element;
begin
if Nkind (Node (Element)) = N_Label then
Parent_Node := Next (R_Node (Element));
-- R_Node (Element) definitely is a list member
while not Is_Statement (Parent_Node) loop
Parent_Node := Next (Parent_Node);
end loop;
elsif Nkind (Node (Element)) = N_Identifier
and then
Parent_Node_Kind = N_Loop_Statement
and then
Is_Rewrite_Substitution (Parent_Node)
and then
Nkind (Original_Node (Parent_Node)) = N_Goto_Statement
then
if Is_Empty_List (Sinfo.Statements (Parent_Node)) then
-- Pathological case of
--
-- <<Target>> goto target;
Result_Kind := A_Goto_Statement;
else
Parent_Node := First (Sinfo.Statements (Parent_Node));
end if;
elsif Parent_Node_Kind = N_Exception_Handler then
Parent_Node := R_Node (Element);
Result_Kind := A_Choice_Parameter_Specification;
elsif Nkind (Parent_Node) = N_Generic_Package_Declaration
and then
Nkind (Original_Node (Parent_Node)) = N_Formal_Package_Declaration
and then
R_Node (Element) =
Defining_Identifier (Original_Node (Parent_Node))
then
-- A formal package with a box (but not its expanded spec!)
Result_Kind := A_Formal_Package_Declaration_With_Box;
elsif not Comes_From_Source (Parent_Node)
and then
Nkind (Parent_Node) = N_Object_Declaration
and then
Present (Etype (R_Node (Element)))
and then
Ekind (Etype (R_Node (Element))) in
E_Task_Type .. E_Protected_Type
then
-- The case of a single task/protected definition - the problem here
-- is that Parent field of the argument node points into artificial
-- object declaration, see G214-005
Parent_Node := Etype (R_Node (Element));
if Ekind (Parent_Node) = E_Protected_Type then
Result_Kind := A_Single_Protected_Declaration;
else
Result_Kind := A_Single_Task_Declaration;
end if;
Parent_Node := Parent (Parent_Node);
else
return A_Defining_Expanded_Name_Enclosing (Element);
end if;
return Node_To_Element_New (Node => Parent_Node,
Internal_Kind => Result_Kind,
Starting_Element => Element);
end A_Defining_Identifier_Enclosing;
------------------------------------------
-- A_Defining_Operator_Symbol_Enclosing --
------------------------------------------
function A_Defining_Operator_Symbol_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id := Parent (R_Node (Element));
Parent_Node_Kind : constant Node_Kind := Nkind (Parent_Node);
begin
if Parent_Node_Kind = N_Function_Specification
then -- one more step up required
Parent_Node := Parent (Parent_Node);
end if;
return Node_To_Element_New (Node => Parent_Node,
Starting_Element => Element);
end A_Defining_Operator_Symbol_Enclosing;
--------------------------------
-- A_Discrete_Range_Enclosing --
--------------------------------
function A_Discrete_Range_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id := Parent (R_Node (Element));
Result_Node_Kind : constant Node_Kind := Nkind (Result_Node);
Result_Elem_Kind : Internal_Element_Kinds := Not_An_Element;
begin
if not Comes_From_Source (Result_Node) or else
not Comes_From_Source (Parent (Result_Node))
then
return An_Expression_Enclosing (Element);
end if;
if Nkind (Node (Element)) = N_Component_Clause then
Result_Node := R_Node (Element);
Result_Elem_Kind := A_Component_Clause;
elsif Result_Node_Kind = N_Component_Association then
Result_Elem_Kind := An_Array_Component_Association;
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => Result_Elem_Kind,
Considering_Parent_Count => False);
end A_Discrete_Range_Enclosing;
-----------------------------------
-- A_Discriminant_Part_Enclosing --
-----------------------------------
function A_Discriminant_Part_Enclosing
(Element : Asis.Element)
return Asis.Element
is
begin
return Node_To_Element_New (Node => R_Node (Element),
Starting_Element => Element);
end A_Discriminant_Part_Enclosing;
--------------------------------------------
-- A_Discriminant_Specification_Enclosing --
--------------------------------------------
function A_Discriminant_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element
is
begin
return Node_To_Element_New (
Node => Parent (R_Node (Element)),
Internal_Kind => A_Known_Discriminant_Part,
Starting_Element => Element);
end A_Discriminant_Specification_Enclosing;
----------------------------------------------
-- A_Loop_Parameter_Specification_Enclosing --
----------------------------------------------
function A_Loop_Parameter_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id;
Tmp : Node_Id;
Result : Asis.Element;
begin
Result_Node := Parent (R_Node (Element));
if Nkind (Result_Node) /= N_Quantified_Expression then
-- We have got to N_Ineration_Sceme node only
Result_Node := Parent (Result_Node);
end if;
if Declaration_Kind (Element) in
A_Generalized_Iterator_Specification ..
An_Element_Iterator_Specification
then
-- Here we may have to get to an artificial block statement the
-- needed loop node is rewritten into
Tmp := Parent (Parent (Result_Node));
if Nkind (Tmp) = N_Block_Statement
and then
Is_Rewrite_Substitution (Tmp)
and then
Nkind (Original_Node (Tmp)) = N_Loop_Statement
then
Result_Node := Tmp;
end if;
end if;
Result := Node_To_Element_New (Node => Result_Node,
Starting_Element => Element);
if Int_Kind (Result) = A_Parenthesized_Expression then
-- This is the case when an iteration scheme is used in a
-- conditional or quantified expression. We go in bottom-up
-- direction, so we can have A_Parenthesized_Expression only as the
-- next enclosing Element
Result := An_Expression_Enclosing (Element);
end if;
return Result;
end A_Loop_Parameter_Specification_Enclosing;
--------------------------------
-- A_Null_Component_Enclosing --
--------------------------------
function A_Null_Component_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : constant Node_Id := Node (Element);
Parent_Internal_Kind : Internal_Element_Kinds;
begin
if Nkind (Parent_Node) = N_Record_Definition then
Parent_Internal_Kind := A_Record_Definition;
else
Parent_Internal_Kind := A_Variant;
end if;
return Node_To_Element_New (Node => Parent_Node,
Internal_Kind => Parent_Internal_Kind,
Starting_Element => Element);
end A_Null_Component_Enclosing;
-----------------------------------------
-- A_Parameter_Specification_Enclosing --
-----------------------------------------
function A_Parameter_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id := Parent (R_Node (Element));
Result_Node_Kind : constant Node_Kind := Nkind (Result_Node);
begin
if not (Result_Node_Kind = N_Entry_Declaration or else
Result_Node_Kind = N_Access_Function_Definition or else
Result_Node_Kind = N_Access_Procedure_Definition or else
Result_Node_Kind = N_Accept_Statement)
-- --|A2005 start
or else
(Nkind (Parent (Result_Node)) = N_Identifier
and then
Is_Rewrite_Substitution (Parent (Result_Node))
and then
Nkind (Original_Node (Parent (Result_Node))) = N_Access_Definition)
or else
Nkind (Parent (Result_Node)) = N_Access_Definition
-- --|A2005 end
then
Result_Node := Parent (Result_Node);
-- the first Parent gives N_Function/Procedure_Specification only
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Considering_Parent_Count => False);
end A_Parameter_Specification_Enclosing;
------------------------
-- A_Pragma_Enclosing --
------------------------
function A_Pragma_Enclosing (Element : Asis.Element) return Asis.Element is
Parent_Node : Node_Id := Atree.Parent (R_Node (Element));
Parent_Node_Kind : Node_Kind := Nkind (Parent_Node);
Parent_Internal_Kind : Internal_Element_Kinds;
begin
if Parent_Node_Kind = N_Loop_Statement
and then
Is_Rewrite_Substitution (Parent_Node)
and then
Nkind (Original_Node (Parent_Node)) = N_Goto_Statement
then
-- This is the case when infinite loop implemented as
--
-- <<Target>> ...
-- ...
-- goto Target;
--
-- is rewritten into N_Loop_Statement
Parent_Node := Parent (Parent_Node);
Parent_Node_Kind := Nkind (Parent_Node);
end if;
-- filtering out compilation pragmas and correcting Parent_Node,
-- if necessary
case Parent_Node_Kind is
when N_Handled_Sequence_Of_Statements
| N_Package_Specification
| N_Component_List =>
Parent_Node := Atree.Parent (Parent_Node);
Parent_Node_Kind := Nkind (Parent_Node);
when N_Compilation_Unit =>
return Asis.Nil_Element;
when others =>
null;
end case;
-- special processing for Nodes requiring by-hand Enclosing Element
-- kind determination and returning the result for all other Nodes
case Parent_Node_Kind is
when N_If_Statement =>
if List_Containing (R_Node (Element)) =
Then_Statements (Parent_Node)
then
Parent_Internal_Kind := An_If_Path;
else
Parent_Internal_Kind := An_Else_Path;
end if;
-- ??? List_Containing (Node (Element)) ??
-- ??? or List_Containing (R_Node (Element)) ??
when N_Conditional_Entry_Call
| N_Selective_Accept =>
Parent_Internal_Kind := An_Else_Path;
when N_Record_Definition =>
Parent_Internal_Kind := An_Else_Path;
when others => -- auto determination of the Enclosing Element kind:
return Node_To_Element_New (Node => Parent_Node,
Starting_Element => Element);
end case;
-- returning the Enclosing Element with the by-hand-defined kind:
return Node_To_Element_New (Node => Parent_Node,
Internal_Kind => Parent_Internal_Kind,
Starting_Element => Element);
end A_Pragma_Enclosing;
-------------------------------------------
-- A_Range_Attribute_Reference_Enclosing --
-------------------------------------------
function A_Range_Attribute_Reference_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id := Parent (R_Node (Element));
Tmp : Node_Id := Parent (Result_Node);
begin
if Nkind (Result_Node) = N_Subtype_Indication and then
Nkind (Tmp) = N_Subtype_Declaration and then
not Comes_From_Source (Tmp)
then
-- This N_Subtype_Declaration is from the tree structure created
-- for an artificial subtype declaration, see C208-003
Tmp := Next (Tmp);
Result_Node := Object_Definition (Tmp);
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Considering_Parent_Count => False);
end A_Range_Attribute_Reference_Enclosing;
-----------------------------------
-- A_Record_Definition_Enclosing --
-----------------------------------
function A_Record_Definition_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id;
Parent_Internal_Kind : Internal_Element_Kinds;
begin
if Nkind (Parent (R_Node (Element))) = N_Derived_Type_Definition then
Parent_Node := Parent (R_Node (Element));
Parent_Internal_Kind := A_Derived_Record_Extension_Definition;
else
Parent_Node := Node (Element);
if Tagged_Present (Parent_Node) then
Parent_Internal_Kind := A_Tagged_Record_Type_Definition;
else
Parent_Internal_Kind := A_Record_Type_Definition;
end if;
end if;
return Node_To_Element_New (Node => Parent_Node,
Internal_Kind => Parent_Internal_Kind,
Starting_Element => Element);
end A_Record_Definition_Enclosing;
-----------------------------------------
-- A_Simple_Expression_Range_Enclosing --
----------------------------------------
function A_Simple_Expression_Range_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Enclosing_Node : Node_Id := Node (Element);
Enclosing_Node_Kind : Node_Kind := Nkind (Enclosing_Node);
Context : Node_Id;
Context_Kind : Node_Kind;
Enclosing_Element_Kind : Internal_Element_Kinds;
begin
if Enclosing_Node_Kind = N_Signed_Integer_Type_Definition then
-- back from Integer_Constraint
return Node_To_Element_New
(Starting_Element => Element,
Node => R_Node (Element),
Internal_Kind => A_Signed_Integer_Type_Definition,
Considering_Parent_Count => False);
else -- one step up
Enclosing_Node := Parent (R_Node (Element));
Enclosing_Node_Kind := Nkind (Enclosing_Node);
-- possible values of corresponding kinds of
-- Enclosing_Node_Kind: Enclosing Element:
--
-- N_Floating_Point_Definition A_Floating_Point_Definition (*)
-- N_Ordinary_Fixed_Point_Definition An_Ordinary_Fixed_Point_Definition (*)
-- N_Decimal_Fixed_Point_Definition A_Decimal_Fixed_Point_Definition (*)
--
-- A_Constraint
-- N_Digits_Constraint A_Digits_Constraint (*)
-- N_Delta_Constraint A_Delta_Constraint (*)
--
--
-- A_Subtype_Indication
-- N_Subtype_Indication A_Discrete_Subtype_Indication
-- (_As_Subtype_Definition)
-- A_Subtype_Indication
--
-- A_Discrete_Range
-- N_Subtype_Indication A_Discrete_Subtype_Indication
--
--
--
-- N_In An_In_Range_Membership_Test (*)
-- N_Not_In A_Not_In_Range_Membership_Test (*)
--
-- (*) means that the Enclosing Element can be obtained by Node_To_Elemen
-- constructor with auto determination of the Element kind
if Enclosing_Node_Kind /= N_Subtype_Indication then
return Node_To_Element_New
(Starting_Element => Element,
Node => Enclosing_Node,
Considering_Parent_Count => False);
else
-- A_Discrete_Subtype_Indication or
-- A_Discrete_Subtype_Indication_As_Subtype_Definition
-- or A_Subtype_Indication?
-- First, we have to skip implicit subtype created for
-- constraint directly included in object declaration,
-- if any
Skip_Implicit_Subtype (Enclosing_Node);
Context := Parent (Enclosing_Node);
Context_Kind := Nkind (Context);
if Context_Kind = N_Subtype_Indication then
-- it's impossible to make a decision on the base
-- of this node, we shall go one more step up
Context := Parent (Context);
Context_Kind := Nkind (Context);
end if;
if Context_Kind = N_Subtype_Declaration or else
((Context_Kind = N_Constrained_Array_Definition or else
Context_Kind = N_Unconstrained_Array_Definition)
and then
Enclosing_Node = Sinfo.Component_Definition (Context))
or else
-- is it enough or should we add:
-- and then Enclosing_Node = Subtype_Indication (Context)?
Context_Kind = N_Derived_Type_Definition or else
Context_Kind = N_Access_To_Object_Definition
then
Enclosing_Element_Kind := A_Subtype_Indication;
elsif Context_Kind = N_Constrained_Array_Definition or else
Context_Kind = N_Entry_Declaration or else
Context_Kind = N_Entry_Index_Specification or else
Context_Kind = N_Loop_Parameter_Specification
then
Enclosing_Element_Kind :=
A_Discrete_Subtype_Indication_As_Subtype_Definition;
elsif Context_Kind = N_Component_Declaration or else
Context_Kind = N_Object_Declaration or else
Context_Kind = N_Component_Definition
then
Enclosing_Element_Kind := A_Subtype_Indication;
else
Enclosing_Element_Kind :=
A_Discrete_Subtype_Indication;
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Enclosing_Node,
Internal_Kind => Enclosing_Element_Kind,
Considering_Parent_Count => False);
end if;
end if;
end A_Simple_Expression_Range_Enclosing;
---------------------------
-- A_Statement_Enclosing --
---------------------------
function A_Statement_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id := Parent (R_Node (Element));
Parent_Node_Kind : Node_Kind := Nkind (Parent_Node);
Parent_Internal_Kind : Internal_Element_Kinds;
begin
if Parent_Node_Kind = N_Loop_Statement
and then
Is_Rewrite_Substitution (Parent_Node)
and then
Nkind (Original_Node (Parent_Node)) = N_Goto_Statement
then
-- This is the case when infinite loop implemented as
--
-- <<Target>> ...
-- ...
-- goto Target;
--
-- is rewritten into N_Loop_Statement
Parent_Node := Parent (Parent_Node);
Parent_Node_Kind := Nkind (Parent_Node);
end if;
if Parent_Node_Kind = N_If_Statement then
if List_Containing (R_Node (Element)) =
Then_Statements (Parent_Node)
then
Parent_Internal_Kind := An_If_Path;
else
Parent_Internal_Kind := An_Else_Path;
end if;
-- ??? List_Containing (Node (Element)) ??
-- ?? or List_Containing (R_Node (Element)) ??
elsif Parent_Node_Kind = N_Conditional_Entry_Call or else
Parent_Node_Kind = N_Selective_Accept
then
Parent_Internal_Kind := An_Else_Path;
else
if Parent_Node_Kind = N_Handled_Sequence_Of_Statements then
-- to go to N_Block_Statement, N_Accept_Statement,
-- N_Subprogram_Body, N_Package_Body, N_Task_Body or
-- N_Entry_Body node
Parent_Node := Parent (Parent_Node);
end if;
return Node_To_Element_New (Node => Parent_Node,
Starting_Element => Element);
end if;
return Node_To_Element_New (Node => Parent_Node,
Internal_Kind => Parent_Internal_Kind,
Starting_Element => Element);
end A_Statement_Enclosing;
------------------------------------
-- A_Subtype_Indication_Enclosing --
------------------------------------
function A_Subtype_Indication_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id := Parent (R_Node (Element));
Result_Node : Node_Id := R_Node (Element);
Parent_Node_Kind : constant Node_Kind := Nkind (Parent_Node);
Result_Kind : Internal_Element_Kinds;
begin
if Parent_Node_Kind = N_Component_Definition then
Parent_Node := Parent (Parent_Node);
-- This skips the normalized component declarations back!
Parent_Node := Sinfo.Component_Definition (Parent_Node);
end if;
if Parent_Node_Kind = N_Allocator and then
Nkind (Parent (Parent_Node)) = N_Component_Association and then
not Comes_From_Source (Parent (Parent_Node))
then
return An_Expression_Enclosing (Element);
end if;
if Parent_Node_Kind = N_Unconstrained_Array_Definition or else
Parent_Node_Kind = N_Constrained_Array_Definition or else
Parent_Node_Kind = N_Component_Declaration
then
Result_Kind := A_Component_Definition;
elsif Parent_Node_Kind = N_Private_Extension_Declaration then
Result_Kind := A_Private_Extension_Definition;
Result_Node := Parent_Node;
else
return Node_To_Element_New
(Starting_Element => Element,
Node => Parent_Node,
Considering_Parent_Count => False);
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => Result_Kind,
Considering_Parent_Count => False);
end A_Subtype_Indication_Enclosing;
-------------------------------------------------
-- A_Terminate_Alternative_Statement_Enclosing --
-------------------------------------------------
function A_Terminate_Alternative_Statement_Enclosing
(Element : Asis.Element)
return Asis.Element
is
begin
return Node_To_Element_New (Node => R_Node (Element),
Starting_Element => Element);
end A_Terminate_Alternative_Statement_Enclosing;
------------------------------
-- A_Variant_Part_Enclosing --
------------------------------
function A_Variant_Part_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : constant Node_Id := Parent (Parent (R_Node (Element)));
Result_Kind : Internal_Element_Kinds;
begin
if Nkind (Result_Node) = N_Record_Definition then
Result_Kind := A_Record_Definition;
else
Result_Kind := A_Variant;
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => Result_Kind,
Considering_Parent_Count => False);
end A_Variant_Part_Enclosing;
------------------------------
-- An_Association_Enclosing --
------------------------------
function An_Association_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result : Asis.Element;
begin
if Normalization_Case (Element) = Is_Not_Normalized then
Result := An_Expression_Enclosing (Element);
else
Result := Node_To_Element_New
(Node => R_Node (Element),
Starting_Element => Element);
Set_From_Implicit (Result, False);
end if;
return Result;
end An_Association_Enclosing;
----------------------------------------------
-- An_Attribute_Definition_Clause_Enclosing --
----------------------------------------------
function An_Attribute_Definition_Clause_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id := Parent (R_Node (Element));
Result_Node_Kind : Node_Kind := Nkind (Result_Node);
Result_Kind : Internal_Element_Kinds := Not_An_Element;
begin
if Result_Node_Kind = N_Component_List or else
Result_Node_Kind = N_Package_Specification
then
Result_Node := Parent (Result_Node);
Result_Node_Kind := Nkind (Result_Node);
end if;
if Result_Node_Kind = N_Record_Definition then
Result_Kind := A_Record_Definition;
elsif Result_Node_Kind = N_Variant then
Result_Kind := A_Variant;
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => Result_Kind,
Considering_Parent_Count => False);
end An_Attribute_Definition_Clause_Enclosing;
----------------------------
-- An_Else_Path_Enclosing --
----------------------------
function An_Else_Path_Enclosing
(Element : Asis.Element)
return Asis.Element
is
begin
return Node_To_Element_New (Node => R_Node (Element),
Starting_Element => Element);
end An_Else_Path_Enclosing;
----------------------------------------------------
-- An_Enumeration_Literal_Specification_Enclosing --
----------------------------------------------------
function An_Enumeration_Literal_Specification_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id;
Start_Elem : Asis.Element := Element;
begin
if Special_Case (Element) = Stand_Char_Literal then
Result_Node := R_Node (Element);
Set_Character_Code (Start_Elem, 0);
Set_Special_Case (Start_Elem, Explicit_From_Standard);
else
Result_Node := Parent (R_Node (Element));
end if;
return Node_To_Element_New
(Starting_Element => Start_Elem,
Node => Result_Node,
Internal_Kind => An_Enumeration_Type_Definition);
end An_Enumeration_Literal_Specification_Enclosing;
----------------------------------------------
-- An_Enumeration_Type_Definition_Enclosing --
----------------------------------------------
function An_Enumeration_Type_Definition_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Result_Node : Node_Id;
begin
if Special_Case (Element) = Stand_Char_Literal then
Result_Node := R_Node (Element);
if Nkind (Result_Node) = N_Defining_Identifier then
-- we are in the definition of Standard.Boolean:
Result_Node := Parent (Etype (Result_Node));
end if;
else
Result_Node := Parent (R_Node (Element));
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => An_Ordinary_Type_Declaration);
end An_Enumeration_Type_Definition_Enclosing;
------------------------------------
-- An_Exception_Handler_Enclosing --
------------------------------------
function An_Exception_Handler_Enclosing
(Element : Asis.Element)
return Asis.Element
is
begin
return Node_To_Element_New
(Node => Parent (Parent (R_Node (Element))),
Starting_Element => Element);
end An_Exception_Handler_Enclosing;
-----------------------------
-- An_Expression_Enclosing --
-----------------------------
function An_Expression_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Start_Elem : Asis.Element := Element;
Rough_Result_Node : Node_Id;
Res_Entity : Entity_Id;
Rough_Result_Element : Asis.Element;
Rough_Res_Spec_Case : Special_Cases;
Result_Element : Asis.Element;
begin
Rough_Result_Node := Get_Rough_Enclosing_Node (Element);
if not (Sloc (Node (Start_Elem)) <= Standard_Location or else
Special_Case (Start_Elem) = Configuration_File_Pragma)
then
Set_Special_Case (Start_Elem, Not_A_Special_Case);
end if;
Rough_Result_Element := Node_To_Element_New
(Node => Rough_Result_Node,
Starting_Element => Start_Elem);
if Is_Top_Of_Expanded_Generic (Rough_Result_Node)
and then
Is_From_Instance (Element)
and then
(Nkind (Original_Node (Rough_Result_Node)) /=
N_Formal_Package_Declaration
or else
Instantiation_Depth (Sloc (R_Node (Element))) >
Instantiation_Depth (Sloc (Rough_Result_Node)))
then
-- ??? The content of this if statement is just a slightly edited
-- ??? fragment of Enclosing_For_Explicit_Instance_Component
if Nkind (Rough_Result_Node) = N_Package_Declaration or else
Nkind (Rough_Result_Node) = N_Package_Body
then
Rough_Res_Spec_Case := Expanded_Package_Instantiation;
-- and here we have to correct the result:
Set_Node (Rough_Result_Element, R_Node (Rough_Result_Element));
if Nkind (Rough_Result_Node) = N_Package_Declaration then
Set_Int_Kind (Rough_Result_Element, A_Package_Declaration);
else
Set_Int_Kind (Rough_Result_Element, A_Package_Body_Declaration);
end if;
else
Rough_Res_Spec_Case := Expanded_Subprogram_Instantiation;
end if;
Set_Special_Case (Rough_Result_Element, Rough_Res_Spec_Case);
end if;
if Special_Case (Element) = Is_From_Gen_Association
and then
Is_Top_Of_Expanded_Generic (Node (Rough_Result_Element))
and then
Instantiation_Depth (Sloc (Node (Rough_Result_Element))) =
Instantiation_Depth (Sloc (Node (Element)))
then
Rough_Result_Element := Enclosing_Element (Rough_Result_Element);
end if;
if Nkind (Rough_Result_Node) = N_Subprogram_Declaration
and then
not Comes_From_Source (Rough_Result_Node)
then
Res_Entity := Defining_Unit_Name (Specification (Rough_Result_Node));
if (Ekind (Res_Entity) = E_Function
and then not Comes_From_Source (Res_Entity)
and then Chars (Res_Entity) = Snames.Name_Op_Ne)
and then Present (Corresponding_Equality (Res_Entity))
then
Set_Special_Case
(Rough_Result_Element, Is_From_Imp_Neq_Declaration);
end if;
end if;
Result_Element := Get_Enclosing
(Approximation => Rough_Result_Element,
Element => Element);
return Result_Element;
end An_Expression_Enclosing;
--------------------------------
-- An_Others_Choice_Enclosing --
--------------------------------
function An_Others_Choice_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : constant Node_Id := Parent (Parent (R_Node (Element)));
Result_Node : Node_Id := Parent (R_Node (Element));
Result_Kind : Internal_Element_Kinds := Not_An_Element;
begin
if Nkind (Result_Node) = N_Component_Association then
-- we have to find out, is it record or array component
-- association. Parent_Node points to the enclosing aggregate
if No (Etype (Parent_Node)) or else
Is_Array_Type (Etype (Parent_Node))
then
-- the first condition in 'or else' is true for multi-dimensional
-- array aggregates
Result_Kind := An_Array_Component_Association;
else
Result_Kind := A_Record_Component_Association;
end if;
elsif Nkind (Result_Node) = N_Package_Declaration
and then
Nkind (Original_Node (Result_Node)) = N_Formal_Package_Declaration
then
Result_Node :=
Last_Non_Pragma
(Generic_Associations (Original_Node (Result_Node)));
Result_Kind := A_Generic_Association;
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Internal_Kind => Result_Kind,
Considering_Parent_Count => False);
end An_Others_Choice_Enclosing;
----------------------------------------------------
-- Not_Implemented_Enclosing_Element_Construction --
----------------------------------------------------
function Not_Implemented_Enclosing_Element_Construction
(Element : Asis.Element) return Asis.Element is
begin
Not_Implemented_Yet (Diagnosis =>
"Enclosing Element retrieval for the explicit Element "
& "of the " & Internal_Element_Kinds'Image
(Int_Kind (Element)) & " kind "
& "has not been implemented yet");
return Asis.Nil_Element; -- to make the code syntactically correct;
end Not_Implemented_Enclosing_Element_Construction;
----------------------------
-- Possible_C_U_Enclosing --
----------------------------
function Possible_C_U_Enclosing
(Element : Asis.Element)
return Asis.Element
is
Parent_Node : Node_Id := Parent (R_Node (Element));
Parent_Node_Kind : constant Node_Kind := Nkind (Parent_Node);
begin
if Parent_Node_Kind = N_Compilation_Unit or else
Parent_Node_Kind = N_Subunit
then
return Asis.Nil_Element;
elsif Parent_Node_Kind = N_Package_Specification then
Parent_Node := Parent (Parent_Node);
elsif Parent_Node_Kind = N_Protected_Definition then
Parent_Node := Parent (Parent_Node);
Parent_Node := Protected_Definition (Original_Node (Parent_Node));
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Parent_Node);
end Possible_C_U_Enclosing;
-----------------------------------------------------------------
-- Section 6 - bodies for the routines defined in the package --
-- spec and local subprograms --
-----------------------------------------------------------------
---------------------------------
-- Corresponding_Instantiation --
---------------------------------
function Corresponding_Instantiation
(Element : Asis.Element)
return Asis.Element
is
Argument_Node : Node_Id := R_Node (Element);
Argument_Kind : constant Internal_Element_Kinds := Int_Kind (Element);
Result_Node : Node_Id := Argument_Node;
Result_Kind : Internal_Element_Kinds;
Result_Unit : constant Asis.Compilation_Unit := Encl_Unit (Element);
begin
if Argument_Kind = A_Package_Declaration or else
Argument_Kind = A_Package_Body_Declaration
then
-- A formal package with box needs a special processing - it is
-- based on the same node as the argument
if Nkind (Original_Node (Argument_Node)) =
N_Formal_Package_Declaration
and then
Box_Present (Original_Node (Argument_Node))
then
Result_Kind := A_Formal_Package_Declaration_With_Box;
else
Argument_Node := Parent (Argument_Node);
if Nkind (Argument_Node) in N_Generic_Declaration and then
Is_List_Member (Result_Node) and then
List_Containing (Result_Node) =
Generic_Formal_Declarations (Argument_Node)
then
Result_Kind := A_Formal_Package_Declaration;
else
Result_Kind := A_Package_Instantiation;
end if;
end if;
else
if Argument_Kind = A_Procedure_Declaration or else
Argument_Kind = A_Procedure_Body_Declaration
then
Result_Kind := A_Procedure_Instantiation;
else
Result_Kind := A_Function_Instantiation;
end if;
-- we have to go the N_Package_Decalaration node of an
-- artificial package created by the compiler for a subprogram
-- instantiation - two steps up the tree are needed:
Result_Node := Parent (Result_Node);
if Argument_Kind = A_Procedure_Declaration or else
Argument_Kind = A_Function_Declaration
then
Result_Node := Parent (Result_Node);
end if;
end if;
if Nkind (Parent (Result_Node)) = N_Compilation_Unit then
-- For library-level subprogram instantiations we may have a
-- problem in the tree created for the instantiation itself.
if Nkind (Result_Node) = N_Package_Declaration and then
not Is_Rewrite_Substitution (Result_Node)
then
Result_Node := Parent (Corresponding_Body (Result_Node));
if Nkind (Result_Node) = N_Defining_Program_Unit_Name then
Result_Node := Parent (Result_Node);
end if;
end if;
elsif Nkind (Original_Node (Result_Node)) /=
N_Formal_Package_Declaration
then
-- "local" instantiation, therefore - one or two steps down the
-- declaration list to get in the instantiation node, a formal
-- package with a box is an exception:
Result_Node := Next_Non_Pragma (Result_Node);
if Nkind (Result_Node) = N_Package_Body then
-- This is an expanded generic body
Result_Node := Next_Non_Pragma (Result_Node);
end if;
end if;
if Is_Rewrite_Substitution (Result_Node) and then
Is_Rewrite_Substitution (Original_Node (Result_Node))
then
Result_Node := Original_Node (Result_Node);
end if;
return Node_To_Element_New
(Node => Result_Node,
Internal_Kind => Result_Kind,
In_Unit => Result_Unit);
end Corresponding_Instantiation;
------------------------------------
-- Enclosing_Element_For_Explicit --
------------------------------------
function Enclosing_Element_For_Explicit
(Element : Asis.Element)
return Asis.Element
is
Enclosing_Construction_Case : Internal_Element_Kinds;
Element_Internal_Kind : Internal_Element_Kinds;
Result_Element : Asis.Element;
Res_Node : constant Node_Id := Standard_Package_Node;
Res_Kind : Internal_Element_Kinds := Not_An_Element;
Res_Spec_Case : Special_Cases;
begin
Element_Internal_Kind := Int_Kind (Element);
-- A special case of fake Numeric_Error renaming is handled
-- separately (see B712-0050)
if Special_Case (Element) = Numeric_Error_Renaming then
case Element_Internal_Kind is
when An_Exception_Renaming_Declaration =>
Res_Kind := A_Package_Declaration;
Res_Spec_Case := Explicit_From_Standard;
when A_Defining_Identifier |
An_Identifier =>
Res_Kind := An_Exception_Renaming_Declaration;
Res_Spec_Case := Numeric_Error_Renaming;
when others =>
null;
end case;
Result_Element := Node_To_Element_New
(Starting_Element => Element,
Node => Res_Node,
Internal_Kind => Res_Kind,
Spec_Case => Res_Spec_Case);
return Result_Element;
end if;
-- A special case of a configuration pragma is handled separately
-- (BA07-013)
if Element_Internal_Kind in Internal_Pragma_Kinds and then
Special_Case (Element) = Configuration_File_Pragma
then
return Asis.Nil_Element;
end if;
Enclosing_Construction_Case :=
Enclosing_Element_For_Explicits_First_Switch (Element_Internal_Kind);
case Enclosing_Construction_Case is
when Not_An_Element =>
return Asis.Nil_Element;
when Trivial_Mapping =>
Result_Element := General_Encl_Elem (Element);
when Non_Trivial_Mapping =>
Result_Element :=
Enclosing_Element_For_Explicits_Second_Switch
(Element_Internal_Kind) (Element);
when No_Mapping =>
No_Enclosing_Element (Element_Kind => Element_Internal_Kind);
return Asis.Nil_Element; -- to avoid GNAT warning
when Not_Implemented_Mapping =>
Not_Implemented_Enclosing_Element_Construction
(Element => Element);
when others =>
-- others means here that the Enclosing Element should
-- based on the same node.
Result_Element := Node_To_Element_New
(Starting_Element => Element,
Node => R_Node (Element),
Internal_Kind => Enclosing_Construction_Case,
Considering_Parent_Count => False);
if Element_Internal_Kind = A_Defining_Character_Literal then
Set_Character_Code (Result_Element, Character_Code (Element));
end if;
end case;
if Is_From_Implicit (Element)
and then
Statement_Kind (Element) = A_Null_Statement
then
-- Case of an implicit NULL statement needed for 'floating' labels,
-- Ada 2012
Set_From_Implicit (Result_Element, False);
end if;
return Result_Element;
end Enclosing_Element_For_Explicit;
-----------------------------------------------
-- Enclosing_For_Explicit_Instance_Component --
-----------------------------------------------
function Enclosing_For_Explicit_Instance_Component
(Element : Asis.Element)
return Asis.Element
is
Result_Element : Asis.Element;
Result_Node : Node_Id;
Tmp_Node : Node_Id;
Res_Spec_Case : Special_Cases;
function Is_Top_Exp_Form_Pack_With_Box
(Potential_Enclosing_Element : Asis.Element;
Arg_Element : Asis.Element)
return Boolean;
-- Checks if Potential_Enclosing_Element is the top expanded spec
-- (??? what about body???) for a formal package declaration with box.
-- The problem here is that when going up the tree, we can get into this
-- argument both from components of the formal package declaration with
-- box and from the corresponding expanded spec. So we have to check
-- if Potential_Enclosing_Element and Arg_Element are the same level
-- of instantiating (nested instances may be a pain! The function needs
-- more testing ???)
-- See the discussion in E425-007
function Is_Top_Exp_Form_Pack_With_Box
(Potential_Enclosing_Element : Asis.Element;
Arg_Element : Asis.Element)
return Boolean
is
EE_Inst_Level : Natural := 0;
Arg_Inst_Level : Natural := 0;
Src : Source_Ptr :=
Instantiation
(Get_Source_File_Index
(Sloc (R_Node (Potential_Enclosing_Element))));
function May_Be_Exp_Pack_Def_Name
(N_Pack : Node_Id;
N_Name : Node_Id)
return Boolean;
-- In case of the defining name of an expanded package created for a
-- formal package with the box, we have the instantiation chain one
-- link shorter then the rest of the expanded package, so we have
-- to detect this situation.
function May_Be_Nested_FP_Instantiation
(N_Pack : Node_Id;
N_Name : Node_Id)
return Boolean;
-- See E430-A01. We try to detect the situation when we go out of
-- a chain of nested instantiations created by formal packages with
-- the box
function May_Be_Exp_Pack_Def_Name
(N_Pack : Node_Id;
N_Name : Node_Id)
return Boolean
is
Result : Boolean := False;
begin
if Nkind (N_Name) = N_Defining_Identifier
and then
Nkind (Original_Node (N_Pack)) = N_Formal_Package_Declaration
and then
Box_Present (Original_Node (N_Pack))
then
Result := N_Name = Defining_Unit_Name (Specification (N_Pack));
end if;
return Result;
end May_Be_Exp_Pack_Def_Name;
function May_Be_Nested_FP_Instantiation
(N_Pack : Node_Id;
N_Name : Node_Id)
return Boolean
is
Result : Boolean := False;
begin
if Nkind (N_Pack) = N_Generic_Package_Declaration
and then
Nkind (Original_Node (N_Pack)) = N_Formal_Package_Declaration
and then
Box_Present (Original_Node (N_Pack))
and then
Nkind (N_Name) = N_Generic_Package_Declaration
and then
Nkind (Original_Node (N_Name)) = N_Formal_Package_Declaration
and then
Box_Present (Original_Node (N_Name))
then
Result := True;
end if;
return Result;
end May_Be_Nested_FP_Instantiation;
begin
if not (Nkind (Node (Potential_Enclosing_Element)) =
N_Formal_Package_Declaration
and then
Nkind (R_Node (Potential_Enclosing_Element)) =
N_Generic_Package_Declaration)
or else
(Int_Kind (Potential_Enclosing_Element) =
A_Formal_Package_Declaration_With_Box
and then
Node (Arg_Element) =
Defining_Identifier (Node (Potential_Enclosing_Element)))
then
return False;
end if;
while Src /= No_Location loop
EE_Inst_Level := EE_Inst_Level + 1;
Src := Instantiation (Get_Source_File_Index (Src));
end loop;
Src :=
Instantiation (Get_Source_File_Index (Sloc (R_Node (Arg_Element))));
while Src /= No_Location loop
Arg_Inst_Level := Arg_Inst_Level + 1;
Src := Instantiation (Get_Source_File_Index (Src));
end loop;
return (May_Be_Exp_Pack_Def_Name
(R_Node (Potential_Enclosing_Element),
R_Node (Arg_Element))
and then
EE_Inst_Level = Arg_Inst_Level + 1)
or else
(May_Be_Nested_FP_Instantiation
(R_Node (Potential_Enclosing_Element),
R_Node (Arg_Element))
and then
EE_Inst_Level + 1 = Arg_Inst_Level)
or else
EE_Inst_Level = Arg_Inst_Level;
end Is_Top_Exp_Form_Pack_With_Box;
begin
Result_Element := Enclosing_Element_For_Explicit (Element);
if Is_Nil (Result_Element) then
-- There is a special case corresponding to the defining name in an
-- artificial subtype declaration that is a means to pass an actual
-- type in the expanded instantiation (see K811-006). Under some
-- conditions the corresponding node in the tree is an Itype node,
-- and it does not have a Parent reference set.
Tmp_Node := Node (Element);
if Nkind (Tmp_Node) = N_Defining_Identifier and then
Is_Itype (Tmp_Node)
then
Tmp_Node := Associated_Node_For_Itype (Tmp_Node);
Result_Element :=
Node_To_Element_New
(Node => Tmp_Node,
Starting_Element => Element,
Internal_Kind => A_Subtype_Declaration);
end if;
end if;
-- In case if the result argument is an artificial declaration
-- used to pass an actual into expanded subprogram, we are
-- in the spec of the artificial wrapper package. So we have to get
-- to the expanded subprogram declaration (see G416-009)
if Is_Top_Of_Expanded_Generic (R_Node (Result_Element)) then
Tmp_Node := (R_Node (Result_Element));
if Nkind (Tmp_Node) = N_Package_Declaration
and then
No (Generic_Parent (Specification (Tmp_Node))) then
-- This IF statement prevents us from doing this special
-- processing for expanded package declarations, we have to do
-- it only for wrapper packages created for subprogram
-- instantiation
Tmp_Node :=
Last (Visible_Declarations (Specification (Tmp_Node)));
Result_Element :=
Node_To_Element_New
(Node => Tmp_Node,
Spec_Case => Expanded_Subprogram_Instantiation,
Starting_Element => Element);
end if;
end if;
-- and now we have to check if we are in the whole expanded
-- declaration
Result_Node := R_Node (Result_Element);
if not (Is_Rewrite_Substitution (Result_Node)
and then
Nkind (Original_Node (Result_Node)) =
N_Formal_Package_Declaration
and then
(Node (Element) =
Defining_Identifier (Original_Node (Result_Node))
or else
(Node (Element) /=
Defining_Unit_Name (Specification (Result_Node))
and then
Instantiation_Depth (Sloc (R_Node (Element))) =
Instantiation_Depth (Sloc (Result_Node)))))
and then
Is_Top_Of_Expanded_Generic (Result_Node)
then
-- this is an artificial package or subprogram declaration
-- created by the compiler as an expanded generic declaration
if Nkind (Result_Node) = N_Package_Declaration or else
Nkind (Result_Node) = N_Package_Body
then
Res_Spec_Case := Expanded_Package_Instantiation;
-- and here we have to correct the result:
Set_Node (Result_Element, R_Node (Result_Element));
if Nkind (Result_Node) = N_Package_Declaration then
Set_Int_Kind (Result_Element, A_Package_Declaration);
else
Set_Int_Kind (Result_Element, A_Package_Body_Declaration);
end if;
else
Res_Spec_Case := Expanded_Subprogram_Instantiation;
end if;
Set_Special_Case (Result_Element, Res_Spec_Case);
elsif Is_Top_Exp_Form_Pack_With_Box (Result_Element, Element) then
-- This case is somewhat special - we have not a package, but a
-- generic package declaration as expanded code here
Set_Int_Kind (Result_Element, A_Package_Declaration);
Set_Special_Case (Result_Element, Expanded_Package_Instantiation);
-- ??? What about expanded bodies for formal packages with a box?
end if;
-- and we have to correct Is_Part_Of_Instance field of the result -
-- just in case. May be, it will not be necessary, if (and when)
-- Enclosing_Element_For_Explicit takes the corresponding fields
-- from its argument
if not Is_Nil (Result_Element) then
Set_From_Instance (Result_Element, True);
end if;
return Result_Element;
end Enclosing_For_Explicit_Instance_Component;
------------------------------------
-- Enclosing_Element_For_Implicit --
------------------------------------
function Enclosing_Element_For_Implicit
(Element : Asis.Element)
return Asis.Element
is
Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Element);
Result_Node : Node_Id := Empty;
Result_Element : Asis.Element;
Result_Kind : Internal_Element_Kinds := Not_An_Element;
Res_Spec_Case : Special_Cases := Not_A_Special_Case;
begin
-- Special treatment for the declaration of implicit "/=", see F903-002:
if Asis.Extensions.Is_Implicit_Neq_Declaration (Element) then
Result_Element :=
Enclosing_Element
(Asis.Declarations.Corresponding_Equality_Operator (Element));
else
case Arg_Kind is
when A_Procedure_Declaration |
A_Function_Declaration |
A_Procedure_Body_Declaration |
A_Function_Body_Declaration |
A_Procedure_Renaming_Declaration |
A_Function_Renaming_Declaration |
A_Discriminant_Specification |
A_Component_Declaration =>
Result_Node := Original_Node (Node_Field_1 (Element));
if Nkind (Result_Node) in N_Entity
and then
(Arg_Kind in A_Procedure_Declaration ..
A_Function_Declaration
or else
Arg_Kind in A_Procedure_Body_Declaration ..
A_Function_Body_Declaration
or else
Arg_Kind in A_Procedure_Renaming_Declaration ..
A_Function_Renaming_Declaration)
then
Result_Node :=
Original_Node (Parent (Node_Field_1 (Element)));
end if;
case Nkind (Result_Node) is
when N_Private_Extension_Declaration =>
Result_Kind := A_Private_Extension_Definition;
when N_Formal_Type_Declaration =>
Result_Node := Sinfo.Formal_Type_Definition (Result_Node);
when others =>
Result_Node := Sinfo.Type_Definition (Result_Node);
end case;
Result_Element := Node_To_Element_New (
Node => Result_Node,
Starting_Element => Element,
Internal_Kind => Result_Kind);
Set_From_Implicit (Result_Element, False);
Set_From_Inherited (Result_Element, False);
Set_Node_Field_1 (Result_Element, Empty);
when Internal_Root_Type_Kinds =>
Result_Element := Element;
Set_Int_Kind (Result_Element, An_Ordinary_Type_Declaration);
when An_Ordinary_Type_Declaration =>
-- The only possible case is the declaration of a root or
-- universal numeric type
Result_Node := Standard_Package_Node;
Res_Spec_Case := Explicit_From_Standard;
Result_Kind := A_Package_Declaration;
Result_Element :=
Node_To_Element_New (Node => Result_Node,
Spec_Case => Res_Spec_Case,
In_Unit => Encl_Unit (Element));
when An_Enumeration_Literal_Specification |
An_Entry_Declaration =>
Result_Node :=
Sinfo.Type_Definition
(Original_Node (Node_Field_1 (Element)));
Result_Kind := A_Derived_Type_Definition;
Result_Element := Node_To_Element_New (
Node => Result_Node,
Starting_Element => Element,
Internal_Kind => Result_Kind);
Set_From_Implicit (Result_Element, False);
Set_From_Inherited (Result_Element, False);
Set_Node_Field_1 (Result_Element, Empty);
when A_Generic_Association =>
Result_Element :=
Node_To_Element_New (Node => R_Node (Element),
In_Unit => Encl_Unit (Element));
when others =>
if Normalization_Case (Element) =
Is_Normalized_Defaulted_For_Box
then
Result_Node := Parent (Parent (Parent (Node (Element))));
while not (Nkind (Result_Node) in N_Generic_Instantiation
or else
Nkind (Original_Node (Result_Node)) =
N_Formal_Package_Declaration)
loop
if Nkind (Parent (Result_Node)) = N_Compilation_Unit then
-- Library level instantiation
if Is_Rewrite_Substitution (Result_Node) then
-- Package instantiation, the package does not have
-- a body
exit;
else
Result_Node := Corresponding_Body (Result_Node);
while Nkind (Result_Node) /= N_Package_Body loop
Result_Node := Parent (Result_Node);
end loop;
end if;
exit;
else
Result_Node := Next (Result_Node);
end if;
end loop;
Result_Element := Node_To_Element_New
(Node => Result_Node,
In_Unit => Encl_Unit (Element));
else
Result_Element := Enclosing_Element_For_Explicit (Element);
end if;
end case;
end if;
if Int_Kind (Result_Element) = A_Function_Renaming_Declaration then
-- See C125-002
Set_Int_Kind (Result_Element, A_Function_Declaration);
elsif Int_Kind (Result_Element) = A_Procedure_Renaming_Declaration then
Set_Int_Kind (Result_Element, A_Procedure_Declaration);
end if;
return Result_Element;
end Enclosing_Element_For_Implicit;
----------------------------------------
-- Enclosing_Element_For_Limited_View --
----------------------------------------
function Enclosing_Element_For_Limited_View
(Element : Asis.Element)
return Asis.Element
is
Result : Asis.Element := Enclosing_Element_For_Explicit (Element);
begin
if not Is_Nil (Result) then
Set_Special_Case (Result, From_Limited_View);
Set_From_Implicit (Result, True);
Set_Int_Kind (Result, Limited_View_Kind (Result));
end if;
return Result;
end Enclosing_Element_For_Limited_View;
-----------------------
-- General_Encl_Elem --
-----------------------
function General_Encl_Elem (Element : Asis.Element) return Asis.Element is
Result_Node : Node_Id;
Result_Nkind : Node_Kind;
begin
Result_Node := Parent (R_Node (Element));
Result_Nkind := Nkind (Result_Node);
-- and now - special processing for some node kinds to skip nodes which
-- are of no use in ASIS
if Result_Nkind = N_Package_Specification or else
Result_Nkind = N_Function_Specification or else
Result_Nkind = N_Procedure_Specification or else
Result_Nkind = N_Entry_Body_Formal_Part
then
Result_Node := Parent (Result_Node);
end if;
return Node_To_Element_New
(Starting_Element => Element,
Node => Result_Node,
Considering_Parent_Count => False);
end General_Encl_Elem;
-------------------
-- Get_Enclosing --
-------------------
function Get_Enclosing
(Approximation : Asis.Element;
Element : Asis.Element)
return Asis.Element
is
-- we need two-level traversing for searching for Enclosing Element:
-- first, we go through the direct children of an approximate
-- result, and none of them Is_Identical to Element, we repeat
-- the search process for each direct child. We may implement
-- this on top of Traverse_Element, but we prefer to code
-- it manually on top of A4G.Queries
Result_Element : Asis.Element;
Result_Found : Boolean := False;
-- needed to simulate the effect of Terminate_Immediatelly
procedure Check_Possible_Enclosing (Appr_Enclosing : Asis.Element);
-- implements the first level of the search. Appr_Enclosing is
-- the "approximate" Enclosing Element, and this procedure
-- checks if some of its components Is_Identical to Element
-- (Element here is the parameter of Get_Enclosing function,
-- as a global constant value inside Get_Enclosing, it is the
-- same for all the (recursive) calls of Check_Possible_Enclosing
------------------------------
-- Check_Possible_Enclosing --
-------------------------------
procedure Check_Possible_Enclosing (Appr_Enclosing : Asis.Element) is
Child_Access : constant Query_Array :=
Appropriate_Queries (Appr_Enclosing);
-- this is the way to traverse the direct children
Next_Child : Asis.Element;
procedure Check_List (L : Asis.Element_List);
-- checks if L contains a component which Is_Identical
-- to (global) Element. Sets Result_Found ON if such a
-- component is found
procedure Check_List_Down (L : Asis.Element_List);
-- calls Get_Enclosing for every component of L, by
-- this the recursion and the second level of the search
-- is implemented
procedure Check_List (L : Asis.Element_List) is
begin
for L_El_Index in L'Range loop
if Is_Identical (Element, L (L_El_Index)) then
Result_Found := True;
return;
end if;
end loop;
end Check_List;
procedure Check_List_Down (L : Asis.Element_List) is
begin
if Result_Found then
return;
-- it seems that we do not need this if... ???
end if;
for L_El_Index in L'Range loop
Check_Possible_Enclosing (L (L_El_Index));
if Result_Found then
return;
end if;
end loop;
end Check_List_Down;
begin -- Check_Possible_Enclosing
if Result_Found then
return;
-- now the only goal is to not disturb the setting of the
-- global variable Result_Element to be returned as a result
end if;
-- first, setting the (global for this procedure) Result_Element:
Result_Element := Appr_Enclosing;
-- the first level of the search - checking all the direct
-- children:
for Each_Query in Child_Access'Range loop
case Child_Access (Each_Query).Query_Kind is
when Bug =>
null;
when Single_Element_Query =>
Next_Child :=
Child_Access (Each_Query).Func_Simple (Appr_Enclosing);
if Is_Identical (Element, Next_Child) then
Result_Found := True;
return;
end if;
when Element_List_Query =>
declare
Child_List : constant Asis.Element_List :=
Child_Access (Each_Query).Func_List (Appr_Enclosing);
begin
Check_List (Child_List);
if Result_Found then
return;
end if;
end;
when Element_List_Query_With_Boolean =>
declare
Child_List : constant Asis.Element_List :=
Child_Access (Each_Query).Func_List_Boolean
(Appr_Enclosing, Child_Access (Each_Query).Bool);
begin
Check_List (Child_List);
if Result_Found then
return;
end if;
end;
end case;
end loop;
-- if we are here, we have hot found Element among the direct
-- children of Appr_Enclosing. So we have to traverse the direct
-- children again, but this time we have to go one step down,
-- so here we have the second level of the search:
for Each_Query in Child_Access'Range loop
case Child_Access (Each_Query).Query_Kind is
when Bug =>
null;
when Single_Element_Query =>
Next_Child :=
Child_Access (Each_Query).Func_Simple (Appr_Enclosing);
-- and here - recursively one step down
if not Is_Nil (Next_Child) then
Check_Possible_Enclosing (Next_Child);
if Result_Found then
return;
end if;
end if;
when Element_List_Query =>
declare
Child_List : constant Asis.Element_List :=
Child_Access (Each_Query).Func_List (Appr_Enclosing);
begin
-- and here - recursively one step down
Check_List_Down (Child_List);
if Result_Found then
return;
end if;
end;
when Element_List_Query_With_Boolean =>
declare
Child_List : constant Asis.Element_List :=
Child_Access (Each_Query).Func_List_Boolean
(Appr_Enclosing, Child_Access (Each_Query).Bool);
begin
-- and here - recursively one step down
Check_List_Down (Child_List);
if Result_Found then
return;
end if;
end;
end case;
end loop;
end Check_Possible_Enclosing;
begin -- Get_Enclosing
Check_Possible_Enclosing (Approximation);
pragma Assert (Result_Found);
return Result_Element;
end Get_Enclosing;
------------------------------
-- Get_Rough_Enclosing_Node --
------------------------------
function Get_Rough_Enclosing_Node (Element : Asis.Element) return Node_Id
is
Arg_Node : constant Node_Id := R_Node (Element);
Result_Node : Node_Id;
Res_Nkind : Node_Kind;
function Is_Acceptable_As_Rough_Enclosing_Node
(N : Node_Id)
return Boolean;
-- this function encapsulates the condition for choosing
-- the rough enclosing node
function Is_Acceptable_Impl_Neq_Decl (N : Node_Id) return Boolean;
-- Implements a special check for Is_Acceptable_As_Rough_Enclosing_Node:
-- in case if Element is a subcomponenet of an implicit declaration of
-- "/=", checks that N represents the whole declaration of this "/="
-------------------------------------------
-- Is_Acceptable_As_Rough_Enclosing_Node --
-------------------------------------------
function Is_Acceptable_As_Rough_Enclosing_Node
(N : Node_Id)
return Boolean
is
N_K : constant Node_Kind := Nkind (N);
Result : Boolean := True;
begin
if not (Is_Acceptable_Impl_Neq_Decl (N)
or else
Is_List_Member (N)
or else
(Nkind (Parent (N)) = N_Compilation_Unit or else
Nkind (Parent (N)) = N_Subunit))
or else
(Nkind (N) in N_Subexpr
and then Nkind (N) /=
N_Procedure_Call_Statement)
or else
Nkind (N) = N_Parameter_Association
then
Result := False;
elsif N_K = N_Range or else
-- N_K = N_Component_Association or else
N_K = N_Subtype_Indication
then
Result := False;
elsif N_K = N_Component_Association then
if Special_Case (Element) = Is_From_Gen_Association
or else
Is_From_Rewritten_Aggregate (N)
then
Result := False;
end if;
elsif N_K = N_Procedure_Call_Statement and then
Nkind (Parent (N)) = N_Pragma
then
Result := False;
elsif not Comes_From_Source (N)
and then
Sloc (N) > Standard_Location
and then
not Is_Acceptable_Impl_Neq_Decl (N)
then
if not (Is_From_Instance (Element)
and then
Is_Top_Of_Expanded_Generic (N))
then
Result := False;
end if;
end if;
return Result;
end Is_Acceptable_As_Rough_Enclosing_Node;
---------------------------------
-- Is_Acceptable_Impl_Neq_Decl --
---------------------------------
function Is_Acceptable_Impl_Neq_Decl (N : Node_Id) return Boolean is
Result : Boolean := False;
begin
if Special_Case (Element) = Is_From_Imp_Neq_Declaration
and then
Nkind (N) = N_Subprogram_Declaration
and then
not Comes_From_Source (N)
and then
Present (Corresponding_Equality
(Defining_Unit_Name (Specification (N))))
then
Result := True;
end if;
return Result;
end Is_Acceptable_Impl_Neq_Decl;
begin -- Get_Rough_Enclosing_Node
Result_Node := Parent (Arg_Node);
if Nkind (Result_Node) = N_Object_Renaming_Declaration
and then
Special_Case (Element) = Is_From_Gen_Association
and then
Present (Corresponding_Generic_Association (Result_Node))
then
Result_Node := Corresponding_Generic_Association (Result_Node);
elsif (Nkind (Result_Node) = N_Attribute_Definition_Clause
or else
Nkind (Result_Node) = N_Pragma)
and then
From_Aspect_Specification (Result_Node)
then
-- Result_Node := Corresponding_Aspect (Result_Node);
null; -- SCz
end if;
while Present (Result_Node) and then
not Is_Acceptable_As_Rough_Enclosing_Node (Result_Node)
loop
Result_Node := Parent (Result_Node);
if Nkind (Result_Node) = N_Object_Renaming_Declaration
and then
Special_Case (Element) = Is_From_Gen_Association
and then
Present (Corresponding_Generic_Association (Result_Node))
then
Result_Node := Corresponding_Generic_Association (Result_Node);
elsif (Nkind (Result_Node) = N_Attribute_Definition_Clause
or else
Nkind (Result_Node) = N_Pragma)
and then
From_Aspect_Specification (Result_Node)
then
-- Result_Node := Corresponding_Aspect (Result_Node);
null; -- SCz
end if;
if Nkind (Result_Node) = N_Compilation_Unit then
-- this means that there is no node list on the way up
-- the tree, and we have to go back to the node
-- for the unit declaration:
if Is_Standard (Encl_Unit (Element)) then
Result_Node := Standard_Package_Node;
else
Result_Node := Unit (Result_Node);
end if;
if Nkind (Result_Node) = N_Subunit then
Result_Node := Proper_Body (Result_Node);
end if;
exit;
end if;
end loop;
-- and here we have to take into account possible normalization
-- of multi-identifier declarations:
Res_Nkind := Nkind (Result_Node);
if Res_Nkind = N_Object_Declaration or else
Res_Nkind = N_Number_Declaration or else
Res_Nkind = N_Discriminant_Specification or else
Res_Nkind = N_Component_Declaration or else
Res_Nkind = N_Parameter_Specification or else
Res_Nkind = N_Exception_Declaration or else
Res_Nkind = N_Formal_Object_Declaration or else
Res_Nkind = N_With_Clause
then
Skip_Normalized_Declarations_Back (Result_Node);
end if;
-- If we've got Result_Node pointing to the artificial package
-- declaration created for library-level generic instantiation,
-- we have to the body for which we have this instantiation as
-- the original node
if Nkind (Result_Node) = N_Package_Declaration and then
not Comes_From_Source (Result_Node) and then
Nkind (Parent (Result_Node)) = N_Compilation_Unit and then
not Is_From_Instance (Element) and then
not Is_Rewrite_Substitution (Result_Node)
then
Result_Node := Corresponding_Body (Result_Node);
while Nkind (Result_Node) /= N_Package_Body loop
Result_Node := Parent (Result_Node);
end loop;
end if;
-- Below is the patch for 8706-003. It is needed when we are looking
-- for the enclosing element for actual parameter in subprogram
-- instantiation. In this case Result_Node points to the spec of a
-- wrapper package, so we have to go to the instantiation.
if Special_Case (Element) = Is_From_Gen_Association
and then
Nkind (Result_Node) = N_Package_Declaration
and then
not (Nkind (Original_Node (Result_Node)) = N_Package_Instantiation
or else
Nkind (Original_Node (Result_Node)) = N_Package_Body
or else
(Present (Generic_Parent (Specification (Result_Node)))
and then
Ekind (Generic_Parent (Specification (Result_Node))) =
E_Generic_Package))
and then
not Comes_From_Source (Result_Node)
and then
(Nkind (Parent (Arg_Node)) = N_Subprogram_Renaming_Declaration
and then
not Comes_From_Source (Parent (Arg_Node)))
and then
Instantiation_Depth (Sloc (Result_Node)) =
Instantiation_Depth (Sloc (Arg_Node))
then
if Is_Rewrite_Substitution (Result_Node)
and then
Nkind (Original_Node (Result_Node)) in N_Generic_Instantiation
then
Result_Node := Original_Node (Result_Node);
else
while not Comes_From_Source (Result_Node) loop
Result_Node := Next_Non_Pragma (Result_Node);
end loop;
end if;
end if;
return Result_Node;
end Get_Rough_Enclosing_Node;
--------------------------------
-- Is_Top_Of_Expanded_Generic --
--------------------------------
function Is_Top_Of_Expanded_Generic (N : Node_Id) return Boolean is
N_Kind : constant Node_Kind := Nkind (N);
Result : Boolean := False;
begin
Result :=
((not Comes_From_Source (N) or else
Is_Rewrite_Insertion (N))
and then
(N_Kind = N_Package_Declaration or else
N_Kind = N_Package_Body or else
N_Kind = N_Subprogram_Declaration or else
N_Kind = N_Subprogram_Body)
and then
Nkind (Original_Node (N)) not in N_Renaming_Declaration)
or else
(Nkind (Parent (N)) = N_Package_Body and then
not Comes_From_Source (Parent (N)))
or else
(Is_Rewrite_Substitution (N) and then
Nkind (Original_Node (N)) = N_Package_Instantiation);
-- Library-level package instantiation
return Result;
end Is_Top_Of_Expanded_Generic;
--------------------------
-- No_Enclosing_Element --
--------------------------
procedure No_Enclosing_Element (Element_Kind : Internal_Element_Kinds) is
begin
Raise_ASIS_Failed
("No Enclosing Element can correspond " &
"to the Element with Internal_Element_Kinds value of " &
Internal_Element_Kinds'Image (Element_Kind));
end No_Enclosing_Element;
----------------------------------------------------
-- Not_Implemented_Enclosing_Element_Construction --
----------------------------------------------------
procedure Not_Implemented_Enclosing_Element_Construction
(Element : Asis.Element)
is
begin
Not_Implemented_Yet (Diagnosis =>
"Enclosing Element retrieval for the explicit Element "
& "of the " & Internal_Element_Kinds'Image
(Int_Kind (Element)) & " kind "
& "has not been implemented yet");
end Not_Implemented_Enclosing_Element_Construction;
------------
-- Parent --
------------
function Parent (Node : Node_Id) return Node_Id is
Result_Node : Node_Id;
begin
Result_Node := Atree.Parent (Node);
Skip_Normalized_Declarations_Back (Result_Node);
return Result_Node;
end Parent;
---------------------------
-- Skip_Implicit_Subtype --
---------------------------
procedure Skip_Implicit_Subtype (Constr : in out Node_Id) is
begin
if not Comes_From_Source (Parent (Constr)) then
Constr := Parent (Constr);
while Nkind (Constr) /= N_Object_Declaration loop
Constr := Next_Non_Pragma (Constr);
end loop;
Constr := Object_Definition (Constr);
end if;
end Skip_Implicit_Subtype;
---------------------------------------
-- Skip_Normalized_Declarations_Back --
---------------------------------------
procedure Skip_Normalized_Declarations_Back (Node : in out Node_Id) is
Arg_Kind : constant Node_Kind := Nkind (Node);
begin
loop
if Arg_Kind = N_Object_Declaration or else
Arg_Kind = N_Number_Declaration or else
Arg_Kind = N_Discriminant_Specification or else
Arg_Kind = N_Component_Declaration or else
Arg_Kind = N_Parameter_Specification or else
Arg_Kind = N_Exception_Declaration or else
Arg_Kind = N_Formal_Object_Declaration
then
if Prev_Ids (Node) then
Node := Prev (Node);
while Nkind (Node) /= Arg_Kind loop
-- some implicit subtype declarations may be inserted by
-- the compiler in between the normalized declarations, so:
Node := Prev (Node);
end loop;
else
return;
end if;
elsif Arg_Kind = N_With_Clause then
if First_Name (Node) then
return;
else
Node := Prev (Node);
end if;
else
return;
-- nothing to do!
end if;
end loop;
end Skip_Normalized_Declarations_Back;
end A4G.Encl_El;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . L O C K _ F I L E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1995-2010, 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. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the necessary routines for using files for the
-- purpose of providing reliable system wide locking capability.
package GNAT.Lock_Files is
pragma Preelaborate;
Lock_Error : exception;
-- Exception raised if file cannot be locked
subtype Path_Name is String;
-- Pathname is used by all services provided in this unit to specified
-- directory name and file name. On DOS based systems both directory
-- separators are handled (i.e. slash and backslash).
procedure Lock_File
(Directory : Path_Name;
Lock_File_Name : Path_Name;
Wait : Duration := 1.0;
Retries : Natural := Natural'Last);
-- Create a lock file Lock_File_Name in directory Directory. If the file
-- cannot be locked because someone already owns the lock, this procedure
-- waits Wait seconds and retries at most Retries times. If the file
-- still cannot be locked, Lock_Error is raised. The default is to try
-- every second, almost forever (Natural'Last times). The full path of
-- the file is constructed by concatenating Directory and Lock_File_Name.
-- Directory can optionally terminate with a directory separator.
procedure Lock_File
(Lock_File_Name : Path_Name;
Wait : Duration := 1.0;
Retries : Natural := Natural'Last);
-- See above. The full lock file path is given as one string
procedure Unlock_File (Directory : Path_Name; Lock_File_Name : Path_Name);
-- Unlock a file. Directory can optionally terminate with a directory
-- separator.
procedure Unlock_File (Lock_File_Name : Path_Name);
-- Unlock a file whose full path is given in Lock_File_Name
end GNAT.Lock_Files;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . T A S K _ T E R M I N A T I O N --
-- --
-- B o d y --
-- --
-- Copyright (C) 2005-2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This is a simplified version of this package body to be used in when the
-- Ravenscar profile and there are no exception handlers present (either of
-- the restrictions No_Exception_Handlers or No_Exception_Propagation are in
-- effect). This means that the only task termination cause that need to be
-- taken into account is normal task termination (abort is not allowed by
-- the Ravenscar profile and the restricted exception support does not
-- include Exception_Occurrence).
with System.Tasking;
-- used for Task_Id
-- Self
-- Fall_Back_Handler
with System.Task_Primitives.Operations;
-- Used for Self
-- Set_Priority
-- Get_Priority
with Unchecked_Conversion;
package body Ada.Task_Termination is
use System.Task_Primitives.Operations;
use type Ada.Task_Identification.Task_Id;
function To_TT is new Unchecked_Conversion
(System.Tasking.Termination_Handler, Termination_Handler);
function To_ST is new Unchecked_Conversion
(Termination_Handler, System.Tasking.Termination_Handler);
-----------------------------------
-- Current_Task_Fallback_Handler --
-----------------------------------
function Current_Task_Fallback_Handler return Termination_Handler is
Self_Id : constant System.Tasking.Task_Id := Self;
Caller_Priority : constant System.Any_Priority := Get_Priority (Self_Id);
Result : Termination_Handler;
begin
-- Raise the priority to prevent race conditions when modifying
-- System.Tasking.Fall_Back_Handler.
Set_Priority (Self_Id, System.Any_Priority'Last);
Result := To_TT (System.Tasking.Fall_Back_Handler);
-- Restore the original priority
Set_Priority (Self_Id, Caller_Priority);
return Result;
end Current_Task_Fallback_Handler;
-------------------------------------
-- Set_Dependents_Fallback_Handler --
-------------------------------------
procedure Set_Dependents_Fallback_Handler (Handler : Termination_Handler) is
Self_Id : constant System.Tasking.Task_Id := Self;
Caller_Priority : constant System.Any_Priority := Get_Priority (Self_Id);
begin
-- Raise the priority to prevent race conditions when modifying
-- System.Tasking.Fall_Back_Handler.
Set_Priority (Self_Id, System.Any_Priority'Last);
System.Tasking.Fall_Back_Handler := To_ST (Handler);
-- Restore the original priority
Set_Priority (Self_Id, Caller_Priority);
end Set_Dependents_Fallback_Handler;
end Ada.Task_Termination;
|
-- Copyright (c) 2015-2017 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with League.Strings.Cursors.Characters;
with Incr.Documents;
with Incr.Lexers.Batch_Lexers;
with Incr.Nodes.Tokens;
with Incr.Version_Trees;
package Incr.Lexers.Incremental is
-- @summary
-- Incremental Lexer
--
-- @description
-- This package provides incremental lexical analyser and related types.
--
-- The lexer uses three versions of the document:
--
-- * Reference - version when last analysis completed
-- * Changing - current version under construction
-- * Previous - last read-olny version of document to be analyzed
--
-- Workflow of this lexer includes next steps:
--
-- * call Prepare_Document to explicitly mark tokens to start re-lexing
-- * find first marked token using Nested_Changes property
-- * get new token by call First_New_Token
-- * continue calling Next_New_Token until Is_Synchronized
-- * now new stream of token in sync with old one at Synchronized_Token
-- * look for next marked token from here and continue from step 3
--
type Incremental_Lexer is tagged limited private;
-- Type to perform incremental lexical analysis
type Incremental_Lexer_Access is access all Incremental_Lexer;
not overriding procedure Set_Batch_Lexer
(Self : in out Incremental_Lexer;
Lexer : Batch_Lexers.Batch_Lexer_Access);
-- Assign batch lexer to Self.
not overriding procedure Prepare_Document
(Self : in out Incremental_Lexer;
Document : Documents.Document_Access;
Reference : Version_Trees.Version);
-- Start analysis by looking for tokens where re-lexing should be start.
-- Mark them with Need_Analysis flag.
not overriding function First_New_Token
(Self : in out Incremental_Lexer;
Token : Nodes.Tokens.Token_Access)
return Nodes.Tokens.Token_Access;
-- Start construction of new token stream from given Token.
-- Token should be marked as Need_Analysis flag in Prepare_Document call.
-- Return first created token.
not overriding function Next_New_Token
(Self : in out Incremental_Lexer) return Nodes.Tokens.Token_Access;
-- with Pre => not Is_Synchronized (Self);
-- Continue construction of new token stream. Return next created token.
-- Should be called when not yet Is_Synchronized (Self);
not overriding function Is_Synchronized
(Self : Incremental_Lexer) return Boolean;
-- Check if new token stream in synch with old one.
not overriding function Synchronized_Token
(Self : Incremental_Lexer) return Nodes.Tokens.Token_Access
with Pre => Is_Synchronized (Self);
-- Return first token after join new token stream with old one.
-- Should be called just after Is_Synchronized returns True.
private
type Token_Pair is array (1 .. 2) of Nodes.Tokens.Token_Access;
type Incremental_Lexer is new Batch_Lexers.Abstract_Source with record
Batch : Batch_Lexers.Batch_Lexer_Access;
Document : Documents.Document_Access;
Reference : Version_Trees.Version; -- Last analyzed version
Previous : Version_Trees.Version; -- Version to analyze
Token : Nodes.Tokens.Token_Access;
Prev_Token : Token_Pair;
Count : Integer; -- Number of chars piped before Token
State : Batch_Lexers.State; -- Lexer State before Token
New_State : Batch_Lexers.State; -- State after Xxx_New_Token
Text : League.Strings.Universal_String; -- Text of Token
Cursor : League.Strings.Cursors.Characters.Character_Cursor;
end record;
overriding function Get_Next (Self : not null access Incremental_Lexer)
return Wide_Wide_Character;
end Incr.Lexers.Incremental;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S O C K E T S . T H I N --
-- --
-- B o d y --
-- --
-- Copyright (C) 2001-2005, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- 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 provides a target dependent thin interface to the sockets
-- layer for use by the GNAT.Sockets package (g-socket.ads). This package
-- should not be directly with'ed by an applications program.
-- This version is for NT
with GNAT.Sockets.Constants; use GNAT.Sockets.Constants;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with System; use System;
package body GNAT.Sockets.Thin is
use type C.unsigned;
WSAData_Dummy : array (1 .. 512) of C.int;
WS_Version : constant := 16#0101#;
Initialized : Boolean := False;
SYSNOTREADY : constant := 10091;
VERNOTSUPPORTED : constant := 10092;
NOTINITIALISED : constant := 10093;
EDISCON : constant := 10101;
function Standard_Connect
(S : C.int;
Name : System.Address;
Namelen : C.int) return C.int;
pragma Import (Stdcall, Standard_Connect, "connect");
function Standard_Select
(Nfds : C.int;
Readfds : Fd_Set_Access;
Writefds : Fd_Set_Access;
Exceptfds : Fd_Set_Access;
Timeout : Timeval_Access) return C.int;
pragma Import (Stdcall, Standard_Select, "select");
type Error_Type is
(N_EINTR,
N_EBADF,
N_EACCES,
N_EFAULT,
N_EINVAL,
N_EMFILE,
N_EWOULDBLOCK,
N_EINPROGRESS,
N_EALREADY,
N_ENOTSOCK,
N_EDESTADDRREQ,
N_EMSGSIZE,
N_EPROTOTYPE,
N_ENOPROTOOPT,
N_EPROTONOSUPPORT,
N_ESOCKTNOSUPPORT,
N_EOPNOTSUPP,
N_EPFNOSUPPORT,
N_EAFNOSUPPORT,
N_EADDRINUSE,
N_EADDRNOTAVAIL,
N_ENETDOWN,
N_ENETUNREACH,
N_ENETRESET,
N_ECONNABORTED,
N_ECONNRESET,
N_ENOBUFS,
N_EISCONN,
N_ENOTCONN,
N_ESHUTDOWN,
N_ETOOMANYREFS,
N_ETIMEDOUT,
N_ECONNREFUSED,
N_ELOOP,
N_ENAMETOOLONG,
N_EHOSTDOWN,
N_EHOSTUNREACH,
N_SYSNOTREADY,
N_VERNOTSUPPORTED,
N_NOTINITIALISED,
N_EDISCON,
N_HOST_NOT_FOUND,
N_TRY_AGAIN,
N_NO_RECOVERY,
N_NO_DATA,
N_OTHERS);
Error_Messages : constant array (Error_Type) of chars_ptr :=
(N_EINTR =>
New_String ("Interrupted system call"),
N_EBADF =>
New_String ("Bad file number"),
N_EACCES =>
New_String ("Permission denied"),
N_EFAULT =>
New_String ("Bad address"),
N_EINVAL =>
New_String ("Invalid argument"),
N_EMFILE =>
New_String ("Too many open files"),
N_EWOULDBLOCK =>
New_String ("Operation would block"),
N_EINPROGRESS =>
New_String ("Operation now in progress. This error is "
& "returned if any Windows Sockets API "
& "function is called while a blocking "
& "function is in progress"),
N_EALREADY =>
New_String ("Operation already in progress"),
N_ENOTSOCK =>
New_String ("Socket operation on nonsocket"),
N_EDESTADDRREQ =>
New_String ("Destination address required"),
N_EMSGSIZE =>
New_String ("Message too long"),
N_EPROTOTYPE =>
New_String ("Protocol wrong type for socket"),
N_ENOPROTOOPT =>
New_String ("Protocol not available"),
N_EPROTONOSUPPORT =>
New_String ("Protocol not supported"),
N_ESOCKTNOSUPPORT =>
New_String ("Socket type not supported"),
N_EOPNOTSUPP =>
New_String ("Operation not supported on socket"),
N_EPFNOSUPPORT =>
New_String ("Protocol family not supported"),
N_EAFNOSUPPORT =>
New_String ("Address family not supported by protocol family"),
N_EADDRINUSE =>
New_String ("Address already in use"),
N_EADDRNOTAVAIL =>
New_String ("Cannot assign requested address"),
N_ENETDOWN =>
New_String ("Network is down. This error may be "
& "reported at any time if the Windows "
& "Sockets implementation detects an "
& "underlying failure"),
N_ENETUNREACH =>
New_String ("Network is unreachable"),
N_ENETRESET =>
New_String ("Network dropped connection on reset"),
N_ECONNABORTED =>
New_String ("Software caused connection abort"),
N_ECONNRESET =>
New_String ("Connection reset by peer"),
N_ENOBUFS =>
New_String ("No buffer space available"),
N_EISCONN =>
New_String ("Socket is already connected"),
N_ENOTCONN =>
New_String ("Socket is not connected"),
N_ESHUTDOWN =>
New_String ("Cannot send after socket shutdown"),
N_ETOOMANYREFS =>
New_String ("Too many references: cannot splice"),
N_ETIMEDOUT =>
New_String ("Connection timed out"),
N_ECONNREFUSED =>
New_String ("Connection refused"),
N_ELOOP =>
New_String ("Too many levels of symbolic links"),
N_ENAMETOOLONG =>
New_String ("File name too long"),
N_EHOSTDOWN =>
New_String ("Host is down"),
N_EHOSTUNREACH =>
New_String ("No route to host"),
N_SYSNOTREADY =>
New_String ("Returned by WSAStartup(), indicating that "
& "the network subsystem is unusable"),
N_VERNOTSUPPORTED =>
New_String ("Returned by WSAStartup(), indicating that "
& "the Windows Sockets DLL cannot support "
& "this application"),
N_NOTINITIALISED =>
New_String ("Winsock not initialized. This message is "
& "returned by any function except WSAStartup(), "
& "indicating that a successful WSAStartup() has "
& "not yet been performed"),
N_EDISCON =>
New_String ("Disconnect"),
N_HOST_NOT_FOUND =>
New_String ("Host not found. This message indicates "
& "that the key (name, address, and so on) was not found"),
N_TRY_AGAIN =>
New_String ("Nonauthoritative host not found. This error may "
& "suggest that the name service itself is not "
& "functioning"),
N_NO_RECOVERY =>
New_String ("Nonrecoverable error. This error may suggest that the "
& "name service itself is not functioning"),
N_NO_DATA =>
New_String ("Valid name, no data record of requested type. "
& "This error indicates that the key (name, address, "
& "and so on) was not found."),
N_OTHERS =>
New_String ("Unknown system error"));
---------------
-- C_Connect --
---------------
function C_Connect
(S : C.int;
Name : System.Address;
Namelen : C.int) return C.int
is
Res : C.int;
begin
Res := Standard_Connect (S, Name, Namelen);
if Res = -1 then
if Socket_Errno = EWOULDBLOCK then
Set_Socket_Errno (EINPROGRESS);
end if;
end if;
return Res;
end C_Connect;
-------------
-- C_Readv --
-------------
function C_Readv
(Socket : C.int;
Iov : System.Address;
Iovcnt : C.int) return C.int
is
Res : C.int;
Count : C.int := 0;
Iovec : array (0 .. Iovcnt - 1) of Vector_Element;
for Iovec'Address use Iov;
pragma Import (Ada, Iovec);
begin
for J in Iovec'Range loop
Res := C_Recv
(Socket,
Iovec (J).Base.all'Address,
C.int (Iovec (J).Length),
0);
if Res < 0 then
return Res;
else
Count := Count + Res;
end if;
end loop;
return Count;
end C_Readv;
--------------
-- C_Select --
--------------
function C_Select
(Nfds : C.int;
Readfds : Fd_Set_Access;
Writefds : Fd_Set_Access;
Exceptfds : Fd_Set_Access;
Timeout : Timeval_Access) return C.int
is
pragma Warnings (Off, Exceptfds);
RFS : constant Fd_Set_Access := Readfds;
WFS : constant Fd_Set_Access := Writefds;
WFSC : Fd_Set_Access := No_Fd_Set;
EFS : Fd_Set_Access := Exceptfds;
Res : C.int;
S : aliased C.int;
Last : aliased C.int;
begin
-- Asynchronous connection failures are notified in the
-- exception fd set instead of the write fd set. To ensure
-- POSIX compatitibility, copy write fd set into exception fd
-- set. Once select() returns, check any socket present in the
-- exception fd set and peek at incoming out-of-band data. If
-- the test is not successful, and the socket is present in
-- the initial write fd set, then move the socket from the
-- exception fd set to the write fd set.
if WFS /= No_Fd_Set then
-- Add any socket present in write fd set into exception fd set
if EFS = No_Fd_Set then
EFS := New_Socket_Set (WFS);
else
WFSC := New_Socket_Set (WFS);
Last := Nfds - 1;
loop
Get_Socket_From_Set
(WFSC, S'Unchecked_Access, Last'Unchecked_Access);
exit when S = -1;
Insert_Socket_In_Set (EFS, S);
end loop;
Free_Socket_Set (WFSC);
end if;
-- Keep a copy of write fd set
WFSC := New_Socket_Set (WFS);
end if;
Res := Standard_Select (Nfds, RFS, WFS, EFS, Timeout);
if EFS /= No_Fd_Set then
declare
EFSC : constant Fd_Set_Access := New_Socket_Set (EFS);
Flag : constant C.int := MSG_PEEK + MSG_OOB;
Buffer : Character;
Length : C.int;
Fromlen : aliased C.int;
begin
Last := Nfds - 1;
loop
Get_Socket_From_Set
(EFSC, S'Unchecked_Access, Last'Unchecked_Access);
-- No more sockets in EFSC
exit when S = -1;
-- Check out-of-band data
Length := C_Recvfrom
(S, Buffer'Address, 1, Flag,
null, Fromlen'Unchecked_Access);
-- If the signal is not an out-of-band data, then it
-- is a connection failure notification.
if Length = -1 then
Remove_Socket_From_Set (EFS, S);
-- If S is present in the initial write fd set,
-- move it from exception fd set back to write fd
-- set. Otherwise, ignore this event since the user
-- is not watching for it.
if WFSC /= No_Fd_Set
and then (Is_Socket_In_Set (WFSC, S) /= 0)
then
Insert_Socket_In_Set (WFS, S);
end if;
end if;
end loop;
Free_Socket_Set (EFSC);
end;
if Exceptfds = No_Fd_Set then
Free_Socket_Set (EFS);
end if;
end if;
-- Free any copy of write fd set
if WFSC /= No_Fd_Set then
Free_Socket_Set (WFSC);
end if;
return Res;
end C_Select;
-----------------
-- C_Inet_Addr --
-----------------
function C_Inet_Addr
(Cp : C.Strings.chars_ptr) return C.int
is
use type C.unsigned_long;
function Internal_Inet_Addr
(Cp : C.Strings.chars_ptr) return C.unsigned_long;
pragma Import (Stdcall, Internal_Inet_Addr, "inet_addr");
Res : C.unsigned_long;
begin
Res := Internal_Inet_Addr (Cp);
if Res = C.unsigned_long'Last then
-- This value is returned in case of error
return -1;
else
return C.int (Internal_Inet_Addr (Cp));
end if;
end C_Inet_Addr;
--------------
-- C_Writev --
--------------
function C_Writev
(Socket : C.int;
Iov : System.Address;
Iovcnt : C.int) return C.int
is
Res : C.int;
Count : C.int := 0;
Iovec : array (0 .. Iovcnt - 1) of Vector_Element;
for Iovec'Address use Iov;
pragma Import (Ada, Iovec);
begin
for J in Iovec'Range loop
Res := C_Send
(Socket,
Iovec (J).Base.all'Address,
C.int (Iovec (J).Length),
0);
if Res < 0 then
return Res;
else
Count := Count + Res;
end if;
end loop;
return Count;
end C_Writev;
--------------
-- Finalize --
--------------
procedure Finalize is
begin
if Initialized then
WSACleanup;
Initialized := False;
end if;
end Finalize;
----------------
-- Initialize --
----------------
procedure Initialize (Process_Blocking_IO : Boolean := False) is
pragma Unreferenced (Process_Blocking_IO);
Return_Value : Interfaces.C.int;
begin
if not Initialized then
Return_Value := WSAStartup (WS_Version, WSAData_Dummy'Address);
pragma Assert (Interfaces.C."=" (Return_Value, 0));
Initialized := True;
end if;
end Initialize;
-----------------
-- Set_Address --
-----------------
procedure Set_Address
(Sin : Sockaddr_In_Access;
Address : In_Addr)
is
begin
Sin.Sin_Addr := Address;
end Set_Address;
----------------
-- Set_Family --
----------------
procedure Set_Family
(Sin : Sockaddr_In_Access;
Family : C.int)
is
begin
Sin.Sin_Family := C.unsigned_short (Family);
end Set_Family;
----------------
-- Set_Length --
----------------
procedure Set_Length
(Sin : Sockaddr_In_Access;
Len : C.int)
is
pragma Unreferenced (Sin);
pragma Unreferenced (Len);
begin
null;
end Set_Length;
--------------
-- Set_Port --
--------------
procedure Set_Port
(Sin : Sockaddr_In_Access;
Port : C.unsigned_short)
is
begin
Sin.Sin_Port := Port;
end Set_Port;
--------------------------
-- Socket_Error_Message --
--------------------------
function Socket_Error_Message
(Errno : Integer) return C.Strings.chars_ptr
is
begin
case Errno is
when EINTR => return Error_Messages (N_EINTR);
when EBADF => return Error_Messages (N_EBADF);
when EACCES => return Error_Messages (N_EACCES);
when EFAULT => return Error_Messages (N_EFAULT);
when EINVAL => return Error_Messages (N_EINVAL);
when EMFILE => return Error_Messages (N_EMFILE);
when EWOULDBLOCK => return Error_Messages (N_EWOULDBLOCK);
when EINPROGRESS => return Error_Messages (N_EINPROGRESS);
when EALREADY => return Error_Messages (N_EALREADY);
when ENOTSOCK => return Error_Messages (N_ENOTSOCK);
when EDESTADDRREQ => return Error_Messages (N_EDESTADDRREQ);
when EMSGSIZE => return Error_Messages (N_EMSGSIZE);
when EPROTOTYPE => return Error_Messages (N_EPROTOTYPE);
when ENOPROTOOPT => return Error_Messages (N_ENOPROTOOPT);
when EPROTONOSUPPORT => return Error_Messages (N_EPROTONOSUPPORT);
when ESOCKTNOSUPPORT => return Error_Messages (N_ESOCKTNOSUPPORT);
when EOPNOTSUPP => return Error_Messages (N_EOPNOTSUPP);
when EPFNOSUPPORT => return Error_Messages (N_EPFNOSUPPORT);
when EAFNOSUPPORT => return Error_Messages (N_EAFNOSUPPORT);
when EADDRINUSE => return Error_Messages (N_EADDRINUSE);
when EADDRNOTAVAIL => return Error_Messages (N_EADDRNOTAVAIL);
when ENETDOWN => return Error_Messages (N_ENETDOWN);
when ENETUNREACH => return Error_Messages (N_ENETUNREACH);
when ENETRESET => return Error_Messages (N_ENETRESET);
when ECONNABORTED => return Error_Messages (N_ECONNABORTED);
when ECONNRESET => return Error_Messages (N_ECONNRESET);
when ENOBUFS => return Error_Messages (N_ENOBUFS);
when EISCONN => return Error_Messages (N_EISCONN);
when ENOTCONN => return Error_Messages (N_ENOTCONN);
when ESHUTDOWN => return Error_Messages (N_ESHUTDOWN);
when ETOOMANYREFS => return Error_Messages (N_ETOOMANYREFS);
when ETIMEDOUT => return Error_Messages (N_ETIMEDOUT);
when ECONNREFUSED => return Error_Messages (N_ECONNREFUSED);
when ELOOP => return Error_Messages (N_ELOOP);
when ENAMETOOLONG => return Error_Messages (N_ENAMETOOLONG);
when EHOSTDOWN => return Error_Messages (N_EHOSTDOWN);
when EHOSTUNREACH => return Error_Messages (N_EHOSTUNREACH);
when SYSNOTREADY => return Error_Messages (N_SYSNOTREADY);
when VERNOTSUPPORTED => return Error_Messages (N_VERNOTSUPPORTED);
when NOTINITIALISED => return Error_Messages (N_NOTINITIALISED);
when EDISCON => return Error_Messages (N_EDISCON);
when HOST_NOT_FOUND => return Error_Messages (N_HOST_NOT_FOUND);
when TRY_AGAIN => return Error_Messages (N_TRY_AGAIN);
when NO_RECOVERY => return Error_Messages (N_NO_RECOVERY);
when NO_DATA => return Error_Messages (N_NO_DATA);
when others => return Error_Messages (N_OTHERS);
end case;
end Socket_Error_Message;
end GNAT.Sockets.Thin;
|
package GDNative.Tokenizer is
type Character_Array is array (Positive range <>) of Character;
type Tokenizer_State (<>) is private;
function Initialize (Input : String; Separators : Character_Array) return Tokenizer_State;
procedure Skip (State : in out Tokenizer_State);
procedure Skip_Until (State : in out Tokenizer_State; Indicators : Character_Array);
procedure Skip_Until_Not (State : in out Tokenizer_State; Indicators : Character_Array);
procedure Skip_Line (State : in out Tokenizer_State);
function Read_String (State : in out Tokenizer_State) return String;
function Read_Integer (State : in out Tokenizer_State) return Integer;
-------
private
-------
type Tokenizer_State (
Input_Length : Positive;
Separators_Length : Positive)
is record
Input : String (1 .. Input_Length);
Separators : Character_Array (1 .. Separators_Length);
Current : Character;
Current_Offset : Natural;
Token_Start : Natural;
Token_End : Natural;
end record;
function At_End_Or_Indicator (State : in Tokenizer_State; Indicators : in Character_Array) return Boolean;
function At_End_Or_Not_Indicator (State : in Tokenizer_State; Indicators : in Character_Array) return Boolean;
procedure Next (State : in out Tokenizer_State);
procedure Start (State : in out Tokenizer_State);
procedure Stop (State : in out Tokenizer_State);
function Read (State : in out Tokenizer_State) return String;
end; |
with AAA.Strings;
private with GNAT.Strings;
package Commands.Init is
type Instance
is new CLIC.Subcommand.Command
with private;
overriding function Name (Cmd : Instance) return
CLIC.Subcommand.Identifier is ("init");
overriding procedure Execute
(Cmd : in out Instance; Args : AAA.Strings.Vector);
overriding
function Switch_Parsing (This : Instance)
return CLIC.Subcommand.Switch_Parsing_Kind
is (CLIC.Subcommand.All_As_Args);
overriding function Long_Description
(Cmd : Instance) return AAA.Strings.Vector is
(AAA.Strings.Empty_Vector.Append
("Initializes a new website in the current folder.")
.New_Line
);
overriding procedure Setup_Switches
(Cmd : in out Instance;
Config : in out CLIC.Subcommand.Switches_Configuration);
overriding function Short_Description (Cmd : Instance) return String is
("Initializes a new website in the current folder.");
overriding function Usage_Custom_Parameters (Cmd : Instance)
return String is ("[-dry-run] [--blueprint <name>]");
private
type Instance is new CLIC.Subcommand.Command with record
Dry_Run : aliased Boolean := False;
Blueprint : aliased GNAT.Strings.String_Access;
end record;
end Commands.Init; |
-- 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 NRF_SVD.RADIO is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Shortcut between READY event and START task.
type SHORTS_READY_START_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_READY_START_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between END event and DISABLE task.
type SHORTS_END_DISABLE_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_END_DISABLE_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between DISABLED event and TXEN task.
type SHORTS_DISABLED_TXEN_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_DISABLED_TXEN_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between DISABLED event and RXEN task.
type SHORTS_DISABLED_RXEN_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_DISABLED_RXEN_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between ADDRESS event and RSSISTART task.
type SHORTS_ADDRESS_RSSISTART_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_ADDRESS_RSSISTART_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between END event and START task.
type SHORTS_END_START_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_END_START_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between ADDRESS event and BCSTART task.
type SHORTS_ADDRESS_BCSTART_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_ADDRESS_BCSTART_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcut between DISABLED event and RSSISTOP task.
type SHORTS_DISABLED_RSSISTOP_Field is
(-- Shortcut disabled.
Disabled,
-- Shortcut enabled.
Enabled)
with Size => 1;
for SHORTS_DISABLED_RSSISTOP_Field use
(Disabled => 0,
Enabled => 1);
-- Shortcuts for the radio.
type SHORTS_Register is record
-- Shortcut between READY event and START task.
READY_START : SHORTS_READY_START_Field := NRF_SVD.RADIO.Disabled;
-- Shortcut between END event and DISABLE task.
END_DISABLE : SHORTS_END_DISABLE_Field := NRF_SVD.RADIO.Disabled;
-- Shortcut between DISABLED event and TXEN task.
DISABLED_TXEN : SHORTS_DISABLED_TXEN_Field :=
NRF_SVD.RADIO.Disabled;
-- Shortcut between DISABLED event and RXEN task.
DISABLED_RXEN : SHORTS_DISABLED_RXEN_Field :=
NRF_SVD.RADIO.Disabled;
-- Shortcut between ADDRESS event and RSSISTART task.
ADDRESS_RSSISTART : SHORTS_ADDRESS_RSSISTART_Field :=
NRF_SVD.RADIO.Disabled;
-- Shortcut between END event and START task.
END_START : SHORTS_END_START_Field := NRF_SVD.RADIO.Disabled;
-- Shortcut between ADDRESS event and BCSTART task.
ADDRESS_BCSTART : SHORTS_ADDRESS_BCSTART_Field :=
NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_7_7 : HAL.Bit := 16#0#;
-- Shortcut between DISABLED event and RSSISTOP task.
DISABLED_RSSISTOP : SHORTS_DISABLED_RSSISTOP_Field :=
NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_9_31 : HAL.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SHORTS_Register use record
READY_START at 0 range 0 .. 0;
END_DISABLE at 0 range 1 .. 1;
DISABLED_TXEN at 0 range 2 .. 2;
DISABLED_RXEN at 0 range 3 .. 3;
ADDRESS_RSSISTART at 0 range 4 .. 4;
END_START at 0 range 5 .. 5;
ADDRESS_BCSTART at 0 range 6 .. 6;
Reserved_7_7 at 0 range 7 .. 7;
DISABLED_RSSISTOP at 0 range 8 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
-- Enable interrupt on READY event.
type INTENSET_READY_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_READY_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on READY event.
type INTENSET_READY_Field_1 is
(-- Reset value for the field
Intenset_Ready_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_READY_Field_1 use
(Intenset_Ready_Field_Reset => 0,
Set => 1);
-- Enable interrupt on ADDRESS event.
type INTENSET_ADDRESS_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_ADDRESS_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on ADDRESS event.
type INTENSET_ADDRESS_Field_1 is
(-- Reset value for the field
Intenset_Address_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_ADDRESS_Field_1 use
(Intenset_Address_Field_Reset => 0,
Set => 1);
-- Enable interrupt on PAYLOAD event.
type INTENSET_PAYLOAD_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_PAYLOAD_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on PAYLOAD event.
type INTENSET_PAYLOAD_Field_1 is
(-- Reset value for the field
Intenset_Payload_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_PAYLOAD_Field_1 use
(Intenset_Payload_Field_Reset => 0,
Set => 1);
-- Enable interrupt on END event.
type INTENSET_END_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_END_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on END event.
type INTENSET_END_Field_1 is
(-- Reset value for the field
Intenset_End_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_END_Field_1 use
(Intenset_End_Field_Reset => 0,
Set => 1);
-- Enable interrupt on DISABLED event.
type INTENSET_DISABLED_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_DISABLED_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on DISABLED event.
type INTENSET_DISABLED_Field_1 is
(-- Reset value for the field
Intenset_Disabled_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_DISABLED_Field_1 use
(Intenset_Disabled_Field_Reset => 0,
Set => 1);
-- Enable interrupt on DEVMATCH event.
type INTENSET_DEVMATCH_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_DEVMATCH_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on DEVMATCH event.
type INTENSET_DEVMATCH_Field_1 is
(-- Reset value for the field
Intenset_Devmatch_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_DEVMATCH_Field_1 use
(Intenset_Devmatch_Field_Reset => 0,
Set => 1);
-- Enable interrupt on DEVMISS event.
type INTENSET_DEVMISS_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_DEVMISS_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on DEVMISS event.
type INTENSET_DEVMISS_Field_1 is
(-- Reset value for the field
Intenset_Devmiss_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_DEVMISS_Field_1 use
(Intenset_Devmiss_Field_Reset => 0,
Set => 1);
-- Enable interrupt on RSSIEND event.
type INTENSET_RSSIEND_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_RSSIEND_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on RSSIEND event.
type INTENSET_RSSIEND_Field_1 is
(-- Reset value for the field
Intenset_Rssiend_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_RSSIEND_Field_1 use
(Intenset_Rssiend_Field_Reset => 0,
Set => 1);
-- Enable interrupt on BCMATCH event.
type INTENSET_BCMATCH_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENSET_BCMATCH_Field use
(Disabled => 0,
Enabled => 1);
-- Enable interrupt on BCMATCH event.
type INTENSET_BCMATCH_Field_1 is
(-- Reset value for the field
Intenset_Bcmatch_Field_Reset,
-- Enable interrupt on write.
Set)
with Size => 1;
for INTENSET_BCMATCH_Field_1 use
(Intenset_Bcmatch_Field_Reset => 0,
Set => 1);
-- Interrupt enable set register.
type INTENSET_Register is record
-- Enable interrupt on READY event.
READY : INTENSET_READY_Field_1 := Intenset_Ready_Field_Reset;
-- Enable interrupt on ADDRESS event.
ADDRESS : INTENSET_ADDRESS_Field_1 :=
Intenset_Address_Field_Reset;
-- Enable interrupt on PAYLOAD event.
PAYLOAD : INTENSET_PAYLOAD_Field_1 :=
Intenset_Payload_Field_Reset;
-- Enable interrupt on END event.
END_k : INTENSET_END_Field_1 := Intenset_End_Field_Reset;
-- Enable interrupt on DISABLED event.
DISABLED : INTENSET_DISABLED_Field_1 :=
Intenset_Disabled_Field_Reset;
-- Enable interrupt on DEVMATCH event.
DEVMATCH : INTENSET_DEVMATCH_Field_1 :=
Intenset_Devmatch_Field_Reset;
-- Enable interrupt on DEVMISS event.
DEVMISS : INTENSET_DEVMISS_Field_1 :=
Intenset_Devmiss_Field_Reset;
-- Enable interrupt on RSSIEND event.
RSSIEND : INTENSET_RSSIEND_Field_1 :=
Intenset_Rssiend_Field_Reset;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Enable interrupt on BCMATCH event.
BCMATCH : INTENSET_BCMATCH_Field_1 :=
Intenset_Bcmatch_Field_Reset;
-- unspecified
Reserved_11_31 : HAL.UInt21 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTENSET_Register use record
READY at 0 range 0 .. 0;
ADDRESS at 0 range 1 .. 1;
PAYLOAD at 0 range 2 .. 2;
END_k at 0 range 3 .. 3;
DISABLED at 0 range 4 .. 4;
DEVMATCH at 0 range 5 .. 5;
DEVMISS at 0 range 6 .. 6;
RSSIEND at 0 range 7 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
BCMATCH at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- Disable interrupt on READY event.
type INTENCLR_READY_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_READY_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on READY event.
type INTENCLR_READY_Field_1 is
(-- Reset value for the field
Intenclr_Ready_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_READY_Field_1 use
(Intenclr_Ready_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on ADDRESS event.
type INTENCLR_ADDRESS_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_ADDRESS_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on ADDRESS event.
type INTENCLR_ADDRESS_Field_1 is
(-- Reset value for the field
Intenclr_Address_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_ADDRESS_Field_1 use
(Intenclr_Address_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on PAYLOAD event.
type INTENCLR_PAYLOAD_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_PAYLOAD_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on PAYLOAD event.
type INTENCLR_PAYLOAD_Field_1 is
(-- Reset value for the field
Intenclr_Payload_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_PAYLOAD_Field_1 use
(Intenclr_Payload_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on END event.
type INTENCLR_END_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_END_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on END event.
type INTENCLR_END_Field_1 is
(-- Reset value for the field
Intenclr_End_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_END_Field_1 use
(Intenclr_End_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on DISABLED event.
type INTENCLR_DISABLED_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_DISABLED_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on DISABLED event.
type INTENCLR_DISABLED_Field_1 is
(-- Reset value for the field
Intenclr_Disabled_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_DISABLED_Field_1 use
(Intenclr_Disabled_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on DEVMATCH event.
type INTENCLR_DEVMATCH_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_DEVMATCH_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on DEVMATCH event.
type INTENCLR_DEVMATCH_Field_1 is
(-- Reset value for the field
Intenclr_Devmatch_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_DEVMATCH_Field_1 use
(Intenclr_Devmatch_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on DEVMISS event.
type INTENCLR_DEVMISS_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_DEVMISS_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on DEVMISS event.
type INTENCLR_DEVMISS_Field_1 is
(-- Reset value for the field
Intenclr_Devmiss_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_DEVMISS_Field_1 use
(Intenclr_Devmiss_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on RSSIEND event.
type INTENCLR_RSSIEND_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_RSSIEND_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on RSSIEND event.
type INTENCLR_RSSIEND_Field_1 is
(-- Reset value for the field
Intenclr_Rssiend_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_RSSIEND_Field_1 use
(Intenclr_Rssiend_Field_Reset => 0,
Clear => 1);
-- Disable interrupt on BCMATCH event.
type INTENCLR_BCMATCH_Field is
(-- Interrupt disabled.
Disabled,
-- Interrupt enabled.
Enabled)
with Size => 1;
for INTENCLR_BCMATCH_Field use
(Disabled => 0,
Enabled => 1);
-- Disable interrupt on BCMATCH event.
type INTENCLR_BCMATCH_Field_1 is
(-- Reset value for the field
Intenclr_Bcmatch_Field_Reset,
-- Disable interrupt on write.
Clear)
with Size => 1;
for INTENCLR_BCMATCH_Field_1 use
(Intenclr_Bcmatch_Field_Reset => 0,
Clear => 1);
-- Interrupt enable clear register.
type INTENCLR_Register is record
-- Disable interrupt on READY event.
READY : INTENCLR_READY_Field_1 := Intenclr_Ready_Field_Reset;
-- Disable interrupt on ADDRESS event.
ADDRESS : INTENCLR_ADDRESS_Field_1 :=
Intenclr_Address_Field_Reset;
-- Disable interrupt on PAYLOAD event.
PAYLOAD : INTENCLR_PAYLOAD_Field_1 :=
Intenclr_Payload_Field_Reset;
-- Disable interrupt on END event.
END_k : INTENCLR_END_Field_1 := Intenclr_End_Field_Reset;
-- Disable interrupt on DISABLED event.
DISABLED : INTENCLR_DISABLED_Field_1 :=
Intenclr_Disabled_Field_Reset;
-- Disable interrupt on DEVMATCH event.
DEVMATCH : INTENCLR_DEVMATCH_Field_1 :=
Intenclr_Devmatch_Field_Reset;
-- Disable interrupt on DEVMISS event.
DEVMISS : INTENCLR_DEVMISS_Field_1 :=
Intenclr_Devmiss_Field_Reset;
-- Disable interrupt on RSSIEND event.
RSSIEND : INTENCLR_RSSIEND_Field_1 :=
Intenclr_Rssiend_Field_Reset;
-- unspecified
Reserved_8_9 : HAL.UInt2 := 16#0#;
-- Disable interrupt on BCMATCH event.
BCMATCH : INTENCLR_BCMATCH_Field_1 :=
Intenclr_Bcmatch_Field_Reset;
-- unspecified
Reserved_11_31 : HAL.UInt21 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for INTENCLR_Register use record
READY at 0 range 0 .. 0;
ADDRESS at 0 range 1 .. 1;
PAYLOAD at 0 range 2 .. 2;
END_k at 0 range 3 .. 3;
DISABLED at 0 range 4 .. 4;
DEVMATCH at 0 range 5 .. 5;
DEVMISS at 0 range 6 .. 6;
RSSIEND at 0 range 7 .. 7;
Reserved_8_9 at 0 range 8 .. 9;
BCMATCH at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- CRC status of received packet.
type CRCSTATUS_CRCSTATUS_Field is
(-- Packet received with CRC error.
Crcerror,
-- Packet received with CRC ok.
Crcok)
with Size => 1;
for CRCSTATUS_CRCSTATUS_Field use
(Crcerror => 0,
Crcok => 1);
-- CRC status of received packet.
type CRCSTATUS_Register is record
-- Read-only. CRC status of received packet.
CRCSTATUS : CRCSTATUS_CRCSTATUS_Field;
-- unspecified
Reserved_1_31 : HAL.UInt31;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CRCSTATUS_Register use record
CRCSTATUS at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
subtype RXMATCH_RXMATCH_Field is HAL.UInt3;
-- Received address.
type RXMATCH_Register is record
-- Read-only. Logical address in which previous packet was received.
RXMATCH : RXMATCH_RXMATCH_Field;
-- unspecified
Reserved_3_31 : HAL.UInt29;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for RXMATCH_Register use record
RXMATCH at 0 range 0 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
subtype RXCRC_RXCRC_Field is HAL.UInt24;
-- Received CRC.
type RXCRC_Register is record
-- Read-only. CRC field of previously received packet.
RXCRC : RXCRC_RXCRC_Field;
-- unspecified
Reserved_24_31 : HAL.UInt8;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for RXCRC_Register use record
RXCRC at 0 range 0 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
subtype DAI_DAI_Field is HAL.UInt3;
-- Device address match index.
type DAI_Register is record
-- Read-only. Index (n) of device address (see DAB[n] and DAP[n]) that
-- obtained an address match.
DAI : DAI_DAI_Field;
-- unspecified
Reserved_3_31 : HAL.UInt29;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DAI_Register use record
DAI at 0 range 0 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
subtype FREQUENCY_FREQUENCY_Field is HAL.UInt7;
-- Frequency.
type FREQUENCY_Register is record
-- Radio channel frequency offset in MHz: RF Frequency = 2400 +
-- FREQUENCY (MHz). Decision point: TXEN or RXEN task.
FREQUENCY : FREQUENCY_FREQUENCY_Field := 16#2#;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for FREQUENCY_Register use record
FREQUENCY at 0 range 0 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- Radio output power. Decision point: TXEN task.
type TXPOWER_TXPOWER_Field is
(-- 0dBm.
Val_0DBm,
-- +4dBm.
Pos4DBm,
-- -30dBm.
Neg30DBm,
-- -20dBm.
Neg20DBm,
-- -16dBm.
Neg16DBm,
-- -12dBm.
Neg12DBm,
-- -8dBm.
Neg8DBm,
-- -4dBm.
Neg4DBm)
with Size => 8;
for TXPOWER_TXPOWER_Field use
(Val_0DBm => 0,
Pos4DBm => 4,
Neg30DBm => 216,
Neg20DBm => 236,
Neg16DBm => 240,
Neg12DBm => 244,
Neg8DBm => 248,
Neg4DBm => 252);
-- Output power.
type TXPOWER_Register is record
-- Radio output power. Decision point: TXEN task.
TXPOWER : TXPOWER_TXPOWER_Field := NRF_SVD.RADIO.Val_0DBm;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for TXPOWER_Register use record
TXPOWER at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- Radio data rate and modulation setting. Decision point: TXEN or RXEN
-- task.
type MODE_MODE_Field is
(-- 1Mbit/s Nordic propietary radio mode.
Nrf_1Mbit,
-- 2Mbit/s Nordic propietary radio mode.
Nrf_2Mbit,
-- 250kbit/s Nordic propietary radio mode.
Nrf_250Kbit,
-- 1Mbit/s Bluetooth Low Energy
Ble_1Mbit)
with Size => 2;
for MODE_MODE_Field use
(Nrf_1Mbit => 0,
Nrf_2Mbit => 1,
Nrf_250Kbit => 2,
Ble_1Mbit => 3);
-- Data rate and modulation.
type MODE_Register is record
-- Radio data rate and modulation setting. Decision point: TXEN or RXEN
-- task.
MODE : MODE_MODE_Field := NRF_SVD.RADIO.Nrf_1Mbit;
-- unspecified
Reserved_2_31 : HAL.UInt30 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for MODE_Register use record
MODE at 0 range 0 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
subtype PCNF0_LFLEN_Field is HAL.UInt4;
subtype PCNF0_S1LEN_Field is HAL.UInt4;
-- Packet configuration 0.
type PCNF0_Register is record
-- Length of length field in number of bits. Decision point: START task.
LFLEN : PCNF0_LFLEN_Field := 16#0#;
-- unspecified
Reserved_4_7 : HAL.UInt4 := 16#0#;
-- Length of S0 field in number of bytes. Decision point: START task.
S0LEN : Boolean := False;
-- unspecified
Reserved_9_15 : HAL.UInt7 := 16#0#;
-- Length of S1 field in number of bits. Decision point: START task.
S1LEN : PCNF0_S1LEN_Field := 16#0#;
-- unspecified
Reserved_20_31 : HAL.UInt12 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PCNF0_Register use record
LFLEN at 0 range 0 .. 3;
Reserved_4_7 at 0 range 4 .. 7;
S0LEN at 0 range 8 .. 8;
Reserved_9_15 at 0 range 9 .. 15;
S1LEN at 0 range 16 .. 19;
Reserved_20_31 at 0 range 20 .. 31;
end record;
subtype PCNF1_MAXLEN_Field is HAL.UInt8;
subtype PCNF1_STATLEN_Field is HAL.UInt8;
subtype PCNF1_BALEN_Field is HAL.UInt3;
-- On air endianness of packet length field. Decision point: START task.
type PCNF1_ENDIAN_Field is
(-- Least significant bit on air first
Little,
-- Most significant bit on air first
Big)
with Size => 1;
for PCNF1_ENDIAN_Field use
(Little => 0,
Big => 1);
-- Packet whitening enable.
type PCNF1_WHITEEN_Field is
(-- Whitening disabled.
Disabled,
-- Whitening enabled.
Enabled)
with Size => 1;
for PCNF1_WHITEEN_Field use
(Disabled => 0,
Enabled => 1);
-- Packet configuration 1.
type PCNF1_Register is record
-- Maximum length of packet payload in number of bytes.
MAXLEN : PCNF1_MAXLEN_Field := 16#0#;
-- Static length in number of bytes. Decision point: START task.
STATLEN : PCNF1_STATLEN_Field := 16#0#;
-- Base address length in number of bytes. Decision point: START task.
BALEN : PCNF1_BALEN_Field := 16#0#;
-- unspecified
Reserved_19_23 : HAL.UInt5 := 16#0#;
-- On air endianness of packet length field. Decision point: START task.
ENDIAN : PCNF1_ENDIAN_Field := NRF_SVD.RADIO.Little;
-- Packet whitening enable.
WHITEEN : PCNF1_WHITEEN_Field := NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_26_31 : HAL.UInt6 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PCNF1_Register use record
MAXLEN at 0 range 0 .. 7;
STATLEN at 0 range 8 .. 15;
BALEN at 0 range 16 .. 18;
Reserved_19_23 at 0 range 19 .. 23;
ENDIAN at 0 range 24 .. 24;
WHITEEN at 0 range 25 .. 25;
Reserved_26_31 at 0 range 26 .. 31;
end record;
-- PREFIX0_AP array element
subtype PREFIX0_AP_Element is HAL.UInt8;
-- PREFIX0_AP array
type PREFIX0_AP_Field_Array is array (0 .. 3) of PREFIX0_AP_Element
with Component_Size => 8, Size => 32;
-- Prefixes bytes for logical addresses 0 to 3.
type PREFIX0_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- AP as a value
Val : HAL.UInt32;
when True =>
-- AP as an array
Arr : PREFIX0_AP_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PREFIX0_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
-- PREFIX1_AP array element
subtype PREFIX1_AP_Element is HAL.UInt8;
-- PREFIX1_AP array
type PREFIX1_AP_Field_Array is array (4 .. 7) of PREFIX1_AP_Element
with Component_Size => 8, Size => 32;
-- Prefixes bytes for logical addresses 4 to 7.
type PREFIX1_Register
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- AP as a value
Val : HAL.UInt32;
when True =>
-- AP as an array
Arr : PREFIX1_AP_Field_Array;
end case;
end record
with Unchecked_Union, Size => 32, Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for PREFIX1_Register use record
Val at 0 range 0 .. 31;
Arr at 0 range 0 .. 31;
end record;
subtype TXADDRESS_TXADDRESS_Field is HAL.UInt3;
-- Transmit address select.
type TXADDRESS_Register is record
-- Logical address to be used when transmitting a packet. Decision
-- point: START task.
TXADDRESS : TXADDRESS_TXADDRESS_Field := 16#0#;
-- unspecified
Reserved_3_31 : HAL.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for TXADDRESS_Register use record
TXADDRESS at 0 range 0 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
-- Enable reception on logical address 0. Decision point: START task.
type RXADDRESSES_ADDR0_Field is
(-- Reception disabled.
Disabled,
-- Reception enabled.
Enabled)
with Size => 1;
for RXADDRESSES_ADDR0_Field use
(Disabled => 0,
Enabled => 1);
-- RXADDRESSES_ADDR array
type RXADDRESSES_ADDR_Field_Array is array (0 .. 7)
of RXADDRESSES_ADDR0_Field
with Component_Size => 1, Size => 8;
-- Type definition for RXADDRESSES_ADDR
type RXADDRESSES_ADDR_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- ADDR as a value
Val : HAL.UInt8;
when True =>
-- ADDR as an array
Arr : RXADDRESSES_ADDR_Field_Array;
end case;
end record
with Unchecked_Union, Size => 8;
for RXADDRESSES_ADDR_Field use record
Val at 0 range 0 .. 7;
Arr at 0 range 0 .. 7;
end record;
-- Receive address select.
type RXADDRESSES_Register is record
-- Enable reception on logical address 0. Decision point: START task.
ADDR : RXADDRESSES_ADDR_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for RXADDRESSES_Register use record
ADDR at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
-- CRC length. Decision point: START task.
type CRCCNF_LEN_Field is
(-- CRC calculation disabled.
Disabled,
-- One byte long CRC.
One,
-- Two bytes long CRC.
Two,
-- Three bytes long CRC.
Three)
with Size => 2;
for CRCCNF_LEN_Field use
(Disabled => 0,
One => 1,
Two => 2,
Three => 3);
-- Leave packet address field out of the CRC calculation. Decision point:
-- START task.
type CRCCNF_SKIPADDR_Field is
(-- Include packet address in CRC calculation.
Include,
-- Packet address is skipped in CRC calculation. The CRC calculation will
-- start at the first byte after the address.
Skip)
with Size => 1;
for CRCCNF_SKIPADDR_Field use
(Include => 0,
Skip => 1);
-- CRC configuration.
type CRCCNF_Register is record
-- CRC length. Decision point: START task.
LEN : CRCCNF_LEN_Field := NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_2_7 : HAL.UInt6 := 16#0#;
-- Leave packet address field out of the CRC calculation. Decision
-- point: START task.
SKIPADDR : CRCCNF_SKIPADDR_Field := NRF_SVD.RADIO.Include;
-- unspecified
Reserved_9_31 : HAL.UInt23 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CRCCNF_Register use record
LEN at 0 range 0 .. 1;
Reserved_2_7 at 0 range 2 .. 7;
SKIPADDR at 0 range 8 .. 8;
Reserved_9_31 at 0 range 9 .. 31;
end record;
subtype CRCPOLY_CRCPOLY_Field is HAL.UInt24;
-- CRC polynomial.
type CRCPOLY_Register is record
-- CRC polynomial. Decision point: START task.
CRCPOLY : CRCPOLY_CRCPOLY_Field := 16#0#;
-- unspecified
Reserved_24_31 : HAL.UInt8 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CRCPOLY_Register use record
CRCPOLY at 0 range 0 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
subtype CRCINIT_CRCINIT_Field is HAL.UInt24;
-- CRC initial value.
type CRCINIT_Register is record
-- Initial value for CRC calculation. Decision point: START task.
CRCINIT : CRCINIT_CRCINIT_Field := 16#0#;
-- unspecified
Reserved_24_31 : HAL.UInt8 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for CRCINIT_Register use record
CRCINIT at 0 range 0 .. 23;
Reserved_24_31 at 0 range 24 .. 31;
end record;
-- Constant carrier. Decision point: TXEN task.
type TEST_CONSTCARRIER_Field is
(-- Constant carrier disabled.
Disabled,
-- Constant carrier enabled.
Enabled)
with Size => 1;
for TEST_CONSTCARRIER_Field use
(Disabled => 0,
Enabled => 1);
-- PLL lock. Decision point: TXEN or RXEN task.
type TEST_PLLLOCK_Field is
(-- PLL lock disabled.
Disabled,
-- PLL lock enabled.
Enabled)
with Size => 1;
for TEST_PLLLOCK_Field use
(Disabled => 0,
Enabled => 1);
-- Test features enable register.
type TEST_Register is record
-- Constant carrier. Decision point: TXEN task.
CONSTCARRIER : TEST_CONSTCARRIER_Field := NRF_SVD.RADIO.Disabled;
-- PLL lock. Decision point: TXEN or RXEN task.
PLLLOCK : TEST_PLLLOCK_Field := NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_2_31 : HAL.UInt30 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for TEST_Register use record
CONSTCARRIER at 0 range 0 .. 0;
PLLLOCK at 0 range 1 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
subtype TIFS_TIFS_Field is HAL.UInt8;
-- Inter Frame Spacing in microseconds.
type TIFS_Register is record
-- Inter frame spacing in microseconds. Decision point: START rask
TIFS : TIFS_TIFS_Field := 16#0#;
-- unspecified
Reserved_8_31 : HAL.UInt24 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for TIFS_Register use record
TIFS at 0 range 0 .. 7;
Reserved_8_31 at 0 range 8 .. 31;
end record;
subtype RSSISAMPLE_RSSISAMPLE_Field is HAL.UInt7;
-- RSSI sample.
type RSSISAMPLE_Register is record
-- Read-only. RSSI sample result. The result is read as a positive value
-- so that ReceivedSignalStrength = -RSSISAMPLE dBm
RSSISAMPLE : RSSISAMPLE_RSSISAMPLE_Field;
-- unspecified
Reserved_7_31 : HAL.UInt25;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for RSSISAMPLE_Register use record
RSSISAMPLE at 0 range 0 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- Current radio state.
type STATE_STATE_Field is
(-- Radio is in the Disabled state.
Disabled,
-- Radio is in the Rx Ramp Up state.
Rxru,
-- Radio is in the Rx Idle state.
Rxidle,
-- Radio is in the Rx state.
Rx,
-- Radio is in the Rx Disable state.
Rxdisable,
-- Radio is in the Tx Ramp Up state.
Txru,
-- Radio is in the Tx Idle state.
Txidle,
-- Radio is in the Tx state.
Tx,
-- Radio is in the Tx Disable state.
Txdisable)
with Size => 4;
for STATE_STATE_Field use
(Disabled => 0,
Rxru => 1,
Rxidle => 2,
Rx => 3,
Rxdisable => 4,
Txru => 9,
Txidle => 10,
Tx => 11,
Txdisable => 12);
-- Current radio state.
type STATE_Register is record
-- Read-only. Current radio state.
STATE : STATE_STATE_Field;
-- unspecified
Reserved_4_31 : HAL.UInt28;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for STATE_Register use record
STATE at 0 range 0 .. 3;
Reserved_4_31 at 0 range 4 .. 31;
end record;
subtype DATAWHITEIV_DATAWHITEIV_Field is HAL.UInt7;
-- Data whitening initial value.
type DATAWHITEIV_Register is record
-- Data whitening initial value. Bit 0 corresponds to Position 0 of the
-- LSFR, Bit 1 to position 5... Decision point: TXEN or RXEN task.
DATAWHITEIV : DATAWHITEIV_DATAWHITEIV_Field := 16#40#;
-- unspecified
Reserved_7_31 : HAL.UInt25 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DATAWHITEIV_Register use record
DATAWHITEIV at 0 range 0 .. 6;
Reserved_7_31 at 0 range 7 .. 31;
end record;
-- Device address base segment.
-- Device address base segment.
type DAB_Registers is array (0 .. 7) of HAL.UInt32;
subtype DAP_DAP_Field is HAL.UInt16;
-- Device address prefix.
type DAP_Register is record
-- Device address prefix.
DAP : DAP_DAP_Field := 16#0#;
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DAP_Register use record
DAP at 0 range 0 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
-- Device address prefix.
type DAP_Registers is array (0 .. 7) of DAP_Register;
-- Enable or disable device address matching using device address 0.
type DACNF_ENA0_Field is
(-- Disabled.
Disabled,
-- Enabled.
Enabled)
with Size => 1;
for DACNF_ENA0_Field use
(Disabled => 0,
Enabled => 1);
-- DACNF_ENA array
type DACNF_ENA_Field_Array is array (0 .. 7) of DACNF_ENA0_Field
with Component_Size => 1, Size => 8;
-- Type definition for DACNF_ENA
type DACNF_ENA_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- ENA as a value
Val : HAL.UInt8;
when True =>
-- ENA as an array
Arr : DACNF_ENA_Field_Array;
end case;
end record
with Unchecked_Union, Size => 8;
for DACNF_ENA_Field use record
Val at 0 range 0 .. 7;
Arr at 0 range 0 .. 7;
end record;
-- DACNF_TXADD array
type DACNF_TXADD_Field_Array is array (0 .. 7) of Boolean
with Component_Size => 1, Size => 8;
-- Type definition for DACNF_TXADD
type DACNF_TXADD_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- TXADD as a value
Val : HAL.UInt8;
when True =>
-- TXADD as an array
Arr : DACNF_TXADD_Field_Array;
end case;
end record
with Unchecked_Union, Size => 8;
for DACNF_TXADD_Field use record
Val at 0 range 0 .. 7;
Arr at 0 range 0 .. 7;
end record;
-- Device address match configuration.
type DACNF_Register is record
-- Enable or disable device address matching using device address 0.
ENA : DACNF_ENA_Field := (As_Array => False, Val => 16#0#);
-- TxAdd for device address 0.
TXADD : DACNF_TXADD_Field := (As_Array => False, Val => 16#0#);
-- unspecified
Reserved_16_31 : HAL.UInt16 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for DACNF_Register use record
ENA at 0 range 0 .. 7;
TXADD at 0 range 8 .. 15;
Reserved_16_31 at 0 range 16 .. 31;
end record;
subtype OVERRIDE4_OVERRIDE4_Field is HAL.UInt28;
-- Enable or disable override of default trim values.
type OVERRIDE4_ENABLE_Field is
(-- Override trim values disabled.
Disabled,
-- Override trim values enabled.
Enabled)
with Size => 1;
for OVERRIDE4_ENABLE_Field use
(Disabled => 0,
Enabled => 1);
-- Trim value override register 4.
type OVERRIDE4_Register is record
-- Trim value override 4.
OVERRIDE4 : OVERRIDE4_OVERRIDE4_Field := 16#0#;
-- unspecified
Reserved_28_30 : HAL.UInt3 := 16#0#;
-- Enable or disable override of default trim values.
ENABLE : OVERRIDE4_ENABLE_Field := NRF_SVD.RADIO.Disabled;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for OVERRIDE4_Register use record
OVERRIDE4 at 0 range 0 .. 27;
Reserved_28_30 at 0 range 28 .. 30;
ENABLE at 0 range 31 .. 31;
end record;
-- Peripheral power control.
type POWER_POWER_Field is
(-- Module power disabled.
Disabled,
-- Module power enabled.
Enabled)
with Size => 1;
for POWER_POWER_Field use
(Disabled => 0,
Enabled => 1);
-- Peripheral power control.
type POWER_Register is record
-- Peripheral power control.
POWER : POWER_POWER_Field := NRF_SVD.RADIO.Disabled;
-- unspecified
Reserved_1_31 : HAL.UInt31 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for POWER_Register use record
POWER at 0 range 0 .. 0;
Reserved_1_31 at 0 range 1 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- The radio.
type RADIO_Peripheral is record
-- Enable radio in TX mode.
TASKS_TXEN : aliased HAL.UInt32;
-- Enable radio in RX mode.
TASKS_RXEN : aliased HAL.UInt32;
-- Start radio.
TASKS_START : aliased HAL.UInt32;
-- Stop radio.
TASKS_STOP : aliased HAL.UInt32;
-- Disable radio.
TASKS_DISABLE : aliased HAL.UInt32;
-- Start the RSSI and take one sample of the receive signal strength.
TASKS_RSSISTART : aliased HAL.UInt32;
-- Stop the RSSI measurement.
TASKS_RSSISTOP : aliased HAL.UInt32;
-- Start the bit counter.
TASKS_BCSTART : aliased HAL.UInt32;
-- Stop the bit counter.
TASKS_BCSTOP : aliased HAL.UInt32;
-- Ready event.
EVENTS_READY : aliased HAL.UInt32;
-- Address event.
EVENTS_ADDRESS : aliased HAL.UInt32;
-- Payload event.
EVENTS_PAYLOAD : aliased HAL.UInt32;
-- End event.
EVENTS_END : aliased HAL.UInt32;
-- Disable event.
EVENTS_DISABLED : aliased HAL.UInt32;
-- A device address match occurred on the last received packet.
EVENTS_DEVMATCH : aliased HAL.UInt32;
-- No device address match occurred on the last received packet.
EVENTS_DEVMISS : aliased HAL.UInt32;
-- Sampling of the receive signal strength complete. A new RSSI sample
-- is ready for readout at the RSSISAMPLE register.
EVENTS_RSSIEND : aliased HAL.UInt32;
-- Bit counter reached bit count value specified in BCC register.
EVENTS_BCMATCH : aliased HAL.UInt32;
-- Shortcuts for the radio.
SHORTS : aliased SHORTS_Register;
-- Interrupt enable set register.
INTENSET : aliased INTENSET_Register;
-- Interrupt enable clear register.
INTENCLR : aliased INTENCLR_Register;
-- CRC status of received packet.
CRCSTATUS : aliased CRCSTATUS_Register;
-- Received address.
RXMATCH : aliased RXMATCH_Register;
-- Received CRC.
RXCRC : aliased RXCRC_Register;
-- Device address match index.
DAI : aliased DAI_Register;
-- Packet pointer. Decision point: START task.
PACKETPTR : aliased HAL.UInt32;
-- Frequency.
FREQUENCY : aliased FREQUENCY_Register;
-- Output power.
TXPOWER : aliased TXPOWER_Register;
-- Data rate and modulation.
MODE : aliased MODE_Register;
-- Packet configuration 0.
PCNF0 : aliased PCNF0_Register;
-- Packet configuration 1.
PCNF1 : aliased PCNF1_Register;
-- Radio base address 0. Decision point: START task.
BASE0 : aliased HAL.UInt32;
-- Radio base address 1. Decision point: START task.
BASE1 : aliased HAL.UInt32;
-- Prefixes bytes for logical addresses 0 to 3.
PREFIX0 : aliased PREFIX0_Register;
-- Prefixes bytes for logical addresses 4 to 7.
PREFIX1 : aliased PREFIX1_Register;
-- Transmit address select.
TXADDRESS : aliased TXADDRESS_Register;
-- Receive address select.
RXADDRESSES : aliased RXADDRESSES_Register;
-- CRC configuration.
CRCCNF : aliased CRCCNF_Register;
-- CRC polynomial.
CRCPOLY : aliased CRCPOLY_Register;
-- CRC initial value.
CRCINIT : aliased CRCINIT_Register;
-- Test features enable register.
TEST : aliased TEST_Register;
-- Inter Frame Spacing in microseconds.
TIFS : aliased TIFS_Register;
-- RSSI sample.
RSSISAMPLE : aliased RSSISAMPLE_Register;
-- Current radio state.
STATE : aliased STATE_Register;
-- Data whitening initial value.
DATAWHITEIV : aliased DATAWHITEIV_Register;
-- Bit counter compare.
BCC : aliased HAL.UInt32;
-- Device address base segment.
DAB : aliased DAB_Registers;
-- Device address prefix.
DAP : aliased DAP_Registers;
-- Device address match configuration.
DACNF : aliased DACNF_Register;
-- Trim value override register 0.
OVERRIDE0 : aliased HAL.UInt32;
-- Trim value override register 1.
OVERRIDE1 : aliased HAL.UInt32;
-- Trim value override register 2.
OVERRIDE2 : aliased HAL.UInt32;
-- Trim value override register 3.
OVERRIDE3 : aliased HAL.UInt32;
-- Trim value override register 4.
OVERRIDE4 : aliased OVERRIDE4_Register;
-- Peripheral power control.
POWER : aliased POWER_Register;
end record
with Volatile;
for RADIO_Peripheral use record
TASKS_TXEN at 16#0# range 0 .. 31;
TASKS_RXEN at 16#4# range 0 .. 31;
TASKS_START at 16#8# range 0 .. 31;
TASKS_STOP at 16#C# range 0 .. 31;
TASKS_DISABLE at 16#10# range 0 .. 31;
TASKS_RSSISTART at 16#14# range 0 .. 31;
TASKS_RSSISTOP at 16#18# range 0 .. 31;
TASKS_BCSTART at 16#1C# range 0 .. 31;
TASKS_BCSTOP at 16#20# range 0 .. 31;
EVENTS_READY at 16#100# range 0 .. 31;
EVENTS_ADDRESS at 16#104# range 0 .. 31;
EVENTS_PAYLOAD at 16#108# range 0 .. 31;
EVENTS_END at 16#10C# range 0 .. 31;
EVENTS_DISABLED at 16#110# range 0 .. 31;
EVENTS_DEVMATCH at 16#114# range 0 .. 31;
EVENTS_DEVMISS at 16#118# range 0 .. 31;
EVENTS_RSSIEND at 16#11C# range 0 .. 31;
EVENTS_BCMATCH at 16#128# range 0 .. 31;
SHORTS at 16#200# range 0 .. 31;
INTENSET at 16#304# range 0 .. 31;
INTENCLR at 16#308# range 0 .. 31;
CRCSTATUS at 16#400# range 0 .. 31;
RXMATCH at 16#408# range 0 .. 31;
RXCRC at 16#40C# range 0 .. 31;
DAI at 16#410# range 0 .. 31;
PACKETPTR at 16#504# range 0 .. 31;
FREQUENCY at 16#508# range 0 .. 31;
TXPOWER at 16#50C# range 0 .. 31;
MODE at 16#510# range 0 .. 31;
PCNF0 at 16#514# range 0 .. 31;
PCNF1 at 16#518# range 0 .. 31;
BASE0 at 16#51C# range 0 .. 31;
BASE1 at 16#520# range 0 .. 31;
PREFIX0 at 16#524# range 0 .. 31;
PREFIX1 at 16#528# range 0 .. 31;
TXADDRESS at 16#52C# range 0 .. 31;
RXADDRESSES at 16#530# range 0 .. 31;
CRCCNF at 16#534# range 0 .. 31;
CRCPOLY at 16#538# range 0 .. 31;
CRCINIT at 16#53C# range 0 .. 31;
TEST at 16#540# range 0 .. 31;
TIFS at 16#544# range 0 .. 31;
RSSISAMPLE at 16#548# range 0 .. 31;
STATE at 16#550# range 0 .. 31;
DATAWHITEIV at 16#554# range 0 .. 31;
BCC at 16#560# range 0 .. 31;
DAB at 16#600# range 0 .. 255;
DAP at 16#620# range 0 .. 255;
DACNF at 16#640# range 0 .. 31;
OVERRIDE0 at 16#724# range 0 .. 31;
OVERRIDE1 at 16#728# range 0 .. 31;
OVERRIDE2 at 16#72C# range 0 .. 31;
OVERRIDE3 at 16#730# range 0 .. 31;
OVERRIDE4 at 16#734# range 0 .. 31;
POWER at 16#FFC# range 0 .. 31;
end record;
-- The radio.
RADIO_Periph : aliased RADIO_Peripheral
with Import, Address => RADIO_Base;
end NRF_SVD.RADIO;
|
pragma Ada_2012;
package body Protypo.Api.Engine_Values.Parameter_Lists is
function Is_Optional (Item : Parameter_Spec) return Boolean
is (Item.Class = Optional_Class);
function Default_Value (Item : Parameter_Spec) return Engine_Value
is (if Is_Optional (Item) then
Item.Default.Element
else
raise Constraint_Error);
------------
-- Create --
------------
function Create (Params : Engine_Value_Vectors.Vector) return Parameter_List
is
Result : Parameter_List;
begin
for Element of Params loop
Result.L.Append (Element);
end loop;
return Result;
end Create;
-----------
-- Shift --
-----------
function Shift (List : in out Parameter_List) return Engine_Value
is
Result : constant Engine_Value := Peek (List);
begin
List.L.Delete_First;
return Result;
end Shift;
function Image (Spec : Parameter_Spec) return String
is (case Spec.Class is
when Mandatory_Class =>
"Mandatory",
when Optional_Class =>
"Optional",
when Varargin_Class =>
"Varargin",
when Void =>
"Void");
function Image (Signature : Parameter_Signature) return String
is
Result : Unbounded_String;
begin
Result := To_Unbounded_String ("(");
for Idx in Signature'Range loop
Result := Result & Image (Signature (Idx));
if Idx < Signature'Last then
Result := Result & ", ";
end if;
end loop;
return To_String (Result & ")");
end Image;
----------------------------------
-- Is_Valid_Parameter_Signature --
----------------------------------
function Is_Valid_Parameter_Signature (Signature : Parameter_Signature)
return Boolean
is
--
-- We check this with the following finite automata
-- non-void
-- Mandatory --------------> Optional
-- || ^ || ^
-- |+--| Void |+--| Non-void
-- | |
-- | Varargin | Varargin
-- +-----------> Varargin <----+
--
-- Note that the next status is determined by the current
-- value class and that Varargin cannot go anywhere
--
Old : Parameter_Class := Mandatory_Class;
begin
--
-- A signature is valid if and only if
--
-- * Any Mandatory is preceded by another Mandatory
-- * Nothing follows Varargin
--
for Param of Signature loop
if Old = Varargin_Class then
return False;
end if;
if Param.Class = Mandatory_Class and Old /= Mandatory_Class then
return False;
end if;
Old := Param.Class;
end loop;
return True;
end Is_Valid_Parameter_Signature;
end Protypo.Api.Engine_Values.Parameter_Lists;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.