CombinedText
stringlengths 4
3.42M
|
|---|
-- Project: Strato
-- System: Stratosphere Balloon Flight Controller
-- Author: Martin Becker (becker@rcs.ei.tum.de)
-- @summary String functions
package MyStrings with SPARK_Mode is
function Is_AlNum (c : Character) return Boolean;
-- is the given character alphanumeric?
function Strip_Non_Alphanum (s : String) return String;
-- remove all non-alphanumeric characters from string
function StrChr (S : String; C : Character) return Integer with
Pre => S'Last < Natural'Last;
-- search for occurence of character in string.
-- return index in S, or S'Last + 1 if not found.
procedure StrCpySpace (outstring : out String; instring : String);
-- turn a string into a fixed-length string:
-- if too short, pad with spaces until it reaches the given length
-- if too long, then crop
function RTrim (S : String) return String;
-- remove trailing spaces
function LTrim (S : String) return String;
-- remove leading spaces
function Trim (S : String) return String;
-- remove leading and trailing spaces
end MyStrings;
|
--------------------------------------------------------------------------------
-- --
-- Copyright (C) 2004, RISC OS Ada Library (RASCAL) developers. --
-- --
-- This library is free software; you can redistribute it and/or --
-- modify it under the terms of the GNU Lesser General Public --
-- License as published by the Free Software Foundation; either --
-- version 2.1 of the License, or (at your option) any later version. --
-- --
-- This library is distributed in the hope that it will be useful, --
-- but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU --
-- Lesser General Public License for more details. --
-- --
-- You should have received a copy of the GNU Lesser General Public --
-- License along with this library; if not, write to the Free Software --
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --
-- --
--------------------------------------------------------------------------------
-- $Author$
-- $Date$
-- $Revision$
with Interfaces.C; use Interfaces.C;
with Ada.Exceptions; use Ada.Exceptions;
with RASCAL.Utility;
package body RASCAL.OS is
--
procedure Raise_Error (Error : OSError_Access) is
Nr : Integer := Utility."And"(Integer(Error.ErrNum),16#FF#);
Message : String := To_Ada(Error.ErrMess);
begin
case Nr is
when Error_Escape => Raise_Exception (Exception_Escape'Identity , Message);
when Error_Bad_mode => Raise_Exception (Exception_Bad_mode'Identity , Message);
when Error_Is_adir => Raise_Exception (Exception_Is_adir'Identity , Message);
when Error_Types_dont_match => Raise_Exception (Exception_Types_dont_match'Identity , Message);
when Error_Bad_rename => Raise_Exception (Exception_Bad_rename'Identity , Message);
when Error_Bad_copy => Raise_Exception (Exception_Bad_copy'Identity , Message);
when Error_Outside_file => Raise_Exception (Exception_Outside_file'Identity , Message);
when Error_Access_violation => Raise_Exception (Exception_Access_violation'Identity , Message);
when Error_Too_many_open_files => Raise_Exception (Exception_Too_many_open_files'Identity , Message);
when Error_Not_open_for_update => Raise_Exception (Exception_Not_open_for_update'Identity , Message);
when Error_File_open => Raise_Exception (Exception_File_open'Identity , Message);
when Error_Object_locked => Raise_Exception (Exception_Object_locked'Identity , Message);
when Error_Already_exists => Raise_Exception (Exception_Already_exists'Identity , Message);
when Error_Bad_file_name => Raise_Exception (Exception_Bad_file_name'Identity , Message);
when Error_File_not_found => Raise_Exception (Exception_File_not_found'Identity , Message);
when Error_Syntax => Raise_Exception (Exception_Syntax'Identity , Message);
when Error_Channel => Raise_Exception (Exception_Channel'Identity , Message);
when Error_End_of_file => Raise_Exception (Exception_End_of_file'Identity , Message);
when Error_Buffer_Overflow => Raise_Exception (Exception_Buffer_Overflow'Identity , Message);
when Error_Bad_filing_system_name => Raise_Exception (Exception_Bad_filing_system_name'Identity , Message);
when Error_Bad_key => Raise_Exception (Exception_Bad_key'Identity , Message);
when Error_Bad_address => Raise_Exception (Exception_Bad_address'Identity , Message);
when Error_Bad_string => Raise_Exception (Exception_Bad_string'Identity , Message);
when Error_Bad_command => Raise_Exception (Exception_Bad_command'Identity , Message);
when Error_Bad_mac_val => Raise_Exception (Exception_Bad_mac_val'Identity , Message);
when Error_Bad_var_nam => Raise_Exception (Exception_Bad_var_nam'Identity , Message);
when Error_Bad_var_type => Raise_Exception (Exception_Bad_var_type'Identity , Message);
when Error_Var_no_room => Raise_Exception (Exception_Var_no_room'Identity , Message);
when Error_Var_cant_find => Raise_Exception (Exception_Var_cant_find'Identity , Message);
when Error_Var_too_long => Raise_Exception (Exception_Var_too_long'Identity , Message);
when Error_Redirect_fail => Raise_Exception (Exception_Redirect_fail'Identity , Message);
when Error_Stack_full => Raise_Exception (Exception_Stack_full'Identity , Message);
when Error_Bad_hex => Raise_Exception (Exception_Bad_hex'Identity , Message);
when Error_Bad_expr => Raise_Exception (Exception_Bad_expr'Identity , Message);
when Error_Bad_bra => Raise_Exception (Exception_Bad_bra'Identity , Message);
when Error_Stk_oflo => Raise_Exception (Exception_Stk_oflo'Identity , Message);
when Error_Miss_opn => Raise_Exception (Exception_Miss_opn'Identity , Message);
when Error_Miss_opr => Raise_Exception (Exception_Miss_opr'Identity , Message);
when Error_Bad_bits => Raise_Exception (Exception_Bad_bits'Identity , Message);
when Error_Str_oflo => Raise_Exception (Exception_Str_oflo'Identity , Message);
when Error_Bad_itm => Raise_Exception (Exception_Bad_itm'Identity , Message);
when Error_Div_zero => Raise_Exception (Exception_Div_zero'Identity , Message);
when Error_Bad_base => Raise_Exception (Exception_Bad_base'Identity , Message);
when Error_Bad_numb => Raise_Exception (Exception_Bad_numb'Identity , Message);
when Error_Numb_too_big => Raise_Exception (Exception_Numb_too_big'Identity , Message);
when Error_Bad_claim_num => Raise_Exception (Exception_Bad_claim_num'Identity , Message);
when Error_Bad_release => Raise_Exception (Exception_Bad_release'Identity , Message);
when Error_Bad_dev_no => Raise_Exception (Exception_Bad_dev_no'Identity , Message);
when Error_Bad_dev_vec_rel => Raise_Exception (Exception_Bad_dev_vec_rel'Identity , Message);
when Error_Bad_env_number => Raise_Exception (Exception_Bad_env_number'Identity , Message);
when Error_Cant_cancel_quit => Raise_Exception (Exception_Cant_cancel_quit'Identity , Message);
when Error_Ch_dynam_cao => Raise_Exception (Exception_Ch_dynam_cao'Identity , Message);
when Error_Ch_dynam_not_all_moved => Raise_Exception (Exception_Ch_dynam_not_all_moved'Identity , Message);
when Error_Apl_wspace_in_use => Raise_Exception (Exception_Apl_wspace_in_use'Identity , Message);
when Error_Ram_fs_unchangeable => Raise_Exception (Exception_Ram_fs_unchangeable'Identity , Message);
when Error_Oscli_long_line => Raise_Exception (Exception_Oscli_long_line'Identity , Message);
when Error_Oscli_too_hard => Raise_Exception (Exception_Oscli_too_hard'Identity , Message);
when Error_Rc_exc => Raise_Exception (Exception_Rc_exc'Identity , Message);
when Error_Sys_heap_full => Raise_Exception (Exception_Sys_heap_full'Identity , Message);
when Error_Buff_overflow => Raise_Exception (Exception_Buff_overflow'Identity , Message);
when Error_Bad_time => Raise_Exception (Exception_Bad_time'Identity , Message);
when Error_No_such_swi => Raise_Exception (Exception_No_such_swi'Identity , Message);
when Error_Unimplemented => Raise_Exception (Exception_Unimplemented'Identity , Message);
when Error_Out_of_range => Raise_Exception (Exception_Out_of_range'Identity , Message);
when Error_No_oscli_specials => Raise_Exception (Exception_No_oscli_specials'Identity , Message);
when Error_Bad_parameters => Raise_Exception (Exception_Bad_parameters'Identity , Message);
when Error_Arg_repeated => Raise_Exception (Exception_Arg_repeated'Identity , Message);
when Error_Bad_read_sys_info => Raise_Exception (Exception_Bad_read_sys_info'Identity , Message);
when Error_Cdat_stack_overflow => Raise_Exception (Exception_Cdat_stack_overflow'Identity , Message);
when Error_Cdat_buffer_overflow => Raise_Exception (Exception_Cdat_buffer_overflow'Identity , Message);
when Error_Cdat_bad_field => Raise_Exception (Exception_Cdat_bad_field'Identity , Message);
when Error_Cant_start_application => Raise_Exception (Exception_Cant_start_application'Identity , Message);
when Error_Tool_Action_Out_of_Memory => Raise_Exception (Exception_Tool_Action_Out_of_Memory'Identity , Message);
when Error_Tool_Action_Cant_Create_Icon => Raise_Exception (Exception_Tool_Action_Cant_Create_Icon'Identity , Message);
when Error_Tool_Action_Cant_Create_Object => Raise_Exception (Exception_Tool_Action_Cant_Create_Object'Identity , Message);
when others => Raise_Exception(Exception_Unknown_Error'Identity,"Error: " & Utility.intstr(Nr) & " - " & Message);
end case;
end Raise_Error;
--
end RASCAL.OS;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2020, AdaCore --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- 1. Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- 2. Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- 3. Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
with NRF_SVD.ADC; use NRF_SVD.ADC;
with nRF.Tasks; use nRF.Tasks;
package body nRF.ADC is
procedure Set_Resolution (Res : Bits_Resolution);
procedure Set_Reference (Ref : Reference_Selection);
--------------------
-- Set_Resolution --
--------------------
procedure Set_Resolution (Res : Bits_Resolution) is
begin
ADC_Periph.CONFIG.RES :=
(case Res is
when 8 => Val_8BIT,
when 9 => Val_9BIT,
when 10 => Val_10BIT);
end Set_Resolution;
-------------------
-- Set_Reference --
-------------------
procedure Set_Reference (Ref : Reference_Selection) is
begin
ADC_Periph.CONFIG.EXTREFSEL := None;
case Ref is
when Internal_1V2 =>
ADC_Periph.CONFIG.REFSEL := Vbg;
when External_AREF0 =>
ADC_Periph.CONFIG.REFSEL := External;
ADC_Periph.CONFIG.EXTREFSEL := Analogreference0;
when External_AREF1 =>
ADC_Periph.CONFIG.REFSEL := External;
ADC_Periph.CONFIG.EXTREFSEL := Analogreference1;
when VDD_Half =>
ADC_Periph.CONFIG.REFSEL := Supplyonehalfprescaling;
when VDD_One_Third =>
ADC_Periph.CONFIG.REFSEL := Supplyonethirdprescaling;
end case;
end Set_Reference;
--------------------------
-- Start_Pin_Conversion --
--------------------------
procedure Start_Pin_Conversion
(Pin : Analog_Pin;
Input : Pin_Input_Selection;
Ref : Reference_Selection;
Res : Bits_Resolution)
is
begin
Set_Resolution (Res);
Set_Reference (Ref);
case Input is
when Pin_Full =>
ADC_Periph.CONFIG.INPSEL := Analoginputnoprescaling;
when Pin_Two_Third =>
ADC_Periph.CONFIG.INPSEL := Analoginputtwothirdsprescaling;
when Pin_One_Third =>
ADC_Periph.CONFIG.INPSEL := Analoginputonethirdprescaling;
end case;
case Pin is
when 0 =>
ADC_Periph.CONFIG.PSEL := Analoginput0;
when 1 =>
ADC_Periph.CONFIG.PSEL := Analoginput1;
when 2 =>
ADC_Periph.CONFIG.PSEL := Analoginput2;
when 3 =>
ADC_Periph.CONFIG.PSEL := Analoginput3;
when 4 =>
ADC_Periph.CONFIG.PSEL := Analoginput4;
when 5 =>
ADC_Periph.CONFIG.PSEL := Analoginput5;
when 6 =>
ADC_Periph.CONFIG.PSEL := Analoginput6;
when 7 =>
ADC_Periph.CONFIG.PSEL := Analoginput7;
end case;
ADC_Periph.ENABLE.ENABLE := Enabled;
Trigger (ADC_START);
end Start_Pin_Conversion;
--------------------------
-- Start_VDD_Conversion --
--------------------------
procedure Start_VDD_Conversion
(Input : VDD_Input_Selection;
Ref : Reference_Selection;
Res : Bits_Resolution)
is
begin
Set_Resolution (Res);
Set_Reference (Ref);
ADC_Periph.CONFIG.PSEL := Disabled;
case Input is
when VDD_Two_Third =>
ADC_Periph.CONFIG.INPSEL := Supplytwothirdsprescaling;
when VDD_One_Third =>
ADC_Periph.CONFIG.INPSEL := Supplyonethirdprescaling;
end case;
ADC_Periph.ENABLE.ENABLE := Enabled;
Trigger (ADC_START);
end Start_VDD_Conversion;
----------
-- Busy --
----------
function Busy return Boolean
is (ADC_Periph.BUSY.BUSY = Busy);
---------------------
-- Wait_For_Result --
---------------------
function Wait_For_Result return UInt10 is
begin
while ADC_Periph.BUSY.BUSY = Busy loop
null;
end loop;
ADC_Periph.ENABLE.ENABLE := Enabled;
return ADC_Periph.RESULT.RESULT;
end Wait_For_Result;
end nRF.ADC;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . S T R I N G S . W I D E _ W I D E _ M A P S --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2006, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Finalization;
package Ada.Strings.Wide_Wide_Maps is
pragma Preelaborate;
------------------------------------------
-- Wide_Wide_Character Set Declarations --
------------------------------------------
type Wide_Wide_Character_Set is private;
-- Representation for a set of Wide_Wide_Character values:
Null_Set : constant Wide_Wide_Character_Set;
-----------------------------------------------
-- Constructors for Wide_Wide_Character Sets --
-----------------------------------------------
type Wide_Wide_Character_Range is record
Low : Wide_Wide_Character;
High : Wide_Wide_Character;
end record;
-- Represents Wide_Wide_Character range Low .. High
type Wide_Wide_Character_Ranges is
array (Positive range <>) of Wide_Wide_Character_Range;
function To_Set
(Ranges : Wide_Wide_Character_Ranges) return Wide_Wide_Character_Set;
function To_Set
(Span : Wide_Wide_Character_Range) return Wide_Wide_Character_Set;
function To_Ranges
(Set : Wide_Wide_Character_Set) return Wide_Wide_Character_Ranges;
---------------------------------------
-- Operations on Wide Character Sets --
---------------------------------------
function "=" (Left, Right : Wide_Wide_Character_Set) return Boolean;
function "not"
(Right : Wide_Wide_Character_Set) return Wide_Wide_Character_Set;
function "and"
(Left, Right : Wide_Wide_Character_Set) return Wide_Wide_Character_Set;
function "or"
(Left, Right : Wide_Wide_Character_Set) return Wide_Wide_Character_Set;
function "xor"
(Left, Right : Wide_Wide_Character_Set) return Wide_Wide_Character_Set;
function "-"
(Left, Right : Wide_Wide_Character_Set) return Wide_Wide_Character_Set;
function Is_In
(Element : Wide_Wide_Character;
Set : Wide_Wide_Character_Set) return Boolean;
function Is_Subset
(Elements : Wide_Wide_Character_Set;
Set : Wide_Wide_Character_Set) return Boolean;
function "<="
(Left : Wide_Wide_Character_Set;
Right : Wide_Wide_Character_Set) return Boolean
renames Is_Subset;
subtype Wide_Wide_Character_Sequence is Wide_Wide_String;
-- Alternative representation for a set of character values
function To_Set
(Sequence : Wide_Wide_Character_Sequence) return Wide_Wide_Character_Set;
function To_Set
(Singleton : Wide_Wide_Character) return Wide_Wide_Character_Set;
function To_Sequence
(Set : Wide_Wide_Character_Set) return Wide_Wide_Character_Sequence;
----------------------------------------------
-- Wide_Wide_Character Mapping Declarations --
----------------------------------------------
type Wide_Wide_Character_Mapping is private;
-- Representation for a wide character to wide character mapping:
function Value
(Map : Wide_Wide_Character_Mapping;
Element : Wide_Wide_Character) return Wide_Wide_Character;
Identity : constant Wide_Wide_Character_Mapping;
--------------------------------------
-- Operations on Wide Wide Mappings --
---------------------------------------
function To_Mapping
(From, To : Wide_Wide_Character_Sequence)
return Wide_Wide_Character_Mapping;
function To_Domain
(Map : Wide_Wide_Character_Mapping) return Wide_Wide_Character_Sequence;
function To_Range
(Map : Wide_Wide_Character_Mapping) return Wide_Wide_Character_Sequence;
type Wide_Wide_Character_Mapping_Function is
access function (From : Wide_Wide_Character) return Wide_Wide_Character;
private
package AF renames Ada.Finalization;
-----------------------------------------------
-- Representation of Wide_Wide_Character_Set --
-----------------------------------------------
-- A wide character set is represented as a sequence of wide character
-- ranges (i.e. an object of type Wide_Wide_Character_Ranges) in which the
-- following hold:
-- The lower bound is 1
-- The ranges are in order by increasing Low values
-- The ranges are non-overlapping and discontigous
-- A character value is in the set if it is contained in one of the
-- ranges. The actual Wide_Wide_Character_Set value is a controlled pointer
-- to this Wide_Wide_Character_Ranges value. The use of a controlled type
-- is necessary to prevent storage leaks.
type Wide_Wide_Character_Ranges_Access is
access all Wide_Wide_Character_Ranges;
type Wide_Wide_Character_Set is new AF.Controlled with record
Set : Wide_Wide_Character_Ranges_Access;
end record;
pragma Finalize_Storage_Only (Wide_Wide_Character_Set);
-- This avoids useless finalizations, and, more importantly avoids
-- incorrect attempts to finalize constants that are statically
-- declared here and in Ada.Strings.Wide_Wide_Maps, which is incorrect.
procedure Initialize (Object : in out Wide_Wide_Character_Set);
procedure Adjust (Object : in out Wide_Wide_Character_Set);
procedure Finalize (Object : in out Wide_Wide_Character_Set);
Null_Range : aliased constant Wide_Wide_Character_Ranges :=
(1 .. 0 => (Low => ' ', High => ' '));
Null_Set : constant Wide_Wide_Character_Set :=
(AF.Controlled with
Set => Null_Range'Unrestricted_Access);
---------------------------------------------------
-- Representation of Wide_Wide_Character_Mapping --
---------------------------------------------------
-- A wide character mapping is represented as two strings of equal
-- length, where any character appearing in Domain is mapped to the
-- corresponding character in Rangev. A character not appearing in
-- Domain is mapped to itself. The characters in Domain are sorted
-- in ascending order.
-- The actual Wide_Wide_Character_Mapping value is a controlled record
-- that contains a pointer to a discriminated record containing the
-- range and domain values.
-- Note: this representation is canonical, and the values stored in
-- Domain and Rangev are exactly the values that are returned by the
-- functions To_Domain and To_Range. The use of a controlled type is
-- necessary to prevent storage leaks.
type Wide_Wide_Character_Mapping_Values (Length : Natural) is record
Domain : Wide_Wide_Character_Sequence (1 .. Length);
Rangev : Wide_Wide_Character_Sequence (1 .. Length);
end record;
type Wide_Wide_Character_Mapping_Values_Access is
access all Wide_Wide_Character_Mapping_Values;
type Wide_Wide_Character_Mapping is new AF.Controlled with record
Map : Wide_Wide_Character_Mapping_Values_Access;
end record;
pragma Finalize_Storage_Only (Wide_Wide_Character_Mapping);
-- This avoids useless finalizations, and, more importantly avoids
-- incorrect attempts to finalize constants that are statically
-- declared here and in Ada.Strings.Wide_Wide_Maps, which is incorrect.
procedure Initialize (Object : in out Wide_Wide_Character_Mapping);
procedure Adjust (Object : in out Wide_Wide_Character_Mapping);
procedure Finalize (Object : in out Wide_Wide_Character_Mapping);
Null_Map : aliased constant Wide_Wide_Character_Mapping_Values :=
(Length => 0,
Domain => "",
Rangev => "");
Identity : constant Wide_Wide_Character_Mapping :=
(AF.Controlled with
Map => Null_Map'Unrestricted_Access);
end Ada.Strings.Wide_Wide_Maps;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2012 Felix Krause <contact@flyx.org>
--
-- 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;
with Orka;
package GL is
pragma Pure;
package C renames Interfaces.C;
-- Index types for vectors and matrices
subtype Index_Homogeneous is Orka.Index_Homogeneous;
subtype Index_2D is Orka.Index_2D;
subtype Index_3D is Orka.Index_3D;
use all type Orka.Integer_32;
use all type Orka.Integer_64;
use all type Orka.Float_32;
use all type Orka.Float_64;
use all type Index_Homogeneous;
Feature_Not_Supported_Exception : exception;
-- Raised when a function that is not available for the current
-- context is called
end GL;
|
--
-- Copyright (C) 2017 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.
--
private package HW.GFX.GMA.PLLs
with
Abstract_State => (State with Part_Of => GMA.State)
is
-- Broxton DDI PHY PLLs are tied to the port.
-- So the allocation will be a stub.
-- XXX: Types should be private (but that triggers a bug in SPARK GPL 2016)
type T is (Invalid_PLL, DPLL_A, DPLL_B, DPLL_C);
Invalid : constant T := Invalid_PLL;
procedure Initialize is null
with
Global => (Output => State);
procedure Alloc
(Port_Cfg : in Port_Config;
PLL : out T;
Success : out Boolean);
procedure Free (PLL : T);
procedure All_Off;
-- Just an interface stub since PLLs are tied to the port.
type Word_Array is array (T) of Word32;
Register_Value : constant Word_Array := (others => 0);
end HW.GFX.GMA.PLLs;
|
-- Copyright 2019 Michael Casadevall <michael@casadevall.pro>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to
-- deal in the Software without restriction, including without limitation the
-- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
-- sell copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-- DEALINGS IN THE SOFTWARE.
with Ada.Unchecked_Conversion;
with System;
package body DNSCatcher.DNS.Processor.RData.Utils is
function Decode_DNS_IPv4_Address
(Parsed_RR : Parsed_DNS_Resource_Record)
return Unbounded_String
is
type Raw_IPv4_Components is record
A : Unsigned_8;
B : Unsigned_8;
C : Unsigned_8;
D : Unsigned_8;
end record;
pragma Pack (Raw_IPv4_Components);
for Raw_IPv4_Components'Bit_Order use System.High_Order_First;
for Raw_IPv4_Components'Scalar_Storage_Order use System.High_Order_First;
IPv4_Components : Raw_IPv4_Components;
ASCII_IPv4 : Unbounded_String;
function To_IPv4_Components is new Ada.Unchecked_Conversion
(Source => String, Target => Raw_IPv4_Components);
begin
IPv4_Components :=
To_IPv4_Components (To_String (Parsed_RR.RData) (1 .. 4));
ASCII_IPv4 :=
ASCII_IPv4 & IPv4_Components.A'Image & IPv4_Components.B'Image &
IPv4_Components.C'Image & IPv4_Components.D'Image;
return ASCII_IPv4;
end Decode_DNS_IPv4_Address;
end DNSCatcher.DNS.Processor.RData.Utils;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Elements.Generic_Hash;
function AMF.UML.Link_Actions.Hash is
new AMF.Elements.Generic_Hash (UML_Link_Action, UML_Link_Action_Access);
|
------------------------------------------------------------------------------
-- --
-- THIS IS AN AUTOMATICALLY GENERATED FILE! DO NOT EDIT! --
-- --
-- WAVEFILES --
-- --
-- Test application --
-- --
-- The MIT License (MIT) --
-- --
-- Copyright (c) 2020 Gustavo A. Hoffmann --
-- --
-- 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. --
------------------------------------------------------------------------------
generic
type PCM_Sample is digits <>;
type PCM_MC_Sample is array (Positive range <>) of PCM_Sample;
package Generic_Float_PCM_Buffer_Ops is
function "+" (PCM_Ref : PCM_MC_Sample;
PCM_DUT : PCM_MC_Sample)
return PCM_MC_Sample;
function "-" (PCM_Ref : PCM_MC_Sample;
PCM_DUT : PCM_MC_Sample)
return PCM_MC_Sample;
end Generic_Float_PCM_Buffer_Ops;
|
pragma License (Unrestricted);
-- implementation unit specialized for FreeBSD
with System.Long_Long_Complex_Types;
package System.Long_Long_Complex_Elementary_Functions is
pragma Pure;
-- Complex
subtype Imaginary is Long_Long_Complex_Types.Imaginary;
subtype Complex is Long_Long_Complex_Types.Complex;
function Fast_Log (X : Complex) return Complex;
pragma Inline (Fast_Log);
function Fast_Exp (X : Complex) return Complex;
function Fast_Exp (X : Imaginary) return Complex;
pragma Inline (Fast_Exp);
function Fast_Pow (Left, Right : Complex) return Complex;
pragma Inline (Fast_Pow);
function Fast_Sin (X : Complex) return Complex;
pragma Inline (Fast_Sin);
function Fast_Cos (X : Complex) return Complex;
pragma Inline (Fast_Cos);
function Fast_Tan (X : Complex) return Complex;
pragma Inline (Fast_Tan);
function Fast_Arcsin (X : Complex) return Complex;
pragma Inline (Fast_Arcsin);
function Fast_Arccos (X : Complex) return Complex;
pragma Inline (Fast_Arccos);
function Fast_Arctan (X : Complex) return Complex;
pragma Inline (Fast_Arctan);
function Fast_Sinh (X : Complex) return Complex;
pragma Inline (Fast_Sinh);
function Fast_Cosh (X : Complex) return Complex;
pragma Inline (Fast_Cosh);
function Fast_Tanh (X : Complex) return Complex;
pragma Inline (Fast_Tanh);
function Fast_Arcsinh (X : Complex) return Complex;
pragma Inline (Fast_Arcsinh);
function Fast_Arccosh (X : Complex) return Complex;
pragma Inline (Fast_Arccosh);
function Fast_Arctanh (X : Complex) return Complex;
pragma Inline (Fast_Arctanh);
-- Long_Complex
subtype Long_Imaginary is Long_Long_Complex_Types.Long_Imaginary;
subtype Long_Complex is Long_Long_Complex_Types.Long_Complex;
function Fast_Log (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Log);
function Fast_Exp (X : Long_Complex) return Long_Complex;
function Fast_Exp (X : Long_Imaginary) return Long_Complex;
pragma Inline (Fast_Exp);
function Fast_Pow (Left, Right : Long_Complex) return Long_Complex;
pragma Inline (Fast_Pow);
function Fast_Sin (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Sin);
function Fast_Cos (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Cos);
function Fast_Tan (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Tan);
function Fast_Arcsin (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arcsin);
function Fast_Arccos (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arccos);
function Fast_Arctan (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arctan);
function Fast_Sinh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Sinh);
function Fast_Cosh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Cosh);
function Fast_Tanh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Tanh);
function Fast_Arcsinh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arcsinh);
function Fast_Arccosh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arccosh);
function Fast_Arctanh (X : Long_Complex) return Long_Complex;
pragma Inline (Fast_Arctanh);
-- Long_Long_Complex
subtype Long_Long_Imaginary is Long_Long_Complex_Types.Long_Long_Imaginary;
subtype Long_Long_Complex is Long_Long_Complex_Types.Long_Long_Complex;
function csqrtl (x : Long_Long_Complex) return Long_Long_Complex
with Import,
Convention => Intrinsic, External_Name => "__builtin_csqrtl";
function Fast_Sqrt (X : Long_Long_Complex) return Long_Long_Complex
renames csqrtl;
function Fast_Log (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Exp (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Exp (X : Long_Long_Imaginary) return Long_Long_Complex;
function Fast_Pow (Left, Right : Long_Long_Complex)
return Long_Long_Complex;
function Fast_Sin (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Cos (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Tan (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arcsin (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arccos (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arctan (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Sinh (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Cosh (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Tanh (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arcsinh (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arccosh (X : Long_Long_Complex) return Long_Long_Complex;
function Fast_Arctanh (X : Long_Long_Complex) return Long_Long_Complex;
end System.Long_Long_Complex_Elementary_Functions;
|
-----------------------------------------------------------------------
-- awa-sysadmin-modules -- Module sysadmin
-- Copyright (C) 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with AWA.Applications;
with AWA.Modules.Get;
with AWA.Modules.Beans;
with AWA.Sysadmin.Models;
with Util.Log.Loggers;
with ADO.Sessions;
with ADO.Statements;
with ADO.Queries;
with ADO.Utils.Serialize;
with Servlet.Rest;
with Swagger.Servers.Operation;
with AWA.Sysadmin.Beans;
package body AWA.Sysadmin.Modules is
Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Awa.Sysadmin.Module");
package Register is new AWA.Modules.Beans (Module => Sysadmin_Module,
Module_Access => Sysadmin_Module_Access);
procedure List_Users
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type);
package API_List_Users is
new Swagger.Servers.Operation (Handler => List_Users,
Method => Swagger.Servers.GET,
URI => "/sysadmin/api/v1/users");
procedure List_Users
(Req : in out Swagger.Servers.Request'Class;
Reply : in out Swagger.Servers.Response'Class;
Stream : in out Swagger.Servers.Output_Stream'Class;
Context : in out Swagger.Servers.Context_Type) is
pragma Unreferenced (Req, Reply);
Module : constant Sysadmin_Module_Access := Get_Sysadmin_Module;
Session : constant ADO.Sessions.Session := Module.Get_Session;
Query : ADO.Queries.Context;
Stmt : ADO.Statements.Query_Statement;
begin
Log.Info ("List users");
Query.Set_Query (AWA.Sysadmin.Models.Query_Sysadmin_User_List);
Stmt := Session.Create_Statement (Query);
Stmt.Execute;
Stream.Start_Document;
ADO.Utils.Serialize.Write_Query (Stream, "", Stmt);
Stream.End_Document;
Context.Set_Status (200);
end List_Users;
-- ------------------------------
-- Initialize the sysadmin module.
-- ------------------------------
overriding
procedure Initialize (Plugin : in out Sysadmin_Module;
App : in AWA.Modules.Application_Access;
Props : in ASF.Applications.Config) is
begin
Log.Info ("Initializing the sysadmin module");
App.Add_Servlet ("sysadmin", Plugin.API_Servlet'Unchecked_Access);
App.Add_Filter ("sysadmin-filter", Plugin.API_Filter'Unchecked_Access);
Register.Register (Plugin => Plugin,
Name => "AWA.Sysadmin.Beans.Authenticate_Bean",
Handler => AWA.Sysadmin.Beans.Create_Authenticate_Bean'Access);
App.Add_Mapping (Name => "sysadmin", Pattern => "/sysadmin/api/*");
AWA.Modules.Module (Plugin).Initialize (App, Props);
Servlet.Rest.Register (App.all, API_List_Users.Definition);
end Initialize;
-- ------------------------------
-- Get the sysadmin module.
-- ------------------------------
function Get_Sysadmin_Module return Sysadmin_Module_Access is
function Get is new AWA.Modules.Get (Sysadmin_Module, Sysadmin_Module_Access, NAME);
begin
return Get;
end Get_Sysadmin_Module;
end AWA.Sysadmin.Modules;
|
pragma Style_Checks (Off);
-- This spec has been automatically generated from ATSAMD51G19A.svd
pragma Restrictions (No_Elaboration_Code);
with HAL;
with System;
package SAM_SVD.HMATRIXB is
pragma Preelaborate;
---------------
-- Registers --
---------------
--------------------------------------
-- HMATRIXB_PRS cluster's Registers --
--------------------------------------
type HMATRIXB_PRS_Cluster is record
-- Priority A for Slave
PRAS : aliased HAL.UInt32;
-- Priority B for Slave
PRBS : aliased HAL.UInt32;
end record
with Size => 64;
for HMATRIXB_PRS_Cluster use record
PRAS at 16#0# range 0 .. 31;
PRBS at 16#4# range 0 .. 31;
end record;
type HMATRIXB_PRS_Clusters is array (0 .. 15) of HMATRIXB_PRS_Cluster;
-----------------
-- Peripherals --
-----------------
-- HSB Matrix
type HMATRIX_Peripheral is record
HMATRIXB_PRS : aliased HMATRIXB_PRS_Clusters;
end record
with Volatile;
for HMATRIX_Peripheral use record
HMATRIXB_PRS at 16#80# range 0 .. 1023;
end record;
-- HSB Matrix
HMATRIX_Periph : aliased HMATRIX_Peripheral
with Import, Address => HMATRIX_Base;
end SAM_SVD.HMATRIXB;
|
--C37404B.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT 'CONSTRAINED IS FALSE FOR VARIABLES THAT HAVE
-- DISCRIMINANTS WITH DEFAULT VALUES.
-- HISTORY:
-- LDC 06/08/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C37404B IS
SUBTYPE INT IS INTEGER RANGE 1 .. 10;
TYPE REC_DEF(A : INT := 5) IS
RECORD
I : INT := 1;
END RECORD;
SUBTYPE REC_DEF_SUB IS REC_DEF;
TYPE REC_DEF_ARR IS ARRAY (INTEGER RANGE -8..7) OF REC_DEF;
TYPE REC_DEF_SARR IS ARRAY (INTEGER RANGE -8..7) OF REC_DEF_SUB;
PACKAGE PRI_PACK IS
TYPE REC_DEF_PRI(A : INTEGER := 5) IS PRIVATE;
TYPE REC_DEF_LIM_PRI(A : INTEGER := 5) IS LIMITED PRIVATE;
PRIVATE
TYPE REC_DEF_PRI(A : INTEGER := 5) IS
RECORD
I : INTEGER := 1;
END RECORD;
TYPE REC_DEF_LIM_PRI(A : INTEGER := 5) IS
RECORD
I : INTEGER := 1;
END RECORD;
END PRI_PACK;
USE PRI_PACK;
A : REC_DEF;
B : REC_DEF_SUB;
C : ARRAY (0..15) OF REC_DEF;
D : ARRAY (0..15) OF REC_DEF_SUB;
E : REC_DEF_ARR;
F : REC_DEF_SARR;
G : REC_DEF_PRI;
H : REC_DEF_LIM_PRI;
Z : REC_DEF;
PROCEDURE SUBPROG(REC : OUT REC_DEF) IS
BEGIN
IF REC'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR SUBPROGRAM OUT " &
"PARAMETER INSIDE THE SUBPROGRAM");
END IF;
END SUBPROG;
BEGIN
TEST("C37404B", "CHECK THAT 'CONSTRAINED IS FALSE FOR VARIABLES" &
" THAT HAVE DISCRIMINANTS WITH DEFAULT VALUES.");
IF A'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR RECORD COMPONENT");
END IF;
IF B'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR SUBTYPE");
END IF;
IF C(1)'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR ARRAY TYPE");
END IF;
IF D(1)'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR ARRAY OF SUBTYPE");
END IF;
IF E(1)'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR ARRAY TYPE");
END IF;
IF F(1)'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR ARRAY OF SUBTYPE");
END IF;
IF G'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR PRIVATE TYPE");
END IF;
IF H'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR LIMITED PRIVATE TYPE");
END IF;
SUBPROG(Z);
IF Z'CONSTRAINED THEN
FAILED("'CONSTRAINED TRUE FOR SUBPROGRAM OUT PARAMETER " &
"AFTER THE CALL");
END IF;
IF IDENT_INT(A.I) /= 1 OR
IDENT_INT(B.I) /= 1 OR
IDENT_INT(C(1).I) /= 1 OR
IDENT_INT(D(1).I) /= 1 OR
IDENT_INT(E(1).I) /= 1 OR
IDENT_INT(F(1).I) /= 1 OR
IDENT_INT(Z.I) /= 1 OR
IDENT_INT(A.A) /= 5 OR
IDENT_INT(B.A) /= 5 OR
IDENT_INT(C(1).A) /= 5 OR
IDENT_INT(D(1).A) /= 5 OR
IDENT_INT(E(1).A) /= 5 OR
IDENT_INT(F(1).A) /= 5 OR
IDENT_INT(G.A) /= 5 OR
IDENT_INT(H.A) /= 5 OR
IDENT_INT(Z.A) /= 5 THEN
FAILED("INCORRECT INITIALIZATION VALUES");
END IF;
RESULT;
END C37404B;
|
------------------------------------------------------------------------------
-- --
-- Command Line Interface Toolkit --
-- --
-- ------------------------------------------------------------------------ --
-- --
-- Copyright (C) 2019-2020, ANNEXI-STRAYLINE Trans-Human Ltd. --
-- All rights reserved. --
-- --
-- Original Contributors: --
-- * Ensi Martini (ANNEXI-STRAYLINE) --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions are --
-- met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in --
-- the documentation and/or other materials provided with the --
-- distribution. --
-- --
-- * Neither the name of the copyright holder nor the names of its --
-- contributors may be used to endorse or promote products derived --
-- from this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A --
-- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT --
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, --
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY --
-- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT --
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE --
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
package CLI is
-- Note: CLI is line-oriented. Any widgets updated after New_Line will
-- be rendered on the new line
type Text_Style is private;
function "+" (Left, Right : Text_Style) return Text_Style;
-- This operator works like an "overwrite"
-- Will keep any attributes of Left, adding to it the attributes of Right
-- that it does not currently have
-- NOTE: The color for the new Text_Style will always be the same as the
-- color of the Right cursor, so if a user wishes to make a cursor that is
-- the same as their current one, just with a different color, they should
-- use: New_Style : Text_Style := Current_Style + New_Desired_Color_Style
-- NOT the other way around
function "-" (Left, Right : Text_Style) return Text_Style;
-- This operator works like a "clear" for all attributes that appear in both
-- Will retain all Left attributes that are not in Right cursor
-- NOTE: The color for the new Text_Style will always be the same as the
-- color of the Left cursor, because this is the one we are subtracting from
-- With the preceding two operators and the following presets, any style
-- and color combination cursor can be made
-- COLOR PRESET CURSORS --
Neutral : constant Text_Style;
-- Follow the text-style set from prior output
-- Foreground Colors --
Black_FG : constant Text_Style;
Red_FG : constant Text_Style;
Green_FG : constant Text_Style;
Yellow_FG : constant Text_Style;
Blue_FG : constant Text_Style;
Magenta_FG : constant Text_Style;
Cyan_FG : constant Text_Style;
White_FG : constant Text_Style;
-- Background Colors --
Black_BG : constant Text_Style;
Red_BG : constant Text_Style;
Green_BG : constant Text_Style;
Yellow_BG : constant Text_Style;
Blue_BG : constant Text_Style;
Magenta_BG : constant Text_Style;
Cyan_BG : constant Text_Style;
White_BG : constant Text_Style;
-- ATTRIBUTE PRESET CURSORS --
Bold : constant Text_Style;
Underline : constant Text_Style;
Blink : constant Text_Style;
Reverse_Vid : constant Text_Style;
function Terminal_Width return Positive;
-- Width of the terminal in columns. If the output is not a terminal,
-- a value of 80 is always returned
procedure Set_Column (Col: in Positive);
function Current_Column return Positive;
-- Sets or returns the current column number of the cursor.
procedure Clear_Screen;
procedure Clear_Line;
procedure Clear_To_End;
-- Note: all Wide_Wide_Strings/Characters are encoded in UTF-8 prior to
-- output
procedure Put (Char : in Character;
Style: in Text_Style := Neutral);
procedure Put (Message: in String;
Style : in Text_Style := Neutral);
procedure Wide_Wide_Put (Char : in Wide_Wide_Character;
Style: in Text_Style := Neutral);
procedure Wide_Wide_Put (Message: in Wide_Wide_String;
Style : in Text_Style := Neutral);
procedure Put_At (Char : in Character;
Column : in Positive;
Style : in Text_Style := Neutral);
procedure Put_At (Message: in String;
Column : in Positive;
Style : in Text_Style := Neutral);
procedure Wide_Wide_Put_At (Char : in Wide_Wide_Character;
Column: in Positive;
Style : in Text_Style := Neutral);
procedure Wide_Wide_Put_At (Message: in Wide_Wide_String;
Column : in Positive;
Style : in Text_Style := Neutral);
-- Put_At opeartions do not change the cursor position
procedure Put_Line (Message: String;
Style : Text_Style := Neutral);
procedure Wide_Wide_Put_Line (Message: Wide_Wide_String;
Style : Text_Style := Neutral);
procedure New_Line;
procedure Get (Item: out String);
procedure Get (Item: out Character);
procedure Get_Line (Item: out String; Last: out Natural);
procedure Get_Immediate (Item: out Character; Available: out Boolean);
function Output_Is_Terminal return Boolean;
-- True if Standard_Output is a terminal, and False otherwise.
-- If False, all ANSI code output is supressed.
--
-- The use should avoid using widgets if Is_TTY is False
private
-- Clears to the end of the line from the current column
type Color is (Black,
Red,
Green,
Yellow,
Blue,
Magenta,
Cyan,
White,
Default);
type Text_Style is
record
Bold : Boolean := False;
Underscore : Boolean := False;
Blink : Boolean := False;
Reverse_Vid : Boolean := False;
Concealed : Boolean := False;
Foreground : Color := Default;
Background : Color := Default;
end record;
Neutral : constant Text_Style := (others => <>);
Black_FG : constant Text_Style := (Foreground => Black, others => <>);
Red_FG : constant Text_Style := (Foreground => Red, others => <>);
Green_FG : constant Text_Style := (Foreground => Green, others => <>);
Yellow_FG : constant Text_Style := (Foreground => Yellow, others => <>);
Blue_FG : constant Text_Style := (Foreground => Blue, others => <>);
Magenta_FG : constant Text_Style := (Foreground => Magenta, others => <>);
Cyan_FG : constant Text_Style := (Foreground => Cyan, others => <>);
White_FG : constant Text_Style := (Foreground => White, others => <>);
Black_BG : constant Text_Style := (Background => Black, others => <>);
Red_BG : constant Text_Style := (Background => Red, others => <>);
Green_BG : constant Text_Style := (Background => Green, others => <>);
Yellow_BG : constant Text_Style := (Background => Yellow, others => <>);
Blue_BG : constant Text_Style := (Background => Blue, others => <>);
Magenta_BG : constant Text_Style := (Background => Magenta, others => <>);
Cyan_BG : constant Text_Style := (Background => Cyan, others => <>);
White_BG : constant Text_Style := (Background => White, others => <>);
Bold : constant Text_Style := (Bold => True, others => <>);
Underline : constant Text_Style := (Underscore => True, others => <>);
Blink : constant Text_Style := (Blink => True, others => <>);
Reverse_Vid: constant Text_Style := (Reverse_Vid => True, others => <>);
procedure Apply_Style (Style: Text_Style);
procedure Clear_Style;
end CLI;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M . O S _ I N T E R F A C E --
-- --
-- B o d y --
-- --
-- Copyright (C) 1991-2005 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 2, or (at your option) any later ver- --
-- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNARL; see file COPYING. If not, write --
-- to the Free Software Foundation, 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. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. It is --
-- now maintained by Ada Core Technologies Inc. in cooperation with Florida --
-- State University (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This is the FreeBSD THREADS version of this package
with Interfaces.C; use Interfaces.C;
package body System.OS_Interface is
function Errno return int is
type int_ptr is access all int;
function internal_errno return int_ptr;
pragma Import (C, internal_errno, "__error");
begin
return (internal_errno.all);
end Errno;
function Get_Stack_Base (thread : pthread_t) return Address is
pragma Unreferenced (thread);
begin
return (0);
end Get_Stack_Base;
procedure pthread_init is
begin
null;
end pthread_init;
-----------------
-- To_Duration --
-----------------
function To_Duration (TS : timespec) return Duration is
begin
return Duration (TS.ts_sec) + Duration (TS.ts_nsec) / 10#1#E9;
end To_Duration;
-----------------
-- To_Timespec --
-----------------
function To_Timespec (D : Duration) return timespec is
S : time_t;
F : Duration;
begin
S := time_t (Long_Long_Integer (D));
F := D - Duration (S);
-- If F has negative value due to a round-up, adjust for positive F
-- value.
if F < 0.0 then S := S - 1; F := F + 1.0; end if;
return timespec'(ts_sec => S,
ts_nsec => long (Long_Long_Integer (F * 10#1#E9)));
end To_Timespec;
function To_Duration (TV : struct_timeval) return Duration is
begin
return Duration (TV.tv_sec) + Duration (TV.tv_usec) / 10#1#E6;
end To_Duration;
function To_Timeval (D : Duration) return struct_timeval is
S : long;
F : Duration;
begin
S := long (Long_Long_Integer (D));
F := D - Duration (S);
-- If F has negative value due to a round-up, adjust for positive F
-- value.
if F < 0.0 then S := S - 1; F := F + 1.0; end if;
return struct_timeval'(tv_sec => S,
tv_usec => long (Long_Long_Integer (F * 10#1#E6)));
end To_Timeval;
end System.OS_Interface;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011-2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
with AMF.Elements.Generic_Hash;
function AMF.UML.Template_Signatures.Hash is
new AMF.Elements.Generic_Hash (UML_Template_Signature, UML_Template_Signature_Access);
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ E L A B --
-- --
-- B o d y --
-- --
-- Copyright (C) 1997-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 ALI; use ALI;
with Atree; use Atree;
with Checks; use Checks;
with Debug; use Debug;
with Einfo; use Einfo;
with Elists; use Elists;
with Errout; use Errout;
with Exp_Ch11; use Exp_Ch11;
with Exp_Tss; use Exp_Tss;
with Exp_Util; use Exp_Util;
with Expander; use Expander;
with Lib; use Lib;
with Lib.Load; use Lib.Load;
with Namet; use Namet;
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_Aux; use Sem_Aux;
with Sem_Cat; use Sem_Cat;
with Sem_Ch7; use Sem_Ch7;
with Sem_Ch8; use Sem_Ch8;
with Sem_Disp; use Sem_Disp;
with Sem_Prag; use Sem_Prag;
with Sem_Util; use Sem_Util;
with Sinfo; use Sinfo;
with Sinput; use Sinput;
with Snames; use Snames;
with Stand; use Stand;
with Table;
with Tbuild; use Tbuild;
with Uintp; use Uintp;
with Uname; use Uname;
with GNAT; use GNAT;
with GNAT.Dynamic_HTables; use GNAT.Dynamic_HTables;
with GNAT.Lists; use GNAT.Lists;
with GNAT.Sets; use GNAT.Sets;
package body Sem_Elab is
-----------------------------------------
-- Access-before-elaboration mechanism --
-----------------------------------------
-- The access-before-elaboration (ABE) mechanism implemented in this unit
-- has the following objectives:
--
-- * Diagnose at compile time or install run-time checks to prevent ABE
-- access to data and behavior.
--
-- The high-level idea is to accurately diagnose ABE issues within a
-- single unit because the ABE mechanism can inspect the whole unit.
-- As soon as the elaboration graph extends to an external unit, the
-- diagnostics stop because the body of the unit may not be available.
-- Due to control and data flow, the ABE mechanism cannot accurately
-- determine whether a particular scenario will be elaborated or not.
-- Conditional ABE checks are therefore used to verify the elaboration
-- status of local and external targets at run time.
--
-- * Supply implicit elaboration dependencies for a unit to binde
--
-- The ABE mechanism creates implicit dependencies in the form of with
-- clauses subject to pragma Elaborate[_All] when the elaboration graph
-- reaches into an external unit. The implicit dependencies are encoded
-- in the ALI file of the main unit. GNATbind and binde then use these
-- dependencies to augment the library item graph and determine the
-- elaboration order of all units in the compilation.
--
-- * Supply pieces of the invocation graph for a unit to bindo
--
-- The ABE mechanism captures paths starting from elaboration code or
-- top level constructs that reach into an external unit. The paths are
-- encoded in the ALI file of the main unit in the form of declarations
-- which represent nodes, and relations which represent edges. GNATbind
-- and bindo then build the full invocation graph in order to augment
-- the library item graph and determine the elaboration order of all
-- units in the compilation.
--
-- The ABE mechanism supports three models of elaboration:
--
-- * Dynamic model - This is the most permissive of the three models.
-- When the dynamic model is in effect, the mechanism diagnoses and
-- installs run-time checks to detect ABE issues in the main unit.
-- The behavior of this model is identical to that specified by the
-- Ada RM. This model is enabled with switch -gnatE.
--
-- Static model - This is the middle ground of the three models. When
-- the static model is in effect, the mechanism diagnoses and installs
-- run-time checks to detect ABE issues in the main unit. In addition,
-- the mechanism generates implicit dependencies between units in the
-- form of with clauses subject to pragma Elaborate[_All] to ensure
-- the prior elaboration of withed units. This is the default model.
--
-- * SPARK model - This is the most conservative of the three models and
-- implements the semantics defined in SPARK RM 7.7. The SPARK model
-- is in effect only when a context resides in a SPARK_Mode On region,
-- otherwise the mechanism falls back to one of the previous models.
--
-- The ABE mechanism consists of a "recording" phase and a "processing"
-- phase.
-----------------
-- Terminology --
-----------------
-- * ABE - An attempt to invoke a scenario which has not been elaborated
-- yet.
--
-- * Bridge target - A type of target. A bridge target is a link between
-- scenarios. It is usually a byproduct of expansion and does not have
-- any direct ABE ramifications.
--
-- * Call marker - A special node used to indicate the presence of a call
-- in the tree in case expansion transforms or eliminates the original
-- call. N_Call_Marker nodes do not have static and run-time semantics.
--
-- * Conditional ABE - A type of ABE. A conditional ABE occurs when the
-- invocation of a target by a scenario within the main unit causes an
-- ABE, but does not cause an ABE for another scenarios within the main
-- unit.
--
-- * Declaration level - A type of enclosing level. A scenario or target is
-- at the declaration level when it appears within the declarations of a
-- block statement, entry body, subprogram body, or task body, ignoring
-- enclosing packages.
--
-- * Early call region - A section of code which ends at a subprogram body
-- and starts from the nearest non-preelaborable construct which precedes
-- the subprogram body. The early call region extends from a package body
-- to a package spec when the spec carries pragma Elaborate_Body.
--
-- * Generic library level - A type of enclosing level. A scenario or
-- target is at the generic library level if it appears in a generic
-- package library unit, ignoring enclosing packages.
--
-- * Guaranteed ABE - A type of ABE. A guaranteed ABE occurs when the
-- invocation of a target by all scenarios within the main unit causes
-- an ABE.
--
-- * Instantiation library level - A type of enclosing level. A scenario
-- or target is at the instantiation library level if it appears in an
-- instantiation library unit, ignoring enclosing packages.
--
-- * Invocation - The act of activating a task, calling a subprogram, or
-- instantiating a generic.
--
-- * Invocation construct - An entry declaration, [single] protected type,
-- subprogram declaration, subprogram instantiation, or a [single] task
-- type declared in the visible, private, or body declarations of the
-- main unit.
--
-- * Invocation relation - A flow link between two invocation constructs
--
-- * Invocation signature - A set of attributes that uniquely identify an
-- invocation construct within the namespace of all ALI files.
--
-- * Library level - A type of enclosing level. A scenario or target is at
-- the library level if it appears in a package library unit, ignoring
-- enclosing packages.
--
-- * Non-library-level encapsulator - A construct that cannot be elaborated
-- on its own and requires elaboration by a top-level scenario.
--
-- * Scenario - A construct or context which is invoked by elaboration code
-- or invocation construct. The scenarios recognized by the ABE mechanism
-- are as follows:
--
-- - '[Unrestricted_]Access of entries, operators, and subprograms
--
-- - Assignments to variables
--
-- - Calls to entries, operators, and subprograms
--
-- - Derived type declarations
--
-- - Instantiations
--
-- - Pragma Refined_State
--
-- - Reads of variables
--
-- - Task activation
--
-- * Target - A construct invoked by a scenario. The targets recognized by
-- the ABE mechanism are as follows:
--
-- - For '[Unrestricted_]Access of entries, operators, and subprograms,
-- the target is the entry, operator, or subprogram.
--
-- - For assignments to variables, the target is the variable
--
-- - For calls, the target is the entry, operator, or subprogram
--
-- - For derived type declarations, the target is the derived type
--
-- - For instantiations, the target is the generic template
--
-- - For pragma Refined_State, the targets are the constituents
--
-- - For reads of variables, the target is the variable
--
-- - For task activation, the target is the task body
------------------
-- Architecture --
------------------
-- Analysis/Resolution
-- |
-- +- Build_Call_Marker
-- |
-- +- Build_Variable_Reference_Marker
-- |
-- +- | -------------------- Recording phase ---------------------------+
-- | v |
-- | Record_Elaboration_Scenario |
-- | | |
-- | +--> Check_Preelaborated_Call |
-- | | |
-- | +--> Process_Guaranteed_ABE |
-- | | | |
-- | | +--> Process_Guaranteed_ABE_Activation |
-- | | +--> Process_Guaranteed_ABE_Call |
-- | | +--> Process_Guaranteed_ABE_Instantiation |
-- | | |
-- +- | ----------------------------------------------------------------+
-- |
-- |
-- +--> Internal_Representation
-- |
-- +--> Scenario_Storage
-- |
-- End of Compilation
-- |
-- +- | --------------------- Processing phase -------------------------+
-- | v |
-- | Check_Elaboration_Scenarios |
-- | | |
-- | +--> Check_Conditional_ABE_Scenarios |
-- | | | |
-- | | +--> Process_Conditional_ABE <----------------------+ |
-- | | | | |
-- | | +--> Process_Conditional_ABE_Activation | |
-- | | | | | |
-- | | | +-----------------------------+ | |
-- | | | | | |
-- | | +--> Process_Conditional_ABE_Call +---> Traverse_Body |
-- | | | | | |
-- | | | +-----------------------------+ |
-- | | | |
-- | | +--> Process_Conditional_ABE_Access_Taken |
-- | | +--> Process_Conditional_ABE_Instantiation |
-- | | +--> Process_Conditional_ABE_Variable_Assignment |
-- | | +--> Process_Conditional_ABE_Variable_Reference |
-- | | |
-- | +--> Check_SPARK_Scenario |
-- | | | |
-- | | +--> Process_SPARK_Scenario |
-- | | | |
-- | | +--> Process_SPARK_Derived_Type |
-- | | +--> Process_SPARK_Instantiation |
-- | | +--> Process_SPARK_Refined_State_Pragma |
-- | | |
-- | +--> Record_Invocation_Graph |
-- | | |
-- | +--> Process_Invocation_Body_Scenarios |
-- | +--> Process_Invocation_Spec_Scenarios |
-- | +--> Process_Main_Unit |
-- | | |
-- | +--> Process_Invocation_Scenario <-------------+ |
-- | | | |
-- | +--> Process_Invocation_Activation | |
-- | | | | |
-- | | +------------------------+ | |
-- | | | | |
-- | +--> Process_Invocation_Call +---> Traverse_Body |
-- | | | |
-- | +------------------------+ |
-- | |
-- +--------------------------------------------------------------------+
---------------------
-- Recording phase --
---------------------
-- The Recording phase coincides with the analysis/resolution phase of the
-- compiler. It has the following objectives:
--
-- * Record all suitable scenarios for examination by the Processing
-- phase.
--
-- Saving only a certain number of nodes improves the performance of
-- the ABE mechanism. This eliminates the need to examine the whole
-- tree in a separate pass.
--
-- * Record certain SPARK scenarios which are not necessarily invoked
-- during elaboration, but still require elaboration-related checks.
--
-- Saving only a certain number of nodes improves the performance of
-- the ABE mechanism. This eliminates the need to examine the whole
-- tree in a separate pass.
--
-- * Detect and diagnose calls in preelaborable or pure units, including
-- generic bodies.
--
-- This diagnostic is carried out during the Recording phase because it
-- does not need the heavy recursive traversal done by the Processing
-- phase.
--
-- * Detect and diagnose guaranteed ABEs caused by instantiations, calls,
-- and task activation.
--
-- The issues detected by the ABE mechanism are reported as warnings
-- because they do not violate Ada semantics. Forward instantiations
-- may thus reach gigi, however gigi cannot handle certain kinds of
-- premature instantiations and may crash. To avoid this limitation,
-- the ABE mechanism must identify forward instantiations as early as
-- possible and suppress their bodies. Calls and task activations are
-- included in this category for completeness.
----------------------
-- Processing phase --
----------------------
-- The Processing phase is a separate pass which starts after instantiating
-- and/or inlining of bodies, but before the removal of Ghost code. It has
-- the following objectives:
--
-- * Examine all scenarios saved during the Recording phase, and perform
-- the following actions:
--
-- - Dynamic model
--
-- Diagnose conditional ABEs, and install run-time conditional ABE
-- checks for all scenarios.
--
-- - SPARK model
--
-- Enforce the SPARK elaboration rules
--
-- - Static model
--
-- Diagnose conditional ABEs, install run-time conditional ABE
-- checks only for scenarios are reachable from elaboration code,
-- and guarantee the elaboration of external units by creating
-- implicit with clauses subject to pragma Elaborate[_All].
--
-- * Examine library-level scenarios and invocation constructs, and
-- perform the following actions:
--
-- - Determine whether the flow of execution reaches into an external
-- unit. If this is the case, encode the path in the ALI file of
-- the main unit.
--
-- - Create declarations for invocation constructs in the ALI file of
-- the main unit.
----------------------
-- Important points --
----------------------
-- The Processing phase starts after the analysis, resolution, expansion
-- phase has completed. As a result, no current semantic information is
-- available. The scope stack is empty, global flags such as In_Instance
-- or Inside_A_Generic become useless. To remedy this, the ABE mechanism
-- must either save or recompute semantic information.
--
-- Expansion heavily transforms calls and to some extent instantiations. To
-- remedy this, the ABE mechanism generates N_Call_Marker nodes in order to
-- capture the target and relevant attributes of the original call.
--
-- The diagnostics of the ABE mechanism depend on accurate source locations
-- to determine the spatial relation of nodes.
-----------------------------------------
-- Suppression of elaboration warnings --
-----------------------------------------
-- Elaboration warnings along multiple traversal paths rooted at a scenario
-- are suppressed when the scenario has elaboration warnings suppressed.
--
-- Root scenario
-- |
-- +-- Child scenario 1
-- | |
-- | +-- Grandchild scenario 1
-- | |
-- | +-- Grandchild scenario N
-- |
-- +-- Child scenario N
--
-- If the root scenario has elaboration warnings suppressed, then all its
-- child, grandchild, etc. scenarios will have their elaboration warnings
-- suppressed.
--
-- In addition to switch -gnatwL, pragma Warnings may be used to suppress
-- elaboration-related warnings when used in the following manner:
--
-- pragma Warnings ("L");
-- <scenario-or-target>
--
-- <target>
-- pragma Warnings (Off, target);
--
-- pragma Warnings (Off);
-- <scenario-or-target>
--
-- * To suppress elaboration warnings for '[Unrestricted_]Access of
-- entries, operators, and subprograms, either:
--
-- - Suppress the entry, operator, or subprogram, or
-- - Suppress the attribute, or
-- - Use switch -gnatw.f
--
-- * To suppress elaboration warnings for calls to entries, operators,
-- and subprograms, either:
--
-- - Suppress the entry, operator, or subprogram, or
-- - Suppress the call
--
-- * To suppress elaboration warnings for instantiations, suppress the
-- instantiation.
--
-- * To suppress elaboration warnings for task activations, either:
--
-- - Suppress the task object, or
-- - Suppress the task type, or
-- - Suppress the activation call
--------------
-- Switches --
--------------
-- The following switches may be used to control the behavior of the ABE
-- mechanism.
--
-- -gnatd_a stop elaboration checks on accept or select statement
--
-- The ABE mechanism stops the traversal of a task body when it
-- encounters an accept or a select statement. This behavior is
-- equivalent to restriction No_Entry_Calls_In_Elaboration_Code,
-- but without penalizing actual entry calls during elaboration.
--
-- -gnatd_e ignore entry calls and requeue statements for elaboration
--
-- The ABE mechanism does not generate N_Call_Marker nodes for
-- protected or task entry calls as well as requeue statements.
-- As a result, the calls and requeues are not recorded or
-- processed.
--
-- -gnatdE elaboration checks on predefined units
--
-- The ABE mechanism considers scenarios which appear in internal
-- units (Ada, GNAT, Interfaces, System).
--
-- -gnatd_F encode full invocation paths in ALI files
--
-- The ABE mechanism encodes the full path from an elaboration
-- procedure or invocable construct to an external target. The
-- path contains all intermediate activations, instantiations,
-- and calls.
--
-- -gnatd.G ignore calls through generic formal parameters for elaboration
--
-- The ABE mechanism does not generate N_Call_Marker nodes for
-- calls which occur in expanded instances, and invoke generic
-- actual subprograms through generic formal subprograms. As a
-- result, the calls are not recorded or processed.
--
-- -gnatd_i ignore activations and calls to instances for elaboration
--
-- The ABE mechanism ignores calls and task activations when they
-- target a subprogram or task type defined an external instance.
-- As a result, the calls and task activations are not processed.
--
-- -gnatdL ignore external calls from instances for elaboration
--
-- The ABE mechanism does not generate N_Call_Marker nodes for
-- calls which occur in expanded instances, do not invoke generic
-- actual subprograms through formal subprograms, and the target
-- is external to the instance. As a result, the calls are not
-- recorded or processed.
--
-- -gnatd.o conservative elaboration order for indirect calls
--
-- The ABE mechanism treats '[Unrestricted_]Access of an entry,
-- operator, or subprogram as an immediate invocation of the
-- target. As a result, it performs ABE checks and diagnostics on
-- the immediate call.
--
-- -gnatd_p ignore assertion pragmas for elaboration
--
-- The ABE mechanism does not generate N_Call_Marker nodes for
-- calls to subprograms which verify the run-time semantics of
-- the following assertion pragmas:
--
-- Default_Initial_Condition
-- Initial_Condition
-- Invariant
-- Invariant'Class
-- Post
-- Post'Class
-- Postcondition
-- Type_Invariant
-- Type_Invariant_Class
--
-- As a result, the assertion expressions of the pragmas are not
-- processed.
--
-- -gnatd_s stop elaboration checks on synchronous suspension
--
-- The ABE mechanism stops the traversal of a task body when it
-- encounters a call to one of the following routines:
--
-- Ada.Synchronous_Barriers.Wait_For_Release
-- Ada.Synchronous_Task_Control.Suspend_Until_True
--
-- -gnatd_T output trace information on invocation relation construction
--
-- The ABE mechanism outputs text information concerning relation
-- construction to standard output.
--
-- -gnatd.U ignore indirect calls for static elaboration
--
-- The ABE mechanism does not consider '[Unrestricted_]Access of
-- entries, operators, and subprograms. As a result, the scenarios
-- are not recorder or processed.
--
-- -gnatd.v enforce SPARK elaboration rules in SPARK code
--
-- The ABE mechanism applies some of the SPARK elaboration rules
-- defined in the SPARK reference manual, chapter 7.7. Note that
-- certain rules are always enforced, regardless of whether the
-- switch is active.
--
-- -gnatd.y disable implicit pragma Elaborate_All on task bodies
--
-- The ABE mechanism does not generate implicit Elaborate_All when
-- the need for the pragma came from a task body.
--
-- -gnatE dynamic elaboration checking mode enabled
--
-- The ABE mechanism assumes that any scenario is elaborated or
-- invoked by elaboration code. The ABE mechanism performs very
-- little diagnostics and generates condintional ABE checks to
-- detect ABE issues at run-time.
--
-- -gnatel turn on info messages on generated Elaborate[_All] pragmas
--
-- The ABE mechanism produces information messages on generated
-- implicit Elabote[_All] pragmas along with traceback showing
-- why the pragma was generated. In addition, the ABE mechanism
-- produces information messages for each scenario elaborated or
-- invoked by elaboration code.
--
-- -gnateL turn off info messages on generated Elaborate[_All] pragmas
--
-- The complementary switch for -gnatel.
--
-- -gnatH legacy elaboration checking mode enabled
--
-- When this switch is in effect, the pre-18.x ABE model becomes
-- the de facto ABE model. This amounts to cutting off all entry
-- points into the new ABE mechanism, and giving full control to
-- the old ABE mechanism.
--
-- -gnatJ permissive elaboration checking mode enabled
--
-- This switch activates the following switches:
--
-- -gnatd_a
-- -gnatd_e
-- -gnatd.G
-- -gnatd_i
-- -gnatdL
-- -gnatd_p
-- -gnatd_s
-- -gnatd.U
-- -gnatd.y
--
-- IMPORTANT: The behavior of the ABE mechanism becomes more
-- permissive at the cost of accurate diagnostics and runtime
-- ABE checks.
--
-- -gnatw.f turn on warnings for suspicious Subp'Access
--
-- The ABE mechanism treats '[Unrestricted_]Access of an entry,
-- operator, or subprogram as a pseudo invocation of the target.
-- As a result, it performs ABE diagnostics on the pseudo call.
--
-- -gnatw.F turn off warnings for suspicious Subp'Access
--
-- The complementary switch for -gnatw.f.
--
-- -gnatwl turn on warnings for elaboration problems
--
-- The ABE mechanism produces warnings on detected ABEs along with
-- a traceback showing the graph of the ABE.
--
-- -gnatwL turn off warnings for elaboration problems
--
-- The complementary switch for -gnatwl.
--------------------------
-- Debugging ABE issues --
--------------------------
-- * If the issue involves a call, ensure that the call is eligible for ABE
-- processing and receives a corresponding call marker. The routines of
-- interest are
--
-- Build_Call_Marker
-- Record_Elaboration_Scenario
--
-- * If the issue involves an arbitrary scenario, ensure that the scenario
-- is either recorded, or is successfully recognized while traversing a
-- body. The routines of interest are
--
-- Record_Elaboration_Scenario
-- Process_Conditional_ABE
-- Process_Guaranteed_ABE
-- Traverse_Body
--
-- * If the issue involves a circularity in the elaboration order, examine
-- the ALI files and look for the following encodings next to units:
--
-- E indicates a source Elaborate
--
-- EA indicates a source Elaborate_All
--
-- AD indicates an implicit Elaborate_All
--
-- ED indicates an implicit Elaborate
--
-- If possible, compare these encodings with those generated by the old
-- ABE mechanism. The routines of interest are
--
-- Ensure_Prior_Elaboration
-----------
-- Kinds --
-----------
-- The following type enumerates all possible elaboration phase statutes
type Elaboration_Phase_Status is
(Inactive,
-- The elaboration phase of the compiler has not started yet
Active,
-- The elaboration phase of the compiler is currently in progress
Completed);
-- The elaboration phase of the compiler has finished
Elaboration_Phase : Elaboration_Phase_Status := Inactive;
-- The status of the elaboration phase. Use routine Set_Elaboration_Phase
-- to alter its value.
-- The following type enumerates all subprogram body traversal modes
type Body_Traversal_Kind is
(Deep_Traversal,
-- The traversal examines the internals of a subprogram
No_Traversal);
-- The following type enumerates all operation modes
type Processing_Kind is
(Conditional_ABE_Processing,
-- The ABE mechanism detects and diagnoses conditional ABEs for library
-- and declaration-level scenarios.
Dynamic_Model_Processing,
-- The ABE mechanism installs conditional ABE checks for all eligible
-- scenarios when the dynamic model is in effect.
Guaranteed_ABE_Processing,
-- The ABE mechanism detects and diagnoses guaranteed ABEs caused by
-- calls, instantiations, and task activations.
Invocation_Construct_Processing,
-- The ABE mechanism locates all invocation constructs within the main
-- unit and utilizes them as roots of miltiple DFS traversals aimed at
-- detecting transitions from the main unit to an external unit.
Invocation_Body_Processing,
-- The ABE mechanism utilizes all library-level body scenarios as roots
-- of miltiple DFS traversals aimed at detecting transitions from the
-- main unit to an external unit.
Invocation_Spec_Processing,
-- The ABE mechanism utilizes all library-level spec scenarios as roots
-- of miltiple DFS traversals aimed at detecting transitions from the
-- main unit to an external unit.
SPARK_Processing,
-- The ABE mechanism detects and diagnoses violations of the SPARK
-- elaboration rules for SPARK-specific scenarios.
No_Processing);
-- The following type enumerates all possible scenario kinds
type Scenario_Kind is
(Access_Taken_Scenario,
-- An attribute reference which takes 'Access or 'Unrestricted_Access of
-- an entry, operator, or subprogram.
Call_Scenario,
-- A call which invokes an entry, operator, or subprogram
Derived_Type_Scenario,
-- A declaration of a derived type. This is a SPARK-specific scenario.
Instantiation_Scenario,
-- An instantiation which instantiates a generic package or subprogram.
-- This scenario is also subject to SPARK-specific rules.
Refined_State_Pragma_Scenario,
-- A Refined_State pragma. This is a SPARK-specific scenario.
Task_Activation_Scenario,
-- A call which activates objects of various task types
Variable_Assignment_Scenario,
-- An assignment statement which modifies the value of some variable
Variable_Reference_Scenario,
-- A reference to a variable. This is a SPARK-specific scenario.
No_Scenario);
-- The following type enumerates all possible consistency models of target
-- and scenario representations.
type Representation_Kind is
(Inconsistent_Representation,
-- A representation is said to be "inconsistent" when it is created from
-- a partially analyzed tree. In such an environment, certain attributes
-- such as a completing body may not be available yet.
Consistent_Representation,
-- A representation is said to be "consistent" when it is created from a
-- fully analyzed tree, where all attributes are available.
No_Representation);
-- The following type enumerates all possible target kinds
type Target_Kind is
(Generic_Target,
-- A generic unit being instantiated
Package_Target,
-- The package form of an instantiation
Subprogram_Target,
-- An entry, operator, or subprogram being invoked, or aliased through
-- 'Access or 'Unrestricted_Access.
Task_Target,
-- A task being activated by an activation call
Variable_Target,
-- A variable being updated through an assignment statement, or read
-- through a variable reference.
No_Target);
-----------
-- Types --
-----------
procedure Destroy (NE : in out Node_Or_Entity_Id);
pragma Inline (Destroy);
-- Destroy node or entity NE
function Hash (NE : Node_Or_Entity_Id) return Bucket_Range_Type;
pragma Inline (Hash);
-- Obtain the hash value of key NE
-- The following is a general purpose list for nodes and entities
package NE_List is new Doubly_Linked_Lists
(Element_Type => Node_Or_Entity_Id,
"=" => "=",
Destroy_Element => Destroy);
-- The following is a general purpose map which relates nodes and entities
-- to lists of nodes and entities.
package NE_List_Map is new Dynamic_Hash_Tables
(Key_Type => Node_Or_Entity_Id,
Value_Type => NE_List.Doubly_Linked_List,
No_Value => NE_List.Nil,
Expansion_Threshold => 1.5,
Expansion_Factor => 2,
Compression_Threshold => 0.3,
Compression_Factor => 2,
"=" => "=",
Destroy_Value => NE_List.Destroy,
Hash => Hash);
-- The following is a general purpose membership set for nodes and entities
package NE_Set is new Membership_Sets
(Element_Type => Node_Or_Entity_Id,
"=" => "=",
Hash => Hash);
-- The following type captures relevant attributes which pertain to the
-- in state of the Processing phase.
type Processing_In_State is record
Processing : Processing_Kind := No_Processing;
-- Operation mode of the Processing phase. Once set, this value should
-- not be changed.
Representation : Representation_Kind := No_Representation;
-- Required level of scenario and target representation. Once set, this
-- value should not be changed.
Suppress_Checks : Boolean := False;
-- This flag is set when the Processing phase must not generate any ABE
-- checks.
Suppress_Implicit_Pragmas : Boolean := False;
-- This flag is set when the Processing phase must not generate any
-- implicit Elaborate[_All] pragmas.
Suppress_Info_Messages : Boolean := False;
-- This flag is set when the Processing phase must not emit any info
-- messages.
Suppress_Up_Level_Targets : Boolean := False;
-- This flag is set when the Processing phase must ignore up-level
-- targets.
Suppress_Warnings : Boolean := False;
-- This flag is set when the Processing phase must not emit any warnings
-- on elaboration problems.
Traversal : Body_Traversal_Kind := No_Traversal;
-- The subprogram body traversal mode. Once set, this value should not
-- be changed.
Within_Generic : Boolean := False;
-- This flag is set when the Processing phase is currently within a
-- generic unit.
Within_Initial_Condition : Boolean := False;
-- This flag is set when the Processing phase is currently examining a
-- scenario which was reached from an initial condition procedure.
Within_Partial_Finalization : Boolean := False;
-- This flag is set when the Processing phase is currently examining a
-- scenario which was reached from a partial finalization procedure.
Within_Task_Body : Boolean := False;
-- This flag is set when the Processing phase is currently examining a
-- scenario which was reached from a task body.
end record;
-- The following constants define the various operational states of the
-- Processing phase.
-- The conditional ABE state is used when processing scenarios that appear
-- at the declaration, instantiation, and library levels to detect errors
-- and install conditional ABE checks.
Conditional_ABE_State : constant Processing_In_State :=
(Processing => Conditional_ABE_Processing,
Representation => Consistent_Representation,
Traversal => Deep_Traversal,
others => False);
-- The dynamic model state is used to install conditional ABE checks when
-- switch -gnatE (dynamic elaboration checking mode enabled) is in effect.
Dynamic_Model_State : constant Processing_In_State :=
(Processing => Dynamic_Model_Processing,
Representation => Consistent_Representation,
Suppress_Implicit_Pragmas => True,
Suppress_Info_Messages => True,
Suppress_Up_Level_Targets => True,
Suppress_Warnings => True,
Traversal => No_Traversal,
others => False);
-- The guaranteed ABE state is used when processing scenarios that appear
-- at the declaration, instantiation, and library levels to detect errors
-- and install guarateed ABE failures.
Guaranteed_ABE_State : constant Processing_In_State :=
(Processing => Guaranteed_ABE_Processing,
Representation => Inconsistent_Representation,
Suppress_Implicit_Pragmas => True,
Traversal => No_Traversal,
others => False);
-- The invocation body state is used when processing scenarios that appear
-- at the body library level to encode paths that start from elaboration
-- code and ultimately reach into external units.
Invocation_Body_State : constant Processing_In_State :=
(Processing => Invocation_Body_Processing,
Representation => Consistent_Representation,
Suppress_Checks => True,
Suppress_Implicit_Pragmas => True,
Suppress_Info_Messages => True,
Suppress_Up_Level_Targets => True,
Suppress_Warnings => True,
Traversal => Deep_Traversal,
others => False);
-- The invocation construct state is used when processing constructs that
-- appear within the spec and body of the main unit and eventually reach
-- into external units.
Invocation_Construct_State : constant Processing_In_State :=
(Processing => Invocation_Construct_Processing,
Representation => Consistent_Representation,
Suppress_Checks => True,
Suppress_Implicit_Pragmas => True,
Suppress_Info_Messages => True,
Suppress_Up_Level_Targets => True,
Suppress_Warnings => True,
Traversal => Deep_Traversal,
others => False);
-- The invocation spec state is used when processing scenarios that appear
-- at the spec library level to encode paths that start from elaboration
-- code and ultimately reach into external units.
Invocation_Spec_State : constant Processing_In_State :=
(Processing => Invocation_Spec_Processing,
Representation => Consistent_Representation,
Suppress_Checks => True,
Suppress_Implicit_Pragmas => True,
Suppress_Info_Messages => True,
Suppress_Up_Level_Targets => True,
Suppress_Warnings => True,
Traversal => Deep_Traversal,
others => False);
-- The SPARK state is used when verying SPARK-specific semantics of certain
-- scenarios.
SPARK_State : constant Processing_In_State :=
(Processing => SPARK_Processing,
Representation => Consistent_Representation,
Traversal => No_Traversal,
others => False);
-- The following type identifies a scenario representation
type Scenario_Rep_Id is new Natural;
No_Scenario_Rep : constant Scenario_Rep_Id := Scenario_Rep_Id'First;
First_Scenario_Rep : constant Scenario_Rep_Id := No_Scenario_Rep + 1;
-- The following type identifies a target representation
type Target_Rep_Id is new Natural;
No_Target_Rep : constant Target_Rep_Id := Target_Rep_Id'First;
First_Target_Rep : constant Target_Rep_Id := No_Target_Rep + 1;
--------------
-- Services --
--------------
-- The following package keeps track of all active scenarios during a DFS
-- traversal.
package Active_Scenarios is
-----------
-- Types --
-----------
-- The following type defines the position within the active scenario
-- stack.
type Active_Scenario_Pos is new Natural;
---------------------
-- Data structures --
---------------------
-- The following table stores all active scenarios in a DFS traversal.
-- This table must be maintained in a FIFO fashion.
package Active_Scenario_Stack is new Table.Table
(Table_Index_Type => Active_Scenario_Pos,
Table_Component_Type => Node_Id,
Table_Low_Bound => 1,
Table_Initial => 50,
Table_Increment => 200,
Table_Name => "Active_Scenario_Stack");
---------
-- API --
---------
procedure Output_Active_Scenarios
(Error_Nod : Node_Id;
In_State : Processing_In_State);
pragma Inline (Output_Active_Scenarios);
-- Output the contents of the active scenario stack from earliest to
-- latest to supplement an earlier error emitted for node Error_Nod.
-- In_State denotes the current state of the Processing phase.
procedure Pop_Active_Scenario (N : Node_Id);
pragma Inline (Pop_Active_Scenario);
-- Pop the top of the scenario stack. A check is made to ensure that the
-- scenario being removed is the same as N.
procedure Push_Active_Scenario (N : Node_Id);
pragma Inline (Push_Active_Scenario);
-- Push scenario N on top of the scenario stack
function Root_Scenario return Node_Id;
pragma Inline (Root_Scenario);
-- Return the scenario which started a DFS traversal
end Active_Scenarios;
use Active_Scenarios;
-- The following package provides the main entry point for task activation
-- processing.
package Activation_Processor is
-----------
-- Types --
-----------
type Activation_Processor_Ptr is access procedure
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State);
-- Reference to a procedure that takes all attributes of an activation
-- and performs a desired action. Call is the activation call. Call_Rep
-- is the representation of the call. Obj_Id is the task object being
-- activated. Obj_Rep is the representation of the object. Task_Typ is
-- the task type whose body is being activated. Task_Rep denotes the
-- representation of the task type. In_State is the current state of
-- the Processing phase.
---------
-- API --
---------
procedure Process_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Processor : Activation_Processor_Ptr;
In_State : Processing_In_State);
-- Find all task objects activated by activation call Call and invoke
-- Processor on them. Call_Rep denotes the representation of the call.
-- In_State is the current state of the Processing phase.
end Activation_Processor;
use Activation_Processor;
-- The following package profides functionality for traversing subprogram
-- bodies in DFS manner and processing of eligible scenarios within.
package Body_Processor is
-----------
-- Types --
-----------
type Scenario_Predicate_Ptr is access function
(N : Node_Id) return Boolean;
-- Reference to a function which determines whether arbitrary node N
-- denotes a suitable scenario for processing.
type Scenario_Processor_Ptr is access procedure
(N : Node_Id; In_State : Processing_In_State);
-- Reference to a procedure which processes scenario N. In_State is the
-- current state of the Processing phase.
---------
-- API --
---------
procedure Traverse_Body
(N : Node_Id;
Requires_Processing : Scenario_Predicate_Ptr;
Processor : Scenario_Processor_Ptr;
In_State : Processing_In_State);
pragma Inline (Traverse_Body);
-- Traverse the declarations and handled statements of subprogram body
-- N, looking for scenarios that satisfy predicate Requires_Processing.
-- Routine Processor is invoked for each such scenario.
procedure Reset_Traversed_Bodies;
pragma Inline (Reset_Traversed_Bodies);
-- Reset the visited status of all subprogram bodies that have already
-- been processed by routine Traverse_Body.
-----------------
-- Maintenance --
-----------------
procedure Finalize_Body_Processor;
pragma Inline (Finalize_Body_Processor);
-- Finalize all internal data structures
procedure Initialize_Body_Processor;
pragma Inline (Initialize_Body_Processor);
-- Initialize all internal data structures
end Body_Processor;
use Body_Processor;
-- The following package provides functionality for installing ABE-related
-- checks and failures.
package Check_Installer is
---------
-- API --
---------
function Check_Or_Failure_Generation_OK return Boolean;
pragma Inline (Check_Or_Failure_Generation_OK);
-- Determine whether a conditional ABE check or guaranteed ABE failure
-- can be generated.
procedure Install_Dynamic_ABE_Checks;
pragma Inline (Install_Dynamic_ABE_Checks);
-- Install conditional ABE checks for all saved scenarios when the
-- dynamic model is in effect.
procedure Install_Scenario_ABE_Check
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Scenario_Rep_Id);
pragma Inline (Install_Scenario_ABE_Check);
-- Install a conditional ABE check for scenario N to ensure that target
-- Targ_Id is properly elaborated. Targ_Rep is the representation of the
-- target. If the check is installed, disable the elaboration checks of
-- scenario Disable.
procedure Install_Scenario_ABE_Check
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Target_Rep_Id);
pragma Inline (Install_Scenario_ABE_Check);
-- Install a conditional ABE check for scenario N to ensure that target
-- Targ_Id is properly elaborated. Targ_Rep is the representation of the
-- target. If the check is installed, disable the elaboration checks of
-- target Disable.
procedure Install_Scenario_ABE_Failure
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Scenario_Rep_Id);
pragma Inline (Install_Scenario_ABE_Failure);
-- Install a guaranteed ABE failure for scenario N with target Targ_Id.
-- Targ_Rep denotes the representation of the target. If the failure is
-- installed, disable the elaboration checks of scenario Disable.
procedure Install_Scenario_ABE_Failure
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Target_Rep_Id);
pragma Inline (Install_Scenario_ABE_Failure);
-- Install a guaranteed ABE failure for scenario N with target Targ_Id.
-- Targ_Rep denotes the representation of the target. If the failure is
-- installed, disable the elaboration checks of target Disable.
procedure Install_Unit_ABE_Check
(N : Node_Id;
Unit_Id : Entity_Id;
Disable : Scenario_Rep_Id);
pragma Inline (Install_Unit_ABE_Check);
-- Install a conditional ABE check for scenario N to ensure that unit
-- Unit_Id is properly elaborated. If the check is installed, disable
-- the elaboration checks of scenario Disable.
procedure Install_Unit_ABE_Check
(N : Node_Id;
Unit_Id : Entity_Id;
Disable : Target_Rep_Id);
pragma Inline (Install_Unit_ABE_Check);
-- Install a conditional ABE check for scenario N to ensure that unit
-- Unit_Id is properly elaborated. If the check is installed, disable
-- the elaboration checks of target Disable.
end Check_Installer;
use Check_Installer;
-- The following package provides the main entry point for conditional ABE
-- checks and diagnostics.
package Conditional_ABE_Processor is
---------
-- API --
---------
procedure Check_Conditional_ABE_Scenarios
(Iter : in out NE_Set.Iterator);
pragma Inline (Check_Conditional_ABE_Scenarios);
-- Perform conditional ABE checks and diagnostics for all scenarios
-- available through iterator Iter.
procedure Process_Conditional_ABE
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE);
-- Perform conditional ABE checks and diagnostics for scenario N.
-- In_State denotes the current state of the Processing phase.
end Conditional_ABE_Processor;
use Conditional_ABE_Processor;
-- The following package provides functionality to emit errors, information
-- messages, and warnings.
package Diagnostics is
---------
-- API --
---------
procedure Elab_Msg_NE
(Msg : String;
N : Node_Id;
Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean);
pragma Inline (Elab_Msg_NE);
-- Wrapper around Error_Msg_NE. Emit message Msg concerning arbitrary
-- node N and entity. If flag Info_Msg is set, the routine emits an
-- information message, otherwise it emits an error. If flag In_SPARK
-- is set, then string " in SPARK" is added to the end of the message.
procedure Info_Call
(Call : Node_Id;
Subp_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean);
pragma Inline (Info_Call);
-- Output information concerning call Call that invokes subprogram
-- Subp_Id. When flag Info_Msg is set, the routine emits an information
-- message, otherwise it emits an error. When flag In_SPARK is set, " in
-- SPARK" is added to the end of the message.
procedure Info_Instantiation
(Inst : Node_Id;
Gen_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean);
pragma Inline (Info_Instantiation);
-- Output information concerning instantiation Inst which instantiates
-- generic unit Gen_Id. If flag Info_Msg is set, the routine emits an
-- information message, otherwise it emits an error. If flag In_SPARK
-- is set, then string " in SPARK" is added to the end of the message.
procedure Info_Variable_Reference
(Ref : Node_Id;
Var_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean);
pragma Inline (Info_Variable_Reference);
-- Output information concerning reference Ref which mentions variable
-- Var_Id. If flag Info_Msg is set, the routine emits an information
-- message, otherwise it emits an error. If flag In_SPARK is set, then
-- string " in SPARK" is added to the end of the message.
end Diagnostics;
use Diagnostics;
-- The following package provides functionality to locate the early call
-- region of a subprogram body.
package Early_Call_Region_Processor is
---------
-- API --
---------
function Find_Early_Call_Region
(Body_Decl : Node_Id;
Assume_Elab_Body : Boolean := False;
Skip_Memoization : Boolean := False) return Node_Id;
pragma Inline (Find_Early_Call_Region);
-- Find the start of the early call region that belongs to subprogram
-- body Body_Decl as defined in SPARK RM 7.7. This routine finds the
-- early call region, memoizes it, and returns it, but this behavior
-- can be altered. Flag Assume_Elab_Body should be set when a package
-- spec may lack pragma Elaborate_Body, but the routine must still
-- examine that spec. Flag Skip_Memoization should be set when the
-- routine must avoid memoizing the region.
-----------------
-- Maintenance --
-----------------
procedure Finalize_Early_Call_Region_Processor;
pragma Inline (Finalize_Early_Call_Region_Processor);
-- Finalize all internal data structures
procedure Initialize_Early_Call_Region_Processor;
pragma Inline (Initialize_Early_Call_Region_Processor);
-- Initialize all internal data structures
end Early_Call_Region_Processor;
use Early_Call_Region_Processor;
-- The following package provides access to the elaboration statuses of all
-- units withed by the main unit.
package Elaborated_Units is
---------
-- API --
---------
procedure Collect_Elaborated_Units;
pragma Inline (Collect_Elaborated_Units);
-- Save the elaboration statuses of all units withed by the main unit
procedure Ensure_Prior_Elaboration
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State);
pragma Inline (Ensure_Prior_Elaboration);
-- Guarantee the elaboration of unit Unit_Id with respect to the main
-- unit by either suggesting or installing an Elaborate[_All] pragma
-- denoted by Prag_Nam. N denotes the related scenario. In_State is the
-- current state of the Processing phase.
function Has_Prior_Elaboration
(Unit_Id : Entity_Id;
Context_OK : Boolean := False;
Elab_Body_OK : Boolean := False;
Same_Unit_OK : Boolean := False) return Boolean;
pragma Inline (Has_Prior_Elaboration);
-- Determine whether unit Unit_Id is elaborated prior to the main unit.
-- If flag Context_OK is set, the routine considers the following case
-- as valid prior elaboration:
--
-- * Unit_Id is in the elaboration context of the main unit
--
-- If flag Elab_Body_OK is set, the routine considers the following case
-- as valid prior elaboration:
--
-- * Unit_Id has pragma Elaborate_Body and is not the main unit
--
-- If flag Same_Unit_OK is set, the routine considers the following
-- cases as valid prior elaboration:
--
-- * Unit_Id is the main unit
--
-- * Unit_Id denotes the spec of the main unit body
procedure Meet_Elaboration_Requirement
(N : Node_Id;
Targ_Id : Entity_Id;
Req_Nam : Name_Id;
In_State : Processing_In_State);
pragma Inline (Meet_Elaboration_Requirement);
-- Determine whether elaboration requirement Req_Nam for scenario N with
-- target Targ_Id is met by the context of the main unit using the SPARK
-- rules. Req_Nam must denote either Elaborate or Elaborate_All. Emit an
-- error if this is not the case. In_State denotes the current state of
-- the Processing phase.
-----------------
-- Maintenance --
-----------------
procedure Finalize_Elaborated_Units;
pragma Inline (Finalize_Elaborated_Units);
-- Finalize all internal data structures
procedure Initialize_Elaborated_Units;
pragma Inline (Initialize_Elaborated_Units);
-- Initialize all internal data structures
end Elaborated_Units;
use Elaborated_Units;
-- The following package provides the main entry point for guaranteed ABE
-- checks and diagnostics.
package Guaranteed_ABE_Processor is
---------
-- API --
---------
procedure Process_Guaranteed_ABE
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Guaranteed_ABE);
-- Perform guaranteed ABE checks and diagnostics for scenario N.
-- In_State is the current state of the Processing phase.
end Guaranteed_ABE_Processor;
use Guaranteed_ABE_Processor;
-- The following package provides access to the internal representation of
-- scenarios and targets.
package Internal_Representation is
-----------
-- Types --
-----------
-- The following type enumerates all possible Ghost mode kinds
type Extended_Ghost_Mode is
(Is_Ignored,
Is_Checked_Or_Not_Specified);
-- The following type enumerates all possible SPARK mode kinds
type Extended_SPARK_Mode is
(Is_On,
Is_Off_Or_Not_Specified);
--------------
-- Builders --
--------------
function Scenario_Representation_Of
(N : Node_Id;
In_State : Processing_In_State) return Scenario_Rep_Id;
pragma Inline (Scenario_Representation_Of);
-- Obtain the id of elaboration scenario N's representation. The routine
-- constructs the representation if it is not available. In_State is the
-- current state of the Processing phase.
function Target_Representation_Of
(Id : Entity_Id;
In_State : Processing_In_State) return Target_Rep_Id;
pragma Inline (Target_Representation_Of);
-- Obtain the id of elaboration target Id's representation. The routine
-- constructs the representation if it is not available. In_State is the
-- current state of the Processing phase.
-------------------------
-- Scenario attributes --
-------------------------
function Activated_Task_Objects
(S_Id : Scenario_Rep_Id) return NE_List.Doubly_Linked_List;
pragma Inline (Activated_Task_Objects);
-- For Task_Activation_Scenario S_Id, obtain the list of task objects
-- the scenario is activating.
function Activated_Task_Type (S_Id : Scenario_Rep_Id) return Entity_Id;
pragma Inline (Activated_Task_Type);
-- For Task_Activation_Scenario S_Id, obtain the currently activated
-- task type.
procedure Disable_Elaboration_Checks (S_Id : Scenario_Rep_Id);
pragma Inline (Disable_Elaboration_Checks);
-- Disable elaboration checks of scenario S_Id
function Elaboration_Checks_OK (S_Id : Scenario_Rep_Id) return Boolean;
pragma Inline (Elaboration_Checks_OK);
-- Determine whether scenario S_Id may be subjected to elaboration
-- checks.
function Elaboration_Warnings_OK (S_Id : Scenario_Rep_Id) return Boolean;
pragma Inline (Elaboration_Warnings_OK);
-- Determine whether scenario S_Id may be subjected to elaboration
-- warnings.
function Ghost_Mode_Of
(S_Id : Scenario_Rep_Id) return Extended_Ghost_Mode;
pragma Inline (Ghost_Mode_Of);
-- Obtain the Ghost mode of scenario S_Id
function Is_Dispatching_Call (S_Id : Scenario_Rep_Id) return Boolean;
pragma Inline (Is_Dispatching_Call);
-- For Call_Scenario S_Id, determine whether the call is dispatching
function Is_Read_Reference (S_Id : Scenario_Rep_Id) return Boolean;
pragma Inline (Is_Read_Reference);
-- For Variable_Reference_Scenario S_Id, determine whether the reference
-- is a read.
function Kind (S_Id : Scenario_Rep_Id) return Scenario_Kind;
pragma Inline (Kind);
-- Obtain the nature of scenario S_Id
function Level (S_Id : Scenario_Rep_Id) return Enclosing_Level_Kind;
pragma Inline (Level);
-- Obtain the enclosing level of scenario S_Id
procedure Set_Activated_Task_Objects
(S_Id : Scenario_Rep_Id;
Task_Objs : NE_List.Doubly_Linked_List);
pragma Inline (Set_Activated_Task_Objects);
-- For Task_Activation_Scenario S_Id, set the list of task objects
-- activated by the scenario to Task_Objs.
procedure Set_Activated_Task_Type
(S_Id : Scenario_Rep_Id;
Task_Typ : Entity_Id);
pragma Inline (Set_Activated_Task_Type);
-- For Task_Activation_Scenario S_Id, set the currently activated task
-- type to Task_Typ.
function SPARK_Mode_Of
(S_Id : Scenario_Rep_Id) return Extended_SPARK_Mode;
pragma Inline (SPARK_Mode_Of);
-- Obtain the SPARK mode of scenario S_Id
function Target (S_Id : Scenario_Rep_Id) return Entity_Id;
pragma Inline (Target);
-- Obtain the target of scenario S_Id
-----------------------
-- Target attributes --
-----------------------
function Barrier_Body_Declaration (T_Id : Target_Rep_Id) return Node_Id;
pragma Inline (Barrier_Body_Declaration);
-- For Subprogram_Target T_Id, obtain the declaration of the barrier
-- function's body.
function Body_Declaration (T_Id : Target_Rep_Id) return Node_Id;
pragma Inline (Body_Declaration);
-- Obtain the declaration of the body which belongs to target T_Id
procedure Disable_Elaboration_Checks (T_Id : Target_Rep_Id);
pragma Inline (Disable_Elaboration_Checks);
-- Disable elaboration checks of target T_Id
function Elaboration_Checks_OK (T_Id : Target_Rep_Id) return Boolean;
pragma Inline (Elaboration_Checks_OK);
-- Determine whether target T_Id may be subjected to elaboration checks
function Elaboration_Warnings_OK (T_Id : Target_Rep_Id) return Boolean;
pragma Inline (Elaboration_Warnings_OK);
-- Determine whether target T_Id may be subjected to elaboration
-- warnings.
function Ghost_Mode_Of (T_Id : Target_Rep_Id) return Extended_Ghost_Mode;
pragma Inline (Ghost_Mode_Of);
-- Obtain the Ghost mode of target T_Id
function Kind (T_Id : Target_Rep_Id) return Target_Kind;
pragma Inline (Kind);
-- Obtain the nature of target T_Id
function SPARK_Mode_Of (T_Id : Target_Rep_Id) return Extended_SPARK_Mode;
pragma Inline (SPARK_Mode_Of);
-- Obtain the SPARK mode of target T_Id
function Spec_Declaration (T_Id : Target_Rep_Id) return Node_Id;
pragma Inline (Spec_Declaration);
-- Obtain the declaration of the spec which belongs to target T_Id
function Unit (T_Id : Target_Rep_Id) return Entity_Id;
pragma Inline (Unit);
-- Obtain the unit where the target is defined
function Variable_Declaration (T_Id : Target_Rep_Id) return Node_Id;
pragma Inline (Variable_Declaration);
-- For Variable_Target T_Id, obtain the declaration of the variable
-----------------
-- Maintenance --
-----------------
procedure Finalize_Internal_Representation;
pragma Inline (Finalize_Internal_Representation);
-- Finalize all internal data structures
procedure Initialize_Internal_Representation;
pragma Inline (Initialize_Internal_Representation);
-- Initialize all internal data structures
end Internal_Representation;
use Internal_Representation;
-- The following package provides functionality for recording pieces of the
-- invocation graph in the ALI file of the main unit.
package Invocation_Graph is
---------
-- API --
---------
procedure Record_Invocation_Graph;
pragma Inline (Record_Invocation_Graph);
-- Process all declaration, instantiation, and library level scenarios,
-- along with invocation construct within the spec and body of the main
-- unit to determine whether any of these reach into an external unit.
-- If such a path exists, encode in the ALI file of the main unit.
-----------------
-- Maintenance --
-----------------
procedure Finalize_Invocation_Graph;
pragma Inline (Finalize_Invocation_Graph);
-- Finalize all internal data structures
procedure Initialize_Invocation_Graph;
pragma Inline (Initialize_Invocation_Graph);
-- Initialize all internal data structures
end Invocation_Graph;
use Invocation_Graph;
-- The following package stores scenarios
package Scenario_Storage is
---------
-- API --
---------
procedure Add_Declaration_Scenario (N : Node_Id);
pragma Inline (Add_Declaration_Scenario);
-- Save declaration level scenario N
procedure Add_Dynamic_ABE_Check_Scenario (N : Node_Id);
pragma Inline (Add_Dynamic_ABE_Check_Scenario);
-- Save scenario N for conditional ABE check installation purposes when
-- the dynamic model is in effect.
procedure Add_Library_Body_Scenario (N : Node_Id);
pragma Inline (Add_Library_Body_Scenario);
-- Save library-level body scenario N
procedure Add_Library_Spec_Scenario (N : Node_Id);
pragma Inline (Add_Library_Spec_Scenario);
-- Save library-level spec scenario N
procedure Add_SPARK_Scenario (N : Node_Id);
pragma Inline (Add_SPARK_Scenario);
-- Save SPARK scenario N
procedure Delete_Scenario (N : Node_Id);
pragma Inline (Delete_Scenario);
-- Delete arbitrary scenario N
function Iterate_Declaration_Scenarios return NE_Set.Iterator;
pragma Inline (Iterate_Declaration_Scenarios);
-- Obtain an iterator over all declaration level scenarios
function Iterate_Dynamic_ABE_Check_Scenarios return NE_Set.Iterator;
pragma Inline (Iterate_Dynamic_ABE_Check_Scenarios);
-- Obtain an iterator over all scenarios that require a conditional ABE
-- check when the dynamic model is in effect.
function Iterate_Library_Body_Scenarios return NE_Set.Iterator;
pragma Inline (Iterate_Library_Body_Scenarios);
-- Obtain an iterator over all library level body scenarios
function Iterate_Library_Spec_Scenarios return NE_Set.Iterator;
pragma Inline (Iterate_Library_Spec_Scenarios);
-- Obtain an iterator over all library level spec scenarios
function Iterate_SPARK_Scenarios return NE_Set.Iterator;
pragma Inline (Iterate_SPARK_Scenarios);
-- Obtain an iterator over all SPARK scenarios
procedure Replace_Scenario (Old_N : Node_Id; New_N : Node_Id);
pragma Inline (Replace_Scenario);
-- Replace scenario Old_N with scenario New_N
-----------------
-- Maintenance --
-----------------
procedure Finalize_Scenario_Storage;
pragma Inline (Finalize_Scenario_Storage);
-- Finalize all internal data structures
procedure Initialize_Scenario_Storage;
pragma Inline (Initialize_Scenario_Storage);
-- Initialize all internal data structures
end Scenario_Storage;
use Scenario_Storage;
-- The following package provides various semantic predicates
package Semantics is
---------
-- API --
---------
function Is_Accept_Alternative_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Accept_Alternative_Proc);
-- Determine whether arbitrary entity Id denotes an internally generated
-- procedure which encapsulates the statements of an accept alternative.
function Is_Activation_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Activation_Proc);
-- Determine whether arbitrary entity Id denotes a runtime procedure in
-- charge with activating tasks.
function Is_Ada_Semantic_Target (Id : Entity_Id) return Boolean;
pragma Inline (Is_Ada_Semantic_Target);
-- Determine whether arbitrary entity Id denodes a source or internally
-- generated subprogram which emulates Ada semantics.
function Is_Assertion_Pragma_Target (Id : Entity_Id) return Boolean;
pragma Inline (Is_Assertion_Pragma_Target);
-- Determine whether arbitrary entity Id denotes a procedure which
-- varifies the run-time semantics of an assertion pragma.
function Is_Bodiless_Subprogram (Subp_Id : Entity_Id) return Boolean;
pragma Inline (Is_Bodiless_Subprogram);
-- Determine whether subprogram Subp_Id will never have a body
function Is_Bridge_Target (Id : Entity_Id) return Boolean;
pragma Inline (Is_Bridge_Target);
-- Determine whether arbitrary entity Id denotes a bridge target
function Is_Controlled_Proc
(Subp_Id : Entity_Id;
Subp_Nam : Name_Id) return Boolean;
pragma Inline (Is_Controlled_Proc);
-- Determine whether subprogram Subp_Id denotes controlled type
-- primitives Adjust, Finalize, or Initialize as denoted by name
-- Subp_Nam.
function Is_Default_Initial_Condition_Proc
(Id : Entity_Id) return Boolean;
pragma Inline (Is_Default_Initial_Condition_Proc);
-- Determine whether arbitrary entity Id denotes internally generated
-- routine Default_Initial_Condition.
function Is_Finalizer_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Finalizer_Proc);
-- Determine whether arbitrary entity Id denotes internally generated
-- routine _Finalizer.
function Is_Initial_Condition_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Initial_Condition_Proc);
-- Determine whether arbitrary entity Id denotes internally generated
-- routine Initial_Condition.
function Is_Initialized (Obj_Decl : Node_Id) return Boolean;
pragma Inline (Is_Initialized);
-- Determine whether object declaration Obj_Decl is initialized
function Is_Invariant_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Invariant_Proc);
-- Determine whether arbitrary entity Id denotes an invariant procedure
function Is_Non_Library_Level_Encapsulator (N : Node_Id) return Boolean;
pragma Inline (Is_Non_Library_Level_Encapsulator);
-- Determine whether arbitrary node N is a non-library encapsulator
function Is_Partial_Invariant_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Partial_Invariant_Proc);
-- Determine whether arbitrary entity Id denotes a partial invariant
-- procedure.
function Is_Postconditions_Proc (Id : Entity_Id) return Boolean;
pragma Inline (Is_Postconditions_Proc);
-- Determine whether arbitrary entity Id denotes internally generated
-- routine _Postconditions.
function Is_Preelaborated_Unit (Id : Entity_Id) return Boolean;
pragma Inline (Is_Preelaborated_Unit);
-- Determine whether arbitrary entity Id denotes a unit which is subject
-- to one of the following pragmas:
--
-- * Preelaborable
-- * Pure
-- * Remote_Call_Interface
-- * Remote_Types
-- * Shared_Passive
function Is_Protected_Entry (Id : Entity_Id) return Boolean;
pragma Inline (Is_Protected_Entry);
-- Determine whether arbitrary entity Id denotes a protected entry
function Is_Protected_Subp (Id : Entity_Id) return Boolean;
pragma Inline (Is_Protected_Subp);
-- Determine whether entity Id denotes a protected subprogram
function Is_Protected_Body_Subp (Id : Entity_Id) return Boolean;
pragma Inline (Is_Protected_Body_Subp);
-- Determine whether entity Id denotes the protected or unprotected
-- version of a protected subprogram.
function Is_Scenario (N : Node_Id) return Boolean;
pragma Inline (Is_Scenario);
-- Determine whether attribute node N denotes a scenario. The scenario
-- may not necessarily be eligible for ABE processing.
function Is_SPARK_Semantic_Target (Id : Entity_Id) return Boolean;
pragma Inline (Is_SPARK_Semantic_Target);
-- Determine whether arbitrary entity Id nodes a source or internally
-- generated subprogram which emulates SPARK semantics.
function Is_Subprogram_Inst (Id : Entity_Id) return Boolean;
pragma Inline (Is_Subprogram_Inst);
-- Determine whether arbitrary entity Id denotes a subprogram instance
function Is_Suitable_Access_Taken (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Access_Taken);
-- Determine whether arbitrary node N denotes a suitable attribute for
-- ABE processing.
function Is_Suitable_Call (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Call);
-- Determine whether arbitrary node N denotes a suitable call for ABE
-- processing.
function Is_Suitable_Instantiation (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Instantiation);
-- Determine whether arbitrary node N is a suitable instantiation for
-- ABE processing.
function Is_Suitable_SPARK_Derived_Type (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_SPARK_Derived_Type);
-- Determine whether arbitrary node N denotes a suitable derived type
-- declaration for ABE processing using the SPARK rules.
function Is_Suitable_SPARK_Instantiation (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_SPARK_Instantiation);
-- Determine whether arbitrary node N denotes a suitable instantiation
-- for ABE processing using the SPARK rules.
function Is_Suitable_SPARK_Refined_State_Pragma
(N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_SPARK_Refined_State_Pragma);
-- Determine whether arbitrary node N denotes a suitable Refined_State
-- pragma for ABE processing using the SPARK rules.
function Is_Suitable_Variable_Assignment (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Variable_Assignment);
-- Determine whether arbitrary node N denotes a suitable assignment for
-- ABE processing.
function Is_Suitable_Variable_Reference (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Variable_Reference);
-- Determine whether arbitrary node N is a suitable variable reference
-- for ABE processing.
function Is_Task_Entry (Id : Entity_Id) return Boolean;
pragma Inline (Is_Task_Entry);
-- Determine whether arbitrary entity Id denotes a task entry
function Is_Up_Level_Target
(Targ_Decl : Node_Id;
In_State : Processing_In_State) return Boolean;
pragma Inline (Is_Up_Level_Target);
-- Determine whether the current root resides at the declaration level.
-- If this is the case, determine whether a target with by declaration
-- Target_Decl is within a context which encloses the current root or is
-- in a different unit. In_State is the current state of the Processing
-- phase.
end Semantics;
use Semantics;
-- The following package provides the main entry point for SPARK-related
-- checks and diagnostics.
package SPARK_Processor is
---------
-- API --
---------
procedure Check_SPARK_Model_In_Effect;
pragma Inline (Check_SPARK_Model_In_Effect);
-- Determine whether a suitable elaboration model is currently in effect
-- for verifying SPARK rules. Emit a warning if this is not the case.
procedure Check_SPARK_Scenarios;
pragma Inline (Check_SPARK_Scenarios);
-- Examine SPARK scenarios which are not necessarily executable during
-- elaboration, but still requires elaboration-related checks.
end SPARK_Processor;
use SPARK_Processor;
-----------------------
-- Local subprograms --
-----------------------
function Assignment_Target (Asmt : Node_Id) return Node_Id;
pragma Inline (Assignment_Target);
-- Obtain the target of assignment statement Asmt
function Call_Name (Call : Node_Id) return Node_Id;
pragma Inline (Call_Name);
-- Obtain the name of an entry, operator, or subprogram call Call
function Canonical_Subprogram (Subp_Id : Entity_Id) return Entity_Id;
pragma Inline (Canonical_Subprogram);
-- Obtain the uniform canonical entity of subprogram Subp_Id
function Compilation_Unit (Unit_Id : Entity_Id) return Node_Id;
pragma Inline (Compilation_Unit);
-- Return the N_Compilation_Unit node of unit Unit_Id
function Elaboration_Phase_Active return Boolean;
pragma Inline (Elaboration_Phase_Active);
-- Determine whether the elaboration phase of the compilation has started
procedure Error_Preelaborated_Call (N : Node_Id);
-- Give an error or warning for a non-static/non-preelaborable call in a
-- preelaborated unit.
procedure Finalize_All_Data_Structures;
pragma Inline (Finalize_All_Data_Structures);
-- Destroy all internal data structures
function Find_Enclosing_Instance (N : Node_Id) return Node_Id;
pragma Inline (Find_Enclosing_Instance);
-- Find the declaration or body of the nearest expanded instance which
-- encloses arbitrary node N. Return Empty if no such instance exists.
function Find_Top_Unit (N : Node_Or_Entity_Id) return Entity_Id;
pragma Inline (Find_Top_Unit);
-- Return the top unit which contains arbitrary node or entity N. The unit
-- is obtained by logically unwinding instantiations and subunits when N
-- resides within one.
function Find_Unit_Entity (N : Node_Id) return Entity_Id;
pragma Inline (Find_Unit_Entity);
-- Return the entity of unit N
function First_Formal_Type (Subp_Id : Entity_Id) return Entity_Id;
pragma Inline (First_Formal_Type);
-- Return the type of subprogram Subp_Id's first formal parameter. If the
-- subprogram lacks formal parameters, return Empty.
function Has_Body (Pack_Decl : Node_Id) return Boolean;
pragma Inline (Has_Body);
-- Determine whether package declaration Pack_Decl has a corresponding body
-- or would eventually have one.
function In_External_Instance
(N : Node_Id;
Target_Decl : Node_Id) return Boolean;
pragma Inline (In_External_Instance);
-- Determine whether a target desctibed by its declaration Target_Decl
-- resides in a package instance which is external to scenario N.
function In_Main_Context (N : Node_Id) return Boolean;
pragma Inline (In_Main_Context);
-- Determine whether arbitrary node N appears within the main compilation
-- unit.
function In_Same_Context
(N1 : Node_Id;
N2 : Node_Id;
Nested_OK : Boolean := False) return Boolean;
pragma Inline (In_Same_Context);
-- Determine whether two arbitrary nodes N1 and N2 appear within the same
-- context ignoring enclosing library levels. Nested_OK should be set when
-- the context of N1 can enclose that of N2.
procedure Initialize_All_Data_Structures;
pragma Inline (Initialize_All_Data_Structures);
-- Create all internal data structures
function Instantiated_Generic (Inst : Node_Id) return Entity_Id;
pragma Inline (Instantiated_Generic);
-- Obtain the generic instantiated by instance Inst
function Is_Safe_Activation
(Call : Node_Id;
Task_Rep : Target_Rep_Id) return Boolean;
pragma Inline (Is_Safe_Activation);
-- Determine whether activation call Call which activates an object of a
-- task type described by representation Task_Rep is always ABE-safe.
function Is_Safe_Call
(Call : Node_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id) return Boolean;
pragma Inline (Is_Safe_Call);
-- Determine whether call Call which invokes entry, operator, or subprogram
-- Subp_Id is always ABE-safe. Subp_Rep is the representation of the entry,
-- operator, or subprogram.
function Is_Safe_Instantiation
(Inst : Node_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id) return Boolean;
pragma Inline (Is_Safe_Instantiation);
-- Determine whether instantiation Inst which instantiates generic Gen_Id
-- is always ABE-safe. Gen_Rep is the representation of the generic.
function Is_Same_Unit
(Unit_1 : Entity_Id;
Unit_2 : Entity_Id) return Boolean;
pragma Inline (Is_Same_Unit);
-- Determine whether entities Unit_1 and Unit_2 denote the same unit
function Main_Unit_Entity return Entity_Id;
pragma Inline (Main_Unit_Entity);
-- Return the entity of the main unit
function Non_Private_View (Typ : Entity_Id) return Entity_Id;
pragma Inline (Non_Private_View);
-- Return the full view of private type Typ if available, otherwise return
-- type Typ.
function Scenario (N : Node_Id) return Node_Id;
pragma Inline (Scenario);
-- Return the appropriate scenario node for scenario N
procedure Set_Elaboration_Phase (Status : Elaboration_Phase_Status);
pragma Inline (Set_Elaboration_Phase);
-- Change the status of the elaboration phase of the compiler to Status
procedure Spec_And_Body_From_Entity
(Id : Node_Id;
Spec_Decl : out Node_Id;
Body_Decl : out Node_Id);
pragma Inline (Spec_And_Body_From_Entity);
-- Given arbitrary entity Id representing a construct with a spec and body,
-- retrieve declaration of the spec in Spec_Decl and the declaration of the
-- body in Body_Decl.
procedure Spec_And_Body_From_Node
(N : Node_Id;
Spec_Decl : out Node_Id;
Body_Decl : out Node_Id);
pragma Inline (Spec_And_Body_From_Node);
-- Given arbitrary node N representing a construct with a spec and body,
-- retrieve declaration of the spec in Spec_Decl and the declaration of
-- the body in Body_Decl.
function Static_Elaboration_Checks return Boolean;
pragma Inline (Static_Elaboration_Checks);
-- Determine whether the static model is in effect
function Unit_Entity (Unit_Id : Entity_Id) return Entity_Id;
pragma Inline (Unit_Entity);
-- Return the entity of the initial declaration for unit Unit_Id
procedure Update_Elaboration_Scenario (New_N : Node_Id; Old_N : Node_Id);
pragma Inline (Update_Elaboration_Scenario);
-- Update all relevant internal data structures when scenario Old_N is
-- transformed into scenario New_N by Atree.Rewrite.
----------------------
-- Active_Scenarios --
----------------------
package body Active_Scenarios is
-----------------------
-- Local subprograms --
-----------------------
procedure Output_Access_Taken
(Attr : Node_Id;
Attr_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Access_Taken);
-- Emit a specific diagnostic message for 'Access attribute reference
-- Attr with representation Attr_Rep. The message is associated with
-- node Error_Nod.
procedure Output_Active_Scenario
(N : Node_Id;
Error_Nod : Node_Id;
In_State : Processing_In_State);
pragma Inline (Output_Active_Scenario);
-- Top level dispatcher for outputting a scenario. Emit a specific
-- diagnostic message for scenario N. The message is associated with
-- node Error_Nod. In_State is the current state of the Processing
-- phase.
procedure Output_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Call);
-- Emit a diagnostic message for call Call with representation Call_Rep.
-- The message is associated with node Error_Nod.
procedure Output_Header (Error_Nod : Node_Id);
pragma Inline (Output_Header);
-- Emit a specific diagnostic message for the unit of the root scenario.
-- The message is associated with node Error_Nod.
procedure Output_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Instantiation);
-- Emit a specific diagnostic message for instantiation Inst with
-- representation Inst_Rep. The message is associated with node
-- Error_Nod.
procedure Output_Refined_State_Pragma
(Prag : Node_Id;
Prag_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Refined_State_Pragma);
-- Emit a specific diagnostic message for Refined_State pragma Prag
-- with representation Prag_Rep. The message is associated with node
-- Error_Nod.
procedure Output_Task_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Task_Activation);
-- Emit a specific diagnostic message for activation call Call
-- with representation Call_Rep. The message is associated with
-- node Error_Nod.
procedure Output_Variable_Assignment
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Variable_Assignment);
-- Emit a specific diagnostic message for assignment statement Asmt
-- with representation Asmt_Rep. The message is associated with node
-- Error_Nod.
procedure Output_Variable_Reference
(Ref : Node_Id;
Ref_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id);
pragma Inline (Output_Variable_Reference);
-- Emit a specific diagnostic message for read reference Ref with
-- representation Ref_Rep. The message is associated with node
-- Error_Nod.
-------------------
-- Output_Access --
-------------------
procedure Output_Access_Taken
(Attr : Node_Id;
Attr_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
Subp_Id : constant Entity_Id := Target (Attr_Rep);
begin
Error_Msg_Name_1 := Attribute_Name (Attr);
Error_Msg_Sloc := Sloc (Attr);
Error_Msg_NE ("\\ % of & taken #", Error_Nod, Subp_Id);
end Output_Access_Taken;
----------------------------
-- Output_Active_Scenario --
----------------------------
procedure Output_Active_Scenario
(N : Node_Id;
Error_Nod : Node_Id;
In_State : Processing_In_State)
is
Scen : constant Node_Id := Scenario (N);
Scen_Rep : Scenario_Rep_Id;
begin
-- 'Access
if Is_Suitable_Access_Taken (Scen) then
Output_Access_Taken
(Attr => Scen,
Attr_Rep => Scenario_Representation_Of (Scen, In_State),
Error_Nod => Error_Nod);
-- Call or task activation
elsif Is_Suitable_Call (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
if Kind (Scen_Rep) = Call_Scenario then
Output_Call
(Call => Scen,
Call_Rep => Scen_Rep,
Error_Nod => Error_Nod);
else
pragma Assert (Kind (Scen_Rep) = Task_Activation_Scenario);
Output_Task_Activation
(Call => Scen,
Call_Rep => Scen_Rep,
Error_Nod => Error_Nod);
end if;
-- Instantiation
elsif Is_Suitable_Instantiation (Scen) then
Output_Instantiation
(Inst => Scen,
Inst_Rep => Scenario_Representation_Of (Scen, In_State),
Error_Nod => Error_Nod);
-- Pragma Refined_State
elsif Is_Suitable_SPARK_Refined_State_Pragma (Scen) then
Output_Refined_State_Pragma
(Prag => Scen,
Prag_Rep => Scenario_Representation_Of (Scen, In_State),
Error_Nod => Error_Nod);
-- Variable assignment
elsif Is_Suitable_Variable_Assignment (Scen) then
Output_Variable_Assignment
(Asmt => Scen,
Asmt_Rep => Scenario_Representation_Of (Scen, In_State),
Error_Nod => Error_Nod);
-- Variable reference
elsif Is_Suitable_Variable_Reference (Scen) then
Output_Variable_Reference
(Ref => Scen,
Ref_Rep => Scenario_Representation_Of (Scen, In_State),
Error_Nod => Error_Nod);
end if;
end Output_Active_Scenario;
-----------------------------
-- Output_Active_Scenarios --
-----------------------------
procedure Output_Active_Scenarios
(Error_Nod : Node_Id;
In_State : Processing_In_State)
is
package Scenarios renames Active_Scenario_Stack;
Header_Posted : Boolean := False;
begin
-- Output the contents of the active scenario stack starting from the
-- bottom, or the least recent scenario.
for Index in Scenarios.First .. Scenarios.Last loop
if not Header_Posted then
Output_Header (Error_Nod);
Header_Posted := True;
end if;
Output_Active_Scenario
(N => Scenarios.Table (Index),
Error_Nod => Error_Nod,
In_State => In_State);
end loop;
end Output_Active_Scenarios;
-----------------
-- Output_Call --
-----------------
procedure Output_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
procedure Output_Accept_Alternative (Alt_Id : Entity_Id);
pragma Inline (Output_Accept_Alternative);
-- Emit a specific diagnostic message concerning accept alternative
-- with entity Alt_Id.
procedure Output_Call (Subp_Id : Entity_Id; Kind : String);
pragma Inline (Output_Call);
-- Emit a specific diagnostic message concerning a call of kind Kind
-- which invokes subprogram Subp_Id.
procedure Output_Type_Actions (Subp_Id : Entity_Id; Action : String);
pragma Inline (Output_Type_Actions);
-- Emit a specific diagnostic message concerning action Action of a
-- type performed by subprogram Subp_Id.
procedure Output_Verification_Call
(Pred : String;
Id : Entity_Id;
Id_Kind : String);
pragma Inline (Output_Verification_Call);
-- Emit a specific diagnostic message concerning the verification of
-- predicate Pred applied to related entity Id with kind Id_Kind.
-------------------------------
-- Output_Accept_Alternative --
-------------------------------
procedure Output_Accept_Alternative (Alt_Id : Entity_Id) is
Entry_Id : constant Entity_Id := Receiving_Entry (Alt_Id);
begin
pragma Assert (Present (Entry_Id));
Error_Msg_NE ("\\ entry & selected #", Error_Nod, Entry_Id);
end Output_Accept_Alternative;
-----------------
-- Output_Call --
-----------------
procedure Output_Call (Subp_Id : Entity_Id; Kind : String) is
begin
Error_Msg_NE ("\\ " & Kind & " & called #", Error_Nod, Subp_Id);
end Output_Call;
-------------------------
-- Output_Type_Actions --
-------------------------
procedure Output_Type_Actions
(Subp_Id : Entity_Id;
Action : String)
is
Typ : constant Entity_Id := First_Formal_Type (Subp_Id);
begin
pragma Assert (Present (Typ));
Error_Msg_NE
("\\ " & Action & " actions for type & #", Error_Nod, Typ);
end Output_Type_Actions;
------------------------------
-- Output_Verification_Call --
------------------------------
procedure Output_Verification_Call
(Pred : String;
Id : Entity_Id;
Id_Kind : String)
is
begin
pragma Assert (Present (Id));
Error_Msg_NE
("\\ " & Pred & " of " & Id_Kind & " & verified #",
Error_Nod, Id);
end Output_Verification_Call;
-- Local variables
Subp_Id : constant Entity_Id := Target (Call_Rep);
-- Start of processing for Output_Call
begin
Error_Msg_Sloc := Sloc (Call);
-- Accept alternative
if Is_Accept_Alternative_Proc (Subp_Id) then
Output_Accept_Alternative (Subp_Id);
-- Adjustment
elsif Is_TSS (Subp_Id, TSS_Deep_Adjust) then
Output_Type_Actions (Subp_Id, "adjustment");
-- Default_Initial_Condition
elsif Is_Default_Initial_Condition_Proc (Subp_Id) then
Output_Verification_Call
(Pred => "Default_Initial_Condition",
Id => First_Formal_Type (Subp_Id),
Id_Kind => "type");
-- Entries
elsif Is_Protected_Entry (Subp_Id) then
Output_Call (Subp_Id, "entry");
-- Task entry calls are never processed because the entry being
-- invoked does not have a corresponding "body", it has a select. A
-- task entry call appears in the stack of active scenarios for the
-- sole purpose of checking No_Entry_Calls_In_Elaboration_Code and
-- nothing more.
elsif Is_Task_Entry (Subp_Id) then
null;
-- Finalization
elsif Is_TSS (Subp_Id, TSS_Deep_Finalize) then
Output_Type_Actions (Subp_Id, "finalization");
-- Calls to _Finalizer procedures must not appear in the output
-- because this creates confusing noise.
elsif Is_Finalizer_Proc (Subp_Id) then
null;
-- Initial_Condition
elsif Is_Initial_Condition_Proc (Subp_Id) then
Output_Verification_Call
(Pred => "Initial_Condition",
Id => Find_Enclosing_Scope (Call),
Id_Kind => "package");
-- Initialization
elsif Is_Init_Proc (Subp_Id)
or else Is_TSS (Subp_Id, TSS_Deep_Initialize)
then
Output_Type_Actions (Subp_Id, "initialization");
-- Invariant
elsif Is_Invariant_Proc (Subp_Id) then
Output_Verification_Call
(Pred => "invariants",
Id => First_Formal_Type (Subp_Id),
Id_Kind => "type");
-- Partial invariant calls must not appear in the output because this
-- creates confusing noise. Note that a partial invariant is always
-- invoked by the "full" invariant which is already placed on the
-- stack.
elsif Is_Partial_Invariant_Proc (Subp_Id) then
null;
-- _Postconditions
elsif Is_Postconditions_Proc (Subp_Id) then
Output_Verification_Call
(Pred => "postconditions",
Id => Find_Enclosing_Scope (Call),
Id_Kind => "subprogram");
-- Subprograms must come last because some of the previous cases fall
-- under this category.
elsif Ekind (Subp_Id) = E_Function then
Output_Call (Subp_Id, "function");
elsif Ekind (Subp_Id) = E_Procedure then
Output_Call (Subp_Id, "procedure");
else
pragma Assert (False);
return;
end if;
end Output_Call;
-------------------
-- Output_Header --
-------------------
procedure Output_Header (Error_Nod : Node_Id) is
Unit_Id : constant Entity_Id := Find_Top_Unit (Root_Scenario);
begin
if Ekind (Unit_Id) = E_Package then
Error_Msg_NE ("\\ spec of unit & elaborated", Error_Nod, Unit_Id);
elsif Ekind (Unit_Id) = E_Package_Body then
Error_Msg_NE ("\\ body of unit & elaborated", Error_Nod, Unit_Id);
else
Error_Msg_NE ("\\ in body of unit &", Error_Nod, Unit_Id);
end if;
end Output_Header;
--------------------------
-- Output_Instantiation --
--------------------------
procedure Output_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
procedure Output_Instantiation (Gen_Id : Entity_Id; Kind : String);
pragma Inline (Output_Instantiation);
-- Emit a specific diagnostic message concerning an instantiation of
-- generic unit Gen_Id. Kind denotes the kind of the instantiation.
--------------------------
-- Output_Instantiation --
--------------------------
procedure Output_Instantiation (Gen_Id : Entity_Id; Kind : String) is
begin
Error_Msg_NE
("\\ " & Kind & " & instantiated as & #", Error_Nod, Gen_Id);
end Output_Instantiation;
-- Local variables
Gen_Id : constant Entity_Id := Target (Inst_Rep);
-- Start of processing for Output_Instantiation
begin
Error_Msg_Node_2 := Defining_Entity (Inst);
Error_Msg_Sloc := Sloc (Inst);
if Nkind (Inst) = N_Function_Instantiation then
Output_Instantiation (Gen_Id, "function");
elsif Nkind (Inst) = N_Package_Instantiation then
Output_Instantiation (Gen_Id, "package");
elsif Nkind (Inst) = N_Procedure_Instantiation then
Output_Instantiation (Gen_Id, "procedure");
else
pragma Assert (False);
return;
end if;
end Output_Instantiation;
---------------------------------
-- Output_Refined_State_Pragma --
---------------------------------
procedure Output_Refined_State_Pragma
(Prag : Node_Id;
Prag_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
pragma Unreferenced (Prag_Rep);
begin
Error_Msg_Sloc := Sloc (Prag);
Error_Msg_N ("\\ refinement constituents read #", Error_Nod);
end Output_Refined_State_Pragma;
----------------------------
-- Output_Task_Activation --
----------------------------
procedure Output_Task_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
pragma Unreferenced (Call_Rep);
function Find_Activator return Entity_Id;
-- Find the nearest enclosing construct which houses call Call
--------------------
-- Find_Activator --
--------------------
function Find_Activator return Entity_Id is
Par : Node_Id;
begin
-- Climb the parent chain looking for a package [body] or a
-- construct with a statement sequence.
Par := Parent (Call);
while Present (Par) loop
if Nkind (Par) in N_Package_Body | N_Package_Declaration then
return Defining_Entity (Par);
elsif Nkind (Par) = N_Handled_Sequence_Of_Statements then
return Defining_Entity (Parent (Par));
end if;
Par := Parent (Par);
end loop;
return Empty;
end Find_Activator;
-- Local variables
Activator : constant Entity_Id := Find_Activator;
-- Start of processing for Output_Task_Activation
begin
pragma Assert (Present (Activator));
Error_Msg_NE ("\\ local tasks of & activated", Error_Nod, Activator);
end Output_Task_Activation;
--------------------------------
-- Output_Variable_Assignment --
--------------------------------
procedure Output_Variable_Assignment
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
Var_Id : constant Entity_Id := Target (Asmt_Rep);
begin
Error_Msg_Sloc := Sloc (Asmt);
Error_Msg_NE ("\\ variable & assigned #", Error_Nod, Var_Id);
end Output_Variable_Assignment;
-------------------------------
-- Output_Variable_Reference --
-------------------------------
procedure Output_Variable_Reference
(Ref : Node_Id;
Ref_Rep : Scenario_Rep_Id;
Error_Nod : Node_Id)
is
Var_Id : constant Entity_Id := Target (Ref_Rep);
begin
Error_Msg_Sloc := Sloc (Ref);
Error_Msg_NE ("\\ variable & read #", Error_Nod, Var_Id);
end Output_Variable_Reference;
-------------------------
-- Pop_Active_Scenario --
-------------------------
procedure Pop_Active_Scenario (N : Node_Id) is
package Scenarios renames Active_Scenario_Stack;
Top : Node_Id renames Scenarios.Table (Scenarios.Last);
begin
pragma Assert (Top = N);
Scenarios.Decrement_Last;
end Pop_Active_Scenario;
--------------------------
-- Push_Active_Scenario --
--------------------------
procedure Push_Active_Scenario (N : Node_Id) is
begin
Active_Scenario_Stack.Append (N);
end Push_Active_Scenario;
-------------------
-- Root_Scenario --
-------------------
function Root_Scenario return Node_Id is
package Scenarios renames Active_Scenario_Stack;
begin
-- Ensure that the scenario stack has at least one active scenario in
-- it. The one at the bottom (index First) is the root scenario.
pragma Assert (Scenarios.Last >= Scenarios.First);
return Scenarios.Table (Scenarios.First);
end Root_Scenario;
end Active_Scenarios;
--------------------------
-- Activation_Processor --
--------------------------
package body Activation_Processor is
------------------------
-- Process_Activation --
------------------------
procedure Process_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Processor : Activation_Processor_Ptr;
In_State : Processing_In_State)
is
procedure Process_Task_Object (Obj_Id : Entity_Id; Typ : Entity_Id);
pragma Inline (Process_Task_Object);
-- Invoke Processor for task object Obj_Id of type Typ
procedure Process_Task_Objects
(Task_Objs : NE_List.Doubly_Linked_List);
pragma Inline (Process_Task_Objects);
-- Invoke Processor for all task objects found in list Task_Objs
procedure Traverse_List
(List : List_Id;
Task_Objs : NE_List.Doubly_Linked_List);
pragma Inline (Traverse_List);
-- Traverse declarative or statement list List while searching for
-- objects of a task type, or containing task components. If such an
-- object is found, first save it in list Task_Objs and then invoke
-- Processor on it.
-------------------------
-- Process_Task_Object --
-------------------------
procedure Process_Task_Object (Obj_Id : Entity_Id; Typ : Entity_Id) is
Root_Typ : constant Entity_Id :=
Non_Private_View (Root_Type (Typ));
Comp_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Root_Rep : Target_Rep_Id;
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
begin
if Is_Task_Type (Typ) then
Obj_Rep := Target_Representation_Of (Obj_Id, New_In_State);
Root_Rep := Target_Representation_Of (Root_Typ, New_In_State);
-- Warnings are suppressed when a prior scenario is already in
-- that mode, or when the object, activation call, or task type
-- have warnings suppressed. Update the state of the Processing
-- phase to reflect this.
New_In_State.Suppress_Warnings :=
New_In_State.Suppress_Warnings
or else not Elaboration_Warnings_OK (Call_Rep)
or else not Elaboration_Warnings_OK (Obj_Rep)
or else not Elaboration_Warnings_OK (Root_Rep);
-- Update the state of the Processing phase to indicate that
-- any further traversal is now within a task body.
New_In_State.Within_Task_Body := True;
-- Associate the current task type with the activation call
Set_Activated_Task_Type (Call_Rep, Root_Typ);
-- Process the activation of the current task object by calling
-- the supplied processor.
Processor.all
(Call => Call,
Call_Rep => Call_Rep,
Obj_Id => Obj_Id,
Obj_Rep => Obj_Rep,
Task_Typ => Root_Typ,
Task_Rep => Root_Rep,
In_State => New_In_State);
-- Reset the association between the current task and the
-- activtion call.
Set_Activated_Task_Type (Call_Rep, Empty);
-- Examine the component type when the object is an array
elsif Is_Array_Type (Typ) and then Has_Task (Root_Typ) then
Process_Task_Object
(Obj_Id => Obj_Id,
Typ => Component_Type (Typ));
-- Examine individual component types when the object is a record
elsif Is_Record_Type (Typ) and then Has_Task (Root_Typ) then
Comp_Id := First_Component (Typ);
while Present (Comp_Id) loop
Process_Task_Object
(Obj_Id => Obj_Id,
Typ => Etype (Comp_Id));
Next_Component (Comp_Id);
end loop;
end if;
end Process_Task_Object;
--------------------------
-- Process_Task_Objects --
--------------------------
procedure Process_Task_Objects
(Task_Objs : NE_List.Doubly_Linked_List)
is
Iter : NE_List.Iterator;
Obj_Id : Entity_Id;
begin
Iter := NE_List.Iterate (Task_Objs);
while NE_List.Has_Next (Iter) loop
NE_List.Next (Iter, Obj_Id);
Process_Task_Object
(Obj_Id => Obj_Id,
Typ => Etype (Obj_Id));
end loop;
end Process_Task_Objects;
-------------------
-- Traverse_List --
-------------------
procedure Traverse_List
(List : List_Id;
Task_Objs : NE_List.Doubly_Linked_List)
is
Item : Node_Id;
Item_Id : Entity_Id;
Item_Typ : Entity_Id;
begin
-- Examine the contents of the list looking for an object
-- declaration of a task type or one that contains a task
-- within.
Item := First (List);
while Present (Item) loop
if Nkind (Item) = N_Object_Declaration then
Item_Id := Defining_Entity (Item);
Item_Typ := Etype (Item_Id);
if Has_Task (Item_Typ) then
-- The object is either of a task type, or contains a
-- task component. Save it in the list of task objects
-- associated with the activation call.
NE_List.Append (Task_Objs, Item_Id);
Process_Task_Object
(Obj_Id => Item_Id,
Typ => Item_Typ);
end if;
end if;
Next (Item);
end loop;
end Traverse_List;
-- Local variables
Context : Node_Id;
Spec : Node_Id;
Task_Objs : NE_List.Doubly_Linked_List;
-- Start of processing for Process_Activation
begin
-- Nothing to do when the activation is a guaranteed ABE
if Is_Known_Guaranteed_ABE (Call) then
return;
end if;
Task_Objs := Activated_Task_Objects (Call_Rep);
-- The activation call has been processed at least once, and all
-- task objects have already been collected. Directly process the
-- objects without having to reexamine the context of the call.
if NE_List.Present (Task_Objs) then
Process_Task_Objects (Task_Objs);
-- Otherwise the activation call is being processed for the first
-- time. Collect all task objects in case the call is reprocessed
-- multiple times.
else
Task_Objs := NE_List.Create;
Set_Activated_Task_Objects (Call_Rep, Task_Objs);
-- Find the context of the activation call where all task objects
-- being activated are declared. This is usually the parent of the
-- call.
Context := Parent (Call);
-- Handle the case where the activation call appears within the
-- handled statements of a block or a body.
if Nkind (Context) = N_Handled_Sequence_Of_Statements then
Context := Parent (Context);
end if;
-- Process all task objects in both the spec and body when the
-- activation call appears in a package body.
if Nkind (Context) = N_Package_Body then
Spec :=
Specification
(Unit_Declaration_Node (Corresponding_Spec (Context)));
Traverse_List
(List => Visible_Declarations (Spec),
Task_Objs => Task_Objs);
Traverse_List
(List => Private_Declarations (Spec),
Task_Objs => Task_Objs);
Traverse_List
(List => Declarations (Context),
Task_Objs => Task_Objs);
-- Process all task objects in the spec when the activation call
-- appears in a package spec.
elsif Nkind (Context) = N_Package_Specification then
Traverse_List
(List => Visible_Declarations (Context),
Task_Objs => Task_Objs);
Traverse_List
(List => Private_Declarations (Context),
Task_Objs => Task_Objs);
-- Otherwise the context must be a block or a body. Process all
-- task objects found in the declarations.
else
pragma Assert
(Nkind (Context) in
N_Block_Statement | N_Entry_Body | N_Protected_Body |
N_Subprogram_Body | N_Task_Body);
Traverse_List
(List => Declarations (Context),
Task_Objs => Task_Objs);
end if;
end if;
end Process_Activation;
end Activation_Processor;
-----------------------
-- Assignment_Target --
-----------------------
function Assignment_Target (Asmt : Node_Id) return Node_Id is
Nam : Node_Id;
begin
Nam := Name (Asmt);
-- When the name denotes an array or record component, find the whole
-- object.
while Nkind (Nam) in
N_Explicit_Dereference | N_Indexed_Component |
N_Selected_Component | N_Slice
loop
Nam := Prefix (Nam);
end loop;
return Nam;
end Assignment_Target;
--------------------
-- Body_Processor --
--------------------
package body Body_Processor is
---------------------
-- Data structures --
---------------------
-- The following map relates scenario lists to subprogram bodies
Nested_Scenarios_Map : NE_List_Map.Dynamic_Hash_Table := NE_List_Map.Nil;
-- The following set contains all subprogram bodies that have been
-- processed by routine Traverse_Body.
Traversed_Bodies_Set : NE_Set.Membership_Set := NE_Set.Nil;
-----------------------
-- Local subprograms --
-----------------------
function Is_Traversed_Body (N : Node_Id) return Boolean;
pragma Inline (Is_Traversed_Body);
-- Determine whether subprogram body N has already been traversed
function Nested_Scenarios
(N : Node_Id) return NE_List.Doubly_Linked_List;
pragma Inline (Nested_Scenarios);
-- Obtain the list of scenarios associated with subprogram body N
procedure Set_Is_Traversed_Body
(N : Node_Id;
Val : Boolean := True);
pragma Inline (Set_Is_Traversed_Body);
-- Mark subprogram body N as traversed depending on value Val
procedure Set_Nested_Scenarios
(N : Node_Id;
Scenarios : NE_List.Doubly_Linked_List);
pragma Inline (Set_Nested_Scenarios);
-- Associate scenario list Scenarios with subprogram body N
-----------------------------
-- Finalize_Body_Processor --
-----------------------------
procedure Finalize_Body_Processor is
begin
NE_List_Map.Destroy (Nested_Scenarios_Map);
NE_Set.Destroy (Traversed_Bodies_Set);
end Finalize_Body_Processor;
-------------------------------
-- Initialize_Body_Processor --
-------------------------------
procedure Initialize_Body_Processor is
begin
Nested_Scenarios_Map := NE_List_Map.Create (250);
Traversed_Bodies_Set := NE_Set.Create (250);
end Initialize_Body_Processor;
-----------------------
-- Is_Traversed_Body --
-----------------------
function Is_Traversed_Body (N : Node_Id) return Boolean is
pragma Assert (Present (N));
begin
return NE_Set.Contains (Traversed_Bodies_Set, N);
end Is_Traversed_Body;
----------------------
-- Nested_Scenarios --
----------------------
function Nested_Scenarios
(N : Node_Id) return NE_List.Doubly_Linked_List
is
pragma Assert (Present (N));
pragma Assert (Nkind (N) = N_Subprogram_Body);
begin
return NE_List_Map.Get (Nested_Scenarios_Map, N);
end Nested_Scenarios;
----------------------------
-- Reset_Traversed_Bodies --
----------------------------
procedure Reset_Traversed_Bodies is
begin
NE_Set.Reset (Traversed_Bodies_Set);
end Reset_Traversed_Bodies;
---------------------------
-- Set_Is_Traversed_Body --
---------------------------
procedure Set_Is_Traversed_Body
(N : Node_Id;
Val : Boolean := True)
is
pragma Assert (Present (N));
begin
if Val then
NE_Set.Insert (Traversed_Bodies_Set, N);
else
NE_Set.Delete (Traversed_Bodies_Set, N);
end if;
end Set_Is_Traversed_Body;
--------------------------
-- Set_Nested_Scenarios --
--------------------------
procedure Set_Nested_Scenarios
(N : Node_Id;
Scenarios : NE_List.Doubly_Linked_List)
is
pragma Assert (Present (N));
begin
NE_List_Map.Put (Nested_Scenarios_Map, N, Scenarios);
end Set_Nested_Scenarios;
-------------------
-- Traverse_Body --
-------------------
procedure Traverse_Body
(N : Node_Id;
Requires_Processing : Scenario_Predicate_Ptr;
Processor : Scenario_Processor_Ptr;
In_State : Processing_In_State)
is
Scenarios : NE_List.Doubly_Linked_List := NE_List.Nil;
-- The list of scenarios that appear within the declarations and
-- statement of subprogram body N. The variable is intentionally
-- global because Is_Potential_Scenario needs to populate it.
function In_Task_Body (Nod : Node_Id) return Boolean;
pragma Inline (In_Task_Body);
-- Determine whether arbitrary node Nod appears within a task body
function Is_Synchronous_Suspension_Call
(Nod : Node_Id) return Boolean;
pragma Inline (Is_Synchronous_Suspension_Call);
-- Determine whether arbitrary node Nod denotes a call to one of
-- these routines:
--
-- Ada.Synchronous_Barriers.Wait_For_Release
-- Ada.Synchronous_Task_Control.Suspend_Until_True
procedure Traverse_Collected_Scenarios;
pragma Inline (Traverse_Collected_Scenarios);
-- Traverse the already collected scenarios in list Scenarios by
-- invoking Processor on each individual one.
procedure Traverse_List (List : List_Id);
pragma Inline (Traverse_List);
-- Invoke Traverse_Potential_Scenarios on each node in list List
function Traverse_Potential_Scenario
(Scen : Node_Id) return Traverse_Result;
pragma Inline (Traverse_Potential_Scenario);
-- Determine whether arbitrary node Scen is a suitable scenario using
-- predicate Is_Scenario and traverse it by invoking Processor on it.
procedure Traverse_Potential_Scenarios is
new Traverse_Proc (Traverse_Potential_Scenario);
------------------
-- In_Task_Body --
------------------
function In_Task_Body (Nod : Node_Id) return Boolean is
Par : Node_Id;
begin
-- Climb the parent chain looking for a task body [procedure]
Par := Nod;
while Present (Par) loop
if Nkind (Par) = N_Task_Body then
return True;
elsif Nkind (Par) = N_Subprogram_Body
and then Is_Task_Body_Procedure (Par)
then
return True;
-- Prevent the search from going too far. Note that this test
-- shares nodes with the two cases above, and must come last.
elsif Is_Body_Or_Package_Declaration (Par) then
return False;
end if;
Par := Parent (Par);
end loop;
return False;
end In_Task_Body;
------------------------------------
-- Is_Synchronous_Suspension_Call --
------------------------------------
function Is_Synchronous_Suspension_Call
(Nod : Node_Id) return Boolean
is
Subp_Id : Entity_Id;
begin
-- To qualify, the call must invoke one of the runtime routines
-- which perform synchronous suspension.
if Is_Suitable_Call (Nod) then
Subp_Id := Target (Nod);
return
Is_RTE (Subp_Id, RE_Suspend_Until_True)
or else
Is_RTE (Subp_Id, RE_Wait_For_Release);
end if;
return False;
end Is_Synchronous_Suspension_Call;
----------------------------------
-- Traverse_Collected_Scenarios --
----------------------------------
procedure Traverse_Collected_Scenarios is
Iter : NE_List.Iterator;
Scen : Node_Id;
begin
Iter := NE_List.Iterate (Scenarios);
while NE_List.Has_Next (Iter) loop
NE_List.Next (Iter, Scen);
-- The current scenario satisfies the input predicate, process
-- it.
if Requires_Processing.all (Scen) then
Processor.all (Scen, In_State);
end if;
end loop;
end Traverse_Collected_Scenarios;
-------------------
-- Traverse_List --
-------------------
procedure Traverse_List (List : List_Id) is
Scen : Node_Id;
begin
Scen := First (List);
while Present (Scen) loop
Traverse_Potential_Scenarios (Scen);
Next (Scen);
end loop;
end Traverse_List;
---------------------------------
-- Traverse_Potential_Scenario --
---------------------------------
function Traverse_Potential_Scenario
(Scen : Node_Id) return Traverse_Result
is
begin
-- Special cases
-- Skip constructs which do not have elaboration of their own and
-- need to be elaborated by other means such as invocation, task
-- activation, etc.
if Is_Non_Library_Level_Encapsulator (Scen) then
return Skip;
-- Terminate the traversal of a task body when encountering an
-- accept or select statement, and
--
-- * Entry calls during elaboration are not allowed. In this
-- case the accept or select statement will cause the task
-- to block at elaboration time because there are no entry
-- calls to unblock it.
--
-- or
--
-- * Switch -gnatd_a (stop elaboration checks on accept or
-- select statement) is in effect.
elsif (Debug_Flag_Underscore_A
or else Restriction_Active
(No_Entry_Calls_In_Elaboration_Code))
and then Nkind (Original_Node (Scen)) in
N_Accept_Statement | N_Selective_Accept
then
return Abandon;
-- Terminate the traversal of a task body when encountering a
-- suspension call, and
--
-- * Entry calls during elaboration are not allowed. In this
-- case the suspension call emulates an entry call and will
-- cause the task to block at elaboration time.
--
-- or
--
-- * Switch -gnatd_s (stop elaboration checks on synchronous
-- suspension) is in effect.
--
-- Note that the guard should not be checking the state of flag
-- Within_Task_Body because only suspension calls which appear
-- immediately within the statements of the task are supported.
-- Flag Within_Task_Body carries over to deeper levels of the
-- traversal.
elsif (Debug_Flag_Underscore_S
or else Restriction_Active
(No_Entry_Calls_In_Elaboration_Code))
and then Is_Synchronous_Suspension_Call (Scen)
and then In_Task_Body (Scen)
then
return Abandon;
-- Certain nodes carry semantic lists which act as repositories
-- until expansion transforms the node and relocates the contents.
-- Examine these lists in case expansion is disabled.
elsif Nkind (Scen) in N_And_Then | N_Or_Else then
Traverse_List (Actions (Scen));
elsif Nkind (Scen) in N_Elsif_Part | N_Iteration_Scheme then
Traverse_List (Condition_Actions (Scen));
elsif Nkind (Scen) = N_If_Expression then
Traverse_List (Then_Actions (Scen));
Traverse_List (Else_Actions (Scen));
elsif Nkind (Scen) in
N_Component_Association | N_Iterated_Component_Association
then
Traverse_List (Loop_Actions (Scen));
-- General case
-- The current node satisfies the input predicate, process it
elsif Requires_Processing.all (Scen) then
Processor.all (Scen, In_State);
end if;
-- Save a general scenario regardless of whether it satisfies the
-- input predicate. This allows for quick subsequent traversals of
-- general scenarios, even with different predicates.
if Is_Suitable_Access_Taken (Scen)
or else Is_Suitable_Call (Scen)
or else Is_Suitable_Instantiation (Scen)
or else Is_Suitable_Variable_Assignment (Scen)
or else Is_Suitable_Variable_Reference (Scen)
then
NE_List.Append (Scenarios, Scen);
end if;
return OK;
end Traverse_Potential_Scenario;
-- Start of processing for Traverse_Body
begin
-- Nothing to do when the traversal is suppressed
if In_State.Traversal = No_Traversal then
return;
-- Nothing to do when there is no input
elsif No (N) then
return;
-- Nothing to do when the input is not a subprogram body
elsif Nkind (N) /= N_Subprogram_Body then
return;
-- Nothing to do if the subprogram body was already traversed
elsif Is_Traversed_Body (N) then
return;
end if;
-- Mark the subprogram body as traversed
Set_Is_Traversed_Body (N);
Scenarios := Nested_Scenarios (N);
-- The subprogram body has been traversed at least once, and all
-- scenarios that appear within its declarations and statements
-- have already been collected. Directly retraverse the scenarios
-- without having to retraverse the subprogram body subtree.
if NE_List.Present (Scenarios) then
Traverse_Collected_Scenarios;
-- Otherwise the subprogram body is being traversed for the first
-- time. Collect all scenarios that appear within its declarations
-- and statements in case the subprogram body has to be retraversed
-- multiple times.
else
Scenarios := NE_List.Create;
Set_Nested_Scenarios (N, Scenarios);
Traverse_List (Declarations (N));
Traverse_Potential_Scenarios (Handled_Statement_Sequence (N));
end if;
end Traverse_Body;
end Body_Processor;
-----------------------
-- Build_Call_Marker --
-----------------------
procedure Build_Call_Marker (N : Node_Id) is
function In_External_Context
(Call : Node_Id;
Subp_Id : Entity_Id) return Boolean;
pragma Inline (In_External_Context);
-- Determine whether entry, operator, or subprogram Subp_Id is external
-- to call Call which must reside within an instance.
function In_Premature_Context (Call : Node_Id) return Boolean;
pragma Inline (In_Premature_Context);
-- Determine whether call Call appears within a premature context
function Is_Default_Expression (Call : Node_Id) return Boolean;
pragma Inline (Is_Default_Expression);
-- Determine whether call Call acts as the expression of a defaulted
-- parameter within a source call.
function Is_Generic_Formal_Subp (Subp_Id : Entity_Id) return Boolean;
pragma Inline (Is_Generic_Formal_Subp);
-- Determine whether subprogram Subp_Id denotes a generic formal
-- subprogram which appears in the "prologue" of an instantiation.
-------------------------
-- In_External_Context --
-------------------------
function In_External_Context
(Call : Node_Id;
Subp_Id : Entity_Id) return Boolean
is
Spec_Decl : constant Entity_Id := Unit_Declaration_Node (Subp_Id);
Inst : Node_Id;
Inst_Body : Node_Id;
Inst_Spec : Node_Id;
begin
Inst := Find_Enclosing_Instance (Call);
-- The call appears within an instance
if Present (Inst) then
-- The call comes from the main unit and the target does not
if In_Extended_Main_Code_Unit (Call)
and then not In_Extended_Main_Code_Unit (Spec_Decl)
then
return True;
-- Otherwise the target declaration must not appear within the
-- instance spec or body.
else
Spec_And_Body_From_Node
(N => Inst,
Spec_Decl => Inst_Spec,
Body_Decl => Inst_Body);
return not In_Subtree
(N => Spec_Decl,
Root1 => Inst_Spec,
Root2 => Inst_Body);
end if;
end if;
return False;
end In_External_Context;
--------------------------
-- In_Premature_Context --
--------------------------
function In_Premature_Context (Call : Node_Id) return Boolean is
Par : Node_Id;
begin
-- Climb the parent chain looking for premature contexts
Par := Parent (Call);
while Present (Par) loop
-- Aspect specifications and generic associations are premature
-- contexts because nested calls has not been relocated to their
-- final context.
if Nkind (Par) in N_Aspect_Specification | N_Generic_Association
then
return True;
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Par) then
exit;
end if;
Par := Parent (Par);
end loop;
return False;
end In_Premature_Context;
---------------------------
-- Is_Default_Expression --
---------------------------
function Is_Default_Expression (Call : Node_Id) return Boolean is
Outer_Call : constant Node_Id := Parent (Call);
Outer_Nam : Node_Id;
begin
-- To qualify, the node must appear immediately within a source call
-- which invokes a source target.
if Nkind (Outer_Call) in N_Entry_Call_Statement
| N_Function_Call
| N_Procedure_Call_Statement
and then Comes_From_Source (Outer_Call)
then
Outer_Nam := Call_Name (Outer_Call);
return
Is_Entity_Name (Outer_Nam)
and then Present (Entity (Outer_Nam))
and then Is_Subprogram_Or_Entry (Entity (Outer_Nam))
and then Comes_From_Source (Entity (Outer_Nam));
end if;
return False;
end Is_Default_Expression;
----------------------------
-- Is_Generic_Formal_Subp --
----------------------------
function Is_Generic_Formal_Subp (Subp_Id : Entity_Id) return Boolean is
Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
Context : constant Node_Id := Parent (Subp_Decl);
begin
-- To qualify, the subprogram must rename a generic actual subprogram
-- where the enclosing context is an instantiation.
return
Nkind (Subp_Decl) = N_Subprogram_Renaming_Declaration
and then not Comes_From_Source (Subp_Decl)
and then Nkind (Context) in N_Function_Specification
| N_Package_Specification
| N_Procedure_Specification
and then Present (Generic_Parent (Context));
end Is_Generic_Formal_Subp;
-- Local variables
Call_Nam : Node_Id;
Marker : Node_Id;
Subp_Id : Entity_Id;
-- Start of processing for Build_Call_Marker
begin
-- Nothing to do when switch -gnatH (legacy elaboration checking mode
-- enabled) is in effect because the legacy ABE mechanism does not need
-- to carry out this action.
if Legacy_Elaboration_Checks then
return;
-- Nothing to do when the call is being preanalyzed as the marker will
-- be inserted in the wrong place.
elsif Preanalysis_Active then
return;
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
elsif not Elaboration_Phase_Active then
return;
-- Nothing to do when the input does not denote a call or a requeue
elsif Nkind (N) not in N_Entry_Call_Statement
| N_Function_Call
| N_Procedure_Call_Statement
| N_Requeue_Statement
then
return;
-- Nothing to do when the input denotes entry call or requeue statement,
-- and switch -gnatd_e (ignore entry calls and requeue statements for
-- elaboration) is in effect.
elsif Debug_Flag_Underscore_E
and then Nkind (N) in N_Entry_Call_Statement | N_Requeue_Statement
then
return;
-- Nothing to do when the call is analyzed/resolved too early within an
-- intermediate context. This check is saved for last because it incurs
-- a performance penalty.
elsif In_Premature_Context (N) then
return;
end if;
Call_Nam := Call_Name (N);
-- Nothing to do when the call is erroneous or left in a bad state
if not (Is_Entity_Name (Call_Nam)
and then Present (Entity (Call_Nam))
and then Is_Subprogram_Or_Entry (Entity (Call_Nam)))
then
return;
end if;
Subp_Id := Canonical_Subprogram (Entity (Call_Nam));
-- Nothing to do when the call invokes a generic formal subprogram and
-- switch -gnatd.G (ignore calls through generic formal parameters for
-- elaboration) is in effect. This check must be performed with the
-- direct target of the call to avoid the side effects of mapping
-- actuals to formals using renamings.
if Debug_Flag_Dot_GG
and then Is_Generic_Formal_Subp (Entity (Call_Nam))
then
return;
-- Nothing to do when the call appears within the expanded spec or
-- body of an instantiated generic, the call does not invoke a generic
-- formal subprogram, the target is external to the instance, and switch
-- -gnatdL (ignore external calls from instances for elaboration) is in
-- effect. This check must be performed with the direct target of the
-- call to avoid the side effects of mapping actuals to formals using
-- renamings.
elsif Debug_Flag_LL
and then not Is_Generic_Formal_Subp (Entity (Call_Nam))
and then In_External_Context
(Call => N,
Subp_Id => Subp_Id)
then
return;
-- Nothing to do when the call invokes an assertion pragma procedure
-- and switch -gnatd_p (ignore assertion pragmas for elaboration) is
-- in effect.
elsif Debug_Flag_Underscore_P
and then Is_Assertion_Pragma_Target (Subp_Id)
then
return;
-- Static expression functions require no ABE processing
elsif Is_Static_Function (Subp_Id) then
return;
-- Source calls to source targets are always considered because they
-- reflect the original call graph.
elsif Comes_From_Source (N) and then Comes_From_Source (Subp_Id) then
null;
-- A call to a source function which acts as the default expression in
-- another call requires special detection.
elsif Comes_From_Source (Subp_Id)
and then Nkind (N) = N_Function_Call
and then Is_Default_Expression (N)
then
null;
-- The target emulates Ada semantics
elsif Is_Ada_Semantic_Target (Subp_Id) then
null;
-- The target acts as a link between scenarios
elsif Is_Bridge_Target (Subp_Id) then
null;
-- The target emulates SPARK semantics
elsif Is_SPARK_Semantic_Target (Subp_Id) then
null;
-- Otherwise the call is not suitable for ABE processing. This prevents
-- the generation of call markers which will never play a role in ABE
-- diagnostics.
else
return;
end if;
-- At this point it is known that the call will play some role in ABE
-- checks and diagnostics. Create a corresponding call marker in case
-- the original call is heavily transformed by expansion later on.
Marker := Make_Call_Marker (Sloc (N));
-- Inherit the attributes of the original call
Set_Is_Declaration_Level_Node
(Marker, Find_Enclosing_Level (N) = Declaration_Level);
Set_Is_Dispatching_Call
(Marker,
Nkind (N) in N_Function_Call | N_Procedure_Call_Statement
and then Present (Controlling_Argument (N)));
Set_Is_Elaboration_Checks_OK_Node
(Marker, Is_Elaboration_Checks_OK_Node (N));
Set_Is_Elaboration_Warnings_OK_Node
(Marker, Is_Elaboration_Warnings_OK_Node (N));
Set_Is_Ignored_Ghost_Node (Marker, Is_Ignored_Ghost_Node (N));
Set_Is_Source_Call (Marker, Comes_From_Source (N));
Set_Is_SPARK_Mode_On_Node (Marker, Is_SPARK_Mode_On_Node (N));
Set_Target (Marker, Subp_Id);
-- Ada 2020 (AI12-0175): Calls to certain functions that are essentially
-- unchecked conversions are preelaborable.
if Ada_Version >= Ada_2020 then
Set_Is_Preelaborable_Call (Marker, Is_Preelaborable_Construct (N));
else
Set_Is_Preelaborable_Call (Marker, False);
end if;
-- The marker is inserted prior to the original call. This placement has
-- several desirable effects:
-- 1) The marker appears in the same context, in close proximity to
-- the call.
-- <marker>
-- <call>
-- 2) Inserting the marker prior to the call ensures that an ABE check
-- will take effect prior to the call.
-- <ABE check>
-- <marker>
-- <call>
-- 3) The above two properties are preserved even when the call is a
-- function which is subsequently relocated in order to capture its
-- result. Note that if the call is relocated to a new context, the
-- relocated call will receive a marker of its own.
-- <ABE check>
-- <maker>
-- Temp : ... := Func_Call ...;
-- ... Temp ...
-- The insertion must take place even when the call does not occur in
-- the main unit to keep the tree symmetric. This ensures that internal
-- name serialization is consistent in case the call marker causes the
-- tree to transform in some way.
Insert_Action (N, Marker);
-- The marker becomes the "corresponding" scenario for the call. Save
-- the marker for later processing by the ABE phase.
Record_Elaboration_Scenario (Marker);
end Build_Call_Marker;
-------------------------------------
-- Build_Variable_Reference_Marker --
-------------------------------------
procedure Build_Variable_Reference_Marker
(N : Node_Id;
Read : Boolean;
Write : Boolean)
is
function Ultimate_Variable (Var_Id : Entity_Id) return Entity_Id;
pragma Inline (Ultimate_Variable);
-- Obtain the ultimate renamed variable of variable Var_Id
-----------------------
-- Ultimate_Variable --
-----------------------
function Ultimate_Variable (Var_Id : Entity_Id) return Entity_Id is
Ren_Id : Entity_Id;
begin
Ren_Id := Var_Id;
while Present (Renamed_Entity (Ren_Id))
and then Nkind (Renamed_Entity (Ren_Id)) in N_Entity
loop
Ren_Id := Renamed_Entity (Ren_Id);
end loop;
return Ren_Id;
end Ultimate_Variable;
-- Local variables
Var_Id : constant Entity_Id := Ultimate_Variable (Entity (N));
Marker : Node_Id;
-- Start of processing for Build_Variable_Reference_Marker
begin
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
if not Elaboration_Phase_Active then
return;
end if;
Marker := Make_Variable_Reference_Marker (Sloc (N));
-- Inherit the attributes of the original variable reference
Set_Is_Elaboration_Checks_OK_Node
(Marker, Is_Elaboration_Checks_OK_Node (N));
Set_Is_Elaboration_Warnings_OK_Node
(Marker, Is_Elaboration_Warnings_OK_Node (N));
Set_Is_Read (Marker, Read);
Set_Is_SPARK_Mode_On_Node (Marker, Is_SPARK_Mode_On_Node (N));
Set_Is_Write (Marker, Write);
Set_Target (Marker, Var_Id);
-- The marker is inserted prior to the original variable reference. The
-- insertion must take place even when the reference does not occur in
-- the main unit to keep the tree symmetric. This ensures that internal
-- name serialization is consistent in case the variable marker causes
-- the tree to transform in some way.
Insert_Action (N, Marker);
-- The marker becomes the "corresponding" scenario for the reference.
-- Save the marker for later processing for the ABE phase.
Record_Elaboration_Scenario (Marker);
end Build_Variable_Reference_Marker;
---------------
-- Call_Name --
---------------
function Call_Name (Call : Node_Id) return Node_Id is
Nam : Node_Id;
begin
Nam := Name (Call);
-- When the call invokes an entry family, the name appears as an indexed
-- component.
if Nkind (Nam) = N_Indexed_Component then
Nam := Prefix (Nam);
end if;
-- When the call employs the object.operation form, the name appears as
-- a selected component.
if Nkind (Nam) = N_Selected_Component then
Nam := Selector_Name (Nam);
end if;
return Nam;
end Call_Name;
--------------------------
-- Canonical_Subprogram --
--------------------------
function Canonical_Subprogram (Subp_Id : Entity_Id) return Entity_Id is
Canon_Id : Entity_Id;
begin
Canon_Id := Subp_Id;
-- Use the original protected subprogram when dealing with one of the
-- specialized lock-manipulating versions.
if Is_Protected_Body_Subp (Canon_Id) then
Canon_Id := Protected_Subprogram (Canon_Id);
end if;
-- Obtain the original subprogram except when the subprogram is also
-- an instantiation. In this case the alias is the internally generated
-- subprogram which appears within the anonymous package created for the
-- instantiation, making it unuitable.
if not Is_Generic_Instance (Canon_Id) then
Canon_Id := Get_Renamed_Entity (Canon_Id);
end if;
return Canon_Id;
end Canonical_Subprogram;
---------------------------------
-- Check_Elaboration_Scenarios --
---------------------------------
procedure Check_Elaboration_Scenarios is
Iter : NE_Set.Iterator;
begin
-- Nothing to do when switch -gnatH (legacy elaboration checking mode
-- enabled) is in effect because the legacy ABE mechanism does not need
-- to carry out this action.
if Legacy_Elaboration_Checks then
Finalize_All_Data_Structures;
return;
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
elsif not Elaboration_Phase_Active then
Finalize_All_Data_Structures;
return;
end if;
-- Restore the original elaboration model which was in effect when the
-- scenarios were first recorded. The model may be specified by pragma
-- Elaboration_Checks which appears on the initial declaration of the
-- main unit.
Install_Elaboration_Model (Unit_Entity (Main_Unit_Entity));
-- Examine the context of the main unit and record all units with prior
-- elaboration with respect to it.
Collect_Elaborated_Units;
-- Examine all scenarios saved during the Recording phase applying the
-- Ada or SPARK elaboration rules in order to detect and diagnose ABE
-- issues, install conditional ABE checks, and ensure the elaboration
-- of units.
Iter := Iterate_Declaration_Scenarios;
Check_Conditional_ABE_Scenarios (Iter);
Iter := Iterate_Library_Body_Scenarios;
Check_Conditional_ABE_Scenarios (Iter);
Iter := Iterate_Library_Spec_Scenarios;
Check_Conditional_ABE_Scenarios (Iter);
-- Examine each SPARK scenario saved during the Recording phase which
-- is not necessarily executable during elaboration, but still requires
-- elaboration-related checks.
Check_SPARK_Scenarios;
-- Add conditional ABE checks for all scenarios that require one when
-- the dynamic model is in effect.
Install_Dynamic_ABE_Checks;
-- Examine all scenarios saved during the Recording phase along with
-- invocation constructs within the spec and body of the main unit.
-- Record the declarations and paths that reach into an external unit
-- in the ALI file of the main unit.
Record_Invocation_Graph;
-- Destroy all internal data structures and complete the elaboration
-- phase of the compiler.
Finalize_All_Data_Structures;
Set_Elaboration_Phase (Completed);
end Check_Elaboration_Scenarios;
---------------------
-- Check_Installer --
---------------------
package body Check_Installer is
-----------------------
-- Local subprograms --
-----------------------
function ABE_Check_Or_Failure_OK
(N : Node_Id;
Targ_Id : Entity_Id;
Unit_Id : Entity_Id) return Boolean;
pragma Inline (ABE_Check_Or_Failure_OK);
-- Determine whether a conditional ABE check or guaranteed ABE failure
-- can be installed for scenario N with target Targ_Id which resides in
-- unit Unit_Id.
function Insertion_Node (N : Node_Id) return Node_Id;
pragma Inline (Insertion_Node);
-- Obtain the proper insertion node of an ABE check or failure for
-- scenario N.
procedure Insert_ABE_Check_Or_Failure (N : Node_Id; Check : Node_Id);
pragma Inline (Insert_ABE_Check_Or_Failure);
-- Insert conditional ABE check or guaranteed ABE failure Check prior to
-- scenario N.
procedure Install_Scenario_ABE_Check_Common
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id);
pragma Inline (Install_Scenario_ABE_Check_Common);
-- Install a conditional ABE check for scenario N to ensure that target
-- Targ_Id is properly elaborated. Targ_Rep is the representation of the
-- target.
procedure Install_Scenario_ABE_Failure_Common (N : Node_Id);
pragma Inline (Install_Scenario_ABE_Failure_Common);
-- Install a guaranteed ABE failure for scenario N
procedure Install_Unit_ABE_Check_Common
(N : Node_Id;
Unit_Id : Entity_Id);
pragma Inline (Install_Unit_ABE_Check_Common);
-- Install a conditional ABE check for scenario N to ensure that unit
-- Unit_Id is properly elaborated.
-----------------------------
-- ABE_Check_Or_Failure_OK --
-----------------------------
function ABE_Check_Or_Failure_OK
(N : Node_Id;
Targ_Id : Entity_Id;
Unit_Id : Entity_Id) return Boolean
is
pragma Unreferenced (Targ_Id);
Ins_Node : constant Node_Id := Insertion_Node (N);
begin
if not Check_Or_Failure_Generation_OK then
return False;
-- Nothing to do when the scenario denots a compilation unit because
-- there is no executable environment at that level.
elsif Nkind (Parent (Ins_Node)) = N_Compilation_Unit then
return False;
-- An ABE check or failure is not needed when the target is defined
-- in a unit which is elaborated prior to the main unit. This check
-- must also consider the following cases:
--
-- * The unit of the target appears in the context of the main unit
--
-- * The unit of the target is subject to pragma Elaborate_Body. An
-- ABE check MUST NOT be generated because the unit is always
-- elaborated prior to the main unit.
--
-- * The unit of the target is the main unit. An ABE check MUST be
-- added in this case because a conditional ABE may be raised
-- depending on the flow of execution within the main unit (flag
-- Same_Unit_OK is False).
elsif Has_Prior_Elaboration
(Unit_Id => Unit_Id,
Context_OK => True,
Elab_Body_OK => True)
then
return False;
end if;
return True;
end ABE_Check_Or_Failure_OK;
------------------------------------
-- Check_Or_Failure_Generation_OK --
------------------------------------
function Check_Or_Failure_Generation_OK return Boolean is
begin
-- An ABE check or failure is not needed when the compilation will
-- not produce an executable.
if Serious_Errors_Detected > 0 then
return False;
-- An ABE check or failure must not be installed when compiling for
-- GNATprove because raise statements are not supported.
elsif GNATprove_Mode then
return False;
end if;
return True;
end Check_Or_Failure_Generation_OK;
--------------------
-- Insertion_Node --
--------------------
function Insertion_Node (N : Node_Id) return Node_Id is
begin
-- When the scenario denotes an instantiation, the proper insertion
-- node is the instance spec. This ensures that the generic actuals
-- will not be evaluated prior to a potential ABE.
if Nkind (N) in N_Generic_Instantiation
and then Present (Instance_Spec (N))
then
return Instance_Spec (N);
-- Otherwise the proper insertion node is the scenario itself
else
return N;
end if;
end Insertion_Node;
---------------------------------
-- Insert_ABE_Check_Or_Failure --
---------------------------------
procedure Insert_ABE_Check_Or_Failure (N : Node_Id; Check : Node_Id) is
Ins_Nod : constant Node_Id := Insertion_Node (N);
Scop_Id : constant Entity_Id := Find_Enclosing_Scope (Ins_Nod);
begin
-- Install the nearest enclosing scope of the scenario as there must
-- be something on the scope stack.
Push_Scope (Scop_Id);
Insert_Action (Ins_Nod, Check);
Pop_Scope;
end Insert_ABE_Check_Or_Failure;
--------------------------------
-- Install_Dynamic_ABE_Checks --
--------------------------------
procedure Install_Dynamic_ABE_Checks is
Iter : NE_Set.Iterator;
N : Node_Id;
begin
if not Check_Or_Failure_Generation_OK then
return;
-- Nothing to do if the dynamic model is not in effect
elsif not Dynamic_Elaboration_Checks then
return;
end if;
-- Install a conditional ABE check for each saved scenario
Iter := Iterate_Dynamic_ABE_Check_Scenarios;
while NE_Set.Has_Next (Iter) loop
NE_Set.Next (Iter, N);
Process_Conditional_ABE
(N => N,
In_State => Dynamic_Model_State);
end loop;
end Install_Dynamic_ABE_Checks;
--------------------------------
-- Install_Scenario_ABE_Check --
--------------------------------
procedure Install_Scenario_ABE_Check
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Scenario_Rep_Id)
is
begin
-- Nothing to do when the scenario does not need an ABE check
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Targ_Id,
Unit_Id => Unit (Targ_Rep))
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Scenario_ABE_Check_Common
(N => N,
Targ_Id => Targ_Id,
Targ_Rep => Targ_Rep);
end Install_Scenario_ABE_Check;
--------------------------------
-- Install_Scenario_ABE_Check --
--------------------------------
procedure Install_Scenario_ABE_Check
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Target_Rep_Id)
is
begin
-- Nothing to do when the scenario does not need an ABE check
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Targ_Id,
Unit_Id => Unit (Targ_Rep))
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Scenario_ABE_Check_Common
(N => N,
Targ_Id => Targ_Id,
Targ_Rep => Targ_Rep);
end Install_Scenario_ABE_Check;
---------------------------------------
-- Install_Scenario_ABE_Check_Common --
---------------------------------------
procedure Install_Scenario_ABE_Check_Common
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id)
is
Targ_Body : constant Node_Id := Body_Declaration (Targ_Rep);
Targ_Decl : constant Node_Id := Spec_Declaration (Targ_Rep);
pragma Assert (Present (Targ_Body));
pragma Assert (Present (Targ_Decl));
procedure Build_Elaboration_Entity;
pragma Inline (Build_Elaboration_Entity);
-- Create a new elaboration flag for Targ_Id, insert it prior to
-- Targ_Decl, and set it after Targ_Body.
------------------------------
-- Build_Elaboration_Entity --
------------------------------
procedure Build_Elaboration_Entity is
Loc : constant Source_Ptr := Sloc (Targ_Id);
Flag_Id : Entity_Id;
begin
-- Nothing to do if the target has an elaboration flag
if Present (Elaboration_Entity (Targ_Id)) then
return;
end if;
-- Create the declaration of the elaboration flag. The name
-- carries a unique counter in case the name is overloaded.
Flag_Id :=
Make_Defining_Identifier (Loc,
Chars => New_External_Name (Chars (Targ_Id), 'E', -1));
Set_Elaboration_Entity (Targ_Id, Flag_Id);
Set_Elaboration_Entity_Required (Targ_Id);
Push_Scope (Scope (Targ_Id));
-- Generate:
-- Enn : Short_Integer := 0;
Insert_Action (Targ_Decl,
Make_Object_Declaration (Loc,
Defining_Identifier => Flag_Id,
Object_Definition =>
New_Occurrence_Of (Standard_Short_Integer, Loc),
Expression => Make_Integer_Literal (Loc, Uint_0)));
-- Generate:
-- Enn := 1;
Set_Elaboration_Flag (Targ_Body, Targ_Id);
Pop_Scope;
end Build_Elaboration_Entity;
-- Local variables
Loc : constant Source_Ptr := Sloc (N);
-- Start for processing for Install_Scenario_ABE_Check_Common
begin
-- Create an elaboration flag for the target when it does not have
-- one.
Build_Elaboration_Entity;
-- Generate:
-- if not Targ_Id'Elaborated then
-- raise Program_Error with "access before elaboration";
-- end if;
Insert_ABE_Check_Or_Failure
(N => N,
Check =>
Make_Raise_Program_Error (Loc,
Condition =>
Make_Op_Not (Loc,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Targ_Id, Loc),
Attribute_Name => Name_Elaborated)),
Reason => PE_Access_Before_Elaboration));
end Install_Scenario_ABE_Check_Common;
----------------------------------
-- Install_Scenario_ABE_Failure --
----------------------------------
procedure Install_Scenario_ABE_Failure
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Scenario_Rep_Id)
is
begin
-- Nothing to do when the scenario does not require an ABE failure
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Targ_Id,
Unit_Id => Unit (Targ_Rep))
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Scenario_ABE_Failure_Common (N);
end Install_Scenario_ABE_Failure;
----------------------------------
-- Install_Scenario_ABE_Failure --
----------------------------------
procedure Install_Scenario_ABE_Failure
(N : Node_Id;
Targ_Id : Entity_Id;
Targ_Rep : Target_Rep_Id;
Disable : Target_Rep_Id)
is
begin
-- Nothing to do when the scenario does not require an ABE failure
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Targ_Id,
Unit_Id => Unit (Targ_Rep))
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Scenario_ABE_Failure_Common (N);
end Install_Scenario_ABE_Failure;
-----------------------------------------
-- Install_Scenario_ABE_Failure_Common --
-----------------------------------------
procedure Install_Scenario_ABE_Failure_Common (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
begin
-- Generate:
-- raise Program_Error with "access before elaboration";
Insert_ABE_Check_Or_Failure
(N => N,
Check =>
Make_Raise_Program_Error (Loc,
Reason => PE_Access_Before_Elaboration));
end Install_Scenario_ABE_Failure_Common;
----------------------------
-- Install_Unit_ABE_Check --
----------------------------
procedure Install_Unit_ABE_Check
(N : Node_Id;
Unit_Id : Entity_Id;
Disable : Scenario_Rep_Id)
is
Spec_Id : constant Entity_Id := Unique_Entity (Unit_Id);
begin
-- Nothing to do when the scenario does not require an ABE check
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Empty,
Unit_Id => Spec_Id)
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Unit_ABE_Check_Common
(N => N,
Unit_Id => Unit_Id);
end Install_Unit_ABE_Check;
----------------------------
-- Install_Unit_ABE_Check --
----------------------------
procedure Install_Unit_ABE_Check
(N : Node_Id;
Unit_Id : Entity_Id;
Disable : Target_Rep_Id)
is
Spec_Id : constant Entity_Id := Unique_Entity (Unit_Id);
begin
-- Nothing to do when the scenario does not require an ABE check
if not ABE_Check_Or_Failure_OK
(N => N,
Targ_Id => Empty,
Unit_Id => Spec_Id)
then
return;
end if;
-- Prevent multiple attempts to install the same ABE check
Disable_Elaboration_Checks (Disable);
Install_Unit_ABE_Check_Common
(N => N,
Unit_Id => Unit_Id);
end Install_Unit_ABE_Check;
-----------------------------------
-- Install_Unit_ABE_Check_Common --
-----------------------------------
procedure Install_Unit_ABE_Check_Common
(N : Node_Id;
Unit_Id : Entity_Id)
is
Loc : constant Source_Ptr := Sloc (N);
Spec_Id : constant Entity_Id := Unique_Entity (Unit_Id);
begin
-- Generate:
-- if not Spec_Id'Elaborated then
-- raise Program_Error with "access before elaboration";
-- end if;
Insert_ABE_Check_Or_Failure
(N => N,
Check =>
Make_Raise_Program_Error (Loc,
Condition =>
Make_Op_Not (Loc,
Right_Opnd =>
Make_Attribute_Reference (Loc,
Prefix => New_Occurrence_Of (Spec_Id, Loc),
Attribute_Name => Name_Elaborated)),
Reason => PE_Access_Before_Elaboration));
end Install_Unit_ABE_Check_Common;
end Check_Installer;
----------------------
-- Compilation_Unit --
----------------------
function Compilation_Unit (Unit_Id : Entity_Id) return Node_Id is
Comp_Unit : Node_Id;
begin
Comp_Unit := Parent (Unit_Id);
-- Handle the case where a concurrent subunit is rewritten as a null
-- statement due to expansion activities.
if Nkind (Comp_Unit) = N_Null_Statement
and then Nkind (Original_Node (Comp_Unit)) in
N_Protected_Body | N_Task_Body
then
Comp_Unit := Parent (Comp_Unit);
pragma Assert (Nkind (Comp_Unit) = N_Subunit);
-- Otherwise use the declaration node of the unit
else
Comp_Unit := Parent (Unit_Declaration_Node (Unit_Id));
end if;
-- Handle the case where a subprogram instantiation which acts as a
-- compilation unit is expanded into an anonymous package that wraps
-- the instantiated subprogram.
if Nkind (Comp_Unit) = N_Package_Specification
and then Nkind (Original_Node (Parent (Comp_Unit))) in
N_Function_Instantiation | N_Procedure_Instantiation
then
Comp_Unit := Parent (Parent (Comp_Unit));
-- Handle the case where the compilation unit is a subunit
elsif Nkind (Comp_Unit) = N_Subunit then
Comp_Unit := Parent (Comp_Unit);
end if;
pragma Assert (Nkind (Comp_Unit) = N_Compilation_Unit);
return Comp_Unit;
end Compilation_Unit;
-------------------------------
-- Conditional_ABE_Processor --
-------------------------------
package body Conditional_ABE_Processor is
-----------------------
-- Local subprograms --
-----------------------
function Is_Conditional_ABE_Scenario (N : Node_Id) return Boolean;
pragma Inline (Is_Conditional_ABE_Scenario);
-- Determine whether node N is a suitable scenario for conditional ABE
-- checks and diagnostics.
procedure Process_Conditional_ABE_Access_Taken
(Attr : Node_Id;
Attr_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Access_Taken);
-- Perform ABE checks and diagnostics for attribute reference Attr with
-- representation Attr_Rep which takes 'Access of an entry, operator, or
-- subprogram. In_State is the current state of the Processing phase.
procedure Process_Conditional_ABE_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Activation);
-- Perform common conditional ABE checks and diagnostics for activation
-- call Call which activates object Obj_Id of task type Task_Typ. Formal
-- Call_Rep denotes the representation of the call. Obj_Rep denotes the
-- representation of the object. Task_Rep denotes the representation of
-- the task type. In_State is the current state of the Processing phase.
procedure Process_Conditional_ABE_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Call);
-- Top-level dispatcher for processing of calls. Perform ABE checks and
-- diagnostics for call Call with representation Call_Rep. In_State is
-- the current state of the Processing phase.
procedure Process_Conditional_ABE_Call_Ada
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Call_Ada);
-- Perform ABE checks and diagnostics for call Call which invokes entry,
-- operator, or subprogram Subp_Id using the Ada rules. Call_Rep denotes
-- the representation of the call. Subp_Rep denotes the representation
-- of the subprogram. In_State is the current state of the Processing
-- phase.
procedure Process_Conditional_ABE_Call_SPARK
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Call_SPARK);
-- Perform ABE checks and diagnostics for call Call which invokes entry,
-- operator, or subprogram Subp_Id using the SPARK rules. Call_Rep is
-- the representation of the call. Subp_Rep denotes the representation
-- of the subprogram. In_State is the current state of the Processing
-- phase.
procedure Process_Conditional_ABE_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Instantiation);
-- Top-level dispatcher for processing of instantiations. Perform ABE
-- checks and diagnostics for instantiation Inst with representation
-- Inst_Rep. In_State is the current state of the Processing phase.
procedure Process_Conditional_ABE_Instantiation_Ada
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Instantiation_Ada);
-- Perform ABE checks and diagnostics for instantiation Inst of generic
-- Gen_Id using the Ada rules. Inst_Rep denotes the representation of
-- the instnace. Gen_Rep is the representation of the generic. In_State
-- is the current state of the Processing phase.
procedure Process_Conditional_ABE_Instantiation_SPARK
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Instantiation_SPARK);
-- Perform ABE checks and diagnostics for instantiation Inst of generic
-- Gen_Id using the SPARK rules. Inst_Rep denotes the representation of
-- the instnace. Gen_Rep is the representation of the generic. In_State
-- is the current state of the Processing phase.
procedure Process_Conditional_ABE_Variable_Assignment
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Variable_Assignment);
-- Top-level dispatcher for processing of variable assignments. Perform
-- ABE checks and diagnostics for assignment Asmt with representation
-- Asmt_Rep. In_State denotes the current state of the Processing phase.
procedure Process_Conditional_ABE_Variable_Assignment_Ada
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Var_Id : Entity_Id;
Var_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Variable_Assignment_Ada);
-- Perform ABE checks and diagnostics for assignment statement Asmt that
-- modifies the value of variable Var_Id using the Ada rules. Asmt_Rep
-- denotes the representation of the assignment. Var_Rep denotes the
-- representation of the variable. In_State is the current state of the
-- Processing phase.
procedure Process_Conditional_ABE_Variable_Assignment_SPARK
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Var_Id : Entity_Id;
Var_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Variable_Assignment_SPARK);
-- Perform ABE checks and diagnostics for assignment statement Asmt that
-- modifies the value of variable Var_Id using the SPARK rules. Asmt_Rep
-- denotes the representation of the assignment. Var_Rep denotes the
-- representation of the variable. In_State is the current state of the
-- Processing phase.
procedure Process_Conditional_ABE_Variable_Reference
(Ref : Node_Id;
Ref_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Conditional_ABE_Variable_Reference);
-- Perform ABE checks and diagnostics for variable reference Ref with
-- representation Ref_Rep. In_State denotes the current state of the
-- Processing phase.
procedure Traverse_Conditional_ABE_Body
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Traverse_Conditional_ABE_Body);
-- Traverse subprogram body N looking for suitable scenarios that need
-- to be processed for conditional ABE checks and diagnostics. In_State
-- is the current state of the Processing phase.
-------------------------------------
-- Check_Conditional_ABE_Scenarios --
-------------------------------------
procedure Check_Conditional_ABE_Scenarios
(Iter : in out NE_Set.Iterator)
is
N : Node_Id;
begin
while NE_Set.Has_Next (Iter) loop
NE_Set.Next (Iter, N);
-- Reset the traversed status of all subprogram bodies because the
-- current conditional scenario acts as a new DFS traversal root.
Reset_Traversed_Bodies;
Process_Conditional_ABE
(N => N,
In_State => Conditional_ABE_State);
end loop;
end Check_Conditional_ABE_Scenarios;
---------------------------------
-- Is_Conditional_ABE_Scenario --
---------------------------------
function Is_Conditional_ABE_Scenario (N : Node_Id) return Boolean is
begin
return
Is_Suitable_Access_Taken (N)
or else Is_Suitable_Call (N)
or else Is_Suitable_Instantiation (N)
or else Is_Suitable_Variable_Assignment (N)
or else Is_Suitable_Variable_Reference (N);
end Is_Conditional_ABE_Scenario;
-----------------------------
-- Process_Conditional_ABE --
-----------------------------
procedure Process_Conditional_ABE
(N : Node_Id;
In_State : Processing_In_State)
is
Scen : constant Node_Id := Scenario (N);
Scen_Rep : Scenario_Rep_Id;
begin
-- Add the current scenario to the stack of active scenarios
Push_Active_Scenario (Scen);
-- 'Access
if Is_Suitable_Access_Taken (Scen) then
Process_Conditional_ABE_Access_Taken
(Attr => Scen,
Attr_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
-- Call or task activation
elsif Is_Suitable_Call (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
-- Routine Build_Call_Marker creates call markers regardless of
-- whether the call occurs within the main unit or not. This way
-- the serialization of internal names is kept consistent. Only
-- call markers found within the main unit must be processed.
if In_Main_Context (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
if Kind (Scen_Rep) = Call_Scenario then
Process_Conditional_ABE_Call
(Call => Scen,
Call_Rep => Scen_Rep,
In_State => In_State);
else
pragma Assert (Kind (Scen_Rep) = Task_Activation_Scenario);
Process_Activation
(Call => Scen,
Call_Rep => Scen_Rep,
Processor => Process_Conditional_ABE_Activation'Access,
In_State => In_State);
end if;
end if;
-- Instantiation
elsif Is_Suitable_Instantiation (Scen) then
Process_Conditional_ABE_Instantiation
(Inst => Scen,
Inst_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
-- Variable assignments
elsif Is_Suitable_Variable_Assignment (Scen) then
Process_Conditional_ABE_Variable_Assignment
(Asmt => Scen,
Asmt_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
-- Variable references
elsif Is_Suitable_Variable_Reference (Scen) then
-- Routine Build_Variable_Reference_Marker makes variable markers
-- regardless of whether the reference occurs within the main unit
-- or not. This way the serialization of internal names is kept
-- consistent. Only variable markers within the main unit must be
-- processed.
if In_Main_Context (Scen) then
Process_Conditional_ABE_Variable_Reference
(Ref => Scen,
Ref_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
end if;
end if;
-- Remove the current scenario from the stack of active scenarios
-- once all ABE diagnostics and checks have been performed.
Pop_Active_Scenario (Scen);
end Process_Conditional_ABE;
------------------------------------------
-- Process_Conditional_ABE_Access_Taken --
------------------------------------------
procedure Process_Conditional_ABE_Access_Taken
(Attr : Node_Id;
Attr_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
function Build_Access_Marker (Subp_Id : Entity_Id) return Node_Id;
pragma Inline (Build_Access_Marker);
-- Create a suitable call marker which invokes subprogram Subp_Id
-------------------------
-- Build_Access_Marker --
-------------------------
function Build_Access_Marker (Subp_Id : Entity_Id) return Node_Id is
Marker : Node_Id;
begin
Marker := Make_Call_Marker (Sloc (Attr));
-- Inherit relevant attributes from the attribute
Set_Target (Marker, Subp_Id);
Set_Is_Declaration_Level_Node
(Marker, Level (Attr_Rep) = Declaration_Level);
Set_Is_Dispatching_Call
(Marker, False);
Set_Is_Elaboration_Checks_OK_Node
(Marker, Elaboration_Checks_OK (Attr_Rep));
Set_Is_Elaboration_Warnings_OK_Node
(Marker, Elaboration_Warnings_OK (Attr_Rep));
Set_Is_Preelaborable_Call
(Marker, False);
Set_Is_Source_Call
(Marker, Comes_From_Source (Attr));
Set_Is_SPARK_Mode_On_Node
(Marker, SPARK_Mode_Of (Attr_Rep) = Is_On);
-- Partially insert the call marker into the tree by setting its
-- parent pointer.
Set_Parent (Marker, Attr);
return Marker;
end Build_Access_Marker;
-- Local variables
Root : constant Node_Id := Root_Scenario;
Subp_Id : constant Entity_Id := Target (Attr_Rep);
Subp_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Subp_Id, In_State);
Body_Decl : constant Node_Id := Body_Declaration (Subp_Rep);
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
-- Start of processing for Process_Conditional_ABE_Access
begin
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not New_In_State.Suppress_Info_Messages
then
Error_Msg_NE
("info: access to & during elaboration", Attr, Subp_Id);
end if;
-- Warnings are suppressed when a prior scenario is already in that
-- mode or when the attribute or the target have warnings suppressed.
-- Update the state of the Processing phase to reflect this.
New_In_State.Suppress_Warnings :=
New_In_State.Suppress_Warnings
or else not Elaboration_Warnings_OK (Attr_Rep)
or else not Elaboration_Warnings_OK (Subp_Rep);
-- Do not emit any ABE diagnostics when the current or previous
-- scenario in this traversal has suppressed elaboration warnings.
if New_In_State.Suppress_Warnings then
null;
-- Both the attribute and the corresponding subprogram body are in
-- the same unit. The body must appear prior to the root scenario
-- which started the recursive search. If this is not the case, then
-- there is a potential ABE if the access value is used to call the
-- subprogram. Emit a warning only when switch -gnatw.f (warnings on
-- suspucious 'Access) is in effect.
elsif Warn_On_Elab_Access
and then Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
and then Earlier_In_Extended_Unit (Root, Body_Decl)
then
Error_Msg_Name_1 := Attribute_Name (Attr);
Error_Msg_NE
("??% attribute of & before body seen", Attr, Subp_Id);
Error_Msg_N ("\possible Program_Error on later references", Attr);
Output_Active_Scenarios (Attr, New_In_State);
end if;
-- Treat the attribute an immediate invocation of the target when
-- switch -gnatd.o (conservative elaboration order for indirect
-- calls) is in effect. This has the following desirable effects:
--
-- * Ensure that the unit with the corresponding body is elaborated
-- prior to the main unit.
--
-- * Perform conditional ABE checks and diagnostics
--
-- * Traverse the body of the target (if available)
if Debug_Flag_Dot_O then
Process_Conditional_ABE
(N => Build_Access_Marker (Subp_Id),
In_State => New_In_State);
-- Otherwise ensure that the unit with the corresponding body is
-- elaborated prior to the main unit.
else
Ensure_Prior_Elaboration
(N => Attr,
Unit_Id => Unit (Subp_Rep),
Prag_Nam => Name_Elaborate_All,
In_State => New_In_State);
end if;
end Process_Conditional_ABE_Access_Taken;
----------------------------------------
-- Process_Conditional_ABE_Activation --
----------------------------------------
procedure Process_Conditional_ABE_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Task_Typ);
Body_Decl : constant Node_Id := Body_Declaration (Task_Rep);
Spec_Decl : constant Node_Id := Spec_Declaration (Task_Rep);
Root : constant Node_Id := Root_Scenario;
Unit_Id : constant Node_Id := Unit (Task_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Obj_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Task_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Obj_Rep)
and then Elaboration_Checks_OK (Task_Rep);
-- A run-time ABE check may be installed only when the object and the
-- task type have active elaboration checks, and both are not ignored
-- Ghost constructs.
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
begin
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not New_In_State.Suppress_Info_Messages
then
Error_Msg_NE
("info: activation of & during elaboration", Call, Obj_Id);
end if;
-- Nothing to do when the call activates a task whose type is defined
-- within an instance and switch -gnatd_i (ignore activations and
-- calls to instances for elaboration) is in effect.
if Debug_Flag_Underscore_I
and then In_External_Instance
(N => Call,
Target_Decl => Spec_Decl)
then
return;
-- Nothing to do when the activation is a guaranteed ABE
elsif Is_Known_Guaranteed_ABE (Call) then
return;
-- Nothing to do when the root scenario appears at the declaration
-- level and the task is in the same unit, but outside this context.
--
-- task type Task_Typ; -- task declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- T : Task_Typ;
-- begin
-- <activation call> -- activation site
-- end;
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- task body Task_Typ is
-- ...
-- end Task_Typ;
--
-- In the example above, the context of X is the declarative list of
-- Proc. The "elaboration" of X may reach the activation of T whose
-- body is defined outside of X's context. The task body is relevant
-- only when Proc is invoked, but this happens only during "normal"
-- elaboration, therefore the task body must not be considered if
-- this is not the case.
elsif Is_Up_Level_Target
(Targ_Decl => Spec_Decl,
In_State => New_In_State)
then
return;
-- Nothing to do when the activation is ABE-safe
--
-- generic
-- package Gen is
-- task type Task_Typ;
-- end Gen;
--
-- package body Gen is
-- task body Task_Typ is
-- begin
-- ...
-- end Task_Typ;
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- package Nested is
-- package Inst is new Gen;
-- T : Inst.Task_Typ;
-- <activation call> -- safe activation
-- end Nested;
-- ...
elsif Is_Safe_Activation (Call, Task_Rep) then
-- Note that the task body must still be examined for any nested
-- scenarios.
null;
-- The activation call and the task body are both in the main unit
--
-- If the root scenario appears prior to the task body, then this is
-- a possible ABE with respect to the root scenario.
--
-- task type Task_Typ;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- package Pack is
-- T : Task_Typ;
-- end Pack; -- activation of T
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
--
-- task body Task_Typ is -- task body
-- ...
-- end Task_Typ;
--
-- Y : ... := A; -- root scenario
--
-- IMPORTANT: The activation of T is a possible ABE for X, but
-- not for Y. Intalling an unconditional ABE raise prior to the
-- activation call would be wrong as it will fail for Y as well
-- but in Y's case the activation of T is never an ABE.
elsif Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
then
if Earlier_In_Extended_Unit (Root, Body_Decl) then
-- Do not emit any ABE diagnostics when a previous scenario in
-- this traversal has suppressed elaboration warnings.
if New_In_State.Suppress_Warnings then
null;
-- Do not emit any ABE diagnostics when the activation occurs
-- in a partial finalization context because this action leads
-- to confusing noise.
elsif New_In_State.Within_Partial_Finalization then
null;
-- Otherwise emit the ABE disgnostic
else
Error_Msg_Sloc := Sloc (Call);
Error_Msg_N
("??task & will be activated # before elaboration of its "
& "body", Obj_Id);
Error_Msg_N
("\Program_Error may be raised at run time", Obj_Id);
Output_Active_Scenarios (Obj_Id, New_In_State);
end if;
-- Install a conditional run-time ABE check to verify that the
-- task body has been elaborated prior to the activation call.
if Check_OK then
Install_Scenario_ABE_Check
(N => Call,
Targ_Id => Defining_Entity (Spec_Decl),
Targ_Rep => Task_Rep,
Disable => Obj_Rep);
-- Update the state of the Processing phase to indicate that
-- no implicit Elaborate[_All] pragma must be generated from
-- this point on.
--
-- task type Task_Typ;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- package Pack is
-- <ABE check>
-- T : Task_Typ;
-- end Pack; -- activation of T
-- ...
-- end A;
--
-- X : ... := A;
--
-- task body Task_Typ is
-- begin
-- External.Subp; -- imparts Elaborate_All
-- end Task_Typ;
--
-- If Some_Condition is True, then the ABE check will fail
-- at runtime and the call to External.Subp will never take
-- place, rendering the implicit Elaborate_All useless.
--
-- If the value of Some_Condition is False, then the call
-- to External.Subp will never take place, rendering the
-- implicit Elaborate_All useless.
New_In_State.Suppress_Implicit_Pragmas := True;
end if;
end if;
-- Otherwise the task body is not available in this compilation or
-- it resides in an external unit. Install a run-time ABE check to
-- verify that the task body has been elaborated prior to the
-- activation call when the dynamic model is in effect.
elsif Check_OK
and then New_In_State.Processing = Dynamic_Model_Processing
then
Install_Unit_ABE_Check
(N => Call,
Unit_Id => Unit_Id,
Disable => Obj_Rep);
end if;
-- Both the activation call and task type are subject to SPARK_Mode
-- On, this triggers the SPARK rules for task activation. Compared
-- to calls and instantiations, task activation in SPARK does not
-- require the presence of Elaborate[_All] pragmas in case the task
-- type is defined outside the main unit. This is because SPARK uses
-- a special policy which activates all tasks after the main unit has
-- finished its elaboration.
if SPARK_Mode_Of (Call_Rep) = Is_On
and then SPARK_Mode_Of (Task_Rep) = Is_On
then
null;
-- Otherwise the Ada rules are in effect. Ensure that the unit with
-- the task body is elaborated prior to the main unit.
else
Ensure_Prior_Elaboration
(N => Call,
Unit_Id => Unit_Id,
Prag_Nam => Name_Elaborate_All,
In_State => New_In_State);
end if;
Traverse_Conditional_ABE_Body
(N => Body_Decl,
In_State => New_In_State);
end Process_Conditional_ABE_Activation;
----------------------------------
-- Process_Conditional_ABE_Call --
----------------------------------
procedure Process_Conditional_ABE_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
function In_Initialization_Context (N : Node_Id) return Boolean;
pragma Inline (In_Initialization_Context);
-- Determine whether arbitrary node N appears within a type init
-- proc, primitive [Deep_]Initialize, or a block created for
-- initialization purposes.
function Is_Partial_Finalization_Proc
(Subp_Id : Entity_Id) return Boolean;
pragma Inline (Is_Partial_Finalization_Proc);
-- Determine whether subprogram Subp_Id is a partial finalization
-- procedure.
-------------------------------
-- In_Initialization_Context --
-------------------------------
function In_Initialization_Context (N : Node_Id) return Boolean is
Par : Node_Id;
Spec_Id : Entity_Id;
begin
-- Climb the parent chain looking for initialization actions
Par := Parent (N);
while Present (Par) loop
-- A block may be part of the initialization actions of a
-- default initialized object.
if Nkind (Par) = N_Block_Statement
and then Is_Initialization_Block (Par)
then
return True;
-- A subprogram body may denote an initialization routine
elsif Nkind (Par) = N_Subprogram_Body then
Spec_Id := Unique_Defining_Entity (Par);
-- The current subprogram body denotes a type init proc or
-- primitive [Deep_]Initialize.
if Is_Init_Proc (Spec_Id)
or else Is_Controlled_Proc (Spec_Id, Name_Initialize)
or else Is_TSS (Spec_Id, TSS_Deep_Initialize)
then
return True;
end if;
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Par) then
exit;
end if;
Par := Parent (Par);
end loop;
return False;
end In_Initialization_Context;
----------------------------------
-- Is_Partial_Finalization_Proc --
----------------------------------
function Is_Partial_Finalization_Proc
(Subp_Id : Entity_Id) return Boolean
is
begin
-- To qualify, the subprogram must denote a finalizer procedure
-- or primitive [Deep_]Finalize, and the call must appear within
-- an initialization context.
return
(Is_Controlled_Proc (Subp_Id, Name_Finalize)
or else Is_Finalizer_Proc (Subp_Id)
or else Is_TSS (Subp_Id, TSS_Deep_Finalize))
and then In_Initialization_Context (Call);
end Is_Partial_Finalization_Proc;
-- Local variables
Subp_Id : constant Entity_Id := Target (Call_Rep);
Subp_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Subp_Id, In_State);
Subp_Decl : constant Node_Id := Spec_Declaration (Subp_Rep);
SPARK_Rules_On : constant Boolean :=
SPARK_Mode_Of (Call_Rep) = Is_On
and then SPARK_Mode_Of (Subp_Rep) = Is_On;
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
-- Start of processing for Process_Conditional_ABE_Call
begin
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not New_In_State.Suppress_Info_Messages
then
Info_Call
(Call => Call,
Subp_Id => Subp_Id,
Info_Msg => True,
In_SPARK => SPARK_Rules_On);
end if;
-- Check whether the invocation of an entry clashes with an existing
-- restriction. This check is relevant only when the processing was
-- started from some library-level scenario.
if Is_Protected_Entry (Subp_Id) then
Check_Restriction (No_Entry_Calls_In_Elaboration_Code, Call);
elsif Is_Task_Entry (Subp_Id) then
Check_Restriction (No_Entry_Calls_In_Elaboration_Code, Call);
-- Task entry calls are never processed because the entry being
-- invoked does not have a corresponding "body", it has a select.
return;
end if;
-- Nothing to do when the call invokes a target defined within an
-- instance and switch -gnatd_i (ignore activations and calls to
-- instances for elaboration) is in effect.
if Debug_Flag_Underscore_I
and then In_External_Instance
(N => Call,
Target_Decl => Subp_Decl)
then
return;
-- Nothing to do when the call is a guaranteed ABE
elsif Is_Known_Guaranteed_ABE (Call) then
return;
-- Nothing to do when the root scenario appears at the declaration
-- level and the target is in the same unit but outside this context.
--
-- function B ...; -- target declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- return B; -- call site
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- function B ... is
-- ...
-- end B;
--
-- In the example above, the context of X is the declarative region
-- of Proc. The "elaboration" of X may eventually reach B which is
-- defined outside of X's context. B is relevant only when Proc is
-- invoked, but this happens only by means of "normal" elaboration,
-- therefore B must not be considered if this is not the case.
elsif Is_Up_Level_Target
(Targ_Decl => Subp_Decl,
In_State => New_In_State)
then
return;
end if;
-- Warnings are suppressed when a prior scenario is already in that
-- mode, or the call or target have warnings suppressed. Update the
-- state of the Processing phase to reflect this.
New_In_State.Suppress_Warnings :=
New_In_State.Suppress_Warnings
or else not Elaboration_Warnings_OK (Call_Rep)
or else not Elaboration_Warnings_OK (Subp_Rep);
-- The call occurs in an initial condition context when a prior
-- scenario is already in that mode, or when the target is an
-- Initial_Condition procedure. Update the state of the Processing
-- phase to reflect this.
New_In_State.Within_Initial_Condition :=
New_In_State.Within_Initial_Condition
or else Is_Initial_Condition_Proc (Subp_Id);
-- The call occurs in a partial finalization context when a prior
-- scenario is already in that mode, or when the target denotes a
-- [Deep_]Finalize primitive or a finalizer within an initialization
-- context. Update the state of the Processing phase to reflect this.
New_In_State.Within_Partial_Finalization :=
New_In_State.Within_Partial_Finalization
or else Is_Partial_Finalization_Proc (Subp_Id);
-- The SPARK rules are in effect. Note that -gnatd.v (enforce SPARK
-- elaboration rules in SPARK code) is intentionally not taken into
-- account here because Process_Conditional_ABE_Call_SPARK has two
-- separate modes of operation.
if SPARK_Rules_On then
Process_Conditional_ABE_Call_SPARK
(Call => Call,
Call_Rep => Call_Rep,
Subp_Id => Subp_Id,
Subp_Rep => Subp_Rep,
In_State => New_In_State);
-- Otherwise the Ada rules are in effect
else
Process_Conditional_ABE_Call_Ada
(Call => Call,
Call_Rep => Call_Rep,
Subp_Id => Subp_Id,
Subp_Rep => Subp_Rep,
In_State => New_In_State);
end if;
-- Inspect the target body (and barried function) for other suitable
-- elaboration scenarios.
Traverse_Conditional_ABE_Body
(N => Barrier_Body_Declaration (Subp_Rep),
In_State => New_In_State);
Traverse_Conditional_ABE_Body
(N => Body_Declaration (Subp_Rep),
In_State => New_In_State);
end Process_Conditional_ABE_Call;
--------------------------------------
-- Process_Conditional_ABE_Call_Ada --
--------------------------------------
procedure Process_Conditional_ABE_Call_Ada
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
Body_Decl : constant Node_Id := Body_Declaration (Subp_Rep);
Root : constant Node_Id := Root_Scenario;
Unit_Id : constant Node_Id := Unit (Subp_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Call_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Subp_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Call_Rep)
and then Elaboration_Checks_OK (Subp_Rep);
-- A run-time ABE check may be installed only when both the call
-- and the target have active elaboration checks, and both are not
-- ignored Ghost constructs.
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
begin
-- Nothing to do for an Ada dispatching call because there are no
-- ABE diagnostics for either models. ABE checks for the dynamic
-- model are handled by Install_Primitive_Elaboration_Check.
if Is_Dispatching_Call (Call_Rep) then
return;
-- Nothing to do when the call is ABE-safe
--
-- generic
-- function Gen ...;
--
-- function Gen ... is
-- begin
-- ...
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- function Inst is new Gen;
-- X : ... := Inst; -- safe call
-- ...
elsif Is_Safe_Call (Call, Subp_Id, Subp_Rep) then
return;
-- The call and the target body are both in the main unit
--
-- If the root scenario appears prior to the target body, then this
-- is a possible ABE with respect to the root scenario.
--
-- function B ...;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- return B; -- call site
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
--
-- function B ... is -- target body
-- ...
-- end B;
--
-- Y : ... := A; -- root scenario
--
-- IMPORTANT: The call to B from A is a possible ABE for X, but
-- not for Y. Installing an unconditional ABE raise prior to the
-- call to B would be wrong as it will fail for Y as well, but in
-- Y's case the call to B is never an ABE.
elsif Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
then
if Earlier_In_Extended_Unit (Root, Body_Decl) then
-- Do not emit any ABE diagnostics when a previous scenario in
-- this traversal has suppressed elaboration warnings.
if New_In_State.Suppress_Warnings then
null;
-- Do not emit any ABE diagnostics when the call occurs in a
-- partial finalization context because this leads to confusing
-- noise.
elsif New_In_State.Within_Partial_Finalization then
null;
-- Otherwise emit the ABE diagnostic
else
Error_Msg_NE
("??cannot call & before body seen", Call, Subp_Id);
Error_Msg_N
("\Program_Error may be raised at run time", Call);
Output_Active_Scenarios (Call, New_In_State);
end if;
-- Install a conditional run-time ABE check to verify that the
-- target body has been elaborated prior to the call.
if Check_OK then
Install_Scenario_ABE_Check
(N => Call,
Targ_Id => Subp_Id,
Targ_Rep => Subp_Rep,
Disable => Call_Rep);
-- Update the state of the Processing phase to indicate that
-- no implicit Elaborate[_All] pragma must be generated from
-- this point on.
--
-- function B ...;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- <ABE check>
-- return B;
-- ...
-- end A;
--
-- X : ... := A;
--
-- function B ... is
-- External.Subp; -- imparts Elaborate_All
-- end B;
--
-- If Some_Condition is True, then the ABE check will fail
-- at runtime and the call to External.Subp will never take
-- place, rendering the implicit Elaborate_All useless.
--
-- If the value of Some_Condition is False, then the call
-- to External.Subp will never take place, rendering the
-- implicit Elaborate_All useless.
New_In_State.Suppress_Implicit_Pragmas := True;
end if;
end if;
-- Otherwise the target body is not available in this compilation or
-- it resides in an external unit. Install a run-time ABE check to
-- verify that the target body has been elaborated prior to the call
-- site when the dynamic model is in effect.
elsif Check_OK
and then New_In_State.Processing = Dynamic_Model_Processing
then
Install_Unit_ABE_Check
(N => Call,
Unit_Id => Unit_Id,
Disable => Call_Rep);
end if;
-- Ensure that the unit with the target body is elaborated prior to
-- the main unit. The implicit Elaborate[_All] is generated only when
-- the call has elaboration checks enabled. This behavior parallels
-- that of the old ABE mechanism.
if Elaboration_Checks_OK (Call_Rep) then
Ensure_Prior_Elaboration
(N => Call,
Unit_Id => Unit_Id,
Prag_Nam => Name_Elaborate_All,
In_State => New_In_State);
end if;
end Process_Conditional_ABE_Call_Ada;
----------------------------------------
-- Process_Conditional_ABE_Call_SPARK --
----------------------------------------
procedure Process_Conditional_ABE_Call_SPARK
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Call_Rep);
Body_Decl : constant Node_Id := Body_Declaration (Subp_Rep);
Region : Node_Id;
begin
-- Ensure that a suitable elaboration model is in effect for SPARK
-- rule verification.
Check_SPARK_Model_In_Effect;
-- The call and the target body are both in the main unit
if Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
and then Earlier_In_Extended_Unit (Call, Body_Decl)
then
-- Do not emit any ABE diagnostics when a previous scenario in
-- this traversal has suppressed elaboration warnings.
if In_State.Suppress_Warnings then
null;
-- Do not emit any ABE diagnostics when the call occurs in an
-- initial condition context because this leads to incorrect
-- diagnostics.
elsif In_State.Within_Initial_Condition then
null;
-- Do not emit any ABE diagnostics when the call occurs in a
-- partial finalization context because this leads to confusing
-- noise.
elsif In_State.Within_Partial_Finalization then
null;
-- Ensure that a call that textually precedes the subprogram body
-- it invokes appears within the early call region of the body.
--
-- IMPORTANT: This check must always be performed even when switch
-- -gnatd.v (enforce SPARK elaboration rules in SPARK code) is not
-- specified because the static model cannot guarantee the absence
-- of elaboration issues when dispatching calls are involved.
else
Region := Find_Early_Call_Region (Body_Decl);
if Earlier_In_Extended_Unit (Call, Region) then
Error_Msg_NE
("call must appear within early call region of subprogram "
& "body & (SPARK RM 7.7(3))",
Call, Subp_Id);
Error_Msg_Sloc := Sloc (Region);
Error_Msg_N ("\region starts #", Call);
Error_Msg_Sloc := Sloc (Body_Decl);
Error_Msg_N ("\region ends #", Call);
Output_Active_Scenarios (Call, In_State);
end if;
end if;
end if;
-- A call to a source target or to a target which emulates Ada
-- or SPARK semantics imposes an Elaborate_All requirement on the
-- context of the main unit. Determine whether the context has a
-- pragma strong enough to meet the requirement.
--
-- IMPORTANT: This check must be performed only when switch -gnatd.v
-- (enforce SPARK elaboration rules in SPARK code) is active because
-- the static model can ensure the prior elaboration of the unit
-- which contains a body by installing an implicit Elaborate[_All]
-- pragma.
if Debug_Flag_Dot_V then
if Comes_From_Source (Subp_Id)
or else Is_Ada_Semantic_Target (Subp_Id)
or else Is_SPARK_Semantic_Target (Subp_Id)
then
Meet_Elaboration_Requirement
(N => Call,
Targ_Id => Subp_Id,
Req_Nam => Name_Elaborate_All,
In_State => In_State);
end if;
-- Otherwise ensure that the unit with the target body is elaborated
-- prior to the main unit.
else
Ensure_Prior_Elaboration
(N => Call,
Unit_Id => Unit (Subp_Rep),
Prag_Nam => Name_Elaborate_All,
In_State => In_State);
end if;
end Process_Conditional_ABE_Call_SPARK;
-------------------------------------------
-- Process_Conditional_ABE_Instantiation --
-------------------------------------------
procedure Process_Conditional_ABE_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Gen_Id : constant Entity_Id := Target (Inst_Rep);
Gen_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Gen_Id, In_State);
SPARK_Rules_On : constant Boolean :=
SPARK_Mode_Of (Inst_Rep) = Is_On
and then SPARK_Mode_Of (Gen_Rep) = Is_On;
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
begin
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not New_In_State.Suppress_Info_Messages
then
Info_Instantiation
(Inst => Inst,
Gen_Id => Gen_Id,
Info_Msg => True,
In_SPARK => SPARK_Rules_On);
end if;
-- Nothing to do when the instantiation is a guaranteed ABE
if Is_Known_Guaranteed_ABE (Inst) then
return;
-- Nothing to do when the root scenario appears at the declaration
-- level and the generic is in the same unit, but outside this
-- context.
--
-- generic
-- procedure Gen is ...; -- generic declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- procedure I is new Gen; -- instantiation site
-- ...
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- procedure Gen is
-- ...
-- end Gen;
--
-- In the example above, the context of X is the declarative region
-- of Proc. The "elaboration" of X may eventually reach Gen which
-- appears outside of X's context. Gen is relevant only when Proc is
-- invoked, but this happens only by means of "normal" elaboration,
-- therefore Gen must not be considered if this is not the case.
elsif Is_Up_Level_Target
(Targ_Decl => Spec_Declaration (Gen_Rep),
In_State => New_In_State)
then
return;
end if;
-- Warnings are suppressed when a prior scenario is already in that
-- mode, or when the instantiation has warnings suppressed. Update
-- the state of the processing phase to reflect this.
New_In_State.Suppress_Warnings :=
New_In_State.Suppress_Warnings
or else not Elaboration_Warnings_OK (Inst_Rep);
-- The SPARK rules are in effect
if SPARK_Rules_On then
Process_Conditional_ABE_Instantiation_SPARK
(Inst => Inst,
Inst_Rep => Inst_Rep,
Gen_Id => Gen_Id,
Gen_Rep => Gen_Rep,
In_State => New_In_State);
-- Otherwise the Ada rules are in effect, or SPARK code is allowed to
-- violate the SPARK rules.
else
Process_Conditional_ABE_Instantiation_Ada
(Inst => Inst,
Inst_Rep => Inst_Rep,
Gen_Id => Gen_Id,
Gen_Rep => Gen_Rep,
In_State => New_In_State);
end if;
end Process_Conditional_ABE_Instantiation;
-----------------------------------------------
-- Process_Conditional_ABE_Instantiation_Ada --
-----------------------------------------------
procedure Process_Conditional_ABE_Instantiation_Ada
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
Body_Decl : constant Node_Id := Body_Declaration (Gen_Rep);
Root : constant Node_Id := Root_Scenario;
Unit_Id : constant Entity_Id := Unit (Gen_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Inst_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Gen_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Inst_Rep)
and then Elaboration_Checks_OK (Gen_Rep);
-- A run-time ABE check may be installed only when both the instance
-- and the generic have active elaboration checks and both are not
-- ignored Ghost constructs.
New_In_State : Processing_In_State := In_State;
-- Each step of the Processing phase constitutes a new state
begin
-- Nothing to do when the instantiation is ABE-safe
--
-- generic
-- package Gen is
-- ...
-- end Gen;
--
-- package body Gen is
-- ...
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- package Inst is new Gen (ABE); -- safe instantiation
-- ...
if Is_Safe_Instantiation (Inst, Gen_Id, Gen_Rep) then
return;
-- The instantiation and the generic body are both in the main unit
--
-- If the root scenario appears prior to the generic body, then this
-- is a possible ABE with respect to the root scenario.
--
-- generic
-- package Gen is
-- ...
-- end Gen;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- package Inst is new Gen; -- instantiation site
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
--
-- package body Gen is -- generic body
-- ...
-- end Gen;
--
-- Y : ... := A; -- root scenario
--
-- IMPORTANT: The instantiation of Gen is a possible ABE for X,
-- but not for Y. Installing an unconditional ABE raise prior to
-- the instance site would be wrong as it will fail for Y as well,
-- but in Y's case the instantiation of Gen is never an ABE.
elsif Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
then
if Earlier_In_Extended_Unit (Root, Body_Decl) then
-- Do not emit any ABE diagnostics when a previous scenario in
-- this traversal has suppressed elaboration warnings.
if New_In_State.Suppress_Warnings then
null;
-- Do not emit any ABE diagnostics when the instantiation
-- occurs in partial finalization context because this leads
-- to unwanted noise.
elsif New_In_State.Within_Partial_Finalization then
null;
-- Otherwise output the diagnostic
else
Error_Msg_NE
("??cannot instantiate & before body seen", Inst, Gen_Id);
Error_Msg_N
("\Program_Error may be raised at run time", Inst);
Output_Active_Scenarios (Inst, New_In_State);
end if;
-- Install a conditional run-time ABE check to verify that the
-- generic body has been elaborated prior to the instantiation.
if Check_OK then
Install_Scenario_ABE_Check
(N => Inst,
Targ_Id => Gen_Id,
Targ_Rep => Gen_Rep,
Disable => Inst_Rep);
-- Update the state of the Processing phase to indicate that
-- no implicit Elaborate[_All] pragma must be generated from
-- this point on.
--
-- generic
-- package Gen is
-- ...
-- end Gen;
--
-- function A ... is
-- begin
-- if Some_Condition then
-- <ABE check>
-- declare Inst is new Gen;
-- ...
-- end A;
--
-- X : ... := A;
--
-- package body Gen is
-- begin
-- External.Subp; -- imparts Elaborate_All
-- end Gen;
--
-- If Some_Condition is True, then the ABE check will fail
-- at runtime and the call to External.Subp will never take
-- place, rendering the implicit Elaborate_All useless.
--
-- If the value of Some_Condition is False, then the call
-- to External.Subp will never take place, rendering the
-- implicit Elaborate_All useless.
New_In_State.Suppress_Implicit_Pragmas := True;
end if;
end if;
-- Otherwise the generic body is not available in this compilation
-- or it resides in an external unit. Install a run-time ABE check
-- to verify that the generic body has been elaborated prior to the
-- instantiation when the dynamic model is in effect.
elsif Check_OK
and then New_In_State.Processing = Dynamic_Model_Processing
then
Install_Unit_ABE_Check
(N => Inst,
Unit_Id => Unit_Id,
Disable => Inst_Rep);
end if;
-- Ensure that the unit with the generic body is elaborated prior
-- to the main unit. No implicit pragma has to be generated if the
-- instantiation has elaboration checks suppressed. This behavior
-- parallels that of the old ABE mechanism.
if Elaboration_Checks_OK (Inst_Rep) then
Ensure_Prior_Elaboration
(N => Inst,
Unit_Id => Unit_Id,
Prag_Nam => Name_Elaborate,
In_State => New_In_State);
end if;
end Process_Conditional_ABE_Instantiation_Ada;
-------------------------------------------------
-- Process_Conditional_ABE_Instantiation_SPARK --
-------------------------------------------------
procedure Process_Conditional_ABE_Instantiation_SPARK
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Inst_Rep);
Req_Nam : Name_Id;
begin
-- Ensure that a suitable elaboration model is in effect for SPARK
-- rule verification.
Check_SPARK_Model_In_Effect;
-- A source instantiation imposes an Elaborate[_All] requirement
-- on the context of the main unit. Determine whether the context
-- has a pragma strong enough to meet the requirement. The check
-- is orthogonal to the ABE ramifications of the instantiation.
--
-- IMPORTANT: This check must be performed only when switch -gnatd.v
-- (enforce SPARK elaboration rules in SPARK code) is active because
-- the static model can ensure the prior elaboration of the unit
-- which contains a body by installing an implicit Elaborate[_All]
-- pragma.
if Debug_Flag_Dot_V then
if Nkind (Inst) = N_Package_Instantiation then
Req_Nam := Name_Elaborate_All;
else
Req_Nam := Name_Elaborate;
end if;
Meet_Elaboration_Requirement
(N => Inst,
Targ_Id => Gen_Id,
Req_Nam => Req_Nam,
In_State => In_State);
-- Otherwise ensure that the unit with the target body is elaborated
-- prior to the main unit.
else
Ensure_Prior_Elaboration
(N => Inst,
Unit_Id => Unit (Gen_Rep),
Prag_Nam => Name_Elaborate,
In_State => In_State);
end if;
end Process_Conditional_ABE_Instantiation_SPARK;
-------------------------------------------------
-- Process_Conditional_ABE_Variable_Assignment --
-------------------------------------------------
procedure Process_Conditional_ABE_Variable_Assignment
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Var_Id : constant Entity_Id := Target (Asmt_Rep);
Var_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Var_Id, In_State);
SPARK_Rules_On : constant Boolean :=
SPARK_Mode_Of (Asmt_Rep) = Is_On
and then SPARK_Mode_Of (Var_Rep) = Is_On;
begin
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not In_State.Suppress_Info_Messages
then
Elab_Msg_NE
(Msg => "assignment to & during elaboration",
N => Asmt,
Id => Var_Id,
Info_Msg => True,
In_SPARK => SPARK_Rules_On);
end if;
-- The SPARK rules are in effect. These rules are applied regardless
-- of whether switch -gnatd.v (enforce SPARK elaboration rules in
-- SPARK code) is in effect because the static model cannot ensure
-- safe assignment of variables.
if SPARK_Rules_On then
Process_Conditional_ABE_Variable_Assignment_SPARK
(Asmt => Asmt,
Asmt_Rep => Asmt_Rep,
Var_Id => Var_Id,
Var_Rep => Var_Rep,
In_State => In_State);
-- Otherwise the Ada rules are in effect
else
Process_Conditional_ABE_Variable_Assignment_Ada
(Asmt => Asmt,
Asmt_Rep => Asmt_Rep,
Var_Id => Var_Id,
Var_Rep => Var_Rep,
In_State => In_State);
end if;
end Process_Conditional_ABE_Variable_Assignment;
-----------------------------------------------------
-- Process_Conditional_ABE_Variable_Assignment_Ada --
-----------------------------------------------------
procedure Process_Conditional_ABE_Variable_Assignment_Ada
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Var_Id : Entity_Id;
Var_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Asmt_Rep);
Var_Decl : constant Node_Id := Variable_Declaration (Var_Rep);
Unit_Id : constant Entity_Id := Unit (Var_Rep);
begin
-- Emit a warning when an uninitialized variable declared in a
-- package spec without a pragma Elaborate_Body is initialized
-- by elaboration code within the corresponding body.
if Is_Elaboration_Warnings_OK_Id (Var_Id)
and then not Is_Initialized (Var_Decl)
and then not Has_Pragma_Elaborate_Body (Unit_Id)
then
-- Do not emit any ABE diagnostics when a previous scenario in
-- this traversal has suppressed elaboration warnings.
if not In_State.Suppress_Warnings then
Error_Msg_NE
("??variable & can be accessed by clients before this "
& "initialization", Asmt, Var_Id);
Error_Msg_NE
("\add pragma ""Elaborate_Body"" to spec & to ensure proper "
& "initialization", Asmt, Unit_Id);
Output_Active_Scenarios (Asmt, In_State);
end if;
-- Generate an implicit Elaborate_Body in the spec
Set_Elaborate_Body_Desirable (Unit_Id);
end if;
end Process_Conditional_ABE_Variable_Assignment_Ada;
-------------------------------------------------------
-- Process_Conditional_ABE_Variable_Assignment_SPARK --
-------------------------------------------------------
procedure Process_Conditional_ABE_Variable_Assignment_SPARK
(Asmt : Node_Id;
Asmt_Rep : Scenario_Rep_Id;
Var_Id : Entity_Id;
Var_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Asmt_Rep);
Var_Decl : constant Node_Id := Variable_Declaration (Var_Rep);
Unit_Id : constant Entity_Id := Unit (Var_Rep);
begin
-- Ensure that a suitable elaboration model is in effect for SPARK
-- rule verification.
Check_SPARK_Model_In_Effect;
-- Do not emit any ABE diagnostics when a previous scenario in this
-- traversal has suppressed elaboration warnings.
if In_State.Suppress_Warnings then
null;
-- Emit an error when an initialized variable declared in a package
-- spec that is missing pragma Elaborate_Body is further modified by
-- elaboration code within the corresponding body.
elsif Is_Elaboration_Warnings_OK_Id (Var_Id)
and then Is_Initialized (Var_Decl)
and then not Has_Pragma_Elaborate_Body (Unit_Id)
then
Error_Msg_NE
("variable & modified by elaboration code in package body",
Asmt, Var_Id);
Error_Msg_NE
("\add pragma ""Elaborate_Body"" to spec & to ensure full "
& "initialization", Asmt, Unit_Id);
Output_Active_Scenarios (Asmt, In_State);
end if;
end Process_Conditional_ABE_Variable_Assignment_SPARK;
------------------------------------------------
-- Process_Conditional_ABE_Variable_Reference --
------------------------------------------------
procedure Process_Conditional_ABE_Variable_Reference
(Ref : Node_Id;
Ref_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Var_Id : constant Entity_Id := Target (Ref);
Var_Rep : Target_Rep_Id;
Unit_Id : Entity_Id;
begin
-- Nothing to do when the variable reference is not a read
if not Is_Read_Reference (Ref_Rep) then
return;
end if;
Var_Rep := Target_Representation_Of (Var_Id, In_State);
Unit_Id := Unit (Var_Rep);
-- Output relevant information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas) is in effect.
if Elab_Info_Messages
and then not In_State.Suppress_Info_Messages
then
Elab_Msg_NE
(Msg => "read of variable & during elaboration",
N => Ref,
Id => Var_Id,
Info_Msg => True,
In_SPARK => True);
end if;
-- Nothing to do when the variable appears within the main unit
-- because diagnostics on reads are relevant only for external
-- variables.
if Is_Same_Unit (Unit_Id, Main_Unit_Entity) then
null;
-- Nothing to do when the variable is already initialized. Note that
-- the variable may be further modified by the external unit.
elsif Is_Initialized (Variable_Declaration (Var_Rep)) then
null;
-- Nothing to do when the external unit guarantees the initialization
-- of the variable by means of pragma Elaborate_Body.
elsif Has_Pragma_Elaborate_Body (Unit_Id) then
null;
-- A variable read imposes an Elaborate requirement on the context of
-- the main unit. Determine whether the context has a pragma strong
-- enough to meet the requirement.
else
Meet_Elaboration_Requirement
(N => Ref,
Targ_Id => Var_Id,
Req_Nam => Name_Elaborate,
In_State => In_State);
end if;
end Process_Conditional_ABE_Variable_Reference;
-----------------------------------
-- Traverse_Conditional_ABE_Body --
-----------------------------------
procedure Traverse_Conditional_ABE_Body
(N : Node_Id;
In_State : Processing_In_State)
is
begin
Traverse_Body
(N => N,
Requires_Processing => Is_Conditional_ABE_Scenario'Access,
Processor => Process_Conditional_ABE'Access,
In_State => In_State);
end Traverse_Conditional_ABE_Body;
end Conditional_ABE_Processor;
-------------
-- Destroy --
-------------
procedure Destroy (NE : in out Node_Or_Entity_Id) is
pragma Unreferenced (NE);
begin
null;
end Destroy;
-----------------
-- Diagnostics --
-----------------
package body Diagnostics is
-----------------
-- Elab_Msg_NE --
-----------------
procedure Elab_Msg_NE
(Msg : String;
N : Node_Id;
Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean)
is
function Prefix return String;
pragma Inline (Prefix);
-- Obtain the prefix of the message
function Suffix return String;
pragma Inline (Suffix);
-- Obtain the suffix of the message
------------
-- Prefix --
------------
function Prefix return String is
begin
if Info_Msg then
return "info: ";
else
return "";
end if;
end Prefix;
------------
-- Suffix --
------------
function Suffix return String is
begin
if In_SPARK then
return " in SPARK";
else
return "";
end if;
end Suffix;
-- Start of processing for Elab_Msg_NE
begin
Error_Msg_NE (Prefix & Msg & Suffix, N, Id);
end Elab_Msg_NE;
---------------
-- Info_Call --
---------------
procedure Info_Call
(Call : Node_Id;
Subp_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean)
is
procedure Info_Accept_Alternative;
pragma Inline (Info_Accept_Alternative);
-- Output information concerning an accept alternative
procedure Info_Simple_Call;
pragma Inline (Info_Simple_Call);
-- Output information concerning the call
procedure Info_Type_Actions (Action : String);
pragma Inline (Info_Type_Actions);
-- Output information concerning action Action of a type
procedure Info_Verification_Call
(Pred : String;
Id : Entity_Id;
Id_Kind : String);
pragma Inline (Info_Verification_Call);
-- Output information concerning the verification of predicate Pred
-- applied to related entity Id with kind Id_Kind.
-----------------------------
-- Info_Accept_Alternative --
-----------------------------
procedure Info_Accept_Alternative is
Entry_Id : constant Entity_Id := Receiving_Entry (Subp_Id);
pragma Assert (Present (Entry_Id));
begin
Elab_Msg_NE
(Msg => "accept for entry & during elaboration",
N => Call,
Id => Entry_Id,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end Info_Accept_Alternative;
----------------------
-- Info_Simple_Call --
----------------------
procedure Info_Simple_Call is
begin
Elab_Msg_NE
(Msg => "call to & during elaboration",
N => Call,
Id => Subp_Id,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end Info_Simple_Call;
-----------------------
-- Info_Type_Actions --
-----------------------
procedure Info_Type_Actions (Action : String) is
Typ : constant Entity_Id := First_Formal_Type (Subp_Id);
pragma Assert (Present (Typ));
begin
Elab_Msg_NE
(Msg => Action & " actions for type & during elaboration",
N => Call,
Id => Typ,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end Info_Type_Actions;
----------------------------
-- Info_Verification_Call --
----------------------------
procedure Info_Verification_Call
(Pred : String;
Id : Entity_Id;
Id_Kind : String)
is
pragma Assert (Present (Id));
begin
Elab_Msg_NE
(Msg =>
"verification of " & Pred & " of " & Id_Kind & " & during "
& "elaboration",
N => Call,
Id => Id,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end Info_Verification_Call;
-- Start of processing for Info_Call
begin
-- Do not output anything for targets defined in internal units
-- because this creates noise.
if not In_Internal_Unit (Subp_Id) then
-- Accept alternative
if Is_Accept_Alternative_Proc (Subp_Id) then
Info_Accept_Alternative;
-- Adjustment
elsif Is_TSS (Subp_Id, TSS_Deep_Adjust) then
Info_Type_Actions ("adjustment");
-- Default_Initial_Condition
elsif Is_Default_Initial_Condition_Proc (Subp_Id) then
Info_Verification_Call
(Pred => "Default_Initial_Condition",
Id => First_Formal_Type (Subp_Id),
Id_Kind => "type");
-- Entries
elsif Is_Protected_Entry (Subp_Id) then
Info_Simple_Call;
-- Task entry calls are never processed because the entry being
-- invoked does not have a corresponding "body", it has a select.
elsif Is_Task_Entry (Subp_Id) then
null;
-- Finalization
elsif Is_TSS (Subp_Id, TSS_Deep_Finalize) then
Info_Type_Actions ("finalization");
-- Calls to _Finalizer procedures must not appear in the output
-- because this creates confusing noise.
elsif Is_Finalizer_Proc (Subp_Id) then
null;
-- Initial_Condition
elsif Is_Initial_Condition_Proc (Subp_Id) then
Info_Verification_Call
(Pred => "Initial_Condition",
Id => Find_Enclosing_Scope (Call),
Id_Kind => "package");
-- Initialization
elsif Is_Init_Proc (Subp_Id)
or else Is_TSS (Subp_Id, TSS_Deep_Initialize)
then
Info_Type_Actions ("initialization");
-- Invariant
elsif Is_Invariant_Proc (Subp_Id) then
Info_Verification_Call
(Pred => "invariants",
Id => First_Formal_Type (Subp_Id),
Id_Kind => "type");
-- Partial invariant calls must not appear in the output because
-- this creates confusing noise.
elsif Is_Partial_Invariant_Proc (Subp_Id) then
null;
-- _Postconditions
elsif Is_Postconditions_Proc (Subp_Id) then
Info_Verification_Call
(Pred => "postconditions",
Id => Find_Enclosing_Scope (Call),
Id_Kind => "subprogram");
-- Subprograms must come last because some of the previous cases
-- fall under this category.
elsif Ekind (Subp_Id) = E_Function then
Info_Simple_Call;
elsif Ekind (Subp_Id) = E_Procedure then
Info_Simple_Call;
else
pragma Assert (False);
return;
end if;
end if;
end Info_Call;
------------------------
-- Info_Instantiation --
------------------------
procedure Info_Instantiation
(Inst : Node_Id;
Gen_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean)
is
begin
Elab_Msg_NE
(Msg => "instantiation of & during elaboration",
N => Inst,
Id => Gen_Id,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end Info_Instantiation;
-----------------------------
-- Info_Variable_Reference --
-----------------------------
procedure Info_Variable_Reference
(Ref : Node_Id;
Var_Id : Entity_Id;
Info_Msg : Boolean;
In_SPARK : Boolean)
is
begin
if Is_Read (Ref) then
Elab_Msg_NE
(Msg => "read of variable & during elaboration",
N => Ref,
Id => Var_Id,
Info_Msg => Info_Msg,
In_SPARK => In_SPARK);
end if;
end Info_Variable_Reference;
end Diagnostics;
---------------------------------
-- Early_Call_Region_Processor --
---------------------------------
package body Early_Call_Region_Processor is
---------------------
-- Data structures --
---------------------
-- The following map relates early call regions to subprogram bodies
procedure Destroy (N : in out Node_Id);
-- Destroy node N
package ECR_Map is new Dynamic_Hash_Tables
(Key_Type => Entity_Id,
Value_Type => Node_Id,
No_Value => Empty,
Expansion_Threshold => 1.5,
Expansion_Factor => 2,
Compression_Threshold => 0.3,
Compression_Factor => 2,
"=" => "=",
Destroy_Value => Destroy,
Hash => Hash);
Early_Call_Regions_Map : ECR_Map.Dynamic_Hash_Table := ECR_Map.Nil;
-----------------------
-- Local subprograms --
-----------------------
function Early_Call_Region (Body_Id : Entity_Id) return Node_Id;
pragma Inline (Early_Call_Region);
-- Obtain the early call region associated with entry or subprogram body
-- Body_Id.
procedure Set_Early_Call_Region (Body_Id : Entity_Id; Start : Node_Id);
pragma Inline (Set_Early_Call_Region);
-- Associate an early call region with begins at construct Start with
-- entry or subprogram body Body_Id.
-------------
-- Destroy --
-------------
procedure Destroy (N : in out Node_Id) is
pragma Unreferenced (N);
begin
null;
end Destroy;
-----------------------
-- Early_Call_Region --
-----------------------
function Early_Call_Region (Body_Id : Entity_Id) return Node_Id is
pragma Assert (Present (Body_Id));
begin
return ECR_Map.Get (Early_Call_Regions_Map, Body_Id);
end Early_Call_Region;
------------------------------------------
-- Finalize_Early_Call_Region_Processor --
------------------------------------------
procedure Finalize_Early_Call_Region_Processor is
begin
ECR_Map.Destroy (Early_Call_Regions_Map);
end Finalize_Early_Call_Region_Processor;
----------------------------
-- Find_Early_Call_Region --
----------------------------
function Find_Early_Call_Region
(Body_Decl : Node_Id;
Assume_Elab_Body : Boolean := False;
Skip_Memoization : Boolean := False) return Node_Id
is
-- NOTE: The routines within Find_Early_Call_Region are intentionally
-- unnested to avoid deep indentation of code.
ECR_Found : exception;
-- This exception is raised when the early call region has been found
Start : Node_Id := Empty;
-- The start of the early call region. This variable is updated by
-- the various nested routines. Due to the use of exceptions, the
-- variable must be global to the nested routines.
-- The algorithm implemented in this routine attempts to find the
-- early call region of a subprogram body by inspecting constructs
-- in reverse declarative order, while navigating the tree. The
-- algorithm consists of an Inspection phase and Advancement phase.
-- The pseudocode is as follows:
--
-- loop
-- inspection phase
-- advancement phase
-- end loop
--
-- The infinite loop is terminated by raising exception ECR_Found.
-- The algorithm utilizes two pointers, Curr and Start, to represent
-- the current construct to inspect and the start of the early call
-- region.
--
-- IMPORTANT: The algorithm must maintain the following invariant at
-- all time for it to function properly:
--
-- A nested construct is entered only when it contains suitable
-- constructs.
--
-- This guarantees that leaving a nested or encapsulating construct
-- functions properly.
--
-- The Inspection phase determines whether the current construct is
-- non-preelaborable, and if it is, the algorithm terminates.
--
-- The Advancement phase walks the tree in reverse declarative order,
-- while entering and leaving nested and encapsulating constructs. It
-- may also terminate the elaborithm. There are several special cases
-- of advancement.
--
-- 1) General case:
--
-- <construct 1>
-- ...
-- <construct N-1> <- Curr
-- <construct N> <- Start
-- <subprogram body>
--
-- In the general case, a declarative or statement list is traversed
-- in reverse order where Curr is the lead pointer, and Start is the
-- last preelaborable construct.
--
-- 2) Entering handled bodies
--
-- package body Nested is <- Curr (2.3)
-- <declarations> <- Curr (2.2)
-- begin
-- <statements> <- Curr (2.1)
-- end Nested;
-- <construct> <- Start
--
-- In this case, the algorithm enters a handled body by starting from
-- the last statement (2.1), or the last declaration (2.2), or the
-- body is consumed (2.3) because it is empty and thus preelaborable.
--
-- 3) Entering package declarations
--
-- package Nested is <- Curr (2.3)
-- <visible declarations> <- Curr (2.2)
-- private
-- <private declarations> <- Curr (2.1)
-- end Nested;
-- <construct> <- Start
--
-- In this case, the algorithm enters a package declaration by
-- starting from the last private declaration (2.1), the last visible
-- declaration (2.2), or the package is consumed (2.3) because it is
-- empty and thus preelaborable.
--
-- 4) Transitioning from list to list of the same construct
--
-- Certain constructs have two eligible lists. The algorithm must
-- thus transition from the second to the first list when the second
-- list is exhausted.
--
-- declare <- Curr (4.2)
-- <declarations> <- Curr (4.1)
-- begin
-- <statements> <- Start
-- end;
--
-- In this case, the algorithm has exhausted the second list (the
-- statements in the example above), and continues with the last
-- declaration (4.1) or the construct is consumed (4.2) because it
-- contains only preelaborable code.
--
-- 5) Transitioning from list to construct
--
-- tack body Task is <- Curr (5.1)
-- <- Curr (Empty)
-- <construct 1> <- Start
--
-- In this case, the algorithm has exhausted a list, Curr is Empty,
-- and the owner of the list is consumed (5.1).
--
-- 6) Transitioning from unit to unit
--
-- A package body with a spec subject to pragma Elaborate_Body
-- extends the possible range of the early call region to the package
-- spec.
--
-- package Pack is <- Curr (6.3)
-- pragma Elaborate_Body; <- Curr (6.2)
-- <visible declarations> <- Curr (6.2)
-- private
-- <private declarations> <- Curr (6.1)
-- end Pack;
--
-- package body Pack is <- Curr, Start
--
-- In this case, the algorithm has reached a package body compilation
-- unit whose spec is subject to pragma Elaborate_Body, or the caller
-- of the algorithm has specified this behavior. This transition is
-- equivalent to 3).
--
-- 7) Transitioning from unit to termination
--
-- Reaching a compilation unit always terminates the algorithm as
-- there are no more lists to examine. This must take case 6) into
-- account.
--
-- 8) Transitioning from subunit to stub
--
-- package body Pack is separate; <- Curr (8.1)
--
-- separate (...)
-- package body Pack is <- Curr, Start
--
-- Reaching a subunit continues the search from the corresponding
-- stub (8.1).
procedure Advance (Curr : in out Node_Id);
pragma Inline (Advance);
-- Update the Curr and Start pointers depending on their location
-- in the tree to the next eligible construct. This routine raises
-- ECR_Found.
procedure Enter_Handled_Body (Curr : in out Node_Id);
pragma Inline (Enter_Handled_Body);
-- Update the Curr and Start pointers to enter a nested handled body
-- if applicable. This routine raises ECR_Found.
procedure Enter_Package_Declaration (Curr : in out Node_Id);
pragma Inline (Enter_Package_Declaration);
-- Update the Curr and Start pointers to enter a nested package spec
-- if applicable. This routine raises ECR_Found.
function Find_ECR (N : Node_Id) return Node_Id;
pragma Inline (Find_ECR);
-- Find an early call region starting from arbitrary node N
function Has_Suitable_Construct (List : List_Id) return Boolean;
pragma Inline (Has_Suitable_Construct);
-- Determine whether list List contains a suitable construct for
-- inclusion into an early call region.
procedure Include (N : Node_Id; Curr : out Node_Id);
pragma Inline (Include);
-- Update the Curr and Start pointers to include arbitrary construct
-- N in the early call region. This routine raises ECR_Found.
function Is_OK_Preelaborable_Construct (N : Node_Id) return Boolean;
pragma Inline (Is_OK_Preelaborable_Construct);
-- Determine whether arbitrary node N denotes a preelaboration-safe
-- construct.
function Is_Suitable_Construct (N : Node_Id) return Boolean;
pragma Inline (Is_Suitable_Construct);
-- Determine whether arbitrary node N denotes a suitable construct
-- for inclusion into the early call region.
procedure Transition_Body_Declarations
(Bod : Node_Id;
Curr : out Node_Id);
pragma Inline (Transition_Body_Declarations);
-- Update the Curr and Start pointers when construct Bod denotes a
-- block statement or a suitable body. This routine raises ECR_Found.
procedure Transition_Handled_Statements
(HSS : Node_Id;
Curr : out Node_Id);
pragma Inline (Transition_Handled_Statements);
-- Update the Curr and Start pointers when node HSS denotes a handled
-- sequence of statements. This routine raises ECR_Found.
procedure Transition_Spec_Declarations
(Spec : Node_Id;
Curr : out Node_Id);
pragma Inline (Transition_Spec_Declarations);
-- Update the Curr and Start pointers when construct Spec denotes
-- a concurrent definition or a package spec. This routine raises
-- ECR_Found.
procedure Transition_Unit (Unit : Node_Id; Curr : out Node_Id);
pragma Inline (Transition_Unit);
-- Update the Curr and Start pointers when node Unit denotes a
-- potential compilation unit. This routine raises ECR_Found.
-------------
-- Advance --
-------------
procedure Advance (Curr : in out Node_Id) is
Context : Node_Id;
begin
-- Curr denotes one of the following cases upon entry into this
-- routine:
--
-- * Empty - There is no current construct when a declarative or
-- a statement list has been exhausted. This does not indicate
-- that the early call region has been computed as it is still
-- possible to transition to another list.
--
-- * Encapsulator - The current construct wraps declarations
-- and/or statements. This indicates that the early call
-- region may extend within the nested construct.
--
-- * Preelaborable - The current construct is preelaborable
-- because Find_ECR would not invoke Advance if this was not
-- the case.
-- The current construct is an encapsulator or is preelaborable
if Present (Curr) then
-- Enter encapsulators by inspecting their declarations and/or
-- statements.
if Nkind (Curr) in N_Block_Statement | N_Package_Body then
Enter_Handled_Body (Curr);
elsif Nkind (Curr) = N_Package_Declaration then
Enter_Package_Declaration (Curr);
-- Early call regions have a property which can be exploited to
-- optimize the algorithm.
--
-- <preceding subprogram body>
-- <preelaborable construct 1>
-- ...
-- <preelaborable construct N>
-- <initiating subprogram body>
--
-- If a traversal initiated from a subprogram body reaches a
-- preceding subprogram body, then both bodies share the same
-- early call region.
--
-- The property results in the following desirable effects:
--
-- * If the preceding body already has an early call region,
-- then the initiating body can reuse it. This minimizes the
-- amount of processing performed by the algorithm.
--
-- * If the preceding body lack an early call region, then the
-- algorithm can compute the early call region, and reuse it
-- for the initiating body. This processing performs the same
-- amount of work, but has the beneficial effect of computing
-- the early call regions of all preceding bodies.
elsif Nkind (Curr) in N_Entry_Body | N_Subprogram_Body then
Start :=
Find_Early_Call_Region
(Body_Decl => Curr,
Assume_Elab_Body => Assume_Elab_Body,
Skip_Memoization => Skip_Memoization);
raise ECR_Found;
-- Otherwise current construct is preelaborable. Unpdate the
-- early call region to include it.
else
Include (Curr, Curr);
end if;
-- Otherwise the current construct is missing, indicating that the
-- current list has been exhausted. Depending on the context of
-- the list, several transitions are possible.
else
-- The invariant of the algorithm ensures that Curr and Start
-- are at the same level of nesting at the point of transition.
-- The algorithm can determine which list the traversal came
-- from by examining Start.
Context := Parent (Start);
-- Attempt the following transitions:
--
-- private declarations -> visible declarations
-- private declarations -> upper level
-- private declarations -> terminate
-- visible declarations -> upper level
-- visible declarations -> terminate
if Nkind (Context) in N_Package_Specification
| N_Protected_Definition
| N_Task_Definition
then
Transition_Spec_Declarations (Context, Curr);
-- Attempt the following transitions:
--
-- statements -> declarations
-- statements -> upper level
-- statements -> corresponding package spec (Elab_Body)
-- statements -> terminate
elsif Nkind (Context) = N_Handled_Sequence_Of_Statements then
Transition_Handled_Statements (Context, Curr);
-- Attempt the following transitions:
--
-- declarations -> upper level
-- declarations -> corresponding package spec (Elab_Body)
-- declarations -> terminate
elsif Nkind (Context) in N_Block_Statement
| N_Entry_Body
| N_Package_Body
| N_Protected_Body
| N_Subprogram_Body
| N_Task_Body
then
Transition_Body_Declarations (Context, Curr);
-- Otherwise it is not possible to transition. Stop the search
-- because there are no more declarations or statements to
-- check.
else
raise ECR_Found;
end if;
end if;
end Advance;
--------------------------
-- Enter_Handled_Body --
--------------------------
procedure Enter_Handled_Body (Curr : in out Node_Id) is
Decls : constant List_Id := Declarations (Curr);
HSS : constant Node_Id := Handled_Statement_Sequence (Curr);
Stmts : List_Id := No_List;
begin
if Present (HSS) then
Stmts := Statements (HSS);
end if;
-- The handled body has a non-empty statement sequence. The
-- construct to inspect is the last statement.
if Has_Suitable_Construct (Stmts) then
Curr := Last (Stmts);
-- The handled body lacks statements, but has non-empty
-- declarations. The construct to inspect is the last declaration.
elsif Has_Suitable_Construct (Decls) then
Curr := Last (Decls);
-- Otherwise the handled body lacks both declarations and
-- statements. The construct to inspect is the node which precedes
-- the handled body. Update the early call region to include the
-- handled body.
else
Include (Curr, Curr);
end if;
end Enter_Handled_Body;
-------------------------------
-- Enter_Package_Declaration --
-------------------------------
procedure Enter_Package_Declaration (Curr : in out Node_Id) is
Pack_Spec : constant Node_Id := Specification (Curr);
Prv_Decls : constant List_Id := Private_Declarations (Pack_Spec);
Vis_Decls : constant List_Id := Visible_Declarations (Pack_Spec);
begin
-- The package has a non-empty private declarations. The construct
-- to inspect is the last private declaration.
if Has_Suitable_Construct (Prv_Decls) then
Curr := Last (Prv_Decls);
-- The package lacks private declarations, but has non-empty
-- visible declarations. In this case the construct to inspect
-- is the last visible declaration.
elsif Has_Suitable_Construct (Vis_Decls) then
Curr := Last (Vis_Decls);
-- Otherwise the package lacks any declarations. The construct
-- to inspect is the node which precedes the package. Update the
-- early call region to include the package declaration.
else
Include (Curr, Curr);
end if;
end Enter_Package_Declaration;
--------------
-- Find_ECR --
--------------
function Find_ECR (N : Node_Id) return Node_Id is
Curr : Node_Id;
begin
-- The early call region starts at N
Curr := Prev (N);
Start := N;
-- Inspect each node in reverse declarative order while going in
-- and out of nested and enclosing constructs. Note that the only
-- way to terminate this infinite loop is to raise ECR_Found.
loop
-- The current construct is not preelaboration-safe. Terminate
-- the traversal.
if Present (Curr)
and then not Is_OK_Preelaborable_Construct (Curr)
then
raise ECR_Found;
end if;
-- Advance to the next suitable construct. This may terminate
-- the traversal by raising ECR_Found.
Advance (Curr);
end loop;
exception
when ECR_Found =>
return Start;
end Find_ECR;
----------------------------
-- Has_Suitable_Construct --
----------------------------
function Has_Suitable_Construct (List : List_Id) return Boolean is
Item : Node_Id;
begin
-- Examine the list in reverse declarative order, looking for a
-- suitable construct.
if Present (List) then
Item := Last (List);
while Present (Item) loop
if Is_Suitable_Construct (Item) then
return True;
end if;
Prev (Item);
end loop;
end if;
return False;
end Has_Suitable_Construct;
-------------
-- Include --
-------------
procedure Include (N : Node_Id; Curr : out Node_Id) is
begin
Start := N;
-- The input node is a compilation unit. This terminates the
-- search because there are no more lists to inspect and there are
-- no more enclosing constructs to climb up to. The transitions
-- are:
--
-- private declarations -> terminate
-- visible declarations -> terminate
-- statements -> terminate
-- declarations -> terminate
if Nkind (Parent (Start)) = N_Compilation_Unit then
raise ECR_Found;
-- Otherwise the input node is still within some list
else
Curr := Prev (Start);
end if;
end Include;
-----------------------------------
-- Is_OK_Preelaborable_Construct --
-----------------------------------
function Is_OK_Preelaborable_Construct (N : Node_Id) return Boolean is
begin
-- Assignment statements are acceptable as long as they were
-- produced by the ABE mechanism to update elaboration flags.
if Nkind (N) = N_Assignment_Statement then
return Is_Elaboration_Code (N);
-- Block statements are acceptable even though they directly
-- violate preelaborability. The intention is not to penalize
-- the early call region when a block contains only preelaborable
-- constructs.
--
-- declare
-- Val : constant Integer := 1;
-- begin
-- pragma Assert (Val = 1);
-- null;
-- end;
--
-- Note that the Advancement phase does enter blocks, and will
-- detect any non-preelaborable declarations or statements within.
elsif Nkind (N) = N_Block_Statement then
return True;
end if;
-- Otherwise the construct must be preelaborable. The check must
-- take the syntactic and semantic structure of the construct. DO
-- NOT use Is_Preelaborable_Construct here.
return not Is_Non_Preelaborable_Construct (N);
end Is_OK_Preelaborable_Construct;
---------------------------
-- Is_Suitable_Construct --
---------------------------
function Is_Suitable_Construct (N : Node_Id) return Boolean is
Context : constant Node_Id := Parent (N);
begin
-- An internally-generated statement sequence which contains only
-- a single null statement is not a suitable construct because it
-- is a byproduct of the parser. Such a null statement should be
-- excluded from the early call region because it carries the
-- source location of the "end" keyword, and may lead to confusing
-- diagnistics.
if Nkind (N) = N_Null_Statement
and then not Comes_From_Source (N)
and then Present (Context)
and then Nkind (Context) = N_Handled_Sequence_Of_Statements
then
return False;
end if;
-- Otherwise only constructs which correspond to pure Ada
-- constructs are considered suitable.
case Nkind (N) is
when N_Call_Marker
| N_Freeze_Entity
| N_Freeze_Generic_Entity
| N_Implicit_Label_Declaration
| N_Itype_Reference
| N_Pop_Constraint_Error_Label
| N_Pop_Program_Error_Label
| N_Pop_Storage_Error_Label
| N_Push_Constraint_Error_Label
| N_Push_Program_Error_Label
| N_Push_Storage_Error_Label
| N_SCIL_Dispatch_Table_Tag_Init
| N_SCIL_Dispatching_Call
| N_SCIL_Membership_Test
| N_Variable_Reference_Marker
=>
return False;
when others =>
return True;
end case;
end Is_Suitable_Construct;
----------------------------------
-- Transition_Body_Declarations --
----------------------------------
procedure Transition_Body_Declarations
(Bod : Node_Id;
Curr : out Node_Id)
is
Decls : constant List_Id := Declarations (Bod);
begin
-- The search must come from the declarations of the body
pragma Assert
(Is_Non_Empty_List (Decls)
and then List_Containing (Start) = Decls);
-- The search finished inspecting the declarations. The construct
-- to inspect is the node which precedes the handled body, unless
-- the body is a compilation unit. The transitions are:
--
-- declarations -> upper level
-- declarations -> corresponding package spec (Elab_Body)
-- declarations -> terminate
Transition_Unit (Bod, Curr);
end Transition_Body_Declarations;
-----------------------------------
-- Transition_Handled_Statements --
-----------------------------------
procedure Transition_Handled_Statements
(HSS : Node_Id;
Curr : out Node_Id)
is
Bod : constant Node_Id := Parent (HSS);
Decls : constant List_Id := Declarations (Bod);
Stmts : constant List_Id := Statements (HSS);
begin
-- The search must come from the statements of certain bodies or
-- statements.
pragma Assert
(Nkind (Bod) in
N_Block_Statement |
N_Entry_Body |
N_Package_Body |
N_Protected_Body |
N_Subprogram_Body |
N_Task_Body);
-- The search must come from the statements of the handled
-- sequence.
pragma Assert
(Is_Non_Empty_List (Stmts)
and then List_Containing (Start) = Stmts);
-- The search finished inspecting the statements. The handled body
-- has non-empty declarations. The construct to inspect is the
-- last declaration. The transitions are:
--
-- statements -> declarations
if Has_Suitable_Construct (Decls) then
Curr := Last (Decls);
-- Otherwise the handled body lacks declarations. The construct to
-- inspect is the node which precedes the handled body, unless the
-- body is a compilation unit. The transitions are:
--
-- statements -> upper level
-- statements -> corresponding package spec (Elab_Body)
-- statements -> terminate
else
Transition_Unit (Bod, Curr);
end if;
end Transition_Handled_Statements;
----------------------------------
-- Transition_Spec_Declarations --
----------------------------------
procedure Transition_Spec_Declarations
(Spec : Node_Id;
Curr : out Node_Id)
is
Prv_Decls : constant List_Id := Private_Declarations (Spec);
Vis_Decls : constant List_Id := Visible_Declarations (Spec);
begin
pragma Assert (Present (Start) and then Is_List_Member (Start));
-- The search came from the private declarations and finished
-- their inspection.
if Has_Suitable_Construct (Prv_Decls)
and then List_Containing (Start) = Prv_Decls
then
-- The context has non-empty visible declarations. The node to
-- inspect is the last visible declaration. The transitions
-- are:
--
-- private declarations -> visible declarations
if Has_Suitable_Construct (Vis_Decls) then
Curr := Last (Vis_Decls);
-- Otherwise the context lacks visible declarations. The
-- construct to inspect is the node which precedes the context
-- unless the context is a compilation unit. The transitions
-- are:
--
-- private declarations -> upper level
-- private declarations -> terminate
else
Transition_Unit (Parent (Spec), Curr);
end if;
-- The search came from the visible declarations and finished
-- their inspections. The construct to inspect is the node which
-- precedes the context, unless the context is a compilaton unit.
-- The transitions are:
--
-- visible declarations -> upper level
-- visible declarations -> terminate
elsif Has_Suitable_Construct (Vis_Decls)
and then List_Containing (Start) = Vis_Decls
then
Transition_Unit (Parent (Spec), Curr);
-- At this point both declarative lists are empty, but the
-- traversal still came from within the spec. This indicates
-- that the invariant of the algorithm has been violated.
else
pragma Assert (False);
raise ECR_Found;
end if;
end Transition_Spec_Declarations;
---------------------
-- Transition_Unit --
---------------------
procedure Transition_Unit
(Unit : Node_Id;
Curr : out Node_Id)
is
Context : constant Node_Id := Parent (Unit);
begin
-- The unit is a compilation unit. This terminates the search
-- because there are no more lists to inspect and there are no
-- more enclosing constructs to climb up to.
if Nkind (Context) = N_Compilation_Unit then
-- A package body with a corresponding spec subject to pragma
-- Elaborate_Body is an exception to the above. The annotation
-- allows the search to continue into the package declaration.
-- The transitions are:
--
-- statements -> corresponding package spec (Elab_Body)
-- declarations -> corresponding package spec (Elab_Body)
if Nkind (Unit) = N_Package_Body
and then (Assume_Elab_Body
or else Has_Pragma_Elaborate_Body
(Corresponding_Spec (Unit)))
then
Curr := Unit_Declaration_Node (Corresponding_Spec (Unit));
Enter_Package_Declaration (Curr);
-- Otherwise terminate the search. The transitions are:
--
-- private declarations -> terminate
-- visible declarations -> terminate
-- statements -> terminate
-- declarations -> terminate
else
raise ECR_Found;
end if;
-- The unit is a subunit. The construct to inspect is the node
-- which precedes the corresponding stub. Update the early call
-- region to include the unit.
elsif Nkind (Context) = N_Subunit then
Start := Unit;
Curr := Corresponding_Stub (Context);
-- Otherwise the unit is nested. The construct to inspect is the
-- node which precedes the unit. Update the early call region to
-- include the unit.
else
Include (Unit, Curr);
end if;
end Transition_Unit;
-- Local variables
Body_Id : constant Entity_Id := Unique_Defining_Entity (Body_Decl);
Region : Node_Id;
-- Start of processing for Find_Early_Call_Region
begin
-- The caller demands the start of the early call region without
-- saving or retrieving it to/from internal data structures.
if Skip_Memoization then
Region := Find_ECR (Body_Decl);
-- Default behavior
else
-- Check whether the early call region of the subprogram body is
-- available.
Region := Early_Call_Region (Body_Id);
if No (Region) then
Region := Find_ECR (Body_Decl);
-- Associate the early call region with the subprogram body in
-- case other scenarios need it.
Set_Early_Call_Region (Body_Id, Region);
end if;
end if;
-- A subprogram body must always have an early call region
pragma Assert (Present (Region));
return Region;
end Find_Early_Call_Region;
--------------------------------------------
-- Initialize_Early_Call_Region_Processor --
--------------------------------------------
procedure Initialize_Early_Call_Region_Processor is
begin
Early_Call_Regions_Map := ECR_Map.Create (100);
end Initialize_Early_Call_Region_Processor;
---------------------------
-- Set_Early_Call_Region --
---------------------------
procedure Set_Early_Call_Region (Body_Id : Entity_Id; Start : Node_Id) is
pragma Assert (Present (Body_Id));
pragma Assert (Present (Start));
begin
ECR_Map.Put (Early_Call_Regions_Map, Body_Id, Start);
end Set_Early_Call_Region;
end Early_Call_Region_Processor;
----------------------
-- Elaborated_Units --
----------------------
package body Elaborated_Units is
-----------
-- Types --
-----------
-- The following type idenfities the elaboration attributes of a unit
type Elaboration_Attributes_Id is new Natural;
No_Elaboration_Attributes : constant Elaboration_Attributes_Id :=
Elaboration_Attributes_Id'First;
First_Elaboration_Attributes : constant Elaboration_Attributes_Id :=
No_Elaboration_Attributes + 1;
-- The following type represents the elaboration attributes of a unit
type Elaboration_Attributes_Record is record
Elab_Pragma : Node_Id := Empty;
-- This attribute denotes a source Elaborate or Elaborate_All pragma
-- which guarantees the prior elaboration of some unit with respect
-- to the main unit. The pragma may come from the following contexts:
--
-- * The main unit
-- * The spec of the main unit (if applicable)
-- * Any parent spec of the main unit (if applicable)
-- * Any parent subunit of the main unit (if applicable)
--
-- The attribute remains Empty if no such pragma is available. Source
-- pragmas play a role in satisfying SPARK elaboration requirements.
With_Clause : Node_Id := Empty;
-- This attribute denotes an internally-generated or a source with
-- clause for some unit withed by the main unit. With clauses carry
-- flags which represent implicit Elaborate or Elaborate_All pragmas.
-- These clauses play a role in supplying elaboration dependencies to
-- binde.
end record;
---------------------
-- Data structures --
---------------------
-- The following table stores all elaboration attributes
package Elaboration_Attributes is new Table.Table
(Table_Index_Type => Elaboration_Attributes_Id,
Table_Component_Type => Elaboration_Attributes_Record,
Table_Low_Bound => First_Elaboration_Attributes,
Table_Initial => 250,
Table_Increment => 200,
Table_Name => "Elaboration_Attributes");
procedure Destroy (EA_Id : in out Elaboration_Attributes_Id);
-- Destroy elaboration attributes EA_Id
package UA_Map is new Dynamic_Hash_Tables
(Key_Type => Entity_Id,
Value_Type => Elaboration_Attributes_Id,
No_Value => No_Elaboration_Attributes,
Expansion_Threshold => 1.5,
Expansion_Factor => 2,
Compression_Threshold => 0.3,
Compression_Factor => 2,
"=" => "=",
Destroy_Value => Destroy,
Hash => Hash);
-- The following map relates an elaboration attributes of a unit to the
-- unit.
Unit_To_Attributes_Map : UA_Map.Dynamic_Hash_Table := UA_Map.Nil;
------------------
-- Constructors --
------------------
function Elaboration_Attributes_Of
(Unit_Id : Entity_Id) return Elaboration_Attributes_Id;
pragma Inline (Elaboration_Attributes_Of);
-- Obtain the elaboration attributes of unit Unit_Id
-----------------------
-- Local subprograms --
-----------------------
function Elab_Pragma (EA_Id : Elaboration_Attributes_Id) return Node_Id;
pragma Inline (Elab_Pragma);
-- Obtain the Elaborate[_All] pragma of elaboration attributes EA_Id
procedure Ensure_Prior_Elaboration_Dynamic
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State);
pragma Inline (Ensure_Prior_Elaboration_Dynamic);
-- Guarantee the elaboration of unit Unit_Id with respect to the main
-- unit by suggesting the use of Elaborate[_All] with name Prag_Nam. N
-- denotes the related scenario. In_State is the current state of the
-- Processing phase.
procedure Ensure_Prior_Elaboration_Static
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State);
pragma Inline (Ensure_Prior_Elaboration_Static);
-- Guarantee the elaboration of unit Unit_Id with respect to the main
-- unit by installing an implicit Elaborate[_All] pragma with name
-- Prag_Nam. N denotes the related scenario. In_State is the current
-- state of the Processing phase.
function Present (EA_Id : Elaboration_Attributes_Id) return Boolean;
pragma Inline (Present);
-- Determine whether elaboration attributes UA_Id exist
procedure Set_Elab_Pragma
(EA_Id : Elaboration_Attributes_Id;
Prag : Node_Id);
pragma Inline (Set_Elab_Pragma);
-- Set the Elaborate[_All] pragma of elaboration attributes EA_Id to
-- Prag.
procedure Set_With_Clause
(EA_Id : Elaboration_Attributes_Id;
Clause : Node_Id);
pragma Inline (Set_With_Clause);
-- Set the with clause of elaboration attributes EA_Id to Clause
function With_Clause (EA_Id : Elaboration_Attributes_Id) return Node_Id;
pragma Inline (With_Clause);
-- Obtain the implicit or source with clause of elaboration attributes
-- EA_Id.
------------------------------
-- Collect_Elaborated_Units --
------------------------------
procedure Collect_Elaborated_Units is
procedure Add_Pragma (Prag : Node_Id);
pragma Inline (Add_Pragma);
-- Determine whether pragma Prag denotes a legal Elaborate[_All]
-- pragma. If this is the case, add the related unit to the context.
-- For pragma Elaborate_All, include recursively all units withed by
-- the related unit.
procedure Add_Unit
(Unit_Id : Entity_Id;
Prag : Node_Id;
Full_Context : Boolean);
pragma Inline (Add_Unit);
-- Add unit Unit_Id to the elaboration context. Prag denotes the
-- pragma which prompted the inclusion of the unit to the context.
-- If flag Full_Context is set, examine the nonlimited clauses of
-- unit Unit_Id and add each withed unit to the context.
procedure Find_Elaboration_Context (Comp_Unit : Node_Id);
pragma Inline (Find_Elaboration_Context);
-- Examine the context items of compilation unit Comp_Unit for
-- suitable elaboration-related pragmas and add all related units
-- to the context.
----------------
-- Add_Pragma --
----------------
procedure Add_Pragma (Prag : Node_Id) is
Prag_Args : constant List_Id :=
Pragma_Argument_Associations (Prag);
Prag_Nam : constant Name_Id := Pragma_Name (Prag);
Unit_Arg : Node_Id;
begin
-- Nothing to do if the pragma is not related to elaboration
if Prag_Nam not in Name_Elaborate | Name_Elaborate_All then
return;
-- Nothing to do when the pragma is illegal
elsif Error_Posted (Prag) then
return;
end if;
Unit_Arg := Get_Pragma_Arg (First (Prag_Args));
-- The argument of the pragma may appear in package.package form
if Nkind (Unit_Arg) = N_Selected_Component then
Unit_Arg := Selector_Name (Unit_Arg);
end if;
Add_Unit
(Unit_Id => Entity (Unit_Arg),
Prag => Prag,
Full_Context => Prag_Nam = Name_Elaborate_All);
end Add_Pragma;
--------------
-- Add_Unit --
--------------
procedure Add_Unit
(Unit_Id : Entity_Id;
Prag : Node_Id;
Full_Context : Boolean)
is
Clause : Node_Id;
EA_Id : Elaboration_Attributes_Id;
Unit_Prag : Node_Id;
begin
-- Nothing to do when some previous error left a with clause or a
-- pragma in a bad state.
if No (Unit_Id) then
return;
end if;
EA_Id := Elaboration_Attributes_Of (Unit_Id);
Unit_Prag := Elab_Pragma (EA_Id);
-- The unit is already included in the context by means of pragma
-- Elaborate[_All].
if Present (Unit_Prag) then
-- Upgrade an existing pragma Elaborate when the unit is
-- subject to Elaborate_All because the new pragma covers a
-- larger set of units.
if Pragma_Name (Unit_Prag) = Name_Elaborate
and then Pragma_Name (Prag) = Name_Elaborate_All
then
Set_Elab_Pragma (EA_Id, Prag);
-- Otherwise the unit retains its existing pragma and does not
-- need to be included in the context again.
else
return;
end if;
-- Otherwise the current unit is not included in the context
else
Set_Elab_Pragma (EA_Id, Prag);
end if;
-- Includes all units withed by the current one when computing the
-- full context.
if Full_Context then
-- Process all nonlimited with clauses found in the context of
-- the current unit. Note that limited clauses do not impose an
-- elaboration order.
Clause := First (Context_Items (Compilation_Unit (Unit_Id)));
while Present (Clause) loop
if Nkind (Clause) = N_With_Clause
and then not Error_Posted (Clause)
and then not Limited_Present (Clause)
then
Add_Unit
(Unit_Id => Entity (Name (Clause)),
Prag => Prag,
Full_Context => Full_Context);
end if;
Next (Clause);
end loop;
end if;
end Add_Unit;
------------------------------
-- Find_Elaboration_Context --
------------------------------
procedure Find_Elaboration_Context (Comp_Unit : Node_Id) is
pragma Assert (Nkind (Comp_Unit) = N_Compilation_Unit);
Prag : Node_Id;
begin
-- Process all elaboration-related pragmas found in the context of
-- the compilation unit.
Prag := First (Context_Items (Comp_Unit));
while Present (Prag) loop
if Nkind (Prag) = N_Pragma then
Add_Pragma (Prag);
end if;
Next (Prag);
end loop;
end Find_Elaboration_Context;
-- Local variables
Par_Id : Entity_Id;
Unit_Id : Node_Id;
-- Start of processing for Collect_Elaborated_Units
begin
-- Perform a traversal to examines the context of the main unit. The
-- traversal performs the following jumps:
--
-- subunit -> parent subunit
-- parent subunit -> body
-- body -> spec
-- spec -> parent spec
-- parent spec -> grandparent spec and so on
--
-- The traversal relies on units rather than scopes because the scope
-- of a subunit is some spec, while this traversal must process the
-- body as well. Given that protected and task bodies can also be
-- subunits, this complicates the scope approach even further.
Unit_Id := Unit (Cunit (Main_Unit));
-- Perform the following traversals when the main unit is a subunit
--
-- subunit -> parent subunit
-- parent subunit -> body
while Present (Unit_Id) and then Nkind (Unit_Id) = N_Subunit loop
Find_Elaboration_Context (Parent (Unit_Id));
-- Continue the traversal by going to the unit which contains the
-- corresponding stub.
if Present (Corresponding_Stub (Unit_Id)) then
Unit_Id :=
Unit (Cunit (Get_Source_Unit (Corresponding_Stub (Unit_Id))));
-- Otherwise the subunit may be erroneous or left in a bad state
else
exit;
end if;
end loop;
-- Perform the following traversal now that subunits have been taken
-- care of, or the main unit is a body.
--
-- body -> spec
if Present (Unit_Id)
and then Nkind (Unit_Id) in N_Package_Body | N_Subprogram_Body
then
Find_Elaboration_Context (Parent (Unit_Id));
-- Continue the traversal by going to the unit which contains the
-- corresponding spec.
if Present (Corresponding_Spec (Unit_Id)) then
Unit_Id :=
Unit (Cunit (Get_Source_Unit (Corresponding_Spec (Unit_Id))));
end if;
end if;
-- Perform the following traversals now that the body has been taken
-- care of, or the main unit is a spec.
--
-- spec -> parent spec
-- parent spec -> grandparent spec and so on
if Present (Unit_Id)
and then Nkind (Unit_Id) in N_Generic_Package_Declaration
| N_Generic_Subprogram_Declaration
| N_Package_Declaration
| N_Subprogram_Declaration
then
Find_Elaboration_Context (Parent (Unit_Id));
-- Process a potential chain of parent units which ends with the
-- main unit spec. The traversal can now safely rely on the scope
-- chain.
Par_Id := Scope (Defining_Entity (Unit_Id));
while Present (Par_Id) and then Par_Id /= Standard_Standard loop
Find_Elaboration_Context (Compilation_Unit (Par_Id));
Par_Id := Scope (Par_Id);
end loop;
end if;
end Collect_Elaborated_Units;
-------------
-- Destroy --
-------------
procedure Destroy (EA_Id : in out Elaboration_Attributes_Id) is
pragma Unreferenced (EA_Id);
begin
null;
end Destroy;
-----------------
-- Elab_Pragma --
-----------------
function Elab_Pragma
(EA_Id : Elaboration_Attributes_Id) return Node_Id
is
pragma Assert (Present (EA_Id));
begin
return Elaboration_Attributes.Table (EA_Id).Elab_Pragma;
end Elab_Pragma;
-------------------------------
-- Elaboration_Attributes_Of --
-------------------------------
function Elaboration_Attributes_Of
(Unit_Id : Entity_Id) return Elaboration_Attributes_Id
is
EA_Id : Elaboration_Attributes_Id;
begin
EA_Id := UA_Map.Get (Unit_To_Attributes_Map, Unit_Id);
-- The unit lacks elaboration attributes. This indicates that the
-- unit is encountered for the first time. Create the elaboration
-- attributes for it.
if not Present (EA_Id) then
Elaboration_Attributes.Append
((Elab_Pragma => Empty,
With_Clause => Empty));
EA_Id := Elaboration_Attributes.Last;
-- Associate the elaboration attributes with the unit
UA_Map.Put (Unit_To_Attributes_Map, Unit_Id, EA_Id);
end if;
pragma Assert (Present (EA_Id));
return EA_Id;
end Elaboration_Attributes_Of;
------------------------------
-- Ensure_Prior_Elaboration --
------------------------------
procedure Ensure_Prior_Elaboration
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State)
is
pragma Assert (Prag_Nam in Name_Elaborate | Name_Elaborate_All);
begin
-- Nothing to do when the need for prior elaboration came from a
-- partial finalization routine which occurs in an initialization
-- context. This behavior parallels that of the old ABE mechanism.
if In_State.Within_Partial_Finalization then
return;
-- Nothing to do when the need for prior elaboration came from a task
-- body and switch -gnatd.y (disable implicit pragma Elaborate_All on
-- task bodies) is in effect.
elsif Debug_Flag_Dot_Y and then In_State.Within_Task_Body then
return;
-- Nothing to do when the unit is elaborated prior to the main unit.
-- This check must also consider the following cases:
--
-- * No check is made against the context of the main unit because
-- this is specific to the elaboration model in effect and requires
-- custom handling (see Ensure_xxx_Prior_Elaboration).
--
-- * Unit_Id is subject to pragma Elaborate_Body. An implicit pragma
-- Elaborate[_All] MUST be generated even though Unit_Id is always
-- elaborated prior to the main unit. This conservative strategy
-- ensures that other units withed by Unit_Id will not lead to an
-- ABE.
--
-- package A is package body A is
-- procedure ABE; procedure ABE is ... end ABE;
-- end A; end A;
--
-- with A;
-- package B is package body B is
-- pragma Elaborate_Body; procedure Proc is
-- begin
-- procedure Proc; A.ABE;
-- package B; end Proc;
-- end B;
--
-- with B;
-- package C is package body C is
-- ... ...
-- end C; begin
-- B.Proc;
-- end C;
--
-- In the example above, the elaboration of C invokes B.Proc. B is
-- subject to pragma Elaborate_Body. If no pragma Elaborate[_All]
-- is gnerated for B in C, then the following elaboratio order will
-- lead to an ABE:
--
-- spec of A elaborated
-- spec of B elaborated
-- body of B elaborated
-- spec of C elaborated
-- body of C elaborated <-- calls B.Proc which calls A.ABE
-- body of A elaborated <-- problem
--
-- The generation of an implicit pragma Elaborate_All (B) ensures
-- that the elaboration-order mechanism will not pick the above
-- order.
--
-- An implicit Elaborate is NOT generated when the unit is subject
-- to Elaborate_Body because both pragmas have the same effect.
--
-- * Unit_Id is the main unit. An implicit pragma Elaborate[_All]
-- MUST NOT be generated in this case because a unit cannot depend
-- on its own elaboration. This case is therefore treated as valid
-- prior elaboration.
elsif Has_Prior_Elaboration
(Unit_Id => Unit_Id,
Same_Unit_OK => True,
Elab_Body_OK => Prag_Nam = Name_Elaborate)
then
return;
end if;
-- Suggest the use of pragma Prag_Nam when the dynamic model is in
-- effect.
if Dynamic_Elaboration_Checks then
Ensure_Prior_Elaboration_Dynamic
(N => N,
Unit_Id => Unit_Id,
Prag_Nam => Prag_Nam,
In_State => In_State);
-- Install an implicit pragma Prag_Nam when the static model is in
-- effect.
else
pragma Assert (Static_Elaboration_Checks);
Ensure_Prior_Elaboration_Static
(N => N,
Unit_Id => Unit_Id,
Prag_Nam => Prag_Nam,
In_State => In_State);
end if;
end Ensure_Prior_Elaboration;
--------------------------------------
-- Ensure_Prior_Elaboration_Dynamic --
--------------------------------------
procedure Ensure_Prior_Elaboration_Dynamic
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State)
is
procedure Info_Missing_Pragma;
pragma Inline (Info_Missing_Pragma);
-- Output information concerning missing Elaborate or Elaborate_All
-- pragma with name Prag_Nam for scenario N, which would ensure the
-- prior elaboration of Unit_Id.
-------------------------
-- Info_Missing_Pragma --
-------------------------
procedure Info_Missing_Pragma is
begin
-- Internal units are ignored as they cause unnecessary noise
if not In_Internal_Unit (Unit_Id) then
-- The name of the unit subjected to the elaboration pragma is
-- fully qualified to improve the clarity of the info message.
Error_Msg_Name_1 := Prag_Nam;
Error_Msg_Qual_Level := Nat'Last;
Error_Msg_NE ("info: missing pragma % for unit &", N, Unit_Id);
Error_Msg_Qual_Level := 0;
end if;
end Info_Missing_Pragma;
-- Local variables
EA_Id : constant Elaboration_Attributes_Id :=
Elaboration_Attributes_Of (Unit_Id);
N_Lvl : Enclosing_Level_Kind;
N_Rep : Scenario_Rep_Id;
-- Start of processing for Ensure_Prior_Elaboration_Dynamic
begin
-- Nothing to do when the unit is guaranteed prior elaboration by
-- means of a source Elaborate[_All] pragma.
if Present (Elab_Pragma (EA_Id)) then
return;
end if;
-- Output extra information on a missing Elaborate[_All] pragma when
-- switch -gnatel (info messages on implicit Elaborate[_All] pragmas
-- is in effect.
if Elab_Info_Messages
and then not In_State.Suppress_Info_Messages
then
N_Rep := Scenario_Representation_Of (N, In_State);
N_Lvl := Level (N_Rep);
-- Declaration-level scenario
if (Is_Suitable_Call (N) or else Is_Suitable_Instantiation (N))
and then N_Lvl = Declaration_Level
then
null;
-- Library-level scenario
elsif N_Lvl in Library_Level then
null;
-- Instantiation library-level scenario
elsif N_Lvl = Instantiation_Level then
null;
-- Otherwise the scenario does not appear at the proper level
else
return;
end if;
Info_Missing_Pragma;
end if;
end Ensure_Prior_Elaboration_Dynamic;
-------------------------------------
-- Ensure_Prior_Elaboration_Static --
-------------------------------------
procedure Ensure_Prior_Elaboration_Static
(N : Node_Id;
Unit_Id : Entity_Id;
Prag_Nam : Name_Id;
In_State : Processing_In_State)
is
function Find_With_Clause
(Items : List_Id;
Withed_Id : Entity_Id) return Node_Id;
pragma Inline (Find_With_Clause);
-- Find a nonlimited with clause in the list of context items Items
-- that withs unit Withed_Id. Return Empty if no such clause exists.
procedure Info_Implicit_Pragma;
pragma Inline (Info_Implicit_Pragma);
-- Output information concerning an implicitly generated Elaborate
-- or Elaborate_All pragma with name Prag_Nam for scenario N which
-- ensures the prior elaboration of unit Unit_Id.
----------------------
-- Find_With_Clause --
----------------------
function Find_With_Clause
(Items : List_Id;
Withed_Id : Entity_Id) return Node_Id
is
Item : Node_Id;
begin
-- Examine the context clauses looking for a suitable with. Note
-- that limited clauses do not affect the elaboration order.
Item := First (Items);
while Present (Item) loop
if Nkind (Item) = N_With_Clause
and then not Error_Posted (Item)
and then not Limited_Present (Item)
and then Entity (Name (Item)) = Withed_Id
then
return Item;
end if;
Next (Item);
end loop;
return Empty;
end Find_With_Clause;
--------------------------
-- Info_Implicit_Pragma --
--------------------------
procedure Info_Implicit_Pragma is
begin
-- Internal units are ignored as they cause unnecessary noise
if not In_Internal_Unit (Unit_Id) then
-- The name of the unit subjected to the elaboration pragma is
-- fully qualified to improve the clarity of the info message.
Error_Msg_Name_1 := Prag_Nam;
Error_Msg_Qual_Level := Nat'Last;
Error_Msg_NE
("info: implicit pragma % generated for unit &", N, Unit_Id);
Error_Msg_Qual_Level := 0;
Output_Active_Scenarios (N, In_State);
end if;
end Info_Implicit_Pragma;
-- Local variables
EA_Id : constant Elaboration_Attributes_Id :=
Elaboration_Attributes_Of (Unit_Id);
Main_Cunit : constant Node_Id := Cunit (Main_Unit);
Loc : constant Source_Ptr := Sloc (Main_Cunit);
Unit_Cunit : constant Node_Id := Compilation_Unit (Unit_Id);
Unit_Prag : constant Node_Id := Elab_Pragma (EA_Id);
Unit_With : constant Node_Id := With_Clause (EA_Id);
Clause : Node_Id;
Items : List_Id;
-- Start of processing for Ensure_Prior_Elaboration_Static
begin
-- Nothing to do when the caller has suppressed the generation of
-- implicit Elaborate[_All] pragmas.
if In_State.Suppress_Implicit_Pragmas then
return;
-- Nothing to do when the unit is guaranteed prior elaboration by
-- means of a source Elaborate[_All] pragma.
elsif Present (Unit_Prag) then
return;
-- Nothing to do when the unit has an existing implicit Elaborate or
-- Elaborate_All pragma installed by a previous scenario.
elsif Present (Unit_With) then
-- The unit is already guaranteed prior elaboration by means of an
-- implicit Elaborate pragma, however the current scenario imposes
-- a stronger requirement of Elaborate_All. "Upgrade" the existing
-- pragma to match this new requirement.
if Elaborate_Desirable (Unit_With)
and then Prag_Nam = Name_Elaborate_All
then
Set_Elaborate_All_Desirable (Unit_With);
Set_Elaborate_Desirable (Unit_With, False);
end if;
return;
end if;
-- At this point it is known that the unit has no prior elaboration
-- according to pragmas and hierarchical relationships.
Items := Context_Items (Main_Cunit);
if No (Items) then
Items := New_List;
Set_Context_Items (Main_Cunit, Items);
end if;
-- Locate the with clause for the unit. Note that there may not be a
-- clause if the unit is visible through a subunit-body, body-spec,
-- or spec-parent relationship.
Clause :=
Find_With_Clause
(Items => Items,
Withed_Id => Unit_Id);
-- Generate:
-- with Id;
-- Note that adding implicit with clauses is safe because analysis,
-- resolution, and expansion have already taken place and it is not
-- possible to interfere with visibility.
if No (Clause) then
Clause :=
Make_With_Clause (Loc,
Name => New_Occurrence_Of (Unit_Id, Loc));
Set_Implicit_With (Clause);
Set_Library_Unit (Clause, Unit_Cunit);
Append_To (Items, Clause);
end if;
-- Mark the with clause depending on the pragma required
if Prag_Nam = Name_Elaborate then
Set_Elaborate_Desirable (Clause);
else
Set_Elaborate_All_Desirable (Clause);
end if;
-- The implicit Elaborate[_All] ensures the prior elaboration of
-- the unit. Include the unit in the elaboration context of the
-- main unit.
Set_With_Clause (EA_Id, Clause);
-- Output extra information on an implicit Elaborate[_All] pragma
-- when switch -gnatel (info messages on implicit Elaborate[_All]
-- pragmas is in effect.
if Elab_Info_Messages then
Info_Implicit_Pragma;
end if;
end Ensure_Prior_Elaboration_Static;
-------------------------------
-- Finalize_Elaborated_Units --
-------------------------------
procedure Finalize_Elaborated_Units is
begin
UA_Map.Destroy (Unit_To_Attributes_Map);
end Finalize_Elaborated_Units;
---------------------------
-- Has_Prior_Elaboration --
---------------------------
function Has_Prior_Elaboration
(Unit_Id : Entity_Id;
Context_OK : Boolean := False;
Elab_Body_OK : Boolean := False;
Same_Unit_OK : Boolean := False) return Boolean
is
EA_Id : constant Elaboration_Attributes_Id :=
Elaboration_Attributes_Of (Unit_Id);
Main_Id : constant Entity_Id := Main_Unit_Entity;
Unit_Prag : constant Node_Id := Elab_Pragma (EA_Id);
Unit_With : constant Node_Id := With_Clause (EA_Id);
begin
-- A preelaborated unit is always elaborated prior to the main unit
if Is_Preelaborated_Unit (Unit_Id) then
return True;
-- An internal unit is always elaborated prior to a non-internal main
-- unit.
elsif In_Internal_Unit (Unit_Id)
and then not In_Internal_Unit (Main_Id)
then
return True;
-- A unit has prior elaboration if it appears within the context
-- of the main unit. Consider this case only when requested by the
-- caller.
elsif Context_OK
and then (Present (Unit_Prag) or else Present (Unit_With))
then
return True;
-- A unit whose body is elaborated together with its spec has prior
-- elaboration except with respect to itself. Consider this case only
-- when requested by the caller.
elsif Elab_Body_OK
and then Has_Pragma_Elaborate_Body (Unit_Id)
and then not Is_Same_Unit (Unit_Id, Main_Id)
then
return True;
-- A unit has no prior elaboration with respect to itself, but does
-- not require any means of ensuring its own elaboration either.
-- Treat this case as valid prior elaboration only when requested by
-- the caller.
elsif Same_Unit_OK and then Is_Same_Unit (Unit_Id, Main_Id) then
return True;
end if;
return False;
end Has_Prior_Elaboration;
---------------------------------
-- Initialize_Elaborated_Units --
---------------------------------
procedure Initialize_Elaborated_Units is
begin
Unit_To_Attributes_Map := UA_Map.Create (250);
end Initialize_Elaborated_Units;
----------------------------------
-- Meet_Elaboration_Requirement --
----------------------------------
procedure Meet_Elaboration_Requirement
(N : Node_Id;
Targ_Id : Entity_Id;
Req_Nam : Name_Id;
In_State : Processing_In_State)
is
pragma Assert (Req_Nam in Name_Elaborate | Name_Elaborate_All);
Main_Id : constant Entity_Id := Main_Unit_Entity;
Unit_Id : constant Entity_Id := Find_Top_Unit (Targ_Id);
procedure Elaboration_Requirement_Error;
pragma Inline (Elaboration_Requirement_Error);
-- Emit an error concerning scenario N which has failed to meet the
-- elaboration requirement.
function Find_Preelaboration_Pragma
(Prag_Nam : Name_Id) return Node_Id;
pragma Inline (Find_Preelaboration_Pragma);
-- Traverse the visible declarations of unit Unit_Id and locate a
-- source preelaboration-related pragma with name Prag_Nam.
procedure Info_Requirement_Met (Prag : Node_Id);
pragma Inline (Info_Requirement_Met);
-- Output information concerning pragma Prag which meets requirement
-- Req_Nam.
-----------------------------------
-- Elaboration_Requirement_Error --
-----------------------------------
procedure Elaboration_Requirement_Error is
begin
if Is_Suitable_Call (N) then
Info_Call
(Call => N,
Subp_Id => Targ_Id,
Info_Msg => False,
In_SPARK => True);
elsif Is_Suitable_Instantiation (N) then
Info_Instantiation
(Inst => N,
Gen_Id => Targ_Id,
Info_Msg => False,
In_SPARK => True);
elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
Error_Msg_N
("read of refinement constituents during elaboration in "
& "SPARK", N);
elsif Is_Suitable_Variable_Reference (N) then
Info_Variable_Reference
(Ref => N,
Var_Id => Targ_Id,
Info_Msg => False,
In_SPARK => True);
-- No other scenario may impose a requirement on the context of
-- the main unit.
else
pragma Assert (False);
return;
end if;
Error_Msg_Name_1 := Req_Nam;
Error_Msg_Node_2 := Unit_Id;
Error_Msg_NE ("\\unit & requires pragma % for &", N, Main_Id);
Output_Active_Scenarios (N, In_State);
end Elaboration_Requirement_Error;
--------------------------------
-- Find_Preelaboration_Pragma --
--------------------------------
function Find_Preelaboration_Pragma
(Prag_Nam : Name_Id) return Node_Id
is
Spec : constant Node_Id := Parent (Unit_Id);
Decl : Node_Id;
begin
-- A preelaboration-related pragma comes from source and appears
-- at the top of the visible declarations of a package.
if Nkind (Spec) = N_Package_Specification then
Decl := First (Visible_Declarations (Spec));
while Present (Decl) loop
if Comes_From_Source (Decl) then
if Nkind (Decl) = N_Pragma
and then Pragma_Name (Decl) = Prag_Nam
then
return Decl;
-- Otherwise the construct terminates the region where
-- the preelaboration-related pragma may appear.
else
exit;
end if;
end if;
Next (Decl);
end loop;
end if;
return Empty;
end Find_Preelaboration_Pragma;
--------------------------
-- Info_Requirement_Met --
--------------------------
procedure Info_Requirement_Met (Prag : Node_Id) is
pragma Assert (Present (Prag));
begin
Error_Msg_Name_1 := Req_Nam;
Error_Msg_Sloc := Sloc (Prag);
Error_Msg_NE
("\\% requirement for unit & met by pragma #", N, Unit_Id);
end Info_Requirement_Met;
-- Local variables
EA_Id : Elaboration_Attributes_Id;
Elab_Nam : Name_Id;
Req_Met : Boolean;
Unit_Prag : Node_Id;
-- Start of processing for Meet_Elaboration_Requirement
begin
-- Assume that the requirement has not been met
Req_Met := False;
-- If the target is within the main unit, either at the source level
-- or through an instantiation, then there is no real requirement to
-- meet because the main unit cannot force its own elaboration by
-- means of an Elaborate[_All] pragma. Treat this case as valid
-- coverage.
if In_Extended_Main_Code_Unit (Targ_Id) then
Req_Met := True;
-- Otherwise the target resides in an external unit
-- The requirement is met when the target comes from an internal unit
-- because such a unit is elaborated prior to a non-internal unit.
elsif In_Internal_Unit (Unit_Id)
and then not In_Internal_Unit (Main_Id)
then
Req_Met := True;
-- The requirement is met when the target comes from a preelaborated
-- unit. This portion must parallel predicate Is_Preelaborated_Unit.
elsif Is_Preelaborated_Unit (Unit_Id) then
Req_Met := True;
-- Output extra information when switch -gnatel (info messages on
-- implicit Elaborate[_All] pragmas.
if Elab_Info_Messages
and then not In_State.Suppress_Info_Messages
then
if Is_Preelaborated (Unit_Id) then
Elab_Nam := Name_Preelaborate;
elsif Is_Pure (Unit_Id) then
Elab_Nam := Name_Pure;
elsif Is_Remote_Call_Interface (Unit_Id) then
Elab_Nam := Name_Remote_Call_Interface;
elsif Is_Remote_Types (Unit_Id) then
Elab_Nam := Name_Remote_Types;
else
pragma Assert (Is_Shared_Passive (Unit_Id));
Elab_Nam := Name_Shared_Passive;
end if;
Info_Requirement_Met (Find_Preelaboration_Pragma (Elab_Nam));
end if;
-- Determine whether the context of the main unit has a pragma strong
-- enough to meet the requirement.
else
EA_Id := Elaboration_Attributes_Of (Unit_Id);
Unit_Prag := Elab_Pragma (EA_Id);
-- The pragma must be either Elaborate_All or be as strong as the
-- requirement.
if Present (Unit_Prag)
and then Pragma_Name (Unit_Prag) in Name_Elaborate_All | Req_Nam
then
Req_Met := True;
-- Output extra information when switch -gnatel (info messages
-- on implicit Elaborate[_All] pragmas.
if Elab_Info_Messages
and then not In_State.Suppress_Info_Messages
then
Info_Requirement_Met (Unit_Prag);
end if;
end if;
end if;
-- The requirement was not met by the context of the main unit, issue
-- an error.
if not Req_Met then
Elaboration_Requirement_Error;
end if;
end Meet_Elaboration_Requirement;
-------------
-- Present --
-------------
function Present (EA_Id : Elaboration_Attributes_Id) return Boolean is
begin
return EA_Id /= No_Elaboration_Attributes;
end Present;
---------------------
-- Set_Elab_Pragma --
---------------------
procedure Set_Elab_Pragma
(EA_Id : Elaboration_Attributes_Id;
Prag : Node_Id)
is
pragma Assert (Present (EA_Id));
begin
Elaboration_Attributes.Table (EA_Id).Elab_Pragma := Prag;
end Set_Elab_Pragma;
---------------------
-- Set_With_Clause --
---------------------
procedure Set_With_Clause
(EA_Id : Elaboration_Attributes_Id;
Clause : Node_Id)
is
pragma Assert (Present (EA_Id));
begin
Elaboration_Attributes.Table (EA_Id).With_Clause := Clause;
end Set_With_Clause;
-----------------
-- With_Clause --
-----------------
function With_Clause
(EA_Id : Elaboration_Attributes_Id) return Node_Id
is
pragma Assert (Present (EA_Id));
begin
return Elaboration_Attributes.Table (EA_Id).With_Clause;
end With_Clause;
end Elaborated_Units;
------------------------------
-- Elaboration_Phase_Active --
------------------------------
function Elaboration_Phase_Active return Boolean is
begin
return Elaboration_Phase = Active;
end Elaboration_Phase_Active;
------------------------------
-- Error_Preelaborated_Call --
------------------------------
procedure Error_Preelaborated_Call (N : Node_Id) is
begin
-- This is a warning in GNAT mode allowing such calls to be used in the
-- predefined library units with appropriate care.
Error_Msg_Warn := GNAT_Mode;
-- Ada 2020 (AI12-0175): Calls to certain functions that are essentially
-- unchecked conversions are preelaborable.
if Ada_Version >= Ada_2020 then
Error_Msg_N
("<<non-preelaborable call not allowed in preelaborated unit", N);
else
Error_Msg_N
("<<non-static call not allowed in preelaborated unit", N);
end if;
end Error_Preelaborated_Call;
----------------------------------
-- Finalize_All_Data_Structures --
----------------------------------
procedure Finalize_All_Data_Structures is
begin
Finalize_Body_Processor;
Finalize_Early_Call_Region_Processor;
Finalize_Elaborated_Units;
Finalize_Internal_Representation;
Finalize_Invocation_Graph;
Finalize_Scenario_Storage;
end Finalize_All_Data_Structures;
-----------------------------
-- Find_Enclosing_Instance --
-----------------------------
function Find_Enclosing_Instance (N : Node_Id) return Node_Id is
Par : Node_Id;
begin
-- Climb the parent chain looking for an enclosing instance spec or body
Par := N;
while Present (Par) loop
if Nkind (Par) in N_Package_Body
| N_Package_Declaration
| N_Subprogram_Body
| N_Subprogram_Declaration
and then Is_Generic_Instance (Unique_Defining_Entity (Par))
then
return Par;
end if;
Par := Parent (Par);
end loop;
return Empty;
end Find_Enclosing_Instance;
--------------------------
-- Find_Enclosing_Level --
--------------------------
function Find_Enclosing_Level (N : Node_Id) return Enclosing_Level_Kind is
function Level_Of (Unit : Node_Id) return Enclosing_Level_Kind;
pragma Inline (Level_Of);
-- Obtain the corresponding level of unit Unit
--------------
-- Level_Of --
--------------
function Level_Of (Unit : Node_Id) return Enclosing_Level_Kind is
Spec_Id : Entity_Id;
begin
if Nkind (Unit) in N_Generic_Instantiation then
return Instantiation_Level;
elsif Nkind (Unit) = N_Generic_Package_Declaration then
return Generic_Spec_Level;
elsif Nkind (Unit) = N_Package_Declaration then
return Library_Spec_Level;
elsif Nkind (Unit) = N_Package_Body then
Spec_Id := Corresponding_Spec (Unit);
-- The body belongs to a generic package
if Present (Spec_Id)
and then Ekind (Spec_Id) = E_Generic_Package
then
return Generic_Body_Level;
-- Otherwise the body belongs to a non-generic package. This also
-- treats an illegal package body without a corresponding spec as
-- a non-generic package body.
else
return Library_Body_Level;
end if;
end if;
return No_Level;
end Level_Of;
-- Local variables
Context : Node_Id;
Curr : Node_Id;
Prev : Node_Id;
-- Start of processing for Find_Enclosing_Level
begin
-- Call markers and instantiations which appear at the declaration level
-- but are later relocated in a different context retain their original
-- declaration level.
if Nkind (N) in N_Call_Marker
| N_Function_Instantiation
| N_Package_Instantiation
| N_Procedure_Instantiation
and then Is_Declaration_Level_Node (N)
then
return Declaration_Level;
end if;
-- Climb the parent chain looking at the enclosing levels
Prev := N;
Curr := Parent (Prev);
while Present (Curr) loop
-- A traversal from a subunit continues via the corresponding stub
if Nkind (Curr) = N_Subunit then
Curr := Corresponding_Stub (Curr);
-- The current construct is a package. Packages are ignored because
-- they are always elaborated when the enclosing context is invoked
-- or elaborated.
elsif Nkind (Curr) in N_Package_Body | N_Package_Declaration then
null;
-- The current construct is a block statement
elsif Nkind (Curr) = N_Block_Statement then
-- Ignore internally generated blocks created by the expander for
-- various purposes such as abort defer/undefer.
if not Comes_From_Source (Curr) then
null;
-- If the traversal came from the handled sequence of statments,
-- then the node appears at the level of the enclosing construct.
-- This is a more reliable test because transients scopes within
-- the declarative region of the encapsulator are hard to detect.
elsif Nkind (Prev) = N_Handled_Sequence_Of_Statements
and then Handled_Statement_Sequence (Curr) = Prev
then
return Find_Enclosing_Level (Parent (Curr));
-- Otherwise the traversal came from the declarations, the node is
-- at the declaration level.
else
return Declaration_Level;
end if;
-- The current construct is a declaration-level encapsulator
elsif Nkind (Curr) in
N_Entry_Body | N_Subprogram_Body | N_Task_Body
then
-- If the traversal came from the handled sequence of statments,
-- then the node cannot possibly appear at any level. This is
-- a more reliable test because transients scopes within the
-- declarative region of the encapsulator are hard to detect.
if Nkind (Prev) = N_Handled_Sequence_Of_Statements
and then Handled_Statement_Sequence (Curr) = Prev
then
return No_Level;
-- Otherwise the traversal came from the declarations, the node is
-- at the declaration level.
else
return Declaration_Level;
end if;
-- The current construct is a non-library-level encapsulator which
-- indicates that the node cannot possibly appear at any level. Note
-- that the check must come after the declaration-level check because
-- both predicates share certain nodes.
elsif Is_Non_Library_Level_Encapsulator (Curr) then
Context := Parent (Curr);
-- The sole exception is when the encapsulator is the compilation
-- utit itself because the compilation unit node requires special
-- processing (see below).
if Present (Context)
and then Nkind (Context) = N_Compilation_Unit
then
null;
-- Otherwise the node is not at any level
else
return No_Level;
end if;
-- The current construct is a compilation unit. The node appears at
-- the [generic] library level when the unit is a [generic] package.
elsif Nkind (Curr) = N_Compilation_Unit then
return Level_Of (Unit (Curr));
end if;
Prev := Curr;
Curr := Parent (Prev);
end loop;
return No_Level;
end Find_Enclosing_Level;
-------------------
-- Find_Top_Unit --
-------------------
function Find_Top_Unit (N : Node_Or_Entity_Id) return Entity_Id is
begin
return Find_Unit_Entity (Unit (Cunit (Get_Top_Level_Code_Unit (N))));
end Find_Top_Unit;
----------------------
-- Find_Unit_Entity --
----------------------
function Find_Unit_Entity (N : Node_Id) return Entity_Id is
Context : constant Node_Id := Parent (N);
Orig_N : constant Node_Id := Original_Node (N);
begin
-- The unit denotes a package body of an instantiation which acts as
-- a compilation unit. The proper entity is that of the package spec.
if Nkind (N) = N_Package_Body
and then Nkind (Orig_N) = N_Package_Instantiation
and then Nkind (Context) = N_Compilation_Unit
then
return Corresponding_Spec (N);
-- The unit denotes an anonymous package created to wrap a subprogram
-- instantiation which acts as a compilation unit. The proper entity is
-- that of the "related instance".
elsif Nkind (N) = N_Package_Declaration
and then Nkind (Orig_N) in
N_Function_Instantiation | N_Procedure_Instantiation
and then Nkind (Context) = N_Compilation_Unit
then
return Related_Instance (Defining_Entity (N));
-- The unit denotes a concurrent body acting as a subunit. Such bodies
-- are generally rewritten into null statements. The proper entity is
-- that of the "original node".
elsif Nkind (N) = N_Subunit
and then Nkind (Proper_Body (N)) = N_Null_Statement
and then Nkind (Original_Node (Proper_Body (N))) in
N_Protected_Body | N_Task_Body
then
return Defining_Entity (Original_Node (Proper_Body (N)));
-- Otherwise the proper entity is the defining entity
else
return Defining_Entity (N);
end if;
end Find_Unit_Entity;
-----------------------
-- First_Formal_Type --
-----------------------
function First_Formal_Type (Subp_Id : Entity_Id) return Entity_Id is
Formal_Id : constant Entity_Id := First_Formal (Subp_Id);
Typ : Entity_Id;
begin
if Present (Formal_Id) then
Typ := Etype (Formal_Id);
-- Handle various combinations of concurrent and private types
loop
if Ekind (Typ) in E_Protected_Type | E_Task_Type
and then Present (Anonymous_Object (Typ))
then
Typ := Anonymous_Object (Typ);
elsif Is_Concurrent_Record_Type (Typ) then
Typ := Corresponding_Concurrent_Type (Typ);
elsif Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
Typ := Full_View (Typ);
else
exit;
end if;
end loop;
return Typ;
end if;
return Empty;
end First_Formal_Type;
------------------------------
-- Guaranteed_ABE_Processor --
------------------------------
package body Guaranteed_ABE_Processor is
function Is_Guaranteed_ABE
(N : Node_Id;
Target_Decl : Node_Id;
Target_Body : Node_Id) return Boolean;
pragma Inline (Is_Guaranteed_ABE);
-- Determine whether scenario N with a target described by its initial
-- declaration Target_Decl and body Target_Decl results in a guaranteed
-- ABE.
procedure Process_Guaranteed_ABE_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Guaranteed_ABE_Activation);
-- Perform common guaranteed ABE checks and diagnostics for activation
-- call Call which activates object Obj_Id of task type Task_Typ. Formal
-- Call_Rep denotes the representation of the call. Obj_Rep denotes the
-- representation of the object. Task_Rep denotes the representation of
-- the task type. In_State is the current state of the Processing phase.
procedure Process_Guaranteed_ABE_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Guaranteed_ABE_Call);
-- Perform common guaranteed ABE checks and diagnostics for call Call
-- with representation Call_Rep. In_State denotes the current state of
-- the Processing phase.
procedure Process_Guaranteed_ABE_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Guaranteed_ABE_Instantiation);
-- Perform common guaranteed ABE checks and diagnostics for instance
-- Inst with representation Inst_Rep. In_State is the current state of
-- the Processing phase.
-----------------------
-- Is_Guaranteed_ABE --
-----------------------
function Is_Guaranteed_ABE
(N : Node_Id;
Target_Decl : Node_Id;
Target_Body : Node_Id) return Boolean
is
Spec : Node_Id;
begin
-- Avoid cascaded errors if there were previous serious infractions.
-- As a result the scenario will not be treated as a guaranteed ABE.
-- This behavior parallels that of the old ABE mechanism.
if Serious_Errors_Detected > 0 then
return False;
-- The scenario and the target appear in the same context ignoring
-- enclosing library levels.
elsif In_Same_Context (N, Target_Decl) then
-- The target body has already been encountered. The scenario
-- results in a guaranteed ABE if it appears prior to the body.
if Present (Target_Body) then
return Earlier_In_Extended_Unit (N, Target_Body);
-- Otherwise the body has not been encountered yet. The scenario
-- is a guaranteed ABE since the body will appear later, unless
-- this is a null specification, which can occur if expansion is
-- disabled (e.g. -gnatc or GNATprove mode). It is assumed that
-- the caller has already ensured that the scenario is ABE-safe
-- because optional bodies are not considered here.
else
Spec := Specification (Target_Decl);
if Nkind (Spec) /= N_Procedure_Specification
or else not Null_Present (Spec)
then
return True;
end if;
end if;
end if;
return False;
end Is_Guaranteed_ABE;
----------------------------
-- Process_Guaranteed_ABE --
----------------------------
procedure Process_Guaranteed_ABE
(N : Node_Id;
In_State : Processing_In_State)
is
Scen : constant Node_Id := Scenario (N);
Scen_Rep : Scenario_Rep_Id;
begin
-- Add the current scenario to the stack of active scenarios
Push_Active_Scenario (Scen);
-- Only calls, instantiations, and task activations may result in a
-- guaranteed ABE.
-- Call or task activation
if Is_Suitable_Call (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
if Kind (Scen_Rep) = Call_Scenario then
Process_Guaranteed_ABE_Call
(Call => Scen,
Call_Rep => Scen_Rep,
In_State => In_State);
else
pragma Assert (Kind (Scen_Rep) = Task_Activation_Scenario);
Process_Activation
(Call => Scen,
Call_Rep => Scenario_Representation_Of (Scen, In_State),
Processor => Process_Guaranteed_ABE_Activation'Access,
In_State => In_State);
end if;
-- Instantiation
elsif Is_Suitable_Instantiation (Scen) then
Process_Guaranteed_ABE_Instantiation
(Inst => Scen,
Inst_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
end if;
-- Remove the current scenario from the stack of active scenarios
-- once all ABE diagnostics and checks have been performed.
Pop_Active_Scenario (Scen);
end Process_Guaranteed_ABE;
---------------------------------------
-- Process_Guaranteed_ABE_Activation --
---------------------------------------
procedure Process_Guaranteed_ABE_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
Spec_Decl : constant Node_Id := Spec_Declaration (Task_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Obj_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Task_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Obj_Rep)
and then Elaboration_Checks_OK (Task_Rep);
-- A run-time ABE check may be installed only when the object and the
-- task type have active elaboration checks, and both are not ignored
-- Ghost constructs.
begin
-- Nothing to do when the root scenario appears at the declaration
-- level and the task is in the same unit, but outside this context.
--
-- task type Task_Typ; -- task declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- T : Task_Typ;
-- begin
-- <activation call> -- activation site
-- end;
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- task body Task_Typ is
-- ...
-- end Task_Typ;
--
-- In the example above, the context of X is the declarative list
-- of Proc. The "elaboration" of X may reach the activation of T
-- whose body is defined outside of X's context. The task body is
-- relevant only when Proc is invoked, but this happens only in
-- "normal" elaboration, therefore the task body must not be
-- considered if this is not the case.
if Is_Up_Level_Target
(Targ_Decl => Spec_Decl,
In_State => In_State)
then
return;
-- Nothing to do when the activation is ABE-safe
--
-- generic
-- package Gen is
-- task type Task_Typ;
-- end Gen;
--
-- package body Gen is
-- task body Task_Typ is
-- begin
-- ...
-- end Task_Typ;
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- package Nested is
-- package Inst is new Gen;
-- T : Inst.Task_Typ;
-- end Nested; -- safe activation
-- ...
elsif Is_Safe_Activation (Call, Task_Rep) then
return;
-- An activation call leads to a guaranteed ABE when the activation
-- call and the task appear within the same context ignoring library
-- levels, and the body of the task has not been seen yet or appears
-- after the activation call.
--
-- procedure Guaranteed_ABE is
-- task type Task_Typ;
--
-- package Nested is
-- T : Task_Typ;
-- <activation call> -- guaranteed ABE
-- end Nested;
--
-- task body Task_Typ is
-- ...
-- end Task_Typ;
-- ...
elsif Is_Guaranteed_ABE
(N => Call,
Target_Decl => Spec_Decl,
Target_Body => Body_Declaration (Task_Rep))
then
if Elaboration_Warnings_OK (Call_Rep) then
Error_Msg_Sloc := Sloc (Call);
Error_Msg_N
("??task & will be activated # before elaboration of its "
& "body", Obj_Id);
Error_Msg_N
("\Program_Error will be raised at run time", Obj_Id);
end if;
-- Mark the activation call as a guaranteed ABE
Set_Is_Known_Guaranteed_ABE (Call);
-- Install a run-time ABE failue because this activation call will
-- always result in an ABE.
if Check_OK then
Install_Scenario_ABE_Failure
(N => Call,
Targ_Id => Task_Typ,
Targ_Rep => Task_Rep,
Disable => Obj_Rep);
end if;
end if;
end Process_Guaranteed_ABE_Activation;
---------------------------------
-- Process_Guaranteed_ABE_Call --
---------------------------------
procedure Process_Guaranteed_ABE_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Subp_Id : constant Entity_Id := Target (Call_Rep);
Subp_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Subp_Id, In_State);
Spec_Decl : constant Node_Id := Spec_Declaration (Subp_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Call_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Subp_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Call_Rep)
and then Elaboration_Checks_OK (Subp_Rep);
-- A run-time ABE check may be installed only when both the call
-- and the target have active elaboration checks, and both are not
-- ignored Ghost constructs.
begin
-- Nothing to do when the root scenario appears at the declaration
-- level and the target is in the same unit but outside this context.
--
-- function B ...; -- target declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- return B; -- call site
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- function B ... is
-- ...
-- end B;
--
-- In the example above, the context of X is the declarative region
-- of Proc. The "elaboration" of X may eventually reach B which is
-- defined outside of X's context. B is relevant only when Proc is
-- invoked, but this happens only by means of "normal" elaboration,
-- therefore B must not be considered if this is not the case.
if Is_Up_Level_Target
(Targ_Decl => Spec_Decl,
In_State => In_State)
then
return;
-- Nothing to do when the call is ABE-safe
--
-- generic
-- function Gen ...;
--
-- function Gen ... is
-- begin
-- ...
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- function Inst is new Gen;
-- X : ... := Inst; -- safe call
-- ...
elsif Is_Safe_Call (Call, Subp_Id, Subp_Rep) then
return;
-- A call leads to a guaranteed ABE when the call and the target
-- appear within the same context ignoring library levels, and the
-- body of the target has not been seen yet or appears after the
-- call.
--
-- procedure Guaranteed_ABE is
-- function Func ...;
--
-- package Nested is
-- Obj : ... := Func; -- guaranteed ABE
-- end Nested;
--
-- function Func ... is
-- ...
-- end Func;
-- ...
elsif Is_Guaranteed_ABE
(N => Call,
Target_Decl => Spec_Decl,
Target_Body => Body_Declaration (Subp_Rep))
then
if Elaboration_Warnings_OK (Call_Rep) then
Error_Msg_NE
("??cannot call & before body seen", Call, Subp_Id);
Error_Msg_N ("\Program_Error will be raised at run time", Call);
end if;
-- Mark the call as a guaranteed ABE
Set_Is_Known_Guaranteed_ABE (Call);
-- Install a run-time ABE failure because the call will always
-- result in an ABE.
if Check_OK then
Install_Scenario_ABE_Failure
(N => Call,
Targ_Id => Subp_Id,
Targ_Rep => Subp_Rep,
Disable => Call_Rep);
end if;
end if;
end Process_Guaranteed_ABE_Call;
------------------------------------------
-- Process_Guaranteed_ABE_Instantiation --
------------------------------------------
procedure Process_Guaranteed_ABE_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Gen_Id : constant Entity_Id := Target (Inst_Rep);
Gen_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Gen_Id, In_State);
Spec_Decl : constant Node_Id := Spec_Declaration (Gen_Rep);
Check_OK : constant Boolean :=
not In_State.Suppress_Checks
and then Ghost_Mode_Of (Inst_Rep) /= Is_Ignored
and then Ghost_Mode_Of (Gen_Rep) /= Is_Ignored
and then Elaboration_Checks_OK (Inst_Rep)
and then Elaboration_Checks_OK (Gen_Rep);
-- A run-time ABE check may be installed only when both the instance
-- and the generic have active elaboration checks and both are not
-- ignored Ghost constructs.
begin
-- Nothing to do when the root scenario appears at the declaration
-- level and the generic is in the same unit, but outside this
-- context.
--
-- generic
-- procedure Gen is ...; -- generic declaration
--
-- procedure Proc is
-- function A ... is
-- begin
-- if Some_Condition then
-- declare
-- procedure I is new Gen; -- instantiation site
-- ...
-- ...
-- end A;
--
-- X : ... := A; -- root scenario
-- ...
--
-- procedure Gen is
-- ...
-- end Gen;
--
-- In the example above, the context of X is the declarative region
-- of Proc. The "elaboration" of X may eventually reach Gen which
-- appears outside of X's context. Gen is relevant only when Proc is
-- invoked, but this happens only by means of "normal" elaboration,
-- therefore Gen must not be considered if this is not the case.
if Is_Up_Level_Target
(Targ_Decl => Spec_Decl,
In_State => In_State)
then
return;
-- Nothing to do when the instantiation is ABE-safe
--
-- generic
-- package Gen is
-- ...
-- end Gen;
--
-- package body Gen is
-- ...
-- end Gen;
--
-- with Gen;
-- procedure Main is
-- package Inst is new Gen (ABE); -- safe instantiation
-- ...
elsif Is_Safe_Instantiation (Inst, Gen_Id, Gen_Rep) then
return;
-- An instantiation leads to a guaranteed ABE when the instantiation
-- and the generic appear within the same context ignoring library
-- levels, and the body of the generic has not been seen yet or
-- appears after the instantiation.
--
-- procedure Guaranteed_ABE is
-- generic
-- procedure Gen;
--
-- package Nested is
-- procedure Inst is new Gen; -- guaranteed ABE
-- end Nested;
--
-- procedure Gen is
-- ...
-- end Gen;
-- ...
elsif Is_Guaranteed_ABE
(N => Inst,
Target_Decl => Spec_Decl,
Target_Body => Body_Declaration (Gen_Rep))
then
if Elaboration_Warnings_OK (Inst_Rep) then
Error_Msg_NE
("??cannot instantiate & before body seen", Inst, Gen_Id);
Error_Msg_N ("\Program_Error will be raised at run time", Inst);
end if;
-- Mark the instantiation as a guarantee ABE. This automatically
-- suppresses the instantiation of the generic body.
Set_Is_Known_Guaranteed_ABE (Inst);
-- Install a run-time ABE failure because the instantiation will
-- always result in an ABE.
if Check_OK then
Install_Scenario_ABE_Failure
(N => Inst,
Targ_Id => Gen_Id,
Targ_Rep => Gen_Rep,
Disable => Inst_Rep);
end if;
end if;
end Process_Guaranteed_ABE_Instantiation;
end Guaranteed_ABE_Processor;
--------------
-- Has_Body --
--------------
function Has_Body (Pack_Decl : Node_Id) return Boolean is
function Find_Corresponding_Body (Spec_Id : Entity_Id) return Node_Id;
pragma Inline (Find_Corresponding_Body);
-- Try to locate the corresponding body of spec Spec_Id. If no body is
-- found, return Empty.
function Find_Body
(Spec_Id : Entity_Id;
From : Node_Id) return Node_Id;
pragma Inline (Find_Body);
-- Try to locate the corresponding body of spec Spec_Id in the node list
-- which follows arbitrary node From. If no body is found, return Empty.
function Load_Package_Body (Unit_Nam : Unit_Name_Type) return Node_Id;
pragma Inline (Load_Package_Body);
-- Attempt to load the body of unit Unit_Nam. If the load failed, return
-- Empty. If the compilation will not generate code, return Empty.
-----------------------------
-- Find_Corresponding_Body --
-----------------------------
function Find_Corresponding_Body (Spec_Id : Entity_Id) return Node_Id is
Context : constant Entity_Id := Scope (Spec_Id);
Spec_Decl : constant Node_Id := Unit_Declaration_Node (Spec_Id);
Body_Decl : Node_Id;
Body_Id : Entity_Id;
begin
if Is_Compilation_Unit (Spec_Id) then
Body_Id := Corresponding_Body (Spec_Decl);
if Present (Body_Id) then
return Unit_Declaration_Node (Body_Id);
-- The package is at the library and requires a body. Load the
-- corresponding body because the optional body may be declared
-- there.
elsif Unit_Requires_Body (Spec_Id) then
return
Load_Package_Body
(Get_Body_Name (Unit_Name (Get_Source_Unit (Spec_Decl))));
-- Otherwise there is no optional body
else
return Empty;
end if;
-- The immediate context is a package. The optional body may be
-- within the body of that package.
-- procedure Proc is
-- package Nested_1 is
-- package Nested_2 is
-- generic
-- package Pack is
-- end Pack;
-- end Nested_2;
-- end Nested_1;
-- package body Nested_1 is
-- package body Nested_2 is separate;
-- end Nested_1;
-- separate (Proc.Nested_1.Nested_2)
-- package body Nested_2 is
-- package body Pack is -- optional body
-- ...
-- end Pack;
-- end Nested_2;
elsif Is_Package_Or_Generic_Package (Context) then
Body_Decl := Find_Corresponding_Body (Context);
-- The optional body is within the body of the enclosing package
if Present (Body_Decl) then
return
Find_Body
(Spec_Id => Spec_Id,
From => First (Declarations (Body_Decl)));
-- Otherwise the enclosing package does not have a body. This may
-- be the result of an error or a genuine lack of a body.
else
return Empty;
end if;
-- Otherwise the immediate context is a body. The optional body may
-- be within the same list as the spec.
-- procedure Proc is
-- generic
-- package Pack is
-- end Pack;
-- package body Pack is -- optional body
-- ...
-- end Pack;
else
return
Find_Body
(Spec_Id => Spec_Id,
From => Next (Spec_Decl));
end if;
end Find_Corresponding_Body;
---------------
-- Find_Body --
---------------
function Find_Body
(Spec_Id : Entity_Id;
From : Node_Id) return Node_Id
is
Spec_Nam : constant Name_Id := Chars (Spec_Id);
Item : Node_Id;
Lib_Unit : Node_Id;
begin
Item := From;
while Present (Item) loop
-- The current item denotes the optional body
if Nkind (Item) = N_Package_Body
and then Chars (Defining_Entity (Item)) = Spec_Nam
then
return Item;
-- The current item denotes a stub, the optional body may be in
-- the subunit.
elsif Nkind (Item) = N_Package_Body_Stub
and then Chars (Defining_Entity (Item)) = Spec_Nam
then
Lib_Unit := Library_Unit (Item);
-- The corresponding subunit was previously loaded
if Present (Lib_Unit) then
return Lib_Unit;
-- Otherwise attempt to load the corresponding subunit
else
return Load_Package_Body (Get_Unit_Name (Item));
end if;
end if;
Next (Item);
end loop;
return Empty;
end Find_Body;
-----------------------
-- Load_Package_Body --
-----------------------
function Load_Package_Body (Unit_Nam : Unit_Name_Type) return Node_Id is
Body_Decl : Node_Id;
Unit_Num : Unit_Number_Type;
begin
-- The load is performed only when the compilation will generate code
if Operating_Mode = Generate_Code then
Unit_Num :=
Load_Unit
(Load_Name => Unit_Nam,
Required => False,
Subunit => False,
Error_Node => Pack_Decl);
-- The load failed most likely because the physical file is
-- missing.
if Unit_Num = No_Unit then
return Empty;
-- Otherwise the load was successful, return the body of the unit
else
Body_Decl := Unit (Cunit (Unit_Num));
-- If the unit is a subunit with an available proper body,
-- return the proper body.
if Nkind (Body_Decl) = N_Subunit
and then Present (Proper_Body (Body_Decl))
then
Body_Decl := Proper_Body (Body_Decl);
end if;
return Body_Decl;
end if;
end if;
return Empty;
end Load_Package_Body;
-- Local variables
Pack_Id : constant Entity_Id := Defining_Entity (Pack_Decl);
-- Start of processing for Has_Body
begin
-- The body is available
if Present (Corresponding_Body (Pack_Decl)) then
return True;
-- The body is required if the package spec contains a construct which
-- requires a completion in a body.
elsif Unit_Requires_Body (Pack_Id) then
return True;
-- The body may be optional
else
return Present (Find_Corresponding_Body (Pack_Id));
end if;
end Has_Body;
----------
-- Hash --
----------
function Hash (NE : Node_Or_Entity_Id) return Bucket_Range_Type is
pragma Assert (Present (NE));
begin
return Bucket_Range_Type (NE);
end Hash;
--------------------------
-- In_External_Instance --
--------------------------
function In_External_Instance
(N : Node_Id;
Target_Decl : Node_Id) return Boolean
is
Inst : Node_Id;
Inst_Body : Node_Id;
Inst_Spec : Node_Id;
begin
Inst := Find_Enclosing_Instance (Target_Decl);
-- The target declaration appears within an instance spec. Visibility is
-- ignored because internally generated primitives for private types may
-- reside in the private declarations and still be invoked from outside.
if Present (Inst) and then Nkind (Inst) = N_Package_Declaration then
-- The scenario comes from the main unit and the instance does not
if In_Extended_Main_Code_Unit (N)
and then not In_Extended_Main_Code_Unit (Inst)
then
return True;
-- Otherwise the scenario must not appear within the instance spec or
-- body.
else
Spec_And_Body_From_Node
(N => Inst,
Spec_Decl => Inst_Spec,
Body_Decl => Inst_Body);
return not In_Subtree
(N => N,
Root1 => Inst_Spec,
Root2 => Inst_Body);
end if;
end if;
return False;
end In_External_Instance;
---------------------
-- In_Main_Context --
---------------------
function In_Main_Context (N : Node_Id) return Boolean is
begin
-- Scenarios outside the main unit are not considered because the ALI
-- information supplied to binde is for the main unit only.
if not In_Extended_Main_Code_Unit (N) then
return False;
-- Scenarios within internal units are not considered unless switch
-- -gnatdE (elaboration checks on predefined units) is in effect.
elsif not Debug_Flag_EE and then In_Internal_Unit (N) then
return False;
end if;
return True;
end In_Main_Context;
---------------------
-- In_Same_Context --
---------------------
function In_Same_Context
(N1 : Node_Id;
N2 : Node_Id;
Nested_OK : Boolean := False) return Boolean
is
function Find_Enclosing_Context (N : Node_Id) return Node_Id;
pragma Inline (Find_Enclosing_Context);
-- Return the nearest enclosing non-library-level or compilation unit
-- node which encapsulates arbitrary node N. Return Empty is no such
-- context is available.
function In_Nested_Context
(Outer : Node_Id;
Inner : Node_Id) return Boolean;
pragma Inline (In_Nested_Context);
-- Determine whether arbitrary node Outer encapsulates arbitrary node
-- Inner.
----------------------------
-- Find_Enclosing_Context --
----------------------------
function Find_Enclosing_Context (N : Node_Id) return Node_Id is
Context : Node_Id;
Par : Node_Id;
begin
Par := Parent (N);
while Present (Par) loop
-- A traversal from a subunit continues via the corresponding stub
if Nkind (Par) = N_Subunit then
Par := Corresponding_Stub (Par);
-- Stop the traversal when the nearest enclosing non-library-level
-- encapsulator has been reached.
elsif Is_Non_Library_Level_Encapsulator (Par) then
Context := Parent (Par);
-- The sole exception is when the encapsulator is the unit of
-- compilation because this case requires special processing
-- (see below).
if Present (Context)
and then Nkind (Context) = N_Compilation_Unit
then
null;
else
return Par;
end if;
-- Reaching a compilation unit node without hitting a non-library-
-- level encapsulator indicates that N is at the library level in
-- which case the compilation unit is the context.
elsif Nkind (Par) = N_Compilation_Unit then
return Par;
end if;
Par := Parent (Par);
end loop;
return Empty;
end Find_Enclosing_Context;
-----------------------
-- In_Nested_Context --
-----------------------
function In_Nested_Context
(Outer : Node_Id;
Inner : Node_Id) return Boolean
is
Par : Node_Id;
begin
Par := Inner;
while Present (Par) loop
-- A traversal from a subunit continues via the corresponding stub
if Nkind (Par) = N_Subunit then
Par := Corresponding_Stub (Par);
elsif Par = Outer then
return True;
end if;
Par := Parent (Par);
end loop;
return False;
end In_Nested_Context;
-- Local variables
Context_1 : constant Node_Id := Find_Enclosing_Context (N1);
Context_2 : constant Node_Id := Find_Enclosing_Context (N2);
-- Start of processing for In_Same_Context
begin
-- Both nodes appear within the same context
if Context_1 = Context_2 then
return True;
-- Both nodes appear in compilation units. Determine whether one unit
-- is the body of the other.
elsif Nkind (Context_1) = N_Compilation_Unit
and then Nkind (Context_2) = N_Compilation_Unit
then
return
Is_Same_Unit
(Unit_1 => Defining_Entity (Unit (Context_1)),
Unit_2 => Defining_Entity (Unit (Context_2)));
-- The context of N1 encloses the context of N2
elsif Nested_OK and then In_Nested_Context (Context_1, Context_2) then
return True;
end if;
return False;
end In_Same_Context;
----------------
-- Initialize --
----------------
procedure Initialize is
begin
-- Set the soft link which enables Atree.Rewrite to update a scenario
-- each time it is transformed into another node.
Set_Rewriting_Proc (Update_Elaboration_Scenario'Access);
-- Create all internal data structures and activate the elaboration
-- phase of the compiler.
Initialize_All_Data_Structures;
Set_Elaboration_Phase (Active);
end Initialize;
------------------------------------
-- Initialize_All_Data_Structures --
------------------------------------
procedure Initialize_All_Data_Structures is
begin
Initialize_Body_Processor;
Initialize_Early_Call_Region_Processor;
Initialize_Elaborated_Units;
Initialize_Internal_Representation;
Initialize_Invocation_Graph;
Initialize_Scenario_Storage;
end Initialize_All_Data_Structures;
--------------------------
-- Instantiated_Generic --
--------------------------
function Instantiated_Generic (Inst : Node_Id) return Entity_Id is
begin
-- Traverse a possible chain of renamings to obtain the original generic
-- being instantiatied.
return Get_Renamed_Entity (Entity (Name (Inst)));
end Instantiated_Generic;
-----------------------------
-- Internal_Representation --
-----------------------------
package body Internal_Representation is
-----------
-- Types --
-----------
-- The following type represents the contents of a scenario
type Scenario_Rep_Record is record
Elab_Checks_OK : Boolean := False;
-- The status of elaboration checks for the scenario
Elab_Warnings_OK : Boolean := False;
-- The status of elaboration warnings for the scenario
GM : Extended_Ghost_Mode := Is_Checked_Or_Not_Specified;
-- The Ghost mode of the scenario
Kind : Scenario_Kind := No_Scenario;
-- The nature of the scenario
Level : Enclosing_Level_Kind := No_Level;
-- The enclosing level where the scenario resides
SM : Extended_SPARK_Mode := Is_Off_Or_Not_Specified;
-- The SPARK mode of the scenario
Target : Entity_Id := Empty;
-- The target of the scenario
-- The following attributes are multiplexed and depend on the Kind of
-- the scenario. They are mapped as follows:
--
-- Call_Scenario
-- Is_Dispatching_Call (Flag_1)
--
-- Task_Activation_Scenario
-- Activated_Task_Objects (List_1)
-- Activated_Task_Type (Field_1)
--
-- Variable_Reference
-- Is_Read_Reference (Flag_1)
Flag_1 : Boolean := False;
Field_1 : Node_Or_Entity_Id := Empty;
List_1 : NE_List.Doubly_Linked_List := NE_List.Nil;
end record;
-- The following type represents the contents of a target
type Target_Rep_Record is record
Body_Decl : Node_Id := Empty;
-- The declaration of the target body
Elab_Checks_OK : Boolean := False;
-- The status of elaboration checks for the target
Elab_Warnings_OK : Boolean := False;
-- The status of elaboration warnings for the target
GM : Extended_Ghost_Mode := Is_Checked_Or_Not_Specified;
-- The Ghost mode of the target
Kind : Target_Kind := No_Target;
-- The nature of the target
SM : Extended_SPARK_Mode := Is_Off_Or_Not_Specified;
-- The SPARK mode of the target
Spec_Decl : Node_Id := Empty;
-- The declaration of the target spec
Unit : Entity_Id := Empty;
-- The top unit where the target is declared
Version : Representation_Kind := No_Representation;
-- The version of the target representation
-- The following attributes are multiplexed and depend on the Kind of
-- the target. They are mapped as follows:
--
-- Subprogram_Target
-- Barrier_Body_Declaration (Field_1)
--
-- Variable_Target
-- Variable_Declaration (Field_1)
Field_1 : Node_Or_Entity_Id := Empty;
end record;
---------------------
-- Data structures --
---------------------
procedure Destroy (T_Id : in out Target_Rep_Id);
-- Destroy a target representation T_Id
package ETT_Map is new Dynamic_Hash_Tables
(Key_Type => Entity_Id,
Value_Type => Target_Rep_Id,
No_Value => No_Target_Rep,
Expansion_Threshold => 1.5,
Expansion_Factor => 2,
Compression_Threshold => 0.3,
Compression_Factor => 2,
"=" => "=",
Destroy_Value => Destroy,
Hash => Hash);
-- The following map relates target representations to entities
Entity_To_Target_Map : ETT_Map.Dynamic_Hash_Table := ETT_Map.Nil;
procedure Destroy (S_Id : in out Scenario_Rep_Id);
-- Destroy a scenario representation S_Id
package NTS_Map is new Dynamic_Hash_Tables
(Key_Type => Node_Id,
Value_Type => Scenario_Rep_Id,
No_Value => No_Scenario_Rep,
Expansion_Threshold => 1.5,
Expansion_Factor => 2,
Compression_Threshold => 0.3,
Compression_Factor => 2,
"=" => "=",
Destroy_Value => Destroy,
Hash => Hash);
-- The following map relates scenario representations to nodes
Node_To_Scenario_Map : NTS_Map.Dynamic_Hash_Table := NTS_Map.Nil;
-- The following table stores all scenario representations
package Scenario_Reps is new Table.Table
(Table_Index_Type => Scenario_Rep_Id,
Table_Component_Type => Scenario_Rep_Record,
Table_Low_Bound => First_Scenario_Rep,
Table_Initial => 1000,
Table_Increment => 200,
Table_Name => "Scenario_Reps");
-- The following table stores all target representations
package Target_Reps is new Table.Table
(Table_Index_Type => Target_Rep_Id,
Table_Component_Type => Target_Rep_Record,
Table_Low_Bound => First_Target_Rep,
Table_Initial => 1000,
Table_Increment => 200,
Table_Name => "Target_Reps");
--------------
-- Builders --
--------------
function Create_Access_Taken_Rep
(Attr : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Access_Taken_Rep);
-- Create the representation of 'Access attribute Attr
function Create_Call_Or_Task_Activation_Rep
(Call : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Call_Or_Task_Activation_Rep);
-- Create the representation of call or task activation Call
function Create_Derived_Type_Rep
(Typ_Decl : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Derived_Type_Rep);
-- Create the representation of a derived type described by declaration
-- Typ_Decl.
function Create_Generic_Rep
(Gen_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Generic_Rep);
-- Create the representation of generic Gen_Id
function Create_Instantiation_Rep
(Inst : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Instantiation_Rep);
-- Create the representation of instantiation Inst
function Create_Package_Rep
(Pack_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Package_Rep);
-- Create the representation of package Pack_Id
function Create_Protected_Entry_Rep
(PE_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Protected_Entry_Rep);
-- Create the representation of protected entry PE_Id
function Create_Protected_Subprogram_Rep
(PS_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Protected_Subprogram_Rep);
-- Create the representation of protected subprogram PS_Id
function Create_Refined_State_Pragma_Rep
(Prag : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Refined_State_Pragma_Rep);
-- Create the representation of Refined_State pragma Prag
function Create_Scenario_Rep
(N : Node_Id;
In_State : Processing_In_State) return Scenario_Rep_Record;
pragma Inline (Create_Scenario_Rep);
-- Top level dispatcher. Create the representation of elaboration
-- scenario N. In_State is the current state of the Processing phase.
function Create_Subprogram_Rep
(Subp_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Subprogram_Rep);
-- Create the representation of entry, operator, or subprogram Subp_Id
function Create_Target_Rep
(Id : Entity_Id;
In_State : Processing_In_State) return Target_Rep_Record;
pragma Inline (Create_Target_Rep);
-- Top level dispatcher. Create the representation of elaboration target
-- Id. In_State is the current state of the Processing phase.
function Create_Task_Entry_Rep
(TE_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Task_Entry_Rep);
-- Create the representation of task entry TE_Id
function Create_Task_Rep (Task_Typ : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Task_Rep);
-- Create the representation of task type Typ
function Create_Variable_Assignment_Rep
(Asmt : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Variable_Assignment_Rep);
-- Create the representation of variable assignment Asmt
function Create_Variable_Reference_Rep
(Ref : Node_Id) return Scenario_Rep_Record;
pragma Inline (Create_Variable_Reference_Rep);
-- Create the representation of variable reference Ref
function Create_Variable_Rep
(Var_Id : Entity_Id) return Target_Rep_Record;
pragma Inline (Create_Variable_Rep);
-- Create the representation of variable Var_Id
-----------------------
-- Local subprograms --
-----------------------
function Ghost_Mode_Of_Entity
(Id : Entity_Id) return Extended_Ghost_Mode;
pragma Inline (Ghost_Mode_Of_Entity);
-- Obtain the extended Ghost mode of arbitrary entity Id
function Ghost_Mode_Of_Node (N : Node_Id) return Extended_Ghost_Mode;
pragma Inline (Ghost_Mode_Of_Node);
-- Obtain the extended Ghost mode of arbitrary node N
function Present (S_Id : Scenario_Rep_Id) return Boolean;
pragma Inline (Present);
-- Determine whether scenario representation S_Id exists
function Present (T_Id : Target_Rep_Id) return Boolean;
pragma Inline (Present);
-- Determine whether target representation T_Id exists
function SPARK_Mode_Of_Entity
(Id : Entity_Id) return Extended_SPARK_Mode;
pragma Inline (SPARK_Mode_Of_Entity);
-- Obtain the extended SPARK mode of arbitrary entity Id
function SPARK_Mode_Of_Node (N : Node_Id) return Extended_SPARK_Mode;
pragma Inline (SPARK_Mode_Of_Node);
-- Obtain the extended SPARK mode of arbitrary node N
function To_Ghost_Mode
(Ignored_Status : Boolean) return Extended_Ghost_Mode;
pragma Inline (To_Ghost_Mode);
-- Convert a Ghost mode indicated by Ignored_Status into its extended
-- equivalent.
function To_SPARK_Mode (On_Status : Boolean) return Extended_SPARK_Mode;
pragma Inline (To_SPARK_Mode);
-- Convert a SPARK mode indicated by On_Status into its extended
-- equivalent.
function Version (T_Id : Target_Rep_Id) return Representation_Kind;
pragma Inline (Version);
-- Obtain the version of target representation T_Id
----------------------------
-- Activated_Task_Objects --
----------------------------
function Activated_Task_Objects
(S_Id : Scenario_Rep_Id) return NE_List.Doubly_Linked_List
is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Task_Activation_Scenario);
begin
return Scenario_Reps.Table (S_Id).List_1;
end Activated_Task_Objects;
-------------------------
-- Activated_Task_Type --
-------------------------
function Activated_Task_Type
(S_Id : Scenario_Rep_Id) return Entity_Id
is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Task_Activation_Scenario);
begin
return Scenario_Reps.Table (S_Id).Field_1;
end Activated_Task_Type;
------------------------------
-- Barrier_Body_Declaration --
------------------------------
function Barrier_Body_Declaration
(T_Id : Target_Rep_Id) return Node_Id
is
pragma Assert (Present (T_Id));
pragma Assert (Kind (T_Id) = Subprogram_Target);
begin
return Target_Reps.Table (T_Id).Field_1;
end Barrier_Body_Declaration;
----------------------
-- Body_Declaration --
----------------------
function Body_Declaration (T_Id : Target_Rep_Id) return Node_Id is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Body_Decl;
end Body_Declaration;
-----------------------------
-- Create_Access_Taken_Rep --
-----------------------------
function Create_Access_Taken_Rep
(Attr : Node_Id) return Scenario_Rep_Record
is
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Node (Attr);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Node (Attr);
Rec.GM := Is_Checked_Or_Not_Specified;
Rec.SM := SPARK_Mode_Of_Node (Attr);
Rec.Kind := Access_Taken_Scenario;
Rec.Target := Canonical_Subprogram (Entity (Prefix (Attr)));
return Rec;
end Create_Access_Taken_Rep;
----------------------------------------
-- Create_Call_Or_Task_Activation_Rep --
----------------------------------------
function Create_Call_Or_Task_Activation_Rep
(Call : Node_Id) return Scenario_Rep_Record
is
Subp_Id : constant Entity_Id := Canonical_Subprogram (Target (Call));
Kind : Scenario_Kind;
Rec : Scenario_Rep_Record;
begin
if Is_Activation_Proc (Subp_Id) then
Kind := Task_Activation_Scenario;
else
Kind := Call_Scenario;
end if;
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Node (Call);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Node (Call);
Rec.GM := Ghost_Mode_Of_Node (Call);
Rec.SM := SPARK_Mode_Of_Node (Call);
Rec.Kind := Kind;
Rec.Target := Subp_Id;
-- Scenario-specific attributes
Rec.Flag_1 := Is_Dispatching_Call (Call); -- Dispatching_Call
return Rec;
end Create_Call_Or_Task_Activation_Rep;
-----------------------------
-- Create_Derived_Type_Rep --
-----------------------------
function Create_Derived_Type_Rep
(Typ_Decl : Node_Id) return Scenario_Rep_Record
is
Typ : constant Entity_Id := Defining_Entity (Typ_Decl);
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := False; -- not relevant
Rec.Elab_Warnings_OK := False; -- not relevant
Rec.GM := Ghost_Mode_Of_Entity (Typ);
Rec.SM := SPARK_Mode_Of_Entity (Typ);
Rec.Kind := Derived_Type_Scenario;
Rec.Target := Typ;
return Rec;
end Create_Derived_Type_Rep;
------------------------
-- Create_Generic_Rep --
------------------------
function Create_Generic_Rep
(Gen_Id : Entity_Id) return Target_Rep_Record
is
Rec : Target_Rep_Record;
begin
Rec.Kind := Generic_Target;
Spec_And_Body_From_Entity
(Id => Gen_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Generic_Rep;
------------------------------
-- Create_Instantiation_Rep --
------------------------------
function Create_Instantiation_Rep
(Inst : Node_Id) return Scenario_Rep_Record
is
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Node (Inst);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Node (Inst);
Rec.GM := Ghost_Mode_Of_Node (Inst);
Rec.SM := SPARK_Mode_Of_Node (Inst);
Rec.Kind := Instantiation_Scenario;
Rec.Target := Instantiated_Generic (Inst);
return Rec;
end Create_Instantiation_Rep;
------------------------
-- Create_Package_Rep --
------------------------
function Create_Package_Rep
(Pack_Id : Entity_Id) return Target_Rep_Record
is
Rec : Target_Rep_Record;
begin
Rec.Kind := Package_Target;
Spec_And_Body_From_Entity
(Id => Pack_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Package_Rep;
--------------------------------
-- Create_Protected_Entry_Rep --
--------------------------------
function Create_Protected_Entry_Rep
(PE_Id : Entity_Id) return Target_Rep_Record
is
Prot_Id : constant Entity_Id := Protected_Body_Subprogram (PE_Id);
Barf_Id : Entity_Id;
Dummy : Node_Id;
Rec : Target_Rep_Record;
Spec_Id : Entity_Id;
begin
-- When the entry [family] has already been expanded, it carries both
-- the procedure which emulates the behavior of the entry [family] as
-- well as the barrier function.
if Present (Prot_Id) then
Barf_Id := Barrier_Function (PE_Id);
Spec_Id := Prot_Id;
-- Otherwise no expansion took place
else
Barf_Id := Empty;
Spec_Id := PE_Id;
end if;
Rec.Kind := Subprogram_Target;
Spec_And_Body_From_Entity
(Id => Spec_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
-- Target-specific attributes
if Present (Barf_Id) then
Spec_And_Body_From_Entity
(Id => Barf_Id,
Body_Decl => Rec.Field_1, -- Barrier_Body_Declaration
Spec_Decl => Dummy);
end if;
return Rec;
end Create_Protected_Entry_Rep;
-------------------------------------
-- Create_Protected_Subprogram_Rep --
-------------------------------------
function Create_Protected_Subprogram_Rep
(PS_Id : Entity_Id) return Target_Rep_Record
is
Prot_Id : constant Entity_Id := Protected_Body_Subprogram (PS_Id);
Rec : Target_Rep_Record;
Spec_Id : Entity_Id;
begin
-- When the protected subprogram has already been expanded, it
-- carries the subprogram which seizes the lock and invokes the
-- original statements.
if Present (Prot_Id) then
Spec_Id := Prot_Id;
-- Otherwise no expansion took place
else
Spec_Id := PS_Id;
end if;
Rec.Kind := Subprogram_Target;
Spec_And_Body_From_Entity
(Id => Spec_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Protected_Subprogram_Rep;
-------------------------------------
-- Create_Refined_State_Pragma_Rep --
-------------------------------------
function Create_Refined_State_Pragma_Rep
(Prag : Node_Id) return Scenario_Rep_Record
is
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := False; -- not relevant
Rec.Elab_Warnings_OK := False; -- not relevant
Rec.GM :=
To_Ghost_Mode (Is_Ignored_Ghost_Pragma (Prag));
Rec.SM := Is_Off_Or_Not_Specified;
Rec.Kind := Refined_State_Pragma_Scenario;
Rec.Target := Empty;
return Rec;
end Create_Refined_State_Pragma_Rep;
-------------------------
-- Create_Scenario_Rep --
-------------------------
function Create_Scenario_Rep
(N : Node_Id;
In_State : Processing_In_State) return Scenario_Rep_Record
is
pragma Unreferenced (In_State);
Rec : Scenario_Rep_Record;
begin
if Is_Suitable_Access_Taken (N) then
Rec := Create_Access_Taken_Rep (N);
elsif Is_Suitable_Call (N) then
Rec := Create_Call_Or_Task_Activation_Rep (N);
elsif Is_Suitable_Instantiation (N) then
Rec := Create_Instantiation_Rep (N);
elsif Is_Suitable_SPARK_Derived_Type (N) then
Rec := Create_Derived_Type_Rep (N);
elsif Is_Suitable_SPARK_Refined_State_Pragma (N) then
Rec := Create_Refined_State_Pragma_Rep (N);
elsif Is_Suitable_Variable_Assignment (N) then
Rec := Create_Variable_Assignment_Rep (N);
elsif Is_Suitable_Variable_Reference (N) then
Rec := Create_Variable_Reference_Rep (N);
else
pragma Assert (False);
return Rec;
end if;
-- Common scenario attributes
Rec.Level := Find_Enclosing_Level (N);
return Rec;
end Create_Scenario_Rep;
---------------------------
-- Create_Subprogram_Rep --
---------------------------
function Create_Subprogram_Rep
(Subp_Id : Entity_Id) return Target_Rep_Record
is
Rec : Target_Rep_Record;
Spec_Id : Entity_Id;
begin
Spec_Id := Subp_Id;
-- The elaboration target denotes an internal function that returns a
-- constrained array type in a SPARK-to-C compilation. In this case
-- the function receives a corresponding procedure which has an out
-- parameter. The proper body for ABE checks and diagnostics is that
-- of the procedure.
if Ekind (Spec_Id) = E_Function
and then Rewritten_For_C (Spec_Id)
then
Spec_Id := Corresponding_Procedure (Spec_Id);
end if;
Rec.Kind := Subprogram_Target;
Spec_And_Body_From_Entity
(Id => Spec_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Subprogram_Rep;
-----------------------
-- Create_Target_Rep --
-----------------------
function Create_Target_Rep
(Id : Entity_Id;
In_State : Processing_In_State) return Target_Rep_Record
is
Rec : Target_Rep_Record;
begin
if Is_Generic_Unit (Id) then
Rec := Create_Generic_Rep (Id);
elsif Is_Protected_Entry (Id) then
Rec := Create_Protected_Entry_Rep (Id);
elsif Is_Protected_Subp (Id) then
Rec := Create_Protected_Subprogram_Rep (Id);
elsif Is_Task_Entry (Id) then
Rec := Create_Task_Entry_Rep (Id);
elsif Is_Task_Type (Id) then
Rec := Create_Task_Rep (Id);
elsif Ekind (Id) in E_Constant | E_Variable then
Rec := Create_Variable_Rep (Id);
elsif Ekind (Id) in E_Entry | E_Function | E_Operator | E_Procedure
then
Rec := Create_Subprogram_Rep (Id);
elsif Ekind (Id) = E_Package then
Rec := Create_Package_Rep (Id);
else
pragma Assert (False);
return Rec;
end if;
-- Common target attributes
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Id (Id);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Id (Id);
Rec.GM := Ghost_Mode_Of_Entity (Id);
Rec.SM := SPARK_Mode_Of_Entity (Id);
Rec.Unit := Find_Top_Unit (Id);
Rec.Version := In_State.Representation;
return Rec;
end Create_Target_Rep;
---------------------------
-- Create_Task_Entry_Rep --
---------------------------
function Create_Task_Entry_Rep
(TE_Id : Entity_Id) return Target_Rep_Record
is
Task_Typ : constant Entity_Id := Non_Private_View (Scope (TE_Id));
Task_Body_Id : constant Entity_Id := Task_Body_Procedure (Task_Typ);
Rec : Target_Rep_Record;
Spec_Id : Entity_Id;
begin
-- The task type has already been expanded, it carries the procedure
-- which emulates the behavior of the task body.
if Present (Task_Body_Id) then
Spec_Id := Task_Body_Id;
-- Otherwise no expansion took place
else
Spec_Id := TE_Id;
end if;
Rec.Kind := Subprogram_Target;
Spec_And_Body_From_Entity
(Id => Spec_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Task_Entry_Rep;
---------------------
-- Create_Task_Rep --
---------------------
function Create_Task_Rep
(Task_Typ : Entity_Id) return Target_Rep_Record
is
Task_Body_Id : constant Entity_Id := Task_Body_Procedure (Task_Typ);
Rec : Target_Rep_Record;
Spec_Id : Entity_Id;
begin
-- The task type has already been expanded, it carries the procedure
-- which emulates the behavior of the task body.
if Present (Task_Body_Id) then
Spec_Id := Task_Body_Id;
-- Otherwise no expansion took place
else
Spec_Id := Task_Typ;
end if;
Rec.Kind := Task_Target;
Spec_And_Body_From_Entity
(Id => Spec_Id,
Body_Decl => Rec.Body_Decl,
Spec_Decl => Rec.Spec_Decl);
return Rec;
end Create_Task_Rep;
------------------------------------
-- Create_Variable_Assignment_Rep --
------------------------------------
function Create_Variable_Assignment_Rep
(Asmt : Node_Id) return Scenario_Rep_Record
is
Var_Id : constant Entity_Id := Entity (Assignment_Target (Asmt));
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Node (Asmt);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Id (Var_Id);
Rec.GM := Ghost_Mode_Of_Node (Asmt);
Rec.SM := SPARK_Mode_Of_Node (Asmt);
Rec.Kind := Variable_Assignment_Scenario;
Rec.Target := Var_Id;
return Rec;
end Create_Variable_Assignment_Rep;
-----------------------------------
-- Create_Variable_Reference_Rep --
-----------------------------------
function Create_Variable_Reference_Rep
(Ref : Node_Id) return Scenario_Rep_Record
is
Rec : Scenario_Rep_Record;
begin
Rec.Elab_Checks_OK := Is_Elaboration_Checks_OK_Node (Ref);
Rec.Elab_Warnings_OK := Is_Elaboration_Warnings_OK_Node (Ref);
Rec.GM := Ghost_Mode_Of_Node (Ref);
Rec.SM := SPARK_Mode_Of_Node (Ref);
Rec.Kind := Variable_Reference_Scenario;
Rec.Target := Target (Ref);
-- Scenario-specific attributes
Rec.Flag_1 := Is_Read (Ref); -- Is_Read_Reference
return Rec;
end Create_Variable_Reference_Rep;
-------------------------
-- Create_Variable_Rep --
-------------------------
function Create_Variable_Rep
(Var_Id : Entity_Id) return Target_Rep_Record
is
Rec : Target_Rep_Record;
begin
Rec.Kind := Variable_Target;
-- Target-specific attributes
Rec.Field_1 := Declaration_Node (Var_Id); -- Variable_Declaration
return Rec;
end Create_Variable_Rep;
-------------
-- Destroy --
-------------
procedure Destroy (S_Id : in out Scenario_Rep_Id) is
pragma Unreferenced (S_Id);
begin
null;
end Destroy;
-------------
-- Destroy --
-------------
procedure Destroy (T_Id : in out Target_Rep_Id) is
pragma Unreferenced (T_Id);
begin
null;
end Destroy;
--------------------------------
-- Disable_Elaboration_Checks --
--------------------------------
procedure Disable_Elaboration_Checks (S_Id : Scenario_Rep_Id) is
pragma Assert (Present (S_Id));
begin
Scenario_Reps.Table (S_Id).Elab_Checks_OK := False;
end Disable_Elaboration_Checks;
--------------------------------
-- Disable_Elaboration_Checks --
--------------------------------
procedure Disable_Elaboration_Checks (T_Id : Target_Rep_Id) is
pragma Assert (Present (T_Id));
begin
Target_Reps.Table (T_Id).Elab_Checks_OK := False;
end Disable_Elaboration_Checks;
---------------------------
-- Elaboration_Checks_OK --
---------------------------
function Elaboration_Checks_OK (S_Id : Scenario_Rep_Id) return Boolean is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).Elab_Checks_OK;
end Elaboration_Checks_OK;
---------------------------
-- Elaboration_Checks_OK --
---------------------------
function Elaboration_Checks_OK (T_Id : Target_Rep_Id) return Boolean is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Elab_Checks_OK;
end Elaboration_Checks_OK;
-----------------------------
-- Elaboration_Warnings_OK --
-----------------------------
function Elaboration_Warnings_OK
(S_Id : Scenario_Rep_Id) return Boolean
is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).Elab_Warnings_OK;
end Elaboration_Warnings_OK;
-----------------------------
-- Elaboration_Warnings_OK --
-----------------------------
function Elaboration_Warnings_OK (T_Id : Target_Rep_Id) return Boolean is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Elab_Warnings_OK;
end Elaboration_Warnings_OK;
--------------------------------------
-- Finalize_Internal_Representation --
--------------------------------------
procedure Finalize_Internal_Representation is
begin
ETT_Map.Destroy (Entity_To_Target_Map);
NTS_Map.Destroy (Node_To_Scenario_Map);
end Finalize_Internal_Representation;
-------------------
-- Ghost_Mode_Of --
-------------------
function Ghost_Mode_Of
(S_Id : Scenario_Rep_Id) return Extended_Ghost_Mode
is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).GM;
end Ghost_Mode_Of;
-------------------
-- Ghost_Mode_Of --
-------------------
function Ghost_Mode_Of
(T_Id : Target_Rep_Id) return Extended_Ghost_Mode
is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).GM;
end Ghost_Mode_Of;
--------------------------
-- Ghost_Mode_Of_Entity --
--------------------------
function Ghost_Mode_Of_Entity
(Id : Entity_Id) return Extended_Ghost_Mode
is
begin
return To_Ghost_Mode (Is_Ignored_Ghost_Entity (Id));
end Ghost_Mode_Of_Entity;
------------------------
-- Ghost_Mode_Of_Node --
------------------------
function Ghost_Mode_Of_Node (N : Node_Id) return Extended_Ghost_Mode is
begin
return To_Ghost_Mode (Is_Ignored_Ghost_Node (N));
end Ghost_Mode_Of_Node;
----------------------------------------
-- Initialize_Internal_Representation --
----------------------------------------
procedure Initialize_Internal_Representation is
begin
Entity_To_Target_Map := ETT_Map.Create (500);
Node_To_Scenario_Map := NTS_Map.Create (500);
end Initialize_Internal_Representation;
-------------------------
-- Is_Dispatching_Call --
-------------------------
function Is_Dispatching_Call (S_Id : Scenario_Rep_Id) return Boolean is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Call_Scenario);
begin
return Scenario_Reps.Table (S_Id).Flag_1;
end Is_Dispatching_Call;
-----------------------
-- Is_Read_Reference --
-----------------------
function Is_Read_Reference (S_Id : Scenario_Rep_Id) return Boolean is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Variable_Reference_Scenario);
begin
return Scenario_Reps.Table (S_Id).Flag_1;
end Is_Read_Reference;
----------
-- Kind --
----------
function Kind (S_Id : Scenario_Rep_Id) return Scenario_Kind is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).Kind;
end Kind;
----------
-- Kind --
----------
function Kind (T_Id : Target_Rep_Id) return Target_Kind is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Kind;
end Kind;
-----------
-- Level --
-----------
function Level (S_Id : Scenario_Rep_Id) return Enclosing_Level_Kind is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).Level;
end Level;
-------------
-- Present --
-------------
function Present (S_Id : Scenario_Rep_Id) return Boolean is
begin
return S_Id /= No_Scenario_Rep;
end Present;
-------------
-- Present --
-------------
function Present (T_Id : Target_Rep_Id) return Boolean is
begin
return T_Id /= No_Target_Rep;
end Present;
--------------------------------
-- Scenario_Representation_Of --
--------------------------------
function Scenario_Representation_Of
(N : Node_Id;
In_State : Processing_In_State) return Scenario_Rep_Id
is
S_Id : Scenario_Rep_Id;
begin
S_Id := NTS_Map.Get (Node_To_Scenario_Map, N);
-- The elaboration scenario lacks a representation. This indicates
-- that the scenario is encountered for the first time. Create the
-- representation of it.
if not Present (S_Id) then
Scenario_Reps.Append (Create_Scenario_Rep (N, In_State));
S_Id := Scenario_Reps.Last;
-- Associate the internal representation with the elaboration
-- scenario.
NTS_Map.Put (Node_To_Scenario_Map, N, S_Id);
end if;
pragma Assert (Present (S_Id));
return S_Id;
end Scenario_Representation_Of;
--------------------------------
-- Set_Activated_Task_Objects --
--------------------------------
procedure Set_Activated_Task_Objects
(S_Id : Scenario_Rep_Id;
Task_Objs : NE_List.Doubly_Linked_List)
is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Task_Activation_Scenario);
begin
Scenario_Reps.Table (S_Id).List_1 := Task_Objs;
end Set_Activated_Task_Objects;
-----------------------------
-- Set_Activated_Task_Type --
-----------------------------
procedure Set_Activated_Task_Type
(S_Id : Scenario_Rep_Id;
Task_Typ : Entity_Id)
is
pragma Assert (Present (S_Id));
pragma Assert (Kind (S_Id) = Task_Activation_Scenario);
begin
Scenario_Reps.Table (S_Id).Field_1 := Task_Typ;
end Set_Activated_Task_Type;
-------------------
-- SPARK_Mode_Of --
-------------------
function SPARK_Mode_Of
(S_Id : Scenario_Rep_Id) return Extended_SPARK_Mode
is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).SM;
end SPARK_Mode_Of;
-------------------
-- SPARK_Mode_Of --
-------------------
function SPARK_Mode_Of
(T_Id : Target_Rep_Id) return Extended_SPARK_Mode
is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).SM;
end SPARK_Mode_Of;
--------------------------
-- SPARK_Mode_Of_Entity --
--------------------------
function SPARK_Mode_Of_Entity
(Id : Entity_Id) return Extended_SPARK_Mode
is
Prag : constant Node_Id := SPARK_Pragma (Id);
begin
return
To_SPARK_Mode
(Present (Prag)
and then Get_SPARK_Mode_From_Annotation (Prag) = On);
end SPARK_Mode_Of_Entity;
------------------------
-- SPARK_Mode_Of_Node --
------------------------
function SPARK_Mode_Of_Node (N : Node_Id) return Extended_SPARK_Mode is
begin
return To_SPARK_Mode (Is_SPARK_Mode_On_Node (N));
end SPARK_Mode_Of_Node;
----------------------
-- Spec_Declaration --
----------------------
function Spec_Declaration (T_Id : Target_Rep_Id) return Node_Id is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Spec_Decl;
end Spec_Declaration;
------------
-- Target --
------------
function Target (S_Id : Scenario_Rep_Id) return Entity_Id is
pragma Assert (Present (S_Id));
begin
return Scenario_Reps.Table (S_Id).Target;
end Target;
------------------------------
-- Target_Representation_Of --
------------------------------
function Target_Representation_Of
(Id : Entity_Id;
In_State : Processing_In_State) return Target_Rep_Id
is
T_Id : Target_Rep_Id;
begin
T_Id := ETT_Map.Get (Entity_To_Target_Map, Id);
-- The elaboration target lacks an internal representation. This
-- indicates that the target is encountered for the first time.
-- Create the internal representation of it.
if not Present (T_Id) then
Target_Reps.Append (Create_Target_Rep (Id, In_State));
T_Id := Target_Reps.Last;
-- Associate the internal representation with the elaboration
-- target.
ETT_Map.Put (Entity_To_Target_Map, Id, T_Id);
-- The Processing phase is working with a partially analyzed tree,
-- where various attributes become available as analysis continues.
-- This case arrises in the context of guaranteed ABE processing.
-- Update the existing representation by including new attributes.
elsif In_State.Representation = Inconsistent_Representation then
Target_Reps.Table (T_Id) := Create_Target_Rep (Id, In_State);
-- Otherwise the Processing phase imposes a particular representation
-- version which is not satisfied by the target. This case arrises
-- when the Processing phase switches from guaranteed ABE checks and
-- diagnostics to some other mode of operation. Update the existing
-- representation to include all attributes.
elsif In_State.Representation /= Version (T_Id) then
Target_Reps.Table (T_Id) := Create_Target_Rep (Id, In_State);
end if;
pragma Assert (Present (T_Id));
return T_Id;
end Target_Representation_Of;
-------------------
-- To_Ghost_Mode --
-------------------
function To_Ghost_Mode
(Ignored_Status : Boolean) return Extended_Ghost_Mode
is
begin
if Ignored_Status then
return Is_Ignored;
else
return Is_Checked_Or_Not_Specified;
end if;
end To_Ghost_Mode;
-------------------
-- To_SPARK_Mode --
-------------------
function To_SPARK_Mode
(On_Status : Boolean) return Extended_SPARK_Mode
is
begin
if On_Status then
return Is_On;
else
return Is_Off_Or_Not_Specified;
end if;
end To_SPARK_Mode;
----------
-- Unit --
----------
function Unit (T_Id : Target_Rep_Id) return Entity_Id is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Unit;
end Unit;
--------------------------
-- Variable_Declaration --
--------------------------
function Variable_Declaration (T_Id : Target_Rep_Id) return Node_Id is
pragma Assert (Present (T_Id));
pragma Assert (Kind (T_Id) = Variable_Target);
begin
return Target_Reps.Table (T_Id).Field_1;
end Variable_Declaration;
-------------
-- Version --
-------------
function Version (T_Id : Target_Rep_Id) return Representation_Kind is
pragma Assert (Present (T_Id));
begin
return Target_Reps.Table (T_Id).Version;
end Version;
end Internal_Representation;
----------------------
-- Invocation_Graph --
----------------------
package body Invocation_Graph is
-----------
-- Types --
-----------
-- The following type represents simplified version of an invocation
-- relation.
type Invoker_Target_Relation is record
Invoker : Entity_Id := Empty;
Target : Entity_Id := Empty;
end record;
-- The following variables define the entities of the dummy elaboration
-- procedures used as origins of library level paths.
Elab_Body_Id : Entity_Id := Empty;
Elab_Spec_Id : Entity_Id := Empty;
---------------------
-- Data structures --
---------------------
-- The following set contains all declared invocation constructs. It
-- ensures that the same construct is not declared multiple times in
-- the ALI file of the main unit.
Saved_Constructs_Set : NE_Set.Membership_Set := NE_Set.Nil;
function Hash (Key : Invoker_Target_Relation) return Bucket_Range_Type;
-- Obtain the hash value of pair Key
package IR_Set is new Membership_Sets
(Element_Type => Invoker_Target_Relation,
"=" => "=",
Hash => Hash);
-- The following set contains all recorded simple invocation relations.
-- It ensures that multiple relations involving the same invoker and
-- target do not appear in the ALI file of the main unit.
Saved_Relations_Set : IR_Set.Membership_Set := IR_Set.Nil;
--------------
-- Builders --
--------------
function Signature_Of (Id : Entity_Id) return Invocation_Signature_Id;
pragma Inline (Signature_Of);
-- Obtain the invication signature id of arbitrary entity Id
-----------------------
-- Local subprograms --
-----------------------
procedure Build_Elaborate_Body_Procedure;
pragma Inline (Build_Elaborate_Body_Procedure);
-- Create a dummy elaborate body procedure and store its entity in
-- Elab_Body_Id.
procedure Build_Elaborate_Procedure
(Proc_Id : out Entity_Id;
Proc_Nam : Name_Id;
Loc : Source_Ptr);
pragma Inline (Build_Elaborate_Procedure);
-- Create a dummy elaborate procedure with name Proc_Nam and source
-- location Loc. The entity is returned in Proc_Id.
procedure Build_Elaborate_Spec_Procedure;
pragma Inline (Build_Elaborate_Spec_Procedure);
-- Create a dummy elaborate spec procedure and store its entity in
-- Elab_Spec_Id.
function Build_Subprogram_Invocation
(Subp_Id : Entity_Id) return Node_Id;
pragma Inline (Build_Subprogram_Invocation);
-- Create a dummy call marker that invokes subprogram Subp_Id
function Build_Task_Activation
(Task_Typ : Entity_Id;
In_State : Processing_In_State) return Node_Id;
pragma Inline (Build_Task_Activation);
-- Create a dummy call marker that activates an anonymous task object of
-- type Task_Typ.
procedure Declare_Invocation_Construct
(Constr_Id : Entity_Id;
In_State : Processing_In_State);
pragma Inline (Declare_Invocation_Construct);
-- Declare invocation construct Constr_Id by creating a declaration for
-- it in the ALI file of the main unit. In_State is the current state of
-- the Processing phase.
function Invocation_Graph_Recording_OK return Boolean;
pragma Inline (Invocation_Graph_Recording_OK);
-- Determine whether the invocation graph can be recorded
function Is_Invocation_Scenario (N : Node_Id) return Boolean;
pragma Inline (Is_Invocation_Scenario);
-- Determine whether node N is a suitable scenario for invocation graph
-- recording purposes.
function Is_Invocation_Target (Id : Entity_Id) return Boolean;
pragma Inline (Is_Invocation_Target);
-- Determine whether arbitrary entity Id denotes an invocation target
function Is_Saved_Construct (Constr : Entity_Id) return Boolean;
pragma Inline (Is_Saved_Construct);
-- Determine whether invocation construct Constr has already been
-- declared in the ALI file of the main unit.
function Is_Saved_Relation
(Rel : Invoker_Target_Relation) return Boolean;
pragma Inline (Is_Saved_Relation);
-- Determine whether simple invocation relation Rel has already been
-- recorded in the ALI file of the main unit.
procedure Process_Declarations
(Decls : List_Id;
In_State : Processing_In_State);
pragma Inline (Process_Declarations);
-- Process declaration list Decls by processing all invocation scenarios
-- within it.
procedure Process_Freeze_Node
(Fnode : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Freeze_Node);
-- Process freeze node Fnode by processing all invocation scenarios in
-- its Actions list.
procedure Process_Invocation_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Invocation_Activation);
-- Process activation call Call which activates object Obj_Id of task
-- type Task_Typ by processing all invocation scenarios within the task
-- body. Call_Rep is the representation of the call. Obj_Rep denotes the
-- representation of the object. Task_Rep is the representation of the
-- task type. In_State is the current state of the Processing phase.
procedure Process_Invocation_Body_Scenarios;
pragma Inline (Process_Invocation_Body_Scenarios);
-- Process all library level body scenarios
procedure Process_Invocation_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Invocation_Call);
-- Process invocation call scenario Call with representation Call_Rep.
-- In_State is the current state of the Processing phase.
procedure Process_Invocation_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_Invocation_Instantiation);
-- Process invocation instantiation scenario Inst with representation
-- Inst_Rep. In_State is the current state of the Processing phase.
procedure Process_Invocation_Scenario
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Invocation_Scenario);
-- Process single invocation scenario N. In_State is the current state
-- of the Processing phase.
procedure Process_Invocation_Scenarios
(Iter : in out NE_Set.Iterator;
In_State : Processing_In_State);
pragma Inline (Process_Invocation_Scenarios);
-- Process all invocation scenarios obtained via iterator Iter. In_State
-- is the current state of the Processing phase.
procedure Process_Invocation_Spec_Scenarios;
pragma Inline (Process_Invocation_Spec_Scenarios);
-- Process all library level spec scenarios
procedure Process_Main_Unit;
pragma Inline (Process_Main_Unit);
-- Process all invocation scenarios within the main unit
procedure Process_Package_Declaration
(Pack_Decl : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Package_Declaration);
-- Process package declaration Pack_Decl by processing all invocation
-- scenarios in its visible and private declarations. If the main unit
-- contains a generic, the declarations of the body are also examined.
-- In_State is the current state of the Processing phase.
procedure Process_Protected_Type_Declaration
(Prot_Decl : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Protected_Type_Declaration);
-- Process the declarations of protected type Prot_Decl. In_State is the
-- current state of the Processing phase.
procedure Process_Subprogram_Declaration
(Subp_Decl : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Subprogram_Declaration);
-- Process subprogram declaration Subp_Decl by processing all invocation
-- scenarios within its body. In_State denotes the current state of the
-- Processing phase.
procedure Process_Subprogram_Instantiation
(Inst : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Subprogram_Instantiation);
-- Process subprogram instantiation Inst. In_State is the current state
-- of the Processing phase.
procedure Process_Task_Type_Declaration
(Task_Decl : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_Task_Type_Declaration);
-- Process task declaration Task_Decl by processing all invocation
-- scenarios within its body. In_State is the current state of the
-- Processing phase.
procedure Record_Full_Invocation_Path (In_State : Processing_In_State);
pragma Inline (Record_Full_Invocation_Path);
-- Record all relations between scenario pairs found in the stack of
-- active scenarios. In_State is the current state of the Processing
-- phase.
procedure Record_Invocation_Graph_Encoding;
pragma Inline (Record_Invocation_Graph_Encoding);
-- Record the encoding format used to capture information related to
-- invocation constructs and relations.
procedure Record_Invocation_Path (In_State : Processing_In_State);
pragma Inline (Record_Invocation_Path);
-- Record the invocation relations found within the path represented in
-- the active scenario stack. In_State denotes the current state of the
-- Processing phase.
procedure Record_Simple_Invocation_Path (In_State : Processing_In_State);
pragma Inline (Record_Simple_Invocation_Path);
-- Record a single relation from the start to the end of the stack of
-- active scenarios. In_State is the current state of the Processing
-- phase.
procedure Record_Invocation_Relation
(Invk_Id : Entity_Id;
Targ_Id : Entity_Id;
In_State : Processing_In_State);
pragma Inline (Record_Invocation_Relation);
-- Record an invocation relation with invoker Invk_Id and target Targ_Id
-- by creating an entry for it in the ALI file of the main unit. Formal
-- In_State denotes the current state of the Processing phase.
procedure Set_Is_Saved_Construct
(Constr : Entity_Id;
Val : Boolean := True);
pragma Inline (Set_Is_Saved_Construct);
-- Mark invocation construct Constr as declared in the ALI file of the
-- main unit depending on value Val.
procedure Set_Is_Saved_Relation
(Rel : Invoker_Target_Relation;
Val : Boolean := True);
pragma Inline (Set_Is_Saved_Relation);
-- Mark simple invocation relation Rel as recorded in the ALI file of
-- the main unit depending on value Val.
function Target_Of
(Pos : Active_Scenario_Pos;
In_State : Processing_In_State) return Entity_Id;
pragma Inline (Target_Of);
-- Given position within the active scenario stack Pos, obtain the
-- target of the indicated scenario. In_State is the current state
-- of the Processing phase.
procedure Traverse_Invocation_Body
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Traverse_Invocation_Body);
-- Traverse subprogram body N looking for suitable invocation scenarios
-- that need to be processed for invocation graph recording purposes.
-- In_State is the current state of the Processing phase.
procedure Write_Invocation_Path (In_State : Processing_In_State);
pragma Inline (Write_Invocation_Path);
-- Write out a path represented by the active scenario on the stack to
-- standard output. In_State denotes the current state of the Processing
-- phase.
------------------------------------
-- Build_Elaborate_Body_Procedure --
------------------------------------
procedure Build_Elaborate_Body_Procedure is
Body_Decl : Node_Id;
Spec_Decl : Node_Id;
begin
-- Nothing to do when a previous call already created the procedure
if Present (Elab_Body_Id) then
return;
end if;
Spec_And_Body_From_Entity
(Id => Main_Unit_Entity,
Body_Decl => Body_Decl,
Spec_Decl => Spec_Decl);
pragma Assert (Present (Body_Decl));
Build_Elaborate_Procedure
(Proc_Id => Elab_Body_Id,
Proc_Nam => Name_B,
Loc => Sloc (Body_Decl));
end Build_Elaborate_Body_Procedure;
-------------------------------
-- Build_Elaborate_Procedure --
-------------------------------
procedure Build_Elaborate_Procedure
(Proc_Id : out Entity_Id;
Proc_Nam : Name_Id;
Loc : Source_Ptr)
is
Proc_Decl : Node_Id;
pragma Unreferenced (Proc_Decl);
begin
Proc_Id := Make_Defining_Identifier (Loc, Proc_Nam);
-- Partially decorate the elaboration procedure because it will not
-- be insertred into the tree and analyzed.
Set_Ekind (Proc_Id, E_Procedure);
Set_Etype (Proc_Id, Standard_Void_Type);
Set_Scope (Proc_Id, Unique_Entity (Main_Unit_Entity));
-- Create a dummy declaration for the elaboration procedure. The
-- declaration does not need to be syntactically legal, but must
-- carry an accurate source location.
Proc_Decl :=
Make_Subprogram_Body (Loc,
Specification =>
Make_Procedure_Specification (Loc,
Defining_Unit_Name => Proc_Id),
Declarations => No_List,
Handled_Statement_Sequence => Empty);
end Build_Elaborate_Procedure;
------------------------------------
-- Build_Elaborate_Spec_Procedure --
------------------------------------
procedure Build_Elaborate_Spec_Procedure is
Body_Decl : Node_Id;
Spec_Decl : Node_Id;
begin
-- Nothing to do when a previous call already created the procedure
if Present (Elab_Spec_Id) then
return;
end if;
Spec_And_Body_From_Entity
(Id => Main_Unit_Entity,
Body_Decl => Body_Decl,
Spec_Decl => Spec_Decl);
pragma Assert (Present (Spec_Decl));
Build_Elaborate_Procedure
(Proc_Id => Elab_Spec_Id,
Proc_Nam => Name_S,
Loc => Sloc (Spec_Decl));
end Build_Elaborate_Spec_Procedure;
---------------------------------
-- Build_Subprogram_Invocation --
---------------------------------
function Build_Subprogram_Invocation
(Subp_Id : Entity_Id) return Node_Id
is
Marker : constant Node_Id := Make_Call_Marker (Sloc (Subp_Id));
Subp_Decl : constant Node_Id := Unit_Declaration_Node (Subp_Id);
begin
-- Create a dummy call marker which invokes the subprogram
Set_Is_Declaration_Level_Node (Marker, False);
Set_Is_Dispatching_Call (Marker, False);
Set_Is_Elaboration_Checks_OK_Node (Marker, False);
Set_Is_Elaboration_Warnings_OK_Node (Marker, False);
Set_Is_Ignored_Ghost_Node (Marker, False);
Set_Is_Preelaborable_Call (Marker, False);
Set_Is_Source_Call (Marker, False);
Set_Is_SPARK_Mode_On_Node (Marker, False);
-- Invoke the uniform canonical entity of the subprogram
Set_Target (Marker, Canonical_Subprogram (Subp_Id));
-- Partially insert the marker into the tree
Set_Parent (Marker, Parent (Subp_Decl));
return Marker;
end Build_Subprogram_Invocation;
---------------------------
-- Build_Task_Activation --
---------------------------
function Build_Task_Activation
(Task_Typ : Entity_Id;
In_State : Processing_In_State) return Node_Id
is
Loc : constant Source_Ptr := Sloc (Task_Typ);
Marker : constant Node_Id := Make_Call_Marker (Loc);
Task_Decl : constant Node_Id := Unit_Declaration_Node (Task_Typ);
Activ_Id : Entity_Id;
Marker_Rep_Id : Scenario_Rep_Id;
Task_Obj : Entity_Id;
Task_Objs : NE_List.Doubly_Linked_List;
begin
-- Create a dummy call marker which activates some tasks
Set_Is_Declaration_Level_Node (Marker, False);
Set_Is_Dispatching_Call (Marker, False);
Set_Is_Elaboration_Checks_OK_Node (Marker, False);
Set_Is_Elaboration_Warnings_OK_Node (Marker, False);
Set_Is_Ignored_Ghost_Node (Marker, False);
Set_Is_Preelaborable_Call (Marker, False);
Set_Is_Source_Call (Marker, False);
Set_Is_SPARK_Mode_On_Node (Marker, False);
-- Invoke the appropriate version of Activate_Tasks
if Restricted_Profile then
Activ_Id := RTE (RE_Activate_Restricted_Tasks);
else
Activ_Id := RTE (RE_Activate_Tasks);
end if;
Set_Target (Marker, Activ_Id);
-- Partially insert the marker into the tree
Set_Parent (Marker, Parent (Task_Decl));
-- Create a dummy task object. Partially decorate the object because
-- it will not be inserted into the tree and analyzed.
Task_Obj := Make_Temporary (Loc, 'T');
Set_Ekind (Task_Obj, E_Variable);
Set_Etype (Task_Obj, Task_Typ);
-- Associate the dummy task object with the activation call
Task_Objs := NE_List.Create;
NE_List.Append (Task_Objs, Task_Obj);
Marker_Rep_Id := Scenario_Representation_Of (Marker, In_State);
Set_Activated_Task_Objects (Marker_Rep_Id, Task_Objs);
Set_Activated_Task_Type (Marker_Rep_Id, Task_Typ);
return Marker;
end Build_Task_Activation;
----------------------------------
-- Declare_Invocation_Construct --
----------------------------------
procedure Declare_Invocation_Construct
(Constr_Id : Entity_Id;
In_State : Processing_In_State)
is
function Body_Placement_Of
(Id : Entity_Id) return Declaration_Placement_Kind;
pragma Inline (Body_Placement_Of);
-- Obtain the placement of arbitrary entity Id's body
function Declaration_Placement_Of_Node
(N : Node_Id) return Declaration_Placement_Kind;
pragma Inline (Declaration_Placement_Of_Node);
-- Obtain the placement of arbitrary node N
function Kind_Of (Id : Entity_Id) return Invocation_Construct_Kind;
pragma Inline (Kind_Of);
-- Obtain the invocation construct kind of arbitrary entity Id
function Spec_Placement_Of
(Id : Entity_Id) return Declaration_Placement_Kind;
pragma Inline (Spec_Placement_Of);
-- Obtain the placement of arbitrary entity Id's spec
-----------------------
-- Body_Placement_Of --
-----------------------
function Body_Placement_Of
(Id : Entity_Id) return Declaration_Placement_Kind
is
Id_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Id, In_State);
Body_Decl : constant Node_Id := Body_Declaration (Id_Rep);
Spec_Decl : constant Node_Id := Spec_Declaration (Id_Rep);
begin
-- The entity has a body
if Present (Body_Decl) then
return Declaration_Placement_Of_Node (Body_Decl);
-- Otherwise the entity must have a spec
else
pragma Assert (Present (Spec_Decl));
return Declaration_Placement_Of_Node (Spec_Decl);
end if;
end Body_Placement_Of;
-----------------------------------
-- Declaration_Placement_Of_Node --
-----------------------------------
function Declaration_Placement_Of_Node
(N : Node_Id) return Declaration_Placement_Kind
is
Main_Unit_Id : constant Entity_Id := Main_Unit_Entity;
N_Unit_Id : constant Entity_Id := Find_Top_Unit (N);
begin
-- The node is in the main unit, its placement depends on the main
-- unit kind.
if N_Unit_Id = Main_Unit_Id then
-- The main unit is a body
if Ekind (Main_Unit_Id) in E_Package_Body | E_Subprogram_Body
then
return In_Body;
-- The main unit is a stand-alone subprogram body
elsif Ekind (Main_Unit_Id) in E_Function | E_Procedure
and then Nkind (Unit_Declaration_Node (Main_Unit_Id)) =
N_Subprogram_Body
then
return In_Body;
-- Otherwise the main unit is a spec
else
return In_Spec;
end if;
-- Otherwise the node is in the complementary unit of the main
-- unit. The main unit is a body, the node is in the spec.
elsif Ekind (Main_Unit_Id) in E_Package_Body | E_Subprogram_Body
then
return In_Spec;
-- The main unit is a spec, the node is in the body
else
return In_Body;
end if;
end Declaration_Placement_Of_Node;
-------------
-- Kind_Of --
-------------
function Kind_Of (Id : Entity_Id) return Invocation_Construct_Kind is
begin
if Id = Elab_Body_Id then
return Elaborate_Body_Procedure;
elsif Id = Elab_Spec_Id then
return Elaborate_Spec_Procedure;
else
return Regular_Construct;
end if;
end Kind_Of;
-----------------------
-- Spec_Placement_Of --
-----------------------
function Spec_Placement_Of
(Id : Entity_Id) return Declaration_Placement_Kind
is
Id_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Id, In_State);
Body_Decl : constant Node_Id := Body_Declaration (Id_Rep);
Spec_Decl : constant Node_Id := Spec_Declaration (Id_Rep);
begin
-- The entity has a spec
if Present (Spec_Decl) then
return Declaration_Placement_Of_Node (Spec_Decl);
-- Otherwise the entity must have a body
else
pragma Assert (Present (Body_Decl));
return Declaration_Placement_Of_Node (Body_Decl);
end if;
end Spec_Placement_Of;
-- Start of processing for Declare_Invocation_Construct
begin
-- Nothing to do when the construct has already been declared in the
-- ALI file.
if Is_Saved_Construct (Constr_Id) then
return;
end if;
-- Mark the construct as declared in the ALI file
Set_Is_Saved_Construct (Constr_Id);
-- Add the construct in the ALI file
Add_Invocation_Construct
(Body_Placement => Body_Placement_Of (Constr_Id),
Kind => Kind_Of (Constr_Id),
Signature => Signature_Of (Constr_Id),
Spec_Placement => Spec_Placement_Of (Constr_Id),
Update_Units => False);
end Declare_Invocation_Construct;
-------------------------------
-- Finalize_Invocation_Graph --
-------------------------------
procedure Finalize_Invocation_Graph is
begin
NE_Set.Destroy (Saved_Constructs_Set);
IR_Set.Destroy (Saved_Relations_Set);
end Finalize_Invocation_Graph;
----------
-- Hash --
----------
function Hash (Key : Invoker_Target_Relation) return Bucket_Range_Type is
pragma Assert (Present (Key.Invoker));
pragma Assert (Present (Key.Target));
begin
return
Hash_Two_Keys
(Bucket_Range_Type (Key.Invoker),
Bucket_Range_Type (Key.Target));
end Hash;
---------------------------------
-- Initialize_Invocation_Graph --
---------------------------------
procedure Initialize_Invocation_Graph is
begin
Saved_Constructs_Set := NE_Set.Create (100);
Saved_Relations_Set := IR_Set.Create (200);
end Initialize_Invocation_Graph;
-----------------------------------
-- Invocation_Graph_Recording_OK --
-----------------------------------
function Invocation_Graph_Recording_OK return Boolean is
Main_Cunit : constant Node_Id := Cunit (Main_Unit);
begin
-- Nothing to do when compiling for GNATprove because the invocation
-- graph is not needed.
if GNATprove_Mode then
return False;
-- Nothing to do when the compilation will not produce an ALI file
elsif Serious_Errors_Detected > 0 then
return False;
-- Nothing to do when the main unit requires a body. Processing the
-- completing body will create the ALI file for the unit and record
-- the invocation graph.
elsif Body_Required (Main_Cunit) then
return False;
end if;
return True;
end Invocation_Graph_Recording_OK;
----------------------------
-- Is_Invocation_Scenario --
----------------------------
function Is_Invocation_Scenario (N : Node_Id) return Boolean is
begin
return
Is_Suitable_Access_Taken (N)
or else Is_Suitable_Call (N)
or else Is_Suitable_Instantiation (N);
end Is_Invocation_Scenario;
--------------------------
-- Is_Invocation_Target --
--------------------------
function Is_Invocation_Target (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must either come from source, or denote an
-- Ada, bridge, or SPARK target.
return
Comes_From_Source (Id)
or else Is_Ada_Semantic_Target (Id)
or else Is_Bridge_Target (Id)
or else Is_SPARK_Semantic_Target (Id);
end Is_Invocation_Target;
------------------------
-- Is_Saved_Construct --
------------------------
function Is_Saved_Construct (Constr : Entity_Id) return Boolean is
pragma Assert (Present (Constr));
begin
return NE_Set.Contains (Saved_Constructs_Set, Constr);
end Is_Saved_Construct;
-----------------------
-- Is_Saved_Relation --
-----------------------
function Is_Saved_Relation
(Rel : Invoker_Target_Relation) return Boolean
is
pragma Assert (Present (Rel.Invoker));
pragma Assert (Present (Rel.Target));
begin
return IR_Set.Contains (Saved_Relations_Set, Rel);
end Is_Saved_Relation;
--------------------------
-- Process_Declarations --
--------------------------
procedure Process_Declarations
(Decls : List_Id;
In_State : Processing_In_State)
is
Decl : Node_Id;
begin
Decl := First (Decls);
while Present (Decl) loop
-- Freeze node
if Nkind (Decl) = N_Freeze_Entity then
Process_Freeze_Node
(Fnode => Decl,
In_State => In_State);
-- Package (nested)
elsif Nkind (Decl) = N_Package_Declaration then
Process_Package_Declaration
(Pack_Decl => Decl,
In_State => In_State);
-- Protected type
elsif Nkind (Decl) in N_Protected_Type_Declaration
| N_Single_Protected_Declaration
then
Process_Protected_Type_Declaration
(Prot_Decl => Decl,
In_State => In_State);
-- Subprogram or entry
elsif Nkind (Decl) in N_Entry_Declaration
| N_Subprogram_Declaration
then
Process_Subprogram_Declaration
(Subp_Decl => Decl,
In_State => In_State);
-- Subprogram body (stand alone)
elsif Nkind (Decl) = N_Subprogram_Body
and then No (Corresponding_Spec (Decl))
then
Process_Subprogram_Declaration
(Subp_Decl => Decl,
In_State => In_State);
-- Subprogram instantiation
elsif Nkind (Decl) in N_Subprogram_Instantiation then
Process_Subprogram_Instantiation
(Inst => Decl,
In_State => In_State);
-- Task type
elsif Nkind (Decl) in N_Single_Task_Declaration
| N_Task_Type_Declaration
then
Process_Task_Type_Declaration
(Task_Decl => Decl,
In_State => In_State);
-- Task type (derived)
elsif Nkind (Decl) = N_Full_Type_Declaration
and then Is_Task_Type (Defining_Entity (Decl))
then
Process_Task_Type_Declaration
(Task_Decl => Decl,
In_State => In_State);
end if;
Next (Decl);
end loop;
end Process_Declarations;
-------------------------
-- Process_Freeze_Node --
-------------------------
procedure Process_Freeze_Node
(Fnode : Node_Id;
In_State : Processing_In_State)
is
begin
Process_Declarations
(Decls => Actions (Fnode),
In_State => In_State);
end Process_Freeze_Node;
-----------------------------------
-- Process_Invocation_Activation --
-----------------------------------
procedure Process_Invocation_Activation
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
Obj_Id : Entity_Id;
Obj_Rep : Target_Rep_Id;
Task_Typ : Entity_Id;
Task_Rep : Target_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Call);
pragma Unreferenced (Call_Rep);
pragma Unreferenced (Obj_Id);
pragma Unreferenced (Obj_Rep);
begin
-- Nothing to do when the task type appears within an internal unit
if In_Internal_Unit (Task_Typ) then
return;
end if;
-- The task type being activated is within the main unit. Extend the
-- DFS traversal into its body.
if In_Extended_Main_Code_Unit (Task_Typ) then
Traverse_Invocation_Body
(N => Body_Declaration (Task_Rep),
In_State => In_State);
-- The task type being activated resides within an external unit
--
-- Main unit External unit
-- +-----------+ +-------------+
-- | | | |
-- | Start ------------> Task_Typ |
-- | | | |
-- +-----------+ +-------------+
--
-- Record the invocation path which originates from Start and reaches
-- the task type.
else
Record_Invocation_Path (In_State);
end if;
end Process_Invocation_Activation;
---------------------------------------
-- Process_Invocation_Body_Scenarios --
---------------------------------------
procedure Process_Invocation_Body_Scenarios is
Iter : NE_Set.Iterator := Iterate_Library_Body_Scenarios;
begin
Process_Invocation_Scenarios
(Iter => Iter,
In_State => Invocation_Body_State);
end Process_Invocation_Body_Scenarios;
-----------------------------
-- Process_Invocation_Call --
-----------------------------
procedure Process_Invocation_Call
(Call : Node_Id;
Call_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Call);
Subp_Id : constant Entity_Id := Target (Call_Rep);
Subp_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Subp_Id, In_State);
begin
-- Nothing to do when the subprogram appears within an internal unit
if In_Internal_Unit (Subp_Id) then
return;
-- Nothing to do for an abstract subprogram because it has no body to
-- examine.
elsif Ekind (Subp_Id) in E_Function | E_Procedure
and then Is_Abstract_Subprogram (Subp_Id)
then
return;
-- Nothin to do for a formal subprogram because it has no body to
-- examine.
elsif Is_Formal_Subprogram (Subp_Id) then
return;
end if;
-- The subprogram being called is within the main unit. Extend the
-- DFS traversal into its barrier function and body.
if In_Extended_Main_Code_Unit (Subp_Id) then
if Ekind (Subp_Id) in E_Entry | E_Entry_Family | E_Procedure then
Traverse_Invocation_Body
(N => Barrier_Body_Declaration (Subp_Rep),
In_State => In_State);
end if;
Traverse_Invocation_Body
(N => Body_Declaration (Subp_Rep),
In_State => In_State);
-- The subprogram being called resides within an external unit
--
-- Main unit External unit
-- +-----------+ +-------------+
-- | | | |
-- | Start ------------> Subp_Id |
-- | | | |
-- +-----------+ +-------------+
--
-- Record the invocation path which originates from Start and reaches
-- the subprogram.
else
Record_Invocation_Path (In_State);
end if;
end Process_Invocation_Call;
--------------------------------------
-- Process_Invocation_Instantiation --
--------------------------------------
procedure Process_Invocation_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Inst);
Gen_Id : constant Entity_Id := Target (Inst_Rep);
begin
-- Nothing to do when the generic appears within an internal unit
if In_Internal_Unit (Gen_Id) then
return;
end if;
-- The generic being instantiated resides within an external unit
--
-- Main unit External unit
-- +-----------+ +-------------+
-- | | | |
-- | Start ------------> Generic |
-- | | | |
-- +-----------+ +-------------+
--
-- Record the invocation path which originates from Start and reaches
-- the generic.
if not In_Extended_Main_Code_Unit (Gen_Id) then
Record_Invocation_Path (In_State);
end if;
end Process_Invocation_Instantiation;
---------------------------------
-- Process_Invocation_Scenario --
---------------------------------
procedure Process_Invocation_Scenario
(N : Node_Id;
In_State : Processing_In_State)
is
Scen : constant Node_Id := Scenario (N);
Scen_Rep : Scenario_Rep_Id;
begin
-- Add the current scenario to the stack of active scenarios
Push_Active_Scenario (Scen);
-- Call or task activation
if Is_Suitable_Call (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
-- Routine Build_Call_Marker creates call markers regardless of
-- whether the call occurs within the main unit or not. This way
-- the serialization of internal names is kept consistent. Only
-- call markers found within the main unit must be processed.
if In_Main_Context (Scen) then
Scen_Rep := Scenario_Representation_Of (Scen, In_State);
if Kind (Scen_Rep) = Call_Scenario then
Process_Invocation_Call
(Call => Scen,
Call_Rep => Scen_Rep,
In_State => In_State);
else
pragma Assert (Kind (Scen_Rep) = Task_Activation_Scenario);
Process_Activation
(Call => Scen,
Call_Rep => Scen_Rep,
Processor => Process_Invocation_Activation'Access,
In_State => In_State);
end if;
end if;
-- Instantiation
elsif Is_Suitable_Instantiation (Scen) then
Process_Invocation_Instantiation
(Inst => Scen,
Inst_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
end if;
-- Remove the current scenario from the stack of active scenarios
-- once all invocation constructs and paths have been saved.
Pop_Active_Scenario (Scen);
end Process_Invocation_Scenario;
----------------------------------
-- Process_Invocation_Scenarios --
----------------------------------
procedure Process_Invocation_Scenarios
(Iter : in out NE_Set.Iterator;
In_State : Processing_In_State)
is
N : Node_Id;
begin
while NE_Set.Has_Next (Iter) loop
NE_Set.Next (Iter, N);
-- Reset the traversed status of all subprogram bodies because the
-- current invocation scenario acts as a new DFS traversal root.
Reset_Traversed_Bodies;
Process_Invocation_Scenario (N, In_State);
end loop;
end Process_Invocation_Scenarios;
---------------------------------------
-- Process_Invocation_Spec_Scenarios --
---------------------------------------
procedure Process_Invocation_Spec_Scenarios is
Iter : NE_Set.Iterator := Iterate_Library_Spec_Scenarios;
begin
Process_Invocation_Scenarios
(Iter => Iter,
In_State => Invocation_Spec_State);
end Process_Invocation_Spec_Scenarios;
-----------------------
-- Process_Main_Unit --
-----------------------
procedure Process_Main_Unit is
Unit_Decl : constant Node_Id := Unit (Cunit (Main_Unit));
Spec_Id : Entity_Id;
begin
-- The main unit is a [generic] package body
if Nkind (Unit_Decl) = N_Package_Body then
Spec_Id := Corresponding_Spec (Unit_Decl);
pragma Assert (Present (Spec_Id));
Process_Package_Declaration
(Pack_Decl => Unit_Declaration_Node (Spec_Id),
In_State => Invocation_Construct_State);
-- The main unit is a [generic] package declaration
elsif Nkind (Unit_Decl) = N_Package_Declaration then
Process_Package_Declaration
(Pack_Decl => Unit_Decl,
In_State => Invocation_Construct_State);
-- The main unit is a [generic] subprogram body
elsif Nkind (Unit_Decl) = N_Subprogram_Body then
Spec_Id := Corresponding_Spec (Unit_Decl);
-- The body completes a previous declaration
if Present (Spec_Id) then
Process_Subprogram_Declaration
(Subp_Decl => Unit_Declaration_Node (Spec_Id),
In_State => Invocation_Construct_State);
-- Otherwise the body is stand-alone
else
Process_Subprogram_Declaration
(Subp_Decl => Unit_Decl,
In_State => Invocation_Construct_State);
end if;
-- The main unit is a subprogram instantiation
elsif Nkind (Unit_Decl) in N_Subprogram_Instantiation then
Process_Subprogram_Instantiation
(Inst => Unit_Decl,
In_State => Invocation_Construct_State);
-- The main unit is an imported subprogram declaration
elsif Nkind (Unit_Decl) = N_Subprogram_Declaration then
Process_Subprogram_Declaration
(Subp_Decl => Unit_Decl,
In_State => Invocation_Construct_State);
end if;
end Process_Main_Unit;
---------------------------------
-- Process_Package_Declaration --
---------------------------------
procedure Process_Package_Declaration
(Pack_Decl : Node_Id;
In_State : Processing_In_State)
is
Body_Id : constant Entity_Id := Corresponding_Body (Pack_Decl);
Spec : constant Node_Id := Specification (Pack_Decl);
Spec_Id : constant Entity_Id := Defining_Entity (Pack_Decl);
begin
-- Add a declaration for the generic package in the ALI of the main
-- unit in case a client unit instantiates it.
if Ekind (Spec_Id) = E_Generic_Package then
Declare_Invocation_Construct
(Constr_Id => Spec_Id,
In_State => In_State);
-- Otherwise inspect the visible and private declarations of the
-- package for invocation constructs.
else
Process_Declarations
(Decls => Visible_Declarations (Spec),
In_State => In_State);
Process_Declarations
(Decls => Private_Declarations (Spec),
In_State => In_State);
-- The package body containst at least one generic unit or an
-- inlinable subprogram. Such constructs may grant clients of
-- the main unit access to the private enclosing contexts of
-- the constructs. Process the main unit body to discover and
-- encode relevant invocation constructs and relations that
-- may ultimately reach an external unit.
if Present (Body_Id)
and then Save_Invocation_Graph_Of_Body (Cunit (Main_Unit))
then
Process_Declarations
(Decls => Declarations (Unit_Declaration_Node (Body_Id)),
In_State => In_State);
end if;
end if;
end Process_Package_Declaration;
----------------------------------------
-- Process_Protected_Type_Declaration --
----------------------------------------
procedure Process_Protected_Type_Declaration
(Prot_Decl : Node_Id;
In_State : Processing_In_State)
is
Prot_Def : constant Node_Id := Protected_Definition (Prot_Decl);
begin
if Present (Prot_Def) then
Process_Declarations
(Decls => Visible_Declarations (Prot_Def),
In_State => In_State);
end if;
end Process_Protected_Type_Declaration;
------------------------------------
-- Process_Subprogram_Declaration --
------------------------------------
procedure Process_Subprogram_Declaration
(Subp_Decl : Node_Id;
In_State : Processing_In_State)
is
Subp_Id : constant Entity_Id := Defining_Entity (Subp_Decl);
begin
-- Nothing to do when the subprogram is not an invocation target
if not Is_Invocation_Target (Subp_Id) then
return;
end if;
-- Add a declaration for the subprogram in the ALI file of the main
-- unit in case a client unit calls or instantiates it.
Declare_Invocation_Construct
(Constr_Id => Subp_Id,
In_State => In_State);
-- Do not process subprograms without a body because they do not
-- contain any invocation scenarios.
if Is_Bodiless_Subprogram (Subp_Id) then
null;
-- Do not process generic subprograms because generics must not be
-- examined.
elsif Is_Generic_Subprogram (Subp_Id) then
null;
-- Otherwise create a dummy scenario which calls the subprogram to
-- act as a root for a DFS traversal.
else
-- Reset the traversed status of all subprogram bodies because the
-- subprogram acts as a new DFS traversal root.
Reset_Traversed_Bodies;
Process_Invocation_Scenario
(N => Build_Subprogram_Invocation (Subp_Id),
In_State => In_State);
end if;
end Process_Subprogram_Declaration;
--------------------------------------
-- Process_Subprogram_Instantiation --
--------------------------------------
procedure Process_Subprogram_Instantiation
(Inst : Node_Id;
In_State : Processing_In_State)
is
begin
-- Add a declaration for the instantiation in the ALI file of the
-- main unit in case a client unit calls it.
Declare_Invocation_Construct
(Constr_Id => Defining_Entity (Inst),
In_State => In_State);
end Process_Subprogram_Instantiation;
-----------------------------------
-- Process_Task_Type_Declaration --
-----------------------------------
procedure Process_Task_Type_Declaration
(Task_Decl : Node_Id;
In_State : Processing_In_State)
is
Task_Typ : constant Entity_Id := Defining_Entity (Task_Decl);
Task_Def : Node_Id;
begin
-- Add a declaration for the task type the ALI file of the main unit
-- in case a client unit creates a task object and activates it.
Declare_Invocation_Construct
(Constr_Id => Task_Typ,
In_State => In_State);
-- Process the entries of the task type because they represent valid
-- entry points into the task body.
if Nkind (Task_Decl) in N_Single_Task_Declaration
| N_Task_Type_Declaration
then
Task_Def := Task_Definition (Task_Decl);
if Present (Task_Def) then
Process_Declarations
(Decls => Visible_Declarations (Task_Def),
In_State => In_State);
end if;
end if;
-- Reset the traversed status of all subprogram bodies because the
-- task type acts as a new DFS traversal root.
Reset_Traversed_Bodies;
-- Create a dummy scenario which activates an anonymous object of the
-- task type to acts as a root of a DFS traversal.
Process_Invocation_Scenario
(N => Build_Task_Activation (Task_Typ, In_State),
In_State => In_State);
end Process_Task_Type_Declaration;
---------------------------------
-- Record_Full_Invocation_Path --
---------------------------------
procedure Record_Full_Invocation_Path (In_State : Processing_In_State) is
package Scenarios renames Active_Scenario_Stack;
begin
-- The path originates from the elaboration of the body. Add an extra
-- relation from the elaboration body procedure to the first active
-- scenario.
if In_State.Processing = Invocation_Body_Processing then
Build_Elaborate_Body_Procedure;
Record_Invocation_Relation
(Invk_Id => Elab_Body_Id,
Targ_Id => Target_Of (Scenarios.First, In_State),
In_State => In_State);
-- The path originates from the elaboration of the spec. Add an extra
-- relation from the elaboration spec procedure to the first active
-- scenario.
elsif In_State.Processing = Invocation_Spec_Processing then
Build_Elaborate_Spec_Procedure;
Record_Invocation_Relation
(Invk_Id => Elab_Spec_Id,
Targ_Id => Target_Of (Scenarios.First, In_State),
In_State => In_State);
end if;
-- Record individual relations formed by pairs of scenarios
for Index in Scenarios.First .. Scenarios.Last - 1 loop
Record_Invocation_Relation
(Invk_Id => Target_Of (Index, In_State),
Targ_Id => Target_Of (Index + 1, In_State),
In_State => In_State);
end loop;
end Record_Full_Invocation_Path;
-----------------------------
-- Record_Invocation_Graph --
-----------------------------
procedure Record_Invocation_Graph is
begin
-- Nothing to do when the invocation graph is not recorded
if not Invocation_Graph_Recording_OK then
return;
end if;
-- Save the encoding format used to capture information about the
-- invocation constructs and relations in the ALI file of the main
-- unit.
Record_Invocation_Graph_Encoding;
-- Examine all library level invocation scenarios and perform DFS
-- traversals from each one. Encode a path in the ALI file of the
-- main unit if it reaches into an external unit.
Process_Invocation_Body_Scenarios;
Process_Invocation_Spec_Scenarios;
-- Examine all invocation constructs within the spec and body of the
-- main unit and perform DFS traversals from each one. Encode a path
-- in the ALI file of the main unit if it reaches into an external
-- unit.
Process_Main_Unit;
end Record_Invocation_Graph;
--------------------------------------
-- Record_Invocation_Graph_Encoding --
--------------------------------------
procedure Record_Invocation_Graph_Encoding is
Kind : Invocation_Graph_Encoding_Kind := No_Encoding;
begin
-- Switch -gnatd_F (encode full invocation paths in ALI files) is in
-- effect.
if Debug_Flag_Underscore_FF then
Kind := Full_Path_Encoding;
else
Kind := Endpoints_Encoding;
end if;
-- Save the encoding format in the ALI file of the main unit
Set_Invocation_Graph_Encoding
(Kind => Kind,
Update_Units => False);
end Record_Invocation_Graph_Encoding;
----------------------------
-- Record_Invocation_Path --
----------------------------
procedure Record_Invocation_Path (In_State : Processing_In_State) is
package Scenarios renames Active_Scenario_Stack;
begin
-- Save a path when the active scenario stack contains at least one
-- invocation scenario.
if Scenarios.Last - Scenarios.First < 0 then
return;
end if;
-- Register all relations in the path when switch -gnatd_F (encode
-- full invocation paths in ALI files) is in effect.
if Debug_Flag_Underscore_FF then
Record_Full_Invocation_Path (In_State);
-- Otherwise register a single relation
else
Record_Simple_Invocation_Path (In_State);
end if;
Write_Invocation_Path (In_State);
end Record_Invocation_Path;
--------------------------------
-- Record_Invocation_Relation --
--------------------------------
procedure Record_Invocation_Relation
(Invk_Id : Entity_Id;
Targ_Id : Entity_Id;
In_State : Processing_In_State)
is
pragma Assert (Present (Invk_Id));
pragma Assert (Present (Targ_Id));
procedure Get_Invocation_Attributes
(Extra : out Entity_Id;
Kind : out Invocation_Kind);
pragma Inline (Get_Invocation_Attributes);
-- Return the additional entity used in error diagnostics in Extra
-- and the invocation kind in Kind which pertain to the invocation
-- relation with invoker Invk_Id and target Targ_Id.
-------------------------------
-- Get_Invocation_Attributes --
-------------------------------
procedure Get_Invocation_Attributes
(Extra : out Entity_Id;
Kind : out Invocation_Kind)
is
Targ_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Targ_Id, In_State);
Spec_Decl : constant Node_Id := Spec_Declaration (Targ_Rep);
begin
-- Accept within a task body
if Is_Accept_Alternative_Proc (Targ_Id) then
Extra := Receiving_Entry (Targ_Id);
Kind := Accept_Alternative;
-- Activation of a task object
elsif Is_Activation_Proc (Targ_Id)
or else Is_Task_Type (Targ_Id)
then
Extra := Empty;
Kind := Task_Activation;
-- Controlled adjustment actions
elsif Is_Controlled_Proc (Targ_Id, Name_Adjust) then
Extra := First_Formal_Type (Targ_Id);
Kind := Controlled_Adjustment;
-- Controlled finalization actions
elsif Is_Controlled_Proc (Targ_Id, Name_Finalize)
or else Is_Finalizer_Proc (Targ_Id)
then
Extra := First_Formal_Type (Targ_Id);
Kind := Controlled_Finalization;
-- Controlled initialization actions
elsif Is_Controlled_Proc (Targ_Id, Name_Initialize) then
Extra := First_Formal_Type (Targ_Id);
Kind := Controlled_Initialization;
-- Default_Initial_Condition verification
elsif Is_Default_Initial_Condition_Proc (Targ_Id) then
Extra := First_Formal_Type (Targ_Id);
Kind := Default_Initial_Condition_Verification;
-- Initialization of object
elsif Is_Init_Proc (Targ_Id) then
Extra := First_Formal_Type (Targ_Id);
Kind := Type_Initialization;
-- Initial_Condition verification
elsif Is_Initial_Condition_Proc (Targ_Id) then
Extra := First_Formal_Type (Targ_Id);
Kind := Initial_Condition_Verification;
-- Instantiation
elsif Is_Generic_Unit (Targ_Id) then
Extra := Empty;
Kind := Instantiation;
-- Internal controlled adjustment actions
elsif Is_TSS (Targ_Id, TSS_Deep_Adjust) then
Extra := First_Formal_Type (Targ_Id);
Kind := Internal_Controlled_Adjustment;
-- Internal controlled finalization actions
elsif Is_TSS (Targ_Id, TSS_Deep_Finalize) then
Extra := First_Formal_Type (Targ_Id);
Kind := Internal_Controlled_Finalization;
-- Internal controlled initialization actions
elsif Is_TSS (Targ_Id, TSS_Deep_Initialize) then
Extra := First_Formal_Type (Targ_Id);
Kind := Internal_Controlled_Initialization;
-- Invariant verification
elsif Is_Invariant_Proc (Targ_Id)
or else Is_Partial_Invariant_Proc (Targ_Id)
then
Extra := First_Formal_Type (Targ_Id);
Kind := Invariant_Verification;
-- Postcondition verification
elsif Is_Postconditions_Proc (Targ_Id) then
Extra := Find_Enclosing_Scope (Spec_Decl);
Kind := Postcondition_Verification;
-- Protected entry call
elsif Is_Protected_Entry (Targ_Id) then
Extra := Empty;
Kind := Protected_Entry_Call;
-- Protected subprogram call
elsif Is_Protected_Subp (Targ_Id) then
Extra := Empty;
Kind := Protected_Subprogram_Call;
-- Task entry call
elsif Is_Task_Entry (Targ_Id) then
Extra := Empty;
Kind := Task_Entry_Call;
-- Entry, operator, or subprogram call. This case must come last
-- because most invocations above are variations of this case.
elsif Ekind (Targ_Id) in
E_Entry | E_Function | E_Operator | E_Procedure
then
Extra := Empty;
Kind := Call;
else
pragma Assert (False);
Extra := Empty;
Kind := No_Invocation;
end if;
end Get_Invocation_Attributes;
-- Local variables
Extra : Entity_Id;
Extra_Nam : Name_Id;
Kind : Invocation_Kind;
Rel : Invoker_Target_Relation;
-- Start of processing for Record_Invocation_Relation
begin
Rel.Invoker := Invk_Id;
Rel.Target := Targ_Id;
-- Nothing to do when the invocation relation has already been
-- recorded in ALI file of the main unit.
if Is_Saved_Relation (Rel) then
return;
end if;
-- Mark the relation as recorded in the ALI file
Set_Is_Saved_Relation (Rel);
-- Declare the invoker in the ALI file
Declare_Invocation_Construct
(Constr_Id => Invk_Id,
In_State => In_State);
-- Obtain the invocation-specific attributes of the relation
Get_Invocation_Attributes (Extra, Kind);
-- Certain invocations lack an extra entity used in error diagnostics
if Present (Extra) then
Extra_Nam := Chars (Extra);
else
Extra_Nam := No_Name;
end if;
-- Add the relation in the ALI file
Add_Invocation_Relation
(Extra => Extra_Nam,
Invoker => Signature_Of (Invk_Id),
Kind => Kind,
Target => Signature_Of (Targ_Id),
Update_Units => False);
end Record_Invocation_Relation;
-----------------------------------
-- Record_Simple_Invocation_Path --
-----------------------------------
procedure Record_Simple_Invocation_Path
(In_State : Processing_In_State)
is
package Scenarios renames Active_Scenario_Stack;
Last_Targ : constant Entity_Id :=
Target_Of (Scenarios.Last, In_State);
First_Targ : Entity_Id;
begin
-- The path originates from the elaboration of the body. Add an extra
-- relation from the elaboration body procedure to the first active
-- scenario.
if In_State.Processing = Invocation_Body_Processing then
Build_Elaborate_Body_Procedure;
First_Targ := Elab_Body_Id;
-- The path originates from the elaboration of the spec. Add an extra
-- relation from the elaboration spec procedure to the first active
-- scenario.
elsif In_State.Processing = Invocation_Spec_Processing then
Build_Elaborate_Spec_Procedure;
First_Targ := Elab_Spec_Id;
else
First_Targ := Target_Of (Scenarios.First, In_State);
end if;
-- Record a single relation from the first to the last scenario
if First_Targ /= Last_Targ then
Record_Invocation_Relation
(Invk_Id => First_Targ,
Targ_Id => Last_Targ,
In_State => In_State);
end if;
end Record_Simple_Invocation_Path;
----------------------------
-- Set_Is_Saved_Construct --
----------------------------
procedure Set_Is_Saved_Construct
(Constr : Entity_Id;
Val : Boolean := True)
is
pragma Assert (Present (Constr));
begin
if Val then
NE_Set.Insert (Saved_Constructs_Set, Constr);
else
NE_Set.Delete (Saved_Constructs_Set, Constr);
end if;
end Set_Is_Saved_Construct;
---------------------------
-- Set_Is_Saved_Relation --
---------------------------
procedure Set_Is_Saved_Relation
(Rel : Invoker_Target_Relation;
Val : Boolean := True)
is
begin
if Val then
IR_Set.Insert (Saved_Relations_Set, Rel);
else
IR_Set.Delete (Saved_Relations_Set, Rel);
end if;
end Set_Is_Saved_Relation;
------------------
-- Signature_Of --
------------------
function Signature_Of (Id : Entity_Id) return Invocation_Signature_Id is
Loc : constant Source_Ptr := Sloc (Id);
function Instantiation_Locations return Name_Id;
pragma Inline (Instantiation_Locations);
-- Create a concatenation of all lines and colums of each instance
-- where source location Loc appears. Return No_Name if no instances
-- exist.
function Qualified_Scope return Name_Id;
pragma Inline (Qualified_Scope);
-- Obtain the qualified name of Id's scope
-----------------------------
-- Instantiation_Locations --
-----------------------------
function Instantiation_Locations return Name_Id is
Buffer : Bounded_String (2052);
Inst : Source_Ptr;
Loc_Nam : Name_Id;
SFI : Source_File_Index;
begin
SFI := Get_Source_File_Index (Loc);
Inst := Instantiation (SFI);
-- The location is within an instance. Construct a concatenation
-- of all lines and colums of each individual instance using the
-- following format:
--
-- line1_column1_line2_column2_ ... _lineN_columnN
if Inst /= No_Location then
loop
Append (Buffer, Nat (Get_Logical_Line_Number (Inst)));
Append (Buffer, '_');
Append (Buffer, Nat (Get_Column_Number (Inst)));
SFI := Get_Source_File_Index (Inst);
Inst := Instantiation (SFI);
exit when Inst = No_Location;
Append (Buffer, '_');
end loop;
Loc_Nam := Name_Find (Buffer);
return Loc_Nam;
-- Otherwise there no instances are involved
else
return No_Name;
end if;
end Instantiation_Locations;
---------------------
-- Qualified_Scope --
---------------------
function Qualified_Scope return Name_Id is
Scop : Entity_Id;
begin
Scop := Scope (Id);
-- The entity appears within an anonymous concurrent type created
-- for a single protected or task type declaration. Use the entity
-- of the anonymous object as it represents the original scope.
if Is_Concurrent_Type (Scop)
and then Present (Anonymous_Object (Scop))
then
Scop := Anonymous_Object (Scop);
end if;
return Get_Qualified_Name (Scop);
end Qualified_Scope;
-- Start of processing for Signature_Of
begin
return
Invocation_Signature_Of
(Column => Nat (Get_Column_Number (Loc)),
Line => Nat (Get_Logical_Line_Number (Loc)),
Locations => Instantiation_Locations,
Name => Chars (Id),
Scope => Qualified_Scope);
end Signature_Of;
---------------
-- Target_Of --
---------------
function Target_Of
(Pos : Active_Scenario_Pos;
In_State : Processing_In_State) return Entity_Id
is
package Scenarios renames Active_Scenario_Stack;
-- Ensure that the position is within the bounds of the active
-- scenario stack.
pragma Assert (Scenarios.First <= Pos);
pragma Assert (Pos <= Scenarios.Last);
Scen_Rep : constant Scenario_Rep_Id :=
Scenario_Representation_Of
(Scenarios.Table (Pos), In_State);
begin
-- The true target of an activation call is the current task type
-- rather than routine Activate_Tasks.
if Kind (Scen_Rep) = Task_Activation_Scenario then
return Activated_Task_Type (Scen_Rep);
else
return Target (Scen_Rep);
end if;
end Target_Of;
------------------------------
-- Traverse_Invocation_Body --
------------------------------
procedure Traverse_Invocation_Body
(N : Node_Id;
In_State : Processing_In_State)
is
begin
Traverse_Body
(N => N,
Requires_Processing => Is_Invocation_Scenario'Access,
Processor => Process_Invocation_Scenario'Access,
In_State => In_State);
end Traverse_Invocation_Body;
---------------------------
-- Write_Invocation_Path --
---------------------------
procedure Write_Invocation_Path (In_State : Processing_In_State) is
procedure Write_Target (Targ_Id : Entity_Id; Is_First : Boolean);
pragma Inline (Write_Target);
-- Write out invocation target Targ_Id to standard output. Flag
-- Is_First should be set when the target is first in a path.
-------------
-- Targ_Id --
-------------
procedure Write_Target (Targ_Id : Entity_Id; Is_First : Boolean) is
begin
if not Is_First then
Write_Str (" --> ");
end if;
Write_Name (Get_Qualified_Name (Targ_Id));
Write_Eol;
end Write_Target;
-- Local variables
package Scenarios renames Active_Scenario_Stack;
First_Seen : Boolean := False;
-- Start of processing for Write_Invocation_Path
begin
-- Nothing to do when flag -gnatd_T (output trace information on
-- invocation path recording) is not in effect.
if not Debug_Flag_Underscore_TT then
return;
end if;
-- The path originates from the elaboration of the body. Write the
-- elaboration body procedure.
if In_State.Processing = Invocation_Body_Processing then
Write_Target (Elab_Body_Id, True);
First_Seen := True;
-- The path originates from the elaboration of the spec. Write the
-- elaboration spec procedure.
elsif In_State.Processing = Invocation_Spec_Processing then
Write_Target (Elab_Spec_Id, True);
First_Seen := True;
end if;
-- Write each individual target invoked by its corresponding scenario
-- on the active scenario stack.
for Index in Scenarios.First .. Scenarios.Last loop
Write_Target
(Targ_Id => Target_Of (Index, In_State),
Is_First => Index = Scenarios.First and then not First_Seen);
end loop;
Write_Eol;
end Write_Invocation_Path;
end Invocation_Graph;
------------------------
-- Is_Safe_Activation --
------------------------
function Is_Safe_Activation
(Call : Node_Id;
Task_Rep : Target_Rep_Id) return Boolean
is
begin
-- The activation of a task coming from an external instance cannot
-- cause an ABE because the generic was already instantiated. Note
-- that the instantiation itself may lead to an ABE.
return
In_External_Instance
(N => Call,
Target_Decl => Spec_Declaration (Task_Rep));
end Is_Safe_Activation;
------------------
-- Is_Safe_Call --
------------------
function Is_Safe_Call
(Call : Node_Id;
Subp_Id : Entity_Id;
Subp_Rep : Target_Rep_Id) return Boolean
is
Body_Decl : constant Node_Id := Body_Declaration (Subp_Rep);
Spec_Decl : constant Node_Id := Spec_Declaration (Subp_Rep);
begin
-- The target is either an abstract subprogram, formal subprogram, or
-- imported, in which case it does not have a body at compile or bind
-- time. Assume that the call is ABE-safe.
if Is_Bodiless_Subprogram (Subp_Id) then
return True;
-- The target is an instantiation of a generic subprogram. The call
-- cannot cause an ABE because the generic was already instantiated.
-- Note that the instantiation itself may lead to an ABE.
elsif Is_Generic_Instance (Subp_Id) then
return True;
-- The invocation of a target coming from an external instance cannot
-- cause an ABE because the generic was already instantiated. Note that
-- the instantiation itself may lead to an ABE.
elsif In_External_Instance
(N => Call,
Target_Decl => Spec_Decl)
then
return True;
-- The target is a subprogram body without a previous declaration. The
-- call cannot cause an ABE because the body has already been seen.
elsif Nkind (Spec_Decl) = N_Subprogram_Body
and then No (Corresponding_Spec (Spec_Decl))
then
return True;
-- The target is a subprogram body stub without a prior declaration.
-- The call cannot cause an ABE because the proper body substitutes
-- the stub.
elsif Nkind (Spec_Decl) = N_Subprogram_Body_Stub
and then No (Corresponding_Spec_Of_Stub (Spec_Decl))
then
return True;
-- Subprogram bodies which wrap attribute references used as actuals
-- in instantiations are always ABE-safe. These bodies are artifacts
-- of expansion.
elsif Present (Body_Decl)
and then Nkind (Body_Decl) = N_Subprogram_Body
and then Was_Attribute_Reference (Body_Decl)
then
return True;
end if;
return False;
end Is_Safe_Call;
---------------------------
-- Is_Safe_Instantiation --
---------------------------
function Is_Safe_Instantiation
(Inst : Node_Id;
Gen_Id : Entity_Id;
Gen_Rep : Target_Rep_Id) return Boolean
is
Spec_Decl : constant Node_Id := Spec_Declaration (Gen_Rep);
begin
-- The generic is an intrinsic subprogram in which case it does not
-- have a body at compile or bind time. Assume that the instantiation
-- is ABE-safe.
if Is_Bodiless_Subprogram (Gen_Id) then
return True;
-- The instantiation of an external nested generic cannot cause an ABE
-- if the outer generic was already instantiated. Note that the instance
-- of the outer generic may lead to an ABE.
elsif In_External_Instance
(N => Inst,
Target_Decl => Spec_Decl)
then
return True;
-- The generic is a package. The instantiation cannot cause an ABE when
-- the package has no body.
elsif Ekind (Gen_Id) = E_Generic_Package
and then not Has_Body (Spec_Decl)
then
return True;
end if;
return False;
end Is_Safe_Instantiation;
------------------
-- Is_Same_Unit --
------------------
function Is_Same_Unit
(Unit_1 : Entity_Id;
Unit_2 : Entity_Id) return Boolean
is
begin
return Unit_Entity (Unit_1) = Unit_Entity (Unit_2);
end Is_Same_Unit;
-------------------------------
-- Kill_Elaboration_Scenario --
-------------------------------
procedure Kill_Elaboration_Scenario (N : Node_Id) is
begin
-- Nothing to do when switch -gnatH (legacy elaboration checking mode
-- enabled) is in effect because the legacy ABE lechanism does not need
-- to carry out this action.
if Legacy_Elaboration_Checks then
return;
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
elsif not Elaboration_Phase_Active then
return;
end if;
-- Eliminate a recorded scenario when it appears within dead code
-- because it will not be executed at elaboration time.
if Is_Scenario (N) then
Delete_Scenario (N);
end if;
end Kill_Elaboration_Scenario;
----------------------
-- Main_Unit_Entity --
----------------------
function Main_Unit_Entity return Entity_Id is
begin
-- Note that Cunit_Entity (Main_Unit) is not reliable in the presence of
-- generic bodies and may return an outdated entity.
return Defining_Entity (Unit (Cunit (Main_Unit)));
end Main_Unit_Entity;
----------------------
-- Non_Private_View --
----------------------
function Non_Private_View (Typ : Entity_Id) return Entity_Id is
begin
if Is_Private_Type (Typ) and then Present (Full_View (Typ)) then
return Full_View (Typ);
else
return Typ;
end if;
end Non_Private_View;
---------------------------------
-- Record_Elaboration_Scenario --
---------------------------------
procedure Record_Elaboration_Scenario (N : Node_Id) is
procedure Check_Preelaborated_Call
(Call : Node_Id;
Call_Lvl : Enclosing_Level_Kind);
pragma Inline (Check_Preelaborated_Call);
-- Verify that entry, operator, or subprogram call Call with enclosing
-- level Call_Lvl does not appear at the library level of preelaborated
-- unit.
function Find_Code_Unit (Nod : Node_Or_Entity_Id) return Entity_Id;
pragma Inline (Find_Code_Unit);
-- Return the code unit which contains arbitrary node or entity Nod.
-- This is the unit of the file which physically contains the related
-- construct denoted by Nod except when Nod is within an instantiation.
-- In that case the unit is that of the top-level instantiation.
function In_Preelaborated_Context (Nod : Node_Id) return Boolean;
pragma Inline (In_Preelaborated_Context);
-- Determine whether arbitrary node Nod appears within a preelaborated
-- context.
procedure Record_Access_Taken
(Attr : Node_Id;
Attr_Lvl : Enclosing_Level_Kind);
pragma Inline (Record_Access_Taken);
-- Record 'Access scenario Attr with enclosing level Attr_Lvl
procedure Record_Call_Or_Task_Activation
(Call : Node_Id;
Call_Lvl : Enclosing_Level_Kind);
pragma Inline (Record_Call_Or_Task_Activation);
-- Record call scenario Call with enclosing level Call_Lvl
procedure Record_Instantiation
(Inst : Node_Id;
Inst_Lvl : Enclosing_Level_Kind);
pragma Inline (Record_Instantiation);
-- Record instantiation scenario Inst with enclosing level Inst_Lvl
procedure Record_Variable_Assignment
(Asmt : Node_Id;
Asmt_Lvl : Enclosing_Level_Kind);
pragma Inline (Record_Variable_Assignment);
-- Record variable assignment scenario Asmt with enclosing level
-- Asmt_Lvl.
procedure Record_Variable_Reference
(Ref : Node_Id;
Ref_Lvl : Enclosing_Level_Kind);
pragma Inline (Record_Variable_Reference);
-- Record variable reference scenario Ref with enclosing level Ref_Lvl
------------------------------
-- Check_Preelaborated_Call --
------------------------------
procedure Check_Preelaborated_Call
(Call : Node_Id;
Call_Lvl : Enclosing_Level_Kind)
is
begin
-- Nothing to do when the call is internally generated because it is
-- assumed that it will never violate preelaboration.
if not Is_Source_Call (Call) then
return;
-- Nothing to do when the call is preelaborable by definition
elsif Is_Preelaborable_Call (Call) then
return;
-- Library-level calls are always considered because they are part of
-- the associated unit's elaboration actions.
elsif Call_Lvl in Library_Level then
null;
-- Calls at the library level of a generic package body have to be
-- checked because they would render an instantiation illegal if the
-- template is marked as preelaborated. Note that this does not apply
-- to calls at the library level of a generic package spec.
elsif Call_Lvl = Generic_Body_Level then
null;
-- Otherwise the call does not appear at the proper level and must
-- not be considered for this check.
else
return;
end if;
-- If the call appears within a preelaborated unit, give an error
if In_Preelaborated_Context (Call) then
Error_Preelaborated_Call (Call);
end if;
end Check_Preelaborated_Call;
--------------------
-- Find_Code_Unit --
--------------------
function Find_Code_Unit (Nod : Node_Or_Entity_Id) return Entity_Id is
begin
return Find_Unit_Entity (Unit (Cunit (Get_Code_Unit (Nod))));
end Find_Code_Unit;
------------------------------
-- In_Preelaborated_Context --
------------------------------
function In_Preelaborated_Context (Nod : Node_Id) return Boolean is
Body_Id : constant Entity_Id := Find_Code_Unit (Nod);
Spec_Id : constant Entity_Id := Unique_Entity (Body_Id);
begin
-- The node appears within a package body whose corresponding spec is
-- subject to pragma Remote_Call_Interface or Remote_Types. This does
-- not result in a preelaborated context because the package body may
-- be on another machine.
if Ekind (Body_Id) = E_Package_Body
and then Is_Package_Or_Generic_Package (Spec_Id)
and then (Is_Remote_Call_Interface (Spec_Id)
or else Is_Remote_Types (Spec_Id))
then
return False;
-- Otherwise the node appears within a preelaborated context when the
-- associated unit is preelaborated.
else
return Is_Preelaborated_Unit (Spec_Id);
end if;
end In_Preelaborated_Context;
-------------------------
-- Record_Access_Taken --
-------------------------
procedure Record_Access_Taken
(Attr : Node_Id;
Attr_Lvl : Enclosing_Level_Kind)
is
begin
-- Signal any enclosing local exception handlers that the 'Access may
-- raise Program_Error due to a failed ABE check when switch -gnatd.o
-- (conservative elaboration order for indirect calls) is in effect.
-- Marking the exception handlers ensures proper expansion by both
-- the front and back end restriction when No_Exception_Propagation
-- is in effect.
if Debug_Flag_Dot_O then
Possible_Local_Raise (Attr, Standard_Program_Error);
end if;
-- Add 'Access to the appropriate set
if Attr_Lvl = Library_Body_Level then
Add_Library_Body_Scenario (Attr);
elsif Attr_Lvl = Library_Spec_Level
or else Attr_Lvl = Instantiation_Level
then
Add_Library_Spec_Scenario (Attr);
end if;
-- 'Access requires a conditional ABE check when the dynamic model is
-- in effect.
Add_Dynamic_ABE_Check_Scenario (Attr);
end Record_Access_Taken;
------------------------------------
-- Record_Call_Or_Task_Activation --
------------------------------------
procedure Record_Call_Or_Task_Activation
(Call : Node_Id;
Call_Lvl : Enclosing_Level_Kind)
is
begin
-- Signal any enclosing local exception handlers that the call may
-- raise Program_Error due to failed ABE check. Marking the exception
-- handlers ensures proper expansion by both the front and back end
-- restriction when No_Exception_Propagation is in effect.
Possible_Local_Raise (Call, Standard_Program_Error);
-- Perform early detection of guaranteed ABEs in order to suppress
-- the instantiation of generic bodies because gigi cannot handle
-- certain types of premature instantiations.
Process_Guaranteed_ABE
(N => Call,
In_State => Guaranteed_ABE_State);
-- Add the call or task activation to the appropriate set
if Call_Lvl = Declaration_Level then
Add_Declaration_Scenario (Call);
elsif Call_Lvl = Library_Body_Level then
Add_Library_Body_Scenario (Call);
elsif Call_Lvl = Library_Spec_Level
or else Call_Lvl = Instantiation_Level
then
Add_Library_Spec_Scenario (Call);
end if;
-- A call or a task activation requires a conditional ABE check when
-- the dynamic model is in effect.
Add_Dynamic_ABE_Check_Scenario (Call);
end Record_Call_Or_Task_Activation;
--------------------------
-- Record_Instantiation --
--------------------------
procedure Record_Instantiation
(Inst : Node_Id;
Inst_Lvl : Enclosing_Level_Kind)
is
begin
-- Signal enclosing local exception handlers that instantiation may
-- raise Program_Error due to failed ABE check. Marking the exception
-- handlers ensures proper expansion by both the front and back end
-- restriction when No_Exception_Propagation is in effect.
Possible_Local_Raise (Inst, Standard_Program_Error);
-- Perform early detection of guaranteed ABEs in order to suppress
-- the instantiation of generic bodies because gigi cannot handle
-- certain types of premature instantiations.
Process_Guaranteed_ABE
(N => Inst,
In_State => Guaranteed_ABE_State);
-- Add the instantiation to the appropriate set
if Inst_Lvl = Declaration_Level then
Add_Declaration_Scenario (Inst);
elsif Inst_Lvl = Library_Body_Level then
Add_Library_Body_Scenario (Inst);
elsif Inst_Lvl = Library_Spec_Level
or else Inst_Lvl = Instantiation_Level
then
Add_Library_Spec_Scenario (Inst);
end if;
-- Instantiations of generics subject to SPARK_Mode On require
-- elaboration-related checks even though the instantiations may
-- not appear within elaboration code.
if Is_Suitable_SPARK_Instantiation (Inst) then
Add_SPARK_Scenario (Inst);
end if;
-- An instantiation requires a conditional ABE check when the dynamic
-- model is in effect.
Add_Dynamic_ABE_Check_Scenario (Inst);
end Record_Instantiation;
--------------------------------
-- Record_Variable_Assignment --
--------------------------------
procedure Record_Variable_Assignment
(Asmt : Node_Id;
Asmt_Lvl : Enclosing_Level_Kind)
is
begin
-- Add the variable assignment to the appropriate set
if Asmt_Lvl = Library_Body_Level then
Add_Library_Body_Scenario (Asmt);
elsif Asmt_Lvl = Library_Spec_Level
or else Asmt_Lvl = Instantiation_Level
then
Add_Library_Spec_Scenario (Asmt);
end if;
end Record_Variable_Assignment;
-------------------------------
-- Record_Variable_Reference --
-------------------------------
procedure Record_Variable_Reference
(Ref : Node_Id;
Ref_Lvl : Enclosing_Level_Kind)
is
begin
-- Add the variable reference to the appropriate set
if Ref_Lvl = Library_Body_Level then
Add_Library_Body_Scenario (Ref);
elsif Ref_Lvl = Library_Spec_Level
or else Ref_Lvl = Instantiation_Level
then
Add_Library_Spec_Scenario (Ref);
end if;
end Record_Variable_Reference;
-- Local variables
Scen : constant Node_Id := Scenario (N);
Scen_Lvl : Enclosing_Level_Kind;
-- Start of processing for Record_Elaboration_Scenario
begin
-- Nothing to do when switch -gnatH (legacy elaboration checking mode
-- enabled) is in effect because the legacy ABE mechanism does not need
-- to carry out this action.
if Legacy_Elaboration_Checks then
return;
-- Nothing to do when the scenario is being preanalyzed
elsif Preanalysis_Active then
return;
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
elsif not Elaboration_Phase_Active then
return;
end if;
Scen_Lvl := Find_Enclosing_Level (Scen);
-- Ensure that a library-level call does not appear in a preelaborated
-- unit. The check must come before ignoring scenarios within external
-- units or inside generics because calls in those context must also be
-- verified.
if Is_Suitable_Call (Scen) then
Check_Preelaborated_Call (Scen, Scen_Lvl);
end if;
-- Nothing to do when the scenario does not appear within the main unit
if not In_Main_Context (Scen) then
return;
-- Nothing to do when the scenario appears within a generic
elsif Inside_A_Generic then
return;
-- 'Access
elsif Is_Suitable_Access_Taken (Scen) then
Record_Access_Taken
(Attr => Scen,
Attr_Lvl => Scen_Lvl);
-- Call or task activation
elsif Is_Suitable_Call (Scen) then
Record_Call_Or_Task_Activation
(Call => Scen,
Call_Lvl => Scen_Lvl);
-- Derived type declaration
elsif Is_Suitable_SPARK_Derived_Type (Scen) then
Add_SPARK_Scenario (Scen);
-- Instantiation
elsif Is_Suitable_Instantiation (Scen) then
Record_Instantiation
(Inst => Scen,
Inst_Lvl => Scen_Lvl);
-- Refined_State pragma
elsif Is_Suitable_SPARK_Refined_State_Pragma (Scen) then
Add_SPARK_Scenario (Scen);
-- Variable assignment
elsif Is_Suitable_Variable_Assignment (Scen) then
Record_Variable_Assignment
(Asmt => Scen,
Asmt_Lvl => Scen_Lvl);
-- Variable reference
elsif Is_Suitable_Variable_Reference (Scen) then
Record_Variable_Reference
(Ref => Scen,
Ref_Lvl => Scen_Lvl);
end if;
end Record_Elaboration_Scenario;
--------------
-- Scenario --
--------------
function Scenario (N : Node_Id) return Node_Id is
Orig_N : constant Node_Id := Original_Node (N);
begin
-- An expanded instantiation is rewritten into a spec-body pair where
-- N denotes the spec. In this case the original instantiation is the
-- proper elaboration scenario.
if Nkind (Orig_N) in N_Generic_Instantiation then
return Orig_N;
-- Otherwise the scenario is already in its proper form
else
return N;
end if;
end Scenario;
----------------------
-- Scenario_Storage --
----------------------
package body Scenario_Storage is
---------------------
-- Data structures --
---------------------
-- The following sets store all scenarios
Declaration_Scenarios : NE_Set.Membership_Set := NE_Set.Nil;
Dynamic_ABE_Check_Scenarios : NE_Set.Membership_Set := NE_Set.Nil;
Library_Body_Scenarios : NE_Set.Membership_Set := NE_Set.Nil;
Library_Spec_Scenarios : NE_Set.Membership_Set := NE_Set.Nil;
SPARK_Scenarios : NE_Set.Membership_Set := NE_Set.Nil;
-------------------------------
-- Finalize_Scenario_Storage --
-------------------------------
procedure Finalize_Scenario_Storage is
begin
NE_Set.Destroy (Declaration_Scenarios);
NE_Set.Destroy (Dynamic_ABE_Check_Scenarios);
NE_Set.Destroy (Library_Body_Scenarios);
NE_Set.Destroy (Library_Spec_Scenarios);
NE_Set.Destroy (SPARK_Scenarios);
end Finalize_Scenario_Storage;
---------------------------------
-- Initialize_Scenario_Storage --
---------------------------------
procedure Initialize_Scenario_Storage is
begin
Declaration_Scenarios := NE_Set.Create (1000);
Dynamic_ABE_Check_Scenarios := NE_Set.Create (500);
Library_Body_Scenarios := NE_Set.Create (1000);
Library_Spec_Scenarios := NE_Set.Create (1000);
SPARK_Scenarios := NE_Set.Create (100);
end Initialize_Scenario_Storage;
------------------------------
-- Add_Declaration_Scenario --
------------------------------
procedure Add_Declaration_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
NE_Set.Insert (Declaration_Scenarios, N);
end Add_Declaration_Scenario;
------------------------------------
-- Add_Dynamic_ABE_Check_Scenario --
------------------------------------
procedure Add_Dynamic_ABE_Check_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
if not Check_Or_Failure_Generation_OK then
return;
-- Nothing to do if the dynamic model is not in effect
elsif not Dynamic_Elaboration_Checks then
return;
end if;
NE_Set.Insert (Dynamic_ABE_Check_Scenarios, N);
end Add_Dynamic_ABE_Check_Scenario;
-------------------------------
-- Add_Library_Body_Scenario --
-------------------------------
procedure Add_Library_Body_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
NE_Set.Insert (Library_Body_Scenarios, N);
end Add_Library_Body_Scenario;
-------------------------------
-- Add_Library_Spec_Scenario --
-------------------------------
procedure Add_Library_Spec_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
NE_Set.Insert (Library_Spec_Scenarios, N);
end Add_Library_Spec_Scenario;
------------------------
-- Add_SPARK_Scenario --
------------------------
procedure Add_SPARK_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
NE_Set.Insert (SPARK_Scenarios, N);
end Add_SPARK_Scenario;
---------------------
-- Delete_Scenario --
---------------------
procedure Delete_Scenario (N : Node_Id) is
pragma Assert (Present (N));
begin
-- Delete the scenario from whichever set it belongs to
NE_Set.Delete (Declaration_Scenarios, N);
NE_Set.Delete (Dynamic_ABE_Check_Scenarios, N);
NE_Set.Delete (Library_Body_Scenarios, N);
NE_Set.Delete (Library_Spec_Scenarios, N);
NE_Set.Delete (SPARK_Scenarios, N);
end Delete_Scenario;
-----------------------------------
-- Iterate_Declaration_Scenarios --
-----------------------------------
function Iterate_Declaration_Scenarios return NE_Set.Iterator is
begin
return NE_Set.Iterate (Declaration_Scenarios);
end Iterate_Declaration_Scenarios;
-----------------------------------------
-- Iterate_Dynamic_ABE_Check_Scenarios --
-----------------------------------------
function Iterate_Dynamic_ABE_Check_Scenarios return NE_Set.Iterator is
begin
return NE_Set.Iterate (Dynamic_ABE_Check_Scenarios);
end Iterate_Dynamic_ABE_Check_Scenarios;
------------------------------------
-- Iterate_Library_Body_Scenarios --
------------------------------------
function Iterate_Library_Body_Scenarios return NE_Set.Iterator is
begin
return NE_Set.Iterate (Library_Body_Scenarios);
end Iterate_Library_Body_Scenarios;
------------------------------------
-- Iterate_Library_Spec_Scenarios --
------------------------------------
function Iterate_Library_Spec_Scenarios return NE_Set.Iterator is
begin
return NE_Set.Iterate (Library_Spec_Scenarios);
end Iterate_Library_Spec_Scenarios;
-----------------------------
-- Iterate_SPARK_Scenarios --
-----------------------------
function Iterate_SPARK_Scenarios return NE_Set.Iterator is
begin
return NE_Set.Iterate (SPARK_Scenarios);
end Iterate_SPARK_Scenarios;
----------------------
-- Replace_Scenario --
----------------------
procedure Replace_Scenario (Old_N : Node_Id; New_N : Node_Id) is
procedure Replace_Scenario_In (Scenarios : NE_Set.Membership_Set);
-- Determine whether scenario Old_N is present in set Scenarios, and
-- if this is the case it, replace it with New_N.
-------------------------
-- Replace_Scenario_In --
-------------------------
procedure Replace_Scenario_In (Scenarios : NE_Set.Membership_Set) is
begin
-- The set is intentionally checked for existance because node
-- rewriting may occur after Sem_Elab has verified all scenarios
-- and data structures have been destroyed.
if NE_Set.Present (Scenarios)
and then NE_Set.Contains (Scenarios, Old_N)
then
NE_Set.Delete (Scenarios, Old_N);
NE_Set.Insert (Scenarios, New_N);
end if;
end Replace_Scenario_In;
-- Start of processing for Replace_Scenario
begin
Replace_Scenario_In (Declaration_Scenarios);
Replace_Scenario_In (Dynamic_ABE_Check_Scenarios);
Replace_Scenario_In (Library_Body_Scenarios);
Replace_Scenario_In (Library_Spec_Scenarios);
Replace_Scenario_In (SPARK_Scenarios);
end Replace_Scenario;
end Scenario_Storage;
---------------
-- Semantics --
---------------
package body Semantics is
--------------------------------
-- Is_Accept_Alternative_Proc --
--------------------------------
function Is_Accept_Alternative_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a procedure with a receiving
-- entry.
return
Ekind (Id) = E_Procedure and then Present (Receiving_Entry (Id));
end Is_Accept_Alternative_Proc;
------------------------
-- Is_Activation_Proc --
------------------------
function Is_Activation_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote one of the runtime procedures
-- in charge of task activation.
if Ekind (Id) = E_Procedure then
if Restricted_Profile then
return Is_RTE (Id, RE_Activate_Restricted_Tasks);
else
return Is_RTE (Id, RE_Activate_Tasks);
end if;
end if;
return False;
end Is_Activation_Proc;
----------------------------
-- Is_Ada_Semantic_Target --
----------------------------
function Is_Ada_Semantic_Target (Id : Entity_Id) return Boolean is
begin
return
Is_Activation_Proc (Id)
or else Is_Controlled_Proc (Id, Name_Adjust)
or else Is_Controlled_Proc (Id, Name_Finalize)
or else Is_Controlled_Proc (Id, Name_Initialize)
or else Is_Init_Proc (Id)
or else Is_Invariant_Proc (Id)
or else Is_Protected_Entry (Id)
or else Is_Protected_Subp (Id)
or else Is_Protected_Body_Subp (Id)
or else Is_Subprogram_Inst (Id)
or else Is_Task_Entry (Id);
end Is_Ada_Semantic_Target;
--------------------------------
-- Is_Assertion_Pragma_Target --
--------------------------------
function Is_Assertion_Pragma_Target (Id : Entity_Id) return Boolean is
begin
return
Is_Default_Initial_Condition_Proc (Id)
or else Is_Initial_Condition_Proc (Id)
or else Is_Invariant_Proc (Id)
or else Is_Partial_Invariant_Proc (Id)
or else Is_Postconditions_Proc (Id);
end Is_Assertion_Pragma_Target;
----------------------------
-- Is_Bodiless_Subprogram --
----------------------------
function Is_Bodiless_Subprogram (Subp_Id : Entity_Id) return Boolean is
begin
-- An abstract subprogram does not have a body
if Ekind (Subp_Id) in E_Function | E_Operator | E_Procedure
and then Is_Abstract_Subprogram (Subp_Id)
then
return True;
-- A formal subprogram does not have a body
elsif Is_Formal_Subprogram (Subp_Id) then
return True;
-- An imported subprogram may have a body, however it is not known at
-- compile or bind time where the body resides and whether it will be
-- elaborated on time.
elsif Is_Imported (Subp_Id) then
return True;
end if;
return False;
end Is_Bodiless_Subprogram;
----------------------
-- Is_Bridge_Target --
----------------------
function Is_Bridge_Target (Id : Entity_Id) return Boolean is
begin
return
Is_Accept_Alternative_Proc (Id)
or else Is_Finalizer_Proc (Id)
or else Is_Partial_Invariant_Proc (Id)
or else Is_Postconditions_Proc (Id)
or else Is_TSS (Id, TSS_Deep_Adjust)
or else Is_TSS (Id, TSS_Deep_Finalize)
or else Is_TSS (Id, TSS_Deep_Initialize);
end Is_Bridge_Target;
------------------------
-- Is_Controlled_Proc --
------------------------
function Is_Controlled_Proc
(Subp_Id : Entity_Id;
Subp_Nam : Name_Id) return Boolean
is
Formal_Id : Entity_Id;
begin
pragma Assert
(Subp_Nam in Name_Adjust | Name_Finalize | Name_Initialize);
-- To qualify, the subprogram must denote a source procedure with
-- name Adjust, Finalize, or Initialize where the sole formal is
-- controlled.
if Comes_From_Source (Subp_Id)
and then Ekind (Subp_Id) = E_Procedure
and then Chars (Subp_Id) = Subp_Nam
then
Formal_Id := First_Formal (Subp_Id);
return
Present (Formal_Id)
and then Is_Controlled (Etype (Formal_Id))
and then No (Next_Formal (Formal_Id));
end if;
return False;
end Is_Controlled_Proc;
---------------------------------------
-- Is_Default_Initial_Condition_Proc --
---------------------------------------
function Is_Default_Initial_Condition_Proc
(Id : Entity_Id) return Boolean
is
begin
-- To qualify, the entity must denote a Default_Initial_Condition
-- procedure.
return Ekind (Id) = E_Procedure and then Is_DIC_Procedure (Id);
end Is_Default_Initial_Condition_Proc;
-----------------------
-- Is_Finalizer_Proc --
-----------------------
function Is_Finalizer_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a _Finalizer procedure
return Ekind (Id) = E_Procedure and then Chars (Id) = Name_uFinalizer;
end Is_Finalizer_Proc;
-------------------------------
-- Is_Initial_Condition_Proc --
-------------------------------
function Is_Initial_Condition_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote an Initial_Condition procedure
return
Ekind (Id) = E_Procedure
and then Is_Initial_Condition_Procedure (Id);
end Is_Initial_Condition_Proc;
--------------------
-- Is_Initialized --
--------------------
function Is_Initialized (Obj_Decl : Node_Id) return Boolean is
begin
-- To qualify, the object declaration must have an expression
return
Present (Expression (Obj_Decl))
or else Has_Init_Expression (Obj_Decl);
end Is_Initialized;
-----------------------
-- Is_Invariant_Proc --
-----------------------
function Is_Invariant_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote the "full" invariant procedure
return Ekind (Id) = E_Procedure and then Is_Invariant_Procedure (Id);
end Is_Invariant_Proc;
---------------------------------------
-- Is_Non_Library_Level_Encapsulator --
---------------------------------------
function Is_Non_Library_Level_Encapsulator
(N : Node_Id) return Boolean
is
begin
case Nkind (N) is
when N_Abstract_Subprogram_Declaration
| N_Aspect_Specification
| N_Component_Declaration
| N_Entry_Body
| N_Entry_Declaration
| N_Expression_Function
| N_Formal_Abstract_Subprogram_Declaration
| N_Formal_Concrete_Subprogram_Declaration
| N_Formal_Object_Declaration
| N_Formal_Package_Declaration
| N_Formal_Type_Declaration
| N_Generic_Association
| N_Implicit_Label_Declaration
| N_Incomplete_Type_Declaration
| N_Private_Extension_Declaration
| N_Private_Type_Declaration
| N_Protected_Body
| N_Protected_Type_Declaration
| N_Single_Protected_Declaration
| N_Single_Task_Declaration
| N_Subprogram_Body
| N_Subprogram_Declaration
| N_Task_Body
| N_Task_Type_Declaration
=>
return True;
when others =>
return Is_Generic_Declaration_Or_Body (N);
end case;
end Is_Non_Library_Level_Encapsulator;
-------------------------------
-- Is_Partial_Invariant_Proc --
-------------------------------
function Is_Partial_Invariant_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote the "partial" invariant
-- procedure.
return
Ekind (Id) = E_Procedure
and then Is_Partial_Invariant_Procedure (Id);
end Is_Partial_Invariant_Proc;
----------------------------
-- Is_Postconditions_Proc --
----------------------------
function Is_Postconditions_Proc (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a _Postconditions procedure
return
Ekind (Id) = E_Procedure and then Chars (Id) = Name_uPostconditions;
end Is_Postconditions_Proc;
---------------------------
-- Is_Preelaborated_Unit --
---------------------------
function Is_Preelaborated_Unit (Id : Entity_Id) return Boolean is
begin
return
Is_Preelaborated (Id)
or else Is_Pure (Id)
or else Is_Remote_Call_Interface (Id)
or else Is_Remote_Types (Id)
or else Is_Shared_Passive (Id);
end Is_Preelaborated_Unit;
------------------------
-- Is_Protected_Entry --
------------------------
function Is_Protected_Entry (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote an entry defined in a protected
-- type.
return
Is_Entry (Id)
and then Is_Protected_Type (Non_Private_View (Scope (Id)));
end Is_Protected_Entry;
-----------------------
-- Is_Protected_Subp --
-----------------------
function Is_Protected_Subp (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a subprogram defined within a
-- protected type.
return
Ekind (Id) in E_Function | E_Procedure
and then Is_Protected_Type (Non_Private_View (Scope (Id)));
end Is_Protected_Subp;
----------------------------
-- Is_Protected_Body_Subp --
----------------------------
function Is_Protected_Body_Subp (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a subprogram with attribute
-- Protected_Subprogram set.
return
Ekind (Id) in E_Function | E_Procedure
and then Present (Protected_Subprogram (Id));
end Is_Protected_Body_Subp;
-----------------
-- Is_Scenario --
-----------------
function Is_Scenario (N : Node_Id) return Boolean is
begin
case Nkind (N) is
when N_Assignment_Statement
| N_Attribute_Reference
| N_Call_Marker
| N_Entry_Call_Statement
| N_Expanded_Name
| N_Function_Call
| N_Function_Instantiation
| N_Identifier
| N_Package_Instantiation
| N_Procedure_Call_Statement
| N_Procedure_Instantiation
| N_Requeue_Statement
=>
return True;
when others =>
return False;
end case;
end Is_Scenario;
------------------------------
-- Is_SPARK_Semantic_Target --
------------------------------
function Is_SPARK_Semantic_Target (Id : Entity_Id) return Boolean is
begin
return
Is_Default_Initial_Condition_Proc (Id)
or else Is_Initial_Condition_Proc (Id);
end Is_SPARK_Semantic_Target;
------------------------
-- Is_Subprogram_Inst --
------------------------
function Is_Subprogram_Inst (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote a function or a procedure which
-- is hidden within an anonymous package, and is a generic instance.
return
Ekind (Id) in E_Function | E_Procedure
and then Is_Hidden (Id)
and then Is_Generic_Instance (Id);
end Is_Subprogram_Inst;
------------------------------
-- Is_Suitable_Access_Taken --
------------------------------
function Is_Suitable_Access_Taken (N : Node_Id) return Boolean is
Nam : Name_Id;
Pref : Node_Id;
Subp_Id : Entity_Id;
begin
-- Nothing to do when switch -gnatd.U (ignore 'Access) is in effect
if Debug_Flag_Dot_UU then
return False;
-- Nothing to do when the scenario is not an attribute reference
elsif Nkind (N) /= N_Attribute_Reference then
return False;
-- Nothing to do for internally-generated attributes because they are
-- assumed to be ABE safe.
elsif not Comes_From_Source (N) then
return False;
end if;
Nam := Attribute_Name (N);
Pref := Prefix (N);
-- Sanitize the prefix of the attribute
if not Is_Entity_Name (Pref) then
return False;
elsif No (Entity (Pref)) then
return False;
end if;
Subp_Id := Entity (Pref);
if not Is_Subprogram_Or_Entry (Subp_Id) then
return False;
end if;
-- Traverse a possible chain of renamings to obtain the original
-- entry or subprogram which the prefix may rename.
Subp_Id := Get_Renamed_Entity (Subp_Id);
-- To qualify, the attribute must meet the following prerequisites:
return
-- The prefix must denote a source entry, operator, or subprogram
-- which is not imported.
Comes_From_Source (Subp_Id)
and then Is_Subprogram_Or_Entry (Subp_Id)
and then not Is_Bodiless_Subprogram (Subp_Id)
-- The attribute name must be one of the 'Access forms. Note that
-- 'Unchecked_Access cannot apply to a subprogram.
and then Nam in Name_Access | Name_Unrestricted_Access;
end Is_Suitable_Access_Taken;
----------------------
-- Is_Suitable_Call --
----------------------
function Is_Suitable_Call (N : Node_Id) return Boolean is
begin
-- Entry and subprogram calls are intentionally ignored because they
-- may undergo expansion depending on the compilation mode, previous
-- errors, generic context, etc. Call markers play the role of calls
-- and provide a uniform foundation for ABE processing.
return Nkind (N) = N_Call_Marker;
end Is_Suitable_Call;
-------------------------------
-- Is_Suitable_Instantiation --
-------------------------------
function Is_Suitable_Instantiation (N : Node_Id) return Boolean is
Inst : constant Node_Id := Scenario (N);
begin
-- To qualify, the instantiation must come from source
return
Comes_From_Source (Inst)
and then Nkind (Inst) in N_Generic_Instantiation;
end Is_Suitable_Instantiation;
------------------------------------
-- Is_Suitable_SPARK_Derived_Type --
------------------------------------
function Is_Suitable_SPARK_Derived_Type (N : Node_Id) return Boolean is
Prag : Node_Id;
Typ : Entity_Id;
begin
-- To qualify, the type declaration must denote a derived tagged type
-- with primitive operations, subject to pragma SPARK_Mode On.
if Nkind (N) = N_Full_Type_Declaration
and then Nkind (Type_Definition (N)) = N_Derived_Type_Definition
then
Typ := Defining_Entity (N);
Prag := SPARK_Pragma (Typ);
return
Is_Tagged_Type (Typ)
and then Has_Primitive_Operations (Typ)
and then Present (Prag)
and then Get_SPARK_Mode_From_Annotation (Prag) = On;
end if;
return False;
end Is_Suitable_SPARK_Derived_Type;
-------------------------------------
-- Is_Suitable_SPARK_Instantiation --
-------------------------------------
function Is_Suitable_SPARK_Instantiation (N : Node_Id) return Boolean is
Inst : constant Node_Id := Scenario (N);
Gen_Id : Entity_Id;
Prag : Node_Id;
begin
-- To qualify, both the instantiation and the generic must be subject
-- to SPARK_Mode On.
if Is_Suitable_Instantiation (N) then
Gen_Id := Instantiated_Generic (Inst);
Prag := SPARK_Pragma (Gen_Id);
return
Is_SPARK_Mode_On_Node (Inst)
and then Present (Prag)
and then Get_SPARK_Mode_From_Annotation (Prag) = On;
end if;
return False;
end Is_Suitable_SPARK_Instantiation;
--------------------------------------------
-- Is_Suitable_SPARK_Refined_State_Pragma --
--------------------------------------------
function Is_Suitable_SPARK_Refined_State_Pragma
(N : Node_Id) return Boolean
is
begin
-- To qualfy, the pragma must denote Refined_State
return
Nkind (N) = N_Pragma
and then Pragma_Name (N) = Name_Refined_State;
end Is_Suitable_SPARK_Refined_State_Pragma;
-------------------------------------
-- Is_Suitable_Variable_Assignment --
-------------------------------------
function Is_Suitable_Variable_Assignment (N : Node_Id) return Boolean is
N_Unit : Node_Id;
N_Unit_Id : Entity_Id;
Nam : Node_Id;
Var_Decl : Node_Id;
Var_Id : Entity_Id;
Var_Unit : Node_Id;
Var_Unit_Id : Entity_Id;
begin
-- Nothing to do when the scenario is not an assignment
if Nkind (N) /= N_Assignment_Statement then
return False;
-- Nothing to do for internally-generated assignments because they
-- are assumed to be ABE safe.
elsif not Comes_From_Source (N) then
return False;
-- Assignments are ignored in GNAT mode on the assumption that
-- they are ABE-safe. This behavior parallels that of the old
-- ABE mechanism.
elsif GNAT_Mode then
return False;
end if;
Nam := Assignment_Target (N);
-- Sanitize the left hand side of the assignment
if not Is_Entity_Name (Nam) then
return False;
elsif No (Entity (Nam)) then
return False;
end if;
Var_Id := Entity (Nam);
-- Sanitize the variable
if Var_Id = Any_Id then
return False;
elsif Ekind (Var_Id) /= E_Variable then
return False;
end if;
Var_Decl := Declaration_Node (Var_Id);
if Nkind (Var_Decl) /= N_Object_Declaration then
return False;
end if;
N_Unit_Id := Find_Top_Unit (N);
N_Unit := Unit_Declaration_Node (N_Unit_Id);
Var_Unit_Id := Find_Top_Unit (Var_Decl);
Var_Unit := Unit_Declaration_Node (Var_Unit_Id);
-- To qualify, the assignment must meet the following prerequisites:
return
Comes_From_Source (Var_Id)
-- The variable must be declared in the spec of compilation unit
-- U.
and then Nkind (Var_Unit) = N_Package_Declaration
and then Find_Enclosing_Level (Var_Decl) = Library_Spec_Level
-- The assignment must occur in the body of compilation unit U
and then Nkind (N_Unit) = N_Package_Body
and then Present (Corresponding_Body (Var_Unit))
and then Corresponding_Body (Var_Unit) = N_Unit_Id;
end Is_Suitable_Variable_Assignment;
------------------------------------
-- Is_Suitable_Variable_Reference --
------------------------------------
function Is_Suitable_Variable_Reference (N : Node_Id) return Boolean is
begin
-- Expanded names and identifiers are intentionally ignored because
-- they be folded, optimized away, etc. Variable references markers
-- play the role of variable references and provide a uniform
-- foundation for ABE processing.
return Nkind (N) = N_Variable_Reference_Marker;
end Is_Suitable_Variable_Reference;
-------------------
-- Is_Task_Entry --
-------------------
function Is_Task_Entry (Id : Entity_Id) return Boolean is
begin
-- To qualify, the entity must denote an entry defined in a task type
return
Is_Entry (Id) and then Is_Task_Type (Non_Private_View (Scope (Id)));
end Is_Task_Entry;
------------------------
-- Is_Up_Level_Target --
------------------------
function Is_Up_Level_Target
(Targ_Decl : Node_Id;
In_State : Processing_In_State) return Boolean
is
Root : constant Node_Id := Root_Scenario;
Root_Rep : constant Scenario_Rep_Id :=
Scenario_Representation_Of (Root, In_State);
begin
-- The root appears within the declaratons of a block statement,
-- entry body, subprogram body, or task body ignoring enclosing
-- packages. The root is always within the main unit.
if not In_State.Suppress_Up_Level_Targets
and then Level (Root_Rep) = Declaration_Level
then
-- The target is within the main unit. It acts as an up-level
-- target when it appears within a context which encloses the
-- root.
--
-- package body Main_Unit is
-- function Func ...; -- target
--
-- procedure Proc is
-- X : ... := Func; -- root scenario
if In_Extended_Main_Code_Unit (Targ_Decl) then
return not In_Same_Context (Root, Targ_Decl, Nested_OK => True);
-- Otherwise the target is external to the main unit which makes
-- it an up-level target.
else
return True;
end if;
end if;
return False;
end Is_Up_Level_Target;
end Semantics;
---------------------------
-- Set_Elaboration_Phase --
---------------------------
procedure Set_Elaboration_Phase (Status : Elaboration_Phase_Status) is
begin
Elaboration_Phase := Status;
end Set_Elaboration_Phase;
---------------------
-- SPARK_Processor --
---------------------
package body SPARK_Processor is
-----------------------
-- Local subprograms --
-----------------------
procedure Process_SPARK_Derived_Type
(Typ_Decl : Node_Id;
Typ_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_SPARK_Derived_Type);
-- Verify that the freeze node of a derived type denoted by declaration
-- Typ_Decl is within the early call region of each overriding primitive
-- body that belongs to the derived type (SPARK RM 7.7(8)). Typ_Rep is
-- the representation of the type. In_State denotes the current state of
-- the Processing phase.
procedure Process_SPARK_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_SPARK_Instantiation);
-- Verify that instanciation Inst does not precede the generic body it
-- instantiates (SPARK RM 7.7(6)). Inst_Rep is the representation of the
-- instantiation. In_State is the current state of the Processing phase.
procedure Process_SPARK_Refined_State_Pragma
(Prag : Node_Id;
Prag_Rep : Scenario_Rep_Id;
In_State : Processing_In_State);
pragma Inline (Process_SPARK_Refined_State_Pragma);
-- Verify that each constituent of Refined_State pragma Prag which
-- belongs to abstract state mentioned in pragma Initializes has prior
-- elaboration with respect to the main unit (SPARK RM 7.7.1(7)).
-- Prag_Rep is the representation of the pragma. In_State denotes the
-- current state of the Processing phase.
procedure Process_SPARK_Scenario
(N : Node_Id;
In_State : Processing_In_State);
pragma Inline (Process_SPARK_Scenario);
-- Top-level dispatcher for verifying SPARK scenarios which are not
-- always executable during elaboration but still need elaboration-
-- related checks. In_State is the current state of the Processing
-- phase.
---------------------------------
-- Check_SPARK_Model_In_Effect --
---------------------------------
SPARK_Model_Warning_Posted : Boolean := False;
-- This flag prevents the same SPARK model-related warning from being
-- emitted multiple times.
procedure Check_SPARK_Model_In_Effect is
Spec_Id : constant Entity_Id := Unique_Entity (Main_Unit_Entity);
begin
-- Do not emit the warning multiple times as this creates useless
-- noise.
if SPARK_Model_Warning_Posted then
null;
-- SPARK rule verification requires the "strict" static model
elsif Static_Elaboration_Checks
and not Relaxed_Elaboration_Checks
then
null;
-- Any other combination of models does not guarantee the absence of
-- ABE problems for SPARK rule verification purposes. Note that there
-- is no need to check for the presence of the legacy ABE mechanism
-- because the legacy code has its own dedicated processing for SPARK
-- rules.
else
SPARK_Model_Warning_Posted := True;
Error_Msg_N
("??SPARK elaboration checks require static elaboration model",
Spec_Id);
if Dynamic_Elaboration_Checks then
Error_Msg_N
("\dynamic elaboration model is in effect", Spec_Id);
else
pragma Assert (Relaxed_Elaboration_Checks);
Error_Msg_N
("\relaxed elaboration model is in effect", Spec_Id);
end if;
end if;
end Check_SPARK_Model_In_Effect;
---------------------------
-- Check_SPARK_Scenarios --
---------------------------
procedure Check_SPARK_Scenarios is
Iter : NE_Set.Iterator;
N : Node_Id;
begin
Iter := Iterate_SPARK_Scenarios;
while NE_Set.Has_Next (Iter) loop
NE_Set.Next (Iter, N);
Process_SPARK_Scenario
(N => N,
In_State => SPARK_State);
end loop;
end Check_SPARK_Scenarios;
--------------------------------
-- Process_SPARK_Derived_Type --
--------------------------------
procedure Process_SPARK_Derived_Type
(Typ_Decl : Node_Id;
Typ_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (In_State);
Typ : constant Entity_Id := Target (Typ_Rep);
Stop_Check : exception;
-- This exception is raised when the freeze node violates the
-- placement rules.
procedure Check_Overriding_Primitive
(Prim : Entity_Id;
FNode : Node_Id);
pragma Inline (Check_Overriding_Primitive);
-- Verify that freeze node FNode is within the early call region of
-- overriding primitive Prim's body.
function Freeze_Node_Location (FNode : Node_Id) return Source_Ptr;
pragma Inline (Freeze_Node_Location);
-- Return a more accurate source location associated with freeze node
-- FNode.
function Precedes_Source_Construct (N : Node_Id) return Boolean;
pragma Inline (Precedes_Source_Construct);
-- Determine whether arbitrary node N appears prior to some source
-- construct.
procedure Suggest_Elaborate_Body
(N : Node_Id;
Body_Decl : Node_Id;
Error_Nod : Node_Id);
pragma Inline (Suggest_Elaborate_Body);
-- Suggest the use of pragma Elaborate_Body when the pragma will
-- allow for node N to appear within the early call region of
-- subprogram body Body_Decl. The suggestion is attached to
-- Error_Nod as a continuation error.
--------------------------------
-- Check_Overriding_Primitive --
--------------------------------
procedure Check_Overriding_Primitive
(Prim : Entity_Id;
FNode : Node_Id)
is
Prim_Decl : constant Node_Id := Unit_Declaration_Node (Prim);
Body_Decl : Node_Id;
Body_Id : Entity_Id;
Region : Node_Id;
begin
-- Nothing to do for predefined primitives because they are
-- artifacts of tagged type expansion and cannot override source
-- primitives. Nothing to do as well for inherited primitives, as
-- the check concerns overriding ones.
if Is_Predefined_Dispatching_Operation (Prim)
or else not Is_Overriding_Subprogram (Prim)
then
return;
end if;
Body_Id := Corresponding_Body (Prim_Decl);
-- Nothing to do when the primitive does not have a corresponding
-- body. This can happen when the unit with the bodies is not the
-- main unit subjected to ABE checks.
if No (Body_Id) then
return;
-- The primitive overrides a parent or progenitor primitive
elsif Present (Overridden_Operation (Prim)) then
-- Nothing to do when overriding an interface primitive happens
-- by inheriting a non-interface primitive as the check would
-- be done on the parent primitive.
if Present (Alias (Prim)) then
return;
end if;
-- Nothing to do when the primitive is not overriding. The body of
-- such a primitive cannot be targeted by a dispatching call which
-- is executable during elaboration, and cannot cause an ABE.
else
return;
end if;
Body_Decl := Unit_Declaration_Node (Body_Id);
Region := Find_Early_Call_Region (Body_Decl);
-- The freeze node appears prior to the early call region of the
-- primitive body.
-- IMPORTANT: This check must always be performed even when
-- -gnatd.v (enforce SPARK elaboration rules in SPARK code) is not
-- specified because the static model cannot guarantee the absence
-- of ABEs in the presence of dispatching calls.
if Earlier_In_Extended_Unit (FNode, Region) then
Error_Msg_Node_2 := Prim;
Error_Msg_NE
("first freezing point of type & must appear within early "
& "call region of primitive body & (SPARK RM 7.7(8))",
Typ_Decl, Typ);
Error_Msg_Sloc := Sloc (Region);
Error_Msg_N ("\region starts #", Typ_Decl);
Error_Msg_Sloc := Sloc (Body_Decl);
Error_Msg_N ("\region ends #", Typ_Decl);
Error_Msg_Sloc := Freeze_Node_Location (FNode);
Error_Msg_N ("\first freezing point #", Typ_Decl);
-- If applicable, suggest the use of pragma Elaborate_Body in
-- the associated package spec.
Suggest_Elaborate_Body
(N => FNode,
Body_Decl => Body_Decl,
Error_Nod => Typ_Decl);
raise Stop_Check;
end if;
end Check_Overriding_Primitive;
--------------------------
-- Freeze_Node_Location --
--------------------------
function Freeze_Node_Location (FNode : Node_Id) return Source_Ptr is
Context : constant Node_Id := Parent (FNode);
Loc : constant Source_Ptr := Sloc (FNode);
Prv_Decls : List_Id;
Vis_Decls : List_Id;
begin
-- In general, the source location of the freeze node is as close
-- as possible to the real freeze point, except when the freeze
-- node is at the "bottom" of a package spec.
if Nkind (Context) = N_Package_Specification then
Prv_Decls := Private_Declarations (Context);
Vis_Decls := Visible_Declarations (Context);
-- The freeze node appears in the private declarations of the
-- package.
if Present (Prv_Decls)
and then List_Containing (FNode) = Prv_Decls
then
null;
-- The freeze node appears in the visible declarations of the
-- package and there are no private declarations.
elsif Present (Vis_Decls)
and then List_Containing (FNode) = Vis_Decls
and then (No (Prv_Decls) or else Is_Empty_List (Prv_Decls))
then
null;
-- Otherwise the freeze node is not in the "last" declarative
-- list of the package. Use the existing source location of the
-- freeze node.
else
return Loc;
end if;
-- The freeze node appears at the "bottom" of the package when
-- it is in the "last" declarative list and is either the last
-- in the list or is followed by internal constructs only. In
-- that case the more appropriate source location is that of
-- the package end label.
if not Precedes_Source_Construct (FNode) then
return Sloc (End_Label (Context));
end if;
end if;
return Loc;
end Freeze_Node_Location;
-------------------------------
-- Precedes_Source_Construct --
-------------------------------
function Precedes_Source_Construct (N : Node_Id) return Boolean is
Decl : Node_Id;
begin
Decl := Next (N);
while Present (Decl) loop
if Comes_From_Source (Decl) then
return True;
-- A generated body for a source expression function is treated
-- as a source construct.
elsif Nkind (Decl) = N_Subprogram_Body
and then Was_Expression_Function (Decl)
and then Comes_From_Source (Original_Node (Decl))
then
return True;
end if;
Next (Decl);
end loop;
return False;
end Precedes_Source_Construct;
----------------------------
-- Suggest_Elaborate_Body --
----------------------------
procedure Suggest_Elaborate_Body
(N : Node_Id;
Body_Decl : Node_Id;
Error_Nod : Node_Id)
is
Unit_Id : constant Node_Id := Unit (Cunit (Main_Unit));
Region : Node_Id;
begin
-- The suggestion applies only when the subprogram body resides in
-- a compilation package body, and a pragma Elaborate_Body would
-- allow for the node to appear in the early call region of the
-- subprogram body. This implies that all code from the subprogram
-- body up to the node is preelaborable.
if Nkind (Unit_Id) = N_Package_Body then
-- Find the start of the early call region again assuming that
-- the package spec has pragma Elaborate_Body. Note that the
-- internal data structures are intentionally not updated
-- because this is a speculative search.
Region :=
Find_Early_Call_Region
(Body_Decl => Body_Decl,
Assume_Elab_Body => True,
Skip_Memoization => True);
-- If the node appears within the early call region, assuming
-- that the package spec carries pragma Elaborate_Body, then it
-- is safe to suggest the pragma.
if Earlier_In_Extended_Unit (Region, N) then
Error_Msg_Name_1 := Name_Elaborate_Body;
Error_Msg_NE
("\consider adding pragma % in spec of unit &",
Error_Nod, Defining_Entity (Unit_Id));
end if;
end if;
end Suggest_Elaborate_Body;
-- Local variables
FNode : constant Node_Id := Freeze_Node (Typ);
Prims : constant Elist_Id := Direct_Primitive_Operations (Typ);
Prim_Elmt : Elmt_Id;
-- Start of processing for Process_SPARK_Derived_Type
begin
-- A type should have its freeze node set by the time SPARK scenarios
-- are being verified.
pragma Assert (Present (FNode));
-- Verify that the freeze node of the derived type is within the
-- early call region of each overriding primitive body
-- (SPARK RM 7.7(8)).
if Present (Prims) then
Prim_Elmt := First_Elmt (Prims);
while Present (Prim_Elmt) loop
Check_Overriding_Primitive
(Prim => Node (Prim_Elmt),
FNode => FNode);
Next_Elmt (Prim_Elmt);
end loop;
end if;
exception
when Stop_Check =>
null;
end Process_SPARK_Derived_Type;
---------------------------------
-- Process_SPARK_Instantiation --
---------------------------------
procedure Process_SPARK_Instantiation
(Inst : Node_Id;
Inst_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
Gen_Id : constant Entity_Id := Target (Inst_Rep);
Gen_Rep : constant Target_Rep_Id :=
Target_Representation_Of (Gen_Id, In_State);
Body_Decl : constant Node_Id := Body_Declaration (Gen_Rep);
begin
-- The instantiation and the generic body are both in the main unit
if Present (Body_Decl)
and then In_Extended_Main_Code_Unit (Body_Decl)
-- If the instantiation appears prior to the generic body, then the
-- instantiation is illegal (SPARK RM 7.7(6)).
-- IMPORTANT: This check must always be performed even when
-- -gnatd.v (enforce SPARK elaboration rules in SPARK code) is not
-- specified because the rule prevents use-before-declaration of
-- objects that may precede the generic body.
and then Earlier_In_Extended_Unit (Inst, Body_Decl)
then
Error_Msg_NE
("cannot instantiate & before body seen", Inst, Gen_Id);
end if;
end Process_SPARK_Instantiation;
----------------------------
-- Process_SPARK_Scenario --
----------------------------
procedure Process_SPARK_Scenario
(N : Node_Id;
In_State : Processing_In_State)
is
Scen : constant Node_Id := Scenario (N);
begin
-- Ensure that a suitable elaboration model is in effect for SPARK
-- rule verification.
Check_SPARK_Model_In_Effect;
-- Add the current scenario to the stack of active scenarios
Push_Active_Scenario (Scen);
-- Derived type
if Is_Suitable_SPARK_Derived_Type (Scen) then
Process_SPARK_Derived_Type
(Typ_Decl => Scen,
Typ_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
-- Instantiation
elsif Is_Suitable_SPARK_Instantiation (Scen) then
Process_SPARK_Instantiation
(Inst => Scen,
Inst_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
-- Refined_State pragma
elsif Is_Suitable_SPARK_Refined_State_Pragma (Scen) then
Process_SPARK_Refined_State_Pragma
(Prag => Scen,
Prag_Rep => Scenario_Representation_Of (Scen, In_State),
In_State => In_State);
end if;
-- Remove the current scenario from the stack of active scenarios
-- once all ABE diagnostics and checks have been performed.
Pop_Active_Scenario (Scen);
end Process_SPARK_Scenario;
----------------------------------------
-- Process_SPARK_Refined_State_Pragma --
----------------------------------------
procedure Process_SPARK_Refined_State_Pragma
(Prag : Node_Id;
Prag_Rep : Scenario_Rep_Id;
In_State : Processing_In_State)
is
pragma Unreferenced (Prag_Rep);
procedure Check_SPARK_Constituent (Constit_Id : Entity_Id);
pragma Inline (Check_SPARK_Constituent);
-- Ensure that a single constituent Constit_Id is elaborated prior to
-- the main unit.
procedure Check_SPARK_Constituents (Constits : Elist_Id);
pragma Inline (Check_SPARK_Constituents);
-- Ensure that all constituents found in list Constits are elaborated
-- prior to the main unit.
procedure Check_SPARK_Initialized_State (State : Node_Id);
pragma Inline (Check_SPARK_Initialized_State);
-- Ensure that the constituents of single abstract state State are
-- elaborated prior to the main unit.
procedure Check_SPARK_Initialized_States (Pack_Id : Entity_Id);
pragma Inline (Check_SPARK_Initialized_States);
-- Ensure that the constituents of all abstract states which appear
-- in the Initializes pragma of package Pack_Id are elaborated prior
-- to the main unit.
-----------------------------
-- Check_SPARK_Constituent --
-----------------------------
procedure Check_SPARK_Constituent (Constit_Id : Entity_Id) is
SM_Prag : Node_Id;
begin
-- Nothing to do for "null" constituents
if Nkind (Constit_Id) = N_Null then
return;
-- Nothing to do for illegal constituents
elsif Error_Posted (Constit_Id) then
return;
end if;
SM_Prag := SPARK_Pragma (Constit_Id);
-- The check applies only when the constituent is subject to
-- pragma SPARK_Mode On.
if Present (SM_Prag)
and then Get_SPARK_Mode_From_Annotation (SM_Prag) = On
then
-- An external constituent of an abstract state which appears
-- in the Initializes pragma of a package spec imposes an
-- Elaborate requirement on the context of the main unit.
-- Determine whether the context has a pragma strong enough to
-- meet the requirement.
-- IMPORTANT: This check is performed only when -gnatd.v
-- (enforce SPARK elaboration rules in SPARK code) is in effect
-- because the static model can ensure the prior elaboration of
-- the unit which contains a constituent by installing implicit
-- Elaborate pragma.
if Debug_Flag_Dot_V then
Meet_Elaboration_Requirement
(N => Prag,
Targ_Id => Constit_Id,
Req_Nam => Name_Elaborate,
In_State => In_State);
-- Otherwise ensure that the unit with the external constituent
-- is elaborated prior to the main unit.
else
Ensure_Prior_Elaboration
(N => Prag,
Unit_Id => Find_Top_Unit (Constit_Id),
Prag_Nam => Name_Elaborate,
In_State => In_State);
end if;
end if;
end Check_SPARK_Constituent;
------------------------------
-- Check_SPARK_Constituents --
------------------------------
procedure Check_SPARK_Constituents (Constits : Elist_Id) is
Constit_Elmt : Elmt_Id;
begin
if Present (Constits) then
Constit_Elmt := First_Elmt (Constits);
while Present (Constit_Elmt) loop
Check_SPARK_Constituent (Node (Constit_Elmt));
Next_Elmt (Constit_Elmt);
end loop;
end if;
end Check_SPARK_Constituents;
-----------------------------------
-- Check_SPARK_Initialized_State --
-----------------------------------
procedure Check_SPARK_Initialized_State (State : Node_Id) is
SM_Prag : Node_Id;
State_Id : Entity_Id;
begin
-- Nothing to do for "null" initialization items
if Nkind (State) = N_Null then
return;
-- Nothing to do for illegal states
elsif Error_Posted (State) then
return;
end if;
State_Id := Entity_Of (State);
-- Sanitize the state
if No (State_Id) then
return;
elsif Error_Posted (State_Id) then
return;
elsif Ekind (State_Id) /= E_Abstract_State then
return;
end if;
-- The check is performed only when the abstract state is subject
-- to SPARK_Mode On.
SM_Prag := SPARK_Pragma (State_Id);
if Present (SM_Prag)
and then Get_SPARK_Mode_From_Annotation (SM_Prag) = On
then
Check_SPARK_Constituents (Refinement_Constituents (State_Id));
end if;
end Check_SPARK_Initialized_State;
------------------------------------
-- Check_SPARK_Initialized_States --
------------------------------------
procedure Check_SPARK_Initialized_States (Pack_Id : Entity_Id) is
Init_Prag : constant Node_Id :=
Get_Pragma (Pack_Id, Pragma_Initializes);
Init : Node_Id;
Inits : Node_Id;
begin
if Present (Init_Prag) then
Inits := Expression (Get_Argument (Init_Prag, Pack_Id));
-- Avoid processing a "null" initialization list. The only
-- other alternative is an aggregate.
if Nkind (Inits) = N_Aggregate then
-- The initialization items appear in list form:
--
-- (state1, state2)
if Present (Expressions (Inits)) then
Init := First (Expressions (Inits));
while Present (Init) loop
Check_SPARK_Initialized_State (Init);
Next (Init);
end loop;
end if;
-- The initialization items appear in associated form:
--
-- (state1 => item1,
-- state2 => (item2, item3))
if Present (Component_Associations (Inits)) then
Init := First (Component_Associations (Inits));
while Present (Init) loop
Check_SPARK_Initialized_State (Init);
Next (Init);
end loop;
end if;
end if;
end if;
end Check_SPARK_Initialized_States;
-- Local variables
Pack_Body : constant Node_Id := Find_Related_Package_Or_Body (Prag);
-- Start of processing for Process_SPARK_Refined_State_Pragma
begin
-- Pragma Refined_State must be associated with a package body
pragma Assert
(Present (Pack_Body) and then Nkind (Pack_Body) = N_Package_Body);
-- Verify that each external contitunent of an abstract state
-- mentioned in pragma Initializes is properly elaborated.
Check_SPARK_Initialized_States (Unique_Defining_Entity (Pack_Body));
end Process_SPARK_Refined_State_Pragma;
end SPARK_Processor;
-------------------------------
-- Spec_And_Body_From_Entity --
-------------------------------
procedure Spec_And_Body_From_Entity
(Id : Node_Id;
Spec_Decl : out Node_Id;
Body_Decl : out Node_Id)
is
begin
Spec_And_Body_From_Node
(N => Unit_Declaration_Node (Id),
Spec_Decl => Spec_Decl,
Body_Decl => Body_Decl);
end Spec_And_Body_From_Entity;
-----------------------------
-- Spec_And_Body_From_Node --
-----------------------------
procedure Spec_And_Body_From_Node
(N : Node_Id;
Spec_Decl : out Node_Id;
Body_Decl : out Node_Id)
is
Body_Id : Entity_Id;
Spec_Id : Entity_Id;
begin
-- Assume that the construct lacks spec and body
Body_Decl := Empty;
Spec_Decl := Empty;
-- Bodies
if Nkind (N) in N_Package_Body
| N_Protected_Body
| N_Subprogram_Body
| N_Task_Body
then
Spec_Id := Corresponding_Spec (N);
-- The body completes a previous declaration
if Present (Spec_Id) then
Spec_Decl := Unit_Declaration_Node (Spec_Id);
-- Otherwise the body acts as the initial declaration, and is both a
-- spec and body. There is no need to look for an optional body.
else
Body_Decl := N;
Spec_Decl := N;
return;
end if;
-- Declarations
elsif Nkind (N) in N_Entry_Declaration
| N_Generic_Package_Declaration
| N_Generic_Subprogram_Declaration
| N_Package_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Declaration
| N_Task_Type_Declaration
then
Spec_Decl := N;
-- Expression function
elsif Nkind (N) = N_Expression_Function then
Spec_Id := Corresponding_Spec (N);
pragma Assert (Present (Spec_Id));
Spec_Decl := Unit_Declaration_Node (Spec_Id);
-- Instantiations
elsif Nkind (N) in N_Generic_Instantiation then
Spec_Decl := Instance_Spec (N);
pragma Assert (Present (Spec_Decl));
-- Stubs
elsif Nkind (N) in N_Body_Stub then
Spec_Id := Corresponding_Spec_Of_Stub (N);
-- The stub completes a previous declaration
if Present (Spec_Id) then
Spec_Decl := Unit_Declaration_Node (Spec_Id);
-- Otherwise the stub acts as a spec
else
Spec_Decl := N;
end if;
end if;
-- Obtain an optional or mandatory body
if Present (Spec_Decl) then
Body_Id := Corresponding_Body (Spec_Decl);
if Present (Body_Id) then
Body_Decl := Unit_Declaration_Node (Body_Id);
end if;
end if;
end Spec_And_Body_From_Node;
-------------------------------
-- Static_Elaboration_Checks --
-------------------------------
function Static_Elaboration_Checks return Boolean is
begin
return not Dynamic_Elaboration_Checks;
end Static_Elaboration_Checks;
-----------------
-- Unit_Entity --
-----------------
function Unit_Entity (Unit_Id : Entity_Id) return Entity_Id is
function Is_Subunit (Id : Entity_Id) return Boolean;
pragma Inline (Is_Subunit);
-- Determine whether the entity of an initial declaration denotes a
-- subunit.
----------------
-- Is_Subunit --
----------------
function Is_Subunit (Id : Entity_Id) return Boolean is
Decl : constant Node_Id := Unit_Declaration_Node (Id);
begin
return
Nkind (Decl) in N_Generic_Package_Declaration
| N_Generic_Subprogram_Declaration
| N_Package_Declaration
| N_Protected_Type_Declaration
| N_Subprogram_Declaration
| N_Task_Type_Declaration
and then Present (Corresponding_Body (Decl))
and then Nkind (Parent (Unit_Declaration_Node
(Corresponding_Body (Decl)))) = N_Subunit;
end Is_Subunit;
-- Local variables
Id : Entity_Id;
-- Start of processing for Unit_Entity
begin
Id := Unique_Entity (Unit_Id);
-- Skip all subunits found in the scope chain which ends at the input
-- unit.
while Is_Subunit (Id) loop
Id := Scope (Id);
end loop;
return Id;
end Unit_Entity;
---------------------------------
-- Update_Elaboration_Scenario --
---------------------------------
procedure Update_Elaboration_Scenario (New_N : Node_Id; Old_N : Node_Id) is
begin
-- Nothing to do when the elaboration phase of the compiler is not
-- active.
if not Elaboration_Phase_Active then
return;
-- Nothing to do when the old and new scenarios are one and the same
elsif Old_N = New_N then
return;
end if;
-- A scenario is being transformed by Atree.Rewrite. Update all relevant
-- internal data structures to reflect this change. This ensures that a
-- potential run-time conditional ABE check or a guaranteed ABE failure
-- is inserted at the proper place in the tree.
if Is_Scenario (Old_N) then
Replace_Scenario (Old_N, New_N);
end if;
end Update_Elaboration_Scenario;
---------------------------------------------------------------------------
-- --
-- L E G A C Y A C C E S S B E F O R E E L A B O R A T I O N --
-- --
-- M E C H A N I S M --
-- --
---------------------------------------------------------------------------
-- This section contains the implementation of the pre-18.x legacy ABE
-- mechanism. The mechanism can be activated using switch -gnatH (legacy
-- elaboration checking mode enabled).
-----------------------------
-- Description of Approach --
-----------------------------
-- Every non-static call that is encountered by Sem_Res results in a call
-- to Check_Elab_Call, with N being the call node, and Outer set to its
-- default value of True. In addition X'Access is treated like a call
-- for the access-to-procedure case, and in SPARK mode only we also
-- check variable references.
-- The goal of Check_Elab_Call is to determine whether or not the reference
-- in question can generate an access before elaboration error (raising
-- Program_Error) either by directly calling a subprogram whose body
-- has not yet been elaborated, or indirectly, by calling a subprogram
-- whose body has been elaborated, but which contains a call to such a
-- subprogram.
-- In addition, in SPARK mode, we are checking for a variable reference in
-- another package, which requires an explicit Elaborate_All pragma.
-- The only references that we need to look at the outer level are
-- references that occur in elaboration code. There are two cases. The
-- reference can be at the outer level of elaboration code, or it can
-- be within another unit, e.g. the elaboration code of a subprogram.
-- In the case of an elaboration call at the outer level, we must trace
-- all calls to outer level routines either within the current unit or to
-- other units that are with'ed. For calls within the current unit, we can
-- determine if the body has been elaborated or not, and if it has not,
-- then a warning is generated.
-- Note that there are two subcases. If the original call directly calls a
-- subprogram whose body has not been elaborated, then we know that an ABE
-- will take place, and we replace the call by a raise of Program_Error.
-- If the call is indirect, then we don't know that the PE will be raised,
-- since the call might be guarded by a conditional. In this case we set
-- Do_Elab_Check on the call so that a dynamic check is generated, and
-- output a warning.
-- For calls to a subprogram in a with'ed unit or a 'Access or variable
-- reference (SPARK mode case), we require that a pragma Elaborate_All
-- or pragma Elaborate be present, or that the referenced unit have a
-- pragma Preelaborate, pragma Pure, or pragma Elaborate_Body. If none
-- of these conditions is met, then a warning is generated that a pragma
-- Elaborate_All may be needed (error in the SPARK case), or an implicit
-- pragma is generated.
-- For the case of an elaboration call at some inner level, we are
-- interested in tracing only calls to subprograms at the same level, i.e.
-- those that can be called during elaboration. Any calls to outer level
-- routines cannot cause ABE's as a result of the original call (there
-- might be an outer level call to the subprogram from outside that causes
-- the ABE, but that gets analyzed separately).
-- Note that we never trace calls to inner level subprograms, since these
-- cannot result in ABE's unless there is an elaboration problem at a lower
-- level, which will be separately detected.
-- Note on pragma Elaborate. The checking here assumes that a pragma
-- Elaborate on a with'ed unit guarantees that subprograms within the unit
-- can be called without causing an ABE. This is not in fact the case since
-- pragma Elaborate does not guarantee the transitive coverage guaranteed
-- by Elaborate_All. However, we decide to trust the user in this case.
--------------------------------------
-- Instantiation Elaboration Errors --
--------------------------------------
-- A special case arises when an instantiation appears in a context that is
-- known to be before the body is elaborated, e.g.
-- generic package x is ...
-- ...
-- package xx is new x;
-- ...
-- package body x is ...
-- In this situation it is certain that an elaboration error will occur,
-- and an unconditional raise Program_Error statement is inserted before
-- the instantiation, and a warning generated.
-- The problem is that in this case we have no place to put the body of
-- the instantiation. We can't put it in the normal place, because it is
-- too early, and will cause errors to occur as a result of referencing
-- entities before they are declared.
-- Our approach in this case is simply to avoid creating the body of the
-- instantiation in such a case. The instantiation spec is modified to
-- include dummy bodies for all subprograms, so that the resulting code
-- does not contain subprogram specs with no corresponding bodies.
-- The following table records the recursive call chain for output in the
-- Output routine. Each entry records the call node and the entity of the
-- called routine. The number of entries in the table (i.e. the value of
-- Elab_Call.Last) indicates the current depth of recursion and is used to
-- identify the outer level.
type Elab_Call_Element is record
Cloc : Source_Ptr;
Ent : Entity_Id;
end record;
package Elab_Call is new Table.Table
(Table_Component_Type => Elab_Call_Element,
Table_Index_Type => Int,
Table_Low_Bound => 1,
Table_Initial => 50,
Table_Increment => 100,
Table_Name => "Elab_Call");
-- The following table records all calls that have been processed starting
-- from an outer level call. The table prevents both infinite recursion and
-- useless reanalysis of calls within the same context. The use of context
-- is important because it allows for proper checks in more complex code:
-- if ... then
-- Call; -- requires a check
-- Call; -- does not need a check thanks to the table
-- elsif ... then
-- Call; -- requires a check, different context
-- end if;
-- Call; -- requires a check, different context
type Visited_Element is record
Subp_Id : Entity_Id;
-- The entity of the subprogram being called
Context : Node_Id;
-- The context where the call to the subprogram occurs
end record;
package Elab_Visited is new Table.Table
(Table_Component_Type => Visited_Element,
Table_Index_Type => Int,
Table_Low_Bound => 1,
Table_Initial => 200,
Table_Increment => 100,
Table_Name => "Elab_Visited");
-- The following table records delayed calls which must be examined after
-- all generic bodies have been instantiated.
type Delay_Element is record
N : Node_Id;
-- The parameter N from the call to Check_Internal_Call. Note that this
-- node may get rewritten over the delay period by expansion in the call
-- case (but not in the instantiation case).
E : Entity_Id;
-- The parameter E from the call to Check_Internal_Call
Orig_Ent : Entity_Id;
-- The parameter Orig_Ent from the call to Check_Internal_Call
Curscop : Entity_Id;
-- The current scope of the call. This is restored when we complete the
-- delayed call, so that we do this in the right scope.
Outer_Scope : Entity_Id;
-- Save scope of outer level call
From_Elab_Code : Boolean;
-- Save indication of whether this call is from elaboration code
In_Task_Activation : Boolean;
-- Save indication of whether this call is from a task body. Tasks are
-- activated at the "begin", which is after all local procedure bodies,
-- so calls to those procedures can't fail, even if they occur after the
-- task body.
From_SPARK_Code : Boolean;
-- Save indication of whether this call is under SPARK_Mode => On
end record;
package Delay_Check is new Table.Table
(Table_Component_Type => Delay_Element,
Table_Index_Type => Int,
Table_Low_Bound => 1,
Table_Initial => 1000,
Table_Increment => 100,
Table_Name => "Delay_Check");
C_Scope : Entity_Id;
-- Top-level scope of current scope. Compute this only once at the outer
-- level, i.e. for a call to Check_Elab_Call from outside this unit.
Outer_Level_Sloc : Source_Ptr;
-- Save Sloc value for outer level call node for comparisons of source
-- locations. A body is too late if it appears after the *outer* level
-- call, not the particular call that is being analyzed.
From_Elab_Code : Boolean;
-- This flag shows whether the outer level call currently being examined
-- is or is not in elaboration code. We are only interested in calls to
-- routines in other units if this flag is True.
In_Task_Activation : Boolean := False;
-- This flag indicates whether we are performing elaboration checks on task
-- bodies, at the point of activation. If true, we do not raise
-- Program_Error for calls to local procedures, because all local bodies
-- are known to be elaborated. However, we still need to trace such calls,
-- because a local procedure could call a procedure in another package,
-- so we might need an implicit Elaborate_All.
Delaying_Elab_Checks : Boolean := True;
-- This is set True till the compilation is complete, including the
-- insertion of all instance bodies. Then when Check_Elab_Calls is called,
-- the delay table is used to make the delayed calls and this flag is reset
-- to False, so that the calls are processed.
-----------------------
-- Local Subprograms --
-----------------------
-- Note: Outer_Scope in all following specs represents the scope of
-- interest of the outer level call. If it is set to Standard_Standard,
-- then it means the outer level call was at elaboration level, and that
-- thus all calls are of interest. If it was set to some other scope,
-- then the original call was an inner call, and we are not interested
-- in calls that go outside this scope.
procedure Activate_Elaborate_All_Desirable (N : Node_Id; U : Entity_Id);
-- Analysis of construct N shows that we should set Elaborate_All_Desirable
-- for the WITH clause for unit U (which will always be present). A special
-- case is when N is a function or procedure instantiation, in which case
-- it is sufficient to set Elaborate_Desirable, since in this case there is
-- no possibility of transitive elaboration issues.
procedure Check_A_Call
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Inter_Unit_Only : Boolean;
Generate_Warnings : Boolean := True;
In_Init_Proc : Boolean := False);
-- This is the internal recursive routine that is called to check for
-- possible elaboration error. The argument N is a subprogram call or
-- generic instantiation, or 'Access attribute reference to be checked, and
-- E is the entity of the called subprogram, or instantiated generic unit,
-- or subprogram referenced by 'Access.
--
-- In SPARK mode, N can also be a variable reference, since in SPARK this
-- also triggers a requirement for Elaborate_All, and in this case E is the
-- entity being referenced.
--
-- Outer_Scope is the outer level scope for the original reference.
-- Inter_Unit_Only is set if the call is only to be checked in the
-- case where it is to another unit (and skipped if within a unit).
-- Generate_Warnings is set to False to suppress warning messages about
-- missing pragma Elaborate_All's. These messages are not wanted for
-- inner calls in the dynamic model. Note that an instance of the Access
-- attribute applied to a subprogram also generates a call to this
-- procedure (since the referenced subprogram may be called later
-- indirectly). Flag In_Init_Proc should be set whenever the current
-- context is a type init proc.
--
-- Note: this might better be called Check_A_Reference to recognize the
-- variable case for SPARK, but we prefer to retain the historical name
-- since in practice this is mostly about checking calls for the possible
-- occurrence of an access-before-elaboration exception.
procedure Check_Bad_Instantiation (N : Node_Id);
-- N is a node for an instantiation (if called with any other node kind,
-- Check_Bad_Instantiation ignores the call). This subprogram checks for
-- the special case of a generic instantiation of a generic spec in the
-- same declarative part as the instantiation where a body is present and
-- has not yet been seen. This is an obvious error, but needs to be checked
-- specially at the time of the instantiation, since it is a case where we
-- cannot insert the body anywhere. If this case is detected, warnings are
-- generated, and a raise of Program_Error is inserted. In addition any
-- subprograms in the generic spec are stubbed, and the Bad_Instantiation
-- flag is set on the instantiation node. The caller in Sem_Ch12 uses this
-- flag as an indication that no attempt should be made to insert an
-- instance body.
procedure Check_Internal_Call
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Orig_Ent : Entity_Id);
-- N is a function call or procedure statement call node and E is the
-- entity of the called function, which is within the current compilation
-- unit (where subunits count as part of the parent). This call checks if
-- this call, or any call within any accessed body could cause an ABE, and
-- if so, outputs a warning. Orig_Ent differs from E only in the case of
-- renamings, and points to the original name of the entity. This is used
-- for error messages. Outer_Scope is the outer level scope for the
-- original call.
procedure Check_Internal_Call_Continue
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Orig_Ent : Entity_Id);
-- The processing for Check_Internal_Call is divided up into two phases,
-- and this represents the second phase. The second phase is delayed if
-- Delaying_Elab_Checks is set to True. In this delayed case, the first
-- phase makes an entry in the Delay_Check table, which is processed when
-- Check_Elab_Calls is called. N, E and Orig_Ent are as for the call to
-- Check_Internal_Call. Outer_Scope is the outer level scope for the
-- original call.
function Get_Referenced_Ent (N : Node_Id) return Entity_Id;
-- N is either a function or procedure call or an access attribute that
-- references a subprogram. This call retrieves the relevant entity. If
-- this is a call to a protected subprogram, the entity is a selected
-- component. The callable entity may be absent, in which case Empty is
-- returned. This happens with non-analyzed calls in nested generics.
--
-- If SPARK_Mode is On, then N can also be a reference to an E_Variable
-- entity, in which case, the value returned is simply this entity.
function Has_Generic_Body (N : Node_Id) return Boolean;
-- N is a generic package instantiation node, and this routine determines
-- if this package spec does in fact have a generic body. If so, then
-- True is returned, otherwise False. Note that this is not at all the
-- same as checking if the unit requires a body, since it deals with
-- the case of optional bodies accurately (i.e. if a body is optional,
-- then it looks to see if a body is actually present). Note: this
-- function can only do a fully correct job if in generating code mode
-- where all bodies have to be present. If we are operating in semantics
-- check only mode, then in some cases of optional bodies, a result of
-- False may incorrectly be given. In practice this simply means that
-- some cases of warnings for incorrect order of elaboration will only
-- be given when generating code, which is not a big problem (and is
-- inevitable, given the optional body semantics of Ada).
procedure Insert_Elab_Check (N : Node_Id; C : Node_Id := Empty);
-- Given code for an elaboration check (or unconditional raise if the check
-- is not needed), inserts the code in the appropriate place. N is the call
-- or instantiation node for which the check code is required. C is the
-- test whose failure triggers the raise.
function Is_Call_Of_Generic_Formal (N : Node_Id) return Boolean;
-- Returns True if node N is a call to a generic formal subprogram
function Is_Finalization_Procedure (Id : Entity_Id) return Boolean;
-- Determine whether entity Id denotes a [Deep_]Finalize procedure
procedure Output_Calls
(N : Node_Id;
Check_Elab_Flag : Boolean);
-- Outputs chain of calls stored in the Elab_Call table. The caller has
-- already generated the main warning message, so the warnings generated
-- are all continuation messages. The argument is the call node at which
-- the messages are to be placed. When Check_Elab_Flag is set, calls are
-- enumerated only when flag Elab_Warning is set for the dynamic case or
-- when flag Elab_Info_Messages is set for the static case.
function Same_Elaboration_Scope (Scop1, Scop2 : Entity_Id) return Boolean;
-- Given two scopes, determine whether they are the same scope from an
-- elaboration point of view, i.e. packages and blocks are ignored.
procedure Set_C_Scope;
-- On entry C_Scope is set to some scope. On return, C_Scope is reset
-- to be the enclosing compilation unit of this scope.
procedure Set_Elaboration_Constraint
(Call : Node_Id;
Subp : Entity_Id;
Scop : Entity_Id);
-- The current unit U may depend semantically on some unit P that is not
-- in the current context. If there is an elaboration call that reaches P,
-- we need to indicate that P requires an Elaborate_All, but this is not
-- effective in U's ali file, if there is no with_clause for P. In this
-- case we add the Elaborate_All on the unit Q that directly or indirectly
-- makes P available. This can happen in two cases:
--
-- a) Q declares a subtype of a type declared in P, and the call is an
-- initialization call for an object of that subtype.
--
-- b) Q declares an object of some tagged type whose root type is
-- declared in P, and the initialization call uses object notation on
-- that object to reach a primitive operation or a classwide operation
-- declared in P.
--
-- If P appears in the context of U, the current processing is correct.
-- Otherwise we must identify these two cases to retrieve Q and place the
-- Elaborate_All_Desirable on it.
function Spec_Entity (E : Entity_Id) return Entity_Id;
-- Given a compilation unit entity, if it is a spec entity, it is returned
-- unchanged. If it is a body entity, then the spec for the corresponding
-- spec is returned
function Within (E1, E2 : Entity_Id) return Boolean;
-- Given two scopes E1 and E2, returns True if E1 is equal to E2, or is one
-- of its contained scopes, False otherwise.
function Within_Elaborate_All
(Unit : Unit_Number_Type;
E : Entity_Id) return Boolean;
-- Return True if we are within the scope of an Elaborate_All for E, or if
-- we are within the scope of an Elaborate_All for some other unit U, and U
-- with's E. This prevents spurious warnings when the called entity is
-- renamed within U, or in case of generic instances.
--------------------------------------
-- Activate_Elaborate_All_Desirable --
--------------------------------------
procedure Activate_Elaborate_All_Desirable (N : Node_Id; U : Entity_Id) is
UN : constant Unit_Number_Type := Get_Code_Unit (N);
CU : constant Node_Id := Cunit (UN);
UE : constant Entity_Id := Cunit_Entity (UN);
Unm : constant Unit_Name_Type := Unit_Name (UN);
CI : constant List_Id := Context_Items (CU);
Itm : Node_Id;
Ent : Entity_Id;
procedure Add_To_Context_And_Mark (Itm : Node_Id);
-- This procedure is called when the elaborate indication must be
-- applied to a unit not in the context of the referencing unit. The
-- unit gets added to the context as an implicit with.
function In_Withs_Of (UEs : Entity_Id) return Boolean;
-- UEs is the spec entity of a unit. If the unit to be marked is
-- in the context item list of this unit spec, then the call returns
-- True and Itm is left set to point to the relevant N_With_Clause node.
procedure Set_Elab_Flag (Itm : Node_Id);
-- Sets Elaborate_[All_]Desirable as appropriate on Itm
-----------------------------
-- Add_To_Context_And_Mark --
-----------------------------
procedure Add_To_Context_And_Mark (Itm : Node_Id) is
CW : constant Node_Id :=
Make_With_Clause (Sloc (Itm),
Name => Name (Itm));
begin
Set_Library_Unit (CW, Library_Unit (Itm));
Set_Implicit_With (CW);
-- Set elaborate all desirable on copy and then append the copy to
-- the list of body with's and we are done.
Set_Elab_Flag (CW);
Append_To (CI, CW);
end Add_To_Context_And_Mark;
-----------------
-- In_Withs_Of --
-----------------
function In_Withs_Of (UEs : Entity_Id) return Boolean is
UNs : constant Unit_Number_Type := Get_Source_Unit (UEs);
CUs : constant Node_Id := Cunit (UNs);
CIs : constant List_Id := Context_Items (CUs);
begin
Itm := First (CIs);
while Present (Itm) loop
if Nkind (Itm) = N_With_Clause then
Ent :=
Cunit_Entity (Get_Cunit_Unit_Number (Library_Unit (Itm)));
if U = Ent then
return True;
end if;
end if;
Next (Itm);
end loop;
return False;
end In_Withs_Of;
-------------------
-- Set_Elab_Flag --
-------------------
procedure Set_Elab_Flag (Itm : Node_Id) is
begin
if Nkind (N) in N_Subprogram_Instantiation then
Set_Elaborate_Desirable (Itm);
else
Set_Elaborate_All_Desirable (Itm);
end if;
end Set_Elab_Flag;
-- Start of processing for Activate_Elaborate_All_Desirable
begin
-- Do not set binder indication if expansion is disabled, as when
-- compiling a generic unit.
if not Expander_Active then
return;
end if;
-- If an instance of a generic package contains a controlled object (so
-- we're calling Initialize at elaboration time), and the instance is in
-- a package body P that says "with P;", then we need to return without
-- adding "pragma Elaborate_All (P);" to P.
if U = Main_Unit_Entity then
return;
end if;
Itm := First (CI);
while Present (Itm) loop
if Nkind (Itm) = N_With_Clause then
Ent := Cunit_Entity (Get_Cunit_Unit_Number (Library_Unit (Itm)));
-- If we find it, then mark elaborate all desirable and return
if U = Ent then
Set_Elab_Flag (Itm);
return;
end if;
end if;
Next (Itm);
end loop;
-- If we fall through then the with clause is not present in the
-- current unit. One legitimate possibility is that the with clause
-- is present in the spec when we are a body.
if Is_Body_Name (Unm)
and then In_Withs_Of (Spec_Entity (UE))
then
Add_To_Context_And_Mark (Itm);
return;
end if;
-- Similarly, we may be in the spec or body of a child unit, where
-- the unit in question is with'ed by some ancestor of the child unit.
if Is_Child_Name (Unm) then
declare
Pkg : Entity_Id;
begin
Pkg := UE;
loop
Pkg := Scope (Pkg);
exit when Pkg = Standard_Standard;
if In_Withs_Of (Pkg) then
Add_To_Context_And_Mark (Itm);
return;
end if;
end loop;
end;
end if;
-- Here if we do not find with clause on spec or body. We just ignore
-- this case; it means that the elaboration involves some other unit
-- than the unit being compiled, and will be caught elsewhere.
end Activate_Elaborate_All_Desirable;
------------------
-- Check_A_Call --
------------------
procedure Check_A_Call
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Inter_Unit_Only : Boolean;
Generate_Warnings : Boolean := True;
In_Init_Proc : Boolean := False)
is
Access_Case : constant Boolean := Nkind (N) = N_Attribute_Reference;
-- Indicates if we have Access attribute case
function Call_To_Instance_From_Outside (Id : Entity_Id) return Boolean;
-- True if we're calling an instance of a generic subprogram, or a
-- subprogram in an instance of a generic package, and the call is
-- outside that instance.
procedure Elab_Warning
(Msg_D : String;
Msg_S : String;
Ent : Node_Or_Entity_Id);
-- Generate a call to Error_Msg_NE with parameters Msg_D or Msg_S (for
-- dynamic or static elaboration model), N and Ent. Msg_D is a real
-- warning (output if Msg_D is non-null and Elab_Warnings is set),
-- Msg_S is an info message (output if Elab_Info_Messages is set).
function Find_W_Scope return Entity_Id;
-- Find top-level scope for called entity (not following renamings
-- or derivations). This is where the Elaborate_All will go if it is
-- needed. We start with the called entity, except in the case of an
-- initialization procedure outside the current package, where the init
-- proc is in the root package, and we start from the entity of the name
-- in the call.
-----------------------------------
-- Call_To_Instance_From_Outside --
-----------------------------------
function Call_To_Instance_From_Outside (Id : Entity_Id) return Boolean is
Scop : Entity_Id := Id;
begin
loop
if Scop = Standard_Standard then
return False;
end if;
if Is_Generic_Instance (Scop) then
return not In_Open_Scopes (Scop);
end if;
Scop := Scope (Scop);
end loop;
end Call_To_Instance_From_Outside;
------------------
-- Elab_Warning --
------------------
procedure Elab_Warning
(Msg_D : String;
Msg_S : String;
Ent : Node_Or_Entity_Id)
is
begin
-- Dynamic elaboration checks, real warning
if Dynamic_Elaboration_Checks then
if not Access_Case then
if Msg_D /= "" and then Elab_Warnings then
Error_Msg_NE (Msg_D, N, Ent);
end if;
-- In the access case emit first warning message as well,
-- otherwise list of calls will appear as errors.
elsif Elab_Warnings then
Error_Msg_NE (Msg_S, N, Ent);
end if;
-- Static elaboration checks, info message
else
if Elab_Info_Messages then
Error_Msg_NE (Msg_S, N, Ent);
end if;
end if;
end Elab_Warning;
------------------
-- Find_W_Scope --
------------------
function Find_W_Scope return Entity_Id is
Refed_Ent : constant Entity_Id := Get_Referenced_Ent (N);
W_Scope : Entity_Id;
begin
if Is_Init_Proc (Refed_Ent)
and then not In_Same_Extended_Unit (N, Refed_Ent)
then
W_Scope := Scope (Refed_Ent);
else
W_Scope := E;
end if;
-- Now loop through scopes to get to the enclosing compilation unit
while not Is_Compilation_Unit (W_Scope) loop
W_Scope := Scope (W_Scope);
end loop;
return W_Scope;
end Find_W_Scope;
-- Local variables
Inst_Case : constant Boolean := Nkind (N) in N_Generic_Instantiation;
-- Indicates if we have instantiation case
Loc : constant Source_Ptr := Sloc (N);
Variable_Case : constant Boolean :=
Nkind (N) in N_Has_Entity
and then Present (Entity (N))
and then Ekind (Entity (N)) = E_Variable;
-- Indicates if we have variable reference case
W_Scope : constant Entity_Id := Find_W_Scope;
-- Top-level scope of directly called entity for subprogram. This
-- differs from E_Scope in the case where renamings or derivations
-- are involved, since it does not follow these links. W_Scope is
-- generally in a visible unit, and it is this scope that may require
-- an Elaborate_All. However, there are some cases (initialization
-- calls and calls involving object notation) where W_Scope might not
-- be in the context of the current unit, and there is an intermediate
-- package that is, in which case the Elaborate_All has to be placed
-- on this intermediate package. These special cases are handled in
-- Set_Elaboration_Constraint.
Ent : Entity_Id;
Callee_Unit_Internal : Boolean;
Caller_Unit_Internal : Boolean;
Decl : Node_Id;
Inst_Callee : Source_Ptr;
Inst_Caller : Source_Ptr;
Unit_Callee : Unit_Number_Type;
Unit_Caller : Unit_Number_Type;
Body_Acts_As_Spec : Boolean;
-- Set to true if call is to body acting as spec (no separate spec)
Cunit_SC : Boolean := False;
-- Set to suppress dynamic elaboration checks where one of the
-- enclosing scopes has Elaboration_Checks_Suppressed set, or else
-- if a pragma Elaborate[_All] applies to that scope, in which case
-- warnings on the scope are also suppressed. For the internal case,
-- we ignore this flag.
E_Scope : Entity_Id;
-- Top-level scope of entity for called subprogram. This value includes
-- following renamings and derivations, so this scope can be in a
-- non-visible unit. This is the scope that is to be investigated to
-- see whether an elaboration check is required.
Is_DIC : Boolean;
-- Flag set when the subprogram being invoked is the procedure generated
-- for pragma Default_Initial_Condition.
SPARK_Elab_Errors : Boolean;
-- Flag set when an entity is called or a variable is read during SPARK
-- dynamic elaboration.
-- Start of processing for Check_A_Call
begin
-- If the call is known to be within a local Suppress Elaboration
-- pragma, nothing to check. This can happen in task bodies. But
-- we ignore this for a call to a generic formal.
if Nkind (N) in N_Subprogram_Call
and then No_Elaboration_Check (N)
and then not Is_Call_Of_Generic_Formal (N)
then
return;
-- If this is a rewrite of a Valid_Scalars attribute, then nothing to
-- check, we don't mind in this case if the call occurs before the body
-- since this is all generated code.
elsif Nkind (Original_Node (N)) = N_Attribute_Reference
and then Attribute_Name (Original_Node (N)) = Name_Valid_Scalars
then
return;
-- Intrinsics such as instances of Unchecked_Deallocation do not have
-- any body, so elaboration checking is not needed, and would be wrong.
elsif Is_Intrinsic_Subprogram (E) then
return;
-- Do not consider references to internal variables for SPARK semantics
elsif Variable_Case and then not Comes_From_Source (E) then
return;
end if;
-- Proceed with check
Ent := E;
-- For a variable reference, just set Body_Acts_As_Spec to False
if Variable_Case then
Body_Acts_As_Spec := False;
-- Additional checks for all other cases
else
-- Go to parent for derived subprogram, or to original subprogram in
-- the case of a renaming (Alias covers both these cases).
loop
if (Suppress_Elaboration_Warnings (Ent)
or else Elaboration_Checks_Suppressed (Ent))
and then (Inst_Case or else No (Alias (Ent)))
then
return;
end if;
-- Nothing to do for imported entities
if Is_Imported (Ent) then
return;
end if;
exit when Inst_Case or else No (Alias (Ent));
Ent := Alias (Ent);
end loop;
Decl := Unit_Declaration_Node (Ent);
if Nkind (Decl) = N_Subprogram_Body then
Body_Acts_As_Spec := True;
elsif Nkind (Decl) in
N_Subprogram_Declaration | N_Subprogram_Body_Stub
or else Inst_Case
then
Body_Acts_As_Spec := False;
-- If we have none of an instantiation, subprogram body or subprogram
-- declaration, or in the SPARK case, a variable reference, then
-- it is not a case that we want to check. (One case is a call to a
-- generic formal subprogram, where we do not want the check in the
-- template).
else
return;
end if;
end if;
E_Scope := Ent;
loop
if Elaboration_Checks_Suppressed (E_Scope)
or else Suppress_Elaboration_Warnings (E_Scope)
then
Cunit_SC := True;
end if;
-- Exit when we get to compilation unit, not counting subunits
exit when Is_Compilation_Unit (E_Scope)
and then (Is_Child_Unit (E_Scope)
or else Scope (E_Scope) = Standard_Standard);
pragma Assert (E_Scope /= Standard_Standard);
-- Move up a scope looking for compilation unit
E_Scope := Scope (E_Scope);
end loop;
-- No checks needed for pure or preelaborated compilation units
if Is_Pure (E_Scope) or else Is_Preelaborated (E_Scope) then
return;
end if;
-- If the generic entity is within a deeper instance than we are, then
-- either the instantiation to which we refer itself caused an ABE, in
-- which case that will be handled separately, or else we know that the
-- body we need appears as needed at the point of the instantiation.
-- However, this assumption is only valid if we are in static mode.
if not Dynamic_Elaboration_Checks
and then
Instantiation_Depth (Sloc (Ent)) > Instantiation_Depth (Sloc (N))
then
return;
end if;
-- Do not give a warning for a package with no body
if Ekind (Ent) = E_Generic_Package and then not Has_Generic_Body (N) then
return;
end if;
-- Case of entity is in same unit as call or instantiation. In the
-- instantiation case, W_Scope may be different from E_Scope; we want
-- the unit in which the instantiation occurs, since we're analyzing
-- based on the expansion.
if W_Scope = C_Scope then
if not Inter_Unit_Only then
Check_Internal_Call (N, Ent, Outer_Scope, E);
end if;
return;
end if;
-- Case of entity is not in current unit (i.e. with'ed unit case)
-- We are only interested in such calls if the outer call was from
-- elaboration code, or if we are in Dynamic_Elaboration_Checks mode.
if not From_Elab_Code and then not Dynamic_Elaboration_Checks then
return;
end if;
-- Nothing to do if some scope said that no checks were required
if Cunit_SC then
return;
end if;
-- Nothing to do for a generic instance, because a call to an instance
-- cannot fail the elaboration check, because the body of the instance
-- is always elaborated immediately after the spec.
if Call_To_Instance_From_Outside (Ent) then
return;
end if;
-- Nothing to do if subprogram with no separate spec. However, a call
-- to Deep_Initialize may result in a call to a user-defined Initialize
-- procedure, which imposes a body dependency. This happens only if the
-- type is controlled and the Initialize procedure is not inherited.
if Body_Acts_As_Spec then
if Is_TSS (Ent, TSS_Deep_Initialize) then
declare
Typ : constant Entity_Id := Etype (First_Formal (Ent));
Init : Entity_Id;
begin
if not Is_Controlled (Typ) then
return;
else
Init := Find_Prim_Op (Typ, Name_Initialize);
if Comes_From_Source (Init) then
Ent := Init;
else
return;
end if;
end if;
end;
else
return;
end if;
end if;
-- Check cases of internal units
Callee_Unit_Internal := In_Internal_Unit (E_Scope);
-- Do not give a warning if the with'ed unit is internal and this is
-- the generic instantiation case (this saves a lot of hassle dealing
-- with the Text_IO special child units)
if Callee_Unit_Internal and Inst_Case then
return;
end if;
if C_Scope = Standard_Standard then
Caller_Unit_Internal := False;
else
Caller_Unit_Internal := In_Internal_Unit (C_Scope);
end if;
-- Do not give a warning if the with'ed unit is internal and the caller
-- is not internal (since the binder always elaborates internal units
-- first).
if Callee_Unit_Internal and not Caller_Unit_Internal then
return;
end if;
-- For now, if debug flag -gnatdE is not set, do no checking for one
-- internal unit withing another. This fixes the problem with the sgi
-- build and storage errors. To be resolved later ???
if (Callee_Unit_Internal and Caller_Unit_Internal)
and not Debug_Flag_EE
then
return;
end if;
if Is_TSS (E, TSS_Deep_Initialize) then
Ent := E;
end if;
-- If the call is in an instance, and the called entity is not
-- defined in the same instance, then the elaboration issue focuses
-- around the unit containing the template, it is this unit that
-- requires an Elaborate_All.
-- However, if we are doing dynamic elaboration, we need to chase the
-- call in the usual manner.
-- We also need to chase the call in the usual manner if it is a call
-- to a generic formal parameter, since that case was not handled as
-- part of the processing of the template.
Inst_Caller := Instantiation (Get_Source_File_Index (Sloc (N)));
Inst_Callee := Instantiation (Get_Source_File_Index (Sloc (Ent)));
if Inst_Caller = No_Location then
Unit_Caller := No_Unit;
else
Unit_Caller := Get_Source_Unit (N);
end if;
if Inst_Callee = No_Location then
Unit_Callee := No_Unit;
else
Unit_Callee := Get_Source_Unit (Ent);
end if;
if Unit_Caller /= No_Unit
and then Unit_Callee /= Unit_Caller
and then not Dynamic_Elaboration_Checks
and then not Is_Call_Of_Generic_Formal (N)
then
E_Scope := Spec_Entity (Cunit_Entity (Unit_Caller));
-- If we don't get a spec entity, just ignore call. Not quite
-- clear why this check is necessary. ???
if No (E_Scope) then
return;
end if;
-- Otherwise step to enclosing compilation unit
while not Is_Compilation_Unit (E_Scope) loop
E_Scope := Scope (E_Scope);
end loop;
-- For the case where N is not an instance, and is not a call within
-- instance to other than a generic formal, we recompute E_Scope
-- for the error message, since we do NOT want to go to the unit
-- that has the ultimate declaration in the case of renaming and
-- derivation and we also want to go to the generic unit in the
-- case of an instance, and no further.
else
-- Loop to carefully follow renamings and derivations one step
-- outside the current unit, but not further.
if not (Inst_Case or Variable_Case)
and then Present (Alias (Ent))
then
E_Scope := Alias (Ent);
else
E_Scope := Ent;
end if;
loop
while not Is_Compilation_Unit (E_Scope) loop
E_Scope := Scope (E_Scope);
end loop;
-- If E_Scope is the same as C_Scope, it means that there
-- definitely was a local renaming or derivation, and we
-- are not yet out of the current unit.
exit when E_Scope /= C_Scope;
Ent := Alias (Ent);
E_Scope := Ent;
-- If no alias, there could be a previous error, but not if we've
-- already reached the outermost level (Standard).
if No (Ent) then
return;
end if;
end loop;
end if;
if Within_Elaborate_All (Current_Sem_Unit, E_Scope) then
return;
end if;
-- Determine whether the Default_Initial_Condition procedure of some
-- type is being invoked.
Is_DIC := Ekind (Ent) = E_Procedure and then Is_DIC_Procedure (Ent);
-- Checks related to Default_Initial_Condition fall under the SPARK
-- umbrella because this is a SPARK-specific annotation.
SPARK_Elab_Errors :=
SPARK_Mode = On and (Is_DIC or Dynamic_Elaboration_Checks);
-- Now check if an Elaborate_All (or dynamic check) is needed
if (Elab_Info_Messages or Elab_Warnings or SPARK_Elab_Errors)
and then Generate_Warnings
and then not Suppress_Elaboration_Warnings (Ent)
and then not Elaboration_Checks_Suppressed (Ent)
and then not Suppress_Elaboration_Warnings (E_Scope)
and then not Elaboration_Checks_Suppressed (E_Scope)
then
-- Instantiation case
if Inst_Case then
if Comes_From_Source (Ent) and then SPARK_Elab_Errors then
Error_Msg_NE
("instantiation of & during elaboration in SPARK", N, Ent);
else
Elab_Warning
("instantiation of & may raise Program_Error?l?",
"info: instantiation of & during elaboration?$?", Ent);
end if;
-- Indirect call case, info message only in static elaboration
-- case, because the attribute reference itself cannot raise an
-- exception. Note that SPARK does not permit indirect calls.
elsif Access_Case then
Elab_Warning ("", "info: access to & during elaboration?$?", Ent);
-- Variable reference in SPARK mode
elsif Variable_Case then
if Comes_From_Source (Ent) and then SPARK_Elab_Errors then
Error_Msg_NE
("reference to & during elaboration in SPARK", N, Ent);
end if;
-- Subprogram call case
else
if Nkind (Name (N)) in N_Has_Entity
and then Is_Init_Proc (Entity (Name (N)))
and then Comes_From_Source (Ent)
then
Elab_Warning
("implicit call to & may raise Program_Error?l?",
"info: implicit call to & during elaboration?$?",
Ent);
elsif SPARK_Elab_Errors then
-- Emit a specialized error message when the elaboration of an
-- object of a private type evaluates the expression of pragma
-- Default_Initial_Condition. This prevents the internal name
-- of the procedure from appearing in the error message.
if Is_DIC then
Error_Msg_N
("call to Default_Initial_Condition during elaboration in "
& "SPARK", N);
else
Error_Msg_NE
("call to & during elaboration in SPARK", N, Ent);
end if;
else
Elab_Warning
("call to & may raise Program_Error?l?",
"info: call to & during elaboration?$?",
Ent);
end if;
end if;
Error_Msg_Qual_Level := Nat'Last;
-- Case of Elaborate_All not present and required, for SPARK this
-- is an error, so give an error message.
if SPARK_Elab_Errors then
Error_Msg_NE -- CODEFIX
("\Elaborate_All pragma required for&", N, W_Scope);
-- Otherwise we generate an implicit pragma. For a subprogram
-- instantiation, Elaborate is good enough, since no transitive
-- call is possible at elaboration time in this case.
elsif Nkind (N) in N_Subprogram_Instantiation then
Elab_Warning
("\missing pragma Elaborate for&?l?",
"\implicit pragma Elaborate for& generated?$?",
W_Scope);
-- For all other cases, we need an implicit Elaborate_All
else
Elab_Warning
("\missing pragma Elaborate_All for&?l?",
"\implicit pragma Elaborate_All for & generated?$?",
W_Scope);
end if;
Error_Msg_Qual_Level := 0;
-- Take into account the flags related to elaboration warning
-- messages when enumerating the various calls involved. This
-- ensures the proper pairing of the main warning and the
-- clarification messages generated by Output_Calls.
Output_Calls (N, Check_Elab_Flag => True);
-- Set flag to prevent further warnings for same unit unless in
-- All_Errors_Mode.
if not All_Errors_Mode and not Dynamic_Elaboration_Checks then
Set_Suppress_Elaboration_Warnings (W_Scope);
end if;
end if;
-- Check for runtime elaboration check required
if Dynamic_Elaboration_Checks then
if not Elaboration_Checks_Suppressed (Ent)
and then not Elaboration_Checks_Suppressed (W_Scope)
and then not Elaboration_Checks_Suppressed (E_Scope)
and then not Cunit_SC
then
-- Runtime elaboration check required. Generate check of the
-- elaboration Boolean for the unit containing the entity.
-- Note that for this case, we do check the real unit (the one
-- from following renamings, since that is the issue).
-- Could this possibly miss a useless but required PE???
Insert_Elab_Check (N,
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Elaborated,
Prefix =>
New_Occurrence_Of (Spec_Entity (E_Scope), Loc)));
-- Prevent duplicate elaboration checks on the same call, which
-- can happen if the body enclosing the call appears itself in a
-- call whose elaboration check is delayed.
if Nkind (N) in N_Subprogram_Call then
Set_No_Elaboration_Check (N);
end if;
end if;
-- Case of static elaboration model
else
-- Do not do anything if elaboration checks suppressed. Note that
-- we check Ent here, not E, since we want the real entity for the
-- body to see if checks are suppressed for it, not the dummy
-- entry for renamings or derivations.
if Elaboration_Checks_Suppressed (Ent)
or else Elaboration_Checks_Suppressed (E_Scope)
or else Elaboration_Checks_Suppressed (W_Scope)
then
null;
-- Do not generate an Elaborate_All for finalization routines
-- that perform partial clean up as part of initialization.
elsif In_Init_Proc and then Is_Finalization_Procedure (Ent) then
null;
-- Here we need to generate an implicit elaborate all
else
-- Generate Elaborate_All warning unless suppressed
if (Elab_Info_Messages and Generate_Warnings and not Inst_Case)
and then not Suppress_Elaboration_Warnings (Ent)
and then not Suppress_Elaboration_Warnings (E_Scope)
and then not Suppress_Elaboration_Warnings (W_Scope)
then
Error_Msg_Node_2 := W_Scope;
Error_Msg_NE
("info: call to& in elaboration code requires pragma "
& "Elaborate_All on&?$?", N, E);
end if;
-- Set indication for binder to generate Elaborate_All
Set_Elaboration_Constraint (N, E, W_Scope);
end if;
end if;
end Check_A_Call;
-----------------------------
-- Check_Bad_Instantiation --
-----------------------------
procedure Check_Bad_Instantiation (N : Node_Id) is
Ent : Entity_Id;
begin
-- Nothing to do if we do not have an instantiation (happens in some
-- error cases, and also in the formal package declaration case)
if Nkind (N) not in N_Generic_Instantiation then
return;
-- Nothing to do if serious errors detected (avoid cascaded errors)
elsif Serious_Errors_Detected /= 0 then
return;
-- Nothing to do if not in full analysis mode
elsif not Full_Analysis then
return;
-- Nothing to do if inside a generic template
elsif Inside_A_Generic then
return;
-- Nothing to do if a library level instantiation
elsif Nkind (Parent (N)) = N_Compilation_Unit then
return;
-- Nothing to do if we are compiling a proper body for semantic
-- purposes only. The generic body may be in another proper body.
elsif
Nkind (Parent (Unit_Declaration_Node (Main_Unit_Entity))) = N_Subunit
then
return;
end if;
Ent := Get_Generic_Entity (N);
-- The case we are interested in is when the generic spec is in the
-- current declarative part
if not Same_Elaboration_Scope (Current_Scope, Scope (Ent))
or else not In_Same_Extended_Unit (N, Ent)
then
return;
end if;
-- If the generic entity is within a deeper instance than we are, then
-- either the instantiation to which we refer itself caused an ABE, in
-- which case that will be handled separately. Otherwise, we know that
-- the body we need appears as needed at the point of the instantiation.
-- If they are both at the same level but not within the same instance
-- then the body of the generic will be in the earlier instance.
declare
D1 : constant Nat := Instantiation_Depth (Sloc (Ent));
D2 : constant Nat := Instantiation_Depth (Sloc (N));
begin
if D1 > D2 then
return;
elsif D1 = D2
and then Is_Generic_Instance (Scope (Ent))
and then not In_Open_Scopes (Scope (Ent))
then
return;
end if;
end;
-- Now we can proceed, if the entity being called has a completion,
-- then we are definitely OK, since we have already seen the body.
if Has_Completion (Ent) then
return;
end if;
-- If there is no body, then nothing to do
if not Has_Generic_Body (N) then
return;
end if;
-- Here we definitely have a bad instantiation
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_NE ("cannot instantiate& before body seen<<", N, Ent);
Error_Msg_N ("\Program_Error [<<", N);
Insert_Elab_Check (N);
Set_Is_Known_Guaranteed_ABE (N);
end Check_Bad_Instantiation;
---------------------
-- Check_Elab_Call --
---------------------
procedure Check_Elab_Call
(N : Node_Id;
Outer_Scope : Entity_Id := Empty;
In_Init_Proc : Boolean := False)
is
Ent : Entity_Id;
P : Node_Id;
begin
pragma Assert (Legacy_Elaboration_Checks);
-- If the reference is not in the main unit, there is nothing to check.
-- Elaboration call from units in the context of the main unit will lead
-- to semantic dependencies when those units are compiled.
if not In_Extended_Main_Code_Unit (N) then
return;
end if;
-- For an entry call, check relevant restriction
if Nkind (N) = N_Entry_Call_Statement
and then not In_Subprogram_Or_Concurrent_Unit
then
Check_Restriction (No_Entry_Calls_In_Elaboration_Code, N);
-- Nothing to do if this is not an expected type of reference (happens
-- in some error conditions, and in some cases where rewriting occurs).
elsif Nkind (N) not in N_Subprogram_Call
and then Nkind (N) /= N_Attribute_Reference
and then (SPARK_Mode /= On
or else Nkind (N) not in N_Has_Entity
or else No (Entity (N))
or else Ekind (Entity (N)) /= E_Variable)
then
return;
-- Nothing to do if this is a call already rewritten for elab checking.
-- Such calls appear as the targets of If_Expressions.
-- This check MUST be wrong, it catches far too much
elsif Nkind (Parent (N)) = N_If_Expression then
return;
-- Nothing to do if inside a generic template
elsif Inside_A_Generic
and then No (Enclosing_Generic_Body (N))
then
return;
-- Nothing to do if call is being preanalyzed, as when within a
-- pre/postcondition, a predicate, or an invariant.
elsif In_Spec_Expression then
return;
end if;
-- Nothing to do if this is a call to a postcondition, which is always
-- within a subprogram body, even though the current scope may be the
-- enclosing scope of the subprogram.
if Nkind (N) = N_Procedure_Call_Statement
and then Is_Entity_Name (Name (N))
and then Chars (Entity (Name (N))) = Name_uPostconditions
then
return;
end if;
-- Here we have a reference at elaboration time that must be checked
if Debug_Flag_Underscore_LL then
Write_Str (" Check_Elab_Ref: ");
if Nkind (N) = N_Attribute_Reference then
if not Is_Entity_Name (Prefix (N)) then
Write_Str ("<<not entity name>>");
else
Write_Name (Chars (Entity (Prefix (N))));
end if;
Write_Str ("'Access");
elsif No (Name (N)) or else not Is_Entity_Name (Name (N)) then
Write_Str ("<<not entity name>> ");
else
Write_Name (Chars (Entity (Name (N))));
end if;
Write_Str (" reference at ");
Write_Location (Sloc (N));
Write_Eol;
end if;
-- Climb up the tree to make sure we are not inside default expression
-- of a parameter specification or a record component, since in both
-- these cases, we will be doing the actual reference later, not now,
-- and it is at the time of the actual reference (statically speaking)
-- that we must do our static check, not at the time of its initial
-- analysis).
-- However, we have to check references within component definitions
-- (e.g. a function call that determines an array component bound),
-- so we terminate the loop in that case.
P := Parent (N);
while Present (P) loop
if Nkind (P) in N_Parameter_Specification | N_Component_Declaration
then
return;
-- The reference occurs within the constraint of a component,
-- so it must be checked.
elsif Nkind (P) = N_Component_Definition then
exit;
else
P := Parent (P);
end if;
end loop;
-- Stuff that happens only at the outer level
if No (Outer_Scope) then
Elab_Visited.Set_Last (0);
-- Nothing to do if current scope is Standard (this is a bit odd, but
-- it happens in the case of generic instantiations).
C_Scope := Current_Scope;
if C_Scope = Standard_Standard then
return;
end if;
-- First case, we are in elaboration code
From_Elab_Code := not In_Subprogram_Or_Concurrent_Unit;
if From_Elab_Code then
-- Complain if ref that comes from source in preelaborated unit
-- and we are not inside a subprogram (i.e. we are in elab code).
-- Ada 2020 (AI12-0175): Calls to certain functions that are
-- essentially unchecked conversions are preelaborable.
if Comes_From_Source (N)
and then In_Preelaborated_Unit
and then not In_Inlined_Body
and then Nkind (N) /= N_Attribute_Reference
and then not (Ada_Version >= Ada_2020
and then Is_Preelaborable_Construct (N))
then
Error_Preelaborated_Call (N);
return;
end if;
-- Second case, we are inside a subprogram or concurrent unit, which
-- means we are not in elaboration code.
else
-- In this case, the issue is whether we are inside the
-- declarative part of the unit in which we live, or inside its
-- statements. In the latter case, there is no issue of ABE calls
-- at this level (a call from outside to the unit in which we live
-- might cause an ABE, but that will be detected when we analyze
-- that outer level call, as it recurses into the called unit).
-- Climb up the tree, doing this test, and also testing for being
-- inside a default expression, which, as discussed above, is not
-- checked at this stage.
declare
P : Node_Id;
L : List_Id;
begin
P := N;
loop
-- If we find a parentless subtree, it seems safe to assume
-- that we are not in a declarative part and that no
-- checking is required.
if No (P) then
return;
end if;
if Is_List_Member (P) then
L := List_Containing (P);
P := Parent (L);
else
L := No_List;
P := Parent (P);
end if;
exit when Nkind (P) = N_Subunit;
-- Filter out case of default expressions, where we do not
-- do the check at this stage.
if Nkind (P) in
N_Parameter_Specification | N_Component_Declaration
then
return;
end if;
-- A protected body has no elaboration code and contains
-- only other bodies.
if Nkind (P) = N_Protected_Body then
return;
elsif Nkind (P) in N_Subprogram_Body
| N_Task_Body
| N_Block_Statement
| N_Entry_Body
then
if L = Declarations (P) then
exit;
-- We are not in elaboration code, but we are doing
-- dynamic elaboration checks, in this case, we still
-- need to do the reference, since the subprogram we are
-- in could be called from another unit, also in dynamic
-- elaboration check mode, at elaboration time.
elsif Dynamic_Elaboration_Checks then
-- We provide a debug flag to disable this check. That
-- way we have an easy work around for regressions
-- that are caused by this new check. This debug flag
-- can be removed later.
if Debug_Flag_DD then
return;
end if;
-- Do the check in this case
exit;
elsif Nkind (P) = N_Task_Body then
-- The check is deferred until Check_Task_Activation
-- but we need to capture local suppress pragmas
-- that may inhibit checks on this call.
Ent := Get_Referenced_Ent (N);
if No (Ent) then
return;
elsif Elaboration_Checks_Suppressed (Current_Scope)
or else Elaboration_Checks_Suppressed (Ent)
or else Elaboration_Checks_Suppressed (Scope (Ent))
then
if Nkind (N) in N_Subprogram_Call then
Set_No_Elaboration_Check (N);
end if;
end if;
return;
-- Static model, call is not in elaboration code, we
-- never need to worry, because in the static model the
-- top-level caller always takes care of things.
else
return;
end if;
end if;
end loop;
end;
end if;
end if;
Ent := Get_Referenced_Ent (N);
if No (Ent) then
return;
end if;
-- Determine whether a prior call to the same subprogram was already
-- examined within the same context. If this is the case, then there is
-- no need to proceed with the various warnings and checks because the
-- work was already done for the previous call.
declare
Self : constant Visited_Element :=
(Subp_Id => Ent, Context => Parent (N));
begin
for Index in 1 .. Elab_Visited.Last loop
if Self = Elab_Visited.Table (Index) then
return;
end if;
end loop;
end;
-- See if we need to analyze this reference. We analyze it if either of
-- the following conditions is met:
-- It is an inner level call (since in this case it was triggered
-- by an outer level call from elaboration code), but only if the
-- call is within the scope of the original outer level call.
-- It is an outer level reference from elaboration code, or a call to
-- an entity is in the same elaboration scope.
-- And in these cases, we will check both inter-unit calls and
-- intra-unit (within a single unit) calls.
C_Scope := Current_Scope;
-- If not outer level reference, then we follow it if it is within the
-- original scope of the outer reference.
if Present (Outer_Scope)
and then Within (Scope (Ent), Outer_Scope)
then
Set_C_Scope;
Check_A_Call
(N => N,
E => Ent,
Outer_Scope => Outer_Scope,
Inter_Unit_Only => False,
In_Init_Proc => In_Init_Proc);
-- Nothing to do if elaboration checks suppressed for this scope.
-- However, an interesting exception, the fact that elaboration checks
-- are suppressed within an instance (because we can trace the body when
-- we process the template) does not extend to calls to generic formal
-- subprograms.
elsif Elaboration_Checks_Suppressed (Current_Scope)
and then not Is_Call_Of_Generic_Formal (N)
then
null;
elsif From_Elab_Code then
Set_C_Scope;
Check_A_Call (N, Ent, Standard_Standard, Inter_Unit_Only => False);
elsif Same_Elaboration_Scope (C_Scope, Scope (Ent)) then
Set_C_Scope;
Check_A_Call (N, Ent, Scope (Ent), Inter_Unit_Only => False);
-- If none of those cases holds, but Dynamic_Elaboration_Checks mode
-- is set, then we will do the check, but only in the inter-unit case
-- (this is to accommodate unguarded elaboration calls from other units
-- in which this same mode is set). We don't want warnings in this case,
-- it would generate warnings having nothing to do with elaboration.
elsif Dynamic_Elaboration_Checks then
Set_C_Scope;
Check_A_Call
(N,
Ent,
Standard_Standard,
Inter_Unit_Only => True,
Generate_Warnings => False);
-- Otherwise nothing to do
else
return;
end if;
-- A call to an Init_Proc in elaboration code may bring additional
-- dependencies, if some of the record components thereof have
-- initializations that are function calls that come from source. We
-- treat the current node as a call to each of these functions, to check
-- their elaboration impact.
if Is_Init_Proc (Ent) and then From_Elab_Code then
Process_Init_Proc : declare
Unit_Decl : constant Node_Id := Unit_Declaration_Node (Ent);
function Check_Init_Call (Nod : Node_Id) return Traverse_Result;
-- Find subprogram calls within body of Init_Proc for Traverse
-- instantiation below.
procedure Traverse_Body is new Traverse_Proc (Check_Init_Call);
-- Traversal procedure to find all calls with body of Init_Proc
---------------------
-- Check_Init_Call --
---------------------
function Check_Init_Call (Nod : Node_Id) return Traverse_Result is
Func : Entity_Id;
begin
if Nkind (Nod) in N_Subprogram_Call
and then Is_Entity_Name (Name (Nod))
then
Func := Entity (Name (Nod));
if Comes_From_Source (Func) then
Check_A_Call
(N, Func, Standard_Standard, Inter_Unit_Only => True);
end if;
return OK;
else
return OK;
end if;
end Check_Init_Call;
-- Start of processing for Process_Init_Proc
begin
if Nkind (Unit_Decl) = N_Subprogram_Body then
Traverse_Body (Handled_Statement_Sequence (Unit_Decl));
end if;
end Process_Init_Proc;
end if;
end Check_Elab_Call;
-----------------------
-- Check_Elab_Assign --
-----------------------
procedure Check_Elab_Assign (N : Node_Id) is
Ent : Entity_Id;
Scop : Entity_Id;
Pkg_Spec : Entity_Id;
Pkg_Body : Entity_Id;
begin
pragma Assert (Legacy_Elaboration_Checks);
-- For record or array component, check prefix. If it is an access type,
-- then there is nothing to do (we do not know what is being assigned),
-- but otherwise this is an assignment to the prefix.
if Nkind (N) in N_Indexed_Component | N_Selected_Component | N_Slice then
if not Is_Access_Type (Etype (Prefix (N))) then
Check_Elab_Assign (Prefix (N));
end if;
return;
end if;
-- For type conversion, check expression
if Nkind (N) = N_Type_Conversion then
Check_Elab_Assign (Expression (N));
return;
end if;
-- Nothing to do if this is not an entity reference otherwise get entity
if Is_Entity_Name (N) then
Ent := Entity (N);
else
return;
end if;
-- What we are looking for is a reference in the body of a package that
-- modifies a variable declared in the visible part of the package spec.
if Present (Ent)
and then Comes_From_Source (N)
and then not Suppress_Elaboration_Warnings (Ent)
and then Ekind (Ent) = E_Variable
and then not In_Private_Part (Ent)
and then Is_Library_Level_Entity (Ent)
then
Scop := Current_Scope;
loop
if No (Scop) or else Scop = Standard_Standard then
return;
elsif Ekind (Scop) = E_Package
and then Is_Compilation_Unit (Scop)
then
exit;
else
Scop := Scope (Scop);
end if;
end loop;
-- Here Scop points to the containing library package
Pkg_Spec := Scop;
Pkg_Body := Body_Entity (Pkg_Spec);
-- All OK if the package has an Elaborate_Body pragma
if Has_Pragma_Elaborate_Body (Scop) then
return;
end if;
-- OK if entity being modified is not in containing package spec
if not In_Same_Source_Unit (Scop, Ent) then
return;
end if;
-- All OK if entity appears in generic package or generic instance.
-- We just get too messed up trying to give proper warnings in the
-- presence of generics. Better no message than a junk one.
Scop := Scope (Ent);
while Present (Scop) and then Scop /= Pkg_Spec loop
if Ekind (Scop) = E_Generic_Package then
return;
elsif Ekind (Scop) = E_Package
and then Is_Generic_Instance (Scop)
then
return;
end if;
Scop := Scope (Scop);
end loop;
-- All OK if in task, don't issue warnings there
if In_Task_Activation then
return;
end if;
-- OK if no package body
if No (Pkg_Body) then
return;
end if;
-- OK if reference is not in package body
if not In_Same_Source_Unit (Pkg_Body, N) then
return;
end if;
-- OK if package body has no handled statement sequence
declare
HSS : constant Node_Id :=
Handled_Statement_Sequence (Declaration_Node (Pkg_Body));
begin
if No (HSS) or else not Comes_From_Source (HSS) then
return;
end if;
end;
-- We definitely have a case of a modification of an entity in
-- the package spec from the elaboration code of the package body.
-- We may not give the warning (because there are some additional
-- checks to avoid too many false positives), but it would be a good
-- idea for the binder to try to keep the body elaboration close to
-- the spec elaboration.
Set_Elaborate_Body_Desirable (Pkg_Spec);
-- All OK in gnat mode (we know what we are doing)
if GNAT_Mode then
return;
end if;
-- All OK if all warnings suppressed
if Warning_Mode = Suppress then
return;
end if;
-- All OK if elaboration checks suppressed for entity
if Checks_May_Be_Suppressed (Ent)
and then Is_Check_Suppressed (Ent, Elaboration_Check)
then
return;
end if;
-- OK if the entity is initialized. Note that the No_Initialization
-- flag usually means that the initialization has been rewritten into
-- assignments, but that still counts for us.
declare
Decl : constant Node_Id := Declaration_Node (Ent);
begin
if Nkind (Decl) = N_Object_Declaration
and then (Present (Expression (Decl))
or else No_Initialization (Decl))
then
return;
end if;
end;
-- Here is where we give the warning
-- All OK if warnings suppressed on the entity
if not Has_Warnings_Off (Ent) then
Error_Msg_Sloc := Sloc (Ent);
Error_Msg_NE
("??& can be accessed by clients before this initialization",
N, Ent);
Error_Msg_NE
("\??add Elaborate_Body to spec to ensure & is initialized",
N, Ent);
end if;
if not All_Errors_Mode then
Set_Suppress_Elaboration_Warnings (Ent);
end if;
end if;
end Check_Elab_Assign;
----------------------
-- Check_Elab_Calls --
----------------------
-- WARNING: This routine manages SPARK regions
procedure Check_Elab_Calls is
Saved_SM : SPARK_Mode_Type;
Saved_SMP : Node_Id;
begin
pragma Assert (Legacy_Elaboration_Checks);
-- If expansion is disabled, do not generate any checks, unless we
-- are in GNATprove mode, so that errors are issued in GNATprove for
-- violations of static elaboration rules in SPARK code. Also skip
-- checks if any subunits are missing because in either case we lack the
-- full information that we need, and no object file will be created in
-- any case.
if (not Expander_Active and not GNATprove_Mode)
or else Is_Generic_Unit (Cunit_Entity (Main_Unit))
or else Subunits_Missing
then
return;
end if;
-- Skip delayed calls if we had any errors
if Serious_Errors_Detected = 0 then
Delaying_Elab_Checks := False;
Expander_Mode_Save_And_Set (True);
for J in Delay_Check.First .. Delay_Check.Last loop
Push_Scope (Delay_Check.Table (J).Curscop);
From_Elab_Code := Delay_Check.Table (J).From_Elab_Code;
In_Task_Activation := Delay_Check.Table (J).In_Task_Activation;
Saved_SM := SPARK_Mode;
Saved_SMP := SPARK_Mode_Pragma;
-- Set appropriate value of SPARK_Mode
if Delay_Check.Table (J).From_SPARK_Code then
SPARK_Mode := On;
end if;
Check_Internal_Call_Continue
(N => Delay_Check.Table (J).N,
E => Delay_Check.Table (J).E,
Outer_Scope => Delay_Check.Table (J).Outer_Scope,
Orig_Ent => Delay_Check.Table (J).Orig_Ent);
Restore_SPARK_Mode (Saved_SM, Saved_SMP);
Pop_Scope;
end loop;
-- Set Delaying_Elab_Checks back on for next main compilation
Expander_Mode_Restore;
Delaying_Elab_Checks := True;
end if;
end Check_Elab_Calls;
------------------------------
-- Check_Elab_Instantiation --
------------------------------
procedure Check_Elab_Instantiation
(N : Node_Id;
Outer_Scope : Entity_Id := Empty)
is
Ent : Entity_Id;
begin
pragma Assert (Legacy_Elaboration_Checks);
-- Check for and deal with bad instantiation case. There is some
-- duplicated code here, but we will worry about this later ???
Check_Bad_Instantiation (N);
if Is_Known_Guaranteed_ABE (N) then
return;
end if;
-- Nothing to do if we do not have an instantiation (happens in some
-- error cases, and also in the formal package declaration case)
if Nkind (N) not in N_Generic_Instantiation then
return;
end if;
-- Nothing to do if inside a generic template
if Inside_A_Generic then
return;
end if;
-- Nothing to do if the instantiation is not in the main unit
if not In_Extended_Main_Code_Unit (N) then
return;
end if;
Ent := Get_Generic_Entity (N);
From_Elab_Code := not In_Subprogram_Or_Concurrent_Unit;
-- See if we need to analyze this instantiation. We analyze it if
-- either of the following conditions is met:
-- It is an inner level instantiation (since in this case it was
-- triggered by an outer level call from elaboration code), but
-- only if the instantiation is within the scope of the original
-- outer level call.
-- It is an outer level instantiation from elaboration code, or the
-- instantiated entity is in the same elaboration scope.
-- And in these cases, we will check both the inter-unit case and
-- the intra-unit (within a single unit) case.
C_Scope := Current_Scope;
if Present (Outer_Scope) and then Within (Scope (Ent), Outer_Scope) then
Set_C_Scope;
Check_A_Call (N, Ent, Outer_Scope, Inter_Unit_Only => False);
elsif From_Elab_Code then
Set_C_Scope;
Check_A_Call (N, Ent, Standard_Standard, Inter_Unit_Only => False);
elsif Same_Elaboration_Scope (C_Scope, Scope (Ent)) then
Set_C_Scope;
Check_A_Call (N, Ent, Scope (Ent), Inter_Unit_Only => False);
-- If none of those cases holds, but Dynamic_Elaboration_Checks mode is
-- set, then we will do the check, but only in the inter-unit case (this
-- is to accommodate unguarded elaboration calls from other units in
-- which this same mode is set). We inhibit warnings in this case, since
-- this instantiation is not occurring in elaboration code.
elsif Dynamic_Elaboration_Checks then
Set_C_Scope;
Check_A_Call
(N,
Ent,
Standard_Standard,
Inter_Unit_Only => True,
Generate_Warnings => False);
else
return;
end if;
end Check_Elab_Instantiation;
-------------------------
-- Check_Internal_Call --
-------------------------
procedure Check_Internal_Call
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Orig_Ent : Entity_Id)
is
function Within_Initial_Condition (Call : Node_Id) return Boolean;
-- Determine whether call Call occurs within pragma Initial_Condition or
-- pragma Check with check_kind set to Initial_Condition.
------------------------------
-- Within_Initial_Condition --
------------------------------
function Within_Initial_Condition (Call : Node_Id) return Boolean is
Args : List_Id;
Nam : Name_Id;
Par : Node_Id;
begin
-- Traverse the parent chain looking for an enclosing pragma
Par := Call;
while Present (Par) loop
if Nkind (Par) = N_Pragma then
Nam := Pragma_Name (Par);
-- Pragma Initial_Condition appears in its alternative from as
-- Check (Initial_Condition, ...).
if Nam = Name_Check then
Args := Pragma_Argument_Associations (Par);
-- Pragma Check should have at least two arguments
pragma Assert (Present (Args));
return
Chars (Expression (First (Args))) = Name_Initial_Condition;
-- Direct match
elsif Nam = Name_Initial_Condition then
return True;
-- Since pragmas are never nested within other pragmas, stop
-- the traversal.
else
return False;
end if;
-- Prevent the search from going too far
elsif Is_Body_Or_Package_Declaration (Par) then
exit;
end if;
Par := Parent (Par);
-- If assertions are not enabled, the check pragma is rewritten
-- as an if_statement in sem_prag, to generate various warnings
-- on boolean expressions. Retrieve the original pragma.
if Nkind (Original_Node (Par)) = N_Pragma then
Par := Original_Node (Par);
end if;
end loop;
return False;
end Within_Initial_Condition;
-- Local variables
Inst_Case : constant Boolean := Nkind (N) in N_Generic_Instantiation;
-- Start of processing for Check_Internal_Call
begin
-- For P'Access, we want to warn if the -gnatw.f switch is set, and the
-- node comes from source.
if Nkind (N) = N_Attribute_Reference
and then ((not Warn_On_Elab_Access and then not Debug_Flag_Dot_O)
or else not Comes_From_Source (N))
then
return;
-- If not function or procedure call, instantiation, or 'Access, then
-- ignore call (this happens in some error cases and rewriting cases).
elsif Nkind (N) not in N_Attribute_Reference
| N_Function_Call
| N_Procedure_Call_Statement
and then not Inst_Case
then
return;
-- Nothing to do if this is a call or instantiation that has already
-- been found to be a sure ABE.
elsif Nkind (N) /= N_Attribute_Reference
and then Is_Known_Guaranteed_ABE (N)
then
return;
-- Nothing to do if errors already detected (avoid cascaded errors)
elsif Serious_Errors_Detected /= 0 then
return;
-- Nothing to do if not in full analysis mode
elsif not Full_Analysis then
return;
-- Nothing to do if analyzing in special spec-expression mode, since the
-- call is not actually being made at this time.
elsif In_Spec_Expression then
return;
-- Nothing to do for call to intrinsic subprogram
elsif Is_Intrinsic_Subprogram (E) then
return;
-- Nothing to do if call is within a generic unit
elsif Inside_A_Generic then
return;
-- Nothing to do when the call appears within pragma Initial_Condition.
-- The pragma is part of the elaboration statements of a package body
-- and may only call external subprograms or subprograms whose body is
-- already available.
elsif Within_Initial_Condition (N) then
return;
end if;
-- Delay this call if we are still delaying calls
if Delaying_Elab_Checks then
Delay_Check.Append
((N => N,
E => E,
Orig_Ent => Orig_Ent,
Curscop => Current_Scope,
Outer_Scope => Outer_Scope,
From_Elab_Code => From_Elab_Code,
In_Task_Activation => In_Task_Activation,
From_SPARK_Code => SPARK_Mode = On));
return;
-- Otherwise, call phase 2 continuation right now
else
Check_Internal_Call_Continue (N, E, Outer_Scope, Orig_Ent);
end if;
end Check_Internal_Call;
----------------------------------
-- Check_Internal_Call_Continue --
----------------------------------
procedure Check_Internal_Call_Continue
(N : Node_Id;
E : Entity_Id;
Outer_Scope : Entity_Id;
Orig_Ent : Entity_Id)
is
function Find_Elab_Reference (N : Node_Id) return Traverse_Result;
-- Function applied to each node as we traverse the body. Checks for
-- call or entity reference that needs checking, and if so checks it.
-- Always returns OK, so entire tree is traversed, except that as
-- described below subprogram bodies are skipped for now.
procedure Traverse is new Atree.Traverse_Proc (Find_Elab_Reference);
-- Traverse procedure using above Find_Elab_Reference function
-------------------------
-- Find_Elab_Reference --
-------------------------
function Find_Elab_Reference (N : Node_Id) return Traverse_Result is
Actual : Node_Id;
begin
-- If user has specified that there are no entry calls in elaboration
-- code, do not trace past an accept statement, because the rendez-
-- vous will happen after elaboration.
if Nkind (Original_Node (N)) in
N_Accept_Statement | N_Selective_Accept
and then Restriction_Active (No_Entry_Calls_In_Elaboration_Code)
then
return Abandon;
-- If we have a function call, check it
elsif Nkind (N) = N_Function_Call then
Check_Elab_Call (N, Outer_Scope);
return OK;
-- If we have a procedure call, check the call, and also check
-- arguments that are assignments (OUT or IN OUT mode formals).
elsif Nkind (N) = N_Procedure_Call_Statement then
Check_Elab_Call (N, Outer_Scope, In_Init_Proc => Is_Init_Proc (E));
Actual := First_Actual (N);
while Present (Actual) loop
if Known_To_Be_Assigned (Actual) then
Check_Elab_Assign (Actual);
end if;
Next_Actual (Actual);
end loop;
return OK;
-- If we have an access attribute for a subprogram, check it.
-- Suppress this behavior under debug flag.
elsif not Debug_Flag_Dot_UU
and then Nkind (N) = N_Attribute_Reference
and then
Attribute_Name (N) in Name_Access | Name_Unrestricted_Access
and then Is_Entity_Name (Prefix (N))
and then Is_Subprogram (Entity (Prefix (N)))
then
Check_Elab_Call (N, Outer_Scope);
return OK;
-- In SPARK mode, if we have an entity reference to a variable, then
-- check it. For now we consider any reference.
elsif SPARK_Mode = On
and then Nkind (N) in N_Has_Entity
and then Present (Entity (N))
and then Ekind (Entity (N)) = E_Variable
then
Check_Elab_Call (N, Outer_Scope);
return OK;
-- If we have a generic instantiation, check it
elsif Nkind (N) in N_Generic_Instantiation then
Check_Elab_Instantiation (N, Outer_Scope);
return OK;
-- Skip subprogram bodies that come from source (wait for call to
-- analyze these). The reason for the come from source test is to
-- avoid catching task bodies.
-- For task bodies, we should really avoid these too, waiting for the
-- task activation, but that's too much trouble to catch for now, so
-- we go in unconditionally. This is not so terrible, it means the
-- error backtrace is not quite complete, and we are too eager to
-- scan bodies of tasks that are unused, but this is hardly very
-- significant.
elsif Nkind (N) = N_Subprogram_Body
and then Comes_From_Source (N)
then
return Skip;
elsif Nkind (N) = N_Assignment_Statement
and then Comes_From_Source (N)
then
Check_Elab_Assign (Name (N));
return OK;
else
return OK;
end if;
end Find_Elab_Reference;
Inst_Case : constant Boolean := Is_Generic_Unit (E);
Loc : constant Source_Ptr := Sloc (N);
Ebody : Entity_Id;
Sbody : Node_Id;
-- Start of processing for Check_Internal_Call_Continue
begin
-- Save outer level call if at outer level
if Elab_Call.Last = 0 then
Outer_Level_Sloc := Loc;
end if;
-- If the call is to a function that renames a literal, no check needed
if Ekind (E) = E_Enumeration_Literal then
return;
end if;
-- Register the subprogram as examined within this particular context.
-- This ensures that calls to the same subprogram but in different
-- contexts receive warnings and checks of their own since the calls
-- may be reached through different flow paths.
Elab_Visited.Append ((Subp_Id => E, Context => Parent (N)));
Sbody := Unit_Declaration_Node (E);
if Nkind (Sbody) not in N_Subprogram_Body | N_Package_Body then
Ebody := Corresponding_Body (Sbody);
if No (Ebody) then
return;
else
Sbody := Unit_Declaration_Node (Ebody);
end if;
end if;
-- If the body appears after the outer level call or instantiation then
-- we have an error case handled below.
if Earlier_In_Extended_Unit (Outer_Level_Sloc, Sloc (Sbody))
and then not In_Task_Activation
then
null;
-- If we have the instantiation case we are done, since we now know that
-- the body of the generic appeared earlier.
elsif Inst_Case then
return;
-- Otherwise we have a call, so we trace through the called body to see
-- if it has any problems.
else
pragma Assert (Nkind (Sbody) = N_Subprogram_Body);
Elab_Call.Append ((Cloc => Loc, Ent => E));
if Debug_Flag_Underscore_LL then
Write_Str ("Elab_Call.Last = ");
Write_Int (Int (Elab_Call.Last));
Write_Str (" Ent = ");
Write_Name (Chars (E));
Write_Str (" at ");
Write_Location (Sloc (N));
Write_Eol;
end if;
-- Now traverse declarations and statements of subprogram body. Note
-- that we cannot simply Traverse (Sbody), since traverse does not
-- normally visit subprogram bodies.
declare
Decl : Node_Id;
begin
Decl := First (Declarations (Sbody));
while Present (Decl) loop
Traverse (Decl);
Next (Decl);
end loop;
end;
Traverse (Handled_Statement_Sequence (Sbody));
Elab_Call.Decrement_Last;
return;
end if;
-- Here is the case of calling a subprogram where the body has not yet
-- been encountered. A warning message is needed, except if this is the
-- case of appearing within an aspect specification that results in
-- a check call, we do not really have such a situation, so no warning
-- is needed (e.g. the case of a precondition, where the call appears
-- textually before the body, but in actual fact is moved to the
-- appropriate subprogram body and so does not need a check).
declare
P : Node_Id;
O : Node_Id;
begin
P := Parent (N);
loop
-- Keep looking at parents if we are still in the subexpression
if Nkind (P) in N_Subexpr then
P := Parent (P);
-- Here P is the parent of the expression, check for special case
else
O := Original_Node (P);
-- Definitely not the special case if orig node is not a pragma
exit when Nkind (O) /= N_Pragma;
-- Check we have an If statement or a null statement (happens
-- when the If has been expanded to be True).
exit when Nkind (P) not in N_If_Statement | N_Null_Statement;
-- Our special case will be indicated either by the pragma
-- coming from an aspect ...
if Present (Corresponding_Aspect (O)) then
return;
-- Or, in the case of an initial condition, specifically by a
-- Check pragma specifying an Initial_Condition check.
elsif Pragma_Name (O) = Name_Check
and then
Chars
(Expression (First (Pragma_Argument_Associations (O)))) =
Name_Initial_Condition
then
return;
-- For anything else, we have an error
else
exit;
end if;
end if;
end loop;
end;
-- Not that special case, warning and dynamic check is required
-- If we have nothing in the call stack, then this is at the outer
-- level, and the ABE is bound to occur, unless it's a 'Access, or
-- it's a renaming.
if Elab_Call.Last = 0 then
Error_Msg_Warn := SPARK_Mode /= On;
declare
Insert_Check : Boolean := True;
-- This flag is set to True if an elaboration check should be
-- inserted.
begin
if In_Task_Activation then
Insert_Check := False;
elsif Inst_Case then
Error_Msg_NE
("cannot instantiate& before body seen<<", N, Orig_Ent);
elsif Nkind (N) = N_Attribute_Reference then
Error_Msg_NE
("Access attribute of & before body seen<<", N, Orig_Ent);
Error_Msg_N
("\possible Program_Error on later references<<", N);
Insert_Check := False;
elsif Nkind (Unit_Declaration_Node (Orig_Ent)) /=
N_Subprogram_Renaming_Declaration
or else Is_Generic_Actual_Subprogram (Orig_Ent)
then
Error_Msg_NE
("cannot call& before body seen<<", N, Orig_Ent);
else
Insert_Check := False;
end if;
if Insert_Check then
Error_Msg_N ("\Program_Error [<<", N);
Insert_Elab_Check (N);
end if;
end;
-- Call is not at outer level
else
-- Do not generate elaboration checks in GNATprove mode because the
-- elaboration counter and the check are both forms of expansion.
if GNATprove_Mode then
null;
-- Generate an elaboration check
elsif not Elaboration_Checks_Suppressed (E) then
Set_Elaboration_Entity_Required (E);
-- Create a declaration of the elaboration entity, and insert it
-- prior to the subprogram or the generic unit, within the same
-- scope. Since the subprogram may be overloaded, create a unique
-- entity.
if No (Elaboration_Entity (E)) then
declare
Loce : constant Source_Ptr := Sloc (E);
Ent : constant Entity_Id :=
Make_Defining_Identifier (Loc,
New_External_Name (Chars (E), 'E', -1));
begin
Set_Elaboration_Entity (E, Ent);
Push_Scope (Scope (E));
Insert_Action (Declaration_Node (E),
Make_Object_Declaration (Loce,
Defining_Identifier => Ent,
Object_Definition =>
New_Occurrence_Of (Standard_Short_Integer, Loce),
Expression =>
Make_Integer_Literal (Loc, Uint_0)));
-- Set elaboration flag at the point of the body
Set_Elaboration_Flag (Sbody, E);
-- Kill current value indication. This is necessary because
-- the tests of this flag are inserted out of sequence and
-- must not pick up bogus indications of the wrong constant
-- value. Also, this is never a true constant, since one way
-- or another, it gets reset.
Set_Current_Value (Ent, Empty);
Set_Last_Assignment (Ent, Empty);
Set_Is_True_Constant (Ent, False);
Pop_Scope;
end;
end if;
-- Generate:
-- if Enn = 0 then
-- raise Program_Error with "access before elaboration";
-- end if;
Insert_Elab_Check (N,
Make_Attribute_Reference (Loc,
Attribute_Name => Name_Elaborated,
Prefix => New_Occurrence_Of (E, Loc)));
end if;
-- Generate the warning
if not Suppress_Elaboration_Warnings (E)
and then not Elaboration_Checks_Suppressed (E)
-- Suppress this warning if we have a function call that occurred
-- within an assertion expression, since we can get false warnings
-- in this case, due to the out of order handling in this case.
and then
(Nkind (Original_Node (N)) /= N_Function_Call
or else not In_Assertion_Expression_Pragma (Original_Node (N)))
then
Error_Msg_Warn := SPARK_Mode /= On;
if Inst_Case then
Error_Msg_NE
("instantiation of& may occur before body is seen<l<",
N, Orig_Ent);
else
-- A rather specific check. For Finalize/Adjust/Initialize, if
-- the type has Warnings_Off set, suppress the warning.
if Chars (E) in Name_Adjust
| Name_Finalize
| Name_Initialize
and then Present (First_Formal (E))
then
declare
T : constant Entity_Id := Etype (First_Formal (E));
begin
if Is_Controlled (T) then
if Warnings_Off (T)
or else (Ekind (T) = E_Private_Type
and then Warnings_Off (Full_View (T)))
then
goto Output;
end if;
end if;
end;
end if;
-- Go ahead and give warning if not this special case
Error_Msg_NE
("call to& may occur before body is seen<l<", N, Orig_Ent);
end if;
Error_Msg_N ("\Program_Error ]<l<", N);
-- There is no need to query the elaboration warning message flags
-- because the main message is an error, not a warning, therefore
-- all the clarification messages produces by Output_Calls must be
-- emitted unconditionally.
<<Output>>
Output_Calls (N, Check_Elab_Flag => False);
end if;
end if;
end Check_Internal_Call_Continue;
---------------------------
-- Check_Task_Activation --
---------------------------
procedure Check_Task_Activation (N : Node_Id) is
Loc : constant Source_Ptr := Sloc (N);
Inter_Procs : constant Elist_Id := New_Elmt_List;
Intra_Procs : constant Elist_Id := New_Elmt_List;
Ent : Entity_Id;
P : Entity_Id;
Task_Scope : Entity_Id;
Cunit_SC : Boolean := False;
Decl : Node_Id;
Elmt : Elmt_Id;
Enclosing : Entity_Id;
procedure Add_Task_Proc (Typ : Entity_Id);
-- Add to Task_Procs the task body procedure(s) of task types in Typ.
-- For record types, this procedure recurses over component types.
procedure Collect_Tasks (Decls : List_Id);
-- Collect the types of the tasks that are to be activated in the given
-- list of declarations, in order to perform elaboration checks on the
-- corresponding task procedures that are called implicitly here.
function Outer_Unit (E : Entity_Id) return Entity_Id;
-- find enclosing compilation unit of Entity, ignoring subunits, or
-- else enclosing subprogram. If E is not a package, there is no need
-- for inter-unit elaboration checks.
-------------------
-- Add_Task_Proc --
-------------------
procedure Add_Task_Proc (Typ : Entity_Id) is
Comp : Entity_Id;
Proc : Entity_Id := Empty;
begin
if Is_Task_Type (Typ) then
Proc := Get_Task_Body_Procedure (Typ);
elsif Is_Array_Type (Typ)
and then Has_Task (Base_Type (Typ))
then
Add_Task_Proc (Component_Type (Typ));
elsif Is_Record_Type (Typ)
and then Has_Task (Base_Type (Typ))
then
Comp := First_Component (Typ);
while Present (Comp) loop
Add_Task_Proc (Etype (Comp));
Next_Component (Comp);
end loop;
end if;
-- If the task type is another unit, we will perform the usual
-- elaboration check on its enclosing unit. If the type is in the
-- same unit, we can trace the task body as for an internal call,
-- but we only need to examine other external calls, because at
-- the point the task is activated, internal subprogram bodies
-- will have been elaborated already. We keep separate lists for
-- each kind of task.
-- Skip this test if errors have occurred, since in this case
-- we can get false indications.
if Serious_Errors_Detected /= 0 then
return;
end if;
if Present (Proc) then
if Outer_Unit (Scope (Proc)) = Enclosing then
if No (Corresponding_Body (Unit_Declaration_Node (Proc)))
and then
(not Is_Generic_Instance (Scope (Proc))
or else Scope (Proc) = Scope (Defining_Identifier (Decl)))
then
Error_Msg_Warn := SPARK_Mode /= On;
Error_Msg_N
("task will be activated before elaboration of its body<<",
Decl);
Error_Msg_N ("\Program_Error [<<", Decl);
elsif Present
(Corresponding_Body (Unit_Declaration_Node (Proc)))
then
Append_Elmt (Proc, Intra_Procs);
end if;
else
-- No need for multiple entries of the same type
Elmt := First_Elmt (Inter_Procs);
while Present (Elmt) loop
if Node (Elmt) = Proc then
return;
end if;
Next_Elmt (Elmt);
end loop;
Append_Elmt (Proc, Inter_Procs);
end if;
end if;
end Add_Task_Proc;
-------------------
-- Collect_Tasks --
-------------------
procedure Collect_Tasks (Decls : List_Id) is
begin
if Present (Decls) then
Decl := First (Decls);
while Present (Decl) loop
if Nkind (Decl) = N_Object_Declaration
and then Has_Task (Etype (Defining_Identifier (Decl)))
then
Add_Task_Proc (Etype (Defining_Identifier (Decl)));
end if;
Next (Decl);
end loop;
end if;
end Collect_Tasks;
----------------
-- Outer_Unit --
----------------
function Outer_Unit (E : Entity_Id) return Entity_Id is
Outer : Entity_Id;
begin
Outer := E;
while Present (Outer) loop
if Elaboration_Checks_Suppressed (Outer) then
Cunit_SC := True;
end if;
exit when Is_Child_Unit (Outer)
or else Scope (Outer) = Standard_Standard
or else Ekind (Outer) /= E_Package;
Outer := Scope (Outer);
end loop;
return Outer;
end Outer_Unit;
-- Start of processing for Check_Task_Activation
begin
pragma Assert (Legacy_Elaboration_Checks);
Enclosing := Outer_Unit (Current_Scope);
-- Find all tasks declared in the current unit
if Nkind (N) = N_Package_Body then
P := Unit_Declaration_Node (Corresponding_Spec (N));
Collect_Tasks (Declarations (N));
Collect_Tasks (Visible_Declarations (Specification (P)));
Collect_Tasks (Private_Declarations (Specification (P)));
elsif Nkind (N) = N_Package_Declaration then
Collect_Tasks (Visible_Declarations (Specification (N)));
Collect_Tasks (Private_Declarations (Specification (N)));
else
Collect_Tasks (Declarations (N));
end if;
-- We only perform detailed checks in all tasks that are library level
-- entities. If the master is a subprogram or task, activation will
-- depend on the activation of the master itself.
-- Should dynamic checks be added in the more general case???
if Ekind (Enclosing) /= E_Package then
return;
end if;
-- For task types defined in other units, we want the unit containing
-- the task body to be elaborated before the current one.
Elmt := First_Elmt (Inter_Procs);
while Present (Elmt) loop
Ent := Node (Elmt);
Task_Scope := Outer_Unit (Scope (Ent));
if not Is_Compilation_Unit (Task_Scope) then
null;
elsif Suppress_Elaboration_Warnings (Task_Scope)
or else Elaboration_Checks_Suppressed (Task_Scope)
then
null;
elsif Dynamic_Elaboration_Checks then
if not Elaboration_Checks_Suppressed (Ent)
and then not Cunit_SC
and then not Restriction_Active
(No_Entry_Calls_In_Elaboration_Code)
then
-- Runtime elaboration check required. Generate check of the
-- elaboration counter for the unit containing the entity.
Insert_Elab_Check (N,
Make_Attribute_Reference (Loc,
Prefix =>
New_Occurrence_Of (Spec_Entity (Task_Scope), Loc),
Attribute_Name => Name_Elaborated));
end if;
else
-- Force the binder to elaborate other unit first
if Elab_Info_Messages
and then not Suppress_Elaboration_Warnings (Ent)
and then not Elaboration_Checks_Suppressed (Ent)
and then not Suppress_Elaboration_Warnings (Task_Scope)
and then not Elaboration_Checks_Suppressed (Task_Scope)
then
Error_Msg_Node_2 := Task_Scope;
Error_Msg_NE
("info: activation of an instance of task type & requires "
& "pragma Elaborate_All on &?$?", N, Ent);
end if;
Activate_Elaborate_All_Desirable (N, Task_Scope);
Set_Suppress_Elaboration_Warnings (Task_Scope);
end if;
Next_Elmt (Elmt);
end loop;
-- For tasks declared in the current unit, trace other calls within the
-- task procedure bodies, which are available.
if not Debug_Flag_Dot_Y then
In_Task_Activation := True;
Elmt := First_Elmt (Intra_Procs);
while Present (Elmt) loop
Ent := Node (Elmt);
Check_Internal_Call_Continue (N, Ent, Enclosing, Ent);
Next_Elmt (Elmt);
end loop;
In_Task_Activation := False;
end if;
end Check_Task_Activation;
------------------------
-- Get_Referenced_Ent --
------------------------
function Get_Referenced_Ent (N : Node_Id) return Entity_Id is
Nam : Node_Id;
begin
if Nkind (N) in N_Has_Entity
and then Present (Entity (N))
and then Ekind (Entity (N)) = E_Variable
then
return Entity (N);
end if;
if Nkind (N) = N_Attribute_Reference then
Nam := Prefix (N);
else
Nam := Name (N);
end if;
if No (Nam) then
return Empty;
elsif Nkind (Nam) = N_Selected_Component then
return Entity (Selector_Name (Nam));
elsif not Is_Entity_Name (Nam) then
return Empty;
else
return Entity (Nam);
end if;
end Get_Referenced_Ent;
----------------------
-- Has_Generic_Body --
----------------------
function Has_Generic_Body (N : Node_Id) return Boolean is
Ent : constant Entity_Id := Get_Generic_Entity (N);
Decl : constant Node_Id := Unit_Declaration_Node (Ent);
Scop : Entity_Id;
function Find_Body_In (E : Entity_Id; N : Node_Id) return Node_Id;
-- Determine if the list of nodes headed by N and linked by Next
-- contains a package body for the package spec entity E, and if so
-- return the package body. If not, then returns Empty.
function Load_Package_Body (Nam : Unit_Name_Type) return Node_Id;
-- This procedure is called load the unit whose name is given by Nam.
-- This unit is being loaded to see whether it contains an optional
-- generic body. The returned value is the loaded unit, which is always
-- a package body (only package bodies can contain other entities in the
-- sense in which Has_Generic_Body is interested). We only attempt to
-- load bodies if we are generating code. If we are in semantics check
-- only mode, then it would be wrong to load bodies that are not
-- required from a semantic point of view, so in this case we return
-- Empty. The result is that the caller may incorrectly decide that a
-- generic spec does not have a body when in fact it does, but the only
-- harm in this is that some warnings on elaboration problems may be
-- lost in semantic checks only mode, which is not big loss. We also
-- return Empty if we go for a body and it is not there.
function Locate_Corresponding_Body (PE : Entity_Id) return Node_Id;
-- PE is the entity for a package spec. This function locates the
-- corresponding package body, returning Empty if none is found. The
-- package body returned is fully parsed but may not yet be analyzed,
-- so only syntactic fields should be referenced.
------------------
-- Find_Body_In --
------------------
function Find_Body_In (E : Entity_Id; N : Node_Id) return Node_Id is
Nod : Node_Id;
begin
Nod := N;
while Present (Nod) loop
-- If we found the package body we are looking for, return it
if Nkind (Nod) = N_Package_Body
and then Chars (Defining_Unit_Name (Nod)) = Chars (E)
then
return Nod;
-- If we found the stub for the body, go after the subunit,
-- loading it if necessary.
elsif Nkind (Nod) = N_Package_Body_Stub
and then Chars (Defining_Identifier (Nod)) = Chars (E)
then
if Present (Library_Unit (Nod)) then
return Unit (Library_Unit (Nod));
else
return Load_Package_Body (Get_Unit_Name (Nod));
end if;
-- If neither package body nor stub, keep looking on chain
else
Next (Nod);
end if;
end loop;
return Empty;
end Find_Body_In;
-----------------------
-- Load_Package_Body --
-----------------------
function Load_Package_Body (Nam : Unit_Name_Type) return Node_Id is
U : Unit_Number_Type;
begin
if Operating_Mode /= Generate_Code then
return Empty;
else
U :=
Load_Unit
(Load_Name => Nam,
Required => False,
Subunit => False,
Error_Node => N);
if U = No_Unit then
return Empty;
else
return Unit (Cunit (U));
end if;
end if;
end Load_Package_Body;
-------------------------------
-- Locate_Corresponding_Body --
-------------------------------
function Locate_Corresponding_Body (PE : Entity_Id) return Node_Id is
Spec : constant Node_Id := Declaration_Node (PE);
Decl : constant Node_Id := Parent (Spec);
Scop : constant Entity_Id := Scope (PE);
PBody : Node_Id;
begin
if Is_Library_Level_Entity (PE) then
-- If package is a library unit that requires a body, we have no
-- choice but to go after that body because it might contain an
-- optional body for the original generic package.
if Unit_Requires_Body (PE) then
-- Load the body. Note that we are a little careful here to use
-- Spec to get the unit number, rather than PE or Decl, since
-- in the case where the package is itself a library level
-- instantiation, Spec will properly reference the generic
-- template, which is what we really want.
return
Load_Package_Body
(Get_Body_Name (Unit_Name (Get_Source_Unit (Spec))));
-- But if the package is a library unit that does NOT require
-- a body, then no body is permitted, so we are sure that there
-- is no body for the original generic package.
else
return Empty;
end if;
-- Otherwise look and see if we are embedded in a further package
elsif Is_Package_Or_Generic_Package (Scop) then
-- If so, get the body of the enclosing package, and look in
-- its package body for the package body we are looking for.
PBody := Locate_Corresponding_Body (Scop);
if No (PBody) then
return Empty;
else
return Find_Body_In (PE, First (Declarations (PBody)));
end if;
-- If we are not embedded in a further package, then the body
-- must be in the same declarative part as we are.
else
return Find_Body_In (PE, Next (Decl));
end if;
end Locate_Corresponding_Body;
-- Start of processing for Has_Generic_Body
begin
if Present (Corresponding_Body (Decl)) then
return True;
elsif Unit_Requires_Body (Ent) then
return True;
-- Compilation units cannot have optional bodies
elsif Is_Compilation_Unit (Ent) then
return False;
-- Otherwise look at what scope we are in
else
Scop := Scope (Ent);
-- Case of entity is in other than a package spec, in this case
-- the body, if present, must be in the same declarative part.
if not Is_Package_Or_Generic_Package (Scop) then
declare
P : Node_Id;
begin
-- Declaration node may get us a spec, so if so, go to
-- the parent declaration.
P := Declaration_Node (Ent);
while not Is_List_Member (P) loop
P := Parent (P);
end loop;
return Present (Find_Body_In (Ent, Next (P)));
end;
-- If the entity is in a package spec, then we have to locate
-- the corresponding package body, and look there.
else
declare
PBody : constant Node_Id := Locate_Corresponding_Body (Scop);
begin
if No (PBody) then
return False;
else
return
Present
(Find_Body_In (Ent, (First (Declarations (PBody)))));
end if;
end;
end if;
end if;
end Has_Generic_Body;
-----------------------
-- Insert_Elab_Check --
-----------------------
procedure Insert_Elab_Check (N : Node_Id; C : Node_Id := Empty) is
Nod : Node_Id;
Loc : constant Source_Ptr := Sloc (N);
Chk : Node_Id;
-- The check (N_Raise_Program_Error) node to be inserted
begin
-- If expansion is disabled, do not generate any checks. Also
-- skip checks if any subunits are missing because in either
-- case we lack the full information that we need, and no object
-- file will be created in any case.
if not Expander_Active or else Subunits_Missing then
return;
end if;
-- If we have a generic instantiation, where Instance_Spec is set,
-- then this field points to a generic instance spec that has
-- been inserted before the instantiation node itself, so that
-- is where we want to insert a check.
if Nkind (N) in N_Generic_Instantiation
and then Present (Instance_Spec (N))
then
Nod := Instance_Spec (N);
else
Nod := N;
end if;
-- Build check node, possibly with condition
Chk :=
Make_Raise_Program_Error (Loc, Reason => PE_Access_Before_Elaboration);
if Present (C) then
Set_Condition (Chk, Make_Op_Not (Loc, Right_Opnd => C));
end if;
-- If we are inserting at the top level, insert in Aux_Decls
if Nkind (Parent (Nod)) = N_Compilation_Unit then
declare
ADN : constant Node_Id := Aux_Decls_Node (Parent (Nod));
begin
if No (Declarations (ADN)) then
Set_Declarations (ADN, New_List (Chk));
else
Append_To (Declarations (ADN), Chk);
end if;
Analyze (Chk);
end;
-- Otherwise just insert as an action on the node in question
else
Insert_Action (Nod, Chk);
end if;
end Insert_Elab_Check;
-------------------------------
-- Is_Call_Of_Generic_Formal --
-------------------------------
function Is_Call_Of_Generic_Formal (N : Node_Id) return Boolean is
begin
return Nkind (N) in N_Function_Call | N_Procedure_Call_Statement
-- Always return False if debug flag -gnatd.G is set
and then not Debug_Flag_Dot_GG
-- For now, we detect this by looking for the strange identifier
-- node, whose Chars reflect the name of the generic formal, but
-- the Chars of the Entity references the generic actual.
and then Nkind (Name (N)) = N_Identifier
and then Chars (Name (N)) /= Chars (Entity (Name (N)));
end Is_Call_Of_Generic_Formal;
-------------------------------
-- Is_Finalization_Procedure --
-------------------------------
function Is_Finalization_Procedure (Id : Entity_Id) return Boolean is
begin
-- Check whether Id is a procedure with at least one parameter
if Ekind (Id) = E_Procedure and then Present (First_Formal (Id)) then
declare
Typ : constant Entity_Id := Etype (First_Formal (Id));
Deep_Fin : Entity_Id := Empty;
Fin : Entity_Id := Empty;
begin
-- If the type of the first formal does not require finalization
-- actions, then this is definitely not [Deep_]Finalize.
if not Needs_Finalization (Typ) then
return False;
end if;
-- At this point we have the following scenario:
-- procedure Name (Param1 : [in] [out] Ctrl[; Param2 : ...]);
-- Recover the two possible versions of [Deep_]Finalize using the
-- type of the first parameter and compare with the input.
Deep_Fin := TSS (Typ, TSS_Deep_Finalize);
if Is_Controlled (Typ) then
Fin := Find_Prim_Op (Typ, Name_Finalize);
end if;
return (Present (Deep_Fin) and then Id = Deep_Fin)
or else (Present (Fin) and then Id = Fin);
end;
end if;
return False;
end Is_Finalization_Procedure;
------------------
-- Output_Calls --
------------------
procedure Output_Calls
(N : Node_Id;
Check_Elab_Flag : Boolean)
is
function Emit (Flag : Boolean) return Boolean;
-- Determine whether to emit an error message based on the combination
-- of flags Check_Elab_Flag and Flag.
function Is_Printable_Error_Name return Boolean;
-- An internal function, used to determine if a name, stored in the
-- Name_Buffer, is either a non-internal name, or is an internal name
-- that is printable by the error message circuits (i.e. it has a single
-- upper case letter at the end).
----------
-- Emit --
----------
function Emit (Flag : Boolean) return Boolean is
begin
if Check_Elab_Flag then
return Flag;
else
return True;
end if;
end Emit;
-----------------------------
-- Is_Printable_Error_Name --
-----------------------------
function Is_Printable_Error_Name return Boolean is
begin
if not Is_Internal_Name then
return True;
elsif Name_Len = 1 then
return False;
else
Name_Len := Name_Len - 1;
return not Is_Internal_Name;
end if;
end Is_Printable_Error_Name;
-- Local variables
Ent : Entity_Id;
-- Start of processing for Output_Calls
begin
for J in reverse 1 .. Elab_Call.Last loop
Error_Msg_Sloc := Elab_Call.Table (J).Cloc;
Ent := Elab_Call.Table (J).Ent;
Get_Name_String (Chars (Ent));
-- Dynamic elaboration model, warnings controlled by -gnatwl
if Dynamic_Elaboration_Checks then
if Emit (Elab_Warnings) then
if Is_Generic_Unit (Ent) then
Error_Msg_NE ("\\?l?& instantiated #", N, Ent);
elsif Is_Init_Proc (Ent) then
Error_Msg_N ("\\?l?initialization procedure called #", N);
elsif Is_Printable_Error_Name then
Error_Msg_NE ("\\?l?& called #", N, Ent);
else
Error_Msg_N ("\\?l?called #", N);
end if;
end if;
-- Static elaboration model, info messages controlled by -gnatel
else
if Emit (Elab_Info_Messages) then
if Is_Generic_Unit (Ent) then
Error_Msg_NE ("\\?$?& instantiated #", N, Ent);
elsif Is_Init_Proc (Ent) then
Error_Msg_N ("\\?$?initialization procedure called #", N);
elsif Is_Printable_Error_Name then
Error_Msg_NE ("\\?$?& called #", N, Ent);
else
Error_Msg_N ("\\?$?called #", N);
end if;
end if;
end if;
end loop;
end Output_Calls;
----------------------------
-- Same_Elaboration_Scope --
----------------------------
function Same_Elaboration_Scope (Scop1, Scop2 : Entity_Id) return Boolean is
S1 : Entity_Id;
S2 : Entity_Id;
begin
-- Find elaboration scope for Scop1
-- This is either a subprogram or a compilation unit.
S1 := Scop1;
while S1 /= Standard_Standard
and then not Is_Compilation_Unit (S1)
and then Ekind (S1) in E_Package | E_Protected_Type | E_Block
loop
S1 := Scope (S1);
end loop;
-- Find elaboration scope for Scop2
S2 := Scop2;
while S2 /= Standard_Standard
and then not Is_Compilation_Unit (S2)
and then Ekind (S2) in E_Package | E_Protected_Type | E_Block
loop
S2 := Scope (S2);
end loop;
return S1 = S2;
end Same_Elaboration_Scope;
-----------------
-- Set_C_Scope --
-----------------
procedure Set_C_Scope is
begin
while not Is_Compilation_Unit (C_Scope) loop
C_Scope := Scope (C_Scope);
end loop;
end Set_C_Scope;
--------------------------------
-- Set_Elaboration_Constraint --
--------------------------------
procedure Set_Elaboration_Constraint
(Call : Node_Id;
Subp : Entity_Id;
Scop : Entity_Id)
is
Elab_Unit : Entity_Id;
-- Check whether this is a call to an Initialize subprogram for a
-- controlled type. Note that Call can also be a 'Access attribute
-- reference, which now generates an elaboration check.
Init_Call : constant Boolean :=
Nkind (Call) = N_Procedure_Call_Statement
and then Chars (Subp) = Name_Initialize
and then Comes_From_Source (Subp)
and then Present (Parameter_Associations (Call))
and then Is_Controlled (Etype (First_Actual (Call)));
begin
-- If the unit is mentioned in a with_clause of the current unit, it is
-- visible, and we can set the elaboration flag.
if Is_Immediately_Visible (Scop)
or else (Is_Child_Unit (Scop) and then Is_Visible_Lib_Unit (Scop))
then
Activate_Elaborate_All_Desirable (Call, Scop);
Set_Suppress_Elaboration_Warnings (Scop);
return;
end if;
-- If this is not an initialization call or a call using object notation
-- we know that the unit of the called entity is in the context, and we
-- can set the flag as well. The unit need not be visible if the call
-- occurs within an instantiation.
if Is_Init_Proc (Subp)
or else Init_Call
or else Nkind (Original_Node (Call)) = N_Selected_Component
then
null; -- detailed processing follows.
else
Activate_Elaborate_All_Desirable (Call, Scop);
Set_Suppress_Elaboration_Warnings (Scop);
return;
end if;
-- If the unit is not in the context, there must be an intermediate unit
-- that is, on which we need to place to elaboration flag. This happens
-- with init proc calls.
if Is_Init_Proc (Subp) or else Init_Call then
-- The initialization call is on an object whose type is not declared
-- in the same scope as the subprogram. The type of the object must
-- be a subtype of the type of operation. This object is the first
-- actual in the call.
declare
Typ : constant Entity_Id :=
Etype (First (Parameter_Associations (Call)));
begin
Elab_Unit := Scope (Typ);
while (Present (Elab_Unit))
and then not Is_Compilation_Unit (Elab_Unit)
loop
Elab_Unit := Scope (Elab_Unit);
end loop;
end;
-- If original node uses selected component notation, the prefix is
-- visible and determines the scope that must be elaborated. After
-- rewriting, the prefix is the first actual in the call.
elsif Nkind (Original_Node (Call)) = N_Selected_Component then
Elab_Unit := Scope (Etype (First (Parameter_Associations (Call))));
-- Not one of special cases above
else
-- Using previously computed scope. If the elaboration check is
-- done after analysis, the scope is not visible any longer, but
-- must still be in the context.
Elab_Unit := Scop;
end if;
Activate_Elaborate_All_Desirable (Call, Elab_Unit);
Set_Suppress_Elaboration_Warnings (Elab_Unit);
end Set_Elaboration_Constraint;
-----------------
-- Spec_Entity --
-----------------
function Spec_Entity (E : Entity_Id) return Entity_Id is
Decl : Node_Id;
begin
-- Check for case of body entity
-- Why is the check for E_Void needed???
if Ekind (E) in E_Void | E_Subprogram_Body | E_Package_Body then
Decl := E;
loop
Decl := Parent (Decl);
exit when Nkind (Decl) in N_Proper_Body;
end loop;
return Corresponding_Spec (Decl);
else
return E;
end if;
end Spec_Entity;
------------
-- Within --
------------
function Within (E1, E2 : Entity_Id) return Boolean is
Scop : Entity_Id;
begin
Scop := E1;
loop
if Scop = E2 then
return True;
elsif Scop = Standard_Standard then
return False;
else
Scop := Scope (Scop);
end if;
end loop;
end Within;
--------------------------
-- Within_Elaborate_All --
--------------------------
function Within_Elaborate_All
(Unit : Unit_Number_Type;
E : Entity_Id) return Boolean
is
type Unit_Number_Set is array (Main_Unit .. Last_Unit) of Boolean;
pragma Pack (Unit_Number_Set);
Seen : Unit_Number_Set := (others => False);
-- Seen (X) is True after we have seen unit X in the walk. This is used
-- to prevent processing the same unit more than once.
Result : Boolean := False;
procedure Helper (Unit : Unit_Number_Type);
-- This helper procedure does all the work for Within_Elaborate_All. It
-- walks the dependency graph, and sets Result to True if it finds an
-- appropriate Elaborate_All.
------------
-- Helper --
------------
procedure Helper (Unit : Unit_Number_Type) is
CU : constant Node_Id := Cunit (Unit);
Item : Node_Id;
Item2 : Node_Id;
Elab_Id : Entity_Id;
Par : Node_Id;
begin
if Seen (Unit) then
return;
else
Seen (Unit) := True;
end if;
-- First, check for Elaborate_Alls on this unit
Item := First (Context_Items (CU));
while Present (Item) loop
if Nkind (Item) = N_Pragma
and then Pragma_Name (Item) = Name_Elaborate_All
then
-- Return if some previous error on the pragma itself. The
-- pragma may be unanalyzed, because of a previous error, or
-- if it is the context of a subunit, inherited by its parent.
if Error_Posted (Item) or else not Analyzed (Item) then
return;
end if;
Elab_Id :=
Entity
(Expression (First (Pragma_Argument_Associations (Item))));
if E = Elab_Id then
Result := True;
return;
end if;
Par := Parent (Unit_Declaration_Node (Elab_Id));
Item2 := First (Context_Items (Par));
while Present (Item2) loop
if Nkind (Item2) = N_With_Clause
and then Entity (Name (Item2)) = E
and then not Limited_Present (Item2)
then
Result := True;
return;
end if;
Next (Item2);
end loop;
end if;
Next (Item);
end loop;
-- Second, recurse on with's. We could do this as part of the above
-- loop, but it's probably more efficient to have two loops, because
-- the relevant Elaborate_All is likely to be on the initial unit. In
-- other words, we're walking the with's breadth-first. This part is
-- only necessary in the dynamic elaboration model.
if Dynamic_Elaboration_Checks then
Item := First (Context_Items (CU));
while Present (Item) loop
if Nkind (Item) = N_With_Clause
and then not Limited_Present (Item)
then
-- Note: the following call to Get_Cunit_Unit_Number does a
-- linear search, which could be slow, but it's OK because
-- we're about to give a warning anyway. Also, there might
-- be hundreds of units, but not millions. If it turns out
-- to be a problem, we could store the Get_Cunit_Unit_Number
-- in each N_Compilation_Unit node, but that would involve
-- rearranging N_Compilation_Unit_Aux to make room.
Helper (Get_Cunit_Unit_Number (Library_Unit (Item)));
if Result then
return;
end if;
end if;
Next (Item);
end loop;
end if;
end Helper;
-- Start of processing for Within_Elaborate_All
begin
Helper (Unit);
return Result;
end Within_Elaborate_All;
end Sem_Elab;
|
-- Copyright 2017 Jeff Foley. All rights reserved.
-- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
local json = require("json")
name = "HackerTarget"
type = "api"
function start()
setratelimit(1)
end
function vertical(ctx, domain)
scrape(ctx, {url=buildurl(domain)})
end
function buildurl(domain)
return "http://api.hackertarget.com/hostsearch/?q=" .. domain
end
function asn(ctx, addr)
local c
local cfg = datasrc_config()
local resp
local aurl = asnurl(addr)
-- Check if the response data is in the graph database
if (cfg and cfg.ttl ~= nil and cfg.ttl > 0) then
resp = obtain_response(aurl, cfg.ttl)
end
if (resp == nil or resp == "") then
local err
resp, err = request({url=aurl})
if (err ~= nil and err ~= "") then
return
end
if (cfg and cfg.ttl ~= nil and cfg.ttl > 0) then
cache_response(aurl, resp)
end
end
local j = json.decode("{\"results\": [" .. resp .. "]}")
if (j == nil or #(j.results) < 4) then
return
end
newasn(ctx, {
['addr']=addr,
asn=tonumber(j.results[2]),
prefix=j.results[3],
desc=j.results[4],
})
end
function asnurl(addr)
return "https://api.hackertarget.com/aslookup/?q=" .. addr
end
|
-----------------------------------------------------------------------
-- wiki-parsers-tests -- Unit tests for wiki parsing
-- Copyright (C) 2011, 2012, 2013, 2015, 2016, 2017, 2021 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Strings.UTF_Encoding.Wide_Wide_Strings;
with Util.Test_Caller;
with Wiki.Utils;
with Wiki.Helpers;
with Wiki.Streams.Builders;
with Wiki.Render.Text;
package body Wiki.Parsers.Tests is
use Wiki.Helpers;
package Caller is new Util.Test_Caller (Test, "Wikis.Parsers");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (bold)",
Test_Wiki_Bold'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic)",
Test_Wiki_Italic'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (italic, bold)",
Test_Wiki_Formats'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (headings)",
Test_Wiki_Section'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (lists)",
Test_Wiki_List'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (links)",
Test_Wiki_Link'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (quote)",
Test_Wiki_Quote'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (line break)",
Test_Wiki_Line_Break'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (image)",
Test_Wiki_Image'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (preformatted)",
Test_Wiki_Preformatted'Access);
Caller.Add_Test (Suite, "Test Wiki.Text.Renderer",
Test_Wiki_Text_Renderer'Access);
Caller.Add_Test (Suite, "Test Wiki.Parsers.Parse (String UTF-8)",
Test_Wiki_UTF_8'Access);
end Add_Tests;
-- ------------------------------
-- Test bold rendering.
-- ------------------------------
procedure Test_Wiki_Bold (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><b>bold</b></p>",
Wiki.Utils.To_Html ("*bold*", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x *bold* y", SYNTAX_GOOGLE),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold y</b></p>",
Wiki.Utils.To_Html ("x *bold y", SYNTAX_MIX),
"Bold rendering invalid (MIX)");
Util.Tests.Assert_Equals (T, "<p>x <b>item y</b> p</p>",
Wiki.Utils.To_Html ("x __item y__ p", SYNTAX_DOTCLEAR),
"Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x _item y_ p</p>",
Wiki.Utils.To_Html ("x _item y_ p", SYNTAX_DOTCLEAR),
"No bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <b>bold</b> y</p>",
Wiki.Utils.To_Html ("x '''bold''' y", SYNTAX_PHPBB),
"Bold rendering invalid (PHPBB)");
end Test_Wiki_Bold;
-- ------------------------------
-- Test italic rendering.
-- ------------------------------
procedure Test_Wiki_Italic (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>item</i></p>",
Wiki.Utils.To_Html ("_item_", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_MIX),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_DOTCLEAR),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i> p</p>",
Wiki.Utils.To_Html ("x ''item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x 'item y<i> p</i></p>",
Wiki.Utils.To_Html ("x 'item y'' p", SYNTAX_PHPBB),
"Italic rendering invalid");
end Test_Wiki_Italic;
-- ------------------------------
-- Test various format rendering.
-- ------------------------------
procedure Test_Wiki_Formats (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><i>it</i><b><i>bold</i></b><i>em</i></p>",
Wiki.Utils.To_Html ("_it*bold*em_", SYNTAX_GOOGLE),
"Italic+Bold rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item</i> y</p>",
Wiki.Utils.To_Html ("x _item_ y", SYNTAX_GOOGLE),
"Italic rendering invalid");
Util.Tests.Assert_Equals (T, "<p>x <i>item y</i></p>",
Wiki.Utils.To_Html ("x _item y", SYNTAX_GOOGLE),
"Italic rendering invalid");
end Test_Wiki_Formats;
-- ------------------------------
-- Test heading rendering.
-- ------------------------------
procedure Test_Wiki_Section (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<h1>item</h1>",
Wiki.Utils.To_Html ("= item =", SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h2>item</h2>",
Wiki.Utils.To_Html ("== item == ", SYNTAX_GOOGLE),
"H2 rendering invalid");
Util.Tests.Assert_Equals (T, "<h3>item</h3>",
Wiki.Utils.To_Html ("=== item === ", SYNTAX_GOOGLE),
"H3 rendering invalid");
Util.Tests.Assert_Equals (T, "<h4>item</h4>",
Wiki.Utils.To_Html ("==== item ==== ", SYNTAX_GOOGLE),
"H4 rendering invalid");
Util.Tests.Assert_Equals (T, "<h5>item</h5>",
Wiki.Utils.To_Html ("===== item =====", SYNTAX_GOOGLE),
"H5 rendering invalid");
Util.Tests.Assert_Equals (T, "<h6>item</h6>",
Wiki.Utils.To_Html ("====== item ===", SYNTAX_GOOGLE),
"H6 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==",
SYNTAX_GOOGLE),
"H1 rendering invalid");
Util.Tests.Assert_Equals (T, "<h1>item</h1><h2>item2</h2>",
Wiki.Utils.To_Html ("= item =" & CR & "== item2 ==",
SYNTAX_GOOGLE),
"H1 rendering invalid");
end Test_Wiki_Section;
-- ------------------------------
-- Test list rendering.
-- ------------------------------
procedure Test_Wiki_List (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<ol><li>item</li></ol>",
Wiki.Utils.To_Html ("# item", SYNTAX_GOOGLE),
"Ordered list rendering invalid");
Util.Tests.Assert_Equals (T, "<ol><li>item item " & ASCII.LF &
"</li><li>item2 item2" & ASCII.LF &
"</li><li><ol>item3</li></ol></ol>",
Wiki.Utils.To_Html ("# item item " & LF & "# item2 item2" & LF & "## item3",
SYNTAX_GOOGLE),
"Ordered rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html (" * item", SYNTAX_GOOGLE),
"Bullet list rendering invalid");
Util.Tests.Assert_Equals (T, "<ul><li>item</li></ul>",
Wiki.Utils.To_Html ("* item", SYNTAX_DOTCLEAR),
"Bullet list rendering invalid");
end Test_Wiki_List;
-- ------------------------------
-- Test link rendering.
-- ------------------------------
procedure Test_Wiki_Link (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[name]", SYNTAX_GOOGLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""http://www.joe.com/item"" "
& "lang=""en"" title=""some""" &
">name</a></p>",
Wiki.Utils.To_Html ("[name |http://www.joe.com/item|en|some]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_CREOLE),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p>[d</p>",
Wiki.Utils.To_Html ("[d", SYNTAX_CREOLE),
"No link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a " &
"href=""http://www.joe.com/item"">http://www.joe.com/item</a></p>",
Wiki.Utils.To_Html ("[http://www.joe.com/item]",
SYNTAX_DOTCLEAR),
"Link rendering invalid");
Util.Tests.Assert_Equals (T, "<p><a href=""name"">name</a></p>",
Wiki.Utils.To_Html ("[[name]]", SYNTAX_MEDIA_WIKI),
"Link rendering invalid");
end Test_Wiki_Link;
-- ------------------------------
-- Test quote rendering.
-- ------------------------------
procedure Test_Wiki_Quote (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><q>quote</q></p>",
Wiki.Utils.To_Html ("{{quote}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en}}", SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p><q cite=""http://www.sun.com"" lang=""en"">quote</q></p>",
Wiki.Utils.To_Html ("{{quote|en|http://www.sun.com}}",
SYNTAX_DOTCLEAR),
"Quote rendering invalid");
Util.Tests.Assert_Equals (T, "<p>{quote}}</p>",
Wiki.Utils.To_Html ("{quote}}", SYNTAX_DOTCLEAR),
"No quote rendering invalid");
end Test_Wiki_Quote;
-- ------------------------------
-- Test line break rendering.
-- ------------------------------
procedure Test_Wiki_Line_Break (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p>a<br>b</p>",
Wiki.Utils.To_Html ("a%%%b", SYNTAX_DOTCLEAR),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a<br>b</p>",
Wiki.Utils.To_Html ("a\\b", SYNTAX_CREOLE),
"Line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%%b</p>",
Wiki.Utils.To_Html ("a%%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
Util.Tests.Assert_Equals (T, "<p>a%b</p>",
Wiki.Utils.To_Html ("a%b", SYNTAX_DOTCLEAR),
"No line break rendering invalid");
end Test_Wiki_Line_Break;
-- ------------------------------
-- Test image rendering.
-- ------------------------------
procedure Test_Wiki_Image (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img src=""/image/t.png"" alt=""title"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title))", SYNTAX_DOTCLEAR),
"Image rendering invalid");
Util.Tests.Assert_Equals (T, "<p><img " &
"src=""/image/t.png"" longdesc=""describe"" alt=""title"" /></p>",
Wiki.Utils.To_Html ("((/image/t.png|title|x|describe))",
SYNTAX_DOTCLEAR),
"Image rendering invalid");
end Test_Wiki_Image;
-- ------------------------------
-- Test preformatted rendering.
-- ------------------------------
procedure Test_Wiki_Preformatted (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, "<p><tt>code</tt></p>",
Wiki.Utils.To_Html ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>* code *" & ASCII.LF & "</pre>",
Wiki.Utils.To_Html ("///" & LF & "* code *" & LF & "///",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x" & ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & LF & " item2 x" & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, "<pre>item1 x" & ASCII.LF & "item2 x"
& ASCII.LF & "item3 x"
& ASCII.LF & "</pre>",
Wiki.Utils.To_Html (" item1 x" & CR & LF & " item2 x"
& CR & LF & " item3 x",
SYNTAX_DOTCLEAR),
"Preformat rendering invalid");
end Test_Wiki_Preformatted;
-- ------------------------------
-- Test the text renderer.
-- ------------------------------
procedure Test_Wiki_Text_Renderer (T : in out Test) is
begin
Util.Tests.Assert_Equals (T, ASCII.LF & "code",
Wiki.Utils.To_Text ("{{{code}}}", SYNTAX_GOOGLE),
"Preformat rendering invalid");
Util.Tests.Assert_Equals (T, ASCII.LF & "bold item my_title" & ASCII.LF,
Wiki.Utils.To_Text ("_bold_ __item__ [my_title]", SYNTAX_GOOGLE),
"Preformat rendering invalid");
end Test_Wiki_Text_Renderer;
-- ------------------------------
-- Test the string parser with UTF-8 support.
-- ------------------------------
procedure Test_Wiki_UTF_8 (T : in out Test) is
procedure Check (Text : in Wiki.Strings.WString);
Test_Chars : constant array (Natural range <>) of Wiki.Strings.WChar
:= (Wiki.Strings.WChar'Val (16#7f#),
Wiki.Strings.WChar'Val (16#80#),
Wiki.Strings.WChar'Val (16#AE#),
Wiki.Strings.WChar'Val (16#1ff#),
Wiki.Strings.WChar'Val (16#1fff#),
Wiki.Strings.WChar'Val (16#1ffff#),
Wiki.Strings.WChar'Val (16#0fffff#));
procedure Check (Text : in Wiki.Strings.WString) is
procedure Get (Value : in Wiki.Strings.WString);
Doc : Wiki.Documents.Document;
Engine : Wiki.Parsers.Parser;
Renderer : aliased Wiki.Render.Text.Text_Renderer;
Stream : aliased Wiki.Streams.Builders.Output_Builder_Stream;
Content : constant String :=
Ada.Strings.UTF_Encoding.Wide_Wide_Strings.Encode (Text);
procedure Get (Value : in Wiki.Strings.WString) is
begin
-- Verify that we got the expected characters.
T.Assert (Wiki.Helpers.LF & Text = Value, "Invalid parsing for [" & Content & "]");
end Get;
begin
Engine.Set_Syntax (SYNTAX_MEDIA_WIKI);
Engine.Parse (Content, Doc);
Renderer.Set_Output_Stream (Stream'Unchecked_Access);
Renderer.Render (Doc);
Stream.Iterate (Get'Access);
end Check;
begin
for I in Test_Chars'Range loop
Check (Test_Chars (I) & "");
end loop;
for J in Test_Chars'Range loop
for I in Test_Chars'Range loop
Check (Test_Chars (I) & Test_Chars (J) & "");
end loop;
end loop;
end Test_Wiki_UTF_8;
end Wiki.Parsers.Tests;
|
-- This package has been generated automatically by GNATtest.
-- Do not edit any part of it, see GNATtest documentation for more details.
-- begin read only
with Gnattest_Generated;
package Tk.MainWindow.Test_Data.Tests is
type Test is new GNATtest_Generated.GNATtest_Standard.Tk.MainWindow
.Test_Data
.Test with
null record;
procedure Test_Get_Main_Window_d38719_603916(Gnattest_T: in out Test);
-- tk-mainwindow.ads:39:4:Get_Main_Window:Test_Main_Window
end Tk.MainWindow.Test_Data.Tests;
-- end read only
|
------------------------------------------------------------------------------
-- Copyright (c) 2021, Lev Kujawski.
--
-- 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 sell copies of the Software, and to permit persons to whom the
-- Software is furnished to do so.
--
-- 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.
--
-- SPDX-License-Identifier: MIT-0
--
-- File: example1.adb (Ada Subprogram Body)
-- Language: Ada (1995) [1]
-- Author: Lev Kujawski
-- Description: Executable example of Felix library usage
--
-- References:
-- [1] Information technology - Programming languages - Ada,
-- ISO/IEC 8652:1995(E), 15 Feb. 1995.
------------------------------------------------------------------------------
--
-- To run this program within the examples directory on a UNIX system,
-- execute: NLSPATH=./%N ./example1
with Ada.Numerics;
with C_Standard_IO;
with Native_Language_System;
with Standard_Text;
use Standard_Text;
procedure Example1 is
package CIO renames C_Standard_IO;
package NLS renames Native_Language_System;
type Messages_T is
(Hello, String_Length, Untranslated);
Pi : aliased constant Long_Float := 3.141593;
Mir : constant String := "мир";
Catalog_Name : constant String := "hello.cat";
Catalog : NLS.Catalog_T;
Previous_Locale : NLS.Locale_T;
procedure Put (The_Message : in Messages_T;
The_Text : in Text_T)
is
begin
CIO.Put (Item => Message (Catalog, 1, Messages_T'Pos (The_Message) + 1,
The_Text));
end Put;
begin -- Example1
NLS.Set_Locale (NLS.LC_ALL, "", Previous_Locale);
begin
NLS.Open_Catalog (Catalog, Catalog_Name);
exception
when NLS.POSIX_Error =>
CIO.Put_Line (CIO.Standard_Error,
"The " & Catalog_Name & " message catalog could not be opened;" &
" is NLSPATH set? Exiting.");
return;
end;
Put (Hello, Text & "Hello, world! π = " & Ada.Numerics.Pi & New_Line);
-- Out-of-order arguments example adapted from the Gettext manual.
Put (String_Length, Text &
"The string " & Raw (Mir) & " has " & Mir'Length & " bytes." &
New_Line);
Put (Untranslated, Text &
"Address of π: " & Pi'Address & New_Line);
Put (Untranslated, Text &
Raw ("Здравствуй, мир!") & New_Line);
Put (Untranslated, Text & Thousands_Grouping &
(-2145729980.0) & New_Line);
Put (Untranslated, Text & Positive_Sign & Thousands_Grouping &
Integer_L (102317123) & New_Line);
Put (Untranslated, Text &
"Ada.Numerics.e: " & Precision (60) & Ada.Numerics.e & New_Line);
NLS.Swap_Locale (NLS.LC_ALL, Previous_Locale);
NLS.Close_Catalog (Catalog);
end Example1;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2010-2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
-- This file is generated, don't edit it.
------------------------------------------------------------------------------
package AMF.Internals.Tables.DI_Metamodel is
pragma Preelaborate;
function MM_DI_DI return AMF.Internals.CMOF_Element;
function MC_DI_Diagram return AMF.Internals.CMOF_Element;
function MC_DI_Diagram_Element return AMF.Internals.CMOF_Element;
function MC_DI_Edge return AMF.Internals.CMOF_Element;
function MC_DI_Shape return AMF.Internals.CMOF_Element;
function MC_DI_Style return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Documentation return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Name return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Resolution return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Element_Local_Style_A_Styled_Element return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Element_Model_Element_A_Diagram_Element return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Element_Owned_Element_Diagram_Element_Owning_Element return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Element_Owning_Element_Diagram_Element_Owned_Element return AMF.Internals.CMOF_Element;
function MP_DI_Diagram_Element_Shared_Style_A_Styled_Element return AMF.Internals.CMOF_Element;
function MP_DI_Edge_Source_A_Source_Edge return AMF.Internals.CMOF_Element;
function MP_DI_Edge_Target_A_Target_Edge return AMF.Internals.CMOF_Element;
function MP_DI_Edge_Waypoint return AMF.Internals.CMOF_Element;
function MP_DI_Shape_Bounds return AMF.Internals.CMOF_Element;
function MP_DI_A_Target_Edge_Edge_Target return AMF.Internals.CMOF_Element;
function MP_DI_A_Source_Edge_Edge_Source return AMF.Internals.CMOF_Element;
function MP_DI_A_Diagram_Element_Diagram_Element_Model_Element return AMF.Internals.CMOF_Element;
function MP_DI_A_Styled_Element_Diagram_Element_Shared_Style return AMF.Internals.CMOF_Element;
function MP_DI_A_Styled_Element_Diagram_Element_Local_Style return AMF.Internals.CMOF_Element;
function MA_DI_Edge_Target_Target_Edge return AMF.Internals.CMOF_Element;
function MA_DI_Edge_Source_Source_Edge return AMF.Internals.CMOF_Element;
function MA_DI_Diagram_Element_Owned_Element_Owning_Element return AMF.Internals.CMOF_Element;
function MA_DI_Diagram_Element_Model_Element_Diagram_Element return AMF.Internals.CMOF_Element;
function MA_DI_Diagram_Element_Shared_Style_Styled_Element return AMF.Internals.CMOF_Element;
function MA_DI_Diagram_Element_Local_Style_Styled_Element return AMF.Internals.CMOF_Element;
function MB_DI return AMF.Internals.AMF_Element;
function ML_DI return AMF.Internals.AMF_Element;
private
Base : AMF.Internals.CMOF_Element := 0;
end AMF.Internals.Tables.DI_Metamodel;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017, Universidad Politécnica de Madrid --
-- --
-- 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 Measurements; use Measurements;
package body Buffer is
------------------------------------
-- Protected object specification --
------------------------------------
type Index is mod Capacity;
type Store is array (Index) of Measurement;
protected Buffer is
procedure Put (M: in Measurement);
procedure Get (M: out Measurement);
function Last return Measurement;
function Empty return Boolean;
function Full return Boolean;
private
Data : Store;
Next_In : Index := 0; -- next new item
Last_In : Index := 0; -- newest item in buffer
Next_Out : Index := 0; -- oldest item in buffer
Count : Natural := 0;
end Buffer;
---------
-- Put --
---------
procedure Put (M: in Measurement) is
begin
Buffer.Put(M);
end Put;
---------
-- Get --
---------
procedure Get (M: out Measurement) is
begin
Buffer.Get(M);
end Get;
----------
-- Last --
----------
function Last return Measurement is
begin
return Buffer.Last;
end Last;
-----------
-- Empty --
-----------
function Empty return Boolean is
begin
return Buffer.Empty;
end Empty;
function Full return Boolean is
begin
return Buffer.Full;
end Full;
---------------------------
-- Protected object body --
---------------------------
protected body Buffer is
procedure Put (M: in Measurement) is
begin
Data(Next_In) := M;
Last_In := Next_In;
Next_In := Next_In + 1;
if Count < Capacity then
Count := Count + 1;
else -- buffer full, overwrite oldest measurement
Next_Out := Next_Out + 1;
end if;
end Put;
procedure Get (M: out Measurement) is
begin
if Empty then
raise Constraint_Error;
end if;
M := Data(Next_Out);
Next_Out := Next_Out + 1;
Count := Count - 1;
end Get;
function Last return Measurement is
begin
return data(Last_In);
end Last;
function Empty return Boolean is
begin
return Count = 0;
end Empty;
function Full return Boolean is
begin
return Count = Capacity;
end Full;
end Buffer;
end Buffer;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- G N A T . S S E . V E C T O R _ T Y P E S --
-- --
-- S p e c --
-- --
-- Copyright (C) 2009-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This unit exposes the Ada __m128 like data types to represent the contents
-- of SSE registers, for use by bindings to the SSE intrinsic operations.
-- See GNAT.SSE for the list of targets where this facility is supported
package GNAT.SSE.Vector_Types is
-- The reference guide states a few usage guidelines for the C types:
-- Since these new data types are not basic ANSI C data types, you
-- must observe the following usage restrictions:
--
-- * Use new data types only on either side of an assignment, as a
-- return value, or as a parameter. You cannot use it with other
-- arithmetic expressions ("+", "-", and so on).
--
-- * Use new data types as objects in aggregates, such as unions to
-- access the byte elements and structures.
--
-- * Use new data types only with the respective intrinsics described
-- in this documentation.
type m128 is private; -- SSE >= 1
type m128d is private; -- SSE >= 2
type m128i is private; -- SSE >= 2
private
-- Each of the m128 types maps to a specific vector_type with an extra
-- "may_alias" attribute as in GCC's definitions for C, for instance in
-- xmmintrin.h:
-- /* The Intel API is flexible enough that we must allow aliasing
-- with other vector types, and their scalar components. */
-- typedef float __m128
-- __attribute__ ((__vector_size__ (16), __may_alias__));
-- /* Internal data types for implementing the intrinsics. */
-- typedef float __v4sf __attribute__ ((__vector_size__ (16)));
------------
-- m128 --
------------
-- The __m128 data type can hold four 32-bit floating-point values
type m128 is array (1 .. 4) of Float32;
for m128'Alignment use VECTOR_ALIGN;
pragma Machine_Attribute (m128, "vector_type");
pragma Machine_Attribute (m128, "may_alias");
-------------
-- m128d --
-------------
-- The __m128d data type can hold two 64-bit floating-point values
type m128d is array (1 .. 2) of Float64;
for m128d'Alignment use VECTOR_ALIGN;
pragma Machine_Attribute (m128d, "vector_type");
pragma Machine_Attribute (m128d, "may_alias");
-------------
-- m128i --
-------------
-- The __m128i data type can hold sixteen 8-bit, eight 16-bit, four 32-bit,
-- or two 64-bit integer values.
type m128i is array (1 .. 2) of Integer64;
for m128i'Alignment use VECTOR_ALIGN;
pragma Machine_Attribute (m128i, "vector_type");
pragma Machine_Attribute (m128i, "may_alias");
end GNAT.SSE.Vector_Types;
|
-- Copyright 2012-2015 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
package body Pck is
procedure Do_Nothing is
begin
null;
end Do_Nothing;
end Pck;
|
package ARM_Syntax is
--
-- Ada reference manual formatter (ARM_Form).
--
-- This package contains the database to collect the syntax summary and
-- cross-reference.
--
-- ---------------------------------------
-- Copyright 2000, 2006, 2011
-- AXE Consultants. All rights reserved.
-- P.O. Box 1512, Madison WI 53701
-- E-Mail: randy@rrsoftware.com
--
-- ARM_Form is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License version 3
-- as published by the Free Software Foundation.
--
-- AXE CONSULTANTS MAKES THIS TOOL AND SOURCE CODE AVAILABLE ON AN "AS IS"
-- BASIS AND MAKES NO WARRANTY, EXPRESS OR IMPLIED, AS TO THE ACCURACY,
-- CAPABILITY, EFFICIENCY, MERCHANTABILITY, OR FUNCTIONING OF THIS TOOL.
-- IN NO EVENT WILL AXE CONSULTANTS BE LIABLE FOR ANY GENERAL,
-- CONSEQUENTIAL, INDIRECT, INCIDENTAL, EXEMPLARY, OR SPECIAL DAMAGES,
-- EVEN IF AXE CONSULTANTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-- DAMAGES.
--
-- A copy of the GNU General Public License is available in the file
-- gpl-3-0.txt in the standard distribution of the ARM_Form tool.
-- Otherwise, see <http://www.gnu.org/licenses/>.
--
-- If the GPLv3 license is not satisfactory for your needs, a commercial
-- use license is available for this tool. Contact Randy at AXE Consultants
-- for more information.
--
-- ---------------------------------------
-- ---------------------------------------
--
-- Edit History:
--
-- 5/17/00 - RLB - Created package.
-- 5/26/00 - RLB - Added a Tabset parameter.
-- 6/22/06 - RLB - Added additional information to improve the links
-- and to be able to use the Ada 83 format for the
-- cross-reference table.
-- 10/13/06 - RLB - Added Defined flag to cross-references to eliminate
-- junk errors from not-quite-non-terminals.
-- 10/18/11 - RLB - Changed to GPLv3 license.
procedure Create;
-- Initialize the syntax database.
procedure Destroy;
-- Destroy the syntax database.
procedure Insert_Rule (
For_Clause : in String;
Rule : in String;
Tabset : in String := "");
-- Add a rule for the syntax summary. The rule appears in For_Clause.
-- Tabset provides any needed tab settings.
subtype Target_Type is String (1..5);
procedure Add_Non_Terminal (
NT_Name : in String;
For_Clause : in String;
Link_Target : out ARM_Syntax.Target_Type);
-- Add a non-terminal to the syntax list. Returns a new Link_Target
-- for the Non-Terminal.
procedure Add_Xref (
Name : in String;
Used_In : in String;
Clause : in String;
Defined : in Boolean);
-- Add a cross-reference entry.
-- The item referenced is Name, and it is referenced in the production
-- for Used_In, in Clause. It is a defined non-terminal if Defined
-- is True (thus it can be linked).
function Non_Terminal_Clause (NT_Name : in String) return String;
-- Return the clause where NT_Name is declared.
-- Returns "" if NT_Name is not a declared Non_Terminal.
function Non_Terminal_Link_Target (NT_Name : in String) return Target_Type;
-- Return the link target for NT_Name.
-- Returns " " if NT_Name is not a declared Non_Terminal.
generic
with procedure Format_Text (Text : in String;
Text_Name : in String);
procedure Report;
-- Output the fully formatted syntax summary to the
-- "Format_Text" routine. "Format_Text" allows all commands
-- for the full formatter. (Text_Name is an identifying name
-- for error messages).
generic
with procedure Format_Text (Text : in String;
Text_Name : in String);
procedure XRef;
-- Output the fully formatted syntax cross-reference to the
-- "Format_Text" routine. "Format_Text" allows all commands
-- for the full formatter. (Text_Name is an identifying name
-- for error messages).
end ARM_Syntax;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M --
-- --
-- S p e c --
-- (VxWorks 7 Kernel Version x86) --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package System is
pragma Pure;
-- Note that we take advantage of the implementation permission to make
-- this unit Pure instead of Preelaborable; see RM 13.7.1(15). In Ada
-- 2005, this is Pure in any case (AI-362).
pragma No_Elaboration_Code_All;
-- Allow the use of that restriction in units that WITH this unit
type Name is (SYSTEM_NAME_GNAT);
System_Name : constant Name := SYSTEM_NAME_GNAT;
-- System-Dependent Named Numbers
Min_Int : constant := -2 ** (Standard'Max_Integer_Size - 1);
Max_Int : constant := 2 ** (Standard'Max_Integer_Size - 1) - 1;
Max_Binary_Modulus : constant := 2 ** Standard'Max_Integer_Size;
Max_Nonbinary_Modulus : constant := 2 ** Integer'Size - 1;
Max_Base_Digits : constant := Long_Long_Float'Digits;
Max_Digits : constant := Long_Long_Float'Digits;
Max_Mantissa : constant := 63;
Fine_Delta : constant := 2.0 ** (-Max_Mantissa);
Tick : constant := 1.0 / 60.0;
-- Storage-related Declarations
type Address is private;
pragma Preelaborable_Initialization (Address);
Null_Address : constant Address;
Storage_Unit : constant := 8;
Word_Size : constant := 32;
Memory_Size : constant := 2 ** 32;
-- Address comparison
function "<" (Left, Right : Address) return Boolean;
function "<=" (Left, Right : Address) return Boolean;
function ">" (Left, Right : Address) return Boolean;
function ">=" (Left, Right : Address) return Boolean;
function "=" (Left, Right : Address) return Boolean;
pragma Import (Intrinsic, "<");
pragma Import (Intrinsic, "<=");
pragma Import (Intrinsic, ">");
pragma Import (Intrinsic, ">=");
pragma Import (Intrinsic, "=");
-- Other System-Dependent Declarations
type Bit_Order is (High_Order_First, Low_Order_First);
Default_Bit_Order : constant Bit_Order := Low_Order_First;
pragma Warnings (Off, Default_Bit_Order); -- kill constant condition warning
-- Priority-related Declarations (RM D.1)
-- Ada priorities are mapped to VxWorks priorities using the following
-- transformation: 255 - Ada Priority
-- Ada priorities are used as follows:
-- 256 is reserved for the VxWorks kernel
-- 248 - 255 correspond to hardware interrupt levels 0 .. 7
-- 247 is a catchall default "interrupt" priority for signals,
-- allowing higher priority than normal tasks, but lower than
-- hardware priority levels. Protected Object ceilings can
-- override these values.
-- 246 is used by the Interrupt_Manager task
Max_Priority : constant Positive := 245;
Max_Interrupt_Priority : constant Positive := 255;
subtype Any_Priority is Integer range 0 .. 255;
subtype Priority is Any_Priority range 0 .. 245;
subtype Interrupt_Priority is Any_Priority range 246 .. 255;
Default_Priority : constant Priority := 122;
private
type Address is mod Memory_Size;
Null_Address : constant Address := 0;
--------------------------------------
-- System Implementation Parameters --
--------------------------------------
-- These parameters provide information about the target that is used
-- by the compiler. They are in the private part of System, where they
-- can be accessed using the special circuitry in the Targparm unit
-- whose source should be consulted for more detailed descriptions
-- of the individual switch values.
Backend_Divide_Checks : constant Boolean := False;
Backend_Overflow_Checks : constant Boolean := True;
Command_Line_Args : constant Boolean := False;
Configurable_Run_Time : constant Boolean := False;
Denorm : constant Boolean := True;
Duration_32_Bits : constant Boolean := False;
Exit_Status_Supported : constant Boolean := True;
Fractional_Fixed_Ops : constant Boolean := False;
Frontend_Layout : constant Boolean := False;
Machine_Overflows : constant Boolean := False;
Machine_Rounds : constant Boolean := True;
Preallocated_Stacks : constant Boolean := False;
Signed_Zeros : constant Boolean := True;
Stack_Check_Default : constant Boolean := False;
Stack_Check_Probes : constant Boolean := True;
Stack_Check_Limits : constant Boolean := False;
Support_Aggregates : constant Boolean := True;
Support_Atomic_Primitives : constant Boolean := True;
Support_Composite_Assign : constant Boolean := True;
Support_Composite_Compare : constant Boolean := True;
Support_Long_Shifts : constant Boolean := True;
Always_Compatible_Rep : constant Boolean := False;
Suppress_Standard_Library : constant Boolean := False;
Use_Ada_Main_Program_Name : constant Boolean := True;
Frontend_Exceptions : constant Boolean := False;
ZCX_By_Default : constant Boolean := True;
Executable_Extension : constant String := ".out";
end System;
|
with HAL.I2C; use HAL.I2C;
use HAL;
package T67XX_I2C_IO is
type Delay_Procedure_Type is access procedure;
type IO_Port is tagged record
Port : Any_I2C_Port;
Device : I2C_Address;
Ptr : Delay_Procedure_Type;
end record;
type Any_IO_Port is access all IO_Port'Class;
procedure Read
(This : Any_IO_Port;
Func : UInt8;
Register : UInt16;
Nxfer : UInt16;
Response : out I2C_Data);
private
type T67XX_Frame is record
Func : UInt8;
RegNum : UInt16;
NReg : UInt16;
end record
with Pack;
procedure Swap (X : in out UInt16);
end T67XX_I2C_IO;
|
-- { dg-do compile }
-- { dg-options "-gnatws" }
procedure Discr17 is
F1_Poe : Integer := 18;
function F1 return Integer is
begin
F1_Poe := F1_Poe - 1;
return F1_Poe;
end F1;
generic
type T is limited private;
with function Is_Ok (X : T) return Boolean;
procedure Check;
procedure Check is
begin
declare
type Poe is new T;
X : Poe;
Y : Poe;
begin
null;
end;
declare
type Poe is new T;
type Arr is array (1 .. 2) of Poe;
X : Arr;
B : Boolean := Is_Ok (T (X (1)));
begin
null;
end;
end;
protected type Poe (D3 : Integer := F1) is
entry E (D3 .. F1); -- F1 evaluated
function Is_Ok return Boolean;
end Poe;
protected body Poe is
entry E (for I in D3 .. F1) when True is
begin
null;
end E;
function Is_Ok return Boolean is
begin
return False;
end Is_Ok;
end Poe;
function Is_Ok (C : Poe) return Boolean is
begin
return C.Is_Ok;
end Is_Ok;
procedure Chk is new Check (Poe, Is_Ok);
begin
Chk;
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- G N A T . I O --
-- --
-- B o d y --
-- --
-- Copyright (C) 1995-2006, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- 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. --
-- --
------------------------------------------------------------------------------
package body GNAT.IO is
Current_Out : File_Type := Stdout;
pragma Atomic (Current_Out);
-- Current output file (modified by Set_Output)
---------
-- Get --
---------
procedure Get (X : out Integer) is
function Get_Int return Integer;
pragma Import (C, Get_Int, "get_int");
begin
X := Get_Int;
end Get;
procedure Get (C : out Character) is
function Get_Char return Character;
pragma Import (C, Get_Char, "get_char");
begin
C := Get_Char;
end Get;
--------------
-- Get_Line --
--------------
procedure Get_Line (Item : out String; Last : out Natural) is
C : Character;
begin
for Nstore in Item'Range loop
Get (C);
if C = ASCII.LF then
Last := Nstore - 1;
return;
else
Item (Nstore) := C;
end if;
end loop;
Last := Item'Last;
end Get_Line;
--------------
-- New_Line --
--------------
procedure New_Line (File : File_Type; Spacing : Positive := 1) is
begin
for J in 1 .. Spacing loop
Put (File, ASCII.LF);
end loop;
end New_Line;
procedure New_Line (Spacing : Positive := 1) is
begin
New_Line (Current_Out, Spacing);
end New_Line;
---------
-- Put --
---------
procedure Put (X : Integer) is
begin
Put (Current_Out, X);
end Put;
procedure Put (File : File_Type; X : Integer) is
procedure Put_Int (X : Integer);
pragma Import (C, Put_Int, "put_int");
procedure Put_Int_Stderr (X : Integer);
pragma Import (C, Put_Int_Stderr, "put_int_stderr");
begin
case File is
when Stdout => Put_Int (X);
when Stderr => Put_Int_Stderr (X);
end case;
end Put;
procedure Put (C : Character) is
begin
Put (Current_Out, C);
end Put;
procedure Put (File : File_Type; C : Character) is
procedure Put_Char (C : Character);
pragma Import (C, Put_Char, "put_char");
procedure Put_Char_Stderr (C : Character);
pragma Import (C, Put_Char_Stderr, "put_char_stderr");
begin
case File is
when Stdout => Put_Char (C);
when Stderr => Put_Char_Stderr (C);
end case;
end Put;
procedure Put (S : String) is
begin
Put (Current_Out, S);
end Put;
procedure Put (File : File_Type; S : String) is
begin
for J in S'Range loop
Put (File, S (J));
end loop;
end Put;
--------------
-- Put_Line --
--------------
procedure Put_Line (S : String) is
begin
Put_Line (Current_Out, S);
end Put_Line;
procedure Put_Line (File : File_Type; S : String) is
begin
Put (File, S);
New_Line (File);
end Put_Line;
----------------
-- Set_Output --
----------------
procedure Set_Output (File : File_Type) is
begin
Current_Out := File;
end Set_Output;
---------------------
-- Standard_Output --
---------------------
function Standard_Output return File_Type is
begin
return Stdout;
end Standard_Output;
--------------------
-- Standard_Error --
--------------------
function Standard_Error return File_Type is
begin
return Stderr;
end Standard_Error;
end GNAT.IO;
|
with Device; use Device;
with Memory.Container; use Memory.Container;
package body Memory.Transform.Shift is
function Create_Shift return Shift_Pointer is
result : constant Shift_Pointer := new Shift_Type;
begin
return result;
end Create_Shift;
function Random_Shift(next : access Memory_Type'Class;
generator : Distribution_Type;
max_cost : Cost_Type) return Memory_Pointer is
result : constant Shift_Pointer := Create_Shift;
abits : constant Positive := Get_Address_Bits;
begin
Set_Memory(result.all, next);
result.value := Long_Integer((Random(generator) mod abits)) + 1;
return Memory_Pointer(result);
end Random_Shift;
function Clone(mem : Shift_Type) return Memory_Pointer is
result : constant Shift_Pointer := new Shift_Type'(mem);
begin
return Memory_Pointer(result);
end Clone;
procedure Permute(mem : in out Shift_Type;
generator : in Distribution_Type;
max_cost : in Cost_Type) is
abits : constant Positive := Get_Address_Bits;
begin
mem.value := Long_Integer((Random(generator) mod abits)) + 1;
end Permute;
function Get_Name(mem : Shift_Type) return String is
begin
return "shift";
end Get_Name;
function Apply(mem : Shift_Type;
address : Address_Type;
dir : Boolean) return Address_Type is
abits : constant Integer := Get_Address_Bits;
wsize : constant Address_Type := Address_Type(Get_Word_Size(mem));
wbits : constant Natural := Log2(Natural(wsize)) - 1;
caddr : constant Address_Type := address mod wsize;
saddr : constant Address_Type := address / wsize;
shift : Long_Integer := mem.value;
rmult : Address_Type;
lmult : Address_Type;
result : Address_Type;
begin
if shift < 0 then
shift := Long_Integer(abits - wbits) + shift;
end if;
shift := shift mod Long_Integer(abits - wbits);
rmult := Address_Type(2) ** Natural(shift);
lmult := Address_Type(2) ** (abits - Natural(shift) - wbits);
if dir then
result := ((saddr * rmult) or (saddr / lmult)) * wsize or caddr;
else
result := ((saddr * lmult) or (saddr / rmult)) * wsize or caddr;
end if;
return result and ((Address_Type(2) ** abits) - 1);
end Apply;
function Is_Empty(mem : Shift_Type) return Boolean is
begin
return mem.value = 0;
end Is_Empty;
function Get_Alignment(mem : Shift_Type) return Positive is
begin
return Get_Word_Size(mem);
end Get_Alignment;
function Get_Transform_Length(mem : Shift_Type) return Natural is
begin
return 0;
end Get_Transform_Length;
end Memory.Transform.Shift;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . R E S T R I C T I O N S --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package body System.Restrictions is
use Rident;
-------------------
-- Abort_Allowed --
-------------------
function Abort_Allowed return Boolean is
begin
return Run_Time_Restrictions.Violated (No_Abort_Statements)
or else
Run_Time_Restrictions.Violated (Max_Asynchronous_Select_Nesting);
end Abort_Allowed;
---------------------
-- Tasking_Allowed --
---------------------
function Tasking_Allowed return Boolean is
begin
return Run_Time_Restrictions.Violated (Max_Tasks)
or else
Run_Time_Restrictions.Violated (No_Tasking);
end Tasking_Allowed;
-- Package elaboration code (acquire restrictions)
begin
Acquire_Restrictions : declare
subtype Big_String is String (Positive);
type Big_String_Ptr is access all Big_String;
RString : Big_String_Ptr;
pragma Import (C, RString, "__gl_restrictions");
P : Natural := 1;
-- Pointer to scan string
C : Character;
-- Next character from string
function Get_Char return Character;
-- Get next character from string
function Get_Natural return Natural;
-- Scan out natural value known to be in range, updating P past it
--------------
-- Get_Char --
--------------
function Get_Char return Character is
begin
P := P + 1;
return RString (P - 1);
end Get_Char;
-----------------
-- Get_Natural --
-----------------
function Get_Natural return Natural is
N : Natural := 0;
begin
while RString (P) in '0' .. '9' loop
N := N * 10 + (Character'Pos (Get_Char) - Character'Pos ('0'));
end loop;
return N;
end Get_Natural;
-- Start of processing for Acquire_Restrictions
begin
-- Acquire data corresponding to first R line
for R in All_Boolean_Restrictions loop
C := Get_Char;
if C = 'v' then
Run_Time_Restrictions.Violated (R) := True;
elsif C = 'r' then
Run_Time_Restrictions.Set (R) := True;
end if;
end loop;
-- Acquire data corresponding to second R line
for RP in All_Parameter_Restrictions loop
-- Acquire restrictions pragma information
if Get_Char = 'r' then
Run_Time_Restrictions.Set (RP) := True;
Run_Time_Restrictions.Value (RP) := Get_Natural;
end if;
-- Acquire restrictions violations information
if Get_Char = 'v' then
Run_Time_Restrictions.Violated (RP) := True;
Run_Time_Restrictions.Count (RP) := Get_Natural;
if RString (P) = '+' then
Run_Time_Restrictions.Unknown (RP) := True;
P := P + 1;
end if;
end if;
end loop;
end Acquire_Restrictions;
end System.Restrictions;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M _ I O --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2009, 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. --
-- --
------------------------------------------------------------------------------
-- A simple text I/O package, used for diagnostic output in the runtime,
-- This package is also preelaborated, unlike Text_Io, and can thus be
-- with'ed by preelaborated library units. It includes only Put routines
-- for character, integer, string and a new line function
package System.IO is
pragma Preelaborate;
procedure Put (X : Integer);
procedure Put (C : Character);
procedure Put (S : String);
procedure Put_Line (S : String);
procedure New_Line (Spacing : Positive := 1);
type File_Type is limited private;
function Standard_Error return File_Type;
function Standard_Output return File_Type;
procedure Set_Output (File : File_Type);
private
type File_Type is (Stdout, Stderr);
-- Stdout = Standard_Output, Stderr = Standard_Error
pragma Inline (Standard_Error);
pragma Inline (Standard_Output);
end System.IO;
|
-----------------------------------------------------------------------
-- util-http-clients-curl -- HTTP Clients with CURL
-- 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 System;
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.Strings.Unbounded;
with Util.Http.Mockups;
package Util.Http.Clients.Curl is
-- Register the CURL Http manager.
procedure Register;
private
package C renames Interfaces.C;
package Strings renames Interfaces.C.Strings;
use type C.size_t;
use type C.int;
-- Define 'Int' and 'Chars_Ptr' with capitals to avoid GNAT warnings due
-- to Eclipse capitalization.
subtype Int is C.int;
subtype Chars_Ptr is Strings.chars_ptr;
subtype Size_T is C.size_t;
subtype CURL is System.Address;
type CURL_Code is new Interfaces.C.int;
CURLE_OK : constant CURL_Code := 0;
type CURL_Info is new Int;
type Curl_Option is new Int;
type CURL_Slist;
type CURL_Slist_Access is access CURL_Slist;
type CURL_Slist is record
Data : Chars_Ptr;
Next : CURL_Slist_Access;
end record;
-- Check the CURL result code and report and exception and a log message if
-- the CURL code indicates an error.
procedure Check_Code (Code : in CURL_Code;
Message : in String);
type Curl_Http_Manager is new Http_Manager with null record;
type Curl_Http_Manager_Access is access all Http_Manager'Class;
-- Create a new HTTP request associated with the current request manager.
procedure Create (Manager : in Curl_Http_Manager;
Http : in out Client'Class);
procedure Do_Get (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Reply : out Response'Class);
procedure Do_Post (Manager : in Curl_Http_Manager;
Http : in Client'Class;
URI : in String;
Data : in String;
Reply : out Response'Class);
type Curl_Http_Request is new Util.Http.Mockups.Mockup_Request with record
Data : CURL := System.Null_Address;
URL : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Content : Chars_Ptr := Interfaces.C.Strings.Null_Ptr;
Headers : CURL_Slist_Access := null;
end record;
type Curl_Http_Request_Access is access all Curl_Http_Request'Class;
overriding
procedure Finalize (Request : in out Curl_Http_Request);
type Curl_Http_Response is new Util.Http.Mockups.Mockup_Response with record
C : CURL;
Content : Ada.Strings.Unbounded.Unbounded_String;
Status : Natural;
Parsing_Body : Boolean := False;
end record;
type Curl_Http_Response_Access is access all Curl_Http_Response'Class;
-- Get the response body as a string.
overriding
function Get_Body (Reply : in Curl_Http_Response) return String;
-- Get the response status code.
overriding
function Get_Status (Reply : in Curl_Http_Response) return Natural;
-- Add a string to a CURL slist.
function Curl_Slist_Append (List : in CURL_Slist_Access;
Value : in Chars_Ptr) return CURL_Slist_Access;
pragma Import (C, Curl_Slist_Append, "curl_slist_append");
-- Free an entrire CURL slist.
procedure Curl_Slist_Free_All (List : in CURL_Slist_Access);
pragma Import (C, Curl_Slist_Free_All, "curl_slist_free_all");
-- Start a libcurl easy session.
function Curl_Easy_Init return CURL;
pragma Import (C, Curl_Easy_Init, "curl_easy_init");
-- End a libcurl easy session.
procedure Curl_Easy_Cleanup (Handle : in CURL);
pragma Import (C, Curl_Easy_Cleanup, "curl_easy_cleanup");
-- Perform a file transfer.
function Curl_Easy_Perform (Handle : in CURL) return CURL_Code;
pragma Import (C, Curl_Easy_Perform, "curl_easy_perform");
-- Return the error message which correspond to the given CURL error code.
function Curl_Easy_Strerror (Code : in CURL_Code) return Chars_Ptr;
pragma Import (C, Curl_Easy_Strerror, "curl_easy_strerror");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_String (Handle : in CURL;
Option : in Curl_Option;
Value : in Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_String, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Long (Handle : in CURL;
Option : in Curl_Option;
Value : in Interfaces.C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Long, "curl_easy_setopt");
-- Get information from a CURL handle for an option returning a String.
function Curl_Easy_Getinfo_String (Handle : in CURL;
Option : in CURL_Info;
Value : access Chars_Ptr) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_String, "curl_easy_getinfo");
-- Get information from a CURL handle for an option returning a Long.
function Curl_Easy_Getinfo_Long (Handle : in CURL;
Option : in CURL_Info;
Value : access C.long) return CURL_Code;
pragma Import (C, Curl_Easy_Getinfo_Long, "curl_easy_getinfo");
function Curl_Easy_Setopt_Write_Callback
(Handle : in CURL;
Option : in Curl_Option;
Func : access function (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Ptr : in Curl_Http_Response_Access) return Size_T)
return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Write_Callback, "curl_easy_setopt");
-- Set options for a curl easy handle.
function Curl_Easy_Setopt_Data (Handle : in CURL;
Option : in Curl_Option;
Value : in Curl_Http_Response_Access) return CURL_Code;
pragma Import (C, Curl_Easy_Setopt_Data, "curl_easy_setopt");
function Read_Response (Data : in Chars_Ptr;
Size : in Size_T;
Nmemb : in Size_T;
Response : in Curl_Http_Response_Access) return Size_T;
end Util.Http.Clients.Curl;
|
-- Ada Standard Libraries
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
-- TJa. Libraries
with TJa.Keyboard; use TJa.Keyboard;
with TJa.Window.Elementary; use TJa.Window.Elementary;
package logic is
--------------------------------------------------------------------------------
type Random_Array_Type is
array (1..2) of Integer;
type Position_Type is
array (1..2) of Integer;
type Snake_Position_Type is
array(Positive Range <>) of Position_Type;
type Coordinate is
array(1..2) of Integer;
type Coordinate_Matrix is
array (Positive Range <>, Positive Range <>) of Coordinate;
type Score_Type is
record
Name : String(1..3);
Score : Integer;
end record;
type Highscore_List_Type is
array(1..3) of Score_Type;
--------------------------------------------------------------------------------
dx, dy : Integer := 0;
--------------------------------------------------------------------------------
procedure Update_Position(X_Pos, Y_Pos : in out Integer);
procedure Update_Direction(Key : in Key_Type);
procedure Init_Snake(Snake : in out Snake_Position_Type);
procedure Check_Snake_Intersection(Length : in Integer; Snake : in Snake_Position_Type; Running : in out Boolean);
procedure Check_Exit_Game(Key : in Key_Type; Running : out Boolean);
procedure Fill_Matrix(X, Y, Size_X, Size_Y : in Integer; Matrix : out Coordinate_Matrix);
procedure Put_Highscore(X_Placement, Y_Placement : in Integer; Highscore_List : in Highscore_List_Type);
procedure Read_Highscore(File_Name : in String; Highscore_List : out Highscore_List_Type);
procedure Add_Score(New_Name : in String; New_Score : in Integer; Highscore_List : out Highscore_List_Type);
procedure Write_Highscore(File_Name : in String; Highscore_List : in Highscore_List_Type);
procedure Swap_Scores(New_Score, Old_Score : in out Score_Type);
procedure Sort_Scores(Highscore_List : in out Highscore_List_Type);
--------------------------------------------------------------------------------
function Check_Fruit(X_Pos, Y_pos, Snake_X, Snake_Y, Fruit_X, Fruit_Y : in Integer; Fruit_Pos : in Random_Array_Type)
return Boolean;
function Random_Coordinate(StartX, StartY, Width, Height, Size_Of_Water : in Integer)
return Random_Array_Type;
--------------------------------------------------------------------------------
private
end logic;
|
-- Copyright 2010-2017 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Pck; use Pck;
procedure Foo is
New_Node : Node_Id;
begin
New_Node := Pn (1234); -- STOP
end Foo;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- G N A T . E X P E C T --
-- --
-- B o d y --
-- --
-- Copyright (C) 2000-2016, 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. --
-- --
------------------------------------------------------------------------------
with System; use System;
with System.OS_Constants; use System.OS_Constants;
with Ada.Calendar; use Ada.Calendar;
with GNAT.IO; use GNAT.IO;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.Regpat; use GNAT.Regpat;
with Ada.Unchecked_Deallocation;
package body GNAT.Expect is
type Array_Of_Pd is array (Positive range <>) of Process_Descriptor_Access;
Expect_Process_Died : constant Expect_Match := -100;
Expect_Internal_Error : constant Expect_Match := -101;
-- Additional possible outputs of Expect_Internal. These are not visible in
-- the spec because the user will never see them.
procedure Expect_Internal
(Descriptors : in out Array_Of_Pd;
Result : out Expect_Match;
Timeout : Integer;
Full_Buffer : Boolean);
-- Internal function used to read from the process Descriptor.
--
-- Several outputs are possible:
-- Result=Expect_Timeout, if no output was available before the timeout
-- expired.
-- Result=Expect_Full_Buffer, if Full_Buffer is True and some characters
-- had to be discarded from the internal buffer of Descriptor.
-- Result=Express_Process_Died if one of the processes was terminated.
-- That process's Input_Fd is set to Invalid_FD
-- Result=Express_Internal_Error
-- Result=<integer>, indicates how many characters were added to the
-- internal buffer. These characters are from indexes
-- Descriptor.Buffer_Index - Result + 1 .. Descriptor.Buffer_Index
-- Process_Died is raised if the process is no longer valid.
procedure Reinitialize_Buffer
(Descriptor : in out Process_Descriptor'Class);
-- Reinitialize the internal buffer.
-- The buffer is deleted up to the end of the last match.
procedure Free is new Ada.Unchecked_Deallocation
(Pattern_Matcher, Pattern_Matcher_Access);
procedure Free is new Ada.Unchecked_Deallocation
(Filter_List_Elem, Filter_List);
procedure Call_Filters
(Pid : Process_Descriptor'Class;
Str : String;
Filter_On : Filter_Type);
-- Call all the filters that have the appropriate type.
-- This function does nothing if the filters are locked
------------------------------
-- Target dependent section --
------------------------------
function Dup (Fd : File_Descriptor) return File_Descriptor;
pragma Import (C, Dup);
procedure Dup2 (Old_Fd, New_Fd : File_Descriptor);
pragma Import (C, Dup2);
procedure Kill (Pid : Process_Id; Sig_Num : Integer; Close : Integer);
pragma Import (C, Kill, "__gnat_kill");
-- if Close is set to 1 all OS resources used by the Pid must be freed
function Create_Pipe (Pipe : not null access Pipe_Type) return Integer;
pragma Import (C, Create_Pipe, "__gnat_pipe");
function Poll
(Fds : System.Address;
Num_Fds : Integer;
Timeout : Integer;
Dead_Process : access Integer;
Is_Set : System.Address) return Integer;
pragma Import (C, Poll, "__gnat_expect_poll");
-- Check whether there is any data waiting on the file descriptors
-- Fds, and wait if there is none, at most Timeout milliseconds
-- Returns -1 in case of error, 0 if the timeout expired before
-- data became available.
--
-- Is_Set is an array of the same size as FDs and elements are set to 1 if
-- data is available for the corresponding File Descriptor, 0 otherwise.
--
-- If a process dies, then Dead_Process is set to the index of the
-- corresponding file descriptor.
function Waitpid (Pid : Process_Id) return Integer;
pragma Import (C, Waitpid, "__gnat_waitpid");
-- Wait for a specific process id, and return its exit code
---------
-- "+" --
---------
function "+" (S : String) return GNAT.OS_Lib.String_Access is
begin
return new String'(S);
end "+";
---------
-- "+" --
---------
function "+"
(P : GNAT.Regpat.Pattern_Matcher) return Pattern_Matcher_Access
is
begin
return new GNAT.Regpat.Pattern_Matcher'(P);
end "+";
----------------
-- Add_Filter --
----------------
procedure Add_Filter
(Descriptor : in out Process_Descriptor;
Filter : Filter_Function;
Filter_On : Filter_Type := Output;
User_Data : System.Address := System.Null_Address;
After : Boolean := False)
is
Current : Filter_List := Descriptor.Filters;
begin
if After then
while Current /= null and then Current.Next /= null loop
Current := Current.Next;
end loop;
if Current = null then
Descriptor.Filters :=
new Filter_List_Elem'
(Filter => Filter, Filter_On => Filter_On,
User_Data => User_Data, Next => null);
else
Current.Next :=
new Filter_List_Elem'
(Filter => Filter, Filter_On => Filter_On,
User_Data => User_Data, Next => null);
end if;
else
Descriptor.Filters :=
new Filter_List_Elem'
(Filter => Filter, Filter_On => Filter_On,
User_Data => User_Data, Next => Descriptor.Filters);
end if;
end Add_Filter;
------------------
-- Call_Filters --
------------------
procedure Call_Filters
(Pid : Process_Descriptor'Class;
Str : String;
Filter_On : Filter_Type)
is
Current_Filter : Filter_List;
begin
if Pid.Filters_Lock = 0 then
Current_Filter := Pid.Filters;
while Current_Filter /= null loop
if Current_Filter.Filter_On = Filter_On then
Current_Filter.Filter
(Pid, Str, Current_Filter.User_Data);
end if;
Current_Filter := Current_Filter.Next;
end loop;
end if;
end Call_Filters;
-----------
-- Close --
-----------
procedure Close
(Descriptor : in out Process_Descriptor;
Status : out Integer)
is
Current_Filter : Filter_List;
Next_Filter : Filter_List;
begin
if Descriptor.Input_Fd /= Invalid_FD then
Close (Descriptor.Input_Fd);
end if;
if Descriptor.Error_Fd /= Descriptor.Output_Fd then
Close (Descriptor.Error_Fd);
end if;
Close (Descriptor.Output_Fd);
-- ??? Should have timeouts for different signals
if Descriptor.Pid > 0 then -- see comment in Send_Signal
Kill (Descriptor.Pid, Sig_Num => 9, Close => 0);
end if;
GNAT.OS_Lib.Free (Descriptor.Buffer);
Descriptor.Buffer_Size := 0;
Current_Filter := Descriptor.Filters;
while Current_Filter /= null loop
Next_Filter := Current_Filter.Next;
Free (Current_Filter);
Current_Filter := Next_Filter;
end loop;
Descriptor.Filters := null;
-- Check process id (see comment in Send_Signal)
if Descriptor.Pid > 0 then
Status := Waitpid (Descriptor.Pid);
else
raise Invalid_Process;
end if;
end Close;
procedure Close (Descriptor : in out Process_Descriptor) is
Status : Integer;
pragma Unreferenced (Status);
begin
Close (Descriptor, Status);
end Close;
------------
-- Expect --
------------
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexp : String;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
begin
if Regexp = "" then
Expect (Descriptor, Result, Never_Match, Timeout, Full_Buffer);
else
Expect (Descriptor, Result, Compile (Regexp), Timeout, Full_Buffer);
end if;
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexp : String;
Matched : out GNAT.Regpat.Match_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
begin
pragma Assert (Matched'First = 0);
if Regexp = "" then
Expect
(Descriptor, Result, Never_Match, Matched, Timeout, Full_Buffer);
else
Expect
(Descriptor, Result, Compile (Regexp), Matched, Timeout,
Full_Buffer);
end if;
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexp : GNAT.Regpat.Pattern_Matcher;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
Matched : GNAT.Regpat.Match_Array (0 .. 0);
pragma Warnings (Off, Matched);
begin
Expect (Descriptor, Result, Regexp, Matched, Timeout, Full_Buffer);
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexp : GNAT.Regpat.Pattern_Matcher;
Matched : out GNAT.Regpat.Match_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
N : Expect_Match;
Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
Try_Until : constant Time := Clock + Duration (Timeout) / 1000.0;
Timeout_Tmp : Integer := Timeout;
begin
pragma Assert (Matched'First = 0);
Reinitialize_Buffer (Descriptor);
loop
-- First, test if what is already in the buffer matches (This is
-- required if this package is used in multi-task mode, since one of
-- the tasks might have added something in the buffer, and we don't
-- want other tasks to wait for new input to be available before
-- checking the regexps).
Match
(Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
if Descriptor.Buffer_Index >= 1 and then Matched (0).First /= 0 then
Result := 1;
Descriptor.Last_Match_Start := Matched (0).First;
Descriptor.Last_Match_End := Matched (0).Last;
return;
end if;
-- Else try to read new input
Expect_Internal (Descriptors, N, Timeout_Tmp, Full_Buffer);
case N is
when Expect_Internal_Error
| Expect_Process_Died
=>
raise Process_Died;
when Expect_Full_Buffer
| Expect_Timeout
=>
Result := N;
return;
when others =>
null; -- See below
end case;
-- Calculate the timeout for the next turn
-- Note that Timeout is, from the caller's perspective, the maximum
-- time until a match, not the maximum time until some output is
-- read, and thus cannot be reused as is for Expect_Internal.
if Timeout /= -1 then
Timeout_Tmp := Integer (Try_Until - Clock) * 1000;
if Timeout_Tmp < 0 then
Result := Expect_Timeout;
exit;
end if;
end if;
end loop;
-- Even if we had the general timeout above, we have to test that the
-- last test we read from the external process didn't match.
Match
(Regexp, Descriptor.Buffer (1 .. Descriptor.Buffer_Index), Matched);
if Matched (0).First /= 0 then
Result := 1;
Descriptor.Last_Match_Start := Matched (0).First;
Descriptor.Last_Match_End := Matched (0).Last;
return;
end if;
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexps : Regexp_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
Patterns : Compiled_Regexp_Array (Regexps'Range);
Matched : GNAT.Regpat.Match_Array (0 .. 0);
pragma Warnings (Off, Matched);
begin
for J in Regexps'Range loop
Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
end loop;
Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
for J in Regexps'Range loop
Free (Patterns (J));
end loop;
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexps : Compiled_Regexp_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
Matched : GNAT.Regpat.Match_Array (0 .. 0);
pragma Warnings (Off, Matched);
begin
Expect (Descriptor, Result, Regexps, Matched, Timeout, Full_Buffer);
end Expect;
procedure Expect
(Result : out Expect_Match;
Regexps : Multiprocess_Regexp_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
Matched : GNAT.Regpat.Match_Array (0 .. 0);
pragma Warnings (Off, Matched);
begin
Expect (Result, Regexps, Matched, Timeout, Full_Buffer);
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexps : Regexp_Array;
Matched : out GNAT.Regpat.Match_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
Patterns : Compiled_Regexp_Array (Regexps'Range);
begin
pragma Assert (Matched'First = 0);
for J in Regexps'Range loop
Patterns (J) := new Pattern_Matcher'(Compile (Regexps (J).all));
end loop;
Expect (Descriptor, Result, Patterns, Matched, Timeout, Full_Buffer);
for J in Regexps'Range loop
Free (Patterns (J));
end loop;
end Expect;
procedure Expect
(Descriptor : in out Process_Descriptor;
Result : out Expect_Match;
Regexps : Compiled_Regexp_Array;
Matched : out GNAT.Regpat.Match_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
N : Expect_Match;
Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
begin
pragma Assert (Matched'First = 0);
Reinitialize_Buffer (Descriptor);
loop
-- First, test if what is already in the buffer matches (This is
-- required if this package is used in multi-task mode, since one of
-- the tasks might have added something in the buffer, and we don't
-- want other tasks to wait for new input to be available before
-- checking the regexps).
if Descriptor.Buffer /= null then
for J in Regexps'Range loop
Match
(Regexps (J).all,
Descriptor.Buffer (1 .. Descriptor.Buffer_Index),
Matched);
if Matched (0) /= No_Match then
Result := Expect_Match (J);
Descriptor.Last_Match_Start := Matched (0).First;
Descriptor.Last_Match_End := Matched (0).Last;
return;
end if;
end loop;
end if;
Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
case N is
when Expect_Internal_Error
| Expect_Process_Died
=>
raise Process_Died;
when Expect_Full_Buffer
| Expect_Timeout
=>
Result := N;
return;
when others =>
null; -- Continue
end case;
end loop;
end Expect;
procedure Expect
(Result : out Expect_Match;
Regexps : Multiprocess_Regexp_Array;
Matched : out GNAT.Regpat.Match_Array;
Timeout : Integer := 10_000;
Full_Buffer : Boolean := False)
is
N : Expect_Match;
Descriptors : Array_Of_Pd (Regexps'Range);
begin
pragma Assert (Matched'First = 0);
for J in Descriptors'Range loop
Descriptors (J) := Regexps (J).Descriptor;
if Descriptors (J) /= null then
Reinitialize_Buffer (Regexps (J).Descriptor.all);
end if;
end loop;
loop
-- First, test if what is already in the buffer matches (This is
-- required if this package is used in multi-task mode, since one of
-- the tasks might have added something in the buffer, and we don't
-- want other tasks to wait for new input to be available before
-- checking the regexps).
for J in Regexps'Range loop
if Regexps (J).Regexp /= null
and then Regexps (J).Descriptor /= null
then
Match (Regexps (J).Regexp.all,
Regexps (J).Descriptor.Buffer
(1 .. Regexps (J).Descriptor.Buffer_Index),
Matched);
if Matched (0) /= No_Match then
Result := Expect_Match (J);
Regexps (J).Descriptor.Last_Match_Start := Matched (0).First;
Regexps (J).Descriptor.Last_Match_End := Matched (0).Last;
return;
end if;
end if;
end loop;
Expect_Internal (Descriptors, N, Timeout, Full_Buffer);
case N is
when Expect_Internal_Error
| Expect_Process_Died
=>
raise Process_Died;
when Expect_Full_Buffer
| Expect_Timeout
=>
Result := N;
return;
when others =>
null; -- Continue
end case;
end loop;
end Expect;
---------------------
-- Expect_Internal --
---------------------
procedure Expect_Internal
(Descriptors : in out Array_Of_Pd;
Result : out Expect_Match;
Timeout : Integer;
Full_Buffer : Boolean)
is
Num_Descriptors : Integer;
Buffer_Size : Integer := 0;
N : Integer;
type File_Descriptor_Array is
array (0 .. Descriptors'Length - 1) of File_Descriptor;
Fds : aliased File_Descriptor_Array;
Fds_Count : Natural := 0;
Fds_To_Descriptor : array (Fds'Range) of Integer;
-- Maps file descriptor entries from Fds to entries in Descriptors.
-- They do not have the same index when entries in Descriptors are null.
type Integer_Array is array (Fds'Range) of Integer;
Is_Set : aliased Integer_Array;
begin
for J in Descriptors'Range loop
if Descriptors (J) /= null then
Fds (Fds'First + Fds_Count) := Descriptors (J).Output_Fd;
Fds_To_Descriptor (Fds'First + Fds_Count) := J;
Fds_Count := Fds_Count + 1;
if Descriptors (J).Buffer_Size = 0 then
Buffer_Size := Integer'Max (Buffer_Size, 4096);
else
Buffer_Size :=
Integer'Max (Buffer_Size, Descriptors (J).Buffer_Size);
end if;
end if;
end loop;
declare
Buffer : aliased String (1 .. Buffer_Size);
-- Buffer used for input. This is allocated only once, not for
-- every iteration of the loop
D : aliased Integer;
-- Index in Descriptors
begin
-- Loop until we match or we have a timeout
loop
Num_Descriptors :=
Poll (Fds'Address, Fds_Count, Timeout, D'Access, Is_Set'Address);
case Num_Descriptors is
-- Error?
when -1 =>
Result := Expect_Internal_Error;
if D /= 0 then
Close (Descriptors (D).Input_Fd);
Descriptors (D).Input_Fd := Invalid_FD;
end if;
return;
-- Timeout?
when 0 =>
Result := Expect_Timeout;
return;
-- Some input
when others =>
for F in Fds'Range loop
if Is_Set (F) = 1 then
D := Fds_To_Descriptor (F);
Buffer_Size := Descriptors (D).Buffer_Size;
if Buffer_Size = 0 then
Buffer_Size := 4096;
end if;
N := Read (Descriptors (D).Output_Fd, Buffer'Address,
Buffer_Size);
-- Error or End of file
if N <= 0 then
-- ??? Note that ddd tries again up to three times
-- in that case. See LiterateA.C:174
Close (Descriptors (D).Input_Fd);
Descriptors (D).Input_Fd := Invalid_FD;
Result := Expect_Process_Died;
return;
else
-- If there is no limit to the buffer size
if Descriptors (D).Buffer_Size = 0 then
declare
Tmp : String_Access := Descriptors (D).Buffer;
begin
if Tmp /= null then
Descriptors (D).Buffer :=
new String (1 .. Tmp'Length + N);
Descriptors (D).Buffer (1 .. Tmp'Length) :=
Tmp.all;
Descriptors (D).Buffer
(Tmp'Length + 1 .. Tmp'Length + N) :=
Buffer (1 .. N);
Free (Tmp);
Descriptors (D).Buffer_Index :=
Descriptors (D).Buffer'Last;
else
Descriptors (D).Buffer :=
new String (1 .. N);
Descriptors (D).Buffer.all :=
Buffer (1 .. N);
Descriptors (D).Buffer_Index := N;
end if;
end;
else
-- Add what we read to the buffer
if Descriptors (D).Buffer_Index + N >
Descriptors (D).Buffer_Size
then
-- If the user wants to know when we have
-- read more than the buffer can contain.
if Full_Buffer then
Result := Expect_Full_Buffer;
return;
end if;
-- Keep as much as possible from the buffer,
-- and forget old characters.
Descriptors (D).Buffer
(1 .. Descriptors (D).Buffer_Size - N) :=
Descriptors (D).Buffer
(N - Descriptors (D).Buffer_Size +
Descriptors (D).Buffer_Index + 1 ..
Descriptors (D).Buffer_Index);
Descriptors (D).Buffer_Index :=
Descriptors (D).Buffer_Size - N;
end if;
-- Keep what we read in the buffer
Descriptors (D).Buffer
(Descriptors (D).Buffer_Index + 1 ..
Descriptors (D).Buffer_Index + N) :=
Buffer (1 .. N);
Descriptors (D).Buffer_Index :=
Descriptors (D).Buffer_Index + N;
end if;
-- Call each of the output filter with what we
-- read.
Call_Filters
(Descriptors (D).all, Buffer (1 .. N), Output);
Result := Expect_Match (D);
return;
end if;
end if;
end loop;
end case;
end loop;
end;
end Expect_Internal;
----------------
-- Expect_Out --
----------------
function Expect_Out (Descriptor : Process_Descriptor) return String is
begin
return Descriptor.Buffer (1 .. Descriptor.Last_Match_End);
end Expect_Out;
----------------------
-- Expect_Out_Match --
----------------------
function Expect_Out_Match (Descriptor : Process_Descriptor) return String is
begin
return Descriptor.Buffer
(Descriptor.Last_Match_Start .. Descriptor.Last_Match_End);
end Expect_Out_Match;
------------------------
-- First_Dead_Process --
------------------------
function First_Dead_Process
(Regexp : Multiprocess_Regexp_Array) return Natural is
begin
for R in Regexp'Range loop
if Regexp (R).Descriptor /= null
and then Regexp (R).Descriptor.Input_Fd = GNAT.OS_Lib.Invalid_FD
then
return R;
end if;
end loop;
return 0;
end First_Dead_Process;
-----------
-- Flush --
-----------
procedure Flush
(Descriptor : in out Process_Descriptor;
Timeout : Integer := 0)
is
Buffer_Size : constant Integer := 8192;
Num_Descriptors : Integer;
N : aliased Integer;
Is_Set : aliased Integer;
Buffer : aliased String (1 .. Buffer_Size);
begin
-- Empty the current buffer
Descriptor.Last_Match_End := Descriptor.Buffer_Index;
Reinitialize_Buffer (Descriptor);
-- Read everything from the process to flush its output
loop
Num_Descriptors :=
Poll (Descriptor.Output_Fd'Address,
1,
Timeout,
N'Access,
Is_Set'Address);
case Num_Descriptors is
-- Error ?
when -1 =>
raise Process_Died;
-- Timeout => End of flush
when 0 =>
return;
-- Some input
when others =>
if Is_Set = 1 then
N := Read (Descriptor.Output_Fd, Buffer'Address,
Buffer_Size);
if N = -1 then
raise Process_Died;
elsif N = 0 then
return;
end if;
end if;
end case;
end loop;
end Flush;
----------
-- Free --
----------
procedure Free (Regexp : in out Multiprocess_Regexp) is
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(Process_Descriptor'Class, Process_Descriptor_Access);
begin
Unchecked_Free (Regexp.Descriptor);
Free (Regexp.Regexp);
end Free;
------------------------
-- Get_Command_Output --
------------------------
function Get_Command_Output
(Command : String;
Arguments : GNAT.OS_Lib.Argument_List;
Input : String;
Status : not null access Integer;
Err_To_Out : Boolean := False) return String
is
use GNAT.Expect;
Process : Process_Descriptor;
Output : String_Access := new String (1 .. 1024);
-- Buffer used to accumulate standard output from the launched
-- command, expanded as necessary during execution.
Last : Integer := 0;
-- Index of the last used character within Output
begin
Non_Blocking_Spawn
(Process, Command, Arguments, Err_To_Out => Err_To_Out,
Buffer_Size => 0);
if Input'Length > 0 then
Send (Process, Input);
end if;
Close (Process.Input_Fd);
Process.Input_Fd := Invalid_FD;
declare
Result : Expect_Match;
pragma Unreferenced (Result);
begin
-- This loop runs until the call to Expect raises Process_Died
loop
Expect (Process, Result, ".+", Timeout => -1);
declare
NOutput : String_Access;
S : constant String := Expect_Out (Process);
pragma Assert (S'Length > 0);
begin
-- Expand buffer if we need more space. Note here that we add
-- S'Length to ensure that S will fit in the new buffer size.
if Last + S'Length > Output'Last then
NOutput := new String (1 .. 2 * Output'Last + S'Length);
NOutput (Output'Range) := Output.all;
Free (Output);
-- Here if current buffer size is OK
else
NOutput := Output;
end if;
NOutput (Last + 1 .. Last + S'Length) := S;
Last := Last + S'Length;
Output := NOutput;
end;
end loop;
exception
when Process_Died =>
Close (Process, Status.all);
end;
if Last = 0 then
Free (Output);
return "";
end if;
declare
S : constant String := Output (1 .. Last);
begin
Free (Output);
return S;
end;
end Get_Command_Output;
------------------
-- Get_Error_Fd --
------------------
function Get_Error_Fd
(Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
is
begin
return Descriptor.Error_Fd;
end Get_Error_Fd;
------------------
-- Get_Input_Fd --
------------------
function Get_Input_Fd
(Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
is
begin
return Descriptor.Input_Fd;
end Get_Input_Fd;
-------------------
-- Get_Output_Fd --
-------------------
function Get_Output_Fd
(Descriptor : Process_Descriptor) return GNAT.OS_Lib.File_Descriptor
is
begin
return Descriptor.Output_Fd;
end Get_Output_Fd;
-------------
-- Get_Pid --
-------------
function Get_Pid
(Descriptor : Process_Descriptor) return Process_Id
is
begin
return Descriptor.Pid;
end Get_Pid;
-----------------
-- Has_Process --
-----------------
function Has_Process (Regexp : Multiprocess_Regexp_Array) return Boolean is
begin
return Regexp /= (Regexp'Range => (null, null));
end Has_Process;
---------------
-- Interrupt --
---------------
procedure Interrupt (Descriptor : in out Process_Descriptor) is
SIGINT : constant := 2;
begin
Send_Signal (Descriptor, SIGINT);
end Interrupt;
------------------
-- Lock_Filters --
------------------
procedure Lock_Filters (Descriptor : in out Process_Descriptor) is
begin
Descriptor.Filters_Lock := Descriptor.Filters_Lock + 1;
end Lock_Filters;
------------------------
-- Non_Blocking_Spawn --
------------------------
procedure Non_Blocking_Spawn
(Descriptor : out Process_Descriptor'Class;
Command : String;
Args : GNAT.OS_Lib.Argument_List;
Buffer_Size : Natural := 4096;
Err_To_Out : Boolean := False)
is
function Fork return Process_Id;
pragma Import (C, Fork, "__gnat_expect_fork");
-- Starts a new process if possible. See the Unix command fork for more
-- information. On systems that do not support this capability (such as
-- Windows...), this command does nothing, and Fork will return
-- Null_Pid.
Pipe1, Pipe2, Pipe3 : aliased Pipe_Type;
Arg : String_Access;
Arg_List : String_List (1 .. Args'Length + 2);
C_Arg_List : aliased array (1 .. Args'Length + 2) of System.Address;
Command_With_Path : String_Access;
begin
Command_With_Path := Locate_Exec_On_Path (Command);
if Command_With_Path = null then
raise Invalid_Process;
end if;
-- Create the rest of the pipes once we know we will be able to
-- execute the process.
Set_Up_Communications
(Descriptor, Err_To_Out, Pipe1'Access, Pipe2'Access, Pipe3'Access);
-- Fork a new process
Descriptor.Pid := Fork;
-- Are we now in the child (or, for Windows, still in the common
-- process).
if Descriptor.Pid = Null_Pid then
-- Prepare an array of arguments to pass to C
Arg := new String (1 .. Command_With_Path'Length + 1);
Arg (1 .. Command_With_Path'Length) := Command_With_Path.all;
Arg (Arg'Last) := ASCII.NUL;
Arg_List (1) := Arg;
for J in Args'Range loop
Arg := new String (1 .. Args (J)'Length + 1);
Arg (1 .. Args (J)'Length) := Args (J).all;
Arg (Arg'Last) := ASCII.NUL;
Arg_List (J + 2 - Args'First) := Arg.all'Access;
end loop;
Arg_List (Arg_List'Last) := null;
-- Make sure all arguments are compatible with OS conventions
Normalize_Arguments (Arg_List);
-- Prepare low-level argument list from the normalized arguments
for K in Arg_List'Range loop
C_Arg_List (K) :=
(if Arg_List (K) /= null
then Arg_List (K).all'Address
else System.Null_Address);
end loop;
-- This does not return on Unix systems
Set_Up_Child_Communications
(Descriptor, Pipe1, Pipe2, Pipe3, Command_With_Path.all,
C_Arg_List'Address);
end if;
Free (Command_With_Path);
-- Did we have an error when spawning the child ?
if Descriptor.Pid < Null_Pid then
raise Invalid_Process;
else
-- We are now in the parent process
Set_Up_Parent_Communications (Descriptor, Pipe1, Pipe2, Pipe3);
end if;
-- Create the buffer
Descriptor.Buffer_Size := Buffer_Size;
if Buffer_Size /= 0 then
Descriptor.Buffer := new String (1 .. Positive (Buffer_Size));
end if;
-- Initialize the filters
Descriptor.Filters := null;
end Non_Blocking_Spawn;
-------------------------
-- Reinitialize_Buffer --
-------------------------
procedure Reinitialize_Buffer
(Descriptor : in out Process_Descriptor'Class)
is
begin
if Descriptor.Buffer_Size = 0 then
declare
Tmp : String_Access := Descriptor.Buffer;
begin
Descriptor.Buffer :=
new String
(1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End);
if Tmp /= null then
Descriptor.Buffer.all := Tmp
(Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
Free (Tmp);
end if;
end;
Descriptor.Buffer_Index := Descriptor.Buffer'Last;
else
Descriptor.Buffer
(1 .. Descriptor.Buffer_Index - Descriptor.Last_Match_End) :=
Descriptor.Buffer
(Descriptor.Last_Match_End + 1 .. Descriptor.Buffer_Index);
if Descriptor.Buffer_Index > Descriptor.Last_Match_End then
Descriptor.Buffer_Index :=
Descriptor.Buffer_Index - Descriptor.Last_Match_End;
else
Descriptor.Buffer_Index := 0;
end if;
end if;
Descriptor.Last_Match_Start := 0;
Descriptor.Last_Match_End := 0;
end Reinitialize_Buffer;
-------------------
-- Remove_Filter --
-------------------
procedure Remove_Filter
(Descriptor : in out Process_Descriptor;
Filter : Filter_Function)
is
Previous : Filter_List := null;
Current : Filter_List := Descriptor.Filters;
begin
while Current /= null loop
if Current.Filter = Filter then
if Previous = null then
Descriptor.Filters := Current.Next;
else
Previous.Next := Current.Next;
end if;
end if;
Previous := Current;
Current := Current.Next;
end loop;
end Remove_Filter;
----------
-- Send --
----------
procedure Send
(Descriptor : in out Process_Descriptor;
Str : String;
Add_LF : Boolean := True;
Empty_Buffer : Boolean := False)
is
Line_Feed : aliased constant String := (1 .. 1 => ASCII.LF);
Descriptors : Array_Of_Pd := (1 => Descriptor'Unrestricted_Access);
Result : Expect_Match;
Discard : Natural;
pragma Warnings (Off, Result);
pragma Warnings (Off, Discard);
begin
if Empty_Buffer then
-- Force a read on the process if there is anything waiting
Expect_Internal
(Descriptors, Result, Timeout => 0, Full_Buffer => False);
if Result = Expect_Internal_Error
or else Result = Expect_Process_Died
then
raise Process_Died;
end if;
Descriptor.Last_Match_End := Descriptor.Buffer_Index;
-- Empty the buffer
Reinitialize_Buffer (Descriptor);
end if;
Call_Filters (Descriptor, Str, Input);
Discard :=
Write (Descriptor.Input_Fd, Str'Address, Str'Last - Str'First + 1);
if Add_LF then
Call_Filters (Descriptor, Line_Feed, Input);
Discard :=
Write (Descriptor.Input_Fd, Line_Feed'Address, 1);
end if;
end Send;
-----------------
-- Send_Signal --
-----------------
procedure Send_Signal
(Descriptor : Process_Descriptor;
Signal : Integer)
is
begin
-- A nonpositive process id passed to kill has special meanings. For
-- example, -1 means kill all processes in sight, including self, in
-- POSIX and Windows (and something slightly different in Linux). See
-- man pages for details. In any case, we don't want to do that. Note
-- that Descriptor.Pid will be -1 if the process was not successfully
-- started; we don't want to kill ourself in that case.
if Descriptor.Pid > 0 then
Kill (Descriptor.Pid, Signal, Close => 1);
-- ??? Need to check process status here
else
raise Invalid_Process;
end if;
end Send_Signal;
---------------------------------
-- Set_Up_Child_Communications --
---------------------------------
procedure Set_Up_Child_Communications
(Pid : in out Process_Descriptor;
Pipe1 : in out Pipe_Type;
Pipe2 : in out Pipe_Type;
Pipe3 : in out Pipe_Type;
Cmd : String;
Args : System.Address)
is
pragma Warnings (Off, Pid);
pragma Warnings (Off, Pipe1);
pragma Warnings (Off, Pipe2);
pragma Warnings (Off, Pipe3);
Input : File_Descriptor;
Output : File_Descriptor;
Error : File_Descriptor;
No_Fork_On_Target : constant Boolean := Target_OS = Windows;
begin
if No_Fork_On_Target then
-- Since Windows does not have a separate fork/exec, we need to
-- perform the following actions:
-- - save stdin, stdout, stderr
-- - replace them by our pipes
-- - create the child with process handle inheritance
-- - revert to the previous stdin, stdout and stderr.
Input := Dup (GNAT.OS_Lib.Standin);
Output := Dup (GNAT.OS_Lib.Standout);
Error := Dup (GNAT.OS_Lib.Standerr);
end if;
-- Since we are still called from the parent process, there is no way
-- currently we can cleanly close the unneeded ends of the pipes, but
-- this doesn't really matter.
-- We could close Pipe1.Output, Pipe2.Input, Pipe3.Input
Dup2 (Pipe1.Input, GNAT.OS_Lib.Standin);
Dup2 (Pipe2.Output, GNAT.OS_Lib.Standout);
Dup2 (Pipe3.Output, GNAT.OS_Lib.Standerr);
Portable_Execvp (Pid.Pid'Access, Cmd & ASCII.NUL, Args);
-- The following lines are only required for Windows systems and will
-- not be executed on Unix systems, but we use the same condition as
-- above to avoid warnings on uninitialized variables on Unix systems.
-- We are now in the parent process.
if No_Fork_On_Target then
-- Restore the old descriptors
Dup2 (Input, GNAT.OS_Lib.Standin);
Dup2 (Output, GNAT.OS_Lib.Standout);
Dup2 (Error, GNAT.OS_Lib.Standerr);
Close (Input);
Close (Output);
Close (Error);
end if;
end Set_Up_Child_Communications;
---------------------------
-- Set_Up_Communications --
---------------------------
procedure Set_Up_Communications
(Pid : in out Process_Descriptor;
Err_To_Out : Boolean;
Pipe1 : not null access Pipe_Type;
Pipe2 : not null access Pipe_Type;
Pipe3 : not null access Pipe_Type)
is
Status : Boolean;
pragma Unreferenced (Status);
begin
-- Create the pipes
if Create_Pipe (Pipe1) /= 0 then
return;
end if;
if Create_Pipe (Pipe2) /= 0 then
Close (Pipe1.Input);
Close (Pipe1.Output);
return;
end if;
-- Record the 'parent' end of the two pipes in Pid:
-- Child stdin is connected to the 'write' end of Pipe1;
-- Child stdout is connected to the 'read' end of Pipe2.
-- We do not want these descriptors to remain open in the child
-- process, so we mark them close-on-exec/non-inheritable.
Pid.Input_Fd := Pipe1.Output;
Set_Close_On_Exec (Pipe1.Output, True, Status);
Pid.Output_Fd := Pipe2.Input;
Set_Close_On_Exec (Pipe2.Input, True, Status);
if Err_To_Out then
-- Reuse the standard output pipe for standard error
Pipe3.all := Pipe2.all;
else
-- Create a separate pipe for standard error
if Create_Pipe (Pipe3) /= 0 then
Pipe3.all := Pipe2.all;
end if;
end if;
-- As above, record the proper fd for the child's standard error stream
Pid.Error_Fd := Pipe3.Input;
Set_Close_On_Exec (Pipe3.Input, True, Status);
end Set_Up_Communications;
----------------------------------
-- Set_Up_Parent_Communications --
----------------------------------
procedure Set_Up_Parent_Communications
(Pid : in out Process_Descriptor;
Pipe1 : in out Pipe_Type;
Pipe2 : in out Pipe_Type;
Pipe3 : in out Pipe_Type)
is
pragma Warnings (Off, Pid);
pragma Warnings (Off, Pipe1);
pragma Warnings (Off, Pipe2);
pragma Warnings (Off, Pipe3);
begin
Close (Pipe1.Input);
Close (Pipe2.Output);
if Pipe3.Output /= Pipe2.Output then
Close (Pipe3.Output);
end if;
end Set_Up_Parent_Communications;
------------------
-- Trace_Filter --
------------------
procedure Trace_Filter
(Descriptor : Process_Descriptor'Class;
Str : String;
User_Data : System.Address := System.Null_Address)
is
pragma Warnings (Off, Descriptor);
pragma Warnings (Off, User_Data);
begin
GNAT.IO.Put (Str);
end Trace_Filter;
--------------------
-- Unlock_Filters --
--------------------
procedure Unlock_Filters (Descriptor : in out Process_Descriptor) is
begin
if Descriptor.Filters_Lock > 0 then
Descriptor.Filters_Lock := Descriptor.Filters_Lock - 1;
end if;
end Unlock_Filters;
end GNAT.Expect;
|
-- Copyright (c) 2019 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Program.Compilation_Units;
with Program.Visibility;
with Program.Elements.Defining_Names;
with Program.Symbols;
private package Program.Resolvers is
pragma Preelaborate;
procedure Resolve_Names
(Env : aliased in out Program.Visibility.Context;
Unit : not null Program.Compilation_Units.Compilation_Unit_Access);
function To_Symbol
(Name : access Program.Elements.Defining_Names.Defining_Name'Class)
return Program.Symbols.Symbol;
-- Return a symbol for given defining name. Return symbol of the
-- selector for expanded defining name.
end Program.Resolvers;
|
A : My_Type := 3;
B : My_Type := A;
|
with Ada.Text_IO, History_Variables;
procedure Test_History is
package Str_With_Hist is new History_Variables(String);
-- define a history variable
S: Str_With_Hist.Variable;
Sum: Integer := 0;
begin
-- assign three values
S.Set("one");
S.Set(S.Get & S.Get); --"oneone"
S.Set("three");
-- non-destructively display the history
for N in reverse 0 .. S.Defined-1 loop
Ada.Text_IO.Put(S.Peek(Generation => N) &" ");
end loop;
Ada.Text_IO.New_Line;
-- recall the three values
while S.Defined > 0 loop
Sum := Sum + S.Get'Length;
S.Undo;
end loop;
Ada.Text_IO.Put_Line(Integer'Image(Sum));
end Test_History;
|
pragma License (Unrestricted);
-- implementation unit specialized for Darwin (or Linux, or Windows)
package System.Long_Long_Elementary_Functions is
pragma Pure;
function logl (x : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_logl";
function Fast_Log (X : Long_Long_Float) return Long_Long_Float
renames logl;
function expl (x : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_expl";
function Fast_Exp (X : Long_Long_Float) return Long_Long_Float
renames expl;
function powl (x, y : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_powl";
function Fast_Pow (Left, Right : Long_Long_Float) return Long_Long_Float
renames powl;
function sinhl (x : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_sinhl";
function Fast_Sinh (X : Long_Long_Float) return Long_Long_Float
renames sinhl;
function coshl (x : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_coshl";
function Fast_Cosh (X : Long_Long_Float) return Long_Long_Float
renames coshl;
function tanhl (x : Long_Long_Float) return Long_Long_Float
with Import, Convention => Intrinsic, External_Name => "__builtin_tanhl";
function Fast_Tanh (X : Long_Long_Float) return Long_Long_Float
renames tanhl;
function asinhl (x : Long_Long_Float) return Long_Long_Float
with Import,
Convention => Intrinsic, External_Name => "__builtin_asinhl";
function Fast_Arcsinh (X : Long_Long_Float) return Long_Long_Float
renames asinhl;
function acoshl (x : Long_Long_Float) return Long_Long_Float
with Import,
Convention => Intrinsic, External_Name => "__builtin_acoshl";
function Fast_Arccosh (X : Long_Long_Float) return Long_Long_Float
renames acoshl;
function atanhl (x : Long_Long_Float) return Long_Long_Float
with Import,
Convention => Intrinsic, External_Name => "__builtin_atanhl";
function Fast_Arctanh (X : Long_Long_Float) return Long_Long_Float
renames atanhl;
end System.Long_Long_Elementary_Functions;
|
--
-- (c) Copyright 1993,1994,1995,1996 Silicon Graphics, Inc.
-- ALL RIGHTS RESERVED
-- Permission to use, copy, modify, and distribute this software for
-- any purpose and without fee is hereby granted, provided that the above
-- copyright notice appear in all copies and that both the copyright notice
-- and this permission notice appear in supporting documentation, and that
-- the name of Silicon Graphics, Inc. not be used in advertising
-- or publicity pertaining to distribution of the software without specific,
-- written prior permission.
--
-- THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
-- AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
-- INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
-- FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-- GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
-- SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
-- KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
-- LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
-- THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
-- ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
-- ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
-- POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
--
-- US Government Users Restricted Rights
-- Use, duplication, or disclosure by the Government is subject to
-- restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
-- (c)(1)(ii) of the Rights in Technical Data and Computer Software
-- clause at DFARS 252.227-7013 and/or in similar or successor
-- clauses in the FAR or the DOD or NASA FAR Supplement.
-- Unpublished-- rights reserved under the copyright laws of the
-- United States. Contractor/manufacturer is Silicon Graphics,
-- Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
--
-- OpenGL(TM) is a trademark of Silicon Graphics, Inc.
--
with GL; use GL;
package Teapots_Procs is
procedure DoInit;
procedure renderTeapot
(x : GLfloat; y : GLfloat; ambr : GLfloat;
ambg : GLfloat; ambb : GLfloat; difr : GLfloat;
difg : GLfloat; difb : GLfloat; specr : GLfloat;
specg : GLfloat; specb : GLfloat; shine : GLfloat);
procedure DoDisplay;
procedure ReshapeCallback (w : Integer; h : Integer);
end Teapots_Procs;
|
-- part of OpenGLAda, (c) 2017 Felix Krause
-- released under the terms of the MIT license, see the file "COPYING"
with Interfaces.C.Pointers;
package GL.Types.Colors is
pragma Preelaborate;
type Color_Index is (R, G, B, A);
subtype Basic_Color_Index is Color_Index range R .. B;
subtype Component is Single range 0.0 .. 1.0;
type Color is array (Color_Index) of aliased Component;
type Basic_Color is array (Basic_Color_Index) of Component;
pragma Convention (C, Color);
pragma Convention (C, Basic_Color);
type Color_Array is array (Size range <>) of aliased Color;
type Basic_Color_Array is array (Size range <>) of aliased Basic_Color;
package Color_Pointers is new Interfaces.C.Pointers
(Size, Color, Color_Array, Color'(others => 0.0));
package Basic_Color_Pointers is new Interfaces.C.Pointers
(Size, Basic_Color, Basic_Color_Array, Basic_Color'(others => 0.0));
end GL.Types.Colors;
|
-- C83024E1M.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT A DECLARATION IN THE DECLARATIVE REGION OF A GENERIC
-- PACKAGE HIDES AN OUTER DECLARATION OF A HOMOGRAPH. ALSO CHECK
-- THAT THE OUTER DECLARATION IS DIRECTLY VISIBLE IN BOTH
-- DECLARATIVE REGIONS BEFORE THE DECLARATION OF THE INNER HOMOGRAPH
-- AND THE OUTER DECLARATION IS VISIBLE BY SELECTION AFTER THE INNER
-- HOMOGRAPH DECLARATION, IF THE GENERIC PACKAGE BODY IS SEPARATELY
-- COMPILED, BUT NOT AS A SUBUNIT.
-- APPLICABILITY CRITERIA:
-- THIS TEST IS APPLICABLE TO IMPLEMENTATIONS THAT SUPPORT SEPARATE
-- COMPILATIONS OF GENERIC SPECIFICATIONS AND BODIES.
-- SEPARATE FILES ARE:
-- C83024E0.ADA -- GENERIC PACKAGE SPECIFICATIONS.
-- C83024E1M.ADA - (THIS FILE) GENERIC PACKAGE BODIES AND
-- MAIN PROGRAM.
-- HISTORY:
-- BCB 08/30/88 CREATED ORIGINAL TEST.
-- PWN 11/30/94 ADDED A PROCEDURE TO KEEP PACKAGE BODIES LEGAL.
PACKAGE BODY C83024E_P1 IS
PROCEDURE REQUIRE_BODY IS
BEGIN
NULL;
END;
PACKAGE BODY C83024E_PACK1 IS
BEGIN
IF A /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 1");
END IF;
IF C83024E_P1.A /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 2");
END IF;
IF C83024E_P1.B /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER VARIABLE - 3");
END IF;
IF C /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 4");
END IF;
IF X /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE PASSED IN - 5");
END IF;
IF EQUAL(1,1) THEN
X := A;
ELSE
X := C83024E_P1.A;
END IF;
END C83024E_PACK1;
END C83024E_P1;
PACKAGE BODY C83024E_P2 IS
PROCEDURE REQUIRE_BODY IS
BEGIN
NULL;
END;
PACKAGE BODY C83024E_PACK2 IS
BEGIN
IF A /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 10");
END IF;
IF C83024E_P2.A /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 11");
END IF;
IF C83024E_P2.B /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER VARIABLE - 12");
END IF;
IF C /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 13");
END IF;
IF X /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE PASSED IN - 14");
END IF;
IF EQUAL(1,1) THEN
A := IDENT_INT(4);
ELSE
A := 1;
END IF;
END C83024E_PACK2;
END C83024E_P2;
PACKAGE BODY C83024E_P3 IS
PROCEDURE REQUIRE_BODY IS
BEGIN
NULL;
END;
PACKAGE BODY C83024E_PACK3 IS
C : INTEGER := A;
A : INTEGER := IDENT_INT(3);
BEGIN
IF A /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE FOR INNER HOMOGRAPH - 20");
END IF;
IF C83024E_P3.A /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER HOMOGRAPH - 21");
END IF;
IF C83024E_P3.B /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR OUTER VARIABLE - 22");
END IF;
IF C /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE FOR INNER VARIABLE - 23");
END IF;
IF X /= IDENT_INT(2) THEN
FAILED ("INCORRECT VALUE PASSED IN - 24");
END IF;
IF EQUAL(1,1) THEN
X := A;
ELSE
NULL;
END IF;
END C83024E_PACK3;
END C83024E_P3;
PACKAGE BODY C83024E_P4 IS
PROCEDURE REQUIRE_BODY IS
BEGIN
NULL;
END;
PACKAGE BODY C83024E_PACK4 IS
BEGIN
X := INTEGER(F);
END C83024E_PACK4;
END C83024E_P4;
WITH REPORT; USE REPORT;
WITH C83024E_P1; WITH C83024E_P2;
WITH C83024E_P3; WITH C83024E_P4;
USE C83024E_P1; USE C83024E_P2;
USE C83024E_P3; USE C83024E_P4;
PROCEDURE C83024E1M IS
BEGIN
TEST ("C83024E", "CHECK THAT A DECLARATION IN THE DECLARATIVE " &
"REGION OF A GENERIC PACKAGE HIDES AN OUTER " &
"DECLARATION OF A HOMOGRAPH");
DECLARE
PACKAGE NEW_C83024E_PACK1 IS NEW C83024E_PACK1 (C83024E_P1.A);
BEGIN
IF C83024E_P1.A /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE PASSED OUT - 6");
END IF;
END;
DECLARE
PACKAGE NEW_C83024E_PACK2 IS
NEW C83024E_PACK2 (A => C83024E_P2.OBJ);
BEGIN
IF C83024E_P2.OBJ /= IDENT_INT(4) THEN
FAILED ("INCORRECT VALUE PASSED OUT - 15");
END IF;
END;
DECLARE
PACKAGE NEW_C83024E_PACK3 IS NEW C83024E_PACK3 (C83024E_P3.A);
BEGIN
IF C83024E_P3.A /= IDENT_INT(3) THEN
FAILED ("INCORRECT VALUE PASSED OUT - 25");
END IF;
END;
DECLARE
PACKAGE NEW_C83024E_PACK4 IS
NEW C83024E_PACK4 (C83024E_P4.OBJ, FLO);
BEGIN
IF C83024E_P4.OBJ /= IDENT_INT(6) THEN
FAILED ("INCORRECT VALUE RETURNED FROM FUNCTION - 60");
END IF;
END;
RESULT;
END C83024E1M;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . F I L E _ I O --
-- --
-- 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. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Finalization; use Ada.Finalization;
with Ada.IO_Exceptions; use Ada.IO_Exceptions;
with Interfaces.C_Streams; use Interfaces.C_Streams;
with System.Soft_Links;
with Unchecked_Deallocation;
package body System.File_IO is
use System.File_Control_Block;
package SSL renames System.Soft_Links;
----------------------
-- Global Variables --
----------------------
Open_Files : AFCB_Ptr;
-- This points to a list of AFCB's for all open files. This is a doubly
-- linked list, with the Prev pointer of the first entry, and the Next
-- pointer of the last entry containing null. Note that this global
-- variable must be properly protected to provide thread safety.
type Temp_File_Record;
type Temp_File_Record_Ptr is access all Temp_File_Record;
type Temp_File_Record is record
Name : String (1 .. L_tmpnam + 1);
Next : Temp_File_Record_Ptr;
end record;
-- One of these is allocated for each temporary file created
Temp_Files : Temp_File_Record_Ptr;
-- Points to list of names of temporary files. Note that this global
-- variable must be properly protected to provide thread safety.
type File_IO_Clean_Up_Type is new Controlled with null record;
-- The closing of all open files and deletion of temporary files is an
-- action which takes place at the end of execution of the main program.
-- This action can be implemented using a library level object which
-- gets finalized at the end of the main program execution. The above is
-- a controlled type introduced for this purpose.
procedure Finalize (V : in out File_IO_Clean_Up_Type);
-- This is the finalize operation that is used to do the cleanup.
File_IO_Clean_Up_Object : File_IO_Clean_Up_Type;
-- This is the single object of the type that triggers the finalization
-- call. Since it is at the library level, this happens just before the
-- environment task is finalized.
text_translation_required : Boolean;
pragma Import
(C, text_translation_required, "__gnat_text_translation_required");
-- If true, add appropriate suffix to control string for Open.
-----------------------
-- Local Subprograms --
-----------------------
procedure Free_String is new Unchecked_Deallocation (String, Pstring);
subtype Fopen_String is String (1 .. 4);
-- Holds open string (longest is "w+b" & nul)
procedure Fopen_Mode
(Mode : File_Mode;
Text : Boolean;
Creat : Boolean;
Amethod : Character;
Fopstr : out Fopen_String);
-- Determines proper open mode for a file to be opened in the given
-- Ada mode. Text is true for a text file and false otherwise, and
-- Creat is true for a create call, and False for an open call. The
-- value stored in Fopstr is a nul-terminated string suitable for a
-- call to fopen or freopen. Amethod is the character designating
-- the access method from the Access_Method field of the FCB.
----------------
-- Append_Set --
----------------
procedure Append_Set (File : AFCB_Ptr) is
begin
if File.Mode = Append_File then
if fseek (File.Stream, 0, SEEK_END) /= 0 then
raise Device_Error;
end if;
end if;
end Append_Set;
----------------
-- Chain_File --
----------------
procedure Chain_File (File : AFCB_Ptr) is
begin
-- Take a task lock, to protect the global data value Open_Files
-- No exception handler needed, since we cannot get an exception.
SSL.Lock_Task.all;
File.Next := Open_Files;
File.Prev := null;
Open_Files := File;
if File.Next /= null then
File.Next.Prev := File;
end if;
SSL.Unlock_Task.all;
end Chain_File;
---------------------
-- Check_File_Open --
---------------------
procedure Check_File_Open (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error;
end if;
end Check_File_Open;
-----------------------
-- Check_Read_Status --
-----------------------
procedure Check_Read_Status (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error;
elsif File.Mode > Inout_File then
raise Mode_Error;
end if;
end Check_Read_Status;
------------------------
-- Check_Write_Status --
------------------------
procedure Check_Write_Status (File : AFCB_Ptr) is
begin
if File = null then
raise Status_Error;
elsif File.Mode = In_File then
raise Mode_Error;
end if;
end Check_Write_Status;
-----------
-- Close --
-----------
procedure Close (File : in out AFCB_Ptr) is
Close_Status : int := 0;
Dup_Strm : Boolean := False;
begin
Check_File_Open (File);
AFCB_Close (File);
-- Sever the association between the given file and its associated
-- external file. The given file is left closed. Do not perform system
-- closes on the standard input, output and error files and also do
-- not attempt to close a stream that does not exist (signalled by a
-- null stream value -- happens in some error situations).
if not File.Is_System_File
and then File.Stream /= NULL_Stream
then
-- Do not do an fclose if this is a shared file and there is
-- at least one other instance of the stream that is open.
if File.Shared_Status = Yes then
declare
P : AFCB_Ptr;
begin
P := Open_Files;
while P /= null loop
if P /= File
and then File.Stream = P.Stream
then
Dup_Strm := True;
exit;
end if;
P := P.Next;
end loop;
end;
end if;
-- Do the fclose unless this was a duplicate in the shared case
if not Dup_Strm then
Close_Status := fclose (File.Stream);
end if;
end if;
-- Dechain file from list of open files and then free the storage
-- Since this is a global data structure, we have to protect against
-- multiple tasks attempting to access this list.
-- Note that we do not use an exception handler to unlock here since
-- no exception can occur inside the lock/unlock pair.
begin
SSL.Lock_Task.all;
if File.Prev = null then
Open_Files := File.Next;
else
File.Prev.Next := File.Next;
end if;
if File.Next /= null then
File.Next.Prev := File.Prev;
end if;
SSL.Unlock_Task.all;
end;
-- Deallocate some parts of the file structure that were kept in heap
-- storage with the exception of system files (standard input, output
-- and error) since they had some information allocated in the stack.
if not File.Is_System_File then
Free_String (File.Name);
Free_String (File.Form);
AFCB_Free (File);
end if;
File := null;
if Close_Status /= 0 then
raise Device_Error;
end if;
end Close;
------------
-- Delete --
------------
procedure Delete (File : in out AFCB_Ptr) is
begin
Check_File_Open (File);
if not File.Is_Regular_File then
raise Use_Error;
end if;
declare
Filename : aliased constant String := File.Name.all;
begin
Close (File);
-- Now unlink the external file. Note that we use the full name
-- in this unlink, because the working directory may have changed
-- since we did the open, and we want to unlink the right file!
if unlink (Filename'Address) = -1 then
raise Use_Error;
end if;
end;
end Delete;
-----------------
-- End_Of_File --
-----------------
function End_Of_File (File : AFCB_Ptr) return Boolean is
begin
Check_File_Open (File);
if feof (File.Stream) /= 0 then
return True;
else
Check_Read_Status (File);
if ungetc (fgetc (File.Stream), File.Stream) = EOF then
clearerr (File.Stream);
return True;
else
return False;
end if;
end if;
end End_Of_File;
--------------
-- Finalize --
--------------
-- Note: we do not need to worry about locking against multiple task
-- access in this routine, since it is called only from the environment
-- task just before terminating execution.
procedure Finalize (V : in out File_IO_Clean_Up_Type) is
Discard : int;
Fptr1 : AFCB_Ptr;
Fptr2 : AFCB_Ptr;
begin
-- First close all open files (the slightly complex form of this loop
-- is required because Close as a side effect nulls out its argument)
Fptr1 := Open_Files;
while Fptr1 /= null loop
Fptr2 := Fptr1.Next;
Close (Fptr1);
Fptr1 := Fptr2;
end loop;
-- Now unlink all temporary files. We do not bother to free the
-- blocks because we are just about to terminate the program. We
-- also ignore any errors while attempting these unlink operations.
while Temp_Files /= null loop
Discard := unlink (Temp_Files.Name'Address);
Temp_Files := Temp_Files.Next;
end loop;
end Finalize;
-----------
-- Flush --
-----------
procedure Flush (File : AFCB_Ptr) is
begin
Check_Write_Status (File);
if fflush (File.Stream) = 0 then
return;
else
raise Device_Error;
end if;
end Flush;
----------------
-- Fopen_Mode --
----------------
-- The fopen mode to be used is shown by the following table:
-- OPEN CREATE
-- Append_File "r+" "w+"
-- In_File "r" "w+"
-- Out_File (Direct_IO) "r+" "w"
-- Out_File (all others) "w" "w"
-- Inout_File "r+" "w+"
-- Note: we do not use "a" or "a+" for Append_File, since this would not
-- work in the case of stream files, where even if in append file mode,
-- you can reset to earlier points in the file. The caller must use the
-- Append_Set routine to deal with the necessary positioning.
-- Note: in several cases, the fopen mode used allows reading and
-- writing, but the setting of the Ada mode is more restrictive. For
-- instance, Create in In_File mode uses "w+" which allows writing,
-- but the Ada mode In_File will cause any write operations to be
-- rejected with Mode_Error in any case.
-- Note: for the Out_File/Open cases for other than the Direct_IO case,
-- an initial call will be made by the caller to first open the file in
-- "r" mode to be sure that it exists. The real open, in "w" mode, will
-- then destroy this file. This is peculiar, but that's what Ada semantics
-- require and the ACVT tests insist on!
-- If text file translation is required, then either b or t is
-- added to the mode, depending on the setting of Text.
procedure Fopen_Mode
(Mode : File_Mode;
Text : Boolean;
Creat : Boolean;
Amethod : Character;
Fopstr : out Fopen_String)
is
Fptr : Positive;
begin
case Mode is
when In_File =>
if Creat then
Fopstr (1) := 'w';
Fopstr (2) := '+';
Fptr := 3;
else
Fopstr (1) := 'r';
Fptr := 2;
end if;
when Out_File =>
if Amethod = 'D' and not Creat then
Fopstr (1) := 'r';
Fopstr (2) := '+';
Fptr := 3;
else
Fopstr (1) := 'w';
Fptr := 2;
end if;
when Inout_File | Append_File =>
if Creat then
Fopstr (1) := 'w';
else
Fopstr (1) := 'r';
end if;
Fopstr (2) := '+';
Fptr := 3;
end case;
-- If text_translation_required is true then we need to append
-- either a t or b to the string to get the right mode
if text_translation_required then
if Text then
Fopstr (Fptr) := 't';
else
Fopstr (Fptr) := 'b';
end if;
Fptr := Fptr + 1;
end if;
Fopstr (Fptr) := ASCII.NUL;
end Fopen_Mode;
----------
-- Form --
----------
function Form (File : in AFCB_Ptr) return String is
begin
if File = null then
raise Status_Error;
else
return File.Form.all (1 .. File.Form'Length - 1);
end if;
end Form;
------------------
-- Form_Boolean --
------------------
function Form_Boolean
(Form : String;
Keyword : String;
Default : Boolean)
return Boolean
is
V1, V2 : Natural;
begin
Form_Parameter (Form, Keyword, V1, V2);
if V1 = 0 then
return Default;
elsif Form (V1) = 'y' then
return True;
elsif Form (V1) = 'n' then
return False;
else
raise Use_Error;
end if;
end Form_Boolean;
------------------
-- Form_Integer --
------------------
function Form_Integer
(Form : String;
Keyword : String;
Default : Integer)
return Integer
is
V1, V2 : Natural;
V : Integer;
begin
Form_Parameter (Form, Keyword, V1, V2);
if V1 = 0 then
return Default;
else
V := 0;
for J in V1 .. V2 loop
if Form (J) not in '0' .. '9' then
raise Use_Error;
else
V := V * 10 + Character'Pos (Form (J)) - Character'Pos ('0');
end if;
if V > 999_999 then
raise Use_Error;
end if;
end loop;
return V;
end if;
end Form_Integer;
--------------------
-- Form_Parameter --
--------------------
procedure Form_Parameter
(Form : String;
Keyword : String;
Start : out Natural;
Stop : out Natural)
is
Klen : constant Integer := Keyword'Length;
-- Start of processing for Form_Parameter
begin
for J in Form'First + Klen .. Form'Last - 1 loop
if Form (J) = '='
and then Form (J - Klen .. J - 1) = Keyword
then
Start := J + 1;
Stop := Start - 1;
while Form (Stop + 1) /= ASCII.NUL
and then Form (Stop + 1) /= ','
loop
Stop := Stop + 1;
end loop;
return;
end if;
end loop;
Start := 0;
Stop := 0;
end Form_Parameter;
-------------
-- Is_Open --
-------------
function Is_Open (File : in AFCB_Ptr) return Boolean is
begin
return (File /= null);
end Is_Open;
-------------------
-- Make_Buffered --
-------------------
procedure Make_Buffered
(File : AFCB_Ptr;
Buf_Siz : Interfaces.C_Streams.size_t) is
status : Integer;
begin
status := setvbuf (File.Stream, Null_Address, IOFBF, Buf_Siz);
end Make_Buffered;
------------------------
-- Make_Line_Buffered --
------------------------
procedure Make_Line_Buffered
(File : AFCB_Ptr;
Line_Siz : Interfaces.C_Streams.size_t) is
status : Integer;
begin
status := setvbuf (File.Stream, Null_Address, IOLBF, Line_Siz);
end Make_Line_Buffered;
---------------------
-- Make_Unbuffered --
---------------------
procedure Make_Unbuffered (File : AFCB_Ptr) is
status : Integer;
begin
status := setvbuf (File.Stream, Null_Address, IONBF, 0);
end Make_Unbuffered;
----------
-- Mode --
----------
function Mode (File : in AFCB_Ptr) return File_Mode is
begin
if File = null then
raise Status_Error;
else
return File.Mode;
end if;
end Mode;
----------
-- Name --
----------
function Name (File : in AFCB_Ptr) return String is
begin
if File = null then
raise Status_Error;
else
return File.Name.all (1 .. File.Name'Length - 1);
end if;
end Name;
----------
-- Open --
----------
procedure Open
(File_Ptr : in out AFCB_Ptr;
Dummy_FCB : in out AFCB'Class;
Mode : File_Mode;
Name : String;
Form : String;
Amethod : Character;
Creat : Boolean;
Text : Boolean;
C_Stream : FILEs := NULL_Stream)
is
procedure Tmp_Name (Buffer : Address);
pragma Import (C, Tmp_Name, "__gnat_tmp_name");
-- set buffer (a String address) with a temporary filename.
Stream : FILEs := C_Stream;
-- Stream which we open in response to this request
Shared : Shared_Status_Type;
-- Setting of Shared_Status field for file
Fopstr : aliased Fopen_String;
-- Mode string used in fopen call
Formstr : aliased String (1 .. Form'Length + 1);
-- Form string with ASCII.NUL appended, folded to lower case
Tempfile : constant Boolean := (Name'Length = 0);
-- Indicates temporary file case
Namelen : constant Integer := max_path_len;
-- Length required for file name, not including final ASCII.NUL
-- Note that we used to reference L_tmpnam here, which is not
-- reliable since __gnat_tmp_name does not always use tmpnam.
Namestr : aliased String (1 .. Namelen + 1);
-- Name as given or temporary file name with ASCII.NUL appended
Fullname : aliased String (1 .. max_path_len + 1);
-- Full name (as required for Name function, and as stored in the
-- control block in the Name field) with ASCII.NUL appended.
Full_Name_Len : Integer;
-- Length of name actually stored in Fullname
begin
if File_Ptr /= null then
raise Status_Error;
end if;
-- Acquire form string, setting required NUL terminator
Formstr (1 .. Form'Length) := Form;
Formstr (Formstr'Last) := ASCII.NUL;
-- Convert form string to lower case
for J in Formstr'Range loop
if Formstr (J) in 'A' .. 'Z' then
Formstr (J) := Character'Val (Character'Pos (Formstr (J)) + 32);
end if;
end loop;
-- Acquire setting of shared parameter
declare
V1, V2 : Natural;
begin
Form_Parameter (Formstr, "shared", V1, V2);
if V1 = 0 then
Shared := None;
elsif Formstr (V1 .. V2) = "yes" then
Shared := Yes;
elsif Formstr (V1 .. V2) = "no" then
Shared := No;
else
raise Use_Error;
end if;
end;
-- If we were given a stream (call from xxx.C_Streams.Open), then set
-- full name to null and that is all we have to do in this case so
-- skip to end of processing.
if Stream /= NULL_Stream then
Fullname (1) := ASCII.Nul;
Full_Name_Len := 1;
-- Normal case of Open or Create
else
-- If temporary file case, get temporary file name and add
-- to the list of temporary files to be deleted on exit.
if Tempfile then
if not Creat then
raise Name_Error;
end if;
Tmp_Name (Namestr'Address);
if Namestr (1) = ASCII.NUL then
raise Use_Error;
end if;
-- Chain to temp file list, ensuring thread safety with a lock
begin
SSL.Lock_Task.all;
Temp_Files :=
new Temp_File_Record'(Name => Namestr, Next => Temp_Files);
SSL.Unlock_Task.all;
exception
when others =>
SSL.Unlock_Task.all;
raise;
end;
-- Normal case of non-null name given
else
Namestr (1 .. Name'Length) := Name;
Namestr (Name'Length + 1) := ASCII.NUL;
end if;
-- Get full name in accordance with the advice of RM A.8.2(22).
full_name (Namestr'Address, Fullname'Address);
if Fullname (1) = ASCII.NUL then
raise Use_Error;
end if;
for J in Fullname'Range loop
if Fullname (J) = ASCII.NUL then
Full_Name_Len := J;
exit;
end if;
end loop;
-- If Shared=None or Shared=Yes, then check for the existence
-- of another file with exactly the same full name.
if Shared /= No then
declare
P : AFCB_Ptr;
begin
P := Open_Files;
while P /= null loop
if Fullname (1 .. Full_Name_Len) = P.Name.all then
-- If we get a match, and either file has Shared=None,
-- then raise Use_Error, since we don't allow two
-- files of the same name to be opened unless they
-- specify the required sharing mode.
if Shared = None
or else P.Shared_Status = None
then
raise Use_Error;
-- If both files have Shared=Yes, then we acquire the
-- stream from the located file to use as our stream.
elsif Shared = Yes
and then P.Shared_Status = Yes
then
Stream := P.Stream;
exit;
-- Otherwise one of the files has Shared=Yes and one
-- has Shared=No. If the current file has Shared=No
-- then all is well but we don't want to share any
-- other file's stream. If the current file has
-- Shared=Yes, we would like to share a stream, but
-- not from a file that has Shared=No, so in either
-- case we just keep going on the search.
else
null;
end if;
end if;
P := P.Next;
end loop;
end;
end if;
-- Open specified file if we did not find an existing stream
if Stream = NULL_Stream then
Fopen_Mode (Mode, Text, Creat, Amethod, Fopstr);
-- A special case, if we are opening (OPEN case) a file and
-- the mode returned by Fopen_Mode is not "r" or "r+", then
-- we first make sure that the file exists as required by
-- Ada semantics.
if Creat = False and then Fopstr (1) /= 'r' then
if file_exists (Namestr'Address) = 0 then
raise Name_Error;
end if;
end if;
-- Now open the file. Note that we use the name as given
-- in the original Open call for this purpose, since that
-- seems the clearest implementation of the intent. It
-- would presumably work to use the full name here, but
-- if there is any difference, then we should use the
-- name used in the call.
-- Note: for a corresponding delete, we will use the
-- full name, since by the time of the delete, the
-- current working directory may have changed and
-- we do not want to delete a different file!
Stream := fopen (Namestr'Address, Fopstr'Address);
if Stream = NULL_Stream then
if file_exists (Namestr'Address) = 0 then
raise Name_Error;
else
raise Use_Error;
end if;
end if;
end if;
end if;
-- Stream has been successfully located or opened, so now we are
-- committed to completing the opening of the file. Allocate block
-- on heap and fill in its fields.
File_Ptr := AFCB_Allocate (Dummy_FCB);
File_Ptr.Is_Regular_File := (is_regular_file
(fileno (Stream)) /= 0);
File_Ptr.Is_System_File := False;
File_Ptr.Is_Text_File := Text;
File_Ptr.Shared_Status := Shared;
File_Ptr.Access_Method := Amethod;
File_Ptr.Stream := Stream;
File_Ptr.Form := new String'(Formstr);
File_Ptr.Name := new String'(Fullname
(1 .. Full_Name_Len));
File_Ptr.Mode := Mode;
File_Ptr.Is_Temporary_File := Tempfile;
Chain_File (File_Ptr);
Append_Set (File_Ptr);
end Open;
--------------
-- Read_Buf --
--------------
procedure Read_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
Nread : size_t;
begin
Nread := fread (Buf, 1, Siz, File.Stream);
if Nread = Siz then
return;
elsif ferror (File.Stream) /= 0 then
raise Device_Error;
elsif Nread = 0 then
raise End_Error;
else -- 0 < Nread < Siz
raise Data_Error;
end if;
end Read_Buf;
procedure Read_Buf
(File : AFCB_Ptr;
Buf : Address;
Siz : in Interfaces.C_Streams.size_t;
Count : out Interfaces.C_Streams.size_t)
is
begin
Count := fread (Buf, 1, Siz, File.Stream);
if Count = 0 and then ferror (File.Stream) /= 0 then
raise Device_Error;
end if;
end Read_Buf;
-----------
-- Reset --
-----------
-- The reset which does not change the mode simply does a rewind.
procedure Reset (File : in out AFCB_Ptr) is
begin
Check_File_Open (File);
Reset (File, File.Mode);
end Reset;
-- The reset with a change in mode is done using freopen, and is
-- not permitted except for regular files (since otherwise there
-- is no name for the freopen, and in any case it seems meaningless)
procedure Reset (File : in out AFCB_Ptr; Mode : in File_Mode) is
Fopstr : aliased Fopen_String;
begin
Check_File_Open (File);
-- Change of mode not allowed for shared file or file with no name
-- or file that is not a regular file, or for a system file.
if File.Shared_Status = Yes
or else File.Name'Length <= 1
or else File.Is_System_File
or else (not File.Is_Regular_File)
then
raise Use_Error;
-- For In_File or Inout_File for a regular file, we can just do a
-- rewind if the mode is unchanged, which is more efficient than
-- doing a full reopen.
elsif Mode = File.Mode
and then Mode <= Inout_File
then
rewind (File.Stream);
-- Here the change of mode is permitted, we do it by reopening the
-- file in the new mode and replacing the stream with a new stream.
else
Fopen_Mode
(Mode, File.Is_Text_File, False, File.Access_Method, Fopstr);
File.Stream :=
freopen (File.Name.all'Address, Fopstr'Address, File.Stream);
if File.Stream = NULL_Stream then
Close (File);
raise Use_Error;
else
File.Mode := Mode;
Append_Set (File);
end if;
end if;
end Reset;
---------------
-- Write_Buf --
---------------
procedure Write_Buf (File : AFCB_Ptr; Buf : Address; Siz : size_t) is
begin
-- Note: for most purposes, the Siz and 1 parameters in the fwrite
-- call could be reversed, but on VMS, this is a better choice, since
-- for some file formats, reversing the parameters results in records
-- of one byte each.
SSL.Abort_Defer.all;
if fwrite (Buf, Siz, 1, File.Stream) /= 1 then
if Siz /= 0 then
SSL.Abort_Undefer.all;
raise Device_Error;
end if;
end if;
SSL.Abort_Undefer.all;
end Write_Buf;
end System.File_IO;
|
-----------------------------------------------------------------------
-- awa-wikis-tests -- Unit tests for wikis module
-- Copyright (C) 2018, 2019, 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 Util.Test_Caller;
with Util.Strings;
with ADO;
with Servlet.Streams;
with ASF.Tests;
with AWA.Tests.Helpers.Users;
with AWA.Storages.Beans;
with AWA.Storages.Models;
with AWA.Storages.Services;
with AWA.Storages.Modules;
with AWA.Services.Contexts;
with Security.Contexts;
package body AWA.Wikis.Tests is
use Ada.Strings.Unbounded;
use AWA.Tests;
use type AWA.Storages.Services.Storage_Service_Access;
package Caller is new Util.Test_Caller (Test, "Wikis.Beans");
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is
begin
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load_List (Anonymous)",
Test_Anonymous_Access'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Save",
Test_Create_Wiki'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (missing)",
Test_Missing_Page'Access);
Caller.Add_Test (Suite, "Test AWA.Wikis.Beans.Load (image)",
Test_Page_With_Image'Access);
end Add_Tests;
-- ------------------------------
-- Setup an image for the wiki page.
-- ------------------------------
procedure Make_Wiki_Image (T : in out Test) is
Sec_Ctx : Security.Contexts.Security_Context;
Context : AWA.Services.Contexts.Service_Context;
Folder : AWA.Storages.Beans.Folder_Bean;
Store : AWA.Storages.Models.Storage_Ref;
Mgr : AWA.Storages.Services.Storage_Service_Access;
Outcome : Ada.Strings.Unbounded.Unbounded_String;
Path : constant String
:= Util.Tests.Get_Path ("regtests/files/images/Ada-Lovelace.jpg");
Wiki : constant String := To_String (T.Wiki_Ident);
begin
AWA.Tests.Helpers.Users.Login (Context, Sec_Ctx, "test-wiki@test.com");
Mgr := AWA.Storages.Modules.Get_Storage_Manager;
T.Assert (Mgr /= null, "Null storage manager");
-- Make a storage folder.
Folder.Module := AWA.Storages.Modules.Get_Storage_Module;
Folder.Set_Name ("Images");
Folder.Save (Outcome);
Store.Set_Folder (Folder);
Store.Set_Is_Public (True);
Store.Set_Mime_Type ("image/jpg");
Store.Set_Name ("Ada-Lovelace.jpg");
Mgr.Save (Store, Path, AWA.Storages.Models.FILE);
declare
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
Id : constant String := ADO.Identifier'Image (Store.Get_Id);
begin
T.Image_Ident := To_Unbounded_String (Id (Id'First + 1 .. Id'Last));
AWA.Tests.Helpers.Users.Login ("test-storage@test.com", Request);
ASF.Tests.Do_Get (Request, Reply,
"/wikis/images/" & Wiki & "/"
& Id (Id'First + 1 .. Id'Last)
& "/original/Ada-Lovelace.jpg",
"wiki-image-get-Ada-Lovelace.jpg");
ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply);
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK,
Reply.Get_Status,
"Invalid response for image");
T.Image_Link := To_Unbounded_String ("/wikis/images/" & Wiki
& "/" & Id (Id'First + 1 .. Id'Last)
& "/default/Ada-Lovelace.jpg");
end;
end Make_Wiki_Image;
-- ------------------------------
-- Get some access on the wiki as anonymous users.
-- ------------------------------
procedure Verify_Anonymous (T : in out Test;
Page : in String;
Title : in String) is
pragma Unreferenced (Title);
function Get_Link (Title : in String) return String;
Wiki : constant String := To_String (T.Wiki_Ident);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
function Get_Link (Title : in String) return String is
Stream : Servlet.Streams.Print_Stream := Reply.Get_Output_Stream;
Content : Ada.Strings.Unbounded.Unbounded_String;
begin
Reply.Read_Content (Content);
Stream.Write (Content);
return AWA.Tests.Helpers.Extract_Link (To_String (Content), Title);
end Get_Link;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Do_Get (Request, Reply, "/wikis/tags/" & Wiki,
"wiki-list-tagged.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki tag page is invalid");
if Page'Length > 0 then
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/" & Page,
"wiki-page-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "The wiki page content", Reply,
"Wiki page " & Page & " is invalid");
declare
Info : constant String := Get_Link ("Info");
History : constant String := Get_Link ("History");
begin
Util.Tests.Assert_Matches (T, "/asfunit/wikis/info/[0-9]+/[0-9]+$", Info,
"Invalid wiki info link in the response");
Util.Tests.Assert_Matches (T, "/asfunit/wikis/history/[0-9]+/[0-9]+$", History,
"Invalid wiki history link in the response");
-- Get the information page.
ASF.Tests.Do_Get (Request, Reply, Info (Info'First + 8 .. Info'Last),
"wiki-info-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-word-list", Reply,
"Wiki info page " & Page & " is invalid");
-- Get the history page.
ASF.Tests.Do_Get (Request, Reply, History (History'First + 8 .. History'Last),
"wiki-history-" & Page & ".html");
ASF.Tests.Assert_Contains (T, "wiki-page-version", Reply,
"Wiki history page " & Page & " is invalid");
end;
end if;
end Verify_Anonymous;
-- ------------------------------
-- Verify that the wiki lists contain the given page.
-- ------------------------------
procedure Verify_List_Contains (T : in out Test;
Page : in String) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/recent",
"wiki-list-recent.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list recent page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list recent page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/popular",
"wiki-list-popular.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list popular page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list popular page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name",
"wiki-list-name.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name page does not reference the page");
ASF.Tests.Do_Get (Request, Reply, "/wikis/list/" & Wiki & "/name/grid",
"wiki-list-name-grid.html");
ASF.Tests.Assert_Contains (T, "List of pages", Reply,
"Wiki list name/grid page is invalid");
ASF.Tests.Assert_Contains (T, "/wikis/view/" & To_String (T.Wiki_Ident)
& "/" & Page, Reply,
"Wiki list name/grid page does not reference the page");
end Verify_List_Contains;
-- ------------------------------
-- Test access to the blog as anonymous user.
-- ------------------------------
procedure Test_Anonymous_Access (T : in out Test) is
begin
T.Verify_Anonymous ("", "");
end Test_Anonymous_Access;
-- ------------------------------
-- Create a wiki page.
-- ------------------------------
procedure Create_Page (T : in out Test;
Request : in out Servlet.Requests.Mockup.Request;
Reply : in out Servlet.Responses.Mockup.Response;
Name : in String;
Title : in String) is
begin
Request.Set_Parameter ("page-wiki-id", To_String (T.Wiki_Ident));
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("page-title", Title);
Request.Set_Parameter ("text", "# Main title" & ASCII.LF
& "* The wiki page content." & ASCII.LF
& "* Second item." & ASCII.LF
& ASCII.LF
& "");
Request.Set_Parameter ("name", Name);
Request.Set_Parameter ("comment", "Created wiki page " & Name);
Request.Set_Parameter ("save", "1");
Request.Set_Parameter ("page-is-public", "1");
Request.Set_Parameter ("wiki-format", "FORMAT_MARKDOWN");
ASF.Tests.Do_Post (Request, Reply, "/wikis/create.html", "create-wiki.html");
T.Page_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/wikis/view/"
& To_String (T.Wiki_Ident) & "/");
Util.Tests.Assert_Equals (T, Name, To_String (T.Page_Ident),
"Invalid redirect after wiki page creation");
-- Remove the 'wikiPage' bean from the request so that we get a new instance
-- for the next call.
Request.Remove_Attribute ("wikiPage");
end Create_Page;
-- ------------------------------
-- Test creation of blog by simulating web requests.
-- ------------------------------
procedure Test_Create_Wiki (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
AWA.Tests.Helpers.Users.Login ("test-wiki@test.com", Request);
Request.Set_Parameter ("title", "The Wiki Space Title");
Request.Set_Parameter ("post", "1");
Request.Set_Parameter ("create", "1");
ASF.Tests.Do_Post (Request, Reply, "/wikis/setup.html", "setup-wiki.html");
T.Assert (Reply.Get_Status = Servlet.Responses.SC_MOVED_TEMPORARILY,
"Invalid response after wiki space creation");
declare
Ident : constant String
:= Helpers.Extract_Redirect (Reply, "/asfunit/wikis/list/");
Pos : constant Natural
:= Util.Strings.Index (Ident, '/');
begin
Util.Tests.Assert_Matches (T, "^[0-9]+/recent/grid$", Ident,
"Invalid wiki space identifier in the response");
T.Wiki_Ident := To_Unbounded_String (Ident (Ident'First .. Pos - 1));
end;
T.Create_Page (Request, Reply, "WikiPageTestName", "Wiki page title1");
T.Verify_List_Contains (To_String (T.Page_Ident));
T.Create_Page (Request, Reply, "WikiSecondPageName", "Wiki page title2");
T.Verify_List_Contains (To_String (T.Page_Ident));
T.Create_Page (Request, Reply, "WikiThirdPageName", "Wiki page title3");
T.Verify_Anonymous ("WikiPageTestName", "Wiki page title1");
T.Verify_Anonymous ("WikiSecondPageName", "Wiki page title2");
T.Verify_Anonymous ("WikiThirdPageName", "Wiki page title3");
end Test_Create_Wiki;
-- ------------------------------
-- Test getting a wiki page which does not exist.
-- ------------------------------
procedure Test_Missing_Page (T : in out Test) is
Wiki : constant String := To_String (T.Wiki_Ident);
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
begin
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/MissingPage",
"wiki-page-missing.html");
ASF.Tests.Assert_Matches (T, ".title.Wiki page does not exist./title.", Reply,
"Wiki page 'MissingPage' is invalid",
Servlet.Responses.SC_NOT_FOUND);
ASF.Tests.Assert_Matches (T, ".h2.MissingPage./h2.", Reply,
"Wiki page 'MissingPage' header is invalid",
Servlet.Responses.SC_NOT_FOUND);
end Test_Missing_Page;
-- ------------------------------
-- Test creation of wiki page with an image.
-- ------------------------------
procedure Test_Page_With_Image (T : in out Test) is
Request : Servlet.Requests.Mockup.Request;
Reply : Servlet.Responses.Mockup.Response;
Wiki : constant String := To_String (T.Wiki_Ident);
begin
AWA.Tests.Helpers.Users.Login ("test-wiki@test.com", Request);
T.Make_Wiki_Image;
T.Create_Page (Request, Reply, "WikiImageTest", "Wiki image title3");
ASF.Tests.Do_Get (Request, Reply, "/wikis/view/" & Wiki & "/WikiImageTest",
"wiki-image-test.html");
ASF.Tests.Assert_Matches (T, "<img src=./wikis/images/[0-9]*/[0-9]*"
& "/default/Ada-Lovelace.jpg.* alt=.Ada Lovelace.></img>",
Reply,
"Wiki page missing image link",
Servlet.Responses.SC_OK);
ASF.Tests.Do_Get (Request, Reply,
To_String (T.Image_Link),
"wiki-image-get-Ada-Lovelace.jpg");
ASF.Tests.Assert_Header (T, "Content-Type", "image/jpg", Reply);
Util.Tests.Assert_Equals (T, Servlet.Responses.SC_OK,
Reply.Get_Status,
"Invalid response for image");
ASF.Tests.Do_Get (Request, Reply, "/wikis/image-info/" & Wiki & "/"
& To_String (T.Image_Ident) & "/Images/Ada-Lovelace.jpg",
"wiki-image-info.html");
ASF.Tests.Assert_Contains (T, "<title>Image information</title>", Reply,
"Wiki image information page is invalid");
ASF.Tests.Assert_Matches (T, "<dt>File name</dt>",
Reply,
"Wiki image information invalid name (1)",
Servlet.Responses.SC_OK);
ASF.Tests.Assert_Matches (T, "<dd>Images/Ada-Lovelace.jpg</dd>",
Reply,
"Wiki image information invalid name (2)",
Servlet.Responses.SC_OK);
end Test_Page_With_Image;
end AWA.Wikis.Tests;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P A N D E R --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This procedure performs any required expansion for the specified node.
-- The argument is the node that is a candidate for possible expansion.
-- If no expansion is required, then Expand returns without doing anything.
-- If the node does need expansion, then the subtree is replaced by the
-- tree corresponding to the required rewriting. This tree is a syntactic
-- tree, except that all Entity fields must be correctly set on all
-- direct names, since the expander presumably knows what it wants, and in
-- any case it doesn't work to have the semantic analyzer perform visibility
-- analysis on these trees (they may have references to non-visible runtime
-- routines etc.) There are a few exceptions to this rule in special cases,
-- but they must be documented clearly.
-- Expand is called in two different situations:
-- Nodes that are not subexpressions (Nkind not in N_Subexpr)
-- In this case, Expand is called from the body of Sem, immediately
-- after completing semantic analysis by calling the corresponding
-- Analyze_N_xxx procedure. If expansion occurs, the given node must
-- be replaced with another node that is also not a subexpression.
-- This seems naturally to be the case, since it is hard to imagine any
-- situation in which it would make sense to replace a non-expression
-- subtree with an expression. Once the substitution is completed, the
-- Expand routine must call Analyze on the resulting node to do any
-- required semantic analysis. Note that references to children copied
-- from the old tree won't be reanalyzed, since their Analyzed flag
-- is set.
-- Nodes that are subexpressions (Nkind in N_Subexpr)
-- In this case, Expand is called from Sem_Res.Resolve after completing
-- the resolution of the subexpression (this means that the expander sees
-- the fully typed subtree). If expansion occurs, the given node must be
-- replaced by a node that is also a subexpression. Again it is hard
-- to see how this restriction could possibly be violated. Once the
-- substitution is completed, the Expand routine must first call Analyze
-- on the resulting node to do any required semantic analysis, and then
-- call Resolve on the node to set the type (typically the type will be
-- the same as the original type of the input node, but this is not
-- always the case).
-- In both these cases, Replace or Rewrite must be used to achieve the
-- expansion of the node, since the Expander routine is only passed the
-- Node_Id of the node to be expanded, and the resulting expanded Node_Id
-- must be the same (the parameter to Expand is mode in, not mode in-out).
-- For nodes other than subexpressions, it is not necessary to preserve the
-- original tree in the Expand routines, unlike the case for modifications
-- to the tree made in the semantic analyzer. This is because anyone who is
-- interested in working with the original tree is required to compile in
-- semantics checks only mode. Thus Replace may be freely used in such
-- instances.
-- For subexpressions, preservation of the original tree is required because
-- of the need for conformance checking of default expressions, which occurs
-- on expanded trees. This means that Replace should not ever be used on
-- on subexpression nodes. Instead use Rewrite.
-- Note: the front end avoids calls to any of the expand routines if code
-- is not being generated. This is done for three reasons:
-- 1. Make sure tree does not get mucked up by the expander if no
-- code is being generated, and is thus usable by ASIS etc.
-- 2. Save time, since expansion is not needed if a compilation is
-- being done only to check the semantics, or if code generation
-- has been canceled due to previously detected errors.
-- 3. Allow the expand routines to assume that the tree is error free.
-- This results from the fact that code generation mode is always
-- cancelled when any error occurs.
-- If we ever decide to implement a feature allowing object modules to be
-- generated even if errors have been detected, then point 3 will no longer
-- hold, and the expand routines will have to be modified to operate properly
-- in the presence of errors (for many reasons this is not currently true).
-- Note: a consequence of this approach is that error messages must never
-- be generated in the expander, since this would mean that such error
-- messages are not generated when the expander is not being called.
-- Expansion is the last stage of analyzing a node, so Expand sets the
-- Analyzed flag of the node being analyzed as its last action. This is
-- done even if expansion is off (in this case, the only effect of the
-- call to Expand is to set the Analyzed flag to True).
with Types; use Types;
package Expander is
-- The flag Opt.Expander_Active controls whether expansion is active
-- (True) or deactivated (False). When expansion is deactivated all
-- calls to expander routines have no effect. To temporarily disable
-- expansion, always call the routines defined below, do NOT change
-- Expander_Active directly.
--
-- You should not use this flag to test if you are currently processing
-- a generic spec or body. Use the flag Inside_A_Generic instead (see
-- the spec of package Sem).
--
-- There is no good reason for permanently changing the value of this flag
-- except after detecting a syntactic or semantic error. In this event
-- this flag is set to False to disable all subsequent expansion activity.
--
-- In general this flag should be used as a read only value. The only
-- exceptions where it makes sense to temporarily change its value are:
--
-- (a) when starting/completing the processing of a generic definition
-- or declaration (see routines Start_Generic_Processing and
-- End_Generic_Processing in Sem_Ch12)
--
-- (b) when starting/completing the preanalysis of an expression
-- (see the spec of package Sem for more info on preanalysis.)
--
-- Note that when processing a spec expression (In_Spec_Expression
-- is True) or performing semantic analysis of a generic spec or body
-- (Inside_A_Generic) or when performing preanalysis (Full_Analysis is
-- False) the Expander_Active flag is False.
procedure Expand (N : Node_Id);
-- Expand node N, as described above
procedure Expander_Mode_Save_And_Set (Status : Boolean);
-- Saves the current setting of the Expander_Active flag on an internal
-- stack and then sets the flag to the given value.
--
-- Note: this routine has no effect in GNATprove mode. In this mode,
-- a very light expansion is performed on specific nodes and
-- Expander_Active is set to False.
-- In situations such as the call to Instantiate_Bodies in Frontend,
-- Expander_Mode_Save_And_Set may be called to temporarily turn the
-- expander on, but this will have no effect in GNATprove mode.
procedure Expander_Mode_Restore;
-- Restores the setting of the Expander_Active flag using the top entry
-- pushed onto the stack by Expander_Mode_Save_And_Reset, popping the
-- stack, except that if any errors have been detected, then the state of
-- the flag is left set to False. Disabled for GNATprove mode (see above).
end Expander;
|
-- Standard Ada library specification
-- Copyright (c) 2003-2018 Maxim Reznik <reznikmm@gmail.com>
-- Copyright (c) 2004-2016 AXE Consultants
-- Copyright (c) 2004, 2005, 2006 Ada-Europe
-- Copyright (c) 2000 The MITRE Corporation, Inc.
-- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc.
-- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual
---------------------------------------------------------------------------
with Ada.Containers;
function Ada.Strings.Wide_Hash (Key : in Wide_String)
return Ada.Containers.Hash_Type;
pragma Pure (Wide_Hash);
|
-- E28002B.ADA
-- Grant of Unlimited Rights
--
-- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687,
-- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained
-- unlimited rights in the software and documentation contained herein.
-- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making
-- this public release, the Government intends to confer upon all
-- recipients unlimited rights equal to those held by the Government.
-- These rights include rights to use, duplicate, release or disclose the
-- released technical data and computer software in whole or in part, in
-- any manner and for any purpose whatsoever, and to have or permit others
-- to do so.
--
-- DISCLAIMER
--
-- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR
-- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED
-- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE
-- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE
-- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A
-- PARTICULAR PURPOSE OF SAID MATERIAL.
--*
-- OBJECTIVE:
-- CHECK THAT A PREDEFINED OR AN UNRECOGNIZED PRAGMA MAY HAVE
-- ARGUMENTS INVOLVING OVERLOADED IDENTIFIERS WITHOUT ENOUGH
-- CONTEXTUAL INFORMATION TO RESOLVE THE OVERLOADING.
-- PASS/FAIL CRITERIA:
-- THIS TEST IS PASSED IF IT REPORTS "TENTATIVELY PASSED" AND
-- THE STARRED COMMENT DOES NOT APPEAR IN THE LISTING.
-- AN IMPLEMENTATION FAILS THIS TEST IF THE STARRED COMMENT
-- LINE APPEARS IN THE COMPILATION LISTING.
-- HISTORY:
-- TBN 02/24/86 CREATED ORIGINAL TEST.
-- JET 01/13/88 ADDED CALLS TO SPECIAL_ACTION AND UPDATED HEADER.
-- EDS 10/28/97 ADDED DECLARATIONS FOR PROCEDURES XYZ.
WITH REPORT, SYSTEM; USE REPORT, SYSTEM;
PROCEDURE E28002B IS
FUNCTION OFF RETURN INTEGER IS
BEGIN
RETURN 1;
END OFF;
FUNCTION OFF RETURN BOOLEAN IS
BEGIN
RETURN TRUE;
END OFF;
PRAGMA LIST (OFF);
--***** THIS LINE MUST NOT APPEAR IN COMPILATION LISTING.
PRAGMA LIST (ON);
FUNCTION ELABORATION_CHECK RETURN INTEGER IS
BEGIN
RETURN 1;
END ELABORATION_CHECK;
FUNCTION ELABORATION_CHECK RETURN BOOLEAN IS
BEGIN
RETURN TRUE;
END ELABORATION_CHECK;
PRAGMA SUPPRESS (ELABORATION_CHECK, ELABORATION_CHECK);
FUNCTION TIME RETURN INTEGER IS
BEGIN
RETURN 1;
END TIME;
FUNCTION TIME RETURN BOOLEAN IS
BEGIN
RETURN TRUE;
END TIME;
PRAGMA OPTIMIZE (TIME);
PROCEDURE XYZ;
PROCEDURE XYZ (COUNT : INTEGER);
PRAGMA INLINE (XYZ);
PRAGMA PHIL_BRASHEAR (XYZ);
PROCEDURE XYZ IS
BEGIN
NULL;
END XYZ;
PROCEDURE XYZ (COUNT : INTEGER) IS
BEGIN
NULL;
END XYZ;
BEGIN
TEST ("E28002B", "CHECK THAT A PREDEFINED OR AN UNRECOGNIZED " &
"PRAGMA MAY HAVE ARGUMENTS INVOLVING " &
"OVERLOADED IDENTIFIERS WITHOUT ENOUGH " &
"CONTEXTUAL INFORMATION TO RESOLVE THE " &
"OVERLOADING");
SPECIAL_ACTION ("CHECK THAT THE COMPILATION LISTING DOES NOT " &
"SHOW THE STARRED COMMENT LINE");
RESULT;
END E28002B;
|
generic
package Symbolic_Expressions.Solving is
-- ==================== --
-- == SYSTEM SOLVING == --
-- ==================== --
package Equation_Tables is
new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => Variable_Name,
Element_Type => Symbolic_Expression);
procedure Triangular_Solve (What : in Equation_Tables.Map;
Result : out Variable_Tables.Map;
Success : out Boolean);
-- Parameter What represents a system of equations of the form
--
-- <variable> = <expression>
--
-- This procedure tries to find a solution for that system of
-- equations. If a solution is found, Success is set to True and Result
-- contains the values found for the variables; if a solution is not
-- found Success is set to False and Result can be partially filled.
--
-- To be honest, this procedure is limited to solving
-- systems that can be solved by "back substitution," such as
--
-- x = y*3 + max(u, v)
-- y = min(u, z)
-- u = v*z
-- v = 10
-- z = -1
--
-- Note that the system above can be solved by evaluating
-- the expressions from last to first. Systems like
--
-- x + y = 0
-- x - y = 4
--
-- have a solution, but they cannot be solved by this procedure.
-- This procedure is useful to solve for constraints that come, for
-- example, from a DAG and it has the advantage that no special constraints
-- are posed on the equations that can include non-linear (and badly
-- behaving) functions like max, abs, and so on...
--
end Symbolic_Expressions.Solving;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M --
-- --
-- S p e c --
-- (RISC-V Version) --
-- --
-- Copyright (C) 2018-2020, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
pragma Restrictions (No_Exception_Propagation);
-- Only local exception handling is supported in this profile
pragma Restrictions (No_Exception_Registration);
-- Disable exception name registration. This capability is not used because
-- it is only required by exception stream attributes which are not supported
-- in this run time.
pragma Restrictions (No_Implicit_Dynamic_Code);
-- Pointers to nested subprograms are not allowed in this run time, in order
-- to prevent the compiler from building "trampolines".
pragma Restrictions (No_Finalization);
-- Controlled types are not supported in this run time
pragma Restrictions (No_Tasking);
-- Tasking is not supported in this run time
pragma Discard_Names;
-- Disable explicitly the generation of names associated with entities in
-- order to reduce the amount of storage used. These names are not used anyway
-- (attributes such as 'Image and 'Value are not supported in this run time).
package System is
pragma Pure;
-- Note that we take advantage of the implementation permission to make
-- this unit Pure instead of Preelaborable; see RM 13.7.1(15). In Ada
-- 2005, this is Pure in any case (AI-362).
pragma No_Elaboration_Code_All;
-- Allow the use of that restriction in units that WITH this unit
type Name is (SYSTEM_NAME_GNAT);
System_Name : constant Name := SYSTEM_NAME_GNAT;
-- System-Dependent Named Numbers
Min_Int : constant := -2 ** (Standard'Max_Integer_Size - 1);
Max_Int : constant := 2 ** (Standard'Max_Integer_Size - 1) - 1;
Max_Binary_Modulus : constant := 2 ** Standard'Max_Integer_Size;
Max_Nonbinary_Modulus : constant := 2 ** Integer'Size - 1;
Max_Base_Digits : constant := Long_Long_Float'Digits;
Max_Digits : constant := Long_Long_Float'Digits;
Max_Mantissa : constant := Standard'Max_Integer_Size - 1;
Fine_Delta : constant := 2.0 ** (-Max_Mantissa);
Tick : constant := 0.0;
-- Storage-related Declarations
type Address is private;
pragma Preelaborable_Initialization (Address);
Null_Address : constant Address;
Storage_Unit : constant := 8;
Word_Size : constant := Standard'Word_Size;
Memory_Size : constant := 2 ** Word_Size;
-- Address comparison
function "<" (Left, Right : Address) return Boolean;
function "<=" (Left, Right : Address) return Boolean;
function ">" (Left, Right : Address) return Boolean;
function ">=" (Left, Right : Address) return Boolean;
function "=" (Left, Right : Address) return Boolean;
pragma Import (Intrinsic, "<");
pragma Import (Intrinsic, "<=");
pragma Import (Intrinsic, ">");
pragma Import (Intrinsic, ">=");
pragma Import (Intrinsic, "=");
-- Other System-Dependent Declarations
type Bit_Order is (High_Order_First, Low_Order_First);
Default_Bit_Order : constant Bit_Order :=
Bit_Order'Val (Standard'Default_Bit_Order);
pragma Warnings (Off, Default_Bit_Order); -- kill constant condition warning
-- Priority-related Declarations (RM D.1)
Max_Priority : constant Positive := 30;
Max_Interrupt_Priority : constant Positive := 31;
subtype Any_Priority is Integer range 0 .. 31;
subtype Priority is Any_Priority range 0 .. 30;
subtype Interrupt_Priority is Any_Priority range 31 .. 31;
Default_Priority : constant Priority := 15;
private
type Address is mod Memory_Size;
Null_Address : constant Address := 0;
--------------------------------------
-- System Implementation Parameters --
--------------------------------------
-- These parameters provide information about the target that is used
-- by the compiler. They are in the private part of System, where they
-- can be accessed using the special circuitry in the Targparm unit
-- whose source should be consulted for more detailed descriptions
-- of the individual switch values.
Atomic_Sync_Default : constant Boolean := False;
Backend_Divide_Checks : constant Boolean := False;
Backend_Overflow_Checks : constant Boolean := True;
Command_Line_Args : constant Boolean := False;
Configurable_Run_Time : constant Boolean := True;
Denorm : constant Boolean := True;
Duration_32_Bits : constant Boolean := True;
Exit_Status_Supported : constant Boolean := False;
Fractional_Fixed_Ops : constant Boolean := False;
Frontend_Layout : constant Boolean := False;
Machine_Overflows : constant Boolean := False;
Machine_Rounds : constant Boolean := True;
Preallocated_Stacks : constant Boolean := False;
Signed_Zeros : constant Boolean := True;
Stack_Check_Default : constant Boolean := False;
Stack_Check_Probes : constant Boolean := False;
Stack_Check_Limits : constant Boolean := False;
Support_Aggregates : constant Boolean := True;
Support_Composite_Assign : constant Boolean := True;
Support_Composite_Compare : constant Boolean := True;
Support_Long_Shifts : constant Boolean := True;
Always_Compatible_Rep : constant Boolean := True;
Suppress_Standard_Library : constant Boolean := True;
Use_Ada_Main_Program_Name : constant Boolean := False;
Frontend_Exceptions : constant Boolean := False;
ZCX_By_Default : constant Boolean := True;
end System;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with AMF.CMOF.Elements;
with AMF.DI.Styles;
with AMF.Internals.UMLDI_UML_Compartmentable_Shapes;
with AMF.UML.Classifiers;
with AMF.UML.Elements.Collections;
with AMF.UMLDI.UML_Classifier_Shapes;
with AMF.UMLDI.UML_Compartments.Collections;
with AMF.UMLDI.UML_Styles;
with AMF.Visitors;
package AMF.Internals.UMLDI_UML_Classifier_Shapes is
type UMLDI_UML_Classifier_Shape_Proxy is
limited new AMF.Internals.UMLDI_UML_Compartmentable_Shapes.UMLDI_UML_Compartmentable_Shape_Proxy
and AMF.UMLDI.UML_Classifier_Shapes.UMLDI_UML_Classifier_Shape with null record;
overriding function Get_Is_Double_Sided
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return Boolean;
-- Getter of UMLClassifierShape::isDoubleSided.
--
-- For modelElements that are Classes with true as a value for isActive
-- that are shown as rectangles, indicates whether the vertical sides
-- shall be rendered as double lines.
overriding procedure Set_Is_Double_Sided
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : Boolean);
-- Setter of UMLClassifierShape::isDoubleSided.
--
-- For modelElements that are Classes with true as a value for isActive
-- that are shown as rectangles, indicates whether the vertical sides
-- shall be rendered as double lines.
overriding function Get_Is_Indent_For_Visibility
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return Boolean;
-- Getter of UMLClassifierShape::isIndentForVisibility.
--
-- For modelElements that are shown with feature compartments, indicates
-- whether features are shown indented under visibility headings.
overriding procedure Set_Is_Indent_For_Visibility
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : Boolean);
-- Setter of UMLClassifierShape::isIndentForVisibility.
--
-- For modelElements that are shown with feature compartments, indicates
-- whether features are shown indented under visibility headings.
overriding function Get_Model_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.UML.Classifiers.UML_Classifier_Access;
-- Getter of UMLClassifierShape::modelElement.
--
-- Restricts UMLClassifierShapes to showing exactly one Classifier.
overriding procedure Set_Model_Element
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : AMF.UML.Classifiers.UML_Classifier_Access);
-- Setter of UMLClassifierShape::modelElement.
--
-- Restricts UMLClassifierShapes to showing exactly one Classifier.
overriding function Get_Compartment
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.UMLDI.UML_Compartments.Collections.Ordered_Set_Of_UMLDI_UML_Compartment;
-- Getter of UMLCompartmentableShape::compartment.
--
-- Separated portions of the shape.
overriding function Get_Is_Icon
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return Boolean;
-- Getter of UMLDiagramElement::isIcon.
--
-- For modelElements that have an option to be shown with shapes other
-- than rectangles, such as Actors, or with other identifying shapes
-- inside them, such as arrows distinguishing InputPins and OutputPins, or
-- edges that have an option to be shown with lines other than solid with
-- open arrow heads, such as Realization. A value of true for isIcon
-- indicates the alternative notation shall be shown.
overriding procedure Set_Is_Icon
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : Boolean);
-- Setter of UMLDiagramElement::isIcon.
--
-- For modelElements that have an option to be shown with shapes other
-- than rectangles, such as Actors, or with other identifying shapes
-- inside them, such as arrows distinguishing InputPins and OutputPins, or
-- edges that have an option to be shown with lines other than solid with
-- open arrow heads, such as Realization. A value of true for isIcon
-- indicates the alternative notation shall be shown.
overriding function Get_Local_Style
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.UMLDI.UML_Styles.UMLDI_UML_Style_Access;
-- Getter of UMLDiagramElement::localStyle.
--
-- Restricts owned styles to UMLStyles.
overriding procedure Set_Local_Style
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : AMF.UMLDI.UML_Styles.UMLDI_UML_Style_Access);
-- Setter of UMLDiagramElement::localStyle.
--
-- Restricts owned styles to UMLStyles.
overriding function Get_Model_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.UML.Elements.Collections.Set_Of_UML_Element;
-- Getter of UMLDiagramElement::modelElement.
--
-- Restricts UMLDiagramElements to show UML Elements, rather than other
-- language elements.
overriding function Get_Model_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.CMOF.Elements.CMOF_Element_Access;
-- Getter of DiagramElement::modelElement.
--
-- a reference to a depicted model element, which can be any MOF-based
-- element
overriding function Get_Local_Style
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy)
return AMF.DI.Styles.DI_Style_Access;
-- Getter of DiagramElement::localStyle.
--
-- a reference to an optional locally-owned style for this diagram element.
overriding procedure Set_Local_Style
(Self : not null access UMLDI_UML_Classifier_Shape_Proxy;
To : AMF.DI.Styles.DI_Style_Access);
-- Setter of DiagramElement::localStyle.
--
-- a reference to an optional locally-owned style for this diagram element.
overriding procedure Enter_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
overriding procedure Leave_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
overriding procedure Visit_Element
(Self : not null access constant UMLDI_UML_Classifier_Shape_Proxy;
Iterator : in out AMF.Visitors.Abstract_Iterator'Class;
Visitor : in out AMF.Visitors.Abstract_Visitor'Class;
Control : in out AMF.Visitors.Traverse_Control);
end AMF.Internals.UMLDI_UML_Classifier_Shapes;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- O S I N T --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the low level, operating system routines used in
-- the GNAT compiler and binder for command line processing and file input
-- output.
with GNAT.OS_Lib; use GNAT.OS_Lib;
with System; use System;
with Types; use Types;
pragma Elaborate (GNAT.OS_Lib);
package Osint is
Multi_Unit_Index_Character : Character := '~';
-- The character before the index of the unit in a multi-unit source,
-- in ALI and object file names. This is not a constant, because it is
-- changed to '$' on VMS.
Ada_Include_Path : constant String := "ADA_INCLUDE_PATH";
Ada_Objects_Path : constant String := "ADA_OBJECTS_PATH";
Project_Include_Path_File : constant String := "ADA_PRJ_INCLUDE_FILE";
Project_Objects_Path_File : constant String := "ADA_PRJ_OBJECTS_FILE";
procedure Initialize;
-- Initialize internal tables
function Normalize_Directory_Name (Directory : String) return String_Ptr;
-- Verify and normalize a directory name. If directory name is invalid,
-- this will return an empty string. Otherwise it will insure a trailing
-- slash and make other normalizations.
type File_Type is (Source, Library, Config, Definition, Preprocessing_Data);
function Find_File
(N : File_Name_Type;
T : File_Type) return File_Name_Type;
-- Finds a source, library or config file depending on the value
-- of T following the directory search order rules unless N is the
-- name of the file just read with Next_Main_File and already
-- contains directiory information, in which case just look in the
-- Primary_Directory. Returns File_Name_Type of the full file name
-- if found, No_File if file not found. Note that for the special
-- case of gnat.adc, only the compilation environment directory is
-- searched, i.e. the directory where the ali and object files are
-- written. Another special case is when Debug_Generated_Code is
-- set and the file name ends on ".dg", in which case we look for
-- the generated file only in the current directory, since that is
-- where it is always built.
function Get_File_Names_Case_Sensitive return Int;
pragma Import (C, Get_File_Names_Case_Sensitive,
"__gnat_get_file_names_case_sensitive");
File_Names_Case_Sensitive : constant Boolean :=
Get_File_Names_Case_Sensitive /= 0;
-- Set to indicate whether the operating system convention is for file
-- names to be case sensitive (e.g., in Unix, set True), or non case
-- sensitive (e.g., in OS/2, set False).
procedure Canonical_Case_File_Name (S : in out String);
-- Given a file name, converts it to canonical case form. For systems
-- where file names are case sensitive, this procedure has no effect.
-- If file names are not case sensitive (i.e. for example if you have
-- the file "xyz.adb", you can refer to it as XYZ.adb or XyZ.AdB), then
-- this call converts the given string to canonical all lower case form,
-- so that two file names compare equal if they refer to the same file.
function Number_Of_Files return Int;
-- Gives the total number of filenames found on the command line
No_Index : constant := -1;
-- Value used in Add_File to indicate no index is specified for main
procedure Add_File (File_Name : String; Index : Int := No_Index);
-- Called by the subprogram processing the command line for each file name
-- found. The index, when not defaulted to No_Index is the index of the
-- subprogram in its source, zero indicating that the source is not
-- multi-unit.
procedure Find_Program_Name;
-- Put simple name of current program being run (excluding the directory
-- path) in Name_Buffer, with the length in Name_Len.
function Program_Name (Nam : String) return String_Access;
-- In the native compilation case, Create a string containing Nam. In the
-- cross compilation case, looks at the prefix of the current program being
-- run and prepend it to Nam. For instance if the program being run is
-- <target>-gnatmake and Nam is "gcc", the returned value will be a pointer
-- to "<target>-gcc". This function clobbers Name_Buffer and Name_Len.
procedure Write_Program_Name;
-- Writes name of program as invoked to the current output
-- (normally standard output).
procedure Fail (S1 : String; S2 : String := ""; S3 : String := "");
pragma No_Return (Fail);
-- Outputs error messages S1 & S2 & S3 preceded by the name of the
-- executing program and exits with E_Fatal. The output goes to standard
-- error, except if special output is in effect (see Output).
function Is_Directory_Separator (C : Character) return Boolean;
-- Returns True if C is a directory separator
function Get_Directory (Name : File_Name_Type) return File_Name_Type;
-- Get the prefix directory name (if any) from Name. The last separator
-- is preserved. Return the normalized current directory if there is no
-- directory part in the name.
function Is_Readonly_Library (File : File_Name_Type) return Boolean;
-- Check if this library file is a read-only file
function Strip_Directory (Name : File_Name_Type) return File_Name_Type;
-- Strips the prefix directory name (if any) from Name. Returns the
-- stripped name. Name cannot end with a directory separator.
function Strip_Suffix (Name : File_Name_Type) return File_Name_Type;
-- Strips the suffix (the last '.' and whatever comes after it) from Name.
-- Returns the stripped name.
function Executable_Name (Name : File_Name_Type) return File_Name_Type;
-- Given a file name it adds the appropriate suffix at the end so that
-- it becomes the name of the executable on the system at end. For
-- instance under DOS it adds the ".exe" suffix, whereas under UNIX no
-- suffix is added.
function File_Stamp (Name : File_Name_Type) return Time_Stamp_Type;
-- Returns the time stamp of file Name. Name should include relative
-- path information in order to locate it. If the source file cannot be
-- opened, or Name = No_File, and all blank time stamp is returned (this is
-- not an error situation).
type String_Access_List is array (Positive range <>) of String_Access;
-- Deferenced type used to return a list of file specs in
-- To_Canonical_File_List.
type String_Access_List_Access is access all String_Access_List;
-- Type used to return a String_Access_List without dragging in secondary
-- stack.
function To_Canonical_File_List
(Wildcard_Host_File : String;
Only_Dirs : Boolean) return String_Access_List_Access;
-- Expand a wildcard host syntax file or directory specification (e.g. on
-- a VMS host, any file or directory spec that contains:
-- "*", or "%", or "...")
-- and return a list of valid Unix syntax file or directory specs.
-- If Only_Dirs is True, then only return directories.
function To_Canonical_Dir_Spec
(Host_Dir : String;
Prefix_Style : Boolean) return String_Access;
-- Convert a host syntax directory specification (e.g. on a VMS host:
-- "SYS$DEVICE:[DIR]") to canonical (Unix) syntax (e.g. "/sys$device/dir").
-- If Prefix_Style then make it a valid file specification prefix. A file
-- specification prefix is a directory specification that can be appended
-- with a simple file specification to yield a valid absolute or relative
-- path to a file. On a conversion to Unix syntax this simply means the
-- spec has a trailing slash ("/").
function To_Canonical_File_Spec
(Host_File : String) return String_Access;
-- Convert a host syntax file specification (e.g. on a VMS host:
-- "SYS$DEVICE:[DIR]FILE.EXT;69 to canonical (Unix) syntax (e.g.
-- "/sys$device/dir/file.ext.69").
function To_Canonical_Path_Spec
(Host_Path : String) return String_Access;
-- Convert a host syntax Path specification (e.g. on a VMS host:
-- "SYS$DEVICE:[BAR],DISK$USER:[FOO] to canonical (Unix) syntax (e.g.
-- "/sys$device/foo:disk$user/foo").
function To_Host_Dir_Spec
(Canonical_Dir : String;
Prefix_Style : Boolean) return String_Access;
-- Convert a canonical syntax directory specification to host syntax.
-- The Prefix_Style flag is currently ignored but should be set to
-- False.
function To_Host_File_Spec
(Canonical_File : String) return String_Access;
-- Convert a canonical syntax file specification to host syntax
function Relocate_Path
(Prefix : String;
Path : String) return String_Ptr;
-- Given an absolute path and a prefix, if Path starts with Prefix,
-- replace the Prefix substring with the root installation directory.
-- By default, try to compute the root installation directory by looking
-- at the executable name as it was typed on the command line and, if
-- needed, use the PATH environment variable. If the above computation
-- fails, return Path. This function assumes Prefix'First = Path'First.
function Shared_Lib (Name : String) return String;
-- Returns the runtime shared library in the form -l<name>-<version> where
-- version is the GNAT runtime library option for the platform. For example
-- this routine called with Name set to "gnat" will return "-lgnat-5.02"
-- on UNIX and Windows and -lgnat_5_02 on VMS.
-------------------------
-- Search Dir Routines --
-------------------------
function Include_Dir_Default_Prefix return String;
-- Return the directory of the run-time library sources, as modified
-- by update_path.
function Object_Dir_Default_Prefix return String;
-- Return the directory of the run-time library ALI and object files, as
-- modified by update_path.
procedure Add_Default_Search_Dirs;
-- This routine adds the default search dirs indicated by the
-- environment variables and sdefault package.
procedure Add_Lib_Search_Dir (Dir : String);
-- Add Dir at the end of the library file search path
procedure Add_Src_Search_Dir (Dir : String);
-- Add Dir at the end of the source file search path
procedure Get_Next_Dir_In_Path_Init
(Search_Path : String_Access);
function Get_Next_Dir_In_Path
(Search_Path : String_Access) return String_Access;
-- These subprograms are used to parse out the directory names in a
-- search path specified by a Search_Path argument. The procedure
-- initializes an internal pointer to point to the initial directory
-- name, and calls to the function return successive directory names,
-- with a null pointer marking the end of the list.
type Search_File_Type is (Include, Objects);
procedure Add_Search_Dirs
(Search_Path : String_Ptr;
Path_Type : Search_File_Type);
-- These procedure adds all the search directories that are in Search_Path
-- in the proper file search path (library or source)
function Get_Primary_Src_Search_Directory return String_Ptr;
-- Retrieved the primary directory (directory containing the main source
-- file for Gnatmake.
function Nb_Dir_In_Src_Search_Path return Natural;
function Dir_In_Src_Search_Path (Position : Natural) return String_Ptr;
-- Functions to access the directory names in the source search path
function Nb_Dir_In_Obj_Search_Path return Natural;
function Dir_In_Obj_Search_Path (Position : Natural) return String_Ptr;
-- Functions to access the directory names in the Object search path
Include_Search_File : constant String_Access :=
new String'("ada_source_path");
Objects_Search_File : constant String_Access :=
new String'("ada_object_path");
-- Names of the files containg the default include or objects search
-- directories. These files, located in Sdefault.Search_Dir_Prefix, do
-- not necessarily exist.
Exec_Name : String_Ptr;
-- Executable name as typed by the user (used to compute the
-- executable prefix).
function Read_Default_Search_Dirs
(Search_Dir_Prefix : String_Access;
Search_File : String_Access;
Search_Dir_Default_Name : String_Access) return String_Access;
-- Read and return the default search directories from the file located
-- in Search_Dir_Prefix (as modified by update_path) and named Search_File.
-- If no such file exists or an error occurs then instead return the
-- Search_Dir_Default_Name (as modified by update_path).
function Get_RTS_Search_Dir
(Search_Dir : String;
File_Type : Search_File_Type) return String_Ptr;
-- This function retrieves the paths to the search (resp. lib) dirs and
-- return them. The search dir can be absolute or relative. If the search
-- dir contains Include_Search_File (resp. Object_Search_File), then this
-- function reads and returns the default search directories from the file.
-- Otherwise, if the directory is absolute, it will try to find 'adalib'
-- (resp. 'adainclude'). If found, null is returned. If the directory is
-- relative, the following directories for the directories 'adalib' and
-- 'adainclude' will be scanned:
--
-- - current directory (from which the tool has been spawned)
-- - $GNAT_ROOT/gcc/gcc-lib/$targ/$vers/
-- - $GNAT_ROOT/gcc/gcc-lib/$targ/$vers/rts-
--
-- The scan will stop as soon as the directory being searched for (adalib
-- or adainclude) is found. If the scan fails, null is returned.
-----------------------
-- Source File Input --
-----------------------
-- Source file input routines are used by the compiler to read the main
-- source files and the subsidiary source files (e.g. with'ed units), and
-- also by the binder to check presence/time stamps of sources.
procedure Read_Source_File
(N : File_Name_Type;
Lo : Source_Ptr;
Hi : out Source_Ptr;
Src : out Source_Buffer_Ptr;
T : File_Type := Source);
-- Allocates a Source_Buffer of appropriate length and then reads the
-- entire contents of the source file N into the buffer. The address of
-- the allocated buffer is returned in Src.
--
-- Each line of text is terminated by one of the sequences:
--
-- CR
-- CR/LF
-- LF/CR
-- LF
-- The source is terminated by an EOF (16#1A#) character, which is
-- the last charcater of the returned source bufer (note that any
-- EOF characters in positions other than the last source character
-- are treated as representing blanks).
--
-- The logical lower bound of the source buffer is the input value of Lo,
-- and on exit Hi is set to the logical upper bound of the source buffer.
-- Note that the returned value in Src points to an array with a physical
-- lower bound of zero. This virtual origin addressing approach means that
-- a constrained array pointer can be used with a low bound of zero which
-- results in more efficient code.
--
-- If the given file cannot be opened, then the action depends on whether
-- this file is the current main unit (i.e. its name matches the name
-- returned by the most recent call to Next_Main_Source). If so, then the
-- failure to find the file is a fatal error, an error message is output,
-- and program execution is terminated. Otherwise (for the case of a
-- subsidiary source loaded directly or indirectly using with), a file
-- not found condition causes null to be set as the result value.
--
-- Note that the name passed to this function is the simple file name,
-- without any directory information. The implementation is responsible
-- for searching for the file in the appropriate directories.
--
-- Note the special case that if the file name is gnat.adc, then the
-- search for the file is done ONLY in the directory corresponding to
-- the current compilation environment, i.e. in the same directory
-- where the ali and object files will be written.
function Full_Source_Name return File_Name_Type;
function Current_Source_File_Stamp return Time_Stamp_Type;
-- Returns the full name/time stamp of the source file most recently read
-- using Read_Source_File. Calling this routine entails no source file
-- directory lookup penalty.
function Full_Source_Name (N : File_Name_Type) return File_Name_Type;
function Source_File_Stamp (N : File_Name_Type) return Time_Stamp_Type;
-- Returns the full name/time stamp of the source file whose simple name
-- is N which should not include path information. Note that if the file
-- cannot be located No_File is returned for the first routine and an
-- all blank time stamp is returned for the second (this is not an error
-- situation). The full name includes the appropriate directory
-- information. The source file directory lookup penalty is incurred
-- every single time the routines are called unless you have previously
-- called Source_File_Data (Cache => True). See below.
function Current_File_Index return Int;
-- Return the index in its source file of the current main unit
function Matching_Full_Source_Name
(N : File_Name_Type;
T : Time_Stamp_Type) return File_Name_Type;
-- Same semantics than Full_Source_Name but will search on the source
-- path until a source file with time stamp matching T is found. If
-- none is found returns No_File.
procedure Source_File_Data (Cache : Boolean);
-- By default source file data (full source file name and time stamp)
-- are looked up every time a call to Full_Source_Name (N) or
-- Source_File_Stamp (N) is made. This may be undesirable in certain
-- applications as this is uselessly slow if source file data does not
-- change during program execution. When this procedure is called with
-- Cache => True access to source file data does not encurr a penalty if
-- this data was previously retrieved.
-------------------------------------------
-- Representation of Library Information --
-------------------------------------------
-- Associated with each compiled source file is library information,
-- a string of bytes whose exact format is described in the body of
-- Lib.Writ. Compiling a source file generates this library information
-- for the compiled unit, and access the library information for units
-- that were compiled previously on which the unit being compiled depends.
-- How this information is stored is up to the implementation of this
-- package. At the interface level, this information is simply associated
-- with its corresponding source.
-- Several different implementations are possible:
-- 1. The information could be directly associated with the source file,
-- e.g. placed in a resource fork of this file on the Mac, or on
-- MS-DOS, written to the source file after the end of file mark.
-- 2. The information could be written into the generated object module
-- if the system supports the inclusion of arbitrary informational
-- byte streams into object files. In this case there must be a naming
-- convention that allows object files to be located given the name of
-- the corresponding source file.
-- 3. The information could be written to a separate file, whose name is
-- related to the name of the source file by a fixed convention.
-- Which of these three methods is chosen depends on the constraints of the
-- host operating system. The interface described here is independent of
-- which of these approaches is used.
-------------------------------
-- Library Information Input --
-------------------------------
-- These subprograms are used by the binder to read library information
-- files, see section above for representation of these files.
function Read_Library_Info
(Lib_File : File_Name_Type;
Fatal_Err : Boolean := False) return Text_Buffer_Ptr;
-- Allocates a Text_Buffer of appropriate length and reads in the entire
-- source of the library information from the library information file
-- whose name is given by the parameter Name.
--
-- See description of Read_Source_File for details on the format of the
-- returned text buffer (the format is identical). THe lower bound of
-- the Text_Buffer is always zero
--
-- If the specified file cannot be opened, then the action depends on
-- Fatal_Err. If Fatal_Err is True, an error message is given and the
-- compilation is abandoned. Otherwise if Fatal_Err is False, then null
-- is returned. Note that the Lib_File is a simple name which does not
-- include any directory information. The implementation is responsible
-- for searching for the file in appropriate directories.
--
-- If Opt.Check_Object_Consistency is set to True then this routine
-- checks whether the object file corresponding to the Lib_File is
-- consistent with it. The object file is inconsistent if the object
-- does not exist or if it has an older time stamp than Lib_File.
-- This check is not performed when the Lib_File is "locked" (i.e.
-- read/only) because in this case the object file may be buried
-- in a library. In case of inconsistencies Read_Library_Info
-- behaves as if it did not find Lib_File (namely if Fatal_Err is
-- False, null is returned).
function Full_Library_Info_Name return File_Name_Type;
function Full_Object_File_Name return File_Name_Type;
-- Returns the full name of the library/object file most recently read
-- using Read_Library_Info, including appropriate directory information.
-- Calling this routine entails no library file directory lookup
-- penalty. Note that the object file corresponding to a library file
-- is not actually read. Its time stamp is fected when the flag
-- Opt.Check_Object_Consistency is set.
function Current_Library_File_Stamp return Time_Stamp_Type;
function Current_Object_File_Stamp return Time_Stamp_Type;
-- The time stamps of the files returned by the previous two routines.
-- It is an error to call Current_Object_File_Stamp if
-- Opt.Check_Object_Consistency is set to False.
function Full_Lib_File_Name (N : File_Name_Type) return File_Name_Type;
function Library_File_Stamp (N : File_Name_Type) return Time_Stamp_Type;
-- Returns the full name/time stamp of library file N. N should not
-- include path information. Note that if the file cannot be located
-- No_File is returned for the first routine and an all blank time stamp
-- is returned for the second (this is not an error situation). The
-- full name includes the appropriate directory information. The library
-- file directory lookup penalty is incurred every single time this
-- routine is called.
function Lib_File_Name
(Source_File : File_Name_Type;
Munit_Index : Nat := 0) return File_Name_Type;
-- Given the name of a source file, returns the name of the corresponding
-- library information file. This may be the name of the object file, or
-- of a separate file used to store the library information. In either case
-- the returned result is suitable for use in a call to Read_Library_Info.
-- The Munit_Index is the unit index in multiple unit per file mode, or
-- zero in normal single unit per file mode (used to add ~nnn suffix).
-- Note: this subprogram is in this section because it is used by the
-- compiler to determine the proper library information names to be placed
-- in the generated library information file.
-----------------
-- Termination --
-----------------
type Exit_Code_Type is (
E_Success, -- No warnings or errors
E_Warnings, -- Compiler warnings generated
E_No_Code, -- No code generated
E_No_Compile, -- Compilation not needed (smart recompilation)
E_Errors, -- Compiler error messages generated
E_Fatal, -- Fatal (serious) error, e.g. source file not found
E_Abort); -- Internally detected compiler error
procedure Exit_Program (Exit_Code : Exit_Code_Type);
pragma No_Return (Exit_Program);
-- A call to Exit_Program terminates execution with the given status.
-- A status of zero indicates normal completion, a non-zero status
-- indicates abnormal termination.
-------------------------
-- Command Line Access --
-------------------------
-- Direct interface to command line parameters. (We don't want to use
-- the predefined command line package because it defines functions
-- returning string)
function Arg_Count return Natural;
pragma Import (C, Arg_Count, "__gnat_arg_count");
-- Get number of arguments (note: optional globbing may be enabled)
procedure Fill_Arg (A : System.Address; Arg_Num : Integer);
pragma Import (C, Fill_Arg, "__gnat_fill_arg");
-- Store one argument
function Len_Arg (Arg_Num : Integer) return Integer;
pragma Import (C, Len_Arg, "__gnat_len_arg");
-- Get length of argument
private
ALI_Suffix : constant String_Ptr := new String'("ali");
-- The suffix used for the library files (also known as ALI files)
Current_Main : File_Name_Type := No_File;
-- Used to save a simple file name between calls to Next_Main_Source and
-- Read_Source_File. If the file name argument to Read_Source_File is
-- No_File, that indicates that the file whose name was returned by the
-- last call to Next_Main_Source (and stored here) is to be read.
Target_Object_Suffix : constant String := Get_Target_Object_Suffix.all;
-- The suffix used for the target object files
Output_FD : File_Descriptor;
-- The file descriptor for the current library info, tree or binder output
Output_File_Name : File_Name_Type;
-- File_Name_Type for name of open file whose FD is in Output_FD, the name
-- stored does not include the trailing NUL character.
Argument_Count : constant Integer := Arg_Count - 1;
-- Number of arguments (excluding program name)
type File_Name_Array is array (Int range <>) of String_Ptr;
type File_Name_Array_Ptr is access File_Name_Array;
File_Names : File_Name_Array_Ptr :=
new File_Name_Array (1 .. Int (Argument_Count) + 2);
-- As arguments are scanned, file names are stored in this array
-- The strings do not have terminating NUL files. The array is
-- extensible, because when using project files, there may be
-- more files than arguments on the command line.
type File_Index_Array is array (Int range <>) of Int;
type File_Index_Array_Ptr is access File_Index_Array;
File_Indexes : File_Index_Array_Ptr :=
new File_Index_Array (1 .. Int (Argument_Count) + 2);
Current_File_Name_Index : Int := 0;
-- The index in File_Names of the last file opened by Next_Main_Source
-- or Next_Main_Lib_File. The value 0 indicates that no files have been
-- opened yet.
procedure Create_File_And_Check
(Fdesc : out File_Descriptor;
Fmode : Mode);
-- Create file whose name (NUL terminated) is in Name_Buffer (with the
-- length in Name_Len), and place the resulting descriptor in Fdesc.
-- Issue message and exit with fatal error if file cannot be created.
-- The Fmode parameter is set to either Text or Binary (see description
-- of GNAT.OS_Lib.Create_File).
type Program_Type is (Compiler, Binder, Make, Gnatls, Unspecified);
-- Program currently running
procedure Set_Program (P : Program_Type);
-- Indicates to the body of Osint the program currently running.
-- This procedure is called by the child packages of Osint.
-- A check is made that this procedure is not called several times.
function More_Files return Boolean;
-- Implements More_Source_Files and More_Lib_Files
function Next_Main_File return File_Name_Type;
-- Implements Next_Main_Source and Next_Main_Lib_File
function Object_File_Name (N : File_Name_Type) return File_Name_Type;
-- Constructs the name of the object file corresponding to library
-- file N. If N is a full file name than the returned file name will
-- also be a full file name. Note that no lookup in the library file
-- directories is done for this file. This routine merely constructs
-- the name.
procedure Write_Info (Info : String);
-- Implementation of Write_Binder_Info, Write_Debug_Info and
-- Write_Library_Info (identical)
end Osint;
|
-----------------------------------------------------------------------
-- Gen.Database.Model -- Gen.Database.Model
-----------------------------------------------------------------------
-- File generated by ada-gen DO NOT MODIFY
-- Template used: templates/model/package-body.xhtml
-- Ada Generator: https://ada-gen.googlecode.com/svn/trunk Revision 305
-----------------------------------------------------------------------
-- Copyright (C) 2011 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Util.Beans.Objects.Time;
package body Gen.Database.Model is
use type ADO.Objects.Object_Record_Access;
use type ADO.Objects.Object_Ref;
use type ADO.Objects.Object_Record;
function Schema_Key (Id : in ADO.Identifier) return ADO.Objects.Object_Key is
Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_STRING,
Of_Class => SCHEMA_TABLE'Access);
begin
ADO.Objects.Set_Value (Result, Id);
return Result;
end Schema_Key;
function Schema_Key (Id : in String) return ADO.Objects.Object_Key is
Result : ADO.Objects.Object_Key (Of_Type => ADO.Objects.KEY_STRING,
Of_Class => SCHEMA_TABLE'Access);
begin
ADO.Objects.Set_Value (Result, Id);
return Result;
end Schema_Key;
function "=" (Left, Right : Schema_Ref'Class) return Boolean is
begin
return ADO.Objects.Object_Ref'Class (Left) = ADO.Objects.Object_Ref'Class (Right);
end "=";
procedure Set_Field (Object : in out Schema_Ref'Class;
Impl : out Schema_Access) is
Result : ADO.Objects.Object_Record_Access;
begin
Object.Prepare_Modify (Result);
Impl := Schema_Impl (Result.all)'Access;
end Set_Field;
-- Internal method to allocate the Object_Record instance
procedure Allocate (Object : in out Schema_Ref) is
Impl : Schema_Access;
begin
Impl := new Schema_Impl;
Impl.Version := 0;
Impl.Date.Is_Null := True;
ADO.Objects.Set_Object (Object, Impl.all'Access);
end Allocate;
-- ----------------------------------------
-- Data object: Schema
-- ----------------------------------------
procedure Set_Name (Object : in out Schema_Ref;
Value : in String) is
Impl : Schema_Access;
begin
Set_Field (Object, Impl);
ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value);
end Set_Name;
procedure Set_Name (Object : in out Schema_Ref;
Value : in Ada.Strings.Unbounded.Unbounded_String) is
Impl : Schema_Access;
begin
Set_Field (Object, Impl);
ADO.Objects.Set_Field_Key_Value (Impl.all, 1, Value);
end Set_Name;
function Get_Name (Object : in Schema_Ref)
return String is
begin
return Ada.Strings.Unbounded.To_String (Object.Get_Name);
end Get_Name;
function Get_Name (Object : in Schema_Ref)
return Ada.Strings.Unbounded.Unbounded_String is
Impl : constant Schema_Access := Schema_Impl (Object.Get_Object.all)'Access;
begin
return Impl.Get_Key_Value;
end Get_Name;
procedure Set_Version (Object : in out Schema_Ref;
Value : in Integer) is
Impl : Schema_Access;
begin
Set_Field (Object, Impl);
ADO.Objects.Set_Field_Integer (Impl.all, 2, Impl.Version, Value);
ADO.Objects.Set_Field_Integer (Impl.all, 2, Impl.Version, Value);
end Set_Version;
function Get_Version (Object : in Schema_Ref)
return Integer is
Impl : constant Schema_Access := Schema_Impl (Object.Get_Load_Object.all)'Access;
begin
return Impl.Version;
end Get_Version;
procedure Set_Date (Object : in out Schema_Ref;
Value : in ADO.Nullable_Time) is
Impl : Schema_Access;
begin
Set_Field (Object, Impl);
ADO.Objects.Set_Field_Time (Impl.all, 3, Impl.Date, Value);
end Set_Date;
function Get_Date (Object : in Schema_Ref)
return ADO.Nullable_Time is
Impl : constant Schema_Access := Schema_Impl (Object.Get_Load_Object.all)'Access;
begin
return Impl.Date;
end Get_Date;
-- Copy of the object.
procedure Copy (Object : in Schema_Ref;
Into : in out Schema_Ref) is
Result : Schema_Ref;
begin
if not Object.Is_Null then
declare
Impl : constant Schema_Access
:= Schema_Impl (Object.Get_Load_Object.all)'Access;
Copy : constant Schema_Access
:= new Schema_Impl;
begin
ADO.Objects.Set_Object (Result, Copy.all'Access);
Copy.Copy (Impl.all);
Copy.all.Set_Key (Impl.all.Get_Key);
Copy.Version := Impl.Version;
Copy.Date := Impl.Date;
end;
end if;
Into := Result;
end Copy;
procedure Find (Object : in out Schema_Ref;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
Impl : constant Schema_Access := new Schema_Impl;
begin
Impl.Find (Session, Query, Found);
if Found then
ADO.Objects.Set_Object (Object, Impl.all'Access);
else
ADO.Objects.Set_Object (Object, null);
Destroy (Impl);
end if;
end Find;
procedure Load (Object : in out Schema_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in Ada.Strings.Unbounded.Unbounded_String) is
Impl : constant Schema_Access := new Schema_Impl;
Found : Boolean;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (Position => 1, Value => Id);
Query.Set_Filter ("name = ?");
Impl.Find (Session, Query, Found);
if not Found then
Destroy (Impl);
raise ADO.Objects.NOT_FOUND;
end if;
ADO.Objects.Set_Object (Object, Impl.all'Access);
end Load;
procedure Load (Object : in out Schema_Ref;
Session : in out ADO.Sessions.Session'Class;
Id : in Ada.Strings.Unbounded.Unbounded_String;
Found : out Boolean) is
Impl : constant Schema_Access := new Schema_Impl;
Query : ADO.SQL.Query;
begin
Query.Bind_Param (Position => 1, Value => Id);
Query.Set_Filter ("name = ?");
Impl.Find (Session, Query, Found);
if not Found then
Destroy (Impl);
else
ADO.Objects.Set_Object (Object, Impl.all'Access);
end if;
end Load;
procedure Save (Object : in out Schema_Ref;
Session : in out ADO.Sessions.Master_Session'Class) is
Impl : ADO.Objects.Object_Record_Access := Object.Get_Object;
begin
if Impl = null then
Impl := new Schema_Impl;
ADO.Objects.Set_Object (Object, Impl);
end if;
if not ADO.Objects.Is_Created (Impl.all) then
Impl.Create (Session);
else
Impl.Save (Session);
end if;
end Save;
procedure Delete (Object : in out Schema_Ref;
Session : in out ADO.Sessions.Master_Session'Class) is
Impl : constant ADO.Objects.Object_Record_Access := Object.Get_Object;
begin
if Impl /= null then
Impl.Delete (Session);
end if;
end Delete;
-- --------------------
-- Free the object
-- --------------------
procedure Destroy (Object : access Schema_Impl) is
type Schema_Impl_Ptr is access all Schema_Impl;
procedure Unchecked_Free is new Ada.Unchecked_Deallocation
(Schema_Impl, Schema_Impl_Ptr);
pragma Warnings (Off, "*redundant conversion*");
Ptr : Schema_Impl_Ptr := Schema_Impl (Object.all)'Access;
pragma Warnings (On, "*redundant conversion*");
begin
Unchecked_Free (Ptr);
end Destroy;
procedure Find (Object : in out Schema_Impl;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class;
Found : out Boolean) is
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (SCHEMA_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
if Stmt.Has_Elements then
Object.Load (Stmt, Session);
Stmt.Next;
Found := not Stmt.Has_Elements;
else
Found := False;
end if;
end Find;
overriding
procedure Load (Object : in out Schema_Impl;
Session : in out ADO.Sessions.Session'Class) is
Found : Boolean;
Query : ADO.SQL.Query;
Id : constant Ada.Strings.Unbounded.Unbounded_String := Object.Get_Key_Value;
begin
Query.Bind_Param (Position => 1, Value => Id);
Query.Set_Filter ("name = ?");
Object.Find (Session, Query, Found);
if not Found then
raise ADO.Objects.NOT_FOUND;
end if;
end Load;
procedure Save (Object : in out Schema_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
Stmt : ADO.Statements.Update_Statement
:= Session.Create_Statement (SCHEMA_TABLE'Access);
begin
if Object.Is_Modified (1) then
Stmt.Save_Field (Name => COL_0_1_NAME, -- NAME
Value => Object.Get_Key);
Object.Clear_Modified (1);
end if;
if Object.Is_Modified (2) then
Stmt.Save_Field (Name => COL_1_1_NAME, -- VERSION
Value => Object.Version);
Object.Clear_Modified (2);
end if;
if Object.Is_Modified (3) then
Stmt.Save_Field (Name => COL_2_1_NAME, -- DATE
Value => Object.Date);
Object.Clear_Modified (3);
end if;
if Stmt.Has_Save_Fields then
Stmt.Set_Filter (Filter => "name = ?");
Stmt.Add_Param (Value => Object.Get_Key);
declare
Result : Integer;
begin
Stmt.Execute (Result);
if Result /= 1 then
if Result /= 0 then
raise ADO.Objects.UPDATE_ERROR;
end if;
end if;
end;
end if;
end Save;
procedure Create (Object : in out Schema_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
Query : ADO.Statements.Insert_Statement
:= Session.Create_Statement (SCHEMA_TABLE'Access);
Result : Integer;
begin
Query.Save_Field (Name => COL_0_1_NAME, -- NAME
Value => Object.Get_Key);
Query.Save_Field (Name => COL_1_1_NAME, -- VERSION
Value => Object.Version);
Query.Save_Field (Name => COL_2_1_NAME, -- DATE
Value => Object.Date);
Query.Execute (Result);
if Result /= 1 then
raise ADO.Objects.INSERT_ERROR;
end if;
ADO.Objects.Set_Created (Object);
end Create;
procedure Delete (Object : in out Schema_Impl;
Session : in out ADO.Sessions.Master_Session'Class) is
Stmt : ADO.Statements.Delete_Statement
:= Session.Create_Statement (SCHEMA_TABLE'Access);
begin
Stmt.Set_Filter (Filter => "name = ?");
Stmt.Add_Param (Value => Object.Get_Key);
Stmt.Execute;
end Delete;
function Get_Value (Item : in Schema_Ref;
Name : in String) return Util.Beans.Objects.Object is
Obj : constant ADO.Objects.Object_Record_Access := Item.Get_Load_Object;
Impl : access Schema_Impl;
begin
if Obj = null then
return Util.Beans.Objects.Null_Object;
end if;
Impl := Schema_Impl (Obj.all)'Access;
if Name = "name" then
return ADO.Objects.To_Object (Impl.Get_Key);
end if;
if Name = "version" then
return Util.Beans.Objects.To_Object (Long_Long_Integer (Impl.Version));
end if;
if Name = "date" then
if Impl.Date.Is_Null then
return Util.Beans.Objects.Null_Object;
else
return Util.Beans.Objects.Time.To_Object (Impl.Date.Value);
end if;
end if;
return Util.Beans.Objects.Null_Object;
end Get_Value;
procedure List (Object : in out Schema_Vector;
Session : in out ADO.Sessions.Session'Class;
Query : in ADO.SQL.Query'Class) is
Stmt : ADO.Statements.Query_Statement := Session.Create_Statement (SCHEMA_TABLE'Access);
begin
Stmt.Set_Parameters (Query);
Stmt.Execute;
Schema_Vectors.Clear (Object);
while Stmt.Has_Elements loop
declare
Item : Schema_Ref;
Impl : constant Schema_Access := new Schema_Impl;
begin
Impl.Load (Stmt, Session);
ADO.Objects.Set_Object (Item, Impl.all'Access);
Object.Append (Item);
end;
Stmt.Next;
end loop;
end List;
-- ------------------------------
-- Load the object from current iterator position
-- ------------------------------
procedure Load (Object : in out Schema_Impl;
Stmt : in out ADO.Statements.Query_Statement'Class;
Session : in out ADO.Sessions.Session'Class) is
pragma Unreferenced (Session);
begin
Object.Set_Key_Value (Stmt.Get_Unbounded_String (0));
Object.Version := Stmt.Get_Integer (1);
Object.Date := Stmt.Get_Time (2);
ADO.Objects.Set_Created (Object);
end Load;
-- --------------------
-- information about the database
-- --------------------
procedure List (Object : in out Database_Info_Vector;
Session : in out ADO.Sessions.Session'Class;
Context : in out ADO.Queries.Context'Class) is
procedure Read (Into : in out Database_Info);
Stmt : ADO.Statements.Query_Statement
:= Session.Create_Statement (Context);
Pos : Natural := 0;
procedure Read (Into : in out Database_Info) is
begin
Into.Name := Stmt.Get_Unbounded_String (0);
end Read;
begin
Stmt.Execute;
Database_Info_Vectors.Clear (Object);
while Stmt.Has_Elements loop
Object.Insert_Space (Before => Pos);
Object.Update_Element (Index => Pos, Process => Read'Access);
Pos := Pos + 1;
Stmt.Next;
end loop;
end List;
end Gen.Database.Model;
|
-- 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 AUnit.Test_Fixtures;
package Missions.Test_Data is
-- begin read only
type Test is new AUnit.Test_Fixtures.Test_Fixture
-- end read only
with null record;
procedure Set_Up(Gnattest_T: in out Test);
procedure Tear_Down(Gnattest_T: in out Test);
end Missions.Test_Data;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2015, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
pragma Restrictions (No_Elaboration_Code);
-- GNAT: enforce generation of preinitialized data section instead of
-- generation of elaboration code.
package Matreshka.Internals.Unicode.Ucd.Core_00F9 is
pragma Preelaborate;
Group_00F9 : aliased constant Core_Second_Stage
:= (others =>
(Other_Letter, Wide,
Other, Other, O_Letter, Ideographic,
(Ideographic
| Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_00F9;
|
-- Abstract :
--
-- call the GPS indentation engine with debug text
--
-- Copyright (C) 2017 All Rights Reserved.
--
-- 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.Text_IO; use Ada.Text_IO;
with Ada_Analyzer;
with Case_Handling;
with GNATCOLL.Symbols;
with Language;
procedure Debug_GPS_Indent is
NL : constant Character := ASCII.LF;
Buffer : constant String :=
"procedure Bug_002 is begin" & NL &
"Error_Report.Report_Error (Severity =>" & NL &
"Error_Report.Severe," & NL &
"Description => ""In theory the counterp_process..., "" &" & NL &
"""as they should not differ but they do... """ & NL &
"& ""the indexes, so that we do not crash....""," & NL &
"Title => ""Curtain indexes should not differ but they do.""," & NL &
"Caller_Scope => ""Curtain_Indexes_May_Differ"");" & NL &
"end Bug_002;";
procedure Replace_Cb
(Line : in Natural;
First : in Natural;
Last : in Natural;
Replace : in String)
is
pragma Unreferenced (Last);
begin
-- Provide a place to put a debugger break when an indentation is computed.
-- analyze calls replace_cb for ":", ":=" etc. We only
-- want the leading spaces, for indentation.
if Replace'Length > 0 and First = 1 then
Put_Line (Natural'Image (Line) & Natural'Image (Replace'Length));
end if;
end Replace_Cb;
begin
Ada_Analyzer.Analyze_Ada_Source
(Buffer, GNATCOLL.Symbols.Allocate,
Indent_Params =>
(Indent_Level => 3,
Indent_Continue => 2,
Indent_Decl => 2, -- no ada-mode equivalent
Indent_Conditional => 1, -- no ada-mode equivalent
Indent_Record => 3,
Indent_Case_Extra => Language.Non_RM_Style,
Casing_Policy => Case_Handling.Disabled,
Reserved_Casing => Case_Handling.Unchanged,
Ident_Casing => Case_Handling.Unchanged,
Format_Operators => False,
Use_Tabs => False,
Align_On_Colons => False,
Align_On_Arrows => False,
Align_Decl_On_Colon => False,
Indent_Comments => True,
Stick_Comments => False), -- no ada-mode equivalent.
From => 1,
To => 7,
Replace => Replace_Cb'Unrestricted_Access);
end Debug_GPS_Indent;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2015-2017, 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 STMicroelectronics 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 file is based on: --
-- --
-- @file stm32f407xx.h et al. --
-- @author MCD Application Team --
-- @version V1.1.0 --
-- @date 19-June-2014 --
-- @brief CMSIS STM32F407xx Device Peripheral Access Layer Header File. --
-- --
-- COPYRIGHT(c) 2014 STMicroelectronics --
------------------------------------------------------------------------------
-- This file provides register definitions for the STM32F4 (ARM Cortex M4F)
-- microcontrollers from ST Microelectronics.
with STM32_SVD.EXTI; use STM32_SVD.EXTI;
with STM32_SVD.SYSCFG; use STM32_SVD.SYSCFG;
with STM32.EXTI;
with STM32.Device; use STM32.Device;
package body STM32.SYSCFG is
subtype GPIO_Pin_Index is Natural range 0 .. 15;
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pin : GPIO_Pin_Index);
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pin : GPIO_Pin_Index)
is
Port_Id : constant UInt4 := GPIO_Port_Representation (Port);
begin
-- overridden.
case Pin is
when 0 .. 3 =>
SYSCFG_Periph.EXTICR1.EXTI.Arr (Pin) := Port_Id;
when 4 .. 7 =>
SYSCFG_Periph.EXTICR2.EXTI.Arr (Pin) := Port_Id;
when 8 .. 11 =>
SYSCFG_Periph.EXTICR3.EXTI.Arr (Pin) := Port_Id;
when 12 .. 15 =>
SYSCFG_Periph.EXTICR4.EXTI.Arr (Pin) := Port_Id;
end case;
end Connect_External_Interrupt;
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pin : GPIO_Pin)
is
begin
Connect_External_Interrupt (Port, GPIO_Pin'Pos (Pin));
end Connect_External_Interrupt;
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Point : GPIO_Point)
is
begin
Connect_External_Interrupt (Point.Periph.all, Point.Pin);
end Connect_External_Interrupt;
--------------------------------
-- Connect_External_Interrupt --
--------------------------------
procedure Connect_External_Interrupt
(Port : GPIO_Port;
Pins : GPIO_Pins)
is
begin
for Pin of Pins loop
Connect_External_Interrupt (Port, Pin);
end loop;
end Connect_External_Interrupt;
------------------------------
-- Clear_External_Interrupt --
------------------------------
procedure Clear_External_Interrupt (Pin : GPIO_Pin) is
use STM32.EXTI;
begin
Clear_External_Interrupt (External_Line_Number'Val (GPIO_Pin'Pos (Pin)));
end Clear_External_Interrupt;
end STM32.SYSCFG;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M L I B . T G T . S P E C I F I C --
-- (Solaris Version) --
-- --
-- B o d y --
-- --
-- Copyright (C) 2002-2008, 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 is the Solaris version of the body
with MLib.Fil;
with MLib.Utl;
with Opt;
with Output; use Output;
package body MLib.Tgt.Specific is
-- Non default subprograms
procedure Build_Dynamic_Library
(Ofiles : Argument_List;
Options : Argument_List;
Interfaces : Argument_List;
Lib_Filename : String;
Lib_Dir : String;
Symbol_Data : Symbol_Record;
Driver_Name : Name_Id := No_Name;
Lib_Version : String := "";
Auto_Init : Boolean := False);
function Is_Archive_Ext (Ext : String) return Boolean;
---------------------------
-- Build_Dynamic_Library --
---------------------------
procedure Build_Dynamic_Library
(Ofiles : Argument_List;
Options : Argument_List;
Interfaces : Argument_List;
Lib_Filename : String;
Lib_Dir : String;
Symbol_Data : Symbol_Record;
Driver_Name : Name_Id := No_Name;
Lib_Version : String := "";
Auto_Init : Boolean := False)
is
pragma Unreferenced (Interfaces);
pragma Unreferenced (Symbol_Data);
pragma Unreferenced (Auto_Init);
Lib_File : constant String :=
"lib" & Fil.Append_To (Lib_Filename, DLL_Ext);
Lib_Path : constant String :=
Lib_Dir & Directory_Separator & Lib_File;
Version_Arg : String_Access;
Symbolic_Link_Needed : Boolean := False;
begin
if Opt.Verbose_Mode then
Write_Str ("building relocatable shared library ");
Write_Line (Lib_Path);
end if;
if Lib_Version = "" then
Utl.Gcc
(Output_File => Lib_Path,
Objects => Ofiles,
Options => Options,
Options_2 => No_Argument_List,
Driver_Name => Driver_Name);
else
declare
Maj_Version : constant String :=
Major_Id_Name (Lib_File, Lib_Version);
begin
if Maj_Version'Length /= 0 then
Version_Arg := new String'("-Wl,-h," & Maj_Version);
else
Version_Arg := new String'("-Wl,-h," & Lib_Version);
end if;
if Is_Absolute_Path (Lib_Version) then
Utl.Gcc
(Output_File => Lib_Version,
Objects => Ofiles,
Options => Options & Version_Arg,
Options_2 => No_Argument_List,
Driver_Name => Driver_Name);
Symbolic_Link_Needed := Lib_Version /= Lib_Path;
else
Utl.Gcc
(Output_File => Lib_Dir & Directory_Separator & Lib_Version,
Objects => Ofiles,
Options => Options & Version_Arg,
Options_2 => No_Argument_List,
Driver_Name => Driver_Name);
Symbolic_Link_Needed :=
Lib_Dir & Directory_Separator & Lib_Version /= Lib_Path;
end if;
if Symbolic_Link_Needed then
Create_Sym_Links
(Lib_Path, Lib_Version, Lib_Dir, Maj_Version);
end if;
end;
end if;
end Build_Dynamic_Library;
--------------------
-- Is_Archive_Ext --
--------------------
function Is_Archive_Ext (Ext : String) return Boolean is
begin
return Ext = ".a" or else Ext = ".so";
end Is_Archive_Ext;
begin
Build_Dynamic_Library_Ptr := Build_Dynamic_Library'Access;
Is_Archive_Ext_Ptr := Is_Archive_Ext'Access;
end MLib.Tgt.Specific;
|
with Ada.Unchecked_Conversion;
with STM32.Board; use STM32.Board;
with STM32.Device; use STM32.Device;
with STM32.GPIO; use STM32.GPIO;
with STM32.SPI; use STM32.SPI;
with HAL.SPI;
package body Framebuffer_ILI9341 is
LCD_SPI : SPI_Port renames SPI_5;
LCD_WIDTH : constant := 240;
LCD_HEIGHT : constant := 320;
procedure LCD_SPI_Init;
procedure LCD_Pins_Init;
------------------
-- LCD_SPI_Init --
------------------
procedure LCD_SPI_Init
is
Conf : GPIO_Port_Configuration;
SPI_Conf : SPI_Configuration;
SPI_Pins : constant GPIO_Points :=
(SPI5_SCK, SPI5_MOSI, SPI5_MISO);
begin
Enable_Clock (SPI_Pins);
Enable_Clock (LCD_SPI);
Conf.Speed := Speed_100MHz;
Conf.Mode := Mode_AF;
Conf.Output_Type := Push_Pull;
Conf.Resistors := Floating;
Configure_Alternate_Function (SPI_Pins, GPIO_AF_SPI5);
Configure_IO (SPI_Pins, Conf);
Reset (LCD_SPI);
if not Enabled (LCD_SPI) then
SPI_Conf :=
(Direction => D2Lines_FullDuplex,
Mode => Master,
Data_Size => HAL.SPI.Data_Size_8b,
Clock_Polarity => Low,
Clock_Phase => P1Edge,
Slave_Management => Software_Managed,
Baud_Rate_Prescaler => BRP_32,
First_Bit => MSB,
CRC_Poly => 7);
Configure (LCD_SPI, SPI_Conf);
STM32.SPI.Enable (LCD_SPI);
end if;
end LCD_SPI_Init;
-------------------
-- LCD_Pins_Init --
-------------------
procedure LCD_Pins_Init is
begin
Enable_Clock (GPIO_Points'(LCD_RESET, LCD_CSX, LCD_WRX_DCX));
Enable_Clock (LCD_PINS);
Configure_IO
(Points => (LCD_RESET, LCD_CSX, LCD_WRX_DCX),
Config => (Speed => Speed_50MHz,
Mode => Mode_Out,
Output_Type => Push_Pull,
Resistors => Floating));
Configure_Alternate_Function (LCD_PINS, GPIO_AF_LTDC);
Configure_Alternate_Function (LCD_RGB_AF9, GPIO_AF_LTDC_2);
Configure_IO
(Points => LCD_PINS,
Config => (Speed => Speed_50MHz,
Mode => Mode_AF,
Output_Type => Push_Pull,
Resistors => Floating));
-- Set LCD_CSX: Chip Unselect
Set (LCD_CSX);
end LCD_Pins_Init;
----------------
-- Initialize --
----------------
procedure Initialize
(Display : in out Frame_Buffer;
Orientation : HAL.Framebuffer.Display_Orientation := Default;
Mode : HAL.Framebuffer.Wait_Mode := Interrupt)
is
begin
LCD_Pins_Init;
LCD_SPI_Init;
Display.Device.Initialize (ILI9341.RGB_Mode);
Display.Initialize
(Width => LCD_WIDTH,
Height => LCD_HEIGHT,
H_Sync => 10,
H_Back_Porch => 20,
H_Front_Porch => 10,
V_Sync => 2,
V_Back_Porch => 2,
V_Front_Porch => 4,
PLLSAI_N => 192,
PLLSAI_R => 4,
DivR => 8,
Orientation => Orientation,
Mode => Mode);
end Initialize;
end Framebuffer_ILI9341;
|
package Loop_Optimization15 is
type B16_T is mod 2 ** 16;
for B16_T'Size use 16;
for B16_T'Alignment use 1;
procedure Proc (L : B16_T);
end Loop_Optimization15;
|
with
AdaM.Factory,
AdaM.Declaration.of_package;
package body AdaM.context_Line
is
-- Storage Pool
--
record_Version : constant := 1;
max_context_Lines : constant := 5_000;
package Pool is new AdaM.Factory.Pools (".adam-store",
"context_lines",
max_context_Lines,
record_Version,
context_Line.item,
context_Line.view);
-- Vector
--
function to_Source (the_Lines : in Vector) return text_Vectors.Vector
is
the_Source : text_Vectors.Vector;
begin
for i in 1 .. the_Lines.Length
loop
the_Source.append (the_Lines.Element (Integer (i)).to_Source);
end loop;
return the_Source;
end to_Source;
-- Forge
--
procedure define (Self : in out Item; Name : in String)
is
begin
Self.package_Name := +Name;
Self.Used := False;
end define;
procedure destruct (Self : in out Item)
is
begin
null;
end destruct;
function new_context_Line (Name : in String := "") return View
is
new_View : constant context_Line.view := Pool.new_Item;
begin
define (context_Line.item (new_View.all), Name);
return new_View;
end new_context_Line;
procedure free (Self : in out context_Line.view)
is
begin
destruct (context_Line.item (Self.all));
Pool.free (Self);
end free;
-- Attributes
--
overriding function Id (Self : access Item) return AdaM.Id
is
begin
return Pool.to_Id (Self);
end Id;
function my_Package (Self : in Item) return Package_view
is
begin
return Self.my_Package;
end my_Package;
procedure Package_is (Self : in out Item; Now : in Package_view)
is
begin
Self.my_Package := Now;
end Package_is;
function Name (Self : access Item) return access Text
is
begin
return Self.package_Name'Access;
end Name;
function Name (Self : in Item) return String
is
begin
return +Self.package_Name;
end Name;
procedure Name_is (Self : in out Item; Now : in String)
is
begin
Self.package_Name := +Now;
end Name_is;
function is_Used (Self : in Item) return Boolean
is
begin
return Self.Used;
end is_Used;
procedure is_Used (Self : in out Item; Now : in Boolean)
is
begin
Self.Used := Now;
end is_Used;
function to_Source (Self : in Item) return text_Vectors.Vector
is
use ada.Strings.unbounded;
the_Line : Text := +"with " & String (Self.my_Package.full_Name) & ";";
the_Source : text_Vectors.Vector;
begin
if Self.Used then
append (the_Line, " use " & String (Self.my_Package.full_Name) & ";");
end if;
the_Source.append (the_Line);
return the_Source;
end to_Source;
-- Streams
--
procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Self : in View)
renames Pool.View_write;
procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Self : out View)
renames Pool.View_read;
procedure Package_view_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Self : in Package_view)
is
begin
Declaration.of_package.View_write (Stream, Declaration.of_package.view (Self));
end Package_view_write;
procedure Package_view_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
Self : out Package_view)
is
begin
Declaration.of_package.View_read (Stream, Declaration.of_package.view (Self));
end Package_view_read;
end AdaM.context_Line;
|
package body Parser is
function Evaluate (Root : in Node_Ptr) return Integer is
Result : Integer := 0;
begin
if Root /= null then
case Root.Node_Type is
when Empty =>
null;
when Literal =>
return Root.Value;
when Plus =>
return Evaluate (Root.Left) + Evaluate (Root.Right);
when Minus =>
return Evaluate (Root.Left) - Evaluate (Root.Right);
when Multiply =>
return Evaluate (Root.Left) * Evaluate (Root.Right);
when Divide =>
return Evaluate (Root.Left) / Evaluate (Root.Right);
end case;
end if;
return 0;
end Evaluate;
end Parser;
|
procedure scan_for_file_ghosts (
directory_path : in String;
file_ghosts : out Filename_Container.Vector;
directory_ghosts : out Filename_Container.Vector);
-- Given an existing directory path, the procedure will produce
-- both a list of deleted directories and a list of files deleted
-- (but with available version) from that directory
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- SYSTEM.TASKING.PROTECTED_OBJECTS.ENTRIES --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2021, 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. --
-- --
-- --
-- --
-- --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains all simple primitives related to Protected_Objects
-- with entries (i.e init, lock, unlock).
-- The handling of protected objects with no entries is done in
-- System.Tasking.Protected_Objects, the complex routines for protected
-- objects with entries in System.Tasking.Protected_Objects.Operations.
-- The split between Entries and Operations is needed to break circular
-- dependencies inside the run time.
-- Note: the compiler generates direct calls to this interface, via Rtsfind.
-- Any changes to this interface may require corresponding compiler changes.
with Ada.Unchecked_Conversion;
package System.Tasking.Protected_Objects.Entries is
pragma Elaborate_Body;
subtype Positive_Protected_Entry_Index is
Protected_Entry_Index range 1 .. Protected_Entry_Index'Last;
-- Index of the entry (and in some cases of the queue)
type Find_Body_Index_Access is access
function
(O : System.Address;
E : Protected_Entry_Index)
return Protected_Entry_Index;
-- Convert a queue index to an entry index (an entry family has one entry
-- index for several queue indexes).
type Protected_Entry_Body_Array is
array (Positive_Protected_Entry_Index range <>) of Entry_Body;
-- Contains executable code for all entry bodies of a protected type
type Protected_Entry_Body_Access is
access constant Protected_Entry_Body_Array;
type Protected_Entry_Queue_Array is
array (Protected_Entry_Index range <>) of Entry_Queue;
type Protected_Entry_Queue_Max_Array is
array (Positive_Protected_Entry_Index range <>) of Natural;
-- Contains Max_Queue_Length values
type Protected_Entry_Queue_Max_Access is
access constant Protected_Entry_Queue_Max_Array;
-- The following declarations define an array that contains the string
-- names of entries and entry family members, together with an associated
-- access type.
-- The following type contains the GNARL state of a protected object.
-- The application-defined portion of the state (i.e. private objects)
-- is maintained by the compiler-generated code. Note that there is a
-- simplified version of this type declared in System.Tasking.PO_Simple
-- that handle the simple case (no entries).
type Protection_Entries (Num_Entries : Protected_Entry_Index) is record
Common : aliased Protection;
-- State of the protected object. This part is common to any protected
-- object, including those without entries.
Compiler_Info : System.Address;
-- Pointer to compiler-generated record representing protected object
Call_In_Progress : Entry_Call_Link;
-- Pointer to the entry call being executed (if any)
Entry_Bodies : Protected_Entry_Body_Access;
-- Pointer to an array containing the executable code for all entry
-- bodies of a protected type.
Find_Body_Index : Find_Body_Index_Access;
-- A function which maps the entry index in a call (which denotes the
-- queue of the proper entry) into the body of the entry.
Entry_Queue_Maxes : Protected_Entry_Queue_Max_Access;
-- Access to an array of naturals representing the max value for each
-- entry's queue length. A value of 0 signifies no max.
Entry_Queues : Protected_Entry_Queue_Array (1 .. Num_Entries);
-- Action and barrier subprograms for the protected type.
end record;
-- No default initial values for this type, since call records will need to
-- be re-initialized before every use.
type Protection_Entries_Access is access all Protection_Entries;
function To_Address is
new Ada.Unchecked_Conversion (Protection_Entries_Access, System.Address);
function To_Protection is
new Ada.Unchecked_Conversion (System.Address, Protection_Entries_Access);
procedure Initialize_Protection_Entries
(Object : Protection_Entries_Access;
Ceiling_Priority : Integer;
Compiler_Info : System.Address;
Entry_Queue_Maxes : Protected_Entry_Queue_Max_Access;
Entry_Bodies : Protected_Entry_Body_Access;
Find_Body_Index : Find_Body_Index_Access);
-- Initialize the Object parameter so that it can be used by the runtime
-- to keep track of the runtime state of a protected object.
procedure Lock_Entries (Object : Protection_Entries_Access);
pragma Inline (Lock_Entries);
-- Lock a protected object for write access. Upon return, the caller owns
-- the lock to this object, and no other call to Lock or Lock_Read_Only
-- with the same argument will return until the corresponding call to
-- Unlock has been made by the caller. Program_Error is raised in case of
-- ceiling violation.
procedure Unlock_Entries (Object : Protection_Entries_Access);
pragma Inline (Unlock_Entries);
-- Relinquish ownership of the lock for the object represented by the
-- Object parameter. If this ownership was for write access, or if it was
-- for read access where there are no other read access locks outstanding,
-- one (or more, in the case of Lock_Read_Only) of the tasks waiting on
-- this lock (if any) will be given the lock and allowed to return from
-- the Lock or Lock_Read_Only call.
end System.Tasking.Protected_Objects.Entries;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . S T R I N G S . W I D E _ W I D E _ B O U N D E D --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2015, Free Software Foundation, Inc. --
-- --
-- This specification is derived from the Ada Reference Manual for use with --
-- GNAT. The copyright notice above, and the license provisions that follow --
-- apply solely to the contents of the part following the private keyword. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Ada.Strings.Wide_Wide_Maps;
with Ada.Strings.Wide_Wide_Superbounded;
package Ada.Strings.Wide_Wide_Bounded is
pragma Preelaborate;
generic
Max : Positive;
-- Maximum length of a Bounded_Wide_Wide_String
package Generic_Bounded_Length is
Max_Length : constant Positive := Max;
type Bounded_Wide_Wide_String is private;
pragma Preelaborable_Initialization (Bounded_Wide_Wide_String);
Null_Bounded_Wide_Wide_String : constant Bounded_Wide_Wide_String;
subtype Length_Range is Natural range 0 .. Max_Length;
function Length (Source : Bounded_Wide_Wide_String) return Length_Range;
--------------------------------------------------------
-- Conversion, Concatenation, and Selection Functions --
--------------------------------------------------------
function To_Bounded_Wide_Wide_String
(Source : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function To_Wide_Wide_String
(Source : Bounded_Wide_Wide_String) return Wide_Wide_String;
procedure Set_Bounded_Wide_Wide_String
(Target : out Bounded_Wide_Wide_String;
Source : Wide_Wide_String;
Drop : Truncation := Error);
pragma Ada_05 (Set_Bounded_Wide_Wide_String);
function Append
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Append
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Append
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Append
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_Character;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Append
(Left : Wide_Wide_Character;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Bounded_Wide_Wide_String;
Drop : Truncation := Error);
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Wide_Wide_String;
Drop : Truncation := Error);
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Wide_Wide_Character;
Drop : Truncation := Error);
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String;
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Bounded_Wide_Wide_String;
function "&"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String;
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_Character) return Bounded_Wide_Wide_String;
function "&"
(Left : Wide_Wide_Character;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String;
function Element
(Source : Bounded_Wide_Wide_String;
Index : Positive) return Wide_Wide_Character;
procedure Replace_Element
(Source : in out Bounded_Wide_Wide_String;
Index : Positive;
By : Wide_Wide_Character);
function Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural) return Wide_Wide_String;
function Bounded_Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural) return Bounded_Wide_Wide_String;
pragma Ada_05 (Bounded_Slice);
procedure Bounded_Slice
(Source : Bounded_Wide_Wide_String;
Target : out Bounded_Wide_Wide_String;
Low : Positive;
High : Natural);
pragma Ada_05 (Bounded_Slice);
function "="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function "="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean;
function "="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function "<"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function "<"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean;
function "<"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function "<="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function "<="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean;
function "<="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function ">"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function ">"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean;
function ">"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function ">="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
function ">="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean;
function ">="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean;
----------------------
-- Search Functions --
----------------------
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural;
function Index
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural;
pragma Ada_05 (Index);
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural;
pragma Ada_05 (Index);
function Index
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward) return Natural;
pragma Ada_05 (Index);
function Index_Non_Blank
(Source : Bounded_Wide_Wide_String;
Going : Direction := Forward) return Natural;
function Index_Non_Blank
(Source : Bounded_Wide_Wide_String;
From : Positive;
Going : Direction := Forward) return Natural;
pragma Ada_05 (Index_Non_Blank);
function Count
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural;
function Count
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural;
function Count
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set) return Natural;
procedure Find_Token
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
From : Positive;
Test : Membership;
First : out Positive;
Last : out Natural);
pragma Ada_2012 (Find_Token);
procedure Find_Token
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
Test : Membership;
First : out Positive;
Last : out Natural);
------------------------------------
-- String Translation Subprograms --
------------------------------------
function Translate
(Source : Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping)
return Bounded_Wide_Wide_String;
procedure Translate
(Source : in out Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping);
function Translate
(Source : Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Bounded_Wide_Wide_String;
procedure Translate
(Source : in out Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function);
---------------------------------------
-- String Transformation Subprograms --
---------------------------------------
function Replace_Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural;
By : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Replace_Slice
(Source : in out Bounded_Wide_Wide_String;
Low : Positive;
High : Natural;
By : Wide_Wide_String;
Drop : Truncation := Error);
function Insert
(Source : Bounded_Wide_Wide_String;
Before : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Insert
(Source : in out Bounded_Wide_Wide_String;
Before : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error);
function Overwrite
(Source : Bounded_Wide_Wide_String;
Position : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Overwrite
(Source : in out Bounded_Wide_Wide_String;
Position : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error);
function Delete
(Source : Bounded_Wide_Wide_String;
From : Positive;
Through : Natural) return Bounded_Wide_Wide_String;
procedure Delete
(Source : in out Bounded_Wide_Wide_String;
From : Positive;
Through : Natural);
---------------------------------
-- String Selector Subprograms --
---------------------------------
function Trim
(Source : Bounded_Wide_Wide_String;
Side : Trim_End) return Bounded_Wide_Wide_String;
procedure Trim
(Source : in out Bounded_Wide_Wide_String;
Side : Trim_End);
function Trim
(Source : Bounded_Wide_Wide_String;
Left : Wide_Wide_Maps.Wide_Wide_Character_Set;
Right : Wide_Wide_Maps.Wide_Wide_Character_Set)
return Bounded_Wide_Wide_String;
procedure Trim
(Source : in out Bounded_Wide_Wide_String;
Left : Wide_Wide_Maps.Wide_Wide_Character_Set;
Right : Wide_Wide_Maps.Wide_Wide_Character_Set);
function Head
(Source : Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Head
(Source : in out Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error);
function Tail
(Source : Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
procedure Tail
(Source : in out Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error);
------------------------------------
-- String Constructor Subprograms --
------------------------------------
function "*"
(Left : Natural;
Right : Wide_Wide_Character) return Bounded_Wide_Wide_String;
function "*"
(Left : Natural;
Right : Wide_Wide_String) return Bounded_Wide_Wide_String;
function "*"
(Left : Natural;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String;
function Replicate
(Count : Natural;
Item : Wide_Wide_Character;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Replicate
(Count : Natural;
Item : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
function Replicate
(Count : Natural;
Item : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String;
private
-- Most of the implementation is in the separate non generic package
-- Ada.Strings.Wide_Wide_Superbounded. Type Bounded_Wide_Wide_String is
-- derived from type Wide_Wide_Superbounded.Super_String with the
-- maximum length constraint. In almost all cases, the routines in
-- Wide_Wide_Superbounded can be called with no requirement to pass the
-- maximum length explicitly, since there is at least one
-- Bounded_Wide_Wide_String argument from which the maximum length can
-- be obtained. For all such routines, the implementation in this
-- private part is simply renaming of the corresponding routine in the
-- super bouded package.
-- The five exceptions are the * and Replicate routines operating on
-- character values. For these cases, we have a routine in the body
-- that calls the superbounded routine passing the maximum length
-- explicitly as an extra parameter.
type Bounded_Wide_Wide_String is
new Wide_Wide_Superbounded.Super_String (Max_Length);
-- Deriving Bounded_Wide_Wide_String from
-- Wide_Wide_Superbounded.Super_String is the real trick, it ensures
-- that the type Bounded_Wide_Wide_String declared in the generic
-- instantiation is compatible with the Super_String type declared in
-- the Wide_Wide_Superbounded package.
Null_Bounded_Wide_Wide_String : constant Bounded_Wide_Wide_String :=
(Max_Length => Max_Length,
Current_Length => 0,
Data =>
(1 .. Max_Length =>
Wide_Wide_Superbounded.Wide_Wide_NUL));
pragma Inline (To_Bounded_Wide_Wide_String);
procedure Set_Bounded_Wide_Wide_String
(Target : out Bounded_Wide_Wide_String;
Source : Wide_Wide_String;
Drop : Truncation := Error)
renames Set_Super_String;
function Length
(Source : Bounded_Wide_Wide_String) return Length_Range
renames Super_Length;
function To_Wide_Wide_String
(Source : Bounded_Wide_Wide_String) return Wide_Wide_String
renames Super_To_String;
function Append
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Append;
function Append
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Append;
function Append
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Append;
function Append
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_Character;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Append;
function Append
(Left : Wide_Wide_Character;
Right : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Append;
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Bounded_Wide_Wide_String;
Drop : Truncation := Error)
renames Super_Append;
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Wide_Wide_String;
Drop : Truncation := Error)
renames Super_Append;
procedure Append
(Source : in out Bounded_Wide_Wide_String;
New_Item : Wide_Wide_Character;
Drop : Truncation := Error)
renames Super_Append;
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String
renames Concat;
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Bounded_Wide_Wide_String
renames Concat;
function "&"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String
renames Concat;
function "&"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_Character) return Bounded_Wide_Wide_String
renames Concat;
function "&"
(Left : Wide_Wide_Character;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String
renames Concat;
function Element
(Source : Bounded_Wide_Wide_String;
Index : Positive) return Wide_Wide_Character
renames Super_Element;
procedure Replace_Element
(Source : in out Bounded_Wide_Wide_String;
Index : Positive;
By : Wide_Wide_Character)
renames Super_Replace_Element;
function Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural) return Wide_Wide_String
renames Super_Slice;
function Bounded_Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural) return Bounded_Wide_Wide_String
renames Super_Slice;
procedure Bounded_Slice
(Source : Bounded_Wide_Wide_String;
Target : out Bounded_Wide_Wide_String;
Low : Positive;
High : Natural)
renames Super_Slice;
overriding function "="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Equal;
function "="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean
renames Equal;
function "="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Equal;
function "<"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Less;
function "<"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean
renames Less;
function "<"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Less;
function "<="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Less_Or_Equal;
function "<="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean
renames Less_Or_Equal;
function "<="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Less_Or_Equal;
function ">"
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Greater;
function ">"
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean
renames Greater;
function ">"
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Greater;
function ">="
(Left : Bounded_Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Greater_Or_Equal;
function ">="
(Left : Bounded_Wide_Wide_String;
Right : Wide_Wide_String) return Boolean
renames Greater_Or_Equal;
function ">="
(Left : Wide_Wide_String;
Right : Bounded_Wide_Wide_String) return Boolean
renames Greater_Or_Equal;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural
renames Super_Index;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural
renames Super_Index;
function Index
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
Test : Membership := Inside;
Going : Direction := Forward) return Natural
renames Super_Index;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural
renames Super_Index;
function Index
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
From : Positive;
Going : Direction := Forward;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural
renames Super_Index;
function Index
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward) return Natural
renames Super_Index;
function Index_Non_Blank
(Source : Bounded_Wide_Wide_String;
Going : Direction := Forward) return Natural
renames Super_Index_Non_Blank;
function Index_Non_Blank
(Source : Bounded_Wide_Wide_String;
From : Positive;
Going : Direction := Forward) return Natural
renames Super_Index_Non_Blank;
function Count
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping :=
Wide_Wide_Maps.Identity)
return Natural
renames Super_Count;
function Count
(Source : Bounded_Wide_Wide_String;
Pattern : Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Natural
renames Super_Count;
function Count
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set) return Natural
renames Super_Count;
procedure Find_Token
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
From : Positive;
Test : Membership;
First : out Positive;
Last : out Natural)
renames Super_Find_Token;
procedure Find_Token
(Source : Bounded_Wide_Wide_String;
Set : Wide_Wide_Maps.Wide_Wide_Character_Set;
Test : Membership;
First : out Positive;
Last : out Natural)
renames Super_Find_Token;
function Translate
(Source : Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping)
return Bounded_Wide_Wide_String
renames Super_Translate;
procedure Translate
(Source : in out Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping)
renames Super_Translate;
function Translate
(Source : Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
return Bounded_Wide_Wide_String
renames Super_Translate;
procedure Translate
(Source : in out Bounded_Wide_Wide_String;
Mapping : Wide_Wide_Maps.Wide_Wide_Character_Mapping_Function)
renames Super_Translate;
function Replace_Slice
(Source : Bounded_Wide_Wide_String;
Low : Positive;
High : Natural;
By : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Replace_Slice;
procedure Replace_Slice
(Source : in out Bounded_Wide_Wide_String;
Low : Positive;
High : Natural;
By : Wide_Wide_String;
Drop : Truncation := Error)
renames Super_Replace_Slice;
function Insert
(Source : Bounded_Wide_Wide_String;
Before : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Insert;
procedure Insert
(Source : in out Bounded_Wide_Wide_String;
Before : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error)
renames Super_Insert;
function Overwrite
(Source : Bounded_Wide_Wide_String;
Position : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Overwrite;
procedure Overwrite
(Source : in out Bounded_Wide_Wide_String;
Position : Positive;
New_Item : Wide_Wide_String;
Drop : Truncation := Error)
renames Super_Overwrite;
function Delete
(Source : Bounded_Wide_Wide_String;
From : Positive;
Through : Natural) return Bounded_Wide_Wide_String
renames Super_Delete;
procedure Delete
(Source : in out Bounded_Wide_Wide_String;
From : Positive;
Through : Natural)
renames Super_Delete;
function Trim
(Source : Bounded_Wide_Wide_String;
Side : Trim_End) return Bounded_Wide_Wide_String
renames Super_Trim;
procedure Trim
(Source : in out Bounded_Wide_Wide_String;
Side : Trim_End)
renames Super_Trim;
function Trim
(Source : Bounded_Wide_Wide_String;
Left : Wide_Wide_Maps.Wide_Wide_Character_Set;
Right : Wide_Wide_Maps.Wide_Wide_Character_Set)
return Bounded_Wide_Wide_String
renames Super_Trim;
procedure Trim
(Source : in out Bounded_Wide_Wide_String;
Left : Wide_Wide_Maps.Wide_Wide_Character_Set;
Right : Wide_Wide_Maps.Wide_Wide_Character_Set)
renames Super_Trim;
function Head
(Source : Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Head;
procedure Head
(Source : in out Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error)
renames Super_Head;
function Tail
(Source : Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Tail;
procedure Tail
(Source : in out Bounded_Wide_Wide_String;
Count : Natural;
Pad : Wide_Wide_Character := Wide_Wide_Space;
Drop : Truncation := Error)
renames Super_Tail;
function "*"
(Left : Natural;
Right : Bounded_Wide_Wide_String) return Bounded_Wide_Wide_String
renames Times;
function Replicate
(Count : Natural;
Item : Bounded_Wide_Wide_String;
Drop : Truncation := Error) return Bounded_Wide_Wide_String
renames Super_Replicate;
end Generic_Bounded_Length;
end Ada.Strings.Wide_Wide_Bounded;
|
-- Copyright 2007-2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
procedure Foo is
begin
begin
raise Constraint_Error;
exception
when Constraint_Error => -- BREAK1
null;
end;
begin
raise Program_Error;
exception
when Program_Error => -- BREAK2
null;
end;
end Foo;
|
------------------------------------------------------------------------------
-- EMAIL: <darkestkhan@gmail.com> --
-- License: ISC License (see COPYING file) --
-- --
-- Copyright © 2015 darkestkhan --
------------------------------------------------------------------------------
-- 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. --
------------------------------------------------------------------------------
with Ada.Characters.Handling;
with Ada.Containers.Hashed_Sets;
with Ada.Command_Line;
with Ada.Strings.Fixed;
with Ada.Strings.Hash;
package body CBAP is
---------------------------------------------------------------------------
function To_Lower (Item: in String) return String
renames Ada.Characters.Handling.To_Lower;
---------------------------------------------------------------------------
type Callback_Data is
record
Hash : Ada.Containers.Hash_Type;
Callback: Callbacks;
Arg_Type: Argument_Types := Value;
Case_Sensitive: Boolean := True;
end record;
function Hash (This: in Callback_Data) return Ada.Containers.Hash_Type
is
begin
return This.Hash;
end Hash;
overriding function "=" (Left, Right: in Callback_Data) return Boolean
is
use type Ada.Containers.Hash_Type;
begin
return Left.Hash = Right.Hash;
end "=";
procedure Null_Callback (Item: in String) is null;
Empty_Callback_Data: constant Callback_Data :=
Callback_Data'(0, Null_Callback'Access, Value, True);
package Callback_Sets is new
Ada.Containers.Hashed_Sets (Callback_Data, Hash, "=");
---------------------------------------------------------------------------
Callback_Set: Callback_Sets.Set := Callback_Sets.Empty_Set;
---------------------------------------------------------------------------
procedure Register
( Callback : in Callbacks;
Called_On : in String;
Argument_Type : in Argument_Types := Value;
Case_Sensitive: in Boolean := True
)
is
Var: Callback_Data :=
Callback_Data'(0, Callback, Argument_Type, Case_Sensitive);
begin
if Ada.Strings.Fixed.Index (Called_On, "=", Called_On'First) /= 0 then
raise Incorrect_Called_On with Called_On;
end if;
if Case_Sensitive then
Var.Hash := Ada.Strings.Hash (Called_On);
else
Var.Hash := Ada.Strings.Hash (To_Lower (Called_On));
end if;
Callback_Set.Insert (Var);
exception
when Constraint_Error => raise Constraint_Error with
"Following argument already has callback registered: " & Called_On;
end Register;
---------------------------------------------------------------------------
procedure Process_Arguments
is
---------------------------------------------------------------------------
package CLI renames Ada.Command_Line;
---------------------------------------------------------------------------
procedure Add_Inputs (From: in Natural)
is
begin
if not (From < CLI.Argument_Count) then
return;
end if;
for K in From + 1 .. CLI.Argument_Count loop
Input_Arguments.Append (CLI.Argument (K));
end loop;
end Add_Inputs;
---------------------------------------------------------------------------
function Extract_Name (Item: in String) return String
is
begin
return Item
(Item'First .. Ada.Strings.Fixed.Index (Item, "=", Item'First) - 1);
end Extract_Name;
---------------------------------------------------------------------------
function Extract_Value (Item: in String) return String
is
Pos: constant Natural := Ada.Strings.Fixed.Index (Item, "=", Item'First);
begin
if Pos = Item'Last then
return ""; -- in case: "variable="
else
return Item (Pos + 1 .. Item'Last);
end if;
end Extract_Value;
---------------------------------------------------------------------------
procedure Check_Callback (Item: in String)
is
Dummy_Callback : Callback_Data := Empty_Callback_Data;
Actual_Callback : Callback_Data := Empty_Callback_Data;
begin
Case_Check: -- loop over case sensitiviness
for Case_Sensitive in Boolean'Range loop
Arg_Type_Check: -- loop over argument type
for Arg_Type in Argument_Types'Range loop
if Arg_Type = Value then
if Case_Sensitive then
Dummy_Callback.Hash := Ada.Strings.Hash (Item);
else
Dummy_Callback.Hash := Ada.Strings.Hash (To_Lower (Item));
end if;
else -- For Variable we need to need to hash name ONLY
if Case_Sensitive then
Dummy_Callback.Hash := Ada.Strings.Hash (Extract_Name (Item));
else
Dummy_Callback.Hash := Ada.Strings.Hash
(Extract_Name (To_Lower (Item)));
end if;
end if;
if Callback_Set.Contains (Dummy_Callback) then
Actual_Callback :=
Callback_Sets.Element (Callback_Set.Find (Dummy_Callback));
if Actual_Callback.Case_Sensitive = Case_Sensitive and
Actual_Callback.Arg_Type = Arg_Type
then
if Arg_Type = Value then
Actual_Callback.Callback (Item);
return;
else -- Special circuitry for Variable type
declare
Pos: constant Natural :=
Ada.Strings.Fixed.Index (Item, "=", Item'First);
begin
if Pos = 0 then
Unknown_Arguments.Append (Item);
return;
else
Actual_Callback.Callback (Extract_Value (Item));
return;
end if;
end;
end if;
end if;
end if; -- Callback_Set.Contains
end loop Arg_Type_Check;
end loop Case_Check;
-- No callback associated with argument has been found.
Unknown_Arguments.Append (Item);
end Check_Callback;
---------------------------------------------------------------------------
begin
if CLI.Argument_Count = 0 then
return;
end if;
for K in 1 .. CLI.Argument_Count loop
declare
Arg: constant String := CLI.Argument (K);
begin
if Arg = "--" then
Add_Inputs (K);
return;
end if;
-- Strip leading hyphens
if Arg'Length > 2 and then Arg (Arg'First .. Arg'First + 1) = "--" then
Check_Callback (Arg (Arg'First + 2 .. Arg'Last));
elsif Arg'Length > 1 and then Arg (1 .. 1) = "-" then
Check_Callback (Arg (Arg'First + 1 .. Arg'Last));
else
Check_Callback (Arg);
end if;
end;
end loop;
end Process_Arguments;
---------------------------------------------------------------------------
end CBAP;
|
private package GID.Decoding_BMP is
--------------------
-- Image decoding --
--------------------
generic
type Primary_color_range is mod <>;
with procedure Set_X_Y (x, y: Natural);
with procedure Put_Pixel (
red, green, blue : Primary_color_range;
alpha : Primary_color_range
);
with procedure Feedback (percents: Natural);
--
procedure Load (image: in out Image_descriptor);
end GID.Decoding_BMP;
|
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="11">
<syndb class_id="0" tracking_level="0" version="0">
<userIPLatency>-1</userIPLatency>
<userIPName/>
<cdfg class_id="1" tracking_level="1" version="0" object_id="_0">
<name>fir</name>
<ret_bitwidth>0</ret_bitwidth>
<ports class_id="2" tracking_level="0" version="0">
<count>3</count>
<item_version>0</item_version>
<item class_id="3" tracking_level="1" version="0" object_id="_1">
<Value class_id="4" tracking_level="0" version="0">
<Obj class_id="5" tracking_level="0" version="0">
<type>1</type>
<id>1</id>
<name>y</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo class_id="6" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>y</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<direction>1</direction>
<if_type>0</if_type>
<array_size>0</array_size>
<bit_vecs class_id="7" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</bit_vecs>
</item>
<item class_id_reference="3" object_id="_2">
<Value>
<Obj>
<type>1</type>
<id>2</id>
<name>c</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>c</originalName>
<rtlName/>
<coreName>RAM</coreName>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<direction>0</direction>
<if_type>1</if_type>
<array_size>11</array_size>
<bit_vecs>
<count>0</count>
<item_version>0</item_version>
</bit_vecs>
</item>
<item class_id_reference="3" object_id="_3">
<Value>
<Obj>
<type>1</type>
<id>3</id>
<name>x</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>x</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<direction>0</direction>
<if_type>0</if_type>
<array_size>0</array_size>
<bit_vecs>
<count>0</count>
<item_version>0</item_version>
</bit_vecs>
</item>
</ports>
<nodes class_id="8" tracking_level="0" version="0">
<count>30</count>
<item_version>0</item_version>
<item class_id="9" tracking_level="1" version="0" object_id="_4">
<Value>
<Obj>
<type>0</type>
<id>9</id>
<name>x_read</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>x</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>49</item>
<item>50</item>
</oprand_edges>
<opcode>read</opcode>
</item>
<item class_id_reference="9" object_id="_5">
<Value>
<Obj>
<type>0</type>
<id>10</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item class_id="11" tracking_level="0" version="0">
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second class_id="12" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="13" tracking_level="0" version="0">
<first class_id="14" tracking_level="0" version="0">
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>51</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_6">
<Value>
<Obj>
<type>0</type>
<id>12</id>
<name>acc</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>acc</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>4</count>
<item_version>0</item_version>
<item>53</item>
<item>54</item>
<item>55</item>
<item>56</item>
</oprand_edges>
<opcode>phi</opcode>
</item>
<item class_id_reference="9" object_id="_7">
<Value>
<Obj>
<type>0</type>
<id>13</id>
<name>i</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>i</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>5</bitwidth>
</Value>
<oprand_edges>
<count>4</count>
<item_version>0</item_version>
<item>58</item>
<item>59</item>
<item>60</item>
<item>61</item>
</oprand_edges>
<opcode>phi</opcode>
</item>
<item class_id_reference="9" object_id="_8">
<Value>
<Obj>
<type>0</type>
<id>14</id>
<name>i_cast</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>i_cast_fu_126_p1</rtlName>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>62</item>
</oprand_edges>
<opcode>sext</opcode>
</item>
<item class_id_reference="9" object_id="_9">
<Value>
<Obj>
<type>0</type>
<id>15</id>
<name>tmp</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_fu_130_p3</rtlName>
<coreName/>
</Obj>
<bitwidth>1</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>64</item>
<item>65</item>
<item>67</item>
</oprand_edges>
<opcode>bitselect</opcode>
</item>
<item class_id_reference="9" object_id="_10">
<Value>
<Obj>
<type>0</type>
<id>17</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>68</item>
<item>69</item>
<item>70</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_11">
<Value>
<Obj>
<type>0</type>
<id>20</id>
<name>tmp_1</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>64</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>64</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_1_fu_138_p2</rtlName>
<coreName/>
</Obj>
<bitwidth>1</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>71</item>
<item>73</item>
</oprand_edges>
<opcode>icmp</opcode>
</item>
<item class_id_reference="9" object_id="_12">
<Value>
<Obj>
<type>0</type>
<id>21</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>64</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>64</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>74</item>
<item>75</item>
<item>76</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_13">
<Value>
<Obj>
<type>0</type>
<id>23</id>
<name>tmp_7</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_7_fu_144_p1</rtlName>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>82</item>
</oprand_edges>
<opcode>trunc</opcode>
</item>
<item class_id_reference="9" object_id="_14">
<Value>
<Obj>
<type>0</type>
<id>24</id>
<name>tmp_2</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_2_fu_148_p2</rtlName>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>84</item>
<item>85</item>
</oprand_edges>
<opcode>add</opcode>
</item>
<item class_id_reference="9" object_id="_15">
<Value>
<Obj>
<type>0</type>
<id>25</id>
<name>tmp_3</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_3_fu_154_p1</rtlName>
<coreName/>
</Obj>
<bitwidth>64</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>86</item>
</oprand_edges>
<opcode>zext</opcode>
</item>
<item class_id_reference="9" object_id="_16">
<Value>
<Obj>
<type>0</type>
<id>26</id>
<name>shift_reg_addr</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>87</item>
<item>89</item>
<item>90</item>
</oprand_edges>
<opcode>getelementptr</opcode>
</item>
<item class_id_reference="9" object_id="_17">
<Value>
<Obj>
<type>0</type>
<id>27</id>
<name>data</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName>data</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>91</item>
</oprand_edges>
<opcode>load</opcode>
</item>
<item class_id_reference="9" object_id="_18">
<Value>
<Obj>
<type>0</type>
<id>28</id>
<name>tmp_4</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_4_fu_159_p1</rtlName>
<coreName/>
</Obj>
<bitwidth>64</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>92</item>
</oprand_edges>
<opcode>zext</opcode>
</item>
<item class_id_reference="9" object_id="_19">
<Value>
<Obj>
<type>0</type>
<id>29</id>
<name>shift_reg_addr_1</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>93</item>
<item>94</item>
<item>95</item>
</oprand_edges>
<opcode>getelementptr</opcode>
</item>
<item class_id_reference="9" object_id="_20">
<Value>
<Obj>
<type>0</type>
<id>30</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>68</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>68</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>96</item>
<item>97</item>
</oprand_edges>
<opcode>store</opcode>
</item>
<item class_id_reference="9" object_id="_21">
<Value>
<Obj>
<type>0</type>
<id>31</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>98</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_22">
<Value>
<Obj>
<type>0</type>
<id>33</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>65</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>65</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>77</item>
<item>80</item>
</oprand_edges>
<opcode>store</opcode>
</item>
<item class_id_reference="9" object_id="_23">
<Value>
<Obj>
<type>0</type>
<id>34</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>67</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>67</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>81</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_24">
<Value>
<Obj>
<type>0</type>
<id>36</id>
<name>data1</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName>data</originalName>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>4</count>
<item_version>0</item_version>
<item>99</item>
<item>100</item>
<item>101</item>
<item>102</item>
</oprand_edges>
<opcode>phi</opcode>
</item>
<item class_id_reference="9" object_id="_25">
<Value>
<Obj>
<type>0</type>
<id>37</id>
<name>tmp_5</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>71</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>71</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>tmp_5_fu_163_p1</rtlName>
<coreName/>
</Obj>
<bitwidth>64</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>103</item>
</oprand_edges>
<opcode>zext</opcode>
</item>
<item class_id_reference="9" object_id="_26">
<Value>
<Obj>
<type>0</type>
<id>38</id>
<name>c_addr</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>71</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>71</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>104</item>
<item>105</item>
<item>106</item>
</oprand_edges>
<opcode>getelementptr</opcode>
</item>
<item class_id_reference="9" object_id="_27">
<Value>
<Obj>
<type>0</type>
<id>39</id>
<name>c_load</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>71</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>71</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>107</item>
</oprand_edges>
<opcode>load</opcode>
</item>
<item class_id_reference="9" object_id="_28">
<Value>
<Obj>
<type>0</type>
<id>40</id>
<name>tmp_6</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>71</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>71</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName>fir_mul_32s_32s_32_3_U0</rtlName>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>108</item>
<item>109</item>
</oprand_edges>
<opcode>mul</opcode>
</item>
<item class_id_reference="9" object_id="_29">
<Value>
<Obj>
<type>0</type>
<id>41</id>
<name>acc_1</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>71</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>71</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName>acc</originalName>
<rtlName>acc_1_fu_178_p2</rtlName>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>110</item>
<item>111</item>
</oprand_edges>
<opcode>add</opcode>
</item>
<item class_id_reference="9" object_id="_30">
<Value>
<Obj>
<type>0</type>
<id>42</id>
<name>i_1</name>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName>i</originalName>
<rtlName>i_1_fu_167_p2</rtlName>
<coreName/>
</Obj>
<bitwidth>5</bitwidth>
</Value>
<oprand_edges>
<count>2</count>
<item_version>0</item_version>
<item>112</item>
<item>114</item>
</oprand_edges>
<opcode>add</opcode>
</item>
<item class_id_reference="9" object_id="_31">
<Value>
<Obj>
<type>0</type>
<id>43</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>63</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>63</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>1</count>
<item_version>0</item_version>
<item>115</item>
</oprand_edges>
<opcode>br</opcode>
</item>
<item class_id_reference="9" object_id="_32">
<Value>
<Obj>
<type>0</type>
<id>45</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>73</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>73</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>3</count>
<item_version>0</item_version>
<item>117</item>
<item>118</item>
<item>119</item>
</oprand_edges>
<opcode>write</opcode>
</item>
<item class_id_reference="9" object_id="_33">
<Value>
<Obj>
<type>0</type>
<id>46</id>
<name/>
<fileName>fir.c</fileName>
<fileDirectory>..</fileDirectory>
<lineNumber>74</lineNumber>
<contextFuncName>fir</contextFuncName>
<inlineStackInfo>
<count>1</count>
<item_version>0</item_version>
<item>
<first>d:/opt/source/Vivado/Vivado_HLS_Tutorial/Introduction/lab3</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>
<first>fir.c</first>
<second>fir</second>
</first>
<second>74</second>
</item>
</second>
</item>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>0</bitwidth>
</Value>
<oprand_edges>
<count>0</count>
<item_version>0</item_version>
</oprand_edges>
<opcode>ret</opcode>
</item>
</nodes>
<consts class_id="15" tracking_level="0" version="0">
<count>8</count>
<item_version>0</item_version>
<item class_id="16" tracking_level="1" version="0" object_id="_34">
<Value>
<Obj>
<type>2</type>
<id>52</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<const_type>0</const_type>
<content>0</content>
</item>
<item class_id_reference="16" object_id="_35">
<Value>
<Obj>
<type>2</type>
<id>57</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>5</bitwidth>
</Value>
<const_type>0</const_type>
<content>10</content>
</item>
<item class_id_reference="16" object_id="_36">
<Value>
<Obj>
<type>2</type>
<id>66</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<const_type>0</const_type>
<content>4</content>
</item>
<item class_id_reference="16" object_id="_37">
<Value>
<Obj>
<type>2</type>
<id>72</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>5</bitwidth>
</Value>
<const_type>0</const_type>
<content>0</content>
</item>
<item class_id_reference="16" object_id="_38">
<Value>
<Obj>
<type>2</type>
<id>78</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>32</bitwidth>
</Value>
<const_type>3</const_type>
<content>0</content>
</item>
<item class_id_reference="16" object_id="_39">
<Value>
<Obj>
<type>2</type>
<id>83</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>4</bitwidth>
</Value>
<const_type>0</const_type>
<content>15</content>
</item>
<item class_id_reference="16" object_id="_40">
<Value>
<Obj>
<type>2</type>
<id>88</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>64</bitwidth>
</Value>
<const_type>0</const_type>
<content>0</content>
</item>
<item class_id_reference="16" object_id="_41">
<Value>
<Obj>
<type>2</type>
<id>113</id>
<name>empty</name>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<bitwidth>5</bitwidth>
</Value>
<const_type>0</const_type>
<content>31</content>
</item>
</consts>
<blocks class_id="17" tracking_level="0" version="0">
<count>7</count>
<item_version>0</item_version>
<item class_id="18" tracking_level="1" version="0" object_id="_42">
<Obj>
<type>3</type>
<id>11</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>2</count>
<item_version>0</item_version>
<item>9</item>
<item>10</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_43">
<Obj>
<type>3</type>
<id>18</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>5</count>
<item_version>0</item_version>
<item>12</item>
<item>13</item>
<item>14</item>
<item>15</item>
<item>17</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_44">
<Obj>
<type>3</type>
<id>22</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>2</count>
<item_version>0</item_version>
<item>20</item>
<item>21</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_45">
<Obj>
<type>3</type>
<id>32</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>9</count>
<item_version>0</item_version>
<item>23</item>
<item>24</item>
<item>25</item>
<item>26</item>
<item>27</item>
<item>28</item>
<item>29</item>
<item>30</item>
<item>31</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_46">
<Obj>
<type>3</type>
<id>35</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>2</count>
<item_version>0</item_version>
<item>33</item>
<item>34</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_47">
<Obj>
<type>3</type>
<id>44</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>8</count>
<item_version>0</item_version>
<item>36</item>
<item>37</item>
<item>38</item>
<item>39</item>
<item>40</item>
<item>41</item>
<item>42</item>
<item>43</item>
</node_objs>
</item>
<item class_id_reference="18" object_id="_48">
<Obj>
<type>3</type>
<id>47</id>
<name/>
<fileName/>
<fileDirectory/>
<lineNumber>0</lineNumber>
<contextFuncName/>
<inlineStackInfo>
<count>0</count>
<item_version>0</item_version>
</inlineStackInfo>
<originalName/>
<rtlName/>
<coreName/>
</Obj>
<node_objs>
<count>2</count>
<item_version>0</item_version>
<item>45</item>
<item>46</item>
</node_objs>
</item>
</blocks>
<edges class_id="19" tracking_level="0" version="0">
<count>66</count>
<item_version>0</item_version>
<item class_id="20" tracking_level="1" version="0" object_id="_49">
<id>50</id>
<edge_type>1</edge_type>
<source_obj>3</source_obj>
<sink_obj>9</sink_obj>
</item>
<item class_id_reference="20" object_id="_50">
<id>51</id>
<edge_type>2</edge_type>
<source_obj>18</source_obj>
<sink_obj>10</sink_obj>
</item>
<item class_id_reference="20" object_id="_51">
<id>53</id>
<edge_type>1</edge_type>
<source_obj>52</source_obj>
<sink_obj>12</sink_obj>
</item>
<item class_id_reference="20" object_id="_52">
<id>54</id>
<edge_type>2</edge_type>
<source_obj>11</source_obj>
<sink_obj>12</sink_obj>
</item>
<item class_id_reference="20" object_id="_53">
<id>55</id>
<edge_type>1</edge_type>
<source_obj>41</source_obj>
<sink_obj>12</sink_obj>
</item>
<item class_id_reference="20" object_id="_54">
<id>56</id>
<edge_type>2</edge_type>
<source_obj>44</source_obj>
<sink_obj>12</sink_obj>
</item>
<item class_id_reference="20" object_id="_55">
<id>58</id>
<edge_type>1</edge_type>
<source_obj>57</source_obj>
<sink_obj>13</sink_obj>
</item>
<item class_id_reference="20" object_id="_56">
<id>59</id>
<edge_type>2</edge_type>
<source_obj>11</source_obj>
<sink_obj>13</sink_obj>
</item>
<item class_id_reference="20" object_id="_57">
<id>60</id>
<edge_type>1</edge_type>
<source_obj>42</source_obj>
<sink_obj>13</sink_obj>
</item>
<item class_id_reference="20" object_id="_58">
<id>61</id>
<edge_type>2</edge_type>
<source_obj>44</source_obj>
<sink_obj>13</sink_obj>
</item>
<item class_id_reference="20" object_id="_59">
<id>62</id>
<edge_type>1</edge_type>
<source_obj>13</source_obj>
<sink_obj>14</sink_obj>
</item>
<item class_id_reference="20" object_id="_60">
<id>65</id>
<edge_type>1</edge_type>
<source_obj>13</source_obj>
<sink_obj>15</sink_obj>
</item>
<item class_id_reference="20" object_id="_61">
<id>67</id>
<edge_type>1</edge_type>
<source_obj>66</source_obj>
<sink_obj>15</sink_obj>
</item>
<item class_id_reference="20" object_id="_62">
<id>68</id>
<edge_type>1</edge_type>
<source_obj>15</source_obj>
<sink_obj>17</sink_obj>
</item>
<item class_id_reference="20" object_id="_63">
<id>69</id>
<edge_type>2</edge_type>
<source_obj>22</source_obj>
<sink_obj>17</sink_obj>
</item>
<item class_id_reference="20" object_id="_64">
<id>70</id>
<edge_type>2</edge_type>
<source_obj>47</source_obj>
<sink_obj>17</sink_obj>
</item>
<item class_id_reference="20" object_id="_65">
<id>71</id>
<edge_type>1</edge_type>
<source_obj>13</source_obj>
<sink_obj>20</sink_obj>
</item>
<item class_id_reference="20" object_id="_66">
<id>73</id>
<edge_type>1</edge_type>
<source_obj>72</source_obj>
<sink_obj>20</sink_obj>
</item>
<item class_id_reference="20" object_id="_67">
<id>74</id>
<edge_type>1</edge_type>
<source_obj>20</source_obj>
<sink_obj>21</sink_obj>
</item>
<item class_id_reference="20" object_id="_68">
<id>75</id>
<edge_type>2</edge_type>
<source_obj>32</source_obj>
<sink_obj>21</sink_obj>
</item>
<item class_id_reference="20" object_id="_69">
<id>76</id>
<edge_type>2</edge_type>
<source_obj>35</source_obj>
<sink_obj>21</sink_obj>
</item>
<item class_id_reference="20" object_id="_70">
<id>77</id>
<edge_type>1</edge_type>
<source_obj>9</source_obj>
<sink_obj>33</sink_obj>
</item>
<item class_id_reference="20" object_id="_71">
<id>79</id>
<edge_type>1</edge_type>
<source_obj>4</source_obj>
<sink_obj>78</sink_obj>
</item>
<item class_id_reference="20" object_id="_72">
<id>80</id>
<edge_type>1</edge_type>
<source_obj>78</source_obj>
<sink_obj>33</sink_obj>
</item>
<item class_id_reference="20" object_id="_73">
<id>81</id>
<edge_type>2</edge_type>
<source_obj>44</source_obj>
<sink_obj>34</sink_obj>
</item>
<item class_id_reference="20" object_id="_74">
<id>82</id>
<edge_type>1</edge_type>
<source_obj>13</source_obj>
<sink_obj>23</sink_obj>
</item>
<item class_id_reference="20" object_id="_75">
<id>84</id>
<edge_type>1</edge_type>
<source_obj>83</source_obj>
<sink_obj>24</sink_obj>
</item>
<item class_id_reference="20" object_id="_76">
<id>85</id>
<edge_type>1</edge_type>
<source_obj>23</source_obj>
<sink_obj>24</sink_obj>
</item>
<item class_id_reference="20" object_id="_77">
<id>86</id>
<edge_type>1</edge_type>
<source_obj>24</source_obj>
<sink_obj>25</sink_obj>
</item>
<item class_id_reference="20" object_id="_78">
<id>87</id>
<edge_type>1</edge_type>
<source_obj>4</source_obj>
<sink_obj>26</sink_obj>
</item>
<item class_id_reference="20" object_id="_79">
<id>89</id>
<edge_type>1</edge_type>
<source_obj>88</source_obj>
<sink_obj>26</sink_obj>
</item>
<item class_id_reference="20" object_id="_80">
<id>90</id>
<edge_type>1</edge_type>
<source_obj>25</source_obj>
<sink_obj>26</sink_obj>
</item>
<item class_id_reference="20" object_id="_81">
<id>91</id>
<edge_type>1</edge_type>
<source_obj>26</source_obj>
<sink_obj>27</sink_obj>
</item>
<item class_id_reference="20" object_id="_82">
<id>92</id>
<edge_type>1</edge_type>
<source_obj>14</source_obj>
<sink_obj>28</sink_obj>
</item>
<item class_id_reference="20" object_id="_83">
<id>93</id>
<edge_type>1</edge_type>
<source_obj>4</source_obj>
<sink_obj>29</sink_obj>
</item>
<item class_id_reference="20" object_id="_84">
<id>94</id>
<edge_type>1</edge_type>
<source_obj>88</source_obj>
<sink_obj>29</sink_obj>
</item>
<item class_id_reference="20" object_id="_85">
<id>95</id>
<edge_type>1</edge_type>
<source_obj>28</source_obj>
<sink_obj>29</sink_obj>
</item>
<item class_id_reference="20" object_id="_86">
<id>96</id>
<edge_type>1</edge_type>
<source_obj>27</source_obj>
<sink_obj>30</sink_obj>
</item>
<item class_id_reference="20" object_id="_87">
<id>97</id>
<edge_type>1</edge_type>
<source_obj>29</source_obj>
<sink_obj>30</sink_obj>
</item>
<item class_id_reference="20" object_id="_88">
<id>98</id>
<edge_type>2</edge_type>
<source_obj>44</source_obj>
<sink_obj>31</sink_obj>
</item>
<item class_id_reference="20" object_id="_89">
<id>99</id>
<edge_type>1</edge_type>
<source_obj>9</source_obj>
<sink_obj>36</sink_obj>
</item>
<item class_id_reference="20" object_id="_90">
<id>100</id>
<edge_type>2</edge_type>
<source_obj>35</source_obj>
<sink_obj>36</sink_obj>
</item>
<item class_id_reference="20" object_id="_91">
<id>101</id>
<edge_type>1</edge_type>
<source_obj>27</source_obj>
<sink_obj>36</sink_obj>
</item>
<item class_id_reference="20" object_id="_92">
<id>102</id>
<edge_type>2</edge_type>
<source_obj>32</source_obj>
<sink_obj>36</sink_obj>
</item>
<item class_id_reference="20" object_id="_93">
<id>103</id>
<edge_type>1</edge_type>
<source_obj>14</source_obj>
<sink_obj>37</sink_obj>
</item>
<item class_id_reference="20" object_id="_94">
<id>104</id>
<edge_type>1</edge_type>
<source_obj>2</source_obj>
<sink_obj>38</sink_obj>
</item>
<item class_id_reference="20" object_id="_95">
<id>105</id>
<edge_type>1</edge_type>
<source_obj>88</source_obj>
<sink_obj>38</sink_obj>
</item>
<item class_id_reference="20" object_id="_96">
<id>106</id>
<edge_type>1</edge_type>
<source_obj>37</source_obj>
<sink_obj>38</sink_obj>
</item>
<item class_id_reference="20" object_id="_97">
<id>107</id>
<edge_type>1</edge_type>
<source_obj>38</source_obj>
<sink_obj>39</sink_obj>
</item>
<item class_id_reference="20" object_id="_98">
<id>108</id>
<edge_type>1</edge_type>
<source_obj>39</source_obj>
<sink_obj>40</sink_obj>
</item>
<item class_id_reference="20" object_id="_99">
<id>109</id>
<edge_type>1</edge_type>
<source_obj>36</source_obj>
<sink_obj>40</sink_obj>
</item>
<item class_id_reference="20" object_id="_100">
<id>110</id>
<edge_type>1</edge_type>
<source_obj>40</source_obj>
<sink_obj>41</sink_obj>
</item>
<item class_id_reference="20" object_id="_101">
<id>111</id>
<edge_type>1</edge_type>
<source_obj>12</source_obj>
<sink_obj>41</sink_obj>
</item>
<item class_id_reference="20" object_id="_102">
<id>112</id>
<edge_type>1</edge_type>
<source_obj>13</source_obj>
<sink_obj>42</sink_obj>
</item>
<item class_id_reference="20" object_id="_103">
<id>114</id>
<edge_type>1</edge_type>
<source_obj>113</source_obj>
<sink_obj>42</sink_obj>
</item>
<item class_id_reference="20" object_id="_104">
<id>115</id>
<edge_type>2</edge_type>
<source_obj>18</source_obj>
<sink_obj>43</sink_obj>
</item>
<item class_id_reference="20" object_id="_105">
<id>118</id>
<edge_type>1</edge_type>
<source_obj>1</source_obj>
<sink_obj>45</sink_obj>
</item>
<item class_id_reference="20" object_id="_106">
<id>119</id>
<edge_type>1</edge_type>
<source_obj>12</source_obj>
<sink_obj>45</sink_obj>
</item>
<item class_id_reference="20" object_id="_107">
<id>141</id>
<edge_type>2</edge_type>
<source_obj>11</source_obj>
<sink_obj>18</sink_obj>
</item>
<item class_id_reference="20" object_id="_108">
<id>142</id>
<edge_type>2</edge_type>
<source_obj>18</source_obj>
<sink_obj>47</sink_obj>
</item>
<item class_id_reference="20" object_id="_109">
<id>143</id>
<edge_type>2</edge_type>
<source_obj>18</source_obj>
<sink_obj>22</sink_obj>
</item>
<item class_id_reference="20" object_id="_110">
<id>144</id>
<edge_type>2</edge_type>
<source_obj>22</source_obj>
<sink_obj>35</sink_obj>
</item>
<item class_id_reference="20" object_id="_111">
<id>145</id>
<edge_type>2</edge_type>
<source_obj>22</source_obj>
<sink_obj>32</sink_obj>
</item>
<item class_id_reference="20" object_id="_112">
<id>146</id>
<edge_type>2</edge_type>
<source_obj>32</source_obj>
<sink_obj>44</sink_obj>
</item>
<item class_id_reference="20" object_id="_113">
<id>147</id>
<edge_type>2</edge_type>
<source_obj>35</source_obj>
<sink_obj>44</sink_obj>
</item>
<item class_id_reference="20" object_id="_114">
<id>148</id>
<edge_type>2</edge_type>
<source_obj>44</source_obj>
<sink_obj>18</sink_obj>
</item>
</edges>
</cdfg>
<cdfg_regions class_id="21" tracking_level="0" version="0">
<count>4</count>
<item_version>0</item_version>
<item class_id="22" tracking_level="1" version="0" object_id="_115">
<mId>1</mId>
<mTag>fir</mTag>
<mType>0</mType>
<sub_regions>
<count>3</count>
<item_version>0</item_version>
<item>2</item>
<item>3</item>
<item>4</item>
</sub_regions>
<basic_blocks>
<count>0</count>
<item_version>0</item_version>
</basic_blocks>
<mII>-1</mII>
<mDepth>-1</mDepth>
<mMinTripCount>-1</mMinTripCount>
<mMaxTripCount>-1</mMaxTripCount>
<mMinLatency>78</mMinLatency>
<mMaxLatency>-1</mMaxLatency>
<mIsDfPipe>0</mIsDfPipe>
<mDfPipe class_id="-1"/>
</item>
<item class_id_reference="22" object_id="_116">
<mId>2</mId>
<mTag>Entry</mTag>
<mType>0</mType>
<sub_regions>
<count>0</count>
<item_version>0</item_version>
</sub_regions>
<basic_blocks>
<count>1</count>
<item_version>0</item_version>
<item>11</item>
</basic_blocks>
<mII>-1</mII>
<mDepth>-1</mDepth>
<mMinTripCount>-1</mMinTripCount>
<mMaxTripCount>-1</mMaxTripCount>
<mMinLatency>0</mMinLatency>
<mMaxLatency>-1</mMaxLatency>
<mIsDfPipe>0</mIsDfPipe>
<mDfPipe class_id="-1"/>
</item>
<item class_id_reference="22" object_id="_117">
<mId>3</mId>
<mTag>Shift_Accum_Loop</mTag>
<mType>1</mType>
<sub_regions>
<count>0</count>
<item_version>0</item_version>
</sub_regions>
<basic_blocks>
<count>5</count>
<item_version>0</item_version>
<item>18</item>
<item>22</item>
<item>32</item>
<item>35</item>
<item>44</item>
</basic_blocks>
<mII>-1</mII>
<mDepth>-1</mDepth>
<mMinTripCount>11</mMinTripCount>
<mMaxTripCount>11</mMaxTripCount>
<mMinLatency>77</mMinLatency>
<mMaxLatency>-1</mMaxLatency>
<mIsDfPipe>0</mIsDfPipe>
<mDfPipe class_id="-1"/>
</item>
<item class_id_reference="22" object_id="_118">
<mId>4</mId>
<mTag>Return</mTag>
<mType>0</mType>
<sub_regions>
<count>0</count>
<item_version>0</item_version>
</sub_regions>
<basic_blocks>
<count>1</count>
<item_version>0</item_version>
<item>47</item>
</basic_blocks>
<mII>-1</mII>
<mDepth>-1</mDepth>
<mMinTripCount>-1</mMinTripCount>
<mMaxTripCount>-1</mMaxTripCount>
<mMinLatency>0</mMinLatency>
<mMaxLatency>-1</mMaxLatency>
<mIsDfPipe>0</mIsDfPipe>
<mDfPipe class_id="-1"/>
</item>
</cdfg_regions>
<fsm class_id="24" tracking_level="1" version="0" object_id="_119">
<states class_id="25" tracking_level="0" version="0">
<count>8</count>
<item_version>0</item_version>
<item class_id="26" tracking_level="1" version="0" object_id="_120">
<id>1</id>
<operations class_id="27" tracking_level="0" version="0">
<count>6</count>
<item_version>0</item_version>
<item class_id="28" tracking_level="1" version="0" object_id="_121">
<id>5</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_122">
<id>6</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_123">
<id>7</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_124">
<id>8</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_125">
<id>9</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_126">
<id>10</id>
<stage>1</stage>
<latency>1</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_127">
<id>2</id>
<operations>
<count>18</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_128">
<id>12</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_129">
<id>13</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_130">
<id>14</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_131">
<id>15</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_132">
<id>16</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_133">
<id>17</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_134">
<id>19</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_135">
<id>20</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_136">
<id>21</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_137">
<id>23</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_138">
<id>24</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_139">
<id>25</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_140">
<id>26</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_141">
<id>27</id>
<stage>2</stage>
<latency>2</latency>
</item>
<item class_id_reference="28" object_id="_142">
<id>33</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_143">
<id>34</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_144">
<id>45</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_145">
<id>46</id>
<stage>1</stage>
<latency>1</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_146">
<id>3</id>
<operations>
<count>9</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_147">
<id>27</id>
<stage>1</stage>
<latency>2</latency>
</item>
<item class_id_reference="28" object_id="_148">
<id>28</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_149">
<id>29</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_150">
<id>30</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_151">
<id>31</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_152">
<id>37</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_153">
<id>38</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_154">
<id>39</id>
<stage>2</stage>
<latency>2</latency>
</item>
<item class_id_reference="28" object_id="_155">
<id>42</id>
<stage>1</stage>
<latency>1</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_156">
<id>4</id>
<operations>
<count>2</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_157">
<id>36</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_158">
<id>39</id>
<stage>1</stage>
<latency>2</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_159">
<id>5</id>
<operations>
<count>1</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_160">
<id>40</id>
<stage>3</stage>
<latency>3</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_161">
<id>6</id>
<operations>
<count>1</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_162">
<id>40</id>
<stage>2</stage>
<latency>3</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_163">
<id>7</id>
<operations>
<count>1</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_164">
<id>40</id>
<stage>1</stage>
<latency>3</latency>
</item>
</operations>
</item>
<item class_id_reference="26" object_id="_165">
<id>8</id>
<operations>
<count>2</count>
<item_version>0</item_version>
<item class_id_reference="28" object_id="_166">
<id>41</id>
<stage>1</stage>
<latency>1</latency>
</item>
<item class_id_reference="28" object_id="_167">
<id>43</id>
<stage>1</stage>
<latency>1</latency>
</item>
</operations>
</item>
</states>
<transitions class_id="29" tracking_level="0" version="0">
<count>8</count>
<item_version>0</item_version>
<item class_id="30" tracking_level="1" version="0" object_id="_168">
<inState>1</inState>
<outState>2</outState>
<condition class_id="31" tracking_level="0" version="0">
<id>26</id>
<sop class_id="32" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="33" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_169">
<inState>2</inState>
<outState>3</outState>
<condition>
<id>27</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>1</count>
<item_version>0</item_version>
<item class_id="34" tracking_level="0" version="0">
<first class_id="35" tracking_level="0" version="0">
<first>15</first>
<second>0</second>
</first>
<second>1</second>
</item>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_170">
<inState>3</inState>
<outState>4</outState>
<condition>
<id>29</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_171">
<inState>4</inState>
<outState>5</outState>
<condition>
<id>32</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_172">
<inState>5</inState>
<outState>6</outState>
<condition>
<id>33</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_173">
<inState>6</inState>
<outState>7</outState>
<condition>
<id>34</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_174">
<inState>7</inState>
<outState>8</outState>
<condition>
<id>35</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
<item class_id_reference="30" object_id="_175">
<inState>8</inState>
<outState>2</outState>
<condition>
<id>37</id>
<sop>
<count>1</count>
<item_version>0</item_version>
<item>
<count>0</count>
<item_version>0</item_version>
</item>
</sop>
</condition>
</item>
</transitions>
</fsm>
<res class_id="36" tracking_level="1" version="0" object_id="_176">
<dp_component_resource class_id="37" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="38" tracking_level="0" version="0">
<first>fir_mul_32s_32s_32_3_U0 (fir_mul_32s_32s_32_3)</first>
<second class_id="39" tracking_level="0" version="0">
<count>3</count>
<item_version>0</item_version>
<item class_id="40" tracking_level="0" version="0">
<first>DSP48E</first>
<second>4</second>
</item>
<item>
<first>FF</first>
<second>0</second>
</item>
<item>
<first>LUT</first>
<second>0</second>
</item>
</second>
</item>
</dp_component_resource>
<dp_expression_resource>
<count>4</count>
<item_version>0</item_version>
<item>
<first>acc_1_fu_178_p2 ( + ) </first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0P0)</first>
<second>32</second>
</item>
<item>
<first>(1P1)</first>
<second>32</second>
</item>
<item>
<first>FF</first>
<second>0</second>
</item>
<item>
<first>LUT</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>i_1_fu_167_p2 ( + ) </first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0P0)</first>
<second>5</second>
</item>
<item>
<first>(1P1)</first>
<second>2</second>
</item>
<item>
<first>FF</first>
<second>0</second>
</item>
<item>
<first>LUT</first>
<second>5</second>
</item>
</second>
</item>
<item>
<first>tmp_1_fu_138_p2 ( icmp ) </first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0P0)</first>
<second>5</second>
</item>
<item>
<first>(1P1)</first>
<second>1</second>
</item>
<item>
<first>FF</first>
<second>0</second>
</item>
<item>
<first>LUT</first>
<second>2</second>
</item>
</second>
</item>
<item>
<first>tmp_2_fu_148_p2 ( + ) </first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0P0)</first>
<second>2</second>
</item>
<item>
<first>(1P1)</first>
<second>4</second>
</item>
<item>
<first>FF</first>
<second>0</second>
</item>
<item>
<first>LUT</first>
<second>4</second>
</item>
</second>
</item>
</dp_expression_resource>
<dp_fifo_resource>
<count>0</count>
<item_version>0</item_version>
</dp_fifo_resource>
<dp_memory_resource>
<count>1</count>
<item_version>0</item_version>
<item>
<first>shift_reg_U</first>
<second>
<count>7</count>
<item_version>0</item_version>
<item>
<first>(0Words)</first>
<second>11</second>
</item>
<item>
<first>(1Bits)</first>
<second>32</second>
</item>
<item>
<first>(2Banks)</first>
<second>1</second>
</item>
<item>
<first>(3W*Bits*Banks)</first>
<second>352</second>
</item>
<item>
<first>BRAM</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>64</second>
</item>
<item>
<first>LUT</first>
<second>6</second>
</item>
</second>
</item>
</dp_memory_resource>
<dp_multiplexer_resource>
<count>6</count>
<item_version>0</item_version>
<item>
<first>acc_reg_91</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>2</second>
</item>
<item>
<first>(1Bits)</first>
<second>32</second>
</item>
<item>
<first>(2Count)</first>
<second>64</second>
</item>
<item>
<first>LUT</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>ap_NS_fsm</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>9</second>
</item>
<item>
<first>(1Bits)</first>
<second>1</second>
</item>
<item>
<first>(2Count)</first>
<second>9</second>
</item>
<item>
<first>LUT</first>
<second>4</second>
</item>
</second>
</item>
<item>
<first>data1_reg_116</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>2</second>
</item>
<item>
<first>(1Bits)</first>
<second>32</second>
</item>
<item>
<first>(2Count)</first>
<second>64</second>
</item>
<item>
<first>LUT</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>i_reg_104</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>2</second>
</item>
<item>
<first>(1Bits)</first>
<second>5</second>
</item>
<item>
<first>(2Count)</first>
<second>10</second>
</item>
<item>
<first>LUT</first>
<second>5</second>
</item>
</second>
</item>
<item>
<first>shift_reg_address0</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>4</second>
</item>
<item>
<first>(1Bits)</first>
<second>4</second>
</item>
<item>
<first>(2Count)</first>
<second>16</second>
</item>
<item>
<first>LUT</first>
<second>4</second>
</item>
</second>
</item>
<item>
<first>shift_reg_d0</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>
<first>(0Size)</first>
<second>3</second>
</item>
<item>
<first>(1Bits)</first>
<second>32</second>
</item>
<item>
<first>(2Count)</first>
<second>96</second>
</item>
<item>
<first>LUT</first>
<second>32</second>
</item>
</second>
</item>
</dp_multiplexer_resource>
<dp_register_resource>
<count>9</count>
<item_version>0</item_version>
<item>
<first>acc_reg_91</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>32</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>ap_CS_fsm</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>8</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>8</second>
</item>
</second>
</item>
<item>
<first>c_load_reg_222</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>32</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>data1_reg_116</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>32</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>i_1_reg_217</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>5</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>5</second>
</item>
</second>
</item>
<item>
<first>i_cast_reg_189</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>32</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>32</second>
</item>
</second>
</item>
<item>
<first>i_reg_104</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>5</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>5</second>
</item>
</second>
</item>
<item>
<first>tmp_1_reg_198</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>1</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>1</second>
</item>
</second>
</item>
<item>
<first>tmp_6_reg_227</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>
<first>(Bits)</first>
<second>32</second>
</item>
<item>
<first>(Consts)</first>
<second>0</second>
</item>
<item>
<first>FF</first>
<second>32</second>
</item>
</second>
</item>
</dp_register_resource>
<dp_component_map class_id="41" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="42" tracking_level="0" version="0">
<first>fir_mul_32s_32s_32_3_U0 (fir_mul_32s_32s_32_3)</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>40</item>
</second>
</item>
</dp_component_map>
<dp_expression_map>
<count>4</count>
<item_version>0</item_version>
<item>
<first>acc_1_fu_178_p2 ( + ) </first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>41</item>
</second>
</item>
<item>
<first>i_1_fu_167_p2 ( + ) </first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
<item>
<first>tmp_1_fu_138_p2 ( icmp ) </first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>20</item>
</second>
</item>
<item>
<first>tmp_2_fu_148_p2 ( + ) </first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>24</item>
</second>
</item>
</dp_expression_map>
<dp_fifo_map>
<count>0</count>
<item_version>0</item_version>
</dp_fifo_map>
<dp_memory_map>
<count>1</count>
<item_version>0</item_version>
<item>
<first>shift_reg_U</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
</dp_memory_map>
</res>
<node_label_latency class_id="43" tracking_level="0" version="0">
<count>30</count>
<item_version>0</item_version>
<item class_id="44" tracking_level="0" version="0">
<first>9</first>
<second class_id="45" tracking_level="0" version="0">
<first>0</first>
<second>0</second>
</second>
</item>
<item>
<first>10</first>
<second>
<first>0</first>
<second>0</second>
</second>
</item>
<item>
<first>12</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>13</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>14</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>15</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>17</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>20</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>21</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>23</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>24</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>25</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>26</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>27</first>
<second>
<first>1</first>
<second>1</second>
</second>
</item>
<item>
<first>28</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>29</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>30</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>31</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>33</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>34</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>36</first>
<second>
<first>3</first>
<second>0</second>
</second>
</item>
<item>
<first>37</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>38</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>39</first>
<second>
<first>2</first>
<second>1</second>
</second>
</item>
<item>
<first>40</first>
<second>
<first>4</first>
<second>2</second>
</second>
</item>
<item>
<first>41</first>
<second>
<first>7</first>
<second>0</second>
</second>
</item>
<item>
<first>42</first>
<second>
<first>2</first>
<second>0</second>
</second>
</item>
<item>
<first>43</first>
<second>
<first>7</first>
<second>0</second>
</second>
</item>
<item>
<first>45</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
<item>
<first>46</first>
<second>
<first>1</first>
<second>0</second>
</second>
</item>
</node_label_latency>
<bblk_ent_exit class_id="46" tracking_level="0" version="0">
<count>7</count>
<item_version>0</item_version>
<item class_id="47" tracking_level="0" version="0">
<first>11</first>
<second class_id="48" tracking_level="0" version="0">
<first>0</first>
<second>0</second>
</second>
</item>
<item>
<first>18</first>
<second>
<first>1</first>
<second>1</second>
</second>
</item>
<item>
<first>22</first>
<second>
<first>1</first>
<second>1</second>
</second>
</item>
<item>
<first>32</first>
<second>
<first>1</first>
<second>2</second>
</second>
</item>
<item>
<first>35</first>
<second>
<first>1</first>
<second>1</second>
</second>
</item>
<item>
<first>44</first>
<second>
<first>2</first>
<second>7</second>
</second>
</item>
<item>
<first>47</first>
<second>
<first>1</first>
<second>1</second>
</second>
</item>
</bblk_ent_exit>
<regions class_id="49" tracking_level="0" version="0">
<count>0</count>
<item_version>0</item_version>
</regions>
<dp_fu_nodes class_id="50" tracking_level="0" version="0">
<count>21</count>
<item_version>0</item_version>
<item class_id="51" tracking_level="0" version="0">
<first>44</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>9</item>
</second>
</item>
<item>
<first>50</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>45</item>
</second>
</item>
<item>
<first>57</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>26</item>
</second>
</item>
<item>
<first>64</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>27</item>
<item>27</item>
<item>33</item>
<item>30</item>
</second>
</item>
<item>
<first>70</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>29</item>
</second>
</item>
<item>
<first>79</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>38</item>
</second>
</item>
<item>
<first>86</first>
<second>
<count>2</count>
<item_version>0</item_version>
<item>39</item>
<item>39</item>
</second>
</item>
<item>
<first>95</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>108</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
<item>
<first>119</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
<item>
<first>126</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>14</item>
</second>
</item>
<item>
<first>130</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>15</item>
</second>
</item>
<item>
<first>138</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>20</item>
</second>
</item>
<item>
<first>144</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>23</item>
</second>
</item>
<item>
<first>148</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>24</item>
</second>
</item>
<item>
<first>154</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>25</item>
</second>
</item>
<item>
<first>159</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>28</item>
</second>
</item>
<item>
<first>163</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>37</item>
</second>
</item>
<item>
<first>167</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
<item>
<first>173</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>40</item>
<item>40</item>
<item>40</item>
</second>
</item>
<item>
<first>178</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>41</item>
</second>
</item>
</dp_fu_nodes>
<dp_fu_nodes_expression class_id="53" tracking_level="0" version="0">
<count>16</count>
<item_version>0</item_version>
<item class_id="54" tracking_level="0" version="0">
<first>acc_1_fu_178</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>41</item>
</second>
</item>
<item>
<first>acc_phi_fu_95</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>c_addr_gep_fu_79</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>38</item>
</second>
</item>
<item>
<first>data1_phi_fu_119</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
<item>
<first>i_1_fu_167</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
<item>
<first>i_cast_fu_126</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>14</item>
</second>
</item>
<item>
<first>i_phi_fu_108</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
<item>
<first>shift_reg_addr_1_gep_fu_70</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>29</item>
</second>
</item>
<item>
<first>shift_reg_addr_gep_fu_57</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>26</item>
</second>
</item>
<item>
<first>tmp_1_fu_138</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>20</item>
</second>
</item>
<item>
<first>tmp_2_fu_148</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>24</item>
</second>
</item>
<item>
<first>tmp_3_fu_154</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>25</item>
</second>
</item>
<item>
<first>tmp_4_fu_159</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>28</item>
</second>
</item>
<item>
<first>tmp_5_fu_163</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>37</item>
</second>
</item>
<item>
<first>tmp_7_fu_144</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>23</item>
</second>
</item>
<item>
<first>tmp_fu_130</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>15</item>
</second>
</item>
</dp_fu_nodes_expression>
<dp_fu_nodes_module>
<count>1</count>
<item_version>0</item_version>
<item>
<first>grp_fu_173</first>
<second>
<count>3</count>
<item_version>0</item_version>
<item>40</item>
<item>40</item>
<item>40</item>
</second>
</item>
</dp_fu_nodes_module>
<dp_fu_nodes_io>
<count>2</count>
<item_version>0</item_version>
<item>
<first>stg_31_write_fu_50</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>45</item>
</second>
</item>
<item>
<first>x_read_read_fu_44</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>9</item>
</second>
</item>
</dp_fu_nodes_io>
<return_ports>
<count>0</count>
<item_version>0</item_version>
</return_ports>
<dp_mem_port_nodes class_id="55" tracking_level="0" version="0">
<count>2</count>
<item_version>0</item_version>
<item class_id="56" tracking_level="0" version="0">
<first class_id="57" tracking_level="0" version="0">
<first>c</first>
<second>0</second>
</first>
<second>
<count>2</count>
<item_version>0</item_version>
<item>39</item>
<item>39</item>
</second>
</item>
<item>
<first>
<first>shift_reg</first>
<second>0</second>
</first>
<second>
<count>4</count>
<item_version>0</item_version>
<item>27</item>
<item>27</item>
<item>33</item>
<item>30</item>
</second>
</item>
</dp_mem_port_nodes>
<dp_reg_nodes>
<count>13</count>
<item_version>0</item_version>
<item>
<first>91</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>104</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
<item>
<first>116</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
<item>
<first>183</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>9</item>
</second>
</item>
<item>
<first>189</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>14</item>
</second>
</item>
<item>
<first>198</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>20</item>
</second>
</item>
<item>
<first>202</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>26</item>
</second>
</item>
<item>
<first>207</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>27</item>
</second>
</item>
<item>
<first>212</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>38</item>
</second>
</item>
<item>
<first>217</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
<item>
<first>222</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>39</item>
</second>
</item>
<item>
<first>227</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>40</item>
</second>
</item>
<item>
<first>232</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>41</item>
</second>
</item>
</dp_reg_nodes>
<dp_regname_nodes>
<count>13</count>
<item_version>0</item_version>
<item>
<first>acc_1_reg_232</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>41</item>
</second>
</item>
<item>
<first>acc_reg_91</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>c_addr_reg_212</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>38</item>
</second>
</item>
<item>
<first>c_load_reg_222</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>39</item>
</second>
</item>
<item>
<first>data1_reg_116</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
<item>
<first>data_reg_207</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>27</item>
</second>
</item>
<item>
<first>i_1_reg_217</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>42</item>
</second>
</item>
<item>
<first>i_cast_reg_189</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>14</item>
</second>
</item>
<item>
<first>i_reg_104</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
<item>
<first>shift_reg_addr_reg_202</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>26</item>
</second>
</item>
<item>
<first>tmp_1_reg_198</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>20</item>
</second>
</item>
<item>
<first>tmp_6_reg_227</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>40</item>
</second>
</item>
<item>
<first>x_read_reg_183</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>9</item>
</second>
</item>
</dp_regname_nodes>
<dp_reg_phi>
<count>3</count>
<item_version>0</item_version>
<item>
<first>91</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>104</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
<item>
<first>116</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
</dp_reg_phi>
<dp_regname_phi>
<count>3</count>
<item_version>0</item_version>
<item>
<first>acc_reg_91</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>12</item>
</second>
</item>
<item>
<first>data1_reg_116</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>36</item>
</second>
</item>
<item>
<first>i_reg_104</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>13</item>
</second>
</item>
</dp_regname_phi>
<dp_port_io_nodes class_id="58" tracking_level="0" version="0">
<count>3</count>
<item_version>0</item_version>
<item class_id="59" tracking_level="0" version="0">
<first>c(p0)</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>load</first>
<second>
<count>2</count>
<item_version>0</item_version>
<item>39</item>
<item>39</item>
</second>
</item>
</second>
</item>
<item>
<first>x</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>read</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>9</item>
</second>
</item>
</second>
</item>
<item>
<first>y</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>
<first>write</first>
<second>
<count>1</count>
<item_version>0</item_version>
<item>45</item>
</second>
</item>
</second>
</item>
</dp_port_io_nodes>
<port2core class_id="60" tracking_level="0" version="0">
<count>1</count>
<item_version>0</item_version>
<item class_id="61" tracking_level="0" version="0">
<first>2</first>
<second>RAM</second>
</item>
</port2core>
<node2core>
<count>0</count>
<item_version>0</item_version>
</node2core>
</syndb>
</boost_serialization>
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
package AMF.DC.Point_Collections is
pragma Preelaborate;
end AMF.DC.Point_Collections;
|
pragma Warnings (Off);
pragma Style_Checks (Off);
package body Float_portable_binary_transfer is
inverse_scaling : constant Num := 1.0 / imposed_scaling;
-- We rely on Ada's attributes of floating - point types, RM : A.5.3
procedure Split (f : in Num; m : out Mantissa_type; e : out Exponent_type) is
begin
if imposed_mantissa then
m := Mantissa_type (imposed_scaling * Num'Fraction (f));
else
m := Mantissa_type (Num'Scaling (Num'Fraction (f), Num'Machine_Mantissa));
end if;
e := Num'Exponent (f);
end Split;
procedure Merge (m : in Mantissa_type; e : in Exponent_type; f : out Num) is
fraction : Num;
begin
if imposed_mantissa then
fraction := Num (m) * inverse_scaling;
else
fraction := Num'Scaling (Num (m), - Num'Machine_Mantissa);
end if;
-- We compose a float with the fraction and the exponent
f := Num'Compose (fraction, e);
end Merge;
-- Split / Merge in two parts --
machine_half_mantissa : constant Integer := 1 + Num'Machine_Mantissa/2;
procedure Split (f : in Num; m1, m2 : out Mantissa_type; e : out Exponent_type) is
f1, f2 : Num;
begin
if imposed_mantissa then
f1 := imposed_scaling * Num'Fraction (f);
else
f1 := Num'Scaling (Num'Fraction (f), machine_half_mantissa);
end if;
m1 := Mantissa_type (f1);
f1 := f1 - Num (m1);
if imposed_mantissa then
f2 := imposed_scaling * f1;
else
f2 := Num'Scaling (f1, machine_half_mantissa);
end if;
m2 := Mantissa_type (f2);
e := Num'Exponent (f);
end Split;
procedure Merge (m1, m2 : in Mantissa_type; e : in Exponent_type; f : out Num) is
fraction : Num;
begin
if imposed_mantissa then
fraction := (Num (m1) + Num (m2) * inverse_scaling) * inverse_scaling;
else
fraction := Num'Scaling (Num (m1) + Num'Scaling (Num (m2), - machine_half_mantissa), - machine_half_mantissa);
end if;
-- We compose a float with the fraction and the exponent
f := Num'Compose (fraction, e);
end Merge;
end Float_portable_binary_transfer;
|
-- Copyright (c) 2020-2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
with Ada.Containers.Generic_Array_Sort;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with GNAT.String_Split; use GNAT.String_Split;
with Tcl.Ada; use Tcl.Ada;
with Tcl.Tk.Ada; use Tcl.Tk.Ada;
with Tcl.Tk.Ada.Grid;
with Tcl.Tk.Ada.Widgets; use Tcl.Tk.Ada.Widgets;
with Tcl.Tk.Ada.Widgets.Canvas; use Tcl.Tk.Ada.Widgets.Canvas;
with Tcl.Tk.Ada.Widgets.Menu; use Tcl.Tk.Ada.Widgets.Menu;
with Tcl.Tk.Ada.Widgets.Toplevel; use Tcl.Tk.Ada.Widgets.Toplevel;
with Tcl.Tk.Ada.Widgets.Toplevel.MainWindow;
use Tcl.Tk.Ada.Widgets.Toplevel.MainWindow;
with Tcl.Tk.Ada.Widgets.TtkEntry; use Tcl.Tk.Ada.Widgets.TtkEntry;
with Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox;
use Tcl.Tk.Ada.Widgets.TtkEntry.TtkComboBox;
with Tcl.Tk.Ada.Widgets.TtkFrame; use Tcl.Tk.Ada.Widgets.TtkFrame;
with Tcl.Tk.Ada.Widgets.TtkLabel; use Tcl.Tk.Ada.Widgets.TtkLabel;
with Tcl.Tk.Ada.Widgets.TtkScrollbar; use Tcl.Tk.Ada.Widgets.TtkScrollbar;
with Tcl.Tk.Ada.Winfo; use Tcl.Tk.Ada.Winfo;
with Tcl.Tklib.Ada.Tooltip; use Tcl.Tklib.Ada.Tooltip;
with Bases; use Bases;
with BasesTypes; use BasesTypes;
with Config; use Config;
with CoreUI; use CoreUI;
with Dialogs; use Dialogs;
with Factions; use Factions;
with Game; use Game;
with Maps; use Maps;
with Messages; use Messages;
with Ships; use Ships;
with Table; use Table;
with Utils; use Utils;
with Utils.UI; use Utils.UI;
package body Knowledge.Bases is
-- ****iv* KBases/KBases.BasesTable
-- FUNCTION
-- Table with info about the know bases
-- SOURCE
BasesTable: Table_Widget (7);
-- ****
-- ****iv* KBases/KBases.Modules_Indexes
-- FUNCTION
-- Indexes of the player ship modules
-- SOURCE
Bases_Indexes: Positive_Container.Vector;
-- ****
-- ****if* KBases/KBases.Get_Reputation_Text
-- FUNCTION
-- Get the name of the reputation level in the selected base
-- PARAMETERS
-- Reputation_Level - The numerical level of reputation in a base
-- RESULT
-- The name of the reputation level in the selected base
-- SOURCE
function Get_Reputation_Text(Reputation_Level: Integer) return String is
-- ****
begin
case Reputation_Level is
when -100 .. -75 =>
return "Hated";
when -74 .. -50 =>
return "Outlaw";
when -49 .. -25 =>
return "Hostile";
when -24 .. -1 =>
return "Unfriendly";
when 0 =>
return "Unknown";
when 1 .. 25 =>
return "Visitor";
when 26 .. 50 =>
return "Trader";
when 51 .. 75 =>
return "Friend";
when 76 .. 100 =>
return "Well known";
when others =>
return "";
end case;
end Get_Reputation_Text;
procedure UpdateBasesList(BaseName: String := ""; Page: Positive := 1) is
BasesCanvas: constant Tk_Canvas :=
Get_Widget(Main_Paned & ".knowledgeframe.bases.canvas");
BasesFrame: constant Ttk_Frame := Get_Widget(BasesCanvas & ".frame");
SearchEntry: constant Ttk_Entry :=
Get_Widget(BasesFrame & ".options.search");
Tokens: Slice_Set;
Rows: Natural := 0;
ComboBox: Ttk_ComboBox := Get_Widget(BasesFrame & ".options.types");
BasesType, BasesOwner, BasesStatus: Unbounded_String;
Start_Row: constant Positive :=
((Page - 1) * Game_Settings.Lists_Limit) + 1;
Current_Row: Positive := 1;
begin
Create(Tokens, Tcl.Tk.Ada.Grid.Grid_Size(BasesFrame), " ");
Rows := Natural'Value(Slice(Tokens, 2));
if BasesTable.Row > 1 then
ClearTable(BasesTable);
end if;
Delete_Widgets(2, Rows - 1, BasesFrame);
BasesTable :=
CreateTable
(Widget_Image(BasesFrame),
(To_Unbounded_String("Name"), To_Unbounded_String("Distance"),
To_Unbounded_String("Population"), To_Unbounded_String("Size"),
To_Unbounded_String("Owner"), To_Unbounded_String("Type"),
To_Unbounded_String("Reputation")),
Get_Widget(".gameframe.paned.knowledgeframe.bases.scrolly"),
"SortKnownBases {" & BaseName & "}",
"Press mouse button to sort the bases.");
if Bases_Indexes.Is_Empty then
for I in Sky_Bases'Range loop
Bases_Indexes.Append(I);
end loop;
end if;
if BaseName'Length = 0 then
configure(SearchEntry, "-validatecommand {}");
Delete(SearchEntry, "0", "end");
configure(SearchEntry, "-validatecommand {ShowBases %P}");
end if;
BasesType := To_Unbounded_String(Get(ComboBox));
ComboBox.Name := New_String(BasesFrame & ".options.status");
BasesStatus := To_Unbounded_String(Get(ComboBox));
ComboBox.Name := New_String(BasesFrame & ".options.owner");
BasesOwner := To_Unbounded_String(Get(ComboBox));
Rows := 0;
Load_Bases_Loop :
for I of Bases_Indexes loop
if not Sky_Bases(I).Known then
goto End_Of_Loop;
end if;
if BaseName'Length > 0
and then
Index
(To_Lower(To_String(Sky_Bases(I).Name)), To_Lower(BaseName),
1) =
0 then
goto End_Of_Loop;
end if;
if BasesStatus = To_Unbounded_String("Only not visited") and
Sky_Bases(I).Visited.Year /= 0 then
goto End_Of_Loop;
end if;
if BasesStatus = To_Unbounded_String("Only visited") and
Sky_Bases(I).Visited.Year = 0 then
goto End_Of_Loop;
end if;
if Sky_Bases(I).Visited.Year = 0
and then
(BasesType /= To_Unbounded_String("Any") or
BasesOwner /= To_Unbounded_String("Any")) then
goto End_Of_Loop;
end if;
if Current_Row < Start_Row then
Current_Row := Current_Row + 1;
goto End_Of_Loop;
end if;
AddButton
(BasesTable, To_String(Sky_Bases(I).Name),
"Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 1);
AddButton
(BasesTable,
Natural'Image
(CountDistance(Sky_Bases(I).Sky_X, Sky_Bases(I).Sky_Y)),
"The distance to the base", "ShowBasesMenu" & Positive'Image(I),
2);
if Sky_Bases(I).Visited.Year > 0 then
AddButton
(BasesTable,
(case Sky_Bases(I).Population is when 0 => "empty",
when 1 .. 150 => "small", when 151 .. 299 => "medium",
when others => "large"),
"The population size of the base",
"ShowBasesMenu" & Positive'Image(I), 3);
AddButton
(BasesTable, To_Lower(Bases_Size'Image(Sky_Bases(I).Size)),
"The size of the base", "ShowBasesMenu" & Positive'Image(I), 4);
AddButton
(BasesTable, To_String(Factions_List(Sky_Bases(I).Owner).Name),
"The faction which own the base",
"ShowBasesMenu" & Positive'Image(I), 5);
AddButton
(BasesTable,
To_String(Bases_Types_List(Sky_Bases(I).Base_Type).Name),
"The type of the base", "ShowBasesMenu" & Positive'Image(I), 6);
AddButton
(BasesTable, Get_Reputation_Text(Sky_Bases(I).Reputation(1)),
"Your reputation in the base",
"ShowBasesMenu" & Positive'Image(I), 7, True);
else
AddButton
(BasesTable, "not", "Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 3);
AddButton
(BasesTable, "", "Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 4);
AddButton
(BasesTable, "visited", "Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 5);
AddButton
(BasesTable, "", "Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 6);
AddButton
(BasesTable, "yet", "Show available base's options",
"ShowBasesMenu" & Positive'Image(I), 7, True);
end if;
Rows := Rows + 1;
exit Load_Bases_Loop when Rows = Game_Settings.Lists_Limit + 1 and
I < Sky_Bases'Last;
<<End_Of_Loop>>
end loop Load_Bases_Loop;
if Page > 1 then
AddPagination
(BasesTable,
"ShowBases {" & BaseName & "}" & Positive'Image(Page - 1),
(if BasesTable.Row < Game_Settings.Lists_Limit + 1 then ""
else "ShowBases {" & BaseName & "}" & Positive'Image(Page + 1)));
elsif BasesTable.Row = Game_Settings.Lists_Limit + 1 then
AddPagination
(BasesTable, "",
"ShowBases {" & BaseName & "}" & Positive'Image(Page + 1));
end if;
UpdateTable
(BasesTable, (if Focus = Widget_Image(SearchEntry) then False));
Xview_Move_To(BasesCanvas, "0.0");
Yview_Move_To(BasesCanvas, "0.0");
Tcl_Eval(Get_Context, "update");
configure
(BasesCanvas, "-scrollregion [list " & BBox(BasesCanvas, "all") & "]");
end UpdateBasesList;
-- ****o* KBases/KBases.Show_Bases_Command
-- FUNCTION
-- Show the list of known bases to a player
-- PARAMETERS
-- ClientData - Custom data send to the command. Unused
-- Interp - Tcl interpreter in which command was executed.
-- Argc - Number of arguments passed to the command.
-- Argv - Values of arguments passed to the command.
-- RESULT
-- This function always return TCL_OK
-- COMMANDS
-- ShowBases ?basename? ?page?
-- Basename parameter is a string which will be looking for in the bases
-- names, page parameter is a index of page from which starts showing
-- bases.
-- SOURCE
function Show_Bases_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Show_Bases_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(ClientData);
begin
case Argc is
when 3 =>
UpdateBasesList
(CArgv.Arg(Argv, 1), Positive'Value(CArgv.Arg(Argv, 2)));
when 2 =>
UpdateBasesList(CArgv.Arg(Argv, 1));
when others =>
UpdateBasesList;
end case;
Tcl_SetResult(Interp, "1");
return TCL_OK;
end Show_Bases_Command;
-- ****if* KBases/KBases.Show_Bases_Menu_Command
-- FUNCTION
-- Show the menu with available the selected base options
-- PARAMETERS
-- ClientData - Custom data send to the command. Unused
-- Interp - Tcl interpreter in which command was executed.
-- Argc - Number of arguments passed to the command. Unused
-- Argv - Values of arguments passed to the command.
-- RESULT
-- This function always return TCL_OK
-- COMMANDS
-- ShowBaseMenu baseindex
-- BaseIndex is the index of the base's menu to show
-- SOURCE
function Show_Bases_Menu_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Show_Bases_Menu_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(ClientData, Argc);
BaseMenu: Tk_Menu := Get_Widget(".baseslistmenu", Interp);
BaseIndex: constant Positive := Positive'Value(CArgv.Arg(Argv, 1));
begin
if Winfo_Get(BaseMenu, "exists") = "0" then
BaseMenu := Create(".baseslistmenu", "-tearoff false");
end if;
Delete(BaseMenu, "0", "end");
Menu.Add
(BaseMenu, "command",
"-label {Show the base on map} -command {ShowOnMap" &
Map_X_Range'Image(Sky_Bases(BaseIndex).Sky_X) &
Map_Y_Range'Image(Sky_Bases(BaseIndex).Sky_Y) & "}");
Menu.Add
(BaseMenu, "command",
"-label {Set the base as destination for the ship} -command {SetDestination2 " &
Map_X_Range'Image(Sky_Bases(BaseIndex).Sky_X) &
Map_Y_Range'Image(Sky_Bases(BaseIndex).Sky_Y) & "}");
if Sky_Bases(BaseIndex).Visited.Year > 0 then
Menu.Add
(BaseMenu, "command",
"-label {Show more information about the base} -command {ShowBaseInfo " &
CArgv.Arg(Argv, 1) & "}");
end if;
Tk_Popup
(BaseMenu, Winfo_Get(Get_Main_Window(Interp), "pointerx"),
Winfo_Get(Get_Main_Window(Interp), "pointery"));
return TCL_OK;
end Show_Bases_Menu_Command;
-- ****o* KBases/KBases.Show_Base_Info_Command
-- FUNCTION
-- Show information about the selected base
-- PARAMETERS
-- ClientData - Custom data send to the command. Unused
-- Interp - Tcl interpreter in which command was executed. Unused
-- Argc - Number of arguments passed to the command. Unused
-- Argv - Values of arguments passed to the command.
-- RESULT
-- This function always return TCL_OK
-- COMMANDS
-- ShowBaseInfo baseindex
-- BaseIndex is the index of the base to show
-- SOURCE
function Show_Base_Info_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Show_Base_Info_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(ClientData, Interp, Argc);
BaseIndex: constant Positive := Positive'Value(CArgv.Arg(Argv, 1));
BaseDialog: constant Ttk_Frame :=
Create_Dialog
(Name => ".basedialog",
Title => To_String(Sky_Bases(BaseIndex).Name), Columns => 2);
BaseLabel: Ttk_Label;
BaseInfo: Unbounded_String;
procedure SetReputationText(ReputationText: String) is
ReputationBar: constant Ttk_Frame :=
Create
(BaseDialog & ".reputation",
"-width 204 -height 24 -style ProgressBar.TFrame");
ReputationLabel: constant Ttk_Label :=
Create(BaseDialog & ".reputationlabel");
ReputationProgress: constant Ttk_Frame :=
Create(ReputationBar & ".reputation", "-height 18");
begin
if Sky_Bases(BaseIndex).Reputation(1) = 0 then
configure(ReputationLabel, "-text {Reputation: Unknown}");
else
configure(ReputationLabel, "-text {Reputation:}");
Tcl.Tk.Ada.Grid.Grid(ReputationBar, "-row 2 -column 1 -padx 5");
Tcl.Tk.Ada.Grid.Grid_Propagate(ReputationBar, "off");
configure
(ReputationProgress,
"-width" &
Positive'Image(abs (Sky_Bases(BaseIndex).Reputation(1))));
if Sky_Bases(BaseIndex).Reputation(1) > 0 then
configure(ReputationProgress, "-style GreenProgressBar.TFrame");
Tcl.Tk.Ada.Grid.Grid
(ReputationProgress, "-padx {100 0} -pady 3");
else
configure(ReputationProgress, "-style RedProgressBar.TFrame");
Tcl.Tk.Ada.Grid.Grid
(ReputationProgress,
"-padx {" &
Trim
(Positive'Image(100 + Sky_Bases(BaseIndex).Reputation(1)),
Left) &
" 0} -pady 3");
end if;
Add(ReputationBar, ReputationText);
end if;
Tcl.Tk.Ada.Grid.Grid(ReputationLabel, "-row 2 -sticky w -padx {5 0}");
end SetReputationText;
begin
BaseInfo :=
To_Unbounded_String
("Coordinates X:" & Positive'Image(Sky_Bases(BaseIndex).Sky_X) &
" Y:" & Positive'Image(Sky_Bases(BaseIndex).Sky_Y));
Append
(BaseInfo,
LF & "Last visited: " & FormatedTime(Sky_Bases(BaseIndex).Visited));
declare
TimeDiff: Integer;
begin
if Sky_Bases(BaseIndex).Population > 0 and
Sky_Bases(BaseIndex).Reputation(1) > -25 then
TimeDiff :=
30 - Days_Difference(Sky_Bases(BaseIndex).Recruit_Date);
if TimeDiff > 0 then
Append
(BaseInfo,
LF & "New recruits available in" & Natural'Image(TimeDiff) &
" days.");
else
Append(BaseInfo, LF & "New recruits available now.");
end if;
else
Append
(BaseInfo, LF & "You can't recruit crew members at this base.");
end if;
if Sky_Bases(BaseIndex).Population > 0 and
Sky_Bases(BaseIndex).Reputation(1) > -25 then
TimeDiff := Days_Difference(Sky_Bases(BaseIndex).Asked_For_Events);
if TimeDiff < 7 then
Append
(BaseInfo,
LF & "You asked for events" & Natural'Image(TimeDiff) &
" days ago.");
else
Append(BaseInfo, LF & "You can ask for events again.");
end if;
else
Append(BaseInfo, LF & "You can't ask for events at this base.");
end if;
if Sky_Bases(BaseIndex).Population > 0 and
Sky_Bases(BaseIndex).Reputation(1) > -1 then
TimeDiff :=
7 - Days_Difference(Sky_Bases(BaseIndex).Missions_Date);
if TimeDiff > 0 then
Append
(BaseInfo,
LF & "New missions available in" & Natural'Image(TimeDiff) &
" days.");
else
Append(BaseInfo, LF & "New missions available now.");
end if;
else
Append(BaseInfo, LF & "You can't take missions at this base.");
end if;
end;
SetReputationText
(Get_Reputation_Text(Sky_Bases(BaseIndex).Reputation(1)));
if BaseIndex = Player_Ship.Home_Base then
Append(BaseInfo, LF & "It is your home base.");
end if;
BaseLabel :=
Create
(BaseDialog & ".info",
"-text {" & To_String(BaseInfo) & "} -wraplength 400");
Tcl.Tk.Ada.Grid.Grid
(BaseLabel, "-row 1 -columnspan 2 -padx 5 -pady {5 0} -sticky w");
Add_Close_Button
(BaseDialog & ".button", "Close", "CloseDialog " & BaseDialog, 2);
Show_Dialog(BaseDialog);
return TCL_OK;
end Show_Base_Info_Command;
-- ****it* KBases/KBases.Bases_Sort_Orders
-- FUNCTION
-- Sorting orders for the known bases list
-- OPTIONS
-- NAMEASC - Sort bases by name ascending
-- NAMEDESC - Sort bases by name descending
-- DISTANCEASC - Sort bases by distance ascending
-- DISTANCEDESC - Sort bases by distance descending
-- POPULATIONASC - Sort bases by population ascending
-- POPULATIONDESC - Sort bases by population descending
-- SIZEASC - Sort bases by size ascending
-- SIZEDESC - Sort bases by size descending
-- OWNERASC - Sort bases by owner ascending
-- OWNERDESC - Sort bases by owner descending
-- TYPEASC - Sort bases by type ascending
-- TYPEDESC - Sort bases by type descending
-- REPUTATIONASC - Sort bases by reputation ascending
-- REPUTATIONDESC - Sort bases by reputation descending
-- NONE - No sorting bases (default)
-- HISTORY
-- 6.4 - Added
-- SOURCE
type Bases_Sort_Orders is
(NAMEASC, NAMEDESC, DISTANCEASC, DISTANCEDESC, POPULATIONASC,
POPULATIONDESC, SIZEASC, SIZEDESC, OWNERASC, OWNERDESC, TYPEASC,
TYPEDESC, REPUTATIONASC, REPUTATIONDESC, NONE) with
Default_Value => NONE;
-- ****
-- ****id* KBases/KBases.Default_Bases_Sort_Order
-- FUNCTION
-- Default sorting order for the list of known bases
-- HISTORY
-- 6.4 - Added
-- SOURCE
Default_Bases_Sort_Order: constant Bases_Sort_Orders := NONE;
-- ****
-- ****iv* KBases/KBases.Bases_Sort_Order
-- FUNCTION
-- The current sorting order for known bases list
-- HISTORY
-- 6.4 - Added
-- SOURCE
Bases_Sort_Order: Bases_Sort_Orders := Default_Bases_Sort_Order;
-- ****
-- ****o* KBases/KBases.Sort_Bases_Command
-- FUNCTION
-- Sort the list of known bases
-- PARAMETERS
-- ClientData - Custom data send to the command. Unused
-- Interp - Tcl interpreter in which command was executed. Unused
-- Argc - Number of arguments passed to the command. Unused
-- Argv - Values of arguments passed to the command.
-- RESULT
-- This function always return TCL_OK
-- COMMANDS
-- SortKnownBases x
-- X is X axis coordinate where the player clicked the mouse button
-- SOURCE
function Sort_Bases_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Sort_Bases_Command
(ClientData: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(ClientData, Interp, Argc);
Column: constant Positive :=
Get_Column_Number(BasesTable, Natural'Value(CArgv.Arg(Argv, 2)));
type Local_Base_Data is record
Name: Unbounded_String;
Distance: Natural;
Population: Integer;
Size: Bases_Size;
Owner: Unbounded_String;
Base_Type: Unbounded_String;
Reputation: Integer;
Id: Positive;
end record;
type Bases_Array is array(Positive range <>) of Local_Base_Data;
Local_Bases: Bases_Array (Bases_Range);
function "<"(Left, Right: Local_Base_Data) return Boolean is
begin
if Bases_Sort_Order = NAMEASC and then Left.Name < Right.Name then
return True;
end if;
if Bases_Sort_Order = NAMEDESC and then Left.Name > Right.Name then
return True;
end if;
if Bases_Sort_Order = DISTANCEASC
and then Left.Distance < Right.Distance then
return True;
end if;
if Bases_Sort_Order = DISTANCEDESC
and then Left.Distance > Right.Distance then
return True;
end if;
if Bases_Sort_Order = POPULATIONASC
and then Left.Population < Right.Population then
return True;
end if;
if Bases_Sort_Order = POPULATIONDESC
and then Left.Population > Right.Population then
return True;
end if;
if Bases_Sort_Order = SIZEASC and then Left.Size < Right.Size then
return True;
end if;
if Bases_Sort_Order = SIZEDESC and then Left.Size > Right.Size then
return True;
end if;
if Bases_Sort_Order = OWNERASC and then Left.Owner < Right.Owner then
return True;
end if;
if Bases_Sort_Order = OWNERDESC and then Left.Owner > Right.Owner then
return True;
end if;
if Bases_Sort_Order = TYPEASC
and then Left.Base_Type < Right.Base_Type then
return True;
end if;
if Bases_Sort_Order = TYPEDESC
and then Left.Base_Type > Right.Base_Type then
return True;
end if;
if Bases_Sort_Order = REPUTATIONASC
and then Left.Reputation < Right.Reputation then
return True;
end if;
if Bases_Sort_Order = REPUTATIONDESC
and then Left.Reputation > Right.Reputation then
return True;
end if;
return False;
end "<";
procedure Sort_Bases is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive, Element_Type => Local_Base_Data,
Array_Type => Bases_Array);
begin
case Column is
when 1 =>
if Bases_Sort_Order = NAMEASC then
Bases_Sort_Order := NAMEDESC;
else
Bases_Sort_Order := NAMEASC;
end if;
when 2 =>
if Bases_Sort_Order = DISTANCEASC then
Bases_Sort_Order := DISTANCEDESC;
else
Bases_Sort_Order := DISTANCEASC;
end if;
when 3 =>
if Bases_Sort_Order = POPULATIONASC then
Bases_Sort_Order := POPULATIONDESC;
else
Bases_Sort_Order := POPULATIONASC;
end if;
when 4 =>
if Bases_Sort_Order = SIZEASC then
Bases_Sort_Order := SIZEDESC;
else
Bases_Sort_Order := SIZEASC;
end if;
when 5 =>
if Bases_Sort_Order = OWNERASC then
Bases_Sort_Order := OWNERDESC;
else
Bases_Sort_Order := OWNERASC;
end if;
when 6 =>
if Bases_Sort_Order = TYPEASC then
Bases_Sort_Order := TYPEDESC;
else
Bases_Sort_Order := TYPEASC;
end if;
when 7 =>
if Bases_Sort_Order = REPUTATIONASC then
Bases_Sort_Order := REPUTATIONDESC;
else
Bases_Sort_Order := REPUTATIONASC;
end if;
when others =>
null;
end case;
if Bases_Sort_Order = NONE then
return TCL_OK;
end if;
for I in Sky_Bases'Range loop
Local_Bases(I) :=
(Name => Sky_Bases(I).Name,
Distance => CountDistance(Sky_Bases(I).Sky_X, Sky_Bases(I).Sky_Y),
Population =>
(if Sky_Bases(I).Visited = (others => 0) then -1
else Sky_Bases(I).Population),
Size =>
(if Sky_Bases(I).Visited = (others => 0) then UNKNOWN
else Sky_Bases(I).Size),
Owner =>
(if Sky_Bases(I).Visited = (others => 0) then
Null_Unbounded_String
else Sky_Bases(I).Owner),
Base_Type =>
(if Sky_Bases(I).Visited = (others => 0) then
Null_Unbounded_String
else Sky_Bases(I).Base_Type),
Reputation =>
(if Sky_Bases(I).Visited = (others => 0) then 200
else Sky_Bases(I).Reputation(1)),
Id => I);
end loop;
Sort_Bases(Local_Bases);
Bases_Indexes.Clear;
for Base of Local_Bases loop
Bases_Indexes.Append(Base.Id);
end loop;
UpdateBasesList(CArgv.Arg(Argv, 1));
return TCL_OK;
end Sort_Bases_Command;
procedure AddCommands is
begin
Add_Command("ShowBases", Show_Bases_Command'Access);
Add_Command("ShowBasesMenu", Show_Bases_Menu_Command'Access);
Add_Command("ShowBaseInfo", Show_Base_Info_Command'Access);
Add_Command("SortKnownBases", Sort_Bases_Command'Access);
end AddCommands;
end Knowledge.Bases;
|
with Ada.Command_Line;
with Ada.Text_IO;
with GNAT.Command_Line;
with GNAT.OS_Lib;
with GNAT.Strings;
with Asis_Adapter.Tool;
procedure Run_Parser_Adapter is
package ACL renames Ada.Command_Line;
package GCL renames GNAT.Command_Line;
type Options_Record is record -- Initialized
Config : GCL.Command_Line_Configuration; -- Initialized
Debug : aliased Boolean := False;
File_Name : aliased GNAT.Strings.String_Access; -- Initialized
GNAT_Home : aliased GNAT.Strings.String_Access; -- Initialized
AsisArgs : aliased GNAT.Strings.String_Access; -- Initialized
Output_Dir : aliased GNAT.Strings.String_Access; -- Initialized
Process_Predefined_Units
: aliased Boolean := False;
Process_Implementation_Units
: aliased Boolean := False;
end record;
Options : aliased Options_Record; -- Initialized
Tool : Asis_Adapter.Tool.Class; -- Initialized
procedure Log (Message : in String; Debug : in Boolean) is
begin
if Debug then
Ada.Text_Io.Put_Line ("Run_Asis_Adapter: " & Message);
end if;
end;
procedure Get_Options is
begin
GCL.Define_Switch (Options.Config, Options.Debug'Access,
"-d", Long_Switch => "--debug",
Help => "Output debug information");
GCL.Define_Switch (Options.Config, Options.File_Name'Access,
"-f:", Long_Switch => "--file=",
Help => "File to process");
GCL.Define_Switch (Options.Config, Options.Gnat_Home'Access,
"-g:", Long_Switch => "--gnat_home=",
Help => "GNAT home directory");
GCL.Define_Switch (Options.Config, Options.AsisArgs'Access,
"-a:", Long_Switch => "--asis_arg=",
Help => "ASIS Argument");
GCL.Define_Switch (Options.Config, Options.Output_Dir'Access,
"-o:", Long_Switch => "--output_dir=",
Help => "Output directory");
GCL.Define_Switch (Options.Config, Options.Process_Predefined_Units'Access,
"-p", Long_Switch => "--process_predefined_units",
Help =>"Process Ada predefined language environment units");
GCL.Define_Switch (Options.Config, Options.Process_Implementation_Units'Access,
"-i", Long_Switch => "--process_implementation_units",
Help =>"Process implementation specific library units");
GCL.Getopt (Options.Config);
exception
when X : GNAT.Command_Line.Exit_From_Command_Line =>
Log ("*** GNAT.Command_Line raised Exit_From_Command_Line. Program will exit now.", Options.Debug);
raise;
end Get_Options;
procedure asis_adapterinit;
pragma Import (C, asis_adapterinit);
procedure asis_adapterfinal;
pragma Import (C, asis_adapterfinal);
begin
Get_Options;
Log ("BEGIN", Options.Debug);
asis_adapterinit;
Tool.Process
(File_Name => Options.File_Name.all,
Output_Dir => Options.Output_Dir.all,
GNAT_Home => Options.GNAT_Home.all,
AsisArgs => Options.AsisArgs.all,
Process_Predefined_Units => Options.Process_Predefined_Units,
Process_Implementation_Units => Options.Process_Implementation_Units,
Debug => Options.Debug);
asis_adapterfinal;
Log ("END", Options.Debug);
end Run_Parser_Adapter;
|
-----------------------------------------------------------------------
-- gen-commands-info -- Collect and give information about the project
-- Copyright (C) 2011, 2012, 2013, 2014 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Text_IO;
with Ada.Directories;
with Gen.Utils;
with Gen.Utils.GNAT;
with Gen.Model.Projects;
with Util.Strings.Sets;
with Util.Files;
package body Gen.Commands.Info is
-- ------------------------------
-- Execute the command with the arguments.
-- ------------------------------
procedure Execute (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd);
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector);
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean);
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition);
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition);
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count);
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition);
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector);
List : Gen.Utils.String_List.Vector;
Names : Util.Strings.Sets.Set;
procedure Collect_Directories (List : in Gen.Utils.String_List.Vector;
Result : out Gen.Utils.String_List.Vector) is
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String);
procedure Add_Model_Dir (Base_Dir : in String;
Dir : in String) is
Path : constant String := Util.Files.Compose (Base_Dir, Dir);
begin
if not Result.Contains (Path)
and then Ada.Directories.Exists (Path) then
Result.Append (Path);
end if;
end Add_Model_Dir;
Iter : Gen.Utils.String_List.Cursor := List.First;
begin
while Gen.Utils.String_List.Has_Element (Iter) loop
declare
Path : constant String := Gen.Utils.String_List.Element (Iter);
Dir : constant String := Ada.Directories.Containing_Directory (Path);
begin
Add_Model_Dir (Dir, "db");
Add_Model_Dir (Dir, "db/regtests");
Add_Model_Dir (Dir, "db/samples");
end;
Gen.Utils.String_List.Next (Iter);
end loop;
end Collect_Directories;
procedure Print_Model_File (Name : in String;
File : in String;
Done : out Boolean) is
pragma Unreferenced (Name);
begin
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (File);
Done := False;
end Print_Model_File;
-- ------------------------------
-- Print the list of GNAT projects used by the main project.
-- ------------------------------
procedure Print_GNAT_Projects (Project : in out Gen.Model.Projects.Project_Definition) is
use Gen.Utils.GNAT;
Iter : Project_Info_Vectors.Cursor := Project.Project_Files.First;
Info : Project_Info;
begin
if Project_Info_Vectors.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("GNAT project files:");
while Project_Info_Vectors.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Info := Project_Info_Vectors.Element (Iter);
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Info.Path));
Project_Info_Vectors.Next (Iter);
end loop;
end if;
end Print_GNAT_Projects;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Project_List (Indent : in Ada.Text_IO.Positive_Count;
List : in Gen.Model.Projects.Project_Vectors.Vector) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := List.First;
Ref : Model.Projects.Project_Reference;
begin
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put (Ada.Strings.Unbounded.To_String (Ref.Name));
Ada.Text_IO.Set_Col (Indent + 30);
if Ref.Project /= null then
Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Ref.Project.Path));
else
Ada.Text_IO.Put_Line ("?");
end if;
Project_Vectors.Next (Iter);
end loop;
end Print_Project_List;
-- ------------------------------
-- Print the list of Dynamo modules
-- ------------------------------
procedure Print_Modules (Project : in out Gen.Model.Projects.Project_Definition'Class;
Indent : in Ada.Text_IO.Positive_Count) is
use Gen.Model.Projects;
use type Ada.Text_IO.Positive_Count;
Iter : Project_Vectors.Cursor := Project.Modules.First;
Ref : Model.Projects.Project_Reference;
begin
if not Project.Modules.Is_Empty then
Ada.Text_IO.Set_Col (Indent);
Ada.Text_IO.Put_Line ("Dynamo plugins:");
Print_Project_List (Indent, Project.Modules);
Print_Project_List (Indent, Project.Dependencies);
Iter := Project.Modules.First;
while Project_Vectors.Has_Element (Iter) loop
Ref := Project_Vectors.Element (Iter);
if Ref.Project /= null and then not Ref.Project.Modules.Is_Empty then
declare
Name : constant String := Ada.Strings.Unbounded.To_String (Ref.Name);
begin
Ada.Text_IO.Set_Col (Indent);
if Names.Contains (Name) then
Ada.Text_IO.Put_Line ("!! " & Name);
else
Names.Insert (Name);
Ada.Text_IO.Put_Line ("== " & Name);
Print_Modules (Ref.Project.all, Indent + 4);
Names.Delete (Name);
end if;
end;
end if;
Project_Vectors.Next (Iter);
end loop;
end if;
end Print_Modules;
-- ------------------------------
-- Print the list of Dynamo projects used by the main project.
-- ------------------------------
procedure Print_Dynamo_Projects (Project : in out Model.Projects.Root_Project_Definition) is
Iter : Gen.Utils.String_List.Cursor := Project.Dynamo_Files.First;
begin
if Gen.Utils.String_List.Has_Element (Iter) then
Ada.Text_IO.Put_Line ("Dynamo project files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Gen.Utils.String_List.Next (Iter);
end loop;
end if;
end Print_Dynamo_Projects;
procedure Print_Project (Project : in out Gen.Model.Projects.Root_Project_Definition) is
begin
Print_GNAT_Projects (Gen.Model.Projects.Project_Definition (Project));
Print_Dynamo_Projects (Project);
Print_Modules (Project, 1);
declare
Model_Dirs : Gen.Utils.String_List.Vector;
begin
Collect_Directories (List, Model_Dirs);
declare
Iter : Gen.Utils.String_List.Cursor := Model_Dirs.First;
begin
Ada.Text_IO.Put_Line ("ADO model files:");
while Gen.Utils.String_List.Has_Element (Iter) loop
Ada.Text_IO.Put (" ");
Ada.Text_IO.Put_Line (Gen.Utils.String_List.Element (Iter));
Util.Files.Iterate_Files_Path (Pattern => "*.xml",
Path => Gen.Utils.String_List.Element (Iter),
Process => Print_Model_File'Access);
Gen.Utils.String_List.Next (Iter);
end loop;
end;
end;
end Print_Project;
begin
Generator.Read_Project ("dynamo.xml", True);
Generator.Update_Project (Print_Project'Access);
end Execute;
-- ------------------------------
-- Write the help associated with the command.
-- ------------------------------
procedure Help (Cmd : in Command;
Generator : in out Gen.Generator.Handler) is
pragma Unreferenced (Cmd, Generator);
begin
Ada.Text_IO.Put_Line ("info: Print information about the current project");
Ada.Text_IO.Put_Line ("Usage: info");
Ada.Text_IO.New_Line;
end Help;
end Gen.Commands.Info;
|
--
-- (c) Copyright 1993,1994,1995,1996 Silicon Graphics, Inc.
-- ALL RIGHTS RESERVED
-- Permission to use, copy, modify, and distribute this software for
-- any purpose and without fee is hereby granted, provided that the above
-- copyright notice appear in all copies and that both the copyright notice
-- and this permission notice appear in supporting documentation, and that
-- the name of Silicon Graphics, Inc. not be used in advertising
-- or publicity pertaining to distribution of the software without specific,
-- written prior permission.
--
-- THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS"
-- AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE,
-- INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR
-- FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-- GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT,
-- SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY
-- KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION,
-- LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF
-- THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN
-- ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON
-- ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE
-- POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE.
--
-- US Government Users Restricted Rights
-- Use, duplication, or disclosure by the Government is subject to
-- restrictions set forth in FAR 52.227.19(c)(2) or subparagraph
-- (c)(1)(ii) of the Rights in Technical Data and Computer Software
-- clause at DFARS 252.227-7013 and/or in similar or successor
-- clauses in the FAR or the DOD or NASA FAR Supplement.
-- Unpublished-- rights reserved under the copyright laws of the
-- United States. Contractor/manufacturer is Silicon Graphics,
-- Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311.
--
-- OpenGL(TM) is a trademark of Silicon Graphics, Inc.
--
with GL; use GL;
with GLU; use GLU;
package body Cone_Procs is
procedure DoInit is
mat_ambient : array (0 .. 3) of aliased GLfloat :=
(0.2, 0.2, 0.2, 1.0);
mat_diffuse : array (0 .. 3) of aliased GLfloat :=
(0.8, 0.8, 0.8, 1.0);
-- Specular and Shininess are not default values
mat_specular : array (0 .. 3) of aliased GLfloat :=
(1.0, 1.0, 1.0, 1.0);
mat_shininess : aliased GLfloat := 50.0;
light_ambient : array (0 .. 3) of aliased GLfloat :=
(0.0, 0.0, 0.0, 1.0);
light_diffuse : array (0 .. 3) of aliased GLfloat :=
(1.0, 1.0, 1.0, 1.0);
light_specular : array (0 .. 3) of aliased GLfloat :=
(1.0, 1.0, 1.0, 1.0);
light_position : array (0 .. 3) of aliased GLfloat :=
(1.0, 1.0, 1.0, 0.0);
lmodel_ambient : array (0 .. 3) of aliased GLfloat :=
(0.2, 0.2, 0.2, 1.0);
begin
glMaterialfv (GL_FRONT, GL_AMBIENT, mat_ambient (0)'Access);
glMaterialfv (GL_FRONT, GL_DIFFUSE, mat_diffuse (0)'Access);
glMaterialfv (GL_FRONT, GL_SPECULAR, mat_specular (0)'Access);
glMaterialfv (GL_FRONT, GL_SHININESS, mat_shininess'Access);
glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient (0)'Access);
glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse (0)'Access);
glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular (0)'Access);
glLightfv (GL_LIGHT0, GL_POSITION, light_position (0)'Access);
glLightModelfv (GL_LIGHT_MODEL_AMBIENT, lmodel_ambient (0)'Access);
glEnable (GL_LIGHTING);
glEnable (GL_LIGHT0);
glEnable (GL_DEPTH_TEST);
end DoInit;
procedure solidCone (base : Float; height : Float) is
quadObj : GLUquadricObj_Ptr;
begin
quadObj := gluNewQuadric;
gluQuadricDrawStyle (quadObj, GLU_FILL);
gluQuadricNormals (quadObj, GLU_SMOOTH);
gluCylinder (quadObj, GLdouble(base), 0.0, GLdouble(height), 15, 10);
gluDeleteQuadric (quadObj);
end solidCone;
procedure DoDisplay is
begin
glClear (GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT);
glPushMatrix;
glTranslatef (0.0, -1.0, 0.0);
glRotatef (250.0, 1.0, 0.0, 0.0);
solidCone (1.0, 2.0);
glPopMatrix;
glFlush;
end DoDisplay;
procedure ReshapeCallback (w : Integer; h : Integer) is
begin
glViewport (0, 0, GLsizei(w), GLsizei(h));
glMatrixMode (GL_PROJECTION);
glLoadIdentity;
if w <= h then
glOrtho (-1.5, 1.5, GLdouble (-1.5*Float (h)/Float (w)),
GLdouble (1.5*Float (h)/Float (w)), -10.0, 10.0);
else
glOrtho (GLdouble (-1.5*Float (w)/Float (h)),
GLdouble (1.5*Float (w)/Float (h)), -1.5, 1.5, -10.0, 10.0);
end if;
glMatrixMode (GL_MODELVIEW);
end ReshapeCallback;
end Cone_Procs;
|
with
GL.lean,
Interfaces.C.Strings,
System;
package GL.Pointers
--
-- Provides pointer conversions.
--
is
use Interfaces;
function to_GLvoid_access (From : in system.Address) return access GLvoid;
function to_GLvoid_access (From : access C.unsigned_char) return access GLvoid;
function to_GLchar_access (From : in C.Strings.chars_ptr) return access lean.GLchar;
function to_GLchar_Pointer_access
(From : access C.Strings.chars_ptr_array)
return access lean.GLchar_Pointer;
function "+" (From : in system.Address) return access GLvoid renames to_GLvoid_access;
function "+" (From : access C.unsigned_char) return access GLvoid renames to_GLvoid_access;
function "+" (From : in C.Strings.chars_ptr) return access lean.GLchar renames to_GLchar_access;
end GL.Pointers;
|
------------------------------------------------------------------------------
-- --
-- GNAT ncurses Binding --
-- --
-- Terminal_Interface.Curses.Panels --
-- --
-- B O D Y --
-- --
------------------------------------------------------------------------------
-- Copyright (c) 1998,2004 Free Software Foundation, Inc. --
-- --
-- Permission is hereby granted, free of charge, to any person obtaining a --
-- copy of this software and associated documentation files (the --
-- "Software"), to deal in the Software without restriction, including --
-- without limitation the rights to use, copy, modify, merge, publish, --
-- distribute, distribute with modifications, sublicense, and/or sell --
-- copies of the Software, and to permit persons to whom the Software is --
-- furnished to do so, subject to the following conditions: --
-- --
-- The above copyright notice and this permission notice shall be included --
-- in all copies or substantial portions of the Software. --
-- --
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS --
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF --
-- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. --
-- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, --
-- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR --
-- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR --
-- THE USE OR OTHER DEALINGS IN THE SOFTWARE. --
-- --
-- Except as contained in this notice, the name(s) of the above copyright --
-- holders shall not be used in advertising or otherwise to promote the --
-- sale, use or other dealings in this Software without prior written --
-- authorization. --
------------------------------------------------------------------------------
-- Author: Juergen Pfeifer, 1996
-- Version Control:
-- $Revision: 1.13 $
-- $Date: 2004/08/21 21:37:00 $
-- Binding Version 01.00
------------------------------------------------------------------------------
with Terminal_Interface.Curses.Aux; use Terminal_Interface.Curses.Aux;
with Interfaces.C;
package body Terminal_Interface.Curses.Panels is
use type Interfaces.C.int;
function Create (Win : Window) return Panel
is
function Newpanel (Win : Window) return Panel;
pragma Import (C, Newpanel, "new_panel");
Pan : Panel;
begin
Pan := Newpanel (Win);
if Pan = Null_Panel then
raise Panel_Exception;
end if;
return Pan;
end Create;
procedure Bottom (Pan : in Panel)
is
function Bottompanel (Pan : Panel) return C_Int;
pragma Import (C, Bottompanel, "bottom_panel");
begin
if Bottompanel (Pan) = Curses_Err then
raise Panel_Exception;
end if;
end Bottom;
procedure Top (Pan : in Panel)
is
function Toppanel (Pan : Panel) return C_Int;
pragma Import (C, Toppanel, "top_panel");
begin
if Toppanel (Pan) = Curses_Err then
raise Panel_Exception;
end if;
end Top;
procedure Show (Pan : in Panel)
is
function Showpanel (Pan : Panel) return C_Int;
pragma Import (C, Showpanel, "show_panel");
begin
if Showpanel (Pan) = Curses_Err then
raise Panel_Exception;
end if;
end Show;
procedure Hide (Pan : in Panel)
is
function Hidepanel (Pan : Panel) return C_Int;
pragma Import (C, Hidepanel, "hide_panel");
begin
if Hidepanel (Pan) = Curses_Err then
raise Panel_Exception;
end if;
end Hide;
function Get_Window (Pan : Panel) return Window
is
function Panel_Win (Pan : Panel) return Window;
pragma Import (C, Panel_Win, "panel_window");
Win : constant Window := Panel_Win (Pan);
begin
if Win = Null_Window then
raise Panel_Exception;
end if;
return Win;
end Get_Window;
procedure Replace (Pan : in Panel;
Win : in Window)
is
function Replace_Pan (Pan : Panel;
Win : Window) return C_Int;
pragma Import (C, Replace_Pan, "replace_panel");
begin
if Replace_Pan (Pan, Win) = Curses_Err then
raise Panel_Exception;
end if;
end Replace;
procedure Move (Pan : in Panel;
Line : in Line_Position;
Column : in Column_Position)
is
function Move (Pan : Panel;
Line : C_Int;
Column : C_Int) return C_Int;
pragma Import (C, Move, "move_panel");
begin
if Move (Pan, C_Int (Line), C_Int (Column)) = Curses_Err then
raise Panel_Exception;
end if;
end Move;
function Is_Hidden (Pan : Panel) return Boolean
is
function Panel_Hidden (Pan : Panel) return C_Int;
pragma Import (C, Panel_Hidden, "panel_hidden");
begin
if Panel_Hidden (Pan) = Curses_False then
return False;
else
return True;
end if;
end Is_Hidden;
procedure Delete (Pan : in out Panel)
is
function Del_Panel (Pan : Panel) return C_Int;
pragma Import (C, Del_Panel, "del_panel");
begin
if Del_Panel (Pan) = Curses_Err then
raise Panel_Exception;
end if;
Pan := Null_Panel;
end Delete;
end Terminal_Interface.Curses.Panels;
|
-- Copyright 2010-2015 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Mixed;
procedure A is
begin
Mixed.Start_Test;
end A;
|
-- Copyright 2015-2016 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with System;
package Pck is
type Table is array (Positive range <>) of Integer;
type Object (N : Integer) is record
Data : Table (1 .. N);
end record;
type Small is new Integer range 0 .. 255;
for Small'Size use 8;
type Small_Table is array (Positive range <>) of Small;
pragma Pack (Small_Table);
type Small_Object (N : Integer) is record
Data : Table (1 .. N);
end record;
procedure Do_Nothing (A : System.Address);
end Pck;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Ada Modeling Framework --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2011, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with AMF.CMOF.Associations;
with AMF.CMOF.Classes;
with AMF.Elements.Collections;
with AMF.Extents;
with AMF.Links.Collections;
with AMF.URI_Extents;
package AMF.Internals.AMF_URI_Extents is
type AMF_URI_Extent is limited new AMF.URI_Extents.URI_Extent with record
Id : AMF_Extent;
end record;
type AMF_URI_Extent_Access is access all AMF_URI_Extent'Class;
---------------------------
-- Extent's operations --
---------------------------
overriding function Use_Containment
(Self : not null access constant AMF_URI_Extent) return Boolean;
-- When true, recursively include all elements contained by members of the
-- elements().
overriding function Elements
(Self : not null access constant AMF_URI_Extent)
return AMF.Elements.Collections.Set_Of_Element;
-- Returns a ReflectiveSequence of the elements directly referenced by this
-- extent. If exclusive()==true, these elements must have
-- container()==null. Extent.elements() is a reflective operation, not a
-- reference between Extent and Element. See Chapter 4, “Reflection” for a
-- definition of ReflectiveSequence.
overriding function Elements_Of_Type
(Self : not null access constant AMF_URI_Extent;
The_Type : not null AMF.CMOF.Classes.CMOF_Class_Access;
Include_Subtypes : Boolean)
return AMF.Elements.Collections.Set_Of_Element;
-- This returns those elements in the extent that are instances of the
-- supplied Class. If includeSubtypes is true, then instances of any
-- subclasses are also returned.
overriding function Links_Of_Type
(Self : not null access constant AMF_URI_Extent;
The_Type : not null AMF.CMOF.Associations.CMOF_Association_Access)
return AMF.Links.Collections.Set_Of_Link;
-- linksOfType(type : Association) : Link[0..*]
-- This returns those links in the extent that are instances of the
-- supplied Association.
overriding function Linked_Elements
(Self : not null access constant AMF_URI_Extent;
Association :
not null AMF.CMOF.Associations.CMOF_Association_Access;
End_Element : not null AMF.Elements.Element_Access;
End_1_To_End_2_Direction : Boolean)
return AMF.Elements.Collections.Set_Of_Element;
-- This navigates the supplied Association from the supplied Element. The
-- direction of navigation is given by the end1ToEnd2Direction parameter:
-- if true, then the supplied Element is treated as the first end of the
-- Association.
overriding function Link_Exists
(Self : not null access constant AMF_URI_Extent;
Association : not null AMF.CMOF.Associations.CMOF_Association_Access;
First_Element : not null AMF.Elements.Element_Access;
Second_Element : not null AMF.Elements.Element_Access)
return Boolean;
-- This returns true if there exists at least one link for the association
-- between the supplied elements at their respective ends.
overriding procedure Add_Element
(Self : not null access AMF_URI_Extent;
Element : not null AMF.Elements.Element_Access);
-- Adds an existing Element to the extent. This is a null operation if the
-- Element is already in the Extent.
overriding procedure Remove_Element
(Self : not null access AMF_URI_Extent;
Element : not null AMF.Elements.Element_Access);
-- Removes the Element from the extent. It is an error if the Element is
-- not a member. This may or may not result in it being deleted (see
-- Section 6.3.2, “Deletion Semantics”).
overriding procedure Move_Element
(Self : not null access AMF_URI_Extent;
Element : not null AMF.Elements.Element_Access;
Target : not null access AMF.Extents.Extent'Class);
-- An atomic combination of addElement and removeElement. targetExtent must
-- be different from the extent on which the operation is invoked.
overriding procedure Delete_Extent (Self : not null access AMF_URI_Extent);
-- Deletes the Extent, but not necessarily the Elements it contains (see
-- Section 6.3.2, “Deletion Semantics).
------------------------------
-- URIExtent's operations --
------------------------------
overriding function Context_URI
(Self : not null access constant AMF_URI_Extent)
return League.Strings.Universal_String;
-- Specifies an identifier for the extent that establishes a URI context
-- for identifying elements in the extent. An extent has an identifier if a
-- URI is assigned. URI is defined in IETF RFC-2396 available at
-- http://www.ietf.org/rfc/rfc2396.txt.
overriding function URI
(Self : not null access constant AMF_URI_Extent;
Element : not null access constant AMF.Elements.Abstract_Element'Class)
return League.Strings.Universal_String;
-- Returns the URI of the given element in the extent. Returns Null if the
-- element is not in the extent.
overriding function Element
(Self : not null access constant AMF_URI_Extent;
URI : League.Strings.Universal_String)
return AMF.Elements.Element_Access;
-- Returns the Element identified by the given URI in the extent. Returns
-- Null if there is no element in the extent with the given URI. Note the
-- Element does not (necessarily) contain a property corresponding to the
-- URI. The URI identifies the element in the context of the extent. The
-- same element may have a different identifier in another extent.
end AMF.Internals.AMF_URI_Extents;
|
pragma License (Unrestricted);
-- implementation unit specialized for Windows
package System.Native_Execution_Time is
subtype CPU_Time is Duration;
function Clock return CPU_Time;
end System.Native_Execution_Time;
|
with
System;
package body lace.Strings.Search
is
use Ada.Strings.Maps,
System;
-----------------------
-- Local Subprograms --
-----------------------
function Belongs
(Element : Character;
Set : Maps.Character_Set;
Test : Membership) return Boolean;
pragma Inline (Belongs);
-- Determines if the given element is in (Test = Inside) or not in
-- (Test = Outside) the given character set.
-------------
-- Belongs --
-------------
function Belongs
(Element : Character;
Set : Maps.Character_Set;
Test : Membership) return Boolean
is
begin
if Test = Inside then
return Is_In (Element, Set);
else
return not Is_In (Element, Set);
end if;
end Belongs;
-----------
-- Count --
-----------
function Count
(Source : String;
Pattern : String;
Mapping : Maps.Character_Mapping := Maps.Identity) return Natural
is
PL1 : constant Integer := Pattern'Length - 1;
Num : Natural;
Ind : Natural;
Cur : Natural;
begin
if Pattern = "" then
raise Pattern_Error;
end if;
Num := 0;
Ind := Source'First;
-- Unmapped case
if Mapping'Address = Maps.Identity'Address then
while Ind <= Source'Last - PL1 loop
if Pattern = Source (Ind .. Ind + PL1) then
Num := Num + 1;
Ind := Ind + Pattern'Length;
else
Ind := Ind + 1;
end if;
end loop;
-- Mapped case
else
while Ind <= Source'Last - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Value (Mapping, Source (Cur)) then
Ind := Ind + 1;
goto Cont;
else
Cur := Cur + 1;
end if;
end loop;
Num := Num + 1;
Ind := Ind + Pattern'Length;
<<Cont>>
null;
end loop;
end if;
-- Return result
return Num;
end Count;
function Count
(Source : String;
Pattern : String;
Mapping : Maps.Character_Mapping_Function) return Natural
is
PL1 : constant Integer := Pattern'Length - 1;
Num : Natural;
Ind : Natural;
Cur : Natural;
begin
if Pattern = "" then
raise Pattern_Error;
end if;
-- Check for null pointer in case checks are off
if Mapping = null then
raise Constraint_Error;
end if;
Num := 0;
Ind := Source'First;
while Ind <= Source'Last - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Mapping (Source (Cur)) then
Ind := Ind + 1;
goto Cont;
else
Cur := Cur + 1;
end if;
end loop;
Num := Num + 1;
Ind := Ind + Pattern'Length;
<<Cont>>
null;
end loop;
return Num;
end Count;
function Count
(Source : String;
Set : Maps.Character_Set) return Natural
is
N : Natural := 0;
begin
for J in Source'Range loop
if Is_In (Source (J), Set) then
N := N + 1;
end if;
end loop;
return N;
end Count;
----------------
-- Find_Token --
----------------
procedure Find_Token
(Source : String;
Set : Maps.Character_Set;
From : Positive;
Test : Membership;
First : out Positive;
Last : out Natural)
is
begin
for J in From .. Source'Last loop
if Belongs (Source (J), Set, Test) then
First := J;
for K in J + 1 .. Source'Last loop
if not Belongs (Source (K), Set, Test) then
Last := K - 1;
return;
end if;
end loop;
-- Here if J indexes first char of token, and all chars after J
-- are in the token.
Last := Source'Last;
return;
end if;
end loop;
-- Here if no token found
First := From;
Last := 0;
end Find_Token;
procedure Find_Token
(Source : String;
Set : Maps.Character_Set;
Test : Membership;
First : out Positive;
Last : out Natural)
is
begin
for J in Source'Range loop
if Belongs (Source (J), Set, Test) then
First := J;
for K in J + 1 .. Source'Last loop
if not Belongs (Source (K), Set, Test) then
Last := K - 1;
return;
end if;
end loop;
-- Here if J indexes first char of token, and all chars after J
-- are in the token.
Last := Source'Last;
return;
end if;
end loop;
-- Here if no token found
First := Source'First;
Last := 0;
end Find_Token;
-----------
-- Index --
-----------
function Index
(Source : String;
Pattern : String;
Going : Direction := Forward;
Mapping : Maps.Character_Mapping := Maps.Identity) return Natural
is
PL1 : constant Integer := Pattern'Length - 1;
Cur : Natural;
Ind : Integer;
-- Index for start of match check. This can be negative if the pattern
-- length is greater than the string length, which is why this variable
-- is Integer instead of Natural. In this case, the search loops do not
-- execute at all, so this Ind value is never used.
begin
if Pattern = "" then
raise Pattern_Error;
end if;
-- Forwards case
if Going = Forward then
Ind := Source'First;
-- Unmapped forward case
if Mapping'Address = Maps.Identity'Address then
for J in 1 .. Source'Length - PL1 loop
if Pattern = Source (Ind .. Ind + PL1) then
return Ind;
else
Ind := Ind + 1;
end if;
end loop;
-- Mapped forward case
else
for J in 1 .. Source'Length - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Value (Mapping, Source (Cur)) then
goto Cont1;
else
Cur := Cur + 1;
end if;
end loop;
return Ind;
<<Cont1>>
Ind := Ind + 1;
end loop;
end if;
-- Backwards case
else
-- Unmapped backward case
Ind := Source'Last - PL1;
if Mapping'Address = Maps.Identity'Address then
for J in reverse 1 .. Source'Length - PL1 loop
if Pattern = Source (Ind .. Ind + PL1) then
return Ind;
else
Ind := Ind - 1;
end if;
end loop;
-- Mapped backward case
else
for J in reverse 1 .. Source'Length - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Value (Mapping, Source (Cur)) then
goto Cont2;
else
Cur := Cur + 1;
end if;
end loop;
return Ind;
<<Cont2>>
Ind := Ind - 1;
end loop;
end if;
end if;
-- Fall through if no match found. Note that the loops are skipped
-- completely in the case of the pattern being longer than the source.
return 0;
end Index;
function Index
(Source : String;
Pattern : String;
Going : Direction := Forward;
Mapping : Maps.Character_Mapping_Function) return Natural
is
PL1 : constant Integer := Pattern'Length - 1;
Ind : Natural;
Cur : Natural;
begin
if Pattern = "" then
raise Pattern_Error;
end if;
-- Check for null pointer in case checks are off
if Mapping = null then
raise Constraint_Error;
end if;
-- If Pattern longer than Source it can't be found
if Pattern'Length > Source'Length then
return 0;
end if;
-- Forwards case
if Going = Forward then
Ind := Source'First;
for J in 1 .. Source'Length - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Mapping.all (Source (Cur)) then
goto Cont1;
else
Cur := Cur + 1;
end if;
end loop;
return Ind;
<<Cont1>>
Ind := Ind + 1;
end loop;
-- Backwards case
else
Ind := Source'Last - PL1;
for J in reverse 1 .. Source'Length - PL1 loop
Cur := Ind;
for K in Pattern'Range loop
if Pattern (K) /= Mapping.all (Source (Cur)) then
goto Cont2;
else
Cur := Cur + 1;
end if;
end loop;
return Ind;
<<Cont2>>
Ind := Ind - 1;
end loop;
end if;
-- Fall through if no match found. Note that the loops are skipped
-- completely in the case of the pattern being longer than the source.
return 0;
end Index;
function Index
(Source : String;
Set : Maps.Character_Set;
Test : Membership := Inside;
Going : Direction := Forward) return Natural
is
begin
-- Forwards case
if Going = Forward then
for J in Source'Range loop
if Belongs (Source (J), Set, Test) then
return J;
end if;
end loop;
-- Backwards case
else
for J in reverse Source'Range loop
if Belongs (Source (J), Set, Test) then
return J;
end if;
end loop;
end if;
-- Fall through if no match
return 0;
end Index;
function Index
(Source : String;
Pattern : String;
From : Positive;
Going : Direction := Forward;
Mapping : Maps.Character_Mapping := Maps.Identity) return Natural
is
begin
if Going = Forward then
if From < Source'First then
raise Index_Error;
end if;
return
Index (Source (From .. Source'Last), Pattern, Forward, Mapping);
else
if From > Source'Last then
raise Index_Error;
end if;
return
Index (Source (Source'First .. From), Pattern, Backward, Mapping);
end if;
end Index;
function Index
(Source : String;
Pattern : String;
From : Positive;
Going : Direction := Forward;
Mapping : Maps.Character_Mapping_Function) return Natural
is
begin
if Going = Forward then
if From < Source'First then
raise Index_Error;
end if;
return Index
(Source (From .. Source'Last), Pattern, Forward, Mapping);
else
if From > Source'Last then
raise Index_Error;
end if;
return Index
(Source (Source'First .. From), Pattern, Backward, Mapping);
end if;
end Index;
function Index
(Source : String;
Set : Maps.Character_Set;
From : Positive;
Test : Membership := Inside;
Going : Direction := Forward) return Natural
is
begin
if Going = Forward then
if From < Source'First then
raise Index_Error;
end if;
return
Index (Source (From .. Source'Last), Set, Test, Forward);
else
if From > Source'Last then
raise Index_Error;
end if;
return
Index (Source (Source'First .. From), Set, Test, Backward);
end if;
end Index;
---------------------
-- Index_Non_Blank --
---------------------
function Index_Non_Blank
(Source : String;
Going : Direction := Forward) return Natural
is
begin
if Going = Forward then
for J in Source'Range loop
if Source (J) /= ' ' then
return J;
end if;
end loop;
else -- Going = Backward
for J in reverse Source'Range loop
if Source (J) /= ' ' then
return J;
end if;
end loop;
end if;
-- Fall through if no match
return 0;
end Index_Non_Blank;
function Index_Non_Blank
(Source : String;
From : Positive;
Going : Direction := Forward) return Natural
is
begin
if Going = Forward then
if From < Source'First then
raise Index_Error;
end if;
return
Index_Non_Blank (Source (From .. Source'Last), Forward);
else
if From > Source'Last then
raise Index_Error;
end if;
return
Index_Non_Blank (Source (Source'First .. From), Backward);
end if;
end Index_Non_Blank;
end lace.Strings.Search;
|
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2017-2018, Fabien Chouteau --
-- --
-- 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 AGATE.Scheduler;
package body AGATE.API.Static_Task is
-- https://stackoverflow.com/questions/33405479/
-- how-to-pass-access-to-a-constrained-string-to-a-subprogram-in-ada
Heap : aliased Task_Heap := (1 .. Heap_Size => 0);
Stack : aliased Task_Stack := (1 .. Stack_Size => 0);
Sec_Stack : aliased Task_Sec_Stack := (1 .. Sec_Stack_Size => 0);
The_Task : aliased Task_Object
(Proc => Proc,
Base_Prio => Internal_Task_Priority (Priority),
Stack => Stack'Access,
Sec_Stack => Sec_Stack'Access,
Heap => Heap'Access);
The_Access : constant Task_Object_Access := The_Task'Access;
--------
-- ID --
--------
function ID return Task_ID
is (Task_ID (The_Access));
begin
AGATE.Scheduler.Register (ID, Name);
end AGATE.API.Static_Task;
|
with
ada.unchecked_Deallocation,
ada.Containers,
ada.Calendar,
ada.Text_IO,
ada.Exceptions;
package body physics.Engine
is
use ada.Text_IO;
protected body safe_command_Set
is
function is_Empty return Boolean
is
begin
return the_Count = 0;
end is_Empty;
procedure add (the_Command : in Command)
is
begin
the_Count := the_Count + 1;
Set (the_Count) := the_Command;
end add;
procedure Fetch (To : out Commands;
Count : out Natural)
is
begin
To (1 .. the_Count) := Set (1 .. the_Count);
Count := the_Count;
the_Count := 0;
end Fetch;
end safe_command_Set;
task body Evolver is
use Math;
use type physics.Joint.view,
ada.Containers.Count_type;
Stopped : Boolean := True;
Cycle : ada.Containers.Count_type := 0;
next_render_Time : ada.Calendar.Time;
max_joint_Force,
max_joint_Torque : Real := 0.0;
procedure free_Objects
is
-- the_free_Objects : gel.Object.views := the_World.free_Object_Set;
begin
-- for Each in the_free_Objects'Range
-- loop
-- log ("Engine is Freeing Object id: " & Object_Id'Image (the_free_Objects (Each).Id));
--
-- if the_free_Objects (Each).owns_Graphics
-- then
-- the_World.Renderer.free (the_free_Objects (Each).Visual.Model);
-- end if;
--
-- gel.Object.free (the_free_Objects (Each));
-- end loop;
null;
end free_Objects;
procedure evolve
is
begin
Cycle := Cycle + 1;
do_engine_Commands:
declare
the_Commands : Commands;
Count : Natural;
command_Count : array (command_Kind) of Natural := (others => 0);
begin
Self.Commands.fetch (the_Commands, Count);
for Each in 1 .. Count
loop
declare
the_Command : Command renames the_Commands (Each);
begin
command_Count (the_Command.Kind) := command_Count (the_Command.Kind) + 1;
case the_Command.Kind
is
when scale_Object =>
the_Command.Object.activate;
the_Command.Object.Shape.Scale_is (the_Command.Scale);
the_Command.Object .Scale_is (the_Command.Scale);
Self.Space.update_Bounds (the_Command.Object);
when update_Bounds =>
Self.Space.update_Bounds (the_Command.Object);
when update_Site =>
the_Command.Object.Site_is (the_Command.Site);
when set_Speed =>
the_Command.Object.Speed_is (the_Command.Speed);
when set_xy_Spin =>
the_Command.Object.xy_Spin_is (the_Command.xy_Spin);
when add_Object =>
declare
-- procedure rebuild_Shape (the_Object : in Object.view)
-- is
-- use type physics.Model.shape_Kind,
-- physics.Model.View;
--
-- the_Scale : aliased Vector_3;
--
-- begin
-- if the_Object.physics_Model = null then
-- return;
-- end if;
--
-- the_Scale := Self.physics_Model.Scale;
--
-- case Self.physics_Model.shape_Info.Kind
-- is
-- when physics.Model.Cube =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_box_Shape (Self.physics_Model.shape_Info.half_Extents));
--
-- when physics.Model.a_Sphere =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_sphere_Shape (Self.physics_Model.shape_Info.sphere_Radius));
--
-- when physics.Model.multi_Sphere =>
-- Self.Shape := physics_Shape_view (Self.World.Physics.new_multisphere_Shape (Self.physics_Model.shape_Info.Sites.all,
-- Self.physics_Model.shape_Info.Radii.all));
-- when physics.Model.Cone =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_cone_Shape (radius => Real (Self.physics_Model.Scale (1) / 2.0),
-- height => Real (Self.physics_Model.Scale (2))));
-- when physics.Model.a_Capsule =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_capsule_Shape (Self.physics_Model.shape_Info.lower_Radius,
-- Self.physics_Model.shape_Info.Height));
-- when physics.Model.Cylinder =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_cylinder_Shape (Self.physics_Model.shape_Info.half_Extents));
--
-- when physics.Model.Hull =>
-- Self.Shape := physics_Shape_view (Self.World.Physics.new_convex_hull_Shape (Self.physics_Model.shape_Info.Points.all));
--
-- when physics.Model.Mesh =>
-- Self.Shape := physics_Shape_view (Self.World.Physics .new_mesh_Shape (Self.physics_Model.shape_Info.Model));
--
-- when physics.Model.Plane =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_plane_Shape (Self.physics_Model.Shape_Info.plane_Normal,
-- Self.physics_Model.Shape_Info.plane_Offset));
-- when physics.Model.Heightfield =>
-- Self.Shape := physics_Shape_view (Self.World.Physics.new_heightfield_Shape (Self.physics_Model.shape_Info.Heights.all,
-- Self.physics_Model.Scale));
-- when physics.Model.Circle =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_circle_Shape (Self.physics_Model.shape_Info.circle_Radius));
--
-- when physics.Model.Polygon =>
-- Self.Shape := physics_Shape_view (Self.World.Physics. new_polygon_Shape (physics.space.polygon_Vertices (Self.physics_Model.shape_Info.Vertices (1 .. Self.physics_Model.shape_Info.vertex_Count))));
-- end case;
--
-- end rebuild_Shape;
procedure add (the_Object : in Object.view)
is
begin
-- the_World.add (the_Object. physics_Model.all'Access);
-- if the_Object.physics_Model.is_Tangible
-- then
-- rebuild_Shape (the_Object);
the_Object.Shape.define;
-- the_Object.define (Shape => the_Object.Shape,
-- Mass => the_Object.Model.Mass,
-- Friction => the_Object.Model.Friction,
-- Restitution => the_Object.Model.Restitution,
-- at_Site => the_Object.Model.Site);
Self.Space.add (the_Object);
-- end if;
-- begin
-- the_Object_Transforms.insert (the_Object, Identity_4x4);
-- the_Object.Solid.user_Data_is (the_Object);
-- end;
-- the_World.Object_Count := the_World.Object_Count + 1;
-- the_World.Objects (the_World.Object_Count) := the_Object;
end add;
begin
add (the_Command.Object);
end;
when rid_Object =>
declare
function find (the_Object : in Object.view) return Index
is
begin
-- for Each in 1 .. the_World.Object_Count
-- loop
-- if the_World.Objects (Each) = the_Object
-- then
-- return Each;
-- end if;
-- end loop;
raise constraint_Error with "no such Object in world";
return 0;
end find;
procedure rid (the_Object : in Object.view)
is
use type Object.view;
begin
if the_Object /= null
then
-- if the_Object.physics_Model.is_Tangible
-- then
Self.Space.rid (the_Object);
-- end if;
-- if the_Object_Transforms.contains (the_Object) then
-- the_Object_Transforms.delete (the_Object);
-- end if;
else
raise program_Error;
end if;
declare
Id : Index;
begin
Id := find (the_Object);
-- if Id <= the_World.Object_Count
-- then
-- the_World.Objects (1 .. the_World.Object_Count - 1)
-- := the_World.Objects ( 1 .. Id - 1)
-- & the_World.Objects (Id + 1 .. the_World.Object_Count);
-- end if;
-- the_World.Object_Count := the_World.Object_Count - 1;
end;
end rid;
begin
rid (the_Command.Object);
end;
when apply_Force =>
the_Command.Object.apply_Force (the_Command.Force);
when destroy_Object =>
declare
-- the_free_Set : free_Set renames the_World.free_Sets (the_World.current_free_Set);
begin
raise Program_Error with "destroy_Object ~ TODO";
-- the_free_Set.Count := the_free_Set.Count + 1;
-- the_free_Set.Objects (the_free_Set.Count) := the_Command.Object;
end;
when add_Joint =>
Self.Space.add (the_Command.Joint.all'Access);
the_Command.Joint.user_Data_is (the_Command.Joint);
when rid_Joint =>
Self.Space.rid (the_Command.Joint.all'Access);
when set_Joint_local_Anchor =>
Self.Space.set_Joint_local_Anchor (the_Command.anchor_Joint.all'Access,
the_Command.is_Anchor_A,
the_Command.local_Anchor);
when free_Joint =>
-- Joint.free (the_Command.Joint);
null;
when cast_Ray =>
null;
-- declare
-- function cast_Ray (Self : in Item'Class; From, To : in math.Vector_3) return ray_Collision
-- is
-- use type std_physics.Object.view;
--
-- physics_Collision : constant standard.physics.Space.ray_Collision := Self.physics.cast_Ray (From, To);
-- begin
-- if physics_Collision.near_Object = null
-- then
-- return ray_Collision' (near_Object => null,
-- others => <>);
-- else
-- return ray_Collision' (to_GEL (physics_Collision.near_Object),
-- physics_Collision.hit_Fraction,
-- physics_Collision.Normal_world,
-- physics_Collision.Site_world);
-- end if;
-- end cast_Ray;
--
-- the_Collision : constant ray_Collision := cast_Ray (the_World.all,
-- the_Command.From,
-- the_Command.To);
-- begin
-- if the_Collision.near_Object = null
-- or else the_Collision.near_Object.is_Destroyed
-- then
-- free (the_Command.Context);
--
-- else
-- declare
-- no_Params : aliased no_Parameters;
-- the_Event : raycast_collision_Event'Class
-- := raycast_collision_Event_dispatching_Constructor (the_Command.event_Kind,
-- no_Params'Access);
-- begin
-- the_Event.near_Object := the_Collision.near_Object;
-- the_Event.Context := the_Command.Context;
-- the_Event.Site_world := the_Collision.Site_world;
--
-- the_Command.Observer.receive (the_Event, from_subject => the_World.Name);
-- end;
-- end if;
-- end;
when set_Gravity =>
Self.Space.Gravity_is (the_Command.Gravity);
end case;
end;
end loop;
end do_engine_Commands;
Self.Space.evolve (by => 1.0 / 60.0); -- Evolve the world.
-- free_Objects;
end evolve;
use ada.Calendar;
begin
-- accept start (space_Kind : in physics.space_Kind)
accept start (the_Space : in Space.view)
do
Stopped := False;
-- Self.Space := physics.Forge.new_Space (space_Kind);
Self.Space := the_Space;
end start;
next_render_Time := ada.Calendar.Clock;
loop
select
accept stop
do
Stopped := True;
-- Add 'destroy' commands for all Objects.
--
-- declare
-- the_Objects : Object.views renames the_World.Objects;
-- begin
-- for i in 1 .. the_World.Object_Count
-- loop
-- the_Objects (i).destroy (and_Children => False);
-- end loop;
-- end;
-- Evolve the world til there are no commands left.
--
while not Self.Commands.is_Empty
loop
evolve;
end loop;
-- Free both sets of freeable Objects.
--
free_Objects;
free_Objects;
end stop;
exit when Stopped;
or
accept reset_Age
do
Self.Age := 0.0;
end reset_Age;
else
null;
end select;
evolve;
-- the_World.new_Object_transforms_Available.signal;
-- the_World.evolver_Done .signal;
-- Check for joint breakage.
--
-- if the_World.broken_joints_Allowed
-- then
-- declare
-- use gel.Joint,
-- standard.physics.Space;
--
-- the_Joint : gel.Joint.view;
-- reaction_Force,
-- reaction_Torque : math.Real;
--
-- Cursor : standard.physics.Space.joint_Cursor'Class := the_World.Physics.first_Joint;
-- begin
-- while has_Element (Cursor)
-- loop
-- the_Joint := to_GEL (Element (Cursor));
--
-- if the_Joint /= null
-- then
-- reaction_Force := abs (the_Joint.reaction_Force);
-- reaction_Torque := abs (the_Joint.reaction_Torque);
--
-- if reaction_Force > 50.0 / 8.0
-- or reaction_Torque > 100.0 / 8.0
-- then
-- begin
-- the_World.Physics .rid (the_Joint.Physics.all'Access);
-- the_World.broken_Joints.add (the_Joint);
--
-- exception
-- when no_such_Child =>
-- put_Line ("Error when breaking joint due to reaction Force: no_such_Child !");
-- end;
-- end if;
--
-- if reaction_Force > max_joint_Force
-- then
-- max_joint_Force := reaction_Force;
-- end if;
--
-- if reaction_Torque > max_joint_Torque
-- then
-- max_joint_Torque := reaction_Torque;
-- end if;
-- end if;
--
-- next (Cursor);
-- end loop;
-- end;
-- end if;
next_render_Time := next_render_Time + Duration (1.0 / 60.0);
end loop;
exception
when E : others =>
new_Line (2);
put_Line ("Error in physics.Engine.evolver task !");
new_Line;
put_Line (Ada.Exceptions.Exception_Information (E));
put_Line ("Evolver has terminated !");
new_Line (2);
end Evolver;
-- procedure start (Self : access Item; space_Kind : in physics.space_Kind)
procedure start (Self : access Item; the_Space : in Space.view)
is
begin
Self.Evolver.start (the_Space);
end start;
procedure stop (Self : access Item)
is
procedure free is new ada.unchecked_Deallocation (safe_command_Set, safe_command_Set_view);
begin
Self.Evolver.stop;
free (Self.Commands);
end stop;
procedure add (Self : access Item; the_Object : in Object.view)
is
begin
put_Line ("physics engine: add Object");
Self.Commands.add ((Kind => add_Object,
Object => the_Object,
add_Children => False));
end add;
procedure rid (Self : in out Item; the_Object : in Object.view)
is
begin
Self.Commands.add ((Kind => rid_Object,
Object => the_Object,
rid_Children => False));
end rid;
procedure add (Self : in out Item; the_Joint : in Joint.view)
is
begin
Self.Commands.add ((Kind => add_Joint,
Object => null,
Joint => the_Joint));
end add;
procedure rid (Self : in out Item; the_Joint : in Joint.view)
is
begin
Self.Commands.add ((Kind => rid_Joint,
Object => null,
Joint => the_Joint));
end rid;
procedure update_Scale (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3)
is
begin
Self.Commands.add ((Kind => scale_Object,
Object => of_Object,
Scale => To));
end update_Scale;
procedure apply_Force (Self : in out Item; to_Object : in Object.view;
Force : in math.Vector_3)
is
begin
Self.Commands.add ((Kind => apply_Force,
Object => to_Object,
Force => Force));
end apply_Force;
procedure update_Site (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3)
is
begin
put_Line ("physics engine: update_Site");
Self.Commands.add ((Kind => update_Site,
Object => of_Object,
Site => To));
end update_Site;
procedure set_Speed (Self : in out Item; of_Object : in Object.view;
To : in math.Vector_3)
is
begin
Self.Commands.add ((Kind => set_Speed,
Object => of_Object,
Speed => To));
end set_Speed;
procedure set_Gravity (Self : in out Item; To : in math.Vector_3)
is
begin
Self.Commands.add ((Kind => set_Gravity,
Object => null,
Gravity => To));
end set_Gravity;
procedure set_xy_Spin (Self : in out Item; of_Object : in Object.view;
To : in math.Radians)
is
begin
Self.Commands.add ((Kind => set_xy_Spin,
Object => of_Object,
xy_Spin => To));
end set_xy_Spin;
procedure update_Bounds (Self : in out Item; of_Object : in Object.view)
is
begin
Self.Commands.add ((Kind => update_Bounds,
Object => of_Object));
end update_Bounds;
procedure set_local_Anchor (Self : in out Item; for_Joint : in Joint.view;
To : in math.Vector_3;
is_Anchor_A : in Boolean)
is
begin
Self.Commands.add ((Kind => set_Joint_local_Anchor,
Object => null,
anchor_Joint => for_Joint,
local_Anchor => To,
is_Anchor_A => is_Anchor_A));
end set_local_Anchor;
end physics.Engine;
|
-----------------------------------------------------------------------
-- net-protos-dispatchers -- Network protocol dispatchers
-- Copyright (C) 2016, 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 Net.Buffers;
with Net.Interfaces;
package Net.Protos.Dispatchers is
-- Set a protocol handler to deal with a packet of the given protocol when it is received.
-- Return the previous protocol handler.
procedure Set_Handler (Proto : in Net.Uint8;
Handler : in Receive_Handler;
Previous : out Receive_Handler);
-- Receive an IPv4 packet and dispatch it according to the protocol.
procedure Receive (Ifnet : in out Net.Interfaces.Ifnet_Type'Class;
Packet : in out Net.Buffers.Buffer_Type) with
Pre => not Packet.Is_Null;
end Net.Protos.Dispatchers;
|
package Natools.Static_Maps.Web.Simple_Pages.Commands is
pragma Pure;
function Hash (S : String) return Natural;
end Natools.Static_Maps.Web.Simple_Pages.Commands;
|
-- Copyright 2013-2014 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
package Pck is
I : Integer := 1;
end Pck;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M L I B . P R J --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 2001, Ada Core Technologies, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- It is now maintained by Ada Core Technologies Inc (http://www.gnat.com). --
-- --
------------------------------------------------------------------------------
-- This package builds a library for a library project file
with Prj; use Prj;
package MLib.Prj is
procedure Build_Library (For_Project : Project_Id);
-- Build the library of library project For_Project
-- Fails if For_Project is not a library project file
end MLib.Prj;
|
--//////////////////////////////////////////////////////////
-- SFML - Simple and Fast Multimedia Library
-- Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org)
-- This software is provided 'as-is', without any express or implied warranty.
-- In no event will the authors be held liable for any damages arising from the use of this software.
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it freely,
-- subject to the following restrictions:
-- 1. The origin of this software must not be misrepresented;
-- you must not claim that you wrote the original software.
-- If you use this software in a product, an acknowledgment
-- in the product documentation would be appreciated but is not required.
-- 2. Altered source versions must be plainly marked as such,
-- and must not be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
package Sf.Window.Clipboard is
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--//////////////////////////////////////////////////////////
--/ @brief Get the content of the clipboard as string data (returns an ANSI string)
--/
--/ This function returns the content of the clipboard
--/ as a string. If the clipboard does not contain string
--/ it returns an empty string.
--/
--/ @return Clipboard contents as a locale-dependent ANSI string
--/
--//////////////////////////////////////////////////////////
function getString return String;
--//////////////////////////////////////////////////////////
--/ @brief Get the content of the clipboard as string data (returns a Unicode string)
--/
--/ This function returns the content of the clipboard
--/ as a string. If the clipboard does not contain string
--/ it returns an empty string.
--/
--/ @return Clipboard contents as UTF-32
--/
--//////////////////////////////////////////////////////////
function getUnicodeString return access sfUint32;
--//////////////////////////////////////////////////////////
--/ @brief Set the content of the clipboard as ANSI string data
--/
--/ This function sets the content of the clipboard as an
--/ ANSI string.
--/
--/ @param text ANSI string containing the data to be sent
--/ to the clipboard
--/
--//////////////////////////////////////////////////////////
procedure setString (text : String);
--//////////////////////////////////////////////////////////
--/ @brief Set the content of the clipboard as Unicode string data
--/
--/ This function sets the content of the clipboard as a
--/ Unicode string.
--/
--/ @param text Unicode string containing the data to be sent
--/ to the clipboard
--/
--//////////////////////////////////////////////////////////
procedure setUnicodeString (text : access sfUint32);
private
pragma Import (C, getUnicodeString, "sfClipboard_getUnicodeString");
pragma Import (C, setUnicodeString, "sfClipboard_setUnicodeString");
end Sf.Window.Clipboard;
|
------------------------------------------------------------------------------
-- G E L A A S I S --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of this file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $:
-- Purpose:
-- Container for befin, end and comment position for each source line
with Gela.Source_Buffers;
with Gela.Containers.Vectors;
use Gela;
package Asis.Gela.Lines is
pragma Preelaborate;
type Line is record
From, To, Comment : Source_Buffers.Cursor;
end record;
package Vectors is new Containers.Vectors (Line, ASIS_Positive);
subtype Vector is Vectors.Vector;
end Asis.Gela.Lines;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . P A C K _ 2 6 --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2014, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- 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 System.Storage_Elements;
with System.Unsigned_Types;
package body System.Pack_26 is
subtype Bit_Order is System.Bit_Order;
Reverse_Bit_Order : constant Bit_Order :=
Bit_Order'Val (1 - Bit_Order'Pos (System.Default_Bit_Order));
subtype Ofs is System.Storage_Elements.Storage_Offset;
subtype Uns is System.Unsigned_Types.Unsigned;
subtype N07 is System.Unsigned_Types.Unsigned range 0 .. 7;
use type System.Storage_Elements.Storage_Offset;
use type System.Unsigned_Types.Unsigned;
type Cluster is record
E0, E1, E2, E3, E4, E5, E6, E7 : Bits_26;
end record;
for Cluster use record
E0 at 0 range 0 * Bits .. 0 * Bits + Bits - 1;
E1 at 0 range 1 * Bits .. 1 * Bits + Bits - 1;
E2 at 0 range 2 * Bits .. 2 * Bits + Bits - 1;
E3 at 0 range 3 * Bits .. 3 * Bits + Bits - 1;
E4 at 0 range 4 * Bits .. 4 * Bits + Bits - 1;
E5 at 0 range 5 * Bits .. 5 * Bits + Bits - 1;
E6 at 0 range 6 * Bits .. 6 * Bits + Bits - 1;
E7 at 0 range 7 * Bits .. 7 * Bits + Bits - 1;
end record;
for Cluster'Size use Bits * 8;
for Cluster'Alignment use Integer'Min (Standard'Maximum_Alignment,
1 +
1 * Boolean'Pos (Bits mod 2 = 0) +
2 * Boolean'Pos (Bits mod 4 = 0));
-- Use maximum possible alignment, given the bit field size, since this
-- will result in the most efficient code possible for the field.
type Cluster_Ref is access Cluster;
type Rev_Cluster is new Cluster
with Bit_Order => Reverse_Bit_Order,
Scalar_Storage_Order => Reverse_Bit_Order;
type Rev_Cluster_Ref is access Rev_Cluster;
-- The following declarations are for the case where the address
-- passed to GetU_26 or SetU_26 is not guaranteed to be aligned.
-- These routines are used when the packed array is itself a
-- component of a packed record, and therefore may not be aligned.
type ClusterU is new Cluster;
for ClusterU'Alignment use 1;
type ClusterU_Ref is access ClusterU;
type Rev_ClusterU is new ClusterU
with Bit_Order => Reverse_Bit_Order,
Scalar_Storage_Order => Reverse_Bit_Order;
type Rev_ClusterU_Ref is access Rev_ClusterU;
------------
-- Get_26 --
------------
function Get_26
(Arr : System.Address;
N : Natural;
Rev_SSO : Boolean) return Bits_26
is
A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8);
C : Cluster_Ref with Address => A'Address, Import;
RC : Rev_Cluster_Ref with Address => A'Address, Import;
begin
if Rev_SSO then
case N07 (Uns (N) mod 8) is
when 0 => return RC.E0;
when 1 => return RC.E1;
when 2 => return RC.E2;
when 3 => return RC.E3;
when 4 => return RC.E4;
when 5 => return RC.E5;
when 6 => return RC.E6;
when 7 => return RC.E7;
end case;
else
case N07 (Uns (N) mod 8) is
when 0 => return C.E0;
when 1 => return C.E1;
when 2 => return C.E2;
when 3 => return C.E3;
when 4 => return C.E4;
when 5 => return C.E5;
when 6 => return C.E6;
when 7 => return C.E7;
end case;
end if;
end Get_26;
-------------
-- GetU_26 --
-------------
function GetU_26
(Arr : System.Address;
N : Natural;
Rev_SSO : Boolean) return Bits_26
is
A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8);
C : ClusterU_Ref with Address => A'Address, Import;
RC : Rev_ClusterU_Ref with Address => A'Address, Import;
begin
if Rev_SSO then
case N07 (Uns (N) mod 8) is
when 0 => return RC.E0;
when 1 => return RC.E1;
when 2 => return RC.E2;
when 3 => return RC.E3;
when 4 => return RC.E4;
when 5 => return RC.E5;
when 6 => return RC.E6;
when 7 => return RC.E7;
end case;
else
case N07 (Uns (N) mod 8) is
when 0 => return C.E0;
when 1 => return C.E1;
when 2 => return C.E2;
when 3 => return C.E3;
when 4 => return C.E4;
when 5 => return C.E5;
when 6 => return C.E6;
when 7 => return C.E7;
end case;
end if;
end GetU_26;
------------
-- Set_26 --
------------
procedure Set_26
(Arr : System.Address;
N : Natural;
E : Bits_26;
Rev_SSO : Boolean)
is
A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8);
C : Cluster_Ref with Address => A'Address, Import;
RC : Rev_Cluster_Ref with Address => A'Address, Import;
begin
if Rev_SSO then
case N07 (Uns (N) mod 8) is
when 0 => RC.E0 := E;
when 1 => RC.E1 := E;
when 2 => RC.E2 := E;
when 3 => RC.E3 := E;
when 4 => RC.E4 := E;
when 5 => RC.E5 := E;
when 6 => RC.E6 := E;
when 7 => RC.E7 := E;
end case;
else
case N07 (Uns (N) mod 8) is
when 0 => C.E0 := E;
when 1 => C.E1 := E;
when 2 => C.E2 := E;
when 3 => C.E3 := E;
when 4 => C.E4 := E;
when 5 => C.E5 := E;
when 6 => C.E6 := E;
when 7 => C.E7 := E;
end case;
end if;
end Set_26;
-------------
-- SetU_26 --
-------------
procedure SetU_26
(Arr : System.Address;
N : Natural;
E : Bits_26;
Rev_SSO : Boolean)
is
A : constant System.Address := Arr + Bits * Ofs (Uns (N) / 8);
C : ClusterU_Ref with Address => A'Address, Import;
RC : Rev_ClusterU_Ref with Address => A'Address, Import;
begin
if Rev_SSO then
case N07 (Uns (N) mod 8) is
when 0 => RC.E0 := E;
when 1 => RC.E1 := E;
when 2 => RC.E2 := E;
when 3 => RC.E3 := E;
when 4 => RC.E4 := E;
when 5 => RC.E5 := E;
when 6 => RC.E6 := E;
when 7 => RC.E7 := E;
end case;
else
case N07 (Uns (N) mod 8) is
when 0 => C.E0 := E;
when 1 => C.E1 := E;
when 2 => C.E2 := E;
when 3 => C.E3 := E;
when 4 => C.E4 := E;
when 5 => C.E5 := E;
when 6 => C.E6 := E;
when 7 => C.E7 := E;
end case;
end if;
end SetU_26;
end System.Pack_26;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- A D A . W I D E _ W I D E _ T E X T _ I O . C O M P L E X _ A U X --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This package contains the routines for Ada.Wide_Wide_Text_IO.Complex_IO
-- that are shared among separate instantiations of this package. The routines
-- in this package are identical semantically to those in Complex_IO itself,
-- except that the generic parameter Complex has been replaced by separate
-- real and imaginary values of type Long_Long_Float, and default parameters
-- have been removed because they are supplied explicitly by the calls from
-- within the generic template.
package Ada.Wide_Wide_Text_IO.Complex_Aux is
procedure Get
(File : File_Type;
ItemR : out Long_Long_Float;
ItemI : out Long_Long_Float;
Width : Field);
procedure Gets
(From : String;
ItemR : out Long_Long_Float;
ItemI : out Long_Long_Float;
Last : out Positive);
procedure Put
(File : File_Type;
ItemR : Long_Long_Float;
ItemI : Long_Long_Float;
Fore : Field;
Aft : Field;
Exp : Field);
procedure Puts
(To : out String;
ItemR : Long_Long_Float;
ItemI : Long_Long_Float;
Aft : Field;
Exp : Field);
end Ada.Wide_Wide_Text_IO.Complex_Aux;
|
------------------------------------------------------------------------------
-- --
-- AUDIO / RIFF --
-- --
-- Common RIFF information for wavefiles --
-- --
-- The MIT License (MIT) --
-- --
-- Copyright (c) 2020 Gustavo A. Hoffmann --
-- --
-- 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. --
------------------------------------------------------------------------------
package Audio.RIFF.Wav with Pure is
end Audio.RIFF.Wav;
|
------------------------------------------------------------------------------
-- --
-- GNAT RUN-TIME COMPONENTS --
-- --
-- S Y S T E M . W W D _ C H A R --
-- --
-- B o d y --
-- --
-- Copyright (C) 1992-2009, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
package body System.WWd_Char is
--------------------------
-- Wide_Width_Character --
--------------------------
function Wide_Width_Character (Lo, Hi : Character) return Natural is
W : Natural;
begin
W := 0;
for C in Lo .. Hi loop
declare
S : constant Wide_String := Character'Wide_Image (C);
begin
W := Natural'Max (W, S'Length);
end;
end loop;
return W;
end Wide_Width_Character;
-------------------------------
-- Wide_Wide_Width_Character --
-------------------------------
function Wide_Wide_Width_Character (Lo, Hi : Character) return Natural is
W : Natural;
begin
W := 0;
for C in Lo .. Hi loop
declare
S : constant String := Character'Image (C);
begin
W := Natural'Max (W, S'Length);
end;
end loop;
return W;
end Wide_Wide_Width_Character;
end System.WWd_Char;
|
------------------------------------------------------------------------------
-- --
-- GNAT LIBRARY COMPONENTS --
-- --
-- G N A T . R E G P A T --
-- --
-- B o d y --
-- --
-- Copyright (C) 1986 by University of Toronto. --
-- Copyright (C) 1999-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. --
-- --
------------------------------------------------------------------------------
-- This is an altered Ada 95 version of the original V8 style regular
-- expression library written in C by Henry Spencer. Apart from the
-- translation to Ada, the interface has been considerably changed to
-- use the Ada String type instead of C-style nul-terminated strings.
-- Beware that some of this code is subtly aware of the way operator
-- precedence is structured in regular expressions. Serious changes in
-- regular-expression syntax might require a total rethink.
with System.IO; use System.IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Unchecked_Conversion;
package body System.Regpat is
Debug : constant Boolean := False;
-- Set to True to activate debug traces. This is normally set to constant
-- False to simply delete all the trace code. It is to be edited to True
-- for internal debugging of the package.
----------------------------
-- Implementation details --
----------------------------
-- This is essentially a linear encoding of a nondeterministic
-- finite-state machine, also known as syntax charts or
-- "railroad normal form" in parsing technology.
-- Each node is an opcode plus a "next" pointer, possibly plus an
-- operand. "Next" pointers of all nodes except BRANCH implement
-- concatenation; a "next" pointer with a BRANCH on both ends of it
-- is connecting two alternatives.
-- The operand of some types of node is a literal string; for others,
-- it is a node leading into a sub-FSM. In particular, the operand of
-- a BRANCH node is the first node of the branch.
-- (NB this is *not* a tree structure: the tail of the branch connects
-- to the thing following the set of BRANCHes).
-- You can see the exact byte-compiled version by using the Dump
-- subprogram. However, here are a few examples:
-- (a|b): 1 : BRANCH (next at 9)
-- 4 : EXACT (next at 17) operand=a
-- 9 : BRANCH (next at 17)
-- 12 : EXACT (next at 17) operand=b
-- 17 : EOP (next at 0)
--
-- (ab)*: 1 : CURLYX (next at 25) { 0, 32767}
-- 8 : OPEN 1 (next at 12)
-- 12 : EXACT (next at 18) operand=ab
-- 18 : CLOSE 1 (next at 22)
-- 22 : WHILEM (next at 0)
-- 25 : NOTHING (next at 28)
-- 28 : EOP (next at 0)
-- The opcodes are:
type Opcode is
-- Name Operand? Meaning
(EOP, -- no End of program
MINMOD, -- no Next operator is not greedy
-- Classes of characters
ANY, -- no Match any one character except newline
SANY, -- no Match any character, including new line
ANYOF, -- class Match any character in this class
EXACT, -- str Match this string exactly
EXACTF, -- str Match this string (case-folding is one)
NOTHING, -- no Match empty string
SPACE, -- no Match any whitespace character
NSPACE, -- no Match any non-whitespace character
DIGIT, -- no Match any numeric character
NDIGIT, -- no Match any non-numeric character
ALNUM, -- no Match any alphanumeric character
NALNUM, -- no Match any non-alphanumeric character
-- Branches
BRANCH, -- node Match this alternative, or the next
-- Simple loops (when the following node is one character in length)
STAR, -- node Match this simple thing 0 or more times
PLUS, -- node Match this simple thing 1 or more times
CURLY, -- 2num node Match this simple thing between n and m times.
-- Complex loops
CURLYX, -- 2num node Match this complex thing {n,m} times
-- The nums are coded on two characters each
WHILEM, -- no Do curly processing and see if rest matches
-- Matches after or before a word
BOL, -- no Match "" at beginning of line
MBOL, -- no Same, assuming multiline (match after \n)
SBOL, -- no Same, assuming single line (don't match at \n)
EOL, -- no Match "" at end of line
MEOL, -- no Same, assuming multiline (match before \n)
SEOL, -- no Same, assuming single line (don't match at \n)
BOUND, -- no Match "" at any word boundary
NBOUND, -- no Match "" at any word non-boundary
-- Parenthesis groups handling
REFF, -- num Match some already matched string, folded
OPEN, -- num Mark this point in input as start of #n
CLOSE); -- num Analogous to OPEN
for Opcode'Size use 8;
-- Opcode notes:
-- BRANCH
-- The set of branches constituting a single choice are hooked
-- together with their "next" pointers, since precedence prevents
-- anything being concatenated to any individual branch. The
-- "next" pointer of the last BRANCH in a choice points to the
-- thing following the whole choice. This is also where the
-- final "next" pointer of each individual branch points; each
-- branch starts with the operand node of a BRANCH node.
-- STAR,PLUS
-- '?', and complex '*' and '+', are implemented with CURLYX.
-- branches. Simple cases (one character per match) are implemented with
-- STAR and PLUS for speed and to minimize recursive plunges.
-- OPEN,CLOSE
-- ...are numbered at compile time.
-- EXACT, EXACTF
-- There are in fact two arguments, the first one is the length (minus
-- one of the string argument), coded on one character, the second
-- argument is the string itself, coded on length + 1 characters.
-- A node is one char of opcode followed by two chars of "next" pointer.
-- "Next" pointers are stored as two 8-bit pieces, high order first. The
-- value is a positive offset from the opcode of the node containing it.
-- An operand, if any, simply follows the node. (Note that much of the
-- code generation knows about this implicit relationship.)
-- Using two bytes for the "next" pointer is vast overkill for most
-- things, but allows patterns to get big without disasters.
Next_Pointer_Bytes : constant := 3;
-- Points after the "next pointer" data. An instruction is therefore:
-- 1 byte: instruction opcode
-- 2 bytes: pointer to next instruction
-- * bytes: optional data for the instruction
-----------------------
-- Character classes --
-----------------------
-- This is the implementation for character classes ([...]) in the
-- syntax for regular expressions. Each character (0..256) has an
-- entry into the table. This makes for a very fast matching
-- algorithm.
type Class_Byte is mod 256;
type Character_Class is array (Class_Byte range 0 .. 31) of Class_Byte;
type Bit_Conversion_Array is array (Class_Byte range 0 .. 7) of Class_Byte;
Bit_Conversion : constant Bit_Conversion_Array :=
(1, 2, 4, 8, 16, 32, 64, 128);
type Std_Class is (ANYOF_NONE,
ANYOF_ALNUM, -- Alphanumeric class [a-zA-Z0-9]
ANYOF_NALNUM,
ANYOF_SPACE, -- Space class [ \t\n\r\f]
ANYOF_NSPACE,
ANYOF_DIGIT, -- Digit class [0-9]
ANYOF_NDIGIT,
ANYOF_ALNUMC, -- Alphanumeric class [a-zA-Z0-9]
ANYOF_NALNUMC,
ANYOF_ALPHA, -- Alpha class [a-zA-Z]
ANYOF_NALPHA,
ANYOF_ASCII, -- Ascii class (7 bits) 0..127
ANYOF_NASCII,
ANYOF_CNTRL, -- Control class
ANYOF_NCNTRL,
ANYOF_GRAPH, -- Graphic class
ANYOF_NGRAPH,
ANYOF_LOWER, -- Lower case class [a-z]
ANYOF_NLOWER,
ANYOF_PRINT, -- printable class
ANYOF_NPRINT,
ANYOF_PUNCT, --
ANYOF_NPUNCT,
ANYOF_UPPER, -- Upper case class [A-Z]
ANYOF_NUPPER,
ANYOF_XDIGIT, -- Hexadecimal digit
ANYOF_NXDIGIT
);
procedure Set_In_Class
(Bitmap : in out Character_Class;
C : Character);
-- Set the entry to True for C in the class Bitmap
function Get_From_Class
(Bitmap : Character_Class;
C : Character) return Boolean;
-- Return True if the entry is set for C in the class Bitmap
procedure Reset_Class (Bitmap : out Character_Class);
-- Clear all the entries in the class Bitmap
pragma Inline (Set_In_Class);
pragma Inline (Get_From_Class);
pragma Inline (Reset_Class);
-----------------------
-- Local Subprograms --
-----------------------
function "=" (Left : Character; Right : Opcode) return Boolean;
function Is_Alnum (C : Character) return Boolean;
-- Return True if C is an alphanum character or an underscore ('_')
function Is_White_Space (C : Character) return Boolean;
-- Return True if C is a whitespace character
function Is_Printable (C : Character) return Boolean;
-- Return True if C is a printable character
function Operand (P : Pointer) return Pointer;
-- Return a pointer to the first operand of the node at P
function String_Length
(Program : Program_Data;
P : Pointer) return Program_Size;
-- Return the length of the string argument of the node at P
function String_Operand (P : Pointer) return Pointer;
-- Return a pointer to the string argument of the node at P
procedure Bitmap_Operand
(Program : Program_Data;
P : Pointer;
Op : out Character_Class);
-- Return a pointer to the string argument of the node at P
function Get_Next
(Program : Program_Data;
IP : Pointer) return Pointer;
-- Dig the next instruction pointer out of a node
procedure Optimize (Self : in out Pattern_Matcher);
-- Optimize a Pattern_Matcher by noting certain special cases
function Read_Natural
(Program : Program_Data;
IP : Pointer) return Natural;
-- Return the 2-byte natural coded at position IP
-- All of the subprograms above are tiny and should be inlined
pragma Inline ("=");
pragma Inline (Is_Alnum);
pragma Inline (Is_White_Space);
pragma Inline (Get_Next);
pragma Inline (Operand);
pragma Inline (Read_Natural);
pragma Inline (String_Length);
pragma Inline (String_Operand);
type Expression_Flags is record
Has_Width, -- Known never to match null string
Simple, -- Simple enough to be STAR/PLUS operand
SP_Start : Boolean; -- Starts with * or +
end record;
Worst_Expression : constant Expression_Flags := (others => False);
-- Worst case
procedure Dump_Until
(Program : Program_Data;
Index : in out Pointer;
Till : Pointer;
Indent : Natural;
Do_Print : Boolean := True);
-- Dump the program until the node Till (not included) is met. Every line
-- is indented with Index spaces at the beginning Dumps till the end if
-- Till is 0.
procedure Dump_Operation
(Program : Program_Data;
Index : Pointer;
Indent : Natural);
-- Same as above, but only dumps a single operation, and compute its
-- indentation from the program.
---------
-- "=" --
---------
function "=" (Left : Character; Right : Opcode) return Boolean is
begin
return Character'Pos (Left) = Opcode'Pos (Right);
end "=";
--------------------
-- Bitmap_Operand --
--------------------
procedure Bitmap_Operand
(Program : Program_Data;
P : Pointer;
Op : out Character_Class)
is
function Convert is new Ada.Unchecked_Conversion
(Program_Data, Character_Class);
begin
Op (0 .. 31) := Convert (Program (P + Next_Pointer_Bytes .. P + 34));
end Bitmap_Operand;
-------------
-- Compile --
-------------
procedure Compile
(Matcher : out Pattern_Matcher;
Expression : String;
Final_Code_Size : out Program_Size;
Flags : Regexp_Flags := No_Flags)
is
-- We can't allocate space until we know how big the compiled form
-- will be, but we can't compile it (and thus know how big it is)
-- until we've got a place to put the code. So we cheat: we compile
-- it twice, once with code generation turned off and size counting
-- turned on, and once "for real".
-- This also means that we don't allocate space until we are sure
-- that the thing really will compile successfully, and we never
-- have to move the code and thus invalidate pointers into it.
-- Beware that the optimization-preparation code in here knows
-- about some of the structure of the compiled regexp.
PM : Pattern_Matcher renames Matcher;
Program : Program_Data renames PM.Program;
Emit_Ptr : Pointer := Program_First;
Parse_Pos : Natural := Expression'First; -- Input-scan pointer
Parse_End : constant Natural := Expression'Last;
----------------------------
-- Subprograms for Create --
----------------------------
procedure Emit (B : Character);
-- Output the Character B to the Program. If code-generation is
-- disabled, simply increments the program counter.
function Emit_Node (Op : Opcode) return Pointer;
-- If code-generation is enabled, Emit_Node outputs the
-- opcode Op and reserves space for a pointer to the next node.
-- Return value is the location of new opcode, i.e. old Emit_Ptr.
procedure Emit_Natural (IP : Pointer; N : Natural);
-- Split N on two characters at position IP
procedure Emit_Class (Bitmap : Character_Class);
-- Emits a character class
procedure Case_Emit (C : Character);
-- Emit C, after converting is to lower-case if the regular
-- expression is case insensitive.
procedure Parse
(Parenthesized : Boolean;
Capturing : Boolean;
Flags : out Expression_Flags;
IP : out Pointer);
-- Parse regular expression, i.e. main body or parenthesized thing.
-- Caller must absorb opening parenthesis. Capturing should be set to
-- True when we have an open parenthesis from which we want the user
-- to extra text.
procedure Parse_Branch
(Flags : out Expression_Flags;
First : Boolean;
IP : out Pointer);
-- Implements the concatenation operator and handles '|'.
-- First should be true if this is the first item of the alternative.
procedure Parse_Piece
(Expr_Flags : out Expression_Flags;
IP : out Pointer);
-- Parse something followed by possible [*+?]
procedure Parse_Atom
(Expr_Flags : out Expression_Flags;
IP : out Pointer);
-- Parse_Atom is the lowest level parse procedure.
--
-- Optimization: Gobbles an entire sequence of ordinary characters so
-- that it can turn them into a single node, which is smaller to store
-- and faster to run. Backslashed characters are exceptions, each
-- becoming a separate node; the code is simpler that way and it's
-- not worth fixing.
procedure Insert_Operator
(Op : Opcode;
Operand : Pointer;
Greedy : Boolean := True);
-- Insert_Operator inserts an operator in front of an already-emitted
-- operand and relocates the operand. This applies to PLUS and STAR.
-- If Minmod is True, then the operator is non-greedy.
function Insert_Operator_Before
(Op : Opcode;
Operand : Pointer;
Greedy : Boolean;
Opsize : Pointer) return Pointer;
-- Insert an operator before Operand (and move the latter forward in the
-- program). Opsize is the size needed to represent the operator. This
-- returns the position at which the operator was inserted, and moves
-- Emit_Ptr after the new position of the operand.
procedure Insert_Curly_Operator
(Op : Opcode;
Min : Natural;
Max : Natural;
Operand : Pointer;
Greedy : Boolean := True);
-- Insert an operator for CURLY ({Min}, {Min,} or {Min,Max}).
-- If Minmod is True, then the operator is non-greedy.
procedure Link_Tail (P, Val : Pointer);
-- Link_Tail sets the next-pointer at the end of a node chain
procedure Link_Operand_Tail (P, Val : Pointer);
-- Link_Tail on operand of first argument; noop if operand-less
procedure Fail (M : String);
pragma No_Return (Fail);
-- Fail with a diagnostic message, if possible
function Is_Curly_Operator (IP : Natural) return Boolean;
-- Return True if IP is looking at a '{' that is the beginning
-- of a curly operator, i.e. it matches {\d+,?\d*}
function Is_Mult (IP : Natural) return Boolean;
-- Return True if C is a regexp multiplier: '+', '*' or '?'
procedure Get_Curly_Arguments
(IP : Natural;
Min : out Natural;
Max : out Natural;
Greedy : out Boolean);
-- Parse the argument list for a curly operator.
-- It is assumed that IP is indeed pointing at a valid operator.
-- So what is IP and how come IP is not referenced in the body ???
procedure Parse_Character_Class (IP : out Pointer);
-- Parse a character class.
-- The calling subprogram should consume the opening '[' before.
procedure Parse_Literal
(Expr_Flags : out Expression_Flags;
IP : out Pointer);
-- Parse_Literal encodes a string of characters to be matched exactly
function Parse_Posix_Character_Class return Std_Class;
-- Parse a posix character class, like [:alpha:] or [:^alpha:].
-- The caller is supposed to absorb the opening [.
pragma Inline (Is_Mult);
pragma Inline (Emit_Natural);
pragma Inline (Parse_Character_Class); -- since used only once
---------------
-- Case_Emit --
---------------
procedure Case_Emit (C : Character) is
begin
if (Flags and Case_Insensitive) /= 0 then
Emit (To_Lower (C));
else
-- Dump current character
Emit (C);
end if;
end Case_Emit;
----------
-- Emit --
----------
procedure Emit (B : Character) is
begin
if Emit_Ptr <= PM.Size then
Program (Emit_Ptr) := B;
end if;
Emit_Ptr := Emit_Ptr + 1;
end Emit;
----------------
-- Emit_Class --
----------------
procedure Emit_Class (Bitmap : Character_Class) is
subtype Program31 is Program_Data (0 .. 31);
function Convert is new Ada.Unchecked_Conversion
(Character_Class, Program31);
begin
-- What is the mysterious constant 31 here??? Can't it be expressed
-- symbolically (size of integer - 1 or some such???). In any case
-- it should be declared as a constant (and referenced presumably
-- as this constant + 1 below.
if Emit_Ptr + 31 <= PM.Size then
Program (Emit_Ptr .. Emit_Ptr + 31) := Convert (Bitmap);
end if;
Emit_Ptr := Emit_Ptr + 32;
end Emit_Class;
------------------
-- Emit_Natural --
------------------
procedure Emit_Natural (IP : Pointer; N : Natural) is
begin
if IP + 1 <= PM.Size then
Program (IP + 1) := Character'Val (N / 256);
Program (IP) := Character'Val (N mod 256);
end if;
end Emit_Natural;
---------------
-- Emit_Node --
---------------
function Emit_Node (Op : Opcode) return Pointer is
Result : constant Pointer := Emit_Ptr;
begin
if Emit_Ptr + 2 <= PM.Size then
Program (Emit_Ptr) := Character'Val (Opcode'Pos (Op));
Program (Emit_Ptr + 1) := ASCII.NUL;
Program (Emit_Ptr + 2) := ASCII.NUL;
end if;
Emit_Ptr := Emit_Ptr + Next_Pointer_Bytes;
return Result;
end Emit_Node;
----------
-- Fail --
----------
procedure Fail (M : String) is
begin
raise Expression_Error with M;
end Fail;
-------------------------
-- Get_Curly_Arguments --
-------------------------
procedure Get_Curly_Arguments
(IP : Natural;
Min : out Natural;
Max : out Natural;
Greedy : out Boolean)
is
pragma Unreferenced (IP);
Save_Pos : Natural := Parse_Pos + 1;
begin
Min := 0;
Max := Max_Curly_Repeat;
while Expression (Parse_Pos) /= '}'
and then Expression (Parse_Pos) /= ','
loop
Parse_Pos := Parse_Pos + 1;
end loop;
Min := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1));
if Expression (Parse_Pos) = ',' then
Save_Pos := Parse_Pos + 1;
while Expression (Parse_Pos) /= '}' loop
Parse_Pos := Parse_Pos + 1;
end loop;
if Save_Pos /= Parse_Pos then
Max := Natural'Value (Expression (Save_Pos .. Parse_Pos - 1));
end if;
else
Max := Min;
end if;
if Parse_Pos < Expression'Last
and then Expression (Parse_Pos + 1) = '?'
then
Greedy := False;
Parse_Pos := Parse_Pos + 1;
else
Greedy := True;
end if;
end Get_Curly_Arguments;
---------------------------
-- Insert_Curly_Operator --
---------------------------
procedure Insert_Curly_Operator
(Op : Opcode;
Min : Natural;
Max : Natural;
Operand : Pointer;
Greedy : Boolean := True)
is
Old : Pointer;
begin
Old := Insert_Operator_Before (Op, Operand, Greedy, Opsize => 7);
Emit_Natural (Old + Next_Pointer_Bytes, Min);
Emit_Natural (Old + Next_Pointer_Bytes + 2, Max);
end Insert_Curly_Operator;
----------------------------
-- Insert_Operator_Before --
----------------------------
function Insert_Operator_Before
(Op : Opcode;
Operand : Pointer;
Greedy : Boolean;
Opsize : Pointer) return Pointer
is
Dest : constant Pointer := Emit_Ptr;
Old : Pointer;
Size : Pointer := Opsize;
begin
-- If not greedy, we have to emit another opcode first
if not Greedy then
Size := Size + Next_Pointer_Bytes;
end if;
-- Move the operand in the byte-compilation, so that we can insert
-- the operator before it.
if Emit_Ptr + Size <= PM.Size then
Program (Operand + Size .. Emit_Ptr + Size) :=
Program (Operand .. Emit_Ptr);
end if;
-- Insert the operator at the position previously occupied by the
-- operand.
Emit_Ptr := Operand;
if not Greedy then
Old := Emit_Node (MINMOD);
Link_Tail (Old, Old + Next_Pointer_Bytes);
end if;
Old := Emit_Node (Op);
Emit_Ptr := Dest + Size;
return Old;
end Insert_Operator_Before;
---------------------
-- Insert_Operator --
---------------------
procedure Insert_Operator
(Op : Opcode;
Operand : Pointer;
Greedy : Boolean := True)
is
Discard : Pointer;
pragma Warnings (Off, Discard);
begin
Discard := Insert_Operator_Before
(Op, Operand, Greedy, Opsize => Next_Pointer_Bytes);
end Insert_Operator;
-----------------------
-- Is_Curly_Operator --
-----------------------
function Is_Curly_Operator (IP : Natural) return Boolean is
Scan : Natural := IP;
begin
if Expression (Scan) /= '{'
or else Scan + 2 > Expression'Last
or else not Is_Digit (Expression (Scan + 1))
then
return False;
end if;
Scan := Scan + 1;
-- The first digit
loop
Scan := Scan + 1;
if Scan > Expression'Last then
return False;
end if;
exit when not Is_Digit (Expression (Scan));
end loop;
if Expression (Scan) = ',' then
loop
Scan := Scan + 1;
if Scan > Expression'Last then
return False;
end if;
exit when not Is_Digit (Expression (Scan));
end loop;
end if;
return Expression (Scan) = '}';
end Is_Curly_Operator;
-------------
-- Is_Mult --
-------------
function Is_Mult (IP : Natural) return Boolean is
C : constant Character := Expression (IP);
begin
return C = '*'
or else C = '+'
or else C = '?'
or else (C = '{' and then Is_Curly_Operator (IP));
end Is_Mult;
-----------------------
-- Link_Operand_Tail --
-----------------------
procedure Link_Operand_Tail (P, Val : Pointer) is
begin
if P <= PM.Size and then Program (P) = BRANCH then
Link_Tail (Operand (P), Val);
end if;
end Link_Operand_Tail;
---------------
-- Link_Tail --
---------------
procedure Link_Tail (P, Val : Pointer) is
Scan : Pointer;
Temp : Pointer;
Offset : Pointer;
begin
-- Find last node (the size of the pattern matcher might be too
-- small, so don't try to read past its end).
Scan := P;
while Scan + Next_Pointer_Bytes <= PM.Size loop
Temp := Get_Next (Program, Scan);
exit when Temp = Scan;
Scan := Temp;
end loop;
Offset := Val - Scan;
Emit_Natural (Scan + 1, Natural (Offset));
end Link_Tail;
-----------
-- Parse --
-----------
-- Combining parenthesis handling with the base level of regular
-- expression is a trifle forced, but the need to tie the tails of the
-- the branches to what follows makes it hard to avoid.
procedure Parse
(Parenthesized : Boolean;
Capturing : Boolean;
Flags : out Expression_Flags;
IP : out Pointer)
is
E : String renames Expression;
Br, Br2 : Pointer;
Ender : Pointer;
Par_No : Natural;
New_Flags : Expression_Flags;
Have_Branch : Boolean := False;
begin
Flags := (Has_Width => True, others => False); -- Tentatively
-- Make an OPEN node, if parenthesized
if Parenthesized and then Capturing then
if Matcher.Paren_Count > Max_Paren_Count then
Fail ("too many ()");
end if;
Par_No := Matcher.Paren_Count + 1;
Matcher.Paren_Count := Matcher.Paren_Count + 1;
IP := Emit_Node (OPEN);
Emit (Character'Val (Par_No));
else
IP := 0;
Par_No := 0;
end if;
-- Pick up the branches, linking them together
Parse_Branch (New_Flags, True, Br);
if Br = 0 then
IP := 0;
return;
end if;
if Parse_Pos <= Parse_End
and then E (Parse_Pos) = '|'
then
Insert_Operator (BRANCH, Br);
Have_Branch := True;
end if;
if IP /= 0 then
Link_Tail (IP, Br); -- OPEN -> first
else
IP := Br;
end if;
if not New_Flags.Has_Width then
Flags.Has_Width := False;
end if;
Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start;
while Parse_Pos <= Parse_End
and then (E (Parse_Pos) = '|')
loop
Parse_Pos := Parse_Pos + 1;
Parse_Branch (New_Flags, False, Br);
if Br = 0 then
IP := 0;
return;
end if;
Link_Tail (IP, Br); -- BRANCH -> BRANCH
if not New_Flags.Has_Width then
Flags.Has_Width := False;
end if;
Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start;
end loop;
-- Make a closing node, and hook it on the end
if Parenthesized then
if Capturing then
Ender := Emit_Node (CLOSE);
Emit (Character'Val (Par_No));
Link_Tail (IP, Ender);
else
-- Need to keep looking after the closing parenthesis
Ender := Emit_Ptr;
end if;
else
Ender := Emit_Node (EOP);
Link_Tail (IP, Ender);
end if;
if Have_Branch and then Emit_Ptr <= PM.Size + 1 then
-- Hook the tails of the branches to the closing node
Br := IP;
loop
Link_Operand_Tail (Br, Ender);
Br2 := Get_Next (Program, Br);
exit when Br2 = Br;
Br := Br2;
end loop;
end if;
-- Check for proper termination
if Parenthesized then
if Parse_Pos > Parse_End or else E (Parse_Pos) /= ')' then
Fail ("unmatched ()");
end if;
Parse_Pos := Parse_Pos + 1;
elsif Parse_Pos <= Parse_End then
if E (Parse_Pos) = ')' then
Fail ("unmatched ')'");
else
Fail ("junk on end"); -- "Can't happen"
end if;
end if;
end Parse;
----------------
-- Parse_Atom --
----------------
procedure Parse_Atom
(Expr_Flags : out Expression_Flags;
IP : out Pointer)
is
C : Character;
begin
-- Tentatively set worst expression case
Expr_Flags := Worst_Expression;
C := Expression (Parse_Pos);
Parse_Pos := Parse_Pos + 1;
case (C) is
when '^' =>
IP :=
Emit_Node
(if (Flags and Multiple_Lines) /= 0 then MBOL
elsif (Flags and Single_Line) /= 0 then SBOL
else BOL);
when '$' =>
IP :=
Emit_Node
(if (Flags and Multiple_Lines) /= 0 then MEOL
elsif (Flags and Single_Line) /= 0 then SEOL
else EOL);
when '.' =>
IP :=
Emit_Node
(if (Flags and Single_Line) /= 0 then SANY else ANY);
Expr_Flags.Has_Width := True;
Expr_Flags.Simple := True;
when '[' =>
Parse_Character_Class (IP);
Expr_Flags.Has_Width := True;
Expr_Flags.Simple := True;
when '(' =>
declare
New_Flags : Expression_Flags;
begin
if Parse_Pos <= Parse_End - 1
and then Expression (Parse_Pos) = '?'
and then Expression (Parse_Pos + 1) = ':'
then
Parse_Pos := Parse_Pos + 2;
-- Non-capturing parenthesis
Parse (True, False, New_Flags, IP);
else
-- Capturing parenthesis
Parse (True, True, New_Flags, IP);
Expr_Flags.Has_Width :=
Expr_Flags.Has_Width or else New_Flags.Has_Width;
Expr_Flags.SP_Start :=
Expr_Flags.SP_Start or else New_Flags.SP_Start;
if IP = 0 then
return;
end if;
end if;
end;
when '|' | ASCII.LF | ')' =>
Fail ("internal urp"); -- Supposed to be caught earlier
when '?' | '+' | '*' =>
Fail (C & " follows nothing");
when '{' =>
if Is_Curly_Operator (Parse_Pos - 1) then
Fail (C & " follows nothing");
else
Parse_Literal (Expr_Flags, IP);
end if;
when '\' =>
if Parse_Pos > Parse_End then
Fail ("trailing \");
end if;
Parse_Pos := Parse_Pos + 1;
case Expression (Parse_Pos - 1) is
when 'b' =>
IP := Emit_Node (BOUND);
when 'B' =>
IP := Emit_Node (NBOUND);
when 's' =>
IP := Emit_Node (SPACE);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'S' =>
IP := Emit_Node (NSPACE);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'd' =>
IP := Emit_Node (DIGIT);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'D' =>
IP := Emit_Node (NDIGIT);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'w' =>
IP := Emit_Node (ALNUM);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'W' =>
IP := Emit_Node (NALNUM);
Expr_Flags.Simple := True;
Expr_Flags.Has_Width := True;
when 'A' =>
IP := Emit_Node (SBOL);
when 'G' =>
IP := Emit_Node (SEOL);
when '0' .. '9' =>
IP := Emit_Node (REFF);
declare
Save : constant Natural := Parse_Pos - 1;
begin
while Parse_Pos <= Expression'Last
and then Is_Digit (Expression (Parse_Pos))
loop
Parse_Pos := Parse_Pos + 1;
end loop;
Emit (Character'Val (Natural'Value
(Expression (Save .. Parse_Pos - 1))));
end;
when others =>
Parse_Pos := Parse_Pos - 1;
Parse_Literal (Expr_Flags, IP);
end case;
when others =>
Parse_Literal (Expr_Flags, IP);
end case;
end Parse_Atom;
------------------
-- Parse_Branch --
------------------
procedure Parse_Branch
(Flags : out Expression_Flags;
First : Boolean;
IP : out Pointer)
is
E : String renames Expression;
Chain : Pointer;
Last : Pointer;
New_Flags : Expression_Flags;
Discard : Pointer;
pragma Warnings (Off, Discard);
begin
Flags := Worst_Expression; -- Tentatively
IP := (if First then Emit_Ptr else Emit_Node (BRANCH));
Chain := 0;
while Parse_Pos <= Parse_End
and then E (Parse_Pos) /= ')'
and then E (Parse_Pos) /= ASCII.LF
and then E (Parse_Pos) /= '|'
loop
Parse_Piece (New_Flags, Last);
if Last = 0 then
IP := 0;
return;
end if;
Flags.Has_Width := Flags.Has_Width or else New_Flags.Has_Width;
if Chain = 0 then -- First piece
Flags.SP_Start := Flags.SP_Start or else New_Flags.SP_Start;
else
Link_Tail (Chain, Last);
end if;
Chain := Last;
end loop;
-- Case where loop ran zero CURLY
if Chain = 0 then
Discard := Emit_Node (NOTHING);
end if;
end Parse_Branch;
---------------------------
-- Parse_Character_Class --
---------------------------
procedure Parse_Character_Class (IP : out Pointer) is
Bitmap : Character_Class;
Invert : Boolean := False;
In_Range : Boolean := False;
Named_Class : Std_Class := ANYOF_NONE;
Value : Character;
Last_Value : Character := ASCII.NUL;
begin
Reset_Class (Bitmap);
-- Do we have an invert character class ?
if Parse_Pos <= Parse_End
and then Expression (Parse_Pos) = '^'
then
Invert := True;
Parse_Pos := Parse_Pos + 1;
end if;
-- First character can be ] or - without closing the class
if Parse_Pos <= Parse_End
and then (Expression (Parse_Pos) = ']'
or else Expression (Parse_Pos) = '-')
then
Set_In_Class (Bitmap, Expression (Parse_Pos));
Parse_Pos := Parse_Pos + 1;
end if;
-- While we don't have the end of the class
while Parse_Pos <= Parse_End
and then Expression (Parse_Pos) /= ']'
loop
Named_Class := ANYOF_NONE;
Value := Expression (Parse_Pos);
Parse_Pos := Parse_Pos + 1;
-- Do we have a Posix character class
if Value = '[' then
Named_Class := Parse_Posix_Character_Class;
elsif Value = '\' then
if Parse_Pos = Parse_End then
Fail ("Trailing \");
end if;
Value := Expression (Parse_Pos);
Parse_Pos := Parse_Pos + 1;
case Value is
when 'w' => Named_Class := ANYOF_ALNUM;
when 'W' => Named_Class := ANYOF_NALNUM;
when 's' => Named_Class := ANYOF_SPACE;
when 'S' => Named_Class := ANYOF_NSPACE;
when 'd' => Named_Class := ANYOF_DIGIT;
when 'D' => Named_Class := ANYOF_NDIGIT;
when 'n' => Value := ASCII.LF;
when 'r' => Value := ASCII.CR;
when 't' => Value := ASCII.HT;
when 'f' => Value := ASCII.FF;
when 'e' => Value := ASCII.ESC;
when 'a' => Value := ASCII.BEL;
-- when 'x' => ??? hexadecimal value
-- when 'c' => ??? control character
-- when '0'..'9' => ??? octal character
when others => null;
end case;
end if;
-- Do we have a character class?
if Named_Class /= ANYOF_NONE then
-- A range like 'a-\d' or 'a-[:digit:] is not a range
if In_Range then
Set_In_Class (Bitmap, Last_Value);
Set_In_Class (Bitmap, '-');
In_Range := False;
end if;
-- Expand the range
case Named_Class is
when ANYOF_NONE => null;
when ANYOF_ALNUM | ANYOF_ALNUMC =>
for Value in Class_Byte'Range loop
if Is_Alnum (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NALNUM | ANYOF_NALNUMC =>
for Value in Class_Byte'Range loop
if not Is_Alnum (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_SPACE =>
for Value in Class_Byte'Range loop
if Is_White_Space (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NSPACE =>
for Value in Class_Byte'Range loop
if not Is_White_Space (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_DIGIT =>
for Value in Class_Byte'Range loop
if Is_Digit (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NDIGIT =>
for Value in Class_Byte'Range loop
if not Is_Digit (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_ALPHA =>
for Value in Class_Byte'Range loop
if Is_Letter (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NALPHA =>
for Value in Class_Byte'Range loop
if not Is_Letter (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_ASCII =>
for Value in 0 .. 127 loop
Set_In_Class (Bitmap, Character'Val (Value));
end loop;
when ANYOF_NASCII =>
for Value in 128 .. 255 loop
Set_In_Class (Bitmap, Character'Val (Value));
end loop;
when ANYOF_CNTRL =>
for Value in Class_Byte'Range loop
if Is_Control (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NCNTRL =>
for Value in Class_Byte'Range loop
if not Is_Control (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_GRAPH =>
for Value in Class_Byte'Range loop
if Is_Graphic (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NGRAPH =>
for Value in Class_Byte'Range loop
if not Is_Graphic (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_LOWER =>
for Value in Class_Byte'Range loop
if Is_Lower (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NLOWER =>
for Value in Class_Byte'Range loop
if not Is_Lower (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_PRINT =>
for Value in Class_Byte'Range loop
if Is_Printable (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NPRINT =>
for Value in Class_Byte'Range loop
if not Is_Printable (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_PUNCT =>
for Value in Class_Byte'Range loop
if Is_Printable (Character'Val (Value))
and then not Is_White_Space (Character'Val (Value))
and then not Is_Alnum (Character'Val (Value))
then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NPUNCT =>
for Value in Class_Byte'Range loop
if not Is_Printable (Character'Val (Value))
or else Is_White_Space (Character'Val (Value))
or else Is_Alnum (Character'Val (Value))
then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_UPPER =>
for Value in Class_Byte'Range loop
if Is_Upper (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NUPPER =>
for Value in Class_Byte'Range loop
if not Is_Upper (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_XDIGIT =>
for Value in Class_Byte'Range loop
if Is_Hexadecimal_Digit (Character'Val (Value)) then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
when ANYOF_NXDIGIT =>
for Value in Class_Byte'Range loop
if not Is_Hexadecimal_Digit
(Character'Val (Value))
then
Set_In_Class (Bitmap, Character'Val (Value));
end if;
end loop;
end case;
-- Not a character range
elsif not In_Range then
Last_Value := Value;
if Parse_Pos > Expression'Last then
Fail ("Empty character class []");
end if;
if Expression (Parse_Pos) = '-'
and then Parse_Pos < Parse_End
and then Expression (Parse_Pos + 1) /= ']'
then
Parse_Pos := Parse_Pos + 1;
-- Do we have a range like '\d-a' and '[:space:]-a'
-- which is not a real range
if Named_Class /= ANYOF_NONE then
Set_In_Class (Bitmap, '-');
else
In_Range := True;
end if;
else
Set_In_Class (Bitmap, Value);
end if;
-- Else in a character range
else
if Last_Value > Value then
Fail ("Invalid Range [" & Last_Value'Img
& "-" & Value'Img & "]");
end if;
while Last_Value <= Value loop
Set_In_Class (Bitmap, Last_Value);
Last_Value := Character'Succ (Last_Value);
end loop;
In_Range := False;
end if;
end loop;
-- Optimize case-insensitive ranges (put the upper case or lower
-- case character into the bitmap)
if (Flags and Case_Insensitive) /= 0 then
for C in Character'Range loop
if Get_From_Class (Bitmap, C) then
Set_In_Class (Bitmap, To_Lower (C));
Set_In_Class (Bitmap, To_Upper (C));
end if;
end loop;
end if;
-- Optimize inverted classes
if Invert then
for J in Bitmap'Range loop
Bitmap (J) := not Bitmap (J);
end loop;
end if;
Parse_Pos := Parse_Pos + 1;
-- Emit the class
IP := Emit_Node (ANYOF);
Emit_Class (Bitmap);
end Parse_Character_Class;
-------------------
-- Parse_Literal --
-------------------
-- This is a bit tricky due to quoted chars and due to
-- the multiplier characters '*', '+', and '?' that
-- take the SINGLE char previous as their operand.
-- On entry, the character at Parse_Pos - 1 is going to go
-- into the string, no matter what it is. It could be
-- following a \ if Parse_Atom was entered from the '\' case.
-- Basic idea is to pick up a good char in C and examine
-- the next char. If Is_Mult (C) then twiddle, if it's a \
-- then frozzle and if it's another magic char then push C and
-- terminate the string. If none of the above, push C on the
-- string and go around again.
-- Start_Pos is used to remember where "the current character"
-- starts in the string, if due to an Is_Mult we need to back
-- up and put the current char in a separate 1-character string.
-- When Start_Pos is 0, C is the only char in the string;
-- this is used in Is_Mult handling, and in setting the SIMPLE
-- flag at the end.
procedure Parse_Literal
(Expr_Flags : out Expression_Flags;
IP : out Pointer)
is
Start_Pos : Natural := 0;
C : Character;
Length_Ptr : Pointer;
Has_Special_Operator : Boolean := False;
begin
Parse_Pos := Parse_Pos - 1; -- Look at current character
IP :=
Emit_Node
(if (Flags and Case_Insensitive) /= 0 then EXACTF else EXACT);
Length_Ptr := Emit_Ptr;
Emit_Ptr := String_Operand (IP);
Parse_Loop :
loop
C := Expression (Parse_Pos); -- Get current character
case C is
when '.' | '[' | '(' | ')' | '|' | ASCII.LF | '$' | '^' =>
if Start_Pos = 0 then
Start_Pos := Parse_Pos;
Emit (C); -- First character is always emitted
else
exit Parse_Loop; -- Else we are done
end if;
when '?' | '+' | '*' | '{' =>
if Start_Pos = 0 then
Start_Pos := Parse_Pos;
Emit (C); -- First character is always emitted
-- Are we looking at an operator, or is this
-- simply a normal character ?
elsif not Is_Mult (Parse_Pos) then
Start_Pos := Parse_Pos;
Case_Emit (C);
else
-- We've got something like "abc?d". Mark this as a
-- special case. What we want to emit is a first
-- constant string for "ab", then one for "c" that will
-- ultimately be transformed with a CURLY operator, A
-- special case has to be handled for "a?", since there
-- is no initial string to emit.
Has_Special_Operator := True;
exit Parse_Loop;
end if;
when '\' =>
Start_Pos := Parse_Pos;
if Parse_Pos = Parse_End then
Fail ("Trailing \");
else
case Expression (Parse_Pos + 1) is
when 'b' | 'B' | 's' | 'S' | 'd' | 'D'
| 'w' | 'W' | '0' .. '9' | 'G' | 'A'
=> exit Parse_Loop;
when 'n' => Emit (ASCII.LF);
when 't' => Emit (ASCII.HT);
when 'r' => Emit (ASCII.CR);
when 'f' => Emit (ASCII.FF);
when 'e' => Emit (ASCII.ESC);
when 'a' => Emit (ASCII.BEL);
when others => Emit (Expression (Parse_Pos + 1));
end case;
Parse_Pos := Parse_Pos + 1;
end if;
when others =>
Start_Pos := Parse_Pos;
Case_Emit (C);
end case;
Parse_Pos := Parse_Pos + 1;
exit Parse_Loop when Parse_Pos > Parse_End
or else Emit_Ptr - Length_Ptr = 254;
end loop Parse_Loop;
-- Is the string followed by a '*+?{' operator ? If yes, and if there
-- is an initial string to emit, do it now.
if Has_Special_Operator
and then Emit_Ptr >= Length_Ptr + Next_Pointer_Bytes
then
Emit_Ptr := Emit_Ptr - 1;
Parse_Pos := Start_Pos;
end if;
if Length_Ptr <= PM.Size then
Program (Length_Ptr) := Character'Val (Emit_Ptr - Length_Ptr - 2);
end if;
Expr_Flags.Has_Width := True;
-- Slight optimization when there is a single character
if Emit_Ptr = Length_Ptr + 2 then
Expr_Flags.Simple := True;
end if;
end Parse_Literal;
-----------------
-- Parse_Piece --
-----------------
-- Note that the branching code sequences used for '?' and the
-- general cases of '*' and + are somewhat optimized: they use
-- the same NOTHING node as both the endmarker for their branch
-- list and the body of the last branch. It might seem that
-- this node could be dispensed with entirely, but the endmarker
-- role is not redundant.
procedure Parse_Piece
(Expr_Flags : out Expression_Flags;
IP : out Pointer)
is
Op : Character;
New_Flags : Expression_Flags;
Greedy : Boolean := True;
begin
Parse_Atom (New_Flags, IP);
if IP = 0 then
return;
end if;
if Parse_Pos > Parse_End
or else not Is_Mult (Parse_Pos)
then
Expr_Flags := New_Flags;
return;
end if;
Op := Expression (Parse_Pos);
Expr_Flags :=
(if Op /= '+'
then (SP_Start => True, others => False)
else (Has_Width => True, others => False));
-- Detect non greedy operators in the easy cases
if Op /= '{'
and then Parse_Pos + 1 <= Parse_End
and then Expression (Parse_Pos + 1) = '?'
then
Greedy := False;
Parse_Pos := Parse_Pos + 1;
end if;
-- Generate the byte code
case Op is
when '*' =>
if New_Flags.Simple then
Insert_Operator (STAR, IP, Greedy);
else
Link_Tail (IP, Emit_Node (WHILEM));
Insert_Curly_Operator
(CURLYX, 0, Max_Curly_Repeat, IP, Greedy);
Link_Tail (IP, Emit_Node (NOTHING));
end if;
when '+' =>
if New_Flags.Simple then
Insert_Operator (PLUS, IP, Greedy);
else
Link_Tail (IP, Emit_Node (WHILEM));
Insert_Curly_Operator
(CURLYX, 1, Max_Curly_Repeat, IP, Greedy);
Link_Tail (IP, Emit_Node (NOTHING));
end if;
when '?' =>
if New_Flags.Simple then
Insert_Curly_Operator (CURLY, 0, 1, IP, Greedy);
else
Link_Tail (IP, Emit_Node (WHILEM));
Insert_Curly_Operator (CURLYX, 0, 1, IP, Greedy);
Link_Tail (IP, Emit_Node (NOTHING));
end if;
when '{' =>
declare
Min, Max : Natural;
begin
Get_Curly_Arguments (Parse_Pos, Min, Max, Greedy);
if New_Flags.Simple then
Insert_Curly_Operator (CURLY, Min, Max, IP, Greedy);
else
Link_Tail (IP, Emit_Node (WHILEM));
Insert_Curly_Operator (CURLYX, Min, Max, IP, Greedy);
Link_Tail (IP, Emit_Node (NOTHING));
end if;
end;
when others =>
null;
end case;
Parse_Pos := Parse_Pos + 1;
if Parse_Pos <= Parse_End
and then Is_Mult (Parse_Pos)
then
Fail ("nested *+{");
end if;
end Parse_Piece;
---------------------------------
-- Parse_Posix_Character_Class --
---------------------------------
function Parse_Posix_Character_Class return Std_Class is
Invert : Boolean := False;
Class : Std_Class := ANYOF_NONE;
E : String renames Expression;
-- Class names. Note that code assumes that the length of all
-- classes starting with the same letter have the same length.
Alnum : constant String := "alnum:]";
Alpha : constant String := "alpha:]";
Ascii_C : constant String := "ascii:]";
Cntrl : constant String := "cntrl:]";
Digit : constant String := "digit:]";
Graph : constant String := "graph:]";
Lower : constant String := "lower:]";
Print : constant String := "print:]";
Punct : constant String := "punct:]";
Space : constant String := "space:]";
Upper : constant String := "upper:]";
Word : constant String := "word:]";
Xdigit : constant String := "xdigit:]";
begin
-- Case of character class specified
if Parse_Pos <= Parse_End
and then Expression (Parse_Pos) = ':'
then
Parse_Pos := Parse_Pos + 1;
-- Do we have something like: [[:^alpha:]]
if Parse_Pos <= Parse_End
and then Expression (Parse_Pos) = '^'
then
Invert := True;
Parse_Pos := Parse_Pos + 1;
end if;
-- Check for class names based on first letter
case Expression (Parse_Pos) is
when 'a' =>
-- All 'a' classes have the same length (Alnum'Length)
if Parse_Pos + Alnum'Length - 1 <= Parse_End then
if
E (Parse_Pos .. Parse_Pos + Alnum'Length - 1) = Alnum
then
Class :=
(if Invert then ANYOF_NALNUMC else ANYOF_ALNUMC);
Parse_Pos := Parse_Pos + Alnum'Length;
elsif
E (Parse_Pos .. Parse_Pos + Alpha'Length - 1) = Alpha
then
Class :=
(if Invert then ANYOF_NALPHA else ANYOF_ALPHA);
Parse_Pos := Parse_Pos + Alpha'Length;
elsif E (Parse_Pos .. Parse_Pos + Ascii_C'Length - 1) =
Ascii_C
then
Class :=
(if Invert then ANYOF_NASCII else ANYOF_ASCII);
Parse_Pos := Parse_Pos + Ascii_C'Length;
else
Fail ("Invalid character class: " & E);
end if;
else
Fail ("Invalid character class: " & E);
end if;
when 'c' =>
if Parse_Pos + Cntrl'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Cntrl'Length - 1) = Cntrl
then
Class := (if Invert then ANYOF_NCNTRL else ANYOF_CNTRL);
Parse_Pos := Parse_Pos + Cntrl'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'd' =>
if Parse_Pos + Digit'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Digit'Length - 1) = Digit
then
Class := (if Invert then ANYOF_NDIGIT else ANYOF_DIGIT);
Parse_Pos := Parse_Pos + Digit'Length;
end if;
when 'g' =>
if Parse_Pos + Graph'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Graph'Length - 1) = Graph
then
Class := (if Invert then ANYOF_NGRAPH else ANYOF_GRAPH);
Parse_Pos := Parse_Pos + Graph'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'l' =>
if Parse_Pos + Lower'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Lower'Length - 1) = Lower
then
Class := (if Invert then ANYOF_NLOWER else ANYOF_LOWER);
Parse_Pos := Parse_Pos + Lower'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'p' =>
-- All 'p' classes have the same length
if Parse_Pos + Print'Length - 1 <= Parse_End then
if
E (Parse_Pos .. Parse_Pos + Print'Length - 1) = Print
then
Class :=
(if Invert then ANYOF_NPRINT else ANYOF_PRINT);
Parse_Pos := Parse_Pos + Print'Length;
elsif
E (Parse_Pos .. Parse_Pos + Punct'Length - 1) = Punct
then
Class :=
(if Invert then ANYOF_NPUNCT else ANYOF_PUNCT);
Parse_Pos := Parse_Pos + Punct'Length;
else
Fail ("Invalid character class: " & E);
end if;
else
Fail ("Invalid character class: " & E);
end if;
when 's' =>
if Parse_Pos + Space'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Space'Length - 1) = Space
then
Class := (if Invert then ANYOF_NSPACE else ANYOF_SPACE);
Parse_Pos := Parse_Pos + Space'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'u' =>
if Parse_Pos + Upper'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Upper'Length - 1) = Upper
then
Class := (if Invert then ANYOF_NUPPER else ANYOF_UPPER);
Parse_Pos := Parse_Pos + Upper'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'w' =>
if Parse_Pos + Word'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Word'Length - 1) = Word
then
Class := (if Invert then ANYOF_NALNUM else ANYOF_ALNUM);
Parse_Pos := Parse_Pos + Word'Length;
else
Fail ("Invalid character class: " & E);
end if;
when 'x' =>
if Parse_Pos + Xdigit'Length - 1 <= Parse_End
and then
E (Parse_Pos .. Parse_Pos + Xdigit'Length - 1) = Xdigit
then
Class := (if Invert then ANYOF_NXDIGIT else ANYOF_XDIGIT);
Parse_Pos := Parse_Pos + Xdigit'Length;
else
Fail ("Invalid character class: " & E);
end if;
when others =>
Fail ("Invalid character class: " & E);
end case;
-- Character class not specified
else
return ANYOF_NONE;
end if;
return Class;
end Parse_Posix_Character_Class;
-- Local Declarations
Result : Pointer;
Expr_Flags : Expression_Flags;
pragma Unreferenced (Expr_Flags);
-- Start of processing for Compile
begin
Parse (False, False, Expr_Flags, Result);
if Result = 0 then
Fail ("Couldn't compile expression");
end if;
Final_Code_Size := Emit_Ptr - 1;
-- Do we want to actually compile the expression, or simply get the
-- code size ???
if Emit_Ptr <= PM.Size then
Optimize (PM);
end if;
PM.Flags := Flags;
end Compile;
function Compile
(Expression : String;
Flags : Regexp_Flags := No_Flags) return Pattern_Matcher
is
-- Assume the compiled regexp will fit in 1000 chars. If it does not we
-- will have to compile a second time once the correct size is known. If
-- it fits, we save a significant amount of time by avoiding the second
-- compilation.
Dummy : Pattern_Matcher (1000);
Size : Program_Size;
begin
Compile (Dummy, Expression, Size, Flags);
if Size <= Dummy.Size then
return Pattern_Matcher'
(Size => Size,
First => Dummy.First,
Anchored => Dummy.Anchored,
Must_Have => Dummy.Must_Have,
Must_Have_Length => Dummy.Must_Have_Length,
Paren_Count => Dummy.Paren_Count,
Flags => Dummy.Flags,
Program =>
Dummy.Program
(Dummy.Program'First .. Dummy.Program'First + Size - 1));
else
-- We have to recompile now that we know the size
-- ??? Can we use Ada 2005's return construct ?
declare
Result : Pattern_Matcher (Size);
begin
Compile (Result, Expression, Size, Flags);
return Result;
end;
end if;
end Compile;
procedure Compile
(Matcher : out Pattern_Matcher;
Expression : String;
Flags : Regexp_Flags := No_Flags)
is
Size : Program_Size;
begin
Compile (Matcher, Expression, Size, Flags);
if Size > Matcher.Size then
raise Expression_Error with "Pattern_Matcher is too small";
end if;
end Compile;
--------------------
-- Dump_Operation --
--------------------
procedure Dump_Operation
(Program : Program_Data;
Index : Pointer;
Indent : Natural)
is
Current : Pointer := Index;
begin
Dump_Until (Program, Current, Current + 1, Indent);
end Dump_Operation;
----------------
-- Dump_Until --
----------------
procedure Dump_Until
(Program : Program_Data;
Index : in out Pointer;
Till : Pointer;
Indent : Natural;
Do_Print : Boolean := True)
is
function Image (S : String) return String;
-- Remove leading space
-----------
-- Image --
-----------
function Image (S : String) return String is
begin
if S (S'First) = ' ' then
return S (S'First + 1 .. S'Last);
else
return S;
end if;
end Image;
-- Local variables
Op : Opcode;
Next : Pointer;
Length : Pointer;
Local_Indent : Natural := Indent;
-- Start of processing for Dump_Until
begin
while Index < Till loop
Op := Opcode'Val (Character'Pos ((Program (Index))));
Next := Get_Next (Program, Index);
if Do_Print then
declare
Point : constant String := Pointer'Image (Index);
begin
Put ((1 .. 4 - Point'Length => ' ')
& Point & ":"
& (1 .. Local_Indent * 2 => ' ') & Opcode'Image (Op));
end;
-- Print the parenthesis number
if Op = OPEN or else Op = CLOSE or else Op = REFF then
Put (Image (Natural'Image
(Character'Pos
(Program (Index + Next_Pointer_Bytes)))));
end if;
if Next = Index then
Put (" (-)");
else
Put (" (" & Image (Pointer'Image (Next)) & ")");
end if;
end if;
case Op is
when ANYOF =>
declare
Bitmap : Character_Class;
Last : Character := ASCII.NUL;
Current : Natural := 0;
Current_Char : Character;
begin
Bitmap_Operand (Program, Index, Bitmap);
if Do_Print then
Put ("[");
while Current <= 255 loop
Current_Char := Character'Val (Current);
-- First item in a range
if Get_From_Class (Bitmap, Current_Char) then
Last := Current_Char;
-- Search for the last item in the range
loop
Current := Current + 1;
exit when Current > 255;
Current_Char := Character'Val (Current);
exit when
not Get_From_Class (Bitmap, Current_Char);
end loop;
if not Is_Graphic (Last) then
Put (Last'Img);
else
Put (Last);
end if;
if Character'Succ (Last) /= Current_Char then
Put ("\-" & Character'Pred (Current_Char));
end if;
else
Current := Current + 1;
end if;
end loop;
Put_Line ("]");
end if;
Index := Index + Next_Pointer_Bytes + Bitmap'Length;
end;
when EXACT | EXACTF =>
Length := String_Length (Program, Index);
if Do_Print then
Put (" (" & Image (Program_Size'Image (Length + 1))
& " chars) <"
& String (Program (String_Operand (Index)
.. String_Operand (Index)
+ Length)));
Put_Line (">");
end if;
Index := String_Operand (Index) + Length + 1;
-- Node operand
when BRANCH | STAR | PLUS =>
if Do_Print then
New_Line;
end if;
Index := Index + Next_Pointer_Bytes;
Dump_Until (Program, Index, Pointer'Min (Next, Till),
Local_Indent + 1, Do_Print);
when CURLY | CURLYX =>
if Do_Print then
Put_Line
(" {"
& Image (Natural'Image
(Read_Natural (Program, Index + Next_Pointer_Bytes)))
& ","
& Image (Natural'Image (Read_Natural (Program, Index + 5)))
& "}");
end if;
Index := Index + 7;
Dump_Until (Program, Index, Pointer'Min (Next, Till),
Local_Indent + 1, Do_Print);
when OPEN =>
if Do_Print then
New_Line;
end if;
Index := Index + 4;
Local_Indent := Local_Indent + 1;
when CLOSE | REFF =>
if Do_Print then
New_Line;
end if;
Index := Index + 4;
if Op = CLOSE then
Local_Indent := Local_Indent - 1;
end if;
when others =>
Index := Index + Next_Pointer_Bytes;
if Do_Print then
New_Line;
end if;
exit when Op = EOP;
end case;
end loop;
end Dump_Until;
----------
-- Dump --
----------
procedure Dump (Self : Pattern_Matcher) is
Program : Program_Data renames Self.Program;
Index : Pointer := Program'First;
-- Start of processing for Dump
begin
Put_Line ("Must start with (Self.First) = "
& Character'Image (Self.First));
if (Self.Flags and Case_Insensitive) /= 0 then
Put_Line (" Case_Insensitive mode");
end if;
if (Self.Flags and Single_Line) /= 0 then
Put_Line (" Single_Line mode");
end if;
if (Self.Flags and Multiple_Lines) /= 0 then
Put_Line (" Multiple_Lines mode");
end if;
Dump_Until (Program, Index, Self.Program'Last + 1, 0);
end Dump;
--------------------
-- Get_From_Class --
--------------------
function Get_From_Class
(Bitmap : Character_Class;
C : Character) return Boolean
is
Value : constant Class_Byte := Character'Pos (C);
begin
return
(Bitmap (Value / 8) and Bit_Conversion (Value mod 8)) /= 0;
end Get_From_Class;
--------------
-- Get_Next --
--------------
function Get_Next (Program : Program_Data; IP : Pointer) return Pointer is
begin
return IP + Pointer (Read_Natural (Program, IP + 1));
end Get_Next;
--------------
-- Is_Alnum --
--------------
function Is_Alnum (C : Character) return Boolean is
begin
return Is_Alphanumeric (C) or else C = '_';
end Is_Alnum;
------------------
-- Is_Printable --
------------------
function Is_Printable (C : Character) return Boolean is
begin
-- Printable if space or graphic character or other whitespace
-- Other white space includes (HT/LF/VT/FF/CR = codes 9-13)
return C in Character'Val (32) .. Character'Val (126)
or else C in ASCII.HT .. ASCII.CR;
end Is_Printable;
--------------------
-- Is_White_Space --
--------------------
function Is_White_Space (C : Character) return Boolean is
begin
-- Note: HT = 9, LF = 10, VT = 11, FF = 12, CR = 13
return C = ' ' or else C in ASCII.HT .. ASCII.CR;
end Is_White_Space;
-----------
-- Match --
-----------
procedure Match
(Self : Pattern_Matcher;
Data : String;
Matches : out Match_Array;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last)
is
Program : Program_Data renames Self.Program; -- Shorter notation
First_In_Data : constant Integer := Integer'Max (Data_First, Data'First);
Last_In_Data : constant Integer := Integer'Min (Data_Last, Data'Last);
-- Global work variables
Input_Pos : Natural; -- String-input pointer
BOL_Pos : Natural; -- Beginning of input, for ^ check
Matched : Boolean := False; -- Until proven True
Matches_Full : Match_Array (0 .. Natural'Max (Self.Paren_Count,
Matches'Last));
-- Stores the value of all the parenthesis pairs.
-- We do not use directly Matches, so that we can also use back
-- references (REFF) even if Matches is too small.
type Natural_Array is array (Match_Count range <>) of Natural;
Matches_Tmp : Natural_Array (Matches_Full'Range);
-- Save the opening position of parenthesis
Last_Paren : Natural := 0;
-- Last parenthesis seen
Greedy : Boolean := True;
-- True if the next operator should be greedy
type Current_Curly_Record;
type Current_Curly_Access is access all Current_Curly_Record;
type Current_Curly_Record is record
Paren_Floor : Natural; -- How far back to strip parenthesis data
Cur : Integer; -- How many instances of scan we've matched
Min : Natural; -- Minimal number of scans to match
Max : Natural; -- Maximal number of scans to match
Greedy : Boolean; -- Whether to work our way up or down
Scan : Pointer; -- The thing to match
Next : Pointer; -- What has to match after it
Lastloc : Natural; -- Where we started matching this scan
Old_Cc : Current_Curly_Access; -- Before we started this one
end record;
-- Data used to handle the curly operator and the plus and star
-- operators for complex expressions.
Current_Curly : Current_Curly_Access := null;
-- The curly currently being processed
-----------------------
-- Local Subprograms --
-----------------------
function Index (Start : Positive; C : Character) return Natural;
-- Find character C in Data starting at Start and return position
function Repeat
(IP : Pointer;
Max : Natural := Natural'Last) return Natural;
-- Repeatedly match something simple, report how many
-- It only matches on things of length 1.
-- Starting from Input_Pos, it matches at most Max CURLY.
function Try (Pos : Positive) return Boolean;
-- Try to match at specific point
function Match (IP : Pointer) return Boolean;
-- This is the main matching routine. Conceptually the strategy
-- is simple: check to see whether the current node matches,
-- call self recursively to see whether the rest matches,
-- and then act accordingly.
--
-- In practice Match makes some effort to avoid recursion, in
-- particular by going through "ordinary" nodes (that don't
-- need to know whether the rest of the match failed) by
-- using a loop instead of recursion.
-- Why is the above comment part of the spec rather than body ???
function Match_Whilem return Boolean;
-- Return True if a WHILEM matches the Current_Curly
function Recurse_Match (IP : Pointer; From : Natural) return Boolean;
pragma Inline (Recurse_Match);
-- Calls Match recursively. It saves and restores the parenthesis
-- status and location in the input stream correctly, so that
-- backtracking is possible
function Match_Simple_Operator
(Op : Opcode;
Scan : Pointer;
Next : Pointer;
Greedy : Boolean) return Boolean;
-- Return True it the simple operator (possibly non-greedy) matches
Dump_Indent : Integer := -1;
procedure Dump_Current (Scan : Pointer; Prefix : Boolean := True);
procedure Dump_Error (Msg : String);
-- Debug: print the current context
pragma Inline (Index);
pragma Inline (Repeat);
-- These are two complex functions, but used only once
pragma Inline (Match_Whilem);
pragma Inline (Match_Simple_Operator);
-----------
-- Index --
-----------
function Index (Start : Positive; C : Character) return Natural is
begin
for J in Start .. Last_In_Data loop
if Data (J) = C then
return J;
end if;
end loop;
return 0;
end Index;
-------------------
-- Recurse_Match --
-------------------
function Recurse_Match (IP : Pointer; From : Natural) return Boolean is
L : constant Natural := Last_Paren;
Tmp_F : constant Match_Array :=
Matches_Full (From + 1 .. Matches_Full'Last);
Start : constant Natural_Array :=
Matches_Tmp (From + 1 .. Matches_Tmp'Last);
Input : constant Natural := Input_Pos;
Dump_Indent_Save : constant Integer := Dump_Indent;
begin
if Match (IP) then
return True;
end if;
Last_Paren := L;
Matches_Full (Tmp_F'Range) := Tmp_F;
Matches_Tmp (Start'Range) := Start;
Input_Pos := Input;
Dump_Indent := Dump_Indent_Save;
return False;
end Recurse_Match;
------------------
-- Dump_Current --
------------------
procedure Dump_Current (Scan : Pointer; Prefix : Boolean := True) is
Length : constant := 10;
Pos : constant String := Integer'Image (Input_Pos);
begin
if Prefix then
Put ((1 .. 5 - Pos'Length => ' '));
Put (Pos & " <"
& Data (Input_Pos
.. Integer'Min (Last_In_Data, Input_Pos + Length - 1)));
Put ((1 .. Length - 1 - Last_In_Data + Input_Pos => ' '));
Put ("> |");
else
Put (" ");
end if;
Dump_Operation (Program, Scan, Indent => Dump_Indent);
end Dump_Current;
----------------
-- Dump_Error --
----------------
procedure Dump_Error (Msg : String) is
begin
Put (" | ");
Put ((1 .. Dump_Indent * 2 => ' '));
Put_Line (Msg);
end Dump_Error;
-----------
-- Match --
-----------
function Match (IP : Pointer) return Boolean is
Scan : Pointer := IP;
Next : Pointer;
Op : Opcode;
Result : Boolean;
begin
Dump_Indent := Dump_Indent + 1;
State_Machine :
loop
pragma Assert (Scan /= 0);
-- Determine current opcode and count its usage in debug mode
Op := Opcode'Val (Character'Pos (Program (Scan)));
-- Calculate offset of next instruction. Second character is most
-- significant in Program_Data.
Next := Get_Next (Program, Scan);
if Debug then
Dump_Current (Scan);
end if;
case Op is
when EOP =>
Dump_Indent := Dump_Indent - 1;
return True; -- Success
when BRANCH =>
if Program (Next) /= BRANCH then
Next := Operand (Scan); -- No choice, avoid recursion
else
loop
if Recurse_Match (Operand (Scan), 0) then
Dump_Indent := Dump_Indent - 1;
return True;
end if;
Scan := Get_Next (Program, Scan);
exit when Scan = 0 or else Program (Scan) /= BRANCH;
end loop;
exit State_Machine;
end if;
when NOTHING =>
null;
when BOL =>
exit State_Machine when Input_Pos /= BOL_Pos
and then ((Self.Flags and Multiple_Lines) = 0
or else Data (Input_Pos - 1) /= ASCII.LF);
when MBOL =>
exit State_Machine when Input_Pos /= BOL_Pos
and then Data (Input_Pos - 1) /= ASCII.LF;
when SBOL =>
exit State_Machine when Input_Pos /= BOL_Pos;
when EOL =>
-- A combination of MEOL and SEOL
if (Self.Flags and Multiple_Lines) = 0 then
-- Single line mode
exit State_Machine when Input_Pos <= Data'Last;
elsif Input_Pos <= Last_In_Data then
exit State_Machine when Data (Input_Pos) /= ASCII.LF;
else
exit State_Machine when Last_In_Data /= Data'Last;
end if;
when MEOL =>
if Input_Pos <= Last_In_Data then
exit State_Machine when Data (Input_Pos) /= ASCII.LF;
else
exit State_Machine when Last_In_Data /= Data'Last;
end if;
when SEOL =>
-- If there is a character before Data'Last (even if
-- Last_In_Data stops before then), we can't have the
-- end of the line.
exit State_Machine when Input_Pos <= Data'Last;
when BOUND | NBOUND =>
-- Was last char in word ?
declare
N : Boolean := False;
Ln : Boolean := False;
begin
if Input_Pos /= First_In_Data then
N := Is_Alnum (Data (Input_Pos - 1));
end if;
Ln :=
(if Input_Pos > Last_In_Data
then False
else Is_Alnum (Data (Input_Pos)));
if Op = BOUND then
if N = Ln then
exit State_Machine;
end if;
else
if N /= Ln then
exit State_Machine;
end if;
end if;
end;
when SPACE =>
exit State_Machine when Input_Pos > Last_In_Data
or else not Is_White_Space (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when NSPACE =>
exit State_Machine when Input_Pos > Last_In_Data
or else Is_White_Space (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when DIGIT =>
exit State_Machine when Input_Pos > Last_In_Data
or else not Is_Digit (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when NDIGIT =>
exit State_Machine when Input_Pos > Last_In_Data
or else Is_Digit (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when ALNUM =>
exit State_Machine when Input_Pos > Last_In_Data
or else not Is_Alnum (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when NALNUM =>
exit State_Machine when Input_Pos > Last_In_Data
or else Is_Alnum (Data (Input_Pos));
Input_Pos := Input_Pos + 1;
when ANY =>
exit State_Machine when Input_Pos > Last_In_Data
or else Data (Input_Pos) = ASCII.LF;
Input_Pos := Input_Pos + 1;
when SANY =>
exit State_Machine when Input_Pos > Last_In_Data;
Input_Pos := Input_Pos + 1;
when EXACT =>
declare
Opnd : Pointer := String_Operand (Scan);
Current : Positive := Input_Pos;
Last : constant Pointer :=
Opnd + String_Length (Program, Scan);
begin
while Opnd <= Last loop
exit State_Machine when Current > Last_In_Data
or else Program (Opnd) /= Data (Current);
Current := Current + 1;
Opnd := Opnd + 1;
end loop;
Input_Pos := Current;
end;
when EXACTF =>
declare
Opnd : Pointer := String_Operand (Scan);
Current : Positive := Input_Pos;
Last : constant Pointer :=
Opnd + String_Length (Program, Scan);
begin
while Opnd <= Last loop
exit State_Machine when Current > Last_In_Data
or else Program (Opnd) /= To_Lower (Data (Current));
Current := Current + 1;
Opnd := Opnd + 1;
end loop;
Input_Pos := Current;
end;
when ANYOF =>
declare
Bitmap : Character_Class;
begin
Bitmap_Operand (Program, Scan, Bitmap);
exit State_Machine when Input_Pos > Last_In_Data
or else not Get_From_Class (Bitmap, Data (Input_Pos));
Input_Pos := Input_Pos + 1;
end;
when OPEN =>
declare
No : constant Natural :=
Character'Pos (Program (Operand (Scan)));
begin
Matches_Tmp (No) := Input_Pos;
end;
when CLOSE =>
declare
No : constant Natural :=
Character'Pos (Program (Operand (Scan)));
begin
Matches_Full (No) := (Matches_Tmp (No), Input_Pos - 1);
if Last_Paren < No then
Last_Paren := No;
end if;
end;
when REFF =>
declare
No : constant Natural :=
Character'Pos (Program (Operand (Scan)));
Data_Pos : Natural;
begin
-- If we haven't seen that parenthesis yet
if Last_Paren < No then
Dump_Indent := Dump_Indent - 1;
if Debug then
Dump_Error ("REFF: No match, backtracking");
end if;
return False;
end if;
Data_Pos := Matches_Full (No).First;
while Data_Pos <= Matches_Full (No).Last loop
if Input_Pos > Last_In_Data
or else Data (Input_Pos) /= Data (Data_Pos)
then
Dump_Indent := Dump_Indent - 1;
if Debug then
Dump_Error ("REFF: No match, backtracking");
end if;
return False;
end if;
Input_Pos := Input_Pos + 1;
Data_Pos := Data_Pos + 1;
end loop;
end;
when MINMOD =>
Greedy := False;
when STAR | PLUS | CURLY =>
declare
Greed : constant Boolean := Greedy;
begin
Greedy := True;
Result := Match_Simple_Operator (Op, Scan, Next, Greed);
Dump_Indent := Dump_Indent - 1;
return Result;
end;
when CURLYX =>
-- Looking at something like:
-- 1: CURLYX {n,m} (->4)
-- 2: code for complex thing (->3)
-- 3: WHILEM (->0)
-- 4: NOTHING
declare
Min : constant Natural :=
Read_Natural (Program, Scan + Next_Pointer_Bytes);
Max : constant Natural :=
Read_Natural
(Program, Scan + Next_Pointer_Bytes + 2);
Cc : aliased Current_Curly_Record;
Has_Match : Boolean;
begin
Cc := (Paren_Floor => Last_Paren,
Cur => -1,
Min => Min,
Max => Max,
Greedy => Greedy,
Scan => Scan + 7,
Next => Next,
Lastloc => 0,
Old_Cc => Current_Curly);
Greedy := True;
Current_Curly := Cc'Unchecked_Access;
Has_Match := Match (Next - Next_Pointer_Bytes);
-- Start on the WHILEM
Current_Curly := Cc.Old_Cc;
Dump_Indent := Dump_Indent - 1;
if not Has_Match then
if Debug then
Dump_Error ("CURLYX failed...");
end if;
end if;
return Has_Match;
end;
when WHILEM =>
Result := Match_Whilem;
Dump_Indent := Dump_Indent - 1;
if Debug and then not Result then
Dump_Error ("WHILEM: no match, backtracking");
end if;
return Result;
end case;
Scan := Next;
end loop State_Machine;
if Debug then
Dump_Error ("failed...");
Dump_Indent := Dump_Indent - 1;
end if;
-- If we get here, there is no match. For successful matches when EOP
-- is the terminating point.
return False;
end Match;
---------------------------
-- Match_Simple_Operator --
---------------------------
function Match_Simple_Operator
(Op : Opcode;
Scan : Pointer;
Next : Pointer;
Greedy : Boolean) return Boolean
is
Next_Char : Character := ASCII.NUL;
Next_Char_Known : Boolean := False;
No : Integer; -- Can be negative
Min : Natural;
Max : Natural := Natural'Last;
Operand_Code : Pointer;
Old : Natural;
Last_Pos : Natural;
Save : constant Natural := Input_Pos;
begin
-- Lookahead to avoid useless match attempts when we know what
-- character comes next.
if Program (Next) = EXACT then
Next_Char := Program (String_Operand (Next));
Next_Char_Known := True;
end if;
-- Find the minimal and maximal values for the operator
case Op is
when STAR =>
Min := 0;
Operand_Code := Operand (Scan);
when PLUS =>
Min := 1;
Operand_Code := Operand (Scan);
when others =>
Min := Read_Natural (Program, Scan + Next_Pointer_Bytes);
Max := Read_Natural (Program, Scan + Next_Pointer_Bytes + 2);
Operand_Code := Scan + 7;
end case;
if Debug then
Dump_Current (Operand_Code, Prefix => False);
end if;
-- Non greedy operators
if not Greedy then
-- Test we can repeat at least Min times
if Min /= 0 then
No := Repeat (Operand_Code, Min);
if No < Min then
if Debug then
Dump_Error ("failed... matched" & No'Img & " times");
end if;
return False;
end if;
end if;
Old := Input_Pos;
-- Find the place where 'next' could work
if Next_Char_Known then
-- Last position to check
if Max = Natural'Last then
Last_Pos := Last_In_Data;
else
Last_Pos := Input_Pos + Max;
if Last_Pos > Last_In_Data then
Last_Pos := Last_In_Data;
end if;
end if;
-- Look for the first possible opportunity
if Debug then
Dump_Error ("Next_Char must be " & Next_Char);
end if;
loop
-- Find the next possible position
while Input_Pos <= Last_Pos
and then Data (Input_Pos) /= Next_Char
loop
Input_Pos := Input_Pos + 1;
end loop;
if Input_Pos > Last_Pos then
return False;
end if;
-- Check that we still match if we stop at the position we
-- just found.
declare
Num : constant Natural := Input_Pos - Old;
begin
Input_Pos := Old;
if Debug then
Dump_Error ("Would we still match at that position?");
end if;
if Repeat (Operand_Code, Num) < Num then
return False;
end if;
end;
-- Input_Pos now points to the new position
if Match (Get_Next (Program, Scan)) then
return True;
end if;
Old := Input_Pos;
Input_Pos := Input_Pos + 1;
end loop;
-- We do not know what the next character is
else
while Max >= Min loop
if Debug then
Dump_Error ("Non-greedy repeat, N=" & Min'Img);
Dump_Error ("Do we still match Next if we stop here?");
end if;
-- If the next character matches
if Recurse_Match (Next, 1) then
return True;
end if;
Input_Pos := Save + Min;
-- Could not or did not match -- move forward
if Repeat (Operand_Code, 1) /= 0 then
Min := Min + 1;
else
if Debug then
Dump_Error ("Non-greedy repeat failed...");
end if;
return False;
end if;
end loop;
end if;
return False;
-- Greedy operators
else
No := Repeat (Operand_Code, Max);
if Debug and then No < Min then
Dump_Error ("failed... matched" & No'Img & " times");
end if;
-- ??? Perl has some special code here in case the next
-- instruction is of type EOL, since $ and \Z can match before
-- *and* after newline at the end.
-- ??? Perl has some special code here in case (paren) is True
-- Else, if we don't have any parenthesis
while No >= Min loop
if not Next_Char_Known
or else (Input_Pos <= Last_In_Data
and then Data (Input_Pos) = Next_Char)
then
if Match (Next) then
return True;
end if;
end if;
-- Could not or did not work, we back up
No := No - 1;
Input_Pos := Save + No;
end loop;
return False;
end if;
end Match_Simple_Operator;
------------------
-- Match_Whilem --
------------------
-- This is really hard to understand, because after we match what we
-- are trying to match, we must make sure the rest of the REx is going
-- to match for sure, and to do that we have to go back UP the parse
-- tree by recursing ever deeper. And if it fails, we have to reset
-- our parent's current state that we can try again after backing off.
function Match_Whilem return Boolean is
Cc : constant Current_Curly_Access := Current_Curly;
N : constant Natural := Cc.Cur + 1;
Ln : Natural := 0;
Lastloc : constant Natural := Cc.Lastloc;
-- Detection of 0-len
begin
-- If degenerate scan matches "", assume scan done
if Input_Pos = Cc.Lastloc
and then N >= Cc.Min
then
-- Temporarily restore the old context, and check that we
-- match was comes after CURLYX.
Current_Curly := Cc.Old_Cc;
if Current_Curly /= null then
Ln := Current_Curly.Cur;
end if;
if Match (Cc.Next) then
return True;
end if;
if Current_Curly /= null then
Current_Curly.Cur := Ln;
end if;
Current_Curly := Cc;
return False;
end if;
-- First, just match a string of min scans
if N < Cc.Min then
Cc.Cur := N;
Cc.Lastloc := Input_Pos;
if Debug then
Dump_Error
("Tests that we match at least" & Cc.Min'Img & " N=" & N'Img);
end if;
if Match (Cc.Scan) then
return True;
end if;
Cc.Cur := N - 1;
Cc.Lastloc := Lastloc;
if Debug then
Dump_Error ("failed...");
end if;
return False;
end if;
-- Prefer next over scan for minimal matching
if not Cc.Greedy then
Current_Curly := Cc.Old_Cc;
if Current_Curly /= null then
Ln := Current_Curly.Cur;
end if;
if Recurse_Match (Cc.Next, Cc.Paren_Floor) then
return True;
end if;
if Current_Curly /= null then
Current_Curly.Cur := Ln;
end if;
Current_Curly := Cc;
-- Maximum greed exceeded ?
if N >= Cc.Max then
if Debug then
Dump_Error ("failed...");
end if;
return False;
end if;
-- Try scanning more and see if it helps
Cc.Cur := N;
Cc.Lastloc := Input_Pos;
if Debug then
Dump_Error ("Next failed, what about Current?");
end if;
if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then
return True;
end if;
Cc.Cur := N - 1;
Cc.Lastloc := Lastloc;
return False;
end if;
-- Prefer scan over next for maximal matching
if N < Cc.Max then -- more greed allowed ?
Cc.Cur := N;
Cc.Lastloc := Input_Pos;
if Debug then
Dump_Error ("Recurse at current position");
end if;
if Recurse_Match (Cc.Scan, Cc.Paren_Floor) then
return True;
end if;
end if;
-- Failed deeper matches of scan, so see if this one works
Current_Curly := Cc.Old_Cc;
if Current_Curly /= null then
Ln := Current_Curly.Cur;
end if;
if Debug then
Dump_Error ("Failed matching for later positions");
end if;
if Match (Cc.Next) then
return True;
end if;
if Current_Curly /= null then
Current_Curly.Cur := Ln;
end if;
Current_Curly := Cc;
Cc.Cur := N - 1;
Cc.Lastloc := Lastloc;
if Debug then
Dump_Error ("failed...");
end if;
return False;
end Match_Whilem;
------------
-- Repeat --
------------
function Repeat
(IP : Pointer;
Max : Natural := Natural'Last) return Natural
is
Scan : Natural := Input_Pos;
Last : Natural;
Op : constant Opcode := Opcode'Val (Character'Pos (Program (IP)));
Count : Natural;
C : Character;
Is_First : Boolean := True;
Bitmap : Character_Class;
begin
if Max = Natural'Last or else Scan + Max - 1 > Last_In_Data then
Last := Last_In_Data;
else
Last := Scan + Max - 1;
end if;
case Op is
when ANY =>
while Scan <= Last
and then Data (Scan) /= ASCII.LF
loop
Scan := Scan + 1;
end loop;
when SANY =>
Scan := Last + 1;
when EXACT =>
-- The string has only one character if Repeat was called
C := Program (String_Operand (IP));
while Scan <= Last
and then C = Data (Scan)
loop
Scan := Scan + 1;
end loop;
when EXACTF =>
-- The string has only one character if Repeat was called
C := Program (String_Operand (IP));
while Scan <= Last
and then To_Lower (C) = Data (Scan)
loop
Scan := Scan + 1;
end loop;
when ANYOF =>
if Is_First then
Bitmap_Operand (Program, IP, Bitmap);
Is_First := False;
end if;
while Scan <= Last
and then Get_From_Class (Bitmap, Data (Scan))
loop
Scan := Scan + 1;
end loop;
when ALNUM =>
while Scan <= Last
and then Is_Alnum (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when NALNUM =>
while Scan <= Last
and then not Is_Alnum (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when SPACE =>
while Scan <= Last
and then Is_White_Space (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when NSPACE =>
while Scan <= Last
and then not Is_White_Space (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when DIGIT =>
while Scan <= Last
and then Is_Digit (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when NDIGIT =>
while Scan <= Last
and then not Is_Digit (Data (Scan))
loop
Scan := Scan + 1;
end loop;
when others =>
raise Program_Error;
end case;
Count := Scan - Input_Pos;
Input_Pos := Scan;
return Count;
end Repeat;
---------
-- Try --
---------
function Try (Pos : Positive) return Boolean is
begin
Input_Pos := Pos;
Last_Paren := 0;
Matches_Full := (others => No_Match);
if Match (Program_First) then
Matches_Full (0) := (Pos, Input_Pos - 1);
return True;
end if;
return False;
end Try;
-- Start of processing for Match
begin
-- Do we have the regexp Never_Match?
if Self.Size = 0 then
Matches := (others => No_Match);
return;
end if;
-- If there is a "must appear" string, look for it
if Self.Must_Have_Length > 0 then
declare
First : constant Character := Program (Self.Must_Have);
Must_First : constant Pointer := Self.Must_Have;
Must_Last : constant Pointer :=
Must_First + Pointer (Self.Must_Have_Length - 1);
Next_Try : Natural := Index (First_In_Data, First);
begin
while Next_Try /= 0
and then Data (Next_Try .. Next_Try + Self.Must_Have_Length - 1)
= String (Program (Must_First .. Must_Last))
loop
Next_Try := Index (Next_Try + 1, First);
end loop;
if Next_Try = 0 then
Matches := (others => No_Match);
return; -- Not present
end if;
end;
end if;
-- Mark beginning of line for ^
BOL_Pos := Data'First;
-- Simplest case first: an anchored match need be tried only once
if Self.Anchored and then (Self.Flags and Multiple_Lines) = 0 then
Matched := Try (First_In_Data);
elsif Self.Anchored then
declare
Next_Try : Natural := First_In_Data;
begin
-- Test the first position in the buffer
Matched := Try (Next_Try);
-- Else only test after newlines
if not Matched then
while Next_Try <= Last_In_Data loop
while Next_Try <= Last_In_Data
and then Data (Next_Try) /= ASCII.LF
loop
Next_Try := Next_Try + 1;
end loop;
Next_Try := Next_Try + 1;
if Next_Try <= Last_In_Data then
Matched := Try (Next_Try);
exit when Matched;
end if;
end loop;
end if;
end;
elsif Self.First /= ASCII.NUL then
-- We know what char it must start with
declare
Next_Try : Natural := Index (First_In_Data, Self.First);
begin
while Next_Try /= 0 loop
Matched := Try (Next_Try);
exit when Matched;
Next_Try := Index (Next_Try + 1, Self.First);
end loop;
end;
else
-- Messy cases: try all locations (including for the empty string)
Matched := Try (First_In_Data);
if not Matched then
for S in First_In_Data + 1 .. Last_In_Data loop
Matched := Try (S);
exit when Matched;
end loop;
end if;
end if;
-- Matched has its value
for J in Last_Paren + 1 .. Matches'Last loop
Matches_Full (J) := No_Match;
end loop;
Matches := Matches_Full (Matches'Range);
end Match;
-----------
-- Match --
-----------
function Match
(Self : Pattern_Matcher;
Data : String;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last) return Natural
is
Matches : Match_Array (0 .. 0);
begin
Match (Self, Data, Matches, Data_First, Data_Last);
if Matches (0) = No_Match then
return Data'First - 1;
else
return Matches (0).First;
end if;
end Match;
function Match
(Self : Pattern_Matcher;
Data : String;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last) return Boolean
is
Matches : Match_Array (0 .. 0);
begin
Match (Self, Data, Matches, Data_First, Data_Last);
return Matches (0).First >= Data'First;
end Match;
procedure Match
(Expression : String;
Data : String;
Matches : out Match_Array;
Size : Program_Size := Auto_Size;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last)
is
PM : Pattern_Matcher (Size);
Finalize_Size : Program_Size;
pragma Unreferenced (Finalize_Size);
begin
if Size = 0 then
Match (Compile (Expression), Data, Matches, Data_First, Data_Last);
else
Compile (PM, Expression, Finalize_Size);
Match (PM, Data, Matches, Data_First, Data_Last);
end if;
end Match;
-----------
-- Match --
-----------
function Match
(Expression : String;
Data : String;
Size : Program_Size := Auto_Size;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last) return Natural
is
PM : Pattern_Matcher (Size);
Final_Size : Program_Size;
pragma Unreferenced (Final_Size);
begin
if Size = 0 then
return Match (Compile (Expression), Data, Data_First, Data_Last);
else
Compile (PM, Expression, Final_Size);
return Match (PM, Data, Data_First, Data_Last);
end if;
end Match;
-----------
-- Match --
-----------
function Match
(Expression : String;
Data : String;
Size : Program_Size := Auto_Size;
Data_First : Integer := -1;
Data_Last : Positive := Positive'Last) return Boolean
is
Matches : Match_Array (0 .. 0);
PM : Pattern_Matcher (Size);
Final_Size : Program_Size;
pragma Unreferenced (Final_Size);
begin
if Size = 0 then
Match (Compile (Expression), Data, Matches, Data_First, Data_Last);
else
Compile (PM, Expression, Final_Size);
Match (PM, Data, Matches, Data_First, Data_Last);
end if;
return Matches (0).First >= Data'First;
end Match;
-------------
-- Operand --
-------------
function Operand (P : Pointer) return Pointer is
begin
return P + Next_Pointer_Bytes;
end Operand;
--------------
-- Optimize --
--------------
procedure Optimize (Self : in out Pattern_Matcher) is
Scan : Pointer;
Program : Program_Data renames Self.Program;
begin
-- Start with safe defaults (no optimization):
-- * No known first character of match
-- * Does not necessarily start at beginning of line
-- * No string known that has to appear in data
Self.First := ASCII.NUL;
Self.Anchored := False;
Self.Must_Have := Program'Last + 1;
Self.Must_Have_Length := 0;
Scan := Program_First; -- First instruction (can be anything)
if Program (Scan) = EXACT then
Self.First := Program (String_Operand (Scan));
elsif Program (Scan) = BOL
or else Program (Scan) = SBOL
or else Program (Scan) = MBOL
then
Self.Anchored := True;
end if;
end Optimize;
-----------------
-- Paren_Count --
-----------------
function Paren_Count (Regexp : Pattern_Matcher) return Match_Count is
begin
return Regexp.Paren_Count;
end Paren_Count;
-----------
-- Quote --
-----------
function Quote (Str : String) return String is
S : String (1 .. Str'Length * 2);
Last : Natural := 0;
begin
for J in Str'Range loop
case Str (J) is
when '^' | '$' | '|' | '*' | '+' | '?' | '{' |
'}' | '[' | ']' | '(' | ')' | '\' | '.' =>
S (Last + 1) := '\';
S (Last + 2) := Str (J);
Last := Last + 2;
when others =>
S (Last + 1) := Str (J);
Last := Last + 1;
end case;
end loop;
return S (1 .. Last);
end Quote;
------------------
-- Read_Natural --
------------------
function Read_Natural
(Program : Program_Data;
IP : Pointer) return Natural
is
begin
return Character'Pos (Program (IP)) +
256 * Character'Pos (Program (IP + 1));
end Read_Natural;
-----------------
-- Reset_Class --
-----------------
procedure Reset_Class (Bitmap : out Character_Class) is
begin
Bitmap := (others => 0);
end Reset_Class;
------------------
-- Set_In_Class --
------------------
procedure Set_In_Class
(Bitmap : in out Character_Class;
C : Character)
is
Value : constant Class_Byte := Character'Pos (C);
begin
Bitmap (Value / 8) := Bitmap (Value / 8)
or Bit_Conversion (Value mod 8);
end Set_In_Class;
-------------------
-- String_Length --
-------------------
function String_Length
(Program : Program_Data;
P : Pointer) return Program_Size
is
begin
pragma Assert (Program (P) = EXACT or else Program (P) = EXACTF);
return Character'Pos (Program (P + Next_Pointer_Bytes));
end String_Length;
--------------------
-- String_Operand --
--------------------
function String_Operand (P : Pointer) return Pointer is
begin
return P + 4;
end String_Operand;
end System.Regpat;
|
with Ada.Text_IO; use Ada.Text_IO;
procedure Adventofcode.Day_18.Main is
begin
Put_Line ("Day-18");
end Adventofcode.Day_18.Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2005, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
-- Boston, MA 02110-1301, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
--------------------------------------
-- Semantic Analysis: General Model --
--------------------------------------
-- Semantic processing involves 3 phases which are highly interwined
-- (ie mutually recursive):
-- Analysis implements the bulk of semantic analysis such as
-- name analysis and type resolution for declarations,
-- instructions and expressions. The main routine
-- driving this process is procedure Analyze given below.
-- This analysis phase is really a bottom up pass that is
-- achieved during the recursive traversal performed by the
-- Analyze_... procedures implemented in the sem_* packages.
-- For expressions this phase determines unambiguous types
-- and collects sets of possible types where the
-- interpretation is potentially ambiguous.
-- Resolution is carried out only for expressions to finish type
-- resolution that was initiated but not necessarily
-- completed during analysis (because of overloading
-- ambiguities). Specifically, after completing the bottom
-- up pass carried out during analysis for expressions, the
-- Resolve routine (see the spec of sem_res for more info)
-- is called to perform a top down resolution with
-- recursive calls to itself to resolve operands.
-- Expansion if we are not generating code this phase is a no-op.
-- otherwise this phase expands, ie transforms, original
-- declaration, expressions or instructions into simpler
-- structures that can be handled by the back-end. This
-- phase is also in charge of generating code which is
-- implicit in the original source (for instance for
-- default initializations, controlled types, etc.)
-- There are two separate instances where expansion is
-- invoked. For declarations and instructions, expansion is
-- invoked just after analysis since no resolution needs
-- to be performed. For expressions, expansion is done just
-- after resolution. In both cases expansion is done from the
-- bottom up just before the end of Analyze for instructions
-- and declarations or the call to Resolve for expressions.
-- The main routine driving expansion is Expand.
-- See the spec of Expander for more details.
-- To summarize, in normal code generation mode we recursively traverse the
-- abstract syntax tree top-down performing semantic analysis bottom
-- up. For instructions and declarations, before the call to the Analyze
-- routine completes we perform expansion since at that point we have all
-- semantic information needed. For expression nodes, after the call to
-- Analysis terminates we invoke the Resolve routine to transmit top-down
-- the type that was gathered by Analyze which will resolve possible
-- ambiguities in the expression. Just before the call to Resolve
-- terminates, the expression can be expanded since all the semantic
-- information is available at that point.
-- If we are not generating code then the expansion phase is a no-op
-- When generating code there are a number of exceptions to the basic
-- Analysis-Resolution-Expansion model for expressions. The most prominent
-- examples are the handling of default expressions and aggregates.
----------------------------------------------------
-- Handling of Default and Per-Object Expressions --
----------------------------------------------------
-- The default expressions in component declarations and in procedure
-- specifications (but not the ones in object declarations) are quite
-- tricky to handle. The problem is that some processing is required
-- at the point where the expression appears:
-- visibility analysis (including user defined operators)
-- freezing of static expressions
-- but other processing must be deferred until the enclosing entity
-- (record or procedure specification) is frozen:
-- freezing of any other types in the expression
-- expansion
-- A similar situation occurs with the argument of priority and interrupt
-- priority pragmas that appear in task and protected definition specs and
-- other cases of per-object expressions (see RM 3.8(18)).
-- Expansion has to be deferred since you can't generate code for
-- expressions that refernce types that have not been frozen yet. As an
-- example, consider the following:
-- type x is delta 0.5 range -10.0 .. +10.0;
-- ...
-- type q is record
-- xx : x := y * z;
-- end record;
-- for x'small use 0.25
-- The expander is in charge of dealing with fixed-point, and of course
-- the small declaration, which is not too late, since the declaration of
-- type q does *not* freeze type x, definitely affects the expanded code.
-- Another reason that we cannot expand early is that expansion can generate
-- range checks. These range checks need to be inserted not at the point of
-- definition but at the point of use. The whole point here is that the value
-- of the expression cannot be obtained at the point of declaration, only at
-- the point of use.
-- Generally our model is to combine analysis resolution and expansion, but
-- this is the one case where this model falls down. Here is how we patch
-- it up without causing too much distortion to our basic model.
-- A switch (sede below) is set to indicate that we are in the initial
-- occurence of a default expression. The analyzer is then called on this
-- expression with the switch set true. Analysis and resolution proceed
-- almost as usual, except that Freeze_Expression will not freeze
-- non-static expressions if this switch is set, and the call to Expand at
-- the end of resolution is skipped. This also skips the code that normally
-- sets the Analyzed flag to True). The result is that when we are done the
-- tree is still marked as unanalyzed, but all types for static expressions
-- are frozen as required, and all entities of variables have been
-- recorded. We then turn off the switch, and later on reanalyze the
-- expression with the switch off. The effect is that this second analysis
-- freezes the rest of the types as required, and generates code but
-- visibility analysis is not repeated since all the entities are marked.
-- The second analysis (the one that generates code) is in the context
-- where the code is required. For a record field default, this is in
-- the initialization procedure for the record and for a subprogram
-- default parameter, it is at the point the subprogram is frozen.
-- For a priority or storage size pragma it is in the context of the
-- Init_Proc for the task or protected object.
------------------
-- Pre-Analysis --
------------------
-- For certain kind of expressions, such as aggregates, we need to defer
-- expansion of the aggregate and its inner expressions after the whole
-- set of expressions appearing inside the aggregate have been analyzed.
-- Consider, for instance the following example:
--
-- (1 .. 100 => new Thing (Function_Call))
--
-- The normal Analysis-Resolution-Expansion mechanism where expansion
-- of the children is performed before expansion of the parent does not
-- work if the code generated for the children by the expander needs
-- to be evaluated repeatdly (for instance in the above aggregate
-- "new Thing (Function_Call)" needs to be called 100 times.)
-- The reason why this mecanism does not work is that, the expanded code
-- for the children is typically inserted above the parent and thus
-- when the father gets expanded no re-evaluation takes place. For instance
-- in the case of aggregates if "new Thing (Function_Call)" is expanded
-- before of the aggregate the expanded code will be placed outside
-- of the aggregate and when expanding the aggregate the loop from 1 to 100
-- will not surround the expanded code for "new Thing (Function_Call)".
--
-- To remedy this situation we introduce a new flag which signals whether
-- we want a full analysis (ie expansion is enabled) or a pre-analysis
-- which performs Analysis and Resolution but no expansion.
--
-- After the complete pre-analysis of an expression has been carried out
-- we can transform the expression and then carry out the full
-- Analyze-Resolve-Expand cycle on the transformed expression top-down
-- so that the expansion of inner expressions happens inside the newly
-- generated node for the parent expression.
--
-- Note that the difference between processing of default expressions and
-- pre-analysis of other expressions is that we do carry out freezing in
-- the latter but not in the former (except for static scalar expressions).
-- The routine that performs pre-analysis is called Pre_Analyze_And_Resolve
-- and is in Sem_Res.
with Alloc;
with Einfo; use Einfo;
with Opt; use Opt;
with Table;
with Types; use Types;
package Sem is
New_Nodes_OK : Int := 1;
-- Temporary flag for use in checking out HLO. Set non-zero if it is
-- OK to generate new nodes.
-----------------------------
-- Semantic Analysis Flags --
-----------------------------
Explicit_Overriding : Boolean := False;
-- Switch to indicate whether checking mechanism described in AI-218
-- is enforced: subprograms that override inherited operations must be
-- be marked explicitly, to prevent accidental or omitted overriding.
Full_Analysis : Boolean := True;
-- Switch to indicate whether we are doing a full analysis or a
-- pre-analysis. In normal analysis mode (Analysis-Expansion for
-- instructions or declarations) or (Analysis-Resolution-Expansion for
-- expressions) this flag is set. Note that if we are not generating
-- code the expansion phase merely sets the Analyzed flag to True in
-- this case. If we are in Pre-Analysis mode (see above) this flag is
-- set to False then the expansion phase is skipped.
-- When this flag is False the flag Expander_Active is also False
-- (the Expander_Activer flag defined in the spec of package Expander
-- tells you whether expansion is currently enabled).
-- You should really regard this as a read only flag.
In_Default_Expression : Boolean := False;
-- Switch to indicate that we are in a default expression, as described
-- above. Note that this must be recursively saved on a Semantics call
-- since it is possible for the analysis of an expression to result in
-- a recursive call (e.g. to get the entity for System.Address as part
-- of the processing of an Address attribute reference).
-- When this switch is True then Full_Analysis above must be False.
-- You should really regard this as a read only flag.
In_Deleted_Code : Boolean := False;
-- If the condition in an if-statement is statically known, the branch
-- that is not taken is analyzed with expansion disabled, and the tree
-- is deleted after analysis. Itypes generated in deleted code must be
-- frozen from start, because the tree on which they depend will not
-- be available at the freeze point.
In_Inlined_Body : Boolean := False;
-- Switch to indicate that we are analyzing and resolving an inlined
-- body. Type checking is disabled in this context, because types are
-- known to be compatible. This avoids problems with private types whose
-- full view is derived from private types.
Inside_A_Generic : Boolean := False;
-- This flag is set if we are processing a generic specification,
-- generic definition, or generic body. When this flag is True the
-- Expander_Active flag is False to disable any code expansion (see
-- package Expander). Only the generic processing can modify the
-- status of this flag, any other client should regard it as read-only.
Unloaded_Subunits : Boolean := False;
-- This flag is set True if we have subunits that are not loaded. This
-- occurs when the main unit is a subunit, and contains lower level
-- subunits that are not loaded. We use this flag to suppress warnings
-- about unused variables, since these warnings are unreliable in this
-- case. We could perhaps do a more accurate job and retain some of the
-- warnings, but it is quite a tricky job. See test 4323-002.
-----------------
-- Scope Stack --
-----------------
-- The scope stack holds all entries of the scope table. As in the parser,
-- we use Last as the stack pointer, so that we can always find the scope
-- that is currently open in Scope_Stack.Table (Scope_Stack.Last). The
-- oldest entry, at Scope_Stack (0) is Standard. The entries in the table
-- include the entity for the referenced scope, together with information
-- used to restore the proper setting of check suppressions on scope exit.
type Scope_Stack_Entry is record
Entity : Entity_Id;
-- Entity representing the scope
Last_Subprogram_Name : String_Ptr;
-- Pointer to name of last subprogram body in this scope. Used for
-- testing proper alpha ordering of subprogram bodies in scope.
Save_Scope_Suppress : Suppress_Array;
-- Save contents of Scope_Suppress on entry
Save_Local_Entity_Suppress : Int;
-- Save contents of Local_Entity_Suppress.Last on entry
Is_Transient : Boolean;
-- Marks Transient Scopes (See Exp_Ch7 body for details)
Previous_Visibility : Boolean;
-- Used when installing the parent (s) of the current compilation
-- unit. The parent may already be visible because of an ongoing
-- compilation, and the proper visibility must be restored on exit.
Node_To_Be_Wrapped : Node_Id;
-- Only used in transient scopes. Records the node which will
-- be wrapped by the transient block.
Actions_To_Be_Wrapped_Before : List_Id;
Actions_To_Be_Wrapped_After : List_Id;
-- Actions that have to be inserted at the start or at the end of a
-- transient block. Used to temporarily hold these actions until the
-- block is created, at which time the actions are moved to the
-- block.
Pending_Freeze_Actions : List_Id;
-- Used to collect freeze entity nodes and associated actions that
-- are generated in a inner context but need to be analyzed outside,
-- such as records and initialization procedures. On exit from the
-- scope, this list of actions is inserted before the scope construct
-- and analyzed to generate the corresponding freeze processing and
-- elaboration of other associated actions.
First_Use_Clause : Node_Id;
-- Head of list of Use_Clauses in current scope. The list is built
-- when the declarations in the scope are processed. The list is
-- traversed on scope exit to undo the effect of the use clauses.
Component_Alignment_Default : Component_Alignment_Kind;
-- Component alignment to be applied to any record or array types
-- that are declared for which a specific component alignment pragma
-- does not set the alignment.
Is_Active_Stack_Base : Boolean;
-- Set to true only when entering the scope for Standard_Standard from
-- from within procedure Semantics. Indicates the base of the current
-- active set of scopes. Needed by In_Open_Scopes to handle cases
-- where Standard_Standard can be pushed in the middle of the active
-- set of scopes (occurs for instantiations of generic child units).
end record;
package Scope_Stack is new Table.Table (
Table_Component_Type => Scope_Stack_Entry,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.Scope_Stack_Initial,
Table_Increment => Alloc.Scope_Stack_Increment,
Table_Name => "Sem.Scope_Stack");
-----------------------------------
-- Handling of Check Suppression --
-----------------------------------
-- There are two kinds of suppress checks: scope based suppress checks,
-- and entity based suppress checks.
-- Scope based suppress chems (from initial command line arguments,
-- or from Suppress pragmas not including an entity name) are recorded
-- in the Sem.Supress variable, and all that is necessary is to save the
-- state of this variable on scope entry, and restore it on scope exit.
-- Entity based suppress checks, from Suppress pragmas giving an Entity_Id,
-- are handled as follows. If a suppress or unsuppress pragma is
-- encountered for a given entity, then the flag Checks_May_Be_Suppressed
-- is set in the entity and an entry is made in either the
-- Local_Entity_Suppress table (case of pragma that appears in other than
-- a package spec), or in the Global_Entity_Suppress table (case of pragma
-- that appears in a package spec, which is by the rule of RM 11.5(7)
-- applicable throughout the life of the entity).
-- If the Checks_May_Be_Suppressed flag is set in an entity then the
-- procedure is to search first the local and then the global suppress
-- tables (the local one being searched in reverse order, i.e. last in
-- searched first). The only other point is that we have to make sure
-- that we have proper nested interaction between such specific pragmas
-- and locally applied general pragmas applying to all entities. This
-- is achieved by including in the Local_Entity_Suppress table dummy
-- entries with an empty Entity field that are applicable to all entities.
Scope_Suppress : Suppress_Array := Suppress_Options;
-- This array contains the current scope based settings of the suppress
-- switches. It is initialized from the options as shown, and then modified
-- by pragma Suppress. On entry to each scope, the current setting is saved
-- the scope stack, and then restored on exit from the scope. This record
-- may be rapidly checked to determine the current status of a check if
-- no specific entity is involved or if the specific entity involved is
-- one for which no specific Suppress/Unsuppress pragma has been set (as
-- indicated by the Checks_May_Be_Suppressed flag being set).
-- This scheme is a little complex, but serves the purpose of enabling
-- a very rapid check in the common case where no entity specific pragma
-- applies, and gives the right result when such pragmas are used even
-- in complex cases of nested Suppress and Unsuppress pragmas.
type Entity_Check_Suppress_Record is record
Entity : Entity_Id;
-- Entity to which the check applies, or Empty for a local check
-- that has no entity name (and thus applies to all entities).
Check : Check_Id;
-- Check which is set (note this cannot be All_Checks, if the All_Checks
-- case, a sequence of eentries appears for the individual checks.
Suppress : Boolean;
-- Set True for Suppress, and False for Unsuppress
end record;
-- The Local_Entity_Suppress table is a stack, to which new entries are
-- added for Suppress and Unsuppress pragmas appearing in other than
-- package specs. Such pragmas are effective only to the end of the scope
-- in which they appear. This is achieved by marking the stack on entry
-- to a scope and then cutting back the stack to that marked point on
-- scope exit.
package Local_Entity_Suppress is new Table.Table (
Table_Component_Type => Entity_Check_Suppress_Record,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.Entity_Suppress_Initial,
Table_Increment => Alloc.Entity_Suppress_Increment,
Table_Name => "Local_Entity_Suppress");
-- The Global_Entity_Suppress table is used for entities which have
-- a Suppress or Unsuppress pragma naming a specific entity in a
-- package spec. Such pragmas always refer to entities in the package
-- spec and are effective throughout the lifetime of the named entity.
package Global_Entity_Suppress is new Table.Table (
Table_Component_Type => Entity_Check_Suppress_Record,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.Entity_Suppress_Initial,
Table_Increment => Alloc.Entity_Suppress_Increment,
Table_Name => "Global_Entity_Suppress");
-----------------
-- Subprograms --
-----------------
procedure Initialize;
-- Initialize internal tables
procedure Lock;
-- Lock internal tables before calling back end
procedure Semantics (Comp_Unit : Node_Id);
-- This procedure is called to perform semantic analysis on the specified
-- node which is the N_Compilation_Unit node for the unit.
procedure Analyze (N : Node_Id);
procedure Analyze (N : Node_Id; Suppress : Check_Id);
-- This is the recursive procedure which is applied to individual nodes
-- of the tree, starting at the top level node (compilation unit node)
-- and then moving down the tree in a top down traversal. It calls
-- individual routines with names Analyze_xxx to analyze node xxx. Each
-- of these routines is responsible for calling Analyze on the components
-- of the subtree.
--
-- Note: In the case of expression components (nodes whose Nkind is in
-- N_Subexpr), the call to Analyze does not complete the semantic analysis
-- of the node, since the type resolution cannot be completed until the
-- complete context is analyzed. The completion of the type analysis occurs
-- in the corresponding Resolve routine (see Sem_Res).
--
-- Note: for integer and real literals, the analyzer sets the flag to
-- indicate that the result is a static expression. If the expander
-- generates a literal that does NOT correspond to a static expression,
-- e.g. by folding an expression whose value is known at compile-time,
-- but is not technically static, then the caller should reset the
-- Is_Static_Expression flag after analyzing but before resolving.
--
-- If the Suppress argument is present, then the analysis is done
-- with the specified check suppressed (can be All_Checks to suppress
-- all checks).
procedure Analyze_List (L : List_Id);
procedure Analyze_List (L : List_Id; Suppress : Check_Id);
-- Analyzes each element of a list. If the Suppress argument is present,
-- then the analysis is done with the specified check suppressed (can
-- be All_Checks to suppress all checks).
procedure Copy_Suppress_Status
(C : Check_Id;
From : Entity_Id;
To : Entity_Id);
-- If From is an entity for which check C is explicitly suppressed
-- then also explicitly suppress the corresponding check in To.
procedure Insert_List_After_And_Analyze
(N : Node_Id; L : List_Id);
procedure Insert_List_After_And_Analyze
(N : Node_Id; L : List_Id; Suppress : Check_Id);
-- Inserts list L after node N using Nlists.Insert_List_After, and then,
-- after this insertion is complete, analyzes all the nodes in the list,
-- including any additional nodes generated by this analysis. If the list
-- is empty or be No_List, the call has no effect. If the Suppress
-- argument is present, then the analysis is done with the specified
-- check suppressed (can be All_Checks to suppress all checks).
procedure Insert_List_Before_And_Analyze
(N : Node_Id; L : List_Id);
procedure Insert_List_Before_And_Analyze
(N : Node_Id; L : List_Id; Suppress : Check_Id);
-- Inserts list L before node N using Nlists.Insert_List_Before, and then,
-- after this insertion is complete, analyzes all the nodes in the list,
-- including any additional nodes generated by this analysis. If the list
-- is empty or be No_List, the call has no effect. If the Suppress
-- argument is present, then the analysis is done with the specified
-- check suppressed (can be All_Checks to suppress all checks).
procedure Insert_After_And_Analyze
(N : Node_Id; M : Node_Id);
procedure Insert_After_And_Analyze
(N : Node_Id; M : Node_Id; Suppress : Check_Id);
-- Inserts node M after node N and then after the insertion is complete,
-- analyzes the inserted node and all nodes that are generated by
-- this analysis. If the node is empty, the call has no effect. If the
-- Suppress argument is present, then the analysis is done with the
-- specified check suppressed (can be All_Checks to suppress all checks).
procedure Insert_Before_And_Analyze
(N : Node_Id; M : Node_Id);
procedure Insert_Before_And_Analyze
(N : Node_Id; M : Node_Id; Suppress : Check_Id);
-- Inserts node M before node N and then after the insertion is complete,
-- analyzes the inserted node and all nodes that could be generated by
-- this analysis. If the node is empty, the call has no effect. If the
-- Suppress argument is present, then the analysis is done with the
-- specified check suppressed (can be All_Checks to suppress all checks).
function External_Ref_In_Generic (E : Entity_Id) return Boolean;
-- Return True if we are in the context of a generic and E is
-- external (more global) to it.
procedure Enter_Generic_Scope (S : Entity_Id);
-- Shall be called each time a Generic subprogram or package scope is
-- entered. S is the entity of the scope.
-- ??? At the moment, only called for package specs because this mechanism
-- is only used for avoiding freezing of external references in generics
-- and this can only be an issue if the outer generic scope is a package
-- spec (otherwise all external entities are already frozen)
procedure Exit_Generic_Scope (S : Entity_Id);
-- Shall be called each time a Generic subprogram or package scope is
-- exited. S is the entity of the scope.
-- ??? At the moment, only called for package specs exit.
function Explicit_Suppress (E : Entity_Id; C : Check_Id) return Boolean;
-- This function returns True if an explicit pragma Suppress for check C
-- is present in the package defining E.
function Is_Check_Suppressed (E : Entity_Id; C : Check_Id) return Boolean;
-- This function is called if Checks_May_Be_Suppressed (E) is True to
-- determine whether check C is suppressed either on the entity E or
-- as the result of a scope suppress pragma. If Checks_May_Be_Suppressed
-- is False, then the status of the check can be determined simply by
-- examining Scope_Checks (C), so this routine is not called in that case.
end Sem;
|
pragma License (Unrestricted);
-- implementation unit required by compiler
with System.Packed_Arrays;
package System.Pack_05 is
pragma Preelaborate;
-- It can not be Pure, subprograms would become __attribute__((const)).
type Bits_05 is mod 2 ** 5;
for Bits_05'Size use 5;
package Indexing is new Packed_Arrays.Indexing (Bits_05);
-- required for accessing arrays by compiler
function Get_05 (
Arr : Address;
N : Natural;
Rev_SSO : Boolean)
return Bits_05
renames Indexing.Get;
procedure Set_05 (
Arr : Address;
N : Natural;
E : Bits_05;
Rev_SSO : Boolean)
renames Indexing.Set;
end System.Pack_05;
|
-- Copyright 2011-2015 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
with Pck; use Pck;
procedure Foo is
begin
Dummy_Task.Start;
end Foo;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.