content stringlengths 23 1.05M |
|---|
------------------------------------------------------------------------------
-- --
-- GNU ADA RUN-TIME LIBRARY (GNARL) COMPONENTS --
-- --
-- S Y S T E M - S T A C K _ U S A G E --
-- --
-- S p e c --
-- --
-- Copyright (C) 2004-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. --
-- --
--
--
--
--
--
--
--
-- GNARL was developed by the GNARL team at Florida State University. --
-- Extensive contributions were provided by Ada Core Technologies, Inc. --
-- --
------------------------------------------------------------------------------
with System;
with System.Storage_Elements;
with System.Address_To_Access_Conversions;
package System.Stack_Usage is
pragma Preelaborate;
package SSE renames System.Storage_Elements;
Byte_Size : constant := 8;
Word_32_Size : constant := 4 * Byte_Size;
type Word_32 is mod 2 ** Word_32_Size;
for Word_32'Alignment use 4;
subtype Stack_Address is SSE.Integer_Address;
-- Address on the stack
--
-- Note: in this package, when comparing two addresses on the stack, the
-- comments use the terms "outer", "inner", "outermost" and "innermost"
-- instead of the ambigous "higher", "lower", "highest" and "lowest".
-- "inner" means "closer to the bottom of stack" and is the contrary of
-- "outer". "innermost" means "closest address to the bottom of stack". The
-- stack is growing from the inner to the outer.
-- Top/Bottom would be much better than inner and outer ???
function To_Stack_Address (Value : System.Address) return Stack_Address
renames System.Storage_Elements.To_Integer;
type Stack_Analyzer is private;
-- Type of the stack analyzer tool. It is used to fill a portion of
-- the stack with Pattern, and to compute the stack used after some
-- execution.
-- Usage:
-- A typical use of the package is something like:
-- A : Stack_Analyzer;
-- task T is
-- pragma Storage_Size (A_Storage_Size);
-- end T;
-- [...]
-- Bottom_Of_Stack : aliased Integer;
-- -- Bottom_Of_Stack'Address will be used as an approximation of
-- -- the bottom of stack. A good practise is to avoid allocating
-- -- other local variables on this stack, as it would degrade
-- -- the quality of this approximation.
-- begin
-- Initialize_Analyzer (A,
-- "Task t",
-- A_Storage_Size - A_Guard,
-- To_Stack_Address (Bottom_Of_Stack'Address));
-- Fill_Stack (A);
-- Some_User_Code;
-- Compute_Result (A);
-- Report_Result (A);
-- end T;
-- Errors:
--
-- We are instrumenting the code to measure the stack used by the user
-- code. This method has a number of systematic errors, but several
-- methods can be used to evaluate or reduce those errors. Here are
-- those errors and the strategy that we use to deal with them:
-- Bottom offset:
-- Description: The procedure used to fill the stack with a given
-- pattern will itself have a stack frame. The value of the stack
-- pointer in this procedure is, therefore, different from the value
-- before the call to the instrumentation procedure.
-- Strategy: The user of this package should measure the bottom of stack
-- before the call to Fill_Stack and pass it in parameter.
-- Instrumentation threshold at writing:
-- Description: The procedure used to fill the stack with a given
-- pattern will itself have a stack frame. Therefore, it will
-- fill the stack after this stack frame. This part of the stack will
-- appear as used in the final measure.
-- Strategy: As the user passes the value of the bottom of stack to
-- the instrumentation to deal with the bottom offset error, and as as
-- the instrumentation procedure knows where the pattern filling start
-- on the stack, the difference between the two values is the minimum
-- stack usage that the method can measure. If, when the results are
-- computed, the pattern zone has been left untouched, we conclude
-- that the stack usage is inferior to this minimum stack usage.
-- Instrumentation threshold at reading:
-- Description: The procedure used to read the stack at the end of the
-- execution clobbers the stack by allocating its stack frame. If this
-- stack frame is bigger than the total stack used by the user code at
-- this point, it will increase the measured stack size.
-- Strategy: We could augment this stack frame and see if it changes the
-- measure. However, this error should be negligeable.
-- Pattern zone overflow:
-- Description: The stack grows outer than the outermost bound of the
-- pattern zone. In that case, the outermost region modified in the
-- pattern is not the maximum value of the stack pointer during the
-- execution.
-- Strategy: At the end of the execution, the difference between the
-- outermost memory region modified in the pattern zone and the
-- outermost bound of the pattern zone can be understood as the
-- biggest allocation that the method could have detect, provided
-- that there is no "Untouched allocated zone" error and no "Pattern
-- usage in user code" error. If no object in the user code is likely
-- to have this size, this is not likely to happen.
-- Pattern usage in user code:
-- Description: The pattern can be found in the object of the user code.
-- Therefore, the address space where this object has been allocated
-- will appear as untouched.
-- Strategy: Choose a pattern that is uncommon. 16#0000_0000# is the
-- worst choice; 16#DEAD_BEEF# can be a good one. A good choice is an
-- address which is not a multiple of 2, and which is not in the
-- target address space. You can also change the pattern to see if it
-- changes the measure. Note that this error *very* rarely influence
-- the measure of the total stack usage: to have some influence, the
-- pattern has to be used in the object that has been allocated on the
-- outermost address of the used stack.
-- Stack overflow:
-- Description: The pattern zone does not fit on the stack. This may
-- lead to an erroneous execution.
-- Strategy: Specify a storage size that is bigger than the size of the
-- pattern. 2 times bigger should be enough.
-- Augmentation of the user stack frames:
-- Description: The use of instrumentation object or procedure may
-- augment the stack frame of the caller.
-- Strategy: Do *not* inline the instrumentation procedures. Do *not*
-- allocate the Stack_Analyzer object on the stack.
-- Untouched allocated zone:
-- Description: The user code may allocate objects that it will never
-- touch. In that case, the pattern will not be changed.
-- Strategy: There are no way to detect this error. Fortunately, this
-- error is really rare, and it is most probably a bug in the user
-- code, e.g. some uninitialized variable. It is (most of the time)
-- harmless: it influences the measure only if the untouched allocated
-- zone happens to be located at the outermost value of the stack
-- pointer for the whole execution.
procedure Initialize (Buffer_Size : Natural);
pragma Export (C, Initialize, "__gnat_stack_usage_initialize");
-- Initializes the size of the buffer that stores the results. Only the
-- first Buffer_Size results are stored. Any results that do not fit in
-- this buffer will be displayed on the fly.
procedure Fill_Stack (Analyzer : in out Stack_Analyzer);
-- Fill an area of the stack with the pattern Analyzer.Pattern. The size
-- of this area is Analyzer.Size. After the call to this procedure,
-- the memory will look like that:
--
-- Stack growing
-- ----------------------------------------------------------------------->
-- |<---------------------->|<----------------------------------->|
-- | Stack frame | Memory filled with Analyzer.Pattern |
-- | of Fill_Stack | |
-- | (deallocated at | |
-- | the end of the call) | |
-- ^ | |
-- Analyzer.Bottom_Of_Stack ^ |
-- Analyzer.Inner_Pattern_Mark ^
-- Analyzer.Outer_Pattern_Mark
procedure Initialize_Analyzer
(Analyzer : in out Stack_Analyzer;
Task_Name : String;
Size : Natural;
Bottom : Stack_Address;
Pattern : Word_32 := 16#DEAD_BEEF#);
-- Should be called before any use of a Stack_Analyzer, to initialize it.
-- Size is the size of the pattern zone. Bottom should be a close
-- approximation of the caller base frame address.
Is_Enabled : Boolean := False;
-- When this flag is true, then stack analysis is enabled
procedure Compute_Result (Analyzer : in out Stack_Analyzer);
-- Read the patern zone and deduce the stack usage. It should be called
-- from the same frame as Fill_Stack. If Analyzer.Probe is not null, an
-- array of Word_32 with Analyzer.Probe elements is allocated on
-- Compute_Result's stack frame. Probe can be used to detect the error:
-- "instrumentation threshold at reading". See above. After the call
-- to this procedure, the memory will look like:
--
-- Stack growing
-- ----------------------------------------------------------------------->
-- |<---------------------->|<-------------->|<--------->|<--------->|
-- | Stack frame | Array of | used | Memory |
-- | of Compute_Result | Analyzer.Probe | during | filled |
-- | (deallocated at | elements | the | with |
-- | the end of the call) | | execution | pattern |
-- | ^ | | |
-- | Inner_Pattern_Mark | | |
-- | | |
-- |<----------------------------------------------------> |
-- Stack used ^
-- Outer_Pattern_Mark
procedure Report_Result (Analyzer : Stack_Analyzer);
-- Store the results of the computation in memory, at the address
-- corresponding to the symbol __gnat_stack_usage_results. This is not
-- done inside Compute_Resuls in order to use as less stack as possible
-- within a task.
procedure Output_Results;
-- Print the results computed so far on the standard output. Should be
-- called when all tasks are dead.
pragma Export (C, Output_Results, "__gnat_stack_usage_output_results");
private
Task_Name_Length : constant := 32;
package Word_32_Addr is
new System.Address_To_Access_Conversions (Word_32);
type Stack_Analyzer is record
Task_Name : String (1 .. Task_Name_Length);
-- Name of the task
Size : Natural;
-- Size of the pattern zone
Pattern : Word_32;
-- Pattern used to recognize untouched memory
Inner_Pattern_Mark : Stack_Address;
-- Innermost bound of the pattern area on the stack
Outer_Pattern_Mark : Stack_Address;
-- Outermost bound of the pattern area on the stack
Outermost_Touched_Mark : Stack_Address;
-- Outermost address of the pattern area whose value it is pointing
-- at has been modified during execution. If the systematic error are
-- compensated, it is the outermost value of the stack pointer during
-- the execution.
Bottom_Of_Stack : Stack_Address;
-- Address of the bottom of the stack, as given by the caller of
-- Initialize_Analyzer.
Array_Address : System.Address;
-- Address of the array of Word_32 that represents the pattern zone
First_Is_Outermost : Boolean;
-- Set to true if the first element of the array of Word_32 that
-- represents the pattern zone is at the outermost address of the
-- pattern zone; false if it is the innermost address.
Result_Id : Positive;
-- Id of the result. If less than value given to gnatbind -u corresponds
-- to the location in the result array of result for the current task.
end record;
Environment_Task_Analyzer : Stack_Analyzer;
Compute_Environment_Task : Boolean;
type Task_Result is record
Task_Name : String (1 .. Task_Name_Length);
Measure : Natural;
Max_Size : Natural;
end record;
type Result_Array_Type is array (Positive range <>) of Task_Result;
type Result_Array_Ptr is access all Result_Array_Type;
Result_Array : Result_Array_Ptr;
pragma Export (C, Result_Array, "__gnat_stack_usage_results");
-- Exported in order to have an easy accessible symbol in when debugging
Next_Id : Positive := 1;
-- Id of the next stack analyzer
function Stack_Size
(SP_Low : Stack_Address;
SP_High : Stack_Address) return Natural;
pragma Inline (Stack_Size);
-- Return the size of a portion of stack delimeted by SP_High and SP_Low
-- (), i.e. the difference between SP_High and SP_Low. The storage element
-- pointed by SP_Low is not included in the size. Inlined to reduce the
-- size of the stack used by the instrumentation code.
end System.Stack_Usage;
|
separate(practica_3)
function Mayor(V:Vector) return TMayor is
Mayor:tMayor;
begin
mayor.elemento:=V(1);--inicializo la variable mayor con el primer elemento
mayor.posi:=1;
for i in 2..v'last loop
if v(i)>mayor.elemento then
mayor.elemento:=v(i);--busco si otro elemento del vector es mayor y si lo es
mayor.posi:=i; --lo guardo en la variable
end if;
end loop;
return mayor;
end Mayor;
|
------------------------------------------------------------------------------
-- --
-- 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_00FF is
pragma Preelaborate;
Group_00FF : aliased constant Core_Second_Stage
:= (16#00# => -- FF00
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#01# => -- FF01
(Other_Punctuation, Fullwidth,
Other, Other, S_Term, Exclamation,
(STerm
| Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#02# => -- FF02
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Quotation_Mark
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#03# => -- FF03
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#04# => -- FF04
(Currency_Symbol, Fullwidth,
Other, Other, Other, Prefix_Numeric,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#05# => -- FF05
(Other_Punctuation, Fullwidth,
Other, Other, Other, Postfix_Numeric,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#06# => -- FF06
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#07# => -- FF07
(Other_Punctuation, Fullwidth,
Other, Mid_Num_Let, Other, Ideographic,
(Quotation_Mark
| Case_Ignorable
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#08# => -- FF08
(Open_Punctuation, Fullwidth,
Other, Other, Close, Open_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#09# => -- FF09
(Close_Punctuation, Fullwidth,
Other, Other, Close, Close_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0A# => -- FF0A
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0B# => -- FF0B
(Math_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0C# => -- FF0C
(Other_Punctuation, Fullwidth,
Other, Mid_Num, S_Continue, Close_Punctuation,
(Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0D# => -- FF0D
(Dash_Punctuation, Fullwidth,
Other, Other, S_Continue, Ideographic,
(Dash
| Hyphen
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0E# => -- FF0E
(Other_Punctuation, Fullwidth,
Other, Mid_Num_Let, A_Term, Close_Punctuation,
(STerm
| Terminal_Punctuation
| Case_Ignorable
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#0F# => -- FF0F
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#10# .. 16#19# => -- FF10 .. FF19
(Decimal_Number, Fullwidth,
Other, Other, Other, Ideographic,
(Hex_Digit
| Grapheme_Base
| ID_Continue
| XID_Continue
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#1A# => -- FF1A
(Other_Punctuation, Fullwidth,
Other, Mid_Letter, S_Continue, Nonstarter,
(Terminal_Punctuation
| Case_Ignorable
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#1B# => -- FF1B
(Other_Punctuation, Fullwidth,
Other, Mid_Num, Other, Nonstarter,
(Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#1C# .. 16#1E# => -- FF1C .. FF1E
(Math_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#1F# => -- FF1F
(Other_Punctuation, Fullwidth,
Other, Other, S_Term, Exclamation,
(STerm
| Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#20# => -- FF20
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#21# .. 16#26# => -- FF21 .. FF26
(Uppercase_Letter, Fullwidth,
Other, A_Letter, Upper, Ideographic,
(Hex_Digit
| Alphabetic
| Cased
| Changes_When_Lowercased
| Changes_When_Casefolded
| Changes_When_Casemapped
| Grapheme_Base
| ID_Continue
| ID_Start
| Uppercase
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#27# .. 16#3A# => -- FF27 .. FF3A
(Uppercase_Letter, Fullwidth,
Other, A_Letter, Upper, Ideographic,
(Alphabetic
| Cased
| Changes_When_Lowercased
| Changes_When_Casefolded
| Changes_When_Casemapped
| Grapheme_Base
| ID_Continue
| ID_Start
| Uppercase
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#3B# => -- FF3B
(Open_Punctuation, Fullwidth,
Other, Other, Close, Open_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#3C# => -- FF3C
(Other_Punctuation, Fullwidth,
Other, Other, Other, Ideographic,
(Other_Math
| Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#3D# => -- FF3D
(Close_Punctuation, Fullwidth,
Other, Other, Close, Close_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#3E# => -- FF3E
(Modifier_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Diacritic
| Other_Math
| Case_Ignorable
| Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#3F# => -- FF3F
(Connector_Punctuation, Fullwidth,
Other, Extend_Num_Let, Other, Ideographic,
(Grapheme_Base
| ID_Continue
| XID_Continue
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#40# => -- FF40
(Modifier_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Diacritic
| Case_Ignorable
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#41# .. 16#46# => -- FF41 .. FF46
(Lowercase_Letter, Fullwidth,
Other, A_Letter, Lower, Ideographic,
(Hex_Digit
| Alphabetic
| Cased
| Changes_When_Uppercased
| Changes_When_Titlecased
| Changes_When_Casemapped
| Grapheme_Base
| ID_Continue
| ID_Start
| Lowercase
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#47# .. 16#5A# => -- FF47 .. FF5A
(Lowercase_Letter, Fullwidth,
Other, A_Letter, Lower, Ideographic,
(Alphabetic
| Cased
| Changes_When_Uppercased
| Changes_When_Titlecased
| Changes_When_Casemapped
| Grapheme_Base
| ID_Continue
| ID_Start
| Lowercase
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#5B# => -- FF5B
(Open_Punctuation, Fullwidth,
Other, Other, Close, Open_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#5C# => -- FF5C
(Math_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#5D# => -- FF5D
(Close_Punctuation, Fullwidth,
Other, Other, Close, Close_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#5E# => -- FF5E
(Math_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#5F# => -- FF5F
(Open_Punctuation, Fullwidth,
Other, Other, Close, Open_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#60# => -- FF60
(Close_Punctuation, Fullwidth,
Other, Other, Close, Close_Punctuation,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#61# => -- FF61
(Other_Punctuation, Halfwidth,
Other, Other, S_Term, Close_Punctuation,
(STerm
| Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#62# => -- FF62
(Open_Punctuation, Halfwidth,
Other, Other, Close, Open_Punctuation,
(Quotation_Mark
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#63# => -- FF63
(Close_Punctuation, Halfwidth,
Other, Other, Close, Close_Punctuation,
(Quotation_Mark
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#64# => -- FF64
(Other_Punctuation, Halfwidth,
Other, Other, S_Continue, Close_Punctuation,
(Terminal_Punctuation
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#65# => -- FF65
(Other_Punctuation, Halfwidth,
Other, Other, Other, Nonstarter,
(Hyphen
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#66# => -- FF66
(Other_Letter, Halfwidth,
Other, Katakana, O_Letter, Alphabetic,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#67# .. 16#6F# => -- FF67 .. FF6F
(Other_Letter, Halfwidth,
Other, Katakana, O_Letter, Conditional_Japanese_Starter,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#70# => -- FF70
(Modifier_Letter, Halfwidth,
Other, Katakana, O_Letter, Conditional_Japanese_Starter,
(Diacritic
| Extender
| Alphabetic
| Case_Ignorable
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#71# .. 16#9D# => -- FF71 .. FF9D
(Other_Letter, Halfwidth,
Other, Katakana, O_Letter, Alphabetic,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#9E# .. 16#9F# => -- FF9E .. FF9F
(Modifier_Letter, Halfwidth,
Extend, Extend, Extend, Nonstarter,
(Diacritic
| Other_Grapheme_Extend
| Alphabetic
| Case_Ignorable
| Grapheme_Extend
| ID_Continue
| ID_Start
| XID_Continue
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#A0# => -- FFA0
(Other_Letter, Halfwidth,
Other, A_Letter, O_Letter, Alphabetic,
(Other_Default_Ignorable_Code_Point
| Alphabetic
| Default_Ignorable_Code_Point
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#BF# .. 16#C1# => -- FFBF .. FFC1
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#C8# .. 16#C9# => -- FFC8 .. FFC9
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#D0# .. 16#D1# => -- FFD0 .. FFD1
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#D8# .. 16#D9# => -- FFD8 .. FFD9
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#DD# .. 16#DF# => -- FFDD .. FFDF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#E0# => -- FFE0
(Currency_Symbol, Fullwidth,
Other, Other, Other, Postfix_Numeric,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E1# => -- FFE1
(Currency_Symbol, Fullwidth,
Other, Other, Other, Prefix_Numeric,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E2# => -- FFE2
(Math_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E3# => -- FFE3
(Modifier_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Diacritic
| Case_Ignorable
| Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E4# => -- FFE4
(Other_Symbol, Fullwidth,
Other, Other, Other, Ideographic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E5# .. 16#E6# => -- FFE5 .. FFE6
(Currency_Symbol, Fullwidth,
Other, Other, Other, Prefix_Numeric,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E7# => -- FFE7
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#E8# => -- FFE8
(Other_Symbol, Halfwidth,
Other, Other, Other, Alphabetic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#E9# .. 16#EC# => -- FFE9 .. FFEC
(Math_Symbol, Halfwidth,
Other, Other, Other, Alphabetic,
(Grapheme_Base
| Math
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#ED# .. 16#EE# => -- FFED .. FFEE
(Other_Symbol, Halfwidth,
Other, Other, Other, Alphabetic,
(Grapheme_Base
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#EF# => -- FFEF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(others => False)),
16#F0# .. 16#F8# => -- FFF0 .. FFF8
(Unassigned, Neutral,
Control, Other, Other, Unknown,
(Other_Default_Ignorable_Code_Point
| Default_Ignorable_Code_Point
| Changes_When_NFKC_Casefolded => True,
others => False)),
16#F9# .. 16#FB# => -- FFF9 .. FFFB
(Format, Neutral,
Control, Format, Format, Combining_Mark,
(Case_Ignorable => True,
others => False)),
16#FC# => -- FFFC
(Other_Symbol, Neutral,
Other, Other, Other, Contingent_Break,
(Grapheme_Base => True,
others => False)),
16#FD# => -- FFFD
(Other_Symbol, Ambiguous,
Other, Other, Other, Ambiguous,
(Grapheme_Base => True,
others => False)),
16#FE# .. 16#FF# => -- FFFE .. FFFF
(Unassigned, Neutral,
Other, Other, Other, Unknown,
(Noncharacter_Code_Point => True,
others => False)),
others =>
(Other_Letter, Halfwidth,
Other, A_Letter, O_Letter, Alphabetic,
(Alphabetic
| Grapheme_Base
| ID_Continue
| ID_Start
| XID_Continue
| XID_Start
| Changes_When_NFKC_Casefolded => True,
others => False)));
end Matreshka.Internals.Unicode.Ucd.Core_00FF;
|
-- Demonstrate a trivial procedure with another nested inside
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure Compute is
procedure Double(Item : in out Integer) is
begin
Item := Item * 2;
end Double;
X : Integer := 1; -- Local variable X of type int
begin -- Actually begin the procedure compute
loop
Put(X);
New_Line;
Double(X);
end loop;
end Compute;
|
-- -----------------------------------------------------------------------------
-- Copyright 2018 Lionel Draghi
--
-- 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.
-- -----------------------------------------------------------------------------
-- This file is part of the List_Image project
-- available at https://github.com/LionelDraghi/List_Image
-- -----------------------------------------------------------------------------
package List_Image.Unix_Predefined_Styles is
EOL : constant String := Unix_EOL;
-- Note that two identical packages exist, named :
-- List_Image.[Unix|Windows]_Predefined_Styles
-- The only difference between those packages is this platform specific
-- EOL definition.
-- --------------------------------------------------------------------------
-- Predefined multi-line style
-- --------------------------------------------------------------------------
--
-- - Bulleted_List_Style :
-- > - A
-- > - B
-- > - C
--
-- - Markdown_Bulleted_List_Style :
-- Like the bulleted list, but surrounded by
-- two empty lines (in some Markdown implementation, if the first bullet
-- is not preceded by an empty line, the list is not recognized)
--
-- - HTML_Bulleted_List_Style :
-- > <ul>
-- > <li>A</li>
-- > <li>B</li>
-- > <li>C</li>
-- > </ul>
-- Note : <ul></ul>, an empty list, is recognized by most navigator,
-- but seems to be illegal html.
-- No problem here, thanks to _If_Empty parameters nothing will
-- be generated if the list is empty.
--
-- --------------------------------------------------------------------------
package Bulleted_List_Style is new Image_Style
(Prefix => EOL & "- ",
Separator => EOL & "- ",
Postfix => EOL,
Prefix_If_Empty => "",
Postfix_If_Empty => "");
package Markdown_Bulleted_List_Style is new Image_Style
(Prefix => EOL & EOL & "- ",
Separator => EOL & "- ",
Postfix => EOL & EOL,
Prefix_If_Empty => EOL,
Postfix_If_Empty => "");
package HTML_Bulleted_List_Style is new Image_Style
(Prefix => "<ul>" & EOL & " <li>",
Separator => "</li>" & EOL & " <li>",
Postfix => "</li>" & EOL & "</ul>",
Prefix_If_Empty => "",
Postfix_If_Empty => "");
end List_Image.Unix_Predefined_Styles;
|
-- This file is covered by the Internet Software Consortium (ISC) License
-- Reference: ../../License.txt
with Ada.Characters.Handling;
package body AdaBase.Connection.Base.PostgreSQL is
package ACH renames Ada.Characters.Handling;
---------------------
-- setCompressed --
---------------------
overriding
procedure setCompressed (conn : out PostgreSQL_Connection; compressed : Boolean)
is
begin
raise UNSUPPORTED_BY_PGSQL;
end setCompressed;
------------------
-- compressed --
------------------
overriding
function compressed (conn : PostgreSQL_Connection) return Boolean is
begin
return False;
end compressed;
--------------------
-- setUseBuffer --
--------------------
overriding
procedure setUseBuffer (conn : out PostgreSQL_Connection;
buffered : Boolean) is
begin
raise UNSUPPORTED_BY_PGSQL;
end setUseBuffer;
-----------------
-- useBuffer --
-----------------
overriding
function useBuffer (conn : PostgreSQL_Connection) return Boolean is
begin
return False;
end useBuffer;
--------------------------------
-- driverMessage (interface) --
--------------------------------
overriding
function driverMessage (conn : PostgreSQL_Connection) return String
is
result : BND.ICS.chars_ptr := BND.PQerrorMessage (conn.handle);
begin
return BND.ICS.Value (result);
end driverMessage;
-----------------------
-- driverMessage #2 --
-----------------------
function driverMessage (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return String
is
result : BND.ICS.chars_ptr := BND.PQresultErrorMessage (res);
begin
return BND.ICS.Value (result);
end driverMessage;
------------------------------
-- driverCode (interface) --
------------------------------
overriding
function driverCode (conn : PostgreSQL_Connection) return Driver_Codes is
begin
if conn.cmd_sql_state = stateless or else
conn.cmd_sql_state = "00000"
then
return 0;
end if;
if conn.cmd_sql_state (1 .. 2) = "01" then
return 1;
end if;
return 2;
end driverCode;
---------------------
-- driverCode #2 --
---------------------
function driverCode (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Driver_Codes
is
SS : constant SQL_State := conn.SqlState (res);
begin
if SS = stateless or else SS = "00000" then
return 0;
end if;
if SS (1 .. 2) = "01" then
return 1;
end if;
return 2;
end driverCode;
----------------------------
-- SqlState (interface) --
----------------------------
overriding
function SqlState (conn : PostgreSQL_Connection) return SQL_State is
begin
return conn.cmd_sql_state;
end SqlState;
-------------------
-- SqlState #2 --
-------------------
function SqlState (conn : PostgreSQL_Connection; res : BND.PGresult_Access)
return SQL_State
is
use type BND.ICS.chars_ptr;
fieldcode : constant BND.IC.int := BND.PG_DIAG_SQLSTATE;
detail : BND.ICS.chars_ptr;
begin
detail := BND.PQresultErrorField (res, fieldcode);
if detail = BND.ICS.Null_Ptr then
return stateless;
end if;
declare
SS : String := BND.ICS.Value (detail);
begin
return SQL_State (SS);
end;
end SqlState;
-------------------
-- description --
-------------------
overriding
function description (conn : PostgreSQL_Connection) return String
is
begin
return conn.info_description;
end description;
-------------------------
-- helper_get_row_id --
-------------------------
function returned_id (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Trax_ID
is
begin
if conn.field_is_null (res, 0, 0) then
return 0;
end if;
declare
field : constant String := conn.field_string (res, 0, 0);
begin
return Trax_ID (Integer'Value (field));
exception
when others => return 0;
end;
end returned_id;
-----------------------
-- private_execute --
-----------------------
procedure private_execute (conn : out PostgreSQL_Connection; sql : String)
is
use type BND.ExecStatusType;
pgres : BND.PGresult_Access;
query : BND.ICS.chars_ptr := BND.ICS.New_String (Str => sql);
success : Boolean;
msg : CT.Text;
ins_cmd : Boolean := False;
begin
if sql'Length > 12 and then
ACH.To_Upper (sql (sql'First .. sql'First + 6)) = "INSERT "
then
ins_cmd := True;
end if;
pgres := BND.PQexec (conn => conn.handle, command => query);
BND.ICS.Free (query);
case conn.examine_result (pgres) is
when executed =>
success := True;
conn.cmd_insert_return := False;
when returned_data =>
success := True;
conn.cmd_insert_return := ins_cmd;
when failed =>
success := False;
msg := CT.SUS (conn.driverMessage (pgres));
end case;
conn.cmd_sql_state := conn.SqlState (pgres);
if success then
conn.cmd_rows_impact := conn.rows_impacted (pgres);
else
conn.cmd_rows_impact := 0;
end if;
if conn.cmd_insert_return then
conn.insert_return_val := conn.returned_id (pgres);
else
conn.insert_return_val := 0;
end if;
BND.PQclear (pgres);
if not success then
raise QUERY_FAIL with CT.USS (msg);
end if;
end private_execute;
----------------------
-- private_select --
----------------------
function private_select (conn : PostgreSQL_Connection; sql : String)
return BND.PGresult_Access
is
use type BND.ExecStatusType;
pgres : BND.PGresult_Access;
query : BND.ICS.chars_ptr := BND.ICS.New_String (Str => sql);
selcmd : Boolean := True;
success : Boolean;
msg : CT.Text;
begin
pgres := BND.PQexec (conn => conn.handle, command => query);
BND.ICS.Free (query);
case conn.examine_result (pgres) is
when executed =>
success := False;
selcmd := False;
when returned_data =>
success := True;
when failed =>
success := False;
msg := CT.SUS (conn.driverMessage (pgres));
end case;
if not success then
if selcmd then
raise QUERY_FAIL with CT.USS (msg);
else
raise QUERY_FAIL with "Not a SELECT query: " & sql;
end if;
end if;
return pgres;
end private_select;
----------------------------------------------
-- rows_affected_by_execution (interface) --
----------------------------------------------
overriding
function rows_affected_by_execution (conn : PostgreSQL_Connection)
return Affected_Rows is
begin
return conn.cmd_rows_impact;
end rows_affected_by_execution;
----------------------
-- rows_in_result --
----------------------
function rows_in_result (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return Affected_Rows
is
use type BND.IC.int;
result : BND.IC.int := BND.PQntuples (res);
begin
if result < 0 then
-- overflowed (e.g. > 2 ** 31 on 32-bit system)
return Affected_Rows'Last;
end if;
return Affected_Rows (result);
end rows_in_result;
---------------------
-- rows_impacted --
---------------------
function rows_impacted (conn : PostgreSQL_Connection;
res : BND.PGresult_Access)
return Affected_Rows
is
result : BND.ICS.chars_ptr := BND.PQcmdTuples (res);
resstr : constant String := BND.ICS.Value (result);
begin
if CT.IsBlank (resstr) then
return 0;
end if;
begin
return Affected_Rows (Integer'Value (resstr));
exception
when others => return 0;
end;
end rows_impacted;
-------------------------
-- begin_transaction --
-------------------------
procedure begin_transaction (conn : out PostgreSQL_Connection) is
begin
conn.private_execute ("BEGIN");
conn.dummy := True;
exception
when E : QUERY_FAIL =>
raise TRAX_BEGIN_FAIL with EX.Exception_Message (E);
end begin_transaction;
--------------
-- commit --
--------------
overriding
procedure commit (conn : out PostgreSQL_Connection)
is
procedure deallocate_prep_statement (Position : stmt_vector.Cursor);
procedure deallocate_prep_statement (Position : stmt_vector.Cursor)
is
identifier : constant Trax_ID := stmt_vector.Element (Position);
stmt_name : constant String := "AdaBase_" & CT.trim (identifier'Img);
begin
if conn.destroy_statement (stmt_name) then
null;
end if;
end deallocate_prep_statement;
begin
begin
conn.private_execute ("COMMIT");
conn.stmts_to_destroy.Iterate (deallocate_prep_statement'Access);
conn.stmts_to_destroy.Clear;
exception
when E : QUERY_FAIL =>
raise COMMIT_FAIL with EX.Exception_Message (E);
end;
if not conn.autoCommit then
conn.begin_transaction;
end if;
end commit;
----------------
-- rollback --
----------------
overriding
procedure rollback (conn : out PostgreSQL_Connection)
is
procedure deallocate_prep_statement (Position : stmt_vector.Cursor);
procedure deallocate_prep_statement (Position : stmt_vector.Cursor)
is
identifier : constant Trax_ID := stmt_vector.Element (Position);
stmt_name : constant String := "AdaBase_" & CT.trim (identifier'Img);
begin
if conn.destroy_statement (stmt_name) then
null;
end if;
end deallocate_prep_statement;
begin
begin
conn.private_execute ("ROLLBACK");
conn.stmts_to_destroy.Iterate (deallocate_prep_statement'Access);
conn.stmts_to_destroy.Clear;
exception
when E : QUERY_FAIL =>
raise ROLLBACK_FAIL with EX.Exception_Message (E);
end;
if not conn.autoCommit then
conn.begin_transaction;
end if;
end rollback;
---------------------
-- setAutoCommit --
---------------------
overriding
procedure setAutoCommit (conn : out PostgreSQL_Connection; auto : Boolean)
is
-- PGSQL server has no setting to disable autocommit. Only issuing
-- a BEGIN transaction command will inhibit autocommit (and commit/
-- rollback enables it again). Thus autocommit has to be handled at
-- the adabase level. A "BEGIN" command is issued immediately after
-- connection, COMMIT and ROLLBACK to ensure we're always in a
-- transaction when autocommit is off.
previous_state : Boolean := conn.prop_auto_commit;
begin
conn.prop_auto_commit := auto;
if conn.prop_active then
if auto /= previous_state then
if conn.within_transaction then
if auto then
conn.commit;
end if;
else
if not auto then
conn.begin_transaction;
end if;
end if;
end if;
end if;
end setAutoCommit;
------------------
-- disconnect --
------------------
overriding
procedure disconnect (conn : out PostgreSQL_Connection)
is
use type BND.PGconn_Access;
begin
if conn.handle /= null then
BND.PQfinish (conn => conn.handle);
conn.handle := null;
end if;
conn.tables.Clear;
conn.data_types.Clear;
conn.prop_active := False;
end disconnect;
--------------------
-- fields_count --
--------------------
function fields_count (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Natural
is
result : BND.IC.int := BND.PQnfields (res);
begin
return Natural (result);
end fields_count;
---------------------
-- field_is_null --
---------------------
function field_is_null (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return Boolean
is
use type BND.IC.int;
rownum : constant BND.IC.int := BND.IC.int (row_number);
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : constant BND.IC.int := BND.PQgetisnull (res, rownum, colnum);
begin
return (result = 1);
end field_is_null;
--------------------
-- field_length --
--------------------
function field_length (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return Natural
is
rownum : constant BND.IC.int := BND.IC.int (row_number);
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : constant BND.IC.int := BND.PQgetlength (res, rownum, colnum);
begin
return Natural (result);
end field_length;
------------------------
-- discard_pgresult --
------------------------
procedure discard_pgresult (conn : PostgreSQL_Connection;
res : out BND.PGresult_Access)
is
use type BND.PGresult_Access;
begin
if res /= null then
BND.PQclear (res);
end if;
res := null;
end discard_pgresult;
----------------------------
-- field_data_is_binary --
----------------------------
function field_data_is_binary (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return Boolean
is
use type BND.IC.int;
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : constant BND.IC.int := BND.PQfformat (res, colnum);
begin
return (result = 1);
end field_data_is_binary;
----------------
-- finalize --
----------------
overriding
procedure finalize (conn : in out PostgreSQL_Connection) is
begin
conn.disconnect;
end finalize;
---------------------
-- setMultiQuery --
---------------------
overriding
procedure setMultiQuery (conn : out PostgreSQL_Connection;
multiple : Boolean)
is
-- Applicable only to driver.execute and implemented manually there
-- (in order to use parameter execute rather than pgexec function
begin
conn.prop_multiquery := multiple;
end setMultiQuery;
------------------
-- multiquery --
------------------
overriding
function multiquery (conn : PostgreSQL_Connection) return Boolean is
begin
return conn.prop_multiquery;
end multiquery;
-------------------------------
-- setTransactionIsolation --
-------------------------------
overriding
procedure setTransactionIsolation (conn : out PostgreSQL_Connection;
isolation : Trax_Isolation)
is
use type Trax_Isolation;
sql : constant String :=
"SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL " &
ISO_Keywords (isolation);
begin
if conn.prop_active then
conn.private_execute (sql);
end if;
conn.prop_trax_isolation := isolation;
exception
when QUERY_FAIL =>
raise TRAXISOL_FAIL with sql;
end setTransactionIsolation;
------------------------------------
-- connection_attempt_succeeded --
------------------------------------
function connection_attempt_succeeded (conn : PostgreSQL_Connection)
return Boolean
is
use type BND.ConnStatusType;
status : constant BND.ConnStatusType := BND.PQstatus (conn.handle);
begin
return (status = BND.CONNECTION_OK);
end connection_attempt_succeeded;
-----------------------
-- convert_version --
-----------------------
function convert_version (pgsql_version : Natural) return CT.Text
is
six : String (1 .. 6) := (others => '0');
raw : constant String := CT.int2str (pgsql_version);
len : constant Natural := raw'Length;
begin
six (7 - len .. 6) := raw;
if six (1) = '0' then
return CT.SUS (six (2) & '.' & six (3 .. 4) & '.' & six (5 .. 6));
else
return CT.SUS
(six (1 .. 2) & '.' & six (3 .. 4) & '.' & six (5 .. 6));
end if;
end convert_version;
--------------------------
-- get_server_version --
--------------------------
function get_server_version (conn : PostgreSQL_Connection) return Natural
is
use type BND.IC.int;
version : BND.IC.int := BND.PQserverVersion (conn.handle);
begin
return Natural (version);
end get_server_version;
---------------------------
-- get_library_version --
---------------------------
function get_library_version return Natural
is
use type BND.IC.int;
version : BND.IC.int := BND.PQlibVersion;
begin
return Natural (version);
end get_library_version;
-----------------------
-- get_server_info --
-----------------------
function get_server_info (conn : PostgreSQL_Connection) return CT.Text
is
use type BND.IC.int;
protocol : BND.IC.int := BND.PQprotocolVersion (conn.handle);
begin
return CT.SUS ("Protocol " & CT.int2str (Integer (protocol)) & ".0");
end get_server_info;
-----------------------
-- is_ipv4_or_ipv6 --
-----------------------
function is_ipv4_or_ipv6 (teststr : String) return Boolean
is
function is_byte (segment : String) return Boolean;
function is_byte (segment : String) return Boolean is
begin
if segment'Length > 3 then
return False;
end if;
for x in segment'Range loop
case segment (x) is
when '0' .. '9' => null;
when others => return False;
end case;
end loop;
return (Integer'Value (segment) < 256);
end is_byte;
num_dots : constant Natural := CT.count_char (teststr, '.');
dot : constant String := ".";
begin
if num_dots = 3 then
declare
P1A : String := CT.part_1 (teststr, dot);
P1B : String := CT.part_2 (teststr, dot);
begin
if is_byte (P1A) then
declare
P2A : String := CT.part_1 (P1B, dot);
P2B : String := CT.part_2 (P1B, dot);
begin
if is_byte (P2A) then
declare
P3A : String := CT.part_1 (P2B, dot);
P3B : String := CT.part_2 (P2B, dot);
begin
if is_byte (P3A) and then is_byte (P3B) then
return True;
end if;
end;
end if;
end;
end if;
end;
end if;
for x in teststr'Range loop
case teststr (x) is
when ':' | '0' .. '9' | 'A' .. 'F' | 'a' .. 'f' => null;
when others => return False;
end case;
end loop;
return True;
end is_ipv4_or_ipv6;
--------------------------
-- within_transaction --
--------------------------
function within_transaction (conn : PostgreSQL_Connection) return Boolean
is
use type BND.PGTransactionStatusType;
status : BND.PGTransactionStatusType;
begin
status := BND.PQtransactionStatus (conn.handle);
return (status /= BND.PQTRANS_IDLE);
end within_transaction;
---------------
-- connect --
---------------
overriding
procedure connect (conn : out PostgreSQL_Connection;
database : String;
username : String := blankstring;
password : String := blankstring;
hostname : String := blankstring;
socket : String := blankstring;
port : Posix_Port := portless)
is
constr : CT.Text := CT.SUS ("dbname=" & database);
begin
if conn.prop_active then
raise NOT_WHILE_CONNECTED;
end if;
if not CT.IsBlank (username) then
CT.SU.Append (constr, " user=" & username);
end if;
if not CT.IsBlank (password) then
CT.SU.Append (constr, " password=" & password);
end if;
if not CT.IsBlank (hostname) then
if is_ipv4_or_ipv6 (hostname) then
CT.SU.Append (constr, " hostaddr=" & hostname);
else
CT.SU.Append (constr, " host=" & hostname);
end if;
else
if not CT.IsBlank (socket) then
CT.SU.Append (constr, " host=" & socket);
end if;
end if;
if port /= portless then
CT.SU.Append (constr, " port=" & CT.int2str (port));
end if;
declare
use type BND.PGconn_Access;
conninfo : BND.ICS.chars_ptr := BND.ICS.New_String (CT.USS (constr));
begin
conn.tables.Clear;
conn.handle := BND.PQconnectdb (conninfo);
BND.ICS.Free (conninfo);
if not conn.connection_attempt_succeeded then
raise CONNECT_FAILED;
end if;
end;
conn.prop_active := True;
conn.info_server_version := convert_version (conn.get_server_version);
conn.info_server := conn.get_server_info;
conn.establish_uniform_encoding;
conn.retrieve_uniform_encoding;
conn.setTransactionIsolation (conn.prop_trax_isolation);
if not conn.prop_auto_commit then
conn.begin_transaction;
end if;
-- dump all tables and data types
conn.cache_table_names;
conn.cache_data_types;
exception
when NOT_WHILE_CONNECTED =>
raise NOT_WHILE_CONNECTED with
"Reconnection attempted during an active connection";
when CONNECT_FAILED =>
declare
msg : String := "connection failure: " & conn.driverMessage;
begin
conn.disconnect;
raise CONNECT_FAILED with msg;
end;
when rest : others =>
conn.disconnect;
EX.Reraise_Occurrence (rest);
end connect;
------------------
-- Initialize --
------------------
overriding
procedure Initialize (conn : in out PostgreSQL_Connection) is
begin
conn.info_client_version := convert_version (get_library_version);
conn.info_client := conn.info_client_version;
end Initialize;
------------------
-- field_name --
------------------
function field_name (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return String
is
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : BND.ICS.chars_ptr := BND.PQfname (res, colnum);
begin
return BND.ICS.Value (result);
end field_name;
--------------------
-- field_string --
--------------------
function field_string (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural) return String
is
rownum : constant BND.IC.int := BND.IC.int (row_number);
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : BND.ICS.chars_ptr := BND.PQgetvalue (res, rownum, colnum);
begin
return BND.ICS.Value (result);
end field_string;
--------------------
-- lastInsertID --
--------------------
overriding
function lastInsertID (conn : PostgreSQL_Connection) return Trax_ID
is
-- PostgreSQL has a non-standard extension to INSERT INTO called
-- RETURNING that is the most reliably method to get the last insert
-- ID on the primary key. We use it (determined in private_execute)
-- if RETURNING was part of the INSERT query, otherwise we fall back
-- to the less reliable lastval() method.
begin
if conn.cmd_insert_return then
return conn.insert_return_val;
else
return conn.select_last_val;
end if;
end lastInsertID;
-----------------------
-- select_last_val --
-----------------------
function select_last_val (conn : PostgreSQL_Connection) return Trax_ID
is
pgres : BND.PGresult_Access;
product : Trax_ID := 0;
begin
-- private_select can raise exception, but don't catch it
-- For lastval(), exceptions should not be thrown so don't mask it
pgres := conn.private_select ("SELECT lastval()");
if conn.field_is_null (pgres, 0, 0) then
BND.PQclear (pgres);
return 0;
end if;
declare
field : constant String := conn.field_string (pgres, 0, 0);
begin
product := Trax_ID (Integer'Value (field));
exception
when others => null;
end;
BND.PQclear (pgres);
return product;
end select_last_val;
---------------
-- execute --
---------------
overriding
procedure execute (conn : out PostgreSQL_Connection; sql : String) is
begin
conn.private_execute (sql => sql);
end execute;
-------------------------
-- cache_table_names --
-------------------------
procedure cache_table_names (conn : out PostgreSQL_Connection)
is
pgres : BND.PGresult_Access;
nrows : Affected_Rows;
sql : constant String :=
"SELECT oid, relname FROM pg_class " &
"WHERE relkind = 'r' and relname !~ '^(pg|sql)_' " &
"ORDER BY oid";
begin
pgres := conn.private_select (sql);
nrows := conn.rows_in_result (pgres);
for x in Natural range 0 .. Natural (nrows) - 1 loop
declare
s_oid : constant String := conn.field_string (pgres, x, 0);
s_table : constant String := conn.field_string (pgres, x, 1);
payload : table_cell := (column_1 => CT.SUS (s_table));
begin
conn.tables.Insert (Key => Integer'Value (s_oid),
New_Item => payload);
end;
end loop;
BND.PQclear (pgres);
end cache_table_names;
-------------------
-- field_table --
-------------------
function field_table (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return String
is
use type BND.Oid;
colnum : constant BND.IC.int := BND.IC.int (column_number);
pg_oid : BND.Oid := BND.PQftable (res, colnum);
pg_key : Integer := Integer (pg_oid);
begin
if pg_oid = BND.InvalidOid then
return "INVALID COLUMN";
end if;
pg_key := Positive (pg_oid);
if conn.tables.Contains (Key => pg_key) then
return CT.USS (conn.tables.Element (pg_key).column_1);
else
return "INVALID OID" & pg_key'Img;
end if;
end field_table;
------------------
-- field_type --
------------------
function field_type (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return field_types
is
colnum : constant BND.IC.int := BND.IC.int (column_number);
pg_oid : BND.Oid := BND.PQftype (res, colnum);
pg_key : Positive := Positive (pg_oid);
begin
if conn.data_types.Contains (Key => pg_key) then
return conn.data_types.Element (pg_key).data_type;
else
-- Not in container, fall back to text tupe
return ft_textual;
end if;
end field_type;
-------------------------
-- prepare_statement --
-------------------------
function prepare_statement (conn : PostgreSQL_Connection;
stmt : aliased out BND.PGresult_Access;
name : String;
sql : String) return Boolean
is
use type BND.ExecStatusType;
c_stmt_name : BND.ICS.chars_ptr := BND.ICS.New_String (name);
c_query : BND.ICS.chars_ptr := BND.ICS.New_String (sql);
begin
stmt := BND.PQprepare (conn => conn.handle,
stmtName => c_stmt_name,
query => c_query,
nParams => 0,
paramTypes => null);
BND.ICS.Free (c_stmt_name);
BND.ICS.Free (c_query);
return (BND.PQresultStatus (stmt) = BND.PGRES_COMMAND_OK);
end prepare_statement;
------------------------
-- prepare_metadata --
------------------------
function prepare_metadata (conn : PostgreSQL_Connection;
meta : aliased out BND.PGresult_Access;
name : String) return Boolean
is
use type BND.ExecStatusType;
c_stmt_name : BND.ICS.chars_ptr := BND.ICS.New_String (name);
begin
meta := BND.PQdescribePrepared (conn => conn.handle,
stmtName => c_stmt_name);
BND.ICS.Free (c_stmt_name);
return (BND.PQresultStatus (meta) = BND.PGRES_COMMAND_OK);
end prepare_metadata;
----------------------
-- examine_result --
----------------------
function examine_result (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return postexec_status
is
begin
case BND.PQresultStatus (res) is
when BND.PGRES_COMMAND_OK =>
return executed;
when BND.PGRES_TUPLES_OK =>
return returned_data;
when others =>
return failed;
end case;
end examine_result;
------------------------
-- direst_stmt_exec --
------------------------
function direct_stmt_exec (conn : out PostgreSQL_Connection;
stmt : aliased out BND.PGresult_Access;
sql : String) return Boolean
is
use type BND.ExecStatusType;
query : BND.ICS.chars_ptr := BND.ICS.New_String (Str => sql);
success : Boolean;
msg : CT.Text;
ins_cmd : Boolean := False;
begin
if sql'Length > 12 and then
ACH.To_Upper (sql (sql'First .. sql'First + 6)) = "INSERT "
then
ins_cmd := True;
end if;
stmt := BND.PQexec (conn => conn.handle, command => query);
BND.ICS.Free (query);
case conn.examine_result (stmt) is
when executed =>
success := True;
conn.cmd_insert_return := False;
when returned_data =>
success := True;
conn.cmd_insert_return := ins_cmd;
when failed =>
success := False;
msg := CT.SUS (conn.driverMessage (stmt));
end case;
conn.insert_return_val := 0;
conn.cmd_sql_state := conn.SqlState (stmt);
if success then
conn.cmd_rows_impact := conn.rows_impacted (stmt);
else
conn.cmd_rows_impact := 0;
end if;
if conn.cmd_insert_return then
if not conn.field_is_null (stmt, 0, 0) then
declare
field : constant String := conn.field_string (stmt, 0, 0);
begin
conn.insert_return_val := Trax_ID (Integer'Value (field));
exception
when others => null;
end;
end if;
end if;
return success;
end direct_stmt_exec;
--------------------
-- piped_tables --
--------------------
function piped_tables (conn : PostgreSQL_Connection) return String
is
result : CT.Text := CT.blank;
procedure add (position : table_map.Cursor);
procedure add (position : table_map.Cursor) is
begin
if not CT.IsBlank (result) then
CT.SU.Append (result, '|');
end if;
CT.SU.Append (result, table_map.Element (position).column_1);
end add;
begin
conn.tables.Iterate (Process => add'Access);
return CT.USS (result);
end piped_tables;
-------------------------
-- refined_byte_type --
-------------------------
function refined_byte_type (byteX : field_types; constraint : String)
return field_types
is
-- This routine is not used!
-- by policy, byteX is ft_byte2, ft_byte3, ft_byte4 or ft_byte8
subtype max_range is Positive range 1 .. 4;
zero_required : constant String := "(VALUE >= 0)";
max_size : max_range;
begin
if CT.IsBlank (constraint) then
return byteX;
end if;
if not CT.contains (S => constraint, fragment => zero_required) then
return byteX;
end if;
case byteX is
when ft_byte8 => max_size := 4; -- NByte4
when ft_byte4 => max_size := 3; -- NByte3
when ft_byte3 => max_size := 2; -- NByte2
when others => max_size := 1; -- NByte1;
end case;
for x in max_range loop
declare
bits : constant Positive := x * 8;
limit1 : constant Positive := 2 ** bits;
limit2 : constant Positive := limit1 - 1;
check1 : constant String := "(VALUE <" & limit1'Img & ")";
check2 : constant String := "(VALUE <=" & limit2'Img & ")";
begin
if x <= max_size then
if CT.contains (S => constraint, fragment => check1) or else
CT.contains (S => constraint, fragment => check2)
then
case x is
when 1 => return ft_nbyte1;
when 2 => return ft_nbyte2;
when 3 => return ft_nbyte3;
when 4 => return ft_nbyte4;
end case;
end if;
end if;
end;
end loop;
return byteX;
end refined_byte_type;
-------------------------
-- convert_data_type --
-------------------------
function convert_data_type (pg_type : String; category : Character;
typelen : Integer; encoded_utf8 : Boolean)
return field_types
is
-- Code Category (typcategory)
-- A Array types
-- B Boolean types
-- C Composite types
-- D Date/time types
-- E Enum types
-- G Geometric types
-- I Network address types
-- N Numeric types
-- P Pseudo-types
-- S String types
-- T Timespan types
-- U User-defined types
-- V Bit-string types
-- X unknown type
desc : constant String := pg_type & " (" & category & ")";
string_type : field_types := ft_textual;
begin
-- One User-defined type, bytea, is a chain. Check for this one first
-- and treat the reast as strings
if pg_type = "bytea" then
return ft_chain;
end if;
if encoded_utf8 then
string_type := ft_utf8;
end if;
case category is
when 'A' => return ft_textual; -- No support for arrays yet
when 'B' => return ft_nbyte0;
when 'C' => return ft_textual; -- No support for composites yet
when 'D' => return ft_timestamp;
when 'E' => return ft_enumtype;
when 'G' => return ft_textual; -- unsupp native geom, not postgis!
when 'I' => return ft_textual;
when 'N' => null; -- Let numerics fall through
when 'S' => return string_type;
when 'T' => return ft_textual; -- Huge, 4/12/16 bytes
when 'U' =>
if pg_type = "geometry" then
-- PostGIS
return ft_geometry;
else
return ft_textual;
end if;
when 'V' => return ft_bits; -- String of 1/0 for now
when 'X' => raise METADATA_FAIL
with "Unknown type encountered: " & desc;
when 'P' => raise METADATA_FAIL
with "Pseudo-type encountered: " & desc;
when others => null;
end case;
-- Pick out standard float/double types from the remaining (numerics)
if pg_type = "real" then
return ft_real9;
elsif pg_type = "float4" then
return ft_real9;
elsif pg_type = "float8" then
return ft_real18;
elsif pg_type = "money" then
return ft_real18;
elsif pg_type = "decimal" then
return ft_real18;
elsif pg_type = "numeric" then
return ft_real18;
elsif pg_type = "double precision" then
return ft_real18;
elsif typelen = -1 then
return ft_real18;
end if;
if typelen = 1 then
return ft_byte1;
elsif typelen = 2 then
return ft_byte2;
elsif typelen = 3 then
return ft_byte3;
elsif typelen = 4 then
return ft_byte4;
elsif typelen = 8 then
return ft_byte8;
else
raise METADATA_FAIL
with "Unknown numeric type encountered: " & desc;
end if;
end convert_data_type;
------------------------
-- cache_data_types --
------------------------
procedure cache_data_types (conn : out PostgreSQL_Connection)
is
pgres : BND.PGresult_Access;
nrows : Affected_Rows;
tables : constant String := conn.piped_tables;
sql : constant String :=
"SELECT DISTINCT a.atttypid,t.typname,t.typlen,t.typcategory " &
"FROM pg_class c, pg_attribute a, pg_type t " &
"WHERE c.relname ~ '^(" & tables & ")$' " &
"AND a.attnum > 0 AND a.attrelid = c.oid " &
"AND a.atttypid = t.oid " &
"ORDER BY a.atttypid";
begin
pgres := conn.private_select (sql);
nrows := conn.rows_in_result (pgres);
for x in Natural range 0 .. Natural (nrows) - 1 loop
declare
s_oid : constant String := conn.field_string (pgres, x, 0);
s_name : constant String := conn.field_string (pgres, x, 1);
s_tlen : constant String := conn.field_string (pgres, x, 2);
s_cat : constant String := conn.field_string (pgres, x, 3);
s_cons : constant String := "";
typcat : constant Character := s_cat (s_cat'First);
typelen : constant Integer := Integer'Value (s_tlen);
payload : data_type_rec :=
(data_type => convert_data_type
(s_name, typcat, typelen, conn.encoding_is_utf8));
begin
conn.data_types.Insert (Key => Integer'Value (s_oid),
New_Item => payload);
end;
end loop;
BND.PQclear (pgres);
end cache_data_types;
--------------------
-- field_binary --
--------------------
function field_binary (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural;
max_length : Natural) return String
is
rownum : constant BND.IC.int := BND.IC.int (row_number);
colnum : constant BND.IC.int := BND.IC.int (column_number);
result : BND.ICS.chars_ptr := BND.PQgetvalue (res, rownum, colnum);
len : Natural := conn.field_length (res, row_number, column_number);
begin
declare
bufmax : constant BND.IC.size_t := BND.IC.size_t (max_length);
subtype data_buffer is BND.IC.char_array (1 .. bufmax);
type db_access is access all data_buffer;
buffer : aliased data_buffer;
function db_convert (dba : db_access; size : Natural) return String;
function db_convert (dba : db_access; size : Natural) return String
is
max : Natural := size;
begin
if max > max_length then
max := max_length;
end if;
declare
result : String (1 .. max);
begin
for x in result'Range loop
result (x) := Character (dba.all (BND.IC.size_t (x)));
end loop;
return result;
end;
end db_convert;
begin
return db_convert (buffer'Access, len);
end;
end field_binary;
--------------------
-- field_chain --
--------------------
function field_chain (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
row_number : Natural;
column_number : Natural;
max_length : Natural) return String
is
-- raw expected in format "/x[hex-byte][hex-byte]...[hex-byte]"
raw : String := conn.field_string (res, row_number, column_number);
maxlen : Natural := raw'Length / 2;
staged : String (1 .. maxlen) := (others => '_');
arrow : Natural := raw'First;
terminus : Natural := raw'Last;
marker : Natural := 0;
begin
if CT.len (raw) < 4 then
return "";
end if;
arrow := arrow + 2; -- skip past "/x"
loop
marker := marker + 1;
if arrow + 1 > terminus then
-- format error! Odd length should never happen
-- replace with zero and eject
staged (marker) := Character'Val (0);
exit;
end if;
declare
hex : constant hexbyte := raw (arrow .. arrow + 1);
begin
staged (marker) := convert_hexbyte_to_char (hex);
arrow := arrow + 2;
end;
exit when arrow > terminus;
exit when marker = max_length;
end loop;
return staged (1 .. marker);
end field_chain;
---------------------
-- markers_found --
---------------------
function markers_found (conn : PostgreSQL_Connection;
res : BND.PGresult_Access) return Natural
is
result : constant BND.IC.int := BND.PQnparams (res);
begin
return (Natural (result));
end markers_found;
-------------------------
-- destroy_statement --
-------------------------
function destroy_statement (conn : out PostgreSQL_Connection;
name : String) return Boolean
is
sql : constant String := "DEALLOCATE " & name;
begin
if conn.prop_active then
conn.private_execute (sql);
end if;
return True;
exception
when QUERY_FAIL =>
return False;
end destroy_statement;
--------------------------------
-- execute_prepared_stmt #1 --
--------------------------------
function execute_prepared_stmt (conn : PostgreSQL_Connection;
name : String;
data : parameter_block)
return BND.PGresult_Access
is
subtype param_range is Positive range 1 .. data'Length;
nParams : constant BND.IC.int := BND.IC.int (data'Length);
resultFormat : constant BND.IC.int := 0; -- specify text results
stmtName : BND.ICS.chars_ptr := BND.ICS.New_String (name);
paramValues : BND.Param_Val_Array (param_range);
paramLengths : BND.Param_Int_Array (param_range);
paramFormats : BND.Param_Int_Array (param_range);
need_free : array (param_range) of Boolean;
pgres : BND.PGresult_Access;
datalen : Natural;
begin
for x in paramLengths'Range loop
datalen := CT.len (data (x).payload);
paramLengths (x) := BND.IC.int (datalen);
if data (x).binary then
paramFormats (x) := BND.IC.int (1);
if data (x).is_null then
need_free (x) := False;
paramValues (x).buffer := null;
else
need_free (x) := True;
declare
Str : constant String := CT.USS (data (x).payload);
bsz : BND.IC.size_t := BND.IC.size_t (datalen);
begin
paramValues (x).buffer := new BND.IC.char_array (1 .. bsz);
paramValues (x).buffer.all := BND.IC.To_C (Str, False);
end;
end if;
else
paramFormats (x) := BND.IC.int (0);
if data (x).is_null then
need_free (x) := False;
paramValues (x).buffer := null;
else
declare
use type BND.IC.size_t;
Str : constant String := CT.USS (data (x).payload);
bsz : BND.IC.size_t := BND.IC.size_t (datalen) + 1;
begin
paramValues (x).buffer := new BND.IC.char_array (1 .. bsz);
paramValues (x).buffer.all := BND.IC.To_C (Str, True);
end;
end if;
end if;
end loop;
pgres := BND.PQexecPrepared
(conn => conn.handle,
stmtName => stmtName,
nParams => nParams,
paramValues => paramValues (1)'Unchecked_Access,
paramLengths => paramLengths (1)'Unchecked_Access,
paramFormats => paramFormats (1)'Unchecked_Access,
resultFormat => resultFormat);
BND.ICS.Free (stmtName);
for x in need_free'Range loop
if need_free (x) then
free_binary (paramValues (x).buffer);
end if;
end loop;
-- Let the caller check the state of pgres, just return it as is
return pgres;
end execute_prepared_stmt;
--------------------------------
-- execute_prepared_stmt #2 --
--------------------------------
function execute_prepared_stmt (conn : PostgreSQL_Connection;
name : String) return BND.PGresult_Access
is
resultFormat : constant BND.IC.int := 0; -- specify text results
stmtName : BND.ICS.chars_ptr := BND.ICS.New_String (name);
pgres : BND.PGresult_Access;
begin
pgres := BND.PQexecPrepared
(conn => conn.handle,
stmtName => stmtName,
nParams => 0,
paramValues => null,
paramLengths => null,
paramFormats => null,
resultFormat => resultFormat);
BND.ICS.Free (stmtName);
-- Let the caller check the state of pgres, just return it as is
return pgres;
end execute_prepared_stmt;
---------------------
-- destroy_later --
---------------------
procedure destroy_later (conn : out PostgreSQL_Connection;
identifier : Trax_ID) is
begin
conn.stmts_to_destroy.Append (New_Item => identifier);
end destroy_later;
-----------------------
-- holds_refcursor --
------------------------
function holds_refcursor (conn : PostgreSQL_Connection;
res : BND.PGresult_Access;
column_number : Natural) return Boolean
is
use type BND.Oid;
colnum : constant BND.IC.int := BND.IC.int (column_number);
pg_oid : BND.Oid := BND.PQftype (res, colnum);
begin
return (pg_oid = BND.PG_TYPE_refcursor);
end holds_refcursor;
-----------------------------
-- convert_octet_to_char --
-----------------------------
function convert_octet_to_char (before : octet) return Character
is
function digit (raw : Character) return Natural;
-- This convert function does no error checking, it expects to receive
-- valid octal numbers. It will no throw an error if illegal
-- characters are found, but rather it will return something value.
function digit (raw : Character) return Natural is
begin
case raw is
when '0' .. '7' => return Character'Pos (raw) - 48;
when others => return 0;
end case;
end digit;
begin
return Character'Val (digit (before (3)) +
digit (before (2)) * 8 +
digit (before (1)) * 64);
end convert_octet_to_char;
-------------------------------
-- convert_hexbyte_to_char --
-------------------------------
function convert_hexbyte_to_char (before : hexbyte) return Character
is
function digit (raw : Character) return Natural;
-- This convert function does no error checking, it expects to receive
-- valid octal numbers. It will no throw an error if illegal
-- characters are found, but rather it will return something value.
function digit (raw : Character) return Natural is
begin
case raw is
when '0' .. '9' => return Character'Pos (raw) -
Character'Pos ('0');
when 'A' .. 'F' => return Character'Pos (raw) + 10 -
Character'Pos ('A');
when 'a' .. 'f' => return Character'Pos (raw) + 10 -
Character'Pos ('a');
when others => return 0;
end case;
end digit;
begin
return Character'Val (digit (before (2)) +
digit (before (1)) * 16);
end convert_hexbyte_to_char;
----------------------------------
-- establish_uniform_encoding --
----------------------------------
procedure establish_uniform_encoding (conn : out PostgreSQL_Connection)
is
sql : constant String := "SET CLIENT_ENCODING TO '" &
CT.USS (conn.character_set) & "'";
begin
if conn.prop_active then
if not CT.IsBlank (conn.character_set) then
execute (conn => conn, sql => sql);
end if;
end if;
exception
when QUERY_FAIL =>
raise CHARSET_FAIL with sql;
end establish_uniform_encoding;
-------------------------
-- set_character_set --
-------------------------
overriding
procedure set_character_set (conn : out PostgreSQL_Connection;
charset : String) is
begin
if conn.prop_active then
raise NOT_WHILE_CONNECTED
with "You may only alter the character set prior to connection";
end if;
conn.character_set := CT.SUS (charset);
end set_character_set;
---------------------
-- character_set --
---------------------
overriding
function character_set (conn : out PostgreSQL_Connection) return String is
begin
if conn.prop_active then
conn.dummy := True;
declare
pgres : BND.PGresult_Access;
begin
-- private_select can raise exception, but don't catch it
pgres := conn.private_select ("SHOW CLIENT_ENCODING");
if conn.field_is_null (pgres, 0, 0) then
-- This should never happen
BND.PQclear (pgres);
return "UNEXPECTED: encoding not set";
end if;
declare
field : constant String := conn.field_string (pgres, 0, 0);
begin
BND.PQclear (pgres);
return field;
end;
end;
else
return CT.USS (conn.character_set);
end if;
end character_set;
---------------------------------
-- retrieve_uniform_encoding --
---------------------------------
procedure retrieve_uniform_encoding (conn : out PostgreSQL_Connection)
is
charset : String := character_set (conn => conn);
charsetuc : String := ACH.To_Upper (charset);
begin
conn.encoding_is_utf8 := (charsetuc = "UTF8");
conn.character_set := CT.SUS (charset);
end retrieve_uniform_encoding;
end AdaBase.Connection.Base.PostgreSQL;
|
pragma Style_Checks (Off);
-- This spec has been automatically generated from STM32G474xx.svd
pragma Restrictions (No_Elaboration_Code);
with System;
-- STM32G474xx
package STM32_SVD is
pragma Preelaborate;
--------------------
-- Base addresses --
--------------------
CRC_Base : constant System.Address := System'To_Address (16#40023000#);
IWDG_Base : constant System.Address := System'To_Address (16#40003000#);
WWDG_Base : constant System.Address := System'To_Address (16#40002C00#);
I2C1_Base : constant System.Address := System'To_Address (16#40005400#);
I2C2_Base : constant System.Address := System'To_Address (16#40005800#);
I2C3_Base : constant System.Address := System'To_Address (16#40007800#);
I2C4_Base : constant System.Address := System'To_Address (16#40008400#);
FLASH_Base : constant System.Address := System'To_Address (16#40022000#);
DBGMCU_Base : constant System.Address := System'To_Address (16#E0042000#);
RCC_Base : constant System.Address := System'To_Address (16#40021000#);
PWR_Base : constant System.Address := System'To_Address (16#40007000#);
RNG_Base : constant System.Address := System'To_Address (16#50060800#);
GPIOA_Base : constant System.Address := System'To_Address (16#48000000#);
GPIOB_Base : constant System.Address := System'To_Address (16#48000400#);
GPIOC_Base : constant System.Address := System'To_Address (16#48000800#);
GPIOD_Base : constant System.Address := System'To_Address (16#48000C00#);
GPIOE_Base : constant System.Address := System'To_Address (16#48001000#);
GPIOF_Base : constant System.Address := System'To_Address (16#48001400#);
GPIOG_Base : constant System.Address := System'To_Address (16#48001800#);
TIM15_Base : constant System.Address := System'To_Address (16#40014000#);
TIM16_Base : constant System.Address := System'To_Address (16#40014400#);
TIM17_Base : constant System.Address := System'To_Address (16#40014800#);
TIM1_Base : constant System.Address := System'To_Address (16#40012C00#);
TIM20_Base : constant System.Address := System'To_Address (16#40015000#);
TIM8_Base : constant System.Address := System'To_Address (16#40013400#);
TIM2_Base : constant System.Address := System'To_Address (16#40000000#);
TIM3_Base : constant System.Address := System'To_Address (16#40000400#);
TIM4_Base : constant System.Address := System'To_Address (16#40000800#);
TIM5_Base : constant System.Address := System'To_Address (16#40000C00#);
TIM6_Base : constant System.Address := System'To_Address (16#40001000#);
TIM7_Base : constant System.Address := System'To_Address (16#40001400#);
LPTIMER1_Base : constant System.Address := System'To_Address (16#40007C00#);
USART1_Base : constant System.Address := System'To_Address (16#40013800#);
USART2_Base : constant System.Address := System'To_Address (16#40004400#);
USART3_Base : constant System.Address := System'To_Address (16#40004800#);
UART4_Base : constant System.Address := System'To_Address (16#40004C00#);
UART5_Base : constant System.Address := System'To_Address (16#40005000#);
LPUART1_Base : constant System.Address := System'To_Address (16#40008000#);
SPI1_Base : constant System.Address := System'To_Address (16#40013000#);
SPI4_Base : constant System.Address := System'To_Address (16#40013C00#);
SPI3_Base : constant System.Address := System'To_Address (16#40003C00#);
SPI2_Base : constant System.Address := System'To_Address (16#40003800#);
EXTI_Base : constant System.Address := System'To_Address (16#40010400#);
RTC_Base : constant System.Address := System'To_Address (16#40002800#);
FMC_Base : constant System.Address := System'To_Address (16#A0000000#);
DMA1_Base : constant System.Address := System'To_Address (16#40020000#);
DMA2_Base : constant System.Address := System'To_Address (16#40020400#);
DMAMUX_Base : constant System.Address := System'To_Address (16#40020800#);
SYSCFG_Base : constant System.Address := System'To_Address (16#40010000#);
VREFBUF_Base : constant System.Address := System'To_Address (16#40010030#);
COMP_Base : constant System.Address := System'To_Address (16#40010200#);
OPAMP_Base : constant System.Address := System'To_Address (16#40010300#);
HRTIM_Master_Base : constant System.Address := System'To_Address (16#40016800#);
HRTIM_TIMA_Base : constant System.Address := System'To_Address (16#40016880#);
HRTIM_TIMB_Base : constant System.Address := System'To_Address (16#40016900#);
HRTIM_TIMC_Base : constant System.Address := System'To_Address (16#40016980#);
HRTIM_TIMD_Base : constant System.Address := System'To_Address (16#40016A00#);
HRTIM_TIME_Base : constant System.Address := System'To_Address (16#40016A80#);
HRTIM_TIMF_Base : constant System.Address := System'To_Address (16#40016B00#);
HRTIM_Common_Base : constant System.Address := System'To_Address (16#40016B80#);
QUADSPI_Base : constant System.Address := System'To_Address (16#A0001000#);
DAC1_Base : constant System.Address := System'To_Address (16#50000800#);
DAC2_Base : constant System.Address := System'To_Address (16#50000C00#);
DAC3_Base : constant System.Address := System'To_Address (16#50001000#);
DAC4_Base : constant System.Address := System'To_Address (16#50001400#);
ADC1_Base : constant System.Address := System'To_Address (16#50000000#);
ADC2_Base : constant System.Address := System'To_Address (16#50000100#);
ADC3_Base : constant System.Address := System'To_Address (16#50000400#);
ADC4_Base : constant System.Address := System'To_Address (16#50000500#);
ADC5_Base : constant System.Address := System'To_Address (16#50000600#);
ADC12_Common_Base : constant System.Address := System'To_Address (16#50000300#);
ADC345_Common_Base : constant System.Address := System'To_Address (16#50000700#);
FMAC_Base : constant System.Address := System'To_Address (16#40021400#);
CORDIC_Base : constant System.Address := System'To_Address (16#40020C00#);
SAI_Base : constant System.Address := System'To_Address (16#40015400#);
TAMP_Base : constant System.Address := System'To_Address (16#40002400#);
FPU_Base : constant System.Address := System'To_Address (16#E000EF34#);
MPU_Base : constant System.Address := System'To_Address (16#E000E084#);
STK_Base : constant System.Address := System'To_Address (16#E000E010#);
SCB_Base : constant System.Address := System'To_Address (16#E000ED00#);
NVIC_Base : constant System.Address := System'To_Address (16#E000E100#);
NVIC_STIR_Base : constant System.Address := System'To_Address (16#E000EF00#);
FPU_CPACR_Base : constant System.Address := System'To_Address (16#E000ED88#);
SCB_ACTLR_Base : constant System.Address := System'To_Address (16#E000E008#);
FDCAN_Base : constant System.Address := System'To_Address (16#4000A400#);
FDCAN1_Base : constant System.Address := System'To_Address (16#40006400#);
FDCAN2_Base : constant System.Address := System'To_Address (16#40006800#);
FDCAN3_Base : constant System.Address := System'To_Address (16#40006C00#);
UCPD1_Base : constant System.Address := System'To_Address (16#4000A000#);
USB_FS_device_Base : constant System.Address := System'To_Address (16#40005C00#);
CRS_Base : constant System.Address := System'To_Address (16#40002000#);
end STM32_SVD;
|
with Cortex_M.Systick;
with System.Machine_Code; use System.Machine_Code;
package body PyGamer.Time is
package Systick renames Cortex_M.Systick;
Clock_Ms : Time_Ms := 0 with Volatile;
Period_Ms : constant Time_Ms := 1;
Subscribers : array (1 .. 10) of Tick_Callback := (others => null);
procedure Initialize;
procedure SysTick_Handler;
pragma Export (C, SysTick_Handler, "__gnat_sys_tick_trap");
----------------
-- Initialize --
----------------
procedure Initialize is
Reload : constant := 120_000_000 / 1_000;
begin
-- Configure for 1kH tick
Systick.Configure (Source => Systick.CPU_Clock,
Generate_Interrupt => True,
Reload_Value => Reload);
Systick.Enable;
end Initialize;
---------------------
-- SysTick_Handler --
---------------------
procedure SysTick_Handler is
begin
Clock_Ms := Clock_Ms + Period_Ms;
for Subs of Subscribers loop
if Subs /= null then
-- Call the subscriber
Subs.all;
end if;
end loop;
end SysTick_Handler;
-----------
-- Clock --
-----------
function Clock return Time_Ms
is (Clock_Ms);
--------------
-- Delay_Ms --
--------------
procedure Delay_Ms (Milliseconds : UInt64) is
begin
Delay_Until (Clock + Milliseconds);
end Delay_Ms;
-----------------
-- Delay_Until --
-----------------
procedure Delay_Until (Wakeup_Time : Time_Ms) is
begin
while Wakeup_Time > Clock loop
Asm (Template => "wfi", -- Wait for interrupt
Volatile => True);
end loop;
end Delay_Until;
-----------------
-- Tick_Period --
-----------------
function Tick_Period return Time_Ms is
begin
return Period_Ms;
end Tick_Period;
---------------------
-- Tick_Subscriber --
---------------------
function Tick_Subscriber (Callback : not null Tick_Callback) return Boolean
is
begin
for Subs of Subscribers loop
if Subs = Callback then
return True;
end if;
end loop;
return False;
end Tick_Subscriber;
--------------------
-- Tick_Subscribe --
--------------------
function Tick_Subscribe (Callback : not null Tick_Callback) return Boolean
is
begin
for Subs of Subscribers loop
if Subs = null then
Subs := Callback;
return True;
end if;
end loop;
return False;
end Tick_Subscribe;
----------------------
-- Tick_Unsubscribe --
----------------------
function Tick_Unsubscribe (Callback : not null Tick_Callback) return Boolean
is
begin
for Subs of Subscribers loop
if Subs = Callback then
Subs := null;
return True;
end if;
end loop;
return False;
end Tick_Unsubscribe;
---------------
-- HAL_Delay --
---------------
Delay_Instance : aliased PG_Delays;
function HAL_Delay return not null HAL.Time.Any_Delays is
begin
return Delay_Instance'Access;
end HAL_Delay;
------------------------
-- Delay_Microseconds --
------------------------
overriding
procedure Delay_Microseconds
(This : in out PG_Delays;
Us : Integer)
is
pragma Unreferenced (This);
begin
Delay_Ms (UInt64 (Us / 1000));
end Delay_Microseconds;
------------------------
-- Delay_Milliseconds --
------------------------
overriding
procedure Delay_Milliseconds
(This : in out PG_Delays;
Ms : Integer)
is
pragma Unreferenced (This);
begin
Delay_Ms (UInt64 (Ms));
end Delay_Milliseconds;
-------------------
-- Delay_Seconds --
-------------------
overriding
procedure Delay_Seconds (This : in out PG_Delays;
S : Integer)
is
pragma Unreferenced (This);
begin
Delay_Ms (UInt64 (S * 1000));
end Delay_Seconds;
begin
Initialize;
end PyGamer.Time;
|
-- Ada_GUI implementation based on Gnoga. Adapted 2021
-- --
-- GNOGA - The GNU Omnificent GUI for Ada --
-- --
-- G N O G A . G U I . B A S E --
-- --
-- S p e c --
-- --
-- --
-- Copyright (C) 2014 David Botton --
-- --
-- This library is free software; you can redistribute it and/or modify --
-- it under terms of the GNU General Public License as published by the --
-- Free Software Foundation; either version 3, or (at your option) any --
-- later version. This library is distributed in the hope that it will be --
-- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of --
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are --
-- granted additional permissions described in the GCC Runtime Library --
-- Exception, version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
-- For more information please go to http://www.gnoga.com --
------------------------------------------------------------------------------
with Ada.Finalization;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Hashed_Maps;
with Ada.Containers.Synchronized_Queue_Interfaces;
with Ada.Containers.Unbounded_Synchronized_Queues;
with Ada.Strings.Hash;
package Ada_GUI.Gnoga.Gui is
-------------------------------------------------------------------------
-- Base_Type
-------------------------------------------------------------------------
type Base_Type is new Ada.Finalization.Limited_Controlled with private;
type Base_Access is access all Base_Type;
type Pointer_To_Base_Class is access all Base_Type'Class;
-- Base_Type is the parent class of all Gnoga GUI Objects.
-- It is generally used internally to create and bind Gnoga objects to
-- HTML5 DOM objects.
Object_Already_Created : exception;
-- Raised when an attempt is made to perform a create method on an already
-- created or attached Gnoga object.
Object_Was_Not_Created : exception;
-- Raised when an attempt was made to use an object that has not yet been
-- created on the client.
overriding
procedure Initialize (Object : in out Base_Type);
overriding
procedure Finalize (Object : in out Base_Type);
procedure Free (Object : in out Base_Type);
-- Free a dynamically created Object
package Base_Type_Arrays is
new Ada.Containers.Vectors
(Index_Type => Positive,
Element_Type => Pointer_To_Base_Class,
"=" => "=");
package Base_Type_Maps is
new Ada.Containers.Indefinite_Hashed_Maps (String,
Pointer_To_Base_Class,
Ada.Strings.Hash,
Equivalent_Keys => "=");
subtype Base_Type_Array is Base_Type_Arrays.Vector;
-- Arrays of Base_Types
subtype Base_Type_Map is Base_Type_Maps.Map;
-- String to Base_Type associative array
-------------------------------------------------------------------------
-- Base_Type - Creation Methods
-------------------------------------------------------------------------
procedure Create_With_Script
(Object : in out Base_Type;
Connection_ID : in Gnoga.Connection_ID;
ID : in String;
Script : in String;
ID_Type : in ID_Enumeration := DOM_ID);
-- Create a Gnoga object on Connection ID with ID using Script.
-- The Script must include creating the id attribute equal to ID.
-- Script is eval'd JavaScript.
-- Note ID _must_ be unique for use in Gnoga.
procedure Attach_Using_Parent
(Object : in out Base_Type;
Parent : in Base_Type'Class;
ID : in String;
ID_Type : in ID_Enumeration := DOM_ID);
-- Attach a Gnoga object using Connection ID from Parent to an existing
-- DOM object with ID. On_Create event is not fired.
-- Note ID _must_ be unique for use in Gnoga.
procedure Attach
(Object : in out Base_Type;
Connection_ID : in Gnoga.Connection_ID;
ID : in String;
ID_Type : in ID_Enumeration := DOM_ID);
-- Attache a Gnoga object on Connection ID to an existing DOM object
-- with ID. On_Create event is not fired.
-- Note ID _must_ be unique for use in Gnoga.
-------------------------------------------------------------------------
-- Base_Type - Properties
-------------------------------------------------------------------------
-- Object Properties --
-- For reference:
-- | Margin | Border | Padding | Scroll | [Element] | Scroll | Padding ...
procedure Height (Object : in out Base_Type; Value : in Integer);
function Height (Object : Base_Type) return Integer;
-- Height of Element, or Window or Document
-- Results in Pixels and numeric unlike using the CSS size properties
-- See Element_Type for additional Height and Width properties
procedure Width (Object : in out Base_Type; Value : in Integer);
function Width (Object : Base_Type) return Integer;
-- Width of Element, or Window or Document
-- Results in Pixels and numeric unlike using the CSS size properties
-- See Element_Type for additional Height and Width properties
-- Framework Properties --
function Unique_ID (Object : Base_Type) return Unique_ID;
-- Returns the Unique_ID for Object
function Connection_ID (Object : Base_Type)
return Gnoga.Connection_ID;
procedure Connection_ID (Object : in out Base_Type;
Value : in Gnoga.Connection_ID);
-- The Gnoga Connection ID of Object.
-- It is almost certainly always a mistake to set Connection_ID instead
-- of using Attach. Only change the Connection ID if you fully understand
-- what you are doing.
function Valid (Object : Base_Type) return Boolean;
-- Returns true if Connection_ID is valid, i.e. Object was created and
-- the connection is still valid.
function ID (Object : Base_Type) return String;
procedure ID (Object : in out Base_Type;
ID : in String;
ID_Type : in ID_Enumeration);
-- The ID for Object. Use Attach for attaching to existing objects in,
-- setting the ID should only be done with full understanding of the Gnoga
-- internals.
function ID_Type (Object : Base_Type) return ID_Enumeration;
-- Returns the type of ID stored for Object or No_ID if object has not
-- been created or attached on the client side.
function DOM_Selector (Object : Base_Type) return String;
-- Returns the DOM_ID for Object, "#" & Object.ID or ID_Type is Gnoga_ID or
-- DOM_ID otherwise returns ID.
function Connection_Data
(Object : Base_Type)
return Pointer_To_Connection_Data_Class;
-- Returns the connection specific Data for the connection Object is on.
-- This is usually set with Gnoga.Gui.Window.Connection_Data
function Parent (Object : Base_Type)
return Pointer_To_Base_Class;
procedure Parent (Object : in out Base_Type;
Value : in out Base_Type'Class);
procedure Parent (Object : in out Base_Type;
Value : in Pointer_To_Base_Class);
-- Parent of Object. Setting/changing the parent will fire the
-- On_Parent_Added event on the Parent object and if changing the parent
-- On_Parent_Removed event on the old Parent
--
-- Setting the parent Object does not change the position Object may have
-- in the DOM by default. That should be done using Element_Type.Place_*
procedure Dynamic (Object : in out Base_Type; Value : Boolean := True);
function Dynamic (Object : Base_Type) return Boolean;
-- Can be used to mark an object as dynamically allocated instead of
-- on the stack. This in of itself does not do anything, but Views
-- will deallocate on finalization children that are marked as Dynamic
-- _before_ being Created with the View as parent.
-- See Gnoga.Gui.View
-- If you plan on deallocating a child element in your code, do not mark it
-- as Dynamic. Marking Dynamic is for the purpose of automatic garbage
-- collection by Gnoga's framework.
function Buffer_Connection (Object : Base_Type) return Boolean;
procedure Buffer_Connection (Object : in out Base_Type;
Value : in Boolean := True);
-- Set buffering all output to browser on connection used by Object.
-- Generic Access --
procedure Property (Object : in out Base_Type;
Name : in String;
Value : in String);
function Property (Object : Base_Type; Name : String) return String;
-- General access to property Name as a String
procedure Property (Object : in out Base_Type;
Name : in String;
Value : in Integer);
function Property (Object : Base_Type; Name : String) return Integer;
-- General access to property Name as an Integer
-- If Property returns a float value it will be converted in to an
-- Integer.
procedure Property (Object : in out Base_Type;
Name : in String;
Value : in Float);
function Property (Object : Base_Type; Name : String) return Float;
-- General access to property Name as a Float
procedure Property (Object : in out Base_Type;
Name : in String;
Value : in Boolean);
function Property (Object : Base_Type; Name : String) return Boolean;
-- General access to property Name as a Boolean
-------------------------------------------------------------------------
-- Base_Type - Methods
-------------------------------------------------------------------------
-- Object Methods --
procedure Focus (Object : in out Base_Type);
-- Set focus on Object
procedure Blur (Object : in out Base_Type);
-- Remove focus from Object
-- Framework Methods --
procedure Flush_Buffer (Object : in out Base_Type);
-- Flush buffer to browser on connection used by Object
-- Generic Methods --
procedure Execute (Object : in out Base_Type; Method : in String);
function Execute (Object : Base_Type; Method : in String) return String;
-- General access to execute a Method and access to a Method as a String
function Execute (Object : Base_Type; Method : String) return Integer;
-- General access to a Method as an Integer
-- If Method returns a float value it will be converted in to an
-- Integer.
function Execute (Object : Base_Type; Method : String) return Float;
-- General access to a Method as a Float
function Execute (Object : Base_Type; Method : String) return Boolean;
-- General access to a Method as a Boolean
-------------------------------------------------------------------------
-- Base_Type - Event Handlers
-------------------------------------------------------------------------
-- When an event handler is set on any event, binding code will be sent
-- to the browser automatically for Gnoga to start receiving notifications
-- of the event. In theory any event can be set on any object not all
-- will be fired by every object.
type Mouse_Message_Type is (Unknown, Click, Double_Click, Right_Click,
Mouse_Down, Mouse_Up, Mouse_Move);
type Mouse_Event_Record is
record
Message : Mouse_Message_Type := Unknown;
X : Integer;
Y : Integer;
Screen_X : Integer;
Screen_Y : Integer;
Left_Button : Boolean := False;
Middle_Button : Boolean := False;
Right_Button : Boolean := False;
Alt : Boolean := False;
Control : Boolean := False;
Shift : Boolean := False;
Meta : Boolean := False;
end record;
type Mouse_Event is access
procedure (Object : in out Base_Type'Class;
Mouse_Event : in Mouse_Event_Record);
type Keyboard_Message_Type is (Unknown, Key_Down, Key_Up, Key_Press);
type Keyboard_Event_Record is
record
Message : Keyboard_Message_Type := Unknown;
Key_Code : Integer;
Key_Char : Wide_Character;
Alt : Boolean := False;
Control : Boolean := False;
Shift : Boolean := False;
Meta : Boolean := False;
end record;
type Keyboard_Event is access
procedure (Object : in out Base_Type'Class;
Keyboard_Event : in Keyboard_Event_Record);
type Character_Event is access
procedure (Object : in out Base_Type'Class;
Key : in Character);
type Wide_Character_Event is access
procedure (Object : in out Base_Type'Class;
Key : in Wide_Character);
type Message_Event is access
procedure (Object : in out Base_Type'Class;
Event : in String;
Message : in String;
Continue : out Boolean);
type Child_Changed_Event is access
procedure (Object : in out Base_Type'Class;
Child : in out Base_Type'Class);
type Drop_Event is access
procedure (Object : in out Base_Type'Class;
X, Y : in Integer;
Drag_Text : in String);
-------------------------------------------------------------------------
-- Base_Type - Event Internals
-------------------------------------------------------------------------
-- Event binding is usually used internally during On_Create or
-- when setting a message handler. It can be used though to bind events
-- not bound by Gnoga or custom events.
procedure Bind_Event (Object : in out Base_Type;
Event : in String;
Message : in String;
Eval : in String := "";
Script : in String := "";
Cancel : in Boolean := False);
-- On Event occurring to Object Gnoga will fire Object.On_Message with
-- Event and Message, the result of Script is concatenated to Message.
--
-- Eval if set is JavaScript to be run before processing the
-- return message which is the result of ("Message|" + Script).
-- The Eval script has access to the event "e" and an optional event
-- parameter "data". The Eval script must be terminated with a ';' if
-- not a block statement.
--
-- If Cancel is true then JS will cancel the default behavior of Event
-- from occurring on browser. (e.g. stopping a form submit in onsubmit)
procedure Bind_Event_Script (Object : in out Base_Type;
Event : in String;
Script : in String);
-- On Event occurring to Object, the Script will be executed on browser.
procedure Unbind_Event (Object : in out Base_Type;
Event : in String);
-- Unbind an event.
procedure Attach_To_Message_Queue (Object : in out Base_Type);
-- Attach Object to Message Queue
procedure Detach_From_Message_Queue (Object : in out Base_Type);
-- Detach Object from Message Queue
function Script_Accessor (ID : String; ID_Type : ID_Enumeration)
return String;
-- General utility for calculating te Script Accessor of an ID based on
-- ID_Type
function Script_Accessor (Object : Base_Type) return String;
-- Returns the script representation for ID. For DOM_ID '#ID' for
-- Script 'ID'
function jQuery (Object : Base_Type) return String;
-- Returns the jQuery selector for Object
procedure jQuery_Execute (Object : in out Base_Type; Method : in String);
function jQuery_Execute (Object : Base_Type; Method : String) return String;
function jQuery_Execute (Object : Base_Type; Method : String)
return Integer;
function jQuery_Execute (Object : Base_Type; Method : String)
return Float;
-- Execute Method of jQuery wrapper object
type Event_Info is record
Event : Ada.Strings.Unbounded.Unbounded_String;
Object : Pointer_To_Base_Class;
Data : Ada.Strings.Unbounded.Unbounded_String;
end record;
package EQ_IF is new Ada.Containers.Synchronized_Queue_Interfaces (Element_Type => Event_Info);
package Event_Queues is new Ada.Containers.Unbounded_Synchronized_Queues (Queue_Interfaces => EQ_IF);
Event_Queue : Event_Queues.Queue;
-------------------------------------------------------------------------
-- Base_Type - Event Methods
-------------------------------------------------------------------------
-- When overriding events, to ensure that the event handlers will still
-- be executed and internal functionality of the event is handled
-- properly, always call the base class event method.
--
-- Event Methods are always bound on creation of Gnoga object or do not
-- require event binding.
-- For Ada GUI, these are null, but are overridden by some descendant types
procedure On_Resize (Object : in out Base_Type) is null;
-- Called by all sizing methods to inform Object it has changed size.
procedure On_Child_Added (Object : in out Base_Type;
Child : in out Base_Type'Class)
is null;
-- Called when a Child is created claiming Object as its parent.
private
type Base_Type is new Ada.Finalization.Limited_Controlled with record
Unique_ID : Gnoga.Unique_ID := No_Unique_ID;
Web_ID : Gnoga.Web_ID;
ID_Type : ID_Enumeration := No_ID;
Connection_ID : Gnoga.Connection_ID := No_Connection;
Parent_Object : Pointer_To_Base_Class := null;
Is_Dynamic : Boolean := False;
In_Resize : Boolean := False;
end record;
end Ada_GUI.Gnoga.Gui;
|
-- Abstract :
--
-- See spec.
--
-- Copyright (C) 2017, 2019 Free Software Foundation All Rights Reserved.
--
-- This library is free software; you can redistribute it and/or modify it
-- under terms of the GNU General Public License as published by the Free
-- Software Foundation; either version 3, or (at your option) any later
-- version. This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN-
-- TABILITY or FITNESS FOR A PARTICULAR PURPOSE.
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with SAL.Gen_Bounded_Definite_Queues;
with SAL.Gen_Unbounded_Definite_Stacks;
package body SAL.Gen_Graphs is
package Vertex_Queues is new SAL.Gen_Bounded_Definite_Queues (Vertex_Index);
package Vertex_Stacks is new SAL.Gen_Unbounded_Definite_Stacks (Vertex_Index);
function Find (Data : in Edge_Data; List : in Edge_Node_Lists.List) return Edge_Node_Lists.Cursor
is begin
for I in List.Iterate loop
if Edge_Node_Lists.Element (I).Data = Data then
return I;
end if;
end loop;
return Edge_Node_Lists.No_Element;
end Find;
----------
-- Visible subprograms
procedure Add_Edge
(Graph : in out Gen_Graphs.Graph;
Vertex_A : in Vertex_Index;
Vertex_B : in Vertex_Index;
Data : in Edge_Data)
is
Multigraph : Boolean := False;
procedure Update_First_Last (Vertex : in Vertex_Index)
is
use all type Ada.Containers.Count_Type;
begin
if Graph.Vertices.Length = 0 then
Graph.Vertices.Set_First_Last (Vertex, Vertex);
else
if Vertex < Graph.Vertices.First_Index then
Graph.Vertices.Set_First (Vertex);
end if;
if Vertex > Graph.Vertices.Last_Index then
Graph.Vertices.Set_Last (Vertex);
end if;
end if;
end Update_First_Last;
begin
Update_First_Last (Vertex_A);
Update_First_Last (Vertex_B);
Graph.Last_Edge_ID := Graph.Last_Edge_ID + 1;
if (for some E of Graph.Vertices (Vertex_A) => E.Vertex_B = Vertex_B) then
Multigraph := True;
Graph.Multigraph := True;
end if;
Graph.Vertices (Vertex_A).Append ((Graph.Last_Edge_ID, Vertex_B, Multigraph, Data));
end Add_Edge;
function Count_Nodes (Graph : in Gen_Graphs.Graph) return Ada.Containers.Count_Type
is begin
return Graph.Vertices.Length;
end Count_Nodes;
function Count_Edges (Graph : in Gen_Graphs.Graph) return Ada.Containers.Count_Type
is
use Ada.Containers;
Result : Count_Type := 0;
begin
for Edges of Graph.Vertices loop
Result := Result + Edges.Length;
end loop;
return Result;
end Count_Edges;
function Multigraph (Graph : in Gen_Graphs.Graph) return Boolean
is begin
return Graph.Multigraph;
end Multigraph;
function "+" (Right : in Edge_Item) return Edge_Lists.List
is
use Edge_Lists;
begin
return Result : List do
Append (Result, Right);
end return;
end "+";
function Edges (Graph : in Gen_Graphs.Graph; Vertex : in Vertex_Index) return Edge_Lists.List
is begin
return Result : Edge_Lists.List do
for E of Graph.Vertices (Vertex) loop
Result.Append ((E.ID, E.Data));
end loop;
end return;
end Edges;
function Image (Item : in Path) return String
is
use Ada.Strings.Unbounded;
Result : Unbounded_String := To_Unbounded_String ("(");
begin
for I in Item'Range loop
Result := Result & Trimmed_Image (Item (I).Vertex) & " " &
Image ((if I = Item'Last then Item (Item'First).Edges else Item (I + 1).Edges)) & " -> ";
end loop;
Result := Result & ")";
return To_String (Result);
end Image;
function "<" (Left, Right : in Path) return Boolean
is begin
for I in Left'Range loop
if I > Right'Last then
return False;
elsif Left (I).Vertex < Right (I).Vertex then
return True;
elsif Left (I).Vertex > Right (I).Vertex then
return False;
else
-- =; check remaining elements
null;
end if;
end loop;
if Left'Last < Right'Last then
return True;
else
-- All =
return False;
end if;
end "<";
function Find_Paths
(Graph : in out Gen_Graphs.Graph;
From : in Vertex_Index;
To : in Edge_Data)
return Path_Arrays.Vector
is
Vertex_Queue : Vertex_Queues.Queue_Type
(Size => Integer (Graph.Vertices.Last_Index - Graph.Vertices.First_Index + 1));
type Colors is (White, Gray, Black);
type Aux_Node is record
Color : Colors := Colors'First;
D : Natural := Natural'Last;
Parent : Vertex_Index'Base := Invalid_Vertex;
Parent_Set : Boolean := False;
Parent_Edge : Edge_Node_Lists.Cursor := Edge_Node_Lists.No_Element;
end record;
package Aux_Arrays is new SAL.Gen_Unbounded_Definite_Vectors (Vertex_Index, Aux_Node, (others => <>));
Aux : Aux_Arrays.Vector;
function Build_Path
(Tail_Vertex : in Vertex_Index;
Tail_Edge : in Edge_Node_Lists.Cursor)
return Path
is
begin
return Result : Path (1 .. Aux (Tail_Vertex).D + 1)
do
declare
use Edge_Node_Lists;
V_Index : Vertex_Index := Tail_Vertex;
Last_Edge : Cursor := Tail_Edge;
begin
for I in reverse 1 .. Result'Length loop
declare
V : Aux_Node renames Aux (V_Index);
begin
if Last_Edge = No_Element then
Result (I) := (V_Index, Edge_Lists.Empty_List);
else
Result (I) := (V_Index, +(Element (Last_Edge).ID, Element (Last_Edge).Data));
end if;
if V.Parent_Set then
Last_Edge := V.Parent_Edge;
V_Index := V.Parent;
end if;
end;
end loop;
end;
end return;
end Build_Path;
Result_List : Path_Arrays.Vector;
Result_Edge : Edge_Node_Lists.Cursor;
begin
-- [1] figure 22.3 breadth-first search; 'From' = s.
Aux.Set_First_Last (Graph.Vertices.First_Index, Graph.Vertices.Last_Index);
for I in Aux.First_Index .. Aux.Last_Index loop
if I = From then
Aux (I).Color := Gray;
Aux (I).D := 0;
Aux (I).Parent_Set := False;
else
Aux (I).Color := White;
Aux (I).D := Natural'Last;
Aux (I).Parent_Set := False;
end if;
end loop;
Vertex_Queue.Put (From);
while not Vertex_Queue.Is_Empty loop
declare
U_Index : constant Vertex_Index := Vertex_Queue.Get;
U : Aux_Node renames Aux (U_Index);
begin
Edges :
for C in Graph.Vertices (U_Index).Iterate loop
declare
use all type Edge_Node_Lists.Cursor;
V_Index : constant Vertex_Index := Edge_Node_Lists.Element (C).Vertex_B;
V : Aux_Node renames Aux (V_Index);
begin
if V.Color = White then
V.Color := Gray;
V.D := U.D + 1;
V.Parent := U_Index;
V.Parent_Edge := C;
V.Parent_Set := True;
Result_Edge := Find (To, Graph.Vertices (V_Index));
if Result_Edge /= Edge_Node_Lists.No_Element then
Result_List.Append (Build_Path (V_Index, Result_Edge));
end if;
Vertex_Queue.Put (V_Index);
end if;
end;
end loop Edges;
U.Color := Black;
end;
end loop;
return Result_List;
end Find_Paths;
function Find_Cycles_Tiernan (Graph : in Gen_Graphs.Graph)
return Path_Arrays.Vector
is
-- Implements [2] "Algorithm EC"
--
-- vertex 0 = Invalid_Vertex
-- vertex 1 = Graph.Vertices.First_Index
-- vertex N = Graph.Vertices.Last_Index
First : Vertex_Index renames Graph.Vertices.First_Index;
Last : Vertex_Index renames Graph.Vertices.Last_Index;
G : Vertex_Arrays.Vector renames Graph.Vertices;
P : Path (1 .. Integer (Last - First + 1));
K : Positive := 1; -- ie P_Last
type H_Row is array (G.First_Index .. G.Last_Index) of Vertex_Index'Base;
H : array (G.First_Index .. G.Last_Index) of H_Row := (others => (others => Invalid_Vertex));
Next_Vertex_Found : Boolean;
Result : Path_Arrays.Vector;
function Contains (P : in Path; V : in Vertex_Index) return Boolean
is (for some N of P => N.Vertex = V);
function Contains (Row : in H_Row; V : in Vertex_Index) return Boolean
is (for some N of Row => N = V);
function Contains (Edges : in Edge_Lists.List; ID : in Edge_ID) return Boolean
is (for some E of Edges => E.ID = ID);
procedure Add_Alternate_Edges (P : in out Path)
is
function Dec (I : in Positive) return Positive
is (if I = P'First then P'Last else I - 1);
begin
for I in P'Range loop
for New_Edge of G (P (Dec (I)).Vertex) loop
if New_Edge.Vertex_B = P (I).Vertex and (not Contains (P (I).Edges, New_Edge.ID)) then
P (I).Edges.Append ((New_Edge.ID, New_Edge.Data));
end if;
end loop;
end loop;
end Add_Alternate_Edges;
begin
P (1) := (First, Edge_Lists.Empty_List);
All_Initial_Vertices :
loop
Explore_Vertex :
loop
Path_Extension :
loop -- EC2 Path Extension
Next_Vertex_Found := False;
Find_Next_Vertex :
for Edge of G (P (K).Vertex) loop
declare
Next_Vertex : constant Vertex_Index := Edge.Vertex_B; -- ie G[P[k],j]
begin
if Next_Vertex > P (1).Vertex and -- (1)
(not Contains (P, Next_Vertex)) and -- (2)
(not Contains (H (P (K).Vertex), Next_Vertex))
then
K := K + 1;
P (K) := (Next_Vertex, +(Edge.ID, Edge.Data));
Next_Vertex_Found := True;
exit Find_Next_Vertex;
end if;
end;
end loop Find_Next_Vertex;
exit Path_Extension when not Next_Vertex_Found;
end loop Path_Extension;
-- EC3 Circuit Confirmation
for Edge of G (P (K).Vertex) loop
if Edge.Vertex_B = P (1).Vertex then
P (1).Edges := +(Edge.ID, Edge.Data);
if Graph.Multigraph then
Add_Alternate_Edges (P (1 .. K));
end if;
Result.Append (P (1 .. K));
exit;
end if;
end loop;
-- EC4 Vertex Closure
exit Explore_Vertex when K = 1;
H (P (K).Vertex) := (others => Invalid_Vertex);
for M in H (P (K - 1).Vertex)'Range loop
if H (P (K - 1).Vertex)(M) = Invalid_Vertex then
H (P (K - 1).Vertex)(M) := P (K).Vertex;
P (K) := (Invalid_Vertex, Edge_Lists.Empty_List);
exit;
end if;
end loop;
K := K - 1;
end loop Explore_Vertex;
-- EC5 Advance Initial Index
exit All_Initial_Vertices when P (1).Vertex = Graph.Vertices.Last_Index;
P (1) := (P (1).Vertex + 1, Edge_Lists.Empty_List);
pragma Assert (K = 1);
H := (others => (others => Invalid_Vertex));
end loop All_Initial_Vertices;
-- EC6 Terminate
return Result;
end Find_Cycles_Tiernan;
function Find_Cycles (Graph : in Gen_Graphs.Graph) return Path_Arrays.Vector
is
-- Implements Circuit-Finding Algorithm from [3]
use all type Ada.Containers.Count_Type;
pragma Warnings (Off, """Edited_Graph"" is not modified, could be declared constant");
Edited_Graph : Gen_Graphs.Graph := Graph;
Result : Path_Arrays.Vector;
A_K : Adjacency_Structures.Vector;
B : Adjacency_Structures.Vector;
Blocked : array (Graph.Vertices.First_Index .. Graph.Vertices.Last_Index) of Boolean := (others => False);
Stack : Vertex_Stacks.Stack;
S : Vertex_Index := Graph.Vertices.First_Index;
Dummy : Boolean;
pragma Unreferenced (Dummy);
function Circuit (V : in Vertex_Index) return Boolean
is
F : Boolean := False;
procedure Unblock (U : in Vertex_Index)
is begin
Blocked (U) := False;
declare
use Vertex_Lists;
Cur : Cursor := B (U).First;
Temp : Cursor;
W : Vertex_Index;
begin
loop
exit when not Has_Element (Cur);
W := Element (Cur);
Temp := Cur;
Next (Cur);
B (U).Delete (Temp);
if Blocked (W) then
Unblock (W);
end if;
end loop;
end;
end Unblock;
procedure Add_Result
is
Cycle : Path (1 .. Integer (Stack.Depth));
begin
for I in 1 .. Stack.Depth loop
Cycle (Integer (Stack.Depth - I + 1)) := (Stack.Peek (I), Edge_Lists.Empty_List);
-- We add the edge info later, after finding all the cycles.
end loop;
Result.Append (Cycle);
if Trace > 0 then
Ada.Text_IO.Put_Line ("cycle " & Image (Cycle));
end if;
end Add_Result;
begin
if Trace > 0 then
Ada.Text_IO.Put_Line ("circuit start" & V'Image);
end if;
Stack.Push (V);
Blocked (V) := True;
if V in A_K.First_Index .. A_K.Last_Index then
for W of A_K (V) loop
if W = S then
Add_Result;
F := True;
elsif not Blocked (W) then
if Circuit (W) then
F := True;
end if;
end if;
end loop;
end if;
if F then
Unblock (V);
else
if V in A_K.First_Index .. A_K.Last_Index then
for W of A_K (V) loop
if (for all V1 of B (W) => V /= V1) then
B (W).Append (V);
end if;
end loop;
end if;
end if;
Stack.Pop;
if Trace > 0 then
Ada.Text_IO.Put_Line ("circuit finish" & V'Image);
end if;
return F;
end Circuit;
begin
-- [3] restricts the graph to not have loops (edge v-v) or multiple
-- edges between two nodes. So we first delete any such edges.
Delete_Loops_Multigraph :
for V in Edited_Graph.Vertices.First_Index .. Edited_Graph.Vertices.Last_Index loop
declare
use Edge_Node_Lists;
Cur : Cursor := Edited_Graph.Vertices (V).First;
Temp : Cursor;
Found_Loop : Boolean := False;
begin
loop
exit when not Has_Element (Cur);
if Element (Cur).Vertex_B = V then
if not Found_Loop then
-- This is a cycle we want in the result. Edge data is added to all
-- cycles later.
Result.Append (Path'(1 => (V, Edge_Lists.Empty_List)));
Found_Loop := True;
end if;
Temp := Cur;
Next (Cur);
Edited_Graph.Vertices (V).Delete (Temp);
elsif Element (Cur).Multigraph then
-- These will be added back from Graph after we find all cycles.
Temp := Cur;
Next (Cur);
Edited_Graph.Vertices (V).Delete (Temp);
else
Next (Cur);
end if;
end loop;
end;
end loop Delete_Loops_Multigraph;
B.Set_First_Last (Graph.Vertices.First_Index, Graph.Vertices.Last_Index);
-- Start of body of Circuit-Finding Algorithm from [3]
loop
exit when S = Graph.Vertices.Last_Index;
declare
use Component_Lists;
Subgraph : Adjacency_Structures.Vector;
Components : Component_Lists.List;
Cur : Component_Lists.Cursor;
Least_Vertex_Cur : Component_Lists.Cursor;
Least_Vertex_V : Vertex_Index := Vertex_Index'Last;
function Delete_Edges (Edges : in Edge_Node_Lists.List) return Vertex_Lists.List
is begin
return Result : Vertex_Lists.List do
for Edge of Edges loop
if Edge.Vertex_B >= S then
Result.Append (Edge.Vertex_B);
end if;
end loop;
end return;
end Delete_Edges;
begin
Subgraph.Set_First_Last (S, Edited_Graph.Vertices.Last_Index);
for V in S .. Edited_Graph.Vertices.Last_Index loop
Subgraph (V) := Delete_Edges (Edited_Graph.Vertices (V));
end loop;
Components := Strongly_Connected_Components (Subgraph, Non_Trivial_Only => True);
Cur := Components.First;
loop
exit when not Has_Element (Cur);
if Element (Cur).Length > 1 then
declare
Comp : Vertex_Lists.List renames Components.Constant_Reference (Cur);
begin
for W of Comp loop
if W < Least_Vertex_V then
Least_Vertex_Cur := Cur;
Least_Vertex_V := W;
end if;
end loop;
end;
end if;
Next (Cur);
end loop;
A_K.Clear;
if Has_Element (Least_Vertex_Cur) then
declare
Component : Vertex_Lists.List renames Components (Least_Vertex_Cur);
Min : Vertex_Index := Vertex_Index'Last;
Max : Vertex_Index := Vertex_Index'First;
begin
if Trace > 0 then
Ada.Text_IO.Put_Line ("strong component " & Least_Vertex_V'Image);
Ada.Text_IO.Put_Line (Image (Component));
end if;
for V of Component loop
if Min > V then
Min := V;
end if;
if Max < V then
Max := V;
end if;
end loop;
A_K.Set_First_Last (Min, Max);
for V of Component loop
for Edge of Edited_Graph.Vertices (V) loop
A_K (V).Append (Edge.Vertex_B);
end loop;
end loop;
end;
end if;
end;
if A_K.Length > 0 then
S := A_K.First_Index;
for I in A_K.First_Index .. A_K.Last_Index loop
Blocked (I) := False;
B (I).Clear;
end loop;
Dummy := Circuit (S);
S := S + 1;
else
S := Graph.Vertices.Last_Index;
end if;
end loop;
-- Add edge data.
for Cycle of Result loop
for I in Cycle'First .. Cycle'Last loop
declare
Prev_I : constant Positive := (if I = Cycle'First then Cycle'Last else I - 1);
begin
for Edge of Graph.Vertices (Cycle (Prev_I).Vertex) loop
if Cycle (I).Vertex = Edge.Vertex_B then
Cycle (I).Edges.Append ((Edge.ID, Edge.Data));
end if;
end loop;
end;
end loop;
end loop;
return Result;
end Find_Cycles;
function Loops (Graph : in Gen_Graphs.Graph) return Vertex_Lists.List
is begin
return Result : Vertex_Lists.List do
for V in Graph.Vertices.First_Index .. Graph.Vertices.Last_Index loop
for Edge of Graph.Vertices (V) loop
if V = Edge.Vertex_B then
Result.Append (V);
exit;
end if;
end loop;
end loop;
end return;
end Loops;
function To_Adjancency (Graph : in Gen_Graphs.Graph) return Adjacency_Structures.Vector
is
function To_Vertex_List (Edges : in Edge_Node_Lists.List) return Vertex_Lists.List
is begin
return Result : Vertex_Lists.List do
for Edge of Edges loop
Result.Append (Edge.Vertex_B);
end loop;
end return;
end To_Vertex_List;
begin
return Result : Adjacency_Structures.Vector do
Result.Set_First_Last (Graph.Vertices.First_Index, Graph.Vertices.Last_Index);
for V in Graph.Vertices.First_Index .. Graph.Vertices.Last_Index loop
Result (V) := To_Vertex_List (Graph.Vertices (V));
end loop;
end return;
end To_Adjancency;
function Strongly_Connected_Components
(Graph : in Adjacency_Structures.Vector;
Non_Trivial_Only : in Boolean := False)
return Component_Lists.List
is
-- Implements [4] section 4.
Low_Link : array (Graph.First_Index .. Graph.Last_Index) of Vertex_Index'Base := (others => Invalid_Vertex);
Number : array (Graph.First_Index .. Graph.Last_Index) of Vertex_Index'Base := (others => Invalid_Vertex);
-- Number is the order visited in the depth-first search.
Points : Vertex_Stacks.Stack;
I : Vertex_Index'Base := Graph.First_Index - 1;
Result : Component_Lists.List;
procedure Strong_Connect (V : in Vertex_Index)
is begin
I := I + 1;
Number (V) := I;
Low_Link (V) := I;
Points.Push (V);
for W of Graph (V) loop
if Number (W) = Invalid_Vertex then
-- (v, w) is a tree arc
Strong_Connect (W);
Low_Link (V) := Vertex_Index'Min (Low_Link (V), Low_Link (W));
elsif Number (W) < Number (V) then
-- (v, w) is a frond or cross-link
if (for some P of Points => P = W) then
Low_Link (V) := Vertex_Index'Min (Low_Link (V), Low_Link (W));
end if;
end if;
end loop;
if Low_Link (V) = Number (V) then
-- v is the root of a component
declare
use all type Ada.Containers.Count_Type;
Component : Vertex_Lists.List;
begin
while (not Points.Is_Empty) and then Number (Points.Peek) >= Number (V) loop
Component.Append (Points.Pop);
end loop;
if (not Non_Trivial_Only) or Component.Length > 1 then
Result.Append (Component);
end if;
end;
end if;
end Strong_Connect;
begin
for W in Graph.First_Index .. Graph.Last_Index loop
if Number (W) = Invalid_Vertex then
Strong_Connect (W);
end if;
end loop;
return Result;
end Strongly_Connected_Components;
end SAL.Gen_Graphs;
|
-- { dg-do compile }
-- { dg-options "-O -fdump-tree-optimized" }
procedure Opt52 (I : Integer) is
begin
if I + 1 < I then
raise Program_Error;
end if;
end;
-- { dg-final { scan-tree-dump-not "check_PE_Explicit_Raise" "optimized" } }
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- B I N D G E N --
-- --
-- B o d y --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992-2002 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with ALI; use ALI;
with Binde; use Binde;
with Butil; use Butil;
with Casing; use Casing;
with Fname; use Fname;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with Gnatvsn; use Gnatvsn;
with Hostparm;
with Namet; use Namet;
with Opt; use Opt;
with Osint; use Osint;
with Output; use Output;
with Types; use Types;
with Sdefault; use Sdefault;
with System; use System;
with GNAT.Heap_Sort_A; use GNAT.Heap_Sort_A;
package body Bindgen is
Statement_Buffer : String (1 .. 1000);
-- Buffer used for constructing output statements
Last : Natural := 0;
-- Last location in Statement_Buffer currently set
With_DECGNAT : Boolean := False;
-- Flag which indicates whether the program uses the DECGNAT library
-- (presence of the unit System.Aux_DEC.DECLIB)
With_GNARL : Boolean := False;
-- Flag which indicates whether the program uses the GNARL library
-- (presence of the unit System.OS_Interface)
Num_Elab_Calls : Nat := 0;
-- Number of generated calls to elaboration routines
subtype chars_ptr is Address;
-----------------------
-- Local Subprograms --
-----------------------
procedure WBI (Info : String) renames Osint.Write_Binder_Info;
-- Convenient shorthand used throughout
function ABE_Boolean_Required (U : Unit_Id) return Boolean;
-- Given a unit id value U, determines if the corresponding unit requires
-- an access-before-elaboration check variable, i.e. it is a non-predefined
-- body for which no pragma Elaborate, Elaborate_All or Elaborate_Body is
-- present, and thus could require ABE checks.
procedure Resolve_Binder_Options;
-- Set the value of With_GNARL and With_DECGNAT. The latter only on VMS
-- since it tests for a package named "dec" which might cause a conflict
-- on non-VMS systems.
procedure Gen_Adainit_Ada;
-- Generates the Adainit procedure (Ada code case)
procedure Gen_Adainit_C;
-- Generates the Adainit procedure (C code case)
procedure Gen_Adafinal_Ada;
-- Generate the Adafinal procedure (Ada code case)
procedure Gen_Adafinal_C;
-- Generate the Adafinal procedure (C code case)
procedure Gen_Elab_Calls_Ada;
-- Generate sequence of elaboration calls (Ada code case)
procedure Gen_Elab_Calls_C;
-- Generate sequence of elaboration calls (C code case)
procedure Gen_Elab_Order_Ada;
-- Generate comments showing elaboration order chosen (Ada case)
procedure Gen_Elab_Order_C;
-- Generate comments showing elaboration order chosen (C case)
procedure Gen_Elab_Defs_C;
-- Generate sequence of definitions for elaboration routines (C code case)
procedure Gen_Exception_Table_Ada;
-- Generate binder exception table (Ada code case). This consists of
-- declarations followed by a begin followed by a call. If zero cost
-- exceptions are not active, then only the begin is generated.
procedure Gen_Exception_Table_C;
-- Generate binder exception table (C code case). This has no effect
-- if zero cost exceptions are not active, otherwise it generates a
-- set of declarations followed by a call.
procedure Gen_Main_Ada;
-- Generate procedure main (Ada code case)
procedure Gen_Main_C;
-- Generate main() procedure (C code case)
procedure Gen_Object_Files_Options;
-- Output comments containing a list of the full names of the object
-- files to be linked and the list of linker options supplied by
-- Linker_Options pragmas in the source. (C and Ada code case)
procedure Gen_Output_File_Ada (Filename : String);
-- Generate output file (Ada code case)
procedure Gen_Output_File_C (Filename : String);
-- Generate output file (C code case)
procedure Gen_Scalar_Values;
-- Generates scalar initialization values for -Snn. A single procedure
-- handles both the Ada and C cases, since there is much common code.
procedure Gen_Versions_Ada;
-- Output series of definitions for unit versions (Ada code case)
procedure Gen_Versions_C;
-- Output series of definitions for unit versions (C code case)
function Get_Ada_Main_Name return String;
-- This function is used in the Ada main output case to compute a usable
-- name for the generated main program. The normal main program name is
-- Ada_Main, but this won't work if the user has a unit with this name.
-- This function tries Ada_Main first, and if there is such a clash, then
-- it tries Ada_Name_01, Ada_Name_02 ... Ada_Name_99 in sequence.
function Get_Main_Name return String;
-- This function is used in the Ada main output case to compute the
-- correct external main program. It is "main" by default, except on
-- VxWorks where it is the name of the Ada main name without the "_ada".
-- the -Mname binder option overrides the default with name.
function Lt_Linker_Option (Op1, Op2 : Natural) return Boolean;
-- Compare linker options, when sorting, first according to
-- Is_Internal_File (internal files come later) and then by elaboration
-- order position (latest to earliest) except its not possible to
-- distinguish between a linker option in the spec and one in the body.
procedure Move_Linker_Option (From : Natural; To : Natural);
-- Move routine for sorting linker options
procedure Set_Char (C : Character);
-- Set given character in Statement_Buffer at the Last + 1 position
-- and increment Last by one to reflect the stored character.
procedure Set_Int (N : Int);
-- Set given value in decimal in Statement_Buffer with no spaces
-- starting at the Last + 1 position, and updating Last past the value.
-- A minus sign is output for a negative value.
procedure Set_Main_Program_Name;
-- Given the main program name in Name_Buffer (length in Name_Len)
-- generate the name of the routine to be used in the call. The name
-- is generated starting at Last + 1, and Last is updated past it.
procedure Set_Name_Buffer;
-- Set the value stored in positions 1 .. Name_Len of the Name_Buffer.
procedure Set_String (S : String);
-- Sets characters of given string in Statement_Buffer, starting at the
-- Last + 1 position, and updating last past the string value.
procedure Set_Unit_Name;
-- Given a unit name in the Name_Buffer, copies it to Statement_Buffer,
-- starting at the Last + 1 position, and updating last past the value.
-- changing periods to double underscores, and updating Last appropriately.
procedure Set_Unit_Number (U : Unit_Id);
-- Sets unit number (first unit is 1, leading zeroes output to line
-- up all output unit numbers nicely as required by the value, and
-- by the total number of units.
procedure Tab_To (N : Natural);
-- If Last is greater than or equal to N, no effect, otherwise store
-- blanks in Statement_Buffer bumping Last, until Last = N.
function Value (chars : chars_ptr) return String;
-- Return C NUL-terminated string at chars as an Ada string
procedure Write_Info_Ada_C (Ada : String; C : String; Common : String);
-- For C code case, write C & Common, for Ada case write Ada & Common
-- to current binder output file using Write_Binder_Info.
procedure Write_Statement_Buffer;
-- Write out contents of statement buffer up to Last, and reset Last to 0
procedure Write_Statement_Buffer (S : String);
-- First writes its argument (using Set_String (S)), then writes out the
-- contents of statement buffer up to Last, and reset Last to 0
--------------------------
-- ABE_Boolean_Required --
--------------------------
function ABE_Boolean_Required (U : Unit_Id) return Boolean is
Typ : constant Unit_Type := Units.Table (U).Utype;
Unit : Unit_Id;
begin
if Typ /= Is_Body then
return False;
else
Unit := U + 1;
return (not Units.Table (Unit).Pure)
and then
(not Units.Table (Unit).Preelab)
and then
(not Units.Table (Unit).Elaborate_Body)
and then
(not Units.Table (Unit).Predefined);
end if;
end ABE_Boolean_Required;
----------------------
-- Gen_Adafinal_Ada --
----------------------
procedure Gen_Adafinal_Ada is
begin
WBI ("");
WBI (" procedure " & Ada_Final_Name.all & " is");
WBI (" begin");
-- If compiling for the JVM, we directly call Adafinal because
-- we don't import it via Do_Finalize (see Gen_Output_File_Ada).
if Hostparm.Java_VM then
WBI (" System.Standard_Library.Adafinal;");
else
WBI (" Do_Finalize;");
end if;
WBI (" end " & Ada_Final_Name.all & ";");
end Gen_Adafinal_Ada;
--------------------
-- Gen_Adafinal_C --
--------------------
procedure Gen_Adafinal_C is
begin
WBI ("void " & Ada_Final_Name.all & " () {");
WBI (" system__standard_library__adafinal ();");
WBI ("}");
WBI ("");
end Gen_Adafinal_C;
---------------------
-- Gen_Adainit_Ada --
---------------------
procedure Gen_Adainit_Ada is
Main_Priority : Int renames ALIs.Table (ALIs.First).Main_Priority;
begin
WBI (" procedure " & Ada_Init_Name.all & " is");
-- Generate externals for elaboration entities
for E in Elab_Order.First .. Elab_Order.Last loop
declare
Unum : constant Unit_Id := Elab_Order.Table (E);
U : Unit_Record renames Units.Table (Unum);
begin
if U.Set_Elab_Entity then
Set_String (" ");
Set_String ("E");
Set_Unit_Number (Unum);
Set_String (" : Boolean; pragma Import (Ada, ");
Set_String ("E");
Set_Unit_Number (Unum);
Set_String (", """);
Get_Name_String (U.Uname);
-- In the case of JGNAT we need to emit an Import name
-- that includes the class name (using '$' separators
-- in the case of a child unit name).
if Hostparm.Java_VM then
for J in 1 .. Name_Len - 2 loop
if Name_Buffer (J) /= '.' then
Set_Char (Name_Buffer (J));
else
Set_String ("$");
end if;
end loop;
Set_String (".");
-- If the unit name is very long, then split the
-- Import link name across lines using "&" (occurs
-- in some C2 tests).
if 2 * Name_Len + 60 > Hostparm.Max_Line_Length then
Set_String (""" &");
Write_Statement_Buffer;
Set_String (" """);
end if;
end if;
Set_Unit_Name;
Set_String ("_E"");");
Write_Statement_Buffer;
end if;
end;
end loop;
Write_Statement_Buffer;
-- Normal case (not No_Run_Time mode). The global values are
-- assigned using the runtime routine Set_Globals (we have to use
-- the routine call, rather than define the globals in the binder
-- file to deal with cross-library calls in some systems.
if No_Run_Time_Specified then
-- Case of No_Run_Time mode. The only global variable that might
-- be needed (by the Ravenscar profile) is the priority of the
-- environment. Also no exception tables are needed.
if Main_Priority /= No_Main_Priority then
WBI (" Main_Priority : Integer;");
WBI (" pragma Import (C, Main_Priority," &
" ""__gl_main_priority"");");
WBI ("");
end if;
WBI (" begin");
if Main_Priority /= No_Main_Priority then
Set_String (" Main_Priority := ");
Set_Int (Main_Priority);
Set_Char (';');
Write_Statement_Buffer;
else
WBI (" null;");
end if;
else
WBI ("");
WBI (" procedure Set_Globals");
WBI (" (Main_Priority : Integer;");
WBI (" Time_Slice_Value : Integer;");
WBI (" WC_Encoding : Character;");
WBI (" Locking_Policy : Character;");
WBI (" Queuing_Policy : Character;");
WBI (" Task_Dispatching_Policy : Character;");
WBI (" Adafinal : System.Address;");
WBI (" Unreserve_All_Interrupts : Integer;");
WBI (" Exception_Tracebacks : Integer);");
WBI (" pragma Import (C, Set_Globals, ""__gnat_set_globals"");");
WBI ("");
-- Import entry point for elaboration time signal handler
-- installation, and indication of whether it's been called
-- previously
WBI ("");
WBI (" procedure Install_Handler;");
WBI (" pragma Import (C, Install_Handler, " &
"""__gnat_install_handler"");");
WBI ("");
WBI (" Handler_Installed : Integer;");
WBI (" pragma Import (C, Handler_Installed, " &
"""__gnat_handler_installed"");");
-- Generate exception table
Gen_Exception_Table_Ada;
-- Generate the call to Set_Globals
WBI (" Set_Globals");
Set_String (" (Main_Priority => ");
Set_Int (Main_Priority);
Set_Char (',');
Write_Statement_Buffer;
Set_String (" Time_Slice_Value => ");
if Task_Dispatching_Policy_Specified = 'F'
and then ALIs.Table (ALIs.First).Time_Slice_Value = -1
then
Set_Int (0);
else
Set_Int (ALIs.Table (ALIs.First).Time_Slice_Value);
end if;
Set_Char (',');
Write_Statement_Buffer;
Set_String (" WC_Encoding => '");
Set_Char (ALIs.Table (ALIs.First).WC_Encoding);
Set_String ("',");
Write_Statement_Buffer;
Set_String (" Locking_Policy => '");
Set_Char (Locking_Policy_Specified);
Set_String ("',");
Write_Statement_Buffer;
Set_String (" Queuing_Policy => '");
Set_Char (Queuing_Policy_Specified);
Set_String ("',");
Write_Statement_Buffer;
Set_String (" Task_Dispatching_Policy => '");
Set_Char (Task_Dispatching_Policy_Specified);
Set_String ("',");
Write_Statement_Buffer;
WBI (" Adafinal => System.Null_Address,");
Set_String (" Unreserve_All_Interrupts => ");
if Unreserve_All_Interrupts_Specified then
Set_String ("1");
else
Set_String ("0");
end if;
Set_String (",");
Write_Statement_Buffer;
Set_String (" Exception_Tracebacks => ");
if Exception_Tracebacks then
Set_String ("1");
else
Set_String ("0");
end if;
Set_String (");");
Write_Statement_Buffer;
-- Generate call to Install_Handler
WBI ("");
WBI (" if Handler_Installed = 0 then");
WBI (" Install_Handler;");
WBI (" end if;");
end if;
Gen_Elab_Calls_Ada;
WBI (" end " & Ada_Init_Name.all & ";");
end Gen_Adainit_Ada;
-------------------
-- Gen_Adainit_C --
--------------------
procedure Gen_Adainit_C is
Main_Priority : Int renames ALIs.Table (ALIs.First).Main_Priority;
begin
WBI ("void " & Ada_Init_Name.all & " ()");
WBI ("{");
-- Generate externals for elaboration entities
for E in Elab_Order.First .. Elab_Order.Last loop
declare
Unum : constant Unit_Id := Elab_Order.Table (E);
U : Unit_Record renames Units.Table (Unum);
begin
if U.Set_Elab_Entity then
Set_String (" extern char ");
Get_Name_String (U.Uname);
Set_Unit_Name;
Set_String ("_E;");
Write_Statement_Buffer;
end if;
end;
end loop;
Write_Statement_Buffer;
if No_Run_Time_Specified then
-- Case of No_Run_Time mode. Set __gl_main_priority if needed
-- for the Ravenscar profile.
if Main_Priority /= No_Main_Priority then
Set_String (" extern int __gl_main_priority = ");
Set_Int (Main_Priority);
Set_Char (';');
Write_Statement_Buffer;
end if;
else
-- Code for normal case (not in No_Run_Time mode)
Gen_Exception_Table_C;
-- Generate call to set the runtime global variables defined in
-- a-init.c. We define the varables in a-init.c, rather than in
-- the binder generated file itself to avoid undefined externals
-- when the runtime is linked as a shareable image library.
-- We call the routine from inside adainit() because this works for
-- both programs with and without binder generated "main" functions.
WBI (" __gnat_set_globals (");
Set_String (" ");
Set_Int (Main_Priority);
Set_Char (',');
Tab_To (15);
Set_String ("/* Main_Priority */");
Write_Statement_Buffer;
Set_String (" ");
if Task_Dispatching_Policy = 'F'
and then ALIs.Table (ALIs.First).Time_Slice_Value = -1
then
Set_Int (0);
else
Set_Int (ALIs.Table (ALIs.First).Time_Slice_Value);
end if;
Set_Char (',');
Tab_To (15);
Set_String ("/* Time_Slice_Value */");
Write_Statement_Buffer;
Set_String (" '");
Set_Char (ALIs.Table (ALIs.First).WC_Encoding);
Set_String ("',");
Tab_To (15);
Set_String ("/* WC_Encoding */");
Write_Statement_Buffer;
Set_String (" '");
Set_Char (Locking_Policy_Specified);
Set_String ("',");
Tab_To (15);
Set_String ("/* Locking_Policy */");
Write_Statement_Buffer;
Set_String (" '");
Set_Char (Queuing_Policy_Specified);
Set_String ("',");
Tab_To (15);
Set_String ("/* Queuing_Policy */");
Write_Statement_Buffer;
Set_String (" '");
Set_Char (Task_Dispatching_Policy_Specified);
Set_String ("',");
Tab_To (15);
Set_String ("/* Tasking_Dispatching_Policy */");
Write_Statement_Buffer;
Set_String (" ");
Set_String ("0,");
Tab_To (15);
Set_String ("/* Finalization routine address, not used anymore */");
Write_Statement_Buffer;
Set_String (" ");
Set_Int (Boolean'Pos (Unreserve_All_Interrupts_Specified));
Set_String (",");
Tab_To (15);
Set_String ("/* Unreserve_All_Interrupts */");
Write_Statement_Buffer;
Set_String (" ");
Set_Int (Boolean'Pos (Exception_Tracebacks));
Set_String (");");
Tab_To (15);
Set_String ("/* Exception_Tracebacks */");
Write_Statement_Buffer;
-- Install elaboration time signal handler
WBI (" if (__gnat_handler_installed == 0)");
WBI (" {");
WBI (" __gnat_install_handler ();");
WBI (" }");
end if;
WBI ("");
Gen_Elab_Calls_C;
WBI ("}");
end Gen_Adainit_C;
------------------------
-- Gen_Elab_Calls_Ada --
------------------------
procedure Gen_Elab_Calls_Ada is
begin
for E in Elab_Order.First .. Elab_Order.Last loop
declare
Unum : constant Unit_Id := Elab_Order.Table (E);
U : Unit_Record renames Units.Table (Unum);
Unum_Spec : Unit_Id;
-- This is the unit number of the spec that corresponds to
-- this entry. It is the same as Unum except when the body
-- and spec are different and we are currently processing
-- the body, in which case it is the spec (Unum + 1).
procedure Set_Elab_Entity;
-- Set name of elaboration entity flag
procedure Set_Elab_Entity is
begin
Get_Decoded_Name_String_With_Brackets (U.Uname);
Name_Len := Name_Len - 2;
Set_Casing (U.Icasing);
Set_Name_Buffer;
end Set_Elab_Entity;
begin
if U.Utype = Is_Body then
Unum_Spec := Unum + 1;
else
Unum_Spec := Unum;
end if;
-- Case of no elaboration code
if U.No_Elab then
-- The only case in which we have to do something is if
-- this is a body, with a separate spec, where the separate
-- spec has an elaboration entity defined.
-- In that case, this is where we set the elaboration entity
-- to True, we do not need to test if this has already been
-- done, since it is quicker to set the flag than to test it.
if U.Utype = Is_Body
and then Units.Table (Unum_Spec).Set_Elab_Entity
then
Set_String (" E");
Set_Unit_Number (Unum_Spec);
Set_String (" := True;");
Write_Statement_Buffer;
end if;
-- Here if elaboration code is present. We generate:
-- if not uname_E then
-- uname'elab_[spec|body];
-- uname_E := True;
-- end if;
-- The uname_E assignment is skipped if this is a separate spec,
-- since the assignment will be done when we process the body.
else
Set_String (" if not E");
Set_Unit_Number (Unum_Spec);
Set_String (" then");
Write_Statement_Buffer;
Set_String (" ");
Get_Decoded_Name_String_With_Brackets (U.Uname);
if Name_Buffer (Name_Len) = 's' then
Name_Buffer (Name_Len - 1 .. Name_Len + 8) := "'elab_spec";
else
Name_Buffer (Name_Len - 1 .. Name_Len + 8) := "'elab_body";
end if;
Name_Len := Name_Len + 8;
Set_Casing (U.Icasing);
Set_Name_Buffer;
Set_Char (';');
Write_Statement_Buffer;
if U.Utype /= Is_Spec then
Set_String (" E");
Set_Unit_Number (Unum_Spec);
Set_String (" := True;");
Write_Statement_Buffer;
end if;
WBI (" end if;");
end if;
end;
end loop;
end Gen_Elab_Calls_Ada;
----------------------
-- Gen_Elab_Calls_C --
----------------------
procedure Gen_Elab_Calls_C is
begin
for E in Elab_Order.First .. Elab_Order.Last loop
declare
Unum : constant Unit_Id := Elab_Order.Table (E);
U : Unit_Record renames Units.Table (Unum);
Unum_Spec : Unit_Id;
-- This is the unit number of the spec that corresponds to
-- this entry. It is the same as Unum except when the body
-- and spec are different and we are currently processing
-- the body, in which case it is the spec (Unum + 1).
begin
if U.Utype = Is_Body then
Unum_Spec := Unum + 1;
else
Unum_Spec := Unum;
end if;
-- Case of no elaboration code
if U.No_Elab then
-- The only case in which we have to do something is if
-- this is a body, with a separate spec, where the separate
-- spec has an elaboration entity defined.
-- In that case, this is where we set the elaboration entity
-- to True, we do not need to test if this has already been
-- done, since it is quicker to set the flag than to test it.
if U.Utype = Is_Body
and then Units.Table (Unum_Spec).Set_Elab_Entity
then
Set_String (" ");
Get_Name_String (U.Uname);
Set_Unit_Name;
Set_String ("_E = 1;");
Write_Statement_Buffer;
end if;
-- Here if elaboration code is present. We generate:
-- if (uname_E == 0) {
-- uname__elab[s|b] ();
-- uname_E++;
-- }
-- The uname_E assignment is skipped if this is a separate spec,
-- since the assignment will be done when we process the body.
else
Set_String (" if (");
Get_Name_String (U.Uname);
Set_Unit_Name;
Set_String ("_E == 0) {");
Write_Statement_Buffer;
Set_String (" ");
Set_Unit_Name;
Set_String ("___elab");
Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
Set_String (" ();");
Write_Statement_Buffer;
if U.Utype /= Is_Spec then
Set_String (" ");
Set_Unit_Name;
Set_String ("_E++;");
Write_Statement_Buffer;
end if;
WBI (" }");
end if;
end;
end loop;
end Gen_Elab_Calls_C;
----------------------
-- Gen_Elab_Defs_C --
----------------------
procedure Gen_Elab_Defs_C is
begin
for E in Elab_Order.First .. Elab_Order.Last loop
-- Generate declaration of elaboration procedure if elaboration
-- needed. Note that passive units are always excluded.
if not Units.Table (Elab_Order.Table (E)).No_Elab then
Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
Set_String ("extern void ");
Set_Unit_Name;
Set_String ("___elab");
Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
Set_String (" PARAMS ((void));");
Write_Statement_Buffer;
end if;
end loop;
WBI ("");
end Gen_Elab_Defs_C;
------------------------
-- Gen_Elab_Order_Ada --
------------------------
procedure Gen_Elab_Order_Ada is
begin
WBI ("");
WBI (" -- BEGIN ELABORATION ORDER");
for J in Elab_Order.First .. Elab_Order.Last loop
Set_String (" -- ");
Get_Unit_Name_String (Units.Table (Elab_Order.Table (J)).Uname);
Set_Name_Buffer;
Write_Statement_Buffer;
end loop;
WBI (" -- END ELABORATION ORDER");
end Gen_Elab_Order_Ada;
----------------------
-- Gen_Elab_Order_C --
----------------------
procedure Gen_Elab_Order_C is
begin
WBI ("");
WBI ("/* BEGIN ELABORATION ORDER");
for J in Elab_Order.First .. Elab_Order.Last loop
Get_Unit_Name_String (Units.Table (Elab_Order.Table (J)).Uname);
Set_Name_Buffer;
Write_Statement_Buffer;
end loop;
WBI (" END ELABORATION ORDER */");
end Gen_Elab_Order_C;
-----------------------------
-- Gen_Exception_Table_Ada --
-----------------------------
procedure Gen_Exception_Table_Ada is
Num : Nat;
Last : ALI_Id := No_ALI_Id;
begin
if not Zero_Cost_Exceptions_Specified then
WBI (" begin");
return;
end if;
-- The code we generate looks like
-- procedure SDP_Table_Build
-- (SDP_Addresses : System.Address;
-- SDP_Count : Natural;
-- Elab_Addresses : System.Address;
-- Elab_Addr_Count : Natural);
-- pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
--
-- ST : aliased constant array (1 .. nnn) of System.Address := (
-- unit_name_1'UET_Address,
-- unit_name_2'UET_Address,
-- ...
-- unit_name_3'UET_Address,
--
-- EA : aliased constant array (1 .. eee) of System.Address := (
-- adainit'Code_Address,
-- adafinal'Code_Address,
-- unit_name'elab[spec|body]'Code_Address,
-- unit_name'elab[spec|body]'Code_Address,
-- unit_name'elab[spec|body]'Code_Address,
-- unit_name'elab[spec|body]'Code_Address);
--
-- begin
-- SDP_Table_Build (ST'Address, nnn, EA'Address, eee);
Num := 0;
for A in ALIs.First .. ALIs.Last loop
if ALIs.Table (A).Unit_Exception_Table then
Num := Num + 1;
Last := A;
end if;
end loop;
if Num = 0 then
-- Happens with "gnatmake -a -f -gnatL ..."
WBI (" ");
WBI (" begin");
return;
end if;
WBI (" procedure SDP_Table_Build");
WBI (" (SDP_Addresses : System.Address;");
WBI (" SDP_Count : Natural;");
WBI (" Elab_Addresses : System.Address;");
WBI (" Elab_Addr_Count : Natural);");
WBI (" " &
"pragma Import (C, SDP_Table_Build, ""__gnat_SDP_Table_Build"");");
WBI (" ");
Set_String (" ST : aliased constant array (1 .. ");
Set_Int (Num);
Set_String (") of System.Address := (");
if Num = 1 then
Set_String ("1 => A1);");
Write_Statement_Buffer;
else
Write_Statement_Buffer;
for A in ALIs.First .. ALIs.Last loop
if ALIs.Table (A).Unit_Exception_Table then
Get_Decoded_Name_String_With_Brackets
(Units.Table (ALIs.Table (A).First_Unit).Uname);
Set_Casing (Mixed_Case);
Set_String (" ");
Set_String (Name_Buffer (1 .. Name_Len - 2));
Set_String ("'UET_Address");
if A = Last then
Set_String (");");
else
Set_Char (',');
end if;
Write_Statement_Buffer;
end if;
end loop;
end if;
WBI (" ");
Set_String (" EA : aliased constant array (1 .. ");
Set_Int (Num_Elab_Calls + 2);
Set_String (") of System.Address := (");
Write_Statement_Buffer;
WBI (" " & Ada_Init_Name.all & "'Code_Address,");
-- If compiling for the JVM, we directly reference Adafinal because
-- we don't import it via Do_Finalize (see Gen_Output_File_Ada).
if Hostparm.Java_VM then
Set_String (" System.Standard_Library.Adafinal'Code_Address");
else
Set_String (" Do_Finalize'Code_Address");
end if;
for E in Elab_Order.First .. Elab_Order.Last loop
Get_Decoded_Name_String_With_Brackets
(Units.Table (Elab_Order.Table (E)).Uname);
if Units.Table (Elab_Order.Table (E)).No_Elab then
null;
else
Set_Char (',');
Write_Statement_Buffer;
Set_String (" ");
if Name_Buffer (Name_Len) = 's' then
Name_Buffer (Name_Len - 1 .. Name_Len + 21) :=
"'elab_spec'code_address";
else
Name_Buffer (Name_Len - 1 .. Name_Len + 21) :=
"'elab_body'code_address";
end if;
Name_Len := Name_Len + 21;
Set_Casing (Units.Table (Elab_Order.Table (E)).Icasing);
Set_Name_Buffer;
end if;
end loop;
Set_String (");");
Write_Statement_Buffer;
WBI (" ");
WBI (" begin");
Set_String (" SDP_Table_Build (ST'Address, ");
Set_Int (Num);
Set_String (", EA'Address, ");
Set_Int (Num_Elab_Calls + 2);
Set_String (");");
Write_Statement_Buffer;
end Gen_Exception_Table_Ada;
---------------------------
-- Gen_Exception_Table_C --
---------------------------
procedure Gen_Exception_Table_C is
Num : Nat;
Num2 : Nat;
begin
if not Zero_Cost_Exceptions_Specified then
return;
end if;
-- The code we generate looks like
-- extern void *__gnat_unitname1__SDP;
-- extern void *__gnat_unitname2__SDP;
-- ...
--
-- void **st[nnn] = {
-- &__gnat_unitname1__SDP,
-- &__gnat_unitname2__SDP,
-- ...
-- &__gnat_unitnamen__SDP};
--
-- extern void unitname1__elabb ();
-- extern void unitname2__elabb ();
-- ...
--
-- void (*ea[eee]) () = {
-- adainit,
-- adafinal,
-- unitname1___elab[b,s],
-- unitname2___elab[b,s],
-- ...
-- unitnamen___elab[b,s]};
--
-- __gnat_SDP_Table_Build (&st, nnn, &ea, eee);
Num := 0;
for A in ALIs.First .. ALIs.Last loop
if ALIs.Table (A).Unit_Exception_Table then
Num := Num + 1;
Set_String (" extern void *__gnat_");
Get_Name_String (Units.Table (ALIs.Table (A).First_Unit).Uname);
Set_Unit_Name;
Set_String ("__SDP");
Set_Char (';');
Write_Statement_Buffer;
end if;
end loop;
if Num = 0 then
-- Happens with "gnatmake -a -f -gnatL ..."
return;
end if;
WBI (" ");
Set_String (" void **st[");
Set_Int (Num);
Set_String ("] = {");
Write_Statement_Buffer;
Num2 := 0;
for A in ALIs.First .. ALIs.Last loop
if ALIs.Table (A).Unit_Exception_Table then
Num2 := Num2 + 1;
Set_String (" &__gnat_");
Get_Name_String (Units.Table (ALIs.Table (A).First_Unit).Uname);
Set_Unit_Name;
Set_String ("__SDP");
if Num = Num2 then
Set_String ("};");
else
Set_Char (',');
end if;
Write_Statement_Buffer;
end if;
end loop;
WBI ("");
for E in Elab_Order.First .. Elab_Order.Last loop
Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
if Units.Table (Elab_Order.Table (E)).No_Elab then
null;
else
Set_String (" extern void ");
Set_Unit_Name;
Set_String ("___elab");
Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
Set_String (" ();");
Write_Statement_Buffer;
end if;
end loop;
WBI ("");
Set_String (" void (*ea[");
Set_Int (Num_Elab_Calls + 2);
Set_String ("]) () = {");
Write_Statement_Buffer;
WBI (" " & Ada_Init_Name.all & ",");
Set_String (" system__standard_library__adafinal");
for E in Elab_Order.First .. Elab_Order.Last loop
Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
if Units.Table (Elab_Order.Table (E)).No_Elab then
null;
else
Set_Char (',');
Write_Statement_Buffer;
Set_String (" ");
Set_Unit_Name;
Set_String ("___elab");
Set_Char (Name_Buffer (Name_Len)); -- 's' or 'b' for spec/body
end if;
end loop;
Set_String ("};");
Write_Statement_Buffer;
WBI (" ");
Set_String (" __gnat_SDP_Table_Build (&st, ");
Set_Int (Num);
Set_String (", ea, ");
Set_Int (Num_Elab_Calls + 2);
Set_String (");");
Write_Statement_Buffer;
end Gen_Exception_Table_C;
------------------
-- Gen_Main_Ada --
------------------
procedure Gen_Main_Ada is
Target : constant String_Ptr := Target_Name;
VxWorks_Target : constant Boolean :=
Target (Target'Last - 7 .. Target'Last) = "vxworks/";
begin
WBI ("");
Set_String (" function ");
Set_String (Get_Main_Name);
if VxWorks_Target then
Set_String (" return Integer is");
Write_Statement_Buffer;
else
Write_Statement_Buffer;
WBI (" (argc : Integer;");
WBI (" argv : System.Address;");
WBI (" envp : System.Address)");
WBI (" return Integer");
WBI (" is");
end if;
-- Initialize and Finalize are not used in No_Run_Time mode
if not No_Run_Time_Specified then
WBI (" procedure initialize;");
WBI (" pragma Import (C, initialize, ""__gnat_initialize"");");
WBI ("");
WBI (" procedure finalize;");
WBI (" pragma Import (C, finalize, ""__gnat_finalize"");");
WBI ("");
end if;
-- Deal with declarations for main program case
if not No_Main_Subprogram then
-- To call the main program, we declare it using a pragma Import
-- Ada with the right link name.
-- It might seem more obvious to "with" the main program, and call
-- it in the normal Ada manner. We do not do this for three reasons:
-- 1. It is more efficient not to recompile the main program
-- 2. We are not entitled to assume the source is accessible
-- 3. We don't know what options to use to compile it
-- It is really reason 3 that is most critical (indeed we used
-- to generate the "with", but several regression tests failed).
WBI ("");
if ALIs.Table (ALIs.First).Main_Program = Func then
WBI (" Result : Integer;");
WBI ("");
WBI (" function Ada_Main_Program return Integer;");
else
WBI (" procedure Ada_Main_Program;");
end if;
Set_String (" pragma Import (Ada, Ada_Main_Program, """);
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
Set_Main_Program_Name;
Set_String (""");");
Write_Statement_Buffer;
WBI ("");
end if;
WBI (" begin");
-- On VxWorks, there are no command line arguments
if VxWorks_Target then
WBI (" gnat_argc := 0;");
WBI (" gnat_argv := System.Null_Address;");
WBI (" gnat_envp := System.Null_Address;");
-- Normal case of command line arguments present
else
WBI (" gnat_argc := argc;");
WBI (" gnat_argv := argv;");
WBI (" gnat_envp := envp;");
WBI ("");
end if;
if not No_Run_Time_Specified then
WBI (" Initialize;");
end if;
WBI (" " & Ada_Init_Name.all & ";");
if not No_Main_Subprogram then
WBI (" Break_Start;");
if ALIs.Table (ALIs.First).Main_Program = Proc then
WBI (" Ada_Main_Program;");
else
WBI (" Result := Ada_Main_Program;");
end if;
end if;
-- Adafinal is only called if we have a run time
if not No_Run_Time_Specified then
-- If compiling for the JVM, we directly call Adafinal because
-- we don't import it via Do_Finalize (see Gen_Output_File_Ada).
if Hostparm.Java_VM then
WBI (" System.Standard_Library.Adafinal;");
else
WBI (" Do_Finalize;");
end if;
end if;
-- Finalize is only called if we have a run time
if not No_Run_Time_Specified then
WBI (" Finalize;");
end if;
-- Return result
if No_Main_Subprogram
or else ALIs.Table (ALIs.First).Main_Program = Proc
then
WBI (" return (gnat_exit_status);");
else
WBI (" return (Result);");
end if;
WBI (" end;");
end Gen_Main_Ada;
----------------
-- Gen_Main_C --
----------------
procedure Gen_Main_C is
Target : constant String_Ptr := Target_Name;
VxWorks_Target : constant Boolean :=
Target (Target'Last - 7 .. Target'Last) = "vxworks/";
begin
Set_String ("int ");
Set_String (Get_Main_Name);
-- On VxWorks, there are no command line arguments
if VxWorks_Target then
Set_String (" ()");
-- Normal case with command line arguments present
else
Set_String (" (argc, argv, envp)");
end if;
Write_Statement_Buffer;
-- VxWorks doesn't have the notion of argc/argv
if VxWorks_Target then
WBI ("{");
WBI (" int result;");
WBI (" gnat_argc = 0;");
WBI (" gnat_argv = 0;");
WBI (" gnat_envp = 0;");
-- Normal case of arguments present
else
WBI (" int argc;");
WBI (" char **argv;");
WBI (" char **envp;");
WBI ("{");
if ALIs.Table (ALIs.First).Main_Program = Func then
WBI (" int result;");
end if;
WBI (" gnat_argc = argc;");
WBI (" gnat_argv = argv;");
WBI (" gnat_envp = envp;");
WBI (" ");
end if;
-- The __gnat_initialize routine is used only if we have a run-time
if not No_Run_Time_Specified then
WBI
(" __gnat_initialize ();");
end if;
WBI (" " & Ada_Init_Name.all & " ();");
if not No_Main_Subprogram then
WBI (" __gnat_break_start ();");
WBI (" ");
-- Output main program name
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
-- Main program is procedure case
if ALIs.Table (ALIs.First).Main_Program = Proc then
Set_String (" ");
Set_Main_Program_Name;
Set_String (" ();");
Write_Statement_Buffer;
-- Main program is function case
else -- ALIs.Table (ALIs_First).Main_Program = Func
Set_String (" result = ");
Set_Main_Program_Name;
Set_String (" ();");
Write_Statement_Buffer;
end if;
end if;
-- Adafinal is called only when we have a run-time
if not No_Run_Time_Specified then
WBI (" ");
WBI (" system__standard_library__adafinal ();");
end if;
-- The finalize routine is used only if we have a run-time
if not No_Run_Time_Specified then
WBI (" __gnat_finalize ();");
end if;
if ALIs.Table (ALIs.First).Main_Program = Func then
if Hostparm.OpenVMS then
-- VMS must use the Posix exit routine in order to get an
-- Unix compatible exit status.
WBI (" __posix_exit (result);");
else
WBI (" exit (result);");
end if;
else
if Hostparm.OpenVMS then
-- VMS must use the Posix exit routine in order to get an
-- Unix compatible exit status.
WBI (" __posix_exit (gnat_exit_status);");
else
WBI (" exit (gnat_exit_status);");
end if;
end if;
WBI ("}");
end Gen_Main_C;
------------------------------
-- Gen_Object_Files_Options --
------------------------------
procedure Gen_Object_Files_Options is
Lgnat : Integer;
procedure Write_Linker_Option;
-- Write binder info linker option.
-------------------------
-- Write_Linker_Option --
-------------------------
procedure Write_Linker_Option is
Start : Natural;
Stop : Natural;
begin
-- Loop through string, breaking at null's
Start := 1;
while Start < Name_Len loop
-- Find null ending this section
Stop := Start + 1;
while Name_Buffer (Stop) /= ASCII.NUL
and then Stop <= Name_Len loop
Stop := Stop + 1;
end loop;
-- Process section if non-null
if Stop > Start then
if Output_Linker_Option_List then
Write_Str (Name_Buffer (Start .. Stop - 1));
Write_Eol;
end if;
Write_Info_Ada_C
(" -- ", "", Name_Buffer (Start .. Stop - 1));
end if;
Start := Stop + 1;
end loop;
end Write_Linker_Option;
-- Start of processing for Gen_Object_Files_Options
begin
WBI ("");
Write_Info_Ada_C ("--", "/*", " BEGIN Object file/option list");
for E in Elab_Order.First .. Elab_Order.Last loop
-- If not spec that has an associated body, then generate a
-- comment giving the name of the corresponding object file.
if Units.Table (Elab_Order.Table (E)).Utype /= Is_Spec then
Get_Name_String
(ALIs.Table
(Units.Table (Elab_Order.Table (E)).My_ALI).Ofile_Full_Name);
-- If the presence of an object file is necessary or if it
-- exists, then use it.
if not Hostparm.Exclude_Missing_Objects
or else
GNAT.OS_Lib.Is_Regular_File (Name_Buffer (1 .. Name_Len))
then
Write_Info_Ada_C (" -- ", "", Name_Buffer (1 .. Name_Len));
if Output_Object_List then
Write_Str (Name_Buffer (1 .. Name_Len));
Write_Eol;
end if;
-- Don't link with the shared library on VMS if an internal
-- filename object is seen. Multiply defined symbols will
-- result.
if Hostparm.OpenVMS
and then Is_Internal_File_Name
(ALIs.Table
(Units.Table (Elab_Order.Table (E)).My_ALI).Sfile)
then
Opt.Shared_Libgnat := False;
end if;
end if;
end if;
end loop;
-- Add a "-Ldir" for each directory in the object path. We skip this
-- in No_Run_Time mode, where we want more precise control of exactly
-- what goes into the resulting object file
if not No_Run_Time_Specified then
for J in 1 .. Nb_Dir_In_Obj_Search_Path loop
declare
Dir : String_Ptr := Dir_In_Obj_Search_Path (J);
begin
Name_Len := 0;
Add_Str_To_Name_Buffer ("-L");
Add_Str_To_Name_Buffer (Dir.all);
Write_Linker_Option;
end;
end loop;
end if;
-- Sort linker options
Sort (Linker_Options.Last, Move_Linker_Option'Access,
Lt_Linker_Option'Access);
-- Write user linker options
Lgnat := Linker_Options.Last + 1;
for J in 1 .. Linker_Options.Last loop
if not Linker_Options.Table (J).Internal_File then
Get_Name_String (Linker_Options.Table (J).Name);
Write_Linker_Option;
else
Lgnat := J;
exit;
end if;
end loop;
if not (No_Run_Time_Specified or else Opt.No_Stdlib) then
Name_Len := 0;
if Opt.Shared_Libgnat then
Add_Str_To_Name_Buffer ("-shared");
else
Add_Str_To_Name_Buffer ("-static");
end if;
-- Write directly to avoid -K output.
Write_Info_Ada_C (" -- ", "", Name_Buffer (1 .. Name_Len));
if With_DECGNAT then
Name_Len := 0;
Add_Str_To_Name_Buffer ("-ldecgnat");
Write_Linker_Option;
end if;
if With_GNARL then
Name_Len := 0;
Add_Str_To_Name_Buffer ("-lgnarl");
Write_Linker_Option;
end if;
Name_Len := 0;
Add_Str_To_Name_Buffer ("-lgnat");
Write_Linker_Option;
end if;
-- Write internal linker options
for J in Lgnat .. Linker_Options.Last loop
Get_Name_String (Linker_Options.Table (J).Name);
Write_Linker_Option;
end loop;
if Ada_Bind_File then
WBI ("-- END Object file/option list ");
else
WBI (" END Object file/option list */");
end if;
end Gen_Object_Files_Options;
---------------------
-- Gen_Output_File --
---------------------
procedure Gen_Output_File (Filename : String) is
-- Start of processing for Gen_Output_File
begin
-- Override Ada_Bind_File and Bind_Main_Program for Java since
-- JGNAT only supports Ada code, and the main program is already
-- generated by the compiler.
if Hostparm.Java_VM then
Ada_Bind_File := True;
Bind_Main_Program := False;
end if;
-- Override time slice value if -T switch is set
if Time_Slice_Set then
ALIs.Table (ALIs.First).Time_Slice_Value := Opt.Time_Slice_Value;
end if;
-- Count number of elaboration calls
for E in Elab_Order.First .. Elab_Order.Last loop
if Units.Table (Elab_Order.Table (E)).No_Elab then
null;
else
Num_Elab_Calls := Num_Elab_Calls + 1;
end if;
end loop;
-- Generate output file in appropriate language
if Ada_Bind_File then
Gen_Output_File_Ada (Filename);
else
Gen_Output_File_C (Filename);
end if;
end Gen_Output_File;
-------------------------
-- Gen_Output_File_Ada --
-------------------------
procedure Gen_Output_File_Ada (Filename : String) is
Bfiles : Name_Id;
-- Name of generated bind file (spec)
Bfileb : Name_Id;
-- Name of generated bind file (body)
Ada_Main : constant String := Get_Ada_Main_Name;
-- Name to be used for generated Ada main program. See the body of
-- function Get_Ada_Main_Name for details on the form of the name.
Target : constant String_Ptr := Target_Name;
VxWorks_Target : constant Boolean :=
Target (Target'Last - 7 .. Target'Last) = "vxworks/";
begin
-- Create spec first
Create_Binder_Output (Filename, 's', Bfiles);
if No_Run_Time_Specified then
WBI ("pragma No_Run_Time;");
end if;
-- Generate with of System so we can reference System.Address, note
-- that such a reference is safe even in No_Run_Time mode, since we
-- do not need any run-time code for such a reference, and we output
-- a pragma No_Run_Time for this compilation above.
WBI ("with System;");
-- Generate with of System.Initialize_Scalars if active
if Initialize_Scalars_Used then
WBI ("with System.Scalar_Values;");
end if;
Resolve_Binder_Options;
if not No_Run_Time_Specified then
-- Usually, adafinal is called using a pragma Import C. Since
-- Import C doesn't have the same semantics for JGNAT, we use
-- standard Ada.
if Hostparm.Java_VM then
WBI ("with System.Standard_Library;");
end if;
end if;
WBI ("package " & Ada_Main & " is");
-- Main program case
if Bind_Main_Program then
-- Generate argc/argv stuff
WBI ("");
WBI (" gnat_argc : Integer;");
WBI (" gnat_argv : System.Address;");
WBI (" gnat_envp : System.Address;");
-- If we have a run time present, these variables are in the
-- runtime data area for easy access from the runtime
if not No_Run_Time_Specified then
WBI ("");
WBI (" pragma Import (C, gnat_argc);");
WBI (" pragma Import (C, gnat_argv);");
WBI (" pragma Import (C, gnat_envp);");
end if;
-- Define exit status. Again in normal mode, this is in the
-- run-time library, and is initialized there, but in the no
-- run time case, the variable is here and initialized here.
WBI ("");
if No_Run_Time_Specified then
WBI (" gnat_exit_status : Integer := 0;");
else
WBI (" gnat_exit_status : Integer;");
WBI (" pragma Import (C, gnat_exit_status);");
end if;
end if;
-- Generate the GNAT_Version and Ada_Main_Program_name info only for
-- the main program. Otherwise, it can lead under some circumstances
-- to a symbol duplication during the link (for instance when a
-- C program uses 2 Ada libraries)
if Bind_Main_Program then
WBI ("");
WBI (" GNAT_Version : constant String :=");
WBI (" ""GNAT Version: " &
Gnat_Version_String & """;");
WBI (" pragma Export (C, GNAT_Version, ""__gnat_version"");");
WBI ("");
Set_String (" Ada_Main_Program_Name : constant String := """);
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
Set_Main_Program_Name;
Set_String (""" & Ascii.NUL;");
Write_Statement_Buffer;
WBI
(" pragma Export (C, Ada_Main_Program_Name, " &
"""__gnat_ada_main_program_name"");");
end if;
-- No need to generate a finalization routine if there is no
-- runtime, since there is nothing to do in this case.
if not No_Run_Time_Specified then
WBI ("");
WBI (" procedure " & Ada_Final_Name.all & ";");
WBI (" pragma Export (C, " & Ada_Final_Name.all & ", """ &
Ada_Final_Name.all & """);");
end if;
WBI ("");
WBI (" procedure " & Ada_Init_Name.all & ";");
WBI (" pragma Export (C, " & Ada_Init_Name.all & ", """ &
Ada_Init_Name.all & """);");
if Bind_Main_Program then
-- If we have a run time, then Break_Start is defined there, but
-- if there is no run-time, Break_Start is defined in this file.
WBI ("");
WBI (" procedure Break_Start;");
if No_Run_Time_Specified then
WBI (" pragma Export (C, Break_Start, ""__gnat_break_start"");");
else
WBI (" pragma Import (C, Break_Start, ""__gnat_break_start"");");
end if;
WBI ("");
WBI (" function " & Get_Main_Name);
-- Generate argument list (except on VxWorks, where none is present)
if not VxWorks_Target then
WBI (" (argc : Integer;");
WBI (" argv : System.Address;");
WBI (" envp : System.Address)");
end if;
WBI (" return Integer;");
WBI (" pragma Export (C, " & Get_Main_Name & ", """ &
Get_Main_Name & """);");
end if;
if Initialize_Scalars_Used then
Gen_Scalar_Values;
end if;
Gen_Versions_Ada;
Gen_Elab_Order_Ada;
-- Spec is complete
WBI ("");
WBI ("end " & Ada_Main & ";");
Close_Binder_Output;
-- Prepare to write body
Create_Binder_Output (Filename, 'b', Bfileb);
-- Output Source_File_Name pragmas which look like
-- pragma Source_File_Name (Ada_Main, Spec_File_Name => "sss");
-- pragma Source_File_Name (Ada_Main, Body_File_Name => "bbb");
-- where sss/bbb are the spec/body file names respectively
Get_Name_String (Bfiles);
Name_Buffer (Name_Len + 1 .. Name_Len + 3) := """);";
WBI ("pragma Source_File_Name (" &
Ada_Main &
", Spec_File_Name => """ &
Name_Buffer (1 .. Name_Len + 3));
Get_Name_String (Bfileb);
Name_Buffer (Name_Len + 1 .. Name_Len + 3) := """);";
WBI ("pragma Source_File_Name (" &
Ada_Main &
", Body_File_Name => """ &
Name_Buffer (1 .. Name_Len + 3));
WBI ("");
WBI ("package body " & Ada_Main & " is");
-- Import the finalization procedure only if there is a runtime.
if not No_Run_Time_Specified then
-- In the Java case, pragma Import C cannot be used, so the
-- standard Ada constructs will be used instead.
if not Hostparm.Java_VM then
WBI ("");
WBI (" procedure Do_Finalize;");
WBI
(" pragma Import (C, Do_Finalize, " &
"""system__standard_library__adafinal"");");
WBI ("");
end if;
end if;
Gen_Adainit_Ada;
-- No need to generate a finalization routine if there is no
-- runtime, since there is nothing to do in this case.
if not No_Run_Time_Specified then
Gen_Adafinal_Ada;
end if;
if Bind_Main_Program then
-- In No_Run_Time mode, generate dummy body for Break_Start
if No_Run_Time_Specified then
WBI ("");
WBI (" procedure Break_Start is");
WBI (" begin");
WBI (" null;");
WBI (" end;");
end if;
Gen_Main_Ada;
end if;
-- Output object file list and the Ada body is complete
Gen_Object_Files_Options;
WBI ("");
WBI ("end " & Ada_Main & ";");
Close_Binder_Output;
end Gen_Output_File_Ada;
-----------------------
-- Gen_Output_File_C --
-----------------------
procedure Gen_Output_File_C (Filename : String) is
Bfile : Name_Id;
-- Name of generated bind file
begin
Create_Binder_Output (Filename, 'c', Bfile);
Resolve_Binder_Options;
WBI ("#ifdef __STDC__");
WBI ("#define PARAMS(paramlist) paramlist");
WBI ("#else");
WBI ("#define PARAMS(paramlist) ()");
WBI ("#endif");
WBI ("");
WBI ("extern void __gnat_set_globals ");
WBI (" PARAMS ((int, int, int, int, int, int, ");
WBI (" void (*) PARAMS ((void)), int, int));");
WBI ("extern void " & Ada_Final_Name.all & " PARAMS ((void));");
WBI ("extern void " & Ada_Init_Name.all & " PARAMS ((void));");
WBI ("extern void system__standard_library__adafinal PARAMS ((void));");
if not No_Main_Subprogram then
WBI ("extern int main PARAMS ((int, char **, char **));");
if Hostparm.OpenVMS then
WBI ("extern void __posix_exit PARAMS ((int));");
else
WBI ("extern void exit PARAMS ((int));");
end if;
WBI ("extern void __gnat_break_start PARAMS ((void));");
Set_String ("extern ");
if ALIs.Table (ALIs.First).Main_Program = Proc then
Set_String ("void ");
else
Set_String ("int ");
end if;
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
Set_Main_Program_Name;
Set_String (" PARAMS ((void));");
Write_Statement_Buffer;
end if;
if not No_Run_Time_Specified then
WBI ("extern void __gnat_initialize PARAMS ((void));");
WBI ("extern void __gnat_finalize PARAMS ((void));");
WBI ("extern void __gnat_install_handler PARAMS ((void));");
end if;
WBI ("");
Gen_Elab_Defs_C;
-- Imported variable used to track elaboration/finalization phase.
-- Used only when we have a runtime.
if not No_Run_Time_Specified then
WBI ("extern int __gnat_handler_installed;");
WBI ("");
end if;
-- Write argv/argc stuff if main program case
if Bind_Main_Program then
-- In the normal case, these are in the runtime library
if not No_Run_Time_Specified then
WBI ("extern int gnat_argc;");
WBI ("extern char **gnat_argv;");
WBI ("extern char **gnat_envp;");
WBI ("extern int gnat_exit_status;");
-- In the No_Run_Time case, they are right in the binder file
-- and we initialize gnat_exit_status in the declaration.
else
WBI ("int gnat_argc;");
WBI ("char **gnat_argv;");
WBI ("char **gnat_envp;");
WBI ("int gnat_exit_status = 0;");
end if;
WBI ("");
end if;
-- In no run-time mode, the __gnat_break_start routine (for the
-- debugger to get initial control) is defined in this file.
if No_Run_Time_Specified then
WBI ("");
WBI ("void __gnat_break_start () {}");
end if;
-- Generate the __gnat_version and __gnat_ada_main_program_name info
-- only for the main program. Otherwise, it can lead under some
-- circumstances to a symbol duplication during the link (for instance
-- when a C program uses 2 Ada libraries)
if Bind_Main_Program then
WBI ("");
WBI ("char __gnat_version[] = ""GNAT Version: " &
Gnat_Version_String & """;");
Set_String ("char __gnat_ada_main_program_name[] = """);
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
Set_Main_Program_Name;
Set_String (""";");
Write_Statement_Buffer;
end if;
-- Generate the adafinal routine. In no runtime mode, this is
-- not needed, since there is no finalization to do.
if not No_Run_Time_Specified then
Gen_Adafinal_C;
end if;
Gen_Adainit_C;
-- Main is only present for Ada main case
if Bind_Main_Program then
Gen_Main_C;
end if;
-- Scalar values, versions and object files needed in both cases
if Initialize_Scalars_Used then
Gen_Scalar_Values;
end if;
Gen_Versions_C;
Gen_Elab_Order_C;
Gen_Object_Files_Options;
-- C binder output is complete
Close_Binder_Output;
end Gen_Output_File_C;
-----------------------
-- Gen_Scalar_Values --
-----------------------
procedure Gen_Scalar_Values is
-- Strings to hold hex values of initialization constants. Note that
-- we store these strings in big endian order, but they are actually
-- used to initialize integer values, so the actual generated data
-- will automaticaly have the right endianess.
IS_Is1 : String (1 .. 2);
IS_Is2 : String (1 .. 4);
IS_Is4 : String (1 .. 8);
IS_Is8 : String (1 .. 16);
IS_Iu1 : String (1 .. 2);
IS_Iu2 : String (1 .. 4);
IS_Iu4 : String (1 .. 8);
IS_Iu8 : String (1 .. 16);
IS_Isf : String (1 .. 8);
IS_Ifl : String (1 .. 8);
IS_Ilf : String (1 .. 16);
-- The string for Long_Long_Float is special. This is used only on the
-- ia32 with 80-bit extended float (stored in 96 bits by gcc). The
-- value here is represented little-endian, since that's the only way
-- it is ever generated (this is not used on big-endian machines.
IS_Ill : String (1 .. 24);
begin
-- -Sin (invalid values)
if Opt.Initialize_Scalars_Mode = 'I' then
IS_Is1 := "80";
IS_Is2 := "8000";
IS_Is4 := "80000000";
IS_Is8 := "8000000000000000";
IS_Iu1 := "FF";
IS_Iu2 := "FFFF";
IS_Iu4 := "FFFFFFFF";
IS_Iu8 := "FFFFFFFFFFFFFFFF";
IS_Isf := IS_Iu4;
IS_Ifl := IS_Iu4;
IS_Ilf := IS_Iu8;
IS_Ill := "00000000000000C0FFFF0000";
-- -Slo (low values)
elsif Opt.Initialize_Scalars_Mode = 'L' then
IS_Is1 := "80";
IS_Is2 := "8000";
IS_Is4 := "80000000";
IS_Is8 := "8000000000000000";
IS_Iu1 := "00";
IS_Iu2 := "0000";
IS_Iu4 := "00000000";
IS_Iu8 := "0000000000000000";
IS_Isf := "FF800000";
IS_Ifl := IS_Isf;
IS_Ilf := "FFF0000000000000";
IS_Ill := "0000000000000080FFFF0000";
-- -Shi (high values)
elsif Opt.Initialize_Scalars_Mode = 'H' then
IS_Is1 := "7F";
IS_Is2 := "7FFF";
IS_Is4 := "7FFFFFFF";
IS_Is8 := "7FFFFFFFFFFFFFFF";
IS_Iu1 := "FF";
IS_Iu2 := "FFFF";
IS_Iu4 := "FFFFFFFF";
IS_Iu8 := "FFFFFFFFFFFFFFFF";
IS_Isf := "7F800000";
IS_Ifl := IS_Isf;
IS_Ilf := "7FF0000000000000";
IS_Ill := "0000000000000080FF7F0000";
-- -Shh (hex byte)
else pragma Assert (Opt.Initialize_Scalars_Mode = 'X');
IS_Is1 (1 .. 2) := Opt.Initialize_Scalars_Val;
IS_Is2 (1 .. 2) := Opt.Initialize_Scalars_Val;
IS_Is2 (3 .. 4) := Opt.Initialize_Scalars_Val;
for J in 1 .. 4 loop
IS_Is4 (2 * J - 1 .. 2 * J) := Opt.Initialize_Scalars_Val;
end loop;
for J in 1 .. 8 loop
IS_Is8 (2 * J - 1 .. 2 * J) := Opt.Initialize_Scalars_Val;
end loop;
IS_Iu1 := IS_Is1;
IS_Iu2 := IS_Is2;
IS_Iu4 := IS_Is4;
IS_Iu8 := IS_Is8;
IS_Isf := IS_Is4;
IS_Ifl := IS_Is4;
IS_Ilf := IS_Is8;
for J in 1 .. 12 loop
IS_Ill (2 * J - 1 .. 2 * J) := Opt.Initialize_Scalars_Val;
end loop;
end if;
-- Generate output, Ada case
if Ada_Bind_File then
WBI ("");
Set_String (" IS_Is1 : constant System.Scalar_Values.Byte1 := 16#");
Set_String (IS_Is1);
Write_Statement_Buffer ("#;");
Set_String (" IS_Is2 : constant System.Scalar_Values.Byte2 := 16#");
Set_String (IS_Is2);
Write_Statement_Buffer ("#;");
Set_String (" IS_Is4 : constant System.Scalar_Values.Byte4 := 16#");
Set_String (IS_Is4);
Write_Statement_Buffer ("#;");
Set_String (" IS_Is8 : constant System.Scalar_Values.Byte8 := 16#");
Set_String (IS_Is8);
Write_Statement_Buffer ("#;");
Set_String (" IS_Iu1 : constant System.Scalar_Values.Byte1 := 16#");
Set_String (IS_Iu1);
Write_Statement_Buffer ("#;");
Set_String (" IS_Iu2 : constant System.Scalar_Values.Byte2 := 16#");
Set_String (IS_Iu2);
Write_Statement_Buffer ("#;");
Set_String (" IS_Iu4 : constant System.Scalar_Values.Byte4 := 16#");
Set_String (IS_Iu4);
Write_Statement_Buffer ("#;");
Set_String (" IS_Iu8 : constant System.Scalar_Values.Byte8 := 16#");
Set_String (IS_Iu8);
Write_Statement_Buffer ("#;");
Set_String (" IS_Isf : constant System.Scalar_Values.Byte4 := 16#");
Set_String (IS_Isf);
Write_Statement_Buffer ("#;");
Set_String (" IS_Ifl : constant System.Scalar_Values.Byte4 := 16#");
Set_String (IS_Ifl);
Write_Statement_Buffer ("#;");
Set_String (" IS_Ilf : constant System.Scalar_Values.Byte8 := 16#");
Set_String (IS_Ilf);
Write_Statement_Buffer ("#;");
-- Special case of Long_Long_Float. This is a 10-byte value used
-- only on the x86. We could omit it for other architectures, but
-- we don't easily have that kind of target specialization in the
-- binder, and it's only 10 bytes, and only if -Sxx is used. Note
-- that for architectures where Long_Long_Float is the same as
-- Long_Float, the expander uses the Long_Float constant for the
-- initializations of Long_Long_Float values.
WBI (" IS_Ill : constant array (1 .. 12) of");
WBI (" System.Scalar_Values.Byte1 := (");
Set_String (" ");
for J in 1 .. 6 loop
Set_String (" 16#");
Set_Char (IS_Ill (2 * J - 1));
Set_Char (IS_Ill (2 * J));
Set_String ("#,");
end loop;
Write_Statement_Buffer;
Set_String (" ");
for J in 7 .. 12 loop
Set_String (" 16#");
Set_Char (IS_Ill (2 * J - 1));
Set_Char (IS_Ill (2 * J));
if J = 12 then
Set_String ("#);");
else
Set_String ("#,");
end if;
end loop;
Write_Statement_Buffer;
-- Output export statements to export to System.Scalar_Values
WBI ("");
WBI (" pragma Export (Ada, IS_Is1, ""__gnat_Is1"");");
WBI (" pragma Export (Ada, IS_Is2, ""__gnat_Is2"");");
WBI (" pragma Export (Ada, IS_Is4, ""__gnat_Is4"");");
WBI (" pragma Export (Ada, IS_Is8, ""__gnat_Is8"");");
WBI (" pragma Export (Ada, IS_Iu1, ""__gnat_Iu1"");");
WBI (" pragma Export (Ada, IS_Iu2, ""__gnat_Iu2"");");
WBI (" pragma Export (Ada, IS_Iu4, ""__gnat_Iu4"");");
WBI (" pragma Export (Ada, IS_Iu8, ""__gnat_Iu8"");");
WBI (" pragma Export (Ada, IS_Isf, ""__gnat_Isf"");");
WBI (" pragma Export (Ada, IS_Ifl, ""__gnat_Ifl"");");
WBI (" pragma Export (Ada, IS_Ilf, ""__gnat_Ilf"");");
WBI (" pragma Export (Ada, IS_Ill, ""__gnat_Ill"");");
-- Generate output C case
else
-- The lines we generate in this case are of the form
-- typ __gnat_I?? = 0x??;
-- where typ is appropriate to the length
WBI ("");
Set_String ("unsigned char __gnat_Is1 = 0x");
Set_String (IS_Is1);
Write_Statement_Buffer (";");
Set_String ("unsigned short __gnat_Is2 = 0x");
Set_String (IS_Is2);
Write_Statement_Buffer (";");
Set_String ("unsigned __gnat_Is4 = 0x");
Set_String (IS_Is4);
Write_Statement_Buffer (";");
Set_String ("long long unsigned __gnat_Is8 = 0x");
Set_String (IS_Is8);
Write_Statement_Buffer ("LL;");
Set_String ("unsigned char __gnat_Iu1 = 0x");
Set_String (IS_Is1);
Write_Statement_Buffer (";");
Set_String ("unsigned short __gnat_Iu2 = 0x");
Set_String (IS_Is2);
Write_Statement_Buffer (";");
Set_String ("unsigned __gnat_Iu4 = 0x");
Set_String (IS_Is4);
Write_Statement_Buffer (";");
Set_String ("long long unsigned __gnat_Iu8 = 0x");
Set_String (IS_Is8);
Write_Statement_Buffer ("LL;");
Set_String ("unsigned __gnat_Isf = 0x");
Set_String (IS_Isf);
Write_Statement_Buffer (";");
Set_String ("unsigned __gnat_Ifl = 0x");
Set_String (IS_Ifl);
Write_Statement_Buffer (";");
Set_String ("long long unsigned __gnat_Ilf = 0x");
Set_String (IS_Ilf);
Write_Statement_Buffer ("LL;");
-- For Long_Long_Float, we generate
-- char __gnat_Ill[12] = {0x??, 0x??, 0x??, 0x??, 0x??, 0x??,
-- 0x??, 0x??, 0x??, 0x??, 0x??, 0x??);
Set_String ("unsigned char __gnat_Ill[12] = {");
for J in 1 .. 6 loop
Set_String ("0x");
Set_Char (IS_Ill (2 * J - 1));
Set_Char (IS_Ill (2 * J));
Set_String (", ");
end loop;
Write_Statement_Buffer;
Set_String (" ");
for J in 7 .. 12 loop
Set_String ("0x");
Set_Char (IS_Ill (2 * J - 1));
Set_Char (IS_Ill (2 * J));
if J = 12 then
Set_String ("};");
else
Set_String (", ");
end if;
end loop;
Write_Statement_Buffer;
end if;
end Gen_Scalar_Values;
----------------------
-- Gen_Versions_Ada --
----------------------
-- This routine generates two sets of lines. The first set has the form:
-- unnnnn : constant Integer := 16#hhhhhhhh#;
-- The second set has the form
-- pragma Export (C, unnnnn, unam);
-- for each unit, where unam is the unit name suffixed by either B or
-- S for body or spec, with dots replaced by double underscores, and
-- hhhhhhhh is the version number, and nnnnn is a 5-digits serial number.
procedure Gen_Versions_Ada is
Ubuf : String (1 .. 6) := "u00000";
procedure Increment_Ubuf;
-- Little procedure to increment the serial number
procedure Increment_Ubuf is
begin
for J in reverse Ubuf'Range loop
Ubuf (J) := Character'Succ (Ubuf (J));
exit when Ubuf (J) <= '9';
Ubuf (J) := '0';
end loop;
end Increment_Ubuf;
-- Start of processing for Gen_Versions_Ada
begin
if Bind_For_Library then
-- When building libraries, the version number of each unit can
-- not be computed, since the binder does not know the full list
-- of units. Therefore, the 'Version and 'Body_Version
-- attributes can not supported in this case.
return;
end if;
WBI ("");
WBI (" type Version_32 is mod 2 ** 32;");
for U in Units.First .. Units.Last loop
Increment_Ubuf;
WBI (" " & Ubuf & " : constant Version_32 := 16#" &
Units.Table (U).Version & "#;");
end loop;
WBI ("");
Ubuf := "u00000";
for U in Units.First .. Units.Last loop
Increment_Ubuf;
Set_String (" pragma Export (C, ");
Set_String (Ubuf);
Set_String (", """);
Get_Name_String (Units.Table (U).Uname);
for K in 1 .. Name_Len loop
if Name_Buffer (K) = '.' then
Set_Char ('_');
Set_Char ('_');
elsif Name_Buffer (K) = '%' then
exit;
else
Set_Char (Name_Buffer (K));
end if;
end loop;
if Name_Buffer (Name_Len) = 's' then
Set_Char ('S');
else
Set_Char ('B');
end if;
Set_String (""");");
Write_Statement_Buffer;
end loop;
end Gen_Versions_Ada;
--------------------
-- Gen_Versions_C --
--------------------
-- This routine generates a line of the form:
-- unsigned unam = 0xhhhhhhhh;
-- for each unit, where unam is the unit name suffixed by either B or
-- S for body or spec, with dots replaced by double underscores.
procedure Gen_Versions_C is
begin
if Bind_For_Library then
-- When building libraries, the version number of each unit can
-- not be computed, since the binder does not know the full list
-- of units. Therefore, the 'Version and 'Body_Version
-- attributes can not supported.
return;
end if;
for U in Units.First .. Units.Last loop
Set_String ("unsigned ");
Get_Name_String (Units.Table (U).Uname);
for K in 1 .. Name_Len loop
if Name_Buffer (K) = '.' then
Set_String ("__");
elsif Name_Buffer (K) = '%' then
exit;
else
Set_Char (Name_Buffer (K));
end if;
end loop;
if Name_Buffer (Name_Len) = 's' then
Set_Char ('S');
else
Set_Char ('B');
end if;
Set_String (" = 0x");
Set_String (Units.Table (U).Version);
Set_Char (';');
Write_Statement_Buffer;
end loop;
end Gen_Versions_C;
-----------------------
-- Get_Ada_Main_Name --
-----------------------
function Get_Ada_Main_Name return String is
Suffix : constant String := "_00";
Name : String (1 .. Opt.Ada_Main_Name.all'Length + Suffix'Length) :=
Opt.Ada_Main_Name.all & Suffix;
Nlen : Natural;
begin
-- The main program generated by JGNAT expects a package called
-- ada_<main procedure>.
if Hostparm.Java_VM then
-- Get main program name
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
-- Remove the %b
return "ada_" & Name_Buffer (1 .. Name_Len - 2);
end if;
-- This loop tries the following possibilities in order
-- <Ada_Main>
-- <Ada_Main>_01
-- <Ada_Main>_02
-- ..
-- <Ada_Main>_99
-- where <Ada_Main> is equal to Opt.Ada_Main_Name. By default,
-- it is set to 'ada_main'.
for J in 0 .. 99 loop
if J = 0 then
Nlen := Name'Length - Suffix'Length;
else
Nlen := Name'Length;
Name (Name'Last) := Character'Val (J mod 10 + Character'Pos ('0'));
Name (Name'Last - 1) :=
Character'Val (J / 10 + Character'Pos ('0'));
end if;
for K in ALIs.First .. ALIs.Last loop
for L in ALIs.Table (K).First_Unit .. ALIs.Table (K).Last_Unit loop
-- Get unit name, removing %b or %e at end
Get_Name_String (Units.Table (L).Uname);
Name_Len := Name_Len - 2;
if Name_Buffer (1 .. Name_Len) = Name (1 .. Nlen) then
goto Continue;
end if;
end loop;
end loop;
return Name (1 .. Nlen);
<<Continue>>
null;
end loop;
-- If we fall through, just use a peculiar unlikely name
return ("Qwertyuiop");
end Get_Ada_Main_Name;
-------------------
-- Get_Main_Name --
-------------------
function Get_Main_Name return String is
Target : constant String_Ptr := Target_Name;
VxWorks_Target : constant Boolean :=
Target (Target'Last - 7 .. Target'Last) = "vxworks/";
begin
-- Explicit name given with -M switch
if Bind_Alternate_Main_Name then
return Alternate_Main_Name.all;
-- Case of main program name to be used directly
elsif VxWorks_Target then
-- Get main program name
Get_Name_String (Units.Table (First_Unit_Entry).Uname);
-- If this is a child name, return only the name of the child,
-- since we can't have dots in a nested program name. Note that
-- we do not include the %b at the end of the unit name.
for J in reverse 1 .. Name_Len - 3 loop
if J = 1 or else Name_Buffer (J - 1) = '.' then
return Name_Buffer (J .. Name_Len - 2);
end if;
end loop;
raise Program_Error; -- impossible exit
-- Case where "main" is to be used as default
else
return "main";
end if;
end Get_Main_Name;
----------------------
-- Lt_Linker_Option --
----------------------
function Lt_Linker_Option (Op1, Op2 : Natural) return Boolean is
begin
if Linker_Options.Table (Op1).Internal_File
/=
Linker_Options.Table (Op2).Internal_File
then
return Linker_Options.Table (Op1).Internal_File
<
Linker_Options.Table (Op2).Internal_File;
else
if Units.Table (Linker_Options.Table (Op1).Unit).Elab_Position
/=
Units.Table (Linker_Options.Table (Op2).Unit).Elab_Position
then
return Units.Table (Linker_Options.Table (Op1).Unit).Elab_Position
>
Units.Table (Linker_Options.Table (Op2).Unit).Elab_Position;
else
return Linker_Options.Table (Op1).Original_Pos
<
Linker_Options.Table (Op2).Original_Pos;
end if;
end if;
end Lt_Linker_Option;
------------------------
-- Move_Linker_Option --
------------------------
procedure Move_Linker_Option (From : Natural; To : Natural) is
begin
Linker_Options.Table (To) := Linker_Options.Table (From);
end Move_Linker_Option;
----------------------------
-- Resolve_Binder_Options --
----------------------------
procedure Resolve_Binder_Options is
begin
for E in Elab_Order.First .. Elab_Order.Last loop
Get_Name_String (Units.Table (Elab_Order.Table (E)).Uname);
-- The procedure of looking for specific packages and setting
-- flags is very wrong, but there isn't a good alternative at
-- this time.
if Name_Buffer (1 .. 19) = "system.os_interface" then
With_GNARL := True;
end if;
if Hostparm.OpenVMS and then Name_Buffer (1 .. 3) = "dec" then
With_DECGNAT := True;
end if;
end loop;
end Resolve_Binder_Options;
--------------
-- Set_Char --
--------------
procedure Set_Char (C : Character) is
begin
Last := Last + 1;
Statement_Buffer (Last) := C;
end Set_Char;
-------------
-- Set_Int --
-------------
procedure Set_Int (N : Int) is
begin
if N < 0 then
Set_String ("-");
Set_Int (-N);
else
if N > 9 then
Set_Int (N / 10);
end if;
Last := Last + 1;
Statement_Buffer (Last) :=
Character'Val (N mod 10 + Character'Pos ('0'));
end if;
end Set_Int;
---------------------------
-- Set_Main_Program_Name --
---------------------------
procedure Set_Main_Program_Name is
begin
-- Note that name has %b on the end which we ignore
-- First we output the initial _ada_ since we know that the main
-- program is a library level subprogram.
Set_String ("_ada_");
-- Copy name, changing dots to double underscores
for J in 1 .. Name_Len - 2 loop
if Name_Buffer (J) = '.' then
Set_String ("__");
else
Set_Char (Name_Buffer (J));
end if;
end loop;
end Set_Main_Program_Name;
---------------------
-- Set_Name_Buffer --
---------------------
procedure Set_Name_Buffer is
begin
for J in 1 .. Name_Len loop
Set_Char (Name_Buffer (J));
end loop;
end Set_Name_Buffer;
----------------
-- Set_String --
----------------
procedure Set_String (S : String) is
begin
Statement_Buffer (Last + 1 .. Last + S'Length) := S;
Last := Last + S'Length;
end Set_String;
-------------------
-- Set_Unit_Name --
-------------------
procedure Set_Unit_Name is
begin
for J in 1 .. Name_Len - 2 loop
if Name_Buffer (J) /= '.' then
Set_Char (Name_Buffer (J));
else
Set_String ("__");
end if;
end loop;
end Set_Unit_Name;
---------------------
-- Set_Unit_Number --
---------------------
procedure Set_Unit_Number (U : Unit_Id) is
Num_Units : constant Nat := Nat (Units.Table'Last) - Nat (Unit_Id'First);
Unum : constant Nat := Nat (U) - Nat (Unit_Id'First);
begin
if Num_Units >= 10 and then Unum < 10 then
Set_Char ('0');
end if;
if Num_Units >= 100 and then Unum < 100 then
Set_Char ('0');
end if;
Set_Int (Unum);
end Set_Unit_Number;
------------
-- Tab_To --
------------
procedure Tab_To (N : Natural) is
begin
while Last < N loop
Set_Char (' ');
end loop;
end Tab_To;
-----------
-- Value --
-----------
function Value (chars : chars_ptr) return String is
function Strlen (chars : chars_ptr) return Natural;
pragma Import (C, Strlen);
begin
if chars = Null_Address then
return "";
else
declare
subtype Result_Type is String (1 .. Strlen (chars));
Result : Result_Type;
for Result'Address use chars;
begin
return Result;
end;
end if;
end Value;
----------------------
-- Write_Info_Ada_C --
----------------------
procedure Write_Info_Ada_C (Ada : String; C : String; Common : String) is
begin
if Ada_Bind_File then
declare
S : String (1 .. Ada'Length + Common'Length);
begin
S (1 .. Ada'Length) := Ada;
S (Ada'Length + 1 .. S'Length) := Common;
WBI (S);
end;
else
declare
S : String (1 .. C'Length + Common'Length);
begin
S (1 .. C'Length) := C;
S (C'Length + 1 .. S'Length) := Common;
WBI (S);
end;
end if;
end Write_Info_Ada_C;
----------------------------
-- Write_Statement_Buffer --
----------------------------
procedure Write_Statement_Buffer is
begin
WBI (Statement_Buffer (1 .. Last));
Last := 0;
end Write_Statement_Buffer;
procedure Write_Statement_Buffer (S : String) is
begin
Set_String (S);
Write_Statement_Buffer;
end Write_Statement_Buffer;
end Bindgen;
|
with Picosystem.Pins;
with RP.Clock;
with RP.Timer;
with RP.GPIO;
with Picosystem.LED;
package body Sound is
use RP.Timer;
use RP.PWM;
P : constant PWM_Point := To_PWM (Picosystem.Pins.AUDIO);
Stop_At : Time := Time'First;
Playing : Boolean := False;
procedure Initialize is
use RP.GPIO;
begin
if not RP.PWM.Initialized then
RP.PWM.Initialize;
end if;
Set_Mode (P.Slice, Free_Running);
Set_Divider (P.Slice, Divider'Last);
Set_Duty_Cycle (P.Slice, P.Channel, 0);
Enable (P.Slice);
Picosystem.Pins.AUDIO.Configure (Output, Floating, RP.GPIO.PWM);
end Initialize;
procedure Update is
begin
if Playing then
Picosystem.LED.Set_Color (16#FF0000#);
else
Picosystem.LED.Set_Color (16#00FF00#);
end if;
if Playing and then Clock >= Stop_At then
Stop;
end if;
end Update;
function Is_Playing
return Boolean
is (Playing);
procedure Play
(Note : Notes;
Octave : Octaves;
Length : Milliseconds)
is
use type RP.PWM.Period;
Div : constant RP.PWM.Divider := Lookup_Div (Octave);
Interval : constant RP.PWM.Period := Lookup_Interval (Octave, Note);
begin
Set_Divider (P.Slice, Div);
Set_Interval (P.Slice, Interval);
Set_Duty_Cycle (P.Slice, P.Channel, Interval / 1000); -- TODO volume control?
if Length = 0 then
Stop_At := Time'Last;
else
Stop_At := Clock + RP.Timer.Milliseconds (Length);
end if;
Playing := True;
end Play;
procedure Stop is
begin
RP.PWM.Set_Duty_Cycle (P.Slice, P.Channel, 0);
Playing := False;
end Stop;
end Sound;
|
-- Copyright (C) 2008-2011 Maciej Sobczak
-- Distributed under the Boost Software License, Version 1.0.
-- (See accompanying file LICENSE_1_0.txt or copy at
-- http://www.boost.org/LICENSE_1_0.txt)
package SOCI.Oracle is
--
-- Registers the Oracle backend so that it is ready for use
-- by the dynamic backend loader.
--
procedure Register_Factory_Oracle;
pragma Import (C, Register_Factory_Oracle,
"register_factory_oracle");
end SOCI.Oracle;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S Y S T E M . S O F T _ L I N K S . T A S K I N G --
-- --
-- B o d y --
-- --
-- Copyright (C) 2004-2020, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
pragma Style_Checks (All_Checks);
-- Turn off subprogram alpha ordering check, since we group soft link bodies
-- and dummy soft link bodies together separately in this unit.
with Ada.Exceptions;
with Ada.Exceptions.Is_Null_Occurrence;
with System.Task_Primitives.Operations;
with System.Tasking;
with System.Stack_Checking;
with System.Secondary_Stack;
package body System.Soft_Links.Tasking is
package STPO renames System.Task_Primitives.Operations;
package SSL renames System.Soft_Links;
use Ada.Exceptions;
use type System.Secondary_Stack.SS_Stack_Ptr;
use type System.Tasking.Task_Id;
use type System.Tasking.Termination_Handler;
----------------
-- Local Data --
----------------
Initialized : Boolean := False;
-- Boolean flag that indicates whether the tasking soft links have
-- already been set.
-----------------------------------------------------------------
-- Tasking Versions of Services Needed by Non-Tasking Programs --
-----------------------------------------------------------------
function Get_Jmpbuf_Address return Address;
procedure Set_Jmpbuf_Address (Addr : Address);
-- Get/Set Jmpbuf_Address for current task
function Get_Sec_Stack return SST.SS_Stack_Ptr;
procedure Set_Sec_Stack (Stack : SST.SS_Stack_Ptr);
-- Get/Set location of current task's secondary stack
procedure Timed_Delay_T (Time : Duration; Mode : Integer);
-- Task-safe version of SSL.Timed_Delay
procedure Task_Termination_Handler_T (Excep : SSL.EO);
-- Task-safe version of the task termination procedure
function Get_Stack_Info return Stack_Checking.Stack_Access;
-- Get access to the current task's Stack_Info
--------------------------
-- Soft-Link Get Bodies --
--------------------------
function Get_Jmpbuf_Address return Address is
begin
return STPO.Self.Common.Compiler_Data.Jmpbuf_Address;
end Get_Jmpbuf_Address;
function Get_Sec_Stack return SST.SS_Stack_Ptr is
begin
return Result : constant SST.SS_Stack_Ptr :=
STPO.Self.Common.Compiler_Data.Sec_Stack_Ptr
do
pragma Assert (Result /= null);
end return;
end Get_Sec_Stack;
function Get_Stack_Info return Stack_Checking.Stack_Access is
begin
return STPO.Self.Common.Compiler_Data.Pri_Stack_Info'Access;
end Get_Stack_Info;
--------------------------
-- Soft-Link Set Bodies --
--------------------------
procedure Set_Jmpbuf_Address (Addr : Address) is
begin
STPO.Self.Common.Compiler_Data.Jmpbuf_Address := Addr;
end Set_Jmpbuf_Address;
procedure Set_Sec_Stack (Stack : SST.SS_Stack_Ptr) is
begin
STPO.Self.Common.Compiler_Data.Sec_Stack_Ptr := Stack;
end Set_Sec_Stack;
-------------------
-- Timed_Delay_T --
-------------------
procedure Timed_Delay_T (Time : Duration; Mode : Integer) is
Self_Id : constant System.Tasking.Task_Id := STPO.Self;
begin
-- In case pragma Detect_Blocking is active then Program_Error
-- must be raised if this potentially blocking operation
-- is called from a protected operation.
if System.Tasking.Detect_Blocking
and then Self_Id.Common.Protected_Action_Nesting > 0
then
raise Program_Error with "potentially blocking operation";
else
Abort_Defer.all;
STPO.Timed_Delay (Self_Id, Time, Mode);
Abort_Undefer.all;
end if;
end Timed_Delay_T;
--------------------------------
-- Task_Termination_Handler_T --
--------------------------------
procedure Task_Termination_Handler_T (Excep : SSL.EO) is
Self_Id : constant System.Tasking.Task_Id := STPO.Self;
Cause : System.Tasking.Cause_Of_Termination;
EO : Ada.Exceptions.Exception_Occurrence;
begin
-- We can only be here because we are terminating the environment task.
-- Task termination for all other tasks is handled in the Task_Wrapper.
-- We do not want to enable this check and e.g. call System.OS_Lib.Abort
-- here because some restricted run-times may not have System.OS_Lib
-- and calling abort may do more harm than good to the main application.
pragma Assert (Self_Id = STPO.Environment_Task);
-- Normal task termination
if Is_Null_Occurrence (Excep) then
Cause := System.Tasking.Normal;
Ada.Exceptions.Save_Occurrence (EO, Ada.Exceptions.Null_Occurrence);
-- Abnormal task termination
elsif Exception_Identity (Excep) = Standard'Abort_Signal'Identity then
Cause := System.Tasking.Abnormal;
Ada.Exceptions.Save_Occurrence (EO, Ada.Exceptions.Null_Occurrence);
-- Termination because of an unhandled exception
else
Cause := System.Tasking.Unhandled_Exception;
Ada.Exceptions.Save_Occurrence (EO, Excep);
end if;
-- There is no need for explicit protection against race conditions for
-- this part because it can only be executed by the environment task
-- after all the other tasks have been finalized. Note that there is no
-- fall-back handler which could apply to this environment task because
-- it has no parents, and, as specified in ARM C.7.3 par. 9/2, "the
-- fall-back handler applies only to the dependent tasks of the task".
if Self_Id.Common.Specific_Handler /= null then
Self_Id.Common.Specific_Handler.all (Cause, Self_Id, EO);
end if;
end Task_Termination_Handler_T;
-----------------------------
-- Init_Tasking_Soft_Links --
-----------------------------
procedure Init_Tasking_Soft_Links is
begin
-- Set links only if not set already
if not Initialized then
-- Mark tasking soft links as initialized
Initialized := True;
-- The application being executed uses tasking so that the tasking
-- version of the following soft links need to be used.
SSL.Get_Jmpbuf_Address := Get_Jmpbuf_Address'Access;
SSL.Set_Jmpbuf_Address := Set_Jmpbuf_Address'Access;
SSL.Get_Sec_Stack := Get_Sec_Stack'Access;
SSL.Get_Stack_Info := Get_Stack_Info'Access;
SSL.Set_Sec_Stack := Set_Sec_Stack'Access;
SSL.Timed_Delay := Timed_Delay_T'Access;
SSL.Task_Termination_Handler := Task_Termination_Handler_T'Access;
-- No need to create a new secondary stack, since we will use the
-- default one created in s-secsta.adb.
SSL.Set_Sec_Stack (SSL.Get_Sec_Stack_NT);
SSL.Set_Jmpbuf_Address (SSL.Get_Jmpbuf_Address_NT);
end if;
pragma Assert (Get_Sec_Stack /= null);
end Init_Tasking_Soft_Links;
end System.Soft_Links.Tasking;
|
-----------------------------------------------------------------------
-- package body Extended_Real.IO, translations between extended precision and text
-- Copyright (C) 2008-2018 Jonathan S. Parker
--
-- 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.
---------------------------------------------------------------------------
-- Test for E_Real_Machine_Emax etc
package body Extended_Real.IO is
-- The following are some global constant sets for ASCII to e_Real
-- Translation.
Is_Numeral : constant Set
:= Set'('0'..'9' => True, others => False);
Is_Sign : constant Set
:= Set'('-' | '+' => True, others => False);
Is_Decimal_Pt : constant Set
:= Set'('.' => True, others => False);
-- A Chunk is a digit in Radix 10**6, which is the radix of decimal
-- number we're translating the binary number into..6 decimal digits
-- at a time. The following are used by both the ASCII to e_Real
-- and e_Real to ASCII routines.
type Chunk_Integer is range -2**31+1 .. 2**31-1;
Chunk : Chunk_Integer;
Chunk_Width : constant := No_Of_Decimal_Digits_Per_Chunk; -- up in spec.
Ten_To_The_Chunk_Width : constant E_Digit
:= Make_E_Digit (10.0**Chunk_Width);
-- The following are for translating the exponent to a string.
-- Exp_String is used by both "e_Real_Image" and "Exp_Image"
Exp_String_Width : constant Positive := E_Integer'Width;
-- Should include space for the sign.
subtype Exp_String is String (1..Exp_String_Width);
Exp_Full_Text : Exp_String := (others => ' ');
Log_Base_10_Of_2 : constant := 0.3010299956639812;
Zero : constant e_Real := +0.0;
Ten : constant e_Real := +10.0;
---------------
-- Exp_Image --
---------------
-- Also returns the sign of Exp_Val: either '+' or '-'.
-- Uses fact that first char of E_Integer'Image is ' ' or '-'.
-- Left justifies the digits of the Exp in a field of blanks.
-- Another option is to right justify in a field of 0's.
function Exp_Image (Exp_Val : E_Integer) return Exp_String is
Result : Exp_String := (others => ' ');
E_String : constant String := E_Integer'Image (Exp_Val);
begin
Result (1..E_String'Length) := E_String;
if Result(1) = ' ' then
Result(1) := '+';
end if;
return Result;
end Exp_Image;
------------------------------
-- Count_of_Trailing_Blanks --
------------------------------
function Count_of_Trailing_Blanks (Exp : Exp_String) return Integer is
cnt : Integer := 0;
begin
for i in reverse 1..Exp_String'Length loop
if Exp(i) = ' ' then
cnt := cnt + 1;
else
exit;
end if;
end loop;
return cnt;
end Count_of_Trailing_Blanks;
------------------
-- e_Real_Image --
------------------
-- Extended Real (e_Real) to Text translation
function e_Real_Image
(X : in e_Real;
Aft : in Positive := Positive'Last)
return String
is
-- Make strings that are large enough to return any desired
-- result that is inside the bounds stated in the spec. The
-- extra chunk is there to fill in for lost digits due to leading
-- zeros.
Max_Result_Length : constant Positive
:= Max_Practical_String_Length + 2*Chunk_Width + Exp_String_Width + 3;
subtype Result_String is String(1..Max_Result_Length);
Result : Result_String := (others => ' ');
Mantissa_String : Result_String := (others => '0');
Sign : Character := ' '; -- init important.
Mantissa_Length : Positive;
Result_Length : Positive;
Exp_Stripped_Length : Integer;
-- Types for translating from extended e_Real to Decimal.
Exp_Base_2 : Real;
Exp_Base_10_Shift : Real;
Exp_Shift, Exp_Val : E_Integer;
I_Exp_Shift : Integer;
Leading_Zeros : Natural;
Y : e_Real := Abs (X);
Leading_Chunk, Trailing_Chunks : e_Real;
Stage_Last : Positive; -- Initialized in Step 0.
-- Read global memory Mantissa_Length.
-- Update global memory "Mantissa_String". Right justify
-- Chunk_Integer'Image(Chunk). Use fact that Mantissa_String is
-- initialized all '0', so no need to add '0's to the left of the
-- right justified Chunk_Integer'Image(Chunk). Recall Mantissa_..
-- allows an extra chunk at the end to adjust for removal of leading
-- zeros.
procedure Add_To_Mantissa_String (Chunk : Chunk_Integer;
Stage : Positive) is
Ascii_Chunk : constant String := Chunk_Integer'Image (Chunk);
Len : constant Integer := Ascii_Chunk'Length;
Start, Ending : Integer;
begin
Start := (Stage - Positive'First + 1)*Chunk_Width - Len + 2;
Ending := (Stage - Positive'First + 1)*Chunk_Width;
-- Right justifies digits in a field of '0's.
if Start > Mantissa_Length + 2*Chunk_Width then
return;
end if;
if Ending > Mantissa_Length + 2*Chunk_Width then
Ending := Mantissa_Length + 2*Chunk_Width;
end if;
Mantissa_String (Start..Ending) := Ascii_Chunk(2..Ending-Start+2);
-- Ascii_Chunk always starts with ' ' or '-'. Here it's always positive.
-- Its min length (Len) is always 2, even if chunk = '0'.
end Add_To_Mantissa_String;
begin
-- STEP 0-. Special cases. Zero and Infinity.
if Are_Equal (X, Zero) then
return "0.0";
end if;
if Are_Equal (X, Positive_Infinity) then
return "+inf";
end if;
if Are_Equal (X, Negative_Infinity) then
return "-inf";
end if;
-- STEP 0. Determine number of decimal digits in Mantissa.
-- Its Min (Aft+1, Max_No_Of_Digits, and Max_Practical_String_Length).
-- It may not be less than 12.
if Aft = Positive'Last then
Mantissa_Length := Aft; -- Positive'Last is the upper limit.
else
Mantissa_Length := Aft + 1; -- the usual case.
end if;
if Mantissa_Length < 13 then Mantissa_Length := 13; end if;
if Mantissa_Length > Max_No_Of_Digits then
Mantissa_Length := Max_No_Of_Digits;
end if;
if Mantissa_Length > Max_Practical_String_Length then
Mantissa_Length := Max_Practical_String_Length;
end if;
Stage_Last := (Mantissa_Length - 1) / Chunk_Width + 3;
-- This is ceiling (Mantissa_Length / Chunk_Width) + 1. (+ 2 really)
-- This is the number of steps required to strip digits of number
-- Mantissa_Length from the e_Real in chunks of Chunk_Width. The
-- extra 2 chunk2 are usually required to fill in for digits lost due
-- to leading zeros in the first chunk. (Normalization of the decimal
-- representation.)
-- STEP 1. Multiply Item by a power of 10.0 to make it less than 1.0.
-- Why a power of ten? Cause then we can shift the final Radix 10 exp
-- by exactly the value of the exponent. The formula is
-- Shift = -Ceiling (Log_Base_10_Of_2 * Exp_Base_2)
-- Exp_Base_2 is the normalized exp: i.e. 2**(-Exp_Base_2) * Item
-- is slightly less than 1. But we want a power of 10 with this property,
-- not a power of 2. 10**(-N) = 2**(-Exp_Base_2) implies
-- N = Log_Base_10_Of_2 * Exp_Base_2, except that we must make N the
-- appropriate nearest integer. If we do that by rounding N up (taking
-- the ceiling) then 10**(-N) < 2**(-Exp_Base_2) which implies that
-- 10**(-N) * X < 2**(-Exp_Base_2) * X, so 10**(-N) * X < 1.0,
-- as required.
Exp_Base_2 := Real (No_Of_Bits_In_Radix) * Real (Exponent (X));
Exp_Base_10_Shift := -Real'Ceiling (Log_Base_10_Of_2 * Exp_Base_2);
I_Exp_Shift := Integer (Exp_Base_10_Shift);
Exp_Shift := E_Integer (Exp_Base_10_Shift);
-- STEP 2. Multiplying X by 10**Shift will make it less than 1.
-- Want to multiply Item by 10**(6 + Shift) to get no more than 6 decimal
-- digits sticking out to the left of the decimal point (and often 0),
-- because we're stripping 6 decimal digits at a time from the left of the
-- decimal point with the truncate function. Remember Y := Abs(X).
-- Loop translates Y into Radix 10**6.
-- Each Chunk is a digit in Radix 10**6.
Y := Ten ** (No_Of_Decimal_Digits_Per_Chunk + I_Exp_Shift) * Y;
-- Y := Machine(Y);
-- Machine would round away all guard digits.
for Stage in 1..Stage_Last loop
Leading_Chunk := Truncation (Y);
Trailing_Chunks := Y - Leading_Chunk;
Chunk := Chunk_Integer (Make_Real (Leading_Chunk));
Add_To_Mantissa_String (Chunk, Stage);
Y := Ten_To_The_Chunk_Width * Trailing_Chunks;
-- Shift another 6 decimal digits to the left of the decimal point.
end loop;
-- STEP 3. Construct the string. Get leading sign. Strip away leading
-- Zeros. Exp is the amount we shifted by above, adjusted for stripped
-- leading zeros. (ie, move decimal point to right of leading zeros
-- and 1st non-zero digit; decrement Exp by 1 for each leading zero etc.)
if X < Zero then
Sign := '-';
end if;
-- Set the sign. Sign is initialized ' '. Recall Y = Abs(X).
-- Count leading zeros:
Leading_Zeros := 0;
for I in 1..20 loop -- Should be no more than 8 if digit 1..10^9.
if Mantissa_String (I) /= '0' then
exit;
else
Leading_Zeros := Leading_Zeros + 1;
end if;
end loop;
-- Right now the virtual decimal point sits to the left of every digit
-- in Mantissa_String, and the Exponent is given by -Shift. We want
-- to shift the decimal point to the right of each leading zero, and to
-- the right of the first non-zero digit. Then DECREASE the exponent
-- by that shift.
Exp_Val := -Exp_Shift - (1 + E_Integer(Leading_Zeros));
-- the 1 accounts for the 1st non-zero digit to the left of decimal point.
Exp_Full_Text := Exp_Image (Exp_Val);
Exp_Stripped_Length := Exp_String_Width - Count_of_Trailing_Blanks (Exp_Full_Text);
Result_Length := Mantissa_Length + Exp_Stripped_Length + 3;
Result(1..Result_Length) :=
Sign & Mantissa_String (1+Leading_Zeros) & '.'
& Mantissa_String (2+Leading_Zeros..Mantissa_Length+Leading_Zeros)
& 'E' & Exp_Full_Text (1..Exp_Stripped_Length);
return Result(1..Result_Length);
end e_Real_Image;
----------------------
-- Integer_Value_Of --
----------------------
-- Assumes that a decimal point is immediately to the right of the last digit.
-- Translate each chunk (Digit_n) of 8 decimal digits into e_Real, and sum
-- the polynomial in powers of 10**8. (Do it this way because we can then
-- use E_Digit*e_Real operations for efficiency.) Horner's rule is
--
-- Digit_0 + 10**8*(Digit_1 + 10**8*(Digit_2 + ... + 10**8*(Digit_n)))))
--
-- Below, the 10**8 is called Ten_To_The_Chunk_Width. It's a Global constant.
-- IMPORTANT to return ZERO if string has 0 length. e_Real_Val requires it.
function Integer_Value_Of (F : String) return e_Real is
Result, Digit_i : e_Real; -- initialized to zero. (Important).
No_Of_Full_Chunk_Iterations : Natural;
First_Partial_Chunk_Width : Natural;
Start, Ending : Integer;
begin
if F'Length = 0 then
return Zero;
end if;
No_Of_Full_Chunk_Iterations := F'Length / Chunk_Width;
First_Partial_Chunk_Width := F'Length MOD Chunk_Width;
-- Special case for highest order Digit_i, the one of width
-- First_Partial_Chunk_Width. If this partial chunk is the only
-- chunk (ie., No_Of_Full_Chunk_Iterations = 0) then there is no
-- multiplication of the result by 10**8. (See formula above.)
if First_Partial_Chunk_Width > 0 then
Start := F'First;
Ending := F'First + First_Partial_Chunk_Width - 1;
Digit_i := +Real (Chunk_Integer'Value (F(Start..Ending)));
if No_Of_Full_Chunk_Iterations > 0 then
Result := Ten_To_The_Chunk_Width * Digit_i;
else
Result := Digit_i;
end if;
end if;
-- Do the lower order Digits_i's. The lowest order Digit_i has no
-- 10**8 multiplied by it.
for i in 0..No_Of_Full_Chunk_Iterations-1 loop
Start := F'First + First_Partial_Chunk_Width + i * Chunk_Width;
Ending := Start + Chunk_Width - 1;
Digit_i := +Real (Chunk_Integer'Value (F(Start..Ending)));
if i < No_Of_Full_Chunk_Iterations-1 then
Result := Ten_To_The_Chunk_Width * (Result + Digit_i);
else
Result := Result + Digit_i;
end if;
end loop;
return Result;
end Integer_Value_Of;
-------------------------
-- Fractional_Value_Of --
-------------------------
-- Assumes that a decimal point is immediately to the left of the 1st digit.
-- IMPORTANT to return ZERO if string has 0 length. e_Real_Val requires it.
--
function Fractional_Value_Of (F : String) return e_Real is
Result : e_Real;
begin
if F'Length = 0 then
return Zero;
end if;
Result := Integer_Value_Of(F);
-- We have Val as though decimal point were to the right of all digits.
-- Want it to the left of all digits: just multiply by Ten**(-F'Length)
-- We do it this way so can use efficiency of E_Digit*e_Real in routine
-- Integer_Value_Of. But many possible optimizations are neglected.
-- If performance is an issue, then maybe try e_Real / E_Digit method
-- where E_Digit = 10**8.
Result := Result * Ten**(-F'Length);
return Result;
end Fractional_Value_Of;
----------------
-- e_Real_Val --
----------------
-- Accepts the following formats:
-- INTEGER : 1234567
-- DECIMAL : 12.34567 or -.1234567 or 1234567.
-- EXPONENTIAL : 1234.567E+002 or .1234567E2 or 123467.E-03
-- NON_DECIMAL_EXPONENTIAL : -1234567E-003
--
-- Notice that
-- 1) The Decimal point may be anywhere to the left of the E.
-- 2) The Leading sign is optional if it's '+'.
-- 3) The sign of the exponent is optional if it's '+'.
--
-- Start_Of_Num is the first non-white space. If the first char of the
-- string is not white-space, then this will be Start_Of_Num. End_Of_Num
-- is the non-white char just before the start of more white-space. BUT if
-- the string comes to an end before any white-space re-appears, then the
-- end of the string is taken as End_Of_Num.
--
procedure e_Real_Val
(X : in String;
Y : out e_Real;
Last : out Natural)
is
No_Of_Decimal_Pts, No_Of_Exp_Symbols, No_Of_Exp_Signs : Natural := 0;
Decimal_Pt_Exists, Exp_Symbol_Exists, Exp_Sign_Exists : Boolean := False;
Leading_Sign_Exists : Boolean := False;
Decimal_Pt_Pos, Exp_Symbol_Pos, Exp_Sign_Pos : Positive;
Start_Of_Aft : Positive;
Num_Is_Positive : Boolean;
Char : Character;
type Format is
(Int, Decimal_Pt_Only, Exponential, No_Decimal_Pt_Exponential);
The_Format : Format;
Start_Of_Num, End_Of_Num, Start_Of_Exp : Natural := 0;
Fore_Width, Aft_Width, Exp_Width : Natural := 0;
Exp_Str : Exp_String := (others => ' ');
Exp_Val : Integer := 0;
Fore, Aft, Result : e_Real;
begin
-- Handle null strings:
if X'Length = 0 then
raise E_Format_Error;
end if;
-- STEP 1. Strip away leading whitespace and sign. Start_Of_Num is the
-- first non-white space character. If it's '-' or '+', then increment
-- Start_Of_Num by 1.
for I in X'Range loop
if not Is_White_Space (X(I)) then
Start_Of_Num := I;
exit;
end if;
end loop;
if Start_Of_Num = 0 then -- The string is all white-space, so:
raise E_Format_Error;
end if;
-- If there is a leading sign, make a note of it, and then bypass it.
Num_Is_Positive := True; -- No sign means positive
Char := X(Start_Of_Num);
if Is_Sign (Char) then
Start_Of_Num := Start_Of_Num + 1;
Leading_Sign_Exists := True;
if Char = '+' then
Num_Is_Positive := True;
elsif Char = '-' then
Num_Is_Positive := False;
end if;
end if;
if Leading_Sign_Exists and then Start_Of_Num > X'Last then
raise E_Format_Error;
end if;
-- when we incremented Start_Of_Num, we went beyond X'Last. So only char
-- is the Sign.
-- STEP 2. Scan everything beyond the leading sign. End_Of_Num is
-- initialized to 0. Here is where we update it.
for I in Start_Of_Num..X'Last loop
Char := X(I);
if Is_White_Space (Char) then -- we know Start.. points to non-whitespace
End_Of_Num := I-1;
exit;
end if;
if Is_Decimal_Pt (Char) then
Decimal_Pt_Exists := True;
Decimal_Pt_Pos := I;
No_Of_Decimal_Pts := No_Of_Decimal_Pts + 1;
elsif Is_Exp_Symbol (Char) then
Exp_Symbol_Exists := True;
Exp_Symbol_Pos := I;
No_Of_Exp_Symbols := No_Of_Exp_Symbols + 1;
elsif Is_Sign (Char) then
Exp_Sign_Exists := True;
Exp_Sign_Pos := I;
No_Of_Exp_Signs := No_Of_Exp_Signs + 1;
elsif not Is_Numeral (Char) then
raise E_Format_Error;
end if;
end loop;
if End_Of_Num = 0 then -- Reached the end of string w/o detecting whitespace
End_Of_Num := X'Last;
end if;
-- Do some error checking:
if No_Of_Decimal_Pts > 1 then
raise E_Format_Error;
end if;
if No_Of_Exp_Signs > 1 then
raise E_Format_Error;
end if;
if No_Of_Exp_Symbols > 1 then
raise E_Format_Error;
end if;
if Decimal_Pt_Exists and Exp_Symbol_Exists then
if Decimal_Pt_Pos >= Exp_Symbol_Pos then
raise E_Format_Error;
end if;
end if;
-- if there's an 'E' and a '+', then the sign must directly follow the
-- the 'E'. Neither can be at the beginning or end of the num. if the
-- sign exists, then 'E' must exist, but not vice-versa.
if Exp_Sign_Exists then
if Exp_Sign_Pos = End_Of_Num or else Exp_Sign_Pos = Start_Of_Num then
raise E_Format_Error;
end if;
end if;
if Exp_Symbol_Exists then
if Exp_Symbol_Pos = End_Of_Num or else Exp_Symbol_Pos = Start_Of_Num then
raise E_Format_Error;
end if;
end if;
if Exp_Sign_Exists and Exp_Symbol_Exists then
if not (Exp_Sign_Pos = Exp_Symbol_Pos + 1) then
raise E_Format_Error;
end if;
end if;
if Exp_Sign_Exists and not Exp_Symbol_Exists then
raise E_Format_Error;
end if;
-- Diagnose the format of the number:
if (not Decimal_Pt_Exists) and (not Exp_Symbol_Exists) then
The_Format := Int;
elsif Decimal_Pt_Exists and (not Exp_Symbol_Exists) then
The_Format := Decimal_Pt_Only;
elsif Decimal_Pt_Exists and Exp_Symbol_Exists then
The_Format := Exponential;
else
The_Format := No_Decimal_Pt_Exponential;
end if;
-- STEP 3. Do the arithmetic. The string goes like Fore . Aft E Exp,
-- in the most general case. The following is not really optimized
-- for speed.
case The_Format is
when Int =>
Fore_Width := End_Of_Num - Start_Of_Num + 1;
if Fore_Width = 0 then
raise E_Format_Error;
end if;
Result := Integer_Value_Of(X (Start_Of_Num..End_Of_Num));
when Decimal_Pt_Only =>
Fore_Width := Decimal_Pt_Pos - Start_Of_Num;
Aft_Width := End_Of_Num - Decimal_Pt_Pos;
Start_Of_Aft := Decimal_Pt_Pos + 1;
if Fore_Width = 0 and Aft_Width = 0 then
raise E_Format_Error;
end if;
-- Notice that Fore or Aft may be 0. The funcs below return
-- 0.0 in that case.
Fore := Integer_Value_Of (X (Start_Of_Num..Start_Of_Num + Fore_Width - 1));
Aft := Fractional_Value_Of (X (Start_Of_Aft..Start_Of_Aft + Aft_Width - 1));
Result := Fore + Aft;
when Exponential =>
if Exp_Sign_Exists then
Start_Of_Exp := Exp_Sign_Pos + 1;
else
Start_Of_Exp := Exp_Symbol_Pos + 1;
end if;
Start_Of_Aft := Decimal_Pt_Pos + 1;
Fore_Width := Decimal_Pt_Pos - Start_Of_Num;
Aft_Width := Exp_Symbol_Pos - Start_Of_Aft;
Exp_Width := End_Of_Num - Start_Of_Exp + 1;
if Exp_Width = 0 then
raise E_Format_Error;
end if;
if Exp_Width > Integer'Width then
-- E_Integer is derived Integer. Both Integer and E_Integer are much
-- wider than the allowed range of Exponents, so Contraint-Error will
-- be raised in the arithmetic package, not here.
raise E_Format_Error;
end if;
if Fore_Width = 0 and Aft_Width = 0 then
raise E_Format_Error;
end if;
-- Notice that Fore or Aft may be 0. The funcs below return
-- 0.0 in that case.
Fore := Integer_Value_Of (X (Start_Of_Num..Start_Of_Num + Fore_Width - 1));
Aft := Fractional_Value_Of (X (Start_Of_Aft..Start_Of_Aft + Aft_Width - 1));
Exp_Str(1..Exp_Width) := X (Start_Of_Exp..Start_Of_Exp + Exp_Width - 1);
Exp_Val := Integer'Value(Exp_Str);
if Exp_Sign_Exists and then X(Exp_Sign_Pos) = '-' then
Exp_Val := -Exp_Val;
end if;
Result := (Fore + Aft) * Ten**Exp_Val;
when No_Decimal_Pt_Exponential =>
-- unusual case. Say there's no Aft, only Fore
if Exp_Sign_Exists then
Start_Of_Exp := Exp_Sign_Pos + 1;
else
Start_Of_Exp := Exp_Symbol_Pos + 1;
end if;
Fore_Width := Exp_Symbol_Pos - Start_Of_Num;
Exp_Width := End_Of_Num - Start_Of_Exp + 1;
if Fore_Width = 0 then
raise E_Format_Error;
end if;
if Exp_Width = 0 then
raise E_Format_Error;
end if;
if Exp_Width > Integer'Width then
raise E_Format_Error;
end if;
Fore := Integer_Value_Of (X (Start_Of_Num..Start_Of_Num + Fore_Width - 1));
Exp_Str(1..Exp_Width) := X (Start_Of_Exp..Start_Of_Exp + Exp_Width - 1);
Exp_Val := Integer'Value(Exp_Str);
if Exp_Sign_Exists and then X(Exp_Sign_Pos) = '-' then
Exp_Val := -Exp_Val;
end if;
Result := Fore * Ten**Exp_Val;
end case;
-- update the 2 out parameters:
if Num_Is_Positive then
Y := Result;
else
Y := -Result;
end if;
Last := End_Of_Num;
end e_Real_Val;
end Extended_Real.IO;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
-----------------------------------------------------------------------------
-- Common types
--
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded;
package Types is
type Job_Id is new Long_Integer; -- Interfaces.Integer_64;
package US renames Ada.Strings.Unbounded;
type Job_Desc is
record
Id : Types.Job_Id;
Title : US.Unbounded_String;
end record;
type Job_Index is new Positive;
package Job_Sets is
new Ada.Containers.Vectors (Job_Index, Job_Desc);
type Job_Info is
record
Title : US.Unbounded_String;
Parent : Types.Job_Id;
Owner : US.Unbounded_String;
end record;
end Types;
|
package ACO.Protocols.Network_Management.Slaves is
type Slave
(Id : ACO.Messages.Node_Nr;
Od : not null access ACO.OD.Object_Dictionary'Class)
is new NMT with private;
private
type Slave
(Id : ACO.Messages.Node_Nr;
Od : not null access ACO.OD.Object_Dictionary'Class)
is new NMT (Id, Od) with null record;
end ACO.Protocols.Network_Management.Slaves;
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO; use Ada.Text_IO;
with Text_IO.Unbounded_IO; use Text_IO.Unbounded_IO;
--with Ada.Sequential_IO;
-- Temporär, ta bort när den inte behövs längre
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Ntest is
type MY_REC is
record
Age : INTEGER;
Sex : CHARACTER;
Initial : CHARACTER;
end record;
package Seq_IO is new Ada.Sequential_IO(MY_REC);
use Seq_IO;
Myself : MY_REC;
My_In_File : Seq_IO.FILE_TYPE;
begin
Open(My_In_File, In_File, "REG.BIN");
for Index in 1..100 loop
Read(My_In_File, Myself);
if Myself.Age >= 82 then
Put("Record number");
Put(Myself.Age, 4);
Put(" ");
Put(Myself.Sex);
Put(" ");
Put(Myself.Initial);
New_Line;
end if;
end loop;
Close(My_In_File);
end Ntest; |
with Taft_Type1_Pkg2;
package body Taft_Type1_Pkg1 is
type TAMT1 is new Taft_Type1_Pkg2.Priv (X => 1);
type TAMT2 is new Taft_Type1_Pkg2.Priv;
procedure Check is
Ptr1 : TAMT1_Access := new TAMT1;
Ptr2 : TAMT2_Access := new TAMT2 (X => 2);
begin
if Ptr1.all.X /= 1 then
raise Program_Error;
end if;
if Ptr2.all.X /= 2 then
raise Program_Error;
end if;
end;
end Taft_Type1_Pkg1;
|
-- Abstract :
--
-- Common utilities for Gen_Emacs_Wisi_*_Parse
--
-- Copyright (C) 2018 - 2019 Free Software Foundation, Inc.
--
-- This program is free software; you can redistribute it and/or
-- modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or (at
-- your option) any later version. This program is distributed in the
-- hope that it will be useful, but WITHOUT ANY WARRANTY; without even
-- the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-- PURPOSE. See the GNU General Public License for more details. You
-- should have received a copy of the GNU General Public License
-- distributed with this program; see file COPYING. If not, write to
-- the Free Software Foundation, 51 Franklin Street, Suite 500, Boston,
-- MA 02110-1335, USA.
pragma License (GPL);
with Ada.Strings.Unbounded;
with System;
with Wisi;
with WisiToken.Parse.LR.Parser;
package Emacs_Wisi_Common_Parse is
Protocol_Version : constant String := "4";
-- Protocol_Version defines the data sent between elisp and the
-- background process, except for the language-specific parameters,
-- which are defined by the Language_Protocol_Version parameter to
-- Parse_Stream, below.
--
-- This value must match wisi-process-parse.el
-- wisi-process-parse-protocol-version.
--
-- See wisi-process-parse.el functions, and this package body, for
-- the implementation of the protocol.
--
-- Only changes once per wisi release. Increment as soon as required,
-- record new version in NEWS-wisi.text.
Prompt : constant String := ";;> ";
Protocol_Error : exception;
Finish : exception;
procedure Usage (Name : in String);
procedure Read_Input (A : System.Address; N : Integer);
function Get_Command_Length return Integer;
function Get_String
(Source : in String;
Last : in out Integer)
return String;
function Get_Integer
(Source : in String;
Last : in out Integer)
return Integer;
type Process_Start_Params is record
Recover_Log_File_Name : Ada.Strings.Unbounded.Unbounded_String;
-- log enabled if non-empty.
end record;
function Get_Process_Start_Params return Process_Start_Params;
-- Get from Ada.Command_Line. Handles --help by outputing help,
-- raising Finish.
procedure Process_Stream
(Name : in String;
Language_Protocol_Version : in String;
Partial_Parse_Active : in out Boolean;
Params : in Process_Start_Params;
Parser : in out WisiToken.Parse.LR.Parser.Parser;
Parse_Data : in out Wisi.Parse_Data_Type'Class;
Descriptor : in WisiToken.Descriptor);
----------
-- Parse command
type Parse_Params is record
Post_Parse_Action : Wisi.Post_Parse_Action_Type;
Source_File_Name : Ada.Strings.Unbounded.Unbounded_String;
Begin_Byte_Pos : Integer;
-- Source file byte position of first char sent; start parse here.
End_Byte_Pos : Integer;
-- Byte position of last char sent.
Goal_Byte_Pos : Integer;
-- Byte position of end of desired parse region; terminate parse at
-- or after here.
Begin_Char_Pos : WisiToken.Buffer_Pos;
-- Char position of first char sent.
Begin_Line : WisiToken.Line_Number_Type;
End_Line : WisiToken.Line_Number_Type;
-- Line number of line containing Begin_Byte_Pos, End_Byte_Pos
Begin_Indent : Integer;
-- Indentation of Line_Begin
Partial_Parse_Active : Boolean;
Debug_Mode : Boolean;
Parse_Verbosity : Integer;
McKenzie_Verbosity : Integer;
Action_Verbosity : Integer;
McKenzie_Disable : Integer;
Task_Count : Integer;
Check_Limit : Integer;
Enqueue_Limit : Integer;
Max_Parallel : Integer;
Byte_Count : Integer;
-- Count of bytes of source file sent.
end record;
function Get_Parse_Params (Command_Line : in String; Last : in out Integer) return Parse_Params;
----------
-- Refactor command
type Refactor_Params is record
Refactor_Action : Positive; -- Language-specific
Source_File_Name : Ada.Strings.Unbounded.Unbounded_String;
Parse_Region : WisiToken.Buffer_Region;
-- Source file byte region to parse.
Edit_Begin : WisiToken.Buffer_Pos;
-- Source file byte position at start of expression to refactor.
Parse_Begin_Char_Pos : WisiToken.Buffer_Pos;
-- Char position of first char sent.
Parse_Begin_Line : WisiToken.Line_Number_Type;
Parse_End_Line : WisiToken.Line_Number_Type;
-- Line numbers of lines containing Parse_Begin_Byte_Pos, Parse_End_Byte_Pos
Debug_Mode : Boolean;
Parse_Verbosity : Integer;
Action_Verbosity : Integer;
Max_Parallel : Integer;
Byte_Count : Integer;
-- Count of bytes of source file sent.
end record;
function Get_Refactor_Params (Command_Line : in String; Last : in out Integer) return Refactor_Params;
end Emacs_Wisi_Common_Parse;
|
with System;
package Init2 is
type Small is mod 2**2;
for Small'Size use 2;
type Count is mod 2**9;
for Count'Size use 9;
type Arr1 is array (1 .. 3) of Count;
pragma Pack (Arr1);
for Arr1'Size use 27;
for Arr1'Scalar_Storage_Order use System.Low_Order_First;
type R1 is record
S1 : Small;
I : Integer;
S2 : Small;
A : Arr1;
B : Boolean;
end record;
for R1'Bit_Order use System.Low_Order_First;
for R1'Scalar_Storage_Order use System.Low_Order_First;
for R1 use record
S1 at 0 range 0 .. 1;
I at 0 range 2 .. 33;
S2 at 0 range 34 .. 35;
A at 0 range 36 .. 62;
B at 0 range 63 .. 63;
end record;
for R1'Size use 64;
type Arr2 is array (1 .. 3) of Count;
pragma Pack (Arr2);
for Arr2'Size use 27;
for Arr2'Scalar_Storage_Order use System.High_Order_First;
type R2 is record
S1 : Small;
I : Integer;
S2 : Small;
A : Arr2;
B : Boolean;
end record;
for R2'Bit_Order use System.High_Order_First;
for R2'Scalar_Storage_Order use System.High_Order_First;
for R2 use record
S1 at 0 range 0 .. 1;
I at 0 range 2 .. 33;
S2 at 0 range 34 .. 35;
A at 0 range 36 .. 62;
B at 0 range 63 .. 63;
end record;
for R2'Size use 64;
My_R1 : constant R1 := (S1 => 2,
I => 16#12345678#,
S2 => 1,
A => (16#AB#, 16#CD#, 16#EF#),
B => True);
My_R2 : constant R2 := (S1 => 2,
I => 16#12345678#,
S2 => 1,
A => (16#AB#, 16#CD#, 16#EF#),
B => True);
end Init2;
|
------------------------------------------------------------------------------
-- --
-- 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;
|
package Eu_Projects.Event_Names is
Begin_Name : constant Dotted_Identifier := To_Bounded_String ("begin");
End_Name : constant Dotted_Identifier := To_Bounded_String ("end");
Duration_Name : constant Dotted_Identifier := To_Bounded_String ("duration");
Event_Time_Name : constant Dotted_Identifier := To_Bounded_String ("when");
Default_Time : constant String := "default";
end Eu_Projects.Event_Names;
|
-- 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.Strings.Wide_Wide_Unbounded;
package Ada.Wide_Wide_Text_IO.Wide_Wide_Unbounded_IO is
procedure Put
(File : in File_Type;
Item : in Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
procedure Put
(Item : in Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
procedure Put_Line
(File : in File_Type;
Item : in Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
procedure Put_Line
(Item : in Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
function Get_Line
(File : in File_Type)
return Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String;
function Get_Line
return Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String;
procedure Get_Line
(File : in File_Type;
Item : out Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
procedure Get_Line
(Item : out Strings.Wide_Wide_Unbounded.Wide_Wide_Unbounded_String);
end Ada.Wide_Wide_Text_IO.Wide_Wide_Unbounded_IO;
|
-- The Village of Vampire by YT, このソースコードはNYSLです
with Ada.Strings.Unbounded;
procedure Vampire.R3.User_Page (
Output : not null access Ada.Streams.Root_Stream_Type'Class;
Form : in Forms.Root_Form_Type'Class;
Template : in String;
Summaries : in Tabula.Villages.Lists.Summary_Maps.Map;
User_Id : in String;
User_Password : in String;
User_Info : in Users.User_Info)
is
use type Ada.Strings.Unbounded.Unbounded_String;
use type Tabula.Villages.Village_State;
-- ユーザーの参加状況
Joined : aliased Ada.Strings.Unbounded.Unbounded_String;
Created : aliased Ada.Strings.Unbounded.Unbounded_String;
begin
for I in Summaries.Iterate loop
declare
V : Tabula.Villages.Lists.Village_Summary
renames Summaries.Constant_Reference (I);
begin
if V.State < Tabula.Villages.Epilogue then
for J in V.People.Iterate loop
if V.People.Constant_Reference (J) = User_Id then
if not Joined.Is_Null then
Ada.Strings.Unbounded.Append(Joined, "、");
end if;
Ada.Strings.Unbounded.Append(Joined, V.Name);
end if;
end loop;
if V.By = User_Id then
Created := V.Name;
end if;
end if;
end;
end loop;
declare
procedure Handle (
Output : not null access Ada.Streams.Root_Stream_Type'Class;
Tag : in String;
Contents : in Web.Producers.Template) is
begin
if Tag = "action_page" then
Forms.Write_Attribute_Name (Output, "action");
Forms.Write_Link (
Output,
Form,
Current_Directory => ".",
Resource => Forms.Self,
Parameters =>
Form.Parameters_To_User_Page (
User_Id => User_Id,
User_Password => User_Password));
elsif Tag = "userpanel" then
Handle_User_Panel (
Output,
Contents,
Form,
User_Id => User_Id,
User_Password => User_Password);
elsif Tag = "id" then
Forms.Write_In_HTML (Output, Form, User_Id);
elsif Tag = "joined" then
if not Joined.Is_Null then
declare
procedure Handle (
Output : not null access Ada.Streams.Root_Stream_Type'Class;
Tag : in String;
Contents : in Web.Producers.Template) is
begin
if Tag = "activevillage" then
Forms.Write_In_HTML (Output, Form, Joined.Constant_Reference);
else
Raise_Unknown_Tag (Tag);
end if;
end Handle;
begin
Web.Producers.Produce(Output, Contents, Handler => Handle'Access);
end;
end if;
elsif Tag = "nojoined" then
if Joined.Is_Null then
Web.Producers.Produce(Output, Contents);
end if;
elsif Tag = "created" then
if not Created.Is_Null then
declare
procedure Handle (
Output : not null access Ada.Streams.Root_Stream_Type'Class;
Tag : in String;
Contents : in Web.Producers.Template) is
begin
if Tag = "createdvillage" then
Forms.Write_In_HTML (Output, Form, Created.Constant_Reference);
else
Raise_Unknown_Tag (Tag);
end if;
end Handle;
begin
Web.Producers.Produce(Output, Contents, Handler => Handle'Access);
end;
end if;
elsif Tag = "creatable" then
if Joined.Is_Null and then Created.Is_Null then
Web.Producers.Produce(Output, Contents, Handler => Handle'Access); -- rec
end if;
elsif Tag = "href_index" then
Forms.Write_Attribute_Name (Output, "href");
Forms.Write_Link (
Output,
Form,
Current_Directory => ".",
Resource => Forms.Self,
Parameters =>
Form.Parameters_To_Index_Page (
User_Id => User_Id,
User_Password => User_Password));
else
Raise_Unknown_Tag (Tag);
end if;
end Handle;
begin
Web.Producers.Produce (Output, Read (Template), Handler => Handle'Access);
end;
end Vampire.R3.User_Page;
|
package body problem_13 is
function Solution_1( arr : Digit_50_Array ) return Int128 is
Higher, Lower: Int128 := 0;
Str_Len : constant Integer := arr(0)'Length;
begin
for I in arr'range loop
Lower := Lower + Int128'Value(arr(I)(Str_Len - 24 .. Str_Len));
Higher := Higher + Int128'Value(arr(I)(1 .. Str_Len - 25));
end loop;
Lower := Lower / (10**25);
Higher := Higher + Lower;
return (Higher / (10**17));
end Solution_1;
procedure Test_Solution_1 is
Solution : constant Int128 := 5537376230;
Input : Digit_50_Array := (
"37107287533902102798797998220837590246510135740250",
"46376937677490009712648124896970078050417018260538",
"74324986199524741059474233309513058123726617309629",
"91942213363574161572522430563301811072406154908250",
"23067588207539346171171980310421047513778063246676",
"89261670696623633820136378418383684178734361726757",
"28112879812849979408065481931592621691275889832738",
"44274228917432520321923589422876796487670272189318",
"47451445736001306439091167216856844588711603153276",
"70386486105843025439939619828917593665686757934951",
"62176457141856560629502157223196586755079324193331",
"64906352462741904929101432445813822663347944758178",
"92575867718337217661963751590579239728245598838407",
"58203565325359399008402633568948830189458628227828",
"80181199384826282014278194139940567587151170094390",
"35398664372827112653829987240784473053190104293586",
"86515506006295864861532075273371959191420517255829",
"71693888707715466499115593487603532921714970056938",
"54370070576826684624621495650076471787294438377604",
"53282654108756828443191190634694037855217779295145",
"36123272525000296071075082563815656710885258350721",
"45876576172410976447339110607218265236877223636045",
"17423706905851860660448207621209813287860733969412",
"81142660418086830619328460811191061556940512689692",
"51934325451728388641918047049293215058642563049483",
"62467221648435076201727918039944693004732956340691",
"15732444386908125794514089057706229429197107928209",
"55037687525678773091862540744969844508330393682126",
"18336384825330154686196124348767681297534375946515",
"80386287592878490201521685554828717201219257766954",
"78182833757993103614740356856449095527097864797581",
"16726320100436897842553539920931837441497806860984",
"48403098129077791799088218795327364475675590848030",
"87086987551392711854517078544161852424320693150332",
"59959406895756536782107074926966537676326235447210",
"69793950679652694742597709739166693763042633987085",
"41052684708299085211399427365734116182760315001271",
"65378607361501080857009149939512557028198746004375",
"35829035317434717326932123578154982629742552737307",
"94953759765105305946966067683156574377167401875275",
"88902802571733229619176668713819931811048770190271",
"25267680276078003013678680992525463401061632866526",
"36270218540497705585629946580636237993140746255962",
"24074486908231174977792365466257246923322810917141",
"91430288197103288597806669760892938638285025333403",
"34413065578016127815921815005561868836468420090470",
"23053081172816430487623791969842487255036638784583",
"11487696932154902810424020138335124462181441773470",
"63783299490636259666498587618221225225512486764533",
"67720186971698544312419572409913959008952310058822",
"95548255300263520781532296796249481641953868218774",
"76085327132285723110424803456124867697064507995236",
"37774242535411291684276865538926205024910326572967",
"23701913275725675285653248258265463092207058596522",
"29798860272258331913126375147341994889534765745501",
"18495701454879288984856827726077713721403798879715",
"38298203783031473527721580348144513491373226651381",
"34829543829199918180278916522431027392251122869539",
"40957953066405232632538044100059654939159879593635",
"29746152185502371307642255121183693803580388584903",
"41698116222072977186158236678424689157993532961922",
"62467957194401269043877107275048102390895523597457",
"23189706772547915061505504953922979530901129967519",
"86188088225875314529584099251203829009407770775672",
"11306739708304724483816533873502340845647058077308",
"82959174767140363198008187129011875491310547126581",
"97623331044818386269515456334926366572897563400500",
"42846280183517070527831839425882145521227251250327",
"55121603546981200581762165212827652751691296897789",
"32238195734329339946437501907836945765883352399886",
"75506164965184775180738168837861091527357929701337",
"62177842752192623401942399639168044983993173312731",
"32924185707147349566916674687634660915035914677504",
"99518671430235219628894890102423325116913619626622",
"73267460800591547471830798392868535206946944540724",
"76841822524674417161514036427982273348055556214818",
"97142617910342598647204516893989422179826088076852",
"87783646182799346313767754307809363333018982642090",
"10848802521674670883215120185883543223812876952786",
"71329612474782464538636993009049310363619763878039",
"62184073572399794223406235393808339651327408011116",
"66627891981488087797941876876144230030984490851411",
"60661826293682836764744779239180335110989069790714",
"85786944089552990653640447425576083659976645795096",
"66024396409905389607120198219976047599490197230297",
"64913982680032973156037120041377903785566085089252",
"16730939319872750275468906903707539413042652315011",
"94809377245048795150954100921645863754710598436791",
"78639167021187492431995700641917969777599028300699",
"15368713711936614952811305876380278410754449733078",
"40789923115535562561142322423255033685442488917353",
"44889911501440648020369068063960672322193204149535",
"41503128880339536053299340368006977710650566631954",
"81234880673210146739058568557934581403627822703280",
"82616570773948327592232845941706525094512325230608",
"22918802058777319719839450180888072429661980811197",
"77158542502016545090413245809786882778948721859617",
"72107838435069186155435662884062257473692284509516",
"20849603980134001723930671666823555245252804609722",
"53503534226472524250874054075591789781264330331690");
begin
Assert( Solution_1(Input) = Solution );
end Test_Solution_1;
function Get_Solutions return Solution_Case is
Ret : Solution_Case;
begin
Set_Name( Ret, "Problem 13" );
Add_Test( Ret, Test_Solution_1'Access );
return Ret;
end Get_Solutions;
end problem_13;
|
-- gen_.ada
with TEXT_IO;
use TEXT_IO;
generic
MAX_STRING_LENGTH: in POSITIVE;
package DYNAMIC_STRING is
subtype STRING_LENGTHS is INTEGER range 0 .. MAX_STRING_LENGTH;
subtype STRING_INDICES is STRING_LENGTHS;
type DYNAMIC_STRINGS(LENGTH: STRING_LENGTHS := 0) is private;
function LENGTH (PASCAL_STRING: DYNAMIC_STRINGS) return STRING_INDICES;
private
type DYNAMIC_STRINGS(LENGTH: STRING_LENGTHS := 0) is record
STRING_ARRAY: STRING (1 .. LENGTH);
end record;
end DYNAMIC_STRING;
package body DYNAMIC_STRING is
function LENGTH (PASCAL_STRING: DYNAMIC_STRINGS) return STRING_INDICES is
begin
return PASCAL_STRING.LENGTH;
end;
end DYNAMIC_STRING;
with DYNAMIC_STRING;
package STRING_80 is new DYNAMIC_STRING(MAX_STRING_LENGTH => 80);
with string_80;
procedure foo is
s : string_80.dynamic_strings;
begin
null;
end;
|
with Ada.Characters.Handling;
with Ada.Strings.Fixed;
with Ada.Strings;
package body Globals is
Environment_String : String :=
Ada.Characters.Handling.To_Upper (
Ada.Environment_Variables.Value ("OS", "linux"));
Unix_Lineending : constant String
:= String'(1 => ASCII.LF);
Windows_Lineending : constant String
:= String'(1 => ASCII.CR, 2 => ASCII.LF);
begin
if Ada.Strings.Fixed.Index (Environment_String,"WINDOWS") = 0 then
Current_OS := Unix;
Current_Lineending := To_Unbounded_String(Unix_Lineending);
else
Current_OS := Windows;
Current_Lineending := To_Unbounded_String(Windows_Lineending);
end if;
end Globals; |
------------------------------------------------------------------------------
-- --
-- Copyright (C) 2010-2011, AdaCore --
-- --
-- GNARL is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNARL is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNARL; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- As a special exception, if other files instantiate generics from this --
-- unit, or you link this unit with other files to produce an executable, --
-- this unit does not by itself cause the resulting executable to be --
-- covered by the GNU General Public License. This exception does not --
-- however invalidate any other reasons why the executable file might be --
-- covered by the GNU Public License. --
-- --
------------------------------------------------------------------------------
pragma Warnings (Off);
with System.IOPorts; use System.IOPorts;
with System.Machine_Reset;
pragma Warnings (On);
with Interfaces; use Interfaces;
package body Gdbstub_Io is
Debug_Port : constant Port_Id := 16#3f8#;
Serial_Port : constant Port_Id := 16#2f8#;
-- IO ports.
RBR : constant Port_Id := 0;
THR : constant Port_Id := 0;
DLL : constant Port_Id := 0;
DLM : constant Port_Id := 1;
FCR : constant Port_Id := 2;
FCR_FE : constant Unsigned_8 := 16#01#;
FCR_ITL_14 : constant Unsigned_8 := 16#c0#;
LCR : constant Port_Id := 3;
LCR_5bits : constant Unsigned_8 := 16#00#;
LCR_6bits : constant Unsigned_8 := 16#01#;
LCR_7bits : constant Unsigned_8 := 16#02#;
LCR_8bits : constant Unsigned_8 := 16#03#;
LCR_2stop : constant Unsigned_8 := 16#04#;
LCR_No_Parity : constant Unsigned_8 := 16#08#;
LCR_Break : constant Unsigned_8 := 16#40#;
LCR_DLAB : constant Unsigned_8 := 16#80#;
LSR : constant Port_Id := 5;
LSR_Data : constant Unsigned_8 := 16#01#;
procedure Initialize_Uart (Port : Port_Id);
-- Initialize an UART.
function Can_Read return Boolean;
-- True if can read on the debug port.
procedure Initialize_Uart (Port : Port_Id) is
begin
-- 115200 8n1
Outb (Port + LCR, LCR_DLAB or LCR_No_Parity or LCR_8bits);
Outb (Port + DLL, 1);
Outb (Port + DLM, 0);
Outb (Port + LCR, LCR_No_Parity or LCR_8bits);
-- Enable FIFO.
Outb (Port + FCR, FCR_FE or FCR_ITL_14);
end Initialize_Uart;
procedure Initialize is
begin
Initialize_Uart (Serial_Port);
Initialize_Uart (Debug_Port);
end Initialize;
function Can_Read return Boolean is
begin
return (Inb (Serial_Port + LSR) and LSR_Data) /= 0;
end Can_Read;
function Read_Byte return Character is
begin
while not Can_Read loop
null;
end loop;
return Character'Val (Inb (Serial_Port + RBR));
end Read_Byte;
procedure Write_Byte (C : Character) is
begin
Outb (Serial_Port + THR, Character'Pos (C));
end Write_Byte;
procedure Write_Debug (C : Character) is
begin
Outb (Debug_Port + THR, Character'Pos (C));
end Write_Debug;
procedure Kill is
begin
System.Machine_Reset.Stop;
end Kill;
end Gdbstub_Io;
|
-- Copyright (c) 2017 Maxim Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-- License-Filename: LICENSE
-------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Streams;
with League.Strings.Hash;
with LSP.Generic_Optional;
with LSP.Types; use LSP.Types;
package LSP.Messages is
pragma Preelaborate;
pragma Style_Checks ("M125-bcht");
--```typescript
--interface Message {
-- jsonrpc: string;
--}
--```
type Message is abstract tagged record
jsonrpc: LSP_String;
end record;
--```typescript
--interface RequestMessage extends Message {
--
-- /**
-- * The request id.
-- */
-- id: number | string;
--
-- /**
-- * The method to be invoked.
-- */
-- method: string;
--
-- /**
-- * The method's params.
-- */
-- params?: any
--}
--```
type RequestMessage is new Message with record
id: LSP_Number_Or_String;
method: LSP_String;
-- params: LSP_Any;
end record;
--```typescript
--interface ResponseMessage extends Message {
-- /**
-- * The request id.
-- */
-- id: number | string | null;
--
-- /**
-- * The result of a request. This can be omitted in
-- * the case of an error.
-- */
-- result?: any;
--
-- /**
-- * The error object in case a request fails.
-- */
-- error?: ResponseError<any>;
--}
--
--interface ResponseError<D> {
-- /**
-- * A number indicating the error type that occurred.
-- */
-- code: number;
--
-- /**
-- * A string providing a short description of the error.
-- */
-- message: string;
--
-- /**
-- * A Primitive or Structured value that contains additional
-- * information about the error. Can be omitted.
-- */
-- data?: D;
--}
--
--export namespace ErrorCodes {
-- // Defined by JSON RPC
-- export const ParseError: number = -32700;
-- export const InvalidRequest: number = -32600;
-- export const MethodNotFound: number = -32601;
-- export const InvalidParams: number = -32602;
-- export const InternalError: number = -32603;
-- export const serverErrorStart: number = -32099;
-- export const serverErrorEnd: number = -32000;
-- export const ServerNotInitialized: number = -32002;
-- export const UnknownErrorCode: number = -32001;
--
-- // Defined by the protocol.
-- export const RequestCancelled: number = -32800;
--}
--```
type ErrorCodes is
(ParseError,
InvalidRequest,
MethodNotFound,
InvalidParams,
InternalError,
serverErrorStart,
serverErrorEnd,
ServerNotInitialized,
UnknownErrorCode,
RequestCancelled);
type ResponseError is record
code: ErrorCodes;
message: LSP_String;
data: LSP_Any;
end record;
not overriding procedure Read_ResponseError
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out ResponseError);
for ResponseError'Read use Read_ResponseError;
not overriding procedure Write_ResponseError
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ResponseError);
for ResponseError'Write use Write_ResponseError;
package Optional_ResponseErrors is new LSP.Generic_Optional (ResponseError);
type Optional_ResponseError is new Optional_ResponseErrors.Optional_Type;
type ResponseMessage is new Message with record
id: LSP_Number_Or_String; -- or null?
-- result: LSP_Any;
error: Optional_ResponseError;
end record;
not overriding procedure Write_ResponseMessage
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ResponseMessage);
for ResponseMessage'Write use Write_ResponseMessage;
--```typescript
--interface NotificationMessage extends Message {
-- /**
-- * The method to be invoked.
-- */
-- method: string;
--
-- /**
-- * The notification's params.
-- */
-- params?: any
--}
--```
type NotificationMessage is new Message with record
method: LSP_String;
-- params: LSP_Any;
end record;
--```typescript
--interface CancelParams {
-- /**
-- * The request id to cancel.
-- */
-- id: number | string;
--}
--```
type CancelParams is record
id: LSP_Number_Or_String;
end record;
--```typescript
--type DocumentUri = string;
--```
subtype DocumentUri is LSP.Types.LSP_String;
--```typescript
--export const EOL: string[] = ['\n', '\r\n', '\r'];
--```
-- This is intentionally empty. Nothing to declare for EOL
--```typescript
--interface Position {
-- /**
-- * Line position in a document (zero-based).
-- */
-- line: number;
--
-- /**
-- * Character offset on a line in a document (zero-based).
-- */
-- character: number;
--}
--```
type Position is record
line: Line_Number;
character: UTF_16_Index;
end record;
not overriding procedure Read_Position
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out Position);
for Position'Read use Read_Position;
not overriding procedure Write_Position
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Position);
for Position'Write use Write_Position;
--```typescript
--interface Range {
-- /**
-- * The range's start position.
-- */
-- start: Position;
--
-- /**
-- * The range's end position.
-- */
-- end: Position;
--}
--```
type Span is record
first: Position;
last: Position; -- end: is reserved work
end record;
not overriding procedure Read_Span
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out Span);
for Span'Read use Read_Span;
not overriding procedure Write_Span
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Span);
for Span'Write use Write_Span;
package Optional_Spans is new LSP.Generic_Optional (Span);
type Optional_Span is new Optional_Spans.Optional_Type;
--```typescript
--interface Location {
-- uri: DocumentUri;
-- range: Range;
--}
--```
type Location is record
uri: DocumentUri;
span: LSP.Messages.Span; -- range: is reserved word
end record;
not overriding procedure Write_Location
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Location);
for Location'Write use Write_Location;
package Location_Vectors is new Ada.Containers.Vectors
(Positive, Location);
--+1
--```typescript
--namespace DiagnosticSeverity {
-- /**
-- * Reports an error.
-- */
-- export const Error = 1;
-- /**
-- * Reports a warning.
-- */
-- export const Warning = 2;
-- /**
-- * Reports an information.
-- */
-- export const Information = 3;
-- /**
-- * Reports a hint.
-- */
-- export const Hint = 4;
--}
--```
type DiagnosticSeverity is (Error, Warning, Information, Hint);
not overriding procedure Write_DiagnosticSeverity
(S : access Ada.Streams.Root_Stream_Type'Class;
V : DiagnosticSeverity);
for DiagnosticSeverity'Write use Write_DiagnosticSeverity;
package Optional_DiagnosticSeveritys is new LSP.Generic_Optional (DiagnosticSeverity);
type Optional_DiagnosticSeverity is new Optional_DiagnosticSeveritys.Optional_Type;
--```typescript
--interface Diagnostic {
-- /**
-- * The range at which the message applies.
-- */
-- range: Range;
--
-- /**
-- * The diagnostic's severity. Can be omitted. If omitted it is up to the
-- * client to interpret diagnostics as error, warning, info or hint.
-- */
-- severity?: number;
--
-- /**
-- * The diagnostic's code. Can be omitted.
-- */
-- code?: number | string;
--
-- /**
-- * A human-readable string describing the source of this
-- * diagnostic, e.g. 'typescript' or 'super lint'.
-- */
-- source?: string;
--
-- /**
-- * The diagnostic's message.
-- */
-- message: string;
--}
--```
type Diagnostic is record
span: LSP.Messages.Span;
severity: Optional_DiagnosticSeverity;
code: LSP_Number_Or_String;
source: Optional_String;
message: LSP_String;
end record;
not overriding procedure Read_Diagnostic
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out Diagnostic);
for Diagnostic'Read use Read_Diagnostic;
not overriding procedure Write_Diagnostic
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Diagnostic);
for Diagnostic'Write use Write_Diagnostic;
package Diagnostic_Vectors is new Ada.Containers.Vectors
(Positive, Diagnostic);
type Diagnostic_Vector is new Diagnostic_Vectors.Vector with null record;
--```typescript
--interface Command {
-- /**
-- * Title of the command, like `save`.
-- */
-- title: string;
-- /**
-- * The identifier of the actual command handler.
-- */
-- command: string;
-- /**
-- * Arguments that the command handler should be
-- * invoked with.
-- */
-- arguments?: any[];
--}
--```
type Command is record
title: LSP_String;
command: LSP_String;
arguments: LSP_Any;
end record;
not overriding procedure Write_Command
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Command);
for Command'Write use Write_Command;
package Command_Vectors is new Ada.Containers.Vectors
(Positive, Command);
type Command_Vector is new Command_Vectors.Vector with null record;
--```typescript
--interface TextEdit {
-- /**
-- * The range of the text document to be manipulated. To insert
-- * text into a document create a range where start === end.
-- */
-- range: Range;
--
-- /**
-- * The string to be inserted. For delete operations use an
-- * empty string.
-- */
-- newText: string;
--}
--```
type TextEdit is record
span: LSP.Messages.Span;
newText: LSP_String;
end record;
not overriding procedure Read_TextEdit
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextEdit);
for TextEdit'Read use Read_TextEdit;
not overriding procedure Write_TextEdit
(S : access Ada.Streams.Root_Stream_Type'Class;
V : TextEdit);
for TextEdit'Write use Write_TextEdit;
package Optional_TextEdits is new LSP.Generic_Optional (TextEdit);
type Optional_TextEdit is new Optional_TextEdits.Optional_Type;
package TextEdit_Vectors is new Ada.Containers.Vectors (Positive, TextEdit);
type TextEdit_Vector is new TextEdit_Vectors.Vector with null record;
not overriding procedure Read_TextEdit_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextEdit_Vector);
for TextEdit_Vector'Read use Read_TextEdit_Vector;
not overriding procedure Write_TextEdit_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : TextEdit_Vector);
for TextEdit_Vector'Write use Write_TextEdit_Vector;
--+N
--```typescript
--interface TextDocumentIdentifier {
-- /**
-- * The text document's URI.
-- */
-- uri: DocumentUri;
--}
--```
type TextDocumentIdentifier is tagged record
uri: DocumentUri;
end record;
not overriding procedure Read_TextDocumentIdentifier
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentIdentifier);
for TextDocumentIdentifier'Read use Read_TextDocumentIdentifier;
--+N+2
--```typescript
--interface VersionedTextDocumentIdentifier extends TextDocumentIdentifier {
-- /**
-- * The version number of this document.
-- */
-- version: number;
--}
--```
type VersionedTextDocumentIdentifier is new TextDocumentIdentifier with record
version: Version_Id;
end record;
not overriding procedure Read_VersionedTextDocumentIdentifier
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out VersionedTextDocumentIdentifier);
for VersionedTextDocumentIdentifier'Read use
Read_VersionedTextDocumentIdentifier;
not overriding procedure Write_VersionedTextDocumentIdentifier
(S : access Ada.Streams.Root_Stream_Type'Class;
V : VersionedTextDocumentIdentifier);
for VersionedTextDocumentIdentifier'Write use
Write_VersionedTextDocumentIdentifier;
--```typescript
--export interface TextDocumentEdit {
-- /**
-- * The text document to change.
-- */
-- textDocument: VersionedTextDocumentIdentifier;
--
-- /**
-- * The edits to be applied.
-- */
-- edits: TextEdit[];
--}
--```
type TextDocumentEdit is record
textDocument: VersionedTextDocumentIdentifier;
edits: TextEdit_Vector;
end record;
not overriding procedure Read_TextDocumentEdit
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentEdit);
for TextDocumentEdit'Read use Read_TextDocumentEdit;
not overriding procedure Write_TextDocumentEdit
(S : access Ada.Streams.Root_Stream_Type'Class;
V : TextDocumentEdit);
for TextDocumentEdit'Write use Write_TextDocumentEdit;
package TextDocumentEdit_Vectors is
new Ada.Containers.Vectors (Positive, TextDocumentEdit);
package TextDocumentEdit_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => League.Strings.Universal_String,
Element_Type => TextEdit_Vector,
Hash => League.Strings.Hash,
Equivalent_Keys => League.Strings."=");
--```typescript
--export interface WorkspaceEdit {
-- /**
-- * Holds changes to existing resources.
-- */
-- changes?: { [uri: string]: TextEdit[]; };
--
-- /**
-- * An array of `TextDocumentEdit`s to express changes to n different text documents
-- * where each text document edit addresses a specific version of a text document.
-- * Whether a client supports versioned document edits is expressed via
-- * `WorkspaceClientCapabilities.workspaceEdit.documentChanges`.
-- */
-- documentChanges?: TextDocumentEdit[];
--}
--```
type WorkspaceEdit is record
changes: TextDocumentEdit_Maps.Map;
documentChanges: TextDocumentEdit_Vectors.Vector;
end record;
--```typescript
--interface TextDocumentItem {
-- /**
-- * The text document's URI.
-- */
-- uri: DocumentUri;
--
-- /**
-- * The text document's language identifier.
-- */
-- languageId: string;
--
-- /**
-- * The version number of this document (it will increase after each
-- * change, including undo/redo).
-- */
-- version: number;
--
-- /**
-- * The content of the opened text document.
-- */
-- text: string;
--}
--```
type TextDocumentItem is record
uri: DocumentUri;
languageId: LSP_String;
version: Version_Id;
text: LSP_String;
end record;
--```typescript
--interface TextDocumentPositionParams {
-- /**
-- * The text document.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The position inside the text document.
-- */
-- position: Position;
--}
--```
type TextDocumentPositionParams is tagged record
textDocument: TextDocumentIdentifier;
position: LSP.Messages.Position;
end record;
not overriding procedure Read_TextDocumentPositionParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentPositionParams);
for TextDocumentPositionParams'Read use Read_TextDocumentPositionParams;
--```typescript
--{ language: 'typescript', scheme: 'file' }
--{ language: 'json', pattern: '**/package.json' }
--```
-- This is just example of filter. Nothing to do
--```typescript
--export interface DocumentFilter {
-- /**
-- * A language id, like `typescript`.
-- */
-- language?: string;
--
-- /**
-- * A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
-- */
-- scheme?: string;
--
-- /**
-- * A glob pattern, like `*.{ts,js}`.
-- */
-- pattern?: string;
--}
--```
type DocumentFilter is record
language: LSP.Types.Optional_String;
scheme: LSP.Types.Optional_String;
pattern: LSP.Types.Optional_String;
end record;
package DocumentFilter_Vectors is new Ada.Containers.Vectors
(Positive, DocumentFilter);
--```typescript
--export type DocumentSelector = DocumentFilter[];
--```
type DocumentSelector is new DocumentFilter_Vectors.Vector with null record;
type dynamicRegistration is new Optional_Boolean;
--+M
--```typescript
--/**
-- * Workspace specific client capabilities.
-- */
--export interface WorkspaceClientCapabilities {
-- /**
-- * The client supports applying batch edits to the workspace by supporting
-- * the request 'workspace/applyEdit'
-- */
-- applyEdit?: boolean;
--
-- /**
-- * Capabilities specific to `WorkspaceEdit`s
-- */
-- workspaceEdit?: {
-- /**
-- * The client supports versioned document changes in `WorkspaceEdit`s
-- */
-- documentChanges?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `workspace/didChangeConfiguration` notification.
-- */
-- didChangeConfiguration?: {
-- /**
-- * Did change configuration notification supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `workspace/didChangeWatchedFiles` notification.
-- */
-- didChangeWatchedFiles?: {
-- /**
-- * Did change watched files notification supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `workspace/symbol` request.
-- */
-- symbol?: {
-- /**
-- * Symbol request supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `workspace/executeCommand` request.
-- */
-- executeCommand?: {
-- /**
-- * Execute command supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--}
--```
type WorkspaceClientCapabilities is record
applyEdit: Optional_Boolean;
workspaceEdit: Optional_Boolean;
didChangeConfiguration: dynamicRegistration;
didChangeWatchedFiles: dynamicRegistration;
symbol: dynamicRegistration;
executeCommand: dynamicRegistration;
end record;
--```typescript
--/**
-- * Text document specific client capabilities.
-- */
--export interface TextDocumentClientCapabilities {
--
-- synchronization?: {
-- /**
-- * Whether text document synchronization supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
--
-- /**
-- * The client supports sending will save notifications.
-- */
-- willSave?: boolean;
--
-- /**
-- * The client supports sending a will save request and
-- * waits for a response providing text edits which will
-- * be applied to the document before it is saved.
-- */
-- willSaveWaitUntil?: boolean;
--
-- /**
-- * The client supports did save notifications.
-- */
-- didSave?: boolean;
-- }
--
-- /**
-- * Capabilities specific to the `textDocument/completion`
-- */
-- completion?: {
-- /**
-- * Whether completion supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
--
-- /**
-- * The client supports the following `CompletionItem` specific
-- * capabilities.
-- */
-- completionItem?: {
-- /**
-- * Client supports snippets as insert text.
-- *
-- * A snippet can define tab stops and placeholders with `$1`, `$2`
-- * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
-- * the end of the snippet. Placeholders with equal identifiers are linked,
-- * that is typing in one will update others too.
-- */
-- snippetSupport?: boolean;
-- }
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/hover`
-- */
-- hover?: {
-- /**
-- * Whether hover supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/signatureHelp`
-- */
-- signatureHelp?: {
-- /**
-- * Whether signature help supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/references`
-- */
-- references?: {
-- /**
-- * Whether references supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/documentHighlight`
-- */
-- documentHighlight?: {
-- /**
-- * Whether document highlight supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/documentSymbol`
-- */
-- documentSymbol?: {
-- /**
-- * Whether document symbol supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/formatting`
-- */
-- formatting?: {
-- /**
-- * Whether formatting supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/rangeFormatting`
-- */
-- rangeFormatting?: {
-- /**
-- * Whether range formatting supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/onTypeFormatting`
-- */
-- onTypeFormatting?: {
-- /**
-- * Whether on type formatting supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/definition`
-- */
-- definition?: {
-- /**
-- * Whether definition supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/codeAction`
-- */
-- codeAction?: {
-- /**
-- * Whether code action supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/codeLens`
-- */
-- codeLens?: {
-- /**
-- * Whether code lens supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/documentLink`
-- */
-- documentLink?: {
-- /**
-- * Whether document link supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--
-- /**
-- * Capabilities specific to the `textDocument/rename`
-- */
-- rename?: {
-- /**
-- * Whether rename supports dynamic registration.
-- */
-- dynamicRegistration?: boolean;
-- };
--}
--```
type synchronization is record
dynamicRegistration : Optional_Boolean;
willSave : Optional_Boolean;
willSaveWaitUntil : Optional_Boolean;
didSave : Optional_Boolean;
end record;
type completion is record
dynamicRegistration : Optional_Boolean;
snippetSupport : Optional_Boolean;
end record;
type TextDocumentClientCapabilities is record
synchronization: LSP.Messages.synchronization;
completion: LSP.Messages.completion;
hover: dynamicRegistration;
signatureHelp: dynamicRegistration;
references: dynamicRegistration;
documentHighlight: dynamicRegistration;
documentSymbol: dynamicRegistration;
formatting: dynamicRegistration;
rangeFormatting: dynamicRegistration;
onTypeFormatting: dynamicRegistration;
definition: dynamicRegistration;
codeAction: dynamicRegistration;
codeLens: dynamicRegistration;
documentLink: dynamicRegistration;
rename: dynamicRegistration;
end record;
--```typescript
--interface ClientCapabilities {
-- /**
-- * Workspace specific client capabilities.
-- */
-- workspace?: WorkspaceClientCapabilities;
--
-- /**
-- * Text document specific client capabilities.
-- */
-- textDocument?: TextDocumentClientCapabilities;
--
-- /**
-- * Experimental client capabilities.
-- */
-- experimental?: any;
--}
--```
type ClientCapabilities is record
workspace: WorkspaceClientCapabilities;
textDocument: TextDocumentClientCapabilities;
-- experimental?: any;
end record;
--```typescript
--interface InitializeParams {
-- /**
-- * The process Id of the parent process that started
-- * the server. Is null if the process has not been started by another process.
-- * If the parent process is not alive then the server should exit (see exit notification) its process.
-- */
-- processId: number | null;
--
-- /**
-- * The rootPath of the workspace. Is null
-- * if no folder is open.
-- *
-- * @deprecated in favour of rootUri.
-- */
-- rootPath?: string | null;
--
-- /**
-- * The rootUri of the workspace. Is null if no
-- * folder is open. If both `rootPath` and `rootUri` are set
-- * `rootUri` wins.
-- */
-- rootUri: DocumentUri | null;
--
-- /**
-- * User provided initialization options.
-- */
-- initializationOptions?: any;
--
-- /**
-- * The capabilities provided by the client (editor or tool)
-- */
-- capabilities: ClientCapabilities;
--
-- /**
-- * The initial trace setting. If omitted trace is disabled ('off').
-- */
-- trace?: 'off' | 'messages' | 'verbose';
--}
--```
type InitializeParams is record
processId: Optional_Number;
rootPath: LSP_String;
rootUri: DocumentUri; -- or null???
-- initializationOptions?: any;
capabilities: ClientCapabilities;
trace: Trace_Kinds;
end record;
--+K
--```typescript
--/**
-- * Defines how the host (editor) should sync document changes to the language server.
-- */
--export namespace TextDocumentSyncKind {
-- /**
-- * Documents should not be synced at all.
-- */
-- export const None = 0;
--
-- /**
-- * Documents are synced by always sending the full content
-- * of the document.
-- */
-- export const Full = 1;
--
-- /**
-- * Documents are synced by sending the full content on open.
-- * After that only incremental updates to the document are
-- * send.
-- */
-- export const Incremental = 2;
--}
--
--/**
-- * Completion options.
-- */
--export interface CompletionOptions {
-- /**
-- * The server provides support to resolve additional
-- * information for a completion item.
-- */
-- resolveProvider?: boolean;
--
-- /**
-- * The characters that trigger completion automatically.
-- */
-- triggerCharacters?: string[];
--}
--/**
-- * Signature help options.
-- */
--export interface SignatureHelpOptions {
-- /**
-- * The characters that trigger signature help
-- * automatically.
-- */
-- triggerCharacters?: string[];
--}
--
--/**
-- * Code Lens options.
-- */
--export interface CodeLensOptions {
-- /**
-- * Code lens has a resolve provider as well.
-- */
-- resolveProvider?: boolean;
--}
--
--/**
-- * Format document on type options
-- */
--export interface DocumentOnTypeFormattingOptions {
-- /**
-- * A character on which formatting should be triggered, like `}`.
-- */
-- firstTriggerCharacter: string;
--
-- /**
-- * More trigger characters.
-- */
-- moreTriggerCharacter?: string[];
--}
--
--/**
-- * Document link options
-- */
--export interface DocumentLinkOptions {
-- /**
-- * Document links have a resolve provider as well.
-- */
-- resolveProvider?: boolean;
--}
--
--/**
-- * Execute command options.
-- */
--export interface ExecuteCommandOptions {
-- /**
-- * The commands to be executed on the server
-- */
-- commands: string[]
--}
--
--/**
-- * Save options.
-- */
--export interface SaveOptions {
-- /**
-- * The client is supposed to include the content on save.
-- */
-- includeText?: boolean;
--}
--
--export interface TextDocumentSyncOptions {
-- /**
-- * Open and close notifications are sent to the server.
-- */
-- openClose?: boolean;
-- /**
-- * Change notificatins are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
-- * and TextDocumentSyncKindIncremental.
-- */
-- change?: number;
-- /**
-- * Will save notifications are sent to the server.
-- */
-- willSave?: boolean;
-- /**
-- * Will save wait until requests are sent to the server.
-- */
-- willSaveWaitUntil?: boolean;
-- /**
-- * Save notifications are sent to the server.
-- */
-- save?: SaveOptions;
--}
--
--interface ServerCapabilities {
-- /**
-- * Defines how text documents are synced. Is either a detailed structure defining each notification or
-- * for backwards compatibility the TextDocumentSyncKind number.
-- */
-- textDocumentSync?: TextDocumentSyncOptions | number;
-- /**
-- * The server provides hover support.
-- */
-- hoverProvider?: boolean;
-- /**
-- * The server provides completion support.
-- */
-- completionProvider?: CompletionOptions;
-- /**
-- * The server provides signature help support.
-- */
-- signatureHelpProvider?: SignatureHelpOptions;
-- /**
-- * The server provides goto definition support.
-- */
-- definitionProvider?: boolean;
-- /**
-- * The server provides find references support.
-- */
-- referencesProvider?: boolean;
-- /**
-- * The server provides document highlight support.
-- */
-- documentHighlightProvider?: boolean;
-- /**
-- * The server provides document symbol support.
-- */
-- documentSymbolProvider?: boolean;
-- /**
-- * The server provides workspace symbol support.
-- */
-- workspaceSymbolProvider?: boolean;
-- /**
-- * The server provides code actions.
-- */
-- codeActionProvider?: boolean;
-- /**
-- * The server provides code lens.
-- */
-- codeLensProvider?: CodeLensOptions;
-- /**
-- * The server provides document formatting.
-- */
-- documentFormattingProvider?: boolean;
-- /**
-- * The server provides document range formatting.
-- */
-- documentRangeFormattingProvider?: boolean;
-- /**
-- * The server provides document formatting on typing.
-- */
-- documentOnTypeFormattingProvider?: DocumentOnTypeFormattingOptions;
-- /**
-- * The server provides rename support.
-- */
-- renameProvider?: boolean;
-- /**
-- * The server provides document link support.
-- */
-- documentLinkProvider?: DocumentLinkOptions;
-- /**
-- * The server provides execute command support.
-- */
-- executeCommandProvider?: ExecuteCommandOptions;
-- /**
-- * Experimental server capabilities.
-- */
-- experimental?: any;
--}
--```
type TextDocumentSyncKind is (None, Full, Incremental);
not overriding procedure Write_TextDocumentSyncKind
(S : access Ada.Streams.Root_Stream_Type'Class;
V : TextDocumentSyncKind);
for TextDocumentSyncKind'Write use Write_TextDocumentSyncKind;
package Optional_TextDocumentSyncKinds is new LSP.Generic_Optional (TextDocumentSyncKind);
type Optional_TextDocumentSyncKind is new Optional_TextDocumentSyncKinds.Optional_Type;
type TextDocumentSyncOptions is record
openClose: Optional_Boolean;
change: Optional_TextDocumentSyncKind;
willSave: Optional_Boolean;
willSaveWaitUntil: Optional_Boolean;
save: Optional_Boolean;
end record;
type Optional_TextDocumentSyncOptions
(Is_Set : Boolean := False;
Is_Number : Boolean := False) is
record
case Is_Set is
when True =>
case Is_Number is
when True =>
Value : TextDocumentSyncKind;
when False =>
Options : TextDocumentSyncOptions;
end case;
when False => null;
end case;
end record;
type CompletionOptions is record
resolveProvider: LSP.Types.Optional_Boolean;
triggerCharacters: LSP.Types.LSP_String_Vector;
end record;
not overriding procedure Write_CompletionOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CompletionOptions);
for CompletionOptions'Write use Write_CompletionOptions;
package Optional_CompletionOptionss is
new LSP.Generic_Optional (CompletionOptions);
type Optional_CompletionOptions is
new Optional_CompletionOptionss.Optional_Type;
type SignatureHelpOptions is record
triggerCharacters: LSP.Types.LSP_String_Vector;
end record;
not overriding procedure Write_SignatureHelpOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SignatureHelpOptions);
for SignatureHelpOptions'Write use Write_SignatureHelpOptions;
package Optional_SignatureHelpOptionss is
new LSP.Generic_Optional (SignatureHelpOptions);
type Optional_SignatureHelpOptions is
new Optional_SignatureHelpOptionss.Optional_Type;
type CodeLensOptions is record
resolveProvider: LSP.Types.Optional_Boolean;
end record;
not overriding procedure Write_CodeLensOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CodeLensOptions);
for CodeLensOptions'Write use Write_CodeLensOptions;
package Optional_CodeLensOptionss is
new LSP.Generic_Optional (CodeLensOptions);
type Optional_CodeLensOptions is
new Optional_CodeLensOptionss.Optional_Type;
type DocumentOnTypeFormattingOptions is record
firstTriggerCharacter: LSP.Types.LSP_String;
moreTriggerCharacter: LSP.Types.LSP_String_Vector;
end record;
not overriding procedure Write_DocumentOnTypeFormattingOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : DocumentOnTypeFormattingOptions);
for DocumentOnTypeFormattingOptions'Write use Write_DocumentOnTypeFormattingOptions;
package Optional_DocumentOnTypeFormattingOptionss is
new LSP.Generic_Optional (DocumentOnTypeFormattingOptions);
type Optional_DocumentOnTypeFormattingOptions is
new Optional_DocumentOnTypeFormattingOptionss.Optional_Type;
type DocumentLinkOptions is record
resolveProvider: LSP.Types.Optional_Boolean;
end record;
type ExecuteCommandOptions is record
commands: LSP.Types.LSP_String_Vector;
end record;
type ServerCapabilities is record
textDocumentSync: Optional_TextDocumentSyncOptions;
hoverProvider: Optional_Boolean;
completionProvider: Optional_CompletionOptions;
signatureHelpProvider: Optional_SignatureHelpOptions;
definitionProvider: Optional_Boolean;
referencesProvider: Optional_Boolean;
documentHighlightProvider: Optional_Boolean;
documentSymbolProvider: Optional_Boolean;
workspaceSymbolProvider: Optional_Boolean;
codeActionProvider: Optional_Boolean;
codeLensProvider: Optional_CodeLensOptions;
documentFormattingProvider: Optional_Boolean;
documentRangeFormattingProvider: Optional_Boolean;
documentOnTypeFormattingProvider: Optional_DocumentOnTypeFormattingOptions;
renameProvider: Optional_Boolean;
documentLinkProvider: DocumentLinkOptions;
executeCommandProvider: ExecuteCommandOptions;
-- experimental?: any;
end record;
--```typescript
--interface InitializeResult {
-- /**
-- * The capabilities the language server provides.
-- */
-- capabilities: ServerCapabilities;
--}
--```
type InitializeResult is record
capabilities: ServerCapabilities;
end record;
type Initialize_Response is new ResponseMessage with record
result: InitializeResult;
end record;
--```typescript
--/**
-- * Known error codes for an `InitializeError`;
-- */
--export namespace InitializeError {
-- /**
-- * If the protocol version provided by the client can't be handled by the server.
-- * @deprecated This initialize error got replaced by client capabilities. There is
-- * no version handshake in version 3.0x
-- */
-- export const unknownProtocolVersion: number = 1;
--}
--```
unknownProtocolVersion: constant := 1;
--```typescript
--interface InitializeError {
-- /**
-- * Indicates whether the client execute the following retry logic:
-- * (1) show the message provided by the ResponseError to the user
-- * (2) user selects retry or cancel
-- * (3) if user selected retry the initialize method is sent again.
-- */
-- retry: boolean;
--}
--```
type InitializeError is record
retry: Boolean;
end record;
--+J
--```typescript
--export namespace MessageType {
-- /**
-- * An error message.
-- */
-- export const Error = 1;
-- /**
-- * A warning message.
-- */
-- export const Warning = 2;
-- /**
-- * An information message.
-- */
-- export const Info = 3;
-- /**
-- * A log message.
-- */
-- export const Log = 4;
--}
--```
type MessageType is (Error, Warning, Info, Log);
--```typescript
--interface ShowMessageParams {
-- /**
-- * The message type. See {@link MessageType}.
-- */
-- type: number;
--
-- /**
-- * The actual message.
-- */
-- message: string;
--}
--```
type ShowMessageParams is record
the_type: MessageType; -- type: is reserver word
message: LSP_String;
end record;
--```typescript
--interface ShowMessageRequestParams {
-- /**
-- * The message type. See {@link MessageType}
-- */
-- type: number;
--
-- /**
-- * The actual message
-- */
-- message: string;
--
-- /**
-- * The message action items to present.
-- */
-- actions?: MessageActionItem[];
--}
--```
type ShowMessageRequestParams is record
the_type: MessageType; -- type: is reserver word
message: LSP_String;
actions: MessageActionItem_Vector;
end record;
--```typescript
--interface MessageActionItem {
-- /**
-- * A short title like 'Retry', 'Open Log' etc.
-- */
-- title: string;
--}
--```
-- Lets use League.Strings.Universal_String for MessageActionItem
--```typescript
--interface LogMessageParams {
-- /**
-- * The message type. See {@link MessageType}
-- */
-- type: number;
--
-- /**
-- * The actual message
-- */
-- message: string;
--}
--```
type LogMessageParams is record
the_type: MessageType; -- type: is reserver word
message: LSP_String;
end record;
--```typescript
--export interface TextDocumentRegistrationOptions {
-- /**
-- * A document selector to identify the scope of the registration. If set to null
-- * the document selector provided on the client side will be used.
-- */
-- documentSelector: DocumentSelector | null;
--}
--```
type TextDocumentRegistrationOptions is tagged record
documentSelector: LSP.Messages.DocumentSelector;
end record;
--```typescript
--/**
-- * Descibe options to be used when registered for text document change events.
-- */
--export interface TextDocumentChangeRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * How documents are synced to the server. See TextDocumentSyncKind.Full
-- * and TextDocumentSyncKindIncremental.
-- */
-- syncKind: number;
--}
--```
type TextDocumentChangeRegistrationOptions is
new TextDocumentRegistrationOptions with
record
syncKind: TextDocumentSyncKind;
end record;
--```typescript
--export interface TextDocumentSaveRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * The client is supposed to include the content on save.
-- */
-- includeText?: boolean;
--}
--```
type TextDocumentSaveRegistrationOptions is
new TextDocumentRegistrationOptions with record
includeText: Optional_Boolean;
end record;
--```typescript
--export interface CompletionRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * The characters that trigger completion automatically.
-- */
-- triggerCharacters?: string[];
--
-- /**
-- * The server provides support to resolve additional
-- * information for a completion item.
-- */
-- resolveProvider?: boolean;
--}
--```
type CompletionRegistrationOptions is new TextDocumentRegistrationOptions with record
triggerCharacters: LSP_String_Vector;
resolveProvider: Optional_Boolean;
end record;
--```typescript
--export interface SignatureHelpRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * The characters that trigger signature help
-- * automatically.
-- */
-- triggerCharacters?: string[];
--}
--```
type SignatureHelpRegistrationOptions is new TextDocumentRegistrationOptions with record
triggerCharacters: LSP_String_Vector;
end record;
--```typescript
--export interface CodeLensRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * Code lens has a resolve provider as well.
-- */
-- resolveProvider?: boolean;
--}
--```
type CodeLensRegistrationOptions is new TextDocumentRegistrationOptions with record
resolveProvider: Optional_Boolean;
end record;
--```typescript
--export interface DocumentLinkRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * Document links have a resolve provider as well.
-- */
-- resolveProvider?: boolean;
--}
--```
type DocumentLinkRegistrationOptions is new TextDocumentRegistrationOptions with record
resolveProvider: Optional_Boolean;
end record;
--```typescript
--export interface DocumentOnTypeFormattingRegistrationOptions extends TextDocumentRegistrationOptions {
-- /**
-- * A character on which formatting should be triggered, like `}`.
-- */
-- firstTriggerCharacter: string;
-- /**
-- * More trigger characters.
-- */
-- moreTriggerCharacter?: string[]
--}
--```
type DocumentOnTypeFormattingRegistrationOptions is new TextDocumentRegistrationOptions with record
firstTriggerCharacter: LSP_String;
moreTriggerCharacter: LSP_String_Vector;
end record;
--```typescript
--/**
-- * Execute command registration options.
-- */
--export interface ExecuteCommandRegistrationOptions {
-- /**
-- * The commands to be executed on the server
-- */
-- commands: string[]
--}
--```
type ExecuteCommandRegistrationOptions is record
commands: LSP_String_Vector;
end record;
type Registration_Option (Kind : Registration_Option_Kinds := Absent) is record
case Kind is
when Absent =>
null;
when Text_Document_Registration_Option =>
Text_Document : TextDocumentRegistrationOptions;
when Text_Document_Change_Registration_Option =>
Text_Document_Change : TextDocumentChangeRegistrationOptions;
when Text_Document_Save_Registration_Option =>
Text_Document_Save : TextDocumentSaveRegistrationOptions;
when Completion_Registration_Option =>
Completion : CompletionRegistrationOptions;
when Signature_Help_Registration_Option =>
SignatureHelp : SignatureHelpRegistrationOptions;
when Code_Lens_Registration_Option =>
CodeLens : CodeLensRegistrationOptions;
when Document_Link_Registration_Option =>
DocumentLink : DocumentLinkRegistrationOptions;
when Document_On_Type_Formatting_Registration_Option =>
DocumentOnTypeFormatting : DocumentOnTypeFormattingRegistrationOptions;
when Execute_Command_Registration_Option =>
ExecuteCommand : ExecuteCommandRegistrationOptions;
end case;
end record;
--```typescript
--/**
-- * General parameters to register for a capability.
-- */
--export interface Registration {
-- /**
-- * The id used to register the request. The id can be used to deregister
-- * the request again.
-- */
-- id: string;
--
-- /**
-- * The method / capability to register for.
-- */
-- method: string;
--
-- /**
-- * Options necessary for the registration.
-- */
-- registerOptions?: any;
--}
--
--export interface RegistrationParams {
-- registrations: Registration[];
--}
--```
type Registration is record
id: LSP_String;
method: LSP_String;
registerOptions: Registration_Option;
end record;
type Registration_Array is array (Positive range <>) of Registration;
type RegistrationParams (Length : Natural) is record
registrations: Registration_Array (1 .. Length);
end record;
--```typescript
--/**
-- * General parameters to unregister a capability.
-- */
--export interface Unregistration {
-- /**
-- * The id used to unregister the request or notification. Usually an id
-- * provided during the register request.
-- */
-- id: string;
--
-- /**
-- * The method / capability to unregister for.
-- */
-- method: string;
--}
--
--export interface UnregistrationParams {
-- unregisterations: Unregistration[];
--}
--```
type Unregistration is record
id: LSP_String;
method: LSP_String;
end record;
package Unregistration_Vectors is new Ada.Containers.Vectors
(Positive, Unregistration);
type UnregistrationParams is
new Unregistration_Vectors.Vector with null record;
--```typescript
--interface DidChangeConfigurationParams {
-- /**
-- * The actual changed settings
-- */
-- settings: any;
--}
--```
type DidChangeConfigurationParams is record
settings: LSP.Types.LSP_Any;
end record;
--```typescript
--interface DidOpenTextDocumentParams {
-- /**
-- * The document that was opened.
-- */
-- textDocument: TextDocumentItem;
--}
--```
type DidOpenTextDocumentParams is record
textDocument: TextDocumentItem;
end record;
--```typescript
--interface DidChangeTextDocumentParams {
-- /**
-- * The document that did change. The version number points
-- * to the version after all provided content changes have
-- * been applied.
-- */
-- textDocument: VersionedTextDocumentIdentifier;
--
-- /**
-- * The actual content changes. The content changes descibe single state changes
-- * to the document. So if there are two content changes c1 and c2 for a document
-- * in state S10 then c1 move the document to S11 and c2 to S12.
-- */
-- contentChanges: TextDocumentContentChangeEvent[];
--}
--
--/**
-- * An event describing a change to a text document. If range and rangeLength are omitted
-- * the new text is considered to be the full content of the document.
-- */
--interface TextDocumentContentChangeEvent {
-- /**
-- * The range of the document that changed.
-- */
-- range?: Range;
--
-- /**
-- * The length of the range that got replaced.
-- */
-- rangeLength?: number;
--
-- /**
-- * The new text of the range/document.
-- */
-- text: string;
--}
--```
type TextDocumentContentChangeEvent is record
span: Optional_Span;
rangeLength: LSP.Types.Optional_Number;
text: LSP_String;
end record;
not overriding procedure Read_TextDocumentContentChangeEvent
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentContentChangeEvent);
for TextDocumentContentChangeEvent'Read use
Read_TextDocumentContentChangeEvent;
package TextDocumentContentChangeEvent_Vectors is new Ada.Containers.Vectors
(Positive, TextDocumentContentChangeEvent);
type TextDocumentContentChangeEvent_Vector is
new TextDocumentContentChangeEvent_Vectors.Vector with null record;
not overriding procedure Read_TextDocumentContentChangeEvent_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentContentChangeEvent_Vector);
for TextDocumentContentChangeEvent_Vector'Read use
Read_TextDocumentContentChangeEvent_Vector;
type DidChangeTextDocumentParams is record
textDocument: VersionedTextDocumentIdentifier;
contentChanges: TextDocumentContentChangeEvent_Vector;
end record;
--```typescript
--/**
-- * The parameters send in a will save text document notification.
-- */
--export interface WillSaveTextDocumentParams {
-- /**
-- * The document that will be saved.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The 'TextDocumentSaveReason'.
-- */
-- reason: number;
--}
--
--/**
-- * Represents reasons why a text document is saved.
-- */
--export namespace TextDocumentSaveReason {
--
-- /**
-- * Manually triggered, e.g. by the user pressing save, by starting debugging,
-- * or by an API call.
-- */
-- export const Manual = 1;
--
-- /**
-- * Automatic after a delay.
-- */
-- export const AfterDelay = 2;
--
-- /**
-- * When the editor lost focus.
-- */
-- export const FocusOut = 3;
--}
--```
type TextDocumentSaveReason is (Manual, AfterDelay, FocusOut);
type WillSaveTextDocumentParams is record
textDocument: TextDocumentIdentifier;
reason: TextDocumentSaveReason;
end record;
--```typescript
--interface DidSaveTextDocumentParams {
-- /**
-- * The document that was saved.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * Optional the content when saved. Depends on the includeText value
-- * when the save notifcation was requested.
-- */
-- text?: string;
--}
--```
type DidSaveTextDocumentParams is record
textDocument: TextDocumentIdentifier;
text: Optional_String;
end record;
--```typescript
--interface DidCloseTextDocumentParams {
-- /**
-- * The document that was closed.
-- */
-- textDocument: TextDocumentIdentifier;
--}
--```
type DidCloseTextDocumentParams is record
textDocument: TextDocumentIdentifier;
end record;
--```typescript
--/**
-- * An event describing a file change.
-- */
--interface FileEvent {
-- /**
-- * The file's URI.
-- */
-- uri: DocumentUri;
-- /**
-- * The change type.
-- */
-- type: number;
--}
--
--/**
-- * The file event type.
-- */
--export namespace FileChangeType {
-- /**
-- * The file got created.
-- */
-- export const Created = 1;
-- /**
-- * The file got changed.
-- */
-- export const Changed = 2;
-- /**
-- * The file got deleted.
-- */
-- export const Deleted = 3;
--}
--```
type FileChangeType is (Created, Changed, Deleted);
type FileEvent is record
uri: DocumentUri;
the_type : FileChangeType; -- type: is reserver word
end record;
package FileEvent_Vectors is new Ada.Containers.Vectors (Positive, FileEvent);
--```typescript
--interface DidChangeWatchedFilesParams {
-- /**
-- * The actual file events.
-- */
-- changes: FileEvent[];
--}
--```
type DidChangeWatchedFilesParams is record
changes: FileEvent_Vectors.Vector;
end record;
--```typescript
--interface PublishDiagnosticsParams {
-- /**
-- * The URI for which diagnostic information is reported.
-- */
-- uri: DocumentUri;
--
-- /**
-- * An array of diagnostic information items.
-- */
-- diagnostics: Diagnostic[];
--}
--```
type PublishDiagnosticsParams is record
uri: DocumentUri;
diagnostics: Diagnostic_Vector;
end record;
--```typescript
--/**
-- * Represents a collection of [completion items](#CompletionItem) to be presented
-- * in the editor.
-- */
--interface CompletionList {
-- /**
-- * This list it not complete. Further typing should result in recomputing
-- * this list.
-- */
-- isIncomplete: boolean;
-- /**
-- * The completion items.
-- */
-- items: CompletionItem[];
--}
--
--/**
-- * Defines whether the insert text in a completion item should be interpreted as
-- * plain text or a snippet.
-- */
--namespace InsertTextFormat {
-- /**
-- * The primary text to be inserted is treated as a plain string.
-- */
-- export const PlainText = 1;
--
-- /**
-- * The primary text to be inserted is treated as a snippet.
-- *
-- * A snippet can define tab stops and placeholders with `$1`, `$2`
-- * and `${3:foo}`. `$0` defines the final tab stop, it defaults to
-- * the end of the snippet. Placeholders with equal identifiers are linked,
-- * that is typing in one will update others too.
-- *
-- * See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md
-- */
-- export const Snippet = 2;
--}
--
--type InsertTextFormat = 1 | 2;
--
--interface CompletionItem {
-- /**
-- * The label of this completion item. By default
-- * also the text that is inserted when selecting
-- * this completion.
-- */
-- label: string;
-- /**
-- * The kind of this completion item. Based of the kind
-- * an icon is chosen by the editor.
-- */
-- kind?: number;
-- /**
-- * A human-readable string with additional information
-- * about this item, like type or symbol information.
-- */
-- detail?: string;
-- /**
-- * A human-readable string that represents a doc-comment.
-- */
-- documentation?: string;
-- /**
-- * A string that shoud be used when comparing this item
-- * with other items. When `falsy` the label is used.
-- */
-- sortText?: string;
-- /**
-- * A string that should be used when filtering a set of
-- * completion items. When `falsy` the label is used.
-- */
-- filterText?: string;
-- /**
-- * A string that should be inserted a document when selecting
-- * this completion. When `falsy` the label is used.
-- */
-- insertText?: string;
-- /**
-- * The format of the insert text. The format applies to both the `insertText` property
-- * and the `newText` property of a provided `textEdit`.
-- */
-- insertTextFormat?: InsertTextFormat;
-- /**
-- * An edit which is applied to a document when selecting this completion. When an edit is provided the value of
-- * `insertText` is ignored.
-- *
-- * *Note:* The range of the edit must be a single line range and it must contain the position at which completion
-- * has been requested.
-- */
-- textEdit?: TextEdit;
-- /**
-- * An optional array of additional text edits that are applied when
-- * selecting this completion. Edits must not overlap with the main edit
-- * nor with themselves.
-- */
-- additionalTextEdits?: TextEdit[];
-- /**
-- * An optional set of characters that when pressed while this completion is active will accept it first and
-- * then type that character. *Note* that all commit characters should have `length=1` and that superfluous
-- * characters will be ignored.
-- */
-- commitCharacters?: string[];
-- /**
-- * An optional command that is executed *after* inserting this completion. *Note* that
-- * additional modifications to the current document should be described with the
-- * additionalTextEdits-property.
-- */
-- command?: Command;
-- /**
-- * An data entry field that is preserved on a completion item between
-- * a completion and a completion resolve request.
-- */
-- data?: any
--}
--
--/**
-- * The kind of a completion entry.
-- */
--namespace CompletionItemKind {
-- export const Text = 1;
-- export const Method = 2;
-- export const Function = 3;
-- export const Constructor = 4;
-- export const Field = 5;
-- export const Variable = 6;
-- export const Class = 7;
-- export const Interface = 8;
-- export const Module = 9;
-- export const Property = 10;
-- export const Unit = 11;
-- export const Value = 12;
-- export const Enum = 13;
-- export const Keyword = 14;
-- export const Snippet = 15;
-- export const Color = 16;
-- export const File = 17;
-- export const Reference = 18;
--}
--```
type InsertTextFormat is (PlainText, Snippet);
not overriding procedure Write_InsertTextFormat
(S : access Ada.Streams.Root_Stream_Type'Class;
V : InsertTextFormat);
for InsertTextFormat'Write use Write_InsertTextFormat;
package Optional_InsertTextFormats is new LSP.Generic_Optional (InsertTextFormat);
type Optional_InsertTextFormat is new Optional_InsertTextFormats.Optional_Type;
type CompletionItemKind is (
Text,
Method,
A_Function,
Constructor,
Field,
Variable,
Class,
An_Interface,
Module,
Property,
Unit,
Value,
Enum,
Keyword,
Snippet,
Color,
File,
Reference);
not overriding procedure Write_CompletionItemKind
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CompletionItemKind);
for CompletionItemKind'Write use Write_CompletionItemKind;
package Optional_CompletionItemKinds is new LSP.Generic_Optional (CompletionItemKind);
type Optional_CompletionItemKind is new Optional_CompletionItemKinds.Optional_Type;
type CompletionItem is record
label: LSP_String;
kind: Optional_CompletionItemKind;
detail: Optional_String;
documentation: Optional_String;
sortText: Optional_String;
filterText: Optional_String;
insertText: Optional_String;
insertTextFormat: Optional_InsertTextFormat;
textEdit: Optional_TextEdit;
additionalTextEdits: TextEdit_Vector;
commitCharacters: LSP_String_Vector;
command: LSP.Messages.Command; -- Optional ???
-- data?: any
end record;
not overriding procedure Write_CompletionItem
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CompletionItem);
for CompletionItem'Write use Write_CompletionItem;
package CompletionItem_Vectors is new Ada.Containers.Vectors
(Positive, CompletionItem);
type CompletionList is record
isIncomplete: Boolean := False;
items: CompletionItem_Vectors.Vector;
end record;
type Completion_Response is new ResponseMessage with record
result: CompletionList;
end record;
--```typescript
--/**
-- * MarkedString can be used to render human readable text. It is either a markdown string
-- * or a code-block that provides a language and a code snippet. The language identifier
-- * is sematically equal to the optional language identifier in fenced code blocks in GitHub
-- * issues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting
-- *
-- * The pair of a language and a value is an equivalent to markdown:
-- * ```${language}
-- * ${value}
-- * ```
-- *
-- * Note that markdown strings will be sanitized - that means html will be escaped.
-- */
--type MarkedString = string | { language: string; value: string };
--```
type MarkedString (Is_String : Boolean := True) is record
value : LSP_String;
case Is_String is
when True =>
null;
when False =>
language : LSP_String;
end case;
end record;
not overriding procedure Write_MarkedString
(S : access Ada.Streams.Root_Stream_Type'Class;
V : MarkedString);
for MarkedString'Write use Write_MarkedString;
package MarkedString_Vectors is new Ada.Containers.Vectors
(Positive, MarkedString);
--```typescript
--/**
-- * The result of a hover request.
-- */
--interface Hover {
-- /**
-- * The hover's content
-- */
-- contents: MarkedString | MarkedString[];
--
-- /**
-- * An optional range is a range inside a text document
-- * that is used to visualize a hover, e.g. by changing the background color.
-- */
-- range?: Range;
--}
--```
type Hover is record
contents: MarkedString_Vectors.Vector;
Span: Optional_Span;
end record;
type Hover_Response is new ResponseMessage with record
result: Hover;
end record;
--```typescript
--/**
-- * Signature help represents the signature of something
-- * callable. There can be multiple signature but only one
-- * active and only one active parameter.
-- */
--interface SignatureHelp {
-- /**
-- * One or more signatures.
-- */
-- signatures: SignatureInformation[];
--
-- /**
-- * The active signature. If omitted or the value lies outside the
-- * range of `signatures` the value defaults to zero or is ignored if
-- * `signatures.length === 0`. Whenever possible implementors should
-- * make an active decision about the active signature and shouldn't
-- * rely on a default value.
-- * In future version of the protocol this property might become
-- * mandantory to better express this.
-- */
-- activeSignature?: number;
--
-- /**
-- * The active parameter of the active signature. If omitted or the value
-- * lies outside the range of `signatures[activeSignature].parameters`
-- * defaults to 0 if the active signature has parameters. If
-- * the active signature has no parameters it is ignored.
-- * In future version of the protocol this property might become
-- * mandantory to better express the active parameter if the
-- * active signature does have any.
-- */
-- activeParameter?: number;
--}
--
--/**
-- * Represents the signature of something callable. A signature
-- * can have a label, like a function-name, a doc-comment, and
-- * a set of parameters.
-- */
--interface SignatureInformation {
-- /**
-- * The label of this signature. Will be shown in
-- * the UI.
-- */
-- label: string;
--
-- /**
-- * The human-readable doc-comment of this signature. Will be shown
-- * in the UI but can be omitted.
-- */
-- documentation?: string;
--
-- /**
-- * The parameters of this signature.
-- */
-- parameters?: ParameterInformation[];
--}
--
--/**
-- * Represents a parameter of a callable-signature. A parameter can
-- * have a label and a doc-comment.
-- */
--interface ParameterInformation {
-- /**
-- * The label of this parameter. Will be shown in
-- * the UI.
-- */
-- label: string;
--
-- /**
-- * The human-readable doc-comment of this parameter. Will be shown
-- * in the UI but can be omitted.
-- */
-- documentation?: string;
--}
--```
type ParameterInformation is record
label: LSP_String;
documentation: Optional_String;
end record;
not overriding procedure Write_ParameterInformation
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ParameterInformation);
for ParameterInformation'Write use Write_ParameterInformation;
package ParameterInformation_Vectors is new Ada.Containers.Vectors
(Positive, ParameterInformation);
type SignatureInformation is record
label: LSP_String;
documentation: Optional_String;
parameters: ParameterInformation_Vectors.Vector;
end record;
not overriding procedure Write_SignatureInformation
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SignatureInformation);
for SignatureInformation'Write use Write_SignatureInformation;
package SignatureInformation_Vectors is new Ada.Containers.Vectors
(Positive, SignatureInformation);
type SignatureHelp is record
signatures: SignatureInformation_Vectors.Vector;
activeSignature: Optional_Number;
activeParameter: Optional_Number;
end record;
type SignatureHelp_Response is new ResponseMessage with record
result: SignatureHelp;
end record;
--```typescript
--interface ReferenceContext {
-- /**
-- * Include the declaration of the current symbol.
-- */
-- includeDeclaration: boolean;
--}
--```
type ReferenceContext is record
includeDeclaration: Boolean;
end record;
--```typescript
--interface ReferenceParams extends TextDocumentPositionParams {
-- context: ReferenceContext
--}
--```
type ReferenceParams is new TextDocumentPositionParams with record
context: ReferenceContext;
end record;
--```typescript
--/**
-- * A document highlight is a range inside a text document which deserves
-- * special attention. Usually a document highlight is visualized by changing
-- * the background color of its range.
-- *
-- */
--interface DocumentHighlight {
-- /**
-- * The range this highlight applies to.
-- */
-- range: Range;
--
-- /**
-- * The highlight kind, default is DocumentHighlightKind.Text.
-- */
-- kind?: number;
--}
--
--/**
-- * A document highlight kind.
-- */
--export namespace DocumentHighlightKind {
-- /**
-- * A textual occurrence.
-- */
-- export const Text = 1;
--
-- /**
-- * Read-access of a symbol, like reading a variable.
-- */
-- export const Read = 2;
--
-- /**
-- * Write-access of a symbol, like writing to a variable.
-- */
-- export const Write = 3;
--}
--```
type DocumentHighlightKind is (Unspecified, Text, Read, Write);
type DocumentHighlight is record
span: LSP.Messages.Span;
kind: DocumentHighlightKind;
end record;
not overriding procedure Write_DocumentHighlight
(S : access Ada.Streams.Root_Stream_Type'Class;
V : DocumentHighlight);
for DocumentHighlight'Write use Write_DocumentHighlight;
package DocumentHighlight_Vectors is new Ada.Containers.Vectors
(Positive, DocumentHighlight);
type Highlight_Response is new ResponseMessage with record
result: DocumentHighlight_Vectors.Vector;
end record;
--```typescript
--interface DocumentSymbolParams {
-- /**
-- * The text document.
-- */
-- textDocument: TextDocumentIdentifier;
--}
--```
type DocumentSymbolParams is record
textDocument: TextDocumentIdentifier;
end record;
--```typescript
--/**
-- * Represents information about programming constructs like variables, classes,
-- * interfaces etc.
-- */
--interface SymbolInformation {
-- /**
-- * The name of this symbol.
-- */
-- name: string;
--
-- /**
-- * The kind of this symbol.
-- */
-- kind: number;
--
-- /**
-- * The location of this symbol. The location's range is used by a tool
-- * to reveal the location in the editor. If the symbol is selected in the
-- * tool the range's start information is used to position the cursor. So
-- * the range usually spwans more then the actual symbol's name and does
-- * normally include thinks like visibility modifiers.
-- *
-- * The range doesn't have to denote a node range in the sense of a abstract
-- * syntax tree. It can therefore not be used to re-construct a hierarchy of
-- * the symbols.
-- */
-- location: Location;
--
-- /**
-- * The name of the symbol containing this symbol. This information is for
-- * user interface purposes (e.g. to render a qaulifier in the user interface
-- * if necessary). It can't be used to re-infer a hierarchy for the document
-- * symbols.
-- */
-- containerName?: string;
--}
--
--/**
-- * A symbol kind.
-- */
--export namespace SymbolKind {
-- export const File = 1;
-- export const Module = 2;
-- export const Namespace = 3;
-- export const Package = 4;
-- export const Class = 5;
-- export const Method = 6;
-- export const Property = 7;
-- export const Field = 8;
-- export const Constructor = 9;
-- export const Enum = 10;
-- export const Interface = 11;
-- export const Function = 12;
-- export const Variable = 13;
-- export const Constant = 14;
-- export const String = 15;
-- export const Number = 16;
-- export const Boolean = 17;
-- export const Array = 18;
--}
--```
type SymbolKind is
(File,
Module,
Namespace,
A_Package,
Class,
Method,
Property,
Field,
Constructor,
Enum,
An_Interface,
A_Function,
Variable,
A_Constant,
String,
Number,
A_Boolean,
An_Array);
type SymbolInformation is record
name: LSP_String;
kind: SymbolKind;
location: LSP.Messages.Location;
containerName: Optional_String;
end record;
not overriding procedure Write_SymbolInformation
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SymbolInformation);
for SymbolInformation'Write use Write_SymbolInformation;
package SymbolInformation_Vectors is new Ada.Containers.Vectors
(Positive, SymbolInformation);
type SymbolInformation_Vector is
new SymbolInformation_Vectors.Vector with null record;
type Symbol_Response is new ResponseMessage with record
result: SymbolInformation_Vector;
end record;
--```typescript
--/**
-- * The parameters of a Workspace Symbol Request.
-- */
--interface WorkspaceSymbolParams {
-- /**
-- * A non-empty query string
-- */
-- query: string;
--}
--```
type WorkspaceSymbolParams is record
query: LSP_String;
end record;
--```typescript
--/**
-- * Params for the CodeActionRequest
-- */
--interface CodeActionParams {
-- /**
-- * The document in which the command was invoked.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The range for which the command was invoked.
-- */
-- range: Range;
--
-- /**
-- * Context carrying additional information.
-- */
-- context: CodeActionContext;
--}
--
--/**
-- * Contains additional diagnostic information about the context in which
-- * a code action is run.
-- */
--interface CodeActionContext {
-- /**
-- * An array of diagnostics.
-- */
-- diagnostics: Diagnostic[];
--}
--```
type CodeActionContext is record
diagnostics: Diagnostic_Vector;
end record;
type CodeActionParams is record
textDocument: TextDocumentIdentifier;
span: LSP.Messages.Span;
context: CodeActionContext;
end record;
type CodeAction_Response is new ResponseMessage with record
result: Command_Vector;
end record;
--```typescript
--interface CodeLensParams {
-- /**
-- * The document to request code lens for.
-- */
-- textDocument: TextDocumentIdentifier;
--}
--```
type CodeLensParams is record
textDocument: TextDocumentIdentifier;
end record;
--```typescript
--/**
-- * A code lens represents a command that should be shown along with
-- * source text, like the number of references, a way to run tests, etc.
-- *
-- * A code lens is _unresolved_ when no command is associated to it. For performance
-- * reasons the creation of a code lens and resolving should be done in two stages.
-- */
--interface CodeLens {
-- /**
-- * The range in which this code lens is valid. Should only span a single line.
-- */
-- range: Range;
--
-- /**
-- * The command this code lens represents.
-- */
-- command?: Command;
--
-- /**
-- * A data entry field that is preserved on a code lens item between
-- * a code lens and a code lens resolve request.
-- */
-- data?: any
--}
--```
type CodeLens is record
span: LSP.Messages.Span;
command: LSP.Messages.Command; -- Optional ???
-- data?: any
end record;
--```typescript
--interface DocumentLinkParams {
-- /**
-- * The document to provide document links for.
-- */
-- textDocument: TextDocumentIdentifier;
--}
--```
type DocumentLinkParams is record
textDocument: TextDocumentIdentifier;
end record;
--```typescript
--/**
-- * A document link is a range in a text document that links to an internal or external resource, like another
-- * text document or a web site.
-- */
--interface DocumentLink {
-- /**
-- * The range this link applies to.
-- */
-- range: Range;
-- /**
-- * The uri this link points to. If missing a resolve request is sent later.
-- */
-- target?: DocumentUri;
--}
--```
type DocumentLink is record
span: LSP.Messages.Span;
target: DocumentUri; -- Optional ???
end record;
--```typescript
--interface DocumentFormattingParams {
-- /**
-- * The document to format.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The format options.
-- */
-- options: FormattingOptions;
--}
--
--/**
-- * Value-object describing what options formatting should use.
-- */
--interface FormattingOptions {
-- /**
-- * Size of a tab in spaces.
-- */
-- tabSize: number;
--
-- /**
-- * Prefer spaces over tabs.
-- */
-- insertSpaces: boolean;
--
-- /**
-- * Signature for further properties.
-- */
-- [key: string]: boolean | number | string;
--}
--```
type FormattingOptions is record
tabSize: LSP_Number;
insertSpaces: Boolean;
-- [key: string]: boolean | number | string; ???
end record;
type DocumentFormattingParams is record
textDocument: TextDocumentIdentifier;
options: FormattingOptions;
end record;
--```typescript
--interface DocumentRangeFormattingParams {
-- /**
-- * The document to format.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The range to format
-- */
-- range: Range;
--
-- /**
-- * The format options
-- */
-- options: FormattingOptions;
--}
--```
type DocumentRangeFormattingParams is record
textDocument: TextDocumentIdentifier;
span: LSP.Messages.Span;
options: FormattingOptions;
end record;
--```typescript
--interface DocumentOnTypeFormattingParams {
-- /**
-- * The document to format.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The position at which this request was sent.
-- */
-- position: Position;
--
-- /**
-- * The character that has been typed.
-- */
-- ch: string;
--
-- /**
-- * The format options.
-- */
-- options: FormattingOptions;
--}
--```
type DocumentOnTypeFormattingParams is record
textDocument: TextDocumentIdentifier;
position: LSP.Messages.Position;
ch: LSP_String;
options: FormattingOptions;
end record;
--```typescript
--interface RenameParams {
-- /**
-- * The document to format.
-- */
-- textDocument: TextDocumentIdentifier;
--
-- /**
-- * The position at which this request was sent.
-- */
-- position: Position;
--
-- /**
-- * The new name of the symbol. If the given name is not valid the
-- * request must return a [ResponseError](#ResponseError) with an
-- * appropriate message set.
-- */
-- newName: string;
--}
--```
type RenameParams is record
textDocument: TextDocumentIdentifier;
position: LSP.Messages.Position;
newName: LSP_String;
end record;
--```typescript
--export interface ExecuteCommandParams {
--
-- /**
-- * The identifier of the actual command handler.
-- */
-- command: string;
-- /**
-- * Arguments that the command should be invoked with.
-- */
-- arguments?: any[];
--}
--```
type ExecuteCommandParams is record
command: LSP_String;
arguments: LSP_Any;
end record;
type ExecuteCommand_Response is new ResponseMessage with null record;
--```typescript
--export interface ApplyWorkspaceEditParams {
-- /**
-- * The edits to apply.
-- */
-- edit: WorkspaceEdit;
--}
--```
type ApplyWorkspaceEditParams is record
edit: WorkspaceEdit;
end record;
--```typescript
--export interface ApplyWorkspaceEditResponse {
-- /**
-- * Indicates whether the edit was applied or not.
-- */
-- applied: boolean;
--}
--```
type ApplyWorkspaceEditResponse is record
applied: Boolean;
end record;
type PublishDiagnostics_Notification is new NotificationMessage with record
params : PublishDiagnosticsParams;
end record;
type ApplyWorkspaceEdit_Request is new RequestMessage with record
params : ApplyWorkspaceEditParams;
end record;
type Location_Response is new ResponseMessage with record
result : Location_Vectors.Vector;
end record;
private
not overriding procedure Read_ClientCapabilities
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out ClientCapabilities);
not overriding procedure Read_CodeActionContext
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out CodeActionContext);
not overriding procedure Read_CodeActionParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out CodeActionParams);
not overriding procedure Read_completion
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out completion);
not overriding procedure Read_Diagnostic_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out Diagnostic_Vector);
not overriding procedure Read_DidChangeConfigurationParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DidChangeConfigurationParams);
not overriding procedure Read_DidChangeTextDocumentParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DidChangeTextDocumentParams);
not overriding procedure Read_DidCloseTextDocumentParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DidCloseTextDocumentParams);
not overriding procedure Read_DidOpenTextDocumentParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DidOpenTextDocumentParams);
not overriding procedure Read_DidSaveTextDocumentParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DidSaveTextDocumentParams);
not overriding procedure Read_DocumentSymbolParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out DocumentSymbolParams);
not overriding procedure Read_dynamicRegistration
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out dynamicRegistration);
not overriding procedure Read_ExecuteCommandParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out ExecuteCommandParams);
not overriding procedure Read_InitializeParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out InitializeParams);
not overriding procedure Read_ReferenceContext
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out ReferenceContext);
not overriding procedure Read_ReferenceParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out ReferenceParams);
not overriding procedure Read_synchronization
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out synchronization);
not overriding procedure Read_TextDocumentClientCapabilities
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentClientCapabilities);
not overriding procedure Read_TextDocumentItem
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out TextDocumentItem);
not overriding procedure Read_WorkspaceClientCapabilities
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out WorkspaceClientCapabilities);
not overriding procedure Read_WorkspaceSymbolParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : out WorkspaceSymbolParams);
not overriding procedure Write_ApplyWorkspaceEdit_Request
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ApplyWorkspaceEdit_Request);
not overriding procedure Write_ApplyWorkspaceEditParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ApplyWorkspaceEditParams);
not overriding procedure Write_CodeAction_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CodeAction_Response);
not overriding procedure Write_Command_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Command_Vector);
not overriding procedure Write_Completion_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Completion_Response);
not overriding procedure Write_CompletionList
(S : access Ada.Streams.Root_Stream_Type'Class;
V : CompletionList);
not overriding procedure Write_Diagnostic_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Diagnostic_Vector);
not overriding procedure Write_DocumentLinkOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : DocumentLinkOptions);
not overriding procedure Write_ExecuteCommand_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ExecuteCommand_Response);
not overriding procedure Write_ExecuteCommandOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ExecuteCommandOptions);
not overriding procedure Write_Highlight_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Highlight_Response);
not overriding procedure Write_Hover
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Hover);
not overriding procedure Write_Hover_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Hover_Response);
not overriding procedure Write_Initialize_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Initialize_Response);
not overriding procedure Write_InitializeResult
(S : access Ada.Streams.Root_Stream_Type'Class;
V : InitializeResult);
not overriding procedure Write_Location_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Location_Response);
not overriding procedure Write_Optional_TextDocumentSyncOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Optional_TextDocumentSyncOptions);
not overriding procedure Write_PublishDiagnostics_Notification
(S : access Ada.Streams.Root_Stream_Type'Class;
V : PublishDiagnostics_Notification);
not overriding procedure Write_PublishDiagnosticsParams
(S : access Ada.Streams.Root_Stream_Type'Class;
V : PublishDiagnosticsParams);
not overriding procedure Write_ServerCapabilities
(S : access Ada.Streams.Root_Stream_Type'Class;
V : ServerCapabilities);
not overriding procedure Write_SignatureHelp
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SignatureHelp);
not overriding procedure Write_SignatureHelp_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SignatureHelp_Response);
not overriding procedure Write_Symbol_Response
(S : access Ada.Streams.Root_Stream_Type'Class;
V : Symbol_Response);
not overriding procedure Write_SymbolInformation_Vector
(S : access Ada.Streams.Root_Stream_Type'Class;
V : SymbolInformation_Vector);
not overriding procedure Write_TextDocumentSyncOptions
(S : access Ada.Streams.Root_Stream_Type'Class;
V : TextDocumentSyncOptions);
not overriding procedure Write_WorkspaceEdit
(S : access Ada.Streams.Root_Stream_Type'Class;
V : WorkspaceEdit);
for ApplyWorkspaceEdit_Request'Write use Write_ApplyWorkspaceEdit_Request;
for ApplyWorkspaceEditParams'Write use Write_ApplyWorkspaceEditParams;
for CodeAction_Response'Write use Write_CodeAction_Response;
for Command_Vector'Write use Write_Command_Vector;
for Completion_Response'Write use Write_Completion_Response;
for CompletionList'Write use Write_CompletionList;
for Diagnostic_Vector'Write use Write_Diagnostic_Vector;
for DocumentLinkOptions'Write use Write_DocumentLinkOptions;
for ExecuteCommand_Response'Write use Write_ExecuteCommand_Response;
for ExecuteCommandOptions'Write use Write_ExecuteCommandOptions;
for Highlight_Response'Write use Write_Highlight_Response;
for Hover'Write use Write_Hover;
for Hover_Response'Write use Write_Hover_Response;
for Initialize_Response'Write use Write_Initialize_Response;
for InitializeResult'Write use Write_InitializeResult;
for Location_Response'Write use Write_Location_Response;
for Optional_TextDocumentSyncOptions'Write use Write_Optional_TextDocumentSyncOptions;
for PublishDiagnostics_Notification'Write use Write_PublishDiagnostics_Notification;
for PublishDiagnosticsParams'Write use Write_PublishDiagnosticsParams;
for ServerCapabilities'Write use Write_ServerCapabilities;
for SignatureHelp'Write use Write_SignatureHelp;
for SignatureHelp_Response'Write use Write_SignatureHelp_Response;
for Symbol_Response'Write use Write_Symbol_Response;
for SymbolInformation_Vector'Write use Write_SymbolInformation_Vector;
for TextDocumentItem'Read use Read_TextDocumentItem;
for TextDocumentSyncOptions'Write use Write_TextDocumentSyncOptions;
for WorkspaceEdit'Write use Write_WorkspaceEdit;
for ClientCapabilities'Read use Read_ClientCapabilities;
for CodeActionContext'Read use Read_CodeActionContext;
for CodeActionParams'Read use Read_CodeActionParams;
for completion'Read use Read_completion;
for Diagnostic_Vector'Read use Read_Diagnostic_Vector;
for DidChangeConfigurationParams'Read use Read_DidChangeConfigurationParams;
for DidChangeTextDocumentParams'Read use Read_DidChangeTextDocumentParams;
for DidCloseTextDocumentParams'Read use Read_DidCloseTextDocumentParams;
for DidOpenTextDocumentParams'Read use Read_DidOpenTextDocumentParams;
for DidSaveTextDocumentParams'Read use Read_DidSaveTextDocumentParams;
for DocumentSymbolParams'Read use Read_DocumentSymbolParams;
for dynamicRegistration'Read use Read_dynamicRegistration;
for ExecuteCommandParams'Read use Read_ExecuteCommandParams;
for InitializeParams'Read use Read_InitializeParams;
for ReferenceContext'Read use Read_ReferenceContext;
for ReferenceParams'Read use Read_ReferenceParams;
for synchronization'Read use Read_synchronization;
for TextDocumentClientCapabilities'Read use Read_TextDocumentClientCapabilities;
for WorkspaceClientCapabilities'Read use Read_WorkspaceClientCapabilities;
for WorkspaceSymbolParams'Read use Read_WorkspaceSymbolParams;
end LSP.Messages;
|
with Ada.Text_Io; use Ada.Text_Io;
procedure Bottles is
begin
for X in reverse 1..99 loop
Put_Line(Integer'Image(X) & " bottles of beer on the wall");
Put_Line(Integer'Image(X) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(X - 1) & " bottles of beer on the wall");
New_Line;
end loop;
end Bottles;
|
with Ada.Numerics.dSFMT.Generating;
with System.Formatting;
with System.Long_Long_Integer_Types;
with System.Random_Initiators;
with System.Storage_Elements;
package body Ada.Numerics.dSFMT is
pragma Check_Policy (Validate => Ignore);
use type Interfaces.Unsigned_32;
use type Interfaces.Unsigned_64;
use type System.Storage_Elements.Storage_Offset;
subtype Word_Unsigned is System.Long_Long_Integer_Types.Word_Unsigned;
subtype Long_Long_Unsigned is
System.Long_Long_Integer_Types.Long_Long_Unsigned;
procedure memset (
b : System.Address;
c : Integer;
n : System.Storage_Elements.Storage_Count)
with Import,
Convention => Intrinsic, External_Name => "__builtin_memset";
type Long_Boolean is new Boolean;
for Long_Boolean'Size use Long_Integer'Size;
function expect (exp, c : Long_Boolean) return Long_Boolean
with Import,
Convention => Intrinsic, External_Name => "__builtin_expect";
package Impl is new Generating;
-- STATIC FUNCTIONS
function ini_func1 (x : Unsigned_32) return Unsigned_32
with Convention => Intrinsic;
function ini_func2 (x : Unsigned_32) return Unsigned_32
with Convention => Intrinsic;
pragma Inline_Always (ini_func1);
pragma Inline_Always (ini_func2);
procedure gen_rand_array_c1o2 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
with Convention => Intrinsic;
procedure gen_rand_array_c0o1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
with Convention => Intrinsic;
procedure gen_rand_array_o0c1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
with Convention => Intrinsic;
procedure gen_rand_array_o0o1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
with Convention => Intrinsic;
pragma Inline_Always (gen_rand_array_c1o2);
pragma Inline_Always (gen_rand_array_c0o1);
pragma Inline_Always (gen_rand_array_o0c1);
pragma Inline_Always (gen_rand_array_o0o1);
function idxof (i : Integer) return Integer
with Convention => Intrinsic;
pragma Inline_Always (idxof);
procedure initial_mask (dsfmt : in out State);
procedure period_certification (dsfmt : in out State);
-- This function simulate a 32-bit array index overlapped to 64-bit array
-- of LITTLE ENDIAN in BIG ENDIAN machine.
function idxof (i : Integer) return Integer is
type Unsigned is mod 2 ** Integer'Size;
begin
case System.Default_Bit_Order is
when System.High_Order_First =>
return Integer (Unsigned'Mod (i) xor 1);
when System.Low_Order_First =>
return i;
end case;
end idxof;
-- This function fills the user-specified array with double precision
-- floating point pseudorandom numbers of the IEEE 754 format.
procedure gen_rand_array_c1o2 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
is
pragma Suppress (Index_Check);
the_array : w128_t_Array (0 .. size - 1);
for the_array'Address use Item'Address;
i, j : Integer;
lung : aliased w128_t := dsfmt.lung;
begin
Impl.do_recursion (
the_array (0),
dsfmt.status (0),
dsfmt.status (POS1),
lung);
i := 1;
while i < N - POS1 loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
dsfmt.status (i + POS1),
lung);
i := i + 1;
end loop;
while i < N loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
the_array (i - (N - POS1)),
lung);
i := i + 1;
end loop;
while i < size - N loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
i := i + 1;
end loop;
j := 0;
while j < N - (size - N) loop
dsfmt.status (j) := the_array (j + (size - N));
j := j + 1;
end loop;
while i < size loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
dsfmt.status (j) := the_array (i);
i := i + 1;
j := j + 1;
end loop;
dsfmt.lung := lung;
end gen_rand_array_c1o2;
-- This function fills the user-specified array with double precision
-- floating point pseudorandom numbers of the IEEE 754 format.
procedure gen_rand_array_c0o1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
is
pragma Suppress (Index_Check);
the_array : w128_t_Array (0 .. size - 1);
for the_array'Address use Item'Address;
i, j : Integer;
lung : aliased w128_t := dsfmt.lung;
begin
Impl.do_recursion (
the_array (0),
dsfmt.status (0),
dsfmt.status (POS1),
lung);
i := 1;
while i < N - POS1 loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
dsfmt.status (i + POS1),
lung);
i := i + 1;
end loop;
while i < N loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
the_array (i - (N - POS1)),
lung);
i := i + 1;
end loop;
while i < size - N loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
Impl.convert_c0o1 (the_array (i - N)); -- [0 .. size - 2 * N)
i := i + 1;
end loop;
j := 0;
while j < N - (size - N) loop
dsfmt.status (j) := the_array (j + (size - N));
j := j + 1;
end loop;
while i < size loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
dsfmt.status (j) := the_array (i);
Impl.convert_c0o1 (the_array (i - N)); -- [size - 2 * N .. size - N)
i := i + 1;
j := j + 1;
end loop;
i := size - N;
while i < size loop
Impl.convert_c0o1 (the_array (i)); -- [size - N .. size)
i := i + 1;
end loop;
dsfmt.lung := lung;
end gen_rand_array_c0o1;
-- This function fills the user-specified array with double precision
-- floating point pseudorandom numbers of the IEEE 754 format.
procedure gen_rand_array_o0c1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
is
pragma Suppress (Index_Check);
the_array : w128_t_Array (0 .. size - 1);
for the_array'Address use Item'Address;
i, j : Integer;
lung : aliased w128_t := dsfmt.lung;
begin
Impl.do_recursion (
the_array (0),
dsfmt.status (0),
dsfmt.status (POS1),
lung);
i := 1;
while i < N - POS1 loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
dsfmt.status (i + POS1),
lung);
i := i + 1;
end loop;
while i < N loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
the_array (i - (N - POS1)),
lung);
i := i + 1;
end loop;
while i < size - N loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
Impl.convert_o0c1 (the_array (i - N));
i := i + 1;
end loop;
j := 0;
while j < N - (size - N) loop
dsfmt.status (j) := the_array (j + (size - N));
j := j + 1;
end loop;
while i < size loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
dsfmt.status (j) := the_array (i);
Impl.convert_o0c1 (the_array (i - N));
i := i + 1;
j := j + 1;
end loop;
i := size - N;
while i < size loop
Impl.convert_o0c1 (the_array (i));
i := i + 1;
end loop;
dsfmt.lung := lung;
end gen_rand_array_o0c1;
-- This function fills the user-specified array with double precision
-- floating point pseudorandom numbers of the IEEE 754 format.
procedure gen_rand_array_o0o1 (
dsfmt : in out State;
Item : out w128_t_Array_1;
size : Integer)
is
pragma Suppress (Index_Check);
the_array : w128_t_Array (0 .. size - 1);
for the_array'Address use Item'Address;
i, j : Integer;
lung : aliased w128_t := dsfmt.lung;
begin
Impl.do_recursion (
the_array (0),
dsfmt.status (0),
dsfmt.status (POS1),
lung);
i := 1;
while i < N - POS1 loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
dsfmt.status (i + POS1),
lung);
i := i + 1;
end loop;
while i < N loop
Impl.do_recursion (
the_array (i),
dsfmt.status (i),
the_array (i - (N - POS1)),
lung);
i := i + 1;
end loop;
while i < size - N loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
Impl.convert_o0o1 (the_array (i - N));
i := i + 1;
end loop;
j := 0;
while j < N - (size - N) loop
dsfmt.status (j) := the_array (j + (size - N));
j := j + 1;
end loop;
while i < size loop
Impl.do_recursion (
the_array (i),
the_array (i - N),
the_array (i - (N - POS1)),
lung);
dsfmt.status (j) := the_array (i);
Impl.convert_o0o1 (the_array (i - N));
i := i + 1;
j := j + 1;
end loop;
i := size - N;
while i < size loop
Impl.convert_o0o1 (the_array (i));
i := i + 1;
end loop;
dsfmt.lung := lung;
end gen_rand_array_o0o1;
-- This function represents a function used in the initialization by
-- init_by_array
function ini_func1 (x : Unsigned_32) return Unsigned_32 is
begin
return (x xor Interfaces.Shift_Right (x, 27)) * Unsigned_32'(1664525);
end ini_func1;
-- This function represents a function used in the initialization by
-- init_by_array
function ini_func2 (x : Unsigned_32) return Unsigned_32 is
begin
return (x xor Interfaces.Shift_Right (x, 27)) * Unsigned_32'(1566083941);
end ini_func2;
-- This function initializes the internal state array to fit the IEEE 754
-- format.
procedure initial_mask (dsfmt : in out State) is
psfmt : Unsigned_64_Array (0 .. N * 2 - 1);
for psfmt'Address use dsfmt.status'Address;
begin
for i in 0 .. N * 2 - 1 loop
psfmt (i) := (psfmt (i) and LOW_MASK) or HIGH_CONST;
end loop;
end initial_mask;
-- This function certificate the period of 2^{SFMT_MEXP}-1.
procedure period_certification (dsfmt : in out State) is
pcv : constant array (0 .. 1) of Unsigned_64 := (PCV1, PCV2);
tmp : array (0 .. 1) of Unsigned_64;
inner : Unsigned_64;
work : Unsigned_64;
begin
tmp (0) := dsfmt.lung (0) xor FIX1;
tmp (1) := dsfmt.lung (1) xor FIX2;
inner := tmp (0) and pcv (0);
inner := inner xor (tmp (1) and pcv (1));
declare
i : Natural := 32;
begin
while i > 0 loop
inner := inner xor Interfaces.Shift_Right (inner, i);
i := i / 2;
end loop;
end;
inner := inner and 1;
-- check OK
if inner = 1 then
return;
end if;
-- check NG, and modification
if (PCV2 and 1) = 1 then
dsfmt.lung (1) := dsfmt.lung (1) xor 1;
else
for i in reverse 0 .. 1 loop
work := 1;
for j in 0 .. 64 - 1 loop
if (work and pcv (i)) /= 0 then
dsfmt.lung (i) := dsfmt.lung (i) xor work;
return;
end if;
work := Interfaces.Shift_Left (work, 1);
end loop;
end loop;
end if;
end period_certification;
-- PUBLIC FUNCTIONS
procedure dsfmt_gen_rand_all (dsfmt : in out State);
procedure dsfmt_chk_init_gen_rand (
dsfmt : in out State;
seed : Unsigned_32);
procedure dsfmt_chk_init_by_array (
dsfmt : in out State;
init_key : Unsigned_32_Array);
-- This function fills the internal state array with double precision
-- floating point pseudorandom numbers of the IEEE 754 format.
procedure dsfmt_gen_rand_all (dsfmt : in out State) is
pragma Suppress (Index_Check);
i : Integer;
lung : aliased w128_t := dsfmt.lung;
begin
Impl.do_recursion (
dsfmt.status (0),
dsfmt.status (0),
dsfmt.status (POS1),
lung);
i := 1;
while i < N - POS1 loop
Impl.do_recursion (
dsfmt.status (i),
dsfmt.status (i),
dsfmt.status (i + POS1),
lung);
i := i + 1;
end loop;
while i < N loop
Impl.do_recursion (
dsfmt.status (i),
dsfmt.status (i),
dsfmt.status (i - (N - POS1)),
lung);
i := i + 1;
end loop;
dsfmt.lung := lung;
end dsfmt_gen_rand_all;
-- This function initializes the internal state array with a 32-bit integer
-- seed.
procedure dsfmt_chk_init_gen_rand (
dsfmt : in out State;
seed : Unsigned_32) is
begin
-- make sure caller program is compiled with the same MEXP
-- fprintf(stderr, "DSFMT_MEXP doesn't match with dSFMT.c\n");
declare
psfmt : Unsigned_32_Array (0 .. (N + 1) * 4 - 1); -- including lung
for psfmt'Address use dsfmt.status'Address;
begin
psfmt (idxof (0)) := seed;
for i in 1 .. (N + 1) * 4 - 1 loop
psfmt (idxof (i)) :=
1812433253
* (
psfmt (idxof (i - 1))
xor Interfaces.Shift_Right (psfmt (idxof (i - 1)), 30))
+ Unsigned_32'Mod (i);
end loop;
end;
initial_mask (dsfmt);
period_certification (dsfmt);
dsfmt.idx := N64;
end dsfmt_chk_init_gen_rand;
-- This function initializes the internal state array, with an array of
-- 32-bit integers used as the seeds
procedure dsfmt_chk_init_by_array (
dsfmt : in out State;
init_key : Unsigned_32_Array)
is
key_length : constant Natural := init_key'Length;
count : Natural;
r : Unsigned_32;
lag : Natural;
mid : Natural;
size : constant Natural := (N + 1) * 4; -- pulmonary
begin
-- make sure caller program is compiled with the same MEXP
-- fprintf(stderr, "DSFMT_MEXP doesn't match with dSFMT.c\n");
if size >= 623 then
lag := 11;
elsif size >= 68 then
lag := 7;
elsif size >= 39 then
lag := 5;
else
lag := 3;
end if;
mid := (size - lag) / 2;
memset (
dsfmt.status'Address,
16#8b#,
System.Storage_Elements.Storage_Offset (
(N + 1) * (128 / Standard'Storage_Unit))); -- including lung
if key_length + 1 > size then
count := key_length + 1;
else
count := size;
end if;
declare
psfmt32 : Unsigned_32_Array (0 .. (N + 1) * 4 - 1); -- including lung
for psfmt32'Address use dsfmt.status'Address;
begin
r :=
ini_func1 (psfmt32 (idxof (0))
xor psfmt32 (idxof (mid rem size))
xor psfmt32 (idxof ((size - 1) rem size)));
declare
Index : constant Natural := idxof (mid rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
r := r + Unsigned_32'Mod (key_length);
declare
Index : constant Natural := idxof ((mid + lag) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
psfmt32 (idxof (0)) := r;
count := count - 1;
declare
i : Natural := 1;
begin
declare
j : Natural := 0;
begin
while j < count and then j < key_length loop
r :=
ini_func1 (psfmt32 (idxof (i))
xor psfmt32 (idxof ((i + mid) rem size))
xor psfmt32 (idxof ((i + (size - 1)) rem size)));
declare
Index : constant Natural := idxof ((i + mid) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
r := r + init_key (j) + Unsigned_32'Mod (i);
declare
Index : constant Natural :=
idxof ((i + mid + lag) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
psfmt32 (idxof (i)) := r;
i := (i + 1) rem size;
j := j + 1;
end loop;
while j < count loop
r :=
ini_func1 (psfmt32 (idxof (i))
xor psfmt32 (idxof ((i + mid) rem size))
xor psfmt32 (idxof ((i + (size - 1)) rem size)));
declare
Index : constant Natural := idxof ((i + mid) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
r := r + Unsigned_32'Mod (i);
declare
Index : constant Natural :=
idxof ((i + mid + lag) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) + r;
end;
psfmt32 (idxof (i)) := r;
i := (i + 1) rem size;
j := j + 1;
end loop;
end;
for j in 0 .. size - 1 loop
r :=
ini_func2 (psfmt32 (idxof (i))
+ psfmt32 (idxof ((i + mid) rem size))
+ psfmt32 (idxof ((i + (size - 1)) rem size)));
declare
Index : constant Natural := idxof ((i + mid) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) xor r;
end;
r := r - Unsigned_32'Mod (i);
declare
Index : constant Natural := idxof ((i + mid + lag) rem size);
begin
psfmt32 (Index) := psfmt32 (Index) xor r;
end;
psfmt32 (idxof (i)) := r;
i := (i + 1) rem size;
end loop;
end;
end;
initial_mask (dsfmt);
period_certification (dsfmt);
dsfmt.idx := N64;
end dsfmt_chk_init_by_array;
-- implementation
-- This function returns the identification string. The string shows the
-- Mersenne exponent, and all parameters of this generator.
-- equivalent to dsfmt_get_idstring
function Id return String is
-- e.g. "dSFMT2-19937:117-19:ffafffffffb3f-ffdfffc90fffd"
Result : String (
1 ..
6 + 1 -- "dSFMT2-"
+ 6 + 1 + 4 + 1 + 2 + 1 -- "216091:1890-23:"
+ 13 + 1 + 13); -- "%.13x-%.13x"
Last : Natural := 0;
Error : Boolean;
begin
Result (Last + 1 .. Last + 7) := "dSFMT2-";
Last := Last + 7;
System.Formatting.Image (
Word_Unsigned (MEXP),
Result (Last + 1 .. Result'Last),
Last,
Error => Error);
Result (Last + 1) := ':';
Last := Last + 1;
System.Formatting.Image (
Word_Unsigned (POS1),
Result (Last + 1 .. Result'Last),
Last,
Error => Error);
Result (Last + 1) := '-';
Last := Last + 1;
System.Formatting.Image (
Word_Unsigned (SL1),
Result (Last + 1 .. Result'Last),
Last,
Error => Error);
Result (Last + 1) := ':';
Last := Last + 1;
if Standard'Word_Size >= 64 then -- 52?
System.Formatting.Image (
Word_Unsigned (MSK1),
Result (Last + 1 .. Result'Last),
Last,
Base => 16,
Set => System.Formatting.Lower_Case,
Width => 13,
Error => Error);
else
System.Formatting.Image (
Long_Long_Unsigned (MSK1),
Result (Last + 1 .. Result'Last),
Last,
Base => 16,
Set => System.Formatting.Lower_Case,
Width => 13,
Error => Error);
end if;
Result (Last + 1) := '-';
Last := Last + 1;
if Standard'Word_Size >= 64 then -- 52?
System.Formatting.Image (
Word_Unsigned (MSK2),
Result (Last + 1 .. Result'Last),
Last,
Base => 16,
Set => System.Formatting.Lower_Case,
Width => 13,
Error => Error);
else
System.Formatting.Image (
Long_Long_Unsigned (MSK2),
Result (Last + 1 .. Result'Last),
Last,
Base => 16,
Set => System.Formatting.Lower_Case,
Width => 13,
Error => Error);
end if;
return Result (1 .. Last);
end Id;
-- This function generates and returns double precision pseudorandom number
-- which distributes uniformly in the range [1, 2). This is the
-- primitive and faster than generating numbers in other ranges.
-- equivalent to dsfmt_genrand_close1_open2
function Random_1_To_Less_Than_2 (Gen : aliased in out Generator)
return Long_Float
is
pragma Suppress (Index_Check);
dsfmt : State renames Gen.dsfmt;
idx : Integer := dsfmt.idx;
begin
if expect (Long_Boolean (idx >= N64), False) then
dsfmt_gen_rand_all (dsfmt);
idx := 0;
end if;
declare
psfmt64 : Long_Float_Array (0 .. N * 2 - 1);
for psfmt64'Address use dsfmt.status'Address;
r : constant Long_Float := psfmt64 (idx);
begin
dsfmt.idx := idx + 1;
return r;
end;
end Random_1_To_Less_Than_2;
-- This function generates and returns double precision pseudorandom number
-- which distributes uniformly in the range [0, 1).
-- equivalent to dsfmt_genrand_close_open
function Random_0_To_Less_Than_1 (Gen : aliased in out Generator)
return Long_Float is
begin
return Random_1_To_Less_Than_2 (Gen) - 1.0;
end Random_0_To_Less_Than_1;
-- This function generates and returns double precision pseudorandom number
-- which distributes uniformly in the range (0, 1].
-- equivalent to dsfmt_genrand_open_close
function Random_Greater_Than_0_To_1 (Gen : aliased in out Generator)
return Long_Float is
begin
return 2.0 - Random_1_To_Less_Than_2 (Gen);
end Random_Greater_Than_0_To_1;
-- This function generates and returns double precision pseudorandom number
-- which distributes uniformly in the range (0, 1).
-- equivalent to dsfmt_genrand_open_open
function Random_Greater_Than_0_To_Less_Than_1 (
Gen : aliased in out Generator)
return Long_Float
is
type union_r_Tag is (d, u);
pragma Discard_Names (union_r_Tag);
type union_r (Unchecked_Tag : union_r_Tag := d) is record
case Unchecked_Tag is
when d =>
d : Long_Float;
when u =>
u : Unsigned_64;
end case;
end record;
pragma Unchecked_Union (union_r);
pragma Suppress_Initialization (union_r);
r : union_r;
begin
r.d := Random_1_To_Less_Than_2 (Gen);
r.u := r.u or 1;
return r.d - 1.0;
end Random_Greater_Than_0_To_Less_Than_1;
-- This function generates double precision floating point pseudorandom
-- numbers which distribute in the range [1, 2) to the specified array[]
-- by one call. The number of pseudorandom numbers is specified by the
-- argument size, which must be at least (SFMT_MEXP / 128) * 2 and a
-- multiple of two. The function get_min_array_size() returns this
-- minimum size. The generation by this function is much faster than the
-- following fill_array_xxx functions.
-- equivalent to dsfmt_fill_array_close1_open2
procedure Fill_Random_1_To_Less_Than_2 (
Gen : aliased in out Generator;
Item : out Long_Float_Array)
is
pragma Suppress (Range_Check);
size : constant Natural := Item'Length;
begin
if Gen.dsfmt.idx /= N64 or else size rem 2 /= 0 or else size < N64 then
-- This function can not be used after calling genrand_xxx functions,
-- without initialization.
for I in Item'Range loop
Item (I) := Random_1_To_Less_Than_2 (Gen);
end loop;
end if;
declare
the_array : w128_t_Array (0 .. 0); -- size / 2 - 1
for the_array'Address use Item'Address;
begin
gen_rand_array_c1o2 (Gen.dsfmt, the_array (0 .. 0), size / 2);
end;
end Fill_Random_1_To_Less_Than_2;
-- This function generates double precision floating point pseudorandom
-- numbers which distribute in the range [0, 1) to the specified array[]
-- by one call. This function is the same as fill_array_close1_open2()
-- except the distribution range.
-- equivalent to dsfmt_fill_array_close_open
procedure Fill_Random_0_To_Less_Than_1 (
Gen : aliased in out Generator;
Item : out Long_Float_Array)
is
pragma Suppress (Range_Check);
size : constant Natural := Item'Length;
begin
if Gen.dsfmt.idx /= N64 or else size rem 2 /= 0 or else size < N64 then
for I in Item'Range loop
Item (I) := Random_0_To_Less_Than_1 (Gen);
end loop;
end if;
declare
the_array : w128_t_Array (0 .. 0); -- size / 2 - 1
for the_array'Address use Item'Address;
begin
gen_rand_array_c0o1 (Gen.dsfmt, the_array (0 .. 0), size / 2);
end;
end Fill_Random_0_To_Less_Than_1;
-- This function generates double precision floating point pseudorandom
-- numbers which distribute in the range (0, 1] to the specified array[]
-- by one call. This function is the same as fill_array_close1_open2()
-- except the distribution range.
-- equivalent to dsfmt_fill_array_open_close
procedure Fill_Random_Greater_Than_0_To_1 (
Gen : aliased in out Generator;
Item : out Long_Float_Array)
is
pragma Suppress (Range_Check);
size : constant Natural := Item'Length;
begin
if Gen.dsfmt.idx /= N64 or else size rem 2 /= 0 or else size < N64 then
for I in Item'Range loop
Item (I) := Random_Greater_Than_0_To_1 (Gen);
end loop;
end if;
declare
the_array : w128_t_Array (0 .. 0); -- size / 2 - 1
for the_array'Address use Item'Address;
begin
gen_rand_array_o0c1 (Gen.dsfmt, the_array (0 .. 0), size / 2);
end;
end Fill_Random_Greater_Than_0_To_1;
-- This function generates double precision floating point pseudorandom
-- numbers which distribute in the range (0, 1) to the specified array[]
-- by one call. This function is the same as fill_array_close1_open2()
-- except the distribution range.
-- equivalent to dsfmt_fill_array_open_open
procedure Fill_Random_Greater_Than_0_To_Less_Than_1 (
Gen : aliased in out Generator;
Item : out Long_Float_Array)
is
pragma Suppress (Range_Check);
size : constant Natural := Item'Length;
begin
if Gen.dsfmt.idx /= N64 or else size rem 2 /= 0 or else size < N64 then
for I in Item'Range loop
Item (I) := Random_Greater_Than_0_To_Less_Than_1 (Gen);
end loop;
end if;
declare
the_array : w128_t_Array (0 .. 0); -- size / 2 - 1
for the_array'Address use Item'Address;
begin
gen_rand_array_o0o1 (Gen.dsfmt, the_array (0 .. 0), size / 2);
end;
end Fill_Random_Greater_Than_0_To_Less_Than_1;
function Initialize return Generator is
begin
return (dsfmt => Initialize);
end Initialize;
function Initialize (Initiator : Unsigned_32) return Generator is
begin
return (dsfmt => Initialize (Initiator));
end Initialize;
function Initialize (Initiator : Unsigned_32_Array) return Generator is
begin
return (dsfmt => Initialize (Initiator));
end Initialize;
procedure Reset (Gen : in out Generator) is
begin
Gen.dsfmt := Initialize;
end Reset;
procedure Reset (Gen : in out Generator; Initiator : Integer) is
begin
Gen.dsfmt := Initialize (Unsigned_32'Mod (Initiator));
end Reset;
function Initialize return State is
Init : aliased Unsigned_32_Array (0 .. N32 - 1);
begin
System.Random_Initiators.Get (
Init'Address,
Init'Size / Standard'Storage_Unit);
return Initialize (Init);
end Initialize;
-- This function initializes the internal state array with a 32-bit integer
-- seed.
-- equivalent to dsfmt_init_gen_rand
function Initialize (Initiator : Unsigned_32) return State is
begin
return Result : State do
dsfmt_chk_init_gen_rand (Result, Initiator);
end return;
end Initialize;
-- This function initializes the internal state array, with an array of
-- 32-bit integers used as the seeds.
-- equivalent to dsfmt_init_by_array
function Initialize (Initiator : Unsigned_32_Array) return State is
begin
return Result : State do
dsfmt_chk_init_by_array (Result, Initiator);
end return;
end Initialize;
procedure Save (Gen : Generator; To_State : out State) is
begin
To_State := Gen.dsfmt;
end Save;
procedure Reset (Gen : in out Generator; From_State : State) is
begin
Gen.dsfmt := From_State;
end Reset;
function Reset (From_State : State) return Generator is
begin
return (dsfmt => From_State);
end Reset;
function Image (Of_State : State) return String is
procedure Put (To : out String; Item : w128_t);
procedure Put (To : out String; Item : w128_t) is
Last : Natural := To'First - 1;
begin
for I in w128_t'Range loop
declare
E : constant Unsigned_64 := Item (I);
Previous_Last : constant Natural := Last;
Error : Boolean;
begin
if Standard'Word_Size >= 64 then
System.Formatting.Image (
Word_Unsigned (E),
To (Previous_Last + 1 .. Previous_Last + 64 / 4),
Last,
Base => 16,
Width => 64 / 4,
Error => Error);
else
System.Formatting.Image (
Long_Long_Unsigned (E),
To (Previous_Last + 1 .. Previous_Last + 64 / 4),
Last,
Base => 16,
Width => 64 / 4,
Error => Error);
end if;
pragma Check (Validate,
Check => not Error and then Last = Previous_Last + 64 / 4);
end;
Last := Last + 1;
To (Last) := ':';
end loop;
end Put;
procedure Put (To : out String; Item : Integer);
procedure Put (To : out String; Item : Integer) is
Error : Boolean;
Last : Natural;
begin
System.Formatting.Image (
Word_Unsigned (Item),
To,
Last,
Base => 16,
Width => 32 / 4,
Error => Error);
pragma Check (Validate, not Error and then Last = To'Last);
end Put;
Last : Natural := 0;
begin
return Result : String (1 .. Max_Image_Width) do
for I in w128_t_Array_N'Range loop
declare
Previous_Last : constant Natural := Last;
begin
Last := Last + 2 * (64 / 4 + 1);
Put (Result (Previous_Last + 1 .. Last), Of_State.status (I));
end;
end loop;
declare
Previous_Last : constant Natural := Last;
begin
Last := Last + 2 * (64 / 4 + 1);
Put (Result (Previous_Last + 1 .. Last), Of_State.lung);
end;
Put (Result (Last + 1 .. Result'Last), Of_State.idx);
end return;
end Image;
function Value (Coded_State : String) return State is
procedure Get (From : String; Item : out w128_t);
procedure Get (From : String; Item : out w128_t) is
Last : Natural := From'First - 1;
begin
for I in w128_t'Range loop
declare
Previous_Last : constant Natural := Last;
E : Unsigned_64;
Error : Boolean;
begin
if Standard'Word_Size >= 64 then
System.Formatting.Value (
From (Previous_Last + 1 .. Previous_Last + 64 / 4),
Last,
Word_Unsigned (E),
Base => 16,
Error => Error);
else
System.Formatting.Value (
From (Previous_Last + 1 .. Previous_Last + 64 / 4),
Last,
Long_Long_Unsigned (E),
Base => 16,
Error => Error);
end if;
if Error or else Last /= Previous_Last + 64 / 4 then
raise Constraint_Error;
end if;
Item (I) := E;
end;
Last := Last + 1;
if From (Last) /= ':' then
raise Constraint_Error;
end if;
end loop;
end Get;
procedure Get (From : String; Item : out Integer);
procedure Get (From : String; Item : out Integer) is
Last : Positive;
Error : Boolean;
begin
System.Formatting.Value (
From,
Last,
Word_Unsigned (Item),
Base => 16,
Error => Error);
if Error or else Last /= From'Last or else Item not in 0 .. N64 then
raise Constraint_Error;
end if;
end Get;
begin
if Coded_State'Length /= Max_Image_Width then
raise Constraint_Error;
end if;
return Result : State do
declare
Last : Natural := Coded_State'First - 1;
begin
for I in w128_t_Array_N'Range loop
declare
Previous_Last : constant Natural := Last;
begin
Last := Last + 2 * (64 / 4 + 1);
Get (
Coded_State (Previous_Last + 1 .. Last),
Result.status (I));
end;
end loop;
declare
Previous_Last : constant Natural := Last;
begin
Last := Last + 2 * (64 / 4 + 1);
Get (Coded_State (Previous_Last + 1 .. Last), Result.lung);
end;
Get (Coded_State (Last + 1 .. Coded_State'Last), Result.idx);
end;
end return;
end Value;
end Ada.Numerics.dSFMT;
|
-- SPDX-License-Identifier: Apache-2.0
--
-- Copyright (c) 2013 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.Strings;
with Ada.Unchecked_Conversion;
with GL.API;
with GL.Enums.Getter;
with GL.Errors;
with GL.Types;
package body GL.Context is
use GL.Types;
function Extension (Index : Positive) return String is
(C.Strings.Value (API.Get_String_I.Ref (Enums.Getter.Extensions, UInt (Index - 1))));
function GLSL_Version (Index : Positive) return String is
(C.Strings.Value (API.Get_String_I.Ref
(Enums.Getter.Shading_Language_Version, UInt (Index - 1))));
procedure Flush is
begin
API.Flush.Ref.all;
end Flush;
function Status return Reset_Status is
begin
return API.Get_Graphics_Reset_Status.Ref.all;
end Status;
function Flags return Context_Flags is
use type Low_Level.Bitfield;
function Convert is new Ada.Unchecked_Conversion
(Low_Level.Bitfield, Context.Context_Flags);
Raw_Bits : Low_Level.Bitfield := 0;
begin
API.Get_Context_Flags.Ref (Enums.Getter.Context_Flags, Raw_Bits);
return Convert (Raw_Bits and 2#0000000000001111#);
end Flags;
function Reset_Notification return Context_Reset_Notification is
Result : Context_Reset_Notification := No_Reset_Notification;
begin
API.Get_Context_Reset_Notification.Ref (Enums.Getter.Context_Reset_Notification, Result);
return Result;
end Reset_Notification;
function Release_Behavior return Context_Release_Behavior is
Result : Context_Release_Behavior := Flush;
begin
API.Get_Context_Release_Behavior.Ref (Enums.Getter.Context_Release_Behavior, Result);
return Result;
end Release_Behavior;
function Major_Version return Natural is
Result : Int := 0;
begin
API.Get_Integer.Ref (Enums.Getter.Major_Version, Result);
return Natural (Result);
end Major_Version;
function Minor_Version return Natural is
Result : Int := 0;
begin
API.Get_Integer.Ref (Enums.Getter.Minor_Version, Result);
return Natural (Result);
end Minor_Version;
function Version_String return String is
begin
return C.Strings.Value (API.Get_String.Ref (Enums.Getter.Version));
end Version_String;
function Vendor return String is
begin
return C.Strings.Value (API.Get_String.Ref (Enums.Getter.Vendor));
end Vendor;
function Renderer return String is
begin
return C.Strings.Value (API.Get_String.Ref (Enums.Getter.Renderer));
end Renderer;
function Extensions return String_List is
use Ada.Strings.Unbounded;
use type Errors.Error_Code;
Count : Int := 0;
begin
API.Get_Integer.Ref (Enums.Getter.Num_Extensions, Count);
pragma Assert (API.Get_Error.Ref.all = Errors.No_Error);
-- We are on OpenGL 3
return List : String_List (1 .. Positive (Count)) do
for I in List'Range loop
List (I) := To_Unbounded_String (Extension (I));
end loop;
end return;
end Extensions;
function Has_Extension
(Extensions : String_List;
Name : String) return Boolean
is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
return (for some Extension of Extensions => Extension = Name);
end Has_Extension;
function Primary_Shading_Language_Version return String is
Result : constant String := C.Strings.Value
(API.Get_String.Ref (Enums.Getter.Shading_Language_Version));
begin
return Result;
end Primary_Shading_Language_Version;
function Supported_Shading_Language_Versions return String_List is
use Ada.Strings.Unbounded;
use type Errors.Error_Code;
Count : Int := 0;
begin
API.Get_Integer.Ref (Enums.Getter.Num_Shading_Language_Versions, Count);
if API.Get_Error.Ref.all = Errors.Invalid_Enum then
raise Feature_Not_Supported_Exception;
end if;
return List : String_List (1 .. Positive (Count)) do
for I in List'Range loop
List (I) := To_Unbounded_String (GLSL_Version (I));
end loop;
end return;
end Supported_Shading_Language_Versions;
function Supports_Shading_Language_Version
(Versions : String_List;
Name : String) return Boolean
is
use type Ada.Strings.Unbounded.Unbounded_String;
begin
return (for some Version of Versions => Version = Name);
end Supports_Shading_Language_Version;
end GL.Context;
|
-- C46021A.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 FLOATING POINT CONVERSIONS ARE PERFORMED CORRECTLY
-- WHEN THE OPERAND TYPE IS AN INTEGER TYPE, FOR 5-DIGIT PRECISION.
-- HISTORY:
-- JET 02/12/88 CREATED ORIGINAL TEST.
WITH REPORT; USE REPORT;
PROCEDURE C46021A IS
TYPE FLOAT5 IS DIGITS 5;
TYPE INT IS RANGE -32768..32767;
TYPE NFLOAT5 IS NEW FLOAT5;
FUNCTION IDENT (A : FLOAT5) RETURN FLOAT5 IS
BEGIN
IF EQUAL(3,3) THEN
RETURN A;
ELSE
RETURN 0.0;
END IF;
END IDENT;
FUNCTION IDENT (A : NFLOAT5) RETURN NFLOAT5 IS
BEGIN
IF EQUAL(3,3) THEN
RETURN A;
ELSE
RETURN 0.0;
END IF;
END IDENT;
BEGIN
TEST ("C46021A", "CHECK THAT FLOATING POINT CONVERSIONS ARE " &
"PERFORMED CORRECTLY WHEN THE OPERAND TYPE " &
"IS AN INTEGER TYPE, FOR 5-DIGIT PRECISION");
IF FLOAT5(IDENT_INT(-7)) /= -7.0 THEN
FAILED ("INCORRECT VALUE (1)");
END IF;
IF FLOAT5(IDENT_INT(3)) /= 3.0 THEN
FAILED ("INCORRECT VALUE (2)");
END IF;
IF FLOAT5(IDENT_INT(-999)) /= -999.0 THEN
FAILED ("INCORRECT VALUE (3)");
END IF;
IF FLOAT5(IDENT_INT(101)) /= 101.0 THEN
FAILED ("INCORRECT VALUE (4)");
END IF;
IF FLOAT5(IDENT_INT(-32767)) /= -32767.0 THEN
FAILED ("INCORRECT VALUE (5)");
END IF;
IF FLOAT5(IDENT_INT(32767)) /= 32767.0 THEN
FAILED ("INCORRECT VALUE (6)");
END IF;
IF FLOAT5(-7) /= IDENT(-7.0) THEN
FAILED ("INCORRECT VALUE (7)");
END IF;
IF FLOAT5(3) /= IDENT(3.0) THEN
FAILED ("INCORRECT VALUE (8)");
END IF;
IF FLOAT5(-999) /= IDENT(-999.0) THEN
FAILED ("INCORRECT VALUE (9)");
END IF;
IF FLOAT5(101) /= IDENT(101.0) THEN
FAILED ("INCORRECT VALUE (10)");
END IF;
IF FLOAT5(-32767) /= IDENT(-32767.0) THEN
FAILED ("INCORRECT VALUE (11)");
END IF;
IF FLOAT5(32767) /= IDENT(32767.0) THEN
FAILED ("INCORRECT VALUE (12)");
END IF;
IF FLOAT5(INT'(-7)) /= IDENT(-7.0) THEN
FAILED ("INCORRECT VALUE (13)");
END IF;
IF FLOAT5(INT'(3)) /= IDENT(3.0) THEN
FAILED ("INCORRECT VALUE (14)");
END IF;
IF FLOAT5(INT'(-999)) /= IDENT(-999.0) THEN
FAILED ("INCORRECT VALUE (15)");
END IF;
IF FLOAT5(INT'(101)) /= IDENT(101.0) THEN
FAILED ("INCORRECT VALUE (16)");
END IF;
IF FLOAT5(INT'(-32767)) /= IDENT(-32767.0) THEN
FAILED ("INCORRECT VALUE (17)");
END IF;
IF FLOAT5(INT'(32767)) /= IDENT(32767.0) THEN
FAILED ("INCORRECT VALUE (18)");
END IF;
IF NFLOAT5(IDENT_INT(-7)) /= -7.0 THEN
FAILED ("INCORRECT VALUE (19)");
END IF;
IF NFLOAT5(IDENT_INT(3)) /= 3.0 THEN
FAILED ("INCORRECT VALUE (20)");
END IF;
IF NFLOAT5(IDENT_INT(-999)) /= -999.0 THEN
FAILED ("INCORRECT VALUE (21)");
END IF;
IF NFLOAT5(IDENT_INT(101)) /= 101.0 THEN
FAILED ("INCORRECT VALUE (22)");
END IF;
IF NFLOAT5(IDENT_INT(-32767)) /= -32767.0 THEN
FAILED ("INCORRECT VALUE (23)");
END IF;
IF NFLOAT5(IDENT_INT(32767)) /= 32767.0 THEN
FAILED ("INCORRECT VALUE (24)");
END IF;
IF NFLOAT5(-7) /= IDENT(-7.0) THEN
FAILED ("INCORRECT VALUE (25)");
END IF;
IF NFLOAT5(3) /= IDENT(3.0) THEN
FAILED ("INCORRECT VALUE (26)");
END IF;
IF NFLOAT5(-999) /= IDENT(-999.0) THEN
FAILED ("INCORRECT VALUE (27)");
END IF;
IF NFLOAT5(101) /= IDENT(101.0) THEN
FAILED ("INCORRECT VALUE (28)");
END IF;
IF NFLOAT5(-32767) /= IDENT(-32767.0) THEN
FAILED ("INCORRECT VALUE (29)");
END IF;
IF NFLOAT5(32767) /= IDENT(32767.0) THEN
FAILED ("INCORRECT VALUE (30)");
END IF;
IF NFLOAT5(INT'(-7)) /= IDENT(-7.0) THEN
FAILED ("INCORRECT VALUE (31)");
END IF;
IF NFLOAT5(INT'(3)) /= IDENT(3.0) THEN
FAILED ("INCORRECT VALUE (32)");
END IF;
IF NFLOAT5(INT'(-999)) /= IDENT(-999.0) THEN
FAILED ("INCORRECT VALUE (33)");
END IF;
IF NFLOAT5(INT'(101)) /= IDENT(101.0) THEN
FAILED ("INCORRECT VALUE (34)");
END IF;
IF NFLOAT5(INT'(-32767)) /= IDENT(-32767.0) THEN
FAILED ("INCORRECT VALUE (35)");
END IF;
IF NFLOAT5(INT'(32767)) /= IDENT(32767.0) THEN
FAILED ("INCORRECT VALUE (36)");
END IF;
RESULT;
END C46021A;
|
generic
package any_Math.any_fast_Rotation
is
function to_Rotation (Angle : in Real) return access constant Matrix_2x2;
private
pragma Inline_Always (to_Rotation);
end any_Math.any_fast_Rotation;
|
-------------------------------------------------------------------------------
-- Copyright (c) 2019, Daniel King
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * The name of the copyright holder may not be used to endorse or promote
-- Products derived from this software without specific prior written
-- permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
with Keccak.Generic_XOF;
with Keccak.Generic_Parallel_XOF;
with Keccak.Types;
-- @summary
-- Generic implementation of the KangarooTwelve hash algorithm.
--
-- @description
-- This API is used as follows:
--
-- 1 Initialise a new context by calling Init.
--
-- 2 Call Update one or more times to input an arbitrary amount of data.
--
-- 3 Call Finish after all input data has been processed. An optional
-- customisation string can be given to provide domain separation
-- between different uses of KangarooTwelve.
--
-- 4 Call Extract one or more times to produce an arbitrary number of output bytes.
--
-- @group KangarooTwelve
generic
CV_Size_Bytes : Positive;
-- The size of each chaining value (CV) in bytes.
-- This is set to 256 bits (32 bytes) for KangarooTwelve
-- and 512 bits (64 bytes) for MarsupilamiFourteen.
with package XOF_Serial is new Keccak.Generic_XOF (<>);
-- This XOF must be configured with NO SUFFIX BITS.
-- The Generic_KangarooTwelve implementation takes care of the appropriate
-- suffix bits when using this XOF_Serial.
with package XOF_Parallel_2 is new Keccak.Generic_Parallel_XOF (<>);
-- This XOF must be configured to add the 3 suffix bits 2#011#.
with package XOF_Parallel_4 is new Keccak.Generic_Parallel_XOF (<>);
-- This XOF must be configured to add the 3 suffix bits 2#011#.
with package XOF_Parallel_8 is new Keccak.Generic_Parallel_XOF (<>);
-- This XOF must be configured to add the 3 suffix bits 2#011#.
package Keccak.Generic_KangarooTwelve
is
-- Assertions to check that the correct parallel instances have
-- been provided.
pragma Assert (XOF_Parallel_2.Num_Parallel_Instances = 2);
pragma Assert (XOF_Parallel_4.Num_Parallel_Instances = 4);
pragma Assert (XOF_Parallel_8.Num_Parallel_Instances = 8);
Block_Size_Bytes : constant := 8192;
-- Size of each parallel block.
-- This is set to 8 kiB in the K12 documentation.
type Context is private;
type States is (Updating, Ready_To_Extract, Extracting);
-- The possible states for the context.
--
-- @value Updating When in this state the context can be fed
-- with input data by calling the Update procedure.
--
-- @value Ready_To_Extract When in this state the Update procedure can
-- no longer be called (i.e. no more data can be input to the context),
-- and the context is ready to generate output data.
--
-- @value Extracting When in this state the context can produce output
-- bytes by calling the Extract procedure.
type Byte_Count is new Long_Long_Integer range 0 .. Long_Long_Integer'Last;
-- Represents a quantity of bytes.
procedure Init (Ctx : out Context)
with Global => null,
Post => State_Of (Ctx) = Updating;
-- Initialise the KangarooTwelve state.
procedure Update (Ctx : in out Context;
Data : in Types.Byte_Array)
with Global => null,
Pre => (State_Of (Ctx) = Updating
and Byte_Count (Data'Length) <= Max_Input_Length (Ctx)),
Post => (State_Of (Ctx) = Updating
and Num_Bytes_Processed (Ctx) =
Num_Bytes_Processed (Ctx'Old) + Byte_Count (Data'Length));
-- Process input bytes.
--
-- This may be called multiple times to process long messages.
--
-- The total number of input bytes that can be processed cannot
-- exceed Byte_Count'Last (a subtype of Long_Long_Integer). This is
-- because KangarooTwelve feeds the total input length into the
-- calculation. The total number of input bytes processed so far
-- can be retrieved by calling the Num_Bytes_Processed function,
-- and the maximum allowed input size remaining can be retrieved
-- by calling Max_Input_Length.
--
-- @param Ctx The KangarooTwelve context.
-- @param Data The input bytes to process. The entire array is processed.
procedure Finish (Ctx : in out Context;
Customization : in String)
with Global => null,
Pre => (State_Of (Ctx) = Updating
and then
(Byte_Count (Customization'Length) + Byte_Count (Long_Long_Integer'Size / 8) + 2
<= Max_Input_Length (Ctx))),
Post => State_Of (Ctx) = Ready_To_Extract;
-- Prepare the KangarooTwelve context to produce output.
--
-- This is called once only, after all input bytes have been
-- processed, and must be called before calling Extract.
--
-- An optional Customization string can be applied to provide
-- domain separation between different KangarooTwelve instances.
-- I.e. processing the exact same input data twice, but with
-- different customization strings will result in unrelated outputs.
--
-- @param Ctx The KangarooTwelve context.
-- @param Customization An optional customization string for domain
-- separation. If not needed, then an empty string can be used.
procedure Extract (Ctx : in out Context;
Data : out Types.Byte_Array)
with Global => null,
Pre => State_Of (Ctx) in Ready_To_Extract | Extracting,
Post => State_Of (Ctx) = Extracting;
-- Get output bytes.
--
-- This can be called multiple times to produce very long outputs.
--
-- The Finish procedure must be called before the first call to Extract.
function State_Of (Ctx : in Context) return States
with Global => null;
-- Get the current state of the context.
function Num_Bytes_Processed (Ctx : in Context) return Byte_Count
with Inline,
Global => null;
-- Get the total number of input bytes processed so far.
function Max_Input_Length (Ctx : in Context) return Byte_Count
with Inline,
Global => null;
-- Get the maximum input length that may be provided to as input
-- to KangarooTwelve. This decreases as input bytes are processed.
private
use type XOF_Serial.States;
subtype Partial_Block_Length_Number is Natural range 0 .. Block_Size_Bytes - 1;
type Context is record
Outer_XOF : XOF_Serial.Context;
Partial_Block_XOF : XOF_Serial.Context;
Input_Len : Byte_Count;
Partial_Block_Length : Partial_Block_Length_Number;
Finished : Boolean;
end record;
function State_Of (Ctx : in Context) return States
is (if (XOF_Serial.State_Of (Ctx.Outer_XOF) = XOF_Serial.Updating
and XOF_Serial.State_Of (Ctx.Partial_Block_XOF) = XOF_Serial.Updating)
then (if Ctx.Finished
then Ready_To_Extract
else Updating)
elsif XOF_Serial.State_Of (Ctx.Outer_XOF) = XOF_Serial.Ready_To_Extract
then Ready_To_Extract
else Extracting);
function Num_Bytes_Processed (Ctx : in Context) return Byte_Count
is (Ctx.Input_Len);
function Max_Input_Length (Ctx : in Context) return Byte_Count
is (Byte_Count'Last - Num_Bytes_Processed (Ctx));
end Keccak.Generic_KangarooTwelve;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Web Framework --
-- --
-- Tools 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$
------------------------------------------------------------------------------
with League.String_Vectors;
with WSDL.AST.Bindings;
pragma Unreferenced (WSDL.AST.Bindings);
-- GNAT Pro 7.2.0w (20130423): package is needed to access to type's
-- components.
with WSDL.AST.Descriptions;
pragma Unreferenced (WSDL.AST.Descriptions);
-- GNAT Pro 7.2.0w (20130423): package is needed to access to type's
-- components.
with WSDL.AST.Endpoints;
with WSDL.AST.Faults;
with WSDL.AST.Interfaces;
with WSDL.AST.Messages;
with WSDL.AST.Operations;
with WSDL.AST.Types;
with WSDL.Constants;
with WSDL.Diagnoses;
with WSDL.MEPs;
with WSDL.Parsers.MEP;
with WSDL.Parsers.SOAP;
package body WSDL.Parsers is
use WSDL.Constants;
use type League.Strings.Universal_String;
use type WSDL.AST.Message_Directions;
use type WSDL.AST.Qualified_Name;
procedure Push
(Self : in out WSDL_Parser'Class; State : Parser_State_Kind);
procedure Pop (Self : in out WSDL_Parser'Class);
function To_Qualified_Name
(Namespaces : Namespace_Maps.Map;
Name : League.Strings.Universal_String)
return WSDL.AST.Qualified_Name;
-- Construct qualified name from the given prefix:localName string.
procedure Start_Description_Element
(Self : in out WSDL_Parser'Class;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean);
-- Handles start of 'description' element.
procedure Start_Types_Element
(Description : WSDL.AST.Description_Access;
Success : in out Boolean);
-- Handles start of 'types' element.
procedure Start_Interface_Element
(Parser : in out WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Description : WSDL.AST.Description_Access;
Node : out WSDL.AST.Interface_Access;
Success : in out Boolean);
-- Handles start of 'interface' element.
procedure Start_Interface_Fault_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Access;
-- Node : out WSDL.AST.Faults.Interface_Fault_Access;
Success : in out Boolean);
-- Handles start of 'fault' element as child of 'interface' element.
procedure Start_Interface_Operation_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Parent : not null WSDL.AST.Interface_Access;
Node : out WSDL.AST.Interface_Operation_Access;
Success : in out Boolean);
-- Handles start of 'operation' element as child of 'interface' element.
procedure Start_Input_Output_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Operation_Access;
Direction : WSDL.AST.Message_Directions;
Success : in out Boolean);
-- Handles start of 'input' and 'output' element as child of 'operation'
-- element as child of 'interface' element.
procedure Start_Input_Output_Fault_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Operation_Access;
Direction : WSDL.AST.Message_Directions;
Success : in out Boolean);
-- Handles start of 'infault' and 'outfault' element as child of
-- 'operation' element as child of 'interface' element.
procedure Start_Binding_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Description_Access;
Node : out WSDL.AST.Binding_Access;
Success : in out Boolean);
-- Handles start of 'interface' element.
procedure End_Binding_Element
(Parser : WSDL_Parser;
Node : WSDL.AST.Binding_Access;
Success : in out Boolean);
-- Handles start of 'interface' element.
procedure Start_Binding_Fault_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Binding_Access;
Success : in out Boolean);
-- Handles start of 'fault' element as child of 'binding' element.
procedure Start_Binding_Operation_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Binding_Access;
-- Node : out WSDL.AST.Operations.Interface_Operation_Access;
Success : in out Boolean);
-- Handles start of 'operation' element as child of 'binding' element.
procedure Start_Service_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Description_Access;
Node : out WSDL.AST.Services.Service_Access;
Success : in out Boolean);
-- Handles start of 'service' element.
procedure Start_Endpoint_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Services.Service_Access;
Success : in out Boolean);
-- Handles start of 'service' element.
-------------------------
-- End_Binding_Element --
-------------------------
procedure End_Binding_Element
(Parser : WSDL_Parser;
Node : WSDL.AST.Binding_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
begin
if Node.Interface_Name.Local_Name.Is_Empty
and (not Node.Binding_Operations.Is_Empty
or not Node.Binding_Faults.Is_Empty)
then
-- Binding-1044: "If a Binding component specifies any
-- operation-specific binding details (by including Binding Operation
-- components) or any fault binding details (by including Binding
-- Fault components), then it MUST specify an interface the Binding
-- component applies to, so as to indicate which interface the
-- operations come from."
Parser.Report (WSDL.Assertions.Binding_1044);
raise WSDL_Error;
end if;
end End_Binding_Element;
-----------------
-- End_Element --
-----------------
overriding procedure End_Element
(Self : in out WSDL_Parser;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Success : in out Boolean)
is
pragma Unreferenced (Qualified_Name);
begin
if Self.Ignore_Depth /= 0 then
Self.Ignore_Depth := Self.Ignore_Depth - 1;
elsif Namespace_URI = WSDL_Namespace_URI then
if Local_Name = Binding_Element then
End_Binding_Element (Self, Self.Current_Binding, Success);
Self.Pop;
elsif Local_Name = Description_Element then
Self.Pop;
elsif Local_Name = Endpoint_Element then
Self.Pop;
elsif Local_Name = Fault_Element then
Self.Pop;
elsif Local_Name = Infault_Element then
Self.Pop;
elsif Local_Name = Input_Element then
Self.Pop;
elsif Local_Name = Interface_Element then
Self.Pop;
elsif Local_Name = Operation_Element then
Self.Pop;
elsif Local_Name = Outfault_Element then
Self.Pop;
elsif Local_Name = Output_Element then
Self.Pop;
elsif Local_Name = Service_Element then
Self.Pop;
elsif Local_Name = Types_Element then
Self.Pop;
end if;
end if;
end End_Element;
------------------
-- Error_String --
------------------
overriding function Error_String
(Self : WSDL_Parser) return League.Strings.Universal_String
is
pragma Unreferenced (Self);
begin
return League.Strings.Empty_Universal_String;
end Error_String;
---------------------
-- Get_Description --
---------------------
function Get_Description
(Self : WSDL_Parser'Class) return WSDL.AST.Description_Access is
begin
return Self.Description;
end Get_Description;
---------
-- Pop --
---------
procedure Pop (Self : in out WSDL_Parser'Class) is
begin
Self.Current_State := Self.Previous_State;
if Self.State_Stack.Is_Empty then
Self.Previous_State := (None, others => <>);
else
Self.Previous_State := Self.State_Stack.Last_Element;
Self.State_Stack.Delete_Last;
end if;
end Pop;
----------
-- Push --
----------
procedure Push
(Self : in out WSDL_Parser'Class; State : Parser_State_Kind)
is
Aux : Parser_State (State);
begin
Self.State_Stack.Append (Self.Previous_State);
Self.Previous_State := Self.Current_State;
Self.Current_State := Aux;
end Push;
------------
-- Report --
------------
procedure Report
(Self : WSDL_Parser;
Assertion : WSDL.Assertions.WSDL_Assertion) is
begin
WSDL.Assertions.Report
(Self.Locator.System_Id,
WSDL.Diagnoses.Line_Number (Self.Locator.Line),
WSDL.Diagnoses.Column_Number (Self.Locator.Column),
Assertion);
end Report;
--------------------------
-- Set_Document_Locator --
--------------------------
overriding procedure Set_Document_Locator
(Self : in out WSDL_Parser;
Locator : XML.SAX.Locators.SAX_Locator) is
begin
Self.Locator := Locator;
end Set_Document_Locator;
---------------------------
-- Start_Binding_Element --
---------------------------
procedure Start_Binding_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Description_Access;
Node : out WSDL.AST.Binding_Access;
Success : in out Boolean)
is
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
begin
-- Binding-1049: "For each Binding component in the {bindings} property
-- of a Description component, the {name} property MUST be unique."
if Parent.Bindings.Contains (Name) then
Parser.Report (WSDL.Assertions.Binding_1049);
raise WSDL_Error;
end if;
Node := WSDL.AST.Bindings.Constructors.Create_Binding (Parent, Name);
-- Analyze 'interface' attribute.
if Attributes.Is_Specified (Interface_Attribute) then
Node.Interface_Name :=
To_Qualified_Name
(Namespaces, Attributes.Value (Interface_Attribute));
end if;
-- Analyze 'type' attribute.
Node.Binding_Type := Attributes.Value (Type_Attribute);
-- Binding-1048: "This xs:anyURI MUST be an absolute IRI as defined by
-- [IETF RFC 3987]."
--
-- XXX Not implemented yet.
-- Analyze SOAP Binding extension's attributes.
if Node.Binding_Type = SOAP_Binding_Type then
-- Call SOAP Binding handler.
WSDL.Parsers.SOAP.Start_Binding_Element (Attributes, Node, Success);
end if;
end Start_Binding_Element;
---------------------------------
-- Start_Binding_Fault_Element --
---------------------------------
procedure Start_Binding_Fault_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Binding_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
use type WSDL.AST.Binding_Fault_Access;
Node : WSDL.AST.Binding_Fault_Access;
begin
Node := new WSDL.AST.Faults.Binding_Fault_Node;
Node.Parent := Parent;
Parent.Binding_Faults.Append (Node);
-- Analyze 'ref' attribute.
Node.Ref := To_Qualified_Name (Namespaces, Attributes.Value (Ref_Attribute));
-- BindingFault-1050: "For each Binding Fault component in the {binding
-- faults} property of a Binding component, the {interface fault}
-- property MUST be unique."
for J of Parent.Binding_Faults loop
if J /= Node and J.Ref = Node.Ref then
Parser.Report (WSDL.Assertions.BindingFault_1050);
raise WSDL_Error;
end if;
end loop;
end Start_Binding_Fault_Element;
-------------------------------------
-- Start_Binding_Operation_Element --
-------------------------------------
procedure Start_Binding_Operation_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Binding_Access;
-- Node : out WSDL.AST.Operations.Interface_Operation_Access;
Success : in out Boolean)
is
use type WSDL.AST.Binding_Operation_Access;
Node : WSDL.AST.Binding_Operation_Access;
begin
Node := new WSDL.AST.Operations.Binding_Operation_Node;
Node.Parent := Parent;
Parent.Binding_Operations.Append (Node);
-- Analyze 'ref' attribute.
Node.Ref :=
To_Qualified_Name (Namespaces, Attributes.Value (Ref_Attribute));
-- BindingOperation-1051: "For each Binding Operation component in the
-- {binding operations} property of a Binding component, the {interface
-- operation} property MUST be unique."
for J of Parent.Binding_Operations loop
if J /= Node and J.Ref = Node.Ref then
Parser.Report (WSDL.Assertions.BindingOperation_1051);
raise WSDL_Error;
end if;
end loop;
-- Analyze SOAP Binding extension's attributes.
if Parent.Binding_Type = SOAP_Binding_Type then
-- Call SOAP Binding handler.
WSDL.Parsers.SOAP.Start_Binding_Operation_Element
(Attributes, Node, Success);
end if;
end Start_Binding_Operation_Element;
-------------------------------
-- Start_Description_Element --
-------------------------------
procedure Start_Description_Element
(Self : in out WSDL_Parser'Class;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean)
is
pragma Unreferenced (Success);
begin
Self.Description := new WSDL.AST.Descriptions.Description_Node;
Self.Description.Target_Namespace :=
Attributes.Value (Target_Namespace_Attribute);
-- Description-1006: "IRI of target namespace must be absolute."
--
-- XXX Not implemented yet.
end Start_Description_Element;
--------------------
-- Start_Document --
--------------------
overriding procedure Start_Document
(Self : in out WSDL_Parser;
Success : in out Boolean)
is
pragma Unreferenced (Success);
begin
Self.Current_State := (Document, others => <>);
end Start_Document;
-------------------
-- Start_Element --
-------------------
overriding procedure Start_Element
(Self : in out WSDL_Parser;
Namespace_URI : League.Strings.Universal_String;
Local_Name : League.Strings.Universal_String;
Qualified_Name : League.Strings.Universal_String;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Success : in out Boolean)
is
pragma Unreferenced (Qualified_Name);
begin
if Self.Ignore_Depth /= 0 then
Self.Ignore_Depth := Self.Ignore_Depth + 1;
elsif Namespace_URI = WSDL_Namespace_URI then
if Local_Name = Binding_Element then
if Self.Current_State.Kind = WSDL_Description then
Self.Current_State.Last_Child_Kind := Interface_Binding_Service;
Self.Push (WSDL_Binding);
Start_Binding_Element
(Self,
Attributes,
Self.Namespaces,
Self.Description,
Self.Current_Binding,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Description_Element then
if Self.Current_State.Kind = Document then
Self.Push (WSDL_Description);
Self.Start_Description_Element (Attributes, Success);
else
raise Program_Error;
end if;
elsif Local_Name = Documentation_Element then
if Self.Current_State.Kind = WSDL_Description then
if Self.Current_State.Last_Child_Kind > Documentation then
-- Description-1005: "Invalid order of children elements of
-- 'description' element."
Self.Report (WSDL.Assertions.Description_1005);
raise WSDL_Error;
else
Self.Current_State.Last_Child_Kind := Documentation;
Self.Ignore_Depth := 1;
end if;
elsif Self.Current_State.Kind = WSDL_Binding
or Self.Current_State.Kind = WSDL_Binding_Operation
or Self.Current_State.Kind = WSDL_Endpoint
or Self.Current_State.Kind = WSDL_Input
or Self.Current_State.Kind = WSDL_Interface
or Self.Current_State.Kind = WSDL_Interface_Operation
or Self.Current_State.Kind = WSDL_Output
or Self.Current_State.Kind = WSDL_Service
then
Self.Ignore_Depth := 1;
else
raise Program_Error;
end if;
elsif Local_Name = Endpoint_Element then
if Self.Current_State.Kind = WSDL_Service then
Self.Push (WSDL_Endpoint);
Start_Endpoint_Element
(Attributes, Self.Namespaces, Self.Current_Service, Success);
else
raise Program_Error;
end if;
elsif Local_Name = Fault_Element then
if Self.Current_State.Kind = WSDL_Interface then
Self.Push (WSDL_Interface_Fault);
Start_Interface_Fault_Element
(Attributes,
Self.Namespaces,
Self.Current_Interface,
-- Self.Current_Fault,
Success);
elsif Self.Current_State.Kind = WSDL_Binding then
Self.Push (WSDL_Binding_Fault);
Start_Binding_Fault_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Binding,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Include_Element then
if Self.Current_State.Kind = WSDL_Description then
if Self.Current_State.Last_Child_Kind > Include_Import then
-- Description-1005: "Invalid order of children elements of
-- 'description' element."
Self.Report (WSDL.Assertions.Description_1005);
raise WSDL_Error;
else
Self.Current_State.Last_Child_Kind := Include_Import;
Self.Ignore_Depth := 1;
end if;
else
raise Program_Error;
end if;
elsif Local_Name = Infault_Element then
if Self.Current_State.Kind = WSDL_Binding_Operation then
-- XXX all children elements are ignored for now.
Self.Ignore_Depth := 1;
elsif Self.Current_State.Kind = WSDL_Interface_Operation then
Self.Push (WSDL_Infault);
Start_Input_Output_Fault_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Operation,
WSDL.AST.In_Message,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Input_Element then
if Self.Current_State.Kind = WSDL_Binding_Operation then
-- XXX all children elements are ignored for now.
Self.Ignore_Depth := 1;
elsif Self.Current_State.Kind = WSDL_Interface_Operation then
Self.Push (WSDL_Input);
Start_Input_Output_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Operation,
WSDL.AST.In_Message,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Interface_Element then
if Self.Current_State.Kind = WSDL_Description then
Self.Current_State.Last_Child_Kind := Interface_Binding_Service;
Self.Push (WSDL_Interface);
Start_Interface_Element
(Self,
Attributes,
Self.Namespaces,
Self.Description,
Self.Current_Interface,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Import_Element then
if Self.Current_State.Kind = WSDL_Description then
if Self.Current_State.Last_Child_Kind > Include_Import then
-- "Description-1005: Invalid order of children elements of
-- 'description' element."
Self.Report (WSDL.Assertions.Description_1005);
raise WSDL_Error;
else
Self.Current_State.Last_Child_Kind := Include_Import;
Self.Ignore_Depth := 1;
end if;
else
raise Program_Error;
end if;
elsif Local_Name = Operation_Element then
if Self.Current_State.Kind = WSDL_Interface then
Self.Push (WSDL_Interface_Operation);
Start_Interface_Operation_Element
(Self,
Attributes,
Self.Current_Interface,
Self.Current_Operation,
Success);
elsif Self.Current_State.Kind = WSDL_Binding then
Self.Push (WSDL_Binding_Operation);
Start_Binding_Operation_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Binding,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Outfault_Element then
if Self.Current_State.Kind = WSDL_Binding_Operation then
-- XXX all children elements are ignored for now.
Self.Ignore_Depth := 1;
elsif Self.Current_State.Kind = WSDL_Interface_Operation then
Self.Push (WSDL_Outfault);
Start_Input_Output_Fault_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Operation,
WSDL.AST.Out_Message,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Output_Element then
if Self.Current_State.Kind = WSDL_Binding_Operation then
-- XXX all children elements are ignored for now.
Self.Ignore_Depth := 1;
elsif Self.Current_State.Kind = WSDL_Interface_Operation then
Self.Push (WSDL_Output);
Start_Input_Output_Element
(Self,
Attributes,
Self.Namespaces,
Self.Current_Operation,
WSDL.AST.Out_Message,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Service_Element then
if Self.Current_State.Kind = WSDL_Description then
Self.Current_State.Last_Child_Kind := Interface_Binding_Service;
Self.Push (WSDL_Service);
Start_Service_Element
(Attributes,
Self.Namespaces,
Self.Description,
Self.Current_Service,
Success);
else
raise Program_Error;
end if;
elsif Local_Name = Types_Element then
if Self.Current_State.Kind = WSDL_Description then
if Self.Current_State.Last_Child_Kind > Types then
-- Description-1005: "Invalid order of children elements of
-- 'description' element."
Self.Report (WSDL.Assertions.Description_1005);
raise WSDL_Error;
else
Self.Current_State.Last_Child_Kind := Types;
Self.Push (WSDL_Types);
Start_Types_Element (Self.Description, Success);
end if;
else
raise Program_Error;
end if;
else
raise Program_Error;
end if;
elsif Namespace_URI = WSDL_1x_Namespace_URI then
-- WSDL 1.x is not supported.
WSDL.Diagnoses.Report
(Self.Locator.System_Id,
WSDL.Diagnoses.Line_Number (Self.Locator.Line),
WSDL.Diagnoses.Column_Number (Self.Locator.Column),
League.Strings.To_Universal_String ("WSDL 1.x is not supported"));
raise WSDL_Error;
else
if Self.Current_State.Kind = WSDL_Description then
-- Extension element can appair in two places of children of
-- 'description' element:
--
-- - in the set of 'include' and 'import' elements;
--
-- - in the set of 'interface', 'binding' and 'service' elements.
--
-- Code below sets current kind of children into the appropriate
-- value.
if Self.Current_State.Last_Child_Kind < Types then
Self.Current_State.Last_Child_Kind := Include_Import;
else
Self.Current_State.Last_Child_Kind := Interface_Binding_Service;
end if;
elsif Self.Current_State.Kind = WSDL_Binding
or Self.Current_State.Kind = WSDL_Binding_Operation
or Self.Current_State.Kind = WSDL_Endpoint
or Self.Current_State.Kind = WSDL_Input
or Self.Current_State.Kind = WSDL_Interface
or Self.Current_State.Kind = WSDL_Interface_Operation
or Self.Current_State.Kind = WSDL_Output
or Self.Current_State.Kind = WSDL_Service
then
-- Ignore unknown extensions of interface component.
Self.Ignore_Depth := 1;
elsif Self.Current_State.Kind = WSDL_Types then
-- XXX all children elements are ignored for now.
Self.Ignore_Depth := 1;
else
raise Program_Error;
end if;
end if;
end Start_Element;
----------------------------
-- Start_Endpoint_Element --
----------------------------
procedure Start_Endpoint_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Services.Service_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
Node : WSDL.AST.Endpoints.Endpoint_Access;
begin
Node := new WSDL.AST.Endpoints.Endpoint_Node;
Node.Parent := WSDL.AST.Endpoints.Service_Access (Parent);
Node.Local_Name := Name;
Parent.Endpoints.Insert (Name, Node);
-- Analyze 'binding' attribute.
Node.Binding_Name :=
To_Qualified_Name (Namespaces, Attributes.Value (Binding_Attribute));
-- Analyze 'address' attribute.
if Attributes.Is_Specified (Address_Attribute) then
Node.Address := Attributes.Value (Address_Attribute);
end if;
end Start_Endpoint_Element;
--------------------------------------
-- Start_Input_Output_Fault_Element --
--------------------------------------
procedure Start_Input_Output_Fault_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Operation_Access;
Direction : WSDL.AST.Message_Directions;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Node : constant WSDL.AST.Interface_Fault_Reference_Access
:= new WSDL.AST.Faults.Interface_Fault_Reference_Node;
Message_Direction : WSDL.AST.Message_Directions;
Found : Boolean;
begin
Node.Parent := Parent;
Parent.Interface_Fault_References.Append (Node);
-- InterfaceFaultReference-1037: "The value of this property MUST match
-- the name of a placeholder message defined by the message exchange
-- pattern."
--
-- Enforced by construction.
-- InterfaceFaultReference-1038: "The direction MUST be consistent with
-- the direction implied by the fault propagation ruleset used in the
-- message exchange pattern of the operation."
--
-- Enforced by construction.
Node.Interface_Fault_Name :=
To_Qualified_Name (Namespaces, Attributes.Value (Ref_Attribute));
Node.Direction := Direction;
case Node.Direction is
when WSDL.AST.In_Message =>
-- MessageLabel-1034: "If the local name is infault then the
-- message exchange pattern MUST support at least one fault in the
-- "In" direction."
if not Parent.Message_Exchange_Pattern.Has_In_Fault then
Parser.Report (WSDL.Assertions.MessageLabel_1034);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
-- MessageLabel-1035: "If the local name is outfault then the
-- message exchange pattern MUST support at least one fault in the
-- "Out" direction."
if not Parent.Message_Exchange_Pattern.Has_Out_Fault then
Parser.Report (WSDL.Assertions.MessageLabel_1034);
raise WSDL_Error;
end if;
end case;
-- Compute corresponding message direction depending on Fault
-- Propagation Rule.
case Parent.Message_Exchange_Pattern.FPR is
when WSDL.MEPs.Fault_Replaces_Message =>
Message_Direction := Direction;
when WSDL.MEPs.Message_Triggers_Fault =>
case Direction is
when WSDL.AST.In_Message =>
Message_Direction := WSDL.AST.Out_Message;
when WSDL.AST.Out_Message =>
Message_Direction := WSDL.AST.In_Message;
end case;
when WSDL.MEPs.No_Faults =>
-- Must never be happen, it violates MessageLabel-1034 and
-- MessageLabel-1035 assertions tested above.
raise Program_Error;
end case;
-- Analyze 'messageLabel' attribute.
if Attributes.Is_Specified (Message_Label_Attribute) then
Node.Message_Label := Attributes.Value (Message_Label_Attribute);
else
-- InterfaceFaultReference-1040: "The messageLabel attribute
-- information item MUST be present in the XML representation of an
-- Interface Fault Reference component with a given {direction}, if
-- the {message exchange pattern} of the parent Interface Operation
-- component has more than one fault with that direction."
case Node.Direction is
when WSDL.AST.In_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_In_Fault then
Parser.Report (WSDL.Assertions.InterfaceFaultReference_1040);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_Out_Fault then
Parser.Report (WSDL.Assertions.InterfaceFaultReference_1040);
raise WSDL_Error;
end if;
end case;
-- MessageLabel-1043: "If the messageLabel attribute information item
-- of an interface fault reference element information item is absent
-- then there MUST be a unique placeholder message with {direction}
-- equal to the message direction."
case Message_Direction is
when WSDL.AST.In_Message =>
if not Parent.Message_Exchange_Pattern.Has_In then
Parser.Report (WSDL.Assertions.MessageLabel_1043);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
if not Parent.Message_Exchange_Pattern.Has_Out then
Parser.Report (WSDL.Assertions.MessageLabel_1043);
raise WSDL_Error;
end if;
end case;
-- MessageLabel-1041: "The messageLabel attribute information item of
-- an interface fault reference element information item MUST be
-- present if the message exchange pattern has more than one
-- placeholder message with {direction} equal to the message
-- direction."
case Message_Direction is
when WSDL.AST.In_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_In then
Parser.Report (WSDL.Assertions.MessageLabel_1041);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_Out then
Parser.Report (WSDL.Assertions.MessageLabel_1041);
raise WSDL_Error;
end if;
end case;
end if;
-- Lookup for placeholder message in the operation's MEP.
Found := False;
for J in Parent.Message_Exchange_Pattern.Placeholders'Range loop
if Parent.Message_Exchange_Pattern.Placeholders (J).Direction
= Message_Direction
and (Node.Message_Label.Is_Empty
or Parent.Message_Exchange_Pattern.Placeholders (J).Label
= Node.Message_Label)
then
-- InterfaceFaultReference-1039: "For each Interface Fault
-- Reference component in the {interface fault references}
-- property of an Interface Operation component, the combination
-- of its {interface fault} and {message label} properties MUST be
-- unique."
--
-- All declared faults corresponding to message placeholder are
-- stored in maps to checks unique of their names.
if Parent.Message_Exchange_Pattern.Placeholders (J).Faults.Contains
(Node.Interface_Fault_Name)
then
Parser.Report (WSDL.Assertions.InterfaceFaultReference_1039);
raise WSDL_Error;
end if;
Parent.Message_Exchange_Pattern.Placeholders (J).Faults.Insert
(Node.Interface_Fault_Name, Node);
Node.Message_Label :=
Parent.Message_Exchange_Pattern.Placeholders (J).Label;
Found := True;
exit;
end if;
end loop;
if not Found then
-- MessageLabel-1042: "If the messageLabel attribute information item
-- of an interface fault reference element information item is
-- present then its actual value MUST match the {message label} of
-- some placeholder message with {direction} equal to the message
-- direction."
--
-- When messageLabel attribute of interface fault reference
-- element is not specified, it always found because there is only
-- one placeholder message in the MEP. Thus, additional checks are
-- not needed here.
Parser.Report (WSDL.Assertions.MessageLabel_1042);
raise WSDL_Error;
end if;
end Start_Input_Output_Fault_Element;
--------------------------------
-- Start_Input_Output_Element --
--------------------------------
procedure Start_Input_Output_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Operation_Access;
Direction : WSDL.AST.Message_Directions;
Success : in out Boolean)
is
pragma Unreferenced (Success);
use type WSDL.AST.Interface_Message_Access;
Node : constant WSDL.AST.Interface_Message_Access
:= new WSDL.AST.Messages.Interface_Message_Node;
Found : Boolean;
begin
Node.Parent := Parent;
Parent.Interface_Message_References.Append (Node);
-- InterfaceMessageReference-1025: "An xs:token with one of the values
-- in or out, indicating whether the message is coming to the service or
-- going from the service, respectively."
--
-- This assertion is enforced by construction.
-- InterfaceMessageReference-1026: "The direction MUST be the same as
-- the direction of the message identified by the {message label}
-- property in the {message exchange pattern} of the Interface Operation
-- component this is contained within."
--
-- This assertion is enforced by construction.
-- MessageLabel-1024: "The value of this property MUST match the name of
-- placeholder message defined by the message exchange pattern."
--
-- This assertion is enforced by construction.
Node.Direction := Direction;
case Direction is
when WSDL.AST.In_Message =>
-- MessageLabel-1032: "If the local name is input then the message
-- exchange pattern MUST have at least one placeholder message
-- with direction "In"."
if not Parent.Message_Exchange_Pattern.Has_In then
Parser.Report (WSDL.Assertions.MessageLabel_1032);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
-- MessageLabel-1033: "If the local name is output then the
-- message exchange pattern MUST have at least one placeholder
-- message with direction "Out"."
if not Parent.Message_Exchange_Pattern.Has_Out then
Parser.Report (WSDL.Assertions.MessageLabel_1033);
raise WSDL_Error;
end if;
end case;
-- Analyze 'messageLabel' attribute.
if Attributes.Is_Specified (Message_Label_Attribute) then
Node.Message_Label := Attributes.Value (Message_Label_Attribute);
else
-- MessageLabel-1031: "If the messageLabel attribute information item
-- of an interface message reference element information item is
-- absent then there MUST be a unique placeholder message with
-- {direction} equal to the message direction."
case Direction is
when WSDL.AST.In_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_In then
Parser.Report (WSDL.Assertions.MessageLabel_1031);
raise WSDL_Error;
end if;
when WSDL.AST.Out_Message =>
if not Parent.Message_Exchange_Pattern.Has_Single_Out then
Parser.Report (WSDL.Assertions.MessageLabel_1031);
raise WSDL_Error;
end if;
end case;
end if;
-- Lookup for placeholder in the operation's MEP.
Found := False;
for J in Parent.Message_Exchange_Pattern.Placeholders'Range loop
if Parent.Message_Exchange_Pattern.Placeholders (J).Direction
= Direction
and (Node.Message_Label.Is_Empty
or Parent.Message_Exchange_Pattern.Placeholders (J).Label
= Node.Message_Label)
then
-- InterfaceMessageReference-1029: "For each Interface Message
-- Reference component in the {interface message references}
-- property of an Interface Operation component, its {message
-- label} property MUST be unique."
--
-- This code assumes that MEP uses unique labels for messages and
-- takes in sense the fact that Message member is filled by
-- interface message reference once it is processed.
if Parent.Message_Exchange_Pattern.Placeholders (J).Message /= null then
Parser.Report (WSDL.Assertions.InterfaceMessageReference_1029);
raise WSDL_Error;
end if;
Parent.Message_Exchange_Pattern.Placeholders (J).Message := Node;
Node.Message_Label :=
Parent.Message_Exchange_Pattern.Placeholders (J).Label;
Found := True;
exit;
end if;
end loop;
if not Found then
-- MessageLabel-1030: "If the messageLabel attribute information item
-- of an interface message reference element information item is
-- present, then its actual value MUST match the {message label} of
-- some placeholder message with {direction} equal to the message
-- direction."
Parser.Report (WSDL.Assertions.MessageLabel_1030);
raise WSDL_Error;
end if;
-- Analyze 'element' attribute.
-- InterfaceMessageReference-1027: "An xs:token with one of the values
-- #any, #none, #other, or #element."
--
-- This assertion is enforced by construction.
-- InterfaceMessageReference-1028: "When the {message content model}
-- property has the value #any or #none, the {element declaration}
-- property MUST be empty."
--
-- This assertion is enforced by construction.
if Attributes.Is_Specified (Element_Attribute) then
declare
Value : constant League.Strings.Universal_String
:= Attributes.Value (Element_Attribute);
begin
if Value = Any_Literal then
Node.Message_Content_Model := WSDL.AST.Any;
elsif Value = None_Literal then
Node.Message_Content_Model := WSDL.AST.None;
elsif Value = Other_Literal then
Node.Message_Content_Model := WSDL.AST.Other;
else
Node.Message_Content_Model := WSDL.AST.Element;
Node.Element := To_Qualified_Name (Namespaces, Value);
end if;
end;
else
Node.Message_Content_Model := WSDL.AST.Other;
end if;
end Start_Input_Output_Element;
-----------------------------
-- Start_Interface_Element --
-----------------------------
procedure Start_Interface_Element
(Parser : in out WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Description : WSDL.AST.Description_Access;
Node : out WSDL.AST.Interface_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
begin
-- Interface-1010: "For each Interface component in the {interfaces}
-- property of a Description component, the {name} property MUST be
-- unique."
--
-- Check whether name of the interface component is not used by another
-- component.
if Description.Interfaces.Contains (Name) then
Parser.Report (WSDL.Assertions.Interface_1010);
raise WSDL_Error;
end if;
Node := new WSDL.AST.Interfaces.Interface_Node;
Node.Parent := Description;
Node.Local_Name := Name;
Description.Interfaces.Insert (Name, Node);
-- Analyze 'extends' attribute when specified.
if Attributes.Is_Specified (Extends_Attribute) then
declare
Values : constant League.String_Vectors.Universal_String_Vector
:= Attributes.Value (Extends_Attribute).Split
(' ', League.Strings.Skip_Empty);
Item : WSDL.AST.Qualified_Name;
begin
for J in 1 .. Values.Length loop
Item := To_Qualified_Name (Namespaces, Values.Element (J));
-- Interface-1011: "The list of xs:QName in an extends
-- attribute information item MUST NOT contain duplicates."
--
-- Check whether this namespace/name pair is not in the set
-- already.
if Node.Extends.Contains (Item) then
Parser.Report (WSDL.Assertions.Interface_1011);
raise WSDL_Error;
end if;
Node.Extends.Insert (Item);
end loop;
end;
end if;
-- Analyze 'styleDefault' attribute when specified.
if Attributes.Is_Specified (Style_Default_Attribute) then
Node.Style_Default :=
Attributes.Value (Style_Default_Attribute).Split
(' ', League.Strings.Skip_Empty);
-- Interface-1012: "The type of the styleDefault attribute
-- information item is list of xs:anyURI. Its value, if present, MUST
-- contain absolute IRIs (see [IETF RFC 3987])."
--
-- XXX This check is not implemented.
end if;
end Start_Interface_Element;
-----------------------------------
-- Start_Interface_Fault_Element --
-----------------------------------
procedure Start_Interface_Fault_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Interface_Access;
-- Node : out WSDL.AST.Faults.Interface_Fault_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
Node : WSDL.AST.Interface_Fault_Access;
begin
Node := new WSDL.AST.Faults.Interface_Fault_Node;
Node.Parent := Parent;
Node.Local_Name := Name;
Parent.Interface_Faults.Insert (Name, Node);
-- Analyze 'element' attribute.
-- Note, there are two assertion is applied to {message content model}
-- and {element declaration} properties of interface's fault component:
--
-- InterfaceFault-1013: "An xs:token with one of the values #any, #none,
-- #other, or #element."
--
-- InterfaceFault-1014: "When the {message content model} property has
-- the value #any or #none the {element declaration} property MUST be
-- empty."
--
-- Both assertions not need to be tested at runtime, they are enforced
-- by construction.
if Attributes.Is_Specified (Element_Attribute) then
declare
Value : constant League.Strings.Universal_String
:= Attributes.Value (Element_Attribute);
begin
if Value = Any_Literal then
Node.Message_Content_Model := WSDL.AST.Any;
elsif Value = None_Literal then
Node.Message_Content_Model := WSDL.AST.None;
elsif Value = Other_Literal then
Node.Message_Content_Model := WSDL.AST.Other;
else
Node.Message_Content_Model := WSDL.AST.Element;
Node.Element := To_Qualified_Name (Namespaces, Value);
end if;
end;
else
Node.Message_Content_Model := WSDL.AST.Other;
end if;
end Start_Interface_Fault_Element;
---------------------------------------
-- Start_Interface_Operation_Element --
---------------------------------------
procedure Start_Interface_Operation_Element
(Parser : WSDL_Parser;
Attributes : XML.SAX.Attributes.SAX_Attributes;
Parent : not null WSDL.AST.Interface_Access;
Node : out WSDL.AST.Interface_Operation_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
MEP_IRI : League.Strings.Universal_String;
begin
Node := new WSDL.AST.Operations.Interface_Operation_Node;
Node.Parent := Parent;
Node.Local_Name := Name;
Parent.Interface_Operations.Insert (Name, Node);
-- Analyze 'pattern' attribute.
if Attributes.Is_Specified (Pattern_Attribute) then
MEP_IRI := Attributes.Value (Pattern_Attribute);
-- InterfaceOperation-1018: "This xs:anyURI MUST be an absolute IRI
-- (see [IETF RFC 3987])."
--
-- XXX Not implemented yet.
else
MEP_IRI := In_Out_MEP;
end if;
Node.Message_Exchange_Pattern := WSDL.Parsers.MEP.Resolve (Parser, MEP_IRI);
-- Analyze 'style' attribute.
if Attributes.Is_Specified (Style_Attribute) then
Node.Style :=
Attributes.Value (Style_Attribute).Split
(' ', League.Strings.Skip_Empty);
for J in 1 .. Node.Style.Length loop
-- InterfaceOperation-1019: "These xs:anyURIs MUST be absolute
-- IRIs (see [IETF RFC 3986])."
--
-- XXX Not implemented yet.
null;
end loop;
else
Node.Style := Node.Parent.Style_Default;
end if;
end Start_Interface_Operation_Element;
--------------------------
-- Start_Prefix_Mapping --
--------------------------
overriding procedure Start_Prefix_Mapping
(Self : in out WSDL_Parser;
Prefix : League.Strings.Universal_String;
Namespace_URI : League.Strings.Universal_String;
Success : in out Boolean)
is
pragma Unreferenced (Success);
begin
Self.Namespaces.Insert (Prefix, Namespace_URI);
end Start_Prefix_Mapping;
---------------------------
-- Start_Service_Element --
---------------------------
procedure Start_Service_Element
(Attributes : XML.SAX.Attributes.SAX_Attributes;
Namespaces : Namespace_Maps.Map;
Parent : WSDL.AST.Description_Access;
Node : out WSDL.AST.Services.Service_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
Name : constant League.Strings.Universal_String
:= Attributes.Value (Name_Attribute);
begin
-- Service-1060: "For each Service component in the {services} property
-- of a Description component, the {name} property MUST be unique."
if Parent.Services.Contains (Name) then
raise Program_Error;
end if;
Node := new WSDL.AST.Services.Service_Node;
Node.Parent := Parent;
Node.Local_Name := Name;
Parent.Services.Insert (Name, Node);
-- Analyze 'interface' attribute.
Node.Interface_Name :=
To_Qualified_Name (Namespaces, Attributes.Value (Interface_Attribute));
end Start_Service_Element;
-------------------------
-- Start_Types_Element --
-------------------------
procedure Start_Types_Element
(Description : WSDL.AST.Description_Access;
Success : in out Boolean)
is
pragma Unreferenced (Success);
begin
Description.Types := new WSDL.AST.Types.Types_Node;
Description.Types.Parent := Description;
end Start_Types_Element;
-----------------------
-- To_Qualified_Name --
-----------------------
function To_Qualified_Name
(Namespaces : Namespace_Maps.Map;
Name : League.Strings.Universal_String)
return WSDL.AST.Qualified_Name
is
Index : constant Natural := Name.Index (':');
begin
return
(Namespace_URI => Namespaces.Element (Name.Slice (1, Index - 1)),
Local_Name => Name.Slice (Index + 1, Name.Length));
end To_Qualified_Name;
end WSDL.Parsers;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- S E M _ C H 4 --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1992,1993,1994,1995,1996 Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 2, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING. If not, write --
-- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, --
-- MA 02111-1307, USA. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Types; use Types;
package Sem_Ch4 is
procedure Analyze_Aggregate (N : Node_Id);
procedure Analyze_Allocator (N : Node_Id);
procedure Analyze_Arithmetic_Op (N : Node_Id);
procedure Analyze_Call (N : Node_Id);
procedure Analyze_Comparison_Op (N : Node_Id);
procedure Analyze_Concatenation (N : Node_Id);
procedure Analyze_Conditional_Expression (N : Node_Id);
procedure Analyze_Equality_Op (N : Node_Id);
procedure Analyze_Explicit_Dereference (N : Node_Id);
procedure Analyze_Logical_Op (N : Node_Id);
procedure Analyze_Membership_Op (N : Node_Id);
procedure Analyze_Negation (N : Node_Id);
procedure Analyze_Null (N : Node_Id);
procedure Analyze_Qualified_Expression (N : Node_Id);
procedure Analyze_Range (N : Node_Id);
procedure Analyze_Reference (N : Node_Id);
procedure Analyze_Selected_Component (N : Node_Id);
procedure Analyze_Short_Circuit (N : Node_Id);
procedure Analyze_Slice (N : Node_Id);
procedure Analyze_Type_Conversion (N : Node_Id);
procedure Analyze_Unary_Op (N : Node_Id);
procedure Analyze_Unchecked_Expression (N : Node_Id);
procedure Analyze_Unchecked_Type_Conversion (N : Node_Id);
procedure Analyze_Indexed_Component_Form (N : Node_Id);
-- Prior to semantic analysis, an indexed component node can denote any
-- of the following syntactic constructs:
-- a) An indexed component of an array
-- b) A function call
-- c) A conversion
-- d) A slice
-- The resolution of the construct requires some semantic information
-- on the prefix and the indices.
end Sem_Ch4;
|
------------------------------------------------------------------------------
-- --
-- GNAT EXAMPLE --
-- --
-- Copyright (C) 2013, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. --
-- --
-- As a special exception under Section 7 of GPL version 3, you are granted --
-- additional permissions described in the GCC Runtime Library Exception, --
-- version 3.1, as published by the Free Software Foundation. --
-- --
-- You should have received a copy of the GNU General Public License and --
-- a copy of the GCC Runtime Library Exception along with this program; --
-- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see --
-- <http://www.gnu.org/licenses/>. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
pragma Warnings (Off);
with System.STM32F4; use System.STM32F4;
pragma Warnings (On);
package Mphone is
pragma Elaborate_Body;
-- Bit definitions for RCC AHB1ENR register
RCC_AHB1ENR_GPIOC : constant Word := 16#04#;
-- Bit definitions for RCC APB1ENR register
RCC_APB1ENR_SPI2 : constant Word := 16#0000_4000#;
GPIOC_Base : constant := AHB1_Peripheral_Base + 16#0800#;
SPI2_Base : constant := APB1_Peripheral_Base + 16#3800#;
GPIOC : GPIO_Registers with Volatile,
Import,
Address => System'To_Address (GPIOC_Base);
type SPI_Registers is record
CR1 : Word;
CR2 : Word;
SR : Word;
DR : Word;
CRCPR : Word;
RXCRCR : Word;
TXCRCR : Word;
I2SCFGR : Word;
I2SPR : Word;
end record;
SPI2 : SPI_Registers with Volatile,
Import,
Address => System'To_Address (SPI2_Base);
package SPI_I2SCFGR is
I2SMOD : constant Word := 16#0800#;
I2SE : constant Word := 16#0400#;
I2SCFG_SlaveTx : constant Word := 16#0000#;
I2SCFG_SlaveRx : constant Word := 16#0100#;
I2SCFG_MasterTx : constant Word := 16#0200#;
I2SCFG_MasterRx : constant Word := 16#0300#;
PCMSYNC : constant Word := 16#0080#;
I2SSTD_Philips : constant Word := 16#0000#;
I2SSTD_MSB : constant Word := 16#0010#;
I2SSTD_LSB : constant Word := 16#0020#;
I2SSTD_PCM : constant Word := 16#0030#;
CKPOL : constant Word := 16#0008#;
DATLEN_16 : constant Word := 16#0000#;
DATLEN_24 : constant Word := 16#0002#;
DATLEN_32 : constant Word := 16#0004#;
CHLEN_16 : constant Word := 16#0000#;
CHLEN_32 : constant Word := 16#0001#;
end SPI_I2SCFGR;
package SPI_I2SPR is
MCKOE : constant Word := 16#200#;
ODD : constant Word := 16#100#;
end SPI_I2SPR;
package SPI_CR2 is
TXEIE : constant Word := 16#80#;
RXNEIE : constant Word := 16#40#;
ERRIE : constant Word := 16#20#;
FRF : constant Word := 16#10#;
SSOE : constant Word := 16#04#;
TXDMAEN : constant Word := 16#02#;
RXDMAEN : constant Word := 16#01#;
end SPI_CR2;
package SPI_SR is
FRE : constant Word := 16#100#;
BSY : constant Word := 16#080#;
OVR : constant Word := 16#040#;
MODF : constant Word := 16#020#;
CRCERR : constant Word := 16#010#;
UDR : constant Word := 16#008#;
CHSIDE : constant Word := 16#004#;
TXE : constant Word := 16#002#;
RXNE : constant Word := 16#001#;
end SPI_SR;
subtype Sample_Type is Natural range 0 .. 32;
function Get_Spd_Sample return Natural;
end Mphone;
|
-- Abstract :
--
-- Generalized LALR parse table generator.
--
-- Copyright (C) 2002 - 2003, 2009 - 2010, 2013 - 2015, 2017 - 2020 Free Software Foundation, Inc.
--
-- This file is part of the WisiToken package.
--
-- The WisiToken package is free software; you can redistribute it
-- and/or modify it under terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or
-- (at your option) any later version. This library is distributed in
-- the hope that it will be useful, but WITHOUT ANY WARRANTY; without
-- even the implied warranty of MERCHAN- TABILITY or FITNESS FOR A
-- PARTICULAR PURPOSE.
--
-- As a special exception under Section 7 of GPL version 3, you are granted
-- additional permissions described in the GCC Runtime Library Exception,
-- version 3.1, as published by the Free Software Foundation.
pragma License (Modified_GPL);
with WisiToken.Generate.LR1_Items;
with WisiToken.Productions;
package WisiToken.Generate.LR.LALR_Generate is
function Generate
(Grammar : in out WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor;
Known_Conflicts : in Conflict_Lists.List := Conflict_Lists.Empty_List;
McKenzie_Param : in McKenzie_Param_Type := Default_McKenzie_Param;
Parse_Table_File_Name : in String := "";
Include_Extra : in Boolean := False;
Ignore_Conflicts : in Boolean := False;
Partial_Recursion : in Boolean := True)
return Parse_Table_Ptr
with Pre =>
Descriptor.Last_Lookahead = Descriptor.First_Nonterminal and
Descriptor.First_Nonterminal = Descriptor.Accept_ID;
-- Generate a generalized LALR parse table for Grammar. The
-- grammar start symbol is the LHS of the first production in
-- Grammar.
--
-- Unless Ignore_Unused_Tokens is True, raise Grammar_Error if
-- there are unused tokens.
--
-- Unless Ignore_Unknown_Conflicts is True, raise Grammar_Error if there
-- are unknown conflicts.
----------
-- Visible for unit tests
function LALR_Goto_Transitions
(Kernel : in LR1_Items.Item_Set;
Symbol : in Token_ID;
First_Nonterm_Set : in Token_Array_Token_Set;
Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Descriptor : in WisiToken.Descriptor)
return LR1_Items.Item_Set;
-- Return the Item_Set that is the goto for Symbol from Kernel.
-- If there is no such Item_Set, Result.Set is null.
function LALR_Kernels
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
First_Nonterm_Set : in Token_Array_Token_Set;
Descriptor : in WisiToken.Descriptor)
return LR1_Items.Item_Set_List;
procedure Fill_In_Lookaheads
(Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Has_Empty_Production : in Token_ID_Set;
First_Terminal_Sequence : in Token_Sequence_Arrays.Vector;
Kernels : in out LR1_Items.Item_Set_List;
Descriptor : in WisiToken.Descriptor);
procedure Add_Actions
(Kernels : in LR1_Items.Item_Set_List;
Grammar : in WisiToken.Productions.Prod_Arrays.Vector;
Has_Empty_Production : in Token_ID_Set;
First_Nonterm_Set : in Token_Array_Token_Set;
First_Terminal_Sequence : in Token_Sequence_Arrays.Vector;
Conflict_Counts : out Conflict_Count_Lists.List;
Conflicts : out Conflict_Lists.List;
Table : in out Parse_Table;
Descriptor : in WisiToken.Descriptor);
end WisiToken.Generate.LR.LALR_Generate;
|
with Bitmaps.RGB;
with Simulated_Annealing;
generic
type Image_Access is access Bitmaps.RGB.Image;
package Problem is
subtype Direction is Integer range -1 .. 1;
type State is record
Img : Image_Access;
E : Long_Integer;
X, Y : Natural;
DX, DY : Direction;
Visited : Boolean;
end record;
function Objective (S : in State) return Float;
procedure Shuffle (S : in State);
procedure Roll (S : in out State);
function Mutate (S : in out State) return State;
package Opt is new Simulated_Annealing.Optimization (State, Objective,
Mutate);
end Problem;
|
-----------------------------------------------------------------------
-- package Runge_8th, 8th order Prince and Dormand Runge-Kutta
-- Copyright (C) 2008-2018 Jonathan S. Parker.
--
-- 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.
-----------------------------------------------------------------------
-- PACKAGE Runge_8th
--
-- Package implements the 8th order Runge Kutta formula of Prince
-- and Dormand (Journal of Computational and Applied Math.
-- vol. 7, p. 67 (1981)).
--
-- Procedure Integrate solves dY/dt = F (t, Y) where t is the
-- independent variable (e.g. time), vector Y is the dependent
-- variable, and F is some function.
--
-- Just a reminder of why high order is important if you want high
-- accuracy: compare a 2nd order method (error per step ~ B*dt^3)
-- with a 9th order method (error per step ~ A*dt^10). Suppose each
-- method gives for this 'dt' a relative error of 10^(-6), (an error
-- of 1 part per million) and we want to reduce this to 10^(-15).
-- In other words we want to reduce the error by a factor of 10^(-9).
-- If the 2nd order step size dt is divided by 2^10, then its error
-- (per step( falls by a factor (1/2^10)^3 = 1/2^30 = 1/10^9 as required.
-- If the 9th order step size dt is divided by 2^3, then its error
-- falls by a factor (1/2^3)^10 = 1/2^30 = 1/10^9 as required. So
-- the 2nd order method needs at least 128 times as many time steps
-- to perform an integration over the same time interval as the 9th
-- order method. Even if the 2nd order method runs 5 times faster
-- per step than the 9th order method, then we should expect the
-- 9th order method to be ~25 times faster than the 2nd order method.
-- (Actually, globally the error term behaves as though it is an order
-- lower than the local (per step) error term, so the higher order is
-- even more favorable than the above argument indicates.)
--
-- Additional note: the error term per step of the Runge-Kutta looks
-- more like A*dt^10 than A*dt^9 as you near machine precision. (Prince
-- and Dormand optimized the coefficients to minimize this term.) Yet
-- another reason why this Runge-Kutta performs better than expected
-- in so many cases.
--
-- NOTES ON USE
--
-- Runge_8th assumes that the Dynamical Variable is a 1 dimensional
-- array of Real numbers.
--
-- To use this routine higher order differential equations have to
-- be reduced to 1st order equations.
-- For example a 3rd order equation in X becomes a first order
-- equation in the vector Y = (Y1,Y2,Y3) = (X, dX/dt, d/dt(dX/dt)).
-- If the equation in X is (d/dt)**3 X = G(t,X), then the
-- equation in vector Y is
--
-- d/dt (Y1, Y2, Y3) = (Y2, Y3, G(t,Y1)).
--
-- If the equation in X is d/dt(d/dt(dX/dt))) = G(t,X,dX/dt),
-- then the equation in Y is
--
-- d/dt (Y1, Y2, Y3) = (Y2, Y3, G(t,Y1,Y2)).
--
-- So the routine solves the equation dY/dt = F(t,Y), or, more
-- explicitly, d/dt (Y1, Y2, Y3) = (Y2, Y3, G(t,Y1,Y2)) = F(t,Y).
-- The user plugs in the function F(t,Y) as a generic formal function.
-- Even if F is t or Y independent, it must be in the form F(t,Y).
-- The user has to do all of the work to convert higher order
-- equations to first order equations. On some compilers,
-- performance is very sensitive to how this is done. That's
-- why this part is best left to the user. I've seen factors of
-- 3 improvement in speed when this part of the data structure
-- is optimized. A pragma Inline is also worth trying.
-- The generic formal parameters "+" and "*" below should be
-- compiled Inline.
--
-- Uses the elementary math functions Log and Exp (used in
-- the error control algorithm to implement the exponentiation
-- function (**)). They're used each step, which can be slow!
--
-- Runge-Kutta routines can be used to integrate moderately
-- stiff equations: use constant step size without error control
-- and make the step size sufficiently small. (Routines specially
-- designed for stiff equations may be orders of magnitude faster.)
--
-- There's no fool proof way of getting the right answer when
-- you numerically integrate. In some cases error control does
-- not work well. In other cases, integration without
-- error control fails simply because it is too ineffient.
-- Using error control: if you have 15 digit floating point,
-- then don't demand more than 12 or 13 digits of accuracy.
-- The error control algorithm begins to fail in that limit.
generic
type Real is digits <>;
-- The independent variable has type Real. It's called Time
-- throughout the package as though the differential
-- equation dY/dt = F (t, Y) were time dependent.
type Dyn_Index is range <>;
type Dynamical_Variable is array(Dyn_Index) of Real;
-- The dependent variable. Declared as an array here so that
-- some inner loop optimizations can be performed below.
--
-- To use this routine, reduce higher order differential
-- equations to 1st order.
-- For example a 3rd order equation in X becomes a first order
-- equation in the vector Y = (X, dX/dt, d/dt(dX/dt)).
with function F
(Time : Real;
Y : Dynamical_Variable)
return Dynamical_Variable is <>;
-- Defines the equation to be integrated: dY/dt = F (t, Y). Even if
-- the equation is t or Y independent, it must be entered in this form.
with function "*"
(Left : Real;
Right : Dynamical_Variable)
return Dynamical_Variable is <>;
-- Multiplication of the independent by the dependent variable.
-- An operation of this sort exists by definition of the
-- derivative, dY/dt = (Y(t+dt) - Y(t)) / dt,
-- which requires multiplication of the (inverse) independent
-- variable t, by the Dynamical variable Y (the dependent variable).
with function "+"
(Left : Dynamical_Variable;
Right : Dynamical_Variable)
return Dynamical_Variable is <>;
-- Summation of the dependent variable.
-- The operation must exist by the definition of the derivative,
-- dY/dt = (Y(t+dt) - Y(t)) / dt = (Y(t+dt) + (-1)*Y(t)) / dt.
with function "-"
(Left : Dynamical_Variable;
Right : Dynamical_Variable)
return Dynamical_Variable is <>;
with function Norm
(Y1: in Dynamical_Variable) return Real is <>;
-- For error control we need to know the distance between two objects.
-- Norm define a distance between the two vector, Y1 and Y2
-- using: distance = Norm (Y1 - Y2),
-- For example, if Dynamical_Variable is complex, then Norm can
-- be Sqrt (Real (Y1(1)) * Conjugate (Y1(1))));
-- If it is a vector then the metric may be
-- Sqrt (Transpose(Y1(1)) * Y1(1)), etc.
--
-- Recommended: Sum the absolute values of the components of the vector.
package Runge_8th is
type Step_Integer is range 1 .. 2**31-1;
-- The step size Delta_t is never input. Instead
-- you input Starting_Time, Final_Time, and No_Of_Steps.
--
-- If error control is disabled, then Delta_t is
-- (Final_Time - Starting_Time) / No_Of_Steps.
--
-- If error control is enabled, then step size Delta_t is variable,
-- and procedure Integrate chooses its own Delta_t each time step.
-- Each time step, Delta_t is chosen to reduce fractional error
-- per step to something less than Error_Tolerance. It does not
-- and cannot reduce global error to any given value.
--
-- All components of vector Initial_State must be initialized.
procedure Integrate
(Final_State : out Dynamical_Variable;
Final_Time : in Real;
Initial_State : in Dynamical_Variable;
Initial_Time : in Real;
No_Of_Steps : in Step_Integer;
Error_Control_Desired : in Boolean := False;
Error_Tolerance : in Real := +1.0E-10);
private
Zero : constant := +0.0;
Half : constant := +0.5;
One : constant := +1.0;
Two : constant := +2.0;
Four : constant := +4.0;
Nine_Tenths : constant := +0.9;
One_Eighth : constant := +0.125;
Test_of_Runge_Coeffs_Desired : constant Boolean := False;
-- The test (exported by Runge_Coeffs_13) prints an error message if
-- failure is detected. Should be set to True during testing.
end Runge_8th;
|
--
-- Copyright (C) 2014-2018 secunet Security Networks AG
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
with GNAT.Source_Info;
with HW.Time;
with HW.Debug;
with HW.GFX.GMA.Config;
with HW.GFX.GMA.Registers;
package body HW.GFX.GMA.Power_And_Clocks_Haswell is
PWR_WELL_CTL_ENABLE_REQUEST : constant := 1 * 2 ** 31;
PWR_WELL_CTL_DISABLE_REQUEST : constant := 0 * 2 ** 31;
PWR_WELL_CTL_STATE_ENABLED : constant := 1 * 2 ** 30;
----------------------------------------------------------------------------
SRD_CTL_ENABLE : constant := 1 * 2 ** 31;
SRD_STATUS_STATE_MASK : constant := 7 * 2 ** 29;
type Pipe is (EDP, A, B, C);
type SRD_Regs is record
CTL : Registers.Registers_Index;
STATUS : Registers.Registers_Index;
end record;
type SRD_Per_Pipe_Regs is array (Pipe) of SRD_Regs;
SRD : constant SRD_Per_Pipe_Regs := SRD_Per_Pipe_Regs'
(A => SRD_Regs'
(CTL => Registers.SRD_CTL_A,
STATUS => Registers.SRD_STATUS_A),
B => SRD_Regs'
(CTL => Registers.SRD_CTL_B,
STATUS => Registers.SRD_STATUS_B),
C => SRD_Regs'
(CTL => Registers.SRD_CTL_C,
STATUS => Registers.SRD_STATUS_C),
EDP => SRD_Regs'
(CTL => Registers.SRD_CTL_EDP,
STATUS => Registers.SRD_STATUS_EDP));
----------------------------------------------------------------------------
IPS_CTL_ENABLE : constant := 1 * 2 ** 31;
DISPLAY_IPS_CONTROL : constant := 16#19#;
GT_MAILBOX_READY : constant := 1 * 2 ** 31;
----------------------------------------------------------------------------
procedure PSR_Off
is
Enabled : Boolean;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Config.Has_Per_Pipe_SRD then
for P in Pipe loop
Registers.Is_Set_Mask (SRD (P).CTL, SRD_CTL_ENABLE, Enabled);
if Enabled then
Registers.Unset_Mask (SRD (P).CTL, SRD_CTL_ENABLE);
Registers.Wait_Unset_Mask (SRD (P).STATUS, SRD_STATUS_STATE_MASK);
pragma Debug (Debug.Put_Line ("Disabled PSR."));
end if;
end loop;
else
Registers.Is_Set_Mask (Registers.SRD_CTL, SRD_CTL_ENABLE, Enabled);
if Enabled then
Registers.Unset_Mask (Registers.SRD_CTL, SRD_CTL_ENABLE);
Registers.Wait_Unset_Mask (Registers.SRD_STATUS, SRD_STATUS_STATE_MASK);
pragma Debug (Debug.Put_Line ("Disabled PSR."));
end if;
end if;
end PSR_Off;
----------------------------------------------------------------------------
procedure GT_Mailbox_Write (MBox : Word32; Value : Word32) is
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
Registers.Wait_Unset_Mask (Registers.GT_MAILBOX, GT_MAILBOX_READY);
Registers.Write (Registers.GT_MAILBOX_DATA, Value);
Registers.Write (Registers.GT_MAILBOX, GT_MAILBOX_READY or MBox);
Registers.Wait_Unset_Mask (Registers.GT_MAILBOX, GT_MAILBOX_READY);
Registers.Write (Registers.GT_MAILBOX_DATA, 0);
end GT_Mailbox_Write;
procedure IPS_Off
is
Enabled : Boolean;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
if Config.Has_IPS then
Registers.Is_Set_Mask (Registers.IPS_CTL, IPS_CTL_ENABLE, Enabled);
if Enabled then
if Config.Has_IPS_CTL_Mailbox then
GT_Mailbox_Write (DISPLAY_IPS_CONTROL, 0);
Registers.Wait_Unset_Mask
(Register => Registers.IPS_CTL,
Mask => IPS_CTL_ENABLE,
TOut_MS => 42);
else
Registers.Unset_Mask (Registers.IPS_CTL, IPS_CTL_ENABLE);
end if;
pragma Debug (Debug.Put_Line ("Disabled IPS."));
-- We have to wait until the next vblank here.
-- 20ms should be enough.
Time.M_Delay (20);
end if;
end if;
end IPS_Off;
----------------------------------------------------------------------------
procedure PDW_Off
is
Ctl1, Ctl2, Ctl3, Ctl4 : Word32;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
Registers.Read (Registers.PWR_WELL_CTL_BIOS, Ctl1);
Registers.Read (Registers.PWR_WELL_CTL_DRIVER, Ctl2);
Registers.Read (Registers.PWR_WELL_CTL_KVMR, Ctl3);
Registers.Read (Registers.PWR_WELL_CTL_DEBUG, Ctl4);
pragma Debug (Registers.Posting_Read (Registers.PWR_WELL_CTL5)); -- Result for debugging only
pragma Debug (Registers.Posting_Read (Registers.PWR_WELL_CTL6)); -- Result for debugging only
if ((Ctl1 or Ctl2 or Ctl3 or Ctl4) and
PWR_WELL_CTL_ENABLE_REQUEST) /= 0
then
Registers.Wait_Set_Mask
(Registers.PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_STATE_ENABLED);
end if;
if (Ctl1 and PWR_WELL_CTL_ENABLE_REQUEST) /= 0 then
Registers.Write (Registers.PWR_WELL_CTL_BIOS, PWR_WELL_CTL_DISABLE_REQUEST);
end if;
if (Ctl2 and PWR_WELL_CTL_ENABLE_REQUEST) /= 0 then
Registers.Write (Registers.PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_DISABLE_REQUEST);
end if;
end PDW_Off;
procedure PDW_On
is
Ctl1, Ctl2, Ctl3, Ctl4 : Word32;
begin
pragma Debug (Debug.Put_Line (GNAT.Source_Info.Enclosing_Entity));
Registers.Read (Registers.PWR_WELL_CTL_BIOS, Ctl1);
Registers.Read (Registers.PWR_WELL_CTL_DRIVER, Ctl2);
Registers.Read (Registers.PWR_WELL_CTL_KVMR, Ctl3);
Registers.Read (Registers.PWR_WELL_CTL_DEBUG, Ctl4);
pragma Debug (Registers.Posting_Read (Registers.PWR_WELL_CTL5)); -- Result for debugging only
pragma Debug (Registers.Posting_Read (Registers.PWR_WELL_CTL6)); -- Result for debugging only
if ((Ctl1 or Ctl2 or Ctl3 or Ctl4) and
PWR_WELL_CTL_ENABLE_REQUEST) = 0
then
Registers.Wait_Unset_Mask
(Registers.PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_STATE_ENABLED);
end if;
if (Ctl2 and PWR_WELL_CTL_ENABLE_REQUEST) = 0 then
Registers.Write (Registers.PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_ENABLE_REQUEST);
Registers.Wait_Set_Mask
(Registers.PWR_WELL_CTL_DRIVER, PWR_WELL_CTL_STATE_ENABLED);
end if;
end PDW_On;
function Need_PDW (Checked_Configs : Pipe_Configs) return Boolean
is
Primary : Pipe_Config renames Checked_Configs (GMA.Primary);
begin
return
(Config.Use_PDW_For_EDP_Scaling and then
(Primary.Port = Internal and Requires_Scaling (Primary)))
or
(Primary.Port /= Disabled and Primary.Port /= Internal)
or
Checked_Configs (Secondary).Port /= Disabled
or
Checked_Configs (Tertiary).Port /= Disabled;
end Need_PDW;
----------------------------------------------------------------------------
procedure Pre_All_Off is
begin
-- HSW: disable panel self refresh (PSR) on eDP if enabled
-- wait for PSR idling
PSR_Off;
IPS_Off;
end Pre_All_Off;
procedure Initialize is
begin
-- HSW: disable power down well
PDW_Off;
Config.Raw_Clock := Config.Default_RawClk_Freq;
end Initialize;
procedure Power_Set_To (Configs : Pipe_Configs) is
begin
if Need_PDW (Configs) then
PDW_On;
else
PDW_Off;
end if;
end Power_Set_To;
procedure Power_Up (Old_Configs, New_Configs : Pipe_Configs) is
begin
if not Need_PDW (Old_Configs) and Need_PDW (New_Configs) then
PDW_On;
end if;
end Power_Up;
procedure Power_Down (Old_Configs, Tmp_Configs, New_Configs : Pipe_Configs)
is
begin
if (Need_PDW (Old_Configs) or Need_PDW (Tmp_Configs)) and
not Need_PDW (New_Configs)
then
PDW_Off;
end if;
end Power_Down;
end HW.GFX.GMA.Power_And_Clocks_Haswell;
|
with Ada.Real_Time; use type Ada.Real_Time.Time; use Ada;
with AdaCar.Parametros;
package body AdaCar.Alarmas is
type Lista_Alarmas is array(Tipo_Alarmas) of Estado_Alarma;
protected Alarmas_PO
with Priority => Parametros.Techo_Alarmas_PO
is
procedure Notificar_Alarma(Alarma: Tipo_Alarmas);
function Leer_Listado_Alarmas return Lista_Alarmas;
private
Listado_Alarmas: Lista_Alarmas:= (Tipo_Alarmas'Range=>
Estado_Alarma'(Desactivada));
end Alarmas_PO;
----------------------
-- Notificar_Alarma --
----------------------
procedure Notificar_Alarma (Alarma : Tipo_Alarmas) is
begin
Alarmas_PO.Notificar_Alarma(Alarma);
end Notificar_Alarma;
task Alarmas_Task with Priority => Parametros.Prioridad_Alarmas_Task;
protected body Alarmas_PO is
procedure Notificar_Alarma(Alarma: Tipo_Alarmas) is
begin
Listado_Alarmas(Alarma):= Estado_Alarma'(Activada);
end Notificar_Alarma;
function Leer_Listado_Alarmas return Lista_Alarmas is
begin
return Listado_Alarmas;
end Leer_Listado_Alarmas;
end Alarmas_PO;
task body Alarmas_Task is
Tseg: constant Duration:= Parametros.Periodo_Alarmas_Task;
Periodo: constant Real_Time.Time_Span:= Real_Time.To_Time_Span(Tseg);
Next: Real_Time.Time:= Real_Time.Clock;
begin
null;
end Alarmas_Task;
end AdaCar.Alarmas;
|
-- DECLS-DGENERALS.ads
-- Paquet de declaracions generals
package Decls.Dgenerals is
Max_Id : constant Integer := 1000;
Long_Num_Ident : constant Integer := 40;
Max_Var : constant Integer := 1000;
type Num_Var is new Natural
range 0 .. Max_Var;
Var_Nul : Num_Var := 0;
Max_Proc : constant Integer := 100;
type Num_Proc is new Natural
range 0 .. Max_Proc;
Proc_Nul : Num_Proc := 0;
Max_Etiquetes : constant Integer := 4000;
type Num_Etiq is new Integer
range 0 .. Max_Etiquetes;
Etiq_Nul : Num_Etiq := 0;
type Tipus_Etiq is
(Etiq_Num,
Etiq_Proc);
type valor is new Integer
range Integer'First..Integer'Last;
type tipus_atribut is
(Atom,
A_Ident,
A_Lit_C,
A_Lit_N,
A_Lit_S,
NodeArbre);
Esem : Boolean := False;
end Decls.Dgenerals;
|
-- SPDX-FileCopyrightText: 2021 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with League.Strings;
with League.String_Vectors;
with WebIDL.Arguments;
with WebIDL.Constructors;
with WebIDL.Enumerations;
with WebIDL.Interfaces;
with WebIDL.Interface_Members;
with WebIDL.Types;
package WebIDL.Factories is
pragma Preelaborate;
type Factory is limited interface;
type Factory_Access is access all Factory'Class with Storage_Size => 0;
not overriding function Enumeration
(Self : in out Factory;
Name : League.Strings.Universal_String;
Values : League.String_Vectors.Universal_String_Vector)
return not null WebIDL.Enumerations.Enumeration_Access is abstract;
type Interface_Member_Vector is limited interface;
type Interface_Member_Vector_Access is access all
Interface_Member_Vector'Class
with Storage_Size => 0;
not overriding procedure Append
(Self : in out Interface_Member_Vector;
Item : not null WebIDL.Interface_Members.Interface_Member_Access)
is abstract;
not overriding function Interface_Members (Self : in out Factory)
return not null Interface_Member_Vector_Access is abstract;
type Argument_Vector is limited interface;
type Argument_Vector_Access is access all Argument_Vector'Class
with Storage_Size => 0;
not overriding procedure Append
(Self : in out Argument_Vector;
Item : not null WebIDL.Arguments.Argument_Access)
is abstract;
not overriding function Arguments (Self : in out Factory)
return not null Argument_Vector_Access is abstract;
not overriding function New_Interface
(Self : in out Factory;
Name : League.Strings.Universal_String;
Parent : League.Strings.Universal_String;
Members : not null Interface_Member_Vector_Access)
return not null WebIDL.Interfaces.Interface_Access is abstract;
not overriding function Constructor
(Self : in out Factory;
Args : not null Argument_Vector_Access)
return not null WebIDL.Constructors.Constructor_Access is abstract;
not overriding function Argument
(Self : in out Factory;
Type_Def : WebIDL.Types.Type_Access;
Name : League.Strings.Universal_String;
Is_Options : Boolean;
Has_Ellipsis : Boolean)
return not null WebIDL.Arguments.Argument_Access is abstract;
not overriding function Any (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Object (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Symbol (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Undefined (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Integer
(Self : in out Factory;
Is_Unsigned : Boolean;
Long : Natural)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Float
(Self : in out Factory;
Restricted : Boolean;
Double : Boolean)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Bool (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Byte (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Octet (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function BigInt (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function DOMString (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function ByteString (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function USVString (Self : in out Factory)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Sequence
(Self : in out Factory;
T : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
-- The sequence<T> type is a parameterized type whose values are (possibly
-- zero-length) lists of values of type T.
not overriding function Frozen_Array
(Self : in out Factory;
T : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
-- A frozen array type is a parameterized type whose values are references
-- to objects that hold a fixed length array of unmodifiable values. The
-- values in the array are of type T.
not overriding function Observable_Array
(Self : in out Factory;
T : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
-- An observable array type is a parameterized type whose values are
-- references to a combination of a mutable list of objects of type T, as
-- well as behavior to perform when author code modifies the contents of
-- the list.
not overriding function Record_Type
(Self : in out Factory;
Key : not null WebIDL.Types.Type_Access;
Value : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
-- A record type is a parameterized type whose values are ordered maps with
-- keys that are instances of K and values that are instances of V. K must
-- be one of DOMString, USVString, or ByteString.
not overriding function Nullable
(Self : in out Factory;
T : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
not overriding function Promise
(Self : in out Factory;
T : not null WebIDL.Types.Type_Access)
return not null WebIDL.Types.Type_Access is abstract;
-- A promise type is a parameterized type whose values are references
-- to objects that “is used as a place holder for the eventual results
-- of a deferred (and possibly asynchronous) computation result of an
-- asynchronous operation”.
not overriding function Buffer_Related_Type
(Self : in out Factory;
Name : League.Strings.Universal_String)
return not null WebIDL.Types.Type_Access is abstract;
type Union_Member_Vector is limited interface;
type Union_Member_Vector_Access is access all
Union_Member_Vector'Class
with Storage_Size => 0;
not overriding procedure Append
(Self : in out Union_Member_Vector;
Item : not null WebIDL.Types.Type_Access)
is abstract;
not overriding function Union_Members (Self : in out Factory)
return not null Union_Member_Vector_Access is abstract;
not overriding function Union
(Self : in out Factory;
T : not null Union_Member_Vector_Access)
return not null WebIDL.Types.Type_Access is abstract;
end WebIDL.Factories;
|
-- Copyright (c) 2016 onox <denkpadje@gmail.com>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with JSON.Types;
with JSON.Streams;
generic
with package Types is new JSON.Types (<>);
Check_Duplicate_Keys : Boolean := False;
-- If enabled, raise a Constraint_Error when an object contains
-- duplicate keys. Parsing a JSON text will be slower if enabled.
package JSON.Parsers with SPARK_Mode => On is
pragma Preelaborate;
function Parse
(Stream : aliased in out Streams.Stream'Class;
Allocator : aliased in out Types.Memory_Allocator) return Types.JSON_Value;
Parse_Error : exception;
end JSON.Parsers;
|
package body TLSF.Proof.Util.Vectors with SPARK_Mode is
----------
-- Find --
----------
function Find
(Container : V.Sequence; E : Element_Type) return Extended_Index_Type
is
begin
if V.Last(Container) >= Index_Type'First then
for Idx in Index_Type'First..Index_Type(V.Last(Container)) loop
if (V.Get(Container, Idx) = E) then
return Idx;
end if;
pragma Loop_Invariant
(not V.Contains(Container, Index_Type'First, Idx, E));
end loop;
end if;
return Extended_Index_Type'First;
end Find;
-----------------
-- Find_Second --
-----------------
function Find_Second
(Container : V.Sequence; E : Element_Type) return Extended_Index_Type
is
use Ada.Containers;
Len : Count_Type renames V.Length(Container);
First_Idx : constant Extended_Index_Type := Find (Container, E);
begin
if Len > 1 and First_Idx in Index_Type'First .. Extended_Index_Type'Pred(V.Last(Container)) then
for Idx in Extended_Index_Type'Succ(First_Idx)..V.Last(Container) loop
if V.Get(Container, Idx) = E then
pragma Assert (Find(Container, E) < Idx and
Idx > Index_Type'First);
return Idx;
end if;
pragma Loop_Invariant (Find(Container, E) < Idx);
end loop;
end if;
return Extended_Index_Type'First;
end Find_Second;
end TLSF.Proof.Util.Vectors;
|
-- ___ _ ___ _ _ --
-- / __| |/ (_) | | Common SKilL implementation --
-- \__ \ ' <| | | |__ file parser implementation --
-- |___/_|\_\_|_|____| by: Timm Felden --
-- --
pragma Ada_2012;
with Ada.Characters.Latin_1;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Ada.Text_IO;
with Ada.Unchecked_Conversion;
with Interfaces;
with Skill.Containers.Vectors;
with Skill.Files;
with Skill.Types;
with Skill.Streams.Reader;
with Skill.Errors;
with Skill.String_Pools;
with Skill.Types.Pools;
with Skill.Internal.Parts;
with Skill.Hashes;
with Skill.Equals;
with Skill.Field_Declarations;
with Skill.Field_Restrictions;
with Skill.Field_Types;
with Skill.Field_Types.Builtin;
-- documentation can be found in java common
package body Skill.Internal.File_Parsers is
use type Interfaces.Integer_32;
use type Interfaces.Integer_64;
use type Types.Annotation;
use Skill;
use type Types.String_Access;
use type Types.Pools.Pool;
function Read
(Input : Skill.Streams.Reader.Input_Stream;
Mode : Skill.Files.Write_Mode) return Result
is
-- begin error reporting
Block_Counter : Positive := 1;
package A3 is new Ada.Containers.Hashed_Sets
(Types.String_Access, Hashes.Hash, Equals.Equals);
Seen_Types : A3.Set;
-- end error reporting
-- preliminary file
Strings : String_Pools.Pool := String_Pools.Create (Input);
String_Type : Field_Types.Builtin.String_Type_P.Field_Type :=
Field_Types.Builtin.String_Type_P.Make(Strings);
Type_Vector : Types.Pools.Type_Vector :=
Types.Pools.P_Type_Vector.Empty_Vector;
Types_By_Name : Skill.Types.Pools.Type_Map :=
Skill.Types.Pools.P_Type_Map.Empty_Map;
Annotation_Type : Field_Types.Builtin.Annotation_Type_P.Field_Type :=
Field_Types.Builtin.Annotation(Type_Vector);
-- parser state --
-- deferred pool resize requests
Resize_Queue : Types.Pools.Type_Vector :=
Types.Pools.P_Type_Vector.Empty_Vector;
-- entries of local fields
type LF_Entry is record
Pool : Types.Pools.Pool_Dyn;
Count : Types.V64;
end record;
package A2 is new Containers.Vectors(Natural, LF_Entry);
-- pool -> local field count
Local_Fields : A2.Vector := A2.Empty_Vector;
-- field data updates: pool x fieldID
type FD_Entry is record
Pool : Types.Pools.Pool_Dyn;
ID : Positive;
end record;
package A4 is new Containers.Vectors (Natural, FD_Entry);
-- field data updates: pool x fieldID
Field_Data_Queue : A4.Vector := A4.Empty_Vector;
-- read an entire string block
procedure String_Block is
Count : Types.v64 := Input.V64;
begin
if 0 = Count then
return;
end if;
-- read offsets
declare
Last : Types.i32 := 0;
Off : Types.i32;
type Offset_Array is
array (Types.v64 range 0 .. Count - 1) of Types.i32;
Offsets : Offset_Array;
begin
for I in Offset_Array'Range loop
Off := Input.I32;
Offsets (I) := Off;
Input.Check_Offset(Types.V64(Off));
end loop;
for I in Offset_Array'Range loop
Off := Offsets (I);
Strings.AddPosition
(Input.Position + Types.v64 (Last), Off - Last);
Last := Off;
end loop;
Input.Jump (Input.Position + Types.v64 (Last));
end;
exception
when E : others =>
raise Skill.Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, E, "corrupted string block");
end String_Block;
-- read an entire type block
procedure Type_Block is
Offset : Types.v64 := 0;
Type_Count : Types.v64 := Input.V64;
-- reads a single type declaration
procedure Type_Definition is
Name : constant Types.String_Access := Strings.Get (Input.V64);
procedure Type_Restriction is
Count : Types.v64 := Input.V64;
Id : Types.V64;
begin
for I in 1 .. Count loop
Id := Input.V64;
case Id is
when 0 =>
-- unique
null;
when 1 =>
-- singleton
null;
when 2 =>
-- monotone
null;
when others =>
if Id <= 5 or else 1 = (id mod 2) then
raise Skill.Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter,
"Found unknown type restriction " &
Integer'Image (Integer (Id)) &
". Please regenerate your binding, if possible.");
end if;
Ada.Text_IO.Put_Line
("Skiped unknown skippable type restriction." &
" Please update the SKilL implementation.");
end case;
end loop;
-- TODO result creation!!
end Type_Restriction;
begin
if null = Name then
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, "corrupted file: nullptr in typename");
end if;
-- type duplication error detection
if Seen_Types.Contains (Name) then
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, "Duplicate definition of type "& Name.all);
end if;
Seen_Types.Include (Name);
-- try to parse the type definition
declare
Block : Skill.Internal.Parts.Block;
Definition : Types.Pools.Pool;
Super_Pool : Types.Pools.Pool;
Super_Id : Integer;
begin
Block.Dynamic_Count := Types.Skill_ID_T(Input.V64);
Block.Static_Count := Block.Dynamic_Count;
if Types_By_Name.Contains (Name) then
Definition := Types_By_Name.Element (Name);
Super_Pool := Definition.Super;
else
-- type restrictions
-- TODO use the result!
Type_Restriction;
-- super
Super_Id := Integer (Input.V64);
if 0 = Super_Id then
Super_Pool := null;
else
if Super_Id > Natural(Type_Vector.Length) then
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, "Type " &
Name.all &
" refers to an ill-formed super type." &
Ada.Characters.Latin_1.LF &
" found: " &
Integer'Image (Super_Id) &
"; current number of other types " &
Integer'Image (Natural(Type_Vector.Length)));
else
Super_Pool := Type_Vector.Element (Super_Id - 1);
pragma Assert (null /= Super_Pool);
end if;
end if;
-- allocate pool
-- TODO add restrictions as parameter
-- definition = newPool(name, superDef, rest);
Definition := New_Pool
(Natural(Type_Vector.Length) + 32, Name, Super_Pool);
Type_Vector.Append (Definition);
Types_By_Name.Include (Name, Definition);
end if;
-- bpo
if 0 /= Block.Dynamic_Count and then null /= Definition.Super then
Block.Bpo := Definition.Base.Data'Length + Types.Skill_ID_T(Input.V64);
elsif null /= Definition.Super and then Seen_Types.Contains (Definition.Super.Skill_Name) then
Block.Bpo := Definition.Super.Blocks.Last_Element.Bpo;
else
Block.Bpo := Definition.Base.Data'Length;
end if;
pragma Assert(Definition /= null);
-- store block info and prepare resize
Definition.Blocks.Append (Block);
Resize_Queue.Append (Definition); -- <-TODO hier nur base pools einfügen!
Local_Fields.Append (LF_Entry'(Definition.Dynamic, Input.V64));
-- fix parent static count
if 0 /= Block.Dynamic_Count and then null /= Super_Pool then
-- calculate static count of our parent
declare
Sb : Internal.Parts.Block := Super_Pool.Blocks.Last_Element;
-- assumed static instances, minus what static instances would be, if p were the first sub pool.
Diff : constant Types.Skill_ID_T := sb.Static_Count -
(Block.bpo - sb.bpo);
begin
-- if positive, then we have to subtract it from the assumed static count (local and global)
if Diff > 0 then
Sb.Static_Count := Sb.Static_Count - Diff;
Super_Pool.Blocks.Replace_Element
(Super_Pool.Blocks.Length-1, Sb);
end if;
end;
end if;
end;
exception
when E : Constraint_Error =>
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, E, "unexpected corruption of parse state");
when E : Storage_Error =>
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, E, "unexpected end of file");
end Type_Definition;
function Parse_Field_Type return Skill.Field_Types.Field_Type is
ID : Natural := Natural (Input.V64);
function Convert is new Ada.Unchecked_Conversion
(Source => Types.Pools.Pool,
Target => Field_Types.Field_Type);
begin
case Id is
when 0 =>
return new Field_Types.Builtin.Constant_I8.Field_Type'
(Value => Input.I8);
when 1 =>
return new Field_Types.Builtin.Constant_I16.Field_Type'
(Value => Input.I16);
when 2 =>
return new Field_Types.Builtin.Constant_I32.Field_Type'
(Value => Input.I32);
when 3 =>
return new Field_Types.Builtin.Constant_I64.Field_Type'
(Value => Input.I64);
when 4 =>
return new Field_Types.Builtin.Constant_V64.Field_Type'
(Value => Input.V64);
when 5 =>
return Field_Types.Field_Type(Annotation_Type);
when 6 =>
return Field_Types.Builtin.Bool;
when 7 =>
return Field_Types.Builtin.I8;
when 8 =>
return Field_Types.Builtin.I16;
when 9 =>
return Field_Types.Builtin.I32;
when 10 =>
return Field_Types.Builtin.I64;
when 11 =>
return Field_Types.Builtin.V64;
when 12 =>
return Field_Types.Builtin.F32;
when 13 =>
return Field_Types.Builtin.F64;
when 14 =>
return Field_Types.Field_Type(String_Type);
when 15 =>
declare
Length : Types.V64 := Input.V64;
T : Field_Types.Field_Type := Parse_Field_Type;
begin
return Field_Types.Builtin.Const_Array(Length, T);
end;
when 17 =>
return Field_Types.Builtin.Var_Array (Parse_Field_Type);
when 18 =>
return Skill.Field_Types.Builtin.List_Type(Parse_Field_Type);
when 19 =>
return Skill.Field_Types.Builtin.Set_Type (Parse_Field_Type);
when 20 =>
declare
K : Field_Types.Field_Type := Parse_Field_Type;
V : Field_Types.Field_Type := Parse_Field_Type;
begin
return Skill.Field_Types.Builtin.Map_Type (K, V);
end;
when others =>
if ID >= 32 and Id < Natural(Type_Vector.Length) + 32 then
return Convert (Type_Vector.Element (ID - 32));
end if;
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter,
"Invalid type ID: " & Natural'Image (ID) & " largest is: "
& Natural'Image (Natural(Type_Vector.Length) + 32));
end case;
end Parse_Field_Type;
procedure Parse_Fields (E : LF_Entry) is
Legal_Field_ID_Barrier : Positive :=
1 + Natural(E.Pool.Data_Fields.Length);
Last_Block : Skill.Internal.Parts.Block :=
E.Pool.Blocks.Last_Element;
End_Offset : Types.V64;
begin
for Field_Counter in 1 .. E.Count loop
declare
Id : Integer := Integer (Input.V64);
begin
if Id <= 0 or else Legal_Field_ID_Barrier < ID then
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter,
"Found an illegal field ID: " & Integer'Image (ID));
end if;
if Id = Legal_Field_ID_Barrier then
Legal_Field_ID_Barrier := Legal_Field_ID_Barrier + 1;
-- new field
declare
Field_Name : Types.String_Access := Strings.Get
(Input.V64);
T : Field_Types.Field_Type;
Restrictions : Field_Restrictions.Vector;
function Field_Restriction return Field_Restrictions.Vector
Is
Count : Types.v64 := Input.V64;
Id : Types.V64;
Rval : Field_Restrictions.Vector :=
Field_Restrictions.Vector_P.Empty_Vector;
B : Types.Box;
L : Types.V64;
begin
for I in 1 .. Count loop
Id := Input.V64;
case Id is
when 0 =>
-- nonnull
Rval.Append (Field_Restrictions.Nonnull);
when 1 =>
-- default
if 5 = T.ID or else T.Id >= 32 then
-- via type ID
L := Input.V64;
else
-- via value
B := T.Read_Box (Input.To);
end if;
null;
when 3 =>
-- range
B := T.Read_Box (Input.To);
B := T.Read_Box (Input.To);
when 5 =>
-- coding
Rval.Append (new Field_Restrictions.Coding_T'(
Name => Strings.Get(Input.V64)));
when 7 =>
Rval.Append
(Field_Restrictions.Constant_Length_Pointer);
when 9 =>
-- one of
for I in 1 .. Input.V64 loop
-- type IDs
L := Input.V64;
end loop;
when others =>
if Id <= 9 or else 1 = (Id mod 2) then
raise Skill.Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter,
"Found unknown field restriction " &
Integer'Image (Integer (Id)) &
". Please regenerate your binding, if possible.");
end if;
Ada.Text_IO.Put_Line
("Skiped unknown skippable field restriction." &
" Please update the SKilL implementation.");
end case;
end loop;
return Rval;
end Field_Restriction;
begin
if null = Field_Name then
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter,
"corrupted file: nullptr in fieldname");
end if;
T := Parse_Field_Type;
Restrictions := Field_Restriction;
End_Offset := Input.V64;
declare
-- TODO restrictions
F : Field_Declarations.Field_Declaration :=
E.Pool.Add_Field (ID, T, Field_Name, Restrictions);
begin
F.Add_Chunk
(new Internal.Parts.Bulk_Chunk'
(Offset,
End_Offset,
E.Pool.Size,
E.Pool.Blocks.Length)
);
exception
when E : Errors.Skill_Error =>
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, E,
"failed to add field");
end;
end;
else
-- field already seen
End_Offset := Input.V64;
E.Pool.Data_Fields.Element (ID).Add_Chunk
(new Internal.Parts.Simple_Chunk'
(Offset,
End_Offset,
Last_Block.Dynamic_Count,
Last_Block.Bpo));
end if;
Offset := End_Offset;
Field_Data_Queue.Append (FD_Entry'(E.Pool, ID));
end;
end loop;
end;
begin
-- reset counters and queues
-- seenTypes.clear();
Seen_Types := A3.Empty_Set;
Resize_Queue.Clear;
Local_Fields.Clear;
Field_Data_Queue.Clear;
-- parse types
for I in 1 .. Type_Count loop
Type_Definition;
end loop;
-- resize pools
declare
Index : Natural := Natural'First;
procedure Resize (E : Skill.Types.Pools.Pool) is
begin
E.Dynamic.Resize_Pool;
end;
begin
Resize_Queue.Foreach (Resize'Access);
end;
-- parse fields
Local_Fields.Foreach(Parse_Fields'Access);
-- update field data information, so that it can be read in parallel or
-- even lazy
-- Process Field Data
declare
-- We Have To Add The File Offset To all Begins and Ends We Encounter
File_Offset : constant Types.V64 := Input.Position;
Data_End : Types.V64 := File_Offset;
begin
-- process field data declarations in order of appearance and update
-- offsets to absolute positions
while not Field_Data_Queue.Is_Empty loop
declare
use type Skill.Field_Declarations.Field_Declaration;
E : FD_Entry := Field_Data_Queue.Pop;
F : Skill.Field_Declarations.Field_Declaration :=
E.Pool.Data_Fields.Element (E.ID);
pragma Assert (F /= null);
-- make begin/end absolute
End_Offset : Types.V64 :=
F.Add_Offset_To_Last_Chunk (Input, File_Offset);
begin
if Data_End < End_Offset then
Data_End := End_Offset;
end if;
end;
end loop;
Input.Jump (Data_End);
end;
end Type_Block;
procedure Free_State is
begin
Local_Fields.Free;
Field_Data_Queue.Free;
Resize_Queue.Free;
end;
begin
while not Input.Eof loop
String_Block;
Type_Block;
Block_Counter := Block_Counter + 1;
end loop;
Free_State;
return Make_State
(Input.Path,
Mode,
Strings,
String_Type,
Annotation_Type,
Type_Vector,
Types_By_Name);
exception
when E : Storage_Error =>
raise Errors.Skill_Error
with Input.Parse_Exception
(Block_Counter, E, "unexpected end of file");
end Read;
end Skill.Internal.File_Parsers;
|
with STM32.GPIO;
use STM32.GPIO;
with HAL.GPIO;
package Analog is
type Analog_Signal_Value is new Integer;
procedure Configure_Pin (Pin : GPIO_Point);
-- Configure a given pin as a analog and establishes his properties
procedure Start_Adquisition (Pin : GPIO_Point);
-- Start the adquisition of the analag pin value
function Get_Value (Pin: GPIO_Point) return Analog_Signal_Value;
-- Obtain the value of the analog pin. A minimum time of 10 microseconds
-- must be given between the procedure Start_Adquisition and this function.
end Analog;
|
-- { dg-do run }
with Ada.Tags;
procedure tag1 is
type T is tagged null record;
X : Ada.Tags.Tag;
begin
begin
X := Ada.Tags.Descendant_Tag ("Internal tag at 16#0#", T'Tag);
raise Program_Error;
exception
when Ada.Tags.Tag_Error => null;
end;
begin
X := Ada.Tags.Descendant_Tag ("Internal tag at 16#XXXX#", T'Tag);
raise Program_Error;
exception
when Ada.Tags.Tag_Error => null;
end;
end;
|
-- Generated by gperfhash
with Util.Strings.Transforms;
with Interfaces; use Interfaces;
package body Sqlite3_H.Perfect_Hash is
C : constant array (Character) of Unsigned_8 :=
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 0, 0, 0, 0, 0,
0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
P : constant array (0 .. 6) of Natural :=
(1, 2, 3, 4, 7, 9, 13);
T1 : constant array (0 .. 6, Unsigned_8 range 0 .. 24) of Unsigned_8 :=
((143, 96, 170, 168, 5, 221, 118, 70, 107, 192, 176, 130, 205, 180, 29,
75, 72, 130, 134, 58, 11, 112, 107, 171, 238),
(180, 2, 196, 77, 209, 61, 149, 97, 43, 57, 69, 126, 232, 154, 25, 211,
62, 215, 181, 201, 228, 167, 28, 102, 215),
(133, 106, 209, 117, 51, 209, 60, 189, 39, 41, 33, 19, 192, 151, 94,
120, 190, 187, 151, 241, 38, 145, 217, 75, 212),
(147, 18, 41, 107, 118, 30, 200, 90, 101, 192, 44, 168, 94, 60, 134,
10, 50, 154, 4, 213, 75, 107, 141, 216, 51),
(41, 104, 175, 241, 124, 61, 0, 11, 87, 21, 236, 106, 178, 89, 202,
193, 188, 51, 144, 208, 221, 139, 171, 90, 222),
(52, 176, 202, 98, 235, 165, 118, 228, 58, 161, 116, 43, 211, 102, 236,
7, 198, 105, 78, 186, 118, 191, 16, 48, 128),
(133, 172, 79, 95, 45, 169, 47, 156, 128, 214, 180, 197, 86, 107, 99,
99, 39, 28, 235, 81, 124, 139, 132, 225, 23));
T2 : constant array (0 .. 6, Unsigned_8 range 0 .. 24) of Unsigned_8 :=
((94, 74, 218, 128, 191, 64, 53, 80, 54, 36, 176, 13, 192, 31, 45, 43,
139, 74, 169, 234, 141, 5, 208, 79, 239),
(35, 233, 99, 220, 99, 211, 131, 143, 149, 138, 37, 42, 35, 57, 202,
217, 88, 108, 105, 114, 42, 103, 27, 56, 67),
(102, 8, 146, 198, 7, 113, 80, 188, 109, 57, 239, 32, 76, 186, 96, 142,
157, 156, 48, 211, 145, 223, 106, 24, 131),
(216, 125, 109, 240, 114, 175, 39, 237, 107, 142, 180, 185, 208, 65,
55, 65, 42, 73, 137, 94, 38, 12, 174, 228, 122),
(151, 225, 8, 68, 9, 166, 38, 56, 223, 64, 116, 197, 63, 224, 30, 6,
175, 188, 140, 240, 98, 105, 210, 183, 235),
(57, 193, 135, 211, 112, 69, 91, 204, 78, 191, 151, 115, 179, 221, 162,
204, 110, 205, 176, 96, 78, 227, 122, 91, 186),
(27, 62, 122, 225, 148, 217, 212, 155, 163, 21, 117, 47, 179, 197, 108,
150, 229, 148, 35, 115, 179, 191, 58, 3, 49));
G : constant array (0 .. 242) of Unsigned_8 :=
(0, 70, 0, 85, 0, 0, 0, 45, 60, 5, 0, 112, 0, 0, 0, 18, 0, 0, 46, 43, 0,
114, 51, 45, 0, 0, 0, 0, 6, 72, 5, 81, 0, 106, 0, 0, 32, 0, 0, 0, 0, 0,
35, 113, 58, 0, 21, 60, 0, 23, 0, 0, 53, 75, 47, 44, 25, 0, 0, 13, 81,
0, 0, 0, 0, 63, 0, 0, 0, 7, 0, 0, 60, 12, 0, 0, 71, 0, 0, 0, 51, 0,
106, 20, 0, 0, 0, 0, 0, 14, 80, 0, 0, 0, 2, 0, 0, 25, 97, 0, 0, 0, 70,
0, 117, 0, 0, 0, 0, 19, 16, 12, 74, 40, 94, 0, 0, 10, 0, 111, 0, 85,
47, 0, 11, 0, 45, 0, 0, 0, 28, 16, 0, 0, 66, 0, 0, 64, 0, 100, 62, 15,
0, 100, 3, 0, 0, 0, 0, 46, 0, 81, 0, 13, 89, 0, 0, 40, 0, 67, 20, 28,
36, 58, 0, 0, 0, 0, 4, 57, 0, 7, 17, 0, 0, 118, 78, 114, 0, 0, 59, 74,
0, 12, 44, 0, 0, 0, 120, 0, 48, 50, 110, 88, 0, 1, 32, 0, 0, 8, 0, 21,
54, 56, 0, 26, 62, 0, 0, 0, 0, 15, 31, 90, 0, 0, 0, 21, 5, 104, 33, 0,
78, 3, 35, 0, 0, 0, 18, 0, 0, 105, 0, 50, 19, 0, 6, 95, 17, 0, 14, 39,
0);
function Hash (S : String) return Natural is
F : constant Natural := S'First - 1;
L : constant Natural := S'Length;
F1, F2 : Natural := 0;
J : Unsigned_8;
begin
for K in P'Range loop
exit when L < P (K);
J := C (S (P (K) + F));
F1 := (F1 + Natural (T1 (K, J))) mod 243;
F2 := (F2 + Natural (T2 (K, J))) mod 243;
end loop;
return (Natural (G (F1)) + Natural (G (F2))) mod 121;
end Hash;
-- Returns true if the string <b>S</b> is a keyword.
function Is_Keyword (S : in String) return Boolean is
H : constant Natural := Hash (S);
begin
return Keywords (H).all = Util.Strings.Transforms.To_Upper_Case (S);
end Is_Keyword;
end Sqlite3_H.Perfect_Hash;
|
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.SUPC is
pragma Preelaborate;
---------------
-- Registers --
---------------
-- Interrupt Enable Clear
type SUPC_INTENCLR_Register is record
-- BOD33 Ready
BOD33RDY : Boolean := False;
-- BOD33 Detection
BOD33DET : Boolean := False;
-- BOD33 Synchronization Ready
B33SRDY : Boolean := False;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
-- Voltage Regulator Ready
VREGRDY : Boolean := False;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- VDDCORE Ready
VCORERDY : Boolean := False;
-- unspecified
Reserved_11_31 : HAL.UInt21 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_INTENCLR_Register use record
BOD33RDY at 0 range 0 .. 0;
BOD33DET at 0 range 1 .. 1;
B33SRDY at 0 range 2 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
VREGRDY at 0 range 8 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
VCORERDY at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- Interrupt Enable Set
type SUPC_INTENSET_Register is record
-- BOD33 Ready
BOD33RDY : Boolean := False;
-- BOD33 Detection
BOD33DET : Boolean := False;
-- BOD33 Synchronization Ready
B33SRDY : Boolean := False;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
-- Voltage Regulator Ready
VREGRDY : Boolean := False;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- VDDCORE Ready
VCORERDY : Boolean := False;
-- unspecified
Reserved_11_31 : HAL.UInt21 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_INTENSET_Register use record
BOD33RDY at 0 range 0 .. 0;
BOD33DET at 0 range 1 .. 1;
B33SRDY at 0 range 2 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
VREGRDY at 0 range 8 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
VCORERDY at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- Interrupt Flag Status and Clear
type SUPC_INTFLAG_Register is record
-- BOD33 Ready
BOD33RDY : Boolean := False;
-- BOD33 Detection
BOD33DET : Boolean := False;
-- BOD33 Synchronization Ready
B33SRDY : Boolean := False;
-- unspecified
Reserved_3_7 : HAL.UInt5 := 16#0#;
-- Voltage Regulator Ready
VREGRDY : Boolean := False;
-- unspecified
Reserved_9_9 : HAL.Bit := 16#0#;
-- VDDCORE Ready
VCORERDY : Boolean := False;
-- unspecified
Reserved_11_31 : HAL.UInt21 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_INTFLAG_Register use record
BOD33RDY at 0 range 0 .. 0;
BOD33DET at 0 range 1 .. 1;
B33SRDY at 0 range 2 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
VREGRDY at 0 range 8 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
VCORERDY at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- Power and Clocks Status
type SUPC_STATUS_Register is record
-- Read-only. BOD33 Ready
BOD33RDY : Boolean;
-- Read-only. BOD33 Detection
BOD33DET : Boolean;
-- Read-only. BOD33 Synchronization Ready
B33SRDY : Boolean;
-- unspecified
Reserved_3_7 : HAL.UInt5;
-- Read-only. Voltage Regulator Ready
VREGRDY : Boolean;
-- unspecified
Reserved_9_9 : HAL.Bit;
-- Read-only. VDDCORE Ready
VCORERDY : Boolean;
-- unspecified
Reserved_11_31 : HAL.UInt21;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_STATUS_Register use record
BOD33RDY at 0 range 0 .. 0;
BOD33DET at 0 range 1 .. 1;
B33SRDY at 0 range 2 .. 2;
Reserved_3_7 at 0 range 3 .. 7;
VREGRDY at 0 range 8 .. 8;
Reserved_9_9 at 0 range 9 .. 9;
VCORERDY at 0 range 10 .. 10;
Reserved_11_31 at 0 range 11 .. 31;
end record;
-- Action when Threshold Crossed
type BOD33_ACTIONSelect is
(-- No action
NONE,
-- The BOD33 generates a reset
RESET,
-- The BOD33 generates an interrupt
INT,
-- The BOD33 puts the device in backup sleep mode
BKUP)
with Size => 2;
for BOD33_ACTIONSelect use
(NONE => 0,
RESET => 1,
INT => 2,
BKUP => 3);
subtype SUPC_BOD33_HYST_Field is HAL.UInt4;
-- Prescaler Select
type BOD33_PSELSelect is
(-- Not divided
NODIV,
-- Divide clock by 4
DIV4,
-- Divide clock by 8
DIV8,
-- Divide clock by 16
DIV16,
-- Divide clock by 32
DIV32,
-- Divide clock by 64
DIV64,
-- Divide clock by 128
DIV128,
-- Divide clock by 256
DIV256)
with Size => 3;
for BOD33_PSELSelect use
(NODIV => 0,
DIV4 => 1,
DIV8 => 2,
DIV16 => 3,
DIV32 => 4,
DIV64 => 5,
DIV128 => 6,
DIV256 => 7);
subtype SUPC_BOD33_LEVEL_Field is HAL.UInt8;
subtype SUPC_BOD33_VBATLEVEL_Field is HAL.UInt8;
-- BOD33 Control
type SUPC_BOD33_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
-- Enable
ENABLE : Boolean := False;
-- Action when Threshold Crossed
ACTION : BOD33_ACTIONSelect := SAM_SVD.SUPC.NONE;
-- Configuration in Standby mode
STDBYCFG : Boolean := False;
-- Run in Standby mode
RUNSTDBY : Boolean := False;
-- Run in Hibernate mode
RUNHIB : Boolean := False;
-- Run in Backup mode
RUNBKUP : Boolean := False;
-- Hysteresis value
HYST : SUPC_BOD33_HYST_Field := 16#0#;
-- Prescaler Select
PSEL : BOD33_PSELSelect := SAM_SVD.SUPC.NODIV;
-- unspecified
Reserved_15_15 : HAL.Bit := 16#0#;
-- Threshold Level for VDD
LEVEL : SUPC_BOD33_LEVEL_Field := 16#0#;
-- Threshold Level in battery backup sleep mode for VBAT
VBATLEVEL : SUPC_BOD33_VBATLEVEL_Field := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_BOD33_Register use record
Reserved_0_0 at 0 range 0 .. 0;
ENABLE at 0 range 1 .. 1;
ACTION at 0 range 2 .. 3;
STDBYCFG at 0 range 4 .. 4;
RUNSTDBY at 0 range 5 .. 5;
RUNHIB at 0 range 6 .. 6;
RUNBKUP at 0 range 7 .. 7;
HYST at 0 range 8 .. 11;
PSEL at 0 range 12 .. 14;
Reserved_15_15 at 0 range 15 .. 15;
LEVEL at 0 range 16 .. 23;
VBATLEVEL at 0 range 24 .. 31;
end record;
-- Voltage Regulator Selection
type VREG_SELSelect is
(-- LDO selection
LDO,
-- Buck selection
BUCK)
with Size => 1;
for VREG_SELSelect use
(LDO => 0,
BUCK => 1);
subtype SUPC_VREG_VSPER_Field is HAL.UInt3;
-- VREG Control
type SUPC_VREG_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
-- Enable
ENABLE : Boolean := True;
-- Voltage Regulator Selection
SEL : VREG_SELSelect := SAM_SVD.SUPC.LDO;
-- unspecified
Reserved_3_6 : HAL.UInt4 := 16#0#;
-- Run in Backup mode
RUNBKUP : Boolean := False;
-- unspecified
Reserved_8_15 : HAL.UInt8 := 16#0#;
-- Voltage Scaling Enable
VSEN : Boolean := False;
-- unspecified
Reserved_17_23 : HAL.UInt7 := 16#0#;
-- Voltage Scaling Period
VSPER : SUPC_VREG_VSPER_Field := 16#0#;
-- unspecified
Reserved_27_31 : HAL.UInt5 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_VREG_Register use record
Reserved_0_0 at 0 range 0 .. 0;
ENABLE at 0 range 1 .. 1;
SEL at 0 range 2 .. 2;
Reserved_3_6 at 0 range 3 .. 6;
RUNBKUP at 0 range 7 .. 7;
Reserved_8_15 at 0 range 8 .. 15;
VSEN at 0 range 16 .. 16;
Reserved_17_23 at 0 range 17 .. 23;
VSPER at 0 range 24 .. 26;
Reserved_27_31 at 0 range 27 .. 31;
end record;
-- Voltage Reference Selection
type VREF_SELSelect is
(-- 1.0V voltage reference typical value
Val_1V0,
-- 1.1V voltage reference typical value
Val_1V1,
-- 1.2V voltage reference typical value
Val_1V2,
-- 1.25V voltage reference typical value
Val_1V25,
-- 2.0V voltage reference typical value
Val_2V0,
-- 2.2V voltage reference typical value
Val_2V2,
-- 2.4V voltage reference typical value
Val_2V4,
-- 2.5V voltage reference typical value
Val_2V5)
with Size => 4;
for VREF_SELSelect use
(Val_1V0 => 0,
Val_1V1 => 1,
Val_1V2 => 2,
Val_1V25 => 3,
Val_2V0 => 4,
Val_2V2 => 5,
Val_2V4 => 6,
Val_2V5 => 7);
-- VREF Control
type SUPC_VREF_Register is record
-- unspecified
Reserved_0_0 : HAL.Bit := 16#0#;
-- Temperature Sensor Output Enable
TSEN : Boolean := False;
-- Voltage Reference Output Enable
VREFOE : Boolean := False;
-- Temperature Sensor Selection
TSSEL : Boolean := False;
-- unspecified
Reserved_4_5 : HAL.UInt2 := 16#0#;
-- Run during Standby
RUNSTDBY : Boolean := False;
-- On Demand Contrl
ONDEMAND : Boolean := False;
-- unspecified
Reserved_8_15 : HAL.UInt8 := 16#0#;
-- Voltage Reference Selection
SEL : VREF_SELSelect := SAM_SVD.SUPC.Val_1V0;
-- unspecified
Reserved_20_31 : HAL.UInt12 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_VREF_Register use record
Reserved_0_0 at 0 range 0 .. 0;
TSEN at 0 range 1 .. 1;
VREFOE at 0 range 2 .. 2;
TSSEL at 0 range 3 .. 3;
Reserved_4_5 at 0 range 4 .. 5;
RUNSTDBY at 0 range 6 .. 6;
ONDEMAND at 0 range 7 .. 7;
Reserved_8_15 at 0 range 8 .. 15;
SEL at 0 range 16 .. 19;
Reserved_20_31 at 0 range 20 .. 31;
end record;
-- Battery Backup Configuration
type BBPS_CONFSelect is
(-- The power switch is handled by the BOD33
BOD33,
-- In Backup Domain, the backup domain is always supplied by battery backup
-- power
FORCED)
with Size => 1;
for BBPS_CONFSelect use
(BOD33 => 0,
FORCED => 1);
-- Battery Backup Power Switch
type SUPC_BBPS_Register is record
-- Battery Backup Configuration
CONF : BBPS_CONFSelect := SAM_SVD.SUPC.BOD33;
-- unspecified
Reserved_1_1 : HAL.Bit := 16#0#;
-- Wake Enable
WAKEEN : Boolean := False;
-- unspecified
Reserved_3_31 : HAL.UInt29 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_BBPS_Register use record
CONF at 0 range 0 .. 0;
Reserved_1_1 at 0 range 1 .. 1;
WAKEEN at 0 range 2 .. 2;
Reserved_3_31 at 0 range 3 .. 31;
end record;
-- SUPC_BKOUT_ENOUT array
type SUPC_BKOUT_ENOUT_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SUPC_BKOUT_ENOUT
type SUPC_BKOUT_ENOUT_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- ENOUT as a value
Val : HAL.UInt2;
when True =>
-- ENOUT as an array
Arr : SUPC_BKOUT_ENOUT_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SUPC_BKOUT_ENOUT_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- SUPC_BKOUT_CLROUT array
type SUPC_BKOUT_CLROUT_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SUPC_BKOUT_CLROUT
type SUPC_BKOUT_CLROUT_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- CLROUT as a value
Val : HAL.UInt2;
when True =>
-- CLROUT as an array
Arr : SUPC_BKOUT_CLROUT_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SUPC_BKOUT_CLROUT_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- SUPC_BKOUT_SETOUT array
type SUPC_BKOUT_SETOUT_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SUPC_BKOUT_SETOUT
type SUPC_BKOUT_SETOUT_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- SETOUT as a value
Val : HAL.UInt2;
when True =>
-- SETOUT as an array
Arr : SUPC_BKOUT_SETOUT_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SUPC_BKOUT_SETOUT_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- SUPC_BKOUT_RTCTGLOUT array
type SUPC_BKOUT_RTCTGLOUT_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SUPC_BKOUT_RTCTGLOUT
type SUPC_BKOUT_RTCTGLOUT_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- RTCTGLOUT as a value
Val : HAL.UInt2;
when True =>
-- RTCTGLOUT as an array
Arr : SUPC_BKOUT_RTCTGLOUT_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SUPC_BKOUT_RTCTGLOUT_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- Backup Output Control
type SUPC_BKOUT_Register is record
-- Enable OUT0
ENOUT : SUPC_BKOUT_ENOUT_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_2_7 : HAL.UInt6 := 16#0#;
-- Clear OUT0
CLROUT : SUPC_BKOUT_CLROUT_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_10_15 : HAL.UInt6 := 16#0#;
-- Set OUT0
SETOUT : SUPC_BKOUT_SETOUT_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_18_23 : HAL.UInt6 := 16#0#;
-- RTC Toggle OUT0
RTCTGLOUT : SUPC_BKOUT_RTCTGLOUT_Field :=
(As_Array => False, Val => 16#0#);
-- unspecified
Reserved_26_31 : HAL.UInt6 := 16#0#;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_BKOUT_Register use record
ENOUT at 0 range 0 .. 1;
Reserved_2_7 at 0 range 2 .. 7;
CLROUT at 0 range 8 .. 9;
Reserved_10_15 at 0 range 10 .. 15;
SETOUT at 0 range 16 .. 17;
Reserved_18_23 at 0 range 18 .. 23;
RTCTGLOUT at 0 range 24 .. 25;
Reserved_26_31 at 0 range 26 .. 31;
end record;
-- SUPC_BKIN_BKIN array
type SUPC_BKIN_BKIN_Field_Array is array (0 .. 1) of Boolean
with Component_Size => 1, Size => 2;
-- Type definition for SUPC_BKIN_BKIN
type SUPC_BKIN_BKIN_Field
(As_Array : Boolean := False)
is record
case As_Array is
when False =>
-- BKIN as a value
Val : HAL.UInt2;
when True =>
-- BKIN as an array
Arr : SUPC_BKIN_BKIN_Field_Array;
end case;
end record
with Unchecked_Union, Size => 2;
for SUPC_BKIN_BKIN_Field use record
Val at 0 range 0 .. 1;
Arr at 0 range 0 .. 1;
end record;
-- Backup Input Control
type SUPC_BKIN_Register is record
-- Read-only. Backup Input 0
BKIN : SUPC_BKIN_BKIN_Field;
-- unspecified
Reserved_2_31 : HAL.UInt30;
end record
with Volatile_Full_Access, Object_Size => 32,
Bit_Order => System.Low_Order_First;
for SUPC_BKIN_Register use record
BKIN at 0 range 0 .. 1;
Reserved_2_31 at 0 range 2 .. 31;
end record;
-----------------
-- Peripherals --
-----------------
-- Supply Controller
type SUPC_Peripheral is record
-- Interrupt Enable Clear
INTENCLR : aliased SUPC_INTENCLR_Register;
-- Interrupt Enable Set
INTENSET : aliased SUPC_INTENSET_Register;
-- Interrupt Flag Status and Clear
INTFLAG : aliased SUPC_INTFLAG_Register;
-- Power and Clocks Status
STATUS : aliased SUPC_STATUS_Register;
-- BOD33 Control
BOD33 : aliased SUPC_BOD33_Register;
-- VREG Control
VREG : aliased SUPC_VREG_Register;
-- VREF Control
VREF : aliased SUPC_VREF_Register;
-- Battery Backup Power Switch
BBPS : aliased SUPC_BBPS_Register;
-- Backup Output Control
BKOUT : aliased SUPC_BKOUT_Register;
-- Backup Input Control
BKIN : aliased SUPC_BKIN_Register;
end record
with Volatile;
for SUPC_Peripheral use record
INTENCLR at 16#0# range 0 .. 31;
INTENSET at 16#4# range 0 .. 31;
INTFLAG at 16#8# range 0 .. 31;
STATUS at 16#C# range 0 .. 31;
BOD33 at 16#10# range 0 .. 31;
VREG at 16#18# range 0 .. 31;
VREF at 16#1C# range 0 .. 31;
BBPS at 16#20# range 0 .. 31;
BKOUT at 16#24# range 0 .. 31;
BKIN at 16#28# range 0 .. 31;
end record;
-- Supply Controller
SUPC_Periph : aliased SUPC_Peripheral
with Import, Address => SUPC_Base;
end SAM_SVD.SUPC;
|
-- { dg-do run }
-- { dg-options "-O2 -fno-unit-at-a-time" }
with Tail_Call_P; use Tail_Call_P;
procedure Tail_Call is
begin
Insert (My_Array, 0, 0);
end;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ D I S P --
-- --
-- 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 routines involved in tagged types and dynamic
-- dispatching expansion.
with Types; use Types;
package Exp_Disp is
-------------------------------------
-- Predefined primitive operations --
-------------------------------------
-- The predefined primitive operations (PPOs) are subprograms generated
-- by GNAT for a particular tagged type. Their role is to provide support
-- for different Ada language features such as the attribute 'Size or
-- handling of dispatching triggers in select statements. PPOs are created
-- when a tagged type is expanded or frozen. These subprograms are later
-- collected and inserted into the dispatch table of a tagged type at
-- fixed positions. Some of the PPOs that manipulate data in tagged objects
-- require the generation of thunks.
-- List of predefined primitive operations
-- Leading underscores designate reserved names. Bracketed numerical
-- values represent dispatch table slot numbers.
-- _Size (1) - implementation of the attribute 'Size for any tagged
-- type. Constructs of the form Prefix'Size are converted into
-- Prefix._Size.
-- _Alignment (2) - implementation of the attribute 'Alignment for
-- any tagged type. Constructs of the form Prefix'Alignment are
-- converted into Prefix._Alignment.
-- TSS_Stream_Read (3) - implementation of the stream attribute Read
-- for any tagged type.
-- TSS_Stream_Write (4) - implementation of the stream attribute Write
-- for any tagged type.
-- TSS_Stream_Input (5) - implementation of the stream attribute Input
-- for any tagged type.
-- TSS_Stream_Output (6) - implementation of the stream attribute
-- Output for any tagged type.
-- Op_Eq (7) - implementation of the equality operator for any non-
-- limited tagged type.
-- _Assign (8) - implementation of the assignment operator for any
-- non-limited tagged type.
-- TSS_Deep_Adjust (9) - implementation of the finalization operation
-- Adjust for any non-limited tagged type.
-- TSS_Deep_Finalize (10) - implementation of the finalization
-- operation Finalize for any non-limited tagged type.
-- _Disp_Asynchronous_Select (11) - used in the expansion of ATC with
-- dispatching triggers. Null implementation for limited interfaces,
-- full body generation for types that implement limited interfaces,
-- not generated for the rest of the cases. See Expand_N_Asynchronous_
-- Select in Exp_Ch9 for more information.
-- _Disp_Conditional_Select (12) - used in the expansion of conditional
-- selects with dispatching triggers. Null implementation for limited
-- interfaces, full body generation for types that implement limited
-- interfaces, not generated for the rest of the cases. See Expand_N_
-- Conditional_Entry_Call in Exp_Ch9 for more information.
-- _Disp_Get_Prim_Op_Kind (13) - helper routine used in the expansion
-- of ATC with dispatching triggers. Null implementation for limited
-- interfaces, full body generation for types that implement limited
-- interfaces, not generated for the rest of the cases.
-- _Disp_Get_Task_Id (14) - helper routine used in the expansion of
-- Abort, attributes 'Callable and 'Terminated for task interface
-- class-wide types. Full body generation for task types, null
-- implementation for limited interfaces, not generated for the rest
-- of the cases. See Expand_N_Attribute_Reference in Exp_Attr and
-- Expand_N_Abort_Statement in Exp_Ch9 for more information.
-- _Disp_Timed_Select (15) - used in the expansion of timed selects
-- with dispatching triggers. Null implementation for limited
-- interfaces, full body generation for types that implement limited
-- interfaces, not generated for the rest of the cases. See Expand_N_
-- Timed_Entry_Call for more information.
-- Lifecycle of predefined primitive operations
-- The specifications and bodies of the PPOs are created by
-- Make_Predefined_Primitive_Specs and Predefined_Primitive_Bodies
-- in Exp_Ch3. The generated specifications are immediately analyzed,
-- while the bodies are left as freeze actions to the tagged type for
-- which they are created.
-- PPOs are collected and added to the Primitive_Operations list of
-- a type by the regular analysis mechanism.
-- PPOs are frozen in Predefined_Primitive_Freeze in Exp_Ch3.
-- Thunks for PPOs are created in Freeze_Subprogram in Exp_Ch6, by a
-- call to Register_Predefined_DT_Entry, also in Exp_Ch6.
-- Dispatch table positions of PPOs are set in Set_All_DT_Position in
-- Exp_Disp.
-- Calls to PPOs procede as regular dispatching calls. If the PPO
-- has a thunk, a call procedes as a regular dispatching call with
-- a thunk.
-- Guidelines for addition of new predefined primitive operations
-- Update the value of constant Default_Prim_Op_Count in A-Tags.ads
-- to reflect the new number of PPOs.
-- Introduce a new predefined name for the new PPO in Snames.ads and
-- Snames.adb.
-- Categorize the new PPO name as predefined by adding an entry in
-- Is_Predefined_Dispatching_Operation in Exp_Util.adb.
-- Generate the specification of the new PPO in Make_Predefined_
-- Primitive_Spec in Exp_Ch3.adb. The Is_Internal flag of the defining
-- identifier of the specification must be set to True.
-- Generate the body of the new PPO in Predefined_Primitive_Bodies in
-- Exp_Ch3.adb. The Is_Internal flag of the defining identifier of the
-- specification must be set to True.
-- If the new PPO requires a thunk, add an entry in Freeze_Subprogram
-- in Exp_Ch6.adb.
-- When generating calls to a PPO, use Find_Prim_Op from Exp_Util.ads
-- to retrieve the entity of the operation directly.
-- Number of predefined primitive operations added by the Expander
-- for a tagged type. If more predefined primitive operations are
-- added, the following items must be changed:
-- Ada.Tags.Defailt_Prim_Op_Count - indirect use
-- Exp_Disp.Default_Prim_Op_Position - indirect use
-- Exp_Disp.Set_All_DT_Position - direct use
type DT_Access_Action is
(CW_Membership,
IW_Membership,
DT_Entry_Size,
DT_Prologue_Size,
Get_Access_Level,
Get_Entry_Index,
Get_External_Tag,
Get_Predefined_Prim_Op_Address,
Get_Prim_Op_Address,
Get_Prim_Op_Kind,
Get_RC_Offset,
Get_Remotely_Callable,
Get_Tagged_Kind,
Inherit_DT,
Inherit_TSD,
Register_Interface_Tag,
Register_Tag,
Set_Access_Level,
Set_Entry_Index,
Set_Expanded_Name,
Set_External_Tag,
Set_Interface_Table,
Set_Offset_Index,
Set_OSD,
Set_Predefined_Prim_Op_Address,
Set_Prim_Op_Address,
Set_Prim_Op_Kind,
Set_RC_Offset,
Set_Remotely_Callable,
Set_Signature,
Set_SSD,
Set_TSD,
Set_Tagged_Kind,
TSD_Entry_Size,
TSD_Prologue_Size);
procedure Expand_Dispatching_Call (Call_Node : Node_Id);
-- Expand the call to the operation through the dispatch table and perform
-- the required tag checks when appropriate. For CPP types the call is
-- done through the Vtable (tag checks are not relevant)
procedure Expand_Interface_Actuals (Call_Node : Node_Id);
-- Ada 2005 (AI-251): Displace all the actuals corresponding to class-wide
-- interfaces to reference the interface tag of the actual object
procedure Expand_Interface_Conversion
(N : Node_Id;
Is_Static : Boolean := True);
-- Ada 2005 (AI-251): N is a type-conversion node. Reference the base of
-- the object to give access to the interface tag associated with the
-- secondary dispatch table.
function Expand_Interface_Thunk
(N : Node_Id;
Thunk_Alias : Node_Id;
Thunk_Id : Entity_Id) return Node_Id;
-- Ada 2005 (AI-251): When a tagged type implements abstract interfaces we
-- generate additional subprograms (thunks) to have a layout compatible
-- with the C++ ABI. The thunk modifies the value of the first actual of
-- the call (that is, the pointer to the object) before transferring
-- control to the target function.
function Fill_DT_Entry
(Loc : Source_Ptr;
Prim : Entity_Id) return Node_Id;
-- Generate the code necessary to fill the appropriate entry of the
-- dispatch table of Prim's controlling type with Prim's address.
function Fill_Secondary_DT_Entry
(Loc : Source_Ptr;
Prim : Entity_Id;
Thunk_Id : Entity_Id;
Iface_DT_Ptr : Entity_Id) return Node_Id;
-- (Ada 2005): Generate the code necessary to fill the appropriate entry of
-- the secondary dispatch table of Prim's controlling type with Thunk_Id's
-- address.
function Get_Remotely_Callable (Obj : Node_Id) return Node_Id;
-- Return an expression that holds True if the object can be transmitted
-- onto another partition according to E.4 (18)
function Init_Predefined_Interface_Primitives
(Typ : Entity_Id) return List_Id;
-- Ada 2005 (AI-251): Initialize the entries associated with predefined
-- primitives in all the secondary dispatch tables of Typ.
function Make_DT_Access_Action
(Typ : Entity_Id;
Action : DT_Access_Action;
Args : List_Id) return Node_Id;
-- Generate a call to one of the Dispatch Table Access Subprograms defined
-- in Ada.Tags or in Interfaces.Cpp
function Make_DT (Typ : Entity_Id) return List_Id;
-- Expand the declarations for the Dispatch Table (or the Vtable in
-- the case of type whose ancestor is a CPP_Class)
function Make_Disp_Asynchronous_Select_Body
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the body of the primitive operation of type
-- Typ used for dispatching in asynchronous selects. Generate a null body
-- if Typ is an interface type.
function Make_Disp_Asynchronous_Select_Spec
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the specification of the primitive operation
-- of type Typ used for dispatching in asynchronous selects.
function Make_Disp_Conditional_Select_Body
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the body of the primitive operation of type
-- Typ used for dispatching in conditional selects. Generate a null body
-- if Typ is an interface type.
function Make_Disp_Conditional_Select_Spec
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the specification of the primitive operation
-- of type Typ used for dispatching in conditional selects.
function Make_Disp_Get_Prim_Op_Kind_Body
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the body of the primitive operation of type
-- Typ used for retrieving the callable entity kind during dispatching in
-- asynchronous selects. Generate a null body if Typ is an interface type.
function Make_Disp_Get_Prim_Op_Kind_Spec
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the specification of the primitive operation
-- of the type Typ use for retrieving the callable entity kind during
-- dispatching in asynchronous selects.
function Make_Disp_Get_Task_Id_Body
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the body of the primitive operation of type
-- Typ used for retrieving the _task_id field of a task interface class-
-- wide type. Generate a null body if Typ is an interface or a non-task
-- type.
function Make_Disp_Get_Task_Id_Spec
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the specification of the primitive operation
-- of type Typ used for retrieving the _task_id field of a task interface
-- class-wide type.
function Make_Disp_Timed_Select_Body
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the body of the primitive operation of type
-- Typ used for dispatching in timed selects. Generate a null body if Nul
-- is an interface type.
function Make_Disp_Timed_Select_Spec
(Typ : Entity_Id) return Node_Id;
-- Ada 2005 (AI-345): Generate the specification of the primitive operation
-- of type Typ used for dispatching in timed selects.
function Make_Select_Specific_Data_Table
(Typ : Entity_Id) return List_Id;
-- Ada 2005 (AI-345): Create and populate the auxiliary table in the TSD
-- of Typ used for dispatching in asynchronous, conditional and timed
-- selects. Generate code to set the primitive operation kinds and entry
-- indices of primitive operations and primitive wrappers.
procedure Make_Secondary_DT
(Typ : Entity_Id;
Ancestor_Typ : Entity_Id;
Suffix_Index : Int;
Iface : Entity_Id;
AI_Tag : Entity_Id;
Acc_Disp_Tables : in out Elist_Id;
Result : out List_Id);
-- Ada 2005 (AI-251): Expand the declarations for the Secondary Dispatch
-- Table of Typ associated with Iface (each abstract interface implemented
-- by Typ has a secondary dispatch table). The arguments Typ, Ancestor_Typ
-- and Suffix_Index are used to generate an unique external name which
-- is added at the end of Acc_Disp_Tables; this external name will be
-- used later by the subprogram Exp_Ch3.Build_Init_Procedure.
procedure Set_All_DT_Position (Typ : Entity_Id);
-- Set the DT_Position field for each primitive operation. In the CPP
-- Class case check that no pragma CPP_Virtual is missing and that the
-- DT_Position are coherent
procedure Set_Default_Constructor (Typ : Entity_Id);
-- Typ is a CPP_Class type. Create the Init procedure of that type to
-- be the default constructor (i.e. the function returning this type,
-- having a pragma CPP_Constructor and no parameter)
procedure Write_DT (Typ : Entity_Id);
pragma Export (Ada, Write_DT);
-- Debugging procedure (to be called within gdb)
end Exp_Disp;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- M L I B . T G T --
-- --
-- B o d y --
-- --
-- Copyright (C) 2001-2010, AdaCore --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. 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 MLib.Fil;
with Prj.Com;
with MLib.Tgt.Specific;
pragma Warnings (Off, MLib.Tgt.Specific);
-- MLib.Tgt.Specific is with'ed only for elaboration purposes
package body MLib.Tgt is
---------------------
-- Archive_Builder --
---------------------
function Archive_Builder return String is
begin
return Archive_Builder_Ptr.all;
end Archive_Builder;
-----------------------------
-- Archive_Builder_Default --
-----------------------------
function Archive_Builder_Default return String is
begin
return "ar";
end Archive_Builder_Default;
-----------------------------
-- Archive_Builder_Options --
-----------------------------
function Archive_Builder_Options return String_List_Access is
begin
return Archive_Builder_Options_Ptr.all;
end Archive_Builder_Options;
-------------------------------------
-- Archive_Builder_Options_Default --
-------------------------------------
function Archive_Builder_Options_Default return String_List_Access is
begin
return new String_List'(1 => new String'("cr"));
end Archive_Builder_Options_Default;
------------------------------------
-- Archive_Builder_Append_Options --
------------------------------------
function Archive_Builder_Append_Options return String_List_Access is
begin
return Archive_Builder_Append_Options_Ptr.all;
end Archive_Builder_Append_Options;
--------------------------------------------
-- Archive_Builder_Append_Options_Default --
--------------------------------------------
function Archive_Builder_Append_Options_Default return String_List_Access is
begin
return new String_List'(1 => new String'("q"));
end Archive_Builder_Append_Options_Default;
-----------------
-- Archive_Ext --
-----------------
function Archive_Ext return String is
begin
return Archive_Ext_Ptr.all;
end Archive_Ext;
-------------------------
-- Archive_Ext_Default --
-------------------------
function Archive_Ext_Default return String is
begin
return "a";
end Archive_Ext_Default;
---------------------
-- Archive_Indexer --
---------------------
function Archive_Indexer return String is
begin
return Archive_Indexer_Ptr.all;
end Archive_Indexer;
-----------------------------
-- Archive_Indexer_Default --
-----------------------------
function Archive_Indexer_Default return String is
begin
return "ranlib";
end Archive_Indexer_Default;
-----------------------------
-- Archive_Indexer_Options --
-----------------------------
function Archive_Indexer_Options return String_List_Access is
begin
return Archive_Indexer_Options_Ptr.all;
end Archive_Indexer_Options;
-------------------------------------
-- Archive_Indexer_Options_Default --
-------------------------------------
function Archive_Indexer_Options_Default return String_List_Access is
begin
return new String_List (1 .. 0);
end Archive_Indexer_Options_Default;
---------------------------
-- 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
begin
Build_Dynamic_Library_Ptr
(Ofiles,
Options,
Interfaces,
Lib_Filename,
Lib_Dir,
Symbol_Data,
Driver_Name,
Lib_Version,
Auto_Init);
end Build_Dynamic_Library;
------------------------------
-- Default_Symbol_File_Name --
------------------------------
function Default_Symbol_File_Name return String is
begin
return Default_Symbol_File_Name_Ptr.all;
end Default_Symbol_File_Name;
--------------------------------------
-- Default_Symbol_File_Name_Default --
--------------------------------------
function Default_Symbol_File_Name_Default return String is
begin
return "";
end Default_Symbol_File_Name_Default;
-------------
-- DLL_Ext --
-------------
function DLL_Ext return String is
begin
return DLL_Ext_Ptr.all;
end DLL_Ext;
---------------------
-- DLL_Ext_Default --
---------------------
function DLL_Ext_Default return String is
begin
return "so";
end DLL_Ext_Default;
----------------
-- DLL_Prefix --
----------------
function DLL_Prefix return String is
begin
return DLL_Prefix_Ptr.all;
end DLL_Prefix;
------------------------
-- DLL_Prefix_Default --
------------------------
function DLL_Prefix_Default return String is
begin
return "lib";
end DLL_Prefix_Default;
--------------------
-- Dynamic_Option --
--------------------
function Dynamic_Option return String is
begin
return Dynamic_Option_Ptr.all;
end Dynamic_Option;
----------------------------
-- Dynamic_Option_Default --
----------------------------
function Dynamic_Option_Default return String is
begin
return "-shared";
end Dynamic_Option_Default;
-------------------
-- Is_Object_Ext --
-------------------
function Is_Object_Ext (Ext : String) return Boolean is
begin
return Is_Object_Ext_Ptr (Ext);
end Is_Object_Ext;
---------------------------
-- Is_Object_Ext_Default --
---------------------------
function Is_Object_Ext_Default (Ext : String) return Boolean is
begin
return Ext = ".o";
end Is_Object_Ext_Default;
--------------
-- Is_C_Ext --
--------------
function Is_C_Ext (Ext : String) return Boolean is
begin
return Is_C_Ext_Ptr (Ext);
end Is_C_Ext;
----------------------
-- Is_C_Ext_Default --
----------------------
function Is_C_Ext_Default (Ext : String) return Boolean is
begin
return Ext = ".c";
end Is_C_Ext_Default;
--------------------
-- Is_Archive_Ext --
--------------------
function Is_Archive_Ext (Ext : String) return Boolean is
begin
return Is_Archive_Ext_Ptr (Ext);
end Is_Archive_Ext;
----------------------------
-- Is_Archive_Ext_Default --
----------------------------
function Is_Archive_Ext_Default (Ext : String) return Boolean is
begin
return Ext = ".a";
end Is_Archive_Ext_Default;
-------------
-- Libgnat --
-------------
function Libgnat return String is
begin
return Libgnat_Ptr.all;
end Libgnat;
---------------------
-- Libgnat_Default --
---------------------
function Libgnat_Default return String is
begin
return "libgnat.a";
end Libgnat_Default;
------------------------
-- Library_Exists_For --
------------------------
function Library_Exists_For
(Project : Project_Id;
In_Tree : Project_Tree_Ref) return Boolean
is
begin
return Library_Exists_For_Ptr (Project, In_Tree);
end Library_Exists_For;
--------------------------------
-- Library_Exists_For_Default --
--------------------------------
function Library_Exists_For_Default
(Project : Project_Id;
In_Tree : Project_Tree_Ref) return Boolean
is
pragma Unreferenced (In_Tree);
begin
if not Project.Library then
Prj.Com.Fail ("INTERNAL ERROR: Library_Exists_For called " &
"for non library project");
return False;
else
declare
Lib_Dir : constant String :=
Get_Name_String (Project.Library_Dir.Display_Name);
Lib_Name : constant String :=
Get_Name_String (Project.Library_Name);
begin
if Project.Library_Kind = Static then
return Is_Regular_File
(Lib_Dir & Directory_Separator & "lib" &
Fil.Append_To (Lib_Name, Archive_Ext));
else
return Is_Regular_File
(Lib_Dir & Directory_Separator & DLL_Prefix &
Fil.Append_To (Lib_Name, DLL_Ext));
end if;
end;
end if;
end Library_Exists_For_Default;
---------------------------
-- Library_File_Name_For --
---------------------------
function Library_File_Name_For
(Project : Project_Id;
In_Tree : Project_Tree_Ref) return File_Name_Type
is
begin
return Library_File_Name_For_Ptr (Project, In_Tree);
end Library_File_Name_For;
-----------------------------------
-- Library_File_Name_For_Default --
-----------------------------------
function Library_File_Name_For_Default
(Project : Project_Id;
In_Tree : Project_Tree_Ref) return File_Name_Type
is
pragma Unreferenced (In_Tree);
begin
if not Project.Library then
Prj.Com.Fail ("INTERNAL ERROR: Library_File_Name_For called " &
"for non library project");
return No_File;
else
declare
Lib_Name : constant String :=
Get_Name_String (Project.Library_Name);
begin
if Project.Library_Kind =
Static
then
Name_Len := 3;
Name_Buffer (1 .. Name_Len) := "lib";
Add_Str_To_Name_Buffer (Fil.Append_To (Lib_Name, Archive_Ext));
else
Name_Len := 0;
Add_Str_To_Name_Buffer (DLL_Prefix);
Add_Str_To_Name_Buffer (Fil.Append_To (Lib_Name, DLL_Ext));
end if;
return Name_Find;
end;
end if;
end Library_File_Name_For_Default;
--------------------------------------
-- Library_Major_Minor_Id_Supported --
--------------------------------------
function Library_Major_Minor_Id_Supported return Boolean is
begin
return Library_Major_Minor_Id_Supported_Ptr.all;
end Library_Major_Minor_Id_Supported;
----------------------------------------------
-- Library_Major_Minor_Id_Supported_Default --
----------------------------------------------
function Library_Major_Minor_Id_Supported_Default return Boolean is
begin
return True;
end Library_Major_Minor_Id_Supported_Default;
----------------
-- Object_Ext --
----------------
function Object_Ext return String is
begin
return Object_Ext_Ptr.all;
end Object_Ext;
------------------------
-- Object_Ext_Default --
------------------------
function Object_Ext_Default return String is
begin
return "o";
end Object_Ext_Default;
----------------
-- PIC_Option --
----------------
function PIC_Option return String is
begin
return PIC_Option_Ptr.all;
end PIC_Option;
------------------------
-- PIC_Option_Default --
------------------------
function PIC_Option_Default return String is
begin
return "-fPIC";
end PIC_Option_Default;
-----------------------------------------------
-- Standalone_Library_Auto_Init_Is_Supported --
-----------------------------------------------
function Standalone_Library_Auto_Init_Is_Supported return Boolean is
begin
return Standalone_Library_Auto_Init_Is_Supported_Ptr.all;
end Standalone_Library_Auto_Init_Is_Supported;
-------------------------------------------------------
-- Standalone_Library_Auto_Init_Is_Supported_Default --
-------------------------------------------------------
function Standalone_Library_Auto_Init_Is_Supported_Default return Boolean is
begin
return True;
end Standalone_Library_Auto_Init_Is_Supported_Default;
---------------------------
-- Support_For_Libraries --
---------------------------
function Support_For_Libraries return Library_Support is
begin
return Support_For_Libraries_Ptr.all;
end Support_For_Libraries;
-----------------------------------
-- Support_For_Libraries_Default --
-----------------------------------
function Support_For_Libraries_Default return Library_Support is
begin
return Full;
end Support_For_Libraries_Default;
end MLib.Tgt;
|
-----------------------------------------------------------------------
-- servlet-routes -- Request routing
-- Copyright (C) 2015, 2016, 2017, 2019, 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.Finalization;
with Util.Beans.Basic;
with Util.Refs;
with EL.Expressions;
with EL.Contexts;
package Servlet.Routes is
type Route_Type is abstract new Util.Refs.Ref_Entity with null record;
type Route_Type_Access is access all Route_Type'Class;
package Route_Type_Refs is
new Util.Refs.Indefinite_References (Element_Type => Route_Type'Class,
Element_Access => Route_Type_Access);
subtype Route_Type_Ref is Route_Type_Refs.Ref;
subtype Route_Type_Accessor is Route_Type_Refs.Element_Accessor;
No_Parameter : exception;
type Path_Mode is (FULL, PREFIX, SUFFIX);
-- The <tt>Route_Context_Type</tt> defines the context information after a path
-- has been routed.
type Route_Context_Type is tagged limited private;
-- Get path information after the routing.
function Get_Path (Context : in Route_Context_Type;
Mode : in Path_Mode := FULL) return String;
-- Get the path parameter value for the given parameter index.
-- The <tt>No_Parameter</tt> exception is raised if the parameter does not exist.
function Get_Parameter (Context : in Route_Context_Type;
Index : in Positive) return String;
-- Get the number of path parameters that were extracted for the route.
function Get_Parameter_Count (Context : in Route_Context_Type) return Natural;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Context : in Route_Context_Type) return Natural;
-- Return the route associated with the resolved route context.
function Get_Route (Context : in Route_Context_Type) return Route_Type_Accessor;
function Get_Route (Context : in Route_Context_Type) return Route_Type_Ref;
-- Return True if there is no route.
function Is_Null (Context : in Route_Context_Type) return Boolean;
-- Change the context to use a new route.
procedure Change_Route (Context : in out Route_Context_Type;
To : in Route_Type_Ref);
-- Inject the parameters that have been extracted from the path according
-- to the selected route.
procedure Inject_Parameters (Context : in Route_Context_Type;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- The <tt>Router_Type</tt> registers the different routes with their rules and
-- resolves a path into a route context information.
type Router_Type is new Ada.Finalization.Limited_Controlled with private;
type Router_Type_Access is access all Router_Type'Class;
-- Add a route associated with the given path pattern. The pattern is split into components.
-- Some path components can be a fixed string (/home) and others can be variable.
-- When a path component is variable, the value can be retrieved from the route context.
-- Once the route path is created, the <tt>Process</tt> procedure is called with the route
-- reference.
procedure Add_Route (Router : in out Router_Type;
Pattern : in String;
ELContext : in EL.Contexts.ELContext'Class;
Process : not null access procedure (Route : in out Route_Type_Ref));
-- Build the route context from the given path by looking at the different routes registered
-- in the router with <tt>Add_Route</tt>.
procedure Find_Route (Router : in Router_Type;
Path : in String;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Router : in Router_Type;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Accessor));
private
type String_Access is access all String;
type Route_Node_Type is tagged;
type Route_Node_Access is access all Route_Node_Type'Class;
-- Describes a variable path component whose value must be injected in an Ada bean.
type Route_Param_Type is limited record
Route : Route_Node_Access;
First : Natural := 0;
Last : Natural := 0;
end record;
type Route_Param_Array is array (Positive range <>) of Route_Param_Type;
type Route_Match_Type is (NO_MATCH, MAYBE_MATCH, WILDCARD_MATCH, EXT_MATCH, YES_MATCH);
type Route_Node_Type is abstract tagged limited record
Next_Route : Route_Node_Access;
Children : Route_Node_Access;
Route : Route_Type_Ref;
end record;
-- Inject the parameter that was extracted from the path.
procedure Inject_Parameter (Node : in Route_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class) is null;
-- Check if the route node accepts the given path component.
function Matches (Node : in Route_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type is abstract;
-- Return the component path pattern that this route node represents.
-- Example: 'index.html', '#{user.id}', ':id'
function Get_Pattern (Node : in Route_Node_Type) return String is abstract;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
function Get_Path_Pos (Node : in Route_Node_Type;
Param : in Route_Param_Type) return Natural;
-- Find recursively a match on the given route sub-tree. The match must start at the position
-- <tt>First</tt> in the path up to the last path position. While the path components are
-- checked, the route context is populated with variable components. When the full path
-- matches, <tt>YES_MATCH</tt> is returned in the context gets the route instance.
procedure Find_Match (Node : in Route_Node_Type;
Path : in String;
First : in Natural;
Match : out Route_Match_Type;
Context : in out Route_Context_Type'Class);
-- Walk the routes that have been added by <tt>Add_Route</tt> and call the <tt>Process</tt>
-- procedure with each path pattern and route object.
procedure Iterate (Node : in Route_Node_Type;
Path : in String;
Process : not null access procedure (Pattern : in String;
Route : in Route_Type_Accessor));
-- A fixed path component identification.
type Path_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : aliased String (1 .. Len);
end record;
type Path_Node_Access is access all Path_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns YES_MATCH if the name corresponds exactly to the node's name.
overriding
function Matches (Node : in Path_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, 'Name').
overriding
function Get_Pattern (Node : in Path_Node_Type) return String;
-- A variable path component whose value is injected in an Ada bean using the EL expression.
-- The route node is created each time an EL expression is found in the route pattern.
-- Example: /home/#{user.id}/index.html
-- In this example, the EL expression refers to <tt>user.id</tt>.
type EL_Node_Type is new Route_Node_Type with record
Value : EL.Expressions.Value_Expression;
end record;
type EL_Node_Access is access all EL_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in EL_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, the EL expr).
overriding
function Get_Pattern (Node : in EL_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in EL_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
-- A variable path component which can be injected in an Ada bean.
-- Example: /home/:id/view.html
-- The path component represented by <tt>:id</tt> is injected in the Ada bean object
-- passed to the <tt>Inject_Parameters</tt> procedure.
type Param_Node_Type (Len : Natural) is new Route_Node_Type with record
Name : String (1 .. Len);
end record;
type Param_Node_Access is access all Param_Node_Type'Class;
-- Check if the route node accepts the given path component.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Param_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, Name).
overriding
function Get_Pattern (Node : in Param_Node_Type) return String;
-- Inject the parameter that was extracted from the path.
overriding
procedure Inject_Parameter (Node : in Param_Node_Type;
Param : in String;
Into : in out Util.Beans.Basic.Bean'Class;
ELContext : in EL.Contexts.ELContext'Class);
type Extension_Node_Type (Len : Natural) is new Route_Node_Type with record
Ext : String (1 .. Len);
end record;
type Extension_Node_Access is access all Extension_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns MAYBE_MATCH.
overriding
function Matches (Node : in Extension_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *.Ext).
overriding
function Get_Pattern (Node : in Extension_Node_Type) return String;
type Wildcard_Node_Type is new Route_Node_Type with null record;
type Wildcard_Node_Access is access all Wildcard_Node_Type'Class;
-- Check if the route node accepts the given extension.
-- Returns WILDCARD_MATCH.
overriding
function Matches (Node : in Wildcard_Node_Type;
Name : in String;
Is_Last : in Boolean) return Route_Match_Type;
-- Return the component path pattern that this route node represents (ie, *).
overriding
function Get_Pattern (Node : in Wildcard_Node_Type) return String;
-- Return the position of the variable part of the path.
-- If the URI matches a wildcard pattern, the position of the last '/' in the wildcard pattern
-- is returned.
overriding
function Get_Path_Pos (Node : in Wildcard_Node_Type;
Param : in Route_Param_Type) return Natural;
MAX_ROUTE_PARAMS : constant Positive := 10;
type Route_Context_Type is limited new Ada.Finalization.Limited_Controlled with record
Route : Route_Type_Ref;
Path : String_Access;
Params : Route_Param_Array (1 .. MAX_ROUTE_PARAMS);
Count : Natural := 0;
end record;
-- Release the storage held by the route context.
overriding
procedure Finalize (Context : in out Route_Context_Type);
type Router_Type is new Ada.Finalization.Limited_Controlled with record
Route : aliased Path_Node_Type (Len => 0);
end record;
-- Release the storage held by the router.
overriding
procedure Finalize (Router : in out Router_Type);
-- Insert the route node at the correct place in the children list
-- according to the rule kind.
procedure Insert (Parent : in Route_Node_Access;
Node : in Route_Node_Access;
Kind : in Route_Match_Type);
end Servlet.Routes;
|
with ada.Containers.Hashed_Maps,display, Ada.Containers.Hashed_Maps,ada.containers.doubly_linked_lists ;
package snake_types is
type Snake_direction is (LEFT,RIGHT,UP,DOWN) ;
type Coordinates is
record
x : integer range display.screen'range(1) ;
y : integer range display.screen'range(2) ;
end record ;
package snake_list is new ada.Containers.doubly_linked_lists(Coordinates) ;
subtype snake is snake_list.list ;
function Hash_Func(Key : character) return Ada.Containers.Hash_Type ;
package User_Controls is new Ada.Containers.Hashed_Maps
(Key_Type => character,
Element_Type => Snake_direction,
Hash => Hash_Func,
Equivalent_Keys => "=");
end snake_types ;
|
------------------------------------------------------------------------------
-- --
-- Matreshka Project --
-- --
-- Localization, Internationalization, Globalization for Ada --
-- --
-- Runtime Library Component --
-- --
------------------------------------------------------------------------------
-- --
-- Copyright © 2012-2017, Vadim Godunko <vgodunko@gmail.com> --
-- All rights reserved. --
-- --
-- Redistribution and use in source and binary forms, with or without --
-- modification, are permitted provided that the following conditions --
-- are met: --
-- --
-- * Redistributions of source code must retain the above copyright --
-- notice, this list of conditions and the following disclaimer. --
-- --
-- * Redistributions in binary form must reproduce the above copyright --
-- notice, this list of conditions and the following disclaimer in the --
-- documentation and/or other materials provided with the distribution. --
-- --
-- * Neither the name of the Vadim Godunko, IE nor the names of its --
-- contributors may be used to endorse or promote products derived from --
-- this software without specific prior written permission. --
-- --
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS --
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT --
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR --
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT --
-- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, --
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED --
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR --
-- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF --
-- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING --
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS --
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --
-- --
------------------------------------------------------------------------------
-- $Revision$ $Date$
------------------------------------------------------------------------------
with Matreshka.Internals.Unicode;
package body UAFLEX.Scanners is
package Tables is
function To_Class (Value : Matreshka.Internals.Unicode.Code_Point)
return Character_Class;
pragma Inline (To_Class);
function Switch (S : State; Class : Character_Class) return State;
pragma Inline (Switch);
function Rule (S : State) return Rule_Index;
pragma Inline (Rule);
end Tables;
procedure On_Accept
(Self : not null access UAFLEX.Handlers.Handler'Class;
Scanner : not null access UAFLEX.Scanners.Scanner'Class;
Rule : Rule_Index;
Token : out Parser_Tokens.Token;
Skip : in out Boolean);
package body Tables is separate;
use Tables;
procedure On_Accept
(Self : not null access UAFLEX.Handlers.Handler'Class;
Scanner : not null access UAFLEX.Scanners.Scanner'Class;
Rule : Rule_Index;
Token : out Parser_Tokens.Token;
Skip : in out Boolean) is separate;
End_Of_Buffer : constant Wide_Wide_Character :=
Wide_Wide_Character'Val (Abstract_Sources.End_Of_Buffer);
-------------------------
-- Get_Start_Condition --
-------------------------
function Get_Start_Condition
(Self : Scanner'Class)
return Start_Condition
is
begin
return Self.Start;
end Get_Start_Condition;
--------------
-- Get_Text --
--------------
function Get_Text
(Self : Scanner'Class)
return League.Strings.Universal_String
is
begin
if Self.From <= Self.To then
return League.Strings.To_Universal_String
(Self.Buffer (Self.From .. Self.To));
elsif Self.From = Self.To + 1 then
return League.Strings.Empty_Universal_String;
else
return League.Strings.To_Universal_String
(Self.Buffer (Self.From .. Self.Buffer'Last)
& Self.Buffer (1 .. Self.To));
end if;
end Get_Text;
---------------
-- Get_Token --
---------------
procedure Get_Token (Self : access Scanner'Class; Result : out Token) is
procedure Next;
procedure Next is
begin
if Self.Next = Self.Buffer'Last then
Self.Next := 1;
else
Self.Next := Self.Next + 1;
end if;
end Next;
EOF : constant Wide_Wide_Character :=
Wide_Wide_Character'Val (Abstract_Sources.End_Of_Input);
-- EOD : constant Wide_Wide_Character :=
-- Wide_Wide_Character'Val (Abstract_Sources.End_Of_Data);
Current_State : State := Self.Start;
Char : Character_Class;
Next_Rule : Rule_Index;
Skip : Boolean := True;
begin
loop
if Self.Buffer (Self.Next) = EOF then
Result := Parser_Tokens.End_Of_Input;
return;
end if;
Current_State := Self.Start;
Self.Rule := 0;
Self.From := Self.Next;
Self.To := Self.Next - 1;
loop
Char := Self.Classes (Self.Next);
if Char /= Error_Character then
Current_State := Switch (Current_State, Char);
if Current_State not in Looping_State then
if Current_State in Final_State then
Self.Rule := Rule (Current_State);
Self.To := Self.Next;
end if;
exit;
elsif Current_State in Final_State then
Next_Rule := Rule (Current_State);
Self.Rule := Next_Rule;
Self.To := Self.Next;
end if;
Next;
elsif Self.Buffer (Self.Next) = End_Of_Buffer then
Self.Read_Buffer;
else
exit;
end if;
end loop;
Self.Next := Self.To;
Next;
if Self.Rule = 0 then
Result := Parser_Tokens.Error;
return;
else
On_Accept (Self.Handler, Self, Self.Rule, Result, Skip);
if not Skip then
return;
end if;
end if;
end loop;
end Get_Token;
----------------------
-- Get_Token_Length --
----------------------
function Get_Token_Length (Self : Scanner'Class) return Positive is
begin
if Self.From <= Self.To then
return Self.To - Self.From + 1;
else
return Buffer_Index'Last - Self.From + 1 + Self.To;
end if;
end Get_Token_Length;
------------------------
-- Get_Token_Position --
------------------------
function Get_Token_Position (Self : Scanner'Class) return Positive is
Half : constant Buffer_Half :=
Buffer_Half'Val (Boolean'Pos (Self.From >= Buffer_Half_Size));
begin
return Self.Offset (Half) + Self.From;
end Get_Token_Position;
-----------------
-- Read_Buffer --
-----------------
procedure Read_Buffer (Self : in out Scanner'Class) is
use Abstract_Sources;
use type Code_Unit_32;
Next : Code_Unit_32;
Pos : Buffer_Index := Self.Next;
begin
if Self.From <= Buffer_Half_Size xor Self.Next <= Buffer_Half_Size then
raise Constraint_Error with "Token too large";
end if;
if Pos = Buffer_Half_Size then
Self.Offset (High) := Self.Offset (High) + Self.Buffer'Length;
elsif Pos = Self.Buffer'Last then
Self.Offset (Low) := Self.Offset (Low) + Self.Buffer'Length;
end if;
loop
Next := Self.Source.Get_Next;
Self.Buffer (Pos) := Wide_Wide_Character'Val (Next);
if Next = End_Of_Input or Next = Error then
Self.Classes (Pos) := Error_Character;
return;
else
Self.Classes (Pos) := To_Class (Next);
if Pos = Self.Buffer'Last then
Pos := 1;
else
Pos := Pos + 1;
end if;
if Pos = Buffer_Half_Size or Pos = Self.Buffer'Last then
Self.Classes (Pos) := Error_Character;
Self.Buffer (Pos) := End_Of_Buffer;
return;
end if;
end if;
end loop;
end Read_Buffer;
-----------------
-- Set_Handler --
-----------------
procedure Set_Handler
(Self : in out Scanner'Class;
Handler : not null UAFLEX.Handlers.Handler_Access) is
begin
Self.Handler := Handler;
end Set_Handler;
----------------
-- Set_Source --
----------------
procedure Set_Source
(Self : in out Scanner'Class;
Source : not null Abstract_Sources.Source_Access)
is
begin
Self.Source := Source;
end Set_Source;
-------------------------
-- Set_Start_Condition --
-------------------------
procedure Set_Start_Condition
(Self : in out Scanner'Class;
Condition : Start_Condition)
is
begin
Self.Start := Condition;
end Set_Start_Condition;
end UAFLEX.Scanners;
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure Twelve_Days_Of_Christmas is
type Days is (First, Second, Third, Fourth, Fifth, Sixth,
Seventh, Eighth, Ninth, Tenth, Eleventh, Twelfth);
package E_IO is new Ada.Text_IO.Enumeration_IO(Days);
use E_IO;
Gifts : array (Days) of Unbounded_String :=
(To_Unbounded_String(" A partridge in a pear-tree."),
To_Unbounded_String(" Two turtle doves"),
To_Unbounded_String(" Three French hens"),
To_Unbounded_String(" Four calling birds"),
To_Unbounded_String(" Five golden rings"),
To_Unbounded_String(" Six geese a-laying"),
To_Unbounded_String(" Seven swans a-swimming"),
To_Unbounded_String(" Eight maids a-milking"),
To_Unbounded_String(" Nine ladies dancing"),
To_Unbounded_String(" Ten lords a-leaping"),
To_Unbounded_String(" Eleven pipers piping"),
To_Unbounded_String(" Twelve drummers drumming"));
begin
for Day in Days loop
Put("On the "); Put(Day, Set => Lower_Case); Put(" day of Christmas,");
New_Line; Put_Line("My true love gave to me:");
for D in reverse Days'First..Day loop
Put_Line(To_String(Gifts(D)));
end loop;
if Day = First then
Replace_Slice(Gifts(Day), 2, 2, "And a");
end if;
New_Line;
end loop;
end Twelve_Days_Of_Christmas;
|
with System;
package body gnatcoll.uuid is
use Interfaces.C;
package bits_types_h is
type uu_timer_t is new System.Address; -- types.h:161:27
end bits_types_h;
package bits_time_h is
CLOCKS_PER_SEC : constant := 1000000; -- time.h:34
CLOCK_REALTIME : constant := 0; -- time.h:46
CLOCK_MONOTONIC : constant := 1; -- time.h:48
CLOCK_PROCESS_CPUTIME_ID : constant := 2; -- time.h:50
CLOCK_THREAD_CPUTIME_ID : constant := 3; -- time.h:52
TIMER_ABSTIME : constant := 1; -- time.h:55
type timeval is record
tv_sec : aliased long; -- time.h:71:14
tv_usec : aliased long; -- time.h:72:19
end record;
pragma Convention (C_Pass_By_Copy, timeval); -- time.h:70:3
end bits_time_h;
package time_h is
subtype time_t is long; -- time.h:76:18
end time_h;
package uuid_uuid_h is
UUID_VARIANT_NCS : constant := 0; -- uuid.h:47
UUID_VARIANT_DCE : constant := 1; -- uuid.h:48
UUID_VARIANT_MICROSOFT : constant := 2; -- uuid.h:49
UUID_VARIANT_OTHER : constant := 3; -- uuid.h:50
UUID_TYPE_DCE_TIME : constant := 1; -- uuid.h:53
UUID_TYPE_DCE_RANDOM : constant := 4; -- uuid.h:54
type uuid_t is array (0 .. 15) of aliased unsigned_char; -- uuid.h:44:23
pragma Unreferenced (uuid_t);
procedure uuid_clear (arg1 : access unsigned_char); -- uuid.h:70:6
pragma Import (C, uuid_clear, "uuid_clear");
function uuid_compare
(arg1 : access unsigned_char;
arg2 : access unsigned_char) return int; -- uuid.h:73:5
pragma Import (C, uuid_compare, "uuid_compare");
procedure uuid_copy (arg1 : access unsigned_char;
arg2 : access unsigned_char); -- uuid.h:76:6
pragma Import (C, uuid_copy, "uuid_copy");
procedure uuid_generate
(arg1 : access unsigned_char); -- uuid.h:79:6
pragma Import (C, uuid_generate, "uuid_generate");
procedure uuid_generate_random
(arg1 : access unsigned_char); -- uuid.h:80:6
pragma Import (C, uuid_generate_random, "uuid_generate_random");
procedure uuid_generate_time
(arg1 : access unsigned_char); -- uuid.h:81:6
pragma Import (C, uuid_generate_time, "uuid_generate_time");
function uuid_is_null
(arg1 : access unsigned_char) return int; -- uuid.h:84:5
pragma Import (C, uuid_is_null, "uuid_is_null");
function uuid_parse
(arg1 : access Character;
arg2 : access unsigned_char) return int; -- uuid.h:87:5
pragma Import (C, uuid_parse, "uuid_parse");
procedure uuid_unparse
(arg1 : access unsigned_char;
arg2 : access Character); -- uuid.h:90:6
pragma Import (C, uuid_unparse, "uuid_unparse");
procedure uuid_unparse_lower
(arg1 : access unsigned_char;
arg2 : access Character); -- uuid.h:91:6
pragma Import (C, uuid_unparse_lower, "uuid_unparse_lower");
procedure uuid_unparse_upper
(arg1 : access unsigned_char;
arg2 : access Character); -- uuid.h:92:6
pragma Import (C, uuid_unparse_upper, "uuid_unparse_upper");
function uuid_time
(arg1 : access unsigned_char;
arg2 : access bits_time_h.timeval) return time_h.time_t; -- uuid.h:95
pragma Import (C, uuid_time, "uuid_time");
function uuid_type
(arg1 : access unsigned_char) return int; -- uuid.h:96:5
pragma Import (C, uuid_type, "uuid_type");
function uuid_variant
(arg1 : access unsigned_char) return int; -- uuid.h:97:5
pragma Import (C, uuid_variant, "uuid_variant");
end uuid_uuid_h;
-----------------------------------------------------
procedure Clear (this : in out UUID) is
begin
uuid_uuid_h.uuid_clear(this.data(this.data'First)'Unrestricted_Access);
end Clear;
function "<" (l, r : UUID) return Boolean is
begin
return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access,
r.data (r.data'first)'Unrestricted_Access) < 0;
end "<";
function ">" (l, r : UUID) return Boolean is
begin
return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access,
r.data(r.data'first)'Unrestricted_Access) > 0;
end ">";
function "=" (l, r : UUID) return Boolean is
begin
return uuid_uuid_h.uuid_compare (l.data (l.data'first)'Unrestricted_Access,
r.data (r.data'first)'Unrestricted_Access) = 0;
end "=";
function Generate return UUID is
begin
return ret : UUID do
uuid_uuid_h.uuid_generate (ret.data (ret.data'First)'Unrestricted_Access);
end return;
end Generate;
procedure Generate (this : out UUID) is
begin
this := Generate;
end Generate;
function Generate_Random return UUID is
begin
return ret : UUID do
uuid_uuid_h.uuid_generate_random (ret.data (ret.data'First)'Unrestricted_Access);
end return;
end Generate_Random;
procedure Generate_Random (this : out UUID) is
begin
this := Generate_Random;
end;
procedure Generate_Time (this : out UUID) is
begin
this := Generate_Time;
end;
function Generate_Time return UUID is
begin
return ret : UUID do
uuid_uuid_h.uuid_generate_time (ret.data (ret.data'First)'Unrestricted_Access);
end return;
end Generate_Time;
function Is_Null (this : UUID) return Boolean is
begin
return uuid_uuid_h.uuid_is_null (this.data (this.data'First)'Unrestricted_Access) /= 0;
end Is_Null;
function Parse (data : String) return UUID is
ret : UUID;
L_Data : constant string := data & ascii.NUL;
res : int;
begin
res := uuid_uuid_h.uuid_parse (L_Data (L_Data'First)'unrestricted_access,
ret.data (ret.data'First)'unrestricted_access);
if res /= 0 then
raise PARSE_ERROR with "Unable to parse: '" & data & "'";
else
return ret;
end if;
end Parse;
function Unparse (this : UUID) return String is
ret : String (1 .. 37);
begin
uuid_uuid_h.uuid_unparse (this.data (this.data'first)'Unrestricted_access, ret (1)'unrestricted_access);
return ret (1 .. 36);
end Unparse;
function Unparse_Lower (this : UUID) return String is
ret : String (1 .. 37);
begin
uuid_uuid_h.uuid_unparse_lower (this.data (this.data'first)'Unrestricted_access, ret (1)'unrestricted_access);
return ret(1..36);
end Unparse_Lower;
function Unparse_Upper (this : UUID) return String is
ret : String (1 .. 37) ;
begin
uuid_uuid_h.uuid_unparse_upper (this.data (this.data'first)'Unrestricted_access, ret (1)'unrestricted_access);
return ret (1 .. 36);
end Unparse_Upper;
function Get_Type (this : UUID) return UUID_Type is
ret : int := uuid_uuid_h.uuid_type (this.data (this.data'first)'Unrestricted_access);
begin
case ret is
when uuid_uuid_h.UUID_TYPE_DCE_TIME =>
return DCE_TIME;
when uuid_uuid_h.UUID_TYPE_DCE_RANDOM =>
return DCE_RANDOM;
when others =>
return DCE_UNDEFINED;
end case;
end Get_Type;
function Get_Variant (this : UUID) return UUID_Variant is
begin
return UUID_Variant'Val (uuid_uuid_h.uuid_variant (this.data (this.data'first)'Unrestricted_access));
end Get_Variant;
end gnatcoll.uuid;
|
-- Copyright (c) 2021 Devin Hill
-- zlib License -- see LICENSE for details.
with System;
use System;
with System.Storage_Elements;
use System.Storage_Elements;
with System.Allocation.Arenas;
use System.Allocation.Arenas;
package GBA.Allocation is
pragma Elaborate_Body;
generic
Size : Storage_Count;
package Stack_Arena is
Storage : Local_Arena (Size);
end Stack_Arena;
subtype Marker is System.Allocation.Arenas.Marker;
subtype Heap_Arena is System.Allocation.Arenas.Heap_Arena;
subtype Local_Arena is System.Allocation.Arenas.Local_Arena;
function Storage_Size (Pool : Heap_Arena) return Storage_Count
renames System.Allocation.Arenas.Storage_Size;
function Storage_Size (Pool : Local_Arena) return Storage_Count
renames System.Allocation.Arenas.Storage_Size;
function Mark (Pool : Heap_Arena) return Marker
renames System.Allocation.Arenas.Mark;
function Mark (Pool : Local_Arena) return Marker
renames System.Allocation.Arenas.Mark;
procedure Release (Pool : in out Heap_Arena; Mark : Marker)
renames System.Allocation.Arenas.Release;
procedure Release (Pool : in out Local_Arena; Mark : Marker)
renames System.Allocation.Arenas.Release;
function Create_Arena (Start_Address, End_Address : Address)
return Heap_Arena renames System.Allocation.Arenas.Create_Arena;
function Create_Arena (Local_Size : SSE.Storage_Count)
return Local_Arena renames System.Allocation.Arenas.Create_Arena;
procedure Init_Arena (Pool : in out Local_Arena)
renames System.Allocation.Arenas.Init_Arena;
end GBA.Allocation; |
-- Ada has bitwise operators in package Interfaces,
-- but they work with Interfaces.Unsigned_*** types only.
-- Use rem or mod for Integer types, and let the compiler
-- optimize it.
declare
N : Integer := 5;
begin
if N rem 2 = 0 then
Put_Line ("Even number");
elseif N rem 2 /= 0 then
Put_Line ("Odd number");
else
Put_Line ("Something went really wrong!");
end if;
end;
|
with Ada.Text_IO;
procedure Example is
begin
Ada.Text_IO.Put_Line ("Hello world!");
end Example;
|
--
-- Copyright (c) 2008 Tero Koskinen <tero.koskinen@iki.fi>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ahven.Framework;
package Ahven.Parameters is
Invalid_Parameter : exception;
type Parameter_Info is private;
type Parameter_Mode is (NORMAL_PARAMETERS, TAP_PARAMETERS);
procedure Parse_Parameters (Mode : Parameter_Mode;
Info : out Parameter_Info);
-- Parse Ada.Command_Line parameters and put the results
-- to the Info parameter. Raises Invalid_Parameter if
-- some parameter is invalid.
procedure Usage (Mode : Parameter_Mode := NORMAL_PARAMETERS);
-- Print usage.
function Capture (Info : Parameter_Info) return Boolean;
-- Capture Ada.Text_IO output?
function Verbose (Info : Parameter_Info) return Boolean;
-- Use verbose mode?
function XML_Results (Info : Parameter_Info) return Boolean;
-- Output XML?
function Single_Test (Info : Parameter_Info) return Boolean;
-- Run a single test (case/suite/routine) only?
function Test_Name (Info : Parameter_Info) return String;
-- Return the name of the test passed as a parameter.
function Result_Dir (Info : Parameter_Info) return String;
-- Return the directory for XML results.
function Timeout (Info : Parameter_Info) return Framework.Test_Duration;
-- Return the timeout value for a test.
private
type Parameter_Info is record
Verbose_Output : Boolean := True;
Xml_Output : Boolean := False;
Capture_Output : Boolean := False;
Test_Name : Natural := 0;
-- Position of test name in the argument array
Result_Dir : Natural := 0;
-- Position of results dir in the argument array
Timeout : Framework.Test_Duration := 0.0;
end record;
end Ahven.Parameters;
|
-- SPDX-FileCopyrightText: 2019 Max Reznik <reznikmm@gmail.com>
--
-- SPDX-License-Identifier: MIT
-------------------------------------------------------------
with Anagram.Grammars.LR_Parsers;
with Program.Parsers.Nodes;
with Program.Parsers.Data;
with Program.Parsers.On_Reduce;
package body Program.Parsers is
procedure Next_Token
(Self : access Parse_Context;
Token : out Anagram.Grammars.Terminal_Count;
Value : out Program.Parsers.Nodes.Node);
procedure Do_Parse is new Anagram.Grammars.LR_Parsers.Parse
(Node => Program.Parsers.Nodes.Node,
Node_Array => Program.Parsers.Nodes.Node_Array,
Lexer => Parse_Context,
Parser => Parse_Context,
Next_Token => Next_Token,
Next_Action => Program.Parsers.Data.Next_Action,
Go_To => Program.Parsers.Data.Go_To,
On_Reduce => Program.Parsers.On_Reduce);
use all type Program.Lexical_Elements.Lexical_Element_Kind;
Map : constant array (Program.Lexical_Elements.Lexical_Element_Kind)
of Anagram.Grammars.Terminal_Count :=
(Error => 0,
End_Of_Input => 0,
Abort_Keyword => 1,
Abs_Keyword => 2,
Abstract_Keyword => 3,
Accept_Keyword => 4,
Access_Keyword => 5,
Aliased_Keyword => 6,
All_Keyword => 7,
Ampersand => 8,
And_Keyword => 9,
Apostrophe => 10,
Array_Keyword => 11,
Arrow => 12,
Assignment => 13,
At_Keyword => 14,
Begin_Keyword => 15,
Body_Keyword => 16,
Box => 17,
Case_Keyword => 18,
Character_Literal => 19,
Colon => 20,
Comma => 21,
Comment => 22,
Constant_Keyword => 23,
Declare_Keyword => 24,
Delay_Keyword => 25,
Delta_Keyword => 26,
Digits_Keyword => 27,
Do_Keyword => 28,
Dot => 29,
Double_Dot => 30,
Double_Star => 31,
Else_Keyword => 32,
Elsif_Keyword => 33,
End_Keyword => 34,
Entry_Keyword => 35,
Equal => 36,
Exception_Keyword => 37,
Exit_Keyword => 38,
For_Keyword => 39,
Function_Keyword => 40,
Generic_Keyword => 41,
Goto_Keyword => 42,
Greater_Or_Equal => 43,
Greater => 44,
Hyphen => 45,
Identifier => 46,
If_Keyword => 47,
In_Keyword => 48,
Inequality => 49,
Interface_Keyword => 50,
Is_Keyword => 51,
Left_Label => 52,
Left_Parenthesis => 53,
Less_Or_Equal => 54,
Less => 55,
Limited_Keyword => 56,
Loop_Keyword => 57,
Mod_Keyword => 58,
New_Keyword => 59,
Not_Keyword => 60,
Null_Keyword => 61,
Numeric_Literal => 62,
Of_Keyword => 63,
Or_Keyword => 64,
Others_Keyword => 65,
Out_Keyword => 66,
Overriding_Keyword => 67,
Package_Keyword => 68,
Plus => 69,
Pragma_Keyword => 70,
Private_Keyword => 71,
Procedure_Keyword => 72,
Protected_Keyword => 73,
Raise_Keyword => 74,
Range_Keyword => 75,
Record_Keyword => 76,
Rem_Keyword => 77,
Renames_Keyword => 78,
Requeue_Keyword => 79,
Return_Keyword => 80,
Reverse_Keyword => 81,
Right_Label => 82,
Right_Parenthesis => 83,
Select_Keyword => 84,
Semicolon => 85,
Separate_Keyword => 86,
Slash => 87,
Some_Keyword => 88,
Star => 89,
String_Literal => 90,
Subtype_Keyword => 91,
Synchronized_Keyword => 92,
Tagged_Keyword => 93,
Task_Keyword => 94,
Terminate_Keyword => 95,
Then_Keyword => 96,
Type_Keyword => 97,
Until_Keyword => 98,
Use_Keyword => 99,
Vertical_Line => 100,
When_Keyword => 101,
While_Keyword => 102,
With_Keyword => 103,
Xor_Keyword => 104);
----------------
-- Next_Token --
----------------
procedure Next_Token
(Self : access Parse_Context;
Token : out Anagram.Grammars.Terminal_Count;
Value : out Program.Parsers.Nodes.Node)
is
Next : Program.Lexical_Elements.Lexical_Element_Access;
Kind : Program.Lexical_Elements.Lexical_Element_Kind;
begin
if Self.Index <= Self.Tokens.Last_Index then
Next := Self.Tokens.Element (Self.Index);
Kind := Next.Kind;
Token := Map (Kind);
Value := Self.Factory.Token (Next);
Self.Index := Self.Index + 1;
else
Token := 0;
Value := Program.Parsers.Nodes.No_Token;
end if;
end Next_Token;
-----------
-- Parse --
-----------
procedure Parse
(Compilation : not null Program.Compilations.Compilation_Access;
Tokens : not null Lexical_Elements.Lexical_Element_Vector_Access;
Subpool : not null System.Storage_Pools.Subpools.Subpool_Handle;
Units : out Unit_Vectors.Vector;
Pragmas : out Element_Vectors.Vector;
Standard : Boolean)
is
Factory : aliased Program.Parsers.Nodes.Node_Factory
(Compilation, Subpool, Standard);
Context : aliased Parse_Context :=
(Factory => Factory'Unchecked_Access,
Tokens => Tokens,
Index => 1);
Root : Program.Parsers.Nodes.Node;
Ok : Boolean;
begin
Do_Parse (Context'Access, Context'Access, Root, Ok);
if Ok then
Program.Parsers.Nodes.Get_Compilation_Units
(Root, Units, Pragmas);
else
raise Constraint_Error with "Parsing error";
end if;
end Parse;
end Program.Parsers;
|
--
-- The author disclaims copyright to this source code. In place of
-- a legal notice, here is a blessing:
--
-- May you do good and not evil.
-- May you find forgiveness for yourself and forgive others.
-- May you share freely, not taking more than you give.
--
package body Symbols is
function "<" (Left : in Symbol_Record;
Right : in Symbol_Record)
return Boolean
is
use type Types.Symbol_Index;
function Value_Of (Item : in Symbol_Record) return Integer;
function Value_Of (Item : in Symbol_Record) return Integer
is
Kind : constant Symbol_Kind := Item.Kind;
Name : constant String := To_String (Item.Name);
Char : constant Character := Name (Name'First);
begin
if Kind = Multi_Terminal then
return 3;
elsif Char > 'Z' then
return 2;
else
return 1;
end if;
end Value_Of;
I_Left : constant Integer := Value_Of (Left);
I_Right : constant Integer := Value_Of (Right);
begin
if I_Left = I_Right then
return Left.Index - Right.Index > 0;
else
return I_Left - I_Right > 0;
end if;
end "<";
procedure Symbol_Init is
begin
null;
end Symbol_Init;
-- Return an array of pointers to all data in the table.
-- The array is obtained from malloc. Return NULL if memory allocation
-- problems, or if the array is empty.
procedure Symbol_Allocate (Count : in Ada.Containers.Count_Type) is
begin
-- Symbol_Lists (Ada.Containers.Doubly_Linked_Lists) does not nave
-- operation for setting length or capacity
-- Symbol_Maps (Ada.Containers.Ordered_Maps does not nave
-- operation for setting length or capacity
null;
-- Symbol_Lists.Set_Length (Extra.Symbol_Vector, Count);
-- Symbol_Maps.
-- Extras.Symbol_Map := Symbols_Maps.Empty_Map;
-- for Index in
-- Symbol_Vectors.First (Extra.Symbol_Vector) ..
-- Symbol_Vectors.Last (Extra.Symbol_Vector)
-- loop
-- Symbol_Maps.Replace_Element (Extras.Symbol_Map,
-- end loop;
end Symbol_Allocate;
-- 2019-09-06 JQ
-- Simply try to make a vector for symbols
package Symbol_Bases is
new Ada.Containers.Vectors (Index_Type => Types.Symbol_Index,
Element_Type => Symbol_Access);
Base : Symbol_Bases.Vector;
procedure Count_Symbols_And_Terminals (Symbol_Count : out Natural;
Terminal_Count : out Natural)
is
use Types;
Index : Symbol_Index;
begin
Symbol_Count := Natural'First;
Terminal_Count := Natural'First;
-- Sequential index of symbols
Index := 0;
for Symbol of Base loop
Symbol.all.Index := Index;
Index := Index + 1;
end loop;
while Base (Index - 1).all.Kind = Multi_Terminal loop
Index := Index - 1;
end loop;
pragma Assert (To_String (Base (Index - 1).Name) = "{default}");
Symbol_Count := Natural (Index - 1);
Index := 1;
while
To_String (Base (Index).all.Name) (1) in 'A' .. 'Z'
loop
Index := Index + 1;
end loop;
Terminal_Count := Natural (Index);
end Count_Symbols_And_Terminals;
function Create (Name : in String)
return Symbol_Access
is
Symbol : Symbol_Access := Find (Name);
begin
if Symbol = null then
Symbol := new Symbol_Record;
Symbol.Name := To_Unbounded_String (Name);
if Name (Name'First) in 'A' .. 'Z' then
Symbol.Kind := Terminal;
else
Symbol.Kind := Non_Terminal;
end if;
Symbol.Rule := null;
Symbol.Fallback := null;
Symbol.Precedence := -1;
Symbol.Association := Unknown_Association;
Symbol.First_Set := Symbol_Sets.Null_Set;
Symbol.Lambda := False;
Symbol.Destructor := Null_Unbounded_String;
Symbol.Dest_Lineno := 0;
Symbol.Data_Type := Null_Unbounded_String;
Symbol.Use_Count := 0;
Symbol_Bases.Append (Base, Symbol);
end if;
Symbol.Use_Count := Symbol.Use_Count + 1;
return Symbol;
end Create;
function Find (Name : in String)
return Symbol_Access
is
begin
for Symbol of Base loop
if Symbol.all.Name = Name then
return Symbol;
end if;
end loop;
return null;
end Find;
function Symbol_Compare (Left : in Symbol_Access;
Right : in Symbol_Access)
return Boolean;
function Symbol_Compare (Left : in Symbol_Access;
Right : in Symbol_Access)
return Boolean
is
use Types;
L : Symbol_Record renames Left.all;
R : Symbol_Record renames Right.all;
L_I : constant Integer
:= (if L.Kind = Multi_Terminal then 3 else
(if To_String (L.Name) (1) > 'Z' then 2 else 1));
R_I : constant Integer
:= (if R.Kind = Multi_Terminal then 3 else
(if To_String (R.Name) (1) > 'Z' then 2 else 1));
begin
if L_I = R_I then
return L.Index < R.Index;
else
return L_I < R_I;
end if;
end Symbol_Compare;
package Symbol_Sorting is
new Symbol_Bases.Generic_Sorting (Symbol_Compare);
procedure Sort
is
use Types;
Index : Symbol_Index;
begin
-- Set index field in symbols in symbol table
Index := 0;
for Symbol of Base loop
Symbol.all.Index := Index;
Index := Index + 1;
end loop;
Symbol_Sorting.Sort (Base);
end Sort;
procedure Set_Lambda_False_And_Set_Firstset (First : in Natural;
Last : in Natural)
is
begin
for Symbol of Base loop
Symbol.Lambda := False;
end loop;
for I in First .. Last loop
declare
Symbol : constant Symbol_Access := Base.Element (Symbol_Index (I));
begin
Symbol.all.First_Set := Symbol_Sets.Set_New;
Base (Symbol_Index (I)) := Symbol;
end;
end loop;
end Set_Lambda_False_And_Set_Firstset;
function Last_Index return Types.Symbol_Index is
begin
return Base.Last_Index;
end Last_Index;
function Element_At (Index : in Types.Symbol_Index) return Symbol_Access
is
begin
return Base.Element (Index);
end Element_At;
end Symbols;
|
-- Copyright (c) 2021 Bartek thindil Jasicki <thindil@laeran.pl>
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
with Tcl; use Tcl;
-- ****h* CalculatorCommands/CalculatorCommands
-- FUNCTION
-- Provide various Tcl commands related to the calculator demo
-- SOURCE
package CalculatorCommands with
SPARK_Mode
is
-- ****
private
-- ****f* CalculatorCommands/CalculatorCommands.Click_Action
-- FUNCTION
-- Update display with the pressed button text or count its expression if
-- button equal was pressed. It is moved from On_Click function so it can
-- be checked by SPARK
-- PARAMETERS
-- ButtonName - The Tk path name of the button which was clicked
-- LabelName - The Tk path name of the display label
-- Interpreter - The Tcl interpreter on which the button was clicked
-- RESULT
-- This function always return TCL_OK
-- SOURCE
function Click_Action
(ButtonName, LabelName: String; Interpreter: Tcl_Interpreter)
return Tcl_Results;
-- ****
-- ****f* CalculatorCommands/CalculatorCommands.Clear_Action
-- FUNCTION
-- Reset the calculator's display to it inital state. Show just zero
-- number. It is moved from On_Click function so it can be checked by SPARK
-- PARAMETERS
-- LabelName - The name of display label to clear
-- Interpreter - The Tcl interpreter on which the button was clicked
-- RESULT
-- This function always return TCL_OK
-- SOURCE
function Clear_Action
(LabelName: String; Interpreter: Tcl_Interpreter) return Tcl_Results;
-- ****
end CalculatorCommands;
|
-- 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.Directories; use Ada.Directories;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with GNAT.String_Split; use GNAT.String_Split;
with Tcl; use Tcl;
with Tcl.Ada; use Tcl.Ada;
with Tcl.Tk.Ada; use Tcl.Tk.Ada;
with Tcl.Tk.Ada.Grid;
with Tcl.Tk.Ada.Widgets.Text; use Tcl.Tk.Ada.Widgets.Text;
with Tcl.Tk.Ada.Widgets.Menu; use Tcl.Tk.Ada.Widgets.Menu;
with Tcl.Tk.Ada.Widgets.TtkButton; use Tcl.Tk.Ada.Widgets.TtkButton;
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.TtkEntry.TtkSpinBox;
use Tcl.Tk.Ada.Widgets.TtkEntry.TtkSpinBox;
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.TtkPanedWindow; use Tcl.Tk.Ada.Widgets.TtkPanedWindow;
with Tcl.Tk.Ada.Widgets.TtkScrollbar; use Tcl.Tk.Ada.Widgets.TtkScrollbar;
with Tcl.Tk.Ada.Winfo; use Tcl.Tk.Ada.Winfo;
with Bases; use Bases;
with Combat.UI; use Combat.UI;
with Config; use Config;
with CoreUI; use CoreUI;
with Crew; use Crew;
with Dialogs; use Dialogs;
with Events; use Events;
with Factions; use Factions;
with Maps; use Maps;
with Maps.UI; use Maps.UI;
with MainMenu; use MainMenu;
with Messages; use Messages;
with Missions; use Missions;
with Ships.Cargo; use Ships.Cargo;
with Ships.Crew; use Ships.Crew;
with Ships.Movement; use Ships.Movement;
with Ships.UI.Crew; use Ships.UI.Crew;
with Ships.UI.Modules; use Ships.UI.Modules;
with Statistics.UI; use Statistics.UI;
package body Utils.UI is
procedure Add_Command
(Name: String; Ada_Command: not null CreateCommands.Tcl_CmdProc) is
Command: Tcl.Tcl_Command;
Steam_Sky_Add_Command_Error: exception;
begin
Tcl_Eval(interp => Get_Context, strng => "info commands " & Name);
if Tcl_GetResult(interp => Get_Context) /= "" then
raise Steam_Sky_Add_Command_Error
with "Command with name " & Name & " exists";
end if;
Command :=
CreateCommands.Tcl_CreateCommand
(interp => Get_Context, cmdName => Name, proc => Ada_Command,
data => 0, deleteProc => null);
if Command = null then
raise Steam_Sky_Add_Command_Error with "Can't add command " & Name;
end if;
end Add_Command;
-- ****o* UUI/UUI.Resize_Canvas_Command
-- PARAMETERS
-- Resize the selected canvas
-- Client_Data - 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
-- ResizeCanvas name width height
-- Name is the name of the canvas to resize, width it a new width, height
-- is a new height
-- SOURCE
function Resize_Canvas_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Resize_Canvas_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
Canvas: constant Ttk_Frame :=
Get_Widget
(pathName => CArgv.Arg(Argv => Argv, N => 1), Interp => Interp);
Parent_Frame: Ttk_Frame;
begin
if Winfo_Get(Widgt => Canvas, Info => "exists") = "0" then
return TCL_OK;
end if;
Parent_Frame :=
Get_Widget
(pathName => Winfo_Get(Widgt => Canvas, Info => "parent"),
Interp => Interp);
Unbind(Widgt => Parent_Frame, Sequence => "<Configure>");
Widgets.configure
(Widgt => Canvas,
options =>
"-width " & CArgv.Arg(Argv => Argv, N => 2) & " -height [expr " &
CArgv.Arg(Argv => Argv, N => 3) & " - 20]");
Bind
(Widgt => Parent_Frame, Sequence => "<Configure>",
Script => "{ResizeCanvas %W.canvas %w %h}");
return TCL_OK;
end Resize_Canvas_Command;
-- ****o* UUI/UUI.Check_Amount_Command
-- PARAMETERS
-- Check amount of the item, if it is not below low level warning or if
-- entered amount is a proper number
-- 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
-- CheckAmount name cargoindex value
-- Name is the name of spinbox which value will be checked, cargoindex is
-- the index of the item in the cargo
-- SOURCE
function Check_Amount_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Check_Amount_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data);
Cargo_Index: constant Natural :=
Natural'Value(CArgv.Arg(Argv => Argv, N => 2));
Warning_Text: Unbounded_String := Null_Unbounded_String;
Amount: Integer := 0;
Label: Ttk_Label :=
Get_Widget(pathName => ".itemdialog.errorlbl", Interp => Interp);
Value: Integer := 0;
Spin_Box: constant Ttk_SpinBox :=
Get_Widget
(pathName => CArgv.Arg(Argv => Argv, N => 1), Interp => Interp);
Max_Value: constant Positive :=
Positive'Value(Widgets.cget(Widgt => Spin_Box, option => "-to"));
begin
if CArgv.Arg(Argv => Argv, N => 3)'Length > 0 then
Check_Argument_Loop :
for Char of CArgv.Arg(Argv => Argv, N => 3) loop
if not Is_Decimal_Digit(Item => Char) then
Tcl_SetResult(interp => Interp, str => "0");
return TCL_OK;
end if;
end loop Check_Argument_Loop;
Value := Integer'Value(CArgv.Arg(Argv => Argv, N => 3));
end if;
if CArgv.Arg(Argv => Argv, N => 1) = ".itemdialog.giveamount" then
Warning_Text :=
To_Unbounded_String
(Source => "You will give amount below low level of ");
else
Warning_Text :=
To_Unbounded_String
(Source =>
"You will " & CArgv.Arg(Argv => Argv, N => 4) &
" amount below low level of ");
end if;
if Value < 1 then
Set(SpinBox => Spin_Box, Value => "1");
Value := 1;
elsif Value > Max_Value then
Set(SpinBox => Spin_Box, Value => Positive'Image(Max_Value));
Value := Max_Value;
end if;
if Argc > 4 then
if CArgv.Arg(Argv => Argv, N => 4) = "take" then
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
elsif CArgv.Arg(Argv => Argv, N => 4) in "buy" | "sell" then
Set_Price_Info_Block :
declare
Cost: Natural :=
Value * Positive'Value(CArgv.Arg(Argv => Argv, N => 5));
begin
Label :=
Get_Widget
(pathName => ".itemdialog.costlbl", Interp => Interp);
Count_Price
(Price => Cost, Trader_Index => FindMember(Order => Talk),
Reduce =>
(if CArgv.Arg(Argv => Argv, N => 4) = "buy" then True
else False));
configure
(Widgt => Label,
options =>
"-text {" &
(if CArgv.Arg(Argv => Argv, N => 4) = "buy" then "Cost:"
else "Gain:") &
Natural'Image(Cost) & " " &
To_String(Source => Money_Name) & "}");
if CArgv.Arg(Argv => Argv, N => 4) = "buy" then
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
end if;
end Set_Price_Info_Block;
end if;
end if;
Label :=
Get_Widget(pathName => ".itemdialog.errorlbl", Interp => Interp);
if Items_List(Player_Ship.Cargo(Cargo_Index).ProtoIndex).IType =
Fuel_Type then
Amount := GetItemAmount(ItemType => Fuel_Type) - Value;
if Amount <= Game_Settings.Low_Fuel then
Widgets.configure
(Widgt => Label,
options =>
"-text {" & To_String(Source => Warning_Text) & "fuel.}");
Tcl.Tk.Ada.Grid.Grid(Slave => Label);
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
end if;
end if;
Check_Food_And_Drinks_Loop :
for Member of Player_Ship.Crew loop
if Factions_List(Member.Faction).DrinksTypes.Contains
(Item =>
Items_List(Player_Ship.Cargo(Cargo_Index).ProtoIndex)
.IType) then
Amount := GetItemsAmount(IType => "Drinks") - Value;
if Amount <= Game_Settings.Low_Drinks then
Widgets.configure
(Widgt => Label,
options =>
"-text {" & To_String(Source => Warning_Text) &
"drinks.}");
Tcl.Tk.Ada.Grid.Grid(Slave => Label);
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
end if;
exit Check_Food_And_Drinks_Loop;
elsif Factions_List(Member.Faction).FoodTypes.Contains
(Item =>
Items_List(Player_Ship.Cargo(Cargo_Index).ProtoIndex)
.IType) then
Amount := GetItemsAmount(IType => "Food") - Value;
if Amount <= Game_Settings.Low_Food then
Widgets.configure
(Widgt => Label,
options =>
"-text {" & To_String(Source => Warning_Text) & "food.}");
Tcl.Tk.Ada.Grid.Grid(Slave => Label);
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
end if;
exit Check_Food_And_Drinks_Loop;
end if;
end loop Check_Food_And_Drinks_Loop;
Tcl.Tk.Ada.Grid.Grid_Remove(Slave => Label);
Tcl_SetResult(interp => Interp, str => "1");
return TCL_OK;
exception
when Constraint_Error =>
Tcl_SetResult(interp => Interp, str => "0");
return TCL_OK;
end Check_Amount_Command;
-- ****o* UUI/UUI.Validate_Amount_Command
-- PARAMETERS
-- Validate amount of the item when button to increase or decrease the
-- amount was pressed
-- ClientData - Custom data send to the command.
-- 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
-- ValidateAmount name
-- Name is the name of spinbox which value will be validated
-- SOURCE
function Validate_Amount_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Validate_Amount_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
Spin_Box: constant Ttk_SpinBox :=
Get_Widget
(pathName => CArgv.Arg(Argv => Argv, N => 1), Interp => Interp);
New_Argv: constant CArgv.Chars_Ptr_Ptr :=
(if Argc < 4 then Argv & Get(Widgt => Spin_Box)
elsif Argc = 4 then
CArgv.Empty & CArgv.Arg(Argv => Argv, N => 0) &
CArgv.Arg(Argv => Argv, N => 1) & CArgv.Arg(Argv => Argv, N => 2) &
Get(Widgt => Spin_Box) & CArgv.Arg(Argv => Argv, N => 3)
else CArgv.Empty & CArgv.Arg(Argv => Argv, N => 0) &
CArgv.Arg(Argv => Argv, N => 1) & CArgv.Arg(Argv => Argv, N => 2) &
Get(Widgt => Spin_Box) & CArgv.Arg(Argv => Argv, N => 3) &
CArgv.Arg(Argv => Argv, N => 4));
begin
return
Check_Amount_Command
(Client_Data => Client_Data, Interp => Interp,
Argc => CArgv.Argc(Argv => New_Argv), Argv => New_Argv);
end Validate_Amount_Command;
-- ****o* UUI/UUI.Set_Text_Variable_Command
-- FUNCTION
-- Set the selected Tcl text variable and the proper the Ada its equivalent
-- 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
-- SetTextVariable variablename
-- Variablename is the name of variable to set
-- SOURCE
function Set_Text_Variable_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Set_Text_Variable_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
T_Entry: constant Ttk_Entry :=
Get_Widget(pathName => ".getstring.entry", Interp => Interp);
Value: constant String := Get(Widgt => T_Entry);
Var_Name: constant String := CArgv.Arg(Argv => Argv, N => 1);
begin
Tcl_SetVar(interp => Interp, varName => Var_Name, newValue => Value);
if Var_Name = "shipname" then
Player_Ship.Name := To_Unbounded_String(Source => Value);
elsif Var_Name'Length > 10 and then Var_Name(1 .. 10) = "modulename" then
Rename_Module_Block :
declare
Module_Index: constant Positive :=
Positive'Value(Var_Name(11 .. Var_Name'Last));
begin
Player_Ship.Modules(Module_Index).Name :=
To_Unbounded_String(Source => Value);
Tcl_UnsetVar(interp => Interp, varName => Var_Name);
UpdateModulesInfo;
end Rename_Module_Block;
elsif Var_Name'Length > 8 and then Var_Name(1 .. 8) = "crewname" then
Rename_Crew_Member_Block :
declare
Crew_Index: constant Positive :=
Positive'Value(Var_Name(9 .. Var_Name'Last));
begin
Player_Ship.Crew(Crew_Index).Name :=
To_Unbounded_String(Source => Value);
Tcl_UnsetVar(interp => Interp, varName => Var_Name);
UpdateCrewInfo;
end Rename_Crew_Member_Block;
end if;
return TCL_OK;
end Set_Text_Variable_Command;
-- ****o* UUI/UUI.Process_Question_Command
-- FUNCTION
-- Process question from dialog when the player answer Yes there
-- 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
-- ProcessQuestion answer
-- Answer is the answer set for the selected question
-- SOURCE
function Process_Question_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Process_Question_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
Result: constant String := CArgv.Arg(Argv => Argv, N => 1);
begin
if Result = "deletesave" then
Delete_File
(Name =>
To_String
(Source =>
Save_Directory &
Tcl_GetVar(interp => Interp, varName => "deletesave")));
Tcl_UnsetVar(interp => Interp, varName => "deletesave");
Tcl_Eval(interp => Interp, strng => "ShowLoadGame");
elsif Result = "sethomebase" then
Set_Home_Base_Block :
declare
Trader_Index: constant Natural := FindMember(Order => Talk);
Price: Positive := 1_000;
Money_Index2: constant Natural :=
FindItem
(Inventory => Player_Ship.Cargo, ProtoIndex => Money_Index);
begin
if Money_Index2 = 0 then
ShowMessage
(Text =>
"You don't have any " & To_String(Source => Money_Name) &
" for change ship home base.",
Title => "No money");
return TCL_OK;
end if;
Count_Price(Price => Price, Trader_Index => Trader_Index);
if Player_Ship.Cargo(Money_Index2).Amount < Price then
ShowMessage
(Text =>
"You don't have enough " &
To_String(Source => Money_Name) &
" for change ship home base.",
Title => "No money");
return TCL_OK;
end if;
Player_Ship.Home_Base :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex;
UpdateCargo
(Ship => Player_Ship, CargoIndex => Money_Index2,
Amount => -Price);
AddMessage
(Message =>
"You changed your ship home base to: " &
To_String(Source => Sky_Bases(Player_Ship.Home_Base).Name),
MType => OtherMessage);
GainExp
(Amount => 1, SkillNumber => Talking_Skill,
CrewIndex => Trader_Index);
Update_Game(Minutes => 10);
ShowSkyMap;
end Set_Home_Base_Block;
elsif Result = "nopilot" then
WaitForRest;
Check_For_Combat_Block :
declare
Starts_Combat: constant Boolean := CheckForEvent;
Message: Unbounded_String := Null_Unbounded_String;
begin
if not Starts_Combat and Game_Settings.Auto_Finish then
Message := To_Unbounded_String(Source => AutoFinishMissions);
end if;
if Message /= Null_Unbounded_String then
ShowMessage
(Text => To_String(Source => Message), Title => "Error");
end if;
CenterX := Player_Ship.Sky_X;
CenterY := Player_Ship.Sky_Y;
if Starts_Combat then
ShowCombatUI;
else
ShowSkyMap;
end if;
end Check_For_Combat_Block;
elsif Result = "quit" then
Game_Settings.Messages_Position :=
Game_Settings.Window_Height -
Natural'Value(SashPos(Paned => Main_Paned, Index => "0"));
End_Game(Save => True);
Show_Main_Menu;
elsif Result = "resign" then
Death
(MemberIndex => 1,
Reason => To_Unbounded_String(Source => "resignation"),
Ship => Player_Ship);
ShowQuestion
(Question =>
"You are dead. Would you like to see your game statistics?",
Result => "showstats");
elsif Result = "showstats" then
Show_Game_Stats_Block :
declare
Button: constant Ttk_Button :=
Get_Widget(pathName => Game_Header & ".menubutton");
begin
Tcl.Tk.Ada.Grid.Grid(Slave => Button);
Widgets.configure
(Widgt => Close_Button, options => "-command ShowMainMenu");
Tcl.Tk.Ada.Grid.Grid
(Slave => Close_Button, Options => "-row 0 -column 1");
Delete(MenuWidget => GameMenu, StartIndex => "3", EndIndex => "4");
Delete
(MenuWidget => GameMenu, StartIndex => "6", EndIndex => "14");
ShowStatistics;
end Show_Game_Stats_Block;
elsif Result = "mainmenu" then
Game_Settings.Messages_Position :=
Game_Settings.Window_Height -
Natural'Value(SashPos(Paned => Main_Paned, Index => "0"));
End_Game(Save => False);
Show_Main_Menu;
elsif Result = "messages" then
Show_Last_Messages_Block :
declare
Type_Box: constant Ttk_ComboBox :=
Get_Widget
(pathName =>
Main_Paned & ".messagesframe.canvas.messages.options.types",
Interp => Get_Context);
begin
ClearMessages;
Current(ComboBox => Type_Box, NewIndex => "0");
Tcl_Eval(interp => Get_Context, strng => "ShowLastMessages");
end Show_Last_Messages_Block;
elsif Result = "retire" then
Death
(MemberIndex => 1,
Reason =>
To_Unbounded_String(Source => "retired after finished the game"),
Ship => Player_Ship);
ShowQuestion
(Question =>
"You are dead. Would you like to see your game statistics?",
Result => "showstats");
else
Dismiss_Member_Block :
declare
Base_Index: constant Positive :=
SkyMap(Player_Ship.Sky_X, Player_Ship.Sky_Y).BaseIndex;
Member_Index: constant Positive :=
Positive'Value(CArgv.Arg(Argv => Argv, N => 1));
begin
AddMessage
(Message =>
"You dismissed " &
To_String(Source => Player_Ship.Crew(Member_Index).Name) &
".",
MType => OrderMessage);
DeleteMember(MemberIndex => Member_Index, Ship => Player_Ship);
Sky_Bases(Base_Index).Population :=
Sky_Bases(Base_Index).Population + 1;
Update_Morale_Loop :
for I in Player_Ship.Crew.Iterate loop
UpdateMorale
(Ship => Player_Ship,
MemberIndex => Crew_Container.To_Index(Position => I),
Value => Get_Random(Min => -5, Max => -1));
end loop Update_Morale_Loop;
UpdateCrewInfo;
UpdateHeader;
Update_Messages;
end Dismiss_Member_Block;
end if;
return TCL_OK;
end Process_Question_Command;
-- ****o* UUI/UUI.Set_Scrollbar_Bindings_Command
-- FUNCTION
-- Assign scrolling events with mouse wheel to the selected vertical
-- scrollbar from the selected widget
-- 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
-- SetScrollbarBindings widget scrollbar
-- Widget is the widget from which events will be fired, scrollbar is
-- Ttk::scrollbar which to which bindings will be added
-- SOURCE
function Set_Scrollbar_Bindings_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int with
Convention => C;
-- ****
function Set_Scrollbar_Bindings_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
Widget: constant Ttk_Frame :=
Get_Widget
(pathName => CArgv.Arg(Argv => Argv, N => 1), Interp => Interp);
Scrollbar: constant Ttk_Scrollbar :=
Get_Widget
(pathName => CArgv.Arg(Argv => Argv, N => 2), Interp => Interp);
begin
Bind
(Widgt => Widget, Sequence => "<Button-4>",
Script =>
"{if {[winfo ismapped " & Scrollbar & "]} {event generate " &
Scrollbar & " <Button-4>}}");
Bind
(Widgt => Widget, Sequence => "<Key-Prior>",
Script =>
"{if {[winfo ismapped " & Scrollbar & "]} {event generate " &
Scrollbar & " <Button-4>}}");
Bind
(Widgt => Widget, Sequence => "<Button-5>",
Script =>
"{if {[winfo ismapped " & Scrollbar & "]} {event generate " &
Scrollbar & " <Button-5>}}");
Bind
(Widgt => Widget, Sequence => "<Key-Next>",
Script =>
"{if {[winfo ismapped " & Scrollbar & "]} {event generate " &
Scrollbar & " <Button-5>}}");
Bind
(Widgt => Widget, Sequence => "<MouseWheel>",
Script =>
"{if {[winfo ismapped " & Scrollbar & "]} {event generate " &
Scrollbar & " <MouseWheel>}}");
return TCL_OK;
end Set_Scrollbar_Bindings_Command;
function Show_On_Map_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
begin
CenterX := Positive'Value(CArgv.Arg(Argv => Argv, N => 1));
CenterY := Positive'Value(CArgv.Arg(Argv => Argv, N => 2));
Entry_Configure
(MenuWidget => GameMenu, Index => "Help",
Options => "-command {ShowHelp general}");
Tcl_Eval(interp => Interp, strng => "InvokeButton " & Close_Button);
Tcl.Tk.Ada.Grid.Grid_Remove(Slave => Close_Button);
return TCL_OK;
end Show_On_Map_Command;
function Set_Destination_Command
(Client_Data: Integer; Interp: Tcl.Tcl_Interp; Argc: Interfaces.C.int;
Argv: CArgv.Chars_Ptr_Ptr) return Interfaces.C.int is
pragma Unreferenced(Client_Data, Argc);
begin
if Positive'Value(CArgv.Arg(Argv => Argv, N => 1)) =
Player_Ship.Sky_X and
Positive'Value(CArgv.Arg(Argv => Argv, N => 2)) =
Player_Ship.Sky_Y then
ShowMessage
(Text => "You are at this location now.",
Title => "Can't set destination");
return TCL_OK;
end if;
Player_Ship.Destination_X :=
Positive'Value(CArgv.Arg(Argv => Argv, N => 1));
Player_Ship.Destination_Y :=
Positive'Value(CArgv.Arg(Argv => Argv, N => 2));
AddMessage
(Message => "You set the travel destination for your ship.",
MType => OrderMessage);
Entry_Configure
(MenuWidget => GameMenu, Index => "Help",
Options => "-command {ShowHelp general}");
Tcl_Eval(interp => Interp, strng => "InvokeButton " & Close_Button);
Tcl.Tk.Ada.Grid.Grid_Remove(Slave => Close_Button);
return TCL_OK;
end Set_Destination_Command;
procedure Add_Commands is
begin
Add_Command
(Name => "ResizeCanvas", Ada_Command => Resize_Canvas_Command'Access);
Add_Command
(Name => "CheckAmount", Ada_Command => Check_Amount_Command'Access);
Add_Command
(Name => "ValidateAmount",
Ada_Command => Validate_Amount_Command'Access);
Add_Command
(Name => "SetTextVariable",
Ada_Command => Set_Text_Variable_Command'Access);
Add_Command
(Name => "ProcessQuestion",
Ada_Command => Process_Question_Command'Access);
Add_Command
(Name => "SetScrollbarBindings",
Ada_Command => Set_Scrollbar_Bindings_Command'Access);
Add_Command
(Name => "ShowOnMap", Ada_Command => Show_On_Map_Command'Access);
Add_Command
(Name => "SetDestination2",
Ada_Command => Set_Destination_Command'Access);
end Add_Commands;
procedure Minutes_To_Date
(Minutes: Natural; Info_Text: in out Unbounded_String) with
SPARK_Mode
is
Travel_Time: Date_Record := (others => 0);
Minutes_Diff: Integer := Minutes;
begin
Count_Time_Loop :
while Minutes_Diff > 0 loop
pragma Loop_Invariant
(Travel_Time.Year < 4_000_000 and Travel_Time.Month < 13 and
Travel_Time.Day < 32 and Travel_Time.Hour < 24);
case Minutes_Diff is
when 518_401 .. Integer'Last =>
Travel_Time.Year := Travel_Time.Year + 1;
Minutes_Diff := Minutes_Diff - 518_400;
when 43_201 .. 518_400 =>
Travel_Time.Month := Travel_Time.Month + 1;
if Travel_Time.Month > 12 then
Travel_Time.Month := 1;
Travel_Time.Year := Travel_Time.Year + 1;
end if;
Minutes_Diff := Minutes_Diff - 43_200;
when 1_441 .. 43_200 =>
Travel_Time.Day := Travel_Time.Day + 1;
if Travel_Time.Day > 31 then
Travel_Time.Day := 1;
Travel_Time.Month := Travel_Time.Month + 1;
if Travel_Time.Month > 12 then
Travel_Time.Month := 1;
Travel_Time.Year := Travel_Time.Year + 1;
end if;
end if;
Minutes_Diff := Minutes_Diff - 1_440;
when 61 .. 1_440 =>
Travel_Time.Hour := Travel_Time.Hour + 1;
if Travel_Time.Hour > 23 then
Travel_Time.Hour := 0;
Travel_Time.Day := Travel_Time.Day + 1;
if Travel_Time.Day > 31 then
Travel_Time.Day := 1;
Travel_Time.Month := Travel_Time.Month + 1;
if Travel_Time.Month > 12 then
Travel_Time.Month := 1;
Travel_Time.Year := Travel_Time.Year + 1;
end if;
end if;
end if;
Minutes_Diff := Minutes_Diff - 60;
when others =>
Travel_Time.Minutes := Minutes_Diff;
Minutes_Diff := 0;
end case;
exit Count_Time_Loop when Travel_Time.Year = 4_000_000;
end loop Count_Time_Loop;
if Travel_Time.Year > 0
and then Length(Source => Info_Text) <
Natural'Last - (Positive'Image(Travel_Time.Year)'Length + 1) then
Append
(Source => Info_Text,
New_Item => Positive'Image(Travel_Time.Year) & "y");
end if;
if Travel_Time.Month > 0
and then Length(Source => Info_Text) <
Natural'Last - (Positive'Image(Travel_Time.Month)'Length + 1) then
Append
(Source => Info_Text,
New_Item => Positive'Image(Travel_Time.Month) & "m");
end if;
if Travel_Time.Day > 0
and then Length(Source => Info_Text) <
Natural'Last - (Positive'Image(Travel_Time.Day)'Length + 1) then
Append
(Source => Info_Text,
New_Item => Positive'Image(Travel_Time.Day) & "d");
end if;
if Travel_Time.Hour > 0
and then Length(Source => Info_Text) <
Natural'Last - (Positive'Image(Travel_Time.Hour)'Length + 1) then
Append
(Source => Info_Text,
New_Item => Positive'Image(Travel_Time.Hour) & "h");
end if;
if Travel_Time.Minutes > 0
and then Length(Source => Info_Text) <
Natural'Last - (Positive'Image(Travel_Time.Minutes)'Length + 4) then
Append
(Source => Info_Text,
New_Item => Positive'Image(Travel_Time.Minutes) & "mins");
end if;
end Minutes_To_Date;
procedure Travel_Info
(Info_Text: in out Unbounded_String; Distance: Positive;
Show_Fuel_Name: Boolean := False) is
type Speed_Type is digits 2;
Speed: constant Speed_Type :=
Speed_Type(RealSpeed(Ship => Player_Ship, InfoOnly => True)) / 1_000.0;
Minutes_Diff: Integer;
Rests, Cabin_Index, Rest_Time, Tired, Cabin_Bonus, Temp_Time: Natural :=
0;
Damage: Damage_Factor := 0.0;
begin
if Speed = 0.0 then
Append(Source => Info_Text, New_Item => LF & "ETA: Never");
return;
end if;
Minutes_Diff := Integer(100.0 / Speed);
case Player_Ship.Speed is
when QUARTER_SPEED =>
if Minutes_Diff < 60 then
Minutes_Diff := 60;
end if;
when HALF_SPEED =>
if Minutes_Diff < 30 then
Minutes_Diff := 30;
end if;
when FULL_SPEED =>
if Minutes_Diff < 15 then
Minutes_Diff := 15;
end if;
when others =>
null;
end case;
Append(Source => Info_Text, New_Item => LF & "ETA:");
Minutes_Diff := Minutes_Diff * Distance;
Count_Rest_Time_Loop :
for I in Player_Ship.Crew.Iterate loop
if Player_Ship.Crew(I).Order not in Pilot | Engineer then
goto End_Of_Count_Loop;
end if;
Tired := (Minutes_Diff / 15) + Player_Ship.Crew(I).Tired;
if
(Tired /
(80 +
Player_Ship.Crew(I).Attributes(Integer(Condition_Index)).Level)) >
Rests then
Rests :=
(Tired /
(80 +
Player_Ship.Crew(I).Attributes(Integer(Condition_Index))
.Level));
end if;
if Rests > 0 then
Cabin_Index :=
FindCabin(MemberIndex => Crew_Container.To_Index(Position => I));
if Cabin_Index > 0 then
Damage :=
1.0 -
Damage_Factor
(Float(Player_Ship.Modules(Cabin_Index).Durability) /
Float(Player_Ship.Modules(Cabin_Index).Max_Durability));
Cabin_Bonus :=
Player_Ship.Modules(Cabin_Index).Cleanliness -
Natural
(Float(Player_Ship.Modules(Cabin_Index).Cleanliness) *
Float(Damage));
if Cabin_Bonus = 0 then
Cabin_Bonus := 1;
end if;
Temp_Time :=
((80 +
Player_Ship.Crew(I).Attributes(Integer(Condition_Index))
.Level) /
Cabin_Bonus) *
15;
if Temp_Time = 0 then
Temp_Time := 15;
end if;
else
Temp_Time :=
(80 +
Player_Ship.Crew(I).Attributes(Integer(Condition_Index))
.Level) *
15;
end if;
Temp_Time := Temp_Time + 15;
if Temp_Time > Rest_Time then
Rest_Time := Temp_Time;
end if;
end if;
<<End_Of_Count_Loop>>
end loop Count_Rest_Time_Loop;
Minutes_Diff := Minutes_Diff + (Rests * Rest_Time);
Minutes_To_Date(Minutes => Minutes_Diff, Info_Text => Info_Text);
Append
(Source => Info_Text,
New_Item =>
LF & "Approx fuel usage:" &
Natural'Image
(abs (Distance * CountFuelNeeded) + (Rests * (Rest_Time / 10))) &
" ");
if Show_Fuel_Name then
Append
(Source => Info_Text,
New_Item => Items_List(FindProtoItem(ItemType => Fuel_Type)).Name);
end if;
end Travel_Info;
procedure Update_Messages with
SPARK_Mode
is
Loop_Start: Integer := 0 - MessagesAmount;
Message: Message_Data;
Tag_Names: constant array(1 .. 5) of Unbounded_String :=
(1 => To_Unbounded_String(Source => "yellow"),
2 => To_Unbounded_String(Source => "green"),
3 => To_Unbounded_String(Source => "red"),
4 => To_Unbounded_String(Source => "blue"),
5 => To_Unbounded_String(Source => "cyan"));
Messages_View: constant Tk_Text :=
Get_Widget(pathName => ".gameframe.paned.controls.messages.view");
procedure Show_Message is
begin
if Message.Color = WHITE then
Insert
(TextWidget => Messages_View, Index => "end",
Text => "{" & To_String(Source => Message.Message) & "}");
else
Insert
(TextWidget => Messages_View, Index => "end",
Text =>
"{" & To_String(Source => Message.Message) & "} [list " &
To_String
(Source => Tag_Names(Message_Color'Pos(Message.Color))) &
"]");
end if;
end Show_Message;
begin
Tcl.Tk.Ada.Widgets.configure
(Widgt => Messages_View, options => "-state normal");
Delete
(TextWidget => Messages_View, StartIndex => "1.0", Indexes => "end");
if Loop_Start = 0 then
return;
end if;
if Loop_Start < -10 then
Loop_Start := -10;
end if;
if Game_Settings.Messages_Order = OLDER_FIRST then
Show_Older_First_Loop :
for I in Loop_Start .. -1 loop
Message := GetMessage(MessageIndex => I + 1);
Show_Message;
if I < -1 then
Insert
(TextWidget => Messages_View, Index => "end",
Text => "{" & LF & "}");
end if;
end loop Show_Older_First_Loop;
Tcl_Eval(interp => Get_Context, strng => "update");
See(TextWidget => Messages_View, Index => "end");
else
Show_Newer_First_Loop :
for I in reverse Loop_Start .. -1 loop
Message := GetMessage(MessageIndex => I + 1);
Show_Message;
if I > Loop_Start then
Insert
(TextWidget => Messages_View, Index => "end",
Text => "{" & LF & "}");
end if;
end loop Show_Newer_First_Loop;
end if;
Tcl.Tk.Ada.Widgets.configure
(Widgt => Messages_View, options => "-state disable");
end Update_Messages;
procedure Show_Screen(New_Screen_Name: String) with
SPARK_Mode
is
Sub_Window, Old_Sub_Window: Ttk_Frame;
Sub_Windows: Unbounded_String;
Messages_Frame: constant Ttk_Frame :=
Get_Widget(pathName => Main_Paned & ".controls.messages");
Paned: constant Ttk_PanedWindow :=
Get_Widget(pathName => Main_Paned & ".controls.buttons");
begin
Sub_Windows := To_Unbounded_String(Source => Panes(Paned => Main_Paned));
Old_Sub_Window :=
(if Index(Source => Sub_Windows, Pattern => " ") = 0 then
Get_Widget(pathName => To_String(Source => Sub_Windows))
else Get_Widget
(pathName =>
Slice
(Source => Sub_Windows, Low => 1,
High => Index(Source => Sub_Windows, Pattern => " "))));
Forget(Paned => Main_Paned, SubWindow => Old_Sub_Window);
Sub_Window.Name :=
New_String(Str => ".gameframe.paned." & New_Screen_Name);
Insert
(Paned => Main_Paned, Position => "0", SubWindow => Sub_Window,
Options => "-weight 1");
if New_Screen_Name in "optionsframe" | "messagesframe" or
not Game_Settings.Show_Last_Messages then
Tcl.Tk.Ada.Grid.Grid_Remove(Slave => Messages_Frame);
if New_Screen_Name /= "mapframe" then
SashPos
(Paned => Main_Paned, Index => "0",
NewPos => Winfo_Get(Widgt => Main_Paned, Info => "height"));
end if;
else
if Trim
(Source => Widget_Image(Win => Old_Sub_Window), Side => Both) in
Main_Paned & ".messagesframe" | Main_Paned & ".optionsframe" then
SashPos
(Paned => Main_Paned, Index => "0",
NewPos =>
Natural'Image
(Game_Settings.Window_Height -
Game_Settings.Messages_Position));
end if;
Tcl.Tk.Ada.Grid.Grid(Slave => Messages_Frame);
end if;
if New_Screen_Name = "mapframe" then
Tcl.Tk.Ada.Grid.Grid(Slave => Paned);
else
Tcl.Tk.Ada.Grid.Grid_Remove(Slave => Paned);
end if;
end Show_Screen;
procedure Show_Inventory_Item_Info
(Parent: String; Item_Index: Positive; Member_Index: Natural) is
Proto_Index, Item_Info: Unbounded_String;
Item_Types: constant array(1 .. 6) of Unbounded_String :=
(1 => Weapon_Type, 2 => Chest_Armor, 3 => Head_Armor, 4 => Arms_Armor,
5 => Legs_Armor, 6 => Shield_Type);
use Tiny_String;
begin
if Member_Index > 0 then
Proto_Index :=
Player_Ship.Crew(Member_Index).Inventory(Item_Index).ProtoIndex;
if Player_Ship.Crew(Member_Index).Inventory(Item_Index).Durability <
Default_Item_Durability then
Append
(Source => Item_Info,
New_Item =>
GetItemDamage
(ItemDurability =>
Player_Ship.Crew(Member_Index).Inventory(Item_Index)
.Durability) &
LF);
end if;
else
Proto_Index := Player_Ship.Cargo(Item_Index).ProtoIndex;
if Player_Ship.Cargo(Item_Index).Durability <
Default_Item_Durability then
Append
(Source => Item_Info,
New_Item =>
GetItemDamage
(ItemDurability =>
Player_Ship.Cargo(Item_Index).Durability) &
LF);
end if;
end if;
Append
(Source => Item_Info,
New_Item =>
"Weight:" & Positive'Image(Items_List(Proto_Index).Weight) & " kg");
if Items_List(Proto_Index).IType = Weapon_Type then
Append
(Source => Item_Info,
New_Item =>
LF & "Skill: " &
To_String
(Source =>
SkillsData_Container.Element
(Container => Skills_List,
Index => Items_List(Proto_Index).Value(3))
.Name) &
"/" &
To_String
(Source =>
AttributesData_Container.Element
(Container => Attributes_List,
Index =>
(SkillsData_Container.Element
(Container => Skills_List,
Index => Items_List(Proto_Index).Value(3))
.Attribute))
.Name));
if Items_List(Proto_Index).Value(4) = 1 then
Append
(Source => Item_Info,
New_Item => LF & "Can be used with shield.");
else
Append
(Source => Item_Info,
New_Item =>
LF & "Can't be used with shield (two-handed weapon).");
end if;
Append
(Source => Item_Info,
New_Item =>
LF & "Damage type: " &
(case Items_List(Proto_Index).Value(5) is when 1 => "cutting",
when 2 => "impaling", when 3 => "blunt", when others => ""));
end if;
Show_More_Item_Info_Loop :
for ItemType of Item_Types loop
if Items_List(Proto_Index).IType = ItemType then
Append
(Source => Item_Info,
New_Item =>
LF & "Damage chance: " & LF & "Strength:" &
Integer'Image(Items_List(Proto_Index).Value(2)));
exit Show_More_Item_Info_Loop;
end if;
end loop Show_More_Item_Info_Loop;
if Tools_List.Contains(Item => Items_List(Proto_Index).IType) then
Append
(Source => Item_Info,
New_Item =>
LF & "Damage chance: " &
GetItemChanceToDamage
(ItemData => Items_List(Proto_Index).Value(1)));
end if;
if Length(Source => Items_List(Proto_Index).IType) > 4
and then
(Slice(Source => Items_List(Proto_Index).IType, Low => 1, High => 4) =
"Ammo" or
Items_List(Proto_Index).IType =
To_Unbounded_String(Source => "Harpoon")) then
Append
(Source => Item_Info,
New_Item =>
LF & "Strength:" &
Integer'Image(Items_List(Proto_Index).Value(1)));
end if;
if Items_List(Proto_Index).Description /= Null_Unbounded_String then
Append
(Source => Item_Info,
New_Item =>
LF & LF &
To_String(Source => Items_List(Proto_Index).Description));
end if;
if Parent = "." then
ShowInfo
(Text => To_String(Source => Item_Info),
Title =>
(if Member_Index > 0 then
GetItemName
(Item =>
Player_Ship.Crew(Member_Index).Inventory(Item_Index),
DamageInfo => False, ToLower => False)
else GetItemName
(Item => Player_Ship.Cargo(Item_Index), DamageInfo => False,
ToLower => False)));
else
ShowInfo
(Text => To_String(Source => Item_Info), ParentName => Parent,
Title =>
(if Member_Index > 0 then
GetItemName
(Item =>
Player_Ship.Crew(Member_Index).Inventory(Item_Index),
DamageInfo => False, ToLower => False)
else GetItemName
(Item => Player_Ship.Cargo(Item_Index), DamageInfo => False,
ToLower => False)));
end if;
end Show_Inventory_Item_Info;
procedure Delete_Widgets
(Start_Index, End_Index: Integer; Frame: Tk_Widget'Class) with
SPARK_Mode
is
Tokens: Slice_Set;
Item: Ttk_Frame;
begin
if End_Index < Start_Index then
return;
end if;
Delete_Widgets_Loop :
for I in Start_Index .. End_Index loop
Create
(S => Tokens,
From =>
Tcl.Tk.Ada.Grid.Grid_Slaves
(Master => Frame, Option => "-row" & Positive'Image(I)),
Separators => " ");
Delete_Row_Loop :
for J in 1 .. Slice_Count(S => Tokens) loop
Item := Get_Widget(pathName => Slice(S => Tokens, Index => J));
Destroy(Widgt => Item);
end loop Delete_Row_Loop;
end loop Delete_Widgets_Loop;
end Delete_Widgets;
function Get_Skill_Marks
(Skill_Index: Skills_Amount_Range; Member_Index: Positive)
return String is
Skill_Value, Crew_Index: Natural := 0;
Skill_String: Unbounded_String := Null_Unbounded_String;
begin
Get_Highest_Skills_Loop :
for I in Player_Ship.Crew.First_Index .. Player_Ship.Crew.Last_Index loop
if GetSkillLevel
(Member => Player_Ship.Crew(I), SkillIndex => Skill_Index) >
Skill_Value then
Crew_Index := I;
Skill_Value :=
GetSkillLevel
(Member => Player_Ship.Crew(I), SkillIndex => Skill_Index);
end if;
end loop Get_Highest_Skills_Loop;
if GetSkillLevel
(Member => Player_Ship.Crew(Member_Index),
SkillIndex => Skill_Index) >
0 then
Skill_String := To_Unbounded_String(Source => " +");
end if;
if Member_Index = Crew_Index then
Skill_String := Skill_String & To_Unbounded_String(Source => "+");
end if;
return To_String(Source => Skill_String);
end Get_Skill_Marks;
end Utils.UI;
|
with Test_Utils.Abstract_Encoder;
with AUnit.Test_Suites;
with AUnit.Test_Fixtures;
private with AUnit.Test_Caller;
package Testsuite.Encode is
type Encoder_Kind is (Simple, Stream, Queue);
procedure Set_Encoder_Kind (K : Encoder_Kind);
procedure Add_Tests (Suite : in out AUnit.Test_Suites.Test_Suite'Class);
function Create_Encoder (K : Encoder_Kind)
return not null Test_Utils.Abstract_Encoder.Any_Acc;
procedure Free_Encoder (Dec : in out Test_Utils.Abstract_Encoder.Any_Acc);
private
type Encoder_Fixture
is new AUnit.Test_Fixtures.Test_Fixture with record
Encoder : Test_Utils.Abstract_Encoder.Any_Acc;
Kind : Encoder_Kind;
end record;
overriding
procedure Set_Up (Test : in out Encoder_Fixture);
overriding
procedure Tear_Down (Test : in out Encoder_Fixture);
package Encoder_Caller is new AUnit.Test_Caller (Encoder_Fixture);
end Testsuite.Encode;
|
with Arduino_Nano_33_Ble_Sense.IOs;
package HCSR04 is
function Distance(TrigPin, EchoPin : Arduino_Nano_33_Ble_Sense.IOs.Pin_Id) return Float;
end HCSR04;
|
with Ada.Text_IO;
with c_code_h;
procedure Ada_C_Main is
package ATI renames Ada.Text_Io;
begin
ATI.Put_Line ("Ada_C_Main: Calling c_func");
c_code_h.c_func;
ATI.Put_Line ("Ada_C_Main: Returned from c_func");
end Ada_C_Main;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- E X P _ C H 6 --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- Expand routines for chapter 6 constructs
with Types; use Types;
package Exp_Ch6 is
procedure Expand_N_Extended_Return_Statement (N : Node_Id);
procedure Expand_N_Function_Call (N : Node_Id);
procedure Expand_N_Procedure_Call_Statement (N : Node_Id);
procedure Expand_N_Simple_Return_Statement (N : Node_Id);
procedure Expand_N_Subprogram_Body (N : Node_Id);
procedure Expand_N_Subprogram_Body_Stub (N : Node_Id);
procedure Expand_N_Subprogram_Declaration (N : Node_Id);
procedure Expand_Call (N : Node_Id);
-- This procedure contains common processing for Expand_N_Function_Call,
-- Expand_N_Procedure_Statement, and Expand_N_Entry_Call.
procedure Freeze_Subprogram (N : Node_Id);
-- generate the appropriate expansions related to Subprogram freeze
-- nodes (e.g. the filling of the corresponding Dispatch Table for
-- Primitive Operations)
-- The following type defines the various forms of allocation used for the
-- results of build-in-place function calls.
type BIP_Allocation_Form is
(Unspecified,
Caller_Allocation,
Secondary_Stack,
Global_Heap,
User_Storage_Pool);
type BIP_Formal_Kind is
-- Ada 2005 (AI-318-02): This type defines the kinds of implicit extra
-- formals created for build-in-place functions. The order of these
-- enumeration literals matches the order in which the formals are
-- declared. See Sem_Ch6.Create_Extra_Formals.
(BIP_Alloc_Form,
-- Present if result subtype is unconstrained or tagged. Indicates
-- whether the return object is allocated by the caller or callee, and
-- if the callee, whether to use the secondary stack or the heap. See
-- Create_Extra_Formals.
BIP_Storage_Pool,
-- Present if result subtype is unconstrained or tagged. If
-- BIP_Alloc_Form = User_Storage_Pool, this is a pointer to the pool
-- (of type access to Root_Storage_Pool'Class). Otherwise null.
BIP_Finalization_Master,
-- Present if result type needs finalization. Pointer to caller's
-- finalization master.
BIP_Task_Master,
-- Present if result type contains tasks. Master associated with
-- calling context.
BIP_Activation_Chain,
-- Present if result type contains tasks. Caller's activation chain
BIP_Object_Access);
-- Present for all build-in-place functions. Address at which to place
-- the return object, or null if BIP_Alloc_Form indicates allocated by
-- callee.
--
-- ??? We might also need to be able to pass in a constrained flag.
procedure Add_Extra_Actual_To_Call
(Subprogram_Call : Node_Id;
Extra_Formal : Entity_Id;
Extra_Actual : Node_Id);
-- Adds Extra_Actual as a named parameter association for the formal
-- Extra_Formal in Subprogram_Call.
function BIP_Formal_Suffix (Kind : BIP_Formal_Kind) return String;
-- Ada 2005 (AI-318-02): Returns a string to be used as the suffix of names
-- for build-in-place formal parameters of the given kind.
function Build_In_Place_Formal
(Func : Entity_Id;
Kind : BIP_Formal_Kind) return Entity_Id;
-- Ada 2005 (AI-318-02): Locates and returns the entity for the implicit
-- build-in-place formal parameter of the given kind associated with the
-- function Func, and returns its Entity_Id. It is a bug if not found; the
-- caller should ensure this is called only when the extra formal exists.
function Build_Procedure_Body_Form
(Func_Id : Entity_Id; Func_Body : Node_Id) return Node_Id;
-- Create a procedure body which emulates the behavior of function Func_Id.
-- Func_Body is the root of the body of the function before its analysis.
-- The returned node is the root of the procedure body which will replace
-- the original function body, which is not needed for the C program.
function Is_Build_In_Place_Function (E : Entity_Id) return Boolean;
-- Ada 2005 (AI-318-02): Returns True if E denotes a function, generic
-- function, or access-to-function type whose result must be built in
-- place; otherwise returns False. For Ada 2005, this is currently
-- restricted to the set of functions whose result subtype is an inherently
-- limited type. In Ada 95, this must be False for inherently limited
-- result types (but currently returns False for all Ada 95 functions).
-- Eventually we plan to support build-in-place for nonlimited types.
-- Build-in-place is usually more efficient for large things, and less
-- efficient for small things. However, we never use build-in-place if the
-- convention is other than Ada, because that would disturb mixed-language
-- programs. Note that for the non-inherently-limited cases, we must make
-- the same decision for Ada 95 and 2005, so that mixed-dialect programs
-- will work.
function Is_Build_In_Place_Function_Call (N : Node_Id) return Boolean;
-- Ada 2005 (AI-318-02): Returns True if N denotes a call to a function
-- that requires handling as a build-in-place call or is a qualified
-- expression applied to such a call; otherwise returns False.
function Is_Null_Procedure (Subp : Entity_Id) return Boolean;
-- Predicate to recognize stubbed procedures and null procedures, which
-- can be inlined unconditionally in all cases.
procedure Make_Build_In_Place_Call_In_Allocator
(Allocator : Node_Id;
Function_Call : Node_Id);
-- Ada 2005 (AI-318-02): Handle a call to a build-in-place function that
-- occurs as the expression initializing an allocator, by passing access
-- to the allocated object as an additional parameter of the function call.
-- A new access object is declared that is initialized to the result of the
-- allocator, passed to the function, and the allocator is rewritten to
-- refer to that access object. Function_Call must denote either an
-- N_Function_Call node for which Is_Build_In_Place_Call is True, or else
-- an N_Qualified_Expression node applied to such a function call.
procedure Make_Build_In_Place_Call_In_Anonymous_Context
(Function_Call : Node_Id);
-- Ada 2005 (AI-318-02): Handle a call to a build-in-place function that
-- occurs in a context that does not provide a separate object. A temporary
-- object is created to act as the return object and an access to the
-- temporary is passed as an additional parameter of the call. This occurs
-- in contexts such as subprogram call actuals and object renamings.
-- Function_Call must denote either an N_Function_Call node for which
-- Is_Build_In_Place_Call is True, or else an N_Qualified_Expression node
-- applied to such a function call.
procedure Make_Build_In_Place_Call_In_Assignment
(Assign : Node_Id;
Function_Call : Node_Id);
-- Ada 2005 (AI-318-02): Handle a call to a build-in-place function that
-- occurs as the right-hand side of an assignment statement by passing
-- access to the left-hand side as an additional parameter of the function
-- call. Assign must denote a N_Assignment_Statement. Function_Call must
-- denote either an N_Function_Call node for which Is_Build_In_Place_Call
-- is True, or an N_Qualified_Expression node applied to such a function
-- call.
procedure Make_Build_In_Place_Call_In_Object_Declaration
(Obj_Decl : Node_Id;
Function_Call : Node_Id);
-- Ada 2005 (AI-318-02): Handle a call to a build-in-place function that
-- occurs as the expression initializing an object declaration by
-- passing access to the declared object as an additional parameter of the
-- function call. Function_Call must denote either an N_Function_Call node
-- for which Is_Build_In_Place_Call is True, or an N_Qualified_Expression
-- node applied to such a function call.
procedure Make_CPP_Constructor_Call_In_Allocator
(Allocator : Node_Id;
Function_Call : Node_Id);
-- Handle a call to a CPP constructor that occurs as the expression that
-- initializes an allocator, by passing access to the allocated object as
-- an additional parameter of the constructor call. A new access object is
-- declared that is initialized to the result of the allocator, passed to
-- the constructor, and the allocator is rewritten to refer to that access
-- object. Function_Call must denote a call to a CPP_Constructor function.
function Needs_BIP_Alloc_Form (Func_Id : Entity_Id) return Boolean;
-- Ada 2005 (AI-318-02): Return True if the function needs an implicit
-- BIP_Alloc_Form parameter (see type BIP_Formal_Kind).
function Needs_BIP_Finalization_Master (Func_Id : Entity_Id) return Boolean;
-- Ada 2005 (AI-318-02): Return True if the result subtype of function
-- Func_Id might need finalization actions. This includes build-in-place
-- functions with tagged result types, since they can be invoked via
-- dispatching calls, and descendant types may require finalization.
function Needs_Result_Accessibility_Level
(Func_Id : Entity_Id) return Boolean;
-- Ada 2012 (AI05-0234): Return True if the function needs an implicit
-- parameter to identify the accessibility level of the function result
-- "determined by the point of call".
end Exp_Ch6;
|
function Spiral (N : Positive) return Array_Type is
Result : Array_Type (1..N, 1..N);
Left : Positive := 1;
Right : Positive := N;
Top : Positive := 1;
Bottom : Positive := N;
Index : Natural := 0;
begin
while Left < Right loop
for I in Left..Right - 1 loop
Result (Top, I) := Index;
Index := Index + 1;
end loop;
for J in Top..Bottom - 1 loop
Result (J, Right) := Index;
Index := Index + 1;
end loop;
for I in reverse Left + 1..Right loop
Result (Bottom, I) := Index;
Index := Index + 1;
end loop;
for J in reverse Top + 1..Bottom loop
Result (J, Left) := Index;
Index := Index + 1;
end loop;
Left := Left + 1;
Right := Right - 1;
Top := Top + 1;
Bottom := Bottom - 1;
end loop;
Result (Top, Left) := Index;
return Result;
end Spiral;
|
with YAML.Abstract_Object;
package YAML.Vector is
subtype Parent is Abstract_Object.Instance;
subtype Parent_Class is Abstract_Object.Class;
type Instance is new Parent with private;
subtype Class is Instance'Class;
overriding
function Get (Item : in Instance;
Name : in String) return Parent_Class;
overriding
function Get (Item : in Instance;
Index : in Positive) return Parent_Class;
overriding
function Get (Item : in Instance;
Name : in String) return String;
overriding
function Get (Item : in Instance;
Index : in Positive) return String;
overriding
function Get (Item : in Instance;
Name : in String;
Default : in String) return String;
overriding
function Get (Item : in Instance;
Index : in Positive;
Default : in String) return String;
overriding
function Has (Item : in Instance;
Name : in String) return Boolean;
overriding
function Has (Item : in Instance;
Index : in Positive) return Boolean;
generic
type Element_Type is private;
with function Value (Item : in String) return Element_Type;
with function Image (Item : in Element_Type) return String;
package Parse is
function Get (Item : in Instance;
Name : in String) return Element_Type;
function Get (Item : in Instance;
Name : in String;
Default : in Element_Type) return Element_Type;
end Parse;
private
type Instance is new Parent with
record
null;
end record;
end YAML.Vector;
|
with System.Formatting;
with System.Img_Int;
with System.Long_Long_Integer_Types;
package body System.Img_LLI is
use type Long_Long_Integer_Types.Long_Long_Unsigned;
subtype Word_Integer is Long_Long_Integer_Types.Word_Integer;
subtype Long_Long_Unsigned is Long_Long_Integer_Types.Long_Long_Unsigned;
procedure Image (
V : Long_Long_Integer;
S : in out String;
P : out Natural);
procedure Image (
V : Long_Long_Integer;
S : in out String;
P : out Natural)
is
X : Long_Long_Unsigned;
Error : Boolean;
begin
pragma Assert (S'Length >= 1);
if V < 0 then
S (S'First) := '-';
X := -Long_Long_Unsigned'Mod (V);
else
S (S'First) := ' ';
X := Long_Long_Unsigned (V);
end if;
Formatting.Image (X, S (S'First + 1 .. S'Last), P, Error => Error);
pragma Assert (not Error);
end Image;
-- implementation
procedure Image_Long_Long_Integer (
V : Long_Long_Integer;
S : in out String;
P : out Natural) is
begin
if Long_Long_Integer'Size <= Standard'Word_Size then
Img_Int.Image (Word_Integer (V), S, P);
else
Image (V, S, P);
end if;
end Image_Long_Long_Integer;
end System.Img_LLI;
|
with impact.d3.min_max;
-- with math; --.Algebra.linear.d3;
package body impact.d3.Vector
--
--
--
is
function x (Self : in Vector_3) return Real
is
begin
return Self (1);
end x;
function y (Self : in Vector_3) return Real
is
begin
return Self (2);
end y;
function z (Self : in Vector_3) return Real
is
begin
return Self (3);
end z;
function dot (Left, Right : in Vector_3) return Real
is
begin
return Left (1) * Right (1)
+ Left (2) * Right (2)
+ Left (3) * Right (3);
end dot;
function cross (Left, Right : in Vector_3) return Vector_3
is
begin
return (Left (2) * Right (3) - Left (3) * Right (2),
Left (3) * Right (1) - Left (1) * Right (3),
Left (1) * Right (2) - Left (2) * Right (1));
end cross;
function length2 (Self : in Vector_3) return Real
is
begin
return dot (Self, Self);
end length2;
function length (Self : in Vector_3) return Real
is
use math.Functions;
begin
return sqRt (length2 (Self));
end length;
function distance2 (Left, Right : in Vector_3) return Real
is
begin
return length2 (Right - Left);
end distance2;
function distance (Left, Right : in Vector_3) return Real
is
begin
return length (Right - Left);
end distance;
function safeNormalize (Self : access Vector_3) return Vector_3
is
absVec : Vector_3 := absolute (Self.all);
maxIndex : constant math.Index := maxAxis (absVec);
begin
if absVec (maxIndex) > 0.0 then
Self.all := Self.all / absVec (maxIndex);
Self.all := Self.all / length (Self.all);
return Self.all;
end if;
Self.all := (1.0, 0.0, 0.0);
return Self.all;
end safeNormalize;
function Normalize (Self : access Vector_3) return Vector_3
is
begin
Self.all := Self.all / length (Self.all);
return Self.all;
end Normalize;
function Normalized (Self : in Vector_3) return Vector_3
is
begin
return Self / length (Self);
end Normalized;
procedure Normalize (Self : in out Vector_3)
is
begin
Self := Normalized (Self);
end Normalize;
function absolute (Self : in Vector_3) return Vector_3
is
begin
return abs (Self);
end absolute;
function minAxis (Self : in Vector_3) return math.Index
is
begin
if Self (1) < Self (2) then
if Self (1) < Self (3) then
return 1;
else
return 3;
end if;
elsif Self (2) < Self (3) then
return 2;
else
return 3;
end if;
end minAxis;
function maxAxis (Self : in Vector_3) return math.Index
is
begin
if Self (1) < Self (2) then
if Self (2) < Self (3) then
return 3;
else
return 2;
end if;
elsif Self (1) < Self (3) then
return 3;
else
return 1;
end if;
end maxAxis;
function rotate (Self : in Vector_3; wAxis : in Vector_3;
Angle : in Real ) return Vector_3
is
use math.Functions;
o : constant Vector_3 := wAxis * dot (wAxis, Self); -- wAxis must be a unit lenght vector
x : constant Vector_3 := Self - o;
y : constant Vector_3 := cross (wAxis, Self);
begin
return o + x * Cos (angle) + y * Sin (angle);
end rotate;
function Angle (Left, Right : in Vector_3) return Real
is
use math.Functions;
s : constant Real := sqRt (length2 (Left) * length2 (Right));
begin
pragma Assert (s /= 0.0);
return arcCos (dot (Left, Right) / s);
end Angle;
function Triple (V1, V2, V3 : in Vector_3) return Real
is
begin
return V1 (1) * (V2 (2) * V3 (3) - V2 (3) * V3 (2))
+ V1 (2) * (V2 (3) * V3 (1) - V2 (1) * V3 (3))
+ V1 (3) * (V2 (1) * V3 (2) - V2 (2) * V3 (1));
end Triple;
function furthestAxis (Self : in Vector_3) return math.Index
is
begin
return minAxis (absolute (Self));
end furthestAxis;
function closestAxis (Self : in Vector_3) return math.Index
is
begin
return maxAxis (absolute (Self));
end closestAxis;
procedure setInterpolate3 (Self : in out Vector_3; V1, V2 : in Vector_3;
rt : in Real)
is
s : constant Real := 1.0 - rt;
begin
Self (1) := s * V1 (1) + rt * V2 (1);
Self (2) := s * V1 (2) + rt * V2 (2);
Self (3) := s * V1 (3) + rt * V2 (3);
-- don't do the unused w component
-- m_co[3] = s * v0[3] + rt * v1[3];
end setInterpolate3;
function lerp (V1, V2 : in Vector_3; t : in Real) return Vector_3
is
begin
return (V1 (1) + (V2 (1) - V1 (1)) * t,
V1 (2) + (V2 (2) - V1 (2)) * t,
V1 (3) + (V2 (3) - V1 (3)) * t);
end lerp;
function Scaled (Self : in Vector_3; By : in Vector_3) return Vector_3
is
begin
return (Self (1) * By (1),
Self (2) * By (2),
Self (3) * By (3));
end Scaled;
function invScaled (Self : in Vector_3; By : in Vector_3) return Vector_3
is
begin
return (Self (1) / By (1),
Self (2) / By (2),
Self (3) / By (3));
end invScaled;
-- function "*" (L : in math.Vector_3; R : in math.Real) return math.Vector_3
-- is
-- begin
-- return (L (1) * R,
-- L (2) * R,
-- L (3) * R);
-- end;
function Scale (Self : access Vector_3; By : in Vector_3) return Vector_3
is
begin
Self.all := Scaled (Self.all, By);
return Self.all;
end Scale;
procedure setMax (Self : in out Vector_3; Other : in Vector_3)
is
begin
Self := (Real'Max (Self (1), Other (1)),
Real'Max (Self (2), Other (2)),
Real'Max (Self (3), Other (3)));
end setMax;
procedure setMin (Self : in out Vector_3; Other : in Vector_3)
is
begin
Self := (Real'Min (Self (1), Other (1)),
Real'Min (Self (2), Other (2)),
Real'Min (Self (3), Other (3)));
end setMin;
procedure getSkewSymmetricMatrix (Self : in Vector_3; V1, V2, V3 : out Vector_3)
is
begin
v1 := ( 0.0, -Self (3), Self (2));
v2 := (Self (3), 0.0, -Self (1));
v3 := (-Self (2), Self (1), 0.0);
end getSkewSymmetricMatrix;
procedure setZero (Self : out Vector_3)
is
begin
Self := (0.0, 0.0, 0.0);
end setZero;
function isZero (Self : in Vector_3) return Boolean
is
begin
return Self (1) = 0.0 and then Self (2) = 0.0 and then Self (3) = 0.0;
end isZero;
function fuzzyZero (Self : in Vector_3) return Boolean
is
use impact.d3.Scalar;
begin
return length2 (Self) < SIMD_EPSILON;
end fuzzyZero;
--- Vector_4
--
function absolute4 (Self : in Vector_4) return Vector_4
is
use math.Vectors;
begin
return abs (Self);
end absolute4;
function maxAxis4 (Self : in Vector_4) return math.Index
is
maxIndex : math.Index := -1;
maxVal : Real := Real'First; -- -BT_LARGE_FLOAT;
begin
if Self (1) > maxVal then
maxIndex := 1;
maxVal := Self (1);
end if;
if Self (2) > maxVal then
maxIndex := 2;
maxVal := Self (2);
end if;
if Self (3) > maxVal then
maxIndex := 3;
maxVal := Self (3);
end if;
if Self (4) > maxVal then
maxIndex := 4;
maxVal := Self (4);
end if;
return maxIndex;
end maxAxis4;
function minAxis4 (Self : in Vector_4) return math.Index
is
minIndex : math.Index := -1;
minVal : Real := Real'Last; -- BT_LARGE_FLOAT;
begin
if Self (1) < minVal then
minIndex := 1;
minVal := Self (1);
end if;
if Self (2) < minVal then
minIndex := 2;
minVal := Self (2);
end if;
if Self (3) < minVal then
minIndex := 3;
minVal := Self (3);
end if;
if Self (4) < minVal then
minIndex := 4;
minVal := Self (4);
end if;
return minIndex;
end minAxis4;
function closestAxis4 (Self : in Vector_4) return math.Index
is
begin
return maxAxis4 (absolute4 (Self));
end closestAxis4;
procedure btPlaneSpace1 (n : in Vector_3; p, q : out Vector_3)
is
use impact.d3.Scalar;
a, k : Real;
begin
if abs n (3) > SIMDSQRT12 then -- choose p in y-z plane
a := n (2) * n (2) + n (3) * n (3);
k := btRecipSqrt (a);
p (1) := 0.0;
p (2) := -n (3) * k;
p (3) := n (2) * k;
-- set q = n x p
q (1) := a * k;
q (2) := -n (1) * p (3);
q (3) := n (1) * p (2);
else -- choose p in x-y plane
a := n (1) * n (1) + n (2) * n (2);
k := btRecipSqrt (a);
p (1) := -n (2) * k;
p (2) := n (1) * k;
p (3) := 0.0;
-- set q = n x p
q (1) := -n (3) * p (2);
q (2) := n (3) * p (1);
q (3) := a * k;
end if;
end btPlaneSpace1;
end impact.d3.Vector;
|
generic
type T is private;
package Varsize3_Pkg3 is
type Object is record
E : T;
end record;
function True return Object;
end Varsize3_Pkg3;
|
--===========================================================================
--
-- This is the main master program for the Tiny as an SPI Master
--
--===========================================================================
--
-- Copyright 2022 (C) Holger Rodriguez
--
-- SPDX-License-Identifier: BSD-3-Clause
--
with HAL;
with HAL.SPI;
with RP.GPIO;
with RP.SPI;
with RP.Device;
with Tiny;
procedure SPI_Master_16 is
Data_Out_16 : HAL.SPI.SPI_Data_16b (1 .. 1);
Status_Out : HAL.SPI.SPI_Status;
Data_In_16 : HAL.SPI.SPI_Data_16b (1 .. 1) := (others => 0);
Status_In : HAL.SPI.SPI_Status;
Word : HAL.UInt16;
use HAL;
use HAL.SPI;
use RP.SPI;
-----------------------------------------------------------------------
SPI : RP.SPI.SPI_Port renames Tiny.SPI;
-- Master section 0
SCK_0 : RP.GPIO.GPIO_Point renames Tiny.SCK_0_2;
NSS_0 : RP.GPIO.GPIO_Point renames Tiny.NSS_0_1;
MOSI_0 : RP.GPIO.GPIO_Point renames Tiny.MOSI_0_3;
MISO_0 : RP.GPIO.GPIO_Point renames Tiny.MISO_0_0;
-- Master section 1
SCK_1 : RP.GPIO.GPIO_Point renames Tiny.SCK_0_6;
NSS_1 : RP.GPIO.GPIO_Point renames Tiny.NSS_0_5;
MOSI_1 : RP.GPIO.GPIO_Point renames Tiny.MOSI_0_7;
MISO_1 : RP.GPIO.GPIO_Point renames Tiny.MISO_0_4;
-----------------------------------------------------------------------
-- Renaming section
SCK : RP.GPIO.GPIO_Point renames SCK_1;
NSS : RP.GPIO.GPIO_Point renames NSS_1;
MOSI : RP.GPIO.GPIO_Point renames MOSI_1;
MISO : RP.GPIO.GPIO_Point renames MISO_1;
-----------------------------------------------------------------------
-- Configuration for the master part for the Tiny
Config : constant RP.SPI.SPI_Configuration
:= (Role => RP.SPI.Master,
Baud => 10_000_000,
Data_Size => HAL.SPI.Data_Size_16b,
others => <>);
-----------------------------------------------------------------------
-- Initializes the Tiny as master SPI
procedure SPI_Initialize is
begin
SCK.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI);
NSS.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI);
MOSI.Configure (RP.GPIO.Output, RP.GPIO.Pull_Up, RP.GPIO.SPI);
MISO.Configure (RP.GPIO.Input, RP.GPIO.Floating, RP.GPIO.SPI);
SPI.Configure (Config);
end SPI_Initialize;
begin
Tiny.Initialize;
SPI_Initialize;
loop
-- construct the values for the transmission
for Higher_Byte in HAL.UInt8'Range loop
for Lower_Byte in HAL.UInt8'Range loop
Word := Shift_Left (Value => HAL.UInt16 (Higher_Byte),
Amount => 8) or HAL.UInt16 (Lower_Byte);
Data_Out_16 (1) := Word;
SPI.Transmit (Data_Out_16, Status_Out);
SPI.Receive (Data_In_16, Status_In, 0);
RP.Device.Timer.Delay_Milliseconds (100);
Tiny.LED_Red.Toggle;
end loop;
end loop;
end loop;
end SPI_Master_16;
|
-- { dg-do compile }
-- { dg-options "-O2" }
package Pack12 is
type Rec1 is record
B : Boolean;
N : Natural;
end record;
type Rec2 is record
B : Boolean;
R : Rec1;
end record;
pragma Pack (Rec2);
type Rec3 is tagged record
R : Rec2;
end record;
end Pack12;
|
with Tkmrpc.Types;
with Tkmrpc.Results;
with Tkmrpc.Operations;
package Tkmrpc.Response is
Response_Size : constant := 1024;
Header_Size : constant := 24;
Body_Size : constant := Response_Size - Header_Size;
type Header_Type is record
Operation : Operations.Operation_Type;
Request_Id : Types.Request_Id_Type;
Result : Results.Result_Type;
end record;
for Header_Type use record
Operation at 0 range 0 .. (8 * 8) - 1;
Request_Id at 8 range 0 .. (8 * 8) - 1;
Result at 16 range 0 .. (8 * 8) - 1;
end record;
for Header_Type'Size use Header_Size * 8;
subtype Padded_Data_Range is Natural range 1 .. Body_Size;
subtype Padded_Data_Type is Types.Byte_Sequence (Padded_Data_Range);
type Data_Type is record
Header : Header_Type;
Padded_Data : Padded_Data_Type;
end record;
for Data_Type use record
Header at 0 range 0 .. (Header_Size * 8) - 1;
Padded_Data at Header_Size range 0 .. (Body_Size * 8) - 1;
end record;
for Data_Type'Size use Response_Size * 8;
Null_Data : constant Data_Type := Data_Type'
(Header => Header_Type'
(Operation => 0,
Request_Id => 0,
Result => Results.Invalid_Operation),
Padded_Data => Padded_Data_Type'(others => 0));
end Tkmrpc.Response;
|
------------------------------------------------------------------------------
-- G E L A A S I S --
-- ASIS implementation for Gela project, a portable Ada compiler --
-- http://gela.ada-ru.org --
-- - - - - - - - - - - - - - - - --
-- Read copyright and license at the end of this file --
------------------------------------------------------------------------------
-- $Revision: 209 $ $Date: 2013-11-30 21:03:24 +0200 (Сб., 30 нояб. 2013) $:
with Asis.Clauses;
with Asis.Elements;
with Asis.Statements;
with Asis.Declarations;
with Asis.Compilation_Units;
with Asis.Gela.Debug;
with Asis.Gela.Utils;
with Asis.Gela.Classes;
with Asis.Gela.Errors;
with Asis.Gela.Element_Utils;
with Asis.Gela.Visibility.Utils;
with Asis.Gela.Private_Operations;
with XASIS.Types;
with XASIS.Utils;
with Ada.Wide_Text_IO;
package body Asis.Gela.Visibility.Create is
procedure Find_Homograph
(Defining_Name : in Asis.Defining_Name;
Point : in Visibility.Point;
Homograph : out Asis.Defining_Name;
Prev : out Region_Item_Access);
procedure Region_Item
(Defining_Name : in Asis.Defining_Name;
Point : in out Visibility.Point;
Tipe : in Asis.Declaration;
Overridden : out Boolean);
function Is_Public_Unit (Element : in Asis.Declaration) return Boolean;
function Is_Overridden
(First, Second : Asis.Defining_Name)
return Boolean;
procedure Is_Character
(Name : in Asis.Defining_Name;
Is_Wide_Wide : out Boolean;
Is_Wide_Char : out Boolean;
Is_Char : out Boolean);
function Is_Library_Unit_Decl
(Element : Asis.Element) return Boolean;
--------------
-- New_Part --
--------------
procedure New_Part
(Region : in Region_Access;
Kind : in Part_Kinds;
Parent_Item : in Region_Item_Access;
Element : in Asis.Element;
Check_Private : in Boolean;
Result : out Part_Access)
is
use Asis.Elements;
--------------------------------
-- Is_Private_Part_Of_Package --
--------------------------------
function Is_Private_Part_Of_Package return Boolean is
Parent : Asis.Element := Enclosing_Element (Element);
begin
if Kind = A_Private_Part and
Declaration_Kind (Parent) = A_Package_Declaration
then
return True;
else
return False;
end if;
end Is_Private_Part_Of_Package;
Part : Part_Access;
Next : Part_Access := Region.Last_Part;
Prev : Part_Access;
Start : Point;
begin
-- Iterate over region parts
-- Invariant: (Prev = null and Next = Region.Last_Part)
-- or (Prev != null and Prev.Next = Next)
while Next /= null loop
if Next.Kind = Kind then
Result := Next;
return;
end if;
exit when Next.Kind < Kind;
Prev := Next;
Next := Prev.Next;
end loop;
if Region.First_Part.Region = null then
Part := Region.First_Part'Access;
else
Part := new Part_Node;
end if;
Part.Dummy_Item.Part := Part;
Part.Region := Region;
Part.Next := Next;
Part.Kind := Kind;
Part.Parent_Item := Parent_Item;
Part.Last_Item := Part.Dummy_Item'Access;
Part.Element := Element;
if Prev = null then
Region.Last_Part := Part;
else
Prev.Next := Part;
end if;
if Check_Private and then Is_Private_Part_Of_Package
and then not Is_Part_Of_Instance (Element)
then
Start := (Item => Part.Last_Item);
-- if not empty private part:
if Element_Kind (Element) /= A_Defining_Name then
Utils.Set_Place (Element, Start);
-- set place to private part to enable visibility check when
-- we call Type_From_Declaration (List (J), Spec_View);
-- where Spec_View is this Element (first in private part).
end if;
Private_Operations.On_Private_Part
(Enclosing_Element (Element), Start);
end if;
Result := Part;
end New_Part;
------------
-- Region --
------------
procedure Region
(Element : in Asis.Element;
Point : in out Visibility.Point)
is
use Asis.Elements;
function Debug_Image return Wide_String is
Spaces : constant Wide_String (1 .. 20) := (others => ' ');
Depth : Natural := 0;
begin
if Point.Item.Part.Region /= null then
Depth := Point.Item.Part.Region.Depth;
end if;
return Spaces (1 .. 2 * Depth) &
Debug_Image (Element) &
" ==> " &
Debug_Image (Point.Item.Part.Region.First_Part.Element);
end Debug_Image;
pragma Assert (Debug.Run (Element, Debug.Create_Region)
or else Debug.Dump (Debug_Image));
Child : Region_Access := new Region_Node;
Part : Part_Access;
Kind : Part_Kinds;
begin
Child.Next := Point.Item.Part.Region.First_Child;
Child.Depth := Point.Item.Part.Region.Depth + 1;
if Is_Part_Of_Implicit (Element) then
Kind := A_Public_Limited_View_Part;
else
Kind := A_Visible_Part;
end if;
if Is_Nil (Enclosing_Element (Element)) then
Child.Library_Unit := True;
Child.Public_Child := Is_Public_Unit (Element);
else
Child.Library_Unit := False;
Child.Public_Child := True;
end if;
New_Part
(Region => Child,
Kind => Kind,
Parent_Item => Point.Item,
Element => Element,
Check_Private => False,
Result => Part);
Point.Item.Part.Region.First_Child := Child;
Point := (Item => Part.Last_Item);
end Region;
-----------------------
-- Completion_Region --
-----------------------
procedure Completion_Region
(Element : in Asis.Element;
Point : in out Visibility.Point;
Is_Instance : in Boolean;
RR_Clause : in Boolean)
is
use Asis.Declarations;
Name : Asis.Expression;
Decl : Asis.Declaration;
Prev : Visibility.Point;
Next : Part_Access;
Kind : Part_Kinds;
begin
if RR_Clause then
Name := Representation_Clause_Name (Element.all);
Decl := Corresponding_Name_Declaration (Name.all);
elsif Is_Instance then
Decl := Asis.Elements.Enclosing_Element (Element);
elsif Is_Subunit (Element) then
Decl := Corresponding_Body_Stub (Element);
if XASIS.Utils.Is_Completion (Decl) then
Decl := XASIS.Utils.Declaration_For_Completion (Decl);
end if;
else
Decl := XASIS.Utils.Declaration_For_Completion (Element);
end if;
if Asis.Elements.Declaration_Kind (Element) = A_Package_Declaration then
Kind := A_Visible_Part;
else
Kind := A_Body_Part;
end if;
Prev := Utils.Find_Region (Decl);
New_Part
(Region => Prev.Item.Part.Region,
Kind => Kind,
Parent_Item => Point.Item,
Element => Element,
Check_Private => False,
Result => Next);
Point.Item := Next.Last_Item;
end Completion_Region;
----------------------
----------------
-- Check_Part --
----------------
procedure Check_Part
(Item : in Region_Item_Access;
Kind : in Part_Kinds;
Element : in Asis.Element)
is
Part : Part_Access;
Next : Region_Item_Access := Item;
begin
if Item.Part.Kind /= Kind then
New_Part
(Region => Item.Part.Region,
Kind => Kind,
Parent_Item => Item.Part.Parent_Item,
Element => Element,
Result => Part,
Check_Private => True);
Item.Part := Part;
else
Part := Item.Part;
end if;
Item.Next := Part.Last_Item;
Part.Last_Item := Item;
end Check_Part;
--------------------
-- Find_Homograph --
--------------------
procedure Find_Homograph
(Defining_Name : in Asis.Defining_Name;
Point : in Visibility.Point;
Homograph : out Asis.Defining_Name;
Prev : out Region_Item_Access)
is
use Asis.Gela.Utils;
Name : constant Asis.Program_Text :=
XASIS.Utils.Direct_Name (Defining_Name);
Decl : constant Asis.Element :=
Asis.Elements.Enclosing_Element (Defining_Name);
begin
Prev := Utils.Find_Name (Name, Point, No_Parent_Region => True);
if Prev = null or else Prev.Count = 0 or else
Asis.Elements.Declaration_Kind (Decl) in
A_Procedure_Instantiation .. A_Function_Instantiation
then
-- Instantiation hasn't expanded at this moment yet, so we can't
-- check it's profile and find homographs
Homograph := Asis.Nil_Element;
return;
end if;
declare
Item : aliased Visibility.Region_Item (Definition);
Index : Asis.ASIS_Natural := 0;
Unit : constant Asis.Compilation_Unit :=
Asis.Elements.Enclosing_Compilation_Unit (Defining_Name);
List : Asis.Defining_Name_List (1 .. Prev.Count + 1);
begin
Item.Part := Point.Item.Part;
Item.Next := Point.Item.Part.Last_Item;
Item.Defining_Name := Defining_Name;
Item.Count := Prev.Count + 1;
Item.Prev := Prev;
Item.Still_Hidden := False;
Utils.Find_All (Item'Unchecked_Access,
Index, List, Unit,
(Item => Item'Unchecked_Access),
True);
for I in 1 .. Index loop
if not Asis.Elements.Is_Equal (Defining_Name, List (I))
and then Are_Homographs (Defining_Name, List (I), Decl)
then
Homograph := List (I);
return;
end if;
end loop;
Homograph := Asis.Nil_Element;
end;
end Find_Homograph;
------------------
-- Is_Character --
------------------
Char : Classes.Type_Info;
Wide : Classes.Type_Info;
Wide_Wide : Classes.Type_Info;
procedure Is_Character
(Name : in Asis.Defining_Name;
Is_Wide_Wide : out Boolean;
Is_Wide_Char : out Boolean;
Is_Char : out Boolean)
is
use Asis.Elements;
Kind : constant Asis.Defining_Name_Kinds := Defining_Name_Kind (Name);
Decl : Asis.Declaration := Enclosing_Element (Name);
Tipe : Classes.Type_Info;
begin
Is_Wide_Wide := False;
Is_Wide_Char := False;
Is_Char := False;
if Kind /= A_Defining_Character_Literal then
return;
end if;
if Classes.Is_Not_Type (Char) then
Char := Classes.Type_From_Declaration (XASIS.Types.Character,
XASIS.Types.Character);
Wide := Classes.Type_From_Declaration (XASIS.Types.Wide_Character,
XASIS.Types.Wide_Character);
Wide_Wide := Classes.Type_From_Declaration
(XASIS.Types.Wide_Wide_Character, XASIS.Types.Wide_Wide_Character);
end if;
Decl := Enclosing_Element (Enclosing_Element (Decl));
Tipe := Classes.Type_From_Declaration (Decl, Decl);
if Classes.Is_Child_Of (Tipe, Char) then
Is_Wide_Wide := True;
Is_Wide_Char := True;
Is_Char := True;
return;
elsif Classes.Is_Child_Of (Tipe, Wide) then
Is_Wide_Wide := True;
Is_Wide_Char := True;
Is_Char := False;
return;
elsif Classes.Is_Child_Of (Tipe, Wide_Wide) then
Is_Wide_Wide := True;
Is_Wide_Char := False;
Is_Char := False;
return;
end if;
end Is_Character;
--------------------------
-- Is_Library_Unit_Decl --
--------------------------
function Is_Library_Unit_Decl
(Element : Asis.Element) return Boolean
is
use Asis.Elements;
use Asis.Compilation_Units;
Class : Unit_Classes;
Enclosing_Unit : constant Compilation_Unit :=
Enclosing_Compilation_Unit (Element);
begin
if Utils.Is_Top_Declaration (Element) then
Class := Unit_Class (Enclosing_Unit);
return Class = A_Public_Declaration or else
Class = A_Public_Declaration_And_Body or else
Class = A_Private_Declaration;
else
return False;
end if;
end Is_Library_Unit_Decl;
-------------------
-- Is_Overridden --
-------------------
function Is_Overridden
(First : Asis.Defining_Name;
Second : Asis.Defining_Name)
return Boolean
is
-- If First Overridden by Second
use Asis.Elements;
begin
if not Is_Part_Of_Implicit (First) then
-- If redeclaration
return False;
elsif not Is_Part_Of_Implicit (Second) then
return True;
elsif Is_Part_Of_Inherited (Second) then
return True;
elsif Operator_Kind (Second) = A_Not_Equal_Operator then
-- This case not in RM, but when user defines "=" there is
-- an implicit declaration of "/=" and it should override
-- predefined "/=".
return True;
else
return False;
end if;
end Is_Overridden;
--------------------
-- Is_Public_Unit --
--------------------
function Is_Public_Unit (Element : in Asis.Declaration) return Boolean is
use Asis.Compilation_Units;
use type Asis.Unit_Classes;
Unit : constant Asis.Compilation_Unit :=
Asis.Elements.Enclosing_Compilation_Unit (Element);
Class : constant Asis.Unit_Classes := Unit_Class (Unit);
begin
if Class = Asis.A_Private_Declaration then
return False;
end if;
return True;
end Is_Public_Unit;
-----------------
-- Region_Item --
-----------------
procedure Region_Item
(Defining_Name : in Asis.Defining_Name;
Point : in out Visibility.Point;
Tipe : in Asis.Declaration;
Overridden : out Boolean)
is
use Asis.Elements;
use type Asis.List_Index;
Item : Region_Item_Access;
Prev : Region_Item_Access;
Homograph : Asis.Defining_Name;
Is_Wide_Wide : Boolean;
Is_Wide_Char : Boolean;
Is_Char : Boolean;
Library_Unit : Boolean := False;
Part_Kind : Part_Kinds;
Decl : constant Asis.Element :=
Enclosing_Element (Defining_Name);
begin
Overridden := False;
if Asis.Declarations.Is_Subunit (Decl) or Utils.Is_Template (Decl) then
return;
end if;
Find_Homograph (Defining_Name, Point, Homograph, Prev);
if Assigned (Homograph) then
Overridden := not Is_Overridden (Homograph, Defining_Name);
if Overridden then
return;
end if;
Element_Utils.Set_Override (Defining_Name, Homograph);
end if;
Is_Character (Defining_Name, Is_Wide_Wide, Is_Wide_Char, Is_Char);
if Is_Wide_Wide then
if Is_Char then
Item := new Visibility.Region_Item (Visibility.Char);
elsif Is_Wide_Char then
Item := new Visibility.Region_Item (Visibility.Wide_Char);
else
Item := new Visibility.Region_Item (Visibility.Wide_Wide_Char);
end if;
else
Item := new Visibility.Region_Item (Definition);
Item.Still_Hidden := Element_Kind (Decl) /= A_Statement;
Item.Library_Unit := Is_Library_Unit_Decl (Decl);
Item.Prev := Prev;
Library_Unit := Item.Library_Unit;
if Prev /= null then
Item.Count := Prev.Count + 1;
else
Item.Count := 0;
end if;
end if;
Item.Defining_Name := Defining_Name;
Item.Part := Point.Item.Part;
Part_Kind := Point.Item.Part.Kind;
if Library_Unit then
if Is_Part_Of_Implicit (Decl) then
if Is_Public_Unit (Decl) then
Part_Kind := A_Public_Limited_View_Part;
else
Part_Kind := A_Private_Limited_View_Part;
end if;
else
if Is_Public_Unit (Decl) then
Part_Kind := A_Public_Children_Part;
else
Part_Kind := A_Private_Children_Part;
end if;
end if;
elsif not Assigned (Tipe) and then
Part_Kind = A_Visible_Part and then
not Gela.Utils.In_Visible_Part (Decl)
then
Part_Kind := A_Private_Part;
end if;
Check_Part (Item, Part_Kind, Decl);
Point.Item := Item;
Utils.Set_Name_Place (Defining_Name, Point);
end Region_Item;
------------------
-- Region_Items --
------------------
procedure Region_Items
(Element : in Asis.Element;
Point : in out Visibility.Point;
Tipe : in Asis.Declaration;
Overridden : out Boolean)
is
use type Asis.Element_Kinds;
begin
Overridden := False;
case Asis.Elements.Element_Kind (Element) is
when Asis.A_Declaration =>
declare
Names : constant Asis.Defining_Name_List :=
Asis.Declarations.Names (Element);
begin
for I in Names'Range loop
Create.Region_Item (Names (I), Point, Tipe, Overridden);
if Overridden then
return;
end if;
end loop;
end;
when A_Statement =>
declare
Names : constant Asis.Defining_Name_List :=
Asis.Statements.Label_Names (Element);
begin
for I in Names'Range loop
Create.Region_Item (Names (I), Point, Tipe, Overridden);
if Overridden then
return;
end if;
end loop;
end;
when others =>
null;
end case;
end Region_Items;
----------------
-- Use_Clause --
----------------
procedure Use_Clause
(Element : in Asis.Element;
Point : in out Visibility.Point)
is
use Asis.Elements;
Kind : Item_Kinds;
begin
case Clause_Kind (Element) is
when A_Use_Package_Clause =>
Kind := Use_Package;
when A_Use_Type_Clause =>
Kind := Use_Type;
when others =>
return;
end case;
declare
use XASIS.Utils;
use Asis.Gela.Utils;
use Asis.Gela.Errors;
Declaration : Asis.Declaration;
Item : Region_Item_Access;
Name_List : constant Asis.Name_List :=
Clauses.Clause_Names (Element);
Visible : constant Boolean :=
In_Visible_Part (Element) or else
In_Context_Clause (Element);
begin
for I in Name_List'Range loop
Declaration := Selected_Name_Declaration
(Name_List (I), True, True);
Item := new Visibility.Region_Item (Kind);
Item.Part := Point.Item.Part;
Point.Item := Item;
if Kind = Use_Package then
Item.Declaration := Declaration;
else
Item.Tipe := Classes.Type_From_Declaration
(Declaration, Element);
end if;
if not Visible and Item.Part.Kind = A_Visible_Part then
Check_Part (Item, A_Private_Part, Element);
else
Item.Next := Item.Part.Last_Item;
Item.Part.Last_Item := Item;
end if;
if not Assigned (Declaration) then
Report (Name_List (I), Error_Unknown_Name);
end if;
end loop;
end;
end Use_Clause;
end Asis.Gela.Visibility.Create;
------------------------------------------------------------------------------
-- Copyright (c) 2006-2013, Maxim Reznik
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the Maxim Reznik, IE nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
-- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-- POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
|
-- { dg-do compile }
with Discr36_Pkg;
package body Discr36 is
function N return Natural is begin return 0; end;
type Arr is array (1 .. N) of R;
function My_Func is new Discr36_Pkg.Func (Arr);
procedure Proc is
A : constant Arr := My_Func;
begin
null;
end;
end Discr36;
|
with Ada.Numerics.Discrete_Random;
with Ada.Integer_Text_IO, Ada.Text_IO;
use Ada.Integer_Text_IO, Ada.Text_IO;
package body Data is
-- Create All-Ones Matrix And Vector
procedure All_Ones_Matrix (MA: out Matrix) is
begin
for i in 1..N loop
for j in 1..N loop
MA(i,j) := 1;
end loop;
end loop;
end All_Ones_Matrix;
procedure All_Ones_Vector (A: out Vector) is
begin
for i in 1..N loop
A(i) := 1;
end loop;
end All_Ones_Vector;
-- Function That Generate Random Numbers From -10..10
function Rand_Gen return Integer is
subtype randRange is Integer range -10..10;
package Rand_Int is new Ada.Numerics.Discrete_Random(randRange);
use Rand_Int;
gen: Rand_Int.Generator;
begin
Rand_Int.Reset(gen);
return Rand_Int.Random(gen);
end Rand_Gen;
-- Generate And Fill Random Matrix And Vector
procedure Random_Matrix (MA: out Matrix) is
begin
for i in 1..N loop
for j in 1..N loop
MA(i,j) := Rand_Gen;
end loop;
end loop;
end Random_Matrix;
procedure Random_Vector (A: out Vector) is
begin
for i in 1..N loop
A(i) := Rand_Gen;
end loop;
end Random_Vector;
-- Print Matrix And Vector Into Console
procedure Matrix_Output (MA: in Matrix; str: in String) is
begin
Put_Line("Matrix " & str & ":");
for i in 1..N loop
for j in 1..N loop
Put(MA(i,j));
end loop;
New_Line;
end loop;
New_Line;
end Matrix_Output;
procedure Vector_Output (A: in Vector; str: in String) is
begin
Put("Vector " & str & ":");
for i in 1..N loop
Put(A(i));
end loop;
New_Line;
end Vector_Output;
procedure Num_Output (a: in Integer; str: in String) is
begin
Put("Number " & str & ":");
Put(a);
New_Line;
end Num_Output;
--Fill And Print Matrices And Vectors Into Console
procedure Matrix_Input (MA: out Matrix; str: in String) is
begin
Put_Line("Enter the" & Positive'Image(N * N) & " elements of the Matrix " & str & ":");
for i in 1..N loop
for j in 1..N loop
Put(str & "(" & Integer'Image(i) & "." & Integer'Image(j) & " ) = ");
Get(MA(i,j));
end loop;
New_Line;
end loop;
end Matrix_Input;
procedure Vector_Input (A: out Vector; str: in String) is
begin
Put_Line("Enter the" & Positive'Image(N) & " elements of the Vector " & str & ":");
for i in 1..N loop
Put(str & "(" & Integer'Image(i) & " ) = ");
Get(A(i));
end loop;
end Vector_Input;
-- Sort Vector
procedure Sort_Vector(A: in out Vector) is
temp: Integer;
begin
for i in 1..n loop
for j in i..n loop
if A(i)>A(j) then
temp:=A(j);
A(j):=A(i);
A(i):=temp;
end if;
end loop;
end loop;
end Sort_Vector;
-- Calculates Sum Of 2 Vectors
function Sum_Vectors (A, B: in Vector) return Vector is
result: Vector;
begin
for i in 1..N loop
result(i) := A(i) + B(i);
end loop;
return result;
end Sum_Vectors;
-- Transposing Matrix
function Matrix_Transposition(MA: in Matrix) return Matrix is
temp: Integer;
MZ: Matrix;
begin
for i in 1..N loop
for j in 1..N loop
temp := MA(j,i);
MZ(j,i) := MA(i,j);
MZ(i,j) := temp;
end loop;
end loop;
return MZ;
end Matrix_Transposition;
-- Multiply 2 Matrices
function Matrix_Multiplication (MA, MB: in Matrix) return Matrix is
product : Integer;
result: Matrix;
begin
for i in 1..N loop
for j in 1..N loop
product := 0;
for k in 1..N loop
product := product + MA(i,k) * MB(k,j);
end loop;
result(i,j) := product;
end loop;
end loop;
return result;
end Matrix_Multiplication;
-- Multipy Matrix And Vector
function Matrix_Vector_Multiplication (MA: in Matrix; A: in Vector) return Vector is
product: Integer;
result: Vector;
begin
for i in 1..N loop
product := 0;
for j in 1..N loop
product := product + A(j) * MA(j,i);
end loop;
result(i) := product;
end loop;
return result;
end Matrix_Vector_Multiplication;
-- Multipy Integer And Matrix
function Matrix_Integer_Multiplication (MA:in Matrix; a: in Integer) return Matrix is
MZ: Matrix;
begin
for i in 1..N loop
for j in 1..N loop
MZ(i,j) := a * MA(i,j);
end loop;
end loop;
return MZ;
end Matrix_Integer_Multiplication;
-- Generate Initial Values
procedure Input_Val_F1 (A,B,C: out Vector; MA,ME: out Matrix; val: Integer) is
begin
case val is
when 2 =>
Random_Vector(A);
Random_Vector(B);
Random_Vector(C);
Random_Matrix(MA);
Random_Matrix(ME);
if N <= 10 then
Put_Line("Entered values T1:");
Vector_Output(A, "A");
Vector_Output(B, "B");
Vector_Output(C, "C");
Matrix_Output(MA, "MA");
Matrix_Output(ME, "ME");
end if;
when 3 =>
Vector_Input(A, "A");
Vector_Input(B, "B");
Vector_Input(C, "C");
Matrix_Input(MA, "MA");
Matrix_Input(ME, "ME");
Put_Line("Entered values T1:");
Vector_Output(A, "A");
Vector_Output(B, "B");
Vector_Output(C, "C");
Matrix_Output(MA, "MA");
Matrix_Output(ME, "ME");
when others =>
All_Ones_Vector(A);
All_Ones_Vector(B);
All_Ones_Vector(C);
All_Ones_Matrix(MA);
All_Ones_Matrix(ME);
end case;
end Input_Val_F1;
procedure Input_Val_F2 (MG,MH,MK: out Matrix; val: Integer) is
begin
case val is
when 2 =>
Random_Matrix(MG);
Random_Matrix(MH);
Random_Matrix(MK);
if N <= 10 then
Put_Line("Entered values T2:");
Matrix_Output(MG, "MG");
Matrix_Output(MH, "MH");
Matrix_Output(MK, "MK");
end if;
when 3 =>
Matrix_Input(MG, "MG");
Matrix_Input(MH, "MH");
Matrix_Input(MK, "MK");
Put_Line("Entered values T2:");
Matrix_Output(MG, "MG");
Matrix_Output(MH, "MH");
Matrix_Output(MK, "MK");
when others =>
All_Ones_Matrix(MG);
All_Ones_Matrix(MH);
All_Ones_Matrix(MK);
end case;
end Input_Val_F2;
procedure Input_Val_F3 (t: out Integer; V,O,P: out Vector; MO,MP,MR: out Matrix; val: Integer) is
begin
case val is
when 2 =>
t := Rand_Gen;
Random_Vector(V);
Random_Vector(O);
Random_Vector(P);
Random_Matrix(MO);
Random_Matrix(MP);
Random_Matrix(MR);
if N <= 10 then
Put_Line("Entered values T3:");
Num_Output(t, "t");
Vector_Output(V, "V");
Vector_Output(O, "O");
Vector_Output(P, "P");
Matrix_Output(MO, "MO");
Matrix_Output(MP, "MP");
Matrix_Output(MR, "MR");
end if;
when 3 =>
Put("t = ");
Get(t);
Vector_Input(V, "V");
Vector_Input(O, "O");
Vector_Input(P, "P");
Matrix_Input(MO, "MO");
Matrix_Input(MP, "MP");
Matrix_Input(MR, "MR");
Put_Line("Entered values T3:");
Num_Output(t, "t");
Vector_Output(V, "V");
Vector_Output(O, "O");
Vector_Output(P, "P");
Matrix_Output(MO, "MO");
Matrix_Output(MP, "MP");
Matrix_Output(MR, "MR");
when others =>
t := 1;
All_Ones_Vector(V);
All_Ones_Vector(O);
All_Ones_Vector(P);
All_Ones_Matrix(MO);
All_Ones_Matrix(MP);
All_Ones_Matrix(MR);
end case;
end Input_Val_F3;
--Function 1 (SORT(A)+SORT(B)+SORT(C)*(MA*ME))
function Func1 (A,B,C: out Vector; MA,ME: in Matrix) return Vector is
MB: Matrix;
R, O, Q: Vector;
begin
Sort_Vector(A);
Sort_Vector(B);
Sort_Vector(C);
R := Sum_Vectors(A, B);
MB := Matrix_Multiplication(MA, ME);
O := Matrix_Vector_Multiplication(MB, C);
Q := Sum_Vectors(R, O);
return Q;
end Func1;
--Function 2 ((MG*MH)*TRANS(MK))
function Func2 (MG,MH, MK: in Matrix) return Matrix is
MA, MB, MC: Matrix;
begin
MA := Matrix_Multiplication(MG,MH);
MB := Matrix_Transposition(MK);
MC := Matrix_Multiplication(MA, MB);
return MC;
end Func2;
--Function 3 ((MO*MP)*V+t*MR*(O+P))
function Func3 (t: in Integer; V, O, P: in Vector; MO, MP, MR: in Matrix) return Vector is
A,B,C,D: Vector;
MM,MZ: Matrix;
begin
MM := Matrix_Multiplication(MO, MP);
A := Matrix_Vector_Multiplication(MM, V);
B := Sum_Vectors(O,P);
MZ := Matrix_Integer_Multiplication(MR, t);
C := Matrix_Vector_Multiplication(MZ, B);
D := Sum_Vectors(A, C);
return D;
end Func3;
end data;
|
---------------------------------------------------------------------------
-- package body rectangular_test_matrices, test matrix generator
-- Copyright (C) 2018 Jonathan S. Parker.
--
-- 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.Numerics.Discrete_Random;
package body Rectangular_Test_Matrices is
type Unsigned32 is mod 2**32;
package Discrete_32_bit is new Ada.Numerics.Discrete_Random (Unsigned32);
Random_Stream_id : Discrete_32_bit.Generator;
function Real_Random return Real is
X : Real := 0.0;
begin
-- up to 64 random bits in X:
--X := 2.0**(-32) * Real (Discrete_32_bit.Random (Random_Stream_id))
--+ 2.0**(-64) * Real (Discrete_32_bit.Random (Random_Stream_id));
-- 16 random bits in X:
--X := 2.0**(32-16) * Real (Discrete_32_bit.Random (Random_Stream_id) / 2**(32-16));
X := 2.0**(-16) * Real (Discrete_32_bit.Random (Random_Stream_id) / 2**(32-16));
-- 1 random bit in X:
--X := 2.0**(-1) * Real (Discrete_32_bit.Random (Random_Stream_id) / 2**(32-1));
return X;
end Real_Random;
procedure Init_Matrix
(M : out Matrix;
Desired_Matrix : in Matrix_Id := Random;
Final_Row : in R_Index := R_Index'Last;
Final_Col : in C_Index := C_Index'Last;
Starting_Row : in R_Index := R_Index'First;
Starting_Col : in C_Index := C_Index'First) is
Denominator : Real;
begin
M := (others => (others => 0.0)); --essential init.
--the 0.0 is essential.
case Desired_Matrix is
when Zero_Diagonal =>
declare
Row : R_Index := Starting_Row;
begin
for Col in C_Index range Starting_Col+1 .. C_Index'Last loop
M(Row, Col) := 1.0;
if Row < R_Index'Last then Row := Row + 1; else exit; end if;
end loop;
Row := Starting_Row+1;
for Col in C_Index range Starting_Col .. C_Index'Last-1 loop
M(Row, Col) := 1.0;
if Row < R_Index'Last then Row := Row + 1; else exit; end if;
end loop;
end;
when Upper_Ones =>
M := (others => (others => 1.0)); --essential init.
declare
Row_Starting_Index : R_Index := Starting_Row;
begin
for Col in C_Index range Starting_Col .. Final_Col loop
for Row in Row_Starting_Index .. R_Index'Last loop
M(Row, Col) := 0.0;
end loop;
if Row_Starting_Index < R_Index'Last then
Row_Starting_Index := Row_Starting_Index + 1;
else
exit;
end if;
end loop;
end;
declare
Row : R_Index := Starting_Row;
begin
for Col in C_Index range Starting_Col .. Final_Col loop
M(Row, Col) := 1.0;
if Row < R_Index'Last then
Row := Row + 1;
else
exit;
end if;
end loop;
end;
when Lower_Ones =>
M := (others => (others => 0.0)); --essential init.
declare
Row_Starting_Index : R_Index := Starting_Row;
begin
for Col in C_Index range Starting_Col .. C_Index'Last loop
for Row in Row_Starting_Index .. R_Index'Last loop
M(Row, Col) := 1.0;
end loop;
if Row_Starting_Index < R_Index'Last then
Row_Starting_Index := Row_Starting_Index + 1;
else
exit;
end if;
end loop;
end;
when Random =>
Discrete_32_bit.Reset (Random_Stream_id);
for Row in R_Index loop
for Col in C_Index loop
M(Row, Col) := Real_Random;
end loop;
end loop;
when Zero_Cols_and_Rows =>
Discrete_32_bit.Reset (Random_Stream_id);
for Row in R_Index loop
for Col in C_Index loop
M(Row, Col) := Real_Random;
end loop;
end loop;
for Row in Starting_Row .. Starting_Row+2 loop
for Col in Starting_Col .. C_Index'Last loop
M(Row, Col) := 0.0;
end loop;
end loop;
for Col in Starting_Col .. Starting_Col+2 loop
for Row in Starting_Row .. R_Index'Last loop
M(Row, Col) := 0.0;
end loop;
end loop;
when Frank =>
declare
c, r : Real;
begin
for Row in R_Index loop
for Col in C_Index loop
c := Real(Col) - Real(C_Index'First);
r := Real(Row) - Real(R_Index'First);
M(Row, Col) := Real'Min (c,r) + 1.0;
end loop;
end loop;
end;
when Ding_Dong =>
for Row in Starting_Row .. R_Index'Last loop
for Col in Starting_Col .. C_Index'Last loop
Denominator := Real(R_Index'Last)
+ Real(Starting_Row) - Real(Row) - Real(Col) + 0.5;
M(Row, Col) := 1.0 / Denominator;
end loop;
end loop;
when Vandermonde =>
--A := 1.0 / 16.0; -- up to 256 x 256 matrix without over/under flow (if digits 15).
--A := 1.0; -- up to 128 x 128 matrix ? without over/under flow (if digits 15).
Vandermondes_Matrix:
declare
Exp, X_Count : Integer;
X : Real;
Half_No_Of_Rows : constant Integer
:= (Integer(Final_Row) - Integer(Starting_Row) + 1)/2;
B : constant Real := 1.0 / Real (Half_No_Of_Rows);
A : constant Real := 2.0 ** (Real'Exponent(B) - 1);
begin
for Row in Starting_Row .. R_Index'Last loop
for Col in Starting_Col .. C_Index'Last loop
Exp := Integer(Col) - Integer(Starting_Col);
X_Count := Integer(Row) - Integer(Starting_Row);
X := A * (Real (X_Count - Half_No_Of_Rows));
M(Row, Col) := X ** Exp;
end loop;
end loop;
end Vandermondes_Matrix;
when All_Ones =>
M := (others => (others => 1.0));
when All_Zeros =>
M := (others => (others => 0.0));
end case;
end Init_Matrix;
end Rectangular_Test_Matrices;
|
pragma Ada_2012;
pragma Style_Checks (Off);
with Interfaces.C; use Interfaces.C;
with Interfaces.C.Strings;
package Pixtend.wiringSerial_h is
function serialOpen (device : Interfaces.C.Strings.chars_ptr; baud : int) return int -- wiringSerial.h:27
with Import => True,
Convention => C,
External_Name => "serialOpen";
procedure serialClose (fd : int) -- wiringSerial.h:28
with Import => True,
Convention => C,
External_Name => "serialClose";
procedure serialFlush (fd : int) -- wiringSerial.h:29
with Import => True,
Convention => C,
External_Name => "serialFlush";
procedure serialPutchar (fd : int; c : unsigned_char) -- wiringSerial.h:30
with Import => True,
Convention => C,
External_Name => "serialPutchar";
procedure serialPuts (fd : int; s : Interfaces.C.Strings.chars_ptr) -- wiringSerial.h:31
with Import => True,
Convention => C,
External_Name => "serialPuts";
procedure serialPrintf (fd : int; message : Interfaces.C.Strings.chars_ptr -- , ...
) -- wiringSerial.h:32
with Import => True,
Convention => C,
External_Name => "serialPrintf";
function serialDataAvail (fd : int) return int -- wiringSerial.h:33
with Import => True,
Convention => C,
External_Name => "serialDataAvail";
function serialGetchar (fd : int) return int -- wiringSerial.h:34
with Import => True,
Convention => C,
External_Name => "serialGetchar";
end Pixtend.wiringSerial_h;
|
with ZMQ.Sockets;
with ZMQ.Contexts;
with Ada.Text_IO;
procedure ZMQ.examples.Display is
use Ada.Text_IO;
Context : aliased Contexts.Context;
Socket : Sockets.Socket;
begin
Context.Initialize (1);
Socket.Initialize (Context, Sockets.SUB);
Socket.Establish_message_filter ("");
Socket.Bind ("tcp://lo:5555");
Ada.Text_IO.Put_Line ("Connected");
Read_Loop : loop
declare
Buffer : constant String := Socket.recv;
begin
Ada.Text_IO.Put_Line (Buffer);
exit Read_Loop when Buffer = END_MESSAGE;
end;
end loop Read_Loop;
end ZMQ.Examples.Display;
|
with
AdaM.Context,
gtk.Widget;
private
with
gtk.Label,
gtk.Frame,
gtk.Box;
package aIDE.Editor.of_context
is
type Item is new Editor.item with private;
type View is access all Item'Class;
package Forge
is
function to_context_Editor (the_Context : in AdaM.Context.view) return View;
end Forge;
overriding
function top_Widget (Self : in Item) return gtk.Widget.Gtk_Widget;
overriding
procedure freshen (Self : in out Item);
procedure Context_is (Self : in out Item; Now : in AdaM.Context.view);
private
use gtk.Widget,
gtk.Box,
gtk.Label,
gtk.Frame;
type Item is new Editor.item with
record
Context : AdaM.Context.view;
Top : Gtk_Frame;
context_Label : Gtk_Label;
context_lines_Box : Gtk_Box;
end record;
end aIDE.Editor.of_context;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- I N L I N E --
-- --
-- S p e c --
-- --
-- Copyright (C) 1992-2016, Free Software Foundation, Inc. --
-- --
-- GNAT is free software; you can redistribute it and/or modify it under --
-- terms of the GNU General Public License as published by the Free Soft- --
-- ware Foundation; either version 3, or (at your option) any later ver- --
-- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
-- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
-- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
-- for more details. You should have received a copy of the GNU General --
-- Public License distributed with GNAT; see file COPYING3. If not, go to --
-- http://www.gnu.org/licenses for a complete copy of the license. --
-- --
-- GNAT was originally developed by the GNAT team at New York University. --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
-- This module handles four kinds of inlining activity:
-- a) Instantiation of generic bodies. This is done unconditionally, after
-- analysis and expansion of the main unit.
-- b) Compilation of unit bodies that contain the bodies of inlined sub-
-- programs. This is done only if inlining is enabled (-gnatn). Full inlining
-- requires that a) and b) be mutually recursive, because each step may
-- generate another generic expansion and further inlined calls.
-- c) Front-end inlining for Inline_Always subprograms. This is primarily an
-- expansion activity that is performed for performance reasons, and when the
-- target does not use the GCC back end.
-- d) Front-end inlining for GNATprove, to perform source transformations
-- to simplify formal verification. The machinery used is the same as for
-- Inline_Always subprograms, but there are fewer restrictions on the source
-- of subprograms.
with Alloc;
with Opt; use Opt;
with Sem; use Sem;
with Table;
with Types; use Types;
with Warnsw; use Warnsw;
package Inline is
--------------------------------
-- Generic Body Instantiation --
--------------------------------
-- The bodies of generic instantiations are built after semantic analysis
-- of the main unit is complete. Generic instantiations are saved in a
-- global data structure, and the bodies constructed by means of a separate
-- analysis and expansion step.
-- See full description in body of Sem_Ch12 for more details
type Pending_Body_Info is record
Inst_Node : Node_Id;
-- Node for instantiation that requires the body
Act_Decl : Node_Id;
-- Declaration for package or subprogram spec for instantiation
Expander_Status : Boolean;
-- If the body is instantiated only for semantic checking, expansion
-- must be inhibited.
Current_Sem_Unit : Unit_Number_Type;
-- The semantic unit within which the instantiation is found. Must be
-- restored when compiling the body, to insure that internal entities
-- use the same counter and are unique over spec and body.
Scope_Suppress : Suppress_Record;
Local_Suppress_Stack_Top : Suppress_Stack_Entry_Ptr;
-- Save suppress information at the point of instantiation. Used to
-- properly inherit check status active at this point (see RM 11.5
-- (7.2/2), AI95-00224-01):
--
-- "If a checking pragma applies to a generic instantiation, then the
-- checking pragma also applies to the instance. If a checking pragma
-- applies to a call to a subprogram that has a pragma Inline applied
-- to it, then the checking pragma also applies to the inlined
-- subprogram body".
--
-- This means we have to capture this information from the current scope
-- at the point of instantiation.
Version : Ada_Version_Type;
-- The body must be compiled with the same language version as the
-- spec. The version may be set by a configuration pragma in a separate
-- file or in the current file, and may differ from body to body.
Version_Pragma : Node_Id;
-- This is linked with the Version value
Warnings : Warning_Record;
-- Capture values of warning flags
SPARK_Mode : SPARK_Mode_Type;
SPARK_Mode_Pragma : Node_Id;
-- SPARK_Mode for an instance is the one applicable at the point of
-- instantiation. SPARK_Mode_Pragma is the related active pragma.
end record;
package Pending_Instantiations is new Table.Table (
Table_Component_Type => Pending_Body_Info,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.Pending_Instantiations_Initial,
Table_Increment => Alloc.Pending_Instantiations_Increment,
Table_Name => "Pending_Instantiations");
-- The following table records subprograms and packages for which
-- generation of subprogram descriptors must be delayed.
package Pending_Descriptor is new Table.Table (
Table_Component_Type => Entity_Id,
Table_Index_Type => Int,
Table_Low_Bound => 0,
Table_Initial => Alloc.Pending_Instantiations_Initial,
Table_Increment => Alloc.Pending_Instantiations_Increment,
Table_Name => "Pending_Descriptor");
-- The following should be initialized in an init call in Frontend, we
-- have thoughts of making the frontend reusable in future ???
-----------------
-- Subprograms --
-----------------
procedure Initialize;
-- Initialize internal tables
procedure Lock;
-- Lock internal tables before calling backend
procedure Instantiate_Bodies;
-- This procedure is called after semantic analysis is complete, to
-- instantiate the bodies of generic instantiations that appear in the
-- compilation unit.
procedure Add_Inlined_Body (E : Entity_Id; N : Node_Id);
-- E is an inlined subprogram appearing in a call, either explicitly or in
-- a discriminant check for which gigi builds a call or an at-end handler.
-- Add E's enclosing unit to Inlined_Bodies so that E can be subsequently
-- retrieved and analyzed. N is the node giving rise to the call to E.
procedure Analyze_Inlined_Bodies;
-- At end of compilation, analyze the bodies of all units that contain
-- inlined subprograms that are actually called.
procedure Build_Body_To_Inline (N : Node_Id; Spec_Id : Entity_Id);
-- If a subprogram has pragma Inline and inlining is active, use generic
-- machinery to build an unexpanded body for the subprogram. This body is
-- subsequently used for inline expansions at call sites. If subprogram can
-- be inlined (depending on size and nature of local declarations) the
-- template body is created. Otherwise subprogram body is treated normally
-- and calls are not inlined in the frontend. If proper warnings are
-- enabled and the subprogram contains a construct that cannot be inlined,
-- the problematic construct is flagged accordingly.
function Call_Can_Be_Inlined_In_GNATprove_Mode
(N : Node_Id;
Subp : Entity_Id) return Boolean;
-- Returns False if the call in node N to subprogram Subp cannot be inlined
-- in GNATprove mode, because it may lead to missing a check on type
-- conversion of input parameters otherwise. Returns True otherwise.
function Can_Be_Inlined_In_GNATprove_Mode
(Spec_Id : Entity_Id;
Body_Id : Entity_Id) return Boolean;
-- Returns True if the subprogram identified by Spec_Id and Body_Id can
-- be inlined in GNATprove mode. One but not both of Spec_Id and Body_Id
-- can be Empty. Body_Id is Empty when doing a partial check on a call
-- to a subprogram whose body has not been seen yet, to know whether this
-- subprogram could possibly be inlined. GNATprove relies on this to adapt
-- its treatment of the subprogram.
procedure Cannot_Inline
(Msg : String;
N : Node_Id;
Subp : Entity_Id;
Is_Serious : Boolean := False);
-- This procedure is called if the node N, an instance of a call to
-- subprogram Subp, cannot be inlined. Msg is the message to be issued,
-- which ends with ? (it does not end with ?p?, this routine takes care of
-- the need to change ? to ?p?). The behavior of this routine depends on
-- the value of Back_End_Inlining:
--
-- * If Back_End_Inlining is not set (ie. legacy frontend inlining model)
-- then if Subp has a pragma Always_Inlined, then an error message is
-- issued (by removing the last character of Msg). If Subp is not
-- Always_Inlined, then a warning is issued if the flag Ineffective_
-- Inline_Warnings is set, adding ?p to the msg, and if not, the call
-- has no effect.
--
-- * If Back_End_Inlining is set then:
-- - If Is_Serious is true, then an error is reported (by removing the
-- last character of Msg);
--
-- - otherwise:
--
-- * Compiling without optimizations if Subp has a pragma
-- Always_Inlined, then an error message is issued; if Subp is
-- not Always_Inlined, then a warning is issued if the flag
-- Ineffective_Inline_Warnings is set (adding p?), and if not,
-- the call has no effect.
--
-- * Compiling with optimizations then a warning is issued if the
-- flag Ineffective_Inline_Warnings is set (adding p?); otherwise
-- no effect since inlining may be performed by the backend.
procedure Check_And_Split_Unconstrained_Function
(N : Node_Id;
Spec_Id : Entity_Id;
Body_Id : Entity_Id);
-- Spec_Id and Body_Id are the entities of the specification and body of
-- the subprogram body N. If N can be inlined by the frontend (supported
-- cases documented in Check_Body_To_Inline) then build the body-to-inline
-- associated with N and attach it to the declaration node of Spec_Id.
procedure Check_Package_Body_For_Inlining (N : Node_Id; P : Entity_Id);
-- If front-end inlining is enabled and a package declaration contains
-- inlined subprograms, load and compile the package body to collect the
-- bodies of these subprograms, so they are available to inline calls.
-- N is the compilation unit for the package.
procedure Expand_Inlined_Call
(N : Node_Id;
Subp : Entity_Id;
Orig_Subp : Entity_Id);
-- If called subprogram can be inlined by the front-end, retrieve the
-- analyzed body, replace formals with actuals and expand call in place.
-- Generate thunks for actuals that are expressions, and insert the
-- corresponding constant declarations before the call. If the original
-- call is to a derived operation, the return type is the one of the
-- derived operation, but the body is that of the original, so return
-- expressions in the body must be converted to the desired type (which
-- is simply not noted in the tree without inline expansion).
function Has_Excluded_Declaration
(Subp : Entity_Id;
Decls : List_Id) return Boolean;
-- Check a list of declarations, Decls, that make the inlining of Subp not
-- worthwhile
function Has_Excluded_Statement
(Subp : Entity_Id;
Stats : List_Id) return Boolean;
-- Check a list of statements, Stats, that make inlining of Subp not
-- worthwhile, including any tasking statement, nested at any level.
procedure List_Inlining_Info;
-- Generate listing of calls inlined by the frontend plus listing of
-- calls to inline subprograms passed to the backend.
procedure Remove_Dead_Instance (N : Node_Id);
-- If an instantiation appears in unreachable code, delete the pending
-- body instance.
end Inline;
|
with Ada.Text_IO, GNAT.Bubble_Sort;
use Ada.Text_IO;
procedure DisjointSort is
package Int_Io is new Integer_IO (Integer);
subtype Index_Range is Natural range 1 .. 8;
Input_Array : array (Index_Range) of Integer := (7, 6, 5, 4, 3, 2, 1, 0);
subtype Subindex_Range is Natural range 1 .. 3;
type Sub_Arrays is array (Subindex_Range) of Integer;
Sub_Index : Sub_Arrays := (7, 2, 8);
Sub_Array : Sub_Arrays;
-- reuse of the somehow generic GNAT.Bubble_Sort (for Ada05)
procedure Sort (Work_Array : in out Sub_Arrays) is
procedure Exchange (Op1, Op2 : Natural) is
Temp : Integer;
begin
Temp := Work_Array (Op1);
Work_Array (Op1) := Work_Array (Op2);
Work_Array (Op2) := Temp;
end Exchange;
function Lt (Op1, Op2 : Natural) return Boolean is
begin
return (Work_Array (Op1) < Work_Array (Op2));
end Lt;
begin
GNAT.Bubble_Sort.Sort
(N => Subindex_Range'Last,
Xchg => Exchange'Unrestricted_Access,
Lt => Lt'Unrestricted_Access);
end Sort;
begin
-- as the positions are not ordered, first sort the positions
Sort (Sub_Index);
-- extract the values to be sorted
for I in Subindex_Range loop
Sub_Array (I) := Input_Array (Sub_Index (I));
end loop;
Sort (Sub_Array);
-- put the sorted values at the right place
for I in Subindex_Range loop
Input_Array (Sub_Index (I)) := Sub_Array (I);
end loop;
for I in Index_Range loop
Int_Io.Put (Input_Array (I), Width => 2);
end loop;
New_Line;
end DisjointSort;
|
with System;
with Interfaces; use Interfaces;
with Interfaces.C; use Interfaces.C;
with HAL.GPIO;
with SAM.Clock_Generator.IDs;
with SAM.Main_Clock;
with SAM.DAC; use SAM.DAC;
with SAM.Device;
with SAM.DMAC; use SAM.DMAC;
with SAM.DMAC.Sources;
with SAM.TC; use SAM.TC;
with SAM.Interrupt_Names;
with Cortex_M.NVIC;
with HAL; use HAL;
package body PyGamer.Audio is
User_Callback : Audio_Callback := null;
Buffer_Size : constant := 64;
Buffer_Left_0 : Data_Array (1 .. Buffer_Size);
Buffer_Left_1 : Data_Array (1 .. Buffer_Size);
Buffer_Right_0 : Data_Array (1 .. Buffer_Size);
Buffer_Right_1 : Data_Array (1 .. Buffer_Size);
Flip : Boolean := False;
procedure DMA_Int_Handler;
pragma Export (C, DMA_Int_Handler, "__dmac_tcmpl_0_handler");
---------------------
-- DMA_Int_Handler --
---------------------
procedure DMA_Int_Handler is
Buffer_0 : System.Address := (if Flip
then Buffer_Left_0'Address
else Buffer_Left_1'Address);
Buffer_1 : System.Address := (if Flip
then Buffer_Right_0'Address
else Buffer_Right_1'Address);
begin
Cortex_M.NVIC.Clear_Pending (SAM.Interrupt_Names.dmac_0_interrupt);
Clear (DMA_DAC_0, Transfer_Complete);
Clear (DMA_DAC_1, Transfer_Complete);
Set_Data_Transfer (DMA_Descs (DMA_DAC_0),
Block_Transfer_Count => Buffer_Left_0'Length,
Src_Addr => Buffer_0,
Dst_Addr => SAM.DAC.Data_Address (0));
Set_Data_Transfer (DMA_Descs (DMA_DAC_1),
Block_Transfer_Count => Buffer_Right_0'Length,
Src_Addr => Buffer_1,
Dst_Addr => SAM.DAC.Data_Address (1));
Enable (DMA_DAC_0);
Enable (DMA_DAC_1);
if User_Callback /= null then
if Flip then
User_Callback (Buffer_Left_1, Buffer_Right_1);
else
User_Callback (Buffer_Left_0, Buffer_Right_0);
end if;
else
if Flip then
Buffer_Left_1 := (others => 0);
Buffer_Right_1 := (others => 0);
else
Buffer_Left_0 := (others => 0);
Buffer_Right_0 := (others => 0);
end if;
end if;
Flip := not Flip;
end DMA_Int_Handler;
------------------
-- Set_Callback --
------------------
procedure Set_Callback (Callback : Audio_Callback;
Sample_Rate : Sample_Rate_Kind)
is
begin
User_Callback := Callback;
-- Set the timer period coresponding to the requested sample rate
SAM.Device.TC0.Set_Period
(case Sample_Rate is
when SR_11025 => UInt8 ((UInt32 (48000000) / 64) / 11025),
when SR_22050 => UInt8 ((UInt32 (48000000) / 64) / 22050),
when SR_44100 => UInt8 ((UInt32 (48000000) / 64) / 44100),
when SR_96000 => UInt8 ((UInt32 (48000000) / 64) / 96000));
end Set_Callback;
begin
-- DAC --
SAM.Clock_Generator.Configure_Periph_Channel
(SAM.Clock_Generator.IDs.DAC, Clk_48Mhz);
SAM.Main_Clock.DAC_On;
SAM.DAC.Configure (Single_Mode, VREFAB);
Debug_Stop_Mode (False);
Configure_Channel (Chan => 0,
Oversampling => OSR_16,
Refresh => 0,
Enable_Dithering => True,
Run_In_Standby => True,
Standalone_Filter => False,
Current => CC1M,
Adjustement => Right_Adjusted,
Enable_Filter_Result_Ready_Evt => False,
Enable_Data_Buffer_Empty_Evt => False,
Enable_Convert_On_Input_Evt => False,
Invert_Input_Evt => False,
Enable_Overrun_Int => False,
Enable_Underrun_Int => False,
Enable_Result_Ready_Int => False,
Enable_Buffer_Empty_Int => False);
Configure_Channel (Chan => 1,
Oversampling => OSR_16,
Refresh => 0,
Enable_Dithering => True,
Run_In_Standby => True,
Standalone_Filter => False,
Current => CC1M,
Adjustement => Right_Adjusted,
Enable_Filter_Result_Ready_Evt => False,
Enable_Data_Buffer_Empty_Evt => False,
Enable_Convert_On_Input_Evt => False,
Invert_Input_Evt => False,
Enable_Overrun_Int => False,
Enable_Underrun_Int => False,
Enable_Result_Ready_Int => False,
Enable_Buffer_Empty_Int => False);
Enable (Chan_0 => True,
Chan_1 => True);
-- Enable speaker --
SAM.Device.PA27.Set_Mode (HAL.GPIO.Output);
SAM.Device.PA27.Set;
-- DMA --
Configure (DMA_DAC_0,
Trig_Src => SAM.DMAC.Sources.TC0_OVF,
Trig_Action => Burst,
Priority => 1,
Burst_Len => 1,
Threshold => BEAT_1,
Run_In_Standby => False);
-- Only enable the channel 0 interrupt
Enable (DMA_DAC_0, Transfer_Complete);
Cortex_M.NVIC.Enable_Interrupt (SAM.Interrupt_Names.dmac_0_interrupt);
Configure (DMA_DAC_1,
Trig_Src => SAM.DMAC.Sources.TC0_OVF,
Trig_Action => Burst,
Priority => 1,
Burst_Len => 1,
Threshold => BEAT_1,
Run_In_Standby => False);
Configure_Descriptor (DMA_Descs (DMA_DAC_0),
Valid => True,
Event_Output => Disable,
Block_Action => Interrupt,
Beat_Size => B_16bit,
Src_Addr_Inc => True,
Dst_Addr_Inc => False,
Step_Selection => Source,
Step_Size => X1);
Configure_Descriptor (DMA_Descs (DMA_DAC_1),
Valid => True,
Event_Output => Disable,
Block_Action => Interrupt,
Beat_Size => B_16bit,
Src_Addr_Inc => True,
Dst_Addr_Inc => False,
Step_Selection => Source,
Step_Size => X1);
-- Timer --
SAM.Clock_Generator.Configure_Periph_Channel
(SAM.Clock_Generator.IDs.TC0, Clk_48Mhz);
SAM.Main_Clock.TC0_On;
SAM.Device.TC0.Configure (Mode => TC_8bit,
Prescaler => DIV64,
Run_In_Standby => True,
Clock_On_Demand => False,
Auto_Lock => False,
Capture_0_Enable => False,
Capture_1_Enable => False,
Capture_0_On_Pin => False,
Capture_1_On_Pin => False,
Capture_0_Mode => Default,
Capture_1_Mode => Default);
-- Start the time with the longest period to have a reduced number of
-- interrupt until the audio is actually used.
SAM.Device.TC0.Set_Period (255);
SAM.Device.TC0.Enable;
-- Start the first DMA transfer
DMA_Int_Handler;
end PyGamer.Audio;
|
with Ada.Text_IO;
with Apollonius;
procedure Test_Apollonius is
use Apollonius;
package Long_Float_IO is new Ada.Text_IO.Float_IO (Long_Float);
C1 : constant Circle := (Center => (X => 0.0, Y => 0.0), Radius => 1.0);
C2 : constant Circle := (Center => (X => 4.0, Y => 0.0), Radius => 1.0);
C3 : constant Circle := (Center => (X => 2.0, Y => 4.0), Radius => 2.0);
R1 : Circle := Solve_CCC (C1, C2, C3, External, External, External);
R2 : Circle := Solve_CCC (C1, C2, C3, Internal, Internal, Internal);
begin
Ada.Text_IO.Put_Line ("R1:");
Long_Float_IO.Put (R1.Center.X, Aft => 3, Exp => 0);
Long_Float_IO.Put (R1.Center.Y, Aft => 3, Exp => 0);
Long_Float_IO.Put (R1.Radius, Aft => 3, Exp => 0);
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line ("R2:");
Long_Float_IO.Put (R2.Center.X, Aft => 3, Exp => 0);
Long_Float_IO.Put (R2.Center.Y, Aft => 3, Exp => 0);
Long_Float_IO.Put (R2.Radius, Aft => 3, Exp => 0);
Ada.Text_IO.New_Line;
end Test_Apollonius;
|
with Interfaces; use Interfaces;
with Ada.Streams.Stream_IO; use Ada.Streams;
with Ada.Text_IO;
package BMP is
type Header is record
Signature : Integer_16;
Size : Integer_32;
Reserved1 : Integer_16;
Reserved2 : Integer_16;
Offset : Integer_32;
end record;
type Info is record
Struct_Size : Integer_32;
Width : Integer_32; -- Image width in pixels
Height : Integer_32; -- Image hieght in pixels
Planes : Integer_16;
Pixel_Size : Integer_16; -- Bits per pixel
Compression : Integer_32; -- Zero means no compression
Image_Size : Integer_32; -- Size of the image data in bytes
PPMX : Integer_32; -- Pixels per meter in x led
PPMY : Integer_32; -- Pixels per meter in y led
Palette_Size : Integer_32; -- Number of colors
Important : Integer_32;
end record;
type Pixel_RGB24 is record
B, G, R : Unsigned_8;
end record with Pack, Size => 24;
type Image_RGB24 is array (Integer range <>) of Pixel_RGB24 with Pack;
type Unsigned_1 is mod 2**1 with Size => 1;
type Unsigned_2 is mod 2**2 with Size => 2;
type Unsigned_4 is mod 2**4 with Size => 4;
type P1_Array is array (Integer range <>) of Unsigned_1 with Pack;
type P2_Array is array (Integer range <>) of Unsigned_2 with Pack;
type P4_Array is array (Integer range <>) of Unsigned_4 with Pack;
type P8_Array is array (Integer range <>) of Unsigned_8 with Pack;
type Pix_Index_Size is (Pix_1, Pix_2, Pix_4, Pix_8);
type Pix_Index_Rec (Size : Pix_Index_Size := Pix_8) is record
case Size is
when Pix_1 => P1 : P1_Array (0 .. 7);
when Pix_2 => P2 : P2_Array (0 .. 3);
when Pix_4 => P4 : P4_Array (0 .. 1);
when Pix_8 => P8 : P8_Array (0 .. 0);
end case;
end record with Pack, Size => 8, Unchecked_Union;
type Pix_Index_Array is array (Integer range <>) of Pix_Index_Rec;
type Color_Definition is record
B, G, R, A : Unsigned_8;
end record with Pack, Size => 4 * 8;
type Palette is array (Unsigned_8 range <>) of Color_Definition with Pack;
procedure Standard
(File_In : Stream_IO.File_Type;
Input : Stream_IO.Stream_Access;
File_Out : Ada.Text_IO.File_Type;
Package_Name : String;
Header : BMP.Header;
Info : BMP.Info;
Row_Size : Integer);
procedure Palettized
(File_In : Stream_IO.File_Type;
Input : Stream_IO.Stream_Access;
File_Out : Ada.Text_IO.File_Type;
Package_Name : String;
Header : BMP.Header;
Info : BMP.Info;
Row_Size : Integer);
DMA2D_Format : Boolean := False;
Verbose : Boolean := False;
end BMP;
|
with MPFR.Root_FR;
generic
Precision : in MPFR.Precision := Default_Precision;
Rounding : in MPFR.Rounding := Default_Rounding;
package MPFR.Generic_FR is
pragma Preelaborate;
type MP_Float is new Root_FR.MP_Float (Precision);
-- conversions
function To_MP_Float (X : Long_Long_Float) return MP_Float;
function "+" (Right : Long_Long_Float) return MP_Float renames To_MP_Float;
function To_Long_Long_Float (X : MP_Float) return Long_Long_Float;
function "+" (Right : MP_Float) return Long_Long_Float
renames To_Long_Long_Float;
pragma Inline (To_MP_Float);
pragma Inline (To_Long_Long_Float);
-- formatting
function Image (Value : MP_Float; Base : Number_Base := 10) return String;
function Value (Image : String; Base : Number_Base := 10) return MP_Float;
pragma Inline (Image);
pragma Inline (Value);
-- relational operators are inherited
-- unary adding operators
function "+" (Right : MP_Float) return MP_Float;
function "-" (Right : MP_Float) return MP_Float;
pragma Inline ("+");
pragma Inline ("-");
-- binary adding operators
function "+" (Left, Right : MP_Float) return MP_Float;
function "+" (Left : MP_Float; Right : Long_Long_Float) return MP_Float;
function "+" (Left : Long_Long_Float; Right : MP_Float) return MP_Float;
function "-" (Left, Right : MP_Float) return MP_Float;
function "-" (Left : MP_Float; Right : Long_Long_Float) return MP_Float;
function "-" (Left : Long_Long_Float; Right : MP_Float) return MP_Float;
pragma Inline ("+");
pragma Inline ("-");
-- multiplying operators
function "*" (Left, Right : MP_Float) return MP_Float;
function "*" (Left : MP_Float; Right : Long_Long_Float) return MP_Float;
function "*" (Left : Long_Long_Float; Right : MP_Float) return MP_Float;
function "/" (Left, Right : MP_Float) return MP_Float;
function "/" (Left : MP_Float; Right : Long_Long_Float) return MP_Float;
function "/" (Left : Long_Long_Float; Right : MP_Float) return MP_Float;
pragma Inline ("*");
pragma Inline ("/");
-- highest precedence operators
function "**" (Left : MP_Float; Right : Integer) return MP_Float;
pragma Inline ("**");
-- subprograms of a scalar type
function Sqrt (X : MP_Float) return MP_Float;
pragma Inline (Sqrt);
-- miscellany
function NaN return MP_Float;
function Infinity return MP_Float;
pragma Inline (NaN);
pragma Inline (Infinity);
end MPFR.Generic_FR;
|
-----------------------------------------------------------------------
-- ado-connections -- Database connections
-- Copyright (C) 2010, 2011, 2012, 2016, 2017, 2018, 2019 Stephane Carrez
-- Written by Stephane Carrez (Stephane.Carrez@gmail.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-----------------------------------------------------------------------
with Ada.Finalization;
with ADO.Statements;
with ADO.Schemas;
with ADO.Configs;
with Util.Strings;
with Util.Strings.Vectors;
with Util.Refs;
-- The `ADO.Connections` package represents the database driver that will create
-- database connections and provide the database specific implementation.
package ADO.Connections is
use ADO.Statements;
-- Raised for all errors reported by the database.
Database_Error : exception;
type Driver is abstract tagged limited private;
type Driver_Access is access all Driver'Class;
subtype Driver_Index is ADO.Configs.Driver_Index range 1 .. ADO.Configs.Driver_Index'Last;
-- ------------------------------
-- Database connection implementation
-- ------------------------------
--
type Database_Connection is abstract new Util.Refs.Ref_Entity with record
Ident : String (1 .. 8) := (others => ' ');
end record;
type Database_Connection_Access is access all Database_Connection'Class;
-- Get the database driver index.
function Get_Driver_Index (Database : in Database_Connection) return Driver_Index;
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Query_Statement_Access is abstract;
function Create_Statement (Database : in Database_Connection;
Query : in String)
return Query_Statement_Access is abstract;
-- Create a delete statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Delete_Statement_Access is abstract;
-- Create an insert statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Insert_Statement_Access is abstract;
-- Create an update statement.
function Create_Statement (Database : in Database_Connection;
Table : in ADO.Schemas.Class_Mapping_Access)
return Update_Statement_Access is abstract;
-- Start a transaction.
procedure Begin_Transaction (Database : in out Database_Connection) is abstract;
-- Commit the current transaction.
procedure Commit (Database : in out Database_Connection) is abstract;
-- Rollback the current transaction.
procedure Rollback (Database : in out Database_Connection) is abstract;
-- Load the database schema definition for the current database.
procedure Load_Schema (Database : in Database_Connection;
Schema : out ADO.Schemas.Schema_Definition) is abstract;
-- Get the database driver which manages this connection.
function Get_Driver (Database : in Database_Connection)
return Driver_Access is abstract;
-- Closes the database connection
procedure Close (Database : in out Database_Connection) is abstract;
package Ref is
new Util.Refs.Indefinite_References (Element_Type => Database_Connection'Class,
Element_Access => Database_Connection_Access);
-- ------------------------------
-- The database configuration properties
-- ------------------------------
type Configuration is new ADO.Configs.Configuration with null record;
-- Get the driver index that corresponds to the driver for this database connection string.
function Get_Driver (Config : in Configuration) return Driver_Index;
-- Create a new connection using the configuration parameters.
procedure Create_Connection (Config : in Configuration'Class;
Result : in out Ref.Ref'Class)
with Post => not Result.Is_Null;
-- ------------------------------
-- Database Driver
-- ------------------------------
-- Create a new connection using the configuration parameters.
procedure Create_Connection (D : in out Driver;
Config : in Configuration'Class;
Result : in out Ref.Ref'Class) is abstract
with Post'Class => not Result.Is_Null;
-- Create the database and initialize it with the schema SQL file.
-- The `Admin` parameter describes the database connection with administrator access.
-- The `Config` parameter describes the target database connection.
procedure Create_Database (D : in out Driver;
Admin : in Configs.Configuration'Class;
Config : in Configs.Configuration'Class;
Schema_Path : in String;
Messages : out Util.Strings.Vectors.Vector) is abstract;
-- Get the driver unique index.
function Get_Driver_Index (D : in Driver) return Driver_Index;
-- Get the driver name.
function Get_Driver_Name (D : in Driver) return String;
-- Register a database driver.
procedure Register (Driver : in Driver_Access);
-- Get a database driver given its name.
function Get_Driver (Name : in String) return Driver_Access;
private
type Driver is abstract new Ada.Finalization.Limited_Controlled with record
Name : Util.Strings.Name_Access;
Index : Driver_Index;
end record;
end ADO.Connections;
|
--
-- Copyright (c) 2007, 2008 Tero Koskinen <tero.koskinen@iki.fi>
--
-- Permission to use, copy, modify, and distribute this software for any
-- purpose with or without fee is hereby granted, provided that the above
-- copyright notice and this permission notice appear in all copies.
--
-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--
with Ahven.SList;
with Ahven.AStrings;
with Ahven.Long_AStrings;
pragma Elaborate_All (Ahven.SList);
-- Like the name implies, the Results package is used for
-- storing the test results.
--
-- Result_Info holds one invidual result and
-- Result_Collection holds multiple Result_Infos.
--
package Ahven.Results is
use Ahven.AStrings;
type Result_Info is private;
Empty_Result_Info : constant Result_Info;
-- Result_Info object which holds no result. It can be used
-- to initialize a new Result_Info object.
procedure Set_Test_Name (Info : in out Result_Info;
Name : Bounded_String);
-- Set a test name for the result.
procedure Set_Routine_Name (Info : in out Result_Info;
Name : Bounded_String);
-- Set a routine name for the result.
procedure Set_Message (Info : in out Result_Info;
Message : Bounded_String);
-- Set a message for the result.
procedure Set_Test_Name (Info : in out Result_Info; Name : String);
-- A helper function, which calls Set_Test_Name (.. ; Bounded_String)
procedure Set_Routine_Name (Info : in out Result_Info; Name : String);
-- A helper function, which calls Set_Routine_Name (.. ; Bounded_String)
procedure Set_Message (Info : in out Result_Info; Message : String);
-- A helper function, which calls Set_Message (.. ; Bounded_String)
procedure Set_Long_Message (Info : in out Result_Info;
Message : Bounded_String);
-- Set a long message for the result
procedure Set_Long_Message
(Info : in out Result_Info;
Message : Long_AStrings.Bounded_String);
-- Set a long message for the result
procedure Set_Long_Message (Info : in out Result_Info; Message : String);
-- A helper function, which calls Set_Long_Message (.. ; Bounded_String)
procedure Set_Execution_Time (Info : in out Result_Info;
Elapsed_Time : Duration);
-- Set the execution time of the result info (test).
procedure Set_Output_File (Info : in out Result_Info;
Filename : Bounded_String);
-- Set the name of the test output file.
procedure Set_Output_File (Info : in out Result_Info;
Filename : String);
-- Set the name of the test output file.
function Get_Test_Name (Info : Result_Info) return String;
-- Return the test name of the result info.
function Get_Routine_Name (Info : Result_Info) return String;
-- Return the routine name of the result info.
function Get_Message (Info : Result_Info) return String;
-- Return the message of the result info.
function Get_Long_Message (Info : Result_Info) return String;
-- Return the long message of the result info.
function Get_Execution_Time (Info : Result_Info) return Duration;
-- Return the execution time of the result info.
function Get_Output_File (Info : Result_Info) return Bounded_String;
-- Return the name of the output file.
-- Empty string is returned in case there is no output file.
type Result_Collection is limited private;
-- A collection of Result_Info objects.
-- Contains also child collections.
type Result_Collection_Access is access Result_Collection;
procedure Add_Child (Collection : in out Result_Collection;
Child : Result_Collection_Access);
-- Add a child collection to the collection.
procedure Add_Error (Collection : in out Result_Collection;
Info : Result_Info);
-- Add a test error to the collection.
procedure Add_Skipped (Collection : in out Result_Collection;
Info : Result_Info);
-- Add a skipped test to the collection.
procedure Add_Failure (Collection : in out Result_Collection;
Info : Result_Info);
-- Add a test failure to the collection.
procedure Add_Pass (Collection : in out Result_Collection;
Info : Result_Info);
-- Add a passed test to the collection
procedure Release (Collection : in out Result_Collection);
-- Release resourced held by the collection.
-- Frees also all children added via Add_Child.
procedure Set_Name (Collection : in out Result_Collection;
Name : Bounded_String);
-- Set a test name for the collection.
procedure Set_Parent (Collection : in out Result_Collection;
Parent : Result_Collection_Access);
-- Set a parent collection to the collection.
function Test_Count (Collection : Result_Collection) return Natural;
-- Return the amount of tests in the collection.
-- Tests in child collections are included.
function Direct_Test_Count (Collection : Result_Collection) return Natural;
-- Return the amount of tests in the collection.
-- The tests in the child collections are NOT included.
function Pass_Count (Collection : Result_Collection) return Natural;
-- Return the amount of passed tests in the collection.
-- Tests in child collections are included.
function Error_Count (Collection : Result_Collection) return Natural;
-- Return the amount of test errors in the collection.
-- Tests in child collections are included.
function Failure_Count (Collection : Result_Collection) return Natural;
-- Return the amount of test errors in the collection.
-- Tests in child collections are included.
function Skipped_Count (Collection : Result_Collection) return Natural;
-- Return the amount of skipped tests in the colleciton.
-- Tests in child collections are included.
function Get_Test_Name (Collection : Result_Collection)
return Bounded_String;
-- Return the name of the collection's test.
function Get_Parent (Collection : Result_Collection)
return Result_Collection_Access;
-- Return the parent of the collection.
function Get_Execution_Time (Collection : Result_Collection)
return Duration;
-- Return the execution time of the whole collection.
type Result_Info_Cursor is private;
-- A cursor type for Pass, Failure and Error results.
function First_Pass (Collection : Result_Collection)
return Result_Info_Cursor;
-- Get the first pass from the collection.
function First_Failure (Collection : Result_Collection)
return Result_Info_Cursor;
-- Get the first failure from the collection.
function First_Skipped (Collection : Result_Collection)
return Result_Info_Cursor;
-- Get the first skipped test from the collection.
function First_Error (Collection : Result_Collection)
return Result_Info_Cursor;
-- Get the first error from the collection.
function Next (Position : Result_Info_Cursor) return Result_Info_Cursor;
-- Get the next pass/failure/error.
function Data (Position : Result_Info_Cursor) return Result_Info;
-- Get the data behind the cursor.
function Is_Valid (Position : Result_Info_Cursor) return Boolean;
-- Is the cursor still valid?
type Result_Collection_Cursor is private;
-- Cursor for iterating over a set of Result_Collection access objects.
function First_Child (Collection : in Result_Collection)
return Result_Collection_Cursor;
-- Get the first child of the collection.
function Next (Position : Result_Collection_Cursor)
return Result_Collection_Cursor;
-- Get the next child.
function Is_Valid (Position : Result_Collection_Cursor) return Boolean;
-- Is the cursor still valid?
function Data (Position : Result_Collection_Cursor)
return Result_Collection_Access;
-- Get the data (Result_Collection_Access) behind the cursor.
function Child_Depth (Collection : Result_Collection) return Natural;
-- Return the maximum depth of children. (a child of a child, etc.)
--
-- Examples: Child_Depth is 0 for a collection without children.
-- Collection with a child containing another child has a depth of 2.
private
type Result_Info is record
Test_Name : Bounded_String := Null_Bounded_String;
Output_File : Bounded_String := Null_Bounded_String;
Routine_Name : Bounded_String := Null_Bounded_String;
Execution_Time : Duration := 0.0;
Message : Bounded_String := Null_Bounded_String;
Long_Message : Long_AStrings.Bounded_String
:= Long_AStrings.Null_Bounded_String;
end record;
Empty_Result_Info : constant Result_Info :=
(Test_Name => Null_Bounded_String,
Routine_Name => Null_Bounded_String,
Message => Null_Bounded_String,
Long_Message => Long_AStrings.Null_Bounded_String,
Execution_Time => 0.0,
Output_File => Null_Bounded_String);
package Result_Info_List is
new Ahven.SList (Element_Type => Result_Info);
type Result_Collection_Wrapper is record
Ptr : Result_Collection_Access;
end record;
-- Work around for Janus/Ada 3.1.1d/3.1.2beta generic bug.
package Result_List is
new Ahven.SList (Element_Type => Result_Collection_Wrapper);
type Result_Info_Cursor is new Result_Info_List.Cursor;
type Result_Collection_Cursor is new Result_List.Cursor;
type Result_Collection is limited record
Test_Name : Bounded_String := Null_Bounded_String;
Passes : Result_Info_List.List;
Failures : Result_Info_List.List;
Errors : Result_Info_List.List;
Skips : Result_Info_List.List;
Children : Result_List.List;
Parent : Result_Collection_Access := null;
end record;
end Ahven.Results;
|
-----------------------------------------------------------------------
-- wiki-plugins-variables -- Variables plugin
-- Copyright (C) 2020, 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 Wiki.Filters.Variables;
package body Wiki.Plugins.Variables is
-- ------------------------------
-- Set or update a variable in the `Wiki.Filters.Variable` filter.
-- ------------------------------
overriding
procedure Expand (Plugin : in out Variable_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in out Plugin_Context) is
pragma Unreferenced (Plugin, Document);
begin
if Wiki.Attributes.Length (Params) >= 3 then
declare
First : Wiki.Attributes.Cursor := Wiki.Attributes.First (Params);
Second : Wiki.Attributes.Cursor;
begin
Wiki.Attributes.Next (First);
Second := First;
Wiki.Attributes.Next (Second);
Wiki.Filters.Variables.Add_Variable (Context.Filters,
Wiki.Attributes.Get_Wide_Value (First),
Wiki.Attributes.Get_Wide_Value (Second));
end;
end if;
end Expand;
-- ------------------------------
-- List the variables from the `Wiki.Filters.Variable` filter.
-- ------------------------------
overriding
procedure Expand (Plugin : in out List_Variable_Plugin;
Document : in out Wiki.Documents.Document;
Params : in out Wiki.Attributes.Attribute_List;
Context : in out Plugin_Context) is
pragma Unreferenced (Plugin, Params);
procedure Print_Variable (Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString);
Has_Table : Boolean := False;
Format : constant Format_Map := (others => False);
Attributes : Wiki.Attributes.Attribute_List;
procedure Print_Variable (Name : in Wiki.Strings.WString;
Value : in Wiki.Strings.WString) is
begin
Has_Table := True;
Context.Filters.Add_Row (Document);
Context.Filters.Add_Column (Document, Attributes);
Context.Filters.Add_Text (Document, Name, Format);
Context.Filters.Add_Column (Document, Attributes);
Context.Filters.Add_Text (Document, Value, Format);
end Print_Variable;
begin
Wiki.Filters.Variables.Iterate (Context.Filters, Print_Variable'Access);
if Has_Table then
Context.Filters.Finish_Table (Document);
end if;
end Expand;
end Wiki.Plugins.Variables;
|
with Ada.Unchecked_Deallocation;
package body Network.Generic_Promises is
procedure Free is new Ada.Unchecked_Deallocation
(List_Node, List_Node_Access);
function Has_Listener
(Self : Promise'Class;
Value : not null Listener_Access) return Boolean;
------------------
-- Add_Listener --
------------------
not overriding procedure Add_Listener
(Self : in out Promise'Class;
Value : not null Listener_Access)
is
Parent : constant Controller_Access := Self.Parent;
begin
case Parent.Data.State is
when Pending =>
if not Self.Has_Listener (Value) then
Parent.Data.Listeners := new List_Node'
(Item => Value,
Next => Parent.Data.Listeners);
end if;
when Resolved =>
Value.On_Resolve (Parent.Data.Resolve_Value);
when Rejected =>
Value.On_Reject (Parent.Data.Reject_Value);
end case;
end Add_Listener;
--------------
-- Finalize --
--------------
overriding procedure Finalize (Self : in out Controller) is
begin
if Self.Data.State = Pending then
declare
Next : List_Node_Access := Self.Data.Listeners;
begin
while Next /= null loop
declare
Item : List_Node_Access := Next;
begin
Next := Item.Next;
Free (Item);
end;
end loop;
end;
end if;
end Finalize;
------------------
-- Has_Listener --
------------------
function Has_Listener
(Self : Promise'Class;
Value : not null Listener_Access) return Boolean
is
Next : List_Node_Access := Self.Parent.Data.Listeners;
begin
while Next /= null loop
if Next.Item = Value then
return True;
end if;
Next := Next.Next;
end loop;
return False;
end Has_Listener;
-----------------
-- Is_Attached --
-----------------
function Is_Attached (Self : Promise'Class) return Boolean is
begin
return Self.Parent /= null;
end Is_Attached;
----------------
-- Is_Pending --
----------------
function Is_Pending (Self : Promise'Class) return Boolean is
begin
return Self.Parent.Is_Pending;
end Is_Pending;
function Is_Pending (Self : Controller'Class) return Boolean is
begin
return Self.Data.State = Pending;
end Is_Pending;
-----------------
-- Is_Rejected --
-----------------
function Is_Rejected (Self : Promise'Class) return Boolean is
begin
return Self.Parent.Is_Rejected;
end Is_Rejected;
function Is_Rejected (Self : Controller'Class) return Boolean is
begin
return Self.Data.State = Rejected;
end Is_Rejected;
-----------------
-- Is_Resolved --
-----------------
function Is_Resolved (Self : Promise'Class) return Boolean is
begin
return Self.Parent.Is_Resolved;
end Is_Resolved;
function Is_Resolved (Self : Controller'Class) return Boolean is
begin
return Self.Data.State = Resolved;
end Is_Resolved;
------------
-- Reject --
------------
procedure Reject (Self : in out Controller'Class;
Value : Reject_Element) is
Next : List_Node_Access := Self.Data.Listeners;
begin
Self.Data := (Rejected, Value);
while Next /= null loop
declare
Item : List_Node_Access := Next;
begin
Item.Item.On_Reject (Self.Data.Reject_Value);
Next := Item.Next;
Free (Item);
end;
end loop;
end Reject;
---------------------
-- Remove_Listener --
---------------------
procedure Remove_Listener
(Self : in out Promise'Class;
Value : not null Listener_Access)
is
Next : List_Node_Access := Self.Parent.Data.Listeners;
begin
if Next.Item = Value then
Self.Parent.Data.Listeners := Next.Next;
Free (Next);
end if;
while Next /= null loop
if Next.Next /= null
and then Next.Next.Item = Value
then
Next.Next := Next.Next.Next;
Free (Next);
exit;
end if;
end loop;
end Remove_Listener;
-------------
-- Resolve --
-------------
procedure Resolve (Self : in out Controller'Class;
Value : Resolve_Element) is
Next : List_Node_Access := Self.Data.Listeners;
begin
Self.Data := (Resolved, Value);
while Next /= null loop
declare
Item : List_Node_Access := Next;
begin
Item.Item.On_Resolve (Self.Data.Resolve_Value);
Next := Item.Next;
Free (Item);
end;
end loop;
end Resolve;
----------------
-- To_Promise --
----------------
function To_Promise (Self : access Controller'Class) return Promise is
begin
return (Parent => Self.all'Unchecked_Access);
end To_Promise;
end Network.Generic_Promises;
|
------------------------------------------------------------------------------
-- --
-- GNAT COMPILER COMPONENTS --
-- --
-- X R E F _ L I B --
-- --
-- S p e c --
-- --
-- $Revision$
-- --
-- Copyright (C) 1998-1999 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. --
-- --
-- Extensive contributions were provided by Ada Core Technologies Inc. --
-- --
------------------------------------------------------------------------------
with Hostparm;
with GNAT.Directory_Operations; use GNAT.Directory_Operations;
with GNAT.OS_Lib; use GNAT.OS_Lib;
with GNAT.Dynamic_Tables;
with Xr_Tabls; use Xr_Tabls;
with GNAT.Regexp; use GNAT.Regexp;
-- Misc. utilities for the cross-referencing tool
package Xref_Lib is
subtype File_Name_String is String (1 .. Hostparm.Max_Name_Length);
subtype Line_String is String (1 .. Hostparm.Max_Line_Length);
type ALI_File is limited private;
---------------------
-- Directory Input --
---------------------
type Rec_DIR is limited private;
-- This one is used for recursive search of .ali files
procedure Find_ALI_Files;
-- Find all the ali files that we will have to parse, and have them to
-- the file list
---------------------
-- Search patterns --
---------------------
type Search_Pattern is private;
type Search_Pattern_Ptr is access all Search_Pattern;
procedure Add_Entity
(Pattern : in out Search_Pattern;
Entity : String;
Glob : Boolean := False);
-- Add a new entity to the search pattern (the entity should have the
-- form pattern[:file[:line[:column]]], and it is parsed entirely in
-- this procedure. Glob indicates if we should use the 'globbing
-- patterns' (True) or the full regular expressions (False)
procedure Add_File (File : String);
-- Add a new file in the list of files to search for references.
-- File is considered to be a globbing regular expression, which is thus
-- expanded
Invalid_Argument : exception;
-- Exception raised when there is a syntax error in the command line
function Match
(Pattern : Search_Pattern;
Symbol : String)
return Boolean;
-- Returns true if Symbol matches one of the entities in the command line
-----------------------
-- Output Algorithms --
-----------------------
procedure Print_Gnatfind
(References : in Boolean;
Full_Path_Name : in Boolean);
procedure Print_Unused (Full_Path_Name : in Boolean);
procedure Print_Vi (Full_Path_Name : in Boolean);
procedure Print_Xref (Full_Path_Name : in Boolean);
-- The actual print procedures. These functions step through the symbol
-- table and print all the symbols if they match the files given on the
-- command line (they already match the entities if they are in the
-- symbol table)
------------------------
-- General Algorithms --
------------------------
function Default_Project_File (Dir_Name : in String) return String;
-- Returns the default Project file name
procedure Search
(Pattern : Search_Pattern;
Local_Symbols : Boolean;
Wide_Search : Boolean;
Read_Only : Boolean;
Der_Info : Boolean;
Type_Tree : Boolean);
-- Search every ali file (following the Readdir rule above), for
-- each line matching Pattern, and executes Process on these
-- lines. If World is True, Search will look into every .ali file
-- in the object search path. If Read_Only is True, we parse the
-- read-only ali files too. If Der_Mode is true then the derived type
-- information will be processed. If Type_Tree is true then the type
-- hierarchy will be search going from pattern to the parent type
procedure Search_Xref
(Local_Symbols : Boolean;
Read_Only : Boolean;
Der_Info : Boolean);
-- Search every ali file given in the command line and all their
-- dependencies. If Read_Only is True, we parse the read-only ali
-- files too. If Der_Mode is true then the derived type information will
-- be processed
---------------
-- ALI files --
---------------
function Current_Xref_File
(File : ALI_File)
return Xr_Tabls.File_Reference;
-- Returns the name of the file in which the last identifier
-- is declared
function File_Name
(File : ALI_File;
Num : Positive)
return Xr_Tabls.File_Reference;
-- Returns the dependency file name number Num
function Get_Full_Type (Abbrev : Character) return String;
-- Returns the full type corresponding to a type letter as found in
-- the .ali files.
procedure Open
(Name : in String;
File : out ALI_File;
Dependencies : in Boolean := False);
-- Open a new ALI file
-- if Dependencies is True, the insert every library file 'with'ed in
-- the files database (used for gnatxref)
private
type Rec_DIR is limited record
Dir : GNAT.Directory_Operations.Dir_Type;
end record;
package Dependencies_Tables is new GNAT.Dynamic_Tables
(Table_Component_Type => Xr_Tabls.File_Reference,
Table_Index_Type => Positive,
Table_Low_Bound => 1,
Table_Initial => 400,
Table_Increment => 100);
use Dependencies_Tables;
type Dependencies is new Dependencies_Tables.Instance;
type ALI_File is limited record
Buffer : String_Access := null;
-- Buffer used to read the whole file at once
Current_Line : Positive;
-- Start of the current line in Buffer
Xref_Line : Positive;
-- Start of the xref lines in Buffer
X_File : Xr_Tabls.File_Reference;
-- Stores the cross-referencing file-name ("X..." lines), as an
-- index into the dependencies table
Dep : Dependencies;
-- Store file name associated with each number ("D..." lines)
end record;
-- The following record type stores all the patterns that are searched for
type Search_Pattern is record
Entity : GNAT.Regexp.Regexp;
-- A regular expression matching the entities we are looking for.
-- File is a list of the places where the declaration of the entities
-- has to be. When the user enters a file:line:column on the command
-- line, it is stored as "Entity_Name Declaration_File:line:column"
Initialized : Boolean := False;
-- Set to True when Entity has been initialized.
end record;
-- Stores all the pattern that are search for.
end Xref_Lib;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.