repo_name
stringlengths
9
74
language
stringclasses
1 value
length_bytes
int64
11
9.34M
extension
stringclasses
2 values
content
stringlengths
11
9.34M
stcarrez/babel
Ada
2,172
ads
----------------------------------------------------------------------- -- babel-filters -- File filters -- Copyright (C) 2014 Stephane.Carrez -- Written by Stephane.Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Ada.Strings.Unbounded; with Ada.Directories; with Util.Strings.Sets; package Babel.Filters is type Filter_Type is limited interface; type Filter_Type_Access is access all Filter_Type'Class; -- Return True if the file or directory is accepted by the filter. function Is_Accepted (Filter : in Filter_Type; Kind : in Ada.Directories.File_Kind; Path : in String; Name : in String) return Boolean is abstract; -- Filter to exclude directories type Exclude_Directory_Filter_Type is new Filter_Type with private; -- Return True if the file or directory is accepted by the filter. overriding function Is_Accepted (Filter : in Exclude_Directory_Filter_Type; Kind : in Ada.Directories.File_Kind; Path : in String; Name : in String) return Boolean; -- Add the given path to the list of excluded directories. procedure Add_Exclude (Filter : in out Exclude_Directory_Filter_Type; Path : in String); private type Exclude_Directory_Filter_Type is new Filter_Type with record Excluded : Util.Strings.Sets.Set; end record; end Babel.Filters;
egustafson/sandbox
Ada
333
adb
with Ada.Command_Line, Ada.Text_IO; use Ada.Command_Line, Ada.Text_IO; procedure Argv is begin Put_Line( "Command : " & Command_Name ); Put( "Args(" & Integer'Image(Argument_Count) & " ) : " ); Put( "[ " ); for I in 1 .. Argument_Count loop Put( Argument(I) & " "); end loop; Put_Line( "]" ); end Argv;
reznikmm/matreshka
Ada
4,755
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ -- A literal real is a specification of a real value. ------------------------------------------------------------------------------ with AMF.UML.Literal_Specifications; package AMF.UML.Literal_Reals is pragma Preelaborate; type UML_Literal_Real is limited interface and AMF.UML.Literal_Specifications.UML_Literal_Specification; type UML_Literal_Real_Access is access all UML_Literal_Real'Class; for UML_Literal_Real_Access'Storage_Size use 0; not overriding function Get_Value (Self : not null access constant UML_Literal_Real) return AMF.Real is abstract; -- Getter of LiteralReal::value. -- not overriding procedure Set_Value (Self : not null access UML_Literal_Real; To : AMF.Real) is abstract; -- Setter of LiteralReal::value. -- overriding function Is_Computable (Self : not null access constant UML_Literal_Real) return Boolean is abstract; -- Operation LiteralReal::isComputable. -- -- The query isComputable() is redefined to be true. not overriding function Real_Value (Self : not null access constant UML_Literal_Real) return AMF.Real is abstract; -- Operation LiteralReal::realValue. -- -- The query realValue() gives the value. end AMF.UML.Literal_Reals;
ecalderini/bingada
Ada
3,266
adb
--***************************************************************************** --* --* PROJECT: BINGADA --* --* FILE: q_bingo.adb --* --* AUTHOR: Javier Fuica Fernandez --* --***************************************************************************** with Q_GEN_SHUFFLE; -- Sound library -- with CANBERRA; with Ada.Directories; with Ada.Strings.Fixed; with GTKADA.Intl; package body Q_BINGO.Q_BOMBO is --================================================================== V_INDEX : T_NUMBER; --================================================================== package Q_SHUFFLE is new Q_GEN_SHUFFLE (ELEMENT_TYPE => T_NUMBER, C_MAX_NUMBER => T_NUMBER'LAST); V_BINGO_ARRAY : Q_SHUFFLE.ARRAY_TYPE; V_CONTEXT : CANBERRA.CONTEXT := CANBERRA.CREATE (NAME => "BingAda", ID => "bingada.lovelace", ICON => "applications-games"); --================================================================== procedure P_INIT is begin for I in 1 .. T_NUMBER'LAST loop V_BINGO_ARRAY (I) := I; end loop; Q_SHUFFLE.P_SHUFFLE (LIST => V_BINGO_ARRAY); V_INDEX := 1; end P_INIT; --================================================================== procedure P_Play_Number (V_NUMBER : Positive) is C_Number_Image : constant String := Ada.Strings.Fixed.Trim (V_Number'Image, Ada.Strings.Left); C_Path : constant String := "media/"; C_Extension : constant String := ".ogg"; C_Lang_Code_Last : constant := 2; C_locale : constant String := GTKADA.INTL.Getlocale; C_Default_Lang : constant String := "en"; V_Lang : String (1 .. C_Lang_Code_Last) := C_Default_Lang; V_Sound : Canberra.Sound; begin if C_locale'Length >= C_Lang_Code_Last then V_Lang := C_Locale (C_Locale'First .. C_Locale'First + C_Lang_Code_Last - 1); end if; if not Ada.Directories.Exists (C_Path & V_Lang & '/' & C_Number_Image & C_Extension) then V_Lang := C_Default_Lang; end if; V_Context.Play_FILE (C_Path & V_Lang & '/' & C_Number_Image & C_Extension, V_SOUND, CANBERRA.Music, "Number"); end P_Play_Number; --================================================================== procedure P_SPIN (V_NUMBER : out POSITIVE; V_CURRENT_INDEX : out T_NUMBER; V_LAST_NUMBER : out BOOLEAN) is begin if V_INDEX = T_NUMBER'LAST then V_NUMBER := V_BINGO_ARRAY (T_NUMBER'LAST); V_LAST_NUMBER := TRUE; V_CURRENT_INDEX := V_INDEX; else V_NUMBER := V_BINGO_ARRAY (V_INDEX); V_CURRENT_INDEX := V_INDEX; V_INDEX := V_INDEX + 1; V_LAST_NUMBER := FALSE; end if; P_PLAY_NUMBER (V_Bingo_Array(V_Current_Index)); end P_SPIN; --================================================================== function F_GET_NUMBER (V_INDEX : T_NUMBER) return T_NUMBER is begin return V_BINGO_ARRAY (V_INDEX); end F_GET_NUMBER; --================================================================== function F_GET_CURRENT_INDEX return T_NUMBER is begin return V_INDEX; end F_GET_CURRENT_INDEX; --================================================================== end Q_BINGO.Q_BOMBO;
reznikmm/matreshka
Ada
11,440
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with AMF.Internals.UML_Named_Elements; with AMF.UML.Dependencies.Collections; with AMF.UML.Named_Elements; with AMF.UML.Namespaces; with AMF.UML.Packages.Collections; with AMF.UML.Pseudostates; with AMF.UML.Regions; with AMF.UML.State_Machines; with AMF.UML.States; with AMF.UML.String_Expressions; with AMF.UML.Transitions.Collections; with AMF.Visitors; package AMF.Internals.UML_Pseudostates is type UML_Pseudostate_Proxy is limited new AMF.Internals.UML_Named_Elements.UML_Named_Element_Proxy and AMF.UML.Pseudostates.UML_Pseudostate with null record; overriding function Get_Kind (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.UML_Pseudostate_Kind; -- Getter of Pseudostate::kind. -- -- Determines the precise type of the Pseudostate and can be one of: -- entryPoint, exitPoint, initial, deepHistory, shallowHistory, join, -- fork, junction, terminate or choice. overriding procedure Set_Kind (Self : not null access UML_Pseudostate_Proxy; To : AMF.UML.UML_Pseudostate_Kind); -- Setter of Pseudostate::kind. -- -- Determines the precise type of the Pseudostate and can be one of: -- entryPoint, exitPoint, initial, deepHistory, shallowHistory, join, -- fork, junction, terminate or choice. overriding function Get_State (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.States.UML_State_Access; -- Getter of Pseudostate::state. -- -- The State that owns this pseudostate and in which it appears. overriding procedure Set_State (Self : not null access UML_Pseudostate_Proxy; To : AMF.UML.States.UML_State_Access); -- Setter of Pseudostate::state. -- -- The State that owns this pseudostate and in which it appears. overriding function Get_State_Machine (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.State_Machines.UML_State_Machine_Access; -- Getter of Pseudostate::stateMachine. -- -- The StateMachine in which this Pseudostate is defined. This only -- applies to Pseudostates of the kind entryPoint or exitPoint. overriding procedure Set_State_Machine (Self : not null access UML_Pseudostate_Proxy; To : AMF.UML.State_Machines.UML_State_Machine_Access); -- Setter of Pseudostate::stateMachine. -- -- The StateMachine in which this Pseudostate is defined. This only -- applies to Pseudostates of the kind entryPoint or exitPoint. overriding function Get_Container (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Regions.UML_Region_Access; -- Getter of Vertex::container. -- -- The region that contains this vertex. overriding procedure Set_Container (Self : not null access UML_Pseudostate_Proxy; To : AMF.UML.Regions.UML_Region_Access); -- Setter of Vertex::container. -- -- The region that contains this vertex. overriding function Get_Incoming (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Transitions.Collections.Set_Of_UML_Transition; -- Getter of Vertex::incoming. -- -- Specifies the transitions entering this vertex. overriding function Get_Outgoing (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Transitions.Collections.Set_Of_UML_Transition; -- Getter of Vertex::outgoing. -- -- Specifies the transitions departing from this vertex. overriding function Get_Client_Dependency (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency; -- Getter of NamedElement::clientDependency. -- -- Indicates the dependencies that reference the client. overriding function Get_Name_Expression (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.String_Expressions.UML_String_Expression_Access; -- Getter of NamedElement::nameExpression. -- -- The string expression used to define the name of this named element. overriding procedure Set_Name_Expression (Self : not null access UML_Pseudostate_Proxy; To : AMF.UML.String_Expressions.UML_String_Expression_Access); -- Setter of NamedElement::nameExpression. -- -- The string expression used to define the name of this named element. overriding function Get_Namespace (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access; -- Getter of NamedElement::namespace. -- -- Specifies the namespace that owns the NamedElement. overriding function Get_Qualified_Name (Self : not null access constant UML_Pseudostate_Proxy) return AMF.Optional_String; -- Getter of NamedElement::qualifiedName. -- -- A name which allows the NamedElement to be identified within a -- hierarchy of nested Namespaces. It is constructed from the names of the -- containing namespaces starting at the root of the hierarchy and ending -- with the name of the NamedElement itself. overriding function Containing_State_Machine (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.State_Machines.UML_State_Machine_Access; -- Operation Vertex::containingStateMachine. -- -- The operation containingStateMachine() returns the state machine in -- which this Vertex is defined overriding function Incoming (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Transitions.Collections.Set_Of_UML_Transition; -- Operation Vertex::incoming. -- -- Missing derivation for Vertex::/incoming : Transition overriding function Outgoing (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Transitions.Collections.Set_Of_UML_Transition; -- Operation Vertex::outgoing. -- -- Missing derivation for Vertex::/outgoing : Transition overriding function All_Owning_Packages (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Packages.Collections.Set_Of_UML_Package; -- Operation NamedElement::allOwningPackages. -- -- The query allOwningPackages() returns all the directly or indirectly -- owning packages. overriding function Is_Distinguishable_From (Self : not null access constant UML_Pseudostate_Proxy; N : AMF.UML.Named_Elements.UML_Named_Element_Access; Ns : AMF.UML.Namespaces.UML_Namespace_Access) return Boolean; -- Operation NamedElement::isDistinguishableFrom. -- -- The query isDistinguishableFrom() determines whether two NamedElements -- may logically co-exist within a Namespace. By default, two named -- elements are distinguishable if (a) they have unrelated types or (b) -- they have related types but different names. overriding function Namespace (Self : not null access constant UML_Pseudostate_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access; -- Operation NamedElement::namespace. -- -- Missing derivation for NamedElement::/namespace : Namespace overriding procedure Enter_Element (Self : not null access constant UML_Pseudostate_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control); -- Dispatch call to corresponding subprogram of visitor interface. overriding procedure Leave_Element (Self : not null access constant UML_Pseudostate_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control); -- Dispatch call to corresponding subprogram of visitor interface. overriding procedure Visit_Element (Self : not null access constant UML_Pseudostate_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control); -- Dispatch call to corresponding subprogram of iterator interface. end AMF.Internals.UML_Pseudostates;
AdaCore/gpr
Ada
9,404
adb
-- -- Copyright (C) 2019-2023, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-Exception -- with Ada.Directories; with Ada.Strings.Less_Case_Insensitive; pragma Warnings (Off, "* is an internal GNAT unit"); with System.Soft_Links; use System.Soft_Links; pragma Warnings (On, "* is an internal GNAT unit"); with GNAT.OS_Lib; package body GPR2 is Is_Multitasking : constant Boolean := System.Soft_Links.Lock_Task /= System.Soft_Links.Task_Lock_NT'Access; --------- -- "<" -- --------- overriding function "<" (Left, Right : Optional_Name_Type) return Boolean is use Ada.Strings; begin return Less_Case_Insensitive (String (Left), String (Right)); end "<"; overriding function "<" (Left, Right : Filename_Optional) return Boolean is begin return (if File_Names_Case_Sensitive then String (Left) < String (Right) else Ada.Strings.Less_Case_Insensitive (String (Left), String (Right))); end "<"; --------- -- "=" -- --------- overriding function "=" (Left, Right : Optional_Name_Type) return Boolean is use Ada.Strings; begin return Equal_Case_Insensitive (String (Left), String (Right)); end "="; overriding function "=" (Left, Right : Filename_Optional) return Boolean is begin return (if File_Names_Case_Sensitive then String (Left) = String (Right) else Ada.Strings.Equal_Case_Insensitive (String (Left), String (Right))); end "="; --------------------------- -- Get_Executable_Suffix -- --------------------------- function Get_Executable_Suffix return String is Exec_Suffix : GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Get_Executable_Suffix; begin return Result : constant String := Exec_Suffix.all do GNAT.OS_Lib.Free (Exec_Suffix); end return; end Get_Executable_Suffix; ------------------------- -- Get_Tools_Directory -- ------------------------- function Get_Tools_Directory return String is GPRls : constant String := Locate_Exec_On_Path ("gprls"); -- Check for GPRls executable begin return (if GPRls = "" then "" else Directories.Containing_Directory (Directories.Containing_Directory (GNAT.OS_Lib.Normalize_Pathname (GPRls, Resolve_Links => True)))); end Get_Tools_Directory; -------- -- Id -- -------- function Id (List : in out Name_List; Name : Optional_Name_Type) return Natural is C : Name_Maps.Cursor; Result : Natural; Value : constant String := Ada.Characters.Handling.To_Lower (String (Name)); begin if Name'Length = 0 then return 0; end if; -- Note: if we just read the value, the operation is thread-safe. -- So let's not add a penalty for the read operation, that should be -- the most common operation. C := List.Name_To_Id.Find (Value); if Name_Maps.Has_Element (C) then return Name_Maps.Element (C); end if; -- We need to add the value: as this operation is not atomic -- and the tables are global, we need to ensure the operation -- cannot be interrupted. begin System.Soft_Links.Lock_Task.all; if Is_Multitasking then -- In a multitasking environment, the value could have been -- inserted by someone else since we've checked it above. -- So let's retry: C := List.Name_To_Id.Find (Value); if Name_Maps.Has_Element (C) then -- return with the value System.Soft_Links.Unlock_Task.all; return Name_Maps.Element (C); end if; end if; -- Still not in there, so let's add the value to the list List.Id_To_Name.Append (Value); Result := Natural (List.Id_To_Name.Last_Index); List.Name_To_Id.Insert (Value, Result); exception when others => System.Soft_Links.Unlock_Task.all; raise; end; -- Don't need the lock anymore System.Soft_Links.Unlock_Task.all; return Result; end Id; ----------- -- Image -- ----------- function Image (List : Name_List; Id : Natural) return String is begin return To_Mixed (String (Name (List, Id))); end Image; -------------------------- -- Is_Runtime_Unit_Name -- -------------------------- function Is_Runtime_Unit_Name (Name : Name_Type) return Boolean is LN : constant String := To_Lower (Name); function Is_It (Root : String) return Boolean is (GNATCOLL.Utils.Starts_With (LN, Root) and then (LN'Length = Root'Length or else (LN'Length > Root'Length + 1 and then LN (LN'First + Root'Length) = '.'))); -- Returns True if LN equal to Root or starts with Root & '.' and has -- length more than Root'Length + 2. begin return Is_It ("ada") or else Is_It ("system") or else Is_It ("interfaces") or else Is_It ("gnat") or else LN in "direct_io" | "calendar" | "io_exceptions" | "machine_code" | "unchecked_conversion" | "unchecked_deallocation"; end Is_Runtime_Unit_Name; ------------------------- -- Locate_Exec_On_Path -- ------------------------- function Locate_Exec_On_Path (Exec_Name : String) return String is use type GNAT.OS_Lib.String_Access; Path : GNAT.OS_Lib.String_Access := GNAT.OS_Lib.Locate_Exec_On_Path (Exec_Name); Path_Str : constant String := (if Path = null then "" else Path.all); begin GNAT.OS_Lib.Free (Path); return Path_Str; end Locate_Exec_On_Path; ---------- -- Name -- ---------- function Name (List : Name_List; Id : Natural) return Optional_Name_Type is begin if Id = 0 then return ""; end if; return Optional_Name_Type (List.Id_To_Name.Element (Id)); end Name; ----------------- -- Parent_Name -- ----------------- function Parent_Name (Name : Name_Type) return Optional_Name_Type is begin for J in reverse Name'Range loop if Name (J) = '.' then return Name (Name'First .. J - 1); end if; end loop; return No_Name; end Parent_Name; ----------- -- Quote -- ----------- function Quote (Str : Value_Type; Quote_With : Character := '"') return Value_Type is begin return Quote_With & GNATCOLL.Utils.Replace (Str, "" & Quote_With, Quote_With & Quote_With) & Quote_With; end Quote; --------------- -- Set_Debug -- --------------- procedure Set_Debug (Mode : Character; Enable : Boolean := True) is begin if Mode = '*' then Debug := (others => Enable); else Debug (Mode) := Enable; end if; end Set_Debug; ------------------- -- To_Hex_String -- ------------------- function To_Hex_String (Num : Word) return String is Hex_Digit : constant array (Word range 0 .. 15) of Character := "0123456789abcdef"; Result : String (1 .. 8); Value : Word := Num; begin for J in reverse Result'Range loop Result (J) := Hex_Digit (Value mod 16); Value := Value / 16; end loop; return Result; end To_Hex_String; -------------- -- To_Mixed -- -------------- function To_Mixed (A : String) return String is use Ada.Characters.Handling; Ucase : Boolean := True; Result : String (A'Range); begin for J in A'Range loop if Ucase then Result (J) := To_Upper (A (J)); else Result (J) := To_Lower (A (J)); end if; Ucase := A (J) in '_' | '.' | ' '; end loop; return Result; end To_Mixed; ------------- -- Unquote -- ------------- function Unquote (Str : Value_Type) return Value_Type is begin if Str'Length >= 2 and then ((Str (Str'First) = ''' and then Str (Str'Last) = ''') or else (Str (Str'First) = '"' and then Str (Str'Last) = '"')) then if Str (Str'First) = ''' then return GNATCOLL.Utils.Replace (S => Str (Str'First + 1 .. Str'Last - 1), Pattern => "''", Replacement => "'"); else return GNATCOLL.Utils.Replace (S => Str (Str'First + 1 .. Str'Last - 1), Pattern => """""", Replacement => """"); end if; else return Str; end if; end Unquote; begin Language_List.Id_To_Name.Append ("ada"); Language_List.Id_To_Name.Append ("c"); Language_List.Id_To_Name.Append ("c++"); Language_List.Name_To_Id.Insert ("ada", 1); Language_List.Name_To_Id.Insert ("c", 2); Language_List.Name_To_Id.Insert ("c++", 3); end GPR2;
T-Bone-Willson/SubmarinesFormalApproaches
Ada
10,703
ads
package SubmarineSubSystem with SPARK_Mode is type Operational is (On, Off); -- Can Submarine Operate? type DoSomething is (Fire, CantFire); -- Test for actions can only be done once, -- Nuclear Submarine is operational. --Door Duntionality types type AirDoorOne is (Closed, Open); -- Airlock door One closed or open type AirDoorTwo is (Closed, Open); -- Airlock door Two Closed or open type DoorOneLock is (Locked, Unlocked); -- Airlock door One Locked or Unlocked type DoorTwoLock is (Locked, Unlocked); -- Airlock door Two Locked or Unlocked -- Depth Sensor types type DepthDive is (Dive, Surface); type DepthStage is (Nominal, Warning, Danger); type DepthLevel is new Integer range 0..10; -- Oxyegen System types type OxygenState is (High, Low); type OxygenWarning is (Oxygen_Fine, Oxygen_Warning); type OxygenTank is new Integer range 0..100; -- Reactor System types type ReactorTemp is (Fine, Overheating); -- Submarine variables type Submarine is record GoodToGo : Operational; OpTest : DoSomething; ClosingOne : AirDoorOne; ClosingTwo : AirDoorTwo; LockingOne : DoorOneLock; LockingTwo : DoorTwoLock; DDive : DepthDive; DStage : DepthStage; DLevel : DepthLevel; OState : OxygenState; OWarning : OxygenWarning; OTank : OxygenTank; RTemp : ReactorTemp; end record; -- Record of NuclearSubmarine NuclearSubmarine : Submarine := (GoodToGo => Off, ClosingOne => Open, ClosingTwo => Closed, LockingOne => Unlocked, LockingTwo => Unlocked, OpTest => CantFire, DDive => Surface, DStage => Nominal, DLevel => 0, OState => High, OWarning => Oxygen_Fine, OTank => 100, RTemp => Fine); -- Try to Start Submarine procedure StartSubmarine with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = Off and then NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.LockingOne = Locked and then NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.LockingTwo = Locked, Post => NuclearSubmarine.GoodToGo = On; -- Can only do if Submarine is operational, TEST! procedure SubmarineAction with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.LockingOne = Locked and then NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.LockingTwo = Locked, Post => NuclearSubmarine.OpTest = Fire; ----------------------------------------------------------------------------------------------- -----------------------------------DOOR FUNCTIONALITY------------------------------------------ ----------------------------------------------------------------------------------------------- -- Airlock Door One can only open if Airlock Door Two is Closed. And Vide Versa -- These Checks are made in procedures: D1Close, D2Close, D1Open and D2 Open -- Airlock Door One Close procedure D1Close with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingOne = Open and then NuclearSubmarine.ClosingTwo = Closed, Post => NuclearSubmarine.ClosingOne = Closed; -- Airlock Door Two Close procedure D2Close with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingTwo = Open and then NuclearSubmarine.ClosingOne = Closed, Post => NuclearSubmarine.ClosingTwo = Closed; --Airlock Door One Lock procedure D1Lock with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.LockingOne = Unlocked, Post => NuclearSubmarine.LockingOne = Locked; -- Airlock Door Two Lock procedure D2Lock with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.LockingTwo = Unlocked, Post => NuclearSubmarine.LockingTwo = Locked; --Airlock Door One Open procedure D1Open with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.LockingOne = Unlocked and then NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.ClosingTwo = Closed, Post => NuclearSubmarine.ClosingOne = Open; -- Airlock Door Two Open procedure D2Open with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.LockingTwo = Unlocked and then NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.ClosingOne = Closed, Post => NuclearSubmarine.ClosingTwo = Open; --Airlock Door One Unlock procedure D1Unlock with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.LockingOne = Locked, Post => NuclearSubmarine.ClosingOne = Closed and then NuclearSubmarine.LockingOne = Unlocked; -- Airlock Door Two Unlock procedure D2Unlock with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.LockingTwo = Locked, Post => NuclearSubmarine.ClosingTwo = Closed and then NuclearSubmarine.LockingTwo = Unlocked; ----------------------------------------------------------------------------------------------- -----------------------------------END OF DOOR FUNCTIONALITY----------------------------------- ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -----------------------------------DEPTH SENSOR FUNCTIONALITY---------------------------------- ----------------------------------------------------------------------------------------------- -- Gauges Depth Meter to see if Submarine is Nominal, Warning or Danger stage procedure DepthMeterCheck with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire, Post => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire; -- Changes the depth of the Submarine. Cannnot go above 9. procedure ChangeDepth with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Dive and then NuclearSubmarine.DLevel < 8, Post => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Dive and then NuclearSubmarine.DLevel /= 0; -- Checks if Submarine can Dive procedure DiveOrNot with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Surface and then NuclearSubmarine.RTemp = Fine, Post => NuclearSubmarine.DDive = Dive; -- Allows submarine to resurface procedure Resurface with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Dive, Post=> NuclearSubmarine.DDive = Surface and then NuclearSubmarine.OTank = 100; ----------------------------------------------------------------------------------------------- --------------------------- END OF DEPTH SENSOR FUNCTIONALITY---------------------------------- ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- ----------------------------------- OXYGEN FUNCTIONALITY -------------------------------------- ----------------------------------------------------------------------------------------------- -- Checks the integer value in OTank procedure OxygenReserveCheck with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.OTank <= 0, Post => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.OTank <= 0; --This procedure will consume 10 oxygen out of OTank procedure ConsumeOxygen with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Dive and then NuclearSubmarine.OTank >= 10, Post => NuclearSubmarine.GoodToGo = On and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Dive and then NuclearSubmarine.OTank >= 0; ----------------------------------------------------------------------------------------------- ------------------------------- END OF OXYGEN FUNCTIONALITY --------------------------------- ----------------------------------------------------------------------------------------------- -- Post condition MIGHT fail here. Look at Comments from in submarinesubsystem.adb -- Code line 242 to 247 for clarification. -- This procedure will still pass "Bronze" level of Proofing procedure ReactorOverheatRoutine with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = on and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.RTemp = Fine and then NuclearSubmarine.DDive = Dive, Post => NuclearSubmarine.GoodToGo = on and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.RTemp = Fine and then NuclearSubmarine.RTemp = Overheating; procedure CoolReactor with Global => (In_Out => NuclearSubmarine), Pre => NuclearSubmarine.GoodToGo = on and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Surface and then NuclearSubmarine.RTemp = Overheating, Post => NuclearSubmarine.GoodToGo = on and then NuclearSubmarine.OpTest = Fire and then NuclearSubmarine.DDive = Surface and then NuclearSubmarine.RTemp = Fine; ----------------------------------------------------------------------------------------------- ------------------------------- END OF REACTOR FUNCTIONALITY --------------------------------- ----------------------------------------------------------------------------------------------- end SubmarineSubSystem;
tum-ei-rcs/StratoX
Ada
33
ads
../../../lib/units-navigation.ads
docandrew/sdlada
Ada
8,335
ads
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Video.Windows -- -- Operating system window access and control. -------------------------------------------------------------------------------------------------------------------- with Ada.Finalization; with Ada.Strings.UTF_Encoding; private with SDL.C_Pointers; with SDL.Video.Displays; with SDL.Video.Pixel_Formats; with SDL.Video.Rectangles; with SDL.Video.Surfaces; with System; package SDL.Video.Windows is Window_Error : exception; -- Return a special coordinate value to indicate that you don't care what -- the window position is. Note that you can still specify a target -- display. function Undefined_Window_Position (Display : Natural := 0) return SDL.Natural_Coordinate; -- Return a special coordinate value to indicate that the window position -- should be centered. function Centered_Window_Position (Display : Natural := 0) return SDL.Natural_Coordinate; type Window_Flags is mod 2 ** 32 with Convention => C; Windowed : constant Window_Flags := 16#0000_0000#; Full_Screen : constant Window_Flags := 16#0000_0001#; OpenGL : constant Window_Flags := 16#0000_0002#; Shown : constant Window_Flags := 16#0000_0004#; Hidden : constant Window_Flags := 16#0000_0008#; Borderless : constant Window_Flags := 16#0000_0010#; Resizable : constant Window_Flags := 16#0000_0020#; Minimised : constant Window_Flags := 16#0000_0040#; Maximised : constant Window_Flags := 16#0000_0080#; Input_Grabbed : constant Window_Flags := 16#0000_0100#; Input_Focus : constant Window_Flags := 16#0000_0200#; Mouse_Focus : constant Window_Flags := 16#0000_0400#; Full_Screen_Desktop : constant Window_Flags := Full_Screen or 16#0000_1000#; Foreign : constant Window_Flags := 16#0000_0800#; -- TODO: Not implemented yet. -- TODO: This isn't raising any exception when I pass a different value for some reason. subtype Full_Screen_Flags is Window_Flags with Static_Predicate => Full_Screen_Flags in Windowed | Full_Screen | Full_Screen_Desktop; type ID is mod 2 ** 32 with Convention => C; type Native_Window is private; -- Allow users to derive new types from this. type User_Data is tagged private; type User_Data_Access is access all User_Data'Class; pragma No_Strict_Aliasing (User_Data_Access); -- TODO: Check this type! type Brightness is digits 3 range 0.0 .. 1.0; -- type Window is tagged limited Private; type Window is new Ada.Finalization.Limited_Controlled with private; Null_Window : constant Window; -- TODO: Normalise the API by adding a destroy sub program and making this one call destroy, -- see textures for more info. overriding procedure Finalize (Self : in out Window); function Get_Brightness (Self : in Window) return Brightness with Inline => True; procedure Set_Brightness (Self : in out Window; How_Bright : in Brightness); function Get_Data (Self : in Window; Name : in String) return User_Data_Access; function Set_Data (Self : in out Window; Name : in String; Item : in User_Data_Access) return User_Data_Access; function Display_Index (Self : in Window) return SDL.Video.Displays.Display_Indices; procedure Get_Display_Mode (Self : in Window; Mode : out SDL.Video.Displays.Mode); procedure Set_Display_Mode (Self : in out Window; Mode : in SDL.Video.Displays.Mode); function Get_Flags (Self : in Window) return Window_Flags; function From_ID (Window_ID : in ID) return Window; procedure Get_Gamma_Ramp (Self : in Window; Red, Green, Blue : out SDL.Video.Pixel_Formats.Gamma_Ramp); procedure Set_Gamma_Ramp (Self : in out Window; Red, Green, Blue : in SDL.Video.Pixel_Formats.Gamma_Ramp); function Is_Grabbed (Self : in Window) return Boolean with Inline => True; procedure Set_Grabbed (Self : in out Window; Grabbed : in Boolean := True) with Inline => True; function Get_ID (Self : in Window) return ID with Inline => True; function Get_Maximum_Size (Self : in Window) return SDL.Sizes; procedure Set_Maximum_Size (Self : in out Window; Size : in SDL.Sizes) with Inline => True; function Get_Minimum_Size (Self : in Window) return SDL.Sizes; procedure Set_Minimum_Size (Self : in out Window; Size : in SDL.Sizes) with Inline => True; function Pixel_Format (Self : in Window) return SDL.Video.Pixel_Formats.Pixel_Format with Inline => True; function Get_Position (Self : in Window) return SDL.Natural_Coordinates; procedure Set_Position (Self : in out Window; Position : SDL.Natural_Coordinates) with Inline => True; function Get_Size (Self : in Window) return SDL.Sizes; procedure Set_Size (Self : in out Window; Size : in SDL.Sizes) with Inline => True; function Get_Surface (Self : in Window) return SDL.Video.Surfaces.Surface; function Get_Title (Self : in Window) return Ada.Strings.UTF_Encoding.UTF_8_String; procedure Set_Title (Self : in Window; Title : in Ada.Strings.UTF_Encoding.UTF_8_String); -- SDL_GetWindowWMInfo procedure Hide (Self : in Window) with Inline => True; procedure Show (Self : in Window) with Inline => True; procedure Maximise (Self : in Window) with Inline => True; procedure Minimise (Self : in Window) with Inline => True; procedure Raise_And_Focus (Self : in Window) with Inline => True; procedure Restore (Self : in Window) with Inline => True; procedure Set_Mode (Self : in out Window; Flags : in Full_Screen_Flags); procedure Set_Icon (Self : in out Window; Icon : in SDL.Video.Surfaces.Surface) with Inline => True; procedure Update_Surface (Self : in Window); procedure Update_Surface_Rectangle (Self : in Window; Rectangle : in SDL.Video.Rectangles.Rectangle); procedure Update_Surface_Rectangles (Self : in Window; Rectangles : in SDL.Video.Rectangles.Rectangle_Arrays); -- Determine whether any windows have been created. function Exist return Boolean with Inline => True; private -- TODO: Make this a proper type. type Native_Window is new System.Address; type User_Data is new Ada.Finalization.Controlled with null record; type Window is new Ada.Finalization.Limited_Controlled with record Internal : SDL.C_Pointers.Windows_Pointer := null; -- System.Address := System.Null_Address; Owns : Boolean := True; -- Does this Window type own the Internal data? end record; function Get_Internal_Window (Self : in Window) return SDL.C_Pointers.Windows_Pointer with Export => True, Convention => Ada; Null_Window : constant Window := (Ada.Finalization.Limited_Controlled with Internal => null, -- System.Null_Address, Owns => True); Total_Windows_Created : Natural := Natural'First; procedure Increment_Windows; procedure Decrement_Windows; end SDL.Video.Windows;
AdaCore/libadalang
Ada
46
ads
package Pkg2 is procedure Dummy; end Pkg2;
twdroeger/ada-awa
Ada
9,340
adb
----------------------------------------------------------------------- -- awa-questions-tests -- Unit tests for questions module -- Copyright (C) 2018, 2019 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Test_Caller; with ASF.Requests.Mockup; with ASF.Responses.Mockup; with ASF.Tests; with AWA.Tests.Helpers.Users; package body AWA.Questions.Tests is use Ada.Strings.Unbounded; use AWA.Tests; package Caller is new Util.Test_Caller (Test, "Questions.Beans"); procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite) is begin Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load_List (Anonymous)", Test_Anonymous_Access'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save", Test_Create_Question'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Load (missing)", Test_Missing_Page'Access); Caller.Add_Test (Suite, "Test AWA.Questions.Beans.Save (answer)", Test_Answer_Question'Access); end Add_Tests; -- ------------------------------ -- Get some access on the wiki as anonymous users. -- ------------------------------ procedure Verify_Anonymous (T : in out Test; Page : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions list page is invalid"); ASF.Tests.Do_Get (Request, Reply, "/questions/tags/tag", "question-list-tagged.html"); ASF.Tests.Assert_Contains (T, "<title>Questions</title>", Reply, "Questions tag page is invalid"); if Page'Length > 0 then ASF.Tests.Do_Get (Request, Reply, "/questions/view/" & Page, "question-page-" & Page & ".html"); ASF.Tests.Assert_Contains (T, Title, Reply, "Question page " & Page & " is invalid"); ASF.Tests.Assert_Matches (T, ".input type=.hidden. name=.question-id. " & "value=.[0-9]+. id=.question-id.../input", Reply, "Question page " & Page & " is invalid"); end if; end Verify_Anonymous; -- ------------------------------ -- Verify that the question list contains the given question. -- ------------------------------ procedure Verify_List_Contains (T : in out Test; Id : in String; Title : in String) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/list.html", "question-list-recent.html"); ASF.Tests.Assert_Contains (T, "Questions", Reply, "List of questions page is invalid"); ASF.Tests.Assert_Contains (T, "/questions/view/" & Id, Reply, "List of questions page does not reference the page"); ASF.Tests.Assert_Contains (T, Title, Reply, "List of questions page does not contain the question"); end Verify_List_Contains; -- ------------------------------ -- Test access to the question as anonymous user. -- ------------------------------ procedure Test_Anonymous_Access (T : in out Test) is begin T.Verify_Anonymous ("", ""); end Test_Anonymous_Access; -- ------------------------------ -- Test creation of question by simulating web requests. -- ------------------------------ procedure Test_Create_Question (T : in out Test) is procedure Create_Question (Title : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Question (Title : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("title", Title); Request.Set_Parameter ("text", "# Main title" & ASCII.LF & "* The question content." & ASCII.LF & "* Second item." & ASCII.LF); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/ask.html", "questions-ask.html"); T.Question_Ident := Helpers.Extract_Redirect (Reply, "/asfunit/questions/view/"); Util.Tests.Assert_Matches (T, "[0-9]+$", To_String (T.Question_Ident), "Invalid redirect after question creation"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("question"); end Create_Question; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Question ("Question 1 page title1"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 1 page title1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 1 page title1"); Create_Question ("Question 2 page title2"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 2 page title2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 2 page title2"); Create_Question ("Question 3 page title3"); T.Verify_List_Contains (To_String (T.Question_Ident), "Question 3 page title3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Question 3 page title3"); end Test_Create_Question; -- ------------------------------ -- Test getting a wiki page which does not exist. -- ------------------------------ procedure Test_Missing_Page (T : in out Test) is Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; begin ASF.Tests.Do_Get (Request, Reply, "/questions/view.html?id=12345678", "question-page-missing.html"); ASF.Tests.Assert_Matches (T, "<title>Question not found</title>", Reply, "Question page title '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); ASF.Tests.Assert_Matches (T, "question.*removed", Reply, "Question page content '12345678' is invalid", ASF.Responses.SC_NOT_FOUND); end Test_Missing_Page; -- ------------------------------ -- Test answer of question by simulating web requests. -- ------------------------------ procedure Test_Answer_Question (T : in out Test) is procedure Create_Answer (Content : in String); Request : ASF.Requests.Mockup.Request; Reply : ASF.Responses.Mockup.Response; procedure Create_Answer (Content : in String) is begin Request.Set_Parameter ("post", "1"); Request.Set_Parameter ("question-id", To_String (T.Question_Ident)); Request.Set_Parameter ("answer-id", ""); Request.Set_Parameter ("text", Content); Request.Set_Parameter ("save", "1"); ASF.Tests.Do_Post (Request, Reply, "/questions/forms/answer-form.html", "questions-answer.html"); ASF.Tests.Assert_Contains (T, "/questions/view/" & To_String (T.Question_Ident), Reply, "Answer response is invalid"); -- Remove the 'question' bean from the request so that we get a new instance -- for the next call. Request.Remove_Attribute ("answer"); end Create_Answer; begin AWA.Tests.Helpers.Users.Login ("[email protected]", Request); Create_Answer ("Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); Create_Answer ("Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); Create_Answer ("Answer content 3"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 1"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 2"); T.Verify_Anonymous (To_String (T.Question_Ident), "Answer content 3"); end Test_Answer_Question; end AWA.Questions.Tests;
optikos/oasis
Ada
5,572
adb
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Program.Nodes.Exception_Declarations is function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Colon_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Exception_Token : not null Program.Lexical_Elements .Lexical_Element_Access; With_Token : Program.Lexical_Elements.Lexical_Element_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Semicolon_Token : not null Program.Lexical_Elements .Lexical_Element_Access) return Exception_Declaration is begin return Result : Exception_Declaration := (Names => Names, Colon_Token => Colon_Token, Exception_Token => Exception_Token, With_Token => With_Token, Aspects => Aspects, Semicolon_Token => Semicolon_Token, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Names : not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access; Aspects : Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False) return Implicit_Exception_Declaration is begin return Result : Implicit_Exception_Declaration := (Names => Names, Aspects => Aspects, Is_Part_Of_Implicit => Is_Part_Of_Implicit, Is_Part_Of_Inherited => Is_Part_Of_Inherited, Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null) do Initialize (Result); end return; end Create; overriding function Names (Self : Base_Exception_Declaration) return not null Program.Elements.Defining_Identifiers .Defining_Identifier_Vector_Access is begin return Self.Names; end Names; overriding function Aspects (Self : Base_Exception_Declaration) return Program.Elements.Aspect_Specifications .Aspect_Specification_Vector_Access is begin return Self.Aspects; end Aspects; overriding function Colon_Token (Self : Exception_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Colon_Token; end Colon_Token; overriding function Exception_Token (Self : Exception_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Exception_Token; end Exception_Token; overriding function With_Token (Self : Exception_Declaration) return Program.Lexical_Elements.Lexical_Element_Access is begin return Self.With_Token; end With_Token; overriding function Semicolon_Token (Self : Exception_Declaration) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Semicolon_Token; end Semicolon_Token; overriding function Is_Part_Of_Implicit (Self : Implicit_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Exception_Declaration) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; procedure Initialize (Self : aliased in out Base_Exception_Declaration'Class) is begin for Item in Self.Names.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; for Item in Self.Aspects.Each_Element loop Set_Enclosing_Element (Item.Element, Self'Unchecked_Access); end loop; null; end Initialize; overriding function Is_Exception_Declaration_Element (Self : Base_Exception_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Exception_Declaration_Element; overriding function Is_Declaration_Element (Self : Base_Exception_Declaration) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Declaration_Element; overriding procedure Visit (Self : not null access Base_Exception_Declaration; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Exception_Declaration (Self); end Visit; overriding function To_Exception_Declaration_Text (Self : aliased in out Exception_Declaration) return Program.Elements.Exception_Declarations .Exception_Declaration_Text_Access is begin return Self'Unchecked_Access; end To_Exception_Declaration_Text; overriding function To_Exception_Declaration_Text (Self : aliased in out Implicit_Exception_Declaration) return Program.Elements.Exception_Declarations .Exception_Declaration_Text_Access is pragma Unreferenced (Self); begin return null; end To_Exception_Declaration_Text; end Program.Nodes.Exception_Declarations;
reznikmm/matreshka
Ada
4,011
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 ODF.DOM.Style_Row_Height_Attributes; package Matreshka.ODF_Style.Row_Height_Attributes is type Style_Row_Height_Attribute_Node is new Matreshka.ODF_Style.Abstract_Style_Attribute_Node and ODF.DOM.Style_Row_Height_Attributes.ODF_Style_Row_Height_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Style_Row_Height_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Style_Row_Height_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Style.Row_Height_Attributes;
persan/testlibadalang
Ada
693
adb
with Utils.Command_Lines; use Utils.Command_Lines; with Utils.Drivers; with JSON_Gen.Actions; with JSON_Gen.Command_Lines; procedure JSON_Gen.Main is -- Main procedure for lalstub -- procedure Callback (Phase : Parse_Phase; Swit : Dynamically_Typed_Switch); procedure Callback (Phase : Parse_Phase; Swit : Dynamically_Typed_Switch) is null; Tool : Actions.Json_Gen_Tool; Cmd : Command_Line (JSON_Gen.Command_Lines.Descriptor'Access); begin Utils.Drivers.Driver (Cmd => Cmd, Tool => Tool, Tool_Package_Name => "jsongen", Needs_Per_File_Output => True, Callback => Callback'Unrestricted_Access); end JSON_Gen.Main;
reznikmm/ada-pretty
Ada
1,508
adb
-- Copyright (c) 2017 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Ada_Pretty.Joins is -------------- -- Document -- -------------- overriding function Document (Self : Join; Printer : not null access League.Pretty_Printers.Printer'Class; Pad : Natural) return League.Pretty_Printers.Document is pragma Unreferenced (Pad); Count : Positive := 1; Next : Node_Access := Self.Left; Max : Natural := Self.Right.Max_Pad; begin while Next.all in Join loop Count := Count + 1; Max := Natural'Max (Max, Join (Next.all).Right.Max_Pad); Next := Join (Next.all).Left; end loop; Max := Natural'Max (Max, Next.Max_Pad); declare List : Node_Access_Array (1 .. Count) := (others => Self.Right); begin List (Count) := Self.Right; Next := Self.Left; for J in reverse 1 .. Count - 1 loop List (J) := Join (Next.all).Right; Next := Join (Next.all).Left; end loop; return Next.Join (List, Max, Printer); end; end Document; -------------- -- New_Join -- -------------- function New_Join (Left : not null Node_Access; Right : not null Node_Access) return Node'Class is begin return Join'(Left, Right); end New_Join; end Ada_Pretty.Joins;
rveenker/sdlada
Ada
2,308
ads
-------------------------------------------------------------------------------------------------------------------- -- Copyright (c) 2013-2020, Luke A. Guest -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -------------------------------------------------------------------------------------------------------------------- -- SDL.Images.Versions -- -- Library version information. -------------------------------------------------------------------------------------------------------------------- with SDL.Versions; package SDL.Images.Versions is -- These allow the user to determine which version of SDLAda_Image they compiled with. Compiled_Major : constant SDL.Versions.Version_Level with Import => True, Convention => C, External_Name => "SDL_Ada_Image_Major_Version"; Compiled_Minor : constant SDL.Versions.Version_Level with Import => True, Convention => C, External_Name => "SDL_Ada_Image_Minor_Version"; Compiled_Patch : constant SDL.Versions.Version_Level with Import => True, Convention => C, External_Name => "SDL_Ada_Image_Patch_Version"; Compiled : constant SDL.Versions.Version := (Major => Compiled_Major, Minor => Compiled_Minor, Patch => Compiled_Patch); procedure Linked_With (Info : in out SDL.Versions.Version); end SDL.Images.Versions;
reznikmm/slimp
Ada
4,632
ads
-- Copyright (c) 2019 Maxim Reznik <[email protected]> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Ada.Calendar; with Ada.Containers.Vectors; with GNAT.Sockets; with League.Stream_Element_Vectors; with League.Strings; with Slim.Fonts; with Slim.Messages; with Slim.Menu_Views; limited with Slim.Players.Displays; with Slim.Menu_Models; package Slim.Players is type Player is tagged limited private; type Player_Access is access all Player'Class; procedure Initialize (Self : in out Player'Class; Socket : GNAT.Sockets.Socket_Type; Font : League.Strings.Universal_String; Splash : League.Strings.Universal_String; Menu : League.Strings.Universal_String); procedure Play_Radio (Self : in out Player'Class; URL : League.Strings.Universal_String); type Song is record File : League.Strings.Universal_String; Title : League.Strings.Universal_String; end record; type Song_Array is array (Positive range <>) of Song; procedure Play_Files (Self : in out Player'Class; Root : League.Strings.Universal_String; M3U : League.Strings.Universal_String; List : Song_Array; From : Positive; Skip : Natural); -- Start playing given playlist. Skip given number of seconds of the first -- song procedure Play_Next_File (Self : in out Player'Class; Immediate : Boolean := True); procedure Play_Previous_File (Self : in out Player'Class; Immediate : Boolean := True); procedure Stop (Self : in out Player'Class); procedure Save_Position (Self : in out Player'Class); -- If play a playlist, then remember current position procedure Get_Position (Self : in out Player'Class; M3U : League.Strings.Universal_String; Index : out Positive; Skip : out Natural); -- Find saved position for given playlist. Return (1,0) if not found procedure Volume (Self : in out Player'Class; Value : Natural); not overriding procedure Process_Message (Self : in out Player); private type State_Kind is (Connected, Idle, Play_Radio, Play_Files); type Play_State is record Volume : Natural range 0 .. 100; Volume_Set_Time : Ada.Calendar.Time; Current_Song : League.Strings.Universal_String; Seconds : Natural; Paused : Boolean; end record; package Song_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Song); type Player_State (Kind : State_Kind := Connected) is record case Kind is when Connected => null; when Idle => Time : Ada.Calendar.Time; -- Time on players display Menu_View : Slim.Menu_Views.Menu_View; when Play_Radio | Play_Files => Play_State : Slim.Players.Play_State; case Kind is when Play_Files => Root : League.Strings.Universal_String; M3U_Name : League.Strings.Universal_String; Playlist : Song_Vectors.Vector; Index : Positive; Offset : Natural; -- If current file started playing with Offset when others => null; end case; end case; end record; type Menu_Model_Access is access all Slim.Menu_Models.Menu_Model'Class; type Player is tagged limited record Socket : GNAT.Sockets.Socket_Type := GNAT.Sockets.No_Socket; State : Player_State; Ping : Ada.Calendar.Time := Ada.Calendar.Clock; Font : aliased Slim.Fonts.Font; Splash : League.Stream_Element_Vectors.Stream_Element_Vector; Menu : Menu_Model_Access; -- Splash screen WiFi : Natural; -- Wireless Signal Strength (0-100) -- Elapsed : Natural := 0; -- elapsed seconds of the current stream end record; procedure Write_Message (Socket : GNAT.Sockets.Socket_Type; Message : Slim.Messages.Message'Class); function Get_Display (Self : Player; Height : Positive := 32; Width : Positive := 160) return Slim.Players.Displays.Display; function First_Menu (Self : Player'Class) return Slim.Menu_Views.Menu_View; function "+" (X : Wide_Wide_String) return League.Strings.Universal_String renames League.Strings.To_Universal_String; procedure Request_Next_File (Self : in out Player'Class); end Slim.Players;
Fabien-Chouteau/Ada_Drivers_Library
Ada
4,142
adb
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016-2019, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Cortex_M.NVIC; with System.Machine_Code; use System.Machine_Code; package body nRF51.Interrupts is Handlers : array (nRF51.Interrupts.Interrupt_Name) of Handler := (others => null); procedure GNAT_IRQ_Handler; pragma Export (Asm, GNAT_IRQ_Handler, "__adl_irq_handler"); ------------------ -- Set_Priority -- ------------------ procedure Set_Priority (Int : Interrupt_Name; Prio : Interrupt_Priority) is begin Cortex_M.NVIC.Set_Priority (Int'Enum_Rep, Prio); end Set_Priority; ------------ -- Enable -- ------------ procedure Enable (Int : Interrupt_Name) is begin Cortex_M.NVIC.Enable (Int'Enum_Rep); end Enable; ------------- -- Disable -- ------------- procedure Disable (Int : Interrupt_Name) is begin Cortex_M.NVIC.Disable (Int'Enum_Rep); end Disable; ------------- -- Pending -- ------------- function Pending (Int : Interrupt_Name) return Boolean is begin return Cortex_M.NVIC.Pending (Int'Enum_Rep); end Pending; -------------- -- Register -- -------------- procedure Register (Id : nRF51.Interrupts.Interrupt_Name; Hdl : Handler) is begin Handlers (Id) := Hdl; end Register; ---------------------- -- GNAT_IRQ_Handler -- ---------------------- procedure GNAT_IRQ_Handler is Id : nRF51.Interrupts.Interrupt_Name; IPSR : UInt32; begin Asm ("mrs %0, ipsr", UInt32'Asm_Output ("=r", IPSR), Volatile => True); IPSR := IPSR and 16#FF#; Id := nRF51.Interrupts.Interrupt_Name'Val (IPSR - 16); if Handlers (Id) /= null then Handlers (Id).all; end if; end GNAT_IRQ_Handler; end nRF51.Interrupts;
niechaojun/Amass
Ada
489
ads
-- Copyright 2017 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. name = "LoCArchive" type = "archive" function start() setratelimit(1) end function vertical(ctx, domain) crawl(ctx, buildurl(domain)) end function resolved(ctx, name, domain, records) crawl(ctx, buildurl(name)) end function buildurl(domain) return "http://webarchive.loc.gov/all/" .. os.date("%Y") .. "/" .. domain end
reznikmm/matreshka
Ada
4,739
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Text_Bookmark_End_Elements; package Matreshka.ODF_Text.Bookmark_End_Elements is type Text_Bookmark_End_Element_Node is new Matreshka.ODF_Text.Abstract_Text_Element_Node and ODF.DOM.Text_Bookmark_End_Elements.ODF_Text_Bookmark_End with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Text_Bookmark_End_Element_Node; overriding function Get_Local_Name (Self : not null access constant Text_Bookmark_End_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Text_Bookmark_End_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Text_Bookmark_End_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Text_Bookmark_End_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Text.Bookmark_End_Elements;
stcarrez/ada-wiki
Ada
4,324
adb
----------------------------------------------------------------------- -- wiki-nodes-dump -- Dump the wiki nodes -- Copyright (C) 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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.Nodes.Lists; with Wiki.Strings; with Wiki.Attributes; procedure Wiki.Nodes.Dump (Node : in Wiki.Nodes.Node_Type) is procedure Dump_Node (Node : in Wiki.Nodes.Node_Type); Level : Positive := 1; procedure Dump_Node (Node : in Wiki.Nodes.Node_Type) is procedure Print_Length (Len : Natural); procedure Print (Name : in String; Value : in Wiki.Strings.WString); Kind : constant Wiki.Strings.WString := Node_Kind'Wide_Wide_Image (Node.Kind); Result : Wiki.Strings.BString (256); procedure Print (Name : in String; Value : in Wiki.Strings.WString) is begin Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Name)); Strings.Append_String (Result, "="); Strings.Append_String (Result, Value); end Print; procedure Print_Length (Len : Natural) is S : constant Wide_Wide_String := Natural'Wide_Wide_Image (Len); begin Strings.Append_String (Result, " ("); Strings.Append_String (Result, S (S'First + 1 .. S'Last)); Strings.Append_String (Result, ")"); end Print_Length; begin if Node.Kind = N_TAG_START then Strings.Append_String (Result, Html_Tag'Wide_Wide_Image (Node.Tag_Start)); else Strings.Append_String (Result, Kind); end if; Print_Length (Node.Len); case Node.Kind is when N_HEADER | N_BLOCKQUOTE | N_INDENT | N_TOC_ENTRY | N_NUM_LIST_START | N_LIST_START | N_DEFINITION => Strings.Append_String (Result, Natural'Wide_Wide_Image (Node.Level)); Strings.Append_String (Result, " "); Write (Level, Wiki.Strings.To_WString (Result)); if Node.Content /= null then Level := Level + 1; Lists.Iterate (Node.Content, Dump_Node'Access); Level := Level - 1; end if; return; when N_TEXT => for Format in Format_Type'Range loop if Node.Format (Format) then Strings.Append_String (Result, " "); Strings.Append_String (Result, Format_Type'Wide_Wide_Image (Format)); end if; end loop; Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Text); when N_IMAGE | N_LINK | N_QUOTE => Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Title); Attributes.Iterate (Node.Link_Attr, Print'Access); when N_TAG_START | N_TABLE | N_ROW | N_COLUMN => Attributes.Iterate (Node.Attributes, Print'Access); Write (Level, Wiki.Strings.To_WString (Result)); if Node.Children /= null then Level := Level + 1; Lists.Iterate (Node.Children, Dump_Node'Access); Level := Level - 1; end if; return; when N_PREFORMAT => Strings.Append_String (Result, " "); Strings.Append_String (Result, Strings.To_WString (Node.Language)); Strings.Append_String (Result, " "); Strings.Append_String (Result, Node.Preformatted); when others => null; end case; Write (Level, Wiki.Strings.To_WString (Result)); end Dump_Node; begin Dump_Node (Node); end Wiki.Nodes.Dump;
zhmu/ananas
Ada
875
adb
-- { dg-do compile } -- { dg-options "-O2 -fdump-tree-optimized" } with Ada.Command_Line; use Ada.Command_Line; with Opt86_Pkg; use Opt86_Pkg; procedure Opt86c is S1, S2, S3, S4 : Enum; begin S1 := Enum'Value (Argument (1)); S2 := Enum'Value (Argument (2)); S3 := Enum'Value (Argument (3)); S4 := Enum'Value (Argument (4)); if S1 in Val16 | Val8 | Val26 | Val2 | Val10 then raise Program_Error; end if; if S2 not in Val16 | Val8 | Val26 | Val2 | Val10 then raise Program_Error; end if; if S3 = Val3 or S3 = Val25 or S3 = Val13 or S3 = Val29 or S3 = Val11 then raise Program_Error; end if; if S4 /= Val3 and S4 /= Val25 and S4 /= Val13 and S4 /= Val29 and s4 /= Val11 then raise Program_Error; end if; end; -- { dg-final { scan-tree-dump-not "> 26" "optimized" } } -- { dg-final { scan-tree-dump-not "> 29" "optimized" } }
zhmu/ananas
Ada
321
adb
-- PR ada/69219 -- Testcae by yuta tomino <[email protected]> */ -- { dg-do compile } procedure Inline12 is procedure NI; procedure IA; pragma Convention (Intrinsic, IA); pragma Inline_Always (IA); procedure IA is begin NI; end; procedure NI is null; begin IA; end;
houey/Amass
Ada
6,827
ads
-- Copyright 2017-2021 Jeff Foley. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. local json = require("json") name = "Spyse" type = "api" function start() setratelimit(1) end function check() local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c ~= nil and c.key ~= nil and c.key ~= "") then return true end return false end function vertical(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end for i = 0,10000,100 do local u = subsurl(domain, i) local resp = getpage(ctx, u, c.key, cfg.ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return false end for i, item in pairs(d['data'].items) do sendnames(ctx, item.name) end end end function subsurl(domain, offset) return "https://api.spyse.com/v3/data/domain/subdomain?domain=" .. domain .. "&limit=100&offset=" .. tostring(offset) end function horizontal(ctx, domain) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end -- Spyse API domain/related/domain often returns false positives (domains not owned by the provided domain) --horizonnames(ctx, domain, c.key, cfg.ttl) horizoncerts(ctx, domain, c.key, cfg.ttl) end function horizonnames(ctx, domain, key, ttl) for i = 0,10000,100 do u = namesurl(domain, i) resp = getpage(ctx, u, key, ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then break end for i, item in pairs(d['data'].items) do if (item.domain.name ~= "") then local names = find(item.domain.name, subdomainre) if (names ~= nil and #names > 0 and names[1] ~= "") then associated(ctx, domain, names[1]) end end end end end function namesurl(domain, offset) return "https://api.spyse.com/v3/data/domain/related/domain?domain=" .. domain .. "&limit=100&offset=" .. tostring(offset) end function horizoncerts(ctx, domain, key, ttl) local u = "https://api.spyse.com/v3/data/domain/org?domain=" .. domain local resp = getpage(ctx, u, key, ttl) if (resp == "") then return end local d = json.decode(resp) if (d == nil or d['data'].id == nil) then return end local orgid = d['data'].id for i = 0,10000,100 do u = certsurl(orgid, i) resp = getpage(ctx, u, key, ttl) if (resp == "") then break end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then break end for i, item in pairs(d['data'].items) do local san = item.parsed.extensions.subject_alt_name if (san ~= nil and #(san.dns_names) > 0) then for j, name in pairs(san.dns_names) do local names = find(name, subdomainre) if (names ~= nil and #names > 0 and names[1] ~= "") then associated(ctx, domain, names[1]) end end end end end end function certsurl(id, offset) return "https://api.spyse.com/v3/data/org/cert/subject?id=" .. id .. "&limit=100&offset=" .. tostring(offset) end function asn(ctx, addr, asn) local c local cfg = datasrc_config() if cfg ~= nil then c = cfg.credentials end if (c == nil or c.key == nil or c.key == "") then return end local prefix if (asn == 0) then if (addr == "") then return end asn, prefix = getasn(ctx, addr, c.key, cfg.ttl) if (asn == 0) then return end end local a = asinfo(ctx, asn, c.key, cfg.ttl) if (a == nil or #(a.netblocks) == 0) then return end if (prefix == "") then prefix = a.netblocks[1] parts = split(prefix, "/") addr = parts[1] end newasn(ctx, { ['addr']=addr, ['asn']=asn, ['prefix']=prefix, ['desc']=a.desc, ['netblocks']=a.netblocks, }) end function getasn(ctx, ip, key, ttl) local u = "https://api.spyse.com/v3/data/ip?ip=" .. tostring(ip) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return 0, "" end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return 0, "" end local cidr local asn = 0 for i, item in pairs(d['data'].items) do local num = item.isp_info.as_num if (asn == 0 or asn < num) then asn = num cidr = item.cidr end end return asn, cidr end function asinfo(ctx, asn, key, ttl) local u = "https://api.spyse.com/v3/data/as?asn=" .. tostring(asn) local resp = getpage(ctx, u, key, ttl) if (resp == "") then return nil end local d = json.decode(resp) if (d == nil or #(d['data'].items) == 0) then return nil end local cidrs = {} for i, p in pairs(d.items[1].ipv4_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end for i, p in pairs(d.items[1].ipv6_cidr_array) do table.insert(cidrs, p.ip .. "/" .. tostring(p.cidr)) end return { desc=d.items[1].as_org, netblocks=cidrs, } end function getpage(ctx, url, key, ttl) local resp, err = request(ctx, { ['url']=url, headers={ ['Authorization']="Bearer " .. key, ['Content-Type']="application/json", }, }) if (err ~= nil and err ~= "") then return "" end return resp end function sendnames(ctx, content) local names = find(content, subdomainre) if (names == nil) then return end local found = {} for i, v in pairs(names) do if (found[v] == nil) then newname(ctx, v) found[v] = true end end end function split(str, delim) local result = {} local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return result end for i, match in pairs(matches) do table.insert(result, match) end return result end
DavJo-dotdotdot/Ada_Drivers_Library
Ada
2,003
ads
-- This package was generated by the Ada_Drivers_Library project wizard script package ADL_Config is Architecture : constant String := "ARM"; -- From board definition Board : constant String := "MicroBit_v2"; -- From user input Boot_Memory : constant String := "flash"; -- From user input CPU_Core : constant String := "ARM Cortex-M4F"; -- From mcu definition Device_Family : constant String := "nRF52"; -- From board definition Device_Name : constant String := "nRF52833xxAA"; -- From board definition Has_Custom_Memory_Area_1 : constant Boolean := False; -- From user input Has_Ravenscar_Full_Runtime : constant String := "True"; -- From board definition Has_Ravenscar_SFP_Runtime : constant String := "True"; -- From board definition Has_ZFP_Runtime : constant String := "True"; -- From board definition Max_Mount_Name_Length : constant := 128; -- From user input Max_Mount_Points : constant := 2; -- From user input Max_Path_Length : constant := 1024; -- From user input Number_Of_Interrupts : constant := 128; -- From MCU definition Runtime_Name : constant String := "ravenscar-sfp-nrf52833"; -- From user input Runtime_Name_Suffix : constant String := "nrf52833"; -- From board definition Runtime_Profile : constant String := "ravenscar-sfp"; -- From user input Use_Startup_Gen : constant Boolean := False; -- From user input Vendor : constant String := "Nordic"; -- From board definition end ADL_Config;
charlie5/lace
Ada
30,902
adb
with openGL.Viewport, openGL.Program, openGL.Camera, openGL.Palette, openGL.Model.billboard.textured, openGL.Geometry. lit_textured_skinned, openGL.Geometry.lit_colored_textured_skinned, openGL.Font.texture, openGL.Server, openGL.Tasks, openGL.IO, openGL.Errors, GL.Binding, GL.lean, Interfaces.C, gnat.heap_Sort, System, ada.Text_IO, ada.Exceptions, ada.Task_Identification, ada.unchecked_Deallocation; package body openGL.Renderer.lean is use GL, Program, Interfaces.C, ada.Text_IO; --------- --- Forge -- procedure define (Self : access Item) is begin Self.safe_Camera_updates_Map.define; end define; procedure destroy (Self : in out Item) is use Texture; begin Self.stop_Engine; while not Self.Engine'Terminated loop delay Duration'Small; end loop; Self.safe_Camera_updates_Map.destruct; declare procedure free is new ada.unchecked_Deallocation (visual_geometry_Couples, visual_geometry_Couples_view); begin free (Self.all_opaque_Couples); free (Self.all_lucid_Couples); end; vacuum (Self.texture_Pool); destroy (Self.texture_Pool); end destroy; procedure free (Self : in out View) is procedure deallocate is new ada.unchecked_Deallocation (Item'Class, View); begin Self.destroy; deallocate (Self); end free; -------------- --- Attributes -- procedure Context_is (Self : in out Item; Now : in Context.view) is begin Self.Context := Now; end Context_is; procedure Context_Setter_is (Self : in out Item; Now : in context_Setter) is begin Self.context_Setter := Now; end Context_Setter_is; procedure Swapper_is (Self : in out Item; Now : in Swapper) is begin Self.Swapper := Now; end Swapper_is; procedure queue_Impostor_updates (Self : in out Item; the_Updates : in impostor_Updates; the_Camera : access Camera.item'Class) is begin Self.safe_Camera_updates_Map.add (the_Updates, Camera_view (the_Camera)); end queue_Impostor_updates; procedure queue_Visuals (Self : in out Item; the_Visuals : in Visual.views; the_Camera : access Camera.item'Class) is begin Self.safe_Camera_updates_Map.add (the_Visuals, Camera_view (the_Camera)); end queue_Visuals; procedure update_Impostors_and_draw_Visuals (Self : in out Item; all_Updates : in camera_updates_Couples) is begin for i in all_Updates'Range loop declare the_Camera : constant Camera_view := all_Updates (i).Camera; the_Updates : constant updates_for_Camera_view := all_Updates (i).Updates; begin Viewport.Extent_is ((the_Camera.Viewport.Max (1), the_Camera.Viewport.Max (2))); Self.update_Impostors (the_Updates.impostor_Updates (1 .. the_Updates.impostor_updates_Last), camera_world_Transform => the_Camera.World_Transform, view_Transform => the_Camera.view_Transform, perspective_Transform => the_Camera.projection_Transform); the_Updates.impostor_updates_Last := 0; end; end loop; Self.swap_Required := False; for i in all_Updates'Range loop declare the_Camera : constant Camera_view := all_Updates (i).Camera; the_Updates : constant updates_for_Camera_view := all_Updates (i).Updates; clear_Frame : constant Boolean := i = all_Updates'First; begin Viewport.Extent_is ((the_Camera.Viewport.Max (1), the_Camera.Viewport.Max (2))); Self.draw (the_Visuals => the_Updates.Visuals (1 .. the_Updates.visuals_Last), camera_world_Transform => the_Camera.World_Transform, view_Transform => the_Camera.view_Transform, perspective_Transform => the_Camera.projection_Transform, clear_Frame => clear_Frame, to_Surface => null); the_Updates.visuals_Last := 0; Self.swap_Required := True; end; end loop; end update_Impostors_and_draw_Visuals; procedure free_old_Models (Self : in out Item) is use Model; free_Models : graphics_Models; Last : Natural; begin Self.obsolete_Models.fetch (free_Models, Last); for i in 1 .. Last loop free (free_Models (i)); end loop; end free_old_Models; procedure free_old_Impostors (Self : in out Item) is use Impostor; free_Impostors : Impostor_Set; Last : Natural; begin Self.obsolete_Impostors.fetch (free_Impostors, Last); for i in 1 .. Last loop free (free_Impostors (i)); end loop; end free_old_Impostors; --------- -- Engine -- task body Engine is the_Context : Context.view with unreferenced; Done : Boolean := False; begin select accept start (Context : openGL.Context.view) do the_Context := Context; -- TODO: This is not used. end start; openGL.Tasks.Renderer_Task := ada.Task_Identification.current_Task; Self.context_Setter.all; put_Line ("openGL Server version: " & Server.Version); or accept Stop do Done := True; end Stop; end select; openGL.Geometry. lit_textured_skinned.define_Program; openGL.Geometry.lit_colored_textured_skinned.define_Program; while not Done loop declare all_Updates : camera_updates_Couples (1 .. 100); -- Caters for 100 cameras. Length : Natural; new_font_Name : asset_Name := null_Asset; new_font_Size : Integer; new_snapshot_Name : asset_Name := null_Asset; snapshot_has_Alpha : Boolean; begin select accept render do Self.is_Busy := True; Self.safe_Camera_updates_Map.fetch_all_Updates (all_Updates, Length); end render; or accept add_Font (font_Id : in Font.font_Id) do new_font_Name := font_Id.Name; new_font_Size := font_Id.Size; end add_Font; or accept Screenshot (Filename : in String; with_Alpha : in Boolean := False) do new_snapshot_Name := to_Asset (Filename); snapshot_has_Alpha := with_Alpha; end Screenshot; or accept Stop do Done := True; end Stop; end select; exit when Done; if new_font_Name /= null_Asset then Self.Fonts.insert ((new_font_Name, new_font_Size), Font.texture.new_Font_texture (to_String (new_font_Name)).all'Access); elsif new_snapshot_Name /= null_Asset then IO.Screenshot (Filename => to_String (new_snapshot_Name), with_Alpha => snapshot_has_Alpha); else Self.update_Impostors_and_draw_Visuals (all_Updates (1 .. Length)); Self.free_old_Models; Self.free_old_Impostors; Self.is_Busy := False; if Self.Swapper /= null and Self.swap_Required then Self.Swapper.all; end if; end if; end; end loop; Self.free_old_Models; Self.free_old_Impostors; -- Free any fonts. -- while not Self.Fonts.is_Empty loop declare use Font, Font.font_id_Maps_of_font; the_Cursor : Cursor := Self.Fonts.First; the_Font : Font.view := Element (the_Cursor); begin free (the_Font); Self.Fonts.delete (the_Cursor); end; end loop; exception when E : others => new_Line; put_Line ("Unhandled exception in openGL Renderer engine !"); put_Line (ada.Exceptions.Exception_Information (E)); end Engine; -------------- --- Operations -- procedure start_Engine (Self : in out Item) is begin Self.Engine.start (null); end start_Engine; procedure stop_Engine (Self : in out Item) is begin Self.Engine.stop; end stop_Engine; procedure render (Self : in out Item; to_Surface : in Surface.view := null) is pragma unreferenced (to_Surface); begin Self.Engine.render; end render; procedure add_Font (Self : in out Item; font_Id : in Font.font_Id) is begin Self.Engine.add_Font (font_Id); end add_Font; procedure Screenshot (Self : in out Item; Filename : in String; with_Alpha : in Boolean := False) is begin Self.Engine.Screenshot (Filename, with_Alpha); end Screenshot; function is_Busy (Self : in Item) return Boolean is begin return Self.is_Busy; end is_Busy; procedure update_Impostors (Self : in out Item; the_Updates : in impostor_Updates; camera_world_Transform : in Matrix_4x4; view_Transform : in Matrix_4x4; perspective_Transform : in Matrix_4x4) is use linear_Algebra_3D; light_Site : constant Vector_3 := [10_000.0, -10_000.0, 10_000.0]; the_Light : openGL.Light.item; begin Tasks.check; the_Light. Site_is (light_Site); the_Light.Color_is (Palette.White); for i in the_Updates'Range loop declare use Texture, Visual, GL.Binding; the_Update : impostor_Update renames the_Updates (i); the_Impostor : Impostor.view renames the_Update.Impostor; texture_Width : constant gl.glSizei := power_of_2_Ceiling (Natural (the_Update.current_Width_pixels )); texture_Height : constant gl.glSizei := power_of_2_Ceiling (Natural (the_Update.current_Height_pixels)); the_Model : constant openGL.Model.billboard.textured.view := openGL.Model.billboard.textured.view (the_Impostor.Visual.Model); begin the_Impostor.Visual.Scale_is (the_Impostor.Target.Scale); the_Impostor.Visual.is_Terrain (the_Impostor.Target.is_Terrain); the_Impostor.Visual.face_Count_is (the_Impostor.Target.face_Count); the_Impostor.Visual.apparent_Size_is (the_Impostor.Target.apparent_Size); -- Render the target after clearing openGL buffers. -- glClearColor (0.0, 0.0, 0.0, 0.0); glClear ( GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT); declare new_view_Transform : Matrix_4x4 := camera_world_Transform; begin set_Rotation (new_view_Transform, the_Update.current_Camera_look_at_Rotation); new_view_Transform := inverse_Transform (new_view_Transform); -- Render the target for subsequent copy to impostor texture. -- Self.draw (the_Visuals => [1 => the_Impostor.Target], camera_world_Transform => camera_world_Transform, view_Transform => new_view_Transform, perspective_Transform => perspective_Transform, clear_Frame => False, to_Surface => null); end; -- Get a new sized texture, if needed. -- if Natural (the_Update.current_Width_pixels) /= the_Model.Texture.Size.Width or else Natural (the_Update.current_Height_pixels) /= the_Model.Texture.Size.Height then free (Self.texture_Pool, the_Model.Texture); the_Model.Texture_is (new_Texture (From => Self.texture_Pool'Access, Size => (Natural (texture_Width), Natural (texture_Height)))); end if; -- Set texture coordinates. -- declare X_first : constant Real := the_Impostor.expand_X; Y_first : constant Real := the_Impostor.expand_Y; X_last : constant Real := Real (the_Update.current_Width_pixels) / Real (texture_Width) - X_First; Y_last : constant Real := Real (the_Update.current_Height_pixels) / Real (texture_Height) - Y_First; begin the_Model.Texture_Coords_are ([1 => (S => X_first, T => Y_first), 2 => (S => X_last, T => Y_first), 3 => (S => X_last, T => Y_last), 4 => (S => X_first, T => Y_last)]); end; the_Model.Texture.enable; GL.lean.glCopyTexSubImage2D (gl.GL_TEXTURE_2D, 0, the_Update.current_copy_x_Offset, the_Update.current_copy_y_Offset, the_Update.current_copy_X, the_Update.current_copy_Y, the_Update.current_copy_Width, the_Update.current_copy_Height); Errors.log; end; end loop; Errors.log; end update_Impostors; procedure draw (Self : in out Item; the_Visuals : in Visual.views; camera_world_Transform : in Matrix_4x4; view_Transform : in Matrix_4x4; perspective_Transform : in Matrix_4x4; clear_Frame : in Boolean; to_Surface : in Surface.view := null) is pragma unreferenced (to_Surface); use linear_Algebra_3D; opaque_Count : math.Index := 0; lucid_Count : math.Index := 0; view_and_perspective_Transform : constant Matrix_4x4 := view_Transform * perspective_Transform; function get_on_Lights return openGL.Light.items is all_Lights : constant openGL.Light.items := Self.Lights.fetch; lit_Lights : openGL.Light.items (all_Lights'Range); Count : Natural := 0; begin for i in all_Lights'Range loop if all_Lights (i).is_On then Count := Count + 1; lit_Lights (Count) := all_Lights (i); end if; end loop; return lit_Lights (1 .. Count); end get_on_Lights; Lights : constant openGL.Light.items := get_on_Lights; begin Tasks.check; if clear_Frame then Self.clear_Frame; end if; --------------------- --- Draw the visuals. -- -- Collect opaque geometry (for state sorting) and collect lucid geometry (for depth sorting). -- for Each in the_Visuals'Range loop declare use type Model.view, Model.access_Geometry_views; the_Visual : Visual.view renames the_Visuals (Each); begin if the_Visual.Model.needs_Rebuild or ( the_Visual.Model.opaque_Geometries = null and the_Visual.Model. lucid_Geometries = null) then the_Visual.Model.create_GL_Geometries (Self.Textures'Access, Self.Fonts); elsif the_Visual.Model.is_Modified then the_Visual.Model.modify; end if; declare opaque_Geometries : Model.access_Geometry_views renames the_Visual.Model.opaque_Geometries; lucid_Geometries : Model.access_Geometry_views renames the_Visual.Model. lucid_Geometries; begin the_Visual.mvp_Transform_is (the_Visual.Transform * view_and_perspective_Transform); if opaque_Geometries /= null then for i in opaque_Geometries'Range loop opaque_Count := opaque_Count + 1; Self.all_opaque_Couples (opaque_Count) := (visual => the_Visual, Geometry => opaque_Geometries (i)); end loop; end if; if lucid_Geometries /= null then for i in lucid_Geometries'Range loop lucid_Count := lucid_Count + 1; Self.all_lucid_Couples (lucid_Count) := (visual => the_Visual, Geometry => lucid_Geometries (i)); end loop; end if; end; end; end loop; Errors.log; -- State sort opaque geometries and render them. -- declare use GL.Binding; procedure Heap_swap (Left, Right : in Natural) is Pad : constant visual_geometry_Couple := Self.all_opaque_Couples (Left); begin Self.all_opaque_Couples (Left) := Self.all_opaque_Couples (Right); Self.all_opaque_Couples (Right) := Pad; end Heap_swap; function Heap_less_than (Left, Right : in Natural) return Boolean is use System; L_Geometry : openGL.Geometry.view renames Self.all_opaque_Couples (Left) .Geometry; R_Geometry : openGL.Geometry.view renames Self.all_opaque_Couples (Right).Geometry; begin if L_Geometry.Program.gl_Program = R_Geometry.Program.gl_Program then return L_Geometry.all'Address < R_Geometry.all'Address; end if; return L_Geometry.Program.gl_Program < R_Geometry.Program.gl_Program; end Heap_less_than; the_Couple : visual_geometry_Couple; current_Program : openGL.Program.view; begin if opaque_Count > 1 then gnat.heap_Sort.sort (opaque_Count, Heap_swap 'unrestricted_Access, Heap_less_than'unrestricted_Access); end if; glDisable (GL_BLEND); glEnable (GL_DEPTH_TEST); glDepthMask (gl_TRUE); -- Make depth buffer read/write. for Each in 1 .. opaque_Count loop the_Couple := Self.all_opaque_Couples (Each); if the_Couple.Geometry.Program /= current_Program then current_Program := the_Couple.Geometry.Program; end if; current_Program.enable; -- TODO: Only need to do this when program changes ? current_Program.mvp_Transform_is (the_Couple.Visual.mvp_Transform); current_Program.model_Matrix_is (the_Couple.Visual.Transform); current_Program.camera_Site_is (get_Translation (camera_world_Transform)); current_Program.Lights_are (Lights); current_Program.Scale_is (the_Couple.Visual.Scale); if the_Couple.Visual.program_Parameters /= null then the_Couple.Visual.program_Parameters.enable; end if; the_Couple.Geometry.render; end loop; end; Errors.log; -- Depth sort lucid geometries and render them. -- declare use GL.Binding; procedure Heap_swap (Left, Right : in Natural) is Pad : constant visual_geometry_Couple := Self.all_lucid_Couples (Left); begin Self.all_lucid_Couples (Left) := Self.all_lucid_Couples (Right); Self.all_lucid_Couples (Right) := Pad; end Heap_swap; function Heap_less_than (Left, Right : in Natural) return Boolean is begin return Self.all_lucid_Couples (Left) .Visual.Transform (4, 3) -- Depth_in_camera_space -- NB: In camera space, negative Z is < Self.all_lucid_Couples (Right).Visual.Transform (4, 3); -- forward, so use '<'. end Heap_less_than; the_Couple : visual_geometry_Couple; current_Program : openGL.Program.view; begin if lucid_Count > 1 then gnat.heap_Sort.sort (lucid_Count, Heap_swap 'unrestricted_Access, Heap_less_than'unrestricted_Access); end if; glDepthMask (gl_False); -- Make depth buffer read-only, for correct transparency. glEnable (GL_BLEND); gl.lean.glBlendEquation (gl.lean.GL_FUNC_ADD); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); for Each in 1 .. lucid_Count loop the_Couple := Self.all_lucid_Couples (Each); current_Program := the_Couple.Geometry.Program; -- TODO: Only do this when program changes (as is done above with opaques) ? current_Program.enable; current_Program.mvp_Transform_is (the_Couple.Visual.mvp_Transform); current_Program.camera_Site_is (get_Translation (camera_world_Transform)); current_Program.model_Matrix_is (the_Couple.Visual.Transform); current_Program.Lights_are (Lights); current_Program.Scale_is (the_Couple.Visual.Scale); if the_Couple.Visual.program_Parameters /= null then the_Couple.Visual.program_Parameters.enable; end if; the_Couple.Geometry.render; end loop; glDepthMask (gl_True); end; Errors.log; end draw; ----------------------------- -- safe_camera_Map_of_updates -- protected body safe_camera_Map_of_updates is procedure define is begin current_Map := Map_1'Unchecked_Access; end define; procedure destruct is use camera_Maps_of_updates; procedure deallocate is new ada.unchecked_Deallocation (updates_for_Camera, updates_for_Camera_view); the_Updates : updates_for_Camera_view; Cursor : camera_Maps_of_updates.Cursor := Map_1.First; begin while has_Element (Cursor) loop the_Updates := Element (Cursor); deallocate (the_Updates); next (Cursor); end loop; Cursor := Map_2.First; while has_Element (Cursor) loop the_Updates := Element (Cursor); deallocate (the_Updates); next (Cursor); end loop; current_Map := null; end destruct; procedure add (the_Updates : in impostor_Updates; the_Camera : in Camera_view) is the_camera_Updates : updates_for_Camera_view; our_Camera : constant Camera_view := the_Camera; begin begin the_camera_Updates := current_Map.Element (our_Camera); exception when constraint_Error => -- No element exists for this camera yet. the_camera_Updates := new updates_for_Camera; current_Map.insert (our_Camera, the_camera_Updates); end; declare First : constant Integer := the_camera_Updates.impostor_updates_Last + 1; Last : constant Integer := the_camera_Updates.impostor_updates_Last + the_Updates'Length; begin the_camera_Updates.Impostor_updates (First .. Last) := the_Updates; the_camera_Updates.impostor_updates_Last := Last; end; end add; procedure add (the_Visuals : in Visual.views; the_Camera : in Camera_view) is the_camera_Updates : updates_for_Camera_view; our_Camera : constant Camera_view := the_Camera; begin begin the_camera_Updates := current_Map.Element (our_Camera); exception when constraint_Error => -- No element exists for this camera yet. the_camera_Updates := new updates_for_Camera; current_Map.Insert (our_Camera, the_camera_Updates); end; declare First : constant Integer := the_camera_Updates.visuals_Last + 1; Last : constant Integer := the_camera_Updates.visuals_Last + the_Visuals'Length; begin the_camera_Updates.Visuals (First .. Last) := the_Visuals; the_camera_Updates.visuals_Last := Last; end; end add; procedure fetch_all_Updates (the_Updates : out camera_updates_Couples; Length : out Natural) is use camera_Maps_of_updates; the_Couples : camera_updates_Couples (1 .. Integer (current_Map.Length)); Cursor : camera_Maps_of_updates.Cursor := current_Map.First; begin for i in the_Couples'Range loop the_Couples (i).Camera := Key (Cursor); the_Couples (i).Updates := Element (Cursor); next (Cursor); end loop; if current_Map = Map_1'unrestricted_Access then current_Map := Map_2'unchecked_Access; else current_Map := Map_1'unchecked_Access; end if; the_Updates (1 .. the_Couples'Length) := the_Couples; Length := the_Couples'Length; end fetch_all_Updates; end safe_camera_Map_of_updates; -------------- -- safe_Models -- protected body safe_Models is procedure add (the_Model : in Model.view) is begin my_Count := my_Count + 1; my_Models (my_Count) := the_Model; end add; procedure fetch (the_Models : out graphics_Models; Count : out Natural) is begin the_Models (1 .. my_Count) := my_Models (1 .. my_Count); Count := my_Count; my_Count := 0; end fetch; end safe_Models; procedure free (Self : in out Item; the_Model : in Model.view) is begin Self.obsolete_Models.add (the_Model); end free; ----------------- -- safe_Impostors -- protected body safe_Impostors is procedure add (the_Impostor : in Impostor.view) is begin the_Count := the_Count + 1; the_Impostors (the_Count) := the_Impostor; end add; procedure fetch (Impostors : out Impostor_Set; Count : out Natural) is begin Impostors (1 .. the_Count) := the_Impostors (1 .. the_Count); Count := the_Count; the_Count := 0; end fetch; end safe_Impostors; procedure free (Self : in out Item; the_Impostor : in Impostor.view) is begin Self.obsolete_Impostors.add (the_Impostor); end free; --------- -- Lights -- function Hash (Id : in openGL.Light.Id_t) return ada.Containers.Hash_type is begin return ada.Containers.Hash_type (Id); end Hash; protected body safe_Lights is procedure add (Light : in openGL.Light.item) is begin the_Lights.insert (Light.Id, Light); end add; procedure set (Light : in openGL.Light.item) is begin the_Lights.replace (Light.Id, Light); end set; procedure rid (Light : in openGL.Light.item) is begin the_Lights.delete (Light.Id); end rid; function get (Id : in openGL.Light.Id_t) return openGL.Light.item is begin return the_Lights.Element (Id); end get; function fetch return openGL.Light.items is all_Lights : openGL.Light.items (1 .. Natural (the_Lights.Length)); i : Natural := 0; begin for Each of the_Lights loop i := i + 1; all_Lights (i) := Each; end loop; return all_Lights; end fetch; end safe_Lights; function new_Light (Self : in out Item) return openGL.Light.item is the_Light : openGL.Light.item; begin Self.prior_Light_Id := Self.prior_Light_Id + 1; the_Light.Id_is (Self.prior_Light_Id); Self.Lights.add (the_Light); return the_Light; end new_Light; procedure set (Self : in out Item; the_Light : in openGL.Light.item) is begin Self.Lights.set (the_Light); end set; procedure rid (Self : in out Item; the_Light : in openGL.Light.item) is begin Self.Lights.rid (the_Light); end rid; function Light (Self : in out Item; Id : in openGL.light.Id_t) return openGL.Light.item is begin return Self.Lights.get (Id); end Light; function fetch (Self : in out Item) return openGL.Light.items is begin return Self.Lights.fetch; end fetch; end openGL.Renderer.lean;
pdaxrom/Kino2
Ada
3,749
ads
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Text_IO.Complex_IO -- -- -- -- S P E C -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer, 1996 -- Contact: http://www.familiepfeifer.de/Contact.aspx?Lang=en -- Version Control: -- $Revision: 1.9 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Ada.Numerics.Generic_Complex_Types; generic with package Complex_Types is new Ada.Numerics.Generic_Complex_Types (<>); package Terminal_Interface.Curses.Text_IO.Complex_IO is use Complex_Types; Default_Fore : Field := 2; Default_Aft : Field := Real'Digits - 1; Default_Exp : Field := 3; procedure Put (Win : in Window; Item : in Complex; Fore : in Field := Default_Fore; Aft : in Field := Default_Aft; Exp : in Field := Default_Exp); procedure Put (Item : in Complex; Fore : in Field := Default_Fore; Aft : in Field := Default_Aft; Exp : in Field := Default_Exp); private pragma Inline (Put); end Terminal_Interface.Curses.Text_IO.Complex_IO;
stcarrez/dynamo
Ada
5,119
adb
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A 4 G . A _ O S I N T -- -- -- -- B o d y -- -- -- -- Copyright (c) 1995-1999, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 59 Temple Place -- -- - Suite 330, Boston, MA 02111-1307, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc -- -- (http://www.gnat.com). -- -- -- ------------------------------------------------------------------------------ with Unchecked_Deallocation; package body A4G.A_Osint is ----------------------- -- Local subprograms -- ----------------------- procedure Free_String is new Unchecked_Deallocation (String, String_Access); procedure Free_List is new Unchecked_Deallocation (Argument_List, Argument_List_Access); ------------------------ -- Free_Argument_List -- ------------------------ procedure Free_Argument_List (List : in out Argument_List_Access) is begin if List = null then return; end if; for J in List'Range loop Free_String (List (J)); end loop; Free_List (List); end Free_Argument_List; ------------------------------ -- Get_Max_File_Name_Length -- ------------------------------ function Get_Max_File_Name_Length return Int is function Get_Maximum_File_Name_Length return Int; pragma Import (C, Get_Maximum_File_Name_Length, "__gnat_get_maximum_file_name_length"); -- This function does what we want, but it returns -1 when there -- is no restriction on the file name length -- -- The implementation has been "stolen" from the body of GNAT -- Osint.Initialize begin if Get_Maximum_File_Name_Length = -1 then return Int'Last; else return Get_Maximum_File_Name_Length; end if; end Get_Max_File_Name_Length; ------------------------------ -- Normalize_Directory_Name -- ------------------------------ function Normalize_Directory_Name (Directory : String) return String is begin -- For now this just insures that the string is terminated with -- the directory separator character. Add more later? if Directory (Directory'Last) = Directory_Separator then return Directory; elsif Directory'Length = 0 then -- now we do not need this, but it is no harm to keep it return '.' & Directory_Separator; else return Directory & Directory_Separator; end if; end Normalize_Directory_Name; end A4G.A_Osint;
SayCV/rtems-addon-packages
Ada
11,230
adb
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Forms.Field_Types -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998-2009,2011 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer, 1996 -- Version Control: -- $Revision$ -- $Date$ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Terminal_Interface.Curses.Aux; use Terminal_Interface.Curses.Aux; with Ada.Unchecked_Deallocation; with System.Address_To_Access_Conversions; -- | -- |===================================================================== -- | man page form_fieldtype.3x -- |===================================================================== -- | package body Terminal_Interface.Curses.Forms.Field_Types is use type System.Address; package Argument_Conversions is new System.Address_To_Access_Conversions (Argument); function Get_Fieldtype (F : Field) return C_Field_Type; pragma Import (C, Get_Fieldtype, "field_type"); function Get_Arg (F : Field) return System.Address; pragma Import (C, Get_Arg, "field_arg"); -- | -- |===================================================================== -- | man page form_field_validation.3x -- |===================================================================== -- | -- | -- | function Get_Type (Fld : Field) return Field_Type_Access is Low_Level : constant C_Field_Type := Get_Fieldtype (Fld); Arg : Argument_Access; begin if Low_Level = Null_Field_Type then return null; else if Low_Level = M_Builtin_Router or else Low_Level = M_Generic_Type or else Low_Level = M_Choice_Router or else Low_Level = M_Generic_Choice then Arg := Argument_Access (Argument_Conversions.To_Pointer (Get_Arg (Fld))); if Arg = null then raise Form_Exception; else return Arg.all.Typ; end if; else raise Form_Exception; end if; end if; end Get_Type; function Copy_Arg (Usr : System.Address) return System.Address is begin return Usr; end Copy_Arg; procedure Free_Arg (Usr : System.Address) is procedure Free_Type is new Ada.Unchecked_Deallocation (Field_Type'Class, Field_Type_Access); procedure Freeargs is new Ada.Unchecked_Deallocation (Argument, Argument_Access); To_Be_Free : Argument_Access := Argument_Access (Argument_Conversions.To_Pointer (Usr)); Low_Level : C_Field_Type; begin if To_Be_Free /= null then if To_Be_Free.all.Usr /= System.Null_Address then Low_Level := To_Be_Free.all.Cft; if Low_Level.all.Freearg /= null then Low_Level.all.Freearg (To_Be_Free.all.Usr); end if; end if; if To_Be_Free.all.Typ /= null then Free_Type (To_Be_Free.all.Typ); end if; Freeargs (To_Be_Free); end if; end Free_Arg; procedure Wrap_Builtin (Fld : Field; Typ : Field_Type'Class; Cft : C_Field_Type := C_Builtin_Router) is Usr_Arg : constant System.Address := Get_Arg (Fld); Low_Level : constant C_Field_Type := Get_Fieldtype (Fld); Arg : Argument_Access; Res : Eti_Error; function Set_Fld_Type (F : Field := Fld; Cf : C_Field_Type := Cft; Arg1 : Argument_Access) return C_Int; pragma Import (C, Set_Fld_Type, "set_field_type_user"); begin pragma Assert (Low_Level /= Null_Field_Type); if Cft /= C_Builtin_Router and then Cft /= C_Choice_Router then raise Form_Exception; else Arg := new Argument'(Usr => System.Null_Address, Typ => new Field_Type'Class'(Typ), Cft => Get_Fieldtype (Fld)); if Usr_Arg /= System.Null_Address then if Low_Level.all.Copyarg /= null then Arg.all.Usr := Low_Level.all.Copyarg (Usr_Arg); else Arg.all.Usr := Usr_Arg; end if; end if; Res := Set_Fld_Type (Arg1 => Arg); if Res /= E_Ok then Eti_Exception (Res); end if; end if; end Wrap_Builtin; function Field_Check_Router (Fld : Field; Usr : System.Address) return Curses_Bool is Arg : constant Argument_Access := Argument_Access (Argument_Conversions.To_Pointer (Usr)); begin pragma Assert (Arg /= null and then Arg.all.Cft /= Null_Field_Type and then Arg.all.Typ /= null); if Arg.all.Cft.all.Fcheck /= null then return Arg.all.Cft.all.Fcheck (Fld, Arg.all.Usr); else return 1; end if; end Field_Check_Router; function Char_Check_Router (Ch : C_Int; Usr : System.Address) return Curses_Bool is Arg : constant Argument_Access := Argument_Access (Argument_Conversions.To_Pointer (Usr)); begin pragma Assert (Arg /= null and then Arg.all.Cft /= Null_Field_Type and then Arg.all.Typ /= null); if Arg.all.Cft.all.Ccheck /= null then return Arg.all.Cft.all.Ccheck (Ch, Arg.all.Usr); else return 1; end if; end Char_Check_Router; function Next_Router (Fld : Field; Usr : System.Address) return Curses_Bool is Arg : constant Argument_Access := Argument_Access (Argument_Conversions.To_Pointer (Usr)); begin pragma Assert (Arg /= null and then Arg.all.Cft /= Null_Field_Type and then Arg.all.Typ /= null); if Arg.all.Cft.all.Next /= null then return Arg.all.Cft.all.Next (Fld, Arg.all.Usr); else return 1; end if; end Next_Router; function Prev_Router (Fld : Field; Usr : System.Address) return Curses_Bool is Arg : constant Argument_Access := Argument_Access (Argument_Conversions.To_Pointer (Usr)); begin pragma Assert (Arg /= null and then Arg.all.Cft /= Null_Field_Type and then Arg.all.Typ /= null); if Arg.all.Cft.all.Prev /= null then return Arg.all.Cft.all.Prev (Fld, Arg.all.Usr); else return 1; end if; end Prev_Router; -- ----------------------------------------------------------------------- -- function C_Builtin_Router return C_Field_Type is Res : Eti_Error; T : C_Field_Type; begin if M_Builtin_Router = Null_Field_Type then T := New_Fieldtype (Field_Check_Router'Access, Char_Check_Router'Access); if T = Null_Field_Type then raise Form_Exception; else Res := Set_Fieldtype_Arg (T, Make_Arg'Access, Copy_Arg'Access, Free_Arg'Access); if Res /= E_Ok then Eti_Exception (Res); end if; end if; M_Builtin_Router := T; end if; pragma Assert (M_Builtin_Router /= Null_Field_Type); return M_Builtin_Router; end C_Builtin_Router; -- ----------------------------------------------------------------------- -- function C_Choice_Router return C_Field_Type is Res : Eti_Error; T : C_Field_Type; begin if M_Choice_Router = Null_Field_Type then T := New_Fieldtype (Field_Check_Router'Access, Char_Check_Router'Access); if T = Null_Field_Type then raise Form_Exception; else Res := Set_Fieldtype_Arg (T, Make_Arg'Access, Copy_Arg'Access, Free_Arg'Access); if Res /= E_Ok then Eti_Exception (Res); end if; Res := Set_Fieldtype_Choice (T, Next_Router'Access, Prev_Router'Access); if Res /= E_Ok then Eti_Exception (Res); end if; end if; M_Choice_Router := T; end if; pragma Assert (M_Choice_Router /= Null_Field_Type); return M_Choice_Router; end C_Choice_Router; end Terminal_Interface.Curses.Forms.Field_Types;
johnperry-math/hac
Ada
443
ads
with HAC_Sys.PCode.Interpreter.In_Defs; package HAC_Sys.PCode.Interpreter.Composite_Data is use In_Defs; ----------------------- -- VM Instructions -- ----------------------- -- Execute instruction stored as Opcode in ND.IR.F. -- ND.IR.F is in the Composite_Data_Opcode subtype range. procedure Do_Composite_Data_Operation (CD : Compiler_Data; ND : in out Interpreter_Data); end HAC_Sys.PCode.Interpreter.Composite_Data;
AdaCore/training_material
Ada
4,106
ads
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with Interfaces.C.Extensions; package umingw_h is USE_u_u_UUIDOF : constant := 0; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:79 WINVER : constant := 16#0502#; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:225 -- unsupported macro: UNALIGNED __unaligned --* -- * This file has no copyright assigned and is placed in the Public Domain. -- * This file is part of the mingw-w64 runtime package. -- * No warranty is given; refer to the file DISCLAIMER.PD within this package. -- -- Include _cygwin.h if we're building a Cygwin application. -- Target specific macro replacement for type "long". In the Windows API, -- the type long is always 32 bit, even if the target is 64 bit (LLP64). -- On 64 bit Cygwin, the type long is 64 bit (LP64). So, to get the right -- sized definitions and declarations, all usage of type long in the Windows -- headers have to be replaced by the below defined macro __LONG32. -- C/C++ specific language defines. -- Note the extern. This is needed to work around GCC's --limitations in handling dllimport attribute. -- Attribute `nonnull' was valid as of gcc 3.3. We don't use GCC's -- variadiac macro facility, because variadic macros cause syntax -- errors with --traditional-cpp. -- High byte is the major version, low byte is the minor. -- other headers depend on this include -- We have to define _DLL for gcc based mingw version. This define is set -- by VC, when DLL-based runtime is used. So, gcc based runtime just have -- DLL-base runtime, therefore this define has to be set. -- As our headers are possibly used by windows compiler having a static -- C-runtime, we make this definition gnu compiler specific here. subtype ssize_t is Long_Long_Integer; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:387 subtype intptr_t is Long_Long_Integer; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:399 subtype uintptr_t is Extensions.unsigned_long_long; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:412 subtype wint_t is unsigned_short; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:443 subtype wctype_t is unsigned_short; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:444 subtype errno_t is int; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:463 subtype uu_time32_t is long; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:468 subtype uu_time64_t is Long_Long_Integer; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:473 subtype time_t is uu_time64_t; -- d:\install\gpl2018\x86_64-pc-mingw32\include\_mingw.h:481 -- MSVC defines _NATIVE_NULLPTR_SUPPORTED when nullptr is supported. We emulate it here for GCC. -- We are activating __USE_MINGW_ANSI_STDIO for various define indicators. -- Note that we enable it also for _GNU_SOURCE in C++, but not for C case. -- Enable __USE_MINGW_ANSI_STDIO if _POSIX defined -- * and If user did _not_ specify it explicitly... -- _dowildcard is an int that controls the globbing of the command line. -- * The MinGW32 (mingw.org) runtime calls it _CRT_glob, so we are adding -- * a compatibility definition here: you can use either of _CRT_glob or -- * _dowildcard . -- * If _dowildcard is non-zero, the command line will be globbed: *.* -- * will be expanded to be all files in the startup directory. -- * In the mingw-w64 library a _dowildcard variable is defined as being -- * 0, therefore command line globbing is DISABLED by default. To turn it -- * on and to leave wildcard command line processing MS's globbing code, -- * include a line in one of your source modules defining _dowildcard and -- * setting it to -1, like so: -- * int _dowildcard = -1; -- -- Macros for __uuidof template-based emulation -- skipped func __debugbreak -- mingw-w64 specific functions: -- skipped func __mingw_get_crt_info end umingw_h;
reznikmm/gela
Ada
3,490
ads
------------------------------------------------------------------------------ -- G E L A G R A M M A R S -- -- Library for dealing with tests for for Gela project, -- -- a portable Ada compiler -- -- http://gela.ada-ru.org/ -- -- - - - - - - - - - - - - - - - -- -- Read copyright and license in gela.ads file -- ------------------------------------------------------------------------------ with League.Calendars; with League.String_Vectors; with League.Strings; with Gela.Test_Cases.Execute; package Gela.Test_Cases.Append is function "+" (Left, Right : access Test_Cases.Test_Case'Class) return Gela.Test_Cases.Test_Case_Access; function "+" (Left : access Test_Cases.Test_Case'Class; Right : access Gela.Test_Cases.Execute.Test_Case'Class) return Gela.Test_Cases.Execute.Test_Case_Access; private type Test_Cases_Array is array (1 .. 2) of Test_Case_Access; type Test_Case is new Test_Cases.Test_Case with record List : Test_Cases_Array; Last : Natural := 0; Duration : League.Calendars.Time; end record; procedure Run (Self : in out Test_Case); function Status (Self : Test_Case) return Status_Kind; function Duration (Self : Test_Case) return League.Calendars.Time; function Name (Self : Test_Case) return League.Strings.Universal_String; function Fixture (Self : Test_Case) return League.Strings.Universal_String; function File (Self : Test_Case) return League.Strings.Universal_String; function Output (Self : Test_Case) return League.Strings.Universal_String; function Traceback (Self : Test_Case) return League.Strings.Universal_String; type Run_Test_Case is new Test_Cases.Execute.Test_Case with record On_Left : Boolean; Left : Test_Case_Access; Right : Gela.Test_Cases.Execute.Test_Case_Access; Duration : League.Calendars.Time; end record; procedure Run (Self : in out Run_Test_Case); function Status (Self : Run_Test_Case) return Status_Kind; function Duration (Self : Run_Test_Case) return League.Calendars.Time; function Name (Self : Run_Test_Case) return League.Strings.Universal_String; function Fixture (Self : Run_Test_Case) return League.Strings.Universal_String; function File (Self : Run_Test_Case) return League.Strings.Universal_String; function Output (Self : Run_Test_Case) return League.Strings.Universal_String; function Traceback (Self : Run_Test_Case) return League.Strings.Universal_String; function Command (Self : Run_Test_Case) return League.Strings.Universal_String; function Arguments (Self : Run_Test_Case) return League.String_Vectors.Universal_String_Vector; procedure Set_Command (Self : in out Run_Test_Case; Command : League.Strings.Universal_String; Arguments : League.String_Vectors.Universal_String_Vector); procedure Set_Name (Self : in out Run_Test_Case; Value : League.Strings.Universal_String); function Build (Self : Run_Test_Case) return League.Strings.Universal_String; function Path (Self : Run_Test_Case) return League.Strings.Universal_String; end Gela.Test_Cases.Append;
reznikmm/matreshka
Ada
4,097
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 ODF.DOM.Draw_Measure_Vertical_Align_Attributes; package Matreshka.ODF_Draw.Measure_Vertical_Align_Attributes is type Draw_Measure_Vertical_Align_Attribute_Node is new Matreshka.ODF_Draw.Abstract_Draw_Attribute_Node and ODF.DOM.Draw_Measure_Vertical_Align_Attributes.ODF_Draw_Measure_Vertical_Align_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Draw_Measure_Vertical_Align_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Draw_Measure_Vertical_Align_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Draw.Measure_Vertical_Align_Attributes;
onox/orka
Ada
5,902
adb
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2018 onox <[email protected]> -- -- 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.Real_Time; with Ada.Text_IO; with GL.Barriers; with GL.Compute; with GL.Types.Compute; with Orka.Contexts.EGL; with Orka.Debug; with Orka.Rendering.Buffers; with Orka.Rendering.Programs.Modules; with Orka.Rendering.Programs.Uniforms; with Orka.Resources.Locations.Directories; with Orka.Types; procedure Orka_10_Compute is Context : constant Orka.Contexts.Context'Class := Orka.Contexts.EGL.Create_Context (Version => (4, 2), Flags => (Debug => True, others => False)); ---------------------------------------------------------------------- use Ada.Text_IO; use type GL.Types.Int; use GL.Types; Numbers : constant Orka.Integer_32_Array := (10, 1, 8, -1, 0, -2, 3, 5, -2, -3, 2, 7, 0, 11, 0, 2); begin Orka.Debug.Set_Log_Messages (Enable => True); declare use Orka.Rendering.Buffers; use Orka.Rendering.Programs; use Orka.Resources; Location_Shaders : constant Locations.Location_Ptr := Locations.Directories.Create_Location ("data/shaders"); Program_1 : Program := Create_Program (Modules.Create_Module (Location_Shaders, CS => "test-10-module-1.comp")); Uniform_1 : constant Uniforms.Uniform := Program_1.Uniform ("maxNumbers"); Max_Work_Groups, Local_Size : Size; begin Program_1.Use_Program; -- Print some limits about compute shaders Put_Line ("Maximum shared size:" & Size'Image (GL.Compute.Max_Compute_Shared_Memory_Size)); Put_Line ("Maximum invocations:" & Size'Image (GL.Compute.Max_Compute_Work_Group_Invocations (GL.Compute.Fixed))); declare R : GL.Types.Compute.Dimension_Size_Array; use all type Orka.Index_4D; begin R := GL.Compute.Max_Compute_Work_Group_Count; Put_Line ("Maximum count:" & R (X)'Image & R (Y)'Image & R (Z)'Image); Max_Work_Groups := R (X); R := GL.Compute.Max_Compute_Work_Group_Size (GL.Compute.Fixed); Put_Line ("Maximum size: " & R (X)'Image & R (Y)'Image & R (Z)'Image); R := Program_1.Compute_Work_Group_Size; Put_Line ("Local size: " & R (X)'Image & R (Y)'Image & R (Z)'Image); Local_Size := R (X); end; declare use all type Orka.Types.Element_Type; use type Ada.Real_Time.Time; Factor : constant Size := (Max_Work_Groups * Local_Size) / Numbers'Length; Buffer_1 : constant Buffer := Create_Buffer (Flags => (Dynamic_Storage => True, others => False), Kind => Int_Type, Length => Numbers'Length * Natural (Factor)); A, B : Ada.Real_Time.Time; procedure Memory_Barrier is begin GL.Barriers.Memory_Barrier ((Shader_Storage | Buffer_Update => True, others => False)); end Memory_Barrier; begin Put_Line ("Factor:" & Factor'Image); -- Upload numbers to SSBO for Index in 0 .. Factor - 1 loop Buffer_1.Set_Data (Data => Numbers, Offset => Numbers'Length * Natural (Index)); end loop; Buffer_1.Bind (Shader_Storage, 0); A := Ada.Real_Time.Clock; declare Count : constant Size := Size (Buffer_1.Length); Ceiling : Size := Count + (Count rem Local_Size); Groups : Size := Ceiling / Local_Size; begin Put_Line ("Numbers:" & Count'Image); Put_Line ("Groups: " & Groups'Image); pragma Assert (Groups <= Max_Work_Groups); -- The uniform is used to set how many numbers need to be -- summed. If a work group has more threads than there are -- numbers to be summed (happens in the last iteration), -- then these threads will use the number 0 in the shader. Uniform_1.Set_UInt (UInt (Count)); while Groups > 0 loop -- Add an SSBO barrier for the next iteration -- and then dispatch the compute shader Memory_Barrier; GL.Compute.Dispatch_Compute (X => UInt (Groups)); Uniform_1.Set_UInt (UInt (Groups)); Ceiling := Groups + (Groups rem Local_Size); Groups := Ceiling / Local_Size; end loop; -- Perform last iteration. Work groups in X dimension needs -- to be at least one. Memory_Barrier; GL.Compute.Dispatch_Compute (X => UInt (Size'Max (1, Groups))); end; Memory_Barrier; declare Output : Orka.Integer_32_Array (1 .. 2) := (others => 0); begin Buffer_1.Get_Data (Output); Put_Line ("Expected Sum:" & Size'Image (Factor * 41)); Put_Line ("Computed sum:" & Output (Output'First)'Image); -- Print the number of shader invocations that execute in -- lockstep. This requires the extension ARB_shader_ballot -- in the shader. Put_Line ("Sub-group size:" & Output (Output'Last)'Image); end; B := Ada.Real_Time.Clock; Put_Line (Duration'Image (1e3 * Ada.Real_Time.To_Duration (B - A)) & " ms"); end; end; end Orka_10_Compute;
io7m/coreland-levenshtein
Ada
693
adb
with ada.command_line; with ada.strings.fixed; with ada.strings; with ada.text_io; with levenshtein; procedure levenshtein_comp is package io renames ada.text_io; package str renames ada.strings; package str_fixed renames ada.strings.fixed; package cmdline renames ada.command_line; begin if cmdline.argument_count < 2 then io.put_line (io.current_error, "levenshtein-comp: usage: str0 str1"); cmdline.set_exit_status (111); return; end if; declare distance : constant natural := levenshtein.distance (cmdline.argument (1), cmdline.argument (2)); begin io.put_line (str_fixed.trim (natural'image (distance), str.left)); end; end levenshtein_comp;
reznikmm/matreshka
Ada
4,404
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Web Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2016-2017, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ generic type Abstract_Object is abstract new Core.Connectables.Connectable_Object with private; with procedure Subprogram (Self : in out Abstract_Object; Parameter_1 : Parameter_1_Type; Parameter_2 : Parameter_2_Type) is abstract; package Core.Connectables.Slots_0.Slots_1.Slots_2.Generic_Slots is pragma Preelaborate; function To_Slot (Self : in out Abstract_Object'Class) return Slots_2.Slot'Class; private type Slot (Object : not null access Abstract_Object'Class) is new Slots_2.Slot with null record; overriding function Create_Slot_End (Self : Slot) return not null Slot_End_Access; type Slot_End (Object : not null access Abstract_Object'Class) is new Slot_End_2 with null record; overriding procedure Invoke (Self : in out Slot_End; Parameter_1 : Parameter_1_Type; Parameter_2 : Parameter_2_Type); overriding function Owner (Self : Slot_End) return not null Connectables.Object_Access; end Core.Connectables.Slots_0.Slots_1.Slots_2.Generic_Slots;
AdaCore/libadalang
Ada
97
ads
package Wat is type A is tagged null record; procedure Prim (Self : A) is null; end Wat;
cborao/Ada-P4-chat
Ada
450
ads
--PRÁCTICA 4: CÉSAR BORAO MORATINOS (Handlers.ads) with Ada.Calendar; with Lower_Layer_UDP; package Handlers is package LLU renames Lower_Layer_UDP; procedure Client_Handler (From: in LLU.End_Point_Type; To: in LLU.End_Point_Type; P_Buffer: access LLU.Buffer_Type); procedure Server_Handler (From: in LLU.End_Point_Type; To: in LLU.End_Point_Type; P_Buffer: access LLU.Buffer_Type); end Handlers;
annexi-strayline/AURA
Ada
8,407
adb
------------------------------------------------------------------------------ -- -- -- Ada User Repository Annex (AURA) -- -- ANNEXI-STRAYLINE Reference Implementation -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2020, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * Richard Wai (ANNEXI-STRAYLINE) -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- -- -- * Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with Ada.Strings; with Ada.Strings.Unbounded; with Ada.Containers.Vectors; with Ada.Exceptions; with Ada.Environment_Variables; with Ada.Directories; package body Child_Processes.Path_Searching is procedure Not_Found_Error (Program: String) with Inline, No_Return is begin raise Not_In_Path with "Program """ & Program & """ was not found in PATH."; end; ----------------- -- Search_Path -- ----------------- function Search_Path (Program: String) return String is use Ada.Strings.Unbounded; package ENV renames Ada.Environment_Variables; package Path_Vectors is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Unbounded_String); Path_List: Path_Vectors.Vector; begin -- Parse the PATH environment varaible - a colon-separated list declare use Ada.Strings; PATH: Unbounded_String; First: Positive := 1; Last : Natural := 1; begin if not ENV.Exists ("PATH") then raise Not_In_Path with "PATH environment variable not set."; end if; Set_Unbounded_String (Target => PATH, Source => ENV.Value ("PATH")); while First <= Length (PATH) loop Last := Index (Source => PATH, Pattern => ":", From => First); if Last < First then Last := Length (PATH); elsif Last = First then raise Not_In_Path with "PATH format error."; else Last := Last - 1; end if; Path_List.Append (Unbounded_Slice (Source => PATH, Low => First, High => Last)); First := Last + 2; end loop; end; declare use Ada.Directories; Ordinary_Files: constant Filter_Type := (Ordinary_File => True, others => False); Search: Search_Type; Match : Directory_Entry_Type; begin -- Search through the paths in order for Path of Path_List loop -- We don't want an exception raised if the indiciated path of -- the PATH environment variable is not a valid path, we just -- want to skip it if Exists (To_String (Path)) then Start_Search (Search => Search, Directory => To_String (Path), Pattern => Program, Filter => Ordinary_Files); if More_Entries (Search) then -- We have a match Get_Next_Entry (Search => Search, Directory_Entry => Match); return Full_Name (Match); end if; -- Otherwise try the next directory end if; end loop; end; -- If we get here, we didn't find it Not_Found_Error (Program); exception when Not_In_Path => raise; when e: others => raise Not_In_Path with "Unable to execute path search due to an exception: " & Ada.Exceptions.Exception_Information (e); end Search_Path; -- -- Elaboration_Path_Search -- ---------------- -- Initialize -- ---------------- function Initialize (Program: aliased String) return Elaboration_Path_Search is use Image_Path_Strings; begin return Search: Elaboration_Path_Search (Program'Access) do Search.Result := To_Bounded_String (Search_Path (Program)); exception when Ada.Directories.Name_Error => Search.Result := Null_Bounded_String; when Ada.Strings.Length_Error => raise Ada.Strings.Length_Error with "Full path for program""" & Program & """ is too long. Child_Processes.Path_Searching must " & "be modified."; end return; end Initialize; ----------- -- Found -- ----------- function Found (Search: Elaboration_Path_Search) return Boolean is use Image_Path_Strings; begin return Length (Search.Result) > 0; end; ---------------- -- Image_Path -- ---------------- function Image_Path (Search: Elaboration_Path_Search) return String is use Image_Path_Strings; begin if not Found (Search) then Not_Found_Error (Search.Program.all); else return To_String (Search.Result); end if; end Image_Path; end Child_Processes.Path_Searching;
seanvictory/mlh-localhost-adacore
Ada
567
adb
package body Stack with SPARK_Mode => On is ----------- -- Clear -- ----------- procedure Clear is begin Last := Tab'First; end Clear; ---------- -- Push -- ---------- procedure Push (V : Character) is begin Tab (Last) := V; end Push; --------- -- Pop -- --------- procedure Pop (V : out Character) is begin Last := Last - 1; V := Tab (Last); end Pop; --------- -- Top -- --------- function Top return Character is begin return Tab (1); end Top; end Stack;
dan76/Amass
Ada
1,674
ads
-- Copyright © by Jeff Foley 2017-2023. All rights reserved. -- Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. -- SPDX-License-Identifier: Apache-2.0 local json = require("json") name = "Crtsh" type = "cert" function start() set_rate_limit(3) end function vertical(ctx, domain) local url = "https://crt.sh/?q=" .. domain .. "&output=json" local resp, err = request(ctx, {['url']=url}) if (err ~= nil and err ~= "") then log(ctx, "vertical request to service failed: " .. err) return elseif (resp.status_code < 200 or resp.status_code >= 400) then log(ctx, "vertical request to service returned with status code: " .. resp.status) return end local body = "{\"subdomains\":" .. resp.body .. "}" local d = json.decode(body) if (d == nil) then log(ctx, "failed to decode the JSON response") return elseif (d.subdomains == nil or #(d.subdomains) == 0) then return end for _, r in pairs(d.subdomains) do if (r['common_name'] ~= nil and r['common_name'] ~= "") then new_name(ctx, r['common_name']) end for _, n in pairs(split(r['name_value'], "\\n")) do if (n ~= nil and n ~= "") then new_name(ctx, n) end end end end function split(str, delim) local pattern = "[^%" .. delim .. "]+" local matches = find(str, pattern) if (matches == nil or #matches == 0) then return {str} end local result = {} for _, match in pairs(matches) do table.insert(result, match) end return result end
stcarrez/ada-asf
Ada
1,832
ads
----------------------------------------------------------------------- -- asf-events -- ASF Events -- Copyright (C) 2009, 2010, 2011, 2022 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- 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 ASF.Applications; with Util.Events; with Util.Beans.Basic; with Util.Beans.Objects; package ASF.Events.Modules is type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with private; -- Set a parameter on the message. procedure Set_Parameter (Message : in out Module_Event; Name : in String; Value : in String); -- Get the parameter with the given name. function Get_Parameter (Message : in Module_Event; Name : String) return String; -- Get the value that corresponds to the parameter with the given name. overriding function Get_Value (Message : in Module_Event; Name : in String) return Util.Beans.Objects.Object; private type Module_Event is new Util.Events.Event and Util.Beans.Basic.Readonly_Bean with record Props : ASF.Applications.Config; end record; end ASF.Events.Modules;
zhmu/ananas
Ada
3,726
adb
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- G N A T . B I N D _ E N V I R O N M E N T -- -- -- -- B o d y -- -- -- -- Copyright (C) 2015-2022, 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/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by AdaCore. -- -- -- ------------------------------------------------------------------------------ with System; package body GNAT.Bind_Environment is --------- -- Get -- --------- function Get (Key : String) return String is use type System.Address; Bind_Env_Addr : constant System.Address; pragma Import (C, Bind_Env_Addr, "__gl_bind_env_addr"); -- Variable provided by init.c/s-init.ads, and initialized by -- the binder generated file. Bind_Env : String (Positive); for Bind_Env'Address use Bind_Env_Addr; pragma Import (Ada, Bind_Env); -- Import Bind_Env string from binder file. Note that we import -- it here as a string with maximum boundaries. The "real" end -- of the string is indicated by a NUL byte. Index, KLen, VLen : Integer; begin if Bind_Env_Addr = System.Null_Address then return ""; end if; Index := Bind_Env'First; loop -- Index points to key length VLen := 0; KLen := Character'Pos (Bind_Env (Index)); exit when KLen = 0; Index := Index + KLen + 1; -- Index points to value length VLen := Character'Pos (Bind_Env (Index)); exit when Bind_Env (Index - KLen .. Index - 1) = Key; Index := Index + VLen + 1; end loop; return Bind_Env (Index + 1 .. Index + VLen); end Get; end GNAT.Bind_Environment;
reznikmm/matreshka
Ada
4,484
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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.DOM_Nodes; --with XML.DOM.Elements.Internals; with XML.DOM.Documents.Internals; package body ODF.DOM.Documents.Internals is ------------ -- Create -- ------------ function Create (Node : Matreshka.ODF_Documents.Document_Access) return ODF.DOM.Documents.ODF_Document is begin return (XML.DOM.Documents.Internals.Create (Matreshka.DOM_Nodes.Document_Access (Node)) with null record); end Create; -------------- -- Internal -- -------------- function Internal (Document : ODF.DOM.Documents.ODF_Document'Class) return Matreshka.ODF_Documents.Document_Access is begin return Matreshka.ODF_Documents.Document_Access (XML.DOM.Documents.Internals.Internal (Document)); end Internal; ---------- -- Wrap -- ---------- function Wrap (Node : Matreshka.ODF_Documents.Document_Access) return ODF.DOM.Documents.ODF_Document is begin return (XML.DOM.Documents.Internals.Wrap (Matreshka.DOM_Nodes.Document_Access (Node)) with null record); end Wrap; end ODF.DOM.Documents.Internals;
MinimSecure/unum-sdk
Ada
927
ads
-- Copyright 2010-2016 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. package Pck is Node_Low_Bound : constant := 0; Node_High_Bound : constant := 099_999_999; type Node_Id is range Node_Low_Bound .. Node_High_Bound; function Pn (N : Node_Id) return Node_Id; end Pck;
osannolik/ada-canopen
Ada
5,793
adb
with ACO.States; package body ACO.Protocols.Synchronization is function To_Ms_From_100us (T : Natural) return Natural is (T / 10); procedure Counter_Reset (This : in out SYNC) is begin This.Counter := Counter_Type'First; end Counter_Reset; procedure Counter_Increment (This : in out SYNC; Overflow_Value : in Sync_Counter) is begin if Natural (This.Counter) >= Overflow_Value then This.Counter_Reset; else This.Counter := Counter_Type'Succ (This.Counter); end if; end Counter_Increment; function Is_Counter_Expected (This : in out SYNC) return Boolean is (This.Od.Get_Sync_Counter_Overflow > 1); function Create_Sync (This : in out SYNC; Overflow_Value : in Sync_Counter) return ACO.Messages.Message is Data : constant ACO.Messages.Data_Array := (if Overflow_Value > 1 then (ACO.Messages.Msg_Data'First => This.Counter) else ACO.Messages.Empty_Data); begin return ACO.Messages.Create (CAN_Id => SYNC_CAN_Id, RTR => False, Data => Data); end Create_Sync; procedure Send_Sync (This : in out SYNC) is Overflow_Value : constant Sync_Counter := This.Od.Get_Sync_Counter_Overflow; begin This.Handler.Put (This.Create_Sync (Overflow_Value)); if Overflow_Value > 1 then This.Counter_Increment (Overflow_Value); end if; end Send_Sync; overriding procedure Signal (This : access Sync_Producer_Alarm; T_Now : in Ada.Real_Time.Time) is use type Ada.Real_Time.Time; use Alarms; SYNC_Ref : access SYNC renames This.SYNC_Ref; Period : constant Natural := To_Ms_From_100us (SYNC_Ref.Od.Get_Communication_Cycle_Period); begin if Period > 0 then SYNC_Ref.Timers.Set (Alarm_Access (This), T_Now + Ada.Real_Time.Milliseconds (Period)); SYNC_Ref.Send_Sync; end if; end Signal; procedure Sync_Producer_Start (This : in out SYNC) is use Ada.Real_Time; Period : constant Natural := To_Ms_From_100us (This.Od.Get_Communication_Cycle_Period); begin if Period > 0 then This.Timers.Set (Alarm => This.Producer_Alarm'Unchecked_Access, Signal_Time => This.Handler.Current_Time + Milliseconds (Period)); end if; end Sync_Producer_Start; procedure Sync_Producer_Stop (This : in out SYNC) is begin This.Timers.Cancel (This.Producer_Alarm'Unchecked_Access); end Sync_Producer_Stop; overriding procedure On_Event (This : in out Node_State_Change_Subscriber; Data : in ACO.Events.Event_Data) is use ACO.States; Active_In_State : constant array (State) of Boolean := (Stopped | Initializing | Unknown_State => False, Pre_Operational | Operational => True); begin if Data.State.Previous = Initializing and Data.State.Current = Pre_Operational then -- Bootup This.Sync_Ref.Counter_Reset; end if; if Active_In_State (Data.State.Current) and not Active_In_State (Data.State.Previous) then if Data.State.Previous = Stopped then This.Sync_Ref.Counter_Reset; end if; This.Sync_Ref.Sync_Producer_Start; elsif not Active_In_State (Data.State.Current) and Active_In_State (Data.State.Previous) then This.Sync_Ref.Sync_Producer_Stop; end if; end On_Event; overriding procedure On_Event (This : in out Entry_Update_Subscriber; Data : in ACO.Events.Event_Data) is pragma Unreferenced (Data); SYNC_Ref : access SYNC renames This.SYNC_Ref; begin if SYNC_Ref.Timers.Is_Pending (SYNC_Ref.Producer_Alarm'Unchecked_Access) then SYNC_Ref.Sync_Producer_Stop; SYNC_Ref.Counter_Reset; SYNC_Ref.Sync_Producer_Start; end if; end On_Event; overriding function Is_Valid (This : in out SYNC; Msg : in ACO.Messages.Message) return Boolean is use type ACO.Messages.Id_Type; pragma Unreferenced (This); begin return ACO.Messages.CAN_Id (Msg) = SYNC_CAN_Id; end Is_Valid; procedure Message_Received (This : in out SYNC; Msg : in ACO.Messages.Message) is begin if This.Is_Counter_Expected and Msg.Length /= 1 then return; end if; -- TODO: Trigger TPDO end Message_Received; procedure Periodic_Actions (This : in out SYNC; T_Now : in Ada.Real_Time.Time) is begin This.Timers.Process (T_Now); end Periodic_Actions; overriding procedure Initialize (This : in out SYNC) is begin Protocol (This).Initialize; This.Od.Events.Node_Events.Attach (This.Entry_Update'Unchecked_Access); This.Od.Events.Node_Events.Attach (This.State_Change'Unchecked_Access); end Initialize; overriding procedure Finalize (This : in out SYNC) is begin Protocol (This).Finalize; This.Od.Events.Node_Events.Detach (This.Entry_Update'Unchecked_Access); This.Od.Events.Node_Events.Detach (This.State_Change'Unchecked_Access); end Finalize; procedure SYNC_Log (This : in out SYNC; Level : in ACO.Log.Log_Level; Message : in String) is pragma Unreferenced (This); begin ACO.Log.Put_Line (Level, "(SYNC) " & Message); end SYNC_Log; end ACO.Protocols.Synchronization;
charlie5/lace
Ada
10,247
adb
with physics.Object, ada.unchecked_Deallocation; package body gel.hinge_Joint is use gel.Joint; procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3; pivot_Anchor : in Vector_3) is pivot_in_A : constant Vector_3 := (pivot_Anchor - Sprite_A.Site); pivot_in_B : constant Vector_3 := (pivot_Anchor - Sprite_B.Site); the_Axis : constant Vector_3 := pivot_Axis; begin Self.define (in_Space, Sprite_A, Sprite_B, the_Axis, pivot_in_A, pivot_in_B, low_Limit => to_Radians (-180.0), high_Limit => to_Radians ( 180.0), collide_Conected => False); end define; procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3) is Midpoint : constant Vector_3 := (Sprite_A.Site + Sprite_B.Site) / 2.0; begin Self.define (in_Space, Sprite_A, Sprite_B, pivot_Axis, pivot_anchor => Midpoint); end define; procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; Frame_A, Frame_B : in Matrix_4x4; low_Limit : in Real := to_Radians (-180.0); high_Limit : in Real := to_Radians ( 180.0); collide_Conected : in Boolean) is A_Frame : constant Matrix_4x4 := Frame_A; B_Frame : constant Matrix_4x4 := Frame_B; type Joint_cast is access all gel.Joint.item; sprite_A_Solid, sprite_B_Solid : std_physics.Object.view; begin if Sprite_A = null or Sprite_B = null then raise Error with "Sprite is null."; end if; sprite_A_Solid := std_physics.Object.view (Sprite_A.Solid); sprite_B_Solid := std_physics.Object.view (Sprite_B.Solid); joint.define (Joint_cast (Self), Sprite_A, Sprite_B); -- Define base class. Self.Physics := in_Space.new_hinge_Joint (sprite_A_Solid, sprite_B_Solid, A_Frame, B_Frame, low_Limit, high_Limit, collide_Conected); end define; procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A : access gel.Sprite.item'Class; Frame_A : in Matrix_4x4) is type Joint_cast is access all gel.Joint.item; A_Frame : constant Matrix_4x4 := Frame_A; sprite_A_Solid : std_physics.Object.view; begin joint.define (Joint_cast (Self), Sprite_A, null); -- Define base class. sprite_A_Solid := std_physics.Object.view (Sprite_A.Solid); Self.Physics := in_Space.new_hinge_Joint (sprite_A_Solid, A_Frame); end define; procedure define (Self : access Item; in_Space : in std_physics.Space.view; Sprite_A, Sprite_B : access gel.Sprite.item'Class; pivot_Axis : in Vector_3; Anchor_in_A, Anchor_in_B : in Vector_3; low_Limit, high_Limit : in Real; collide_Conected : in Boolean) is type Joint_cast is access all gel.Joint.item; sprite_A_Solid, sprite_B_Solid : std_physics.Object.view; begin if Sprite_A = null or Sprite_B = null then raise Error with "Attempt to join a null sprite."; end if; sprite_A_Solid := std_physics.Object.view (Sprite_A.Solid); sprite_B_Solid := std_physics.Object.view (Sprite_B.Solid); Joint.define (Joint_cast (Self), Sprite_A, Sprite_B); -- Define base class. Self.Physics := in_Space.new_hinge_Joint (sprite_A_Solid, sprite_B_Solid, Anchor_in_A, Anchor_in_B, pivot_Axis, low_Limit, high_Limit, collide_Conected); end define; overriding procedure destroy (Self : in out Item) is my_Physics : std_physics.Joint.view := std_physics.Joint.view (Self.Physics); procedure deallocate is new ada.unchecked_Deallocation (std_physics.Joint.item'Class, std_physics.Joint.view); begin my_Physics.destruct; deallocate (my_Physics); Self.Physics := null; end destroy; -------------- --- Attributes -- overriding function Degrees_of_freedom (Self : in Item) return joint.degree_of_Freedom is pragma unreferenced (Self); begin return 1; end Degrees_of_freedom; function Angle (Self : in Item'Class) return Real is begin raise Error with "TODO"; return 0.0; end Angle; overriding function Frame_A (Self : in Item) return Matrix_4x4 is begin return Self.Physics.Frame_A; end Frame_A; overriding function Frame_B (Self : in Item) return Matrix_4x4 is begin return Self.Physics.Frame_B; end Frame_B; overriding procedure Frame_A_is (Self : in out Item; Now : in Matrix_4x4) is begin Self.Physics.Frame_A_is (Now); end Frame_A_is; overriding procedure Frame_B_is (Self : in out Item; Now : in Matrix_4x4) is begin Self.Physics.Frame_B_is (Now); end Frame_B_is; overriding function Physics (Self : in Item) return joint.Physics_view is begin return Joint.Physics_view (Self.Physics); end Physics; ---------------- --- Joint Limits -- procedure Limits_are (Self : in out Item'Class; Low, High : in Real; Softness : in Real := 0.9; bias_Factor : in Real := 0.3; relaxation_Factor : in Real := 1.0) is begin Self.low_Bound := Low; Self.high_Bound := High; Self.Softness := Softness; Self.bias_Factor := bias_Factor; Self.relaxation_Factor := relaxation_Factor; end Limits_are; procedure apply_Limits (Self : in out Item) is begin Self.Physics.Limits_are (Self.low_Bound, Self.high_Bound, Self.Softness, Self.bias_Factor, Self.relaxation_Factor); end apply_Limits; -- Bounds - limits the range of motion for a Degree of freedom. -- overriding function low_Bound (Self : access Item; for_Degree : in joint.Degree_of_freedom) return Real is use type joint.Degree_of_freedom; begin if for_Degree /= Revolve then raise Error with "Invalid degree of freedom:" & for_Degree'Image; end if; return Self.low_Bound; end low_Bound; overriding procedure low_Bound_is (Self : access Item; for_Degree : in joint.Degree_of_freedom; Now : in Real) is use type joint.Degree_of_freedom; begin if for_Degree /= Revolve then raise Error with "Invalid degree of freedom:" & for_Degree'Image; end if; Self.low_Bound := Now; Self.apply_Limits; end low_Bound_is; overriding function high_Bound (Self : access Item; for_Degree : in joint.Degree_of_freedom) return Real is use type joint.Degree_of_freedom; begin if for_Degree /= Revolve then raise Error with "Invalid degree of freedom:" & for_Degree'Image; end if; return Self.high_Bound; end high_Bound; overriding procedure high_Bound_is (Self : access Item; for_Degree : in joint.Degree_of_freedom; Now : in Real) is use type joint.Degree_of_freedom; Span : Real := abs (Now) * 2.0; begin if for_Degree /= Revolve then raise Error with "Invalid degree of freedom:" & for_Degree'Image; end if; Self.high_Bound := Now; Self.apply_Limits; end high_Bound_is; overriding function Extent (Self : in Item; for_Degree : in Degree_of_freedom) return Real is use type joint.Degree_of_freedom; begin if for_Degree /= Revolve then raise Error with "Invalid degree of freedom:" & for_Degree'Image; end if; return Self.Angle; end Extent; overriding function is_Bound (Self : in Item; for_Degree : in joint.Degree_of_freedom) return Boolean is begin return Self.Physics.is_Limited (for_Degree); end is_Bound; overriding procedure Velocity_is (Self : in Item; for_Degree : in joint.Degree_of_freedom; Now : in Real) is begin self.Physics.Velocity_is (Now, for_Degree); end Velocity_is; end gel.hinge_Joint;
LiberatorUSA/GUCEF
Ada
9,795
adb
with C_String; with Interfaces.C; with Interfaces.C.Strings; package body Agar.Core.Object is package C renames Interfaces.C; package C_Strings renames Interfaces.C.Strings; use type C.int; function New_Object (Parent : in Object_Access_t; Name : in String; Object_Class : in Class_Not_Null_Access_t) return Object_Access_t is Ch_Name : aliased C.char_array := C.To_C (Name); begin return Thin.Object.New_Object (Parent => Parent, Name => C_String.To_C_String (Ch_Name'Unchecked_Access), Object_Class => Object_Class); end New_Object; procedure Attach_To_Named (VFS_Root : in Object_Not_Null_Access_t; Path : in String; Child : in Object_Access_t) is Ch_Path : aliased C.char_array := C.To_C (Path); begin Thin.Object.Attach_To_Named (VFS_Root => VFS_Root, Path => C_String.To_C_String (Ch_Path'Unchecked_Access), Child => Child); end Attach_To_Named; function Find (VFS_Root : in Object_Not_Null_Access_t; Pattern : in String) return Object_Access_t is Ch_Format : aliased C.char_array := C.To_C ("%s"); Ch_Pattern : aliased C.char_array := C.To_C (Pattern); begin return Thin.Object.Find (VFS_Root => VFS_Root, Format => C_String.To_C_String (Ch_Format'Unchecked_Access), Data => C_String.To_C_String (Ch_Pattern'Unchecked_Access)); end Find; function Find_Parent (VFS_Root : in Object_Not_Null_Access_t; Name : in String; Object_Type : in String) return Object_Access_t is Ch_Name : aliased C.char_array := C.To_C (Name); Ch_Object_Type : aliased C.char_array := C.To_C (Object_Type); begin return Thin.Object.Find_Parent (VFS_Root => VFS_Root, Name => C_String.To_C_String (Ch_Name'Unchecked_Access), Object_Type => C_String.To_C_String (Ch_Object_Type'Unchecked_Access)); end Find_Parent; function Find_Child (VFS_Root : in Object_Not_Null_Access_t; Name : in String) return Object_Access_t is Ch_Name : aliased C.char_array := C.To_C (Name); begin return Thin.Object.Find_Child (VFS_Root => VFS_Root, Name => C_String.To_C_String (Ch_Name'Unchecked_Access)); end Find_Child; procedure Copy_Name (Object : in Object_Not_Null_Access_t; Path : out String; Used : out Natural) is Path_Length : constant C.size_t := Path'Length; Ch_Path : aliased C.char_array := (Path_Length => C.nul); Ch_Path_Acc : constant C_Strings.char_array_access := Ch_Path'Unchecked_Access; Result : C.int; Length : C.size_t; begin Result := Thin.Object.Copy_Name (Object => Object, Path => C_String.To_C_Char_Array (Ch_Path_Acc), Size => Ch_Path'Length); if Result = 0 then Length := C_String.Length (C_String.To_C_String (Ch_Path_Acc)); Path (Path'First .. Path'First + Natural (Length)) := C_String.To_String (Item => C_String.To_C_Char_Array (Ch_Path_Acc), Size => Length); Used := Natural (Length); else Path (Path'First) := Character'Val (0); Used := 0; end if; end Copy_Name; procedure Set_Name (Object : in Object_Not_Null_Access_t; Name : in String) is Ch_Format : aliased C.char_array := C.To_C ("%s"); Ch_Name : aliased C.char_array := C.To_C (Name); begin Thin.Object.Set_Name (Object => Object, Format => C_String.To_C_String (Ch_Format'Unchecked_Access), Data => C_String.To_C_String (Ch_Name'Unchecked_Access)); end Set_Name; procedure Register_Namespace (Name : in String; Prefix : in String; URL : in String) is Ch_Name : aliased C.char_array := C.To_C (Name); Ch_Prefix : aliased C.char_array := C.To_C (Prefix); Ch_URL : aliased C.char_array := C.To_C (URL); begin Thin.Object.Register_Namespace (Name => C_String.To_C_String (Ch_Name'Unchecked_Access), Prefix => C_String.To_C_String (Ch_Prefix'Unchecked_Access), URL => C_String.To_C_String (Ch_URL'Unchecked_Access)); end Register_Namespace; procedure Unregister_Namespace (Name : in String) is Ch_Name : aliased C.char_array := C.To_C (Name); begin Thin.Object.Unregister_Namespace (C_String.To_C_String (Ch_Name'Unchecked_Access)); end Unregister_Namespace; function Lookup_Class (Spec : in String) return Class_Access_t is Ch_Spec : aliased C.char_array := C.To_C (Spec); begin return Thin.Object.Lookup_Class (C_String.To_C_String (Ch_Spec'Unchecked_Access)); end Lookup_Class; function Load_Class (Spec : in String) return Class_Access_t is Ch_Spec : aliased C.char_array := C.To_C (Spec); begin return Thin.Object.Load_Class (C_String.To_C_String (Ch_Spec'Unchecked_Access)); end Load_Class; procedure Register_Module_Directory (Path : in String) is Ch_Path : aliased C.char_array := C.To_C (Path); begin Thin.Object.Register_Module_Directory (C_String.To_C_String (Ch_Path'Unchecked_Access)); end Register_Module_Directory; procedure Unregister_Module_Directory (Path : in String) is Ch_Path : aliased C.char_array := C.To_C (Path); begin Thin.Object.Unregister_Module_Directory (C_String.To_C_String (Ch_Path'Unchecked_Access)); end Unregister_Module_Directory; function Is_Of_Class (Object : in Object_Not_Null_Access_t; Pattern : in String) return Boolean is Ch_Pattern : aliased C.char_array := C.To_C (Pattern); begin return 1 = Thin.Object.Is_Of_Class (Object => Object, Pattern => C_String.To_C_String (Ch_Pattern'Unchecked_Access)); end Is_Of_Class; function In_Use (Object : in Object_Not_Null_Access_t) return Boolean is begin return 1 = Thin.Object.In_Use (Object); end In_Use; function Add_Dependency (Object : in Object_Not_Null_Access_t; Dependency : in Object_Not_Null_Access_t; Persistent : in Boolean) return Dependency_Access_t is begin return Thin.Object.Add_Dependency (Object => Object, Dependency => Dependency, Persistent => Boolean'Pos (Persistent)); end Add_Dependency; function Find_Dependency (Object : in Object_Not_Null_Access_t; Index : in Interfaces.Unsigned_32; Pointer : access Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Find_Dependency (Object => Object, Index => Index, Pointer => Pointer); end Find_Dependency; function Load (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Load (Object); end Load; function Load_From_File (Object : in Object_Not_Null_Access_t; File : in String) return Boolean is Ch_File : aliased C.char_array := C.To_C (File); begin return 0 = Thin.Object.Load_From_File (Object => Object, File => C_String.To_C_String (Ch_File'Unchecked_Access)); end Load_From_File; function Load_Data (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Load_Data (Object); end Load_Data; function Load_Data_From_File (Object : in Object_Not_Null_Access_t; File : in String) return Boolean is Ch_File : aliased C.char_array := C.To_C (File); begin return 0 = Thin.Object.Load_Data_From_File (Object => Object, File => C_String.To_C_String (Ch_File'Unchecked_Access)); end Load_Data_From_File; function Load_Generic (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Load_Generic (Object); end Load_Generic; function Load_Generic_From_File (Object : in Object_Not_Null_Access_t; File : in String) return Boolean is Ch_File : aliased C.char_array := C.To_C (File); begin return 0 = Thin.Object.Load_Generic_From_File (Object => Object, File => C_String.To_C_String (Ch_File'Unchecked_Access)); end Load_Generic_From_File; function Save (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Save (Object); end Save; function Save_All (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Save_All (Object); end Save_All; function Save_To_File (Object : in Object_Not_Null_Access_t; File : in String) return Boolean is Ch_File : aliased C.char_array := C.To_C (File); begin return 0 = Thin.Object.Save_To_File (Object => Object, File => C_String.To_C_String (Ch_File'Unchecked_Access)); end Save_To_File; function Serialize (Object : in Object_Not_Null_Access_t; Source : in Data_Source.Data_Source_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Serialize (Object, Source); end Serialize; function Unserialize (Object : in Object_Not_Null_Access_t; Source : in Data_Source.Data_Source_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Unserialize (Object, Source); end Unserialize; function Read_Header (Object : in Object_Not_Null_Access_t; Header : in Object_Header_Access_t) return Boolean is begin return 0 = Thin.Object.Read_Header (Object, Header); end Read_Header; function Page_In (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Page_In (Object); end Page_In; function Page_Out (Object : in Object_Not_Null_Access_t) return Boolean is begin return 0 = Thin.Object.Page_Out (Object); end Page_Out; end Agar.Core.Object;
reznikmm/matreshka
Ada
3,699
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Text_Tab_Ref_Attributes is pragma Preelaborate; type ODF_Text_Tab_Ref_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Text_Tab_Ref_Attribute_Access is access all ODF_Text_Tab_Ref_Attribute'Class with Storage_Size => 0; end ODF.DOM.Text_Tab_Ref_Attributes;
reznikmm/matreshka
Ada
11,845
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2010-2015, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package provides abstraction for Unicode characters (code points). -- Some operations in this package and its children packages depends from the -- current or explicitly specified locale. -- -- Universal_Character provides the gateway to Unicode Character Database. ------------------------------------------------------------------------------ private with Matreshka.Internals.Unicode; package League.Characters is pragma Preelaborate; pragma Remote_Types; type General_Category_Values is (Uppercase_Letter, Lowercase_Letter, Titlecase_Letter, Modifier_Letter, Other_Letter, Nonspacing_Mark, Spacing_Mark, Enclosing_Mark, Decimal_Number, Letter_Number, Other_Number, Connector_Punctuation, Dash_Punctuation, Open_Punctuation, Close_Punctuation, Initial_Punctuation, Final_Punctuation, Other_Punctuation, Math_Symbol, Currency_Symbol, Modifier_Symbol, Other_Symbol, Space_Separator, Line_Separator, Paragraph_Separator, Control, Format, Surrogate, Private_Use, Unassigned); -- subtype Cased_Letter is General_Category_Values -- range Uppercase_Letter .. Titlecase_Letter; -- -- subtype Letter is General_Category_Values -- range Uppercase_Letter .. Other_Letter; -- -- subtype Mark is General_Category_Values -- range Nonspacing_Mark .. Enclosing_Mark; -- -- subtype Number is General_Category_Values -- range Decimal_Number .. Other_Number; -- -- subtype Punctuation is General_Category_Values -- range Connector_Punctuation .. Other_Punctuation; -- -- subtype Symbol is General_Category_Values -- range Math_Symbol .. Other_Symbol; -- -- subtype Separator is General_Category_Values -- range Space_Separator .. Paragraph_Separator; -- -- subtype Other is General_Category_Values -- range Control .. Unassigned; type East_Asian_Width_Values is (Ambiguous, Fullwidth, Halfwidth, Neutral, Narrow, Wide); type Universal_Character is tagged private; pragma Preelaborable_Initialization (Universal_Character); function To_Wide_Wide_Character (Self : Universal_Character'Class) return Wide_Wide_Character; function To_Universal_Character (Self : Wide_Wide_Character) return Universal_Character; function Is_Valid (Self : Universal_Character'Class) return Boolean; -- Returns True when code point of the specified character is inside valid -- code point range and it is not a surrogate code point. function General_Category (Self : Universal_Character'Class) return General_Category_Values; -- Returns general category of the specified character. function Is_Noncharacter_Code_Point (Self : Universal_Character'Class) return Boolean; -- Code points permanently reserved for internal use. function Is_Digit (Self : Universal_Character'Class) return Boolean; -- Returns True when character's general catewgory is one of Number -- categories: -- -- - Decimal_Number -- - Letter_Number -- - Other_Number function Is_Punctuation (Self : Universal_Character'Class) return Boolean; -- Returns True when character's general catewgory is one of Punctuation -- categories: -- -- - Connector_Punctuation -- - Dash_Punctuation -- - Open_Punctuation -- - Close_Punctuation -- - Initial_Punctuation -- - Final_Punctuation -- - Other_Punctuation function Is_ID_Start (Self : Universal_Character'Class) return Boolean; -- Returns True when character is start character of identifier: -- -- "Character having the Unicode General_Category of uppercase letters -- (Lu), lowercase letters (Ll), titlecase letters (Lt), modifier letters -- (Lm), other letters (Lo), letter numbers (Nl), minus Pattern_Syntax and -- Pattern_White_Space code points, plus stability extensions. Note that -- “other letters” includes ideographs." function Is_ID_Continue (Self : Universal_Character'Class) return Boolean; -- Returns True when character is continue of identifier: -- -- "All of the start character of identifier characters, plus characters -- having the Unicode General_Category of nonspacing marks (Mn), spacing -- combining marks (Mc), decimal number (Nd), connector punctuations (Pc), -- plus stability extensions, minus Pattern_Syntax and Pattern_White_Space -- code points." function Is_White_Space (Self : Universal_Character'Class) return Boolean; -- Returns True when character is white space: -- -- "Spaces, separator characters and other control characters which should -- be treated by programming languages as "white space" for the purpose of -- parsing elements. See also Line_Break, Grapheme_Cluster_Break, -- Sentence_Break, and Word_Break, which classify space characters and -- related controls somewhat differently for particular text segmentation -- contexts." function East_Asian_Width (Self : Universal_Character'Class) return East_Asian_Width_Values; -- Returns value of East Asian Width property of specified character. function Lowercase (Self : Universal_Character'Class) return Boolean; -- Returns True when character is lowercase letter. function Uppercase (Self : Universal_Character'Class) return Boolean; -- Returns True when character is uppercase letter. function Simple_Uppercase_Mapping (Self : Universal_Character'Class) return Universal_Character; -- Returns simple uppercase mapping for the specified character. function Simple_Lowercase_Mapping (Self : Universal_Character'Class) return Universal_Character; -- Returns simple lowercase mapping for the specified character. function Simple_Titlecase_Mapping (Self : Universal_Character'Class) return Universal_Character; -- Returns simple titlecase mapping for the specified character. function Simple_Casefold_Mapping (Self : Universal_Character'Class) return Universal_Character; -- Returns simple casefold mapping for the specified character. overriding function "=" (Left : Universal_Character; Right : Universal_Character) return Boolean; not overriding function "<" (Left : Universal_Character; Right : Universal_Character) return Boolean; not overriding function "<=" (Left : Universal_Character; Right : Universal_Character) return Boolean; not overriding function ">" (Left : Universal_Character; Right : Universal_Character) return Boolean; not overriding function ">=" (Left : Universal_Character; Right : Universal_Character) return Boolean; not overriding function "=" (Left : Universal_Character; Right : Wide_Wide_Character) return Boolean; not overriding function "<" (Left : Universal_Character; Right : Wide_Wide_Character) return Boolean; not overriding function "<=" (Left : Universal_Character; Right : Wide_Wide_Character) return Boolean; not overriding function ">" (Left : Universal_Character; Right : Wide_Wide_Character) return Boolean; not overriding function ">=" (Left : Universal_Character; Right : Wide_Wide_Character) return Boolean; not overriding function "=" (Left : Wide_Wide_Character; Right : Universal_Character) return Boolean; not overriding function "<" (Left : Wide_Wide_Character; Right : Universal_Character) return Boolean; not overriding function "<=" (Left : Wide_Wide_Character; Right : Universal_Character) return Boolean; not overriding function ">" (Left : Wide_Wide_Character; Right : Universal_Character) return Boolean; not overriding function ">=" (Left : Wide_Wide_Character; Right : Universal_Character) return Boolean; -- Subprograms to compare characters in code point order. private Invalid : constant Matreshka.Internals.Unicode.Code_Unit_32 := Matreshka.Internals.Unicode.Code_Unit_32'Last; -- Invalid code point to be used to represent uninitialized -- Universal_Character object. ------------------------- -- Universal_Character -- ------------------------- type Universal_Character is tagged record Code : Matreshka.Internals.Unicode.Code_Unit_32 := Invalid; end record; pragma Inline ("<"); pragma Inline ("<="); pragma Inline ("="); pragma Inline (">"); pragma Inline (">="); pragma Inline (To_Wide_Wide_Character); end League.Characters;
reznikmm/matreshka
Ada
3,764
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Style_Layout_Grid_Display_Attributes is pragma Preelaborate; type ODF_Style_Layout_Grid_Display_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Style_Layout_Grid_Display_Attribute_Access is access all ODF_Style_Layout_Grid_Display_Attribute'Class with Storage_Size => 0; end ODF.DOM.Style_Layout_Grid_Display_Attributes;
OneWingedShark/Byron
Ada
173
ads
Pragma Ada_2012; Pragma Assertion_Policy( Check ); With Lexington.Token_Vector_Pkg; -- Generate Ticks. Procedure Lexington.Aux.P11(Data : in out Token_Vector_Pkg.Vector);
BrickBot/Bound-T-H8-300
Ada
66,303
ads
-- Storage.Bounds (decl) -- -- Representing bounds (constraints) on variables and expression values. -- -- The term "bounds" has here a very general (perhaps even vague) meaning -- as any constraint on the joint values of a set of program or processor -- state elements (variables or expressions) valid at some point(s) in -- the execution of the program. -- -- Various kinds of data-flow / data-range analysis yield such bounds -- with different form and precision. For example, a constant-propagation -- analysis yields bounds that give, for each variable in question, either -- a single possible value (the constant) or a "not constant" value, while -- interval analysis provides an interval (min, max) for each variable, -- perhaps with one or both ends unlimited (infinite). -- -- The above examples are forms of "bounds" that apply separately to each -- variable, although the analysis that derived the bounds will take -- into account the flow of data between variables. There are also more -- complex forms of bounds that define how variable values are related, -- for example by stating that the value of variable X is the sum of the -- values of variables Y and Z. -- -- This package defines some concrete kinds of bounds, and also a -- general type of bounds as an extensible type (class), thus -- allowing several representations of the type, simple or complex. -- -- Two groups of concrete bounds are defined. The first group applies -- to signed integer numbers of indefinite width (number of bits), as -- represented by the type Arithmetic.Value_T. The second group applies -- to binary words of a specific width, as represented by the types -- Arithmetic.Word_T and Arithmetic.Width_T. Such words are normally -- considered unsigned but can be viewed as signed. -- -- For both groups of concrete bounds (integers/words) the bounds are -- constructed in two steps. The first step defines a one-sided bound -- or limit that defines a limiting value that can be used as a lower -- bound or an upper bound. The second step combines two limits to -- make an interval with both a lower and an upper bound. -- -- In the second group, the "interval" type for binary words includes -- "complement intervals" (co-intervals) that comprise all values less -- than a first limit or greater than a second (larger) limit. Co-intervals -- are needed to represent intervals of word values in the signed view. -- They also close the word-interval domain with respect to the operations -- of logical (set) complement and modular addition and subtraction. -- -- In addition to limits and intervals, both groups of concrete bounds -- (integers/words) include a third type of bound that consists of a -- list of the possible values of the bounded variable. -- -- Our main use of bounds (of various forms) is to use them to constrain -- or refine "boundable" things. The boundable things are elements or -- parts of our model of a program or an execution of a program. The -- result of applying some "bounds" to a "boundable" thing is more -- knowledge (less options) for the nature and effects of the thing, -- in the limit (best case) a full static characterization of the thing. -- -- The type "boundable" is defined as an extensible type (class) since -- we want to bound many different things: dynamic jumps, dynamic data -- accesses, loop iterations, stack usage, etc. -- -- The main operation, that of applying "bounds" to a "boundable", is -- thus doubly dispatching. -- -- At this top level, not much that is concrete can be said or defined -- about "bounds" and "boundables", but these top-level definitions -- provide an (access) type for "boundables" that can be embedded in -- program and execution models in a uniform way. -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- 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. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.22 $ -- $Date: 2015/10/24 19:36:52 $ -- -- $Log: storage-bounds.ads,v $ -- Revision 1.22 2015/10/24 19:36:52 niklas -- Moved to free licence. -- -- Revision 1.21 2014/07/01 22:07:01 niklas -- Added Image functions for Var_Interval(_List)_T. -- -- Revision 1.20 2013/12/08 20:08:23 niklas -- Added the function Number_Of_Values. -- -- Revision 1.19 2012-02-13 17:52:20 niklas -- BT-CH-0230: Options -max_loop and -max_stack for spurious bounds. -- -- Revision 1.18 2009-11-27 11:28:07 niklas -- BT-CH-0184: Bit-widths, Word_T, failed modular analysis. -- -- Revision 1.17 2008/09/24 08:38:53 niklas -- BT-CH-0146: Assertions on "loop starts <bound> times". -- BT-CH-0146: Loop-repeat assertions set both lower and upper bound. -- BT-CH-0146: Report locations of contradictory "count" assertions. -- BT-CH-0146: Contradictory "count" assertions imply infeasibility. -- -- Revision 1.16 2008/06/18 20:52:56 niklas -- BT-CH-0130: Data pointers relative to initial-value cells. -- -- Revision 1.15 2008/03/11 22:08:07 niklas -- BT-CH-0121: Delayed calls and other SHARC support. -- -- Revision 1.14 2007/12/17 13:54:41 niklas -- BT-CH-0098: Assertions on stack usage and final stack height, etc. -- -- Revision 1.13 2007/07/21 18:18:43 niklas -- BT-CH-0064. Support for AVR/IAR switch-handler analysis. -- -- Revision 1.12 2007/07/09 13:42:51 niklas -- Added the Bounds_T primitive functions Intervals and Full_Image. -- -- Revision 1.11 2007/05/02 09:30:04 niklas -- Added Exactly_Zero. -- -- Revision 1.10 2007/04/18 18:34:39 niklas -- BT-CH-0057. -- -- Revision 1.9 2007/03/29 15:18:04 niklas -- BT-CH-0056. -- -- Revision 1.8 2007/03/18 12:50:41 niklas -- BT-CH-0050. -- -- Revision 1.7 2007/01/25 21:25:19 niklas -- BT-CH-0043. -- -- Revision 1.6 2006/05/27 21:33:23 niklas -- Added function Is_In (Value, Interval) for BT-CH-0020. -- -- Revision 1.5 2006/02/27 10:04:14 niklas -- Added functions Min (Interval_T) and Max (Interval_T). -- -- Revision 1.4 2005/03/04 09:32:35 niklas -- Added functions "+" and "-" to shift limits and intervals -- up or down by adding a constant value to the bounds. -- Added function Intersects to show if two intervals meet. -- -- Revision 1.3 2005/02/23 09:05:21 niklas -- BT-CH-0005. -- -- Revision 1.2 2005/02/19 20:34:56 niklas -- BT-CH-0003. -- -- Revision 1.1 2005/02/16 21:11:49 niklas -- BT-CH-0002. -- --:dbpool with GNAT.Debug_Pools; with Processor; package Storage.Bounds is Unbounded : exception; -- -- Signals that a variable (cell) is not bounded, by some given -- bounds, to the extent required for the current operation to -- return the desired result. -- --- Limits, intervals, and lists for signed integers of indefinite width -- -- --- Division with ceiling/floor -- -- Our computations need "floor" and "ceiling" functions, which may -- as well be provided in public. function Floor (Left, Right : Value_T) return Value_T; -- -- Floor (Left / Right), when Right /= 0. -- In other words, the largest integer <= Left/Right. function Ceil (Left, Right : Value_T) return Value_T; -- -- Ceiling (Left / Right), when Right /= 0. -- In other words, the smallest integer >= Left/Right. -- --- Limits (one-sided or on a single value) on signed integers -- -- These are not yet "bounds", but can be derived from "bounds" and -- can be used to construct "bounds". type Limit_Kind_T is (Unlimited, Finite); -- -- An upper or lower limit on a variable, or a limit that defines -- a single value for the variable (depending on context) can be -- of two kinds: -- -- Unlimited -- No limit is deduced. As far as we know the limit is -- minus infinity for a lower limit and plus infinity for -- an upper limit, or an unknown value for a single-value limit. -- -- Finite -- A limiting (literal) value is deduced. type Limit_T is record Kind : Limit_Kind_T := Unlimited; Value : Value_T := 0; end record; -- -- One end of a bounded interval, or a possibly defined single value -- for a variable. -- -- Whether this is an upper or lower limit or a single-value limit -- must be known from context. -- -- The Value is relevant mainly if Kind = Finite, but may also be -- important if Kind = Unlimited because it is often set to be the -- corresponding infinity (plus or minus). Not_Limited : constant Limit_T := ( Kind => Unlimited, Value => 0); -- -- An unknown limit. function Image (Item : Limit_T) return String; -- -- The value for a known limit, "?" otherwise. function Image ( Item : Limit_T; Unknown : String) return String; -- -- The value for a known limit, the Unknown string otherwise. function Over (Value : Value_T; Max : Limit_T) return Boolean; -- -- Whether the Value is over the (upper) limit Max, which is true -- if and only if the Max is known and Value > Max.Value. function Under (Value : Value_T; Min : Limit_T) return Boolean; -- -- Whether the Value is under the (lower) limit Min, which is true -- if and only if the Min is known and Value < Min.Value. function Limit (Value : Value_T) return Limit_T; -- -- The finite limit at Value. function Unlimited (L : Limit_T) return Boolean; -- -- Whether the limit is unlimited (infinity). function Known (L : Limit_T) return Boolean; -- -- Whether the limit is finite and known (a constant). function Value (L : Limit_T) return Value_T; -- -- The value of the limit, assumed to be Known. -- If the limit-value is not Known, Unbounded is raised. procedure Limit_Value ( Limit : in Limit_T; Value : out Value_T; Is_Const : out Boolean); -- -- Returns the limiting value if constant, as shown by a True return -- value in Is_Const. Otherwise Is_Const is False and Value is -- undefined. function And_Max (Left, Right : Limit_T) return Limit_T; -- -- Given two upper limits, returns their logical conjunction -- or, in other words, the tighter (lesser) limit. function And_Min (Left, Right : Limit_T) return Limit_T; -- -- Given two lower limits, returns their logical conjunction -- or, in other words, the tighter (greater) limit. function Or_Min (Left, Right : Limit_T) return Limit_T; -- -- Given two lower limits, returns their logical disjunction -- or, in other words, the looser (lesser) limit. function Or_Max (Left, Right : Limit_T) return Limit_T; -- -- Given two upper limits, returns their logical disjunction -- or, in other words, the looser (greater) limit. procedure Increase ( Limit : in out Limit_T; To_Allow : in Value_T); -- -- Increases the upper Limit To_Allow the given value, if the -- value is not already within (less or equal to) the Limit. procedure Decrease ( Limit : in out Limit_T; To_Allow : in Value_T); -- -- Decreases the lower Limit To_Allow the given value, if the -- value is not already within (greater or equal to) the Limit. function "+" (Left : Limit_T; Right : Value_T) return Limit_T; -- -- The Left limit shifted by adding Right to the Value. -- If Left is unlimited, so is the result. function "-" (Left : Limit_T; Right : Value_T) return Limit_T; -- -- The Left limit shifted by subtracting Right from the Value. -- If Left is unlimited, so is the result. function "-" (Item : Limit_T) return Limit_T; -- -- The limit with the opposite sign to the given limit. -- --- Intervals of signed integers -- -- These are not yet "bounds", but can be derived from bounds and -- used to construct bounds. type Interval_T is record Min : Limit_T; Max : Limit_T; end record; -- -- Bounds the value of some value (such as a cell, or an expression) -- to an interval Min .. Max. -- The value (cell or expression) to which this bound applies -- must be known from context. Void_Interval : constant Interval_T := ( Min => (Kind => Finite, Value => 1), Max => (Kind => Finite, Value => 0)); -- -- A bound that represents the empty set (since Min > Max). Universal_Interval : constant Interval_T := ( Min => (Kind => Unlimited, Value => Value_T'First), Max => (Kind => Unlimited, Value => Value_T'Last )); -- -- An interval that accepts any value. -- The Min and Max values are defined to make it easier -- to intersect this interval with other (bounded) intervals. Non_Negative_Interval : constant Interval_T := ( Min => (Kind => Finite, Value => 0), Max => Not_Limited); -- -- An interval that contains all values >= 0. Minus_One : constant := -1; -- -- For use in Negative_Interval below. Negative_Interval : constant Interval_T := ( Min => Not_Limited, Max => (Kind => Finite, Value => Minus_One)); -- -- An interval that contains all values < 0. Exactly_Zero : constant Interval_T := ( Min => (Kind => Finite, Value => 0), Max => (Kind => Finite, Value => 0)); -- -- The singleton interval that contains only the value 0. function Interval (Min, Max : Value_T) return Interval_T; -- -- The interval Min .. Max. function Min (Item : Interval_T) return Value_T; -- -- Short for Value (Interval.Min). Can raise Unbounded. function Max (Item : Interval_T) return Value_T; -- -- Short for Value (Interval.Max). Can raise Unbounded. function Singleton (Value : Value_T) return Interval_T; -- -- The one-point interval Value .. Value. function One_Or_All (Value : Limit_T) return Interval_T; -- -- The one-point interval Value .. Value if Value is Known, else -- the universal (unlimited) interval. function Void (Item : Interval_T) return Boolean; -- -- Whether the interval represents the empty (void) set. -- In other words, no value can satisfy both the lower-limit -- and the upper-limit. -- False is returned for indeterminate cases. function Known (Interval : Interval_T) return Boolean; -- -- Whether the interval has finite and known (constant) components -- at one or both ends. Note that we do not require both ends -- (min and max) to be finite. function Bounded (Interval : Interval_T) return Boolean; -- -- Whether both ends of the Interval are known and finite. function Universal (Interval : Interval_T) return Boolean; -- -- Whether the Interval is the universal interval. This is the -- case if both ends are Unlimited. function Number_Of_Values (Within : Interval_T) return Value_T; -- -- The number of values Within the interval. If the interval is -- unbounded, or the number of values is too large to fit in Value_T, -- the function propagates Unbounded. function Is_In ( Value : Value_T; Interval : Interval_T) return Boolean; -- -- Whether the Value lies in the Interval. function "<" (Value : Value_T; Interval : Interval_T) return Boolean; -- -- Whether the Value is less than the lower bound, Interval.Min. -- False if Interval.Min is Unlimited. function ">" (Value : Value_T; Interval : Interval_T) return Boolean; -- -- Whether the Value is greater than the upper bound, Interval.Max. -- False if Interval.Max is unlimited. Multiple_Values : exception; -- -- Raised by Single_Value (below) if the given interval does not -- define a single value. function Singular (Interval : Interval_T) return Boolean; -- -- Whether the Interval allows only a single value (Min and Max -- are constants and equal). The single value in question can -- be retrieved with Single_Value, see below. function Single_Value (Interval : Interval_T) return Value_T; -- -- If the Interval allows a single value, that is if Singular (Interval) -- is True (which means that Min and Max are constants and equal), -- returns this value. -- Otherwise, that is if Singular (Interval) is False, raises -- Multiple_Values. function "and" (Left, Right : Interval_T) return Interval_T; -- -- The conjunction (intersection) of two intervals. function "or" (Left, Right : Interval_T) return Interval_T; -- -- The disjunction (union) of two intervals. procedure Widen ( Interval : in out Interval_T; To_Contain : in Value_T); -- -- Widens the Interval To_Contain the given value, if it does -- not already contain this value. function "<=" (Left, Right : Interval_T) return Boolean; -- -- Whether the Left interval is a subset of the Right interval. -- In other words, the Left interval is narrower than (or the -- same as) the Right interval. Always True if the Left interval -- is Void. function Intersects (Left, Right : Interval_T) return Boolean; -- -- Whether the intersection of the Left and Right intervals is -- non-empty. function "+" (Left : Interval_T; Right : Value_T) return Interval_T; -- -- The Left interval shifted by adding Right to the Min and Max limits. -- If either Left limit is unlimited, so is the corresponding limit in -- the result. function "-" (Left : Interval_T; Right : Value_T) return Interval_T; -- -- The Left interval shifted by subtracting Right from the Min and -- Max limits. If either Left limit is unlimited, so is the -- corresponding limit in the result. function "+" (Left, Right : Interval_T) return Interval_T; -- -- The interval sum of Left and Right. If either operand is -- void, so is the sum. If one end of either operand is unlimited, -- so is the corresponding end of the sum. function "-" (Item : Interval_T) return Interval_T; -- -- The interval of the opposite sign, converting min .. max -- to -max .. -min. function "-" (Left, Right : Interval_T) return Interval_T; -- -- The interval difference of Left - Right. If either operand is -- void, so is the sum. If one end of either operand is unlimited, -- so is the corresponding end of the difference. -- Equivalent to Left + (- Right). function Image (Item : Interval_T) return String; -- -- The interval as (low limit) .. (high limit). -- An unknown (unbounded) limit is written as "-inf" or "+inf". -- If the interval is singular, just the single value is shown. function Image ( Item : Interval_T; Name : String) return String; -- -- The Name is used to denote the value (cell or expression) -- to which the bound applies. The result has the form -- -- min <= Name <= max -- -- where "min <= " and/or "<= max" is missing if unbounded. function Image ( Item : Interval_T; Cell : Cell_T) return String; -- -- Same as Image (Item, Image (Cell)). type Interval_List_T is array (Positive range <>) of Interval_T; -- -- A set of interval bounds on values. -- The value (cell or expression) to which each interval applies -- must be known from context. type Value_List_T is array (Positive range <>) of Value_T; -- -- A list of values. The indexing and meaning depend on usage. function Single_Value (Intervals : Interval_List_T) return Value_List_T; -- -- The list of single values allowed by each of the listed singular -- Intervals. If some of the Intervals are not singular the function -- propagates Multiple_Values. function Image ( Item : Interval_List_T; Prefix : String) return String; -- -- Describes each interval in the list, using a Name for the -- bounded value composed from the Prefix and the index of -- the interval in the list. -- --- Intervals of signed integers for cells -- -- These are not yet "bounds", but can be derived from bounds and can -- be used to construct bounds. type Cell_Interval_T is record Cell : Cell_T; Interval : Interval_T; end record; -- -- An interval that bounds the value of a cell. type Cell_Interval_List_T is array (Positive range <>) of Cell_Interval_T; -- -- A set of interval bounds on cell values, giving both the cells -- and the value-interval for each cell. function Empty return Cell_Interval_List_T; -- -- An empty (null) list of cell-interval bounds. function Interval ( Cell : Storage.Cell_T; From : Cell_Interval_List_T) return Interval_T; -- -- The interval bounds on the given Cell, taken From the given list. -- If the list has several interval bounds for the cell, their -- conjunction (intersection) is returned. If the list has no interval -- bounds for the cell, Universal_Interval is returned. function Intervals_For_Cells ( Cells : Cell_Set_T; From : Cell_Interval_List_T) return Cell_Interval_List_T; -- -- Returns the interval bounds From the list on the given Cells. -- If a cell from Cells occurs several times in the From list, it -- will occur as many times in the result. function "and" (Left, Right : Cell_Interval_List_T) return Cell_Interval_List_T; -- -- The conjunction of the two lists of interval bounds on cells. -- If the same cell is mentioned in both lists, it occurs -- but once in the result, with the conjunction (intersection) -- of the intervals from all its ocurrences. -- If a cell is mentioned only in one of the two lists, that list -- defines the interval for the cell in the result. function Image (Item : Cell_Interval_T) return String; -- -- As in Image (Item => Item.Bound, Name => Image (Item.Cell)). function Image (Item : Cell_Interval_List_T) return String; -- -- Describes the bounds as a list of Image (Bound, Image(Cell)). function Cells_Of (Item : Cell_Interval_List_T) return Cell_List_T; -- -- All the cells in the given list of cells and intervals, in the -- same order and with possible duplicates. -- --- Intervals of signed integers for variables with moving locations -- -- These are not yet "bounds", nor can they be derived from bounds, but -- they can be used to construct bounds when the point in the program is -- known so that the variable can be associated with a cell. type Var_Interval_T is record Location : Location_Ref; Interval : Interval_T; end record; -- -- Interval bounds on the value of a variable that may occupy different -- storage locations at different points in the program. function Image (Item : Var_Interval_T) return String; -- -- A readable description of the variable and its interval bound. type Var_Interval_List_T is array (Positive range <>) of Var_Interval_T; -- -- A set of interval bounds on variable values, giving both the location -- of each variable (possibly varying with the execution point) and -- the interval that bounds each variable. function Image (Item : Var_Interval_List_T) return String; -- -- A readable description of the list of variables and their -- interval bounds. function "and" (Left, Right : Var_Interval_List_T) return Var_Interval_List_T; -- -- The conjunction of the two lists of interval bounds in variables. -- If the same variable (same location-ref) is mentioned in both lists, -- it occurs but once in the result, with the conjunction (intersection) -- of the intervals from all its ocurrences. -- If a variable is mentioned only in one of the two lists, that list -- defines the interval for the variable in the result. -- Variables are identified by the locations (reference equality). function Cell_Intervals ( From : Var_Interval_List_T; Point : Processor.Code_Address_T) return Cell_Interval_List_T; -- -- Interval bounds on cell values derived From interval bounds on -- variables by mapping the location of each variable to a cell at -- the given Point in the target program. -- -- If a variable maps to several cells at this point, the bounds for -- the variable are applied to each cell in the result. -- -- If a variable maps to no cells at this point, the bounds for the -- variable are not used in the result. -- -- If several variables map to the same cell at this point, the bounds -- for these variables are conjoined (intersected) to give the bounds -- on this cell in the result. -- --- Lists (enumerations) of signed integer values -- -- These are not yet "bounds" but can be derived from bounds. -- -- Some "bounds" can yield a list of possible values for the -- bounded variable(s). This will usually be an ordered list -- (ascending order) without duplicates. function Values (Within : Interval_T) return Value_List_T; -- -- All the values Within the interval, assuming that the interval -- is fully Bounded, else Unbounded is raised. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. function "-" (Left, Right : Interval_T) return Value_List_T; -- -- All the values allowed by Left, except the values also -- allowed by Right. In other words, the difference between -- the set defined by Left and the set defined by Right. -- All limits involved must be known constants, otherwise -- Unbounded is raised. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. subtype Positive_Value_T is Value_T range 1 .. Value_T'Last; -- -- The non-negative values. function Values (Within : Interval_T; Aligned : Positive_Value_T) return Value_List_T; -- -- All the values that are Within the given interval and are -- also integral multiples of Aligned, assuming that the interval -- is fully Bounded, else Unbounded is raised. -- TBD if the limits must be multiples of Aligned. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. function Difference ( Included : in Interval_T; Excluded : in Interval_T; Aligned : in Positive_Value_T) return Value_List_T; -- -- All the values allowed by the Included interval, except the -- values also allowed by the Excluded interval, and considering -- only those values that are integral multiples of Aligned. -- All limits involved must be known constants, otherwise the -- Unbounded exception is raised. -- TBD if the limits must be multiples of Aligned. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. -- --- Limits, intervals, and lists for binary words of specific width -- -- --- Limits (one-sided or on a single value) for binary words -- -- These are not yet "bounds", but can be derived from "bounds" and -- can be used to construct "bounds". type Word_Limit_T is record Kind : Limit_Kind_T := Unlimited; Value : Word_T := 0; end record; -- -- One end of a bounded interval, or a possibly defined single value -- for a variable. -- -- Whether this is an upper or lower limit or a single-value limit -- must be known from context. -- -- The Value is relevant mainly if Kind = Finite. The significant width -- of the Value is not defined here, nor is its signedness, so they -- must be taken from context. The excess (high) bits in Value must -- be zero. Word_Not_Limited : constant Word_Limit_T := ( Kind => Unlimited, Value => 0); -- -- An unknown limit. function Image (Item : Word_Limit_T) return String; -- -- The value for a known limit, "?" otherwise. function Image ( Item : Word_Limit_T; Unknown : String) return String; -- -- The value for a known limit, the Unknown string otherwise. function Limit (Value : Word_T) return Word_Limit_T; -- -- The finite limit at Value. function Unlimited (L : Word_Limit_T) return Boolean; -- -- Whether the limit is unlimited (infinity). function Known (L : Word_Limit_T) return Boolean; -- -- Whether the limit is finite and known (a constant). function Value (L : Word_Limit_T) return Word_T; -- -- The value of the limit, assumed to be Known. -- If the limit-value is not Known, Unbounded is raised. function And_Max (Left, Right : Word_Limit_T) return Word_Limit_T; -- -- Given two upper limits, returns their logical conjunction -- or, in other words, the tighter (lesser) limit, in the -- unsigned view. function And_Min (Left, Right : Word_Limit_T) return Word_Limit_T; -- -- Given two lower limits, returns their logical conjunction -- or, in other words, the tighter (greater) limit, in the -- unsigned view. function Or_Min (Left, Right : Word_Limit_T) return Word_Limit_T; -- -- Given two lower limits, returns their logical disjunction -- or, in other words, the looser (lesser) limit, in the -- unsigned view. function Or_Max (Left, Right : Word_Limit_T) return Word_Limit_T; -- -- Given two upper limits, returns their logical disjunction -- or, in other words, the looser (greater) limit, in the -- unsigned view. procedure Increase ( Limit : in out Word_Limit_T; To_Allow : in Word_T); -- -- Increases the upper Limit To_Allow the given value, if the -- value is not already within (less or equal to) the Limit, -- in the unsigned view. procedure Decrease ( Limit : in out Word_Limit_T; To_Allow : in Word_T); -- -- Decreases the lower Limit To_Allow the given value, if the -- value is not already within (greater or equal to) the Limit, -- in the unsigned view. -- --- Intervals of binary words -- -- These are not yet "bounds", but can be derived from bounds and -- used to construct bounds. type Word_Interval_T is record Min : Word_Limit_T; Max : Word_Limit_T; Width : Width_T; Inside : Boolean; end record; -- -- Bounds the value of some value (such as a cell, or an expression) -- by the Min and Max limits, either or both of which may be Finite -- or Unlimited. The bounds can require the value to be Inside the -- interval Min .. Max, or outside this interval (< Min or > Max). -- -- The former case is called a true interval or "eu-interval", and -- the latter case is called a complement interval or "co-interval". -- Co-intervals are useful mainly for representing interval bounds -- on signed values. For a co-interval the interval Min .. Max is -- called the "gap" of the co-interval. It is the set complement of -- the co-interval. Of course, it is also useful that co-intervals -- close the domain with respect to logical negation (set complement). -- -- The Width of the values is also given. The value (cell or -- expression) to which this bound applies must be known from context. -- -- The empty (void) interval is represented as an eu-interval with -- finite Min and Max such that Min.Value > Max.Value. -- -- Intervals with one or both ends Unlimited are always defined as -- eu-intervals with Inside = True. Thus, a co-interval always has -- both ends Finite, and moreover Min.Value is greater than zero, -- Max.Value is less than Max_Word (Width), and Min.Value is less or -- equal to Max.Value. See the To_Normal function below. -- -- Thus, a (normalized) co-interval always contains both the value zero -- and the value Max_Word (Width) but never contains all values. Thus, -- a (normalized) co-interval is never "void" nor "universal". -- -- Operations on intervals include intersection ("and"), union ("or"), -- and complement ("not"). Some operations can return an approximate -- result, which is always an over-estimate, in other words, a superset -- of the exact result. Details: -- -- > Intersection ("and") is exact for eu-intervals and for co-intervals -- with intersecting gaps (so that the exact intersection has only -- one gap). This includes all co-intervals that represent signed -- intervals. The intersection of an eu-interval with a co-interval -- can be inexact. The intersection of two co-intervals with non- -- intersecting gaps is always an over-estimate (only one gap is left). -- -- > Union ("or") is exact for all co-intervals and for intersecting -- eu-intervals. The union of an eu-interval with a co-interval can -- be inexact. The union of two non-intersecting eu-intervals is -- always an over-estimate (the values between the two eu-intervals -- are included in the union). (TBA/TBC presenting the union as a -- co-interval, which may be exact or at least more precise.) -- -- > Complement ("not") is always exact (it simply complements Inside). -- -- The presence of an exact complement operation ("not") lets us use the -- De Morgan rules to compute under-estimates of the intersection and -- union of intervals. To compute an under-estimate of the intersection -- "I and J" of two intervals, compute not ((not I) or (not J)). -- Similarly, an under-estimate of the union "I or J" is computed by -- not ((not I) and (not J)). function To_Normal (Item : Word_Interval_T) return Word_Interval_T; -- -- Normalises an "outside" interval with one or both ends Unlimited -- or with Min > Max to the corresponding Inside interval. -- Returns Inside intervals unchanged. If the result is an "outside" -- interval (Inside = False) its Min and Max are both Finite, Min.Value -- is greater than zero, Max.Value is less than Max_Word (Item.Width), -- and Min.Value <= Max.Value. function Void_Word_Interval (Width : Width_T) return Word_Interval_T; -- -- An interval that represents the empty set, with the given Width -- of values. function Universal_Word_Interval (Width : Width_T) return Word_Interval_T; -- -- An interval that contains all values of the given Width. -- It is not defined if the ends are unlimited or limited to -- the extreme values of words of this Width. function Exactly_Zero_Word (Width : Width_T) return Word_Interval_T; -- -- The singleton interval that contains only the value 0, of -- the given Width. function Positive_Interval (Width : Width_T) return Word_Interval_T; -- -- The interval that contains all the positive words of the -- given width, from 1 to Max_Positive (Width). function Eu_Interval (Min, Max : Word_T; Width : Width_T) return Word_Interval_T; -- -- The eu-interval Min .. Max, for values of the given Width. function Interval (Min, Max : Word_T; Width : Width_T) return Word_Interval_T renames Eu_Interval; function Co_Interval (Min, Max : Word_T; Width : Width_T) return Word_Interval_T; -- -- The complement of the interval Min .. Max, for values of -- the given Width. That is, the set of values < Min or > Max. Negative_Limit : exception; -- -- Signals an attempt to convert a negative, signed limit -- to an unsigned limit. function Unsigned_Limit (Item : Limit_T) return Word_Limit_T; -- -- The corresponding unsigned limit, if the given signed -- limit has a non-negative value, or is unlimited. -- If the signed limit has a negative value, the function -- propagates Negative_Limit. function Unsigned_Limit (Value : Value_T) return Word_Limit_T; -- -- The limit (Finite, Word_T (Value)), if Value >= 0, -- else Negative_Limit is propagated. function To_Word_Interval ( Item : Interval_T; Width : Width_T) return Word_Interval_T; -- -- The finite-word interval corresponding to the given -- signed interval, when limited to the given Width. function Min (Item : Word_Interval_T) return Word_T; -- -- Short for Value (Interval.Min). Can raise Unbounded. function Max (Item : Word_Interval_T) return Word_T; -- -- Short for Value (Interval.Max). Can raise Unbounded. function Signed_Min (Item : Word_Interval_T) return Value_T; -- -- Short for Signed_Value (Min (Item), Item.Width). -- Can raise Unbounded. function Signed_Max (Item : Word_Interval_T) return Value_T; -- -- Short for Signed_Value (Max (Item), Item.Width). -- Can raise Unbounded. function Singleton (Value : Word_T; Width : Width_T) return Word_Interval_T; -- -- The one-point interval Value .. Value. function One_Or_All (Value : Word_Limit_T; Width : Width_T) return Word_Interval_T; -- -- The one-point interval Value .. Value if Value is Known, else -- the universal (unlimited) interval. function Void (Item : Word_Interval_T) return Boolean; -- -- Whether the interval represents the empty (void) set. -- In other words, no value can satisfy both the lower-limit -- and the upper-limit. function Known (Interval : Word_Interval_T) return Boolean; -- -- Whether the interval has finite and known (constant) components -- at one or both ends. Note that we do not require both ends -- (min and max) to be finite. function Bounded (Interval : Word_Interval_T) return Boolean; -- -- Whether both ends of the Interval are known and finite. function Universal (Interval : Word_Interval_T) return Boolean; -- -- Whether the Interval contains all values of its width (is -- the universal interval). This is the case if both ends are -- Unlimited, or limited to the minimum or maximum word value -- (0 or Max_Word). function Length (Item : Word_Interval_T) return Word_T; -- -- The maximum difference between any two elements of the -- given non-void interval. For a co-interval, we consider -- the wrapped interval Max + 1 .. Min - 1 + 2**Width. -- The number of values in the interval (the cardinality of -- the interval as a set) is Length + 1. -- -- Precondition: not Void (Item). function Is_In ( Value : Word_T; Interval : Word_Interval_T) return Boolean; -- -- Whether the Value lies in the Interval, using the unsigned view. function "<" (Value : Word_T; Interval : Word_Interval_T) return Boolean; -- -- Whether the Value is less than all values in the Interval. function Singular (Interval : Word_Interval_T) return Boolean; -- -- Whether the Interval allows only a single value (Min and Max -- are constants and equal). The single value in question can -- be retrieved with Single_Value, see below. function Single_Value (Interval : Word_Interval_T) return Word_T; -- -- If the Interval allows a single value, that is if Singular (Interval) -- is True (which means that Min and Max are constants and equal), -- returns this value. -- Otherwise, that is if Singular (Interval) is False, raises -- Multiple_Values. function Signed_Single_Value (Interval : Word_Interval_T) return Value_T; -- -- The signed view of Single_Value (Interval), using the Width -- of the Interval. function Is_Only (Value : Word_T; Interval : Word_Interval_T) return Boolean; -- -- Whether the Interval contains exactly the given Value and -- nothing more. function Is_Only_Zero (Item : Word_Interval_T) return Boolean; -- -- Whether the interval contains only zero and nothing more. function "and" (Left, Right : Word_Interval_T) return Word_Interval_T; -- -- The conjunction (intersection) of two intervals. -- The result may be an over-estimate (superset). function "or" (Left, Right : Word_Interval_T) return Word_Interval_T; -- -- The disjunction (union) of two intervals. -- The result may be an over-estimate (superset). function "not" (Item : Word_Interval_T) return Word_Interval_T; -- -- The complement interval. This just inverts the Item.Inside, so -- it is always an exact complement. procedure Widen ( Interval : in out Word_Interval_T; To_Contain : in Word_T); -- -- Widens the Interval To_Contain the given value, if it does -- not already contain this value. function "<=" (Left, Right : Word_Interval_T) return Boolean; -- -- Whether the Left interval is a subset of the Right interval. -- In other words, the Left interval is narrower than (or the -- same as) the Right interval. Always True if the Left interval -- is Void. function Intersects (Left, Right : Word_Interval_T) return Boolean; -- -- Whether the intersection of the Left and Right intervals is -- non-empty. function "+" (Left : Word_Interval_T; Right : Word_T) return Word_Interval_T; -- -- The Left interval shifted by adding Right to the Min and Max limits. -- If Right is zero, the result is the Left interval unchanged. -- Otherwise, the result is an interval with both ends limited by the -- sum of the Left ends and Right. If the limits wrap around in the -- range of Left.Width, the operation may turn an eu-interval into a -- co-interval or vice versa. function "-" (Left : Word_Interval_T; Right : Word_T) return Word_Interval_T; -- -- The Left interval shifted by subtracting Right from the Min and -- Max limits. The same as Left + Opposite_Sign (Right, Left.Width). function "+" (Left, Right : Word_Interval_T) return Word_Interval_T; -- -- The interval sum of Left and Right. If either operand is -- void, so is the sum. function "-" (Item : Word_Interval_T) return Word_Interval_T; -- -- The interval that contains the values of Opposite_Sign to -- the values in the given interval. function "-" (Left, Right : Word_Interval_T) return Word_Interval_T; -- -- The interval difference of Left - Right. If either operand is -- void, so is the sum. Equivalent to Left + (- Right). function Image (Item : Word_Interval_T) return String; -- -- The interval as "(low limit) .. (high limit)" for an eu-interval, -- or "not (low limit) .. (high limit)" for a co-interval. -- An unknown (unbounded) limit is written as "-inf" or "+inf". -- If the interval is singular, or the complement of a singular -- eu-interval, just the single value is shown (preceded by "not" -- for a co-interval). function Image ( Item : Word_Interval_T; Name : String) return String; -- -- The Name is used to denote the value (cell or expression) -- to which the bound applies. The result has one of the forms: -- -- min <= Name <= max for a bounded eu-interval -- min <= Name for an eu-interval with only lower bound -- Name <= max for an eu-interval with only upper bound -- Name for an unbounded eu-interval -- Name = value for a singular eu-interval -- Name /= value for the co-interval of a singular eu-interval -- Name not min .. max for other co-intervals. function Image ( Item : Word_Interval_T; Cell : Cell_T) return String; -- -- Same as Image (Item, Image (Cell)). type Word_Interval_List_T is array (Positive range <>) of Word_Interval_T; -- -- A set of interval bounds on word values. -- The value (cell or expression) to which each interval applies -- must be known from context. type Word_List_T is array (Positive range <>) of Word_T; -- -- A list of word values. The indexing and meaning depend on usage. -- The width of the words must be known from context. function Single_Value (Intervals : Word_Interval_List_T) return Word_List_T; -- -- The list of single values allowed by each of the listed singular -- Intervals. If some of the Intervals are not singular the function -- propagates Multiple_Values. function Image ( Item : Word_Interval_List_T; Prefix : String) return String; -- -- Describes each interval in the list, using a Name for the -- bounded value composed from the Prefix and the index of -- the interval in the list. -- --- Intervals of binary words for cells -- -- These are not yet "bounds", but can be derived from bounds and can -- be used to construct bounds. type Cell_Word_Interval_T is record Cell : Cell_T; Interval : Word_Interval_T; end record; -- -- An interval that bounds the value of a cell, viewed as a binary -- word. Normally Interval.Width = Width_Of (Cell). type Cell_Word_Interval_List_T is array (Positive range <>) of Cell_Word_Interval_T; -- -- A set of interval bounds on cell values, giving both the cells -- and the value-interval for each cell, viewed as a binary word. function Empty return Cell_Word_Interval_List_T; -- -- An empty (null) list of cell-interval bounds. function Interval ( Cell : Storage.Cell_T; From : Cell_Word_Interval_List_T) return Word_Interval_T; -- -- The interval bounds on the given Cell, taken From the given list. -- If the list has several interval bounds for the cell, their -- conjunction (intersection) is returned. If the list has no interval -- bounds for the cell, Universal_Interval is returned. function Intervals_For_Cells ( Cells : Cell_Set_T; From : Cell_Word_Interval_List_T) return Cell_Word_Interval_List_T; -- -- Returns the interval bounds From the list on the given Cells. -- If a cell from Cells occurs several times in the From list, it -- will occur as many times in the result. function "and" (Left, Right : Cell_Word_Interval_List_T) return Cell_Word_Interval_List_T; -- -- The conjunction of the two lists of interval bounds on cells. -- If the same cell is mentioned in both lists, it occurs -- but once in the result, with the conjunction (intersection) -- of the intervals from all its ocurrences. -- If a cell is mentioned only in one of the two lists, that list -- defines the interval for the cell in the result. function Image (Item : Cell_Word_Interval_T) return String; -- -- As in Image (Item => Item.Bound, Name => Image (Item.Cell)). function Image (Item : Cell_Word_Interval_List_T) return String; -- -- Describes the bounds as a list of Image (Bound, Image(Cell)). function Cells_Of (Item : Cell_Word_Interval_List_T) return Cell_List_T; -- -- All the cells in the given list of cells and intervals, in the -- same order and with possible duplicates. -- --- Intervals of binary words for variables with moving locations -- -- These are not yet "bounds", nor can they be derived from bounds, but -- they can be used to construct bounds when the point in the program is -- known so that the variable can be associated with a cell. type Var_Word_Interval_T is record Location : Location_Ref; Interval : Word_Interval_T; end record; -- -- Interval bounds on the value of a variable that may occupy different -- storage locations at different points in the program, when the value -- is viewed as a binary word. type Var_Word_Interval_List_T is array (Positive range <>) of Var_Word_Interval_T; -- -- A set of interval bounds on variable values, giving both the location -- of each variable (possibly varying with the execution point) and -- the interval that bounds each variable, when the values are viewed -- as binary words. function "and" (Left, Right : Var_Word_Interval_List_T) return Var_Word_Interval_List_T; -- -- The conjunction of the two lists of interval bounds in variables. -- If the same variable (same location-ref) is mentioned in both lists, -- it occurs but once in the result, with the conjunction (intersection) -- of the intervals from all its ocurrences. -- If a variable is mentioned only in one of the two lists, that list -- defines the interval for the variable in the result. -- Variables are identified by the locations (reference equality). function Cell_Intervals ( From : Var_Word_Interval_List_T; Point : Processor.Code_Address_T) return Cell_Word_Interval_List_T; -- -- Interval bounds on cell values derived From interval bounds on -- variables by mapping the location of each variable to a cell at -- the given Point in the target program. -- -- If a variable maps to several cells at this point, the bounds for -- the variable are applied to each cell in the result. -- -- If a variable maps to no cells at this point, the bounds for the -- variable are not used in the result. -- -- If several variables map to the same cell at this point, the bounds -- for these variables are conjoined (intersected) to give the bounds -- on this cell in the result. -- --- Lists (enumerations) of binary word values -- -- These are not yet "bounds" but can be derived from bounds. -- -- Some "bounds" can yield a list of possible values for the -- bounded variable(s). This will usually be an ordered list -- (ascending order) without duplicates. function Values (Within : Word_Interval_T) return Word_List_T; -- -- All the values Within the interval, assuming that the interval -- is fully Bounded, else Unbounded is raised. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. For an "outside" interval the result -- can contain twice this number of values, because the low end -- and high end are handled separately as two Inside intervals. function "-" (Left, Right : Word_Interval_T) return Word_List_T; -- -- All the values allowed by Left, except the values also -- allowed by Right. In other words, the difference between -- the set defined by Left and the set defined by Right. -- All limits involved must be known constants, otherwise -- Unbounded is raised. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. subtype Positive_Word_T is Word_T range 1 .. Word_T'Last; -- -- The non-zero values of binary words. function Values (Within : Word_Interval_T; Aligned : Positive_Word_T) return Word_List_T; -- -- All the values that are Within the given interval and are -- also integral multiples of Aligned, assuming that the interval -- is fully Bounded, else Unbounded is raised. -- TBD if the limits must be multiples of Aligned. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. function Difference ( Included : Word_Interval_T; Excluded : Word_Interval_T; Aligned : Positive_Word_T) return Word_List_T; -- -- All the values allowed by the Included interval, except the -- values also allowed by the Excluded interval, and considering -- only those values that are integral multiples of Aligned. -- All limits involved must be known constants, otherwise the -- Unbounded exception is raised. -- -- The result equals Values (Included and not Excluded, Aligned) if -- the intersection ("and") is computed exactly. Otherwise, the -- result from Difference is more exact that from the Values call. -- -- TBD if the limits must be multiples of Aligned. -- -- If the number of values would exceed Opt.Max_Listed_Values the -- function raises Unbounded. -- --- Bounds on variables in the abstract -- type Bounds_T is abstract tagged null record; -- -- Bounds (constraints, limits, restrictions) on the (joint or -- separate) values of a set of variables at some point(s) in a -- program or an execution. function Basis (Item : Bounds_T) return Cell_List_T is abstract; -- -- The cells that the Item bounds. The list may be empty, although -- this is a degenerate case as the Item is then useless; it does -- not constrain any cell values. -- -- Depending on the type of Item, the bounds may or may not imply -- bounds (eg. an interval) for each cell in the basis. Some types -- of bounds may only imply relationships between the values of -- the cells without constraining the value of an individual cell. function Interval (Cell : Cell_T; Under : Bounds_T) return Interval_T is abstract; -- -- The interval (range) of values of the Cell, permitted Under the -- given Bounds. Note that the Cell does not necessarily take on -- every value in this interval. The function shall not propagate -- Unbounded but may return an interval where either or both the -- Min and Max are unlimited. function Difference (To, From : Cell_T; Under : Bounds_T) return Interval_T; -- -- The interval (range) of values of the difference To - From -- between two cells, permitted Under the given Bounds. Note that -- the difference does not necessarily take on every value in -- this interval. The function shall not propagate Unbounded but -- may return an interval where either or both the Min and Max -- are unlimited. -- -- The default operation computes the interval-arithmetic -- difference Interval (To, Under) - Interval (From, Under), -- with (of course) redispatching on Under. function Intervals (Under : Bounds_T) return Cell_Interval_List_T; -- -- The list of Basis cells and the Interval permitted for each -- basis cell, Under the given bounds. -- -- The default operation applies the Basis and Interval functions. function Value (Cell : Cell_T; Under : Bounds_T) return Value_T; -- -- The single value of the Cell permitted Under the given bounds. -- Propagates Unbounded if the bounds do not constrain the cell -- to a single value. -- -- The default operation is Single_Value (Interval (Cell, Under)). function Values (Cell : Cell_T; Under : Bounds_T) return Value_List_T; -- -- The list of possible values of the Cell, permitted Under the -- given Bounds. This list should contain all and only the possible -- values of the Cell. If such a list cannot be derived from the -- bounds, the function should propagate Unbounded. -- -- The maximum length of the returned list may be bounded by a -- command-line option. -- -- The default operation is Values (Interval (Cell, Under)). function Image (Item : Bounds_T) return String; -- -- Textual description of the bounds object. -- -- The default implementation displays the Expanded_Name -- of the Item's tag. function Full_Image (Item : Bounds_T) return String; -- -- Textual description of the bounds object including the -- basis cells and the bounds placed on the basis cells. -- -- The default implementation displays Image followed by the -- Interval bounds on each of the Basis cells. type Bounds_Ref is access all Bounds_T'Class; -- -- A reference to some kind of bounds. --:dbpool Bounds_Pool : GNAT.Debug_Pools.Debug_Pool; --:dbpool for Bounds_Ref'Storage_Pool use Bounds_Pool; procedure Discard (Item : in out Bounds_Ref); -- -- Discards (deallocates) a heap-allocated bounds Item. -- As for all unchecked-deallocation, the user must be careful -- with dangling references. type Bounds_List_T is array (Positive range <>) of Bounds_Ref; -- -- A list of references to some kind(s) of bounds. -- The significance, if any, of the indices and the order -- depends on the context and usage. procedure Discard (List : in out Bounds_List_T); -- -- Discards all bounds objects in the List using unchecked -- deallocation. -- -- The bottom: no bounds at all. -- type No_Bounds_T is new Bounds_T with null record; -- -- A class of bounds that places no bounds on any cells at all. function Basis (Item : No_Bounds_T) return Cell_List_T; -- -- The empty list. -- Overrides (implements) Basis (Bounds_T). function Interval (Cell : Cell_T; Under : No_Bounds_T) return Interval_T; -- -- The universal interval. -- Overrides (implements) Interval (Bounds_T). function No_Bounds return Bounds_Ref; -- -- A reference to a specific No_Bounds object that is created -- at package elaboration, so the returned value is constant. -- There is really no need for any other objects of this type -- since they would all behave the same way. -- -- Bounds composed of single values -- -- The simplest type of "bounds" defines a single value for each cell -- in the basis. The set of allowed cell-tuple values is the single -- tuple where each basis cell has the single allowed value. type Singular_Bounds_T (Length : Positive) is new Bounds_T with record List : Cell_Value_List_T (1 .. Length); end record; -- -- Bounds each List.Cell to the single corresponding List.Value and -- no other. function Basis (Item : Singular_Bounds_T) return Cell_List_T; -- -- Overrides (implements) Basis for Bounds. function Interval (Cell : Cell_T; Under : Singular_Bounds_T) return Interval_T; -- -- Overrides (implements) Interval for Bounds. function Value (Cell : Cell_T; Under : Singular_Bounds_T) return Value_T; -- -- Overrides Value for Bounds. function Singular_Bounds (List : Cell_Value_List_T) return Singular_Bounds_T; -- -- Converts a list of cells and their values to a Bounds_T'Class. -- -- Bounds composed of intervals -- -- One (rather simple) type of "bounds" defines an interval for -- each cell in the basis. Thus, no interaction between cells is -- modelled. The set of allowed cell-tuple values is the cartesian -- product of the intervals for each cell. type Interval_Bounds_T (Length : Positive) is new Bounds_T with record List : Cell_Interval_List_T (1 .. Length); end record; -- -- Bounds each List.Cell to the corresponding List.Interval. function Basis (Item : Interval_Bounds_T) return Cell_List_T; -- -- Overrides (implements) Basis for Bounds. function Interval (Cell : Cell_T; Under : Interval_Bounds_T) return Interval_T; -- -- Overrides (implements) Interval for Bounds. function Interval_Bounds (List : Cell_Interval_List_T) return Interval_Bounds_T; -- -- Converts a list of interval bounds on cell values to -- a Bounds_T'Class. function Interval_Bounds ( From : Var_Interval_List_T; Point : Processor.Code_Address_T) return Bounds_Ref; -- -- The Bounds_T object created From a list of interval bounds on -- variables, mapped to the corresponding cells at a given Point, -- and stored in the heap. The object is of type Interval_Bounds_T -- or No_Bounds_T. -- -- Boundable things -- type Boundable_T is abstract tagged null record; -- -- A thing that can be bounded (constrained, refined) by some bounds -- because the meaning (nature, result, effect) of the thing depends on -- the values of some variables (cells) at the point in the program -- (or execution) where the boundable thing resides (or is executed). function Basis (Item : Boundable_T) return Cell_List_T is abstract; -- -- The cells on which the boundable Item depends. The list is usually -- non-empty, as otherwise the Item must be statically known and is -- not really "boundable". -- -- The main purpose of this function is to tell various analysis -- algorithms which cells should be bounded in order to bound this -- Item. procedure Add_Basis_Cells ( From : in Boundable_T; To : in out Cell_Set_T); -- -- Adds all the cells From the boundable Item's Basis set To the -- given set of cells. -- -- The default implementation uses the Basis function, which may be -- inefficient. procedure Add_Basis_Cells ( From : in Boundable_T; To : in out Cell_Set_T; Added : in out Boolean); -- -- Adds all the cells From the boundable Item's Basis set To the -- given set of cells. If some of the added cells were not already -- in the set, Added is set to True, otherwise (no change in the -- set) Added is not changed. -- -- The default implementation uses the Basis function, which may be -- inefficient. function Is_Used (Cell : Cell_T; By : Boundable_T) return Boolean; -- -- Whether the given Cell is used By the boundable, in other words -- whether the Cell belongs to the Basis of the boundable. -- -- The default implementation uses the Basis function, which is -- likely to be inefficient. function Image (Item : Boundable_T) return String; -- -- Textual description of the boundable object. -- -- The default implementation displays the Expanded_Name -- of the Item's tag. type Resolution_T is ( Fail_Changed, Changed, Fail_Stable, Stable); -- -- The overall result of applying some "bounds" to a "boundable" -- object. -- -- Fail_Changed -- The boundable object was changed (elaborated or constrained) -- by the bounds, but at the same time some sort of failure was -- detected which means that the boundable object cannot be -- analyzed further but should be deleted, perhaps leaving some -- space-holder or dummy object. The details of the deletion and -- the possible dummy object depend on the specific kind of -- boundable object and its role. However, since the object was -- changed, the program model should be re-analyzed or the -- analysis should be updated to include this change. -- -- Changed -- The boundable object was successfully changed by the bounds, -- so that the program model must be re-analyzed to include -- the change. Moreover, the boundable object retains some -- dynamic characteristics, so if the program re-analysis leads -- to sharper bounds the new bounds should again be applied to -- this boundable object. -- -- Fail_Stable -- Some sort of failure was detected which means that the -- boundable object cannot be analyzed further. The object was -- not changed but should be deleted as for Fail_Changed. -- -- Stable -- The bounds were successfully applied to the boundable object -- but did not change the object. The analysis of this object -- has reached a stable point. When all boundable objects in -- the program model are stable, the analysis of the model -- has converged (as far as dynamic bounding is concerned). -- -- The elements are listed in such an order that the combined -- result of two Resolution_T values is the "lesser" (earlier) -- of the two. For example Changed+Stable => Changed, -- and Fail_Changed+anything => Fail_Changed. procedure Apply ( Bounds : in Bounds_T'Class; Upon : in out Boundable_T; Result : out Resolution_T); -- -- Applies the Bounds Upon a thing, perhaps modifying the thing, -- as shown by the Result value. -- -- This operation is primitive (and thus overridable and dispatchable) -- for Boundable_T, but class-wide for Bounds_T. Thus, the general -- parts of Bound-T are transparent to whatever sorts of boundable -- things the processor-specific parts define, while the processor- -- specific parts must depend on the sort of "bounds" that the -- general analysis can compute. -- -- The Apply operation at this level is probably too general to -- be useful, because it can only affect the boundable thing itself -- and not, for example, the program-model of which this thing is a -- part. Therefore, we provide a default, do-nothing implementation -- that simply returns Result as Stable. -- -- The next derivation level of Boundable_T will define more useful -- derived types such as dynamic memory references and dynamic jumps. type Boundable_Ref is access Boundable_T'Class; -- -- A reference to some kind of boundable thing. end Storage.Bounds;
sungyeon/drake
Ada
18,949
ads
pragma License (Unrestricted); package Ada.Characters.Latin_1 is pragma Pure; -- Control characters: NUL : constant Character := Character'Val (0); SOH : constant Character := Character'Val (1); STX : constant Character := Character'Val (2); ETX : constant Character := Character'Val (3); EOT : constant Character := Character'Val (4); ENQ : constant Character := Character'Val (5); ACK : constant Character := Character'Val (6); BEL : constant Character := Character'Val (7); BS : constant Character := Character'Val (8); HT : constant Character := Character'Val (9); LF : constant Character := Character'Val (10); VT : constant Character := Character'Val (11); FF : constant Character := Character'Val (12); CR : constant Character := Character'Val (13); SO : constant Character := Character'Val (14); SI : constant Character := Character'Val (15); DLE : constant Character := Character'Val (16); DC1 : constant Character := Character'Val (17); DC2 : constant Character := Character'Val (18); DC3 : constant Character := Character'Val (19); DC4 : constant Character := Character'Val (20); NAK : constant Character := Character'Val (21); SYN : constant Character := Character'Val (22); ETB : constant Character := Character'Val (23); CAN : constant Character := Character'Val (24); EM : constant Character := Character'Val (25); SUB : constant Character := Character'Val (26); ESC : constant Character := Character'Val (27); FS : constant Character := Character'Val (28); GS : constant Character := Character'Val (29); RS : constant Character := Character'Val (30); US : constant Character := Character'Val (31); -- ISO 646 graphic characters: Space : constant Character := Character'Val (32); -- ' ' Exclamation : constant Character := Character'Val (33); -- '!' Quotation : constant Character := Character'Val (34); -- '"' Number_Sign : constant Character := Character'Val (35); -- '#' Dollar_Sign : constant Character := Character'Val (36); -- '$' Percent_Sign : constant Character := Character'Val (37); -- '%' Ampersand : constant Character := Character'Val (38); -- '&' Apostrophe : constant Character := Character'Val (39); -- ''' Left_Parenthesis : constant Character := Character'Val (40); -- '(' Right_Parenthesis : constant Character := Character'Val (41); -- ')' Asterisk : constant Character := Character'Val (42); -- '*' Plus_Sign : constant Character := Character'Val (43); -- '+' Comma : constant Character := Character'Val (44); -- ',' Hyphen : constant Character := Character'Val (45); -- '-' Minus_Sign : Character renames Hyphen; Full_Stop : constant Character := Character'Val (46); -- '.' Solidus : constant Character := Character'Val (47); -- '/' -- Decimal digits '0' though '9' are at positions 48 through 57 Colon : constant Character := Character'Val (58); -- ':' Semicolon : constant Character := Character'Val (59); -- ';' Less_Than_Sign : constant Character := Character'Val (60); -- '<' Equals_Sign : constant Character := Character'Val (61); -- '=' Greater_Than_Sign : constant Character := Character'Val (62); -- '>' Question : constant Character := Character'Val (63); -- '?' Commercial_At : constant Character := Character'Val (64); -- '@' -- Letters 'A' through 'Z' are at positions 65 through 90 Left_Square_Bracket : constant Character := Character'Val (91); -- '[' Reverse_Solidus : constant Character := Character'Val (92); -- '\' Right_Square_Bracket : constant Character := Character'Val (93); -- ']' Circumflex : constant Character := Character'Val (94); -- '^' Low_Line : constant Character := Character'Val (95); -- '_' Grave : constant Character := Character'Val (96); -- '`' LC_A : constant Character := Character'Val (97); -- 'a' LC_B : constant Character := Character'Val (98); -- 'b' LC_C : constant Character := Character'Val (99); -- 'c' LC_D : constant Character := Character'Val (100); -- 'd' LC_E : constant Character := Character'Val (101); -- 'e' LC_F : constant Character := Character'Val (102); -- 'f' LC_G : constant Character := Character'Val (103); -- 'g' LC_H : constant Character := Character'Val (104); -- 'h' LC_I : constant Character := Character'Val (105); -- 'i' LC_J : constant Character := Character'Val (106); -- 'j' LC_K : constant Character := Character'Val (107); -- 'k' LC_L : constant Character := Character'Val (108); -- 'l' LC_M : constant Character := Character'Val (109); -- 'm' LC_N : constant Character := Character'Val (110); -- 'n' LC_O : constant Character := Character'Val (111); -- 'o' LC_P : constant Character := Character'Val (112); -- 'p' LC_Q : constant Character := Character'Val (113); -- 'q' LC_R : constant Character := Character'Val (114); -- 'r' LC_S : constant Character := Character'Val (115); -- 's' LC_T : constant Character := Character'Val (116); -- 't' LC_U : constant Character := Character'Val (117); -- 'u' LC_V : constant Character := Character'Val (118); -- 'v' LC_W : constant Character := Character'Val (119); -- 'w' LC_X : constant Character := Character'Val (120); -- 'x' LC_Y : constant Character := Character'Val (121); -- 'y' LC_Z : constant Character := Character'Val (122); -- 'z' Left_Curly_Bracket : constant Character := Character'Val (123); -- '{' Vertical_Line : constant Character := Character'Val (124); -- '|' Right_Curly_Bracket : constant Character := Character'Val (125); -- '}' Tilde : constant Character := Character'Val (126); -- '~' DEL : constant Character := Character'Val (127); -- ISO 6429 control characters: IS4 : Character renames FS; IS3 : Character renames GS; IS2 : Character renames RS; IS1 : Character renames US; -- modified from here -- These constants are stored as UTF-8 as a String. Reserved_128 : constant String := Character'Val (16#c2#) & Character'Val (16#80#); Reserved_129 : constant String := Character'Val (16#c2#) & Character'Val (16#81#); BPH : constant String := Character'Val (16#c2#) & Character'Val (16#82#); NBH : constant String := Character'Val (16#c2#) & Character'Val (16#83#); Reserved_132 : constant String := Character'Val (16#c2#) & Character'Val (16#84#); NEL : constant String := Character'Val (16#c2#) & Character'Val (16#85#); SSA : constant String := Character'Val (16#c2#) & Character'Val (16#86#); ESA : constant String := Character'Val (16#c2#) & Character'Val (16#87#); HTS : constant String := Character'Val (16#c2#) & Character'Val (16#88#); HTJ : constant String := Character'Val (16#c2#) & Character'Val (16#89#); VTS : constant String := Character'Val (16#c2#) & Character'Val (16#8a#); PLD : constant String := Character'Val (16#c2#) & Character'Val (16#8b#); PLU : constant String := Character'Val (16#c2#) & Character'Val (16#8c#); RI : constant String := Character'Val (16#c2#) & Character'Val (16#8d#); SS2 : constant String := Character'Val (16#c2#) & Character'Val (16#8e#); SS3 : constant String := Character'Val (16#c2#) & Character'Val (16#8f#); DCS : constant String := Character'Val (16#c2#) & Character'Val (16#90#); PU1 : constant String := Character'Val (16#c2#) & Character'Val (16#91#); PU2 : constant String := Character'Val (16#c2#) & Character'Val (16#92#); STS : constant String := Character'Val (16#c2#) & Character'Val (16#93#); CCH : constant String := Character'Val (16#c2#) & Character'Val (16#94#); MW : constant String := Character'Val (16#c2#) & Character'Val (16#95#); SPA : constant String := Character'Val (16#c2#) & Character'Val (16#96#); EPA : constant String := Character'Val (16#c2#) & Character'Val (16#97#); SOS : constant String := Character'Val (16#c2#) & Character'Val (16#98#); Reserved_153 : constant String := Character'Val (16#c2#) & Character'Val (16#99#); SCI : constant String := Character'Val (16#c2#) & Character'Val (16#9a#); CSI : constant String := Character'Val (16#c2#) & Character'Val (16#9b#); ST : constant String := Character'Val (16#c2#) & Character'Val (16#9c#); OSC : constant String := Character'Val (16#c2#) & Character'Val (16#9d#); PM : constant String := Character'Val (16#c2#) & Character'Val (16#9e#); APC : constant String := Character'Val (16#c2#) & Character'Val (16#9f#); -- Other graphic characters: -- Character positions 160 (16#A0#) .. 175 (16#AF#): No_Break_Space : constant String := Character'Val (16#c2#) & Character'Val (16#a0#); -- ' ' NBSP : String renames No_Break_Space; Inverted_Exclamation : constant String := Character'Val (16#c2#) & Character'Val (16#a1#); -- '¡' Cent_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a2#); -- '¢' Pound_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a3#); -- '£' Currency_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a4#); -- '¤' Yen_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a5#); -- '¥' Broken_Bar : constant String := Character'Val (16#c2#) & Character'Val (16#a6#); -- '¦' Section_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a7#); -- '§' Diaeresis : constant String := Character'Val (16#c2#) & Character'Val (16#a8#); -- '¨' Copyright_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#a9#); -- '©' Feminine_Ordinal_Indicator : constant String := Character'Val (16#c2#) & Character'Val (16#aa#); -- 'ª' Left_Angle_Quotation : constant String := Character'Val (16#c2#) & Character'Val (16#ab#); -- '«' Not_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#ac#); -- '¬' Soft_Hyphen : constant String := Character'Val (16#c2#) & Character'Val (16#ad#); -- ' ' Registered_Trade_Mark_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#ae#); -- '®' Macron : constant String := Character'Val (16#c2#) & Character'Val (16#af#); -- '¯' -- Character positions 176 (16#B0#) .. 191 (16#BF#): Degree_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#b0#); -- '°' Ring_Above : String renames Degree_Sign; Plus_Minus_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#b1#); -- '±' Superscript_Two : constant String := Character'Val (16#c2#) & Character'Val (16#b2#); -- '²' Superscript_Three : constant String := Character'Val (16#c2#) & Character'Val (16#b3#); -- '³' Acute : constant String := Character'Val (16#c2#) & Character'Val (16#b4#); -- '´' Micro_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#b5#); -- 'µ' Pilcrow_Sign : constant String := Character'Val (16#c2#) & Character'Val (16#b6#); -- '¶' Paragraph_Sign : String renames Pilcrow_Sign; Middle_Dot : constant String := Character'Val (16#c2#) & Character'Val (16#b7#); -- '·' Cedilla : constant String := Character'Val (16#c2#) & Character'Val (16#b8#); -- '¸' Superscript_One : constant String := Character'Val (16#c2#) & Character'Val (16#b9#); -- '¹' Masculine_Ordinal_Indicator : constant String := Character'Val (16#c2#) & Character'Val (16#ba#); -- 'º' Right_Angle_Quotation : constant String := Character'Val (16#c2#) & Character'Val (16#bb#); -- '»' Fraction_One_Quarter : constant String := Character'Val (16#c2#) & Character'Val (16#bc#); -- '¼' Fraction_One_Half : constant String := Character'Val (16#c2#) & Character'Val (16#bd#); -- '½' Fraction_Three_Quarters : constant String := Character'Val (16#c2#) & Character'Val (16#be#); -- '¾' Inverted_Question : constant String := Character'Val (16#c2#) & Character'Val (16#bf#); -- '¿' -- Character positions 192 (16#C0#) .. 207 (16#CF#): UC_A_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#80#); -- 'À' UC_A_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#81#); -- 'Á' UC_A_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#82#); -- 'Â' UC_A_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#83#); -- 'Ã' UC_A_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#84#); -- 'Ä' UC_A_Ring : constant String := Character'Val (16#c3#) & Character'Val (16#85#); -- 'Å' UC_AE_Diphthong : constant String := Character'Val (16#c3#) & Character'Val (16#86#); -- 'Æ' UC_C_Cedilla : constant String := Character'Val (16#c3#) & Character'Val (16#87#); -- 'Ç' UC_E_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#88#); -- 'È' UC_E_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#89#); -- 'É' UC_E_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#8a#); -- 'Ê' UC_E_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#8b#); -- 'Ë' UC_I_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#8c#); -- 'Ì' UC_I_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#8d#); -- 'Í' UC_I_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#8e#); -- 'Î' UC_I_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#8f#); -- 'Ï' -- Character positions 208 (16#D0#) .. 223 (16#DF#): UC_Icelandic_Eth : constant String := Character'Val (16#c3#) & Character'Val (16#90#); -- 'Ð' UC_N_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#91#); -- 'Ñ' UC_O_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#92#); -- 'Ò' UC_O_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#93#); -- 'Ó' UC_O_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#94#); -- 'Ô' UC_O_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#95#); -- 'Õ' UC_O_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#96#); -- 'Ö' Multiplication_Sign : constant String := Character'Val (16#c3#) & Character'Val (16#97#); -- '×' UC_O_Oblique_Stroke : constant String := Character'Val (16#c3#) & Character'Val (16#98#); -- 'Ø' UC_U_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#99#); -- 'Ù' UC_U_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#9a#); -- 'Ú' UC_U_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#9b#); -- 'Û' UC_U_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#9c#); -- 'Ü' UC_Y_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#9d#); -- 'Ý' UC_Icelandic_Thorn : constant String := Character'Val (16#c3#) & Character'Val (16#9e#); -- 'Þ' LC_German_Sharp_S : constant String := Character'Val (16#c3#) & Character'Val (16#9f#); -- 'ß' -- Character positions 224 (16#E0#) .. 239 (16#EF#): LC_A_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#a0#); -- 'à' LC_A_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#a1#); -- 'á' LC_A_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#a2#); -- 'â' LC_A_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#a3#); -- 'ã' LC_A_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#a4#); -- 'ä' LC_A_Ring : constant String := Character'Val (16#c3#) & Character'Val (16#a5#); -- 'å' LC_AE_Diphthong : constant String := Character'Val (16#c3#) & Character'Val (16#a6#); -- 'æ' LC_C_Cedilla : constant String := Character'Val (16#c3#) & Character'Val (16#a7#); -- 'ç' LC_E_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#a8#); -- 'è' LC_E_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#a9#); -- 'é' LC_E_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#aa#); -- 'ê' LC_E_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#ab#); -- 'ë' LC_I_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#ac#); -- 'ì' LC_I_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#ad#); -- 'í' LC_I_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#ae#); -- 'î' LC_I_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#af#); -- 'ï' -- Character positions 240 (16#F0#) .. 255 (16#FF#): LC_Icelandic_Eth : constant String := Character'Val (16#c3#) & Character'Val (16#b0#); -- 'ð' LC_N_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#b1#); -- 'ñ' LC_O_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#b2#); -- 'ò' LC_O_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#b3#); -- 'ó' LC_O_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#b4#); -- 'ô' LC_O_Tilde : constant String := Character'Val (16#c3#) & Character'Val (16#b5#); -- 'õ' LC_O_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#b6#); -- 'ö' Division_Sign : constant String := Character'Val (16#c3#) & Character'Val (16#b7#); -- '÷'; LC_O_Oblique_Stroke : constant String := Character'Val (16#c3#) & Character'Val (16#b8#); -- 'ø' LC_U_Grave : constant String := Character'Val (16#c3#) & Character'Val (16#b9#); -- 'ù' LC_U_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#ba#); -- 'ú' LC_U_Circumflex : constant String := Character'Val (16#c3#) & Character'Val (16#bb#); -- 'û'; LC_U_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#bc#); -- 'ü' LC_Y_Acute : constant String := Character'Val (16#c3#) & Character'Val (16#bd#); -- 'ý' LC_Icelandic_Thorn : constant String := Character'Val (16#c3#) & Character'Val (16#be#); -- 'þ' LC_Y_Diaeresis : constant String := Character'Val (16#c3#) & Character'Val (16#bf#); -- 'ÿ' end Ada.Characters.Latin_1;
reznikmm/matreshka
Ada
35,699
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ with AMF.Elements; with AMF.Internals.Element_Collections; with AMF.Internals.Helpers; with AMF.Internals.Tables.UML_Attributes; with AMF.Visitors.UML_Iterators; with AMF.Visitors.UML_Visitors; with League.Strings.Internals; with Matreshka.Internals.Strings; package body AMF.Internals.UML_Sequence_Nodes is ------------------- -- Enter_Element -- ------------------- overriding procedure Enter_Element (Self : not null access constant UML_Sequence_Node_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Enter_Sequence_Node (AMF.UML.Sequence_Nodes.UML_Sequence_Node_Access (Self), Control); end if; end Enter_Element; ------------------- -- Leave_Element -- ------------------- overriding procedure Leave_Element (Self : not null access constant UML_Sequence_Node_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.UML_Visitors.UML_Visitor'Class then AMF.Visitors.UML_Visitors.UML_Visitor'Class (Visitor).Leave_Sequence_Node (AMF.UML.Sequence_Nodes.UML_Sequence_Node_Access (Self), Control); end if; end Leave_Element; ------------------- -- Visit_Element -- ------------------- overriding procedure Visit_Element (Self : not null access constant UML_Sequence_Node_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Iterator in AMF.Visitors.UML_Iterators.UML_Iterator'Class then AMF.Visitors.UML_Iterators.UML_Iterator'Class (Iterator).Visit_Sequence_Node (Visitor, AMF.UML.Sequence_Nodes.UML_Sequence_Node_Access (Self), Control); end if; end Visit_Element; ------------------------- -- Get_Executable_Node -- ------------------------- overriding function Get_Executable_Node (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Executable_Nodes.Collections.Ordered_Set_Of_UML_Executable_Node is begin return AMF.UML.Executable_Nodes.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Executable_Node (Self.Element))); end Get_Executable_Node; ------------------ -- Get_Activity -- ------------------ overriding function Get_Activity (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activities.UML_Activity_Access is begin return AMF.UML.Activities.UML_Activity_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Activity (Self.Element))); end Get_Activity; ------------------ -- Set_Activity -- ------------------ overriding procedure Set_Activity (Self : not null access UML_Sequence_Node_Proxy; To : AMF.UML.Activities.UML_Activity_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Activity (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Activity; -------------- -- Get_Edge -- -------------- overriding function Get_Edge (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Edges.Collections.Set_Of_UML_Activity_Edge is begin return AMF.UML.Activity_Edges.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Edge (Self.Element))); end Get_Edge; ---------------------- -- Get_Must_Isolate -- ---------------------- overriding function Get_Must_Isolate (Self : not null access constant UML_Sequence_Node_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Must_Isolate (Self.Element); end Get_Must_Isolate; ---------------------- -- Set_Must_Isolate -- ---------------------- overriding procedure Set_Must_Isolate (Self : not null access UML_Sequence_Node_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Must_Isolate (Self.Element, To); end Set_Must_Isolate; -------------- -- Get_Node -- -------------- overriding function Get_Node (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Nodes.Collections.Set_Of_UML_Activity_Node is begin return AMF.UML.Activity_Nodes.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Node (Self.Element))); end Get_Node; ------------------------------- -- Get_Structured_Node_Input -- ------------------------------- overriding function Get_Structured_Node_Input (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Input_Pins.Collections.Set_Of_UML_Input_Pin is begin return AMF.UML.Input_Pins.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Structured_Node_Input (Self.Element))); end Get_Structured_Node_Input; -------------------------------- -- Get_Structured_Node_Output -- -------------------------------- overriding function Get_Structured_Node_Output (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Output_Pins.Collections.Set_Of_UML_Output_Pin is begin return AMF.UML.Output_Pins.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Structured_Node_Output (Self.Element))); end Get_Structured_Node_Output; ------------------ -- Get_Variable -- ------------------ overriding function Get_Variable (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Variables.Collections.Set_Of_UML_Variable is begin return AMF.UML.Variables.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Variable (Self.Element))); end Get_Variable; ------------------------ -- Get_Element_Import -- ------------------------ overriding function Get_Element_Import (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Element_Imports.Collections.Set_Of_UML_Element_Import is begin return AMF.UML.Element_Imports.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Element_Import (Self.Element))); end Get_Element_Import; ------------------------- -- Get_Imported_Member -- ------------------------- overriding function Get_Imported_Member (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin return AMF.UML.Packageable_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Imported_Member (Self.Element))); end Get_Imported_Member; ---------------- -- Get_Member -- ---------------- overriding function Get_Member (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin return AMF.UML.Named_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Member (Self.Element))); end Get_Member; ---------------------- -- Get_Owned_Member -- ---------------------- overriding function Get_Owned_Member (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin return AMF.UML.Named_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Member (Self.Element))); end Get_Owned_Member; -------------------- -- Get_Owned_Rule -- -------------------- overriding function Get_Owned_Rule (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint is begin return AMF.UML.Constraints.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Owned_Rule (Self.Element))); end Get_Owned_Rule; ------------------------ -- Get_Package_Import -- ------------------------ overriding function Get_Package_Import (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Package_Imports.Collections.Set_Of_UML_Package_Import is begin return AMF.UML.Package_Imports.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Package_Import (Self.Element))); end Get_Package_Import; --------------------------- -- Get_Client_Dependency -- --------------------------- overriding function Get_Client_Dependency (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency is begin return AMF.UML.Dependencies.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Client_Dependency (Self.Element))); end Get_Client_Dependency; ------------------------- -- Get_Name_Expression -- ------------------------- overriding function Get_Name_Expression (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.String_Expressions.UML_String_Expression_Access is begin return AMF.UML.String_Expressions.UML_String_Expression_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Name_Expression (Self.Element))); end Get_Name_Expression; ------------------------- -- Set_Name_Expression -- ------------------------- overriding procedure Set_Name_Expression (Self : not null access UML_Sequence_Node_Proxy; To : AMF.UML.String_Expressions.UML_String_Expression_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Name_Expression (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Name_Expression; ------------------- -- Get_Namespace -- ------------------- overriding function Get_Namespace (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin return AMF.UML.Namespaces.UML_Namespace_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Namespace (Self.Element))); end Get_Namespace; ------------------------ -- Get_Qualified_Name -- ------------------------ overriding function Get_Qualified_Name (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.Optional_String is begin declare use type Matreshka.Internals.Strings.Shared_String_Access; Aux : constant Matreshka.Internals.Strings.Shared_String_Access := AMF.Internals.Tables.UML_Attributes.Internal_Get_Qualified_Name (Self.Element); begin if Aux = null then return (Is_Empty => True); else return (False, League.Strings.Internals.Create (Aux)); end if; end; end Get_Qualified_Name; ------------------------ -- Get_Contained_Edge -- ------------------------ overriding function Get_Contained_Edge (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Edges.Collections.Set_Of_UML_Activity_Edge is begin return AMF.UML.Activity_Edges.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Contained_Edge (Self.Element))); end Get_Contained_Edge; ------------------------ -- Get_Contained_Node -- ------------------------ overriding function Get_Contained_Node (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Nodes.Collections.Set_Of_UML_Activity_Node is begin return AMF.UML.Activity_Nodes.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Contained_Node (Self.Element))); end Get_Contained_Node; --------------------- -- Get_In_Activity -- --------------------- overriding function Get_In_Activity (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activities.UML_Activity_Access is begin return AMF.UML.Activities.UML_Activity_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_In_Activity (Self.Element))); end Get_In_Activity; --------------------- -- Set_In_Activity -- --------------------- overriding procedure Set_In_Activity (Self : not null access UML_Sequence_Node_Proxy; To : AMF.UML.Activities.UML_Activity_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_In_Activity (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_In_Activity; ------------------ -- Get_Subgroup -- ------------------ overriding function Get_Subgroup (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Groups.Collections.Set_Of_UML_Activity_Group is begin return AMF.UML.Activity_Groups.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Subgroup (Self.Element))); end Get_Subgroup; --------------------- -- Get_Super_Group -- --------------------- overriding function Get_Super_Group (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Groups.UML_Activity_Group_Access is begin return AMF.UML.Activity_Groups.UML_Activity_Group_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Super_Group (Self.Element))); end Get_Super_Group; ----------------- -- Get_Context -- ----------------- overriding function Get_Context (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Classifiers.UML_Classifier_Access is begin return AMF.UML.Classifiers.UML_Classifier_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_Context (Self.Element))); end Get_Context; --------------- -- Get_Input -- --------------- overriding function Get_Input (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Input_Pins.Collections.Ordered_Set_Of_UML_Input_Pin is begin return AMF.UML.Input_Pins.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Input (Self.Element))); end Get_Input; ------------------------------ -- Get_Is_Locally_Reentrant -- ------------------------------ overriding function Get_Is_Locally_Reentrant (Self : not null access constant UML_Sequence_Node_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Locally_Reentrant (Self.Element); end Get_Is_Locally_Reentrant; ------------------------------ -- Set_Is_Locally_Reentrant -- ------------------------------ overriding procedure Set_Is_Locally_Reentrant (Self : not null access UML_Sequence_Node_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Locally_Reentrant (Self.Element, To); end Set_Is_Locally_Reentrant; ----------------------------- -- Get_Local_Postcondition -- ----------------------------- overriding function Get_Local_Postcondition (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint is begin return AMF.UML.Constraints.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Local_Postcondition (Self.Element))); end Get_Local_Postcondition; ---------------------------- -- Get_Local_Precondition -- ---------------------------- overriding function Get_Local_Precondition (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint is begin return AMF.UML.Constraints.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Local_Precondition (Self.Element))); end Get_Local_Precondition; ---------------- -- Get_Output -- ---------------- overriding function Get_Output (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Output_Pins.Collections.Ordered_Set_Of_UML_Output_Pin is begin return AMF.UML.Output_Pins.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Output (Self.Element))); end Get_Output; ----------------- -- Get_Handler -- ----------------- overriding function Get_Handler (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Exception_Handlers.Collections.Set_Of_UML_Exception_Handler is begin return AMF.UML.Exception_Handlers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Handler (Self.Element))); end Get_Handler; ------------------ -- Get_In_Group -- ------------------ overriding function Get_In_Group (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Groups.Collections.Set_Of_UML_Activity_Group is begin return AMF.UML.Activity_Groups.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_In_Group (Self.Element))); end Get_In_Group; --------------------------------- -- Get_In_Interruptible_Region -- --------------------------------- overriding function Get_In_Interruptible_Region (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Interruptible_Activity_Regions.Collections.Set_Of_UML_Interruptible_Activity_Region is begin return AMF.UML.Interruptible_Activity_Regions.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_In_Interruptible_Region (Self.Element))); end Get_In_Interruptible_Region; ---------------------- -- Get_In_Partition -- ---------------------- overriding function Get_In_Partition (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Partitions.Collections.Set_Of_UML_Activity_Partition is begin return AMF.UML.Activity_Partitions.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_In_Partition (Self.Element))); end Get_In_Partition; ---------------------------- -- Get_In_Structured_Node -- ---------------------------- overriding function Get_In_Structured_Node (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Structured_Activity_Nodes.UML_Structured_Activity_Node_Access is begin return AMF.UML.Structured_Activity_Nodes.UML_Structured_Activity_Node_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.UML_Attributes.Internal_Get_In_Structured_Node (Self.Element))); end Get_In_Structured_Node; ---------------------------- -- Set_In_Structured_Node -- ---------------------------- overriding procedure Set_In_Structured_Node (Self : not null access UML_Sequence_Node_Proxy; To : AMF.UML.Structured_Activity_Nodes.UML_Structured_Activity_Node_Access) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_In_Structured_Node (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_In_Structured_Node; ------------------ -- Get_Incoming -- ------------------ overriding function Get_Incoming (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Edges.Collections.Set_Of_UML_Activity_Edge is begin return AMF.UML.Activity_Edges.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Incoming (Self.Element))); end Get_Incoming; ------------------ -- Get_Outgoing -- ------------------ overriding function Get_Outgoing (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Edges.Collections.Set_Of_UML_Activity_Edge is begin return AMF.UML.Activity_Edges.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Outgoing (Self.Element))); end Get_Outgoing; ------------------------ -- Get_Redefined_Node -- ------------------------ overriding function Get_Redefined_Node (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Activity_Nodes.Collections.Set_Of_UML_Activity_Node is begin return AMF.UML.Activity_Nodes.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefined_Node (Self.Element))); end Get_Redefined_Node; ----------------- -- Get_Is_Leaf -- ----------------- overriding function Get_Is_Leaf (Self : not null access constant UML_Sequence_Node_Proxy) return Boolean is begin return AMF.Internals.Tables.UML_Attributes.Internal_Get_Is_Leaf (Self.Element); end Get_Is_Leaf; ----------------- -- Set_Is_Leaf -- ----------------- overriding procedure Set_Is_Leaf (Self : not null access UML_Sequence_Node_Proxy; To : Boolean) is begin AMF.Internals.Tables.UML_Attributes.Internal_Set_Is_Leaf (Self.Element, To); end Set_Is_Leaf; --------------------------- -- Get_Redefined_Element -- --------------------------- overriding function Get_Redefined_Element (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Redefinable_Elements.Collections.Set_Of_UML_Redefinable_Element is begin return AMF.UML.Redefinable_Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefined_Element (Self.Element))); end Get_Redefined_Element; ------------------------------ -- Get_Redefinition_Context -- ------------------------------ overriding function Get_Redefinition_Context (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier is begin return AMF.UML.Classifiers.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.UML_Attributes.Internal_Get_Redefinition_Context (Self.Element))); end Get_Redefinition_Context; ------------------------ -- Exclude_Collisions -- ------------------------ overriding function Exclude_Collisions (Self : not null access constant UML_Sequence_Node_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Exclude_Collisions unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Exclude_Collisions"; return Exclude_Collisions (Self, Imps); end Exclude_Collisions; ------------------------- -- Get_Names_Of_Member -- ------------------------- overriding function Get_Names_Of_Member (Self : not null access constant UML_Sequence_Node_Proxy; Element : AMF.UML.Named_Elements.UML_Named_Element_Access) return AMF.String_Collections.Set_Of_String is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Get_Names_Of_Member unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Get_Names_Of_Member"; return Get_Names_Of_Member (Self, Element); end Get_Names_Of_Member; -------------------- -- Import_Members -- -------------------- overriding function Import_Members (Self : not null access constant UML_Sequence_Node_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Import_Members unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Import_Members"; return Import_Members (Self, Imps); end Import_Members; --------------------- -- Imported_Member -- --------------------- overriding function Imported_Member (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Imported_Member unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Imported_Member"; return Imported_Member (Self); end Imported_Member; --------------------------------- -- Members_Are_Distinguishable -- --------------------------------- overriding function Members_Are_Distinguishable (Self : not null access constant UML_Sequence_Node_Proxy) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Members_Are_Distinguishable unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Members_Are_Distinguishable"; return Members_Are_Distinguishable (Self); end Members_Are_Distinguishable; ------------------ -- Owned_Member -- ------------------ overriding function Owned_Member (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Owned_Member unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Owned_Member"; return Owned_Member (Self); end Owned_Member; ------------------------- -- All_Owning_Packages -- ------------------------- overriding function All_Owning_Packages (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Packages.Collections.Set_Of_UML_Package is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "All_Owning_Packages unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.All_Owning_Packages"; return All_Owning_Packages (Self); end All_Owning_Packages; ----------------------------- -- Is_Distinguishable_From -- ----------------------------- overriding function Is_Distinguishable_From (Self : not null access constant UML_Sequence_Node_Proxy; N : AMF.UML.Named_Elements.UML_Named_Element_Access; Ns : AMF.UML.Namespaces.UML_Namespace_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Is_Distinguishable_From unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Is_Distinguishable_From"; return Is_Distinguishable_From (Self, N, Ns); end Is_Distinguishable_From; --------------- -- Namespace -- --------------- overriding function Namespace (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Namespace unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Namespace"; return Namespace (Self); end Namespace; ------------- -- Context -- ------------- overriding function Context (Self : not null access constant UML_Sequence_Node_Proxy) return AMF.UML.Classifiers.UML_Classifier_Access is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Context unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Context"; return Context (Self); end Context; ------------------------ -- Is_Consistent_With -- ------------------------ overriding function Is_Consistent_With (Self : not null access constant UML_Sequence_Node_Proxy; Redefinee : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Is_Consistent_With unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Is_Consistent_With"; return Is_Consistent_With (Self, Redefinee); end Is_Consistent_With; ----------------------------------- -- Is_Redefinition_Context_Valid -- ----------------------------------- overriding function Is_Redefinition_Context_Valid (Self : not null access constant UML_Sequence_Node_Proxy; Redefined : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Is_Redefinition_Context_Valid unimplemented"); raise Program_Error with "Unimplemented procedure UML_Sequence_Node_Proxy.Is_Redefinition_Context_Valid"; return Is_Redefinition_Context_Valid (Self, Redefined); end Is_Redefinition_Context_Valid; end AMF.Internals.UML_Sequence_Nodes;
reznikmm/matreshka
Ada
25,196
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2009-2014, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package provides abstractions for strings (sequences of Unicode code -- points), string's slices, and vectors of strings. Many operations in this -- package and its children packages depends from the current or explicitly -- specified locale. -- -- Universal_String type provides unbounded strings of Unicode characters. -- It utilizes implicit sharing technology (also known as copy-on-write), so -- copy operations has constant execution time. -- -- Universal_Slice is intended to be used primary when its period of life -- is inside of period of life of referenced string. There are two important -- advantages to use it: (1) slice data is not copied, (2) additional memory -- is not allocated. Nethertheless, some operations on slices can be less -- efficient, because data is not alligned properly as in string case. -- -- Universal_String_Vector is unbounded form of vector of Universal_String. -- -- Cursors child package and its children provides different kinds of -- iterators - character, grapheme cluster, word, sentence, line breaks. -- See these packages for detailed information. ------------------------------------------------------------------------------ pragma Ada_2012; private with Ada.Finalization; private with Ada.Streams; with Ada.Strings.UTF_Encoding; with League.Characters; limited with League.String_Vectors; private with Matreshka.Internals.Strings; private with Matreshka.Internals.Utf16; package League.Strings is pragma Preelaborate; pragma Remote_Types; type Split_Behavior is (Keep_Empty, Skip_Empty); type Universal_String is tagged private with Iterator_Element => League.Characters.Universal_Character, Constant_Indexing => Element; -- Universal_String is a base type to represent information in textual form -- as unbounded sequence of Unicode characters (Unicode code points). type Universal_Slice is tagged private; type Sort_Key is private; pragma Preelaborable_Initialization (Sort_Key); Empty_Universal_String : constant Universal_String; ---------------------- -- Universal_String -- ---------------------- function To_Universal_String (Item : Wide_Wide_String) return Universal_String; function To_Wide_Wide_String (Self : Universal_String'Class) return Wide_Wide_String; function Hash (Self : Universal_String'Class) return League.Hash_Type; function Length (Self : Universal_String'Class) return Natural; function Is_Empty (Self : Universal_String'Class) return Boolean; procedure Clear (Self : in out Universal_String'Class); function Element (Self : Universal_String'Class; Index : Positive) return League.Characters.Universal_Character; function Slice (Self : Universal_String'Class; Low : Positive; High : Natural) return Universal_String; -- procedure Slice -- (Self : in out Universal_String'Class; -- Low : Positive; -- High : Natural); -- Returns slice of the string. Raises Constraint_Error when given indices -- specifies non-empty and out of bounds range. procedure Slice (Self : in out Universal_String'Class; Low : Positive; High : Natural); function "&" (Left : Universal_String'Class; Right : Universal_String'Class) return Universal_String; function "&" (Left : Universal_String'Class; Right : League.Characters.Universal_Character'Class) return Universal_String; function "&" (Left : League.Characters.Universal_Character'Class; Right : Universal_String'Class) return Universal_String; function "&" (Left : Universal_String'Class; Right : Wide_Wide_Character) return Universal_String; function "&" (Left : Wide_Wide_Character; Right : Universal_String'Class) return Universal_String; function "&" (Left : Universal_String'Class; Right : Wide_Wide_String) return Universal_String; function "&" (Left : Wide_Wide_String; Right : Universal_String'Class) return Universal_String; procedure Append (Self : in out Universal_String'Class; Item : Universal_String'Class); procedure Append (Self : in out Universal_String'Class; Item : League.Characters.Universal_Character'Class); procedure Append (Self : in out Universal_String'Class; Item : Wide_Wide_String); procedure Append (Self : in out Universal_String'Class; Item : Wide_Wide_Character); -- Appends the character of the string onto the end of the string. procedure Prepend (Self : in out Universal_String'Class; Item : Universal_String'Class); procedure Prepend (Self : in out Universal_String'Class; Item : League.Characters.Universal_Character'Class); procedure Prepend (Self : in out Universal_String'Class; Item : Wide_Wide_String); procedure Prepend (Self : in out Universal_String'Class; Item : Wide_Wide_Character); -- Prepends the character or the string to the beginning of the string. -- procedure Replace -- (Self : in out Universal_String'Class; -- Index : Positive; -- By : Universal_Character'Class); -- -- procedure Replace -- (Self : in out Universal_String'Class; -- Index : Positive; -- By : Wide_Wide_Characters); procedure Replace (Self : in out Universal_String'Class; Low : Positive; High : Natural; By : Universal_String'Class); procedure Replace (Self : in out Universal_String'Class; Low : Positive; High : Natural; By : Wide_Wide_String); function Split (Self : Universal_String'Class; Separator : League.Characters.Universal_Character'Class; Behavior : Split_Behavior := Keep_Empty) return League.String_Vectors.Universal_String_Vector; -- Splits the string into substrings wherever Separator occurs, and returns -- the list of those strings. If Separator does not match anywhere in the -- string, returns a single-element list containing this string. function Split (Self : Universal_String'Class; Separator : Wide_Wide_Character; Behavior : Split_Behavior := Keep_Empty) return League.String_Vectors.Universal_String_Vector; -- Splits the string into substrings wherever Separator occurs, and returns -- the list of those strings. If Separator does not match anywhere in the -- string, returns a single-element list containing this string. function Head (Self : Universal_String'Class; Count : Natural) return Universal_String; -- procedure Head -- (Self : in out Universal_String'Class; -- Count : Natural); -- Returns specified number of starting characters of the string. Raises -- Constraint_Error when length of the string is less then number of -- requested characters. function Tail (Self : Universal_String'Class; Count : Natural) return Universal_String; -- procedure Tail -- (Self : in out Universal_String'Class; -- Count : Natural); -- Returns specified number of ending characters of the string. Raises -- Constraint_Error when length of the string is less then number of -- requested characters. function Head_To (Self : Universal_String'Class; To : Natural) return Universal_String renames Head; -- procedure Head_To -- (Self : in out Universal_String'Class; -- To : Natural); -- Returns leading characters up to and including specified position. -- Raises Constraint_Error when length of the string is less than requested -- position. function Tail_From (Self : Universal_String'Class; From : Positive) return Universal_String; -- procedure Tail_From -- (Self : in out Universal_String'Class; -- From : Positive); -- Returns tailing characters starting from the given position. function Index (Self : Universal_String'Class; Character : League.Characters.Universal_Character'Class) return Natural; function Index (Self : Universal_String'Class; Character : Wide_Wide_Character) return Natural; function Index (Self : Universal_String'Class; From : Positive; Character : League.Characters.Universal_Character'Class) return Natural; function Index (Self : Universal_String'Class; From : Positive; Character : Wide_Wide_Character) return Natural; function Index (Self : Universal_String'Class; From : Positive; To : Natural; Character : League.Characters.Universal_Character'Class) return Natural; function Index (Self : Universal_String'Class; From : Positive; To : Natural; Character : Wide_Wide_Character) return Natural; -- Returns index of the first occurrence of the specified character in the -- string, or zero if there are no occurrences. function Index (Self : Universal_String'Class; Pattern : Universal_String'Class) return Natural; function Index (Self : Universal_String'Class; Pattern : Wide_Wide_String) return Natural; function Index (Self : Universal_String'Class; From : Positive; Pattern : Universal_String'Class) return Natural; function Index (Self : Universal_String'Class; From : Positive; Pattern : Wide_Wide_String) return Natural; function Index (Self : Universal_String'Class; From : Positive; To : Natural; Pattern : Universal_String'Class) return Natural; function Index (Self : Universal_String'Class; From : Positive; To : Natural; Pattern : Wide_Wide_String) return Natural; -- Returns index of the first occurrence of the specified pattern in the -- string, or zero if there are no occurrences. function Last_Index (Self : Universal_String'Class; Character : League.Characters.Universal_Character'Class) return Natural; function Last_Index (Self : Universal_String'Class; Character : Wide_Wide_Character) return Natural; function Last_Index (Self : Universal_String'Class; To : Natural; Character : League.Characters.Universal_Character'Class) return Natural; function Last_Index (Self : Universal_String'Class; To : Natural; Character : Wide_Wide_Character) return Natural; function Last_Index (Self : Universal_String'Class; From : Positive; To : Natural; Character : League.Characters.Universal_Character'Class) return Natural; function Last_Index (Self : Universal_String'Class; From : Positive; To : Natural; Character : Wide_Wide_Character) return Natural; -- Returns the index position of the last occurrence of the character in -- this string, searching backward, or zero if character is not found. function Count (Self : Universal_String'Class; Character : League.Characters.Universal_Character'Class) return Natural; function Count (Self : Universal_String'Class; Character : Wide_Wide_Character) return Natural; -- Returns the number of occurrences of the Character in this string. function Ends_With (Self : Universal_String'Class; Pattern : Universal_String'Class) return Boolean; function Ends_With (Self : Universal_String'Class; Pattern : Wide_Wide_String) return Boolean; -- Returns True if the string ends with Pattern; otherwise returns False. function Starts_With (Self : Universal_String'Class; Pattern : Universal_String'Class) return Boolean; function Starts_With (Self : Universal_String'Class; Pattern : Wide_Wide_String) return Boolean; -- Returns True if the string starts with Pattern; otherwise returns False. ----------------- -- Conversions -- ----------------- function To_Uppercase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to uppercase form using -- full case conversion (both context-dependent mappings and tailoring are -- used). Returns result string. function To_Lowercase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to lowercase form using -- full case conversion (both context-dependent mappings and tailoring are -- used). Returns result string. function To_Titlecase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to titlecase form using -- full case conversion (both context-dependent mappings and tailoring are -- used). Returns result string. function To_Casefold (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to case folding form -- using full case conversion (only tailoring is used). Returns result -- string. function To_Simple_Uppercase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to uppercase form using -- simple case conversion (only tailoring is used). Returns result string. function To_Simple_Lowercase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to lowercase form using -- simple case conversion (only tailoring is used). Returns result string. function To_Simple_Titlecase (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to titlecase form using -- simple case conversion (only tailoring is used). Returns result string. function To_Simple_Casefold (Self : Universal_String'Class) return Universal_String; -- Converts each character in the specified string to case folding form -- using simple case conversion (only tailoring is used). Returns result -- string. function To_NFC (Self : Universal_String'Class) return Universal_String; -- Returns specified string converted into Normalization Form C (canonical -- decomposition and cacnonical composition). function To_NFD (Self : Universal_String'Class) return Universal_String; -- Returns specified string converted into Normalization Form D (canonical -- decomposition). function To_NFKC (Self : Universal_String'Class) return Universal_String; -- Returns specified string converted into Normalization Form KC -- (compatibility decomposition and canonical composition). function To_NFKD (Self : Universal_String'Class) return Universal_String; -- Returns specified string converted into Normalization Form KD -- (compatibility decomposition). -------------------------------------- -- Equivalence tests and comparison -- -------------------------------------- overriding function "=" (Left : Universal_String; Right : Universal_String) return Boolean; function "<" (Left : Universal_String; Right : Universal_String) return Boolean; function ">" (Left : Universal_String; Right : Universal_String) return Boolean; function "<=" (Left : Universal_String; Right : Universal_String) return Boolean; function ">=" (Left : Universal_String; Right : Universal_String) return Boolean; -- Compare two strings in binary order of Unicode Code Points. function Collation (Self : Universal_String'Class) return Sort_Key; -- Construct sort key for string comparison. ------------------------------- -- UTF Encoding end Decoding -- ------------------------------- function From_UTF_8_String (Item : Ada.Strings.UTF_Encoding.UTF_8_String) return Universal_String; -- Converts standard String in UTF-8 encoding into string. function To_UTF_8_String (Self : Universal_String'Class) return Ada.Strings.UTF_Encoding.UTF_8_String; -- Converts string to UTF-8 encoded standard String. function From_UTF_16_Wide_String (Item : Ada.Strings.UTF_Encoding.UTF_16_Wide_String) return Universal_String; -- Converts standard String in UTF-16 host-endian encoding into string. function To_UTF_16_Wide_String (Self : Universal_String'Class) return Ada.Strings.UTF_Encoding.UTF_16_Wide_String; -- Converts string to UTF-16 encoded standard Wide_String using host-endian -- variant. --------------------------------------- -- Comparison operators for Sort_Key -- --------------------------------------- overriding function "=" (Left : Sort_Key; Right : Sort_Key) return Boolean; function "<" (Left : Sort_Key; Right : Sort_Key) return Boolean; function "<=" (Left : Sort_Key; Right : Sort_Key) return Boolean; function ">" (Left : Sort_Key; Right : Sort_Key) return Boolean; function ">=" (Left : Sort_Key; Right : Sort_Key) return Boolean; private type Abstract_Cursor is tagged; type Cursor_Access is access all Abstract_Cursor'Class; ---------------------- -- Universal_String -- ---------------------- procedure Read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Universal_String); procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : Universal_String); procedure Emit_Changed (Self : Universal_String'Class; Changed_First : Matreshka.Internals.Utf16.Utf16_String_Index; Removed_Last : Matreshka.Internals.Utf16.Utf16_String_Index; Inserted_Last : Matreshka.Internals.Utf16.Utf16_String_Index); -- Must be called when internal string data is changed. It notify all -- cursors about this change. All positions are in code units. -- procedure Emit_Changed -- (Self : not null String_Private_Data_Access; -- Cursor : not null Modify_Cursor_Access; -- Changed_First : Positive; -- Removed_Last : Natural; -- Inserted_Last : Natural); -- Must be called when internal string data is changed. It notify all -- iterators (except originator) about this change. All positions are in -- code units. type Cursor_List is record Head : Cursor_Access := null; end record; type Universal_String is new Ada.Finalization.Controlled with record Data : Matreshka.Internals.Strings.Shared_String_Access := Matreshka.Internals.Strings.Shared_Empty'Access; -- Data component is non-null by convention. It is set to null only -- during finalization to mark object as finalized. List : aliased Cursor_List; -- Storage for holder of the head of the list of cursors Cursors : access Cursor_List; -- List of cursors. This member is initialized to reference to List -- member. end record; for Universal_String'Read use Read; for Universal_String'Write use Write; overriding procedure Initialize (Self : in out Universal_String); overriding procedure Adjust (Self : in out Universal_String) with Inline => True; overriding procedure Finalize (Self : in out Universal_String); Empty_String_Cursors : aliased Cursor_List := (Head => null); Empty_Universal_String : constant Universal_String := (Ada.Finalization.Controlled with Data => Matreshka.Internals.Strings.Shared_Empty'Access, List => (Head => null), Cursors => Empty_String_Cursors'Access); -- To satisfy requerements of language to prevent modification of component -- of constant the separate object is used to store list of associated -- cursors. --------------------- -- Universal_Slice -- --------------------- type Universal_Slice is new Ada.Finalization.Controlled with null record; --------------------- -- Abstract_Cursor -- --------------------- type Universal_String_Access is access constant Universal_String'Class; type Abstract_Cursor is abstract new Ada.Finalization.Controlled with record Object : Universal_String_Access := null; Next : Cursor_Access := null; Previous : Cursor_Access := null; end record; not overriding procedure On_Changed (Self : not null access Abstract_Cursor; Changed_First : Positive; Removed_Last : Natural; Inserted_Last : Natural); -- Called when internal string data is changed. All positions are in code -- units. Default implementation invalidate iterator. procedure Attach (Self : in out Abstract_Cursor'Class; Item : in out Universal_String'Class); -- Attaches iterator to the specified string. Exclusive copy of the string -- is created if needed. overriding procedure Adjust (Self : in out Abstract_Cursor) with Inline => True; overriding procedure Finalize (Self : in out Abstract_Cursor); -------------- -- Sort_Key -- -------------- procedure Read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : out Sort_Key); procedure Write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Item : Sort_Key); type Sort_Key is new Ada.Finalization.Controlled with record Data : Matreshka.Internals.Strings.Shared_Sort_Key_Access := Matreshka.Internals.Strings.Shared_Empty_Key'Access; end record; for Sort_Key'Read use Read; for Sort_Key'Write use Write; overriding procedure Adjust (Self : in out Sort_Key) with Inline => True; overriding procedure Finalize (Self : in out Sort_Key); pragma Inline ("="); pragma Inline ("<"); pragma Inline (">"); pragma Inline ("<="); pragma Inline (">="); pragma Inline (Clear); pragma Inline (Finalize); pragma Inline (Is_Empty); pragma Inline (Length); end League.Strings;
reznikmm/matreshka
Ada
3,689
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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.Strings; package Matreshka.ODF_Attributes.Text is type Text_Node_Base is abstract new Matreshka.ODF_Attributes.ODF_Attribute_Node with null record; overriding function Get_Namespace_URI (Self : not null access constant Text_Node_Base) return League.Strings.Universal_String; end Matreshka.ODF_Attributes.Text;
charlie5/lace
Ada
18,909
adb
--------------------------------- -- GID - Generic Image Decoder -- --------------------------------- -- -- Private child of GID, with helpers for identifying -- image formats and reading header informations. -- with GID.Buffering, GID.Color_tables, GID.Decoding_JPG, GID.Decoding_PNG; with Ada.Exceptions, Ada.Unchecked_Deallocation; package body GID.Headers is use Ada.Exceptions; ------------------------------------------------------- -- The very first: read signature to identify format -- ------------------------------------------------------- procedure Load_signature ( image : in out Image_descriptor; try_tga : Boolean:= False ) is use Bounded_255; c, d: Character; FITS_challenge: String(1..5); -- without the initial GIF_challenge : String(1..5); -- without the initial PNG_challenge : String(1..7); -- without the initial PNG_signature: constant String:= "PNG" & ASCII.CR & ASCII.LF & ASCII.SUB & ASCII.LF; procedure Dispose is new Ada.Unchecked_Deallocation(Color_table, p_Color_table); begin -- Some cleanup Dispose(image.palette); image.next_frame:= 0.0; image.display_orientation:= Unchanged; -- Character'Read(image.stream, c); image.first_byte:= Character'Pos(c); case c is when 'B' => Character'Read(image.stream, c); if c='M' then image.detailed_format:= To_Bounded_String("BMP"); image.format:= BMP; return; end if; when 'S' => String'Read(image.stream, FITS_challenge); if FITS_challenge = "IMPLE" then image.detailed_format:= To_Bounded_String("FITS"); image.format:= FITS; return; end if; when 'G' => String'Read(image.stream, GIF_challenge); if GIF_challenge = "IF87a" or GIF_challenge = "IF89a" then image.detailed_format:= To_Bounded_String('G' & GIF_challenge & ", "); image.format:= GIF; return; end if; when 'I' | 'M' => Character'Read(image.stream, d); if c=d then if c = 'I' then image.detailed_format:= To_Bounded_String("TIFF, little-endian"); else image.detailed_format:= To_Bounded_String("TIFF, big-endian"); end if; image.format:= TIFF; return; end if; when Character'Val(16#FF#) => Character'Read(image.stream, c); if c=Character'Val(16#D8#) then -- SOI (Start of Image) segment marker (FFD8) image.detailed_format:= To_Bounded_String("JPEG"); image.format:= JPEG; return; end if; when Character'Val(16#89#) => String'Read(image.stream, PNG_challenge); if PNG_challenge = PNG_signature then image.detailed_format:= To_Bounded_String("PNG"); image.format:= PNG; return; end if; when others => if try_tga then image.detailed_format:= To_Bounded_String("TGA"); image.format:= TGA; return; else raise unknown_image_format; end if; end case; raise unknown_image_format; end Load_signature; generic type Number is mod <>; procedure Read_Intel_x86_number( from : in Stream_Access; n : out Number ); pragma Inline(Read_Intel_x86_number); generic type Number is mod <>; procedure Big_endian_number( from : in out Input_buffer; n : out Number ); pragma Inline(Big_endian_number); procedure Read_Intel_x86_number( from : in Stream_Access; n : out Number ) is b: U8; m: Number:= 1; begin n:= 0; for i in 1..Number'Size/8 loop U8'Read(from, b); n:= n + m * Number(b); m:= m * 256; end loop; end Read_Intel_x86_number; procedure Big_endian_number( from : in out Input_buffer; n : out Number ) is b: U8; begin n:= 0; for i in 1..Number'Size/8 loop Buffering.Get_Byte(from, b); n:= n * 256 + Number(b); end loop; end Big_endian_number; procedure Read_Intel is new Read_Intel_x86_number( U16 ); procedure Read_Intel is new Read_Intel_x86_number( U32 ); procedure Big_endian is new Big_endian_number( U32 ); ---------------------------------------------------------- -- Loading of various format's headers (past signature) -- ---------------------------------------------------------- ---------------- -- BMP header -- ---------------- procedure Load_BMP_header (image: in out Image_descriptor) is n, dummy: U32; pragma Warnings(off, dummy); w, dummy16: U16; pragma Warnings(off, dummy16); begin -- Pos= 3, read the file size Read_Intel(image.stream, dummy); -- Pos= 7, read four bytes, unknown Read_Intel(image.stream, dummy); -- Pos= 11, read four bytes offset, file top to bitmap data. -- For 256 colors, this is usually 36 04 00 00 Read_Intel(image.stream, dummy); -- Pos= 15. The beginning of Bitmap information header. -- Data expected: 28H, denoting 40 byte header Read_Intel(image.stream, dummy); -- Pos= 19. Bitmap width, in pixels. Four bytes Read_Intel(image.stream, n); image.width:= Natural(n); -- Pos= 23. Bitmap height, in pixels. Four bytes Read_Intel(image.stream, n); image.height:= Natural(n); -- Pos= 27, skip two bytes. Data is number of Bitmap planes. Read_Intel(image.stream, dummy16); -- perform the skip -- Pos= 29, Number of bits per pixel -- Value 8, denoting 256 color, is expected Read_Intel(image.stream, w); case w is when 1 | 4 | 8 | 24 => null; when others => Raise_exception( unsupported_image_subformat'Identity, "bit depth =" & U16'Image(w) ); end case; image.bits_per_pixel:= Integer(w); -- Pos= 31, read four bytes Read_Intel(image.stream, n); -- Type of compression used -- BI_RLE8 = 1 -- BI_RLE4 = 2 if n /= 0 then Raise_exception( unsupported_image_subformat'Identity, "RLE compression" ); end if; -- Read_Intel(image.stream, dummy); -- Pos= 35, image size Read_Intel(image.stream, dummy); -- Pos= 39, horizontal resolution Read_Intel(image.stream, dummy); -- Pos= 43, vertical resolution Read_Intel(image.stream, n); -- Pos= 47, number of palette colors if image.bits_per_pixel <= 8 then if n = 0 then image.palette:= new Color_Table(0..2**image.bits_per_pixel-1); else image.palette:= new Color_Table(0..Natural(n)-1); end if; end if; Read_Intel(image.stream, dummy); -- Pos= 51, number of important colors -- Pos= 55 (36H), - start of palette Color_tables.Load_palette(image); end Load_BMP_header; procedure Load_FITS_header (image: in out Image_descriptor) is begin raise known_but_unsupported_image_format; end Load_FITS_header; ---------------- -- GIF header -- ---------------- procedure Load_GIF_header (image: in out Image_descriptor) is -- GIF - logical screen descriptor screen_width, screen_height : U16; packed, background, aspect_ratio_code : U8; global_palette: Boolean; begin Read_Intel(image.stream, screen_width); Read_Intel(image.stream, screen_height); image.width:= Natural(screen_width); image.height:= Natural(screen_height); image.transparency:= True; -- cannot exclude transparency at this level. U8'Read(image.stream, packed); -- Global Color Table Flag 1 Bit -- Color Resolution 3 Bits -- Sort Flag 1 Bit -- Size of Global Color Table 3 Bits global_palette:= (packed and 16#80#) /= 0; image.bits_per_pixel:= Natural((packed and 16#7F#)/16#10#) + 1; -- Indicative: -- iv) [...] This value should be set to indicate the -- richness of the original palette U8'Read(image.stream, background); U8'Read(image.stream, aspect_ratio_code); Buffering.Attach_stream(image.buffer, image.stream); if global_palette then image.subformat_id:= 1+(Natural(packed and 16#07#)); -- palette's bits per pixels, usually <= image's -- -- if image.subformat_id > image.bits_per_pixel then -- Raise_exception( -- error_in_image_data'Identity, -- "GIF: global palette has more colors than the image" & -- image.subformat_id'img & image.bits_per_pixel'img -- ); -- end if; image.palette:= new Color_Table(0..2**(image.subformat_id)-1); Color_tables.Load_palette(image); end if; end Load_GIF_header; ----------------- -- JPEG header -- ----------------- procedure Load_JPEG_header (image: in out Image_descriptor) is -- http://en.wikipedia.org/wiki/JPEG use GID.Decoding_JPG, GID.Buffering, Bounded_255; sh: Segment_head; b: U8; begin -- We have already passed the SOI (Start of Image) segment marker (FFD8). image.JPEG_stuff.restart_interval:= 0; Attach_stream(image.buffer, image.stream); loop Read(image, sh); case sh.kind is when DHT => -- Huffman Table Read_DHT(image, Natural(sh.length)); when DQT => Read_DQT(image, Natural(sh.length)); when DRI => -- Restart Interval Read_DRI(image); when SOF_0 .. SOF_15 => Read_SOF(image, sh); exit; -- we've got header-style informations, then it's time to quit when APP_1 => Read_EXIF(image, Natural(sh.length)); when others => -- Skip segment data for i in 1..sh.length loop Get_Byte(image.buffer, b); end loop; end case; end loop; end Load_JPEG_header; ---------------- -- PNG header -- ---------------- procedure Load_PNG_header (image: in out Image_descriptor) is use Decoding_PNG, Buffering; ch: Chunk_head; n, dummy: U32; pragma Warnings(off, dummy); b, color_type: U8; palette: Boolean:= False; begin Buffering.Attach_stream(image.buffer, image.stream); Read(image, ch); if ch.kind /= IHDR then Raise_exception( error_in_image_data'Identity, "Expected 'IHDR' chunk as first chunk in PNG stream" ); end if; Big_endian(image.buffer, n); if n = 0 then Raise_exception( error_in_image_data'Identity, "PNG image with zero width" ); end if; image.width:= Natural(n); Big_endian(image.buffer, n); if n = 0 then Raise_exception( error_in_image_data'Identity, "PNG image with zero height" ); end if; image.height:= Natural(n); Get_Byte(image.buffer, b); image.bits_per_pixel:= Integer(b); Get_Byte(image.buffer, color_type); image.subformat_id:= Integer(color_type); case color_type is when 0 => -- Greyscale image.greyscale:= True; case image.bits_per_pixel is when 1 | 2 | 4 | 8 | 16 => null; when others => Raise_exception( error_in_image_data'Identity, "PNG, type 0 (greyscale): wrong bit-per-channel depth" ); end case; when 2 => -- RGB TrueColor case image.bits_per_pixel is when 8 | 16 => image.bits_per_pixel:= 3 * image.bits_per_pixel; when others => Raise_exception( error_in_image_data'Identity, "PNG, type 2 (RGB): wrong bit-per-channel depth" ); end case; when 3 => -- RGB with palette palette:= True; case image.bits_per_pixel is when 1 | 2 | 4 | 8 => null; when others => Raise_exception( error_in_image_data'Identity, "PNG, type 3: wrong bit-per-channel depth" ); end case; when 4 => -- Grey & Alpha image.greyscale:= True; image.transparency:= True; case image.bits_per_pixel is when 8 | 16 => image.bits_per_pixel:= 2 * image.bits_per_pixel; when others => Raise_exception( error_in_image_data'Identity, "PNG, type 4 (Greyscale & Alpha): wrong bit-per-channel depth" ); end case; when 6 => -- RGBA image.transparency:= True; case image.bits_per_pixel is when 8 | 16 => image.bits_per_pixel:= 4 * image.bits_per_pixel; when others => Raise_exception( error_in_image_data'Identity, "PNG, type 6 (RGBA): wrong bit-per-channel depth" ); end case; when others => Raise_exception( error_in_image_data'Identity, "Unknown PNG color type" ); end case; Get_Byte(image.buffer, b); if b /= 0 then Raise_exception( error_in_image_data'Identity, "Unknown PNG compression; ISO/IEC 15948:2003" & " knows only 'method 0' (deflate)" ); end if; Get_Byte(image.buffer, b); if b /= 0 then Raise_exception( error_in_image_data'Identity, "Unknown PNG filtering; ISO/IEC 15948:2003 knows only 'method 0'" ); end if; Get_Byte(image.buffer, b); image.interlaced:= b = 1; -- Adam7 Big_endian(image.buffer, dummy); -- Chunk's CRC if palette then loop Read(image, ch); case ch.kind is when IEND => Raise_exception( error_in_image_data'Identity, "PNG: there must be a palette, found IEND" ); when PLTE => if ch.length rem 3 /= 0 then Raise_exception( error_in_image_data'Identity, "PNG: palette chunk byte length must be a multiple of 3" ); end if; image.palette:= new Color_Table(0..Integer(ch.length/3)-1); Color_tables.Load_palette(image); Big_endian(image.buffer, dummy); -- Chunk's CRC exit; when others => -- skip chunk data and CRC for i in 1..ch.length + 4 loop Get_Byte(image.buffer, b); end loop; end case; end loop; end if; end Load_PNG_header; ------------------------ -- TGA (Targa) header -- ------------------------ procedure Load_TGA_header (image: in out Image_descriptor) is -- TGA FILE HEADER, p.6 -- image_ID_length: U8; -- Field 1 color_map_type : U8; -- Field 2 image_type : U8; -- Field 3 -- Color Map Specification - Field 4 first_entry_index : U16; -- Field 4.1 color_map_length : U16; -- Field 4.2 color_map_entry_size: U8; -- Field 4.3 -- Image Specification - Field 5 x_origin: U16; y_origin: U16; image_width: U16; image_height: U16; pixel_depth: U8; tga_image_descriptor: U8; -- dummy: U8; base_image_type: Integer; begin -- Read the header image_ID_length:= image.first_byte; U8'Read(image.stream, color_map_type); U8'Read(image.stream, image_type); -- Color Map Specification - Field 4 Read_Intel(image.stream, first_entry_index); Read_Intel(image.stream, color_map_length); U8'Read(image.stream, color_map_entry_size); -- Image Specification - Field 5 Read_Intel(image.stream, x_origin); Read_Intel(image.stream, y_origin); Read_Intel(image.stream, image_width); Read_Intel(image.stream, image_height); U8'Read(image.stream, pixel_depth); U8'Read(image.stream, tga_image_descriptor); -- Done. -- -- Image type: -- 1 = 8-bit palette style -- 2 = Direct [A]RGB image -- 3 = grayscale -- 9 = RLE version of Type 1 -- 10 = RLE version of Type 2 -- 11 = RLE version of Type 3 -- base_image_type:= U8'Pos(image_type and 7); image.RLE_encoded:= (image_type and 8) /= 0; -- if color_map_type /= 0 then image.palette:= new Color_Table( Integer(first_entry_index).. Integer(first_entry_index)+Integer(color_map_length)-1 ); image.subformat_id:= Integer(color_map_entry_size); case image.subformat_id is -- = palette's bit depth when 8 => -- Grey null; when 15 | 16 => -- RGB 3*5 bit | RGBA 3*3+1 bit null; when 24 | 32 => -- RGB 3*8 bit | RGBA 4*8 bit null; when others => Raise_exception( error_in_image_data'Identity, "TGA color map (palette): wrong bit depth:" & Integer'Image(image.subformat_id) ); end case; end if; -- image.greyscale:= False; -- ev. overridden later case base_image_type is when 1 => image.greyscale:= color_map_entry_size = 8; when 2 => null; when 3 => image.greyscale:= True; when others => Raise_exception( unsupported_image_subformat'Identity, "TGA type =" & Integer'Image(base_image_type) ); end case; image.width := U16'Pos(image_width); image.height := U16'Pos(image_height); image.bits_per_pixel := U8'Pos(pixel_depth); -- Make sure we are loading a supported TGA_type case image.bits_per_pixel is when 32 | 24 | 16 | 15 | 8 => null; when others => Raise_exception( unsupported_image_subformat'Identity, "TGA bits per pixels =" & Integer'Image(image.bits_per_pixel) ); end case; image.flag_1:= (tga_image_descriptor and 32) /= 0; -- top first -- *** Image and color map data -- * Image ID for i in 1..image_ID_length loop U8'Read( image.stream, dummy ); end loop; -- * Color map data (palette) Color_tables.Load_palette(image); -- * Image data: Read by Load_image_contents. end Load_TGA_header; procedure Load_TIFF_header (image: in out Image_descriptor) is begin raise known_but_unsupported_image_format; end Load_TIFF_header; end;
reznikmm/gela
Ada
29,044
adb
-- with Gela.Plain_Environments.Debug; package body Gela.Plain_Environments is function Name_To_Region (Self : access Environment_Set'Class; Index : Gela.Semantic_Types.Env_Index; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Region_Item_List; package Visible_Cursors is -- Cursor over names in Local type Defining_Name_Cursor is new Gela.Defining_Name_Cursors.Defining_Name_Cursor with record Set : Plain_Environment_Set_Access; Current : Gela.Name_List_Managers.Defining_Name_Cursor; end record; overriding function Has_Element (Self : Defining_Name_Cursor) return Boolean; overriding function Element (Self : Defining_Name_Cursor) return Gela.Elements.Defining_Names.Defining_Name_Access; overriding procedure Next (Self : in out Defining_Name_Cursor); procedure Initialize (Self : in out Defining_Name_Cursor'Class; Symbol : Gela.Lexical_Types.Symbol; Region : Region_Item_List); end Visible_Cursors; package body Visible_Cursors is overriding function Has_Element (Self : Defining_Name_Cursor) return Boolean is begin return Self.Current.Has_Element; end Has_Element; overriding function Element (Self : Defining_Name_Cursor) return Gela.Elements.Defining_Names.Defining_Name_Access is begin return Self.Current.Element; end Element; overriding procedure Next (Self : in out Defining_Name_Cursor) is begin Self.Current.Next; end Next; procedure Initialize (Self : in out Defining_Name_Cursor'Class; Symbol : Gela.Lexical_Types.Symbol; Region : Region_Item_List) is Local : constant Gela.Name_List_Managers.List := Self.Set.Region.Head (Region).Local; begin Self.Current := Self.Set.Names.Find (Local, Symbol); end Initialize; end Visible_Cursors; package Direct_Visible_Cursors is -- Cursor over names in Local then go to enclosing region, etc type Defining_Name_Cursor is new Visible_Cursors.Defining_Name_Cursor with record Region : Region_Item_List; end record; overriding procedure Next (Self : in out Defining_Name_Cursor); procedure Initialize (Self : in out Defining_Name_Cursor; Symbol : Gela.Lexical_Types.Symbol); end Direct_Visible_Cursors; ---------------------------- -- Direct_Visible_Cursors -- ---------------------------- package body Direct_Visible_Cursors is overriding procedure Next (Self : in out Defining_Name_Cursor) is use type Region_Item_List; Symbol : constant Gela.Lexical_Types.Symbol := Self.Current.Symbol; Region : Region_Item_List; begin Visible_Cursors.Defining_Name_Cursor (Self).Next; while not Self.Has_Element loop Region := Self.Set.Region.Tail (Self.Region); if Region /= Region_Item_Lists.Empty then Self.Region := Region; Visible_Cursors.Initialize (Self, Symbol, Region); else return; end if; end loop; end Next; ---------------- -- Initialize -- ---------------- procedure Initialize (Self : in out Defining_Name_Cursor; Symbol : Gela.Lexical_Types.Symbol) is use type Region_Item_List; Region : Region_Item_List := Self.Region; begin while Region /= Region_Item_Lists.Empty loop Self.Region := Region; Visible_Cursors.Initialize (Self, Symbol, Region); exit when Self.Has_Element; Region := Self.Set.Region.Tail (Self.Region); end loop; end Initialize; end Direct_Visible_Cursors; package Use_Package_Cursors is -- Cursor over names in each used package type Defining_Name_Cursor is new Visible_Cursors.Defining_Name_Cursor with record Env : Env_Item_Index; Region : Region_Item_List; -- Position in Env_Item.Nested_Region_List list Use_Name : Defining_Name_List; -- Position in Region.Use_Package list end record; overriding procedure Next (Self : in out Defining_Name_Cursor); function Name_To_Region (Self : Defining_Name_Cursor; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Region_Item_List; procedure Initialize (Self : in out Defining_Name_Cursor; Symbol : Gela.Lexical_Types.Symbol); end Use_Package_Cursors; ------------------------- -- Use_Package_Cursors -- ------------------------- package body Use_Package_Cursors is overriding procedure Next (Self : in out Defining_Name_Cursor) is use type Region_Item_List; use type Defining_Name_List; Symbol : constant Gela.Lexical_Types.Symbol := Self.Current.Symbol; Region : Region_Item_List; begin Visible_Cursors.Defining_Name_Cursor (Self).Next; while not Self.Current.Has_Element loop Region := Region_Item_Lists.Empty; while Region = Region_Item_Lists.Empty loop -- Next name in use clauses of Region Self.Use_Name := Self.Set.Use_Package.Tail (Self.Use_Name); while Self.Use_Name = Defining_Name_Lists.Empty loop Self.Region := Self.Set.Region.Tail (Self.Region); if Self.Region = Region_Item_Lists.Empty then return; end if; Self.Use_Name := Self.Set.Region.Head (Self.Region).Use_Package; end loop; Region := Self.Name_To_Region (Self.Set.Use_Package.Head (Self.Use_Name)); end loop; Visible_Cursors.Initialize (Self, Symbol, Region); end loop; end Next; -------------------- -- Name_To_Region -- -------------------- function Name_To_Region (Self : Defining_Name_Cursor; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Region_Item_List is begin return Name_To_Region (Self.Set, Self.Env, Name); end Name_To_Region; ---------------- -- Initialize -- ---------------- procedure Initialize (Self : in out Defining_Name_Cursor; Symbol : Gela.Lexical_Types.Symbol) is use type Region_Item_List; use type Defining_Name_List; Env : constant Env_Item := Self.Set.Env.Element (Self.Env); Target : Region_Item_List; Local : Gela.Name_List_Managers.List; begin Self.Region := Env.Region_List (Nested); while Self.Region /= Region_Item_Lists.Empty loop Self.Use_Name := Self.Set.Region.Head (Self.Region).Use_Package; while Self.Use_Name /= Defining_Name_Lists.Empty loop Target := Self.Name_To_Region (Self.Set.Use_Package.Head (Self.Use_Name)); if Target /= Region_Item_Lists.Empty then Local := Self.Set.Region.Head (Target).Local; Self.Current := Self.Set.Names.Find (Local, Symbol); if Self.Has_Element then return; end if; end if; Self.Use_Name := Self.Set.Use_Package.Tail (Self.Use_Name); end loop; Self.Region := Self.Set.Region.Tail (Self.Region); end loop; end Initialize; end Use_Package_Cursors; overriding function Add_Completion (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Name : Gela.Elements.Defining_Names.Defining_Name_Access; Completion : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is Env_Index : Gela.Semantic_Types.Env_Index; Env : Env_Item; Reg : Region_Item; begin if Index in 0 | Self.Library_Level_Environment then -- Fix constraint_error because library_bodies doesn have env yet return Index; end if; Env := Self.Env.Element (Index); Reg := Self.Region.Head (Env.Region_List (Nested)); Self.Use_Package.Prepend (Value => Name, Input => Reg.Completion, Output => Reg.Completion); Self.Use_Package.Prepend (Value => Completion, Input => Reg.Completion, Output => Reg.Completion); -- Replace head of Nested_Region_List with Reg Self.Region.Prepend (Value => Reg, Input => Self.Region.Tail (Env.Region_List (Nested)), Output => Env.Region_List (Nested)); Env_Index := Self.Env.Find_Index (Env); if Env_Index = 0 then Self.Env.Append (Env); Env_Index := Self.Env.Last_Index; end if; return Env_Index; end Add_Completion; ----------------- -- Completions -- ----------------- overriding function Completions (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Environments.Completion_List is use type Region_Item_List; use type Gela.Elements.Defining_Names.Defining_Name_Access; procedure Find_Completion (List : Defining_Name_List; Result : out Gela.Elements.Defining_Names.Defining_Name_Access; Restart : in out Boolean); --------------------- -- Find_Completion -- --------------------- procedure Find_Completion (List : Defining_Name_List; Result : out Gela.Elements.Defining_Names.Defining_Name_Access; Restart : in out Boolean) is use type Defining_Name_List; Next : Defining_Name_List := List; Completion : Gela.Elements.Defining_Names.Defining_Name_Access; begin while Next /= Defining_Name_Lists.Empty loop Result := Self.Use_Package.Head (Next); Next := Self.Use_Package.Tail (Next); Completion := Self.Use_Package.Head (Next); if Completion = Name then return; elsif Result = Name then Result := Completion; Restart := True; end if; Next := Self.Use_Package.Tail (Next); end loop; Result := null; end Find_Completion; Env : Env_Item; Next : Region_Item_List; Result : Gela.Elements.Defining_Names.Defining_Name_Access; Data : Gela.Environments.Completion_Array (1 .. Gela.Environments.Completion_Index'Last); Last : Gela.Environments.Completion_Index := 0; Restart : Boolean := False; begin if Index = Gela.Library_Environments.Library_Env then return Self.Lib.Completions (Index, Name); else Env := Self.Env.Element (Index); end if; for J of Env.Region_List loop Next := J; while Next /= Region_Item_Lists.Empty loop Find_Completion (Self.Region.Head (Next).Completion, Result, Restart); if Restart then return Completions (Self, Index, Result); elsif Result.Assigned then Last := Last + 1; Data (Last) := Result; end if; Next := Self.Region.Tail (Next); end loop; end loop; return (Last, Data (1 .. Last)); end Completions; ----------------------- -- Add_Defining_Name -- ----------------------- overriding function Add_Defining_Name (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Symbol : Gela.Lexical_Types.Symbol; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is use type Region_Item_List; procedure Update_Lib_Unit_Env (Old_Env : Gela.Semantic_Types.Env_Index; New_Env : Env_Item_Index); ------------------------- -- Update_Lib_Unit_Env -- ------------------------- procedure Update_Lib_Unit_Env (Old_Env : Gela.Semantic_Types.Env_Index; New_Env : Env_Item_Index) is Cursor : Env_Maps.Cursor := Self.Lib_Env.Find (Old_Env); Symbol : Gela.Lexical_Types.Symbol; begin if Env_Maps.Has_Element (Cursor) then Symbol := Env_Maps.Element (Cursor); Self.Lib_Env.Delete (Cursor); Self.Lib_Env.Insert (New_Env, Symbol); Self.Units_Env.Replace (Symbol, New_Env); end if; end Update_Lib_Unit_Env; Env : Env_Item; Env_Index : Gela.Semantic_Types.Env_Index; Reg : Region_Item; begin if Index in Env_Item_Index then Env := Self.Env.Element (Index); else Env := (Region_List => (Nested | Other | Withed => Region_Item_Lists.Empty)); end if; if Env.Region_List (Nested) = Region_Item_Lists.Empty then Reg := (Name => null, Local => Self.Names.Empty_List, Rename => Self.Names.Empty_List, Use_Package | Completion => Defining_Name_Lists.Empty); else Reg := Self.Region.Head (Env.Region_List (Nested)); end if; Self.Names.Append (Symbol => Symbol, Name => Name, Input => Reg.Local, Output => Reg.Local); if Env.Region_List (Nested) = Region_Item_Lists.Empty then -- Create Nested_Region_List as (Reg) Self.Region.Prepend (Value => Reg, Input => Region_Item_Lists.Empty, Output => Env.Region_List (Nested)); else -- Replace head of Nested_Region_List with Reg Self.Region.Prepend (Value => Reg, Input => Self.Region.Tail (Env.Region_List (Nested)), Output => Env.Region_List (Nested)); end if; Env_Index := Self.Env.Find_Index (Env); if Env_Index = 0 then Self.Env.Append (Env); Env_Index := Self.Env.Last_Index; end if; Update_Lib_Unit_Env (Index, Env_Index); return Env_Index; end Add_Defining_Name; ------------------------ -- Add_Rename_Package -- ------------------------ overriding function Add_Rename_Package (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Region : Gela.Elements.Defining_Names.Defining_Name_Access; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is Env_Index : Gela.Semantic_Types.Env_Index; Env : Env_Item; Reg : Region_Item; begin if Index in 0 | Self.Library_Level_Environment then -- Fix constraint_error because library_bodies doesn have env yet return Index; end if; Env := Self.Env.Element (Index); Reg := Self.Region.Head (Env.Region_List (Nested)); Self.Names.Append (Symbol => Region.Full_Name, Name => Name, Input => Reg.Rename, Output => Reg.Rename); -- Replace head of Nested_Region_List with Reg Self.Region.Prepend (Value => Reg, Input => Self.Region.Tail (Env.Region_List (Nested)), Output => Env.Region_List (Nested)); Env_Index := Self.Env.Find_Index (Env); if Env_Index = 0 then Self.Env.Append (Env); Env_Index := Self.Env.Last_Index; end if; return Env_Index; end Add_Rename_Package; --------------------- -- Add_Use_Package -- --------------------- overriding function Add_Use_Package (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is Env_Index : Gela.Semantic_Types.Env_Index; Env : Env_Item; Reg : Region_Item; begin if Index in 0 | Self.Library_Level_Environment then -- Fix constraint_error because library_bodies doesn have env yet return Index; end if; Env := Self.Env.Element (Index); Reg := Self.Region.Head (Env.Region_List (Nested)); Self.Use_Package.Prepend (Value => Name, Input => Reg.Use_Package, Output => Reg.Use_Package); -- Replace head of Nested_Region_List with Reg Self.Region.Prepend (Value => Reg, Input => Self.Region.Tail (Env.Region_List (Nested)), Output => Env.Region_List (Nested)); Env_Index := Self.Env.Find_Index (Env); if Env_Index = 0 then Self.Env.Append (Env); Env_Index := Self.Env.Last_Index; end if; return Env_Index; end Add_Use_Package; --------------------- -- Add_With_Clause -- --------------------- overriding function Add_With_Clause (Self : in out Environment_Set; Index : Gela.Semantic_Types.Env_Index; Symbol : Gela.Lexical_Types.Symbol) return Gela.Semantic_Types.Env_Index is procedure Append (Item : Region_Item); Env_Index : Gela.Semantic_Types.Env_Index; Env : Env_Item := Self.Env.Element (Index); Target : Gela.Semantic_Types.Env_Index := Self.Library_Unit_Environment (Symbol); Target_Env : Env_Item; List : Region_Item_List; procedure Append (Item : Region_Item) is begin Self.Region.Prepend (Value => Item, Input => Env.Region_List (Withed), Output => Env.Region_List (Withed)); end Append; begin if Target in 0 | Self.Library_Level_Environment then -- Fix constraint_error because library_bodies doesn have env yet return Index; end if; Target := Self.Leave_Declarative_Region (Target); Target_Env := Self.Env.Element (Target); List := Target_Env.Region_List (Other); -- Gela.Plain_Environments.Debug -- (Self => Self'Access, -- Index => Target); -- Self.Region.For_Each (List, Append'Access); Env_Index := Self.Env.Find_Index (Env); if Env_Index = 0 then Self.Env.Append (Env); Env_Index := Self.Env.Last_Index; end if; return Env_Index; end Add_With_Clause; -------------------- -- Direct_Visible -- -------------------- overriding function Direct_Visible (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index; Symbol : Gela.Lexical_Types.Symbol) return Gela.Defining_Name_Cursors.Defining_Name_Cursor'Class is Env : Env_Item; begin if Index = Gela.Library_Environments.Library_Env then return Self.Lib.Direct_Visible (Index, Symbol); elsif Index not in Env_Item_Index then return None : constant Direct_Visible_Cursors.Defining_Name_Cursor := (others => <>); end if; Env := Self.Env.Element (Index); return Result : Direct_Visible_Cursors.Defining_Name_Cursor := (Set => Plain_Environment_Set_Access (Self), Region => Env.Region_List (Nested), others => <>) do Result.Initialize (Symbol); end return; end Direct_Visible; ----------------------------- -- Enter_Completion_Region -- ----------------------------- overriding function Enter_Completion_Region (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index; Region : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is use type Region_Item_List; Env : Env_Item; Found : Gela.Semantic_Types.Env_Index; Spec : constant Region_Item_List := Name_To_Region (Self, Index, Region); Next : Region_Item := (Name => Region, Local => Self.Names.Empty_List, Use_Package => Defining_Name_Lists.Empty, Completion => Defining_Name_Lists.Empty, Rename => Self.Names.Empty_List); begin if Index in Env_Item_Index then Env := Self.Env.Element (Index); else Env := (Region_List => (Nested | Other | Withed => Region_Item_Lists.Empty)); end if; if Spec /= Region_Item_Lists.Empty then Next := Self.Region.Head (Spec); end if; -- Shall we delete region with the same Name from Other_Region_List? Self.Region.Prepend (Value => Next, Input => Env.Region_List (Nested), Output => Env.Region_List (Nested)); Found := Self.Env.Find_Index (Env); if Found not in Env_Item_Index then Self.Env.Append (Env); Found := Self.Env.Last_Index; end if; return Found; end Enter_Completion_Region; ------------------------------ -- Enter_Declarative_Region -- ------------------------------ overriding function Enter_Declarative_Region (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index; Region : Gela.Elements.Defining_Names.Defining_Name_Access) return Gela.Semantic_Types.Env_Index is Env : Env_Item; Found : Gela.Semantic_Types.Env_Index; Next : constant Region_Item := (Name => Region, Local => Self.Names.Empty_List, Use_Package => Defining_Name_Lists.Empty, Completion => Defining_Name_Lists.Empty, Rename => Self.Names.Empty_List); begin if Index in Env_Item_Index then Env := Self.Env.Element (Index); else Env := (Region_List => (Nested | Other | Withed => Region_Item_Lists.Empty)); end if; Self.Region.Prepend (Value => Next, Input => Env.Region_List (Nested), Output => Env.Region_List (Nested)); -- Shall we delete region with the same Name from Other_Region_List? -- Self.Region.Delete -- (Input => Env.Other_Region_List, -- Value => Next, -- Output => Env.Other_Region_List); Found := Self.Env.Find_Index (Env); if Found not in Env_Item_Index then Self.Env.Append (Env); Found := Self.Env.Last_Index; end if; return Found; end Enter_Declarative_Region; ---------- -- Hash -- ---------- function Hash (X : Gela.Lexical_Types.Symbol) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (X); end Hash; ---------- -- Hash -- ---------- function Hash (X : Gela.Semantic_Types.Env_Index) return Ada.Containers.Hash_Type is begin return Ada.Containers.Hash_Type (X); end Hash; ------------------------------ -- Leave_Declarative_Region -- ------------------------------ overriding function Leave_Declarative_Region (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index) return Gela.Semantic_Types.Env_Index is Found : Gela.Semantic_Types.Env_Index; Env : Env_Item := Self.Env.Element (Index); Region : constant Region_Item := Self.Region.Head (Env.Region_List (Nested)); begin -- Push top region to Other_Region_List Self.Region.Prepend (Value => Region, Input => Env.Region_List (Other), Output => Env.Region_List (Other)); -- Pop top region from Nested_Region_List Env.Region_List (Nested) := Self.Region.Tail (Env.Region_List (Nested)); Found := Self.Env.Find_Index (Env); if Found not in Env_Item_Index then Self.Env.Append (Env); Found := Self.Env.Last_Index; end if; return Found; end Leave_Declarative_Region; ------------------------------- -- Library_Level_Environment -- ------------------------------- overriding function Library_Level_Environment (Self : Environment_Set) return Gela.Semantic_Types.Env_Index is begin return Self.Lib.Library_Level_Environment; end Library_Level_Environment; ------------------------------ -- Library_Unit_Environment -- ------------------------------ overriding function Library_Unit_Environment (Self : access Environment_Set; Symbol : Gela.Lexical_Types.Symbol) return Gela.Semantic_Types.Env_Index is use type Gela.Lexical_Types.Symbol; begin if Symbol = 0 then return 0; else return Self.Units_Env.Element (Symbol); end if; end Library_Unit_Environment; -------------------- -- Name_To_Region -- -------------------- function Name_To_Region (Self : access Environment_Set'Class; Index : Gela.Semantic_Types.Env_Index; Name : Gela.Elements.Defining_Names.Defining_Name_Access) return Region_Item_List is use type Region_Item_List; use type Gela.Elements.Defining_Names.Defining_Name_Access; Env : constant Env_Item := Self.Env.Element (Index); Next : Region_Item_List; begin for J of Env.Region_List loop Next := J; while Next /= Region_Item_Lists.Empty loop if Self.Region.Head (Next).Name = Name then return Next; elsif Name.Assigned then declare Pos : constant Gela.Name_List_Managers.Defining_Name_Cursor := Self.Names.Find (Self.Region.Head (Next).Rename, Name.Full_Name); begin if Pos.Has_Element then return Name_To_Region (Self, Index, Pos.Element); end if; end; end if; Next := Self.Region.Tail (Next); end loop; end loop; return Region_Item_Lists.Empty; end Name_To_Region; ---------------------------------- -- Set_Library_Unit_Environment -- ---------------------------------- overriding procedure Set_Library_Unit_Environment (Self : access Environment_Set; Symbol : Gela.Lexical_Types.Symbol; Value : Gela.Semantic_Types.Env_Index) is begin Self.Units_Env.Include (Symbol, Value); Self.Lib_Env.Include (Value, Symbol); end Set_Library_Unit_Environment; ----------------- -- Use_Visible -- ----------------- overriding function Use_Visible (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index; Symbol : Gela.Lexical_Types.Symbol) return Gela.Defining_Name_Cursors.Defining_Name_Cursor'Class is begin if Index = Gela.Library_Environments.Library_Env then return Self.Lib.Use_Visible (Index, Symbol); end if; return Result : Use_Package_Cursors.Defining_Name_Cursor := (Set => Plain_Environment_Set_Access (Self), Env => Index, Region => Region_Item_Lists.Empty, Use_Name => Defining_Name_Lists.Empty, others => <>) do Result.Initialize (Symbol); end return; end Use_Visible; ------------- -- Visible -- ------------- overriding function Visible (Self : access Environment_Set; Index : Gela.Semantic_Types.Env_Index; Region : Gela.Elements.Defining_Names.Defining_Name_Access; Symbol : Gela.Lexical_Types.Symbol; Found : access Boolean) return Gela.Defining_Name_Cursors.Defining_Name_Cursor'Class is use type Region_Item_List; Item : Region_Item_List; begin Found.all := False; if Index = Gela.Library_Environments.Library_Env then return Self.Lib.Visible (Index, Region, Symbol, Found); elsif Index not in Env_Item_Index then return None : constant Visible_Cursors.Defining_Name_Cursor := (others => <>); end if; if Region.Assigned then Item := Name_To_Region (Self, Index, Region); else declare Env : constant Env_Item := Self.Env.Element (Index); begin Item := Env.Region_List (Nested); end; end if; if Item = Region_Item_Lists.Empty then return None : constant Visible_Cursors.Defining_Name_Cursor := (others => <>); end if; Found.all := True; return Result : Visible_Cursors.Defining_Name_Cursor := (Set => Plain_Environment_Set_Access (Self), others => <>) do Result.Initialize (Symbol, Item); end return; end Visible; end Gela.Plain_Environments;
reznikmm/matreshka
Ada
4,183
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This package provides implementation of string handling subprograms for -- x86 platform. This is default string handler to support string operations -- at application elaboration, it is intended to be replaced by more optimized -- version after determination of CPU capabilities. ------------------------------------------------------------------------------ with Matreshka.Internals.Strings.Handlers.Portable; package Matreshka.Internals.Strings.Handlers.X86 is pragma Preelaborate; type X86_String_Handler is new Matreshka.Internals.Strings.Handlers.Portable.Portable_String_Handler with null record; overriding procedure Fill_Null_Terminator (Self : X86_String_Handler; Item : not null Shared_String_Access); Handler : aliased X86_String_Handler; end Matreshka.Internals.Strings.Handlers.X86;
AdaCore/gpr
Ada
793
ads
-- -- Copyright (C) 2023, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 WITH LLVM-Exception -- -- This package provides to GPR library the known description of defined -- packages. with Ada.Containers; use Ada.Containers; package GPR2.Project.Registry.Pack.Description is procedure Set_Package_Description (Key : Package_Id; Description : String); -- Set a package description function Get_Package_Description (Key : Package_Id) return String; -- Retrieves a description for a given package private function Hash (Key : Package_Id) return Hash_Type; package Pack_Package_Description is new Indefinite_Hashed_Maps (Package_Id, String, Hash, "=", "="); Package_Description : Pack_Package_Description.Map; end GPR2.Project.Registry.Pack.Description;
charlie5/aIDE
Ada
1,632
adb
with AdaM.Factory; package body AdaM.Partition is -- Storage Pool -- record_Version : constant := 1; pool_Size : constant := 5_000; package Pool is new AdaM.Factory.Pools (".adam-store", "partitions", pool_Size, record_Version, Partition.item, Partition.view); -- Forge -- procedure define (Self : in out Item) is begin null; end define; procedure destruct (Self : in out Item) is begin null; end destruct; function new_Subprogram return View is new_View : constant Partition.view := Pool.new_Item; begin define (Partition.item (new_View.all)); return new_View; end new_Subprogram; procedure free (Self : in out Partition.view) is begin destruct (Partition.item (Self.all)); Pool.free (Self); end free; -- Attributes -- overriding function Id (Self : access Item) return AdaM.Id is begin return Pool.to_Id (Self); end Id; -- Streams -- procedure View_write (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : in View) renames Pool.View_write; procedure View_read (Stream : not null access Ada.Streams.Root_Stream_Type'Class; Self : out View) renames Pool.View_read; end AdaM.Partition;
reznikmm/matreshka
Ada
3,704
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Form_Readonly_Attributes is pragma Preelaborate; type ODF_Form_Readonly_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Form_Readonly_Attribute_Access is access all ODF_Form_Readonly_Attribute'Class with Storage_Size => 0; end ODF.DOM.Form_Readonly_Attributes;
AaronC98/PlaneSystem
Ada
5,902
ads
------------------------------------------------------------------------------ -- Ada Web Server -- -- -- -- Copyright (C) 2004-2015, AdaCore -- -- -- -- 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. -- -- -- -- -- -- -- -- -- -- -- -- 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/>. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ------------------------------------------------------------------------------ pragma Ada_2012; with Ada.Strings.Unbounded; package SOAP.Name_Space is type Object is private; Default_Prefix : constant String := "xmlns"; SOAP_URL : constant String := "http://schemas.xmlsoap.org/wsdl/soap/"; SOAPENC_URL : constant String := "http://schemas.xmlsoap.org/soap/encoding/"; SOAPENV_URL : constant String := "http://schemas.xmlsoap.org/soap/envelope/"; XSD_URL : constant String := "http://www.w3.org/2001/XMLSchema"; XSI_URL : constant String := "http://www.w3.org/2001/XMLSchema-instance"; WSDL_URL : constant String := "http://schemas.xmlsoap.org/wsdl/"; XSD : constant Object; XSI : constant Object; SOAP : constant Object; SOAPENC : constant Object; SOAPENV : constant Object; WSDL : constant Object; No_Name_Space : constant Object; function AWS return Object; -- Returns the AWS namespace (used to generate schema) procedure Set_AWS_NS (Value : String) with Post => Value = "soapaws" or else not Is_Default_AWS_NS; -- Set the root value of the AWS name-space. This is used by ada2wsdl to -- generate specific schema root name. function Is_Default_AWS_NS return Boolean; -- Returns whether the AWS NS is the default one or not. That is, if -- Set_AWS_NS has been called or not. function Create (Name, Value : String; Prefix : String := Default_Prefix) return Object; -- Returns a name space procedure Set (O : in out Object; Name, Value : String; Prefix : String := Default_Prefix); -- Set value for the name space object function Is_Defined (O : Object) return Boolean; -- Returns True if the name space is defined function Prefix (O : Object) return String; -- Returns the name space prefix function Name (O : Object) return String; -- Returns the name space name function Value (O : Object) return String; -- Returns the name space value function Image (O : Object) return String; -- Return the name space string representation prefix:name="value" private use Ada.Strings.Unbounded; type Object is record Prefix : Unbounded_String; Name : Unbounded_String; Value : Unbounded_String; end record; No_Name_Space : constant Object := (Null_Unbounded_String, Null_Unbounded_String, Null_Unbounded_String); XSD : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("xsd"), To_Unbounded_String (XSD_URL)); XSI : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("xsi"), To_Unbounded_String (XSI_URL)); SOAP : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("soap"), To_Unbounded_String (SOAP_URL)); SOAPENC : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("soapenc"), To_Unbounded_String (SOAPENC_URL)); SOAPENV : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("soapenv"), To_Unbounded_String (SOAPENV_URL)); WSDL : constant Object := (To_Unbounded_String (Default_Prefix), To_Unbounded_String ("wsdl"), To_Unbounded_String (WSDL_URL)); end SOAP.Name_Space;
charlie5/lace
Ada
1,953
adb
package body gel.Conversions is use Math; function to_GL (Self : in geometry_3d.bounding_Box) return openGL.Bounds is the_Bounds : opengl.Bounds := (Ball => <>, Box => (Lower => to_GL (Self.Lower), Upper => to_GL (Self.Upper))); begin openGL.set_Ball_from_Box (the_Bounds); return the_Bounds; end to_GL; function to_GL (Self : in Real) return opengl.Real is begin return opengl.Real (Self); exception when constraint_Error => if Self > 0.0 then return opengl.Real'Last; else return opengl.Real'First; end if; end to_GL; function to_GL (Self : in Vector_3) return opengl.Vector_3 is begin return [to_GL (Self (1)), to_GL (Self (2)), to_GL (Self (3))]; end to_GL; function to_GL (Self : in Matrix_3x3) return opengl.Matrix_3x3 is begin return [[to_gl (Self (1, 1)), to_gl (Self (1, 2)), to_gl (Self (1, 3))], [to_gl (Self (2, 1)), to_gl (Self (2, 2)), to_gl (Self (2, 3))], [to_gl (Self (3, 1)), to_gl (Self (3, 2)), to_gl (Self (3, 3))]]; end to_GL; function to_GL (Self : in Matrix_4x4) return opengl.Matrix_4x4 is begin return [[to_gl (Self (1, 1)), to_gl (Self (1, 2)), to_gl (Self (1, 3)), to_gl (Self (1, 4))], [to_gl (Self (2, 1)), to_gl (Self (2, 2)), to_gl (Self (2, 3)), to_gl (Self (2, 4))], [to_gl (Self (3, 1)), to_gl (Self (3, 2)), to_gl (Self (3, 3)), to_gl (Self (3, 4))], [to_gl (Self (4, 1)), to_gl (Self (4, 2)), to_gl (Self (4, 3)), to_gl (Self (4, 4))]]; end to_GL; function to_Math (Self : in opengl.Vector_3) return math.Vector_3 is begin return [Self (1), Self (2), Self (3)]; end to_Math; end gel.Conversions;
sungyeon/drake
Ada
1,021
ads
pragma License (Unrestricted); -- separated and auto-loaded by compiler private generic type Num is digits <>; package Ada.Wide_Text_IO.Float_IO is Default_Fore : Field := 2; Default_Aft : Field := Num'Digits - 1; Default_Exp : Field := 3; -- procedure Get ( -- File : File_Type; -- Input_File_Type -- Item : out Num; -- Width : Field := 0); -- procedure Get ( -- Item : out Num; -- Width : Field := 0); -- procedure Put ( -- File : File_Type; -- Output_File_Type -- Item : Num; -- Fore : Field := Default_Fore; -- Aft : Field := Default_Aft; -- Exp : Field := Default_Exp); -- procedure Put ( -- Item : Num; -- Fore : Field := Default_Fore; -- Aft : Field := Default_Aft; -- Exp : Field := Default_Exp); -- procedure Get ( -- From : String; -- Item : out Num; -- Last : out Positive); -- procedure Put ( -- To : out String; -- Item : Num; -- Aft : Field := Default_Aft; -- Exp : Field := Default_Exp); end Ada.Wide_Text_IO.Float_IO;
AdaCore/libadalang
Ada
166
adb
procedure Test1 is type Int is range 0 .. 10; A : Int; B : Int; begin A := B; pragma Test_Statement; A := 12; pragma Test_Statement; end Test1;
reznikmm/matreshka
Ada
17,769
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ with AMF.Elements; with AMF.Internals.Element_Collections; with AMF.Internals.Helpers; with AMF.Internals.Tables.OCL_Attributes; with AMF.OCL.Tuple_Literal_Parts.Collections; with AMF.UML.Comments.Collections; with AMF.UML.Dependencies.Collections; with AMF.UML.Elements.Collections; with AMF.UML.Named_Elements; with AMF.UML.Namespaces.Collections; with AMF.UML.Packages.Collections; with AMF.UML.String_Expressions; with AMF.UML.Types; with AMF.Visitors.OCL_Iterators; with AMF.Visitors.OCL_Visitors; with League.Strings.Internals; with Matreshka.Internals.Strings; package body AMF.Internals.OCL_Tuple_Literal_Exps is -------------- -- Get_Part -- -------------- overriding function Get_Part (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.OCL.Tuple_Literal_Parts.Collections.Ordered_Set_Of_OCL_Tuple_Literal_Part is begin return AMF.OCL.Tuple_Literal_Parts.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Part (Self.Element))); end Get_Part; -------------- -- Get_Type -- -------------- overriding function Get_Type (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Types.UML_Type_Access is begin return AMF.UML.Types.UML_Type_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Type (Self.Element))); end Get_Type; -------------- -- Set_Type -- -------------- overriding procedure Set_Type (Self : not null access OCL_Tuple_Literal_Exp_Proxy; To : AMF.UML.Types.UML_Type_Access) is begin AMF.Internals.Tables.OCL_Attributes.Internal_Set_Type (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Type; --------------------------- -- Get_Client_Dependency -- --------------------------- overriding function Get_Client_Dependency (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Dependencies.Collections.Set_Of_UML_Dependency is begin return AMF.UML.Dependencies.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Client_Dependency (Self.Element))); end Get_Client_Dependency; -------------- -- Get_Name -- -------------- overriding function Get_Name (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.Optional_String is begin declare use type Matreshka.Internals.Strings.Shared_String_Access; Aux : constant Matreshka.Internals.Strings.Shared_String_Access := AMF.Internals.Tables.OCL_Attributes.Internal_Get_Name (Self.Element); begin if Aux = null then return (Is_Empty => True); else return (False, League.Strings.Internals.Create (Aux)); end if; end; end Get_Name; -------------- -- Set_Name -- -------------- overriding procedure Set_Name (Self : not null access OCL_Tuple_Literal_Exp_Proxy; To : AMF.Optional_String) is begin if To.Is_Empty then AMF.Internals.Tables.OCL_Attributes.Internal_Set_Name (Self.Element, null); else AMF.Internals.Tables.OCL_Attributes.Internal_Set_Name (Self.Element, League.Strings.Internals.Internal (To.Value)); end if; end Set_Name; ------------------------- -- Get_Name_Expression -- ------------------------- overriding function Get_Name_Expression (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.String_Expressions.UML_String_Expression_Access is begin return AMF.UML.String_Expressions.UML_String_Expression_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Name_Expression (Self.Element))); end Get_Name_Expression; ------------------------- -- Set_Name_Expression -- ------------------------- overriding procedure Set_Name_Expression (Self : not null access OCL_Tuple_Literal_Exp_Proxy; To : AMF.UML.String_Expressions.UML_String_Expression_Access) is begin AMF.Internals.Tables.OCL_Attributes.Internal_Set_Name_Expression (Self.Element, AMF.Internals.Helpers.To_Element (AMF.Elements.Element_Access (To))); end Set_Name_Expression; ------------------- -- Get_Namespace -- ------------------- overriding function Get_Namespace (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin return AMF.UML.Namespaces.UML_Namespace_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Namespace (Self.Element))); end Get_Namespace; ------------------------ -- Get_Qualified_Name -- ------------------------ overriding function Get_Qualified_Name (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.Optional_String is begin declare use type Matreshka.Internals.Strings.Shared_String_Access; Aux : constant Matreshka.Internals.Strings.Shared_String_Access := AMF.Internals.Tables.OCL_Attributes.Internal_Get_Qualified_Name (Self.Element); begin if Aux = null then return (Is_Empty => True); else return (False, League.Strings.Internals.Create (Aux)); end if; end; end Get_Qualified_Name; -------------------- -- Get_Visibility -- -------------------- overriding function Get_Visibility (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Optional_UML_Visibility_Kind is begin return AMF.Internals.Tables.OCL_Attributes.Internal_Get_Visibility (Self.Element); end Get_Visibility; -------------------- -- Set_Visibility -- -------------------- overriding procedure Set_Visibility (Self : not null access OCL_Tuple_Literal_Exp_Proxy; To : AMF.UML.Optional_UML_Visibility_Kind) is begin AMF.Internals.Tables.OCL_Attributes.Internal_Set_Visibility (Self.Element, To); end Set_Visibility; ----------------------- -- Get_Owned_Comment -- ----------------------- overriding function Get_Owned_Comment (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Comments.Collections.Set_Of_UML_Comment is begin return AMF.UML.Comments.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Owned_Comment (Self.Element))); end Get_Owned_Comment; ----------------------- -- Get_Owned_Element -- ----------------------- overriding function Get_Owned_Element (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Elements.Collections.Set_Of_UML_Element is begin return AMF.UML.Elements.Collections.Wrap (AMF.Internals.Element_Collections.Wrap (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Owned_Element (Self.Element))); end Get_Owned_Element; --------------- -- Get_Owner -- --------------- overriding function Get_Owner (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Elements.UML_Element_Access is begin return AMF.UML.Elements.UML_Element_Access (AMF.Internals.Helpers.To_Element (AMF.Internals.Tables.OCL_Attributes.Internal_Get_Owner (Self.Element))); end Get_Owner; -------------------- -- All_Namespaces -- -------------------- overriding function All_Namespaces (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Namespaces.Collections.Ordered_Set_Of_UML_Namespace is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "All_Namespaces unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.All_Namespaces"; return All_Namespaces (Self); end All_Namespaces; ------------------------- -- All_Owning_Packages -- ------------------------- overriding function All_Owning_Packages (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Packages.Collections.Set_Of_UML_Package is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "All_Owning_Packages unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.All_Owning_Packages"; return All_Owning_Packages (Self); end All_Owning_Packages; ----------------------------- -- Is_Distinguishable_From -- ----------------------------- overriding function Is_Distinguishable_From (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy; N : AMF.UML.Named_Elements.UML_Named_Element_Access; Ns : AMF.UML.Namespaces.UML_Namespace_Access) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Is_Distinguishable_From unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.Is_Distinguishable_From"; return Is_Distinguishable_From (Self, N, Ns); end Is_Distinguishable_From; --------------- -- Namespace -- --------------- overriding function Namespace (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Namespace unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.Namespace"; return Namespace (Self); end Namespace; -------------------- -- Qualified_Name -- -------------------- overriding function Qualified_Name (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return League.Strings.Universal_String is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Qualified_Name unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.Qualified_Name"; return Qualified_Name (Self); end Qualified_Name; --------------- -- Separator -- --------------- overriding function Separator (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return League.Strings.Universal_String is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Separator unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.Separator"; return Separator (Self); end Separator; ------------------------ -- All_Owned_Elements -- ------------------------ overriding function All_Owned_Elements (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return AMF.UML.Elements.Collections.Set_Of_UML_Element is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "All_Owned_Elements unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.All_Owned_Elements"; return All_Owned_Elements (Self); end All_Owned_Elements; ------------------- -- Must_Be_Owned -- ------------------- overriding function Must_Be_Owned (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy) return Boolean is begin -- Generated stub: replace with real body! pragma Compile_Time_Warning (Standard.True, "Must_Be_Owned unimplemented"); raise Program_Error with "Unimplemented procedure OCL_Tuple_Literal_Exp_Proxy.Must_Be_Owned"; return Must_Be_Owned (Self); end Must_Be_Owned; ------------------- -- Enter_Element -- ------------------- overriding procedure Enter_Element (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.OCL_Visitors.OCL_Visitor'Class then AMF.Visitors.OCL_Visitors.OCL_Visitor'Class (Visitor).Enter_Tuple_Literal_Exp (AMF.OCL.Tuple_Literal_Exps.OCL_Tuple_Literal_Exp_Access (Self), Control); end if; end Enter_Element; ------------------- -- Leave_Element -- ------------------- overriding procedure Leave_Element (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Visitor in AMF.Visitors.OCL_Visitors.OCL_Visitor'Class then AMF.Visitors.OCL_Visitors.OCL_Visitor'Class (Visitor).Leave_Tuple_Literal_Exp (AMF.OCL.Tuple_Literal_Exps.OCL_Tuple_Literal_Exp_Access (Self), Control); end if; end Leave_Element; ------------------- -- Visit_Element -- ------------------- overriding procedure Visit_Element (Self : not null access constant OCL_Tuple_Literal_Exp_Proxy; Iterator : in out AMF.Visitors.Abstract_Iterator'Class; Visitor : in out AMF.Visitors.Abstract_Visitor'Class; Control : in out AMF.Visitors.Traverse_Control) is begin if Iterator in AMF.Visitors.OCL_Iterators.OCL_Iterator'Class then AMF.Visitors.OCL_Iterators.OCL_Iterator'Class (Iterator).Visit_Tuple_Literal_Exp (Visitor, AMF.OCL.Tuple_Literal_Exps.OCL_Tuple_Literal_Exp_Access (Self), Control); end if; end Visit_Element; end AMF.Internals.OCL_Tuple_Literal_Exps;
zhmu/ananas
Ada
3,071
ads
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- C S T A N D -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the procedure that is used to create the tree for -- package Standard and initialize the entities in package Stand. with Types; use Types; package CStand is procedure Create_Standard; -- This procedure creates the tree for package standard, and initializes -- the Standard_Entities array and Standard_Package_Node. First the -- syntactic representation is created (as though the parser had parsed -- a copy of the source of Standard) and then semantic information is -- added as it would be by the semantic phases of the compiler. The -- tree is in the standard format defined by Syntax_Info, except that -- all Sloc values are set to Standard_Location except for nodes that -- are part of package ASCII, which have Sloc = Standard_ASCII_Location. -- The semantics info is in the format given by Entity_Info. The global -- variables Last_Standard_Node_Id and Last_Standard_List_Id are also set. procedure Set_Float_Bounds (Id : Entity_Id); -- Procedure to set bounds for float type or subtype. Id is the entity -- whose bounds and type are to be set (a floating-point type). end CStand;
AdaCore/libadalang
Ada
478,360
adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S E M _ R E S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2017, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Debug; use Debug; with Debug_A; use Debug_A; with Einfo; use Einfo; with Errout; use Errout; with Expander; use Expander; with Exp_Disp; use Exp_Disp; with Exp_Ch6; use Exp_Ch6; with Exp_Ch7; use Exp_Ch7; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Fname; use Fname; with Freeze; use Freeze; with Ghost; use Ghost; with Inline; use Inline; with Itypes; use Itypes; with Lib; use Lib; with Lib.Xref; use Lib.Xref; with Namet; use Namet; with Nmake; use Nmake; with Nlists; use Nlists; with Opt; use Opt; with Output; use Output; with Par_SCO; use Par_SCO; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Aggr; use Sem_Aggr; with Sem_Attr; use Sem_Attr; with Sem_Cat; use Sem_Cat; with Sem_Ch4; use Sem_Ch4; with Sem_Ch3; use Sem_Ch3; with Sem_Ch6; use Sem_Ch6; with Sem_Ch8; use Sem_Ch8; with Sem_Ch13; use Sem_Ch13; with Sem_Dim; use Sem_Dim; with Sem_Disp; use Sem_Disp; with Sem_Dist; use Sem_Dist; with Sem_Elim; use Sem_Elim; with Sem_Elab; use Sem_Elab; with Sem_Eval; use Sem_Eval; with Sem_Intr; use Sem_Intr; with Sem_Util; use Sem_Util; with Targparm; use Targparm; with Sem_Type; use Sem_Type; with Sem_Warn; use Sem_Warn; with Sinfo; use Sinfo; with Sinfo.CN; use Sinfo.CN; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with Style; use Style; with Tbuild; use Tbuild; with Uintp; use Uintp; with Urealp; use Urealp; package body Sem_Res is ----------------------- -- Local Subprograms -- ----------------------- -- Second pass (top-down) type checking and overload resolution procedures -- Typ is the type required by context. These procedures propagate the -- type information recursively to the descendants of N. If the node is not -- overloaded, its Etype is established in the first pass. If overloaded, -- the Resolve routines set the correct type. For arithmetic operators, the -- Etype is the base type of the context. -- Note that Resolve_Attribute is separated off in Sem_Attr procedure Check_Discriminant_Use (N : Node_Id); -- Enforce the restrictions on the use of discriminants when constraining -- a component of a discriminated type (record or concurrent type). procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id); -- Given a node for an operator associated with type T, check that the -- operator is visible. Operators all of whose operands are universal must -- be checked for visibility during resolution because their type is not -- determinable based on their operands. procedure Check_Fully_Declared_Prefix (Typ : Entity_Id; Pref : Node_Id); -- Check that the type of the prefix of a dereference is not incomplete function Check_Infinite_Recursion (N : Node_Id) return Boolean; -- Given a call node, N, which is known to occur immediately within the -- subprogram being called, determines whether it is a detectable case of -- an infinite recursion, and if so, outputs appropriate messages. Returns -- True if an infinite recursion is detected, and False otherwise. procedure Check_Initialization_Call (N : Entity_Id; Nam : Entity_Id); -- If the type of the object being initialized uses the secondary stack -- directly or indirectly, create a transient scope for the call to the -- init proc. This is because we do not create transient scopes for the -- initialization of individual components within the init proc itself. -- Could be optimized away perhaps? procedure Check_No_Direct_Boolean_Operators (N : Node_Id); -- N is the node for a logical operator. If the operator is predefined, and -- the root type of the operands is Standard.Boolean, then a check is made -- for restriction No_Direct_Boolean_Operators. This procedure also handles -- the style check for Style_Check_Boolean_And_Or. function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean; -- N is either an indexed component or a selected component. This function -- returns true if the prefix refers to an object that has an address -- clause (the case in which we may want to issue a warning). function Is_Definite_Access_Type (E : Entity_Id) return Boolean; -- Determine whether E is an access type declared by an access declaration, -- and not an (anonymous) allocator type. function Is_Predefined_Op (Nam : Entity_Id) return Boolean; -- Utility to check whether the entity for an operator is a predefined -- operator, in which case the expression is left as an operator in the -- tree (else it is rewritten into a call). An instance of an intrinsic -- conversion operation may be given an operator name, but is not treated -- like an operator. Note that an operator that is an imported back-end -- builtin has convention Intrinsic, but is expected to be rewritten into -- a call, so such an operator is not treated as predefined by this -- predicate. procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id); -- If a default expression in entry call N depends on the discriminants -- of the task, it must be replaced with a reference to the discriminant -- of the task being called. procedure Resolve_Op_Concat_Arg (N : Node_Id; Arg : Node_Id; Typ : Entity_Id; Is_Comp : Boolean); -- Internal procedure for Resolve_Op_Concat to resolve one operand of -- concatenation operator. The operand is either of the array type or of -- the component type. If the operand is an aggregate, and the component -- type is composite, this is ambiguous if component type has aggregates. procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id); -- Does the first part of the work of Resolve_Op_Concat procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id); -- Does the "rest" of the work of Resolve_Op_Concat, after the left operand -- has been resolved. See Resolve_Op_Concat for details. procedure Resolve_Allocator (N : Node_Id; Typ : Entity_Id); procedure Resolve_Arithmetic_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Call (N : Node_Id; Typ : Entity_Id); procedure Resolve_Case_Expression (N : Node_Id; Typ : Entity_Id); procedure Resolve_Character_Literal (N : Node_Id; Typ : Entity_Id); procedure Resolve_Comparison_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Entity_Name (N : Node_Id; Typ : Entity_Id); procedure Resolve_Equality_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Explicit_Dereference (N : Node_Id; Typ : Entity_Id); procedure Resolve_Expression_With_Actions (N : Node_Id; Typ : Entity_Id); procedure Resolve_If_Expression (N : Node_Id; Typ : Entity_Id); procedure Resolve_Generalized_Indexing (N : Node_Id; Typ : Entity_Id); procedure Resolve_Indexed_Component (N : Node_Id; Typ : Entity_Id); procedure Resolve_Integer_Literal (N : Node_Id; Typ : Entity_Id); procedure Resolve_Logical_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Membership_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Null (N : Node_Id; Typ : Entity_Id); procedure Resolve_Operator_Symbol (N : Node_Id; Typ : Entity_Id); procedure Resolve_Op_Concat (N : Node_Id; Typ : Entity_Id); procedure Resolve_Op_Expon (N : Node_Id; Typ : Entity_Id); procedure Resolve_Op_Not (N : Node_Id; Typ : Entity_Id); procedure Resolve_Qualified_Expression (N : Node_Id; Typ : Entity_Id); procedure Resolve_Raise_Expression (N : Node_Id; Typ : Entity_Id); procedure Resolve_Range (N : Node_Id; Typ : Entity_Id); procedure Resolve_Real_Literal (N : Node_Id; Typ : Entity_Id); procedure Resolve_Reference (N : Node_Id; Typ : Entity_Id); procedure Resolve_Selected_Component (N : Node_Id; Typ : Entity_Id); procedure Resolve_Shift (N : Node_Id; Typ : Entity_Id); procedure Resolve_Short_Circuit (N : Node_Id; Typ : Entity_Id); procedure Resolve_Slice (N : Node_Id; Typ : Entity_Id); procedure Resolve_String_Literal (N : Node_Id; Typ : Entity_Id); procedure Resolve_Target_Name (N : Node_Id; Typ : Entity_Id); procedure Resolve_Type_Conversion (N : Node_Id; Typ : Entity_Id); procedure Resolve_Unary_Op (N : Node_Id; Typ : Entity_Id); procedure Resolve_Unchecked_Expression (N : Node_Id; Typ : Entity_Id); procedure Resolve_Unchecked_Type_Conversion (N : Node_Id; Typ : Entity_Id); function Operator_Kind (Op_Name : Name_Id; Is_Binary : Boolean) return Node_Kind; -- Utility to map the name of an operator into the corresponding Node. Used -- by other node rewriting procedures. procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id); -- Resolve actuals of call, and add default expressions for missing ones. -- N is the Node_Id for the subprogram call, and Nam is the entity of the -- called subprogram. procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id); -- Called from Resolve_Call, when the prefix denotes an entry or element -- of entry family. Actuals are resolved as for subprograms, and the node -- is rebuilt as an entry call. Also called for protected operations. Typ -- is the context type, which is used when the operation is a protected -- function with no arguments, and the return value is indexed. procedure Resolve_Intrinsic_Operator (N : Node_Id; Typ : Entity_Id); -- A call to a user-defined intrinsic operator is rewritten as a call to -- the corresponding predefined operator, with suitable conversions. Note -- that this applies only for intrinsic operators that denote predefined -- operators, not ones that are intrinsic imports of back-end builtins. procedure Resolve_Intrinsic_Unary_Operator (N : Node_Id; Typ : Entity_Id); -- Ditto, for arithmetic unary operators procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id); -- If an operator node resolves to a call to a user-defined operator, -- rewrite the node as a function call. procedure Make_Call_Into_Operator (N : Node_Id; Typ : Entity_Id; Op_Id : Entity_Id); -- Inverse transformation: if an operator is given in functional notation, -- then after resolving the node, transform into an operator node, so that -- operands are resolved properly. Recall that predefined operators do not -- have a full signature and special resolution rules apply. procedure Rewrite_Renamed_Operator (N : Node_Id; Op : Entity_Id; Typ : Entity_Id); -- An operator can rename another, e.g. in an instantiation. In that -- case, the proper operator node must be constructed and resolved. procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id); -- The String_Literal_Subtype is built for all strings that are not -- operands of a static concatenation operation. If the argument is not -- a N_String_Literal node, then the call has no effect. procedure Set_Slice_Subtype (N : Node_Id); -- Build subtype of array type, with the range specified by the slice procedure Simplify_Type_Conversion (N : Node_Id); -- Called after N has been resolved and evaluated, but before range checks -- have been applied. Currently simplifies a combination of floating-point -- to integer conversion and Rounding or Truncation attribute. function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id; -- A universal_fixed expression in an universal context is unambiguous if -- there is only one applicable fixed point type. Determining whether there -- is only one requires a search over all visible entities, and happens -- only in very pathological cases (see 6115-006). ------------------------- -- Ambiguous_Character -- ------------------------- procedure Ambiguous_Character (C : Node_Id) is E : Entity_Id; begin if Nkind (C) = N_Character_Literal then Error_Msg_N ("ambiguous character literal", C); -- First the ones in Standard Error_Msg_N ("\\possible interpretation: Character!", C); Error_Msg_N ("\\possible interpretation: Wide_Character!", C); -- Include Wide_Wide_Character in Ada 2005 mode if Ada_Version >= Ada_2005 then Error_Msg_N ("\\possible interpretation: Wide_Wide_Character!", C); end if; -- Now any other types that match E := Current_Entity (C); while Present (E) loop Error_Msg_NE ("\\possible interpretation:}!", C, Etype (E)); E := Homonym (E); end loop; end if; end Ambiguous_Character; ------------------------- -- Analyze_And_Resolve -- ------------------------- procedure Analyze_And_Resolve (N : Node_Id) is begin Analyze (N); Resolve (N); end Analyze_And_Resolve; procedure Analyze_And_Resolve (N : Node_Id; Typ : Entity_Id) is begin Analyze (N); Resolve (N, Typ); end Analyze_And_Resolve; -- Versions with check(s) suppressed procedure Analyze_And_Resolve (N : Node_Id; Typ : Entity_Id; Suppress : Check_Id) is Scop : constant Entity_Id := Current_Scope; begin if Suppress = All_Checks then declare Sva : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Analyze_And_Resolve (N, Typ); Scope_Suppress.Suppress := Sva; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Analyze_And_Resolve (N, Typ); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; if Current_Scope /= Scop and then Scope_Is_Transient then -- This can only happen if a transient scope was created for an inner -- expression, which will be removed upon completion of the analysis -- of an enclosing construct. The transient scope must have the -- suppress status of the enclosing environment, not of this Analyze -- call. Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress := Scope_Suppress; end if; end Analyze_And_Resolve; procedure Analyze_And_Resolve (N : Node_Id; Suppress : Check_Id) is Scop : constant Entity_Id := Current_Scope; begin if Suppress = All_Checks then declare Sva : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Analyze_And_Resolve (N); Scope_Suppress.Suppress := Sva; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Analyze_And_Resolve (N); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; if Current_Scope /= Scop and then Scope_Is_Transient then Scope_Stack.Table (Scope_Stack.Last).Save_Scope_Suppress := Scope_Suppress; end if; end Analyze_And_Resolve; ---------------------------- -- Check_Discriminant_Use -- ---------------------------- procedure Check_Discriminant_Use (N : Node_Id) is PN : constant Node_Id := Parent (N); Disc : constant Entity_Id := Entity (N); P : Node_Id; D : Node_Id; begin -- Any use in a spec-expression is legal if In_Spec_Expression then null; elsif Nkind (PN) = N_Range then -- Discriminant cannot be used to constrain a scalar type P := Parent (PN); if Nkind (P) = N_Range_Constraint and then Nkind (Parent (P)) = N_Subtype_Indication and then Nkind (Parent (Parent (P))) = N_Component_Definition then Error_Msg_N ("discriminant cannot constrain scalar type", N); elsif Nkind (P) = N_Index_Or_Discriminant_Constraint then -- The following check catches the unusual case where a -- discriminant appears within an index constraint that is part -- of a larger expression within a constraint on a component, -- e.g. "C : Int range 1 .. F (new A(1 .. D))". For now we only -- check case of record components, and note that a similar check -- should also apply in the case of discriminant constraints -- below. ??? -- Note that the check for N_Subtype_Declaration below is to -- detect the valid use of discriminants in the constraints of a -- subtype declaration when this subtype declaration appears -- inside the scope of a record type (which is syntactically -- illegal, but which may be created as part of derived type -- processing for records). See Sem_Ch3.Build_Derived_Record_Type -- for more info. if Ekind (Current_Scope) = E_Record_Type and then Scope (Disc) = Current_Scope and then not (Nkind (Parent (P)) = N_Subtype_Indication and then Nkind_In (Parent (Parent (P)), N_Component_Definition, N_Subtype_Declaration) and then Paren_Count (N) = 0) then Error_Msg_N ("discriminant must appear alone in component constraint", N); return; end if; -- Detect a common error: -- type R (D : Positive := 100) is record -- Name : String (1 .. D); -- end record; -- The default value causes an object of type R to be allocated -- with room for Positive'Last characters. The RM does not mandate -- the allocation of the maximum size, but that is what GNAT does -- so we should warn the programmer that there is a problem. Check_Large : declare SI : Node_Id; T : Entity_Id; TB : Node_Id; CB : Entity_Id; function Large_Storage_Type (T : Entity_Id) return Boolean; -- Return True if type T has a large enough range that any -- array whose index type covered the whole range of the type -- would likely raise Storage_Error. ------------------------ -- Large_Storage_Type -- ------------------------ function Large_Storage_Type (T : Entity_Id) return Boolean is begin -- The type is considered large if its bounds are known at -- compile time and if it requires at least as many bits as -- a Positive to store the possible values. return Compile_Time_Known_Value (Type_Low_Bound (T)) and then Compile_Time_Known_Value (Type_High_Bound (T)) and then Minimum_Size (T, Biased => True) >= RM_Size (Standard_Positive); end Large_Storage_Type; -- Start of processing for Check_Large begin -- Check that the Disc has a large range if not Large_Storage_Type (Etype (Disc)) then goto No_Danger; end if; -- If the enclosing type is limited, we allocate only the -- default value, not the maximum, and there is no need for -- a warning. if Is_Limited_Type (Scope (Disc)) then goto No_Danger; end if; -- Check that it is the high bound if N /= High_Bound (PN) or else No (Discriminant_Default_Value (Disc)) then goto No_Danger; end if; -- Check the array allows a large range at this bound. First -- find the array SI := Parent (P); if Nkind (SI) /= N_Subtype_Indication then goto No_Danger; end if; T := Entity (Subtype_Mark (SI)); if not Is_Array_Type (T) then goto No_Danger; end if; -- Next, find the dimension TB := First_Index (T); CB := First (Constraints (P)); while True and then Present (TB) and then Present (CB) and then CB /= PN loop Next_Index (TB); Next (CB); end loop; if CB /= PN then goto No_Danger; end if; -- Now, check the dimension has a large range if not Large_Storage_Type (Etype (TB)) then goto No_Danger; end if; -- Warn about the danger Error_Msg_N ("??creation of & object may raise Storage_Error!", Scope (Disc)); <<No_Danger>> null; end Check_Large; end if; -- Legal case is in index or discriminant constraint elsif Nkind_In (PN, N_Index_Or_Discriminant_Constraint, N_Discriminant_Association) then if Paren_Count (N) > 0 then Error_Msg_N ("discriminant in constraint must appear alone", N); elsif Nkind (N) = N_Expanded_Name and then Comes_From_Source (N) then Error_Msg_N ("discriminant must appear alone as a direct name", N); end if; return; -- Otherwise, context is an expression. It should not be within (i.e. a -- subexpression of) a constraint for a component. else D := PN; P := Parent (PN); while not Nkind_In (P, N_Component_Declaration, N_Subtype_Indication, N_Entry_Declaration) loop D := P; P := Parent (P); exit when No (P); end loop; -- If the discriminant is used in an expression that is a bound of a -- scalar type, an Itype is created and the bounds are attached to -- its range, not to the original subtype indication. Such use is of -- course a double fault. if (Nkind (P) = N_Subtype_Indication and then Nkind_In (Parent (P), N_Component_Definition, N_Derived_Type_Definition) and then D = Constraint (P)) -- The constraint itself may be given by a subtype indication, -- rather than by a more common discrete range. or else (Nkind (P) = N_Subtype_Indication and then Nkind (Parent (P)) = N_Index_Or_Discriminant_Constraint) or else Nkind (P) = N_Entry_Declaration or else Nkind (D) = N_Defining_Identifier then Error_Msg_N ("discriminant in constraint must appear alone", N); end if; end if; end Check_Discriminant_Use; -------------------------------- -- Check_For_Visible_Operator -- -------------------------------- procedure Check_For_Visible_Operator (N : Node_Id; T : Entity_Id) is begin if Is_Invisible_Operator (N, T) then Error_Msg_NE -- CODEFIX ("operator for} is not directly visible!", N, First_Subtype (T)); Error_Msg_N -- CODEFIX ("use clause would make operation legal!", N); end if; end Check_For_Visible_Operator; ---------------------------------- -- Check_Fully_Declared_Prefix -- ---------------------------------- procedure Check_Fully_Declared_Prefix (Typ : Entity_Id; Pref : Node_Id) is begin -- Check that the designated type of the prefix of a dereference is -- not an incomplete type. This cannot be done unconditionally, because -- dereferences of private types are legal in default expressions. This -- case is taken care of in Check_Fully_Declared, called below. There -- are also 2005 cases where it is legal for the prefix to be unfrozen. -- This consideration also applies to similar checks for allocators, -- qualified expressions, and type conversions. -- An additional exception concerns other per-object expressions that -- are not directly related to component declarations, in particular -- representation pragmas for tasks. These will be per-object -- expressions if they depend on discriminants or some global entity. -- If the task has access discriminants, the designated type may be -- incomplete at the point the expression is resolved. This resolution -- takes place within the body of the initialization procedure, where -- the discriminant is replaced by its discriminal. if Is_Entity_Name (Pref) and then Ekind (Entity (Pref)) = E_In_Parameter then null; -- Ada 2005 (AI-326): Tagged incomplete types allowed. The wrong usages -- are handled by Analyze_Access_Attribute, Analyze_Assignment, -- Analyze_Object_Renaming, and Freeze_Entity. elsif Ada_Version >= Ada_2005 and then Is_Entity_Name (Pref) and then Is_Access_Type (Etype (Pref)) and then Ekind (Directly_Designated_Type (Etype (Pref))) = E_Incomplete_Type and then Is_Tagged_Type (Directly_Designated_Type (Etype (Pref))) then null; else Check_Fully_Declared (Typ, Parent (Pref)); end if; end Check_Fully_Declared_Prefix; ------------------------------ -- Check_Infinite_Recursion -- ------------------------------ function Check_Infinite_Recursion (N : Node_Id) return Boolean is P : Node_Id; C : Node_Id; function Same_Argument_List return Boolean; -- Check whether list of actuals is identical to list of formals of -- called function (which is also the enclosing scope). ------------------------ -- Same_Argument_List -- ------------------------ function Same_Argument_List return Boolean is A : Node_Id; F : Entity_Id; Subp : Entity_Id; begin if not Is_Entity_Name (Name (N)) then return False; else Subp := Entity (Name (N)); end if; F := First_Formal (Subp); A := First_Actual (N); while Present (F) and then Present (A) loop if not Is_Entity_Name (A) or else Entity (A) /= F then return False; end if; Next_Actual (A); Next_Formal (F); end loop; return True; end Same_Argument_List; -- Start of processing for Check_Infinite_Recursion begin -- Special case, if this is a procedure call and is a call to the -- current procedure with the same argument list, then this is for -- sure an infinite recursion and we insert a call to raise SE. if Is_List_Member (N) and then List_Length (List_Containing (N)) = 1 and then Same_Argument_List then declare P : constant Node_Id := Parent (N); begin if Nkind (P) = N_Handled_Sequence_Of_Statements and then Nkind (Parent (P)) = N_Subprogram_Body and then Is_Empty_List (Declarations (Parent (P))) then Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("!infinite recursion<<", N); Error_Msg_N ("\!Storage_Error [<<", N); Insert_Action (N, Make_Raise_Storage_Error (Sloc (N), Reason => SE_Infinite_Recursion)); return True; end if; end; end if; -- If not that special case, search up tree, quitting if we reach a -- construct (e.g. a conditional) that tells us that this is not a -- case for an infinite recursion warning. C := N; loop P := Parent (C); -- If no parent, then we were not inside a subprogram, this can for -- example happen when processing certain pragmas in a spec. Just -- return False in this case. if No (P) then return False; end if; -- Done if we get to subprogram body, this is definitely an infinite -- recursion case if we did not find anything to stop us. exit when Nkind (P) = N_Subprogram_Body; -- If appearing in conditional, result is false if Nkind_In (P, N_Or_Else, N_And_Then, N_Case_Expression, N_Case_Statement, N_If_Expression, N_If_Statement) then return False; elsif Nkind (P) = N_Handled_Sequence_Of_Statements and then C /= First (Statements (P)) then -- If the call is the expression of a return statement and the -- actuals are identical to the formals, it's worth a warning. -- However, we skip this if there is an immediately preceding -- raise statement, since the call is never executed. -- Furthermore, this corresponds to a common idiom: -- function F (L : Thing) return Boolean is -- begin -- raise Program_Error; -- return F (L); -- end F; -- for generating a stub function if Nkind (Parent (N)) = N_Simple_Return_Statement and then Same_Argument_List then exit when not Is_List_Member (Parent (N)); -- OK, return statement is in a statement list, look for raise declare Nod : Node_Id; begin -- Skip past N_Freeze_Entity nodes generated by expansion Nod := Prev (Parent (N)); while Present (Nod) and then Nkind (Nod) = N_Freeze_Entity loop Prev (Nod); end loop; -- If no raise statement, give warning. We look at the -- original node, because in the case of "raise ... with -- ...", the node has been transformed into a call. exit when Nkind (Original_Node (Nod)) /= N_Raise_Statement and then (Nkind (Nod) not in N_Raise_xxx_Error or else Present (Condition (Nod))); end; end if; return False; else C := P; end if; end loop; Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("!possible infinite recursion<<", N); Error_Msg_N ("\!??Storage_Error ]<<", N); return True; end Check_Infinite_Recursion; ------------------------------- -- Check_Initialization_Call -- ------------------------------- procedure Check_Initialization_Call (N : Entity_Id; Nam : Entity_Id) is Typ : constant Entity_Id := Etype (First_Formal (Nam)); function Uses_SS (T : Entity_Id) return Boolean; -- Check whether the creation of an object of the type will involve -- use of the secondary stack. If T is a record type, this is true -- if the expression for some component uses the secondary stack, e.g. -- through a call to a function that returns an unconstrained value. -- False if T is controlled, because cleanups occur elsewhere. ------------- -- Uses_SS -- ------------- function Uses_SS (T : Entity_Id) return Boolean is Comp : Entity_Id; Expr : Node_Id; Full_Type : Entity_Id := Underlying_Type (T); begin -- Normally we want to use the underlying type, but if it's not set -- then continue with T. if not Present (Full_Type) then Full_Type := T; end if; if Is_Controlled (Full_Type) then return False; elsif Is_Array_Type (Full_Type) then return Uses_SS (Component_Type (Full_Type)); elsif Is_Record_Type (Full_Type) then Comp := First_Component (Full_Type); while Present (Comp) loop if Ekind (Comp) = E_Component and then Nkind (Parent (Comp)) = N_Component_Declaration then -- The expression for a dynamic component may be rewritten -- as a dereference, so retrieve original node. Expr := Original_Node (Expression (Parent (Comp))); -- Return True if the expression is a call to a function -- (including an attribute function such as Image, or a -- user-defined operator) with a result that requires a -- transient scope. if (Nkind (Expr) = N_Function_Call or else Nkind (Expr) in N_Op or else (Nkind (Expr) = N_Attribute_Reference and then Present (Expressions (Expr)))) and then Requires_Transient_Scope (Etype (Expr)) then return True; elsif Uses_SS (Etype (Comp)) then return True; end if; end if; Next_Component (Comp); end loop; return False; else return False; end if; end Uses_SS; -- Start of processing for Check_Initialization_Call begin -- Establish a transient scope if the type needs it if Uses_SS (Typ) then Establish_Transient_Scope (First_Actual (N), Sec_Stack => True); end if; end Check_Initialization_Call; --------------------------------------- -- Check_No_Direct_Boolean_Operators -- --------------------------------------- procedure Check_No_Direct_Boolean_Operators (N : Node_Id) is begin if Scope (Entity (N)) = Standard_Standard and then Root_Type (Etype (Left_Opnd (N))) = Standard_Boolean then -- Restriction only applies to original source code if Comes_From_Source (N) then Check_Restriction (No_Direct_Boolean_Operators, N); end if; end if; -- Do style check (but skip if in instance, error is on template) if Style_Check then if not In_Instance then Check_Boolean_Operator (N); end if; end if; end Check_No_Direct_Boolean_Operators; ------------------------------ -- Check_Parameterless_Call -- ------------------------------ procedure Check_Parameterless_Call (N : Node_Id) is Nam : Node_Id; function Prefix_Is_Access_Subp return Boolean; -- If the prefix is of an access_to_subprogram type, the node must be -- rewritten as a call. Ditto if the prefix is overloaded and all its -- interpretations are access to subprograms. --------------------------- -- Prefix_Is_Access_Subp -- --------------------------- function Prefix_Is_Access_Subp return Boolean is I : Interp_Index; It : Interp; begin -- If the context is an attribute reference that can apply to -- functions, this is never a parameterless call (RM 4.1.4(6)). if Nkind (Parent (N)) = N_Attribute_Reference and then Nam_In (Attribute_Name (Parent (N)), Name_Address, Name_Code_Address, Name_Access) then return False; end if; if not Is_Overloaded (N) then return Ekind (Etype (N)) = E_Subprogram_Type and then Base_Type (Etype (Etype (N))) /= Standard_Void_Type; else Get_First_Interp (N, I, It); while Present (It.Typ) loop if Ekind (It.Typ) /= E_Subprogram_Type or else Base_Type (Etype (It.Typ)) = Standard_Void_Type then return False; end if; Get_Next_Interp (I, It); end loop; return True; end if; end Prefix_Is_Access_Subp; -- Start of processing for Check_Parameterless_Call begin -- Defend against junk stuff if errors already detected if Total_Errors_Detected /= 0 then if Nkind (N) in N_Has_Etype and then Etype (N) = Any_Type then return; elsif Nkind (N) in N_Has_Chars and then Chars (N) in Error_Name_Or_No_Name then return; end if; Require_Entity (N); end if; -- If the context expects a value, and the name is a procedure, this is -- most likely a missing 'Access. Don't try to resolve the parameterless -- call, error will be caught when the outer call is analyzed. if Is_Entity_Name (N) and then Ekind (Entity (N)) = E_Procedure and then not Is_Overloaded (N) and then Nkind_In (Parent (N), N_Parameter_Association, N_Function_Call, N_Procedure_Call_Statement) then return; end if; -- Rewrite as call if overloadable entity that is (or could be, in the -- overloaded case) a function call. If we know for sure that the entity -- is an enumeration literal, we do not rewrite it. -- If the entity is the name of an operator, it cannot be a call because -- operators cannot have default parameters. In this case, this must be -- a string whose contents coincide with an operator name. Set the kind -- of the node appropriately. if (Is_Entity_Name (N) and then Nkind (N) /= N_Operator_Symbol and then Is_Overloadable (Entity (N)) and then (Ekind (Entity (N)) /= E_Enumeration_Literal or else Is_Overloaded (N))) -- Rewrite as call if it is an explicit dereference of an expression of -- a subprogram access type, and the subprogram type is not that of a -- procedure or entry. or else (Nkind (N) = N_Explicit_Dereference and then Prefix_Is_Access_Subp) -- Rewrite as call if it is a selected component which is a function, -- this is the case of a call to a protected function (which may be -- overloaded with other protected operations). or else (Nkind (N) = N_Selected_Component and then (Ekind (Entity (Selector_Name (N))) = E_Function or else (Ekind_In (Entity (Selector_Name (N)), E_Entry, E_Procedure) and then Is_Overloaded (Selector_Name (N))))) -- If one of the above three conditions is met, rewrite as call. Apply -- the rewriting only once. then if Nkind (Parent (N)) /= N_Function_Call or else N /= Name (Parent (N)) then -- This may be a prefixed call that was not fully analyzed, e.g. -- an actual in an instance. if Ada_Version >= Ada_2005 and then Nkind (N) = N_Selected_Component and then Is_Dispatching_Operation (Entity (Selector_Name (N))) then Analyze_Selected_Component (N); if Nkind (N) /= N_Selected_Component then return; end if; end if; -- The node is the name of the parameterless call. Preserve its -- descendants, which may be complex expressions. Nam := Relocate_Node (N); -- If overloaded, overload set belongs to new copy Save_Interps (N, Nam); -- Change node to parameterless function call (note that the -- Parameter_Associations associations field is left set to Empty, -- its normal default value since there are no parameters) Change_Node (N, N_Function_Call); Set_Name (N, Nam); Set_Sloc (N, Sloc (Nam)); Analyze_Call (N); end if; elsif Nkind (N) = N_Parameter_Association then Check_Parameterless_Call (Explicit_Actual_Parameter (N)); elsif Nkind (N) = N_Operator_Symbol then Change_Operator_Symbol_To_String_Literal (N); Set_Is_Overloaded (N, False); Set_Etype (N, Any_String); end if; end Check_Parameterless_Call; -------------------------------- -- Is_Atomic_Ref_With_Address -- -------------------------------- function Is_Atomic_Ref_With_Address (N : Node_Id) return Boolean is Pref : constant Node_Id := Prefix (N); begin if not Is_Entity_Name (Pref) then return False; else declare Pent : constant Entity_Id := Entity (Pref); Ptyp : constant Entity_Id := Etype (Pent); begin return not Is_Access_Type (Ptyp) and then (Is_Atomic (Ptyp) or else Is_Atomic (Pent)) and then Present (Address_Clause (Pent)); end; end if; end Is_Atomic_Ref_With_Address; ----------------------------- -- Is_Definite_Access_Type -- ----------------------------- function Is_Definite_Access_Type (E : Entity_Id) return Boolean is Btyp : constant Entity_Id := Base_Type (E); begin return Ekind (Btyp) = E_Access_Type or else (Ekind (Btyp) = E_Access_Subprogram_Type and then Comes_From_Source (Btyp)); end Is_Definite_Access_Type; ---------------------- -- Is_Predefined_Op -- ---------------------- function Is_Predefined_Op (Nam : Entity_Id) return Boolean is begin -- Predefined operators are intrinsic subprograms if not Is_Intrinsic_Subprogram (Nam) then return False; end if; -- A call to a back-end builtin is never a predefined operator if Is_Imported (Nam) and then Present (Interface_Name (Nam)) then return False; end if; return not Is_Generic_Instance (Nam) and then Chars (Nam) in Any_Operator_Name and then (No (Alias (Nam)) or else Is_Predefined_Op (Alias (Nam))); end Is_Predefined_Op; ----------------------------- -- Make_Call_Into_Operator -- ----------------------------- procedure Make_Call_Into_Operator (N : Node_Id; Typ : Entity_Id; Op_Id : Entity_Id) is Op_Name : constant Name_Id := Chars (Op_Id); Act1 : Node_Id := First_Actual (N); Act2 : Node_Id := Next_Actual (Act1); Error : Boolean := False; Func : constant Entity_Id := Entity (Name (N)); Is_Binary : constant Boolean := Present (Act2); Op_Node : Node_Id; Opnd_Type : Entity_Id; Orig_Type : Entity_Id := Empty; Pack : Entity_Id; type Kind_Test is access function (E : Entity_Id) return Boolean; function Operand_Type_In_Scope (S : Entity_Id) return Boolean; -- If the operand is not universal, and the operator is given by an -- expanded name, verify that the operand has an interpretation with a -- type defined in the given scope of the operator. function Type_In_P (Test : Kind_Test) return Entity_Id; -- Find a type of the given class in package Pack that contains the -- operator. --------------------------- -- Operand_Type_In_Scope -- --------------------------- function Operand_Type_In_Scope (S : Entity_Id) return Boolean is Nod : constant Node_Id := Right_Opnd (Op_Node); I : Interp_Index; It : Interp; begin if not Is_Overloaded (Nod) then return Scope (Base_Type (Etype (Nod))) = S; else Get_First_Interp (Nod, I, It); while Present (It.Typ) loop if Scope (Base_Type (It.Typ)) = S then return True; end if; Get_Next_Interp (I, It); end loop; return False; end if; end Operand_Type_In_Scope; --------------- -- Type_In_P -- --------------- function Type_In_P (Test : Kind_Test) return Entity_Id is E : Entity_Id; function In_Decl return Boolean; -- Verify that node is not part of the type declaration for the -- candidate type, which would otherwise be invisible. ------------- -- In_Decl -- ------------- function In_Decl return Boolean is Decl_Node : constant Node_Id := Parent (E); N2 : Node_Id; begin N2 := N; if Etype (E) = Any_Type then return True; elsif No (Decl_Node) then return False; else while Present (N2) and then Nkind (N2) /= N_Compilation_Unit loop if N2 = Decl_Node then return True; else N2 := Parent (N2); end if; end loop; return False; end if; end In_Decl; -- Start of processing for Type_In_P begin -- If the context type is declared in the prefix package, this is the -- desired base type. if Scope (Base_Type (Typ)) = Pack and then Test (Typ) then return Base_Type (Typ); else E := First_Entity (Pack); while Present (E) loop if Test (E) and then not In_Decl then return E; end if; Next_Entity (E); end loop; return Empty; end if; end Type_In_P; -- Start of processing for Make_Call_Into_Operator begin Op_Node := New_Node (Operator_Kind (Op_Name, Is_Binary), Sloc (N)); -- Binary operator if Is_Binary then Set_Left_Opnd (Op_Node, Relocate_Node (Act1)); Set_Right_Opnd (Op_Node, Relocate_Node (Act2)); Save_Interps (Act1, Left_Opnd (Op_Node)); Save_Interps (Act2, Right_Opnd (Op_Node)); Act1 := Left_Opnd (Op_Node); Act2 := Right_Opnd (Op_Node); -- Unary operator else Set_Right_Opnd (Op_Node, Relocate_Node (Act1)); Save_Interps (Act1, Right_Opnd (Op_Node)); Act1 := Right_Opnd (Op_Node); end if; -- If the operator is denoted by an expanded name, and the prefix is -- not Standard, but the operator is a predefined one whose scope is -- Standard, then this is an implicit_operator, inserted as an -- interpretation by the procedure of the same name. This procedure -- overestimates the presence of implicit operators, because it does -- not examine the type of the operands. Verify now that the operand -- type appears in the given scope. If right operand is universal, -- check the other operand. In the case of concatenation, either -- argument can be the component type, so check the type of the result. -- If both arguments are literals, look for a type of the right kind -- defined in the given scope. This elaborate nonsense is brought to -- you courtesy of b33302a. The type itself must be frozen, so we must -- find the type of the proper class in the given scope. -- A final wrinkle is the multiplication operator for fixed point types, -- which is defined in Standard only, and not in the scope of the -- fixed point type itself. if Nkind (Name (N)) = N_Expanded_Name then Pack := Entity (Prefix (Name (N))); -- If this is a package renaming, get renamed entity, which will be -- the scope of the operands if operaton is type-correct. if Present (Renamed_Entity (Pack)) then Pack := Renamed_Entity (Pack); end if; -- If the entity being called is defined in the given package, it is -- a renaming of a predefined operator, and known to be legal. if Scope (Entity (Name (N))) = Pack and then Pack /= Standard_Standard then null; -- Visibility does not need to be checked in an instance: if the -- operator was not visible in the generic it has been diagnosed -- already, else there is an implicit copy of it in the instance. elsif In_Instance then null; elsif Nam_In (Op_Name, Name_Op_Multiply, Name_Op_Divide) and then Is_Fixed_Point_Type (Etype (Left_Opnd (Op_Node))) and then Is_Fixed_Point_Type (Etype (Right_Opnd (Op_Node))) then if Pack /= Standard_Standard then Error := True; end if; -- Ada 2005 AI-420: Predefined equality on Universal_Access is -- available. elsif Ada_Version >= Ada_2005 and then Nam_In (Op_Name, Name_Op_Eq, Name_Op_Ne) and then Ekind (Etype (Act1)) = E_Anonymous_Access_Type then null; else Opnd_Type := Base_Type (Etype (Right_Opnd (Op_Node))); if Op_Name = Name_Op_Concat then Opnd_Type := Base_Type (Typ); elsif (Scope (Opnd_Type) = Standard_Standard and then Is_Binary) or else (Nkind (Right_Opnd (Op_Node)) = N_Attribute_Reference and then Is_Binary and then not Comes_From_Source (Opnd_Type)) then Opnd_Type := Base_Type (Etype (Left_Opnd (Op_Node))); end if; if Scope (Opnd_Type) = Standard_Standard then -- Verify that the scope contains a type that corresponds to -- the given literal. Optimize the case where Pack is Standard. if Pack /= Standard_Standard then if Opnd_Type = Universal_Integer then Orig_Type := Type_In_P (Is_Integer_Type'Access); elsif Opnd_Type = Universal_Real then Orig_Type := Type_In_P (Is_Real_Type'Access); elsif Opnd_Type = Any_String then Orig_Type := Type_In_P (Is_String_Type'Access); elsif Opnd_Type = Any_Access then Orig_Type := Type_In_P (Is_Definite_Access_Type'Access); elsif Opnd_Type = Any_Composite then Orig_Type := Type_In_P (Is_Composite_Type'Access); if Present (Orig_Type) then if Has_Private_Component (Orig_Type) then Orig_Type := Empty; else Set_Etype (Act1, Orig_Type); if Is_Binary then Set_Etype (Act2, Orig_Type); end if; end if; end if; else Orig_Type := Empty; end if; Error := No (Orig_Type); end if; elsif Ekind (Opnd_Type) = E_Allocator_Type and then No (Type_In_P (Is_Definite_Access_Type'Access)) then Error := True; -- If the type is defined elsewhere, and the operator is not -- defined in the given scope (by a renaming declaration, e.g.) -- then this is an error as well. If an extension of System is -- present, and the type may be defined there, Pack must be -- System itself. elsif Scope (Opnd_Type) /= Pack and then Scope (Op_Id) /= Pack and then (No (System_Aux_Id) or else Scope (Opnd_Type) /= System_Aux_Id or else Pack /= Scope (System_Aux_Id)) then if not Is_Overloaded (Right_Opnd (Op_Node)) then Error := True; else Error := not Operand_Type_In_Scope (Pack); end if; elsif Pack = Standard_Standard and then not Operand_Type_In_Scope (Standard_Standard) then Error := True; end if; end if; if Error then Error_Msg_Node_2 := Pack; Error_Msg_NE ("& not declared in&", N, Selector_Name (Name (N))); Set_Etype (N, Any_Type); return; -- Detect a mismatch between the context type and the result type -- in the named package, which is otherwise not detected if the -- operands are universal. Check is only needed if source entity is -- an operator, not a function that renames an operator. elsif Nkind (Parent (N)) /= N_Type_Conversion and then Ekind (Entity (Name (N))) = E_Operator and then Is_Numeric_Type (Typ) and then not Is_Universal_Numeric_Type (Typ) and then Scope (Base_Type (Typ)) /= Pack and then not In_Instance then if Is_Fixed_Point_Type (Typ) and then Nam_In (Op_Name, Name_Op_Multiply, Name_Op_Divide) then -- Already checked above null; -- Operator may be defined in an extension of System elsif Present (System_Aux_Id) and then Scope (Opnd_Type) = System_Aux_Id then null; else -- Could we use Wrong_Type here??? (this would require setting -- Etype (N) to the actual type found where Typ was expected). Error_Msg_NE ("expect }", N, Typ); end if; end if; end if; Set_Chars (Op_Node, Op_Name); if not Is_Private_Type (Etype (N)) then Set_Etype (Op_Node, Base_Type (Etype (N))); else Set_Etype (Op_Node, Etype (N)); end if; -- If this is a call to a function that renames a predefined equality, -- the renaming declaration provides a type that must be used to -- resolve the operands. This must be done now because resolution of -- the equality node will not resolve any remaining ambiguity, and it -- assumes that the first operand is not overloaded. if Nam_In (Op_Name, Name_Op_Eq, Name_Op_Ne) and then Ekind (Func) = E_Function and then Is_Overloaded (Act1) then Resolve (Act1, Base_Type (Etype (First_Formal (Func)))); Resolve (Act2, Base_Type (Etype (First_Formal (Func)))); end if; Set_Entity (Op_Node, Op_Id); Generate_Reference (Op_Id, N, ' '); -- Do rewrite setting Comes_From_Source on the result if the original -- call came from source. Although it is not strictly the case that the -- operator as such comes from the source, logically it corresponds -- exactly to the function call in the source, so it should be marked -- this way (e.g. to make sure that validity checks work fine). declare CS : constant Boolean := Comes_From_Source (N); begin Rewrite (N, Op_Node); Set_Comes_From_Source (N, CS); end; -- If this is an arithmetic operator and the result type is private, -- the operands and the result must be wrapped in conversion to -- expose the underlying numeric type and expand the proper checks, -- e.g. on division. if Is_Private_Type (Typ) then case Nkind (N) is when N_Op_Add | N_Op_Divide | N_Op_Expon | N_Op_Mod | N_Op_Multiply | N_Op_Rem | N_Op_Subtract => Resolve_Intrinsic_Operator (N, Typ); when N_Op_Abs | N_Op_Minus | N_Op_Plus => Resolve_Intrinsic_Unary_Operator (N, Typ); when others => Resolve (N, Typ); end case; else Resolve (N, Typ); end if; -- If in ASIS_Mode, propagate operand types to original actuals of -- function call, which would otherwise not be fully resolved. If -- the call has already been constant-folded, nothing to do. We -- relocate the operand nodes rather than copy them, to preserve -- original_node pointers, given that the operands themselves may -- have been rewritten. If the call was itself a rewriting of an -- operator node, nothing to do. if ASIS_Mode and then Nkind (N) in N_Op and then Nkind (Original_Node (N)) = N_Function_Call then declare L : Node_Id; R : constant Node_Id := Right_Opnd (N); Old_First : constant Node_Id := First (Parameter_Associations (Original_Node (N))); Old_Sec : Node_Id; begin if Is_Binary then L := Left_Opnd (N); Old_Sec := Next (Old_First); -- If the original call has named associations, replace the -- explicit actual parameter in the association with the proper -- resolved operand. if Nkind (Old_First) = N_Parameter_Association then if Chars (Selector_Name (Old_First)) = Chars (First_Entity (Op_Id)) then Rewrite (Explicit_Actual_Parameter (Old_First), Relocate_Node (L)); else Rewrite (Explicit_Actual_Parameter (Old_First), Relocate_Node (R)); end if; else Rewrite (Old_First, Relocate_Node (L)); end if; if Nkind (Old_Sec) = N_Parameter_Association then if Chars (Selector_Name (Old_Sec)) = Chars (First_Entity (Op_Id)) then Rewrite (Explicit_Actual_Parameter (Old_Sec), Relocate_Node (L)); else Rewrite (Explicit_Actual_Parameter (Old_Sec), Relocate_Node (R)); end if; else Rewrite (Old_Sec, Relocate_Node (R)); end if; else if Nkind (Old_First) = N_Parameter_Association then Rewrite (Explicit_Actual_Parameter (Old_First), Relocate_Node (R)); else Rewrite (Old_First, Relocate_Node (R)); end if; end if; end; Set_Parent (Original_Node (N), Parent (N)); end if; end Make_Call_Into_Operator; ------------------- -- Operator_Kind -- ------------------- function Operator_Kind (Op_Name : Name_Id; Is_Binary : Boolean) return Node_Kind is Kind : Node_Kind; begin -- Use CASE statement or array??? if Is_Binary then if Op_Name = Name_Op_And then Kind := N_Op_And; elsif Op_Name = Name_Op_Or then Kind := N_Op_Or; elsif Op_Name = Name_Op_Xor then Kind := N_Op_Xor; elsif Op_Name = Name_Op_Eq then Kind := N_Op_Eq; elsif Op_Name = Name_Op_Ne then Kind := N_Op_Ne; elsif Op_Name = Name_Op_Lt then Kind := N_Op_Lt; elsif Op_Name = Name_Op_Le then Kind := N_Op_Le; elsif Op_Name = Name_Op_Gt then Kind := N_Op_Gt; elsif Op_Name = Name_Op_Ge then Kind := N_Op_Ge; elsif Op_Name = Name_Op_Add then Kind := N_Op_Add; elsif Op_Name = Name_Op_Subtract then Kind := N_Op_Subtract; elsif Op_Name = Name_Op_Concat then Kind := N_Op_Concat; elsif Op_Name = Name_Op_Multiply then Kind := N_Op_Multiply; elsif Op_Name = Name_Op_Divide then Kind := N_Op_Divide; elsif Op_Name = Name_Op_Mod then Kind := N_Op_Mod; elsif Op_Name = Name_Op_Rem then Kind := N_Op_Rem; elsif Op_Name = Name_Op_Expon then Kind := N_Op_Expon; else raise Program_Error; end if; -- Unary operators else if Op_Name = Name_Op_Add then Kind := N_Op_Plus; elsif Op_Name = Name_Op_Subtract then Kind := N_Op_Minus; elsif Op_Name = Name_Op_Abs then Kind := N_Op_Abs; elsif Op_Name = Name_Op_Not then Kind := N_Op_Not; else raise Program_Error; end if; end if; return Kind; end Operator_Kind; ---------------------------- -- Preanalyze_And_Resolve -- ---------------------------- procedure Preanalyze_And_Resolve (N : Node_Id; T : Entity_Id) is Save_Full_Analysis : constant Boolean := Full_Analysis; begin Full_Analysis := False; Expander_Mode_Save_And_Set (False); -- Normally, we suppress all checks for this preanalysis. There is no -- point in processing them now, since they will be applied properly -- and in the proper location when the default expressions reanalyzed -- and reexpanded later on. We will also have more information at that -- point for possible suppression of individual checks. -- However, in SPARK mode, most expansion is suppressed, and this -- later reanalysis and reexpansion may not occur. SPARK mode does -- require the setting of checking flags for proof purposes, so we -- do the SPARK preanalysis without suppressing checks. -- This special handling for SPARK mode is required for example in the -- case of Ada 2012 constructs such as quantified expressions, which are -- expanded in two separate steps. if GNATprove_Mode then Analyze_And_Resolve (N, T); else Analyze_And_Resolve (N, T, Suppress => All_Checks); end if; Expander_Mode_Restore; Full_Analysis := Save_Full_Analysis; end Preanalyze_And_Resolve; -- Version without context type procedure Preanalyze_And_Resolve (N : Node_Id) is Save_Full_Analysis : constant Boolean := Full_Analysis; begin Full_Analysis := False; Expander_Mode_Save_And_Set (False); Analyze (N); Resolve (N, Etype (N), Suppress => All_Checks); Expander_Mode_Restore; Full_Analysis := Save_Full_Analysis; end Preanalyze_And_Resolve; ---------------------------------- -- Replace_Actual_Discriminants -- ---------------------------------- procedure Replace_Actual_Discriminants (N : Node_Id; Default : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Tsk : Node_Id := Empty; function Process_Discr (Nod : Node_Id) return Traverse_Result; -- Comment needed??? ------------------- -- Process_Discr -- ------------------- function Process_Discr (Nod : Node_Id) return Traverse_Result is Ent : Entity_Id; begin if Nkind (Nod) = N_Identifier then Ent := Entity (Nod); if Present (Ent) and then Ekind (Ent) = E_Discriminant then Rewrite (Nod, Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Tsk, New_Sloc => Loc), Selector_Name => Make_Identifier (Loc, Chars (Ent)))); Set_Etype (Nod, Etype (Ent)); end if; end if; return OK; end Process_Discr; procedure Replace_Discrs is new Traverse_Proc (Process_Discr); -- Start of processing for Replace_Actual_Discriminants begin if not Expander_Active then return; end if; if Nkind (Name (N)) = N_Selected_Component then Tsk := Prefix (Name (N)); elsif Nkind (Name (N)) = N_Indexed_Component then Tsk := Prefix (Prefix (Name (N))); end if; if No (Tsk) then return; else Replace_Discrs (Default); end if; end Replace_Actual_Discriminants; ------------- -- Resolve -- ------------- procedure Resolve (N : Node_Id; Typ : Entity_Id) is Ambiguous : Boolean := False; Ctx_Type : Entity_Id := Typ; Expr_Type : Entity_Id := Empty; -- prevent junk warning Err_Type : Entity_Id := Empty; Found : Boolean := False; From_Lib : Boolean; I : Interp_Index; I1 : Interp_Index := 0; -- prevent junk warning It : Interp; It1 : Interp; Seen : Entity_Id := Empty; -- prevent junk warning function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean; -- Determine whether a node comes from a predefined library unit or -- Standard. procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id); -- Try and fix up a literal so that it matches its expected type. New -- literals are manufactured if necessary to avoid cascaded errors. procedure Report_Ambiguous_Argument; -- Additional diagnostics when an ambiguous call has an ambiguous -- argument (typically a controlling actual). procedure Resolution_Failed; -- Called when attempt at resolving current expression fails ------------------------------------ -- Comes_From_Predefined_Lib_Unit -- ------------------------------------- function Comes_From_Predefined_Lib_Unit (Nod : Node_Id) return Boolean is begin return Sloc (Nod) = Standard_Location or else Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (Sloc (Nod)))); end Comes_From_Predefined_Lib_Unit; -------------------- -- Patch_Up_Value -- -------------------- procedure Patch_Up_Value (N : Node_Id; Typ : Entity_Id) is begin if Nkind (N) = N_Integer_Literal and then Is_Real_Type (Typ) then Rewrite (N, Make_Real_Literal (Sloc (N), Realval => UR_From_Uint (Intval (N)))); Set_Etype (N, Universal_Real); Set_Is_Static_Expression (N); elsif Nkind (N) = N_Real_Literal and then Is_Integer_Type (Typ) then Rewrite (N, Make_Integer_Literal (Sloc (N), Intval => UR_To_Uint (Realval (N)))); Set_Etype (N, Universal_Integer); Set_Is_Static_Expression (N); elsif Nkind (N) = N_String_Literal and then Is_Character_Type (Typ) then Set_Character_Literal_Name (Char_Code (Character'Pos ('A'))); Rewrite (N, Make_Character_Literal (Sloc (N), Chars => Name_Find, Char_Literal_Value => UI_From_Int (Character'Pos ('A')))); Set_Etype (N, Any_Character); Set_Is_Static_Expression (N); elsif Nkind (N) /= N_String_Literal and then Is_String_Type (Typ) then Rewrite (N, Make_String_Literal (Sloc (N), Strval => End_String)); elsif Nkind (N) = N_Range then Patch_Up_Value (Low_Bound (N), Typ); Patch_Up_Value (High_Bound (N), Typ); end if; end Patch_Up_Value; ------------------------------- -- Report_Ambiguous_Argument -- ------------------------------- procedure Report_Ambiguous_Argument is Arg : constant Node_Id := First (Parameter_Associations (N)); I : Interp_Index; It : Interp; begin if Nkind (Arg) = N_Function_Call and then Is_Entity_Name (Name (Arg)) and then Is_Overloaded (Name (Arg)) then Error_Msg_NE ("ambiguous call to&", Arg, Name (Arg)); -- Could use comments on what is going on here??? Get_First_Interp (Name (Arg), I, It); while Present (It.Nam) loop Error_Msg_Sloc := Sloc (It.Nam); if Nkind (Parent (It.Nam)) = N_Full_Type_Declaration then Error_Msg_N ("interpretation (inherited) #!", Arg); else Error_Msg_N ("interpretation #!", Arg); end if; Get_Next_Interp (I, It); end loop; end if; end Report_Ambiguous_Argument; ----------------------- -- Resolution_Failed -- ----------------------- procedure Resolution_Failed is begin Patch_Up_Value (N, Typ); -- Set the type to the desired one to minimize cascaded errors. Note -- that this is an approximation and does not work in all cases. Set_Etype (N, Typ); Debug_A_Exit ("resolving ", N, " (done, resolution failed)"); Set_Is_Overloaded (N, False); -- The caller will return without calling the expander, so we need -- to set the analyzed flag. Note that it is fine to set Analyzed -- to True even if we are in the middle of a shallow analysis, -- (see the spec of sem for more details) since this is an error -- situation anyway, and there is no point in repeating the -- analysis later (indeed it won't work to repeat it later, since -- we haven't got a clear resolution of which entity is being -- referenced.) Set_Analyzed (N, True); return; end Resolution_Failed; -- Start of processing for Resolve begin if N = Error then return; end if; -- Access attribute on remote subprogram cannot be used for a non-remote -- access-to-subprogram type. if Nkind (N) = N_Attribute_Reference and then Nam_In (Attribute_Name (N), Name_Access, Name_Unrestricted_Access, Name_Unchecked_Access) and then Comes_From_Source (N) and then Is_Entity_Name (Prefix (N)) and then Is_Subprogram (Entity (Prefix (N))) and then Is_Remote_Call_Interface (Entity (Prefix (N))) and then not Is_Remote_Access_To_Subprogram_Type (Typ) then Error_Msg_N ("prefix must statically denote a non-remote subprogram", N); end if; From_Lib := Comes_From_Predefined_Lib_Unit (N); -- If the context is a Remote_Access_To_Subprogram, access attributes -- must be resolved with the corresponding fat pointer. There is no need -- to check for the attribute name since the return type of an -- attribute is never a remote type. if Nkind (N) = N_Attribute_Reference and then Comes_From_Source (N) and then (Is_Remote_Call_Interface (Typ) or else Is_Remote_Types (Typ)) then declare Attr : constant Attribute_Id := Get_Attribute_Id (Attribute_Name (N)); Pref : constant Node_Id := Prefix (N); Decl : Node_Id; Spec : Node_Id; Is_Remote : Boolean := True; begin -- Check that Typ is a remote access-to-subprogram type if Is_Remote_Access_To_Subprogram_Type (Typ) then -- Prefix (N) must statically denote a remote subprogram -- declared in a package specification. if Attr = Attribute_Access or else Attr = Attribute_Unchecked_Access or else Attr = Attribute_Unrestricted_Access then Decl := Unit_Declaration_Node (Entity (Pref)); if Nkind (Decl) = N_Subprogram_Body then Spec := Corresponding_Spec (Decl); if Present (Spec) then Decl := Unit_Declaration_Node (Spec); end if; end if; Spec := Parent (Decl); if not Is_Entity_Name (Prefix (N)) or else Nkind (Spec) /= N_Package_Specification or else not Is_Remote_Call_Interface (Defining_Entity (Spec)) then Is_Remote := False; Error_Msg_N ("prefix must statically denote a remote subprogram ", N); end if; -- If we are generating code in distributed mode, perform -- semantic checks against corresponding remote entities. if Expander_Active and then Get_PCS_Name /= Name_No_DSA then Check_Subtype_Conformant (New_Id => Entity (Prefix (N)), Old_Id => Designated_Type (Corresponding_Remote_Type (Typ)), Err_Loc => N); if Is_Remote then Process_Remote_AST_Attribute (N, Typ); end if; end if; end if; end if; end; end if; Debug_A_Entry ("resolving ", N); if Debug_Flag_V then Write_Overloads (N); end if; if Comes_From_Source (N) then if Is_Fixed_Point_Type (Typ) then Check_Restriction (No_Fixed_Point, N); elsif Is_Floating_Point_Type (Typ) and then Typ /= Universal_Real and then Typ /= Any_Real then Check_Restriction (No_Floating_Point, N); end if; end if; -- Return if already analyzed if Analyzed (N) then Debug_A_Exit ("resolving ", N, " (done, already analyzed)"); Analyze_Dimension (N); return; -- Any case of Any_Type as the Etype value means that we had a -- previous error. elsif Etype (N) = Any_Type then Debug_A_Exit ("resolving ", N, " (done, Etype = Any_Type)"); return; end if; Check_Parameterless_Call (N); -- The resolution of an Expression_With_Actions is determined by -- its Expression. if Nkind (N) = N_Expression_With_Actions then Resolve (Expression (N), Typ); Found := True; Expr_Type := Etype (Expression (N)); -- If not overloaded, then we know the type, and all that needs doing -- is to check that this type is compatible with the context. elsif not Is_Overloaded (N) then Found := Covers (Typ, Etype (N)); Expr_Type := Etype (N); -- In the overloaded case, we must select the interpretation that -- is compatible with the context (i.e. the type passed to Resolve) else -- Loop through possible interpretations Get_First_Interp (N, I, It); Interp_Loop : while Present (It.Typ) loop if Debug_Flag_V then Write_Str ("Interp: "); Write_Interp (It); end if; -- We are only interested in interpretations that are compatible -- with the expected type, any other interpretations are ignored. if not Covers (Typ, It.Typ) then if Debug_Flag_V then Write_Str (" interpretation incompatible with context"); Write_Eol; end if; else -- Skip the current interpretation if it is disabled by an -- abstract operator. This action is performed only when the -- type against which we are resolving is the same as the -- type of the interpretation. if Ada_Version >= Ada_2005 and then It.Typ = Typ and then Typ /= Universal_Integer and then Typ /= Universal_Real and then Present (It.Abstract_Op) then if Debug_Flag_V then Write_Line ("Skip."); end if; goto Continue; end if; -- First matching interpretation if not Found then Found := True; I1 := I; Seen := It.Nam; Expr_Type := It.Typ; -- Matching interpretation that is not the first, maybe an -- error, but there are some cases where preference rules are -- used to choose between the two possibilities. These and -- some more obscure cases are handled in Disambiguate. else -- If the current statement is part of a predefined library -- unit, then all interpretations which come from user level -- packages should not be considered. Check previous and -- current one. if From_Lib then if not Comes_From_Predefined_Lib_Unit (It.Nam) then goto Continue; elsif not Comes_From_Predefined_Lib_Unit (Seen) then -- Previous interpretation must be discarded I1 := I; Seen := It.Nam; Expr_Type := It.Typ; Set_Entity (N, Seen); goto Continue; end if; end if; -- Otherwise apply further disambiguation steps Error_Msg_Sloc := Sloc (Seen); It1 := Disambiguate (N, I1, I, Typ); -- Disambiguation has succeeded. Skip the remaining -- interpretations. if It1 /= No_Interp then Seen := It1.Nam; Expr_Type := It1.Typ; while Present (It.Typ) loop Get_Next_Interp (I, It); end loop; else -- Before we issue an ambiguity complaint, check for the -- case of a subprogram call where at least one of the -- arguments is Any_Type, and if so suppress the message, -- since it is a cascaded error. This can also happen for -- a generalized indexing operation. if Nkind (N) in N_Subprogram_Call or else (Nkind (N) = N_Indexed_Component and then Present (Generalized_Indexing (N))) then declare A : Node_Id; E : Node_Id; begin if Nkind (N) = N_Indexed_Component then Rewrite (N, Generalized_Indexing (N)); end if; A := First_Actual (N); while Present (A) loop E := A; if Nkind (E) = N_Parameter_Association then E := Explicit_Actual_Parameter (E); end if; if Etype (E) = Any_Type then if Debug_Flag_V then Write_Str ("Any_Type in call"); Write_Eol; end if; exit Interp_Loop; end if; Next_Actual (A); end loop; end; elsif Nkind (N) in N_Binary_Op and then (Etype (Left_Opnd (N)) = Any_Type or else Etype (Right_Opnd (N)) = Any_Type) then exit Interp_Loop; elsif Nkind (N) in N_Unary_Op and then Etype (Right_Opnd (N)) = Any_Type then exit Interp_Loop; end if; -- Not that special case, so issue message using the flag -- Ambiguous to control printing of the header message -- only at the start of an ambiguous set. if not Ambiguous then if Nkind (N) = N_Function_Call and then Nkind (Name (N)) = N_Explicit_Dereference then Error_Msg_N ("ambiguous expression (cannot resolve indirect " & "call)!", N); else Error_Msg_NE -- CODEFIX ("ambiguous expression (cannot resolve&)!", N, It.Nam); end if; Ambiguous := True; if Nkind (Parent (Seen)) = N_Full_Type_Declaration then Error_Msg_N ("\\possible interpretation (inherited)#!", N); else Error_Msg_N -- CODEFIX ("\\possible interpretation#!", N); end if; if Nkind (N) in N_Subprogram_Call and then Present (Parameter_Associations (N)) then Report_Ambiguous_Argument; end if; end if; Error_Msg_Sloc := Sloc (It.Nam); -- By default, the error message refers to the candidate -- interpretation. But if it is a predefined operator, it -- is implicitly declared at the declaration of the type -- of the operand. Recover the sloc of that declaration -- for the error message. if Nkind (N) in N_Op and then Scope (It.Nam) = Standard_Standard and then not Is_Overloaded (Right_Opnd (N)) and then Scope (Base_Type (Etype (Right_Opnd (N)))) /= Standard_Standard then Err_Type := First_Subtype (Etype (Right_Opnd (N))); if Comes_From_Source (Err_Type) and then Present (Parent (Err_Type)) then Error_Msg_Sloc := Sloc (Parent (Err_Type)); end if; elsif Nkind (N) in N_Binary_Op and then Scope (It.Nam) = Standard_Standard and then not Is_Overloaded (Left_Opnd (N)) and then Scope (Base_Type (Etype (Left_Opnd (N)))) /= Standard_Standard then Err_Type := First_Subtype (Etype (Left_Opnd (N))); if Comes_From_Source (Err_Type) and then Present (Parent (Err_Type)) then Error_Msg_Sloc := Sloc (Parent (Err_Type)); end if; -- If this is an indirect call, use the subprogram_type -- in the message, to have a meaningful location. Also -- indicate if this is an inherited operation, created -- by a type declaration. elsif Nkind (N) = N_Function_Call and then Nkind (Name (N)) = N_Explicit_Dereference and then Is_Type (It.Nam) then Err_Type := It.Nam; Error_Msg_Sloc := Sloc (Associated_Node_For_Itype (Err_Type)); else Err_Type := Empty; end if; if Nkind (N) in N_Op and then Scope (It.Nam) = Standard_Standard and then Present (Err_Type) then -- Special-case the message for universal_fixed -- operators, which are not declared with the type -- of the operand, but appear forever in Standard. if It.Typ = Universal_Fixed and then Scope (It.Nam) = Standard_Standard then Error_Msg_N ("\\possible interpretation as universal_fixed " & "operation (RM 4.5.5 (19))", N); else Error_Msg_N ("\\possible interpretation (predefined)#!", N); end if; elsif Nkind (Parent (It.Nam)) = N_Full_Type_Declaration then Error_Msg_N ("\\possible interpretation (inherited)#!", N); else Error_Msg_N -- CODEFIX ("\\possible interpretation#!", N); end if; end if; end if; -- We have a matching interpretation, Expr_Type is the type -- from this interpretation, and Seen is the entity. -- For an operator, just set the entity name. The type will be -- set by the specific operator resolution routine. if Nkind (N) in N_Op then Set_Entity (N, Seen); Generate_Reference (Seen, N); elsif Nkind (N) = N_Case_Expression then Set_Etype (N, Expr_Type); elsif Nkind (N) = N_Character_Literal then Set_Etype (N, Expr_Type); elsif Nkind (N) = N_If_Expression then Set_Etype (N, Expr_Type); -- AI05-0139-2: Expression is overloaded because type has -- implicit dereference. If type matches context, no implicit -- dereference is involved. elsif Has_Implicit_Dereference (Expr_Type) then Set_Etype (N, Expr_Type); Set_Is_Overloaded (N, False); exit Interp_Loop; elsif Is_Overloaded (N) and then Present (It.Nam) and then Ekind (It.Nam) = E_Discriminant and then Has_Implicit_Dereference (It.Nam) then -- If the node is a general indexing, the dereference is -- is inserted when resolving the rewritten form, else -- insert it now. if Nkind (N) /= N_Indexed_Component or else No (Generalized_Indexing (N)) then Build_Explicit_Dereference (N, It.Nam); end if; -- For an explicit dereference, attribute reference, range, -- short-circuit form (which is not an operator node), or call -- with a name that is an explicit dereference, there is -- nothing to be done at this point. elsif Nkind_In (N, N_Attribute_Reference, N_And_Then, N_Explicit_Dereference, N_Identifier, N_Indexed_Component, N_Or_Else, N_Range, N_Selected_Component, N_Slice) or else Nkind (Name (N)) = N_Explicit_Dereference then null; -- For procedure or function calls, set the type of the name, -- and also the entity pointer for the prefix. elsif Nkind (N) in N_Subprogram_Call and then Is_Entity_Name (Name (N)) then Set_Etype (Name (N), Expr_Type); Set_Entity (Name (N), Seen); Generate_Reference (Seen, Name (N)); elsif Nkind (N) = N_Function_Call and then Nkind (Name (N)) = N_Selected_Component then Set_Etype (Name (N), Expr_Type); Set_Entity (Selector_Name (Name (N)), Seen); Generate_Reference (Seen, Selector_Name (Name (N))); -- For all other cases, just set the type of the Name else Set_Etype (Name (N), Expr_Type); end if; end if; <<Continue>> -- Move to next interpretation exit Interp_Loop when No (It.Typ); Get_Next_Interp (I, It); end loop Interp_Loop; end if; -- At this stage Found indicates whether or not an acceptable -- interpretation exists. If not, then we have an error, except that if -- the context is Any_Type as a result of some other error, then we -- suppress the error report. if not Found then if Typ /= Any_Type then -- If type we are looking for is Void, then this is the procedure -- call case, and the error is simply that what we gave is not a -- procedure name (we think of procedure calls as expressions with -- types internally, but the user doesn't think of them this way). if Typ = Standard_Void_Type then -- Special case message if function used as a procedure if Nkind (N) = N_Procedure_Call_Statement and then Is_Entity_Name (Name (N)) and then Ekind (Entity (Name (N))) = E_Function then Error_Msg_NE ("cannot use function & in a procedure call", Name (N), Entity (Name (N))); -- Otherwise give general message (not clear what cases this -- covers, but no harm in providing for them). else Error_Msg_N ("expect procedure name in procedure call", N); end if; Found := True; -- Otherwise we do have a subexpression with the wrong type -- Check for the case of an allocator which uses an access type -- instead of the designated type. This is a common error and we -- specialize the message, posting an error on the operand of the -- allocator, complaining that we expected the designated type of -- the allocator. elsif Nkind (N) = N_Allocator and then Is_Access_Type (Typ) and then Is_Access_Type (Etype (N)) and then Designated_Type (Etype (N)) = Typ then Wrong_Type (Expression (N), Designated_Type (Typ)); Found := True; -- Check for view mismatch on Null in instances, for which the -- view-swapping mechanism has no identifier. elsif (In_Instance or else In_Inlined_Body) and then (Nkind (N) = N_Null) and then Is_Private_Type (Typ) and then Is_Access_Type (Full_View (Typ)) then Resolve (N, Full_View (Typ)); Set_Etype (N, Typ); return; -- Check for an aggregate. Sometimes we can get bogus aggregates -- from misuse of parentheses, and we are about to complain about -- the aggregate without even looking inside it. -- Instead, if we have an aggregate of type Any_Composite, then -- analyze and resolve the component fields, and then only issue -- another message if we get no errors doing this (otherwise -- assume that the errors in the aggregate caused the problem). elsif Nkind (N) = N_Aggregate and then Etype (N) = Any_Composite then -- Disable expansion in any case. If there is a type mismatch -- it may be fatal to try to expand the aggregate. The flag -- would otherwise be set to false when the error is posted. Expander_Active := False; declare procedure Check_Aggr (Aggr : Node_Id); -- Check one aggregate, and set Found to True if we have a -- definite error in any of its elements procedure Check_Elmt (Aelmt : Node_Id); -- Check one element of aggregate and set Found to True if -- we definitely have an error in the element. ---------------- -- Check_Aggr -- ---------------- procedure Check_Aggr (Aggr : Node_Id) is Elmt : Node_Id; begin if Present (Expressions (Aggr)) then Elmt := First (Expressions (Aggr)); while Present (Elmt) loop Check_Elmt (Elmt); Next (Elmt); end loop; end if; if Present (Component_Associations (Aggr)) then Elmt := First (Component_Associations (Aggr)); while Present (Elmt) loop -- If this is a default-initialized component, then -- there is nothing to check. The box will be -- replaced by the appropriate call during late -- expansion. if Nkind (Elmt) /= N_Iterated_Component_Association and then not Box_Present (Elmt) then Check_Elmt (Expression (Elmt)); end if; Next (Elmt); end loop; end if; end Check_Aggr; ---------------- -- Check_Elmt -- ---------------- procedure Check_Elmt (Aelmt : Node_Id) is begin -- If we have a nested aggregate, go inside it (to -- attempt a naked analyze-resolve of the aggregate can -- cause undesirable cascaded errors). Do not resolve -- expression if it needs a type from context, as for -- integer * fixed expression. if Nkind (Aelmt) = N_Aggregate then Check_Aggr (Aelmt); else Analyze (Aelmt); if not Is_Overloaded (Aelmt) and then Etype (Aelmt) /= Any_Fixed then Resolve (Aelmt); end if; if Etype (Aelmt) = Any_Type then Found := True; end if; end if; end Check_Elmt; begin Check_Aggr (N); end; end if; -- Looks like we have a type error, but check for special case -- of Address wanted, integer found, with the configuration pragma -- Allow_Integer_Address active. If we have this case, introduce -- an unchecked conversion to allow the integer expression to be -- treated as an Address. The reverse case of integer wanted, -- Address found, is treated in an analogous manner. if Address_Integer_Convert_OK (Typ, Etype (N)) then Rewrite (N, Unchecked_Convert_To (Typ, Relocate_Node (N))); Analyze_And_Resolve (N, Typ); return; -- Under relaxed RM semantics silently replace occurrences of null -- by System.Address_Null. elsif Null_To_Null_Address_Convert_OK (N, Typ) then Replace_Null_By_Null_Address (N); Analyze_And_Resolve (N, Typ); return; end if; -- That special Allow_Integer_Address check did not apply, so we -- have a real type error. If an error message was issued already, -- Found got reset to True, so if it's still False, issue standard -- Wrong_Type message. if not Found then if Is_Overloaded (N) and then Nkind (N) = N_Function_Call then declare Subp_Name : Node_Id; begin if Is_Entity_Name (Name (N)) then Subp_Name := Name (N); elsif Nkind (Name (N)) = N_Selected_Component then -- Protected operation: retrieve operation name Subp_Name := Selector_Name (Name (N)); else raise Program_Error; end if; Error_Msg_Node_2 := Typ; Error_Msg_NE ("no visible interpretation of& matches expected type&", N, Subp_Name); end; if All_Errors_Mode then declare Index : Interp_Index; It : Interp; begin Error_Msg_N ("\\possible interpretations:", N); Get_First_Interp (Name (N), Index, It); while Present (It.Nam) loop Error_Msg_Sloc := Sloc (It.Nam); Error_Msg_Node_2 := It.Nam; Error_Msg_NE ("\\ type& for & declared#", N, It.Typ); Get_Next_Interp (Index, It); end loop; end; else Error_Msg_N ("\use -gnatf for details", N); end if; else Wrong_Type (N, Typ); end if; end if; end if; Resolution_Failed; return; -- Test if we have more than one interpretation for the context elsif Ambiguous then Resolution_Failed; return; -- Only one intepretation else -- In Ada 2005, if we have something like "X : T := 2 + 2;", where -- the "+" on T is abstract, and the operands are of universal type, -- the above code will have (incorrectly) resolved the "+" to the -- universal one in Standard. Therefore check for this case and give -- an error. We can't do this earlier, because it would cause legal -- cases to get errors (when some other type has an abstract "+"). if Ada_Version >= Ada_2005 and then Nkind (N) in N_Op and then Is_Overloaded (N) and then Is_Universal_Numeric_Type (Etype (Entity (N))) then Get_First_Interp (N, I, It); while Present (It.Typ) loop if Present (It.Abstract_Op) and then Etype (It.Abstract_Op) = Typ then Error_Msg_NE ("cannot call abstract subprogram &!", N, It.Abstract_Op); return; end if; Get_Next_Interp (I, It); end loop; end if; -- Here we have an acceptable interpretation for the context -- Propagate type information and normalize tree for various -- predefined operations. If the context only imposes a class of -- types, rather than a specific type, propagate the actual type -- downward. if Typ = Any_Integer or else Typ = Any_Boolean or else Typ = Any_Modular or else Typ = Any_Real or else Typ = Any_Discrete then Ctx_Type := Expr_Type; -- Any_Fixed is legal in a real context only if a specific fixed- -- point type is imposed. If Norman Cohen can be confused by this, -- it deserves a separate message. if Typ = Any_Real and then Expr_Type = Any_Fixed then Error_Msg_N ("illegal context for mixed mode operation", N); Set_Etype (N, Universal_Real); Ctx_Type := Universal_Real; end if; end if; -- A user-defined operator is transformed into a function call at -- this point, so that further processing knows that operators are -- really operators (i.e. are predefined operators). User-defined -- operators that are intrinsic are just renamings of the predefined -- ones, and need not be turned into calls either, but if they rename -- a different operator, we must transform the node accordingly. -- Instantiations of Unchecked_Conversion are intrinsic but are -- treated as functions, even if given an operator designator. if Nkind (N) in N_Op and then Present (Entity (N)) and then Ekind (Entity (N)) /= E_Operator then if not Is_Predefined_Op (Entity (N)) then Rewrite_Operator_As_Call (N, Entity (N)); elsif Present (Alias (Entity (N))) and then Nkind (Parent (Parent (Entity (N)))) = N_Subprogram_Renaming_Declaration then Rewrite_Renamed_Operator (N, Alias (Entity (N)), Typ); -- If the node is rewritten, it will be fully resolved in -- Rewrite_Renamed_Operator. if Analyzed (N) then return; end if; end if; end if; case N_Subexpr'(Nkind (N)) is when N_Aggregate => Resolve_Aggregate (N, Ctx_Type); when N_Allocator => Resolve_Allocator (N, Ctx_Type); when N_Short_Circuit => Resolve_Short_Circuit (N, Ctx_Type); when N_Attribute_Reference => Resolve_Attribute (N, Ctx_Type); when N_Case_Expression => Resolve_Case_Expression (N, Ctx_Type); when N_Character_Literal => Resolve_Character_Literal (N, Ctx_Type); when N_Delta_Aggregate => Resolve_Delta_Aggregate (N, Ctx_Type); when N_Expanded_Name => Resolve_Entity_Name (N, Ctx_Type); when N_Explicit_Dereference => Resolve_Explicit_Dereference (N, Ctx_Type); when N_Expression_With_Actions => Resolve_Expression_With_Actions (N, Ctx_Type); when N_Extension_Aggregate => Resolve_Extension_Aggregate (N, Ctx_Type); when N_Function_Call => Resolve_Call (N, Ctx_Type); when N_Identifier => Resolve_Entity_Name (N, Ctx_Type); when N_If_Expression => Resolve_If_Expression (N, Ctx_Type); when N_Indexed_Component => Resolve_Indexed_Component (N, Ctx_Type); when N_Integer_Literal => Resolve_Integer_Literal (N, Ctx_Type); when N_Membership_Test => Resolve_Membership_Op (N, Ctx_Type); when N_Null => Resolve_Null (N, Ctx_Type); when N_Op_And | N_Op_Or | N_Op_Xor => Resolve_Logical_Op (N, Ctx_Type); when N_Op_Eq | N_Op_Ne => Resolve_Equality_Op (N, Ctx_Type); when N_Op_Ge | N_Op_Gt | N_Op_Le | N_Op_Lt => Resolve_Comparison_Op (N, Ctx_Type); when N_Op_Not => Resolve_Op_Not (N, Ctx_Type); when N_Op_Add | N_Op_Divide | N_Op_Mod | N_Op_Multiply | N_Op_Rem | N_Op_Subtract => Resolve_Arithmetic_Op (N, Ctx_Type); when N_Op_Concat => Resolve_Op_Concat (N, Ctx_Type); when N_Op_Expon => Resolve_Op_Expon (N, Ctx_Type); when N_Op_Abs | N_Op_Minus | N_Op_Plus => Resolve_Unary_Op (N, Ctx_Type); when N_Op_Shift => Resolve_Shift (N, Ctx_Type); when N_Procedure_Call_Statement => Resolve_Call (N, Ctx_Type); when N_Operator_Symbol => Resolve_Operator_Symbol (N, Ctx_Type); when N_Qualified_Expression => Resolve_Qualified_Expression (N, Ctx_Type); -- Why is the following null, needs a comment ??? when N_Quantified_Expression => null; when N_Raise_Expression => Resolve_Raise_Expression (N, Ctx_Type); when N_Raise_xxx_Error => Set_Etype (N, Ctx_Type); when N_Range => Resolve_Range (N, Ctx_Type); when N_Real_Literal => Resolve_Real_Literal (N, Ctx_Type); when N_Reference => Resolve_Reference (N, Ctx_Type); when N_Selected_Component => Resolve_Selected_Component (N, Ctx_Type); when N_Slice => Resolve_Slice (N, Ctx_Type); when N_String_Literal => Resolve_String_Literal (N, Ctx_Type); when N_Target_Name => Resolve_Target_Name (N, Ctx_Type); when N_Type_Conversion => Resolve_Type_Conversion (N, Ctx_Type); when N_Unchecked_Expression => Resolve_Unchecked_Expression (N, Ctx_Type); when N_Unchecked_Type_Conversion => Resolve_Unchecked_Type_Conversion (N, Ctx_Type); end case; -- Ada 2012 (AI05-0149): Apply an (implicit) conversion to an -- expression of an anonymous access type that occurs in the context -- of a named general access type, except when the expression is that -- of a membership test. This ensures proper legality checking in -- terms of allowed conversions (expressions that would be illegal to -- convert implicitly are allowed in membership tests). if Ada_Version >= Ada_2012 and then Ekind (Ctx_Type) = E_General_Access_Type and then Ekind (Etype (N)) = E_Anonymous_Access_Type and then Nkind (Parent (N)) not in N_Membership_Test then Rewrite (N, Convert_To (Ctx_Type, Relocate_Node (N))); Analyze_And_Resolve (N, Ctx_Type); end if; -- If the subexpression was replaced by a non-subexpression, then -- all we do is to expand it. The only legitimate case we know of -- is converting procedure call statement to entry call statements, -- but there may be others, so we are making this test general. if Nkind (N) not in N_Subexpr then Debug_A_Exit ("resolving ", N, " (done)"); Expand (N); return; end if; -- The expression is definitely NOT overloaded at this point, so -- we reset the Is_Overloaded flag to avoid any confusion when -- reanalyzing the node. Set_Is_Overloaded (N, False); -- Freeze expression type, entity if it is a name, and designated -- type if it is an allocator (RM 13.14(10,11,13)). -- Now that the resolution of the type of the node is complete, and -- we did not detect an error, we can expand this node. We skip the -- expand call if we are in a default expression, see section -- "Handling of Default Expressions" in Sem spec. Debug_A_Exit ("resolving ", N, " (done)"); -- We unconditionally freeze the expression, even if we are in -- default expression mode (the Freeze_Expression routine tests this -- flag and only freezes static types if it is set). -- Ada 2012 (AI05-177): The declaration of an expression function -- does not cause freezing, but we never reach here in that case. -- Here we are resolving the corresponding expanded body, so we do -- need to perform normal freezing. Freeze_Expression (N); -- Now we can do the expansion Expand (N); end if; end Resolve; ------------- -- Resolve -- ------------- -- Version with check(s) suppressed procedure Resolve (N : Node_Id; Typ : Entity_Id; Suppress : Check_Id) is begin if Suppress = All_Checks then declare Sva : constant Suppress_Array := Scope_Suppress.Suppress; begin Scope_Suppress.Suppress := (others => True); Resolve (N, Typ); Scope_Suppress.Suppress := Sva; end; else declare Svg : constant Boolean := Scope_Suppress.Suppress (Suppress); begin Scope_Suppress.Suppress (Suppress) := True; Resolve (N, Typ); Scope_Suppress.Suppress (Suppress) := Svg; end; end if; end Resolve; ------------- -- Resolve -- ------------- -- Version with implicit type procedure Resolve (N : Node_Id) is begin Resolve (N, Etype (N)); end Resolve; --------------------- -- Resolve_Actuals -- --------------------- procedure Resolve_Actuals (N : Node_Id; Nam : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); A : Node_Id; A_Id : Entity_Id; A_Typ : Entity_Id; F : Entity_Id; F_Typ : Entity_Id; Prev : Node_Id := Empty; Orig_A : Node_Id; Real_F : Entity_Id; Real_Subp : Entity_Id; -- If the subprogram being called is an inherited operation for -- a formal derived type in an instance, Real_Subp is the subprogram -- that will be called. It may have different formal names than the -- operation of the formal in the generic, so after actual is resolved -- the name of the actual in a named association must carry the name -- of the actual of the subprogram being called. procedure Check_Aliased_Parameter; -- Check rules on aliased parameters and related accessibility rules -- in (RM 3.10.2 (10.2-10.4)). procedure Check_Argument_Order; -- Performs a check for the case where the actuals are all simple -- identifiers that correspond to the formal names, but in the wrong -- order, which is considered suspicious and cause for a warning. procedure Check_Prefixed_Call; -- If the original node is an overloaded call in prefix notation, -- insert an 'Access or a dereference as needed over the first actual. -- Try_Object_Operation has already verified that there is a valid -- interpretation, but the form of the actual can only be determined -- once the primitive operation is identified. procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id); -- Emit an error concerning the illegal usage of an effectively volatile -- object in interfering context (SPARK RM 7.13(12)). procedure Insert_Default; -- If the actual is missing in a call, insert in the actuals list -- an instance of the default expression. The insertion is always -- a named association. procedure Property_Error (Var : Node_Id; Var_Id : Entity_Id; Prop_Nam : Name_Id); -- Emit an error concerning variable Var with entity Var_Id that has -- enabled property Prop_Nam when it acts as an actual parameter in a -- call and the corresponding formal parameter is of mode IN. function Same_Ancestor (T1, T2 : Entity_Id) return Boolean; -- Check whether T1 and T2, or their full views, are derived from a -- common type. Used to enforce the restrictions on array conversions -- of AI95-00246. function Static_Concatenation (N : Node_Id) return Boolean; -- Predicate to determine whether an actual that is a concatenation -- will be evaluated statically and does not need a transient scope. -- This must be determined before the actual is resolved and expanded -- because if needed the transient scope must be introduced earlier. ----------------------------- -- Check_Aliased_Parameter -- ----------------------------- procedure Check_Aliased_Parameter is Nominal_Subt : Entity_Id; begin if Is_Aliased (F) then if Is_Tagged_Type (A_Typ) then null; elsif Is_Aliased_View (A) then if Is_Constr_Subt_For_U_Nominal (A_Typ) then Nominal_Subt := Base_Type (A_Typ); else Nominal_Subt := A_Typ; end if; if Subtypes_Statically_Match (F_Typ, Nominal_Subt) then null; -- In a generic body assume the worst for generic formals: -- they can have a constrained partial view (AI05-041). elsif Has_Discriminants (F_Typ) and then not Is_Constrained (F_Typ) and then not Has_Constrained_Partial_View (F_Typ) and then not Is_Generic_Type (F_Typ) then null; else Error_Msg_NE ("untagged actual does not match " & "aliased formal&", A, F); end if; else Error_Msg_NE ("actual for aliased formal& must be " & "aliased object", A, F); end if; if Ekind (Nam) = E_Procedure then null; elsif Ekind (Etype (Nam)) = E_Anonymous_Access_Type then if Nkind (Parent (N)) = N_Type_Conversion and then Type_Access_Level (Etype (Parent (N))) < Object_Access_Level (A) then Error_Msg_N ("aliased actual has wrong accessibility", A); end if; elsif Nkind (Parent (N)) = N_Qualified_Expression and then Nkind (Parent (Parent (N))) = N_Allocator and then Type_Access_Level (Etype (Parent (Parent (N)))) < Object_Access_Level (A) then Error_Msg_N ("aliased actual in allocator has wrong accessibility", A); end if; end if; end Check_Aliased_Parameter; -------------------------- -- Check_Argument_Order -- -------------------------- procedure Check_Argument_Order is begin -- Nothing to do if no parameters, or original node is neither a -- function call nor a procedure call statement (happens in the -- operator-transformed-to-function call case), or the call does -- not come from source, or this warning is off. if not Warn_On_Parameter_Order or else No (Parameter_Associations (N)) or else Nkind (Original_Node (N)) not in N_Subprogram_Call or else not Comes_From_Source (N) then return; end if; declare Nargs : constant Nat := List_Length (Parameter_Associations (N)); begin -- Nothing to do if only one parameter if Nargs < 2 then return; end if; -- Here if at least two arguments declare Actuals : array (1 .. Nargs) of Node_Id; Actual : Node_Id; Formal : Node_Id; Wrong_Order : Boolean := False; -- Set True if an out of order case is found begin -- Collect identifier names of actuals, fail if any actual is -- not a simple identifier, and record max length of name. Actual := First (Parameter_Associations (N)); for J in Actuals'Range loop if Nkind (Actual) /= N_Identifier then return; else Actuals (J) := Actual; Next (Actual); end if; end loop; -- If we got this far, all actuals are identifiers and the list -- of their names is stored in the Actuals array. Formal := First_Formal (Nam); for J in Actuals'Range loop -- If we ran out of formals, that's odd, probably an error -- which will be detected elsewhere, but abandon the search. if No (Formal) then return; end if; -- If name matches and is in order OK if Chars (Formal) = Chars (Actuals (J)) then null; else -- If no match, see if it is elsewhere in list and if so -- flag potential wrong order if type is compatible. for K in Actuals'Range loop if Chars (Formal) = Chars (Actuals (K)) and then Has_Compatible_Type (Actuals (K), Etype (Formal)) then Wrong_Order := True; goto Continue; end if; end loop; -- No match return; end if; <<Continue>> Next_Formal (Formal); end loop; -- If Formals left over, also probably an error, skip warning if Present (Formal) then return; end if; -- Here we give the warning if something was out of order if Wrong_Order then Error_Msg_N ("?P?actuals for this call may be in wrong order", N); end if; end; end; end Check_Argument_Order; ------------------------- -- Check_Prefixed_Call -- ------------------------- procedure Check_Prefixed_Call is Act : constant Node_Id := First_Actual (N); A_Type : constant Entity_Id := Etype (Act); F_Type : constant Entity_Id := Etype (First_Formal (Nam)); Orig : constant Node_Id := Original_Node (N); New_A : Node_Id; begin -- Check whether the call is a prefixed call, with or without -- additional actuals. if Nkind (Orig) = N_Selected_Component or else (Nkind (Orig) = N_Indexed_Component and then Nkind (Prefix (Orig)) = N_Selected_Component and then Is_Entity_Name (Prefix (Prefix (Orig))) and then Is_Entity_Name (Act) and then Chars (Act) = Chars (Prefix (Prefix (Orig)))) then if Is_Access_Type (A_Type) and then not Is_Access_Type (F_Type) then -- Introduce dereference on object in prefix New_A := Make_Explicit_Dereference (Sloc (Act), Prefix => Relocate_Node (Act)); Rewrite (Act, New_A); Analyze (Act); elsif Is_Access_Type (F_Type) and then not Is_Access_Type (A_Type) then -- Introduce an implicit 'Access in prefix if not Is_Aliased_View (Act) then Error_Msg_NE ("object in prefixed call to& must be aliased " & "(RM 4.1.3 (13 1/2))", Prefix (Act), Nam); end if; Rewrite (Act, Make_Attribute_Reference (Loc, Attribute_Name => Name_Access, Prefix => Relocate_Node (Act))); end if; Analyze (Act); end if; end Check_Prefixed_Call; --------------------------------------- -- Flag_Effectively_Volatile_Objects -- --------------------------------------- procedure Flag_Effectively_Volatile_Objects (Expr : Node_Id) is function Flag_Object (N : Node_Id) return Traverse_Result; -- Determine whether arbitrary node N denotes an effectively volatile -- object and if it does, emit an error. ----------------- -- Flag_Object -- ----------------- function Flag_Object (N : Node_Id) return Traverse_Result is Id : Entity_Id; begin -- Do not consider nested function calls because they have already -- been processed during their own resolution. if Nkind (N) = N_Function_Call then return Skip; elsif Is_Entity_Name (N) and then Present (Entity (N)) then Id := Entity (N); if Is_Object (Id) and then Is_Effectively_Volatile (Id) and then (Async_Writers_Enabled (Id) or else Effective_Reads_Enabled (Id)) then Error_Msg_N ("volatile object cannot appear in this context (SPARK " & "RM 7.1.3(11))", N); return Skip; end if; end if; return OK; end Flag_Object; procedure Flag_Objects is new Traverse_Proc (Flag_Object); -- Start of processing for Flag_Effectively_Volatile_Objects begin Flag_Objects (Expr); end Flag_Effectively_Volatile_Objects; -------------------- -- Insert_Default -- -------------------- procedure Insert_Default is Actval : Node_Id; Assoc : Node_Id; begin -- Missing argument in call, nothing to insert if No (Default_Value (F)) then return; else -- Note that we do a full New_Copy_Tree, so that any associated -- Itypes are properly copied. This may not be needed any more, -- but it does no harm as a safety measure. Defaults of a generic -- formal may be out of bounds of the corresponding actual (see -- cc1311b) and an additional check may be required. Actval := New_Copy_Tree (Default_Value (F), New_Scope => Current_Scope, New_Sloc => Loc); -- Propagate dimension information, if any. Copy_Dimensions (Default_Value (F), Actval); if Is_Concurrent_Type (Scope (Nam)) and then Has_Discriminants (Scope (Nam)) then Replace_Actual_Discriminants (N, Actval); end if; if Is_Overloadable (Nam) and then Present (Alias (Nam)) then if Base_Type (Etype (F)) /= Base_Type (Etype (Actval)) and then not Is_Tagged_Type (Etype (F)) then -- If default is a real literal, do not introduce a -- conversion whose effect may depend on the run-time -- size of universal real. if Nkind (Actval) = N_Real_Literal then Set_Etype (Actval, Base_Type (Etype (F))); else Actval := Unchecked_Convert_To (Etype (F), Actval); end if; end if; if Is_Scalar_Type (Etype (F)) then Enable_Range_Check (Actval); end if; Set_Parent (Actval, N); -- Resolve aggregates with their base type, to avoid scope -- anomalies: the subtype was first built in the subprogram -- declaration, and the current call may be nested. if Nkind (Actval) = N_Aggregate then Analyze_And_Resolve (Actval, Etype (F)); else Analyze_And_Resolve (Actval, Etype (Actval)); end if; else Set_Parent (Actval, N); -- See note above concerning aggregates if Nkind (Actval) = N_Aggregate and then Has_Discriminants (Etype (Actval)) then Analyze_And_Resolve (Actval, Base_Type (Etype (Actval))); -- Resolve entities with their own type, which may differ from -- the type of a reference in a generic context (the view -- swapping mechanism did not anticipate the re-analysis of -- default values in calls). elsif Is_Entity_Name (Actval) then Analyze_And_Resolve (Actval, Etype (Entity (Actval))); else Analyze_And_Resolve (Actval, Etype (Actval)); end if; end if; -- If default is a tag indeterminate function call, propagate tag -- to obtain proper dispatching. if Is_Controlling_Formal (F) and then Nkind (Default_Value (F)) = N_Function_Call then Set_Is_Controlling_Actual (Actval); end if; end if; -- If the default expression raises constraint error, then just -- silently replace it with an N_Raise_Constraint_Error node, since -- we already gave the warning on the subprogram spec. If node is -- already a Raise_Constraint_Error leave as is, to prevent loops in -- the warnings removal machinery. if Raises_Constraint_Error (Actval) and then Nkind (Actval) /= N_Raise_Constraint_Error then Rewrite (Actval, Make_Raise_Constraint_Error (Loc, Reason => CE_Range_Check_Failed)); Set_Raises_Constraint_Error (Actval); Set_Etype (Actval, Etype (F)); end if; Assoc := Make_Parameter_Association (Loc, Explicit_Actual_Parameter => Actval, Selector_Name => Make_Identifier (Loc, Chars (F))); -- Case of insertion is first named actual if No (Prev) or else Nkind (Parent (Prev)) /= N_Parameter_Association then Set_Next_Named_Actual (Assoc, First_Named_Actual (N)); Set_First_Named_Actual (N, Actval); if No (Prev) then if No (Parameter_Associations (N)) then Set_Parameter_Associations (N, New_List (Assoc)); else Append (Assoc, Parameter_Associations (N)); end if; else Insert_After (Prev, Assoc); end if; -- Case of insertion is not first named actual else Set_Next_Named_Actual (Assoc, Next_Named_Actual (Parent (Prev))); Set_Next_Named_Actual (Parent (Prev), Actval); Append (Assoc, Parameter_Associations (N)); end if; Mark_Rewrite_Insertion (Assoc); Mark_Rewrite_Insertion (Actval); Prev := Actval; end Insert_Default; -------------------- -- Property_Error -- -------------------- procedure Property_Error (Var : Node_Id; Var_Id : Entity_Id; Prop_Nam : Name_Id) is begin Error_Msg_Name_1 := Prop_Nam; Error_Msg_NE ("external variable & with enabled property % cannot appear as " & "actual in procedure call (SPARK RM 7.1.3(10))", Var, Var_Id); Error_Msg_N ("\\corresponding formal parameter has mode In", Var); end Property_Error; ------------------- -- Same_Ancestor -- ------------------- function Same_Ancestor (T1, T2 : Entity_Id) return Boolean is FT1 : Entity_Id := T1; FT2 : Entity_Id := T2; begin if Is_Private_Type (T1) and then Present (Full_View (T1)) then FT1 := Full_View (T1); end if; if Is_Private_Type (T2) and then Present (Full_View (T2)) then FT2 := Full_View (T2); end if; return Root_Type (Base_Type (FT1)) = Root_Type (Base_Type (FT2)); end Same_Ancestor; -------------------------- -- Static_Concatenation -- -------------------------- function Static_Concatenation (N : Node_Id) return Boolean is begin case Nkind (N) is when N_String_Literal => return True; when N_Op_Concat => -- Concatenation is static when both operands are static and -- the concatenation operator is a predefined one. return Scope (Entity (N)) = Standard_Standard and then Static_Concatenation (Left_Opnd (N)) and then Static_Concatenation (Right_Opnd (N)); when others => if Is_Entity_Name (N) then declare Ent : constant Entity_Id := Entity (N); begin return Ekind (Ent) = E_Constant and then Present (Constant_Value (Ent)) and then Is_OK_Static_Expression (Constant_Value (Ent)); end; else return False; end if; end case; end Static_Concatenation; -- Start of processing for Resolve_Actuals begin Check_Argument_Order; if Is_Overloadable (Nam) and then Is_Inherited_Operation (Nam) and then In_Instance and then Present (Alias (Nam)) and then Present (Overridden_Operation (Alias (Nam))) then Real_Subp := Alias (Nam); else Real_Subp := Empty; end if; if Present (First_Actual (N)) then Check_Prefixed_Call; end if; A := First_Actual (N); F := First_Formal (Nam); if Present (Real_Subp) then Real_F := First_Formal (Real_Subp); end if; while Present (F) loop if No (A) and then Needs_No_Actuals (Nam) then null; -- If we have an error in any actual or formal, indicated by a type -- of Any_Type, then abandon resolution attempt, and set result type -- to Any_Type. Skip this if the actual is a Raise_Expression, whose -- type is imposed from context. elsif (Present (A) and then Etype (A) = Any_Type) or else Etype (F) = Any_Type then if Nkind (A) /= N_Raise_Expression then Set_Etype (N, Any_Type); return; end if; end if; -- Case where actual is present -- If the actual is an entity, generate a reference to it now. We -- do this before the actual is resolved, because a formal of some -- protected subprogram, or a task discriminant, will be rewritten -- during expansion, and the source entity reference may be lost. if Present (A) and then Is_Entity_Name (A) and then Comes_From_Source (A) then Orig_A := Entity (A); if Present (Orig_A) then if Is_Formal (Orig_A) and then Ekind (F) /= E_In_Parameter then Generate_Reference (Orig_A, A, 'm'); elsif not Is_Overloaded (A) then if Ekind (F) /= E_Out_Parameter then Generate_Reference (Orig_A, A); -- RM 6.4.1(12): For an out parameter that is passed by -- copy, the formal parameter object is created, and: -- * For an access type, the formal parameter is initialized -- from the value of the actual, without checking that the -- value satisfies any constraint, any predicate, or any -- exclusion of the null value. -- * For a scalar type that has the Default_Value aspect -- specified, the formal parameter is initialized from the -- value of the actual, without checking that the value -- satisfies any constraint or any predicate. -- I do not understand why this case is included??? this is -- not a case where an OUT parameter is treated as IN OUT. -- * For a composite type with discriminants or that has -- implicit initial values for any subcomponents, the -- behavior is as for an in out parameter passed by copy. -- Hence for these cases we generate the read reference now -- (the write reference will be generated later by -- Note_Possible_Modification). elsif Is_By_Copy_Type (Etype (F)) and then (Is_Access_Type (Etype (F)) or else (Is_Scalar_Type (Etype (F)) and then Present (Default_Aspect_Value (Etype (F)))) or else (Is_Composite_Type (Etype (F)) and then (Has_Discriminants (Etype (F)) or else Is_Partially_Initialized_Type (Etype (F))))) then Generate_Reference (Orig_A, A); end if; end if; end if; end if; if Present (A) and then (Nkind (Parent (A)) /= N_Parameter_Association or else Chars (Selector_Name (Parent (A))) = Chars (F)) then -- If style checking mode on, check match of formal name if Style_Check then if Nkind (Parent (A)) = N_Parameter_Association then Check_Identifier (Selector_Name (Parent (A)), F); end if; end if; -- If the formal is Out or In_Out, do not resolve and expand the -- conversion, because it is subsequently expanded into explicit -- temporaries and assignments. However, the object of the -- conversion can be resolved. An exception is the case of tagged -- type conversion with a class-wide actual. In that case we want -- the tag check to occur and no temporary will be needed (no -- representation change can occur) and the parameter is passed by -- reference, so we go ahead and resolve the type conversion. -- Another exception is the case of reference to component or -- subcomponent of a bit-packed array, in which case we want to -- defer expansion to the point the in and out assignments are -- performed. if Ekind (F) /= E_In_Parameter and then Nkind (A) = N_Type_Conversion and then not Is_Class_Wide_Type (Etype (Expression (A))) then if Ekind (F) = E_In_Out_Parameter and then Is_Array_Type (Etype (F)) then -- In a view conversion, the conversion must be legal in -- both directions, and thus both component types must be -- aliased, or neither (4.6 (8)). -- The extra rule in 4.6 (24.9.2) seems unduly restrictive: -- the privacy requirement should not apply to generic -- types, and should be checked in an instance. ARG query -- is in order ??? if Has_Aliased_Components (Etype (Expression (A))) /= Has_Aliased_Components (Etype (F)) then Error_Msg_N ("both component types in a view conversion must be" & " aliased, or neither", A); -- Comment here??? what set of cases??? elsif not Same_Ancestor (Etype (F), Etype (Expression (A))) then -- Check view conv between unrelated by ref array types if Is_By_Reference_Type (Etype (F)) or else Is_By_Reference_Type (Etype (Expression (A))) then Error_Msg_N ("view conversion between unrelated by reference " & "array types not allowed (\'A'I-00246)", A); -- In Ada 2005 mode, check view conversion component -- type cannot be private, tagged, or volatile. Note -- that we only apply this to source conversions. The -- generated code can contain conversions which are -- not subject to this test, and we cannot extract the -- component type in such cases since it is not present. elsif Comes_From_Source (A) and then Ada_Version >= Ada_2005 then declare Comp_Type : constant Entity_Id := Component_Type (Etype (Expression (A))); begin if (Is_Private_Type (Comp_Type) and then not Is_Generic_Type (Comp_Type)) or else Is_Tagged_Type (Comp_Type) or else Is_Volatile (Comp_Type) then Error_Msg_N ("component type of a view conversion cannot" & " be private, tagged, or volatile" & " (RM 4.6 (24))", Expression (A)); end if; end; end if; end if; end if; -- Resolve expression if conversion is all OK if (Conversion_OK (A) or else Valid_Conversion (A, Etype (A), Expression (A))) and then not Is_Ref_To_Bit_Packed_Array (Expression (A)) then Resolve (Expression (A)); end if; -- If the actual is a function call that returns a limited -- unconstrained object that needs finalization, create a -- transient scope for it, so that it can receive the proper -- finalization list. elsif Nkind (A) = N_Function_Call and then Is_Limited_Record (Etype (F)) and then not Is_Constrained (Etype (F)) and then Expander_Active and then (Is_Controlled (Etype (F)) or else Has_Task (Etype (F))) then Establish_Transient_Scope (A, Sec_Stack => False); Resolve (A, Etype (F)); -- A small optimization: if one of the actuals is a concatenation -- create a block around a procedure call to recover stack space. -- This alleviates stack usage when several procedure calls in -- the same statement list use concatenation. We do not perform -- this wrapping for code statements, where the argument is a -- static string, and we want to preserve warnings involving -- sequences of such statements. elsif Nkind (A) = N_Op_Concat and then Nkind (N) = N_Procedure_Call_Statement and then Expander_Active and then not (Is_Intrinsic_Subprogram (Nam) and then Chars (Nam) = Name_Asm) and then not Static_Concatenation (A) then Establish_Transient_Scope (A, Sec_Stack => False); Resolve (A, Etype (F)); else if Nkind (A) = N_Type_Conversion and then Is_Array_Type (Etype (F)) and then not Same_Ancestor (Etype (F), Etype (Expression (A))) and then (Is_Limited_Type (Etype (F)) or else Is_Limited_Type (Etype (Expression (A)))) then Error_Msg_N ("conversion between unrelated limited array types " & "not allowed ('A'I-00246)", A); if Is_Limited_Type (Etype (F)) then Explain_Limited_Type (Etype (F), A); end if; if Is_Limited_Type (Etype (Expression (A))) then Explain_Limited_Type (Etype (Expression (A)), A); end if; end if; -- (Ada 2005: AI-251): If the actual is an allocator whose -- directly designated type is a class-wide interface, we build -- an anonymous access type to use it as the type of the -- allocator. Later, when the subprogram call is expanded, if -- the interface has a secondary dispatch table the expander -- will add a type conversion to force the correct displacement -- of the pointer. if Nkind (A) = N_Allocator then declare DDT : constant Entity_Id := Directly_Designated_Type (Base_Type (Etype (F))); New_Itype : Entity_Id; begin if Is_Class_Wide_Type (DDT) and then Is_Interface (DDT) then New_Itype := Create_Itype (E_Anonymous_Access_Type, A); Set_Etype (New_Itype, Etype (A)); Set_Directly_Designated_Type (New_Itype, Directly_Designated_Type (Etype (A))); Set_Etype (A, New_Itype); end if; -- Ada 2005, AI-162:If the actual is an allocator, the -- innermost enclosing statement is the master of the -- created object. This needs to be done with expansion -- enabled only, otherwise the transient scope will not -- be removed in the expansion of the wrapped construct. if (Is_Controlled (DDT) or else Has_Task (DDT)) and then Expander_Active then Establish_Transient_Scope (A, Sec_Stack => False); end if; end; if Ekind (Etype (F)) = E_Anonymous_Access_Type then Check_Restriction (No_Access_Parameter_Allocators, A); end if; end if; -- (Ada 2005): The call may be to a primitive operation of a -- tagged synchronized type, declared outside of the type. In -- this case the controlling actual must be converted to its -- corresponding record type, which is the formal type. The -- actual may be a subtype, either because of a constraint or -- because it is a generic actual, so use base type to locate -- concurrent type. F_Typ := Base_Type (Etype (F)); if Is_Tagged_Type (F_Typ) and then (Is_Concurrent_Type (F_Typ) or else Is_Concurrent_Record_Type (F_Typ)) then -- If the actual is overloaded, look for an interpretation -- that has a synchronized type. if not Is_Overloaded (A) then A_Typ := Base_Type (Etype (A)); else declare Index : Interp_Index; It : Interp; begin Get_First_Interp (A, Index, It); while Present (It.Typ) loop if Is_Concurrent_Type (It.Typ) or else Is_Concurrent_Record_Type (It.Typ) then A_Typ := Base_Type (It.Typ); exit; end if; Get_Next_Interp (Index, It); end loop; end; end if; declare Full_A_Typ : Entity_Id; begin if Present (Full_View (A_Typ)) then Full_A_Typ := Base_Type (Full_View (A_Typ)); else Full_A_Typ := A_Typ; end if; -- Tagged synchronized type (case 1): the actual is a -- concurrent type. if Is_Concurrent_Type (A_Typ) and then Corresponding_Record_Type (A_Typ) = F_Typ then Rewrite (A, Unchecked_Convert_To (Corresponding_Record_Type (A_Typ), A)); Resolve (A, Etype (F)); -- Tagged synchronized type (case 2): the formal is a -- concurrent type. elsif Ekind (Full_A_Typ) = E_Record_Type and then Present (Corresponding_Concurrent_Type (Full_A_Typ)) and then Is_Concurrent_Type (F_Typ) and then Present (Corresponding_Record_Type (F_Typ)) and then Full_A_Typ = Corresponding_Record_Type (F_Typ) then Resolve (A, Corresponding_Record_Type (F_Typ)); -- Common case else Resolve (A, Etype (F)); end if; end; -- Not a synchronized operation else Resolve (A, Etype (F)); end if; end if; A_Typ := Etype (A); F_Typ := Etype (F); -- An actual cannot be an untagged formal incomplete type if Ekind (A_Typ) = E_Incomplete_Type and then not Is_Tagged_Type (A_Typ) and then Is_Generic_Type (A_Typ) then Error_Msg_N ("invalid use of untagged formal incomplete type", A); end if; if Comes_From_Source (Original_Node (N)) and then Nkind_In (Original_Node (N), N_Function_Call, N_Procedure_Call_Statement) then -- In formal mode, check that actual parameters matching -- formals of tagged types are objects (or ancestor type -- conversions of objects), not general expressions. if Is_Actual_Tagged_Parameter (A) then if Is_SPARK_05_Object_Reference (A) then null; elsif Nkind (A) = N_Type_Conversion then declare Operand : constant Node_Id := Expression (A); Operand_Typ : constant Entity_Id := Etype (Operand); Target_Typ : constant Entity_Id := A_Typ; begin if not Is_SPARK_05_Object_Reference (Operand) then Check_SPARK_05_Restriction ("object required", Operand); -- In formal mode, the only view conversions are those -- involving ancestor conversion of an extended type. elsif not (Is_Tagged_Type (Target_Typ) and then not Is_Class_Wide_Type (Target_Typ) and then Is_Tagged_Type (Operand_Typ) and then not Is_Class_Wide_Type (Operand_Typ) and then Is_Ancestor (Target_Typ, Operand_Typ)) then if Ekind_In (F, E_Out_Parameter, E_In_Out_Parameter) then Check_SPARK_05_Restriction ("ancestor conversion is the only permitted " & "view conversion", A); else Check_SPARK_05_Restriction ("ancestor conversion required", A); end if; else null; end if; end; else Check_SPARK_05_Restriction ("object required", A); end if; -- In formal mode, the only view conversions are those -- involving ancestor conversion of an extended type. elsif Nkind (A) = N_Type_Conversion and then Ekind_In (F, E_Out_Parameter, E_In_Out_Parameter) then Check_SPARK_05_Restriction ("ancestor conversion is the only permitted view " & "conversion", A); end if; end if; -- has warnings suppressed, then we reset Never_Set_In_Source for -- the calling entity. The reason for this is to catch cases like -- GNAT.Spitbol.Patterns.Vstring_Var where the called subprogram -- uses trickery to modify an IN parameter. if Ekind (F) = E_In_Parameter and then Is_Entity_Name (A) and then Present (Entity (A)) and then Ekind (Entity (A)) = E_Variable and then Has_Warnings_Off (F_Typ) then Set_Never_Set_In_Source (Entity (A), False); end if; -- Perform error checks for IN and IN OUT parameters if Ekind (F) /= E_Out_Parameter then -- Check unset reference. For scalar parameters, it is clearly -- wrong to pass an uninitialized value as either an IN or -- IN-OUT parameter. For composites, it is also clearly an -- error to pass a completely uninitialized value as an IN -- parameter, but the case of IN OUT is trickier. We prefer -- not to give a warning here. For example, suppose there is -- a routine that sets some component of a record to False. -- It is perfectly reasonable to make this IN-OUT and allow -- either initialized or uninitialized records to be passed -- in this case. -- For partially initialized composite values, we also avoid -- warnings, since it is quite likely that we are passing a -- partially initialized value and only the initialized fields -- will in fact be read in the subprogram. if Is_Scalar_Type (A_Typ) or else (Ekind (F) = E_In_Parameter and then not Is_Partially_Initialized_Type (A_Typ)) then Check_Unset_Reference (A); end if; -- In Ada 83 we cannot pass an OUT parameter as an IN or IN OUT -- actual to a nested call, since this constitutes a reading of -- the parameter, which is not allowed. if Ada_Version = Ada_83 and then Is_Entity_Name (A) and then Ekind (Entity (A)) = E_Out_Parameter then Error_Msg_N ("(Ada 83) illegal reading of out parameter", A); end if; end if; -- In -gnatd.q mode, forget that a given array is constant when -- it is passed as an IN parameter to a foreign-convention -- subprogram. This is in case the subprogram evilly modifies the -- object. Of course, correct code would use IN OUT. if Debug_Flag_Dot_Q and then Ekind (F) = E_In_Parameter and then Has_Foreign_Convention (Nam) and then Is_Array_Type (F_Typ) and then Nkind (A) in N_Has_Entity and then Present (Entity (A)) then Set_Is_True_Constant (Entity (A), False); end if; -- Case of OUT or IN OUT parameter if Ekind (F) /= E_In_Parameter then -- For an Out parameter, check for useless assignment. Note -- that we can't set Last_Assignment this early, because we may -- kill current values in Resolve_Call, and that call would -- clobber the Last_Assignment field. -- Note: call Warn_On_Useless_Assignment before doing the check -- below for Is_OK_Variable_For_Out_Formal so that the setting -- of Referenced_As_LHS/Referenced_As_Out_Formal properly -- reflects the last assignment, not this one. if Ekind (F) = E_Out_Parameter then if Warn_On_Modified_As_Out_Parameter (F) and then Is_Entity_Name (A) and then Present (Entity (A)) and then Comes_From_Source (N) then Warn_On_Useless_Assignment (Entity (A), A); end if; end if; -- Validate the form of the actual. Note that the call to -- Is_OK_Variable_For_Out_Formal generates the required -- reference in this case. -- A call to an initialization procedure for an aggregate -- component may initialize a nested component of a constant -- designated object. In this context the object is variable. if not Is_OK_Variable_For_Out_Formal (A) and then not Is_Init_Proc (Nam) then Error_Msg_NE ("actual for& must be a variable", A, F); if Is_Subprogram (Current_Scope) then if Is_Invariant_Procedure (Current_Scope) or else Is_Partial_Invariant_Procedure (Current_Scope) then Error_Msg_N ("function used in invariant cannot modify its " & "argument", F); elsif Is_Predicate_Function (Current_Scope) then Error_Msg_N ("function used in predicate cannot modify its " & "argument", F); end if; end if; end if; -- What's the following about??? if Is_Entity_Name (A) then Kill_Checks (Entity (A)); else Kill_All_Checks; end if; end if; if Etype (A) = Any_Type then Set_Etype (N, Any_Type); return; end if; -- Apply appropriate constraint/predicate checks for IN [OUT] case if Ekind_In (F, E_In_Parameter, E_In_Out_Parameter) then -- Apply predicate tests except in certain special cases. Note -- that it might be more consistent to apply these only when -- expansion is active (in Exp_Ch6.Expand_Actuals), as we do -- for the outbound predicate tests ??? In any case indicate -- the function being called, for better warnings if the call -- leads to an infinite recursion. if Predicate_Tests_On_Arguments (Nam) then Apply_Predicate_Check (A, F_Typ, Nam); end if; -- Apply required constraint checks -- Gigi looks at the check flag and uses the appropriate types. -- For now since one flag is used there is an optimization -- which might not be done in the IN OUT case since Gigi does -- not do any analysis. More thought required about this ??? -- In fact is this comment obsolete??? doesn't the expander now -- generate all these tests anyway??? if Is_Scalar_Type (Etype (A)) then Apply_Scalar_Range_Check (A, F_Typ); elsif Is_Array_Type (Etype (A)) then Apply_Length_Check (A, F_Typ); elsif Is_Record_Type (F_Typ) and then Has_Discriminants (F_Typ) and then Is_Constrained (F_Typ) and then (not Is_Derived_Type (F_Typ) or else Comes_From_Source (Nam)) then Apply_Discriminant_Check (A, F_Typ); -- For view conversions of a discriminated object, apply -- check to object itself, the conversion alreay has the -- proper type. if Nkind (A) = N_Type_Conversion and then Is_Constrained (Etype (Expression (A))) then Apply_Discriminant_Check (Expression (A), F_Typ); end if; elsif Is_Access_Type (F_Typ) and then Is_Array_Type (Designated_Type (F_Typ)) and then Is_Constrained (Designated_Type (F_Typ)) then Apply_Length_Check (A, F_Typ); elsif Is_Access_Type (F_Typ) and then Has_Discriminants (Designated_Type (F_Typ)) and then Is_Constrained (Designated_Type (F_Typ)) then Apply_Discriminant_Check (A, F_Typ); else Apply_Range_Check (A, F_Typ); end if; -- Ada 2005 (AI-231): Note that the controlling parameter case -- already existed in Ada 95, which is partially checked -- elsewhere (see Checks), and we don't want the warning -- message to differ. if Is_Access_Type (F_Typ) and then Can_Never_Be_Null (F_Typ) and then Known_Null (A) then if Is_Controlling_Formal (F) then Apply_Compile_Time_Constraint_Error (N => A, Msg => "null value not allowed here??", Reason => CE_Access_Check_Failed); elsif Ada_Version >= Ada_2005 then Apply_Compile_Time_Constraint_Error (N => A, Msg => "(Ada 2005) null not allowed in " & "null-excluding formal??", Reason => CE_Null_Not_Allowed); end if; end if; end if; -- Checks for OUT parameters and IN OUT parameters if Ekind_In (F, E_Out_Parameter, E_In_Out_Parameter) then -- If there is a type conversion, make sure the return value -- meets the constraints of the variable before the conversion. if Nkind (A) = N_Type_Conversion then if Is_Scalar_Type (A_Typ) then Apply_Scalar_Range_Check (Expression (A), Etype (Expression (A)), A_Typ); -- In addition, the returned value of the parameter must -- satisfy the bounds of the object type (see comment -- below). Apply_Scalar_Range_Check (A, A_Typ, F_Typ); else Apply_Range_Check (Expression (A), Etype (Expression (A)), A_Typ); end if; -- If no conversion, apply scalar range checks and length check -- based on the subtype of the actual (NOT that of the formal). -- This indicates that the check takes place on return from the -- call. During expansion the required constraint checks are -- inserted. In GNATprove mode, in the absence of expansion, -- the flag indicates that the returned value is valid. else if Is_Scalar_Type (F_Typ) then Apply_Scalar_Range_Check (A, A_Typ, F_Typ); elsif Is_Array_Type (F_Typ) and then Ekind (F) = E_Out_Parameter then Apply_Length_Check (A, F_Typ); else Apply_Range_Check (A, A_Typ, F_Typ); end if; end if; -- Note: we do not apply the predicate checks for the case of -- OUT and IN OUT parameters. They are instead applied in the -- Expand_Actuals routine in Exp_Ch6. end if; -- An actual associated with an access parameter is implicitly -- converted to the anonymous access type of the formal and must -- satisfy the legality checks for access conversions. if Ekind (F_Typ) = E_Anonymous_Access_Type then if not Valid_Conversion (A, F_Typ, A) then Error_Msg_N ("invalid implicit conversion for access parameter", A); end if; -- If the actual is an access selected component of a variable, -- the call may modify its designated object. It is reasonable -- to treat this as a potential modification of the enclosing -- record, to prevent spurious warnings that it should be -- declared as a constant, because intuitively programmers -- regard the designated subcomponent as part of the record. if Nkind (A) = N_Selected_Component and then Is_Entity_Name (Prefix (A)) and then not Is_Constant_Object (Entity (Prefix (A))) then Note_Possible_Modification (A, Sure => False); end if; end if; -- Check bad case of atomic/volatile argument (RM C.6(12)) if Is_By_Reference_Type (Etype (F)) and then Comes_From_Source (N) then if Is_Atomic_Object (A) and then not Is_Atomic (Etype (F)) then Error_Msg_NE ("cannot pass atomic argument to non-atomic formal&", A, F); elsif Is_Volatile_Object (A) and then not Is_Volatile (Etype (F)) then Error_Msg_NE ("cannot pass volatile argument to non-volatile formal&", A, F); end if; end if; -- Check that subprograms don't have improper controlling -- arguments (RM 3.9.2 (9)). -- A primitive operation may have an access parameter of an -- incomplete tagged type, but a dispatching call is illegal -- if the type is still incomplete. if Is_Controlling_Formal (F) then Set_Is_Controlling_Actual (A); if Ekind (Etype (F)) = E_Anonymous_Access_Type then declare Desig : constant Entity_Id := Designated_Type (Etype (F)); begin if Ekind (Desig) = E_Incomplete_Type and then No (Full_View (Desig)) and then No (Non_Limited_View (Desig)) then Error_Msg_NE ("premature use of incomplete type& " & "in dispatching call", A, Desig); end if; end; end if; elsif Nkind (A) = N_Explicit_Dereference then Validate_Remote_Access_To_Class_Wide_Type (A); end if; -- Apply legality rule 3.9.2 (9/1) if (Is_Class_Wide_Type (A_Typ) or else Is_Dynamically_Tagged (A)) and then not Is_Class_Wide_Type (F_Typ) and then not Is_Controlling_Formal (F) and then not In_Instance then Error_Msg_N ("class-wide argument not allowed here!", A); if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then Error_Msg_Node_2 := F_Typ; Error_Msg_NE ("& is not a dispatching operation of &!", A, Nam); end if; -- Apply the checks described in 3.10.2(27): if the context is a -- specific access-to-object, the actual cannot be class-wide. -- Use base type to exclude access_to_subprogram cases. elsif Is_Access_Type (A_Typ) and then Is_Access_Type (F_Typ) and then not Is_Access_Subprogram_Type (Base_Type (F_Typ)) and then (Is_Class_Wide_Type (Designated_Type (A_Typ)) or else (Nkind (A) = N_Attribute_Reference and then Is_Class_Wide_Type (Etype (Prefix (A))))) and then not Is_Class_Wide_Type (Designated_Type (F_Typ)) and then not Is_Controlling_Formal (F) -- Disable these checks for call to imported C++ subprograms and then not (Is_Entity_Name (Name (N)) and then Is_Imported (Entity (Name (N))) and then Convention (Entity (Name (N))) = Convention_CPP) then Error_Msg_N ("access to class-wide argument not allowed here!", A); if Is_Subprogram (Nam) and then Comes_From_Source (Nam) then Error_Msg_Node_2 := Designated_Type (F_Typ); Error_Msg_NE ("& is not a dispatching operation of &!", A, Nam); end if; end if; Check_Aliased_Parameter; Eval_Actual (A); -- If it is a named association, treat the selector_name as a -- proper identifier, and mark the corresponding entity. if Nkind (Parent (A)) = N_Parameter_Association -- Ignore reference in SPARK mode, as it refers to an entity not -- in scope at the point of reference, so the reference should -- be ignored for computing effects of subprograms. and then not GNATprove_Mode then -- If subprogram is overridden, use name of formal that -- is being called. if Present (Real_Subp) then Set_Entity (Selector_Name (Parent (A)), Real_F); Set_Etype (Selector_Name (Parent (A)), Etype (Real_F)); else Set_Entity (Selector_Name (Parent (A)), F); Generate_Reference (F, Selector_Name (Parent (A))); Set_Etype (Selector_Name (Parent (A)), F_Typ); Generate_Reference (F_Typ, N, ' '); end if; end if; Prev := A; if Ekind (F) /= E_Out_Parameter then Check_Unset_Reference (A); end if; -- The following checks are only relevant when SPARK_Mode is on as -- they are not standard Ada legality rule. Internally generated -- temporaries are ignored. if SPARK_Mode = On and then Comes_From_Source (A) then -- An effectively volatile object may act as an actual when the -- corresponding formal is of a non-scalar effectively volatile -- type (SPARK RM 7.1.3(11)). if not Is_Scalar_Type (Etype (F)) and then Is_Effectively_Volatile (Etype (F)) then null; -- An effectively volatile object may act as an actual in a -- call to an instance of Unchecked_Conversion. -- (SPARK RM 7.1.3(11)). elsif Is_Unchecked_Conversion_Instance (Nam) then null; -- The actual denotes an object elsif Is_Effectively_Volatile_Object (A) then Error_Msg_N ("volatile object cannot act as actual in a call (SPARK " & "RM 7.1.3(11))", A); -- Otherwise the actual denotes an expression. Inspect the -- expression and flag each effectively volatile object with -- enabled property Async_Writers or Effective_Reads as illegal -- because it apprears within an interfering context. Note that -- this is usually done in Resolve_Entity_Name, but when the -- effectively volatile object appears as an actual in a call, -- the call must be resolved first. else Flag_Effectively_Volatile_Objects (A); end if; -- Detect an external variable with an enabled property that -- does not match the mode of the corresponding formal in a -- procedure call. Functions are not considered because they -- cannot have effectively volatile formal parameters in the -- first place. if Ekind (Nam) = E_Procedure and then Ekind (F) = E_In_Parameter and then Is_Entity_Name (A) and then Present (Entity (A)) and then Ekind (Entity (A)) = E_Variable then A_Id := Entity (A); if Async_Readers_Enabled (A_Id) then Property_Error (A, A_Id, Name_Async_Readers); elsif Effective_Reads_Enabled (A_Id) then Property_Error (A, A_Id, Name_Effective_Reads); elsif Effective_Writes_Enabled (A_Id) then Property_Error (A, A_Id, Name_Effective_Writes); end if; end if; end if; -- A formal parameter of a specific tagged type whose related -- subprogram is subject to pragma Extensions_Visible with value -- "False" cannot act as an actual in a subprogram with value -- "True" (SPARK RM 6.1.7(3)). if Is_EVF_Expression (A) and then Extensions_Visible_Status (Nam) = Extensions_Visible_True then Error_Msg_N ("formal parameter cannot act as actual parameter when " & "Extensions_Visible is False", A); Error_Msg_NE ("\subprogram & has Extensions_Visible True", A, Nam); end if; -- The actual parameter of a Ghost subprogram whose formal is of -- mode IN OUT or OUT must be a Ghost variable (SPARK RM 6.9(12)). if Comes_From_Source (Nam) and then Is_Ghost_Entity (Nam) and then Ekind_In (F, E_In_Out_Parameter, E_Out_Parameter) and then Is_Entity_Name (A) and then Present (Entity (A)) and then not Is_Ghost_Entity (Entity (A)) then Error_Msg_NE ("non-ghost variable & cannot appear as actual in call to " & "ghost procedure", A, Entity (A)); if Ekind (F) = E_In_Out_Parameter then Error_Msg_N ("\corresponding formal has mode `IN OUT`", A); else Error_Msg_N ("\corresponding formal has mode OUT", A); end if; end if; Next_Actual (A); -- Case where actual is not present else Insert_Default; end if; Next_Formal (F); if Present (Real_Subp) then Next_Formal (Real_F); end if; end loop; end Resolve_Actuals; ----------------------- -- Resolve_Allocator -- ----------------------- procedure Resolve_Allocator (N : Node_Id; Typ : Entity_Id) is Desig_T : constant Entity_Id := Designated_Type (Typ); E : constant Node_Id := Expression (N); Subtyp : Entity_Id; Discrim : Entity_Id; Constr : Node_Id; Aggr : Node_Id; Assoc : Node_Id := Empty; Disc_Exp : Node_Id; procedure Check_Allocator_Discrim_Accessibility (Disc_Exp : Node_Id; Alloc_Typ : Entity_Id); -- Check that accessibility level associated with an access discriminant -- initialized in an allocator by the expression Disc_Exp is not deeper -- than the level of the allocator type Alloc_Typ. An error message is -- issued if this condition is violated. Specialized checks are done for -- the cases of a constraint expression which is an access attribute or -- an access discriminant. function In_Dispatching_Context return Boolean; -- If the allocator is an actual in a call, it is allowed to be class- -- wide when the context is not because it is a controlling actual. ------------------------------------------- -- Check_Allocator_Discrim_Accessibility -- ------------------------------------------- procedure Check_Allocator_Discrim_Accessibility (Disc_Exp : Node_Id; Alloc_Typ : Entity_Id) is begin if Type_Access_Level (Etype (Disc_Exp)) > Deepest_Type_Access_Level (Alloc_Typ) then Error_Msg_N ("operand type has deeper level than allocator type", Disc_Exp); -- When the expression is an Access attribute the level of the prefix -- object must not be deeper than that of the allocator's type. elsif Nkind (Disc_Exp) = N_Attribute_Reference and then Get_Attribute_Id (Attribute_Name (Disc_Exp)) = Attribute_Access and then Object_Access_Level (Prefix (Disc_Exp)) > Deepest_Type_Access_Level (Alloc_Typ) then Error_Msg_N ("prefix of attribute has deeper level than allocator type", Disc_Exp); -- When the expression is an access discriminant the check is against -- the level of the prefix object. elsif Ekind (Etype (Disc_Exp)) = E_Anonymous_Access_Type and then Nkind (Disc_Exp) = N_Selected_Component and then Object_Access_Level (Prefix (Disc_Exp)) > Deepest_Type_Access_Level (Alloc_Typ) then Error_Msg_N ("access discriminant has deeper level than allocator type", Disc_Exp); -- All other cases are legal else null; end if; end Check_Allocator_Discrim_Accessibility; ---------------------------- -- In_Dispatching_Context -- ---------------------------- function In_Dispatching_Context return Boolean is Par : constant Node_Id := Parent (N); begin return Nkind (Par) in N_Subprogram_Call and then Is_Entity_Name (Name (Par)) and then Is_Dispatching_Operation (Entity (Name (Par))); end In_Dispatching_Context; -- Start of processing for Resolve_Allocator begin -- Replace general access with specific type if Ekind (Etype (N)) = E_Allocator_Type then Set_Etype (N, Base_Type (Typ)); end if; if Is_Abstract_Type (Typ) then Error_Msg_N ("type of allocator cannot be abstract", N); end if; -- For qualified expression, resolve the expression using the given -- subtype (nothing to do for type mark, subtype indication) if Nkind (E) = N_Qualified_Expression then if Is_Class_Wide_Type (Etype (E)) and then not Is_Class_Wide_Type (Desig_T) and then not In_Dispatching_Context then Error_Msg_N ("class-wide allocator not allowed for this access type", N); end if; Resolve (Expression (E), Etype (E)); Check_Non_Static_Context (Expression (E)); Check_Unset_Reference (Expression (E)); -- Allocators generated by the build-in-place expansion mechanism -- are explicitly marked as coming from source but do not need to be -- checked for limited initialization. To exclude this case, ensure -- that the parent of the allocator is a source node. if Is_Limited_Type (Etype (E)) and then Comes_From_Source (N) and then Comes_From_Source (Parent (N)) and then not In_Instance_Body then if not OK_For_Limited_Init (Etype (E), Expression (E)) then if Nkind (Parent (N)) = N_Assignment_Statement then Error_Msg_N ("illegal expression for initialized allocator of a " & "limited type (RM 7.5 (2.7/2))", N); else Error_Msg_N ("initialization not allowed for limited types", N); end if; Explain_Limited_Type (Etype (E), N); end if; end if; -- A qualified expression requires an exact match of the type. Class- -- wide matching is not allowed. if (Is_Class_Wide_Type (Etype (Expression (E))) or else Is_Class_Wide_Type (Etype (E))) and then Base_Type (Etype (Expression (E))) /= Base_Type (Etype (E)) then Wrong_Type (Expression (E), Etype (E)); end if; -- Calls to build-in-place functions are not currently supported in -- allocators for access types associated with a simple storage pool. -- Supporting such allocators may require passing additional implicit -- parameters to build-in-place functions (or a significant revision -- of the current b-i-p implementation to unify the handling for -- multiple kinds of storage pools). ??? if Is_Limited_View (Desig_T) and then Nkind (Expression (E)) = N_Function_Call then declare Pool : constant Entity_Id := Associated_Storage_Pool (Root_Type (Typ)); begin if Present (Pool) and then Present (Get_Rep_Pragma (Etype (Pool), Name_Simple_Storage_Pool_Type)) then Error_Msg_N ("limited function calls not yet supported in simple " & "storage pool allocators", Expression (E)); end if; end; end if; -- A special accessibility check is needed for allocators that -- constrain access discriminants. The level of the type of the -- expression used to constrain an access discriminant cannot be -- deeper than the type of the allocator (in contrast to access -- parameters, where the level of the actual can be arbitrary). -- We can't use Valid_Conversion to perform this check because in -- general the type of the allocator is unrelated to the type of -- the access discriminant. if Ekind (Typ) /= E_Anonymous_Access_Type or else Is_Local_Anonymous_Access (Typ) then Subtyp := Entity (Subtype_Mark (E)); Aggr := Original_Node (Expression (E)); if Has_Discriminants (Subtyp) and then Nkind_In (Aggr, N_Aggregate, N_Extension_Aggregate) then Discrim := First_Discriminant (Base_Type (Subtyp)); -- Get the first component expression of the aggregate if Present (Expressions (Aggr)) then Disc_Exp := First (Expressions (Aggr)); elsif Present (Component_Associations (Aggr)) then Assoc := First (Component_Associations (Aggr)); if Present (Assoc) then Disc_Exp := Expression (Assoc); else Disc_Exp := Empty; end if; else Disc_Exp := Empty; end if; while Present (Discrim) and then Present (Disc_Exp) loop if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then Check_Allocator_Discrim_Accessibility (Disc_Exp, Typ); end if; Next_Discriminant (Discrim); if Present (Discrim) then if Present (Assoc) then Next (Assoc); Disc_Exp := Expression (Assoc); elsif Present (Next (Disc_Exp)) then Next (Disc_Exp); else Assoc := First (Component_Associations (Aggr)); if Present (Assoc) then Disc_Exp := Expression (Assoc); else Disc_Exp := Empty; end if; end if; end if; end loop; end if; end if; -- For a subtype mark or subtype indication, freeze the subtype else Freeze_Expression (E); if Is_Access_Constant (Typ) and then not No_Initialization (N) then Error_Msg_N ("initialization required for access-to-constant allocator", N); end if; -- A special accessibility check is needed for allocators that -- constrain access discriminants. The level of the type of the -- expression used to constrain an access discriminant cannot be -- deeper than the type of the allocator (in contrast to access -- parameters, where the level of the actual can be arbitrary). -- We can't use Valid_Conversion to perform this check because -- in general the type of the allocator is unrelated to the type -- of the access discriminant. if Nkind (Original_Node (E)) = N_Subtype_Indication and then (Ekind (Typ) /= E_Anonymous_Access_Type or else Is_Local_Anonymous_Access (Typ)) then Subtyp := Entity (Subtype_Mark (Original_Node (E))); if Has_Discriminants (Subtyp) then Discrim := First_Discriminant (Base_Type (Subtyp)); Constr := First (Constraints (Constraint (Original_Node (E)))); while Present (Discrim) and then Present (Constr) loop if Ekind (Etype (Discrim)) = E_Anonymous_Access_Type then if Nkind (Constr) = N_Discriminant_Association then Disc_Exp := Original_Node (Expression (Constr)); else Disc_Exp := Original_Node (Constr); end if; Check_Allocator_Discrim_Accessibility (Disc_Exp, Typ); end if; Next_Discriminant (Discrim); Next (Constr); end loop; end if; end if; end if; -- Ada 2005 (AI-344): A class-wide allocator requires an accessibility -- check that the level of the type of the created object is not deeper -- than the level of the allocator's access type, since extensions can -- now occur at deeper levels than their ancestor types. This is a -- static accessibility level check; a run-time check is also needed in -- the case of an initialized allocator with a class-wide argument (see -- Expand_Allocator_Expression). if Ada_Version >= Ada_2005 and then Is_Class_Wide_Type (Desig_T) then declare Exp_Typ : Entity_Id; begin if Nkind (E) = N_Qualified_Expression then Exp_Typ := Etype (E); elsif Nkind (E) = N_Subtype_Indication then Exp_Typ := Entity (Subtype_Mark (Original_Node (E))); else Exp_Typ := Entity (E); end if; if Type_Access_Level (Exp_Typ) > Deepest_Type_Access_Level (Typ) then if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("type in allocator has deeper level than " & "designated class-wide type<<", E); Error_Msg_N ("\Program_Error [<<", E); Rewrite (N, Make_Raise_Program_Error (Sloc (N), Reason => PE_Accessibility_Check_Failed)); Set_Etype (N, Typ); -- Do not apply Ada 2005 accessibility checks on a class-wide -- allocator if the type given in the allocator is a formal -- type. A run-time check will be performed in the instance. elsif not Is_Generic_Type (Exp_Typ) then Error_Msg_N ("type in allocator has deeper level than " & "designated class-wide type", E); end if; end if; end; end if; -- Check for allocation from an empty storage pool if No_Pool_Assigned (Typ) then Error_Msg_N ("allocation from empty storage pool!", N); -- If the context is an unchecked conversion, as may happen within an -- inlined subprogram, the allocator is being resolved with its own -- anonymous type. In that case, if the target type has a specific -- storage pool, it must be inherited explicitly by the allocator type. elsif Nkind (Parent (N)) = N_Unchecked_Type_Conversion and then No (Associated_Storage_Pool (Typ)) then Set_Associated_Storage_Pool (Typ, Associated_Storage_Pool (Etype (Parent (N)))); end if; if Ekind (Etype (N)) = E_Anonymous_Access_Type then Check_Restriction (No_Anonymous_Allocators, N); end if; -- Check that an allocator with task parts isn't for a nested access -- type when restriction No_Task_Hierarchy applies. if not Is_Library_Level_Entity (Base_Type (Typ)) and then Has_Task (Base_Type (Desig_T)) then Check_Restriction (No_Task_Hierarchy, N); end if; -- An illegal allocator may be rewritten as a raise Program_Error -- statement. if Nkind (N) = N_Allocator then -- An anonymous access discriminant is the definition of a -- coextension. if Ekind (Typ) = E_Anonymous_Access_Type and then Nkind (Associated_Node_For_Itype (Typ)) = N_Discriminant_Specification then declare Discr : constant Entity_Id := Defining_Identifier (Associated_Node_For_Itype (Typ)); begin Check_Restriction (No_Coextensions, N); -- Ada 2012 AI05-0052: If the designated type of the allocator -- is limited, then the allocator shall not be used to define -- the value of an access discriminant unless the discriminated -- type is immutably limited. if Ada_Version >= Ada_2012 and then Is_Limited_Type (Desig_T) and then not Is_Limited_View (Scope (Discr)) then Error_Msg_N ("only immutably limited types can have anonymous " & "access discriminants designating a limited type", N); end if; end; -- Avoid marking an allocator as a dynamic coextension if it is -- within a static construct. if not Is_Static_Coextension (N) then Set_Is_Dynamic_Coextension (N); end if; -- Cleanup for potential static coextensions else Set_Is_Dynamic_Coextension (N, False); Set_Is_Static_Coextension (N, False); end if; end if; -- Report a simple error: if the designated object is a local task, -- its body has not been seen yet, and its activation will fail an -- elaboration check. if Is_Task_Type (Desig_T) and then Scope (Base_Type (Desig_T)) = Current_Scope and then Is_Compilation_Unit (Current_Scope) and then Ekind (Current_Scope) = E_Package and then not In_Package_Body (Current_Scope) then Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("cannot activate task before body seen<<", N); Error_Msg_N ("\Program_Error [<<", N); end if; -- Ada 2012 (AI05-0111-3): Detect an attempt to allocate a task or a -- type with a task component on a subpool. This action must raise -- Program_Error at runtime. if Ada_Version >= Ada_2012 and then Nkind (N) = N_Allocator and then Present (Subpool_Handle_Name (N)) and then Has_Task (Desig_T) then Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("cannot allocate task on subpool<<", N); Error_Msg_N ("\Program_Error [<<", N); Rewrite (N, Make_Raise_Program_Error (Sloc (N), Reason => PE_Explicit_Raise)); Set_Etype (N, Typ); end if; end Resolve_Allocator; --------------------------- -- Resolve_Arithmetic_Op -- --------------------------- -- Used for resolving all arithmetic operators except exponentiation procedure Resolve_Arithmetic_Op (N : Node_Id; Typ : Entity_Id) is L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); TL : constant Entity_Id := Base_Type (Etype (L)); TR : constant Entity_Id := Base_Type (Etype (R)); T : Entity_Id; Rop : Node_Id; B_Typ : constant Entity_Id := Base_Type (Typ); -- We do the resolution using the base type, because intermediate values -- in expressions always are of the base type, not a subtype of it. function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean; -- Returns True if N is in a context that expects "any real type" function Is_Integer_Or_Universal (N : Node_Id) return Boolean; -- Return True iff given type is Integer or universal real/integer procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id); -- Choose type of integer literal in fixed-point operation to conform -- to available fixed-point type. T is the type of the other operand, -- which is needed to determine the expected type of N. procedure Set_Operand_Type (N : Node_Id); -- Set operand type to T if universal ------------------------------- -- Expected_Type_Is_Any_Real -- ------------------------------- function Expected_Type_Is_Any_Real (N : Node_Id) return Boolean is begin -- N is the expression after "delta" in a fixed_point_definition; -- see RM-3.5.9(6): return Nkind_In (Parent (N), N_Ordinary_Fixed_Point_Definition, N_Decimal_Fixed_Point_Definition, -- N is one of the bounds in a real_range_specification; -- see RM-3.5.7(5): N_Real_Range_Specification, -- N is the expression of a delta_constraint; -- see RM-J.3(3): N_Delta_Constraint); end Expected_Type_Is_Any_Real; ----------------------------- -- Is_Integer_Or_Universal -- ----------------------------- function Is_Integer_Or_Universal (N : Node_Id) return Boolean is T : Entity_Id; Index : Interp_Index; It : Interp; begin if not Is_Overloaded (N) then T := Etype (N); return Base_Type (T) = Base_Type (Standard_Integer) or else T = Universal_Integer or else T = Universal_Real; else Get_First_Interp (N, Index, It); while Present (It.Typ) loop if Base_Type (It.Typ) = Base_Type (Standard_Integer) or else It.Typ = Universal_Integer or else It.Typ = Universal_Real then return True; end if; Get_Next_Interp (Index, It); end loop; end if; return False; end Is_Integer_Or_Universal; ---------------------------- -- Set_Mixed_Mode_Operand -- ---------------------------- procedure Set_Mixed_Mode_Operand (N : Node_Id; T : Entity_Id) is Index : Interp_Index; It : Interp; begin if Universal_Interpretation (N) = Universal_Integer then -- A universal integer literal is resolved as standard integer -- except in the case of a fixed-point result, where we leave it -- as universal (to be handled by Exp_Fixd later on) if Is_Fixed_Point_Type (T) then Resolve (N, Universal_Integer); else Resolve (N, Standard_Integer); end if; elsif Universal_Interpretation (N) = Universal_Real and then (T = Base_Type (Standard_Integer) or else T = Universal_Integer or else T = Universal_Real) then -- A universal real can appear in a fixed-type context. We resolve -- the literal with that context, even though this might raise an -- exception prematurely (the other operand may be zero). Resolve (N, B_Typ); elsif Etype (N) = Base_Type (Standard_Integer) and then T = Universal_Real and then Is_Overloaded (N) then -- Integer arg in mixed-mode operation. Resolve with universal -- type, in case preference rule must be applied. Resolve (N, Universal_Integer); elsif Etype (N) = T and then B_Typ /= Universal_Fixed then -- Not a mixed-mode operation, resolve with context Resolve (N, B_Typ); elsif Etype (N) = Any_Fixed then -- N may itself be a mixed-mode operation, so use context type Resolve (N, B_Typ); elsif Is_Fixed_Point_Type (T) and then B_Typ = Universal_Fixed and then Is_Overloaded (N) then -- Must be (fixed * fixed) operation, operand must have one -- compatible interpretation. Resolve (N, Any_Fixed); elsif Is_Fixed_Point_Type (B_Typ) and then (T = Universal_Real or else Is_Fixed_Point_Type (T)) and then Is_Overloaded (N) then -- C * F(X) in a fixed context, where C is a real literal or a -- fixed-point expression. F must have either a fixed type -- interpretation or an integer interpretation, but not both. Get_First_Interp (N, Index, It); while Present (It.Typ) loop if Base_Type (It.Typ) = Base_Type (Standard_Integer) then if Analyzed (N) then Error_Msg_N ("ambiguous operand in fixed operation", N); else Resolve (N, Standard_Integer); end if; elsif Is_Fixed_Point_Type (It.Typ) then if Analyzed (N) then Error_Msg_N ("ambiguous operand in fixed operation", N); else Resolve (N, It.Typ); end if; end if; Get_Next_Interp (Index, It); end loop; -- Reanalyze the literal with the fixed type of the context. If -- context is Universal_Fixed, we are within a conversion, leave -- the literal as a universal real because there is no usable -- fixed type, and the target of the conversion plays no role in -- the resolution. declare Op2 : Node_Id; T2 : Entity_Id; begin if N = L then Op2 := R; else Op2 := L; end if; if B_Typ = Universal_Fixed and then Nkind (Op2) = N_Real_Literal then T2 := Universal_Real; else T2 := B_Typ; end if; Set_Analyzed (Op2, False); Resolve (Op2, T2); end; -- A universal real conditional expression can appear in a fixed-type -- context and must be resolved with that context to facilitate the -- code generation to the backend. elsif Nkind_In (N, N_Case_Expression, N_If_Expression) and then Etype (N) = Universal_Real and then Is_Fixed_Point_Type (B_Typ) then Resolve (N, B_Typ); else Resolve (N); end if; end Set_Mixed_Mode_Operand; ---------------------- -- Set_Operand_Type -- ---------------------- procedure Set_Operand_Type (N : Node_Id) is begin if Etype (N) = Universal_Integer or else Etype (N) = Universal_Real then Set_Etype (N, T); end if; end Set_Operand_Type; -- Start of processing for Resolve_Arithmetic_Op begin if Comes_From_Source (N) and then Ekind (Entity (N)) = E_Function and then Is_Imported (Entity (N)) and then Is_Intrinsic_Subprogram (Entity (N)) then Resolve_Intrinsic_Operator (N, Typ); return; -- Special-case for mixed-mode universal expressions or fixed point type -- operation: each argument is resolved separately. The same treatment -- is required if one of the operands of a fixed point operation is -- universal real, since in this case we don't do a conversion to a -- specific fixed-point type (instead the expander handles the case). -- Set the type of the node to its universal interpretation because -- legality checks on an exponentiation operand need the context. elsif (B_Typ = Universal_Integer or else B_Typ = Universal_Real) and then Present (Universal_Interpretation (L)) and then Present (Universal_Interpretation (R)) then Set_Etype (N, B_Typ); Resolve (L, Universal_Interpretation (L)); Resolve (R, Universal_Interpretation (R)); elsif (B_Typ = Universal_Real or else Etype (N) = Universal_Fixed or else (Etype (N) = Any_Fixed and then Is_Fixed_Point_Type (B_Typ)) or else (Is_Fixed_Point_Type (B_Typ) and then (Is_Integer_Or_Universal (L) or else Is_Integer_Or_Universal (R)))) and then Nkind_In (N, N_Op_Multiply, N_Op_Divide) then if TL = Universal_Integer or else TR = Universal_Integer then Check_For_Visible_Operator (N, B_Typ); end if; -- If context is a fixed type and one operand is integer, the other -- is resolved with the type of the context. if Is_Fixed_Point_Type (B_Typ) and then (Base_Type (TL) = Base_Type (Standard_Integer) or else TL = Universal_Integer) then Resolve (R, B_Typ); Resolve (L, TL); elsif Is_Fixed_Point_Type (B_Typ) and then (Base_Type (TR) = Base_Type (Standard_Integer) or else TR = Universal_Integer) then Resolve (L, B_Typ); Resolve (R, TR); else Set_Mixed_Mode_Operand (L, TR); Set_Mixed_Mode_Operand (R, TL); end if; -- Check the rule in RM05-4.5.5(19.1/2) disallowing universal_fixed -- multiplying operators from being used when the expected type is -- also universal_fixed. Note that B_Typ will be Universal_Fixed in -- some cases where the expected type is actually Any_Real; -- Expected_Type_Is_Any_Real takes care of that case. if Etype (N) = Universal_Fixed or else Etype (N) = Any_Fixed then if B_Typ = Universal_Fixed and then not Expected_Type_Is_Any_Real (N) and then not Nkind_In (Parent (N), N_Type_Conversion, N_Unchecked_Type_Conversion) then Error_Msg_N ("type cannot be determined from context!", N); Error_Msg_N ("\explicit conversion to result type required", N); Set_Etype (L, Any_Type); Set_Etype (R, Any_Type); else if Ada_Version = Ada_83 and then Etype (N) = Universal_Fixed and then not Nkind_In (Parent (N), N_Type_Conversion, N_Unchecked_Type_Conversion) then Error_Msg_N ("(Ada 83) fixed-point operation needs explicit " & "conversion", N); end if; -- The expected type is "any real type" in contexts like -- type T is delta <universal_fixed-expression> ... -- in which case we need to set the type to Universal_Real -- so that static expression evaluation will work properly. if Expected_Type_Is_Any_Real (N) then Set_Etype (N, Universal_Real); else Set_Etype (N, B_Typ); end if; end if; elsif Is_Fixed_Point_Type (B_Typ) and then (Is_Integer_Or_Universal (L) or else Nkind (L) = N_Real_Literal or else Nkind (R) = N_Real_Literal or else Is_Integer_Or_Universal (R)) then Set_Etype (N, B_Typ); elsif Etype (N) = Any_Fixed then -- If no previous errors, this is only possible if one operand is -- overloaded and the context is universal. Resolve as such. Set_Etype (N, B_Typ); end if; else if (TL = Universal_Integer or else TL = Universal_Real) and then (TR = Universal_Integer or else TR = Universal_Real) then Check_For_Visible_Operator (N, B_Typ); end if; -- If the context is Universal_Fixed and the operands are also -- universal fixed, this is an error, unless there is only one -- applicable fixed_point type (usually Duration). if B_Typ = Universal_Fixed and then Etype (L) = Universal_Fixed then T := Unique_Fixed_Point_Type (N); if T = Any_Type then Set_Etype (N, T); return; else Resolve (L, T); Resolve (R, T); end if; else Resolve (L, B_Typ); Resolve (R, B_Typ); end if; -- If one of the arguments was resolved to a non-universal type. -- label the result of the operation itself with the same type. -- Do the same for the universal argument, if any. T := Intersect_Types (L, R); Set_Etype (N, Base_Type (T)); Set_Operand_Type (L); Set_Operand_Type (R); end if; Generate_Operator_Reference (N, Typ); Analyze_Dimension (N); Eval_Arithmetic_Op (N); -- In SPARK, a multiplication or division with operands of fixed point -- types must be qualified or explicitly converted to identify the -- result type. if (Is_Fixed_Point_Type (Etype (L)) or else Is_Fixed_Point_Type (Etype (R))) and then Nkind_In (N, N_Op_Multiply, N_Op_Divide) and then not Nkind_In (Parent (N), N_Qualified_Expression, N_Type_Conversion) then Check_SPARK_05_Restriction ("operation should be qualified or explicitly converted", N); end if; -- Set overflow and division checking bit if Nkind (N) in N_Op then if not Overflow_Checks_Suppressed (Etype (N)) then Enable_Overflow_Check (N); end if; -- Give warning if explicit division by zero if Nkind_In (N, N_Op_Divide, N_Op_Rem, N_Op_Mod) and then not Division_Checks_Suppressed (Etype (N)) then Rop := Right_Opnd (N); if Compile_Time_Known_Value (Rop) and then ((Is_Integer_Type (Etype (Rop)) and then Expr_Value (Rop) = Uint_0) or else (Is_Real_Type (Etype (Rop)) and then Expr_Value_R (Rop) = Ureal_0)) then -- Specialize the warning message according to the operation. -- When SPARK_Mode is On, force a warning instead of an error -- in that case, as this likely corresponds to deactivated -- code. The following warnings are for the case case Nkind (N) is when N_Op_Divide => -- For division, we have two cases, for float division -- of an unconstrained float type, on a machine where -- Machine_Overflows is false, we don't get an exception -- at run-time, but rather an infinity or Nan. The Nan -- case is pretty obscure, so just warn about infinities. if Is_Floating_Point_Type (Typ) and then not Is_Constrained (Typ) and then not Machine_Overflows_On_Target then Error_Msg_N ("float division by zero, may generate " & "'+'/'- infinity??", Right_Opnd (N)); -- For all other cases, we get a Constraint_Error else Apply_Compile_Time_Constraint_Error (N, "division by zero??", CE_Divide_By_Zero, Loc => Sloc (Right_Opnd (N)), Warn => SPARK_Mode = On); end if; when N_Op_Rem => Apply_Compile_Time_Constraint_Error (N, "rem with zero divisor??", CE_Divide_By_Zero, Loc => Sloc (Right_Opnd (N)), Warn => SPARK_Mode = On); when N_Op_Mod => Apply_Compile_Time_Constraint_Error (N, "mod with zero divisor??", CE_Divide_By_Zero, Loc => Sloc (Right_Opnd (N)), Warn => SPARK_Mode = On); -- Division by zero can only happen with division, rem, -- and mod operations. when others => raise Program_Error; end case; -- In GNATprove mode, we enable the division check so that -- GNATprove will issue a message if it cannot be proved. if GNATprove_Mode then Activate_Division_Check (N); end if; -- Otherwise just set the flag to check at run time else Activate_Division_Check (N); end if; end if; -- If Restriction No_Implicit_Conditionals is active, then it is -- violated if either operand can be negative for mod, or for rem -- if both operands can be negative. if Restriction_Check_Required (No_Implicit_Conditionals) and then Nkind_In (N, N_Op_Rem, N_Op_Mod) then declare Lo : Uint; Hi : Uint; OK : Boolean; LNeg : Boolean; RNeg : Boolean; -- Set if corresponding operand might be negative begin Determine_Range (Left_Opnd (N), OK, Lo, Hi, Assume_Valid => True); LNeg := (not OK) or else Lo < 0; Determine_Range (Right_Opnd (N), OK, Lo, Hi, Assume_Valid => True); RNeg := (not OK) or else Lo < 0; -- Check if we will be generating conditionals. There are two -- cases where that can happen, first for REM, the only case -- is largest negative integer mod -1, where the division can -- overflow, but we still have to give the right result. The -- front end generates a test for this annoying case. Here we -- just test if both operands can be negative (that's what the -- expander does, so we match its logic here). -- The second case is mod where either operand can be negative. -- In this case, the back end has to generate additional tests. if (Nkind (N) = N_Op_Rem and then (LNeg and RNeg)) or else (Nkind (N) = N_Op_Mod and then (LNeg or RNeg)) then Check_Restriction (No_Implicit_Conditionals, N); end if; end; end if; end if; Check_Unset_Reference (L); Check_Unset_Reference (R); end Resolve_Arithmetic_Op; ------------------ -- Resolve_Call -- ------------------ procedure Resolve_Call (N : Node_Id; Typ : Entity_Id) is function Same_Or_Aliased_Subprograms (S : Entity_Id; E : Entity_Id) return Boolean; -- Returns True if the subprogram entity S is the same as E or else -- S is an alias of E. --------------------------------- -- Same_Or_Aliased_Subprograms -- --------------------------------- function Same_Or_Aliased_Subprograms (S : Entity_Id; E : Entity_Id) return Boolean is Subp_Alias : constant Entity_Id := Alias (S); begin return S = E or else (Present (Subp_Alias) and then Subp_Alias = E); end Same_Or_Aliased_Subprograms; -- Local variables Loc : constant Source_Ptr := Sloc (N); Subp : constant Node_Id := Name (N); Body_Id : Entity_Id; I : Interp_Index; It : Interp; Nam : Entity_Id; Nam_Decl : Node_Id; Nam_UA : Entity_Id; Norm_OK : Boolean; Rtype : Entity_Id; Scop : Entity_Id; -- Start of processing for Resolve_Call begin -- The context imposes a unique interpretation with type Typ on a -- procedure or function call. Find the entity of the subprogram that -- yields the expected type, and propagate the corresponding formal -- constraints on the actuals. The caller has established that an -- interpretation exists, and emitted an error if not unique. -- First deal with the case of a call to an access-to-subprogram, -- dereference made explicit in Analyze_Call. if Ekind (Etype (Subp)) = E_Subprogram_Type then if not Is_Overloaded (Subp) then Nam := Etype (Subp); else -- Find the interpretation whose type (a subprogram type) has a -- return type that is compatible with the context. Analysis of -- the node has established that one exists. Nam := Empty; Get_First_Interp (Subp, I, It); while Present (It.Typ) loop if Covers (Typ, Etype (It.Typ)) then Nam := It.Typ; exit; end if; Get_Next_Interp (I, It); end loop; if No (Nam) then raise Program_Error; end if; end if; -- If the prefix is not an entity, then resolve it if not Is_Entity_Name (Subp) then Resolve (Subp, Nam); end if; -- For an indirect call, we always invalidate checks, since we do not -- know whether the subprogram is local or global. Yes we could do -- better here, e.g. by knowing that there are no local subprograms, -- but it does not seem worth the effort. Similarly, we kill all -- knowledge of current constant values. Kill_Current_Values; -- If this is a procedure call which is really an entry call, do -- the conversion of the procedure call to an entry call. Protected -- operations use the same circuitry because the name in the call -- can be an arbitrary expression with special resolution rules. elsif Nkind_In (Subp, N_Selected_Component, N_Indexed_Component) or else (Is_Entity_Name (Subp) and then Ekind (Entity (Subp)) = E_Entry) then Resolve_Entry_Call (N, Typ); Check_Elab_Call (N); -- Kill checks and constant values, as above for indirect case -- Who knows what happens when another task is activated? Kill_Current_Values; return; -- Normal subprogram call with name established in Resolve elsif not (Is_Type (Entity (Subp))) then Nam := Entity (Subp); Set_Entity_With_Checks (Subp, Nam); -- Otherwise we must have the case of an overloaded call else pragma Assert (Is_Overloaded (Subp)); -- Initialize Nam to prevent warning (we know it will be assigned -- in the loop below, but the compiler does not know that). Nam := Empty; Get_First_Interp (Subp, I, It); while Present (It.Typ) loop if Covers (Typ, It.Typ) then Nam := It.Nam; Set_Entity_With_Checks (Subp, Nam); exit; end if; Get_Next_Interp (I, It); end loop; end if; if Is_Access_Subprogram_Type (Base_Type (Etype (Nam))) and then not Is_Access_Subprogram_Type (Base_Type (Typ)) and then Nkind (Subp) /= N_Explicit_Dereference and then Present (Parameter_Associations (N)) then -- The prefix is a parameterless function call that returns an access -- to subprogram. If parameters are present in the current call, add -- add an explicit dereference. We use the base type here because -- within an instance these may be subtypes. -- The dereference is added either in Analyze_Call or here. Should -- be consolidated ??? Set_Is_Overloaded (Subp, False); Set_Etype (Subp, Etype (Nam)); Insert_Explicit_Dereference (Subp); Nam := Designated_Type (Etype (Nam)); Resolve (Subp, Nam); end if; -- Check that a call to Current_Task does not occur in an entry body if Is_RTE (Nam, RE_Current_Task) then declare P : Node_Id; begin P := N; loop P := Parent (P); -- Exclude calls that occur within the default of a formal -- parameter of the entry, since those are evaluated outside -- of the body. exit when No (P) or else Nkind (P) = N_Parameter_Specification; if Nkind (P) = N_Entry_Body or else (Nkind (P) = N_Subprogram_Body and then Is_Entry_Barrier_Function (P)) then Rtype := Etype (N); Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_NE ("& should not be used in entry body (RM C.7(17))<<", N, Nam); Error_Msg_NE ("\Program_Error [<<", N, Nam); Rewrite (N, Make_Raise_Program_Error (Loc, Reason => PE_Current_Task_In_Entry_Body)); Set_Etype (N, Rtype); return; end if; end loop; end; end if; -- Check that a procedure call does not occur in the context of the -- entry call statement of a conditional or timed entry call. Note that -- the case of a call to a subprogram renaming of an entry will also be -- rejected. The test for N not being an N_Entry_Call_Statement is -- defensive, covering the possibility that the processing of entry -- calls might reach this point due to later modifications of the code -- above. if Nkind (Parent (N)) = N_Entry_Call_Alternative and then Nkind (N) /= N_Entry_Call_Statement and then Entry_Call_Statement (Parent (N)) = N then if Ada_Version < Ada_2005 then Error_Msg_N ("entry call required in select statement", N); -- Ada 2005 (AI-345): If a procedure_call_statement is used -- for a procedure_or_entry_call, the procedure_name or -- procedure_prefix of the procedure_call_statement shall denote -- an entry renamed by a procedure, or (a view of) a primitive -- subprogram of a limited interface whose first parameter is -- a controlling parameter. elsif Nkind (N) = N_Procedure_Call_Statement and then not Is_Renamed_Entry (Nam) and then not Is_Controlling_Limited_Procedure (Nam) then Error_Msg_N ("entry call or dispatching primitive of interface required", N); end if; end if; -- If the SPARK_05 restriction is active, we are not allowed -- to have a call to a subprogram before we see its completion. if not Has_Completion (Nam) and then Restriction_Check_Required (SPARK_05) -- Don't flag strange internal calls and then Comes_From_Source (N) and then Comes_From_Source (Nam) -- Only flag calls in extended main source and then In_Extended_Main_Source_Unit (Nam) and then In_Extended_Main_Source_Unit (N) -- Exclude enumeration literals from this processing and then Ekind (Nam) /= E_Enumeration_Literal then Check_SPARK_05_Restriction ("call to subprogram cannot appear before its body", N); end if; -- Check that this is not a call to a protected procedure or entry from -- within a protected function. Check_Internal_Protected_Use (N, Nam); -- Freeze the subprogram name if not in a spec-expression. Note that -- we freeze procedure calls as well as function calls. Procedure calls -- are not frozen according to the rules (RM 13.14(14)) because it is -- impossible to have a procedure call to a non-frozen procedure in -- pure Ada, but in the code that we generate in the expander, this -- rule needs extending because we can generate procedure calls that -- need freezing. -- In Ada 2012, expression functions may be called within pre/post -- conditions of subsequent functions or expression functions. Such -- calls do not freeze when they appear within generated bodies, -- (including the body of another expression function) which would -- place the freeze node in the wrong scope. An expression function -- is frozen in the usual fashion, by the appearance of a real body, -- or at the end of a declarative part. if Is_Entity_Name (Subp) and then not In_Spec_Expression and then not Is_Expression_Function_Or_Completion (Current_Scope) and then (not Is_Expression_Function_Or_Completion (Entity (Subp)) or else Scope (Entity (Subp)) = Current_Scope) then Freeze_Expression (Subp); end if; -- For a predefined operator, the type of the result is the type imposed -- by context, except for a predefined operation on universal fixed. -- Otherwise The type of the call is the type returned by the subprogram -- being called. if Is_Predefined_Op (Nam) then if Etype (N) /= Universal_Fixed then Set_Etype (N, Typ); end if; -- If the subprogram returns an array type, and the context requires the -- component type of that array type, the node is really an indexing of -- the parameterless call. Resolve as such. A pathological case occurs -- when the type of the component is an access to the array type. In -- this case the call is truly ambiguous. If the call is to an intrinsic -- subprogram, it can't be an indexed component. This check is necessary -- because if it's Unchecked_Conversion, and we have "type T_Ptr is -- access T;" and "type T is array (...) of T_Ptr;" (i.e. an array of -- pointers to the same array), the compiler gets confused and does an -- infinite recursion. elsif (Needs_No_Actuals (Nam) or else Needs_One_Actual (Nam)) and then ((Is_Array_Type (Etype (Nam)) and then Covers (Typ, Component_Type (Etype (Nam)))) or else (Is_Access_Type (Etype (Nam)) and then Is_Array_Type (Designated_Type (Etype (Nam))) and then Covers (Typ, Component_Type (Designated_Type (Etype (Nam)))) and then not Is_Intrinsic_Subprogram (Entity (Subp)))) then declare Index_Node : Node_Id; New_Subp : Node_Id; Ret_Type : constant Entity_Id := Etype (Nam); begin if Is_Access_Type (Ret_Type) and then Ret_Type = Component_Type (Designated_Type (Ret_Type)) then Error_Msg_N ("cannot disambiguate function call and indexing", N); else New_Subp := Relocate_Node (Subp); -- The called entity may be an explicit dereference, in which -- case there is no entity to set. if Nkind (New_Subp) /= N_Explicit_Dereference then Set_Entity (Subp, Nam); end if; if (Is_Array_Type (Ret_Type) and then Component_Type (Ret_Type) /= Any_Type) or else (Is_Access_Type (Ret_Type) and then Component_Type (Designated_Type (Ret_Type)) /= Any_Type) then if Needs_No_Actuals (Nam) then -- Indexed call to a parameterless function Index_Node := Make_Indexed_Component (Loc, Prefix => Make_Function_Call (Loc, Name => New_Subp), Expressions => Parameter_Associations (N)); else -- An Ada 2005 prefixed call to a primitive operation -- whose first parameter is the prefix. This prefix was -- prepended to the parameter list, which is actually a -- list of indexes. Remove the prefix in order to build -- the proper indexed component. Index_Node := Make_Indexed_Component (Loc, Prefix => Make_Function_Call (Loc, Name => New_Subp, Parameter_Associations => New_List (Remove_Head (Parameter_Associations (N)))), Expressions => Parameter_Associations (N)); end if; -- Preserve the parenthesis count of the node Set_Paren_Count (Index_Node, Paren_Count (N)); -- Since we are correcting a node classification error made -- by the parser, we call Replace rather than Rewrite. Replace (N, Index_Node); Set_Etype (Prefix (N), Ret_Type); Set_Etype (N, Typ); Resolve_Indexed_Component (N, Typ); Check_Elab_Call (Prefix (N)); end if; end if; return; end; else -- If the called function is not declared in the main unit and it -- returns the limited view of type then use the available view (as -- is done in Try_Object_Operation) to prevent back-end confusion; -- for the function entity itself. The call must appear in a context -- where the nonlimited view is available. If the function entity is -- in the extended main unit then no action is needed, because the -- back end handles this case. In either case the type of the call -- is the nonlimited view. if From_Limited_With (Etype (Nam)) and then Present (Available_View (Etype (Nam))) then Set_Etype (N, Available_View (Etype (Nam))); if not In_Extended_Main_Code_Unit (Nam) then Set_Etype (Nam, Available_View (Etype (Nam))); end if; else Set_Etype (N, Etype (Nam)); end if; end if; -- In the case where the call is to an overloaded subprogram, Analyze -- calls Normalize_Actuals once per overloaded subprogram. Therefore in -- such a case Normalize_Actuals needs to be called once more to order -- the actuals correctly. Otherwise the call will have the ordering -- given by the last overloaded subprogram whether this is the correct -- one being called or not. if Is_Overloaded (Subp) then Normalize_Actuals (N, Nam, False, Norm_OK); pragma Assert (Norm_OK); end if; -- In any case, call is fully resolved now. Reset Overload flag, to -- prevent subsequent overload resolution if node is analyzed again Set_Is_Overloaded (Subp, False); Set_Is_Overloaded (N, False); -- A Ghost entity must appear in a specific context if Is_Ghost_Entity (Nam) and then Comes_From_Source (N) then Check_Ghost_Context (Nam, N); end if; -- If we are calling the current subprogram from immediately within its -- body, then that is the case where we can sometimes detect cases of -- infinite recursion statically. Do not try this in case restriction -- No_Recursion is in effect anyway, and do it only for source calls. if Comes_From_Source (N) then Scop := Current_Scope; -- Check violation of SPARK_05 restriction which does not permit -- a subprogram body to contain a call to the subprogram directly. if Restriction_Check_Required (SPARK_05) and then Same_Or_Aliased_Subprograms (Nam, Scop) then Check_SPARK_05_Restriction ("subprogram may not contain direct call to itself", N); end if; -- Issue warning for possible infinite recursion in the absence -- of the No_Recursion restriction. if Same_Or_Aliased_Subprograms (Nam, Scop) and then not Restriction_Active (No_Recursion) and then Check_Infinite_Recursion (N) then -- Here we detected and flagged an infinite recursion, so we do -- not need to test the case below for further warnings. Also we -- are all done if we now have a raise SE node. if Nkind (N) = N_Raise_Storage_Error then return; end if; -- If call is to immediately containing subprogram, then check for -- the case of a possible run-time detectable infinite recursion. else Scope_Loop : while Scop /= Standard_Standard loop if Same_Or_Aliased_Subprograms (Nam, Scop) then -- Although in general case, recursion is not statically -- checkable, the case of calling an immediately containing -- subprogram is easy to catch. Check_Restriction (No_Recursion, N); -- If the recursive call is to a parameterless subprogram, -- then even if we can't statically detect infinite -- recursion, this is pretty suspicious, and we output a -- warning. Furthermore, we will try later to detect some -- cases here at run time by expanding checking code (see -- Detect_Infinite_Recursion in package Exp_Ch6). -- If the recursive call is within a handler, do not emit a -- warning, because this is a common idiom: loop until input -- is correct, catch illegal input in handler and restart. if No (First_Formal (Nam)) and then Etype (Nam) = Standard_Void_Type and then not Error_Posted (N) and then Nkind (Parent (N)) /= N_Exception_Handler then -- For the case of a procedure call. We give the message -- only if the call is the first statement in a sequence -- of statements, or if all previous statements are -- simple assignments. This is simply a heuristic to -- decrease false positives, without losing too many good -- warnings. The idea is that these previous statements -- may affect global variables the procedure depends on. -- We also exclude raise statements, that may arise from -- constraint checks and are probably unrelated to the -- intended control flow. if Nkind (N) = N_Procedure_Call_Statement and then Is_List_Member (N) then declare P : Node_Id; begin P := Prev (N); while Present (P) loop if not Nkind_In (P, N_Assignment_Statement, N_Raise_Constraint_Error) then exit Scope_Loop; end if; Prev (P); end loop; end; end if; -- Do not give warning if we are in a conditional context declare K : constant Node_Kind := Nkind (Parent (N)); begin if (K = N_Loop_Statement and then Present (Iteration_Scheme (Parent (N)))) or else K = N_If_Statement or else K = N_Elsif_Part or else K = N_Case_Statement_Alternative then exit Scope_Loop; end if; end; -- Here warning is to be issued Set_Has_Recursive_Call (Nam); Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("possible infinite recursion<<!", N); Error_Msg_N ("\Storage_Error ]<<!", N); end if; exit Scope_Loop; end if; Scop := Scope (Scop); end loop Scope_Loop; end if; end if; -- Check obsolescent reference to Ada.Characters.Handling subprogram Check_Obsolescent_2005_Entity (Nam, Subp); -- If subprogram name is a predefined operator, it was given in -- functional notation. Replace call node with operator node, so -- that actuals can be resolved appropriately. if Is_Predefined_Op (Nam) or else Ekind (Nam) = E_Operator then Make_Call_Into_Operator (N, Typ, Entity (Name (N))); return; elsif Present (Alias (Nam)) and then Is_Predefined_Op (Alias (Nam)) then Resolve_Actuals (N, Nam); Make_Call_Into_Operator (N, Typ, Alias (Nam)); return; end if; -- Create a transient scope if the resulting type requires it -- There are several notable exceptions: -- a) In init procs, the transient scope overhead is not needed, and is -- even incorrect when the call is a nested initialization call for a -- component whose expansion may generate adjust calls. However, if the -- call is some other procedure call within an initialization procedure -- (for example a call to Create_Task in the init_proc of the task -- run-time record) a transient scope must be created around this call. -- b) Enumeration literal pseudo-calls need no transient scope -- c) Intrinsic subprograms (Unchecked_Conversion and source info -- functions) do not use the secondary stack even though the return -- type may be unconstrained. -- d) Calls to a build-in-place function, since such functions may -- allocate their result directly in a target object, and cases where -- the result does get allocated in the secondary stack are checked for -- within the specialized Exp_Ch6 procedures for expanding those -- build-in-place calls. -- e) Calls to inlinable expression functions do not use the secondary -- stack (since the call will be replaced by its returned object). -- f) If the subprogram is marked Inline_Always, then even if it returns -- an unconstrained type the call does not require use of the secondary -- stack. However, inlining will only take place if the body to inline -- is already present. It may not be available if e.g. the subprogram is -- declared in a child instance. -- If this is an initialization call for a type whose construction -- uses the secondary stack, and it is not a nested call to initialize -- a component, we do need to create a transient scope for it. We -- check for this by traversing the type in Check_Initialization_Call. if Is_Inlined (Nam) and then Has_Pragma_Inline (Nam) and then Nkind (Unit_Declaration_Node (Nam)) = N_Subprogram_Declaration and then Present (Body_To_Inline (Unit_Declaration_Node (Nam))) then null; elsif Ekind (Nam) = E_Enumeration_Literal or else Is_Build_In_Place_Function (Nam) or else Is_Intrinsic_Subprogram (Nam) or else Is_Inlinable_Expression_Function (Nam) then null; elsif Expander_Active and then Is_Type (Etype (Nam)) and then Requires_Transient_Scope (Etype (Nam)) and then (not Within_Init_Proc or else (not Is_Init_Proc (Nam) and then Ekind (Nam) /= E_Function)) then Establish_Transient_Scope (N, Sec_Stack => True); -- If the call appears within the bounds of a loop, it will -- be rewritten and reanalyzed, nothing left to do here. if Nkind (N) /= N_Function_Call then return; end if; elsif Is_Init_Proc (Nam) and then not Within_Init_Proc then Check_Initialization_Call (N, Nam); end if; -- A protected function cannot be called within the definition of the -- enclosing protected type, unless it is part of a pre/postcondition -- on another protected operation. This may appear in the entry wrapper -- created for an entry with preconditions. if Is_Protected_Type (Scope (Nam)) and then In_Open_Scopes (Scope (Nam)) and then not Has_Completion (Scope (Nam)) and then not In_Spec_Expression and then not Is_Entry_Wrapper (Current_Scope) then Error_Msg_NE ("& cannot be called before end of protected definition", N, Nam); end if; -- Propagate interpretation to actuals, and add default expressions -- where needed. if Present (First_Formal (Nam)) then Resolve_Actuals (N, Nam); -- Overloaded literals are rewritten as function calls, for purpose of -- resolution. After resolution, we can replace the call with the -- literal itself. elsif Ekind (Nam) = E_Enumeration_Literal then Copy_Node (Subp, N); Resolve_Entity_Name (N, Typ); -- Avoid validation, since it is a static function call Generate_Reference (Nam, Subp); return; end if; -- If the subprogram is not global, then kill all saved values and -- checks. This is a bit conservative, since in many cases we could do -- better, but it is not worth the effort. Similarly, we kill constant -- values. However we do not need to do this for internal entities -- (unless they are inherited user-defined subprograms), since they -- are not in the business of molesting local values. -- If the flag Suppress_Value_Tracking_On_Calls is set, then we also -- kill all checks and values for calls to global subprograms. This -- takes care of the case where an access to a local subprogram is -- taken, and could be passed directly or indirectly and then called -- from almost any context. -- Note: we do not do this step till after resolving the actuals. That -- way we still take advantage of the current value information while -- scanning the actuals. -- We suppress killing values if we are processing the nodes associated -- with N_Freeze_Entity nodes. Otherwise the declaration of a tagged -- type kills all the values as part of analyzing the code that -- initializes the dispatch tables. if Inside_Freezing_Actions = 0 and then (not Is_Library_Level_Entity (Nam) or else Suppress_Value_Tracking_On_Call (Nearest_Dynamic_Scope (Current_Scope))) and then (Comes_From_Source (Nam) or else (Present (Alias (Nam)) and then Comes_From_Source (Alias (Nam)))) then Kill_Current_Values; end if; -- If we are warning about unread OUT parameters, this is the place to -- set Last_Assignment for OUT and IN OUT parameters. We have to do this -- after the above call to Kill_Current_Values (since that call clears -- the Last_Assignment field of all local variables). if (Warn_On_Modified_Unread or Warn_On_All_Unread_Out_Parameters) and then Comes_From_Source (N) and then In_Extended_Main_Source_Unit (N) then declare F : Entity_Id; A : Node_Id; begin F := First_Formal (Nam); A := First_Actual (N); while Present (F) and then Present (A) loop if Ekind_In (F, E_Out_Parameter, E_In_Out_Parameter) and then Warn_On_Modified_As_Out_Parameter (F) and then Is_Entity_Name (A) and then Present (Entity (A)) and then Comes_From_Source (N) and then Safe_To_Capture_Value (N, Entity (A)) then Set_Last_Assignment (Entity (A), A); end if; Next_Formal (F); Next_Actual (A); end loop; end; end if; -- If the subprogram is a primitive operation, check whether or not -- it is a correct dispatching call. if Is_Overloadable (Nam) and then Is_Dispatching_Operation (Nam) then Check_Dispatching_Call (N); elsif Ekind (Nam) /= E_Subprogram_Type and then Is_Abstract_Subprogram (Nam) and then not In_Instance then Error_Msg_NE ("cannot call abstract subprogram &!", N, Nam); end if; -- If this is a dispatching call, generate the appropriate reference, -- for better source navigation in GPS. if Is_Overloadable (Nam) and then Present (Controlling_Argument (N)) then Generate_Reference (Nam, Subp, 'R'); -- Normal case, not a dispatching call: generate a call reference else Generate_Reference (Nam, Subp, 's'); end if; if Is_Intrinsic_Subprogram (Nam) then Check_Intrinsic_Call (N); end if; -- Check for violation of restriction No_Specific_Termination_Handlers -- and warn on a potentially blocking call to Abort_Task. if Restriction_Check_Required (No_Specific_Termination_Handlers) and then (Is_RTE (Nam, RE_Set_Specific_Handler) or else Is_RTE (Nam, RE_Specific_Handler)) then Check_Restriction (No_Specific_Termination_Handlers, N); elsif Is_RTE (Nam, RE_Abort_Task) then Check_Potentially_Blocking_Operation (N); end if; -- A call to Ada.Real_Time.Timing_Events.Set_Handler to set a relative -- timing event violates restriction No_Relative_Delay (AI-0211). We -- need to check the second argument to determine whether it is an -- absolute or relative timing event. if Restriction_Check_Required (No_Relative_Delay) and then Is_RTE (Nam, RE_Set_Handler) and then Is_RTE (Etype (Next_Actual (First_Actual (N))), RE_Time_Span) then Check_Restriction (No_Relative_Delay, N); end if; -- Issue an error for a call to an eliminated subprogram. This routine -- will not perform the check if the call appears within a default -- expression. Check_For_Eliminated_Subprogram (Subp, Nam); -- In formal mode, the primitive operations of a tagged type or type -- extension do not include functions that return the tagged type. if Nkind (N) = N_Function_Call and then Is_Tagged_Type (Etype (N)) and then Is_Entity_Name (Name (N)) and then Is_Inherited_Operation_For_Type (Entity (Name (N)), Etype (N)) then Check_SPARK_05_Restriction ("function not inherited", N); end if; -- Implement rule in 12.5.1 (23.3/2): In an instance, if the actual is -- class-wide and the call dispatches on result in a context that does -- not provide a tag, the call raises Program_Error. if Nkind (N) = N_Function_Call and then In_Instance and then Is_Generic_Actual_Type (Typ) and then Is_Class_Wide_Type (Typ) and then Has_Controlling_Result (Nam) and then Nkind (Parent (N)) = N_Object_Declaration then -- Verify that none of the formals are controlling declare Call_OK : Boolean := False; F : Entity_Id; begin F := First_Formal (Nam); while Present (F) loop if Is_Controlling_Formal (F) then Call_OK := True; exit; end if; Next_Formal (F); end loop; if not Call_OK then Error_Msg_Warn := SPARK_Mode /= On; Error_Msg_N ("!cannot determine tag of result<<", N); Error_Msg_N ("\Program_Error [<<!", N); Insert_Action (N, Make_Raise_Program_Error (Sloc (N), Reason => PE_Explicit_Raise)); end if; end; end if; -- Check for calling a function with OUT or IN OUT parameter when the -- calling context (us right now) is not Ada 2012, so does not allow -- OUT or IN OUT parameters in function calls. Functions declared in -- a predefined unit are OK, as they may be called indirectly from a -- user-declared instantiation. if Ada_Version < Ada_2012 and then Ekind (Nam) = E_Function and then Has_Out_Or_In_Out_Parameter (Nam) and then not In_Predefined_Unit (Nam) then Error_Msg_NE ("& has at least one OUT or `IN OUT` parameter", N, Nam); Error_Msg_N ("\call to this function only allowed in Ada 2012", N); end if; -- Check the dimensions of the actuals in the call. For function calls, -- propagate the dimensions from the returned type to N. Analyze_Dimension_Call (N, Nam); -- All done, evaluate call and deal with elaboration issues Eval_Call (N); Check_Elab_Call (N); -- In GNATprove mode, expansion is disabled, but we want to inline some -- subprograms to facilitate formal verification. Indirect calls through -- a subprogram type or within a generic cannot be inlined. Inlining is -- performed only for calls subject to SPARK_Mode on. if GNATprove_Mode and then SPARK_Mode = On and then Is_Overloadable (Nam) and then not Inside_A_Generic then Nam_UA := Ultimate_Alias (Nam); Nam_Decl := Unit_Declaration_Node (Nam_UA); if Nkind (Nam_Decl) = N_Subprogram_Declaration then Body_Id := Corresponding_Body (Nam_Decl); -- Nothing to do if the subprogram is not eligible for inlining in -- GNATprove mode, or inlining is disabled with switch -gnatdm if not Is_Inlined_Always (Nam_UA) or else not Can_Be_Inlined_In_GNATprove_Mode (Nam_UA, Body_Id) or else Debug_Flag_M then null; -- Calls cannot be inlined inside assertions, as GNATprove treats -- assertions as logic expressions. elsif In_Assertion_Expr /= 0 then Cannot_Inline ("cannot inline & (in assertion expression)?", N, Nam_UA); -- Calls cannot be inlined inside default expressions elsif In_Default_Expr then Cannot_Inline ("cannot inline & (in default expression)?", N, Nam_UA); -- Inlining should not be performed during pre-analysis elsif Full_Analysis then -- With the one-pass inlining technique, a call cannot be -- inlined if the corresponding body has not been seen yet. if No (Body_Id) then Cannot_Inline ("cannot inline & (body not seen yet)?", N, Nam_UA); -- Nothing to do if there is no body to inline, indicating that -- the subprogram is not suitable for inlining in GNATprove -- mode. elsif No (Body_To_Inline (Nam_Decl)) then null; -- Do not inline calls inside expression functions, as this -- would prevent interpreting them as logical formulas in -- GNATprove. elsif Present (Current_Subprogram) and then Is_Expression_Function_Or_Completion (Current_Subprogram) then Cannot_Inline ("cannot inline & (inside expression function)?", N, Nam_UA); -- Calls cannot be inlined inside potentially unevaluated -- expressions, as this would create complex actions inside -- expressions, that are not handled by GNATprove. elsif Is_Potentially_Unevaluated (N) then Cannot_Inline ("cannot inline & (in potentially unevaluated context)?", N, Nam_UA); -- Do not inline calls which would possibly lead to missing a -- type conversion check on an input parameter. elsif not Call_Can_Be_Inlined_In_GNATprove_Mode (N, Nam) then Cannot_Inline ("cannot inline & (possible check on input parameters)?", N, Nam_UA); -- Otherwise, inline the call else Expand_Inlined_Call (N, Nam_UA, Nam); end if; end if; end if; end if; Warn_On_Overlapping_Actuals (Nam, N); end Resolve_Call; ----------------------------- -- Resolve_Case_Expression -- ----------------------------- procedure Resolve_Case_Expression (N : Node_Id; Typ : Entity_Id) is Alt : Node_Id; Alt_Expr : Node_Id; Alt_Typ : Entity_Id; Is_Dyn : Boolean; begin Alt := First (Alternatives (N)); while Present (Alt) loop Alt_Expr := Expression (Alt); Resolve (Alt_Expr, Typ); Alt_Typ := Etype (Alt_Expr); -- When the expression is of a scalar subtype different from the -- result subtype, then insert a conversion to ensure the generation -- of a constraint check. if Is_Scalar_Type (Alt_Typ) and then Alt_Typ /= Typ then Rewrite (Alt_Expr, Convert_To (Typ, Alt_Expr)); Analyze_And_Resolve (Alt_Expr, Typ); end if; Next (Alt); end loop; -- Apply RM 4.5.7 (17/3): whether the expression is statically or -- dynamically tagged must be known statically. if Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then Alt := First (Alternatives (N)); Is_Dyn := Is_Dynamically_Tagged (Expression (Alt)); while Present (Alt) loop if Is_Dynamically_Tagged (Expression (Alt)) /= Is_Dyn then Error_Msg_N ("all or none of the dependent expressions can be " & "dynamically tagged", N); end if; Next (Alt); end loop; end if; Set_Etype (N, Typ); Eval_Case_Expression (N); end Resolve_Case_Expression; ------------------------------- -- Resolve_Character_Literal -- ------------------------------- procedure Resolve_Character_Literal (N : Node_Id; Typ : Entity_Id) is B_Typ : constant Entity_Id := Base_Type (Typ); C : Entity_Id; begin -- Verify that the character does belong to the type of the context Set_Etype (N, B_Typ); Eval_Character_Literal (N); -- Wide_Wide_Character literals must always be defined, since the set -- of wide wide character literals is complete, i.e. if a character -- literal is accepted by the parser, then it is OK for wide wide -- character (out of range character literals are rejected). if Root_Type (B_Typ) = Standard_Wide_Wide_Character then return; -- Always accept character literal for type Any_Character, which -- occurs in error situations and in comparisons of literals, both -- of which should accept all literals. elsif B_Typ = Any_Character then return; -- For Standard.Character or a type derived from it, check that the -- literal is in range. elsif Root_Type (B_Typ) = Standard_Character then if In_Character_Range (UI_To_CC (Char_Literal_Value (N))) then return; end if; -- For Standard.Wide_Character or a type derived from it, check that the -- literal is in range. elsif Root_Type (B_Typ) = Standard_Wide_Character then if In_Wide_Character_Range (UI_To_CC (Char_Literal_Value (N))) then return; end if; -- For Standard.Wide_Wide_Character or a type derived from it, we -- know the literal is in range, since the parser checked. elsif Root_Type (B_Typ) = Standard_Wide_Wide_Character then return; -- If the entity is already set, this has already been resolved in a -- generic context, or comes from expansion. Nothing else to do. elsif Present (Entity (N)) then return; -- Otherwise we have a user defined character type, and we can use the -- standard visibility mechanisms to locate the referenced entity. else C := Current_Entity (N); while Present (C) loop if Etype (C) = B_Typ then Set_Entity_With_Checks (N, C); Generate_Reference (C, N); return; end if; C := Homonym (C); end loop; end if; -- If we fall through, then the literal does not match any of the -- entries of the enumeration type. This isn't just a constraint error -- situation, it is an illegality (see RM 4.2). Error_Msg_NE ("character not defined for }", N, First_Subtype (B_Typ)); end Resolve_Character_Literal; --------------------------- -- Resolve_Comparison_Op -- --------------------------- -- Context requires a boolean type, and plays no role in resolution. -- Processing identical to that for equality operators. The result type is -- the base type, which matters when pathological subtypes of booleans with -- limited ranges are used. procedure Resolve_Comparison_Op (N : Node_Id; Typ : Entity_Id) is L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); T : Entity_Id; begin -- If this is an intrinsic operation which is not predefined, use the -- types of its declared arguments to resolve the possibly overloaded -- operands. Otherwise the operands are unambiguous and specify the -- expected type. if Scope (Entity (N)) /= Standard_Standard then T := Etype (First_Entity (Entity (N))); else T := Find_Unique_Type (L, R); if T = Any_Fixed then T := Unique_Fixed_Point_Type (L); end if; end if; Set_Etype (N, Base_Type (Typ)); Generate_Reference (T, N, ' '); -- Skip remaining processing if already set to Any_Type if T = Any_Type then return; end if; -- Deal with other error cases if T = Any_String or else T = Any_Composite or else T = Any_Character then if T = Any_Character then Ambiguous_Character (L); else Error_Msg_N ("ambiguous operands for comparison", N); end if; Set_Etype (N, Any_Type); return; end if; -- Resolve the operands if types OK Resolve (L, T); Resolve (R, T); Check_Unset_Reference (L); Check_Unset_Reference (R); Generate_Operator_Reference (N, T); Check_Low_Bound_Tested (N); -- In SPARK, ordering operators <, <=, >, >= are not defined for Boolean -- types or array types except String. if Is_Boolean_Type (T) then Check_SPARK_05_Restriction ("comparison is not defined on Boolean type", N); elsif Is_Array_Type (T) and then Base_Type (T) /= Standard_String then Check_SPARK_05_Restriction ("comparison is not defined on array types other than String", N); end if; -- Check comparison on unordered enumeration if Bad_Unordered_Enumeration_Reference (N, Etype (L)) then Error_Msg_Sloc := Sloc (Etype (L)); Error_Msg_NE ("comparison on unordered enumeration type& declared#?U?", N, Etype (L)); end if; Analyze_Dimension (N); -- Evaluate the relation (note we do this after the above check since -- this Eval call may change N to True/False. Skip this evaluation -- inside assertions, in order to keep assertions as written by users -- for tools that rely on these, e.g. GNATprove for loop invariants. -- Except evaluation is still performed even inside assertions for -- comparisons between values of universal type, which are useless -- for static analysis tools, and not supported even by GNATprove. if In_Assertion_Expr = 0 or else (Is_Universal_Numeric_Type (Etype (L)) and then Is_Universal_Numeric_Type (Etype (R))) then Eval_Relational_Op (N); end if; end Resolve_Comparison_Op; ----------------------------------------- -- Resolve_Discrete_Subtype_Indication -- ----------------------------------------- procedure Resolve_Discrete_Subtype_Indication (N : Node_Id; Typ : Entity_Id) is R : Node_Id; S : Entity_Id; begin Analyze (Subtype_Mark (N)); S := Entity (Subtype_Mark (N)); if Nkind (Constraint (N)) /= N_Range_Constraint then Error_Msg_N ("expect range constraint for discrete type", N); Set_Etype (N, Any_Type); else R := Range_Expression (Constraint (N)); if R = Error then return; end if; Analyze (R); if Base_Type (S) /= Base_Type (Typ) then Error_Msg_NE ("expect subtype of }", N, First_Subtype (Typ)); -- Rewrite the constraint as a range of Typ -- to allow compilation to proceed further. Set_Etype (N, Typ); Rewrite (Low_Bound (R), Make_Attribute_Reference (Sloc (Low_Bound (R)), Prefix => New_Occurrence_Of (Typ, Sloc (R)), Attribute_Name => Name_First)); Rewrite (High_Bound (R), Make_Attribute_Reference (Sloc (High_Bound (R)), Prefix => New_Occurrence_Of (Typ, Sloc (R)), Attribute_Name => Name_First)); else Resolve (R, Typ); Set_Etype (N, Etype (R)); -- Additionally, we must check that the bounds are compatible -- with the given subtype, which might be different from the -- type of the context. Apply_Range_Check (R, S); -- ??? If the above check statically detects a Constraint_Error -- it replaces the offending bound(s) of the range R with a -- Constraint_Error node. When the itype which uses these bounds -- is frozen the resulting call to Duplicate_Subexpr generates -- a new temporary for the bounds. -- Unfortunately there are other itypes that are also made depend -- on these bounds, so when Duplicate_Subexpr is called they get -- a forward reference to the newly created temporaries and Gigi -- aborts on such forward references. This is probably sign of a -- more fundamental problem somewhere else in either the order of -- itype freezing or the way certain itypes are constructed. -- To get around this problem we call Remove_Side_Effects right -- away if either bounds of R are a Constraint_Error. declare L : constant Node_Id := Low_Bound (R); H : constant Node_Id := High_Bound (R); begin if Nkind (L) = N_Raise_Constraint_Error then Remove_Side_Effects (L); end if; if Nkind (H) = N_Raise_Constraint_Error then Remove_Side_Effects (H); end if; end; Check_Unset_Reference (Low_Bound (R)); Check_Unset_Reference (High_Bound (R)); end if; end if; end Resolve_Discrete_Subtype_Indication; ------------------------- -- Resolve_Entity_Name -- ------------------------- -- Used to resolve identifiers and expanded names procedure Resolve_Entity_Name (N : Node_Id; Typ : Entity_Id) is function Is_Assignment_Or_Object_Expression (Context : Node_Id; Expr : Node_Id) return Boolean; -- Determine whether node Context denotes an assignment statement or an -- object declaration whose expression is node Expr. ---------------------------------------- -- Is_Assignment_Or_Object_Expression -- ---------------------------------------- function Is_Assignment_Or_Object_Expression (Context : Node_Id; Expr : Node_Id) return Boolean is begin if Nkind_In (Context, N_Assignment_Statement, N_Object_Declaration) and then Expression (Context) = Expr then return True; -- Check whether a construct that yields a name is the expression of -- an assignment statement or an object declaration. elsif (Nkind_In (Context, N_Attribute_Reference, N_Explicit_Dereference, N_Indexed_Component, N_Selected_Component, N_Slice) and then Prefix (Context) = Expr) or else (Nkind_In (Context, N_Type_Conversion, N_Unchecked_Type_Conversion) and then Expression (Context) = Expr) then return Is_Assignment_Or_Object_Expression (Context => Parent (Context), Expr => Context); -- Otherwise the context is not an assignment statement or an object -- declaration. else return False; end if; end Is_Assignment_Or_Object_Expression; -- Local variables E : constant Entity_Id := Entity (N); Par : Node_Id; -- Start of processing for Resolve_Entity_Name begin -- If garbage from errors, set to Any_Type and return if No (E) and then Total_Errors_Detected /= 0 then Set_Etype (N, Any_Type); return; end if; -- Replace named numbers by corresponding literals. Note that this is -- the one case where Resolve_Entity_Name must reset the Etype, since -- it is currently marked as universal. if Ekind (E) = E_Named_Integer then Set_Etype (N, Typ); Eval_Named_Integer (N); elsif Ekind (E) = E_Named_Real then Set_Etype (N, Typ); Eval_Named_Real (N); -- For enumeration literals, we need to make sure that a proper style -- check is done, since such literals are overloaded, and thus we did -- not do a style check during the first phase of analysis. elsif Ekind (E) = E_Enumeration_Literal then Set_Entity_With_Checks (N, E); Eval_Entity_Name (N); -- Case of (sub)type name appearing in a context where an expression -- is expected. This is legal if occurrence is a current instance. -- See RM 8.6 (17/3). elsif Is_Type (E) then if Is_Current_Instance (N) then null; -- Any other use is an error else Error_Msg_N ("invalid use of subtype mark in expression or call", N); end if; -- Check discriminant use if entity is discriminant in current scope, -- i.e. discriminant of record or concurrent type currently being -- analyzed. Uses in corresponding body are unrestricted. elsif Ekind (E) = E_Discriminant and then Scope (E) = Current_Scope and then not Has_Completion (Current_Scope) then Check_Discriminant_Use (N); -- A parameterless generic function cannot appear in a context that -- requires resolution. elsif Ekind (E) = E_Generic_Function then Error_Msg_N ("illegal use of generic function", N); -- In Ada 83 an OUT parameter cannot be read elsif Ekind (E) = E_Out_Parameter and then (Nkind (Parent (N)) in N_Op or else Nkind (Parent (N)) = N_Explicit_Dereference or else Is_Assignment_Or_Object_Expression (Context => Parent (N), Expr => N)) then if Ada_Version = Ada_83 then Error_Msg_N ("(Ada 83) illegal reading of out parameter", N); end if; -- In all other cases, just do the possible static evaluation else -- A deferred constant that appears in an expression must have a -- completion, unless it has been removed by in-place expansion of -- an aggregate. A constant that is a renaming does not need -- initialization. if Ekind (E) = E_Constant and then Comes_From_Source (E) and then No (Constant_Value (E)) and then Is_Frozen (Etype (E)) and then not In_Spec_Expression and then not Is_Imported (E) and then Nkind (Parent (E)) /= N_Object_Renaming_Declaration then if No_Initialization (Parent (E)) or else (Present (Full_View (E)) and then No_Initialization (Parent (Full_View (E)))) then null; else Error_Msg_N ("deferred constant is frozen before completion", N); end if; end if; Eval_Entity_Name (N); end if; Par := Parent (N); -- When the entity appears in a parameter association, retrieve the -- related subprogram call. if Nkind (Par) = N_Parameter_Association then Par := Parent (Par); end if; if Comes_From_Source (N) then -- The following checks are only relevant when SPARK_Mode is on as -- they are not standard Ada legality rules. if SPARK_Mode = On then -- An effectively volatile object subject to enabled properties -- Async_Writers or Effective_Reads must appear in non-interfering -- context (SPARK RM 7.1.3(12)). if Is_Object (E) and then Is_Effectively_Volatile (E) and then (Async_Writers_Enabled (E) or else Effective_Reads_Enabled (E)) and then not Is_OK_Volatile_Context (Par, N) then SPARK_Msg_N ("volatile object cannot appear in this context " & "(SPARK RM 7.1.3(12))", N); end if; -- Check for possible elaboration issues with respect to reads of -- variables. The act of renaming the variable is not considered a -- read as it simply establishes an alias. if Ekind (E) = E_Variable and then Dynamic_Elaboration_Checks and then Nkind (Par) /= N_Object_Renaming_Declaration then Check_Elab_Call (N); end if; -- The variable may eventually become a constituent of a single -- protected/task type. Record the reference now and verify its -- legality when analyzing the contract of the variable -- (SPARK RM 9.3). if Ekind (E) = E_Variable then Record_Possible_Part_Of_Reference (E, N); end if; end if; -- A Ghost entity must appear in a specific context if Is_Ghost_Entity (E) then Check_Ghost_Context (E, N); end if; end if; end Resolve_Entity_Name; ------------------- -- Resolve_Entry -- ------------------- procedure Resolve_Entry (Entry_Name : Node_Id) is Loc : constant Source_Ptr := Sloc (Entry_Name); Nam : Entity_Id; New_N : Node_Id; S : Entity_Id; Tsk : Entity_Id; E_Name : Node_Id; Index : Node_Id; function Actual_Index_Type (E : Entity_Id) return Entity_Id; -- If the bounds of the entry family being called depend on task -- discriminants, build a new index subtype where a discriminant is -- replaced with the value of the discriminant of the target task. -- The target task is the prefix of the entry name in the call. ----------------------- -- Actual_Index_Type -- ----------------------- function Actual_Index_Type (E : Entity_Id) return Entity_Id is Typ : constant Entity_Id := Entry_Index_Type (E); Tsk : constant Entity_Id := Scope (E); Lo : constant Node_Id := Type_Low_Bound (Typ); Hi : constant Node_Id := Type_High_Bound (Typ); New_T : Entity_Id; function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id; -- If the bound is given by a discriminant, replace with a reference -- to the discriminant of the same name in the target task. If the -- entry name is the target of a requeue statement and the entry is -- in the current protected object, the bound to be used is the -- discriminal of the object (see Apply_Range_Checks for details of -- the transformation). ----------------------------- -- Actual_Discriminant_Ref -- ----------------------------- function Actual_Discriminant_Ref (Bound : Node_Id) return Node_Id is Typ : constant Entity_Id := Etype (Bound); Ref : Node_Id; begin Remove_Side_Effects (Bound); if not Is_Entity_Name (Bound) or else Ekind (Entity (Bound)) /= E_Discriminant then return Bound; elsif Is_Protected_Type (Tsk) and then In_Open_Scopes (Tsk) and then Nkind (Parent (Entry_Name)) = N_Requeue_Statement then -- Note: here Bound denotes a discriminant of the corresponding -- record type tskV, whose discriminal is a formal of the -- init-proc tskVIP. What we want is the body discriminal, -- which is associated to the discriminant of the original -- concurrent type tsk. return New_Occurrence_Of (Find_Body_Discriminal (Entity (Bound)), Loc); else Ref := Make_Selected_Component (Loc, Prefix => New_Copy_Tree (Prefix (Prefix (Entry_Name))), Selector_Name => New_Occurrence_Of (Entity (Bound), Loc)); Analyze (Ref); Resolve (Ref, Typ); return Ref; end if; end Actual_Discriminant_Ref; -- Start of processing for Actual_Index_Type begin if not Has_Discriminants (Tsk) or else (not Is_Entity_Name (Lo) and then not Is_Entity_Name (Hi)) then return Entry_Index_Type (E); else New_T := Create_Itype (Ekind (Typ), Parent (Entry_Name)); Set_Etype (New_T, Base_Type (Typ)); Set_Size_Info (New_T, Typ); Set_RM_Size (New_T, RM_Size (Typ)); Set_Scalar_Range (New_T, Make_Range (Sloc (Entry_Name), Low_Bound => Actual_Discriminant_Ref (Lo), High_Bound => Actual_Discriminant_Ref (Hi))); return New_T; end if; end Actual_Index_Type; -- Start of processing for Resolve_Entry begin -- Find name of entry being called, and resolve prefix of name with its -- own type. The prefix can be overloaded, and the name and signature of -- the entry must be taken into account. if Nkind (Entry_Name) = N_Indexed_Component then -- Case of dealing with entry family within the current tasks E_Name := Prefix (Entry_Name); else E_Name := Entry_Name; end if; if Is_Entity_Name (E_Name) then -- Entry call to an entry (or entry family) in the current task. This -- is legal even though the task will deadlock. Rewrite as call to -- current task. -- This can also be a call to an entry in an enclosing task. If this -- is a single task, we have to retrieve its name, because the scope -- of the entry is the task type, not the object. If the enclosing -- task is a task type, the identity of the task is given by its own -- self variable. -- Finally this can be a requeue on an entry of the same task or -- protected object. S := Scope (Entity (E_Name)); for J in reverse 0 .. Scope_Stack.Last loop if Is_Task_Type (Scope_Stack.Table (J).Entity) and then not Comes_From_Source (S) then -- S is an enclosing task or protected object. The concurrent -- declaration has been converted into a type declaration, and -- the object itself has an object declaration that follows -- the type in the same declarative part. Tsk := Next_Entity (S); while Etype (Tsk) /= S loop Next_Entity (Tsk); end loop; S := Tsk; exit; elsif S = Scope_Stack.Table (J).Entity then -- Call to current task. Will be transformed into call to Self exit; end if; end loop; New_N := Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (S, Loc), Selector_Name => New_Occurrence_Of (Entity (E_Name), Loc)); Rewrite (E_Name, New_N); Analyze (E_Name); elsif Nkind (Entry_Name) = N_Selected_Component and then Is_Overloaded (Prefix (Entry_Name)) then -- Use the entry name (which must be unique at this point) to find -- the prefix that returns the corresponding task/protected type. declare Pref : constant Node_Id := Prefix (Entry_Name); Ent : constant Entity_Id := Entity (Selector_Name (Entry_Name)); I : Interp_Index; It : Interp; begin Get_First_Interp (Pref, I, It); while Present (It.Typ) loop if Scope (Ent) = It.Typ then Set_Etype (Pref, It.Typ); exit; end if; Get_Next_Interp (I, It); end loop; end; end if; if Nkind (Entry_Name) = N_Selected_Component then Resolve (Prefix (Entry_Name)); else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component); Nam := Entity (Selector_Name (Prefix (Entry_Name))); Resolve (Prefix (Prefix (Entry_Name))); Index := First (Expressions (Entry_Name)); Resolve (Index, Entry_Index_Type (Nam)); -- Up to this point the expression could have been the actual in a -- simple entry call, and be given by a named association. if Nkind (Index) = N_Parameter_Association then Error_Msg_N ("expect expression for entry index", Index); else Apply_Range_Check (Index, Actual_Index_Type (Nam)); end if; end if; end Resolve_Entry; ------------------------ -- Resolve_Entry_Call -- ------------------------ procedure Resolve_Entry_Call (N : Node_Id; Typ : Entity_Id) is Entry_Name : constant Node_Id := Name (N); Loc : constant Source_Ptr := Sloc (Entry_Name); Actuals : List_Id; First_Named : Node_Id; Nam : Entity_Id; Norm_OK : Boolean; Obj : Node_Id; Was_Over : Boolean; begin -- We kill all checks here, because it does not seem worth the effort to -- do anything better, an entry call is a big operation. Kill_All_Checks; -- Processing of the name is similar for entry calls and protected -- operation calls. Once the entity is determined, we can complete -- the resolution of the actuals. -- The selector may be overloaded, in the case of a protected object -- with overloaded functions. The type of the context is used for -- resolution. if Nkind (Entry_Name) = N_Selected_Component and then Is_Overloaded (Selector_Name (Entry_Name)) and then Typ /= Standard_Void_Type then declare I : Interp_Index; It : Interp; begin Get_First_Interp (Selector_Name (Entry_Name), I, It); while Present (It.Typ) loop if Covers (Typ, It.Typ) then Set_Entity (Selector_Name (Entry_Name), It.Nam); Set_Etype (Entry_Name, It.Typ); Generate_Reference (It.Typ, N, ' '); end if; Get_Next_Interp (I, It); end loop; end; end if; Resolve_Entry (Entry_Name); if Nkind (Entry_Name) = N_Selected_Component then -- Simple entry call Nam := Entity (Selector_Name (Entry_Name)); Obj := Prefix (Entry_Name); Was_Over := Is_Overloaded (Selector_Name (Entry_Name)); else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component); -- Call to member of entry family Nam := Entity (Selector_Name (Prefix (Entry_Name))); Obj := Prefix (Prefix (Entry_Name)); Was_Over := Is_Overloaded (Selector_Name (Prefix (Entry_Name))); end if; -- We cannot in general check the maximum depth of protected entry calls -- at compile time. But we can tell that any protected entry call at all -- violates a specified nesting depth of zero. if Is_Protected_Type (Scope (Nam)) then Check_Restriction (Max_Entry_Queue_Length, N); end if; -- Use context type to disambiguate a protected function that can be -- called without actuals and that returns an array type, and where the -- argument list may be an indexing of the returned value. if Ekind (Nam) = E_Function and then Needs_No_Actuals (Nam) and then Present (Parameter_Associations (N)) and then ((Is_Array_Type (Etype (Nam)) and then Covers (Typ, Component_Type (Etype (Nam)))) or else (Is_Access_Type (Etype (Nam)) and then Is_Array_Type (Designated_Type (Etype (Nam))) and then Covers (Typ, Component_Type (Designated_Type (Etype (Nam)))))) then declare Index_Node : Node_Id; begin Index_Node := Make_Indexed_Component (Loc, Prefix => Make_Function_Call (Loc, Name => Relocate_Node (Entry_Name)), Expressions => Parameter_Associations (N)); -- Since we are correcting a node classification error made by the -- parser, we call Replace rather than Rewrite. Replace (N, Index_Node); Set_Etype (Prefix (N), Etype (Nam)); Set_Etype (N, Typ); Resolve_Indexed_Component (N, Typ); return; end; end if; if Ekind_In (Nam, E_Entry, E_Entry_Family) and then Present (Contract_Wrapper (Nam)) and then Current_Scope /= Contract_Wrapper (Nam) then -- Note the entity being called before rewriting the call, so that -- it appears used at this point. Generate_Reference (Nam, Entry_Name, 'r'); -- Rewrite as call to the precondition wrapper, adding the task -- object to the list of actuals. If the call is to a member of an -- entry family, include the index as well. declare New_Call : Node_Id; New_Actuals : List_Id; begin New_Actuals := New_List (Obj); if Nkind (Entry_Name) = N_Indexed_Component then Append_To (New_Actuals, New_Copy_Tree (First (Expressions (Entry_Name)))); end if; Append_List (Parameter_Associations (N), New_Actuals); New_Call := Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Contract_Wrapper (Nam), Loc), Parameter_Associations => New_Actuals); Rewrite (N, New_Call); -- Preanalyze and resolve new call. Current procedure is called -- from Resolve_Call, after which expansion will take place. Preanalyze_And_Resolve (N); return; end; end if; -- The operation name may have been overloaded. Order the actuals -- according to the formals of the resolved entity, and set the return -- type to that of the operation. if Was_Over then Normalize_Actuals (N, Nam, False, Norm_OK); pragma Assert (Norm_OK); Set_Etype (N, Etype (Nam)); -- Reset the Is_Overloaded flag, since resolution is now completed -- Simple entry call if Nkind (Entry_Name) = N_Selected_Component then Set_Is_Overloaded (Selector_Name (Entry_Name), False); -- Call to a member of an entry family else pragma Assert (Nkind (Entry_Name) = N_Indexed_Component); Set_Is_Overloaded (Selector_Name (Prefix (Entry_Name)), False); end if; end if; Resolve_Actuals (N, Nam); Check_Internal_Protected_Use (N, Nam); -- Create a call reference to the entry Generate_Reference (Nam, Entry_Name, 's'); if Ekind_In (Nam, E_Entry, E_Entry_Family) then Check_Potentially_Blocking_Operation (N); end if; -- Verify that a procedure call cannot masquerade as an entry -- call where an entry call is expected. if Ekind (Nam) = E_Procedure then if Nkind (Parent (N)) = N_Entry_Call_Alternative and then N = Entry_Call_Statement (Parent (N)) then Error_Msg_N ("entry call required in select statement", N); elsif Nkind (Parent (N)) = N_Triggering_Alternative and then N = Triggering_Statement (Parent (N)) then Error_Msg_N ("triggering statement cannot be procedure call", N); elsif Ekind (Scope (Nam)) = E_Task_Type and then not In_Open_Scopes (Scope (Nam)) then Error_Msg_N ("task has no entry with this name", Entry_Name); end if; end if; -- After resolution, entry calls and protected procedure calls are -- changed into entry calls, for expansion. The structure of the node -- does not change, so it can safely be done in place. Protected -- function calls must keep their structure because they are -- subexpressions. if Ekind (Nam) /= E_Function then -- A protected operation that is not a function may modify the -- corresponding object, and cannot apply to a constant. If this -- is an internal call, the prefix is the type itself. if Is_Protected_Type (Scope (Nam)) and then not Is_Variable (Obj) and then (not Is_Entity_Name (Obj) or else not Is_Type (Entity (Obj))) then Error_Msg_N ("prefix of protected procedure or entry call must be variable", Entry_Name); end if; Actuals := Parameter_Associations (N); First_Named := First_Named_Actual (N); Rewrite (N, Make_Entry_Call_Statement (Loc, Name => Entry_Name, Parameter_Associations => Actuals)); Set_First_Named_Actual (N, First_Named); Set_Analyzed (N, True); -- Protected functions can return on the secondary stack, in which -- case we must trigger the transient scope mechanism. elsif Expander_Active and then Requires_Transient_Scope (Etype (Nam)) then Establish_Transient_Scope (N, Sec_Stack => True); end if; end Resolve_Entry_Call; ------------------------- -- Resolve_Equality_Op -- ------------------------- -- Both arguments must have the same type, and the boolean context does -- not participate in the resolution. The first pass verifies that the -- interpretation is not ambiguous, and the type of the left argument is -- correctly set, or is Any_Type in case of ambiguity. If both arguments -- are strings or aggregates, allocators, or Null, they are ambiguous even -- though they carry a single (universal) type. Diagnose this case here. procedure Resolve_Equality_Op (N : Node_Id; Typ : Entity_Id) is L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); T : Entity_Id := Find_Unique_Type (L, R); procedure Check_If_Expression (Cond : Node_Id); -- The resolution rule for if expressions requires that each such must -- have a unique type. This means that if several dependent expressions -- are of a non-null anonymous access type, and the context does not -- impose an expected type (as can be the case in an equality operation) -- the expression must be rejected. procedure Explain_Redundancy (N : Node_Id); -- Attempt to explain the nature of a redundant comparison with True. If -- the expression N is too complex, this routine issues a general error -- message. function Find_Unique_Access_Type return Entity_Id; -- In the case of allocators and access attributes, the context must -- provide an indication of the specific access type to be used. If -- one operand is of such a "generic" access type, check whether there -- is a specific visible access type that has the same designated type. -- This is semantically dubious, and of no interest to any real code, -- but c48008a makes it all worthwhile. ------------------------- -- Check_If_Expression -- ------------------------- procedure Check_If_Expression (Cond : Node_Id) is Then_Expr : Node_Id; Else_Expr : Node_Id; begin if Nkind (Cond) = N_If_Expression then Then_Expr := Next (First (Expressions (Cond))); Else_Expr := Next (Then_Expr); if Nkind (Then_Expr) /= N_Null and then Nkind (Else_Expr) /= N_Null then Error_Msg_N ("cannot determine type of if expression", Cond); end if; end if; end Check_If_Expression; ------------------------ -- Explain_Redundancy -- ------------------------ procedure Explain_Redundancy (N : Node_Id) is Error : Name_Id; Val : Node_Id; Val_Id : Entity_Id; begin Val := N; -- Strip the operand down to an entity loop if Nkind (Val) = N_Selected_Component then Val := Selector_Name (Val); else exit; end if; end loop; -- The construct denotes an entity if Is_Entity_Name (Val) and then Present (Entity (Val)) then Val_Id := Entity (Val); -- Do not generate an error message when the comparison is done -- against the enumeration literal Standard.True. if Ekind (Val_Id) /= E_Enumeration_Literal then -- Build a customized error message Name_Len := 0; Add_Str_To_Name_Buffer ("?r?"); if Ekind (Val_Id) = E_Component then Add_Str_To_Name_Buffer ("component "); elsif Ekind (Val_Id) = E_Constant then Add_Str_To_Name_Buffer ("constant "); elsif Ekind (Val_Id) = E_Discriminant then Add_Str_To_Name_Buffer ("discriminant "); elsif Is_Formal (Val_Id) then Add_Str_To_Name_Buffer ("parameter "); elsif Ekind (Val_Id) = E_Variable then Add_Str_To_Name_Buffer ("variable "); end if; Add_Str_To_Name_Buffer ("& is always True!"); Error := Name_Find; Error_Msg_NE (Get_Name_String (Error), Val, Val_Id); end if; -- The construct is too complex to disect, issue a general message else Error_Msg_N ("?r?expression is always True!", Val); end if; end Explain_Redundancy; ----------------------------- -- Find_Unique_Access_Type -- ----------------------------- function Find_Unique_Access_Type return Entity_Id is Acc : Entity_Id; E : Entity_Id; S : Entity_Id; begin if Ekind_In (Etype (R), E_Allocator_Type, E_Access_Attribute_Type) then Acc := Designated_Type (Etype (R)); elsif Ekind_In (Etype (L), E_Allocator_Type, E_Access_Attribute_Type) then Acc := Designated_Type (Etype (L)); else return Empty; end if; S := Current_Scope; while S /= Standard_Standard loop E := First_Entity (S); while Present (E) loop if Is_Type (E) and then Is_Access_Type (E) and then Ekind (E) /= E_Allocator_Type and then Designated_Type (E) = Base_Type (Acc) then return E; end if; Next_Entity (E); end loop; S := Scope (S); end loop; return Empty; end Find_Unique_Access_Type; -- Start of processing for Resolve_Equality_Op begin Set_Etype (N, Base_Type (Typ)); Generate_Reference (T, N, ' '); if T = Any_Fixed then T := Unique_Fixed_Point_Type (L); end if; if T /= Any_Type then if T = Any_String or else T = Any_Composite or else T = Any_Character then if T = Any_Character then Ambiguous_Character (L); else Error_Msg_N ("ambiguous operands for equality", N); end if; Set_Etype (N, Any_Type); return; elsif T = Any_Access or else Ekind_In (T, E_Allocator_Type, E_Access_Attribute_Type) then T := Find_Unique_Access_Type; if No (T) then Error_Msg_N ("ambiguous operands for equality", N); Set_Etype (N, Any_Type); return; end if; -- If expressions must have a single type, and if the context does -- not impose one the dependent expressions cannot be anonymous -- access types. -- Why no similar processing for case expressions??? elsif Ada_Version >= Ada_2012 and then Ekind_In (Etype (L), E_Anonymous_Access_Type, E_Anonymous_Access_Subprogram_Type) and then Ekind_In (Etype (R), E_Anonymous_Access_Type, E_Anonymous_Access_Subprogram_Type) then Check_If_Expression (L); Check_If_Expression (R); end if; Resolve (L, T); Resolve (R, T); -- In SPARK, equality operators = and /= for array types other than -- String are only defined when, for each index position, the -- operands have equal static bounds. if Is_Array_Type (T) then -- Protect call to Matching_Static_Array_Bounds to avoid costly -- operation if not needed. if Restriction_Check_Required (SPARK_05) and then Base_Type (T) /= Standard_String and then Base_Type (Etype (L)) = Base_Type (Etype (R)) and then Etype (L) /= Any_Composite -- or else L in error and then Etype (R) /= Any_Composite -- or else R in error and then not Matching_Static_Array_Bounds (Etype (L), Etype (R)) then Check_SPARK_05_Restriction ("array types should have matching static bounds", N); end if; end if; -- If the unique type is a class-wide type then it will be expanded -- into a dispatching call to the predefined primitive. Therefore we -- check here for potential violation of such restriction. if Is_Class_Wide_Type (T) then Check_Restriction (No_Dispatching_Calls, N); end if; if Warn_On_Redundant_Constructs and then Comes_From_Source (N) and then Comes_From_Source (R) and then Is_Entity_Name (R) and then Entity (R) = Standard_True then Error_Msg_N -- CODEFIX ("?r?comparison with True is redundant!", N); Explain_Redundancy (Original_Node (R)); end if; Check_Unset_Reference (L); Check_Unset_Reference (R); Generate_Operator_Reference (N, T); Check_Low_Bound_Tested (N); -- If this is an inequality, it may be the implicit inequality -- created for a user-defined operation, in which case the corres- -- ponding equality operation is not intrinsic, and the operation -- cannot be constant-folded. Else fold. if Nkind (N) = N_Op_Eq or else Comes_From_Source (Entity (N)) or else Ekind (Entity (N)) = E_Operator or else Is_Intrinsic_Subprogram (Corresponding_Equality (Entity (N))) then Analyze_Dimension (N); Eval_Relational_Op (N); elsif Nkind (N) = N_Op_Ne and then Is_Abstract_Subprogram (Entity (N)) then Error_Msg_NE ("cannot call abstract subprogram &!", N, Entity (N)); end if; -- Ada 2005: If one operand is an anonymous access type, convert the -- other operand to it, to ensure that the underlying types match in -- the back-end. Same for access_to_subprogram, and the conversion -- verifies that the types are subtype conformant. -- We apply the same conversion in the case one of the operands is a -- private subtype of the type of the other. -- Why the Expander_Active test here ??? if Expander_Active and then (Ekind_In (T, E_Anonymous_Access_Type, E_Anonymous_Access_Subprogram_Type) or else Is_Private_Type (T)) then if Etype (L) /= T then Rewrite (L, Make_Unchecked_Type_Conversion (Sloc (L), Subtype_Mark => New_Occurrence_Of (T, Sloc (L)), Expression => Relocate_Node (L))); Analyze_And_Resolve (L, T); end if; if (Etype (R)) /= T then Rewrite (R, Make_Unchecked_Type_Conversion (Sloc (R), Subtype_Mark => New_Occurrence_Of (Etype (L), Sloc (R)), Expression => Relocate_Node (R))); Analyze_And_Resolve (R, T); end if; end if; end if; end Resolve_Equality_Op; ---------------------------------- -- Resolve_Explicit_Dereference -- ---------------------------------- procedure Resolve_Explicit_Dereference (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); New_N : Node_Id; P : constant Node_Id := Prefix (N); P_Typ : Entity_Id; -- The candidate prefix type, if overloaded I : Interp_Index; It : Interp; begin Check_Fully_Declared_Prefix (Typ, P); P_Typ := Empty; -- A useful optimization: check whether the dereference denotes an -- element of a container, and if so rewrite it as a call to the -- corresponding Element function. -- Disabled for now, on advice of ARG. A more restricted form of the -- predicate might be acceptable ??? -- if Is_Container_Element (N) then -- return; -- end if; if Is_Overloaded (P) then -- Use the context type to select the prefix that has the correct -- designated type. Keep the first match, which will be the inner- -- most. Get_First_Interp (P, I, It); while Present (It.Typ) loop if Is_Access_Type (It.Typ) and then Covers (Typ, Designated_Type (It.Typ)) then if No (P_Typ) then P_Typ := It.Typ; end if; -- Remove access types that do not match, but preserve access -- to subprogram interpretations, in case a further dereference -- is needed (see below). elsif Ekind (It.Typ) /= E_Access_Subprogram_Type then Remove_Interp (I); end if; Get_Next_Interp (I, It); end loop; if Present (P_Typ) then Resolve (P, P_Typ); Set_Etype (N, Designated_Type (P_Typ)); else -- If no interpretation covers the designated type of the prefix, -- this is the pathological case where not all implementations of -- the prefix allow the interpretation of the node as a call. Now -- that the expected type is known, Remove other interpretations -- from prefix, rewrite it as a call, and resolve again, so that -- the proper call node is generated. Get_First_Interp (P, I, It); while Present (It.Typ) loop if Ekind (It.Typ) /= E_Access_Subprogram_Type then Remove_Interp (I); end if; Get_Next_Interp (I, It); end loop; New_N := Make_Function_Call (Loc, Name => Make_Explicit_Dereference (Loc, Prefix => P), Parameter_Associations => New_List); Save_Interps (N, New_N); Rewrite (N, New_N); Analyze_And_Resolve (N, Typ); return; end if; -- If not overloaded, resolve P with its own type else Resolve (P); end if; -- If the prefix might be null, add an access check if Is_Access_Type (Etype (P)) and then not Can_Never_Be_Null (Etype (P)) then Apply_Access_Check (N); end if; -- If the designated type is a packed unconstrained array type, and the -- explicit dereference is not in the context of an attribute reference, -- then we must compute and set the actual subtype, since it is needed -- by Gigi. The reason we exclude the attribute case is that this is -- handled fine by Gigi, and in fact we use such attributes to build the -- actual subtype. We also exclude generated code (which builds actual -- subtypes directly if they are needed). if Is_Array_Type (Etype (N)) and then Is_Packed (Etype (N)) and then not Is_Constrained (Etype (N)) and then Nkind (Parent (N)) /= N_Attribute_Reference and then Comes_From_Source (N) then Set_Etype (N, Get_Actual_Subtype (N)); end if; Analyze_Dimension (N); -- Note: No Eval processing is required for an explicit dereference, -- because such a name can never be static. end Resolve_Explicit_Dereference; ------------------------------------- -- Resolve_Expression_With_Actions -- ------------------------------------- procedure Resolve_Expression_With_Actions (N : Node_Id; Typ : Entity_Id) is begin Set_Etype (N, Typ); -- If N has no actions, and its expression has been constant folded, -- then rewrite N as just its expression. Note, we can't do this in -- the general case of Is_Empty_List (Actions (N)) as this would cause -- Expression (N) to be expanded again. if Is_Empty_List (Actions (N)) and then Compile_Time_Known_Value (Expression (N)) then Rewrite (N, Expression (N)); end if; end Resolve_Expression_With_Actions; ---------------------------------- -- Resolve_Generalized_Indexing -- ---------------------------------- procedure Resolve_Generalized_Indexing (N : Node_Id; Typ : Entity_Id) is Indexing : constant Node_Id := Generalized_Indexing (N); Call : Node_Id; Indexes : List_Id; Pref : Node_Id; begin -- In ASIS mode, propagate the information about the indexes back to -- to the original indexing node. The generalized indexing is either -- a function call, or a dereference of one. The actuals include the -- prefix of the original node, which is the container expression. if ASIS_Mode then Resolve (Indexing, Typ); Set_Etype (N, Etype (Indexing)); Set_Is_Overloaded (N, False); Call := Indexing; while Nkind_In (Call, N_Explicit_Dereference, N_Selected_Component) loop Call := Prefix (Call); end loop; if Nkind (Call) = N_Function_Call then Indexes := New_Copy_List (Parameter_Associations (Call)); Pref := Remove_Head (Indexes); Set_Expressions (N, Indexes); -- If expression is to be reanalyzed, reset Generalized_Indexing -- to recreate call node, as is the case when the expression is -- part of an expression function. if In_Spec_Expression then Set_Generalized_Indexing (N, Empty); end if; Set_Prefix (N, Pref); end if; else Rewrite (N, Indexing); Resolve (N, Typ); end if; end Resolve_Generalized_Indexing; --------------------------- -- Resolve_If_Expression -- --------------------------- procedure Resolve_If_Expression (N : Node_Id; Typ : Entity_Id) is Condition : constant Node_Id := First (Expressions (N)); Then_Expr : constant Node_Id := Next (Condition); Else_Expr : Node_Id := Next (Then_Expr); Else_Typ : Entity_Id; Then_Typ : Entity_Id; begin Resolve (Condition, Any_Boolean); Resolve (Then_Expr, Typ); Then_Typ := Etype (Then_Expr); -- When the "then" expression is of a scalar subtype different from the -- result subtype, then insert a conversion to ensure the generation of -- a constraint check. The same is done for the else part below, again -- comparing subtypes rather than base types. if Is_Scalar_Type (Then_Typ) and then Then_Typ /= Typ then Rewrite (Then_Expr, Convert_To (Typ, Then_Expr)); Analyze_And_Resolve (Then_Expr, Typ); end if; -- If ELSE expression present, just resolve using the determined type -- If type is universal, resolve to any member of the class. if Present (Else_Expr) then if Typ = Universal_Integer then Resolve (Else_Expr, Any_Integer); elsif Typ = Universal_Real then Resolve (Else_Expr, Any_Real); else Resolve (Else_Expr, Typ); end if; Else_Typ := Etype (Else_Expr); if Is_Scalar_Type (Else_Typ) and then Else_Typ /= Typ then Rewrite (Else_Expr, Convert_To (Typ, Else_Expr)); Analyze_And_Resolve (Else_Expr, Typ); -- Apply RM 4.5.7 (17/3): whether the expression is statically or -- dynamically tagged must be known statically. elsif Is_Tagged_Type (Typ) and then not Is_Class_Wide_Type (Typ) then if Is_Dynamically_Tagged (Then_Expr) /= Is_Dynamically_Tagged (Else_Expr) then Error_Msg_N ("all or none of the dependent expressions " & "can be dynamically tagged", N); end if; end if; -- If no ELSE expression is present, root type must be Standard.Boolean -- and we provide a Standard.True result converted to the appropriate -- Boolean type (in case it is a derived boolean type). elsif Root_Type (Typ) = Standard_Boolean then Else_Expr := Convert_To (Typ, New_Occurrence_Of (Standard_True, Sloc (N))); Analyze_And_Resolve (Else_Expr, Typ); Append_To (Expressions (N), Else_Expr); else Error_Msg_N ("can only omit ELSE expression in Boolean case", N); Append_To (Expressions (N), Error); end if; Set_Etype (N, Typ); Eval_If_Expression (N); end Resolve_If_Expression; ------------------------------- -- Resolve_Indexed_Component -- ------------------------------- procedure Resolve_Indexed_Component (N : Node_Id; Typ : Entity_Id) is Name : constant Node_Id := Prefix (N); Expr : Node_Id; Array_Type : Entity_Id := Empty; -- to prevent junk warning Index : Node_Id; begin if Present (Generalized_Indexing (N)) then Resolve_Generalized_Indexing (N, Typ); return; end if; if Is_Overloaded (Name) then -- Use the context type to select the prefix that yields the correct -- component type. declare I : Interp_Index; It : Interp; I1 : Interp_Index := 0; P : constant Node_Id := Prefix (N); Found : Boolean := False; begin Get_First_Interp (P, I, It); while Present (It.Typ) loop if (Is_Array_Type (It.Typ) and then Covers (Typ, Component_Type (It.Typ))) or else (Is_Access_Type (It.Typ) and then Is_Array_Type (Designated_Type (It.Typ)) and then Covers (Typ, Component_Type (Designated_Type (It.Typ)))) then if Found then It := Disambiguate (P, I1, I, Any_Type); if It = No_Interp then Error_Msg_N ("ambiguous prefix for indexing", N); Set_Etype (N, Typ); return; else Found := True; Array_Type := It.Typ; I1 := I; end if; else Found := True; Array_Type := It.Typ; I1 := I; end if; end if; Get_Next_Interp (I, It); end loop; end; else Array_Type := Etype (Name); end if; Resolve (Name, Array_Type); Array_Type := Get_Actual_Subtype_If_Available (Name); -- If prefix is access type, dereference to get real array type. -- Note: we do not apply an access check because the expander always -- introduces an explicit dereference, and the check will happen there. if Is_Access_Type (Array_Type) then Array_Type := Designated_Type (Array_Type); end if; -- If name was overloaded, set component type correctly now -- If a misplaced call to an entry family (which has no index types) -- return. Error will be diagnosed from calling context. if Is_Array_Type (Array_Type) then Set_Etype (N, Component_Type (Array_Type)); else return; end if; Index := First_Index (Array_Type); Expr := First (Expressions (N)); -- The prefix may have resolved to a string literal, in which case its -- etype has a special representation. This is only possible currently -- if the prefix is a static concatenation, written in functional -- notation. if Ekind (Array_Type) = E_String_Literal_Subtype then Resolve (Expr, Standard_Positive); else while Present (Index) and Present (Expr) loop Resolve (Expr, Etype (Index)); Check_Unset_Reference (Expr); if Is_Scalar_Type (Etype (Expr)) then Apply_Scalar_Range_Check (Expr, Etype (Index)); else Apply_Range_Check (Expr, Get_Actual_Subtype (Index)); end if; Next_Index (Index); Next (Expr); end loop; end if; Analyze_Dimension (N); -- Do not generate the warning on suspicious index if we are analyzing -- package Ada.Tags; otherwise we will report the warning with the -- Prims_Ptr field of the dispatch table. if Scope (Etype (Prefix (N))) = Standard_Standard or else not Is_RTU (Cunit_Entity (Get_Source_Unit (Etype (Prefix (N)))), Ada_Tags) then Warn_On_Suspicious_Index (Name, First (Expressions (N))); Eval_Indexed_Component (N); end if; -- If the array type is atomic, and the component is not atomic, then -- this is worth a warning, since we have a situation where the access -- to the component may cause extra read/writes of the atomic array -- object, or partial word accesses, which could be unexpected. if Nkind (N) = N_Indexed_Component and then Is_Atomic_Ref_With_Address (N) and then not (Has_Atomic_Components (Array_Type) or else (Is_Entity_Name (Prefix (N)) and then Has_Atomic_Components (Entity (Prefix (N))))) and then not Is_Atomic (Component_Type (Array_Type)) then Error_Msg_N ("??access to non-atomic component of atomic array", Prefix (N)); Error_Msg_N ("??\may cause unexpected accesses to atomic object", Prefix (N)); end if; end Resolve_Indexed_Component; ----------------------------- -- Resolve_Integer_Literal -- ----------------------------- procedure Resolve_Integer_Literal (N : Node_Id; Typ : Entity_Id) is begin Set_Etype (N, Typ); Eval_Integer_Literal (N); end Resolve_Integer_Literal; -------------------------------- -- Resolve_Intrinsic_Operator -- -------------------------------- procedure Resolve_Intrinsic_Operator (N : Node_Id; Typ : Entity_Id) is Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ)); Op : Entity_Id; Arg1 : Node_Id; Arg2 : Node_Id; function Convert_Operand (Opnd : Node_Id) return Node_Id; -- If the operand is a literal, it cannot be the expression in a -- conversion. Use a qualified expression instead. --------------------- -- Convert_Operand -- --------------------- function Convert_Operand (Opnd : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Opnd); Res : Node_Id; begin if Nkind_In (Opnd, N_Integer_Literal, N_Real_Literal) then Res := Make_Qualified_Expression (Loc, Subtype_Mark => New_Occurrence_Of (Btyp, Loc), Expression => Relocate_Node (Opnd)); Analyze (Res); else Res := Unchecked_Convert_To (Btyp, Opnd); end if; return Res; end Convert_Operand; -- Start of processing for Resolve_Intrinsic_Operator begin -- We must preserve the original entity in a generic setting, so that -- the legality of the operation can be verified in an instance. if not Expander_Active then return; end if; Op := Entity (N); while Scope (Op) /= Standard_Standard loop Op := Homonym (Op); pragma Assert (Present (Op)); end loop; Set_Entity (N, Op); Set_Is_Overloaded (N, False); -- If the result or operand types are private, rewrite with unchecked -- conversions on the operands and the result, to expose the proper -- underlying numeric type. if Is_Private_Type (Typ) or else Is_Private_Type (Etype (Left_Opnd (N))) or else Is_Private_Type (Etype (Right_Opnd (N))) then Arg1 := Convert_Operand (Left_Opnd (N)); if Nkind (N) = N_Op_Expon then Arg2 := Unchecked_Convert_To (Standard_Integer, Right_Opnd (N)); else Arg2 := Convert_Operand (Right_Opnd (N)); end if; if Nkind (Arg1) = N_Type_Conversion then Save_Interps (Left_Opnd (N), Expression (Arg1)); end if; if Nkind (Arg2) = N_Type_Conversion then Save_Interps (Right_Opnd (N), Expression (Arg2)); end if; Set_Left_Opnd (N, Arg1); Set_Right_Opnd (N, Arg2); Set_Etype (N, Btyp); Rewrite (N, Unchecked_Convert_To (Typ, N)); Resolve (N, Typ); elsif Typ /= Etype (Left_Opnd (N)) or else Typ /= Etype (Right_Opnd (N)) then -- Add explicit conversion where needed, and save interpretations in -- case operands are overloaded. Arg1 := Convert_To (Typ, Left_Opnd (N)); Arg2 := Convert_To (Typ, Right_Opnd (N)); if Nkind (Arg1) = N_Type_Conversion then Save_Interps (Left_Opnd (N), Expression (Arg1)); else Save_Interps (Left_Opnd (N), Arg1); end if; if Nkind (Arg2) = N_Type_Conversion then Save_Interps (Right_Opnd (N), Expression (Arg2)); else Save_Interps (Right_Opnd (N), Arg2); end if; Rewrite (Left_Opnd (N), Arg1); Rewrite (Right_Opnd (N), Arg2); Analyze (Arg1); Analyze (Arg2); Resolve_Arithmetic_Op (N, Typ); else Resolve_Arithmetic_Op (N, Typ); end if; end Resolve_Intrinsic_Operator; -------------------------------------- -- Resolve_Intrinsic_Unary_Operator -- -------------------------------------- procedure Resolve_Intrinsic_Unary_Operator (N : Node_Id; Typ : Entity_Id) is Btyp : constant Entity_Id := Base_Type (Underlying_Type (Typ)); Op : Entity_Id; Arg2 : Node_Id; begin Op := Entity (N); while Scope (Op) /= Standard_Standard loop Op := Homonym (Op); pragma Assert (Present (Op)); end loop; Set_Entity (N, Op); if Is_Private_Type (Typ) then Arg2 := Unchecked_Convert_To (Btyp, Right_Opnd (N)); Save_Interps (Right_Opnd (N), Expression (Arg2)); Set_Right_Opnd (N, Arg2); Set_Etype (N, Btyp); Rewrite (N, Unchecked_Convert_To (Typ, N)); Resolve (N, Typ); else Resolve_Unary_Op (N, Typ); end if; end Resolve_Intrinsic_Unary_Operator; ------------------------ -- Resolve_Logical_Op -- ------------------------ procedure Resolve_Logical_Op (N : Node_Id; Typ : Entity_Id) is B_Typ : Entity_Id; begin Check_No_Direct_Boolean_Operators (N); -- Predefined operations on scalar types yield the base type. On the -- other hand, logical operations on arrays yield the type of the -- arguments (and the context). if Is_Array_Type (Typ) then B_Typ := Typ; else B_Typ := Base_Type (Typ); end if; -- The following test is required because the operands of the operation -- may be literals, in which case the resulting type appears to be -- compatible with a signed integer type, when in fact it is compatible -- only with modular types. If the context itself is universal, the -- operation is illegal. if not Valid_Boolean_Arg (Typ) then Error_Msg_N ("invalid context for logical operation", N); Set_Etype (N, Any_Type); return; elsif Typ = Any_Modular then Error_Msg_N ("no modular type available in this context", N); Set_Etype (N, Any_Type); return; elsif Is_Modular_Integer_Type (Typ) and then Etype (Left_Opnd (N)) = Universal_Integer and then Etype (Right_Opnd (N)) = Universal_Integer then Check_For_Visible_Operator (N, B_Typ); end if; -- Replace AND by AND THEN, or OR by OR ELSE, if Short_Circuit_And_Or -- is active and the result type is standard Boolean (do not mess with -- ops that return a nonstandard Boolean type, because something strange -- is going on). -- Note: you might expect this replacement to be done during expansion, -- but that doesn't work, because when the pragma Short_Circuit_And_Or -- is used, no part of the right operand of an "and" or "or" operator -- should be executed if the left operand would short-circuit the -- evaluation of the corresponding "and then" or "or else". If we left -- the replacement to expansion time, then run-time checks associated -- with such operands would be evaluated unconditionally, due to being -- before the condition prior to the rewriting as short-circuit forms -- during expansion. if Short_Circuit_And_Or and then B_Typ = Standard_Boolean and then Nkind_In (N, N_Op_And, N_Op_Or) then -- Mark the corresponding putative SCO operator as truly a logical -- (and short-circuit) operator. if Generate_SCO and then Comes_From_Source (N) then Set_SCO_Logical_Operator (N); end if; if Nkind (N) = N_Op_And then Rewrite (N, Make_And_Then (Sloc (N), Left_Opnd => Relocate_Node (Left_Opnd (N)), Right_Opnd => Relocate_Node (Right_Opnd (N)))); Analyze_And_Resolve (N, B_Typ); -- Case of OR changed to OR ELSE else Rewrite (N, Make_Or_Else (Sloc (N), Left_Opnd => Relocate_Node (Left_Opnd (N)), Right_Opnd => Relocate_Node (Right_Opnd (N)))); Analyze_And_Resolve (N, B_Typ); end if; -- Return now, since analysis of the rewritten ops will take care of -- other reference bookkeeping and expression folding. return; end if; Resolve (Left_Opnd (N), B_Typ); Resolve (Right_Opnd (N), B_Typ); Check_Unset_Reference (Left_Opnd (N)); Check_Unset_Reference (Right_Opnd (N)); Set_Etype (N, B_Typ); Generate_Operator_Reference (N, B_Typ); Eval_Logical_Op (N); -- In SPARK, logical operations AND, OR and XOR for arrays are defined -- only when both operands have same static lower and higher bounds. Of -- course the types have to match, so only check if operands are -- compatible and the node itself has no errors. if Is_Array_Type (B_Typ) and then Nkind (N) in N_Binary_Op then declare Left_Typ : constant Node_Id := Etype (Left_Opnd (N)); Right_Typ : constant Node_Id := Etype (Right_Opnd (N)); begin -- Protect call to Matching_Static_Array_Bounds to avoid costly -- operation if not needed. if Restriction_Check_Required (SPARK_05) and then Base_Type (Left_Typ) = Base_Type (Right_Typ) and then Left_Typ /= Any_Composite -- or Left_Opnd in error and then Right_Typ /= Any_Composite -- or Right_Opnd in error and then not Matching_Static_Array_Bounds (Left_Typ, Right_Typ) then Check_SPARK_05_Restriction ("array types should have matching static bounds", N); end if; end; end if; end Resolve_Logical_Op; --------------------------- -- Resolve_Membership_Op -- --------------------------- -- The context can only be a boolean type, and does not determine the -- arguments. Arguments should be unambiguous, but the preference rule for -- universal types applies. procedure Resolve_Membership_Op (N : Node_Id; Typ : Entity_Id) is pragma Warnings (Off, Typ); L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); T : Entity_Id; procedure Resolve_Set_Membership; -- Analysis has determined a unique type for the left operand. Use it to -- resolve the disjuncts. ---------------------------- -- Resolve_Set_Membership -- ---------------------------- procedure Resolve_Set_Membership is Alt : Node_Id; Ltyp : Entity_Id; begin -- If the left operand is overloaded, find type compatible with not -- overloaded alternative of the right operand. if Is_Overloaded (L) then Ltyp := Empty; Alt := First (Alternatives (N)); while Present (Alt) loop if not Is_Overloaded (Alt) then Ltyp := Intersect_Types (L, Alt); exit; else Next (Alt); end if; end loop; -- Unclear how to resolve expression if all alternatives are also -- overloaded. if No (Ltyp) then Error_Msg_N ("ambiguous expression", N); end if; else Ltyp := Etype (L); end if; Resolve (L, Ltyp); Alt := First (Alternatives (N)); while Present (Alt) loop -- Alternative is an expression, a range -- or a subtype mark. if not Is_Entity_Name (Alt) or else not Is_Type (Entity (Alt)) then Resolve (Alt, Ltyp); end if; Next (Alt); end loop; -- Check for duplicates for discrete case if Is_Discrete_Type (Ltyp) then declare type Ent is record Alt : Node_Id; Val : Uint; end record; Alts : array (0 .. List_Length (Alternatives (N))) of Ent; Nalts : Nat; begin -- Loop checking duplicates. This is quadratic, but giant sets -- are unlikely in this context so it's a reasonable choice. Nalts := 0; Alt := First (Alternatives (N)); while Present (Alt) loop if Is_OK_Static_Expression (Alt) and then (Nkind_In (Alt, N_Integer_Literal, N_Character_Literal) or else Nkind (Alt) in N_Has_Entity) then Nalts := Nalts + 1; Alts (Nalts) := (Alt, Expr_Value (Alt)); for J in 1 .. Nalts - 1 loop if Alts (J).Val = Alts (Nalts).Val then Error_Msg_Sloc := Sloc (Alts (J).Alt); Error_Msg_N ("duplicate of value given#??", Alt); end if; end loop; end if; Alt := Next (Alt); end loop; end; end if; end Resolve_Set_Membership; -- Start of processing for Resolve_Membership_Op begin if L = Error or else R = Error then return; end if; if Present (Alternatives (N)) then Resolve_Set_Membership; goto SM_Exit; elsif not Is_Overloaded (R) and then (Etype (R) = Universal_Integer or else Etype (R) = Universal_Real) and then Is_Overloaded (L) then T := Etype (R); -- Ada 2005 (AI-251): Support the following case: -- type I is interface; -- type T is tagged ... -- function Test (O : I'Class) is -- begin -- return O in T'Class. -- end Test; -- In this case we have nothing else to do. The membership test will be -- done at run time. elsif Ada_Version >= Ada_2005 and then Is_Class_Wide_Type (Etype (L)) and then Is_Interface (Etype (L)) and then Is_Class_Wide_Type (Etype (R)) and then not Is_Interface (Etype (R)) then return; else T := Intersect_Types (L, R); end if; -- If mixed-mode operations are present and operands are all literal, -- the only interpretation involves Duration, which is probably not -- the intention of the programmer. if T = Any_Fixed then T := Unique_Fixed_Point_Type (N); if T = Any_Type then return; end if; end if; Resolve (L, T); Check_Unset_Reference (L); if Nkind (R) = N_Range and then not Is_Scalar_Type (T) then Error_Msg_N ("scalar type required for range", R); end if; if Is_Entity_Name (R) then Freeze_Expression (R); else Resolve (R, T); Check_Unset_Reference (R); end if; -- Here after resolving membership operation <<SM_Exit>> Eval_Membership_Op (N); end Resolve_Membership_Op; ------------------ -- Resolve_Null -- ------------------ procedure Resolve_Null (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); begin -- Handle restriction against anonymous null access values This -- restriction can be turned off using -gnatdj. -- Ada 2005 (AI-231): Remove restriction if Ada_Version < Ada_2005 and then not Debug_Flag_J and then Ekind (Typ) = E_Anonymous_Access_Type and then Comes_From_Source (N) then -- In the common case of a call which uses an explicitly null value -- for an access parameter, give specialized error message. if Nkind (Parent (N)) in N_Subprogram_Call then Error_Msg_N ("null is not allowed as argument for an access parameter", N); -- Standard message for all other cases (are there any?) else Error_Msg_N ("null cannot be of an anonymous access type", N); end if; end if; -- Ada 2005 (AI-231): Generate the null-excluding check in case of -- assignment to a null-excluding object if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (Typ) and then Nkind (Parent (N)) = N_Assignment_Statement then if not Inside_Init_Proc then Insert_Action (Compile_Time_Constraint_Error (N, "(Ada 2005) null not allowed in null-excluding objects??"), Make_Raise_Constraint_Error (Loc, Reason => CE_Access_Check_Failed)); else Insert_Action (N, Make_Raise_Constraint_Error (Loc, Reason => CE_Access_Check_Failed)); end if; end if; -- In a distributed context, null for a remote access to subprogram may -- need to be replaced with a special record aggregate. In this case, -- return after having done the transformation. if (Ekind (Typ) = E_Record_Type or else Is_Remote_Access_To_Subprogram_Type (Typ)) and then Remote_AST_Null_Value (N, Typ) then return; end if; -- The null literal takes its type from the context Set_Etype (N, Typ); end Resolve_Null; ----------------------- -- Resolve_Op_Concat -- ----------------------- procedure Resolve_Op_Concat (N : Node_Id; Typ : Entity_Id) is -- We wish to avoid deep recursion, because concatenations are often -- deeply nested, as in A&B&...&Z. Therefore, we walk down the left -- operands nonrecursively until we find something that is not a simple -- concatenation (A in this case). We resolve that, and then walk back -- up the tree following Parent pointers, calling Resolve_Op_Concat_Rest -- to do the rest of the work at each level. The Parent pointers allow -- us to avoid recursion, and thus avoid running out of memory. See also -- Sem_Ch4.Analyze_Concatenation, where a similar approach is used. NN : Node_Id := N; Op1 : Node_Id; begin -- The following code is equivalent to: -- Resolve_Op_Concat_First (NN, Typ); -- Resolve_Op_Concat_Arg (N, ...); -- Resolve_Op_Concat_Rest (N, Typ); -- where the Resolve_Op_Concat_Arg call recurses back here if the left -- operand is a concatenation. -- Walk down left operands loop Resolve_Op_Concat_First (NN, Typ); Op1 := Left_Opnd (NN); exit when not (Nkind (Op1) = N_Op_Concat and then not Is_Array_Type (Component_Type (Typ)) and then Entity (Op1) = Entity (NN)); NN := Op1; end loop; -- Now (given the above example) NN is A&B and Op1 is A -- First resolve Op1 ... Resolve_Op_Concat_Arg (NN, Op1, Typ, Is_Component_Left_Opnd (NN)); -- ... then walk NN back up until we reach N (where we started), calling -- Resolve_Op_Concat_Rest along the way. loop Resolve_Op_Concat_Rest (NN, Typ); exit when NN = N; NN := Parent (NN); end loop; if Base_Type (Etype (N)) /= Standard_String then Check_SPARK_05_Restriction ("result of concatenation should have type String", N); end if; end Resolve_Op_Concat; --------------------------- -- Resolve_Op_Concat_Arg -- --------------------------- procedure Resolve_Op_Concat_Arg (N : Node_Id; Arg : Node_Id; Typ : Entity_Id; Is_Comp : Boolean) is Btyp : constant Entity_Id := Base_Type (Typ); Ctyp : constant Entity_Id := Component_Type (Typ); begin if In_Instance then if Is_Comp or else (not Is_Overloaded (Arg) and then Etype (Arg) /= Any_Composite and then Covers (Ctyp, Etype (Arg))) then Resolve (Arg, Ctyp); else Resolve (Arg, Btyp); end if; -- If both Array & Array and Array & Component are visible, there is a -- potential ambiguity that must be reported. elsif Has_Compatible_Type (Arg, Ctyp) then if Nkind (Arg) = N_Aggregate and then Is_Composite_Type (Ctyp) then if Is_Private_Type (Ctyp) then Resolve (Arg, Btyp); -- If the operation is user-defined and not overloaded use its -- profile. The operation may be a renaming, in which case it has -- been rewritten, and we want the original profile. elsif not Is_Overloaded (N) and then Comes_From_Source (Entity (Original_Node (N))) and then Ekind (Entity (Original_Node (N))) = E_Function then Resolve (Arg, Etype (Next_Formal (First_Formal (Entity (Original_Node (N)))))); return; -- Otherwise an aggregate may match both the array type and the -- component type. else Error_Msg_N ("ambiguous aggregate must be qualified", Arg); Set_Etype (Arg, Any_Type); end if; else if Is_Overloaded (Arg) and then Has_Compatible_Type (Arg, Typ) and then Etype (Arg) /= Any_Type then declare I : Interp_Index; It : Interp; Func : Entity_Id; begin Get_First_Interp (Arg, I, It); Func := It.Nam; Get_Next_Interp (I, It); -- Special-case the error message when the overloading is -- caused by a function that yields an array and can be -- called without parameters. if It.Nam = Func then Error_Msg_Sloc := Sloc (Func); Error_Msg_N ("ambiguous call to function#", Arg); Error_Msg_NE ("\\interpretation as call yields&", Arg, Typ); Error_Msg_NE ("\\interpretation as indexing of call yields&", Arg, Component_Type (Typ)); else Error_Msg_N ("ambiguous operand for concatenation!", Arg); Get_First_Interp (Arg, I, It); while Present (It.Nam) loop Error_Msg_Sloc := Sloc (It.Nam); if Base_Type (It.Typ) = Btyp or else Base_Type (It.Typ) = Base_Type (Ctyp) then Error_Msg_N -- CODEFIX ("\\possible interpretation#", Arg); end if; Get_Next_Interp (I, It); end loop; end if; end; end if; Resolve (Arg, Component_Type (Typ)); if Nkind (Arg) = N_String_Literal then Set_Etype (Arg, Component_Type (Typ)); end if; if Arg = Left_Opnd (N) then Set_Is_Component_Left_Opnd (N); else Set_Is_Component_Right_Opnd (N); end if; end if; else Resolve (Arg, Btyp); end if; -- Concatenation is restricted in SPARK: each operand must be either a -- string literal, the name of a string constant, a static character or -- string expression, or another concatenation. Arg cannot be a -- concatenation here as callers of Resolve_Op_Concat_Arg call it -- separately on each final operand, past concatenation operations. if Is_Character_Type (Etype (Arg)) then if not Is_OK_Static_Expression (Arg) then Check_SPARK_05_Restriction ("character operand for concatenation should be static", Arg); end if; elsif Is_String_Type (Etype (Arg)) then if not (Nkind_In (Arg, N_Identifier, N_Expanded_Name) and then Is_Constant_Object (Entity (Arg))) and then not Is_OK_Static_Expression (Arg) then Check_SPARK_05_Restriction ("string operand for concatenation should be static", Arg); end if; -- Do not issue error on an operand that is neither a character nor a -- string, as the error is issued in Resolve_Op_Concat. else null; end if; Check_Unset_Reference (Arg); end Resolve_Op_Concat_Arg; ----------------------------- -- Resolve_Op_Concat_First -- ----------------------------- procedure Resolve_Op_Concat_First (N : Node_Id; Typ : Entity_Id) is Btyp : constant Entity_Id := Base_Type (Typ); Op1 : constant Node_Id := Left_Opnd (N); Op2 : constant Node_Id := Right_Opnd (N); begin -- The parser folds an enormous sequence of concatenations of string -- literals into "" & "...", where the Is_Folded_In_Parser flag is set -- in the right operand. If the expression resolves to a predefined "&" -- operator, all is well. Otherwise, the parser's folding is wrong, so -- we give an error. See P_Simple_Expression in Par.Ch4. if Nkind (Op2) = N_String_Literal and then Is_Folded_In_Parser (Op2) and then Ekind (Entity (N)) = E_Function then pragma Assert (Nkind (Op1) = N_String_Literal -- should be "" and then String_Length (Strval (Op1)) = 0); Error_Msg_N ("too many user-defined concatenations", N); return; end if; Set_Etype (N, Btyp); if Is_Limited_Composite (Btyp) then Error_Msg_N ("concatenation not available for limited array", N); Explain_Limited_Type (Btyp, N); end if; end Resolve_Op_Concat_First; ---------------------------- -- Resolve_Op_Concat_Rest -- ---------------------------- procedure Resolve_Op_Concat_Rest (N : Node_Id; Typ : Entity_Id) is Op1 : constant Node_Id := Left_Opnd (N); Op2 : constant Node_Id := Right_Opnd (N); begin Resolve_Op_Concat_Arg (N, Op2, Typ, Is_Component_Right_Opnd (N)); Generate_Operator_Reference (N, Typ); if Is_String_Type (Typ) then Eval_Concatenation (N); end if; -- If this is not a static concatenation, but the result is a string -- type (and not an array of strings) ensure that static string operands -- have their subtypes properly constructed. if Nkind (N) /= N_String_Literal and then Is_Character_Type (Component_Type (Typ)) then Set_String_Literal_Subtype (Op1, Typ); Set_String_Literal_Subtype (Op2, Typ); end if; end Resolve_Op_Concat_Rest; ---------------------- -- Resolve_Op_Expon -- ---------------------- procedure Resolve_Op_Expon (N : Node_Id; Typ : Entity_Id) is B_Typ : constant Entity_Id := Base_Type (Typ); begin -- Catch attempts to do fixed-point exponentiation with universal -- operands, which is a case where the illegality is not caught during -- normal operator analysis. This is not done in preanalysis mode -- since the tree is not fully decorated during preanalysis. if Full_Analysis then if Is_Fixed_Point_Type (Typ) and then Comes_From_Source (N) then Error_Msg_N ("exponentiation not available for fixed point", N); return; elsif Nkind (Parent (N)) in N_Op and then Is_Fixed_Point_Type (Etype (Parent (N))) and then Etype (N) = Universal_Real and then Comes_From_Source (N) then Error_Msg_N ("exponentiation not available for fixed point", N); return; end if; end if; if Comes_From_Source (N) and then Ekind (Entity (N)) = E_Function and then Is_Imported (Entity (N)) and then Is_Intrinsic_Subprogram (Entity (N)) then Resolve_Intrinsic_Operator (N, Typ); return; end if; if Etype (Left_Opnd (N)) = Universal_Integer or else Etype (Left_Opnd (N)) = Universal_Real then Check_For_Visible_Operator (N, B_Typ); end if; -- We do the resolution using the base type, because intermediate values -- in expressions are always of the base type, not a subtype of it. Resolve (Left_Opnd (N), B_Typ); Resolve (Right_Opnd (N), Standard_Integer); -- For integer types, right argument must be in Natural range if Is_Integer_Type (Typ) then Apply_Scalar_Range_Check (Right_Opnd (N), Standard_Natural); end if; Check_Unset_Reference (Left_Opnd (N)); Check_Unset_Reference (Right_Opnd (N)); Set_Etype (N, B_Typ); Generate_Operator_Reference (N, B_Typ); Analyze_Dimension (N); if Ada_Version >= Ada_2012 and then Has_Dimension_System (B_Typ) then -- Evaluate the exponentiation operator for dimensioned type Eval_Op_Expon_For_Dimensioned_Type (N, B_Typ); else Eval_Op_Expon (N); end if; -- Set overflow checking bit. Much cleverer code needed here eventually -- and perhaps the Resolve routines should be separated for the various -- arithmetic operations, since they will need different processing. ??? if Nkind (N) in N_Op then if not Overflow_Checks_Suppressed (Etype (N)) then Enable_Overflow_Check (N); end if; end if; end Resolve_Op_Expon; -------------------- -- Resolve_Op_Not -- -------------------- procedure Resolve_Op_Not (N : Node_Id; Typ : Entity_Id) is B_Typ : Entity_Id; function Parent_Is_Boolean return Boolean; -- This function determines if the parent node is a boolean operator or -- operation (comparison op, membership test, or short circuit form) and -- the not in question is the left operand of this operation. Note that -- if the not is in parens, then false is returned. ----------------------- -- Parent_Is_Boolean -- ----------------------- function Parent_Is_Boolean return Boolean is begin if Paren_Count (N) /= 0 then return False; else case Nkind (Parent (N)) is when N_And_Then | N_In | N_Not_In | N_Op_And | N_Op_Eq | N_Op_Ge | N_Op_Gt | N_Op_Le | N_Op_Lt | N_Op_Ne | N_Op_Or | N_Op_Xor | N_Or_Else => return Left_Opnd (Parent (N)) = N; when others => return False; end case; end if; end Parent_Is_Boolean; -- Start of processing for Resolve_Op_Not begin -- Predefined operations on scalar types yield the base type. On the -- other hand, logical operations on arrays yield the type of the -- arguments (and the context). if Is_Array_Type (Typ) then B_Typ := Typ; else B_Typ := Base_Type (Typ); end if; -- Straightforward case of incorrect arguments if not Valid_Boolean_Arg (Typ) then Error_Msg_N ("invalid operand type for operator&", N); Set_Etype (N, Any_Type); return; -- Special case of probable missing parens elsif Typ = Universal_Integer or else Typ = Any_Modular then if Parent_Is_Boolean then Error_Msg_N ("operand of not must be enclosed in parentheses", Right_Opnd (N)); else Error_Msg_N ("no modular type available in this context", N); end if; Set_Etype (N, Any_Type); return; -- OK resolution of NOT else -- Warn if non-boolean types involved. This is a case like not a < b -- where a and b are modular, where we will get (not a) < b and most -- likely not (a < b) was intended. if Warn_On_Questionable_Missing_Parens and then not Is_Boolean_Type (Typ) and then Parent_Is_Boolean then Error_Msg_N ("?q?not expression should be parenthesized here!", N); end if; -- Warn on double negation if checking redundant constructs if Warn_On_Redundant_Constructs and then Comes_From_Source (N) and then Comes_From_Source (Right_Opnd (N)) and then Root_Type (Typ) = Standard_Boolean and then Nkind (Right_Opnd (N)) = N_Op_Not then Error_Msg_N ("redundant double negation?r?", N); end if; -- Complete resolution and evaluation of NOT Resolve (Right_Opnd (N), B_Typ); Check_Unset_Reference (Right_Opnd (N)); Set_Etype (N, B_Typ); Generate_Operator_Reference (N, B_Typ); Eval_Op_Not (N); end if; end Resolve_Op_Not; ----------------------------- -- Resolve_Operator_Symbol -- ----------------------------- -- Nothing to be done, all resolved already procedure Resolve_Operator_Symbol (N : Node_Id; Typ : Entity_Id) is pragma Warnings (Off, N); pragma Warnings (Off, Typ); begin null; end Resolve_Operator_Symbol; ---------------------------------- -- Resolve_Qualified_Expression -- ---------------------------------- procedure Resolve_Qualified_Expression (N : Node_Id; Typ : Entity_Id) is pragma Warnings (Off, Typ); Target_Typ : constant Entity_Id := Entity (Subtype_Mark (N)); Expr : constant Node_Id := Expression (N); begin Resolve (Expr, Target_Typ); -- Protect call to Matching_Static_Array_Bounds to avoid costly -- operation if not needed. if Restriction_Check_Required (SPARK_05) and then Is_Array_Type (Target_Typ) and then Is_Array_Type (Etype (Expr)) and then Etype (Expr) /= Any_Composite -- or else Expr in error and then not Matching_Static_Array_Bounds (Target_Typ, Etype (Expr)) then Check_SPARK_05_Restriction ("array types should have matching static bounds", N); end if; -- A qualified expression requires an exact match of the type, class- -- wide matching is not allowed. However, if the qualifying type is -- specific and the expression has a class-wide type, it may still be -- okay, since it can be the result of the expansion of a call to a -- dispatching function, so we also have to check class-wideness of the -- type of the expression's original node. if (Is_Class_Wide_Type (Target_Typ) or else (Is_Class_Wide_Type (Etype (Expr)) and then Is_Class_Wide_Type (Etype (Original_Node (Expr))))) and then Base_Type (Etype (Expr)) /= Base_Type (Target_Typ) then Wrong_Type (Expr, Target_Typ); end if; -- If the target type is unconstrained, then we reset the type of the -- result from the type of the expression. For other cases, the actual -- subtype of the expression is the target type. if Is_Composite_Type (Target_Typ) and then not Is_Constrained (Target_Typ) then Set_Etype (N, Etype (Expr)); end if; Analyze_Dimension (N); Eval_Qualified_Expression (N); -- If we still have a qualified expression after the static evaluation, -- then apply a scalar range check if needed. The reason that we do this -- after the Eval call is that otherwise, the application of the range -- check may convert an illegal static expression and result in warning -- rather than giving an error (e.g Integer'(Integer'Last + 1)). if Nkind (N) = N_Qualified_Expression and then Is_Scalar_Type (Typ) then Apply_Scalar_Range_Check (Expr, Typ); end if; -- Finally, check whether a predicate applies to the target type. This -- comes from AI12-0100. As for type conversions, check the enclosing -- context to prevent an infinite expansion. if Has_Predicates (Target_Typ) then if Nkind (Parent (N)) = N_Function_Call and then Present (Name (Parent (N))) and then (Is_Predicate_Function (Entity (Name (Parent (N)))) or else Is_Predicate_Function_M (Entity (Name (Parent (N))))) then null; -- In the case of a qualified expression in an allocator, the check -- is applied when expanding the allocator, so avoid redundant check. elsif Nkind (N) = N_Qualified_Expression and then Nkind (Parent (N)) /= N_Allocator then Apply_Predicate_Check (N, Target_Typ); end if; end if; end Resolve_Qualified_Expression; ------------------------------ -- Resolve_Raise_Expression -- ------------------------------ procedure Resolve_Raise_Expression (N : Node_Id; Typ : Entity_Id) is begin if Typ = Raise_Type then Error_Msg_N ("cannot find unique type for raise expression", N); Set_Etype (N, Any_Type); else Set_Etype (N, Typ); end if; end Resolve_Raise_Expression; ------------------- -- Resolve_Range -- ------------------- procedure Resolve_Range (N : Node_Id; Typ : Entity_Id) is L : constant Node_Id := Low_Bound (N); H : constant Node_Id := High_Bound (N); function First_Last_Ref return Boolean; -- Returns True if N is of the form X'First .. X'Last where X is the -- same entity for both attributes. -------------------- -- First_Last_Ref -- -------------------- function First_Last_Ref return Boolean is Lorig : constant Node_Id := Original_Node (L); Horig : constant Node_Id := Original_Node (H); begin if Nkind (Lorig) = N_Attribute_Reference and then Nkind (Horig) = N_Attribute_Reference and then Attribute_Name (Lorig) = Name_First and then Attribute_Name (Horig) = Name_Last then declare PL : constant Node_Id := Prefix (Lorig); PH : constant Node_Id := Prefix (Horig); begin if Is_Entity_Name (PL) and then Is_Entity_Name (PH) and then Entity (PL) = Entity (PH) then return True; end if; end; end if; return False; end First_Last_Ref; -- Start of processing for Resolve_Range begin Set_Etype (N, Typ); -- The lower bound should be in Typ. The higher bound can be in Typ's -- base type if the range is null. It may still be invalid if it is -- higher than the lower bound. This is checked later in the context in -- which the range appears. Resolve (L, Typ); Resolve (H, Base_Type (Typ)); -- Check for inappropriate range on unordered enumeration type if Bad_Unordered_Enumeration_Reference (N, Typ) -- Exclude X'First .. X'Last if X is the same entity for both and then not First_Last_Ref then Error_Msg_Sloc := Sloc (Typ); Error_Msg_NE ("subrange of unordered enumeration type& declared#?U?", N, Typ); end if; Check_Unset_Reference (L); Check_Unset_Reference (H); -- We have to check the bounds for being within the base range as -- required for a non-static context. Normally this is automatic and -- done as part of evaluating expressions, but the N_Range node is an -- exception, since in GNAT we consider this node to be a subexpression, -- even though in Ada it is not. The circuit in Sem_Eval could check for -- this, but that would put the test on the main evaluation path for -- expressions. Check_Non_Static_Context (L); Check_Non_Static_Context (H); -- Check for an ambiguous range over character literals. This will -- happen with a membership test involving only literals. if Typ = Any_Character then Ambiguous_Character (L); Set_Etype (N, Any_Type); return; end if; -- If bounds are static, constant-fold them, so size computations are -- identical between front-end and back-end. Do not perform this -- transformation while analyzing generic units, as type information -- would be lost when reanalyzing the constant node in the instance. if Is_Discrete_Type (Typ) and then Expander_Active then if Is_OK_Static_Expression (L) then Fold_Uint (L, Expr_Value (L), Is_OK_Static_Expression (L)); end if; if Is_OK_Static_Expression (H) then Fold_Uint (H, Expr_Value (H), Is_OK_Static_Expression (H)); end if; end if; end Resolve_Range; -------------------------- -- Resolve_Real_Literal -- -------------------------- procedure Resolve_Real_Literal (N : Node_Id; Typ : Entity_Id) is Actual_Typ : constant Entity_Id := Etype (N); begin -- Special processing for fixed-point literals to make sure that the -- value is an exact multiple of small where this is required. We skip -- this for the universal real case, and also for generic types. if Is_Fixed_Point_Type (Typ) and then Typ /= Universal_Fixed and then Typ /= Any_Fixed and then not Is_Generic_Type (Typ) then declare Val : constant Ureal := Realval (N); Cintr : constant Ureal := Val / Small_Value (Typ); Cint : constant Uint := UR_Trunc (Cintr); Den : constant Uint := Norm_Den (Cintr); Stat : Boolean; begin -- Case of literal is not an exact multiple of the Small if Den /= 1 then -- For a source program literal for a decimal fixed-point type, -- this is statically illegal (RM 4.9(36)). if Is_Decimal_Fixed_Point_Type (Typ) and then Actual_Typ = Universal_Real and then Comes_From_Source (N) then Error_Msg_N ("value has extraneous low order digits", N); end if; -- Generate a warning if literal from source if Is_OK_Static_Expression (N) and then Warn_On_Bad_Fixed_Value then Error_Msg_N ("?b?static fixed-point value is not a multiple of Small!", N); end if; -- Replace literal by a value that is the exact representation -- of a value of the type, i.e. a multiple of the small value, -- by truncation, since Machine_Rounds is false for all GNAT -- fixed-point types (RM 4.9(38)). Stat := Is_OK_Static_Expression (N); Rewrite (N, Make_Real_Literal (Sloc (N), Realval => Small_Value (Typ) * Cint)); Set_Is_Static_Expression (N, Stat); end if; -- In all cases, set the corresponding integer field Set_Corresponding_Integer_Value (N, Cint); end; end if; -- Now replace the actual type by the expected type as usual Set_Etype (N, Typ); Eval_Real_Literal (N); end Resolve_Real_Literal; ----------------------- -- Resolve_Reference -- ----------------------- procedure Resolve_Reference (N : Node_Id; Typ : Entity_Id) is P : constant Node_Id := Prefix (N); begin -- Replace general access with specific type if Ekind (Etype (N)) = E_Allocator_Type then Set_Etype (N, Base_Type (Typ)); end if; Resolve (P, Designated_Type (Etype (N))); -- If we are taking the reference of a volatile entity, then treat it as -- a potential modification of this entity. This is too conservative, -- but necessary because remove side effects can cause transformations -- of normal assignments into reference sequences that otherwise fail to -- notice the modification. if Is_Entity_Name (P) and then Treat_As_Volatile (Entity (P)) then Note_Possible_Modification (P, Sure => False); end if; end Resolve_Reference; -------------------------------- -- Resolve_Selected_Component -- -------------------------------- procedure Resolve_Selected_Component (N : Node_Id; Typ : Entity_Id) is Comp : Entity_Id; Comp1 : Entity_Id := Empty; -- prevent junk warning P : constant Node_Id := Prefix (N); S : constant Node_Id := Selector_Name (N); T : Entity_Id := Etype (P); I : Interp_Index; I1 : Interp_Index := 0; -- prevent junk warning It : Interp; It1 : Interp; Found : Boolean; function Init_Component return Boolean; -- Check whether this is the initialization of a component within an -- init proc (by assignment or call to another init proc). If true, -- there is no need for a discriminant check. -------------------- -- Init_Component -- -------------------- function Init_Component return Boolean is begin return Inside_Init_Proc and then Nkind (Prefix (N)) = N_Identifier and then Chars (Prefix (N)) = Name_uInit and then Nkind (Parent (Parent (N))) = N_Case_Statement_Alternative; end Init_Component; -- Start of processing for Resolve_Selected_Component begin if Is_Overloaded (P) then -- Use the context type to select the prefix that has a selector -- of the correct name and type. Found := False; Get_First_Interp (P, I, It); Search : while Present (It.Typ) loop if Is_Access_Type (It.Typ) then T := Designated_Type (It.Typ); else T := It.Typ; end if; -- Locate selected component. For a private prefix the selector -- can denote a discriminant. if Is_Record_Type (T) or else Is_Private_Type (T) then -- The visible components of a class-wide type are those of -- the root type. if Is_Class_Wide_Type (T) then T := Etype (T); end if; Comp := First_Entity (T); while Present (Comp) loop if Chars (Comp) = Chars (S) and then Covers (Typ, Etype (Comp)) then if not Found then Found := True; I1 := I; It1 := It; Comp1 := Comp; else It := Disambiguate (P, I1, I, Any_Type); if It = No_Interp then Error_Msg_N ("ambiguous prefix for selected component", N); Set_Etype (N, Typ); return; else It1 := It; -- There may be an implicit dereference. Retrieve -- designated record type. if Is_Access_Type (It1.Typ) then T := Designated_Type (It1.Typ); else T := It1.Typ; end if; if Scope (Comp1) /= T then -- Resolution chooses the new interpretation. -- Find the component with the right name. Comp1 := First_Entity (T); while Present (Comp1) and then Chars (Comp1) /= Chars (S) loop Comp1 := Next_Entity (Comp1); end loop; end if; exit Search; end if; end if; end if; Comp := Next_Entity (Comp); end loop; end if; Get_Next_Interp (I, It); end loop Search; -- There must be a legal interpretation at this point pragma Assert (Found); Resolve (P, It1.Typ); Set_Etype (N, Typ); Set_Entity_With_Checks (S, Comp1); else -- Resolve prefix with its type Resolve (P, T); end if; -- Generate cross-reference. We needed to wait until full overloading -- resolution was complete to do this, since otherwise we can't tell if -- we are an lvalue or not. if May_Be_Lvalue (N) then Generate_Reference (Entity (S), S, 'm'); else Generate_Reference (Entity (S), S, 'r'); end if; -- If prefix is an access type, the node will be transformed into an -- explicit dereference during expansion. The type of the node is the -- designated type of that of the prefix. if Is_Access_Type (Etype (P)) then T := Designated_Type (Etype (P)); Check_Fully_Declared_Prefix (T, P); else T := Etype (P); end if; -- Set flag for expander if discriminant check required on a component -- appearing within a variant. if Has_Discriminants (T) and then Ekind (Entity (S)) = E_Component and then Present (Original_Record_Component (Entity (S))) and then Ekind (Original_Record_Component (Entity (S))) = E_Component and then Is_Declared_Within_Variant (Original_Record_Component (Entity (S))) and then not Discriminant_Checks_Suppressed (T) and then not Init_Component then Set_Do_Discriminant_Check (N); end if; if Ekind (Entity (S)) = E_Void then Error_Msg_N ("premature use of component", S); end if; -- If the prefix is a record conversion, this may be a renamed -- discriminant whose bounds differ from those of the original -- one, so we must ensure that a range check is performed. if Nkind (P) = N_Type_Conversion and then Ekind (Entity (S)) = E_Discriminant and then Is_Discrete_Type (Typ) then Set_Etype (N, Base_Type (Typ)); end if; -- Note: No Eval processing is required, because the prefix is of a -- record type, or protected type, and neither can possibly be static. -- If the record type is atomic, and the component is non-atomic, then -- this is worth a warning, since we have a situation where the access -- to the component may cause extra read/writes of the atomic array -- object, or partial word accesses, both of which may be unexpected. if Nkind (N) = N_Selected_Component and then Is_Atomic_Ref_With_Address (N) and then not Is_Atomic (Entity (S)) and then not Is_Atomic (Etype (Entity (S))) then Error_Msg_N ("??access to non-atomic component of atomic record", Prefix (N)); Error_Msg_N ("\??may cause unexpected accesses to atomic object", Prefix (N)); end if; Analyze_Dimension (N); end Resolve_Selected_Component; ------------------- -- Resolve_Shift -- ------------------- procedure Resolve_Shift (N : Node_Id; Typ : Entity_Id) is B_Typ : constant Entity_Id := Base_Type (Typ); L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); begin -- We do the resolution using the base type, because intermediate values -- in expressions always are of the base type, not a subtype of it. Resolve (L, B_Typ); Resolve (R, Standard_Natural); Check_Unset_Reference (L); Check_Unset_Reference (R); Set_Etype (N, B_Typ); Generate_Operator_Reference (N, B_Typ); Eval_Shift (N); end Resolve_Shift; --------------------------- -- Resolve_Short_Circuit -- --------------------------- procedure Resolve_Short_Circuit (N : Node_Id; Typ : Entity_Id) is B_Typ : constant Entity_Id := Base_Type (Typ); L : constant Node_Id := Left_Opnd (N); R : constant Node_Id := Right_Opnd (N); begin -- Ensure all actions associated with the left operand (e.g. -- finalization of transient objects) are fully evaluated locally within -- an expression with actions. This is particularly helpful for coverage -- analysis. However this should not happen in generics or if option -- Minimize_Expression_With_Actions is set. if Expander_Active and not Minimize_Expression_With_Actions then declare Reloc_L : constant Node_Id := Relocate_Node (L); begin Save_Interps (Old_N => L, New_N => Reloc_L); Rewrite (L, Make_Expression_With_Actions (Sloc (L), Actions => New_List, Expression => Reloc_L)); -- Set Comes_From_Source on L to preserve warnings for unset -- reference. Set_Comes_From_Source (L, Comes_From_Source (Reloc_L)); end; end if; Resolve (L, B_Typ); Resolve (R, B_Typ); -- Check for issuing warning for always False assert/check, this happens -- when assertions are turned off, in which case the pragma Assert/Check -- was transformed into: -- if False and then <condition> then ... -- and we detect this pattern if Warn_On_Assertion_Failure and then Is_Entity_Name (R) and then Entity (R) = Standard_False and then Nkind (Parent (N)) = N_If_Statement and then Nkind (N) = N_And_Then and then Is_Entity_Name (L) and then Entity (L) = Standard_False then declare Orig : constant Node_Id := Original_Node (Parent (N)); begin -- Special handling of Asssert pragma if Nkind (Orig) = N_Pragma and then Pragma_Name (Orig) = Name_Assert then declare Expr : constant Node_Id := Original_Node (Expression (First (Pragma_Argument_Associations (Orig)))); begin -- Don't warn if original condition is explicit False, -- since obviously the failure is expected in this case. if Is_Entity_Name (Expr) and then Entity (Expr) = Standard_False then null; -- Issue warning. We do not want the deletion of the -- IF/AND-THEN to take this message with it. We achieve this -- by making sure that the expanded code points to the Sloc -- of the expression, not the original pragma. else -- Note: Use Error_Msg_F here rather than Error_Msg_N. -- The source location of the expression is not usually -- the best choice here. For example, it gets located on -- the last AND keyword in a chain of boolean expressiond -- AND'ed together. It is best to put the message on the -- first character of the assertion, which is the effect -- of the First_Node call here. Error_Msg_F ("?A?assertion would fail at run time!", Expression (First (Pragma_Argument_Associations (Orig)))); end if; end; -- Similar processing for Check pragma elsif Nkind (Orig) = N_Pragma and then Pragma_Name (Orig) = Name_Check then -- Don't want to warn if original condition is explicit False declare Expr : constant Node_Id := Original_Node (Expression (Next (First (Pragma_Argument_Associations (Orig))))); begin if Is_Entity_Name (Expr) and then Entity (Expr) = Standard_False then null; -- Post warning else -- Again use Error_Msg_F rather than Error_Msg_N, see -- comment above for an explanation of why we do this. Error_Msg_F ("?A?check would fail at run time!", Expression (Last (Pragma_Argument_Associations (Orig)))); end if; end; end if; end; end if; -- Continue with processing of short circuit Check_Unset_Reference (L); Check_Unset_Reference (R); Set_Etype (N, B_Typ); Eval_Short_Circuit (N); end Resolve_Short_Circuit; ------------------- -- Resolve_Slice -- ------------------- procedure Resolve_Slice (N : Node_Id; Typ : Entity_Id) is Drange : constant Node_Id := Discrete_Range (N); Name : constant Node_Id := Prefix (N); Array_Type : Entity_Id := Empty; Dexpr : Node_Id := Empty; Index_Type : Entity_Id; begin if Is_Overloaded (Name) then -- Use the context type to select the prefix that yields the correct -- array type. declare I : Interp_Index; I1 : Interp_Index := 0; It : Interp; P : constant Node_Id := Prefix (N); Found : Boolean := False; begin Get_First_Interp (P, I, It); while Present (It.Typ) loop if (Is_Array_Type (It.Typ) and then Covers (Typ, It.Typ)) or else (Is_Access_Type (It.Typ) and then Is_Array_Type (Designated_Type (It.Typ)) and then Covers (Typ, Designated_Type (It.Typ))) then if Found then It := Disambiguate (P, I1, I, Any_Type); if It = No_Interp then Error_Msg_N ("ambiguous prefix for slicing", N); Set_Etype (N, Typ); return; else Found := True; Array_Type := It.Typ; I1 := I; end if; else Found := True; Array_Type := It.Typ; I1 := I; end if; end if; Get_Next_Interp (I, It); end loop; end; else Array_Type := Etype (Name); end if; Resolve (Name, Array_Type); if Is_Access_Type (Array_Type) then Apply_Access_Check (N); Array_Type := Designated_Type (Array_Type); -- If the prefix is an access to an unconstrained array, we must use -- the actual subtype of the object to perform the index checks. The -- object denoted by the prefix is implicit in the node, so we build -- an explicit representation for it in order to compute the actual -- subtype. if not Is_Constrained (Array_Type) then Remove_Side_Effects (Prefix (N)); declare Obj : constant Node_Id := Make_Explicit_Dereference (Sloc (N), Prefix => New_Copy_Tree (Prefix (N))); begin Set_Etype (Obj, Array_Type); Set_Parent (Obj, Parent (N)); Array_Type := Get_Actual_Subtype (Obj); end; end if; elsif Is_Entity_Name (Name) or else Nkind (Name) = N_Explicit_Dereference or else (Nkind (Name) = N_Function_Call and then not Is_Constrained (Etype (Name))) then Array_Type := Get_Actual_Subtype (Name); -- If the name is a selected component that depends on discriminants, -- build an actual subtype for it. This can happen only when the name -- itself is overloaded; otherwise the actual subtype is created when -- the selected component is analyzed. elsif Nkind (Name) = N_Selected_Component and then Full_Analysis and then Depends_On_Discriminant (First_Index (Array_Type)) then declare Act_Decl : constant Node_Id := Build_Actual_Subtype_Of_Component (Array_Type, Name); begin Insert_Action (N, Act_Decl); Array_Type := Defining_Identifier (Act_Decl); end; -- Maybe this should just be "else", instead of checking for the -- specific case of slice??? This is needed for the case where the -- prefix is an Image attribute, which gets expanded to a slice, and so -- has a constrained subtype which we want to use for the slice range -- check applied below (the range check won't get done if the -- unconstrained subtype of the 'Image is used). elsif Nkind (Name) = N_Slice then Array_Type := Etype (Name); end if; -- Obtain the type of the array index if Ekind (Array_Type) = E_String_Literal_Subtype then Index_Type := Etype (String_Literal_Low_Bound (Array_Type)); else Index_Type := Etype (First_Index (Array_Type)); end if; -- If name was overloaded, set slice type correctly now Set_Etype (N, Array_Type); -- Handle the generation of a range check that compares the array index -- against the discrete_range. The check is not applied to internally -- built nodes associated with the expansion of dispatch tables. Check -- that Ada.Tags has already been loaded to avoid extra dependencies on -- the unit. if Tagged_Type_Expansion and then RTU_Loaded (Ada_Tags) and then Nkind (Prefix (N)) = N_Selected_Component and then Present (Entity (Selector_Name (Prefix (N)))) and then Entity (Selector_Name (Prefix (N))) = RTE_Record_Component (RE_Prims_Ptr) then null; -- The discrete_range is specified by a subtype indication. Create a -- shallow copy and inherit the type, parent and source location from -- the discrete_range. This ensures that the range check is inserted -- relative to the slice and that the runtime exception points to the -- proper construct. elsif Is_Entity_Name (Drange) then Dexpr := New_Copy (Scalar_Range (Entity (Drange))); Set_Etype (Dexpr, Etype (Drange)); Set_Parent (Dexpr, Parent (Drange)); Set_Sloc (Dexpr, Sloc (Drange)); -- The discrete_range is a regular range. Resolve the bounds and remove -- their side effects. else Resolve (Drange, Base_Type (Index_Type)); if Nkind (Drange) = N_Range then Force_Evaluation (Low_Bound (Drange)); Force_Evaluation (High_Bound (Drange)); Dexpr := Drange; end if; end if; if Present (Dexpr) then Apply_Range_Check (Dexpr, Index_Type); end if; Set_Slice_Subtype (N); -- Check bad use of type with predicates declare Subt : Entity_Id; begin if Nkind (Drange) = N_Subtype_Indication and then Has_Predicates (Entity (Subtype_Mark (Drange))) then Subt := Entity (Subtype_Mark (Drange)); else Subt := Etype (Drange); end if; if Has_Predicates (Subt) then Bad_Predicated_Subtype_Use ("subtype& has predicate, not allowed in slice", Drange, Subt); end if; end; -- Otherwise here is where we check suspicious indexes if Nkind (Drange) = N_Range then Warn_On_Suspicious_Index (Name, Low_Bound (Drange)); Warn_On_Suspicious_Index (Name, High_Bound (Drange)); end if; Analyze_Dimension (N); Eval_Slice (N); end Resolve_Slice; ---------------------------- -- Resolve_String_Literal -- ---------------------------- procedure Resolve_String_Literal (N : Node_Id; Typ : Entity_Id) is C_Typ : constant Entity_Id := Component_Type (Typ); R_Typ : constant Entity_Id := Root_Type (C_Typ); Loc : constant Source_Ptr := Sloc (N); Str : constant String_Id := Strval (N); Strlen : constant Nat := String_Length (Str); Subtype_Id : Entity_Id; Need_Check : Boolean; begin -- For a string appearing in a concatenation, defer creation of the -- string_literal_subtype until the end of the resolution of the -- concatenation, because the literal may be constant-folded away. This -- is a useful optimization for long concatenation expressions. -- If the string is an aggregate built for a single character (which -- happens in a non-static context) or a is null string to which special -- checks may apply, we build the subtype. Wide strings must also get a -- string subtype if they come from a one character aggregate. Strings -- generated by attributes might be static, but it is often hard to -- determine whether the enclosing context is static, so we generate -- subtypes for them as well, thus losing some rarer optimizations ??? -- Same for strings that come from a static conversion. Need_Check := (Strlen = 0 and then Typ /= Standard_String) or else Nkind (Parent (N)) /= N_Op_Concat or else (N /= Left_Opnd (Parent (N)) and then N /= Right_Opnd (Parent (N))) or else ((Typ = Standard_Wide_String or else Typ = Standard_Wide_Wide_String) and then Nkind (Original_Node (N)) /= N_String_Literal); -- If the resolving type is itself a string literal subtype, we can just -- reuse it, since there is no point in creating another. if Ekind (Typ) = E_String_Literal_Subtype then Subtype_Id := Typ; elsif Nkind (Parent (N)) = N_Op_Concat and then not Need_Check and then not Nkind_In (Original_Node (N), N_Character_Literal, N_Attribute_Reference, N_Qualified_Expression, N_Type_Conversion) then Subtype_Id := Typ; -- Do not generate a string literal subtype for the default expression -- of a formal parameter in GNATprove mode. This is because the string -- subtype is associated with the freezing actions of the subprogram, -- however freezing is disabled in GNATprove mode and as a result the -- subtype is unavailable. elsif GNATprove_Mode and then Nkind (Parent (N)) = N_Parameter_Specification then Subtype_Id := Typ; -- Otherwise we must create a string literal subtype. Note that the -- whole idea of string literal subtypes is simply to avoid the need -- for building a full fledged array subtype for each literal. else Set_String_Literal_Subtype (N, Typ); Subtype_Id := Etype (N); end if; if Nkind (Parent (N)) /= N_Op_Concat or else Need_Check then Set_Etype (N, Subtype_Id); Eval_String_Literal (N); end if; if Is_Limited_Composite (Typ) or else Is_Private_Composite (Typ) then Error_Msg_N ("string literal not available for private array", N); Set_Etype (N, Any_Type); return; end if; -- The validity of a null string has been checked in the call to -- Eval_String_Literal. if Strlen = 0 then return; -- Always accept string literal with component type Any_Character, which -- occurs in error situations and in comparisons of literals, both of -- which should accept all literals. elsif R_Typ = Any_Character then return; -- If the type is bit-packed, then we always transform the string -- literal into a full fledged aggregate. elsif Is_Bit_Packed_Array (Typ) then null; -- Deal with cases of Wide_Wide_String, Wide_String, and String else -- For Standard.Wide_Wide_String, or any other type whose component -- type is Standard.Wide_Wide_Character, we know that all the -- characters in the string must be acceptable, since the parser -- accepted the characters as valid character literals. if R_Typ = Standard_Wide_Wide_Character then null; -- For the case of Standard.String, or any other type whose component -- type is Standard.Character, we must make sure that there are no -- wide characters in the string, i.e. that it is entirely composed -- of characters in range of type Character. -- If the string literal is the result of a static concatenation, the -- test has already been performed on the components, and need not be -- repeated. elsif R_Typ = Standard_Character and then Nkind (Original_Node (N)) /= N_Op_Concat then for J in 1 .. Strlen loop if not In_Character_Range (Get_String_Char (Str, J)) then -- If we are out of range, post error. This is one of the -- very few places that we place the flag in the middle of -- a token, right under the offending wide character. Not -- quite clear if this is right wrt wide character encoding -- sequences, but it's only an error message. Error_Msg ("literal out of range of type Standard.Character", Source_Ptr (Int (Loc) + J)); return; end if; end loop; -- For the case of Standard.Wide_String, or any other type whose -- component type is Standard.Wide_Character, we must make sure that -- there are no wide characters in the string, i.e. that it is -- entirely composed of characters in range of type Wide_Character. -- If the string literal is the result of a static concatenation, -- the test has already been performed on the components, and need -- not be repeated. elsif R_Typ = Standard_Wide_Character and then Nkind (Original_Node (N)) /= N_Op_Concat then for J in 1 .. Strlen loop if not In_Wide_Character_Range (Get_String_Char (Str, J)) then -- If we are out of range, post error. This is one of the -- very few places that we place the flag in the middle of -- a token, right under the offending wide character. -- This is not quite right, because characters in general -- will take more than one character position ??? Error_Msg ("literal out of range of type Standard.Wide_Character", Source_Ptr (Int (Loc) + J)); return; end if; end loop; -- If the root type is not a standard character, then we will convert -- the string into an aggregate and will let the aggregate code do -- the checking. Standard Wide_Wide_Character is also OK here. else null; end if; -- See if the component type of the array corresponding to the string -- has compile time known bounds. If yes we can directly check -- whether the evaluation of the string will raise constraint error. -- Otherwise we need to transform the string literal into the -- corresponding character aggregate and let the aggregate code do -- the checking. if Is_Standard_Character_Type (R_Typ) then -- Check for the case of full range, where we are definitely OK if Component_Type (Typ) = Base_Type (Component_Type (Typ)) then return; end if; -- Here the range is not the complete base type range, so check declare Comp_Typ_Lo : constant Node_Id := Type_Low_Bound (Component_Type (Typ)); Comp_Typ_Hi : constant Node_Id := Type_High_Bound (Component_Type (Typ)); Char_Val : Uint; begin if Compile_Time_Known_Value (Comp_Typ_Lo) and then Compile_Time_Known_Value (Comp_Typ_Hi) then for J in 1 .. Strlen loop Char_Val := UI_From_Int (Int (Get_String_Char (Str, J))); if Char_Val < Expr_Value (Comp_Typ_Lo) or else Char_Val > Expr_Value (Comp_Typ_Hi) then Apply_Compile_Time_Constraint_Error (N, "character out of range??", CE_Range_Check_Failed, Loc => Source_Ptr (Int (Loc) + J)); end if; end loop; return; end if; end; end if; end if; -- If we got here we meed to transform the string literal into the -- equivalent qualified positional array aggregate. This is rather -- heavy artillery for this situation, but it is hard work to avoid. declare Lits : constant List_Id := New_List; P : Source_Ptr := Loc + 1; C : Char_Code; begin -- Build the character literals, we give them source locations that -- correspond to the string positions, which is a bit tricky given -- the possible presence of wide character escape sequences. for J in 1 .. Strlen loop C := Get_String_Char (Str, J); Set_Character_Literal_Name (C); Append_To (Lits, Make_Character_Literal (P, Chars => Name_Find, Char_Literal_Value => UI_From_CC (C))); if In_Character_Range (C) then P := P + 1; -- Should we have a call to Skip_Wide here ??? -- ??? else -- Skip_Wide (P); end if; end loop; Rewrite (N, Make_Qualified_Expression (Loc, Subtype_Mark => New_Occurrence_Of (Typ, Loc), Expression => Make_Aggregate (Loc, Expressions => Lits))); Analyze_And_Resolve (N, Typ); end; end Resolve_String_Literal; ------------------------- -- Resolve_Target_Name -- ------------------------- procedure Resolve_Target_Name (N : Node_Id; Typ : Entity_Id) is begin Set_Etype (N, Typ); end Resolve_Target_Name; ----------------------------- -- Resolve_Type_Conversion -- ----------------------------- procedure Resolve_Type_Conversion (N : Node_Id; Typ : Entity_Id) is Conv_OK : constant Boolean := Conversion_OK (N); Operand : constant Node_Id := Expression (N); Operand_Typ : constant Entity_Id := Etype (Operand); Target_Typ : constant Entity_Id := Etype (N); Rop : Node_Id; Orig_N : Node_Id; Orig_T : Node_Id; Test_Redundant : Boolean := Warn_On_Redundant_Constructs; -- Set to False to suppress cases where we want to suppress the test -- for redundancy to avoid possible false positives on this warning. begin if not Conv_OK and then not Valid_Conversion (N, Target_Typ, Operand) then return; end if; -- If the Operand Etype is Universal_Fixed, then the conversion is -- never redundant. We need this check because by the time we have -- finished the rather complex transformation, the conversion looks -- redundant when it is not. if Operand_Typ = Universal_Fixed then Test_Redundant := False; -- If the operand is marked as Any_Fixed, then special processing is -- required. This is also a case where we suppress the test for a -- redundant conversion, since most certainly it is not redundant. elsif Operand_Typ = Any_Fixed then Test_Redundant := False; -- Mixed-mode operation involving a literal. Context must be a fixed -- type which is applied to the literal subsequently. -- Multiplication and division involving two fixed type operands must -- yield a universal real because the result is computed in arbitrary -- precision. if Is_Fixed_Point_Type (Typ) and then Nkind_In (Operand, N_Op_Divide, N_Op_Multiply) and then Etype (Left_Opnd (Operand)) = Any_Fixed and then Etype (Right_Opnd (Operand)) = Any_Fixed then Set_Etype (Operand, Universal_Real); elsif Is_Numeric_Type (Typ) and then Nkind_In (Operand, N_Op_Multiply, N_Op_Divide) and then (Etype (Right_Opnd (Operand)) = Universal_Real or else Etype (Left_Opnd (Operand)) = Universal_Real) then -- Return if expression is ambiguous if Unique_Fixed_Point_Type (N) = Any_Type then return; -- If nothing else, the available fixed type is Duration else Set_Etype (Operand, Standard_Duration); end if; -- Resolve the real operand with largest available precision if Etype (Right_Opnd (Operand)) = Universal_Real then Rop := New_Copy_Tree (Right_Opnd (Operand)); else Rop := New_Copy_Tree (Left_Opnd (Operand)); end if; Resolve (Rop, Universal_Real); -- If the operand is a literal (it could be a non-static and -- illegal exponentiation) check whether the use of Duration -- is potentially inaccurate. if Nkind (Rop) = N_Real_Literal and then Realval (Rop) /= Ureal_0 and then abs (Realval (Rop)) < Delta_Value (Standard_Duration) then Error_Msg_N ("??universal real operand can only " & "be interpreted as Duration!", Rop); Error_Msg_N ("\??precision will be lost in the conversion!", Rop); end if; elsif Is_Numeric_Type (Typ) and then Nkind (Operand) in N_Op and then Unique_Fixed_Point_Type (N) /= Any_Type then Set_Etype (Operand, Standard_Duration); else Error_Msg_N ("invalid context for mixed mode operation", N); Set_Etype (Operand, Any_Type); return; end if; end if; Resolve (Operand); -- In SPARK, a type conversion between array types should be restricted -- to types which have matching static bounds. -- Protect call to Matching_Static_Array_Bounds to avoid costly -- operation if not needed. if Restriction_Check_Required (SPARK_05) and then Is_Array_Type (Target_Typ) and then Is_Array_Type (Operand_Typ) and then Operand_Typ /= Any_Composite -- or else Operand in error and then not Matching_Static_Array_Bounds (Target_Typ, Operand_Typ) then Check_SPARK_05_Restriction ("array types should have matching static bounds", N); end if; -- In formal mode, the operand of an ancestor type conversion must be an -- object (not an expression). if Is_Tagged_Type (Target_Typ) and then not Is_Class_Wide_Type (Target_Typ) and then Is_Tagged_Type (Operand_Typ) and then not Is_Class_Wide_Type (Operand_Typ) and then Is_Ancestor (Target_Typ, Operand_Typ) and then not Is_SPARK_05_Object_Reference (Operand) then Check_SPARK_05_Restriction ("object required", Operand); end if; Analyze_Dimension (N); -- Note: we do the Eval_Type_Conversion call before applying the -- required checks for a subtype conversion. This is important, since -- both are prepared under certain circumstances to change the type -- conversion to a constraint error node, but in the case of -- Eval_Type_Conversion this may reflect an illegality in the static -- case, and we would miss the illegality (getting only a warning -- message), if we applied the type conversion checks first. Eval_Type_Conversion (N); -- Even when evaluation is not possible, we may be able to simplify the -- conversion or its expression. This needs to be done before applying -- checks, since otherwise the checks may use the original expression -- and defeat the simplifications. This is specifically the case for -- elimination of the floating-point Truncation attribute in -- float-to-int conversions. Simplify_Type_Conversion (N); -- If after evaluation we still have a type conversion, then we may need -- to apply checks required for a subtype conversion. -- Skip these type conversion checks if universal fixed operands -- operands involved, since range checks are handled separately for -- these cases (in the appropriate Expand routines in unit Exp_Fixd). if Nkind (N) = N_Type_Conversion and then not Is_Generic_Type (Root_Type (Target_Typ)) and then Target_Typ /= Universal_Fixed and then Operand_Typ /= Universal_Fixed then Apply_Type_Conversion_Checks (N); end if; -- Issue warning for conversion of simple object to its own type. We -- have to test the original nodes, since they may have been rewritten -- by various optimizations. Orig_N := Original_Node (N); -- Here we test for a redundant conversion if the warning mode is -- active (and was not locally reset), and we have a type conversion -- from source not appearing in a generic instance. if Test_Redundant and then Nkind (Orig_N) = N_Type_Conversion and then Comes_From_Source (Orig_N) and then not In_Instance then Orig_N := Original_Node (Expression (Orig_N)); Orig_T := Target_Typ; -- If the node is part of a larger expression, the Target_Type -- may not be the original type of the node if the context is a -- condition. Recover original type to see if conversion is needed. if Is_Boolean_Type (Orig_T) and then Nkind (Parent (N)) in N_Op then Orig_T := Etype (Parent (N)); end if; -- If we have an entity name, then give the warning if the entity -- is the right type, or if it is a loop parameter covered by the -- original type (that's needed because loop parameters have an -- odd subtype coming from the bounds). if (Is_Entity_Name (Orig_N) and then (Etype (Entity (Orig_N)) = Orig_T or else (Ekind (Entity (Orig_N)) = E_Loop_Parameter and then Covers (Orig_T, Etype (Entity (Orig_N)))))) -- If not an entity, then type of expression must match or else Etype (Orig_N) = Orig_T then -- One more check, do not give warning if the analyzed conversion -- has an expression with non-static bounds, and the bounds of the -- target are static. This avoids junk warnings in cases where the -- conversion is necessary to establish staticness, for example in -- a case statement. if not Is_OK_Static_Subtype (Operand_Typ) and then Is_OK_Static_Subtype (Target_Typ) then null; -- Finally, if this type conversion occurs in a context requiring -- a prefix, and the expression is a qualified expression then the -- type conversion is not redundant, since a qualified expression -- is not a prefix, whereas a type conversion is. For example, "X -- := T'(Funx(...)).Y;" is illegal because a selected component -- requires a prefix, but a type conversion makes it legal: "X := -- T(T'(Funx(...))).Y;" -- In Ada 2012, a qualified expression is a name, so this idiom is -- no longer needed, but we still suppress the warning because it -- seems unfriendly for warnings to pop up when you switch to the -- newer language version. elsif Nkind (Orig_N) = N_Qualified_Expression and then Nkind_In (Parent (N), N_Attribute_Reference, N_Indexed_Component, N_Selected_Component, N_Slice, N_Explicit_Dereference) then null; -- Never warn on conversion to Long_Long_Integer'Base since -- that is most likely an artifact of the extended overflow -- checking and comes from complex expanded code. elsif Orig_T = Base_Type (Standard_Long_Long_Integer) then null; -- Here we give the redundant conversion warning. If it is an -- entity, give the name of the entity in the message. If not, -- just mention the expression. -- Shoudn't we test Warn_On_Redundant_Constructs here ??? else if Is_Entity_Name (Orig_N) then Error_Msg_Node_2 := Orig_T; Error_Msg_NE -- CODEFIX ("??redundant conversion, & is of type &!", N, Entity (Orig_N)); else Error_Msg_NE ("??redundant conversion, expression is of type&!", N, Orig_T); end if; end if; end if; end if; -- Ada 2005 (AI-251): Handle class-wide interface type conversions. -- No need to perform any interface conversion if the type of the -- expression coincides with the target type. if Ada_Version >= Ada_2005 and then Expander_Active and then Operand_Typ /= Target_Typ then declare Opnd : Entity_Id := Operand_Typ; Target : Entity_Id := Target_Typ; begin -- If the type of the operand is a limited view, use nonlimited -- view when available. If it is a class-wide type, recover the -- class-wide type of the nonlimited view. if From_Limited_With (Opnd) and then Has_Non_Limited_View (Opnd) then Opnd := Non_Limited_View (Opnd); Set_Etype (Expression (N), Opnd); end if; if Is_Access_Type (Opnd) then Opnd := Designated_Type (Opnd); end if; if Is_Access_Type (Target_Typ) then Target := Designated_Type (Target); end if; if Opnd = Target then null; -- Conversion from interface type elsif Is_Interface (Opnd) then -- Ada 2005 (AI-217): Handle entities from limited views if From_Limited_With (Opnd) then Error_Msg_Qual_Level := 99; Error_Msg_NE -- CODEFIX ("missing WITH clause on package &", N, Cunit_Entity (Get_Source_Unit (Base_Type (Opnd)))); Error_Msg_N ("type conversions require visibility of the full view", N); elsif From_Limited_With (Target) and then not (Is_Access_Type (Target_Typ) and then Present (Non_Limited_View (Etype (Target)))) then Error_Msg_Qual_Level := 99; Error_Msg_NE -- CODEFIX ("missing WITH clause on package &", N, Cunit_Entity (Get_Source_Unit (Base_Type (Target)))); Error_Msg_N ("type conversions require visibility of the full view", N); else Expand_Interface_Conversion (N); end if; -- Conversion to interface type elsif Is_Interface (Target) then -- Handle subtypes if Ekind_In (Opnd, E_Protected_Subtype, E_Task_Subtype) then Opnd := Etype (Opnd); end if; if Is_Class_Wide_Type (Opnd) or else Interface_Present_In_Ancestor (Typ => Opnd, Iface => Target) then Expand_Interface_Conversion (N); else Error_Msg_Name_1 := Chars (Etype (Target)); Error_Msg_Name_2 := Chars (Opnd); Error_Msg_N ("wrong interface conversion (% is not a progenitor " & "of %)", N); end if; end if; end; end if; -- Ada 2012: once the type conversion is resolved, check whether the -- operand statisfies the static predicate of the target type. if Has_Predicates (Target_Typ) then Check_Expression_Against_Static_Predicate (N, Target_Typ); end if; -- If at this stage we have a real to integer conversion, make sure that -- the Do_Range_Check flag is set, because such conversions in general -- need a range check. We only need this if expansion is off. -- In GNATprove mode, we only do that when converting from fixed-point -- (as floating-point to integer conversions are now handled in -- GNATprove mode). if Nkind (N) = N_Type_Conversion and then not Expander_Active and then Is_Integer_Type (Target_Typ) and then (Is_Fixed_Point_Type (Operand_Typ) or else (not GNATprove_Mode and then Is_Floating_Point_Type (Operand_Typ))) then Set_Do_Range_Check (Operand); end if; -- Generating C code a type conversion of an access to constrained -- array type to access to unconstrained array type involves building -- a fat pointer which in general cannot be generated on the fly. We -- remove side effects in order to store the result of the conversion -- into a temporary. if Modify_Tree_For_C and then Nkind (N) = N_Type_Conversion and then Nkind (Parent (N)) /= N_Object_Declaration and then Is_Access_Type (Etype (N)) and then Is_Array_Type (Designated_Type (Etype (N))) and then not Is_Constrained (Designated_Type (Etype (N))) and then Is_Constrained (Designated_Type (Etype (Expression (N)))) then Remove_Side_Effects (N); end if; end Resolve_Type_Conversion; ---------------------- -- Resolve_Unary_Op -- ---------------------- procedure Resolve_Unary_Op (N : Node_Id; Typ : Entity_Id) is B_Typ : constant Entity_Id := Base_Type (Typ); R : constant Node_Id := Right_Opnd (N); OK : Boolean; Lo : Uint; Hi : Uint; begin if Is_Modular_Integer_Type (Typ) and then Nkind (N) /= N_Op_Not then Error_Msg_Name_1 := Chars (Typ); Check_SPARK_05_Restriction ("unary operator not defined for modular type%", N); end if; -- Deal with intrinsic unary operators if Comes_From_Source (N) and then Ekind (Entity (N)) = E_Function and then Is_Imported (Entity (N)) and then Is_Intrinsic_Subprogram (Entity (N)) then Resolve_Intrinsic_Unary_Operator (N, Typ); return; end if; -- Deal with universal cases if Etype (R) = Universal_Integer or else Etype (R) = Universal_Real then Check_For_Visible_Operator (N, B_Typ); end if; Set_Etype (N, B_Typ); Resolve (R, B_Typ); -- Generate warning for expressions like abs (x mod 2) if Warn_On_Redundant_Constructs and then Nkind (N) = N_Op_Abs then Determine_Range (Right_Opnd (N), OK, Lo, Hi); if OK and then Hi >= Lo and then Lo >= 0 then Error_Msg_N -- CODEFIX ("?r?abs applied to known non-negative value has no effect", N); end if; end if; -- Deal with reference generation Check_Unset_Reference (R); Generate_Operator_Reference (N, B_Typ); Analyze_Dimension (N); Eval_Unary_Op (N); -- Set overflow checking bit. Much cleverer code needed here eventually -- and perhaps the Resolve routines should be separated for the various -- arithmetic operations, since they will need different processing ??? if Nkind (N) in N_Op then if not Overflow_Checks_Suppressed (Etype (N)) then Enable_Overflow_Check (N); end if; end if; -- Generate warning for expressions like -5 mod 3 for integers. No need -- to worry in the floating-point case, since parens do not affect the -- result so there is no point in giving in a warning. declare Norig : constant Node_Id := Original_Node (N); Rorig : Node_Id; Val : Uint; HB : Uint; LB : Uint; Lval : Uint; Opnd : Node_Id; begin if Warn_On_Questionable_Missing_Parens and then Comes_From_Source (Norig) and then Is_Integer_Type (Typ) and then Nkind (Norig) = N_Op_Minus then Rorig := Original_Node (Right_Opnd (Norig)); -- We are looking for cases where the right operand is not -- parenthesized, and is a binary operator, multiply, divide, or -- mod. These are the cases where the grouping can affect results. if Paren_Count (Rorig) = 0 and then Nkind_In (Rorig, N_Op_Mod, N_Op_Multiply, N_Op_Divide) then -- For mod, we always give the warning, since the value is -- affected by the parenthesization (e.g. (-5) mod 315 /= -- -(5 mod 315)). But for the other cases, the only concern is -- overflow, e.g. for the case of 8 big signed (-(2 * 64) -- overflows, but (-2) * 64 does not). So we try to give the -- message only when overflow is possible. if Nkind (Rorig) /= N_Op_Mod and then Compile_Time_Known_Value (R) then Val := Expr_Value (R); if Compile_Time_Known_Value (Type_High_Bound (Typ)) then HB := Expr_Value (Type_High_Bound (Typ)); else HB := Expr_Value (Type_High_Bound (Base_Type (Typ))); end if; if Compile_Time_Known_Value (Type_Low_Bound (Typ)) then LB := Expr_Value (Type_Low_Bound (Typ)); else LB := Expr_Value (Type_Low_Bound (Base_Type (Typ))); end if; -- Note that the test below is deliberately excluding the -- largest negative number, since that is a potentially -- troublesome case (e.g. -2 * x, where the result is the -- largest negative integer has an overflow with 2 * x). if Val > LB and then Val <= HB then return; end if; end if; -- For the multiplication case, the only case we have to worry -- about is when (-a)*b is exactly the largest negative number -- so that -(a*b) can cause overflow. This can only happen if -- a is a power of 2, and more generally if any operand is a -- constant that is not a power of 2, then the parentheses -- cannot affect whether overflow occurs. We only bother to -- test the left most operand -- Loop looking at left operands for one that has known value Opnd := Rorig; Opnd_Loop : while Nkind (Opnd) = N_Op_Multiply loop if Compile_Time_Known_Value (Left_Opnd (Opnd)) then Lval := UI_Abs (Expr_Value (Left_Opnd (Opnd))); -- Operand value of 0 or 1 skips warning if Lval <= 1 then return; -- Otherwise check power of 2, if power of 2, warn, if -- anything else, skip warning. else while Lval /= 2 loop if Lval mod 2 = 1 then return; else Lval := Lval / 2; end if; end loop; exit Opnd_Loop; end if; end if; -- Keep looking at left operands Opnd := Left_Opnd (Opnd); end loop Opnd_Loop; -- For rem or "/" we can only have a problematic situation -- if the divisor has a value of minus one or one. Otherwise -- overflow is impossible (divisor > 1) or we have a case of -- division by zero in any case. if Nkind_In (Rorig, N_Op_Divide, N_Op_Rem) and then Compile_Time_Known_Value (Right_Opnd (Rorig)) and then UI_Abs (Expr_Value (Right_Opnd (Rorig))) /= 1 then return; end if; -- If we fall through warning should be issued -- Shouldn't we test Warn_On_Questionable_Missing_Parens ??? Error_Msg_N ("??unary minus expression should be parenthesized here!", N); end if; end if; end; end Resolve_Unary_Op; ---------------------------------- -- Resolve_Unchecked_Expression -- ---------------------------------- procedure Resolve_Unchecked_Expression (N : Node_Id; Typ : Entity_Id) is begin Resolve (Expression (N), Typ, Suppress => All_Checks); Set_Etype (N, Typ); end Resolve_Unchecked_Expression; --------------------------------------- -- Resolve_Unchecked_Type_Conversion -- --------------------------------------- procedure Resolve_Unchecked_Type_Conversion (N : Node_Id; Typ : Entity_Id) is pragma Warnings (Off, Typ); Operand : constant Node_Id := Expression (N); Opnd_Type : constant Entity_Id := Etype (Operand); begin -- Resolve operand using its own type Resolve (Operand, Opnd_Type); -- In an inlined context, the unchecked conversion may be applied -- to a literal, in which case its type is the type of the context. -- (In other contexts conversions cannot apply to literals). if In_Inlined_Body and then (Opnd_Type = Any_Character or else Opnd_Type = Any_Integer or else Opnd_Type = Any_Real) then Set_Etype (Operand, Typ); end if; Analyze_Dimension (N); Eval_Unchecked_Conversion (N); end Resolve_Unchecked_Type_Conversion; ------------------------------ -- Rewrite_Operator_As_Call -- ------------------------------ procedure Rewrite_Operator_As_Call (N : Node_Id; Nam : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Actuals : constant List_Id := New_List; New_N : Node_Id; begin if Nkind (N) in N_Binary_Op then Append (Left_Opnd (N), Actuals); end if; Append (Right_Opnd (N), Actuals); New_N := Make_Function_Call (Sloc => Loc, Name => New_Occurrence_Of (Nam, Loc), Parameter_Associations => Actuals); Preserve_Comes_From_Source (New_N, N); Preserve_Comes_From_Source (Name (New_N), N); Rewrite (N, New_N); Set_Etype (N, Etype (Nam)); end Rewrite_Operator_As_Call; ------------------------------ -- Rewrite_Renamed_Operator -- ------------------------------ procedure Rewrite_Renamed_Operator (N : Node_Id; Op : Entity_Id; Typ : Entity_Id) is Nam : constant Name_Id := Chars (Op); Is_Binary : constant Boolean := Nkind (N) in N_Binary_Op; Op_Node : Node_Id; begin -- Do not perform this transformation within a pre/postcondition, -- because the expression will be re-analyzed, and the transformation -- might affect the visibility of the operator, e.g. in an instance. -- Note that fully analyzed and expanded pre/postconditions appear as -- pragma Check equivalents. if In_Pre_Post_Condition (N) then return; end if; -- Rewrite the operator node using the real operator, not its renaming. -- Exclude user-defined intrinsic operations of the same name, which are -- treated separately and rewritten as calls. if Ekind (Op) /= E_Function or else Chars (N) /= Nam then Op_Node := New_Node (Operator_Kind (Nam, Is_Binary), Sloc (N)); Set_Chars (Op_Node, Nam); Set_Etype (Op_Node, Etype (N)); Set_Entity (Op_Node, Op); Set_Right_Opnd (Op_Node, Right_Opnd (N)); -- Indicate that both the original entity and its renaming are -- referenced at this point. Generate_Reference (Entity (N), N); Generate_Reference (Op, N); if Is_Binary then Set_Left_Opnd (Op_Node, Left_Opnd (N)); end if; Rewrite (N, Op_Node); -- If the context type is private, add the appropriate conversions so -- that the operator is applied to the full view. This is done in the -- routines that resolve intrinsic operators. if Is_Intrinsic_Subprogram (Op) and then Is_Private_Type (Typ) then case Nkind (N) is when N_Op_Add | N_Op_Divide | N_Op_Expon | N_Op_Mod | N_Op_Multiply | N_Op_Rem | N_Op_Subtract => Resolve_Intrinsic_Operator (N, Typ); when N_Op_Abs | N_Op_Minus | N_Op_Plus => Resolve_Intrinsic_Unary_Operator (N, Typ); when others => Resolve (N, Typ); end case; end if; elsif Ekind (Op) = E_Function and then Is_Intrinsic_Subprogram (Op) then -- Operator renames a user-defined operator of the same name. Use the -- original operator in the node, which is the one Gigi knows about. Set_Entity (N, Op); Set_Is_Overloaded (N, False); end if; end Rewrite_Renamed_Operator; ----------------------- -- Set_Slice_Subtype -- ----------------------- -- Build an implicit subtype declaration to represent the type delivered by -- the slice. This is an abbreviated version of an array subtype. We define -- an index subtype for the slice, using either the subtype name or the -- discrete range of the slice. To be consistent with index usage elsewhere -- we create a list header to hold the single index. This list is not -- otherwise attached to the syntax tree. procedure Set_Slice_Subtype (N : Node_Id) is Loc : constant Source_Ptr := Sloc (N); Index_List : constant List_Id := New_List; Index : Node_Id; Index_Subtype : Entity_Id; Index_Type : Entity_Id; Slice_Subtype : Entity_Id; Drange : constant Node_Id := Discrete_Range (N); begin Index_Type := Base_Type (Etype (Drange)); if Is_Entity_Name (Drange) then Index_Subtype := Entity (Drange); else -- We force the evaluation of a range. This is definitely needed in -- the renamed case, and seems safer to do unconditionally. Note in -- any case that since we will create and insert an Itype referring -- to this range, we must make sure any side effect removal actions -- are inserted before the Itype definition. if Nkind (Drange) = N_Range then Force_Evaluation (Low_Bound (Drange)); Force_Evaluation (High_Bound (Drange)); -- If the discrete range is given by a subtype indication, the -- type of the slice is the base of the subtype mark. elsif Nkind (Drange) = N_Subtype_Indication then declare R : constant Node_Id := Range_Expression (Constraint (Drange)); begin Index_Type := Base_Type (Entity (Subtype_Mark (Drange))); Force_Evaluation (Low_Bound (R)); Force_Evaluation (High_Bound (R)); end; end if; Index_Subtype := Create_Itype (Subtype_Kind (Ekind (Index_Type)), N); -- Take a new copy of Drange (where bounds have been rewritten to -- reference side-effect-free names). Using a separate tree ensures -- that further expansion (e.g. while rewriting a slice assignment -- into a FOR loop) does not attempt to remove side effects on the -- bounds again (which would cause the bounds in the index subtype -- definition to refer to temporaries before they are defined) (the -- reason is that some names are considered side effect free here -- for the subtype, but not in the context of a loop iteration -- scheme). Set_Scalar_Range (Index_Subtype, New_Copy_Tree (Drange)); Set_Parent (Scalar_Range (Index_Subtype), Index_Subtype); Set_Etype (Index_Subtype, Index_Type); Set_Size_Info (Index_Subtype, Index_Type); Set_RM_Size (Index_Subtype, RM_Size (Index_Type)); end if; Slice_Subtype := Create_Itype (E_Array_Subtype, N); Index := New_Occurrence_Of (Index_Subtype, Loc); Set_Etype (Index, Index_Subtype); Append (Index, Index_List); Set_First_Index (Slice_Subtype, Index); Set_Etype (Slice_Subtype, Base_Type (Etype (N))); Set_Is_Constrained (Slice_Subtype, True); Check_Compile_Time_Size (Slice_Subtype); -- The Etype of the existing Slice node is reset to this slice subtype. -- Its bounds are obtained from its first index. Set_Etype (N, Slice_Subtype); -- For bit-packed slice subtypes, freeze immediately (except in the case -- of being in a "spec expression" where we never freeze when we first -- see the expression). if Is_Bit_Packed_Array (Slice_Subtype) and not In_Spec_Expression then Freeze_Itype (Slice_Subtype, N); -- For all other cases insert an itype reference in the slice's actions -- so that the itype is frozen at the proper place in the tree (i.e. at -- the point where actions for the slice are analyzed). Note that this -- is different from freezing the itype immediately, which might be -- premature (e.g. if the slice is within a transient scope). This needs -- to be done only if expansion is enabled. elsif Expander_Active then Ensure_Defined (Typ => Slice_Subtype, N => N); end if; end Set_Slice_Subtype; -------------------------------- -- Set_String_Literal_Subtype -- -------------------------------- procedure Set_String_Literal_Subtype (N : Node_Id; Typ : Entity_Id) is Loc : constant Source_Ptr := Sloc (N); Low_Bound : constant Node_Id := Type_Low_Bound (Etype (First_Index (Typ))); Subtype_Id : Entity_Id; begin if Nkind (N) /= N_String_Literal then return; end if; Subtype_Id := Create_Itype (E_String_Literal_Subtype, N); Set_String_Literal_Length (Subtype_Id, UI_From_Int (String_Length (Strval (N)))); Set_Etype (Subtype_Id, Base_Type (Typ)); Set_Is_Constrained (Subtype_Id); Set_Etype (N, Subtype_Id); -- The low bound is set from the low bound of the corresponding index -- type. Note that we do not store the high bound in the string literal -- subtype, but it can be deduced if necessary from the length and the -- low bound. if Is_OK_Static_Expression (Low_Bound) then Set_String_Literal_Low_Bound (Subtype_Id, Low_Bound); -- If the lower bound is not static we create a range for the string -- literal, using the index type and the known length of the literal. -- The index type is not necessarily Positive, so the upper bound is -- computed as T'Val (T'Pos (Low_Bound) + L - 1). else declare Index_List : constant List_Id := New_List; Index_Type : constant Entity_Id := Etype (First_Index (Typ)); High_Bound : constant Node_Id := Make_Attribute_Reference (Loc, Attribute_Name => Name_Val, Prefix => New_Occurrence_Of (Index_Type, Loc), Expressions => New_List ( Make_Op_Add (Loc, Left_Opnd => Make_Attribute_Reference (Loc, Attribute_Name => Name_Pos, Prefix => New_Occurrence_Of (Index_Type, Loc), Expressions => New_List (New_Copy_Tree (Low_Bound))), Right_Opnd => Make_Integer_Literal (Loc, String_Length (Strval (N)) - 1)))); Array_Subtype : Entity_Id; Drange : Node_Id; Index : Node_Id; Index_Subtype : Entity_Id; begin if Is_Integer_Type (Index_Type) then Set_String_Literal_Low_Bound (Subtype_Id, Make_Integer_Literal (Loc, 1)); else -- If the index type is an enumeration type, build bounds -- expression with attributes. Set_String_Literal_Low_Bound (Subtype_Id, Make_Attribute_Reference (Loc, Attribute_Name => Name_First, Prefix => New_Occurrence_Of (Base_Type (Index_Type), Loc))); Set_Etype (String_Literal_Low_Bound (Subtype_Id), Index_Type); end if; Analyze_And_Resolve (String_Literal_Low_Bound (Subtype_Id)); -- Build bona fide subtype for the string, and wrap it in an -- unchecked conversion, because the backend expects the -- String_Literal_Subtype to have a static lower bound. Index_Subtype := Create_Itype (Subtype_Kind (Ekind (Index_Type)), N); Drange := Make_Range (Loc, New_Copy_Tree (Low_Bound), High_Bound); Set_Scalar_Range (Index_Subtype, Drange); Set_Parent (Drange, N); Analyze_And_Resolve (Drange, Index_Type); -- In the context, the Index_Type may already have a constraint, -- so use common base type on string subtype. The base type may -- be used when generating attributes of the string, for example -- in the context of a slice assignment. Set_Etype (Index_Subtype, Base_Type (Index_Type)); Set_Size_Info (Index_Subtype, Index_Type); Set_RM_Size (Index_Subtype, RM_Size (Index_Type)); Array_Subtype := Create_Itype (E_Array_Subtype, N); Index := New_Occurrence_Of (Index_Subtype, Loc); Set_Etype (Index, Index_Subtype); Append (Index, Index_List); Set_First_Index (Array_Subtype, Index); Set_Etype (Array_Subtype, Base_Type (Typ)); Set_Is_Constrained (Array_Subtype, True); Rewrite (N, Make_Unchecked_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Array_Subtype, Loc), Expression => Relocate_Node (N))); Set_Etype (N, Array_Subtype); end; end if; end Set_String_Literal_Subtype; ------------------------------ -- Simplify_Type_Conversion -- ------------------------------ procedure Simplify_Type_Conversion (N : Node_Id) is begin if Nkind (N) = N_Type_Conversion then declare Operand : constant Node_Id := Expression (N); Target_Typ : constant Entity_Id := Etype (N); Opnd_Typ : constant Entity_Id := Etype (Operand); begin -- Special processing if the conversion is the expression of a -- Rounding or Truncation attribute reference. In this case we -- replace: -- ityp (ftyp'Rounding (x)) or ityp (ftyp'Truncation (x)) -- by -- ityp (x) -- with the Float_Truncate flag set to False or True respectively, -- which is more efficient. if Is_Floating_Point_Type (Opnd_Typ) and then (Is_Integer_Type (Target_Typ) or else (Is_Fixed_Point_Type (Target_Typ) and then Conversion_OK (N))) and then Nkind (Operand) = N_Attribute_Reference and then Nam_In (Attribute_Name (Operand), Name_Rounding, Name_Truncation) then declare Truncate : constant Boolean := Attribute_Name (Operand) = Name_Truncation; begin Rewrite (Operand, Relocate_Node (First (Expressions (Operand)))); Set_Float_Truncate (N, Truncate); end; end if; end; end if; end Simplify_Type_Conversion; ----------------------------- -- Unique_Fixed_Point_Type -- ----------------------------- function Unique_Fixed_Point_Type (N : Node_Id) return Entity_Id is procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id); -- Give error messages for true ambiguity. Messages are posted on node -- N, and entities T1, T2 are the possible interpretations. ----------------------- -- Fixed_Point_Error -- ----------------------- procedure Fixed_Point_Error (T1 : Entity_Id; T2 : Entity_Id) is begin Error_Msg_N ("ambiguous universal_fixed_expression", N); Error_Msg_NE ("\\possible interpretation as}", N, T1); Error_Msg_NE ("\\possible interpretation as}", N, T2); end Fixed_Point_Error; -- Local variables ErrN : Node_Id; Item : Node_Id; Scop : Entity_Id; T1 : Entity_Id; T2 : Entity_Id; -- Start of processing for Unique_Fixed_Point_Type begin -- The operations on Duration are visible, so Duration is always a -- possible interpretation. T1 := Standard_Duration; -- Look for fixed-point types in enclosing scopes Scop := Current_Scope; while Scop /= Standard_Standard loop T2 := First_Entity (Scop); while Present (T2) loop if Is_Fixed_Point_Type (T2) and then Current_Entity (T2) = T2 and then Scope (Base_Type (T2)) = Scop then if Present (T1) then Fixed_Point_Error (T1, T2); return Any_Type; else T1 := T2; end if; end if; Next_Entity (T2); end loop; Scop := Scope (Scop); end loop; -- Look for visible fixed type declarations in the context Item := First (Context_Items (Cunit (Current_Sem_Unit))); while Present (Item) loop if Nkind (Item) = N_With_Clause then Scop := Entity (Name (Item)); T2 := First_Entity (Scop); while Present (T2) loop if Is_Fixed_Point_Type (T2) and then Scope (Base_Type (T2)) = Scop and then (Is_Potentially_Use_Visible (T2) or else In_Use (T2)) then if Present (T1) then Fixed_Point_Error (T1, T2); return Any_Type; else T1 := T2; end if; end if; Next_Entity (T2); end loop; end if; Next (Item); end loop; if Nkind (N) = N_Real_Literal then Error_Msg_NE ("??real literal interpreted as }!", N, T1); else -- When the context is a type conversion, issue the warning on the -- expression of the conversion because it is the actual operation. if Nkind_In (N, N_Type_Conversion, N_Unchecked_Type_Conversion) then ErrN := Expression (N); else ErrN := N; end if; Error_Msg_NE ("??universal_fixed expression interpreted as }!", ErrN, T1); end if; return T1; end Unique_Fixed_Point_Type; ---------------------- -- Valid_Conversion -- ---------------------- function Valid_Conversion (N : Node_Id; Target : Entity_Id; Operand : Node_Id; Report_Errs : Boolean := True) return Boolean is Target_Type : constant Entity_Id := Base_Type (Target); Opnd_Type : Entity_Id := Etype (Operand); Inc_Ancestor : Entity_Id; function Conversion_Check (Valid : Boolean; Msg : String) return Boolean; -- Little routine to post Msg if Valid is False, returns Valid value procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id); -- If Report_Errs, then calls Errout.Error_Msg_N with its arguments procedure Conversion_Error_NE (Msg : String; N : Node_Or_Entity_Id; E : Node_Or_Entity_Id); -- If Report_Errs, then calls Errout.Error_Msg_NE with its arguments function Valid_Tagged_Conversion (Target_Type : Entity_Id; Opnd_Type : Entity_Id) return Boolean; -- Specifically test for validity of tagged conversions function Valid_Array_Conversion return Boolean; -- Check index and component conformance, and accessibility levels if -- the component types are anonymous access types (Ada 2005). ---------------------- -- Conversion_Check -- ---------------------- function Conversion_Check (Valid : Boolean; Msg : String) return Boolean is begin if not Valid -- A generic unit has already been analyzed and we have verified -- that a particular conversion is OK in that context. Since the -- instance is reanalyzed without relying on the relationships -- established during the analysis of the generic, it is possible -- to end up with inconsistent views of private types. Do not emit -- the error message in such cases. The rest of the machinery in -- Valid_Conversion still ensures the proper compatibility of -- target and operand types. and then not In_Instance then Conversion_Error_N (Msg, Operand); end if; return Valid; end Conversion_Check; ------------------------ -- Conversion_Error_N -- ------------------------ procedure Conversion_Error_N (Msg : String; N : Node_Or_Entity_Id) is begin if Report_Errs then Error_Msg_N (Msg, N); end if; end Conversion_Error_N; ------------------------- -- Conversion_Error_NE -- ------------------------- procedure Conversion_Error_NE (Msg : String; N : Node_Or_Entity_Id; E : Node_Or_Entity_Id) is begin if Report_Errs then Error_Msg_NE (Msg, N, E); end if; end Conversion_Error_NE; ---------------------------- -- Valid_Array_Conversion -- ---------------------------- function Valid_Array_Conversion return Boolean is Opnd_Comp_Type : constant Entity_Id := Component_Type (Opnd_Type); Opnd_Comp_Base : constant Entity_Id := Base_Type (Opnd_Comp_Type); Opnd_Index : Node_Id; Opnd_Index_Type : Entity_Id; Target_Comp_Type : constant Entity_Id := Component_Type (Target_Type); Target_Comp_Base : constant Entity_Id := Base_Type (Target_Comp_Type); Target_Index : Node_Id; Target_Index_Type : Entity_Id; begin -- Error if wrong number of dimensions if Number_Dimensions (Target_Type) /= Number_Dimensions (Opnd_Type) then Conversion_Error_N ("incompatible number of dimensions for conversion", Operand); return False; -- Number of dimensions matches else -- Loop through indexes of the two arrays Target_Index := First_Index (Target_Type); Opnd_Index := First_Index (Opnd_Type); while Present (Target_Index) and then Present (Opnd_Index) loop Target_Index_Type := Etype (Target_Index); Opnd_Index_Type := Etype (Opnd_Index); -- Error if index types are incompatible if not (Is_Integer_Type (Target_Index_Type) and then Is_Integer_Type (Opnd_Index_Type)) and then (Root_Type (Target_Index_Type) /= Root_Type (Opnd_Index_Type)) then Conversion_Error_N ("incompatible index types for array conversion", Operand); return False; end if; Next_Index (Target_Index); Next_Index (Opnd_Index); end loop; -- If component types have same base type, all set if Target_Comp_Base = Opnd_Comp_Base then null; -- Here if base types of components are not the same. The only -- time this is allowed is if we have anonymous access types. -- The conversion of arrays of anonymous access types can lead -- to dangling pointers. AI-392 formalizes the accessibility -- checks that must be applied to such conversions to prevent -- out-of-scope references. elsif Ekind_In (Target_Comp_Base, E_Anonymous_Access_Type, E_Anonymous_Access_Subprogram_Type) and then Ekind (Opnd_Comp_Base) = Ekind (Target_Comp_Base) and then Subtypes_Statically_Match (Target_Comp_Type, Opnd_Comp_Type) then if Type_Access_Level (Target_Type) < Deepest_Type_Access_Level (Opnd_Type) then if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Conversion_Error_N ("source array type has deeper accessibility " & "level than target<<", Operand); Conversion_Error_N ("\Program_Error [<<", Operand); Rewrite (N, Make_Raise_Program_Error (Sloc (N), Reason => PE_Accessibility_Check_Failed)); Set_Etype (N, Target_Type); return False; -- Conversion not allowed because of accessibility levels else Conversion_Error_N ("source array type has deeper accessibility " & "level than target", Operand); return False; end if; else null; end if; -- All other cases where component base types do not match else Conversion_Error_N ("incompatible component types for array conversion", Operand); return False; end if; -- Check that component subtypes statically match. For numeric -- types this means that both must be either constrained or -- unconstrained. For enumeration types the bounds must match. -- All of this is checked in Subtypes_Statically_Match. if not Subtypes_Statically_Match (Target_Comp_Type, Opnd_Comp_Type) then Conversion_Error_N ("component subtypes must statically match", Operand); return False; end if; end if; return True; end Valid_Array_Conversion; ----------------------------- -- Valid_Tagged_Conversion -- ----------------------------- function Valid_Tagged_Conversion (Target_Type : Entity_Id; Opnd_Type : Entity_Id) return Boolean is begin -- Upward conversions are allowed (RM 4.6(22)) if Covers (Target_Type, Opnd_Type) or else Is_Ancestor (Target_Type, Opnd_Type) then return True; -- Downward conversion are allowed if the operand is class-wide -- (RM 4.6(23)). elsif Is_Class_Wide_Type (Opnd_Type) and then Covers (Opnd_Type, Target_Type) then return True; elsif Covers (Opnd_Type, Target_Type) or else Is_Ancestor (Opnd_Type, Target_Type) then return Conversion_Check (False, "downward conversion of tagged objects not allowed"); -- Ada 2005 (AI-251): The conversion to/from interface types is -- always valid. The types involved may be class-wide (sub)types. elsif Is_Interface (Etype (Base_Type (Target_Type))) or else Is_Interface (Etype (Base_Type (Opnd_Type))) then return True; -- If the operand is a class-wide type obtained through a limited_ -- with clause, and the context includes the nonlimited view, use -- it to determine whether the conversion is legal. elsif Is_Class_Wide_Type (Opnd_Type) and then From_Limited_With (Opnd_Type) and then Present (Non_Limited_View (Etype (Opnd_Type))) and then Is_Interface (Non_Limited_View (Etype (Opnd_Type))) then return True; elsif Is_Access_Type (Opnd_Type) and then Is_Interface (Directly_Designated_Type (Opnd_Type)) then return True; else Conversion_Error_NE ("invalid tagged conversion, not compatible with}", N, First_Subtype (Opnd_Type)); return False; end if; end Valid_Tagged_Conversion; -- Start of processing for Valid_Conversion begin Check_Parameterless_Call (Operand); if Is_Overloaded (Operand) then declare I : Interp_Index; I1 : Interp_Index; It : Interp; It1 : Interp; N1 : Entity_Id; T1 : Entity_Id; begin -- Remove procedure calls, which syntactically cannot appear in -- this context, but which cannot be removed by type checking, -- because the context does not impose a type. -- The node may be labelled overloaded, but still contain only one -- interpretation because others were discarded earlier. If this -- is the case, retain the single interpretation if legal. Get_First_Interp (Operand, I, It); Opnd_Type := It.Typ; Get_Next_Interp (I, It); if Present (It.Typ) and then Opnd_Type /= Standard_Void_Type then -- More than one candidate interpretation is available Get_First_Interp (Operand, I, It); while Present (It.Typ) loop if It.Typ = Standard_Void_Type then Remove_Interp (I); end if; -- When compiling for a system where Address is of a visible -- integer type, spurious ambiguities can be produced when -- arithmetic operations have a literal operand and return -- System.Address or a descendant of it. These ambiguities -- are usually resolved by the context, but for conversions -- there is no context type and the removal of the spurious -- operations must be done explicitly here. if not Address_Is_Private and then Is_Descendant_Of_Address (It.Typ) then Remove_Interp (I); end if; Get_Next_Interp (I, It); end loop; end if; Get_First_Interp (Operand, I, It); I1 := I; It1 := It; if No (It.Typ) then Conversion_Error_N ("illegal operand in conversion", Operand); return False; end if; Get_Next_Interp (I, It); if Present (It.Typ) then N1 := It1.Nam; T1 := It1.Typ; It1 := Disambiguate (Operand, I1, I, Any_Type); if It1 = No_Interp then Conversion_Error_N ("ambiguous operand in conversion", Operand); -- If the interpretation involves a standard operator, use -- the location of the type, which may be user-defined. if Sloc (It.Nam) = Standard_Location then Error_Msg_Sloc := Sloc (It.Typ); else Error_Msg_Sloc := Sloc (It.Nam); end if; Conversion_Error_N -- CODEFIX ("\\possible interpretation#!", Operand); if Sloc (N1) = Standard_Location then Error_Msg_Sloc := Sloc (T1); else Error_Msg_Sloc := Sloc (N1); end if; Conversion_Error_N -- CODEFIX ("\\possible interpretation#!", Operand); return False; end if; end if; Set_Etype (Operand, It1.Typ); Opnd_Type := It1.Typ; end; end if; -- Deal with conversion of integer type to address if the pragma -- Allow_Integer_Address is in effect. We convert the conversion to -- an unchecked conversion in this case and we are all done. if Address_Integer_Convert_OK (Opnd_Type, Target_Type) then Rewrite (N, Unchecked_Convert_To (Target_Type, Expression (N))); Analyze_And_Resolve (N, Target_Type); return True; end if; -- If we are within a child unit, check whether the type of the -- expression has an ancestor in a parent unit, in which case it -- belongs to its derivation class even if the ancestor is private. -- See RM 7.3.1 (5.2/3). Inc_Ancestor := Get_Incomplete_View_Of_Ancestor (Opnd_Type); -- Numeric types if Is_Numeric_Type (Target_Type) then -- A universal fixed expression can be converted to any numeric type if Opnd_Type = Universal_Fixed then return True; -- Also no need to check when in an instance or inlined body, because -- the legality has been established when the template was analyzed. -- Furthermore, numeric conversions may occur where only a private -- view of the operand type is visible at the instantiation point. -- This results in a spurious error if we check that the operand type -- is a numeric type. -- Note: in a previous version of this unit, the following tests were -- applied only for generated code (Comes_From_Source set to False), -- but in fact the test is required for source code as well, since -- this situation can arise in source code. elsif In_Instance or else In_Inlined_Body then return True; -- Otherwise we need the conversion check else return Conversion_Check (Is_Numeric_Type (Opnd_Type) or else (Present (Inc_Ancestor) and then Is_Numeric_Type (Inc_Ancestor)), "illegal operand for numeric conversion"); end if; -- Array types elsif Is_Array_Type (Target_Type) then if not Is_Array_Type (Opnd_Type) or else Opnd_Type = Any_Composite or else Opnd_Type = Any_String then Conversion_Error_N ("illegal operand for array conversion", Operand); return False; else return Valid_Array_Conversion; end if; -- Ada 2005 (AI-251): Internally generated conversions of access to -- interface types added to force the displacement of the pointer to -- reference the corresponding dispatch table. elsif not Comes_From_Source (N) and then Is_Access_Type (Target_Type) and then Is_Interface (Designated_Type (Target_Type)) then return True; -- Ada 2005 (AI-251): Anonymous access types where target references an -- interface type. elsif Is_Access_Type (Opnd_Type) and then Ekind_In (Target_Type, E_General_Access_Type, E_Anonymous_Access_Type) and then Is_Interface (Directly_Designated_Type (Target_Type)) then -- Check the static accessibility rule of 4.6(17). Note that the -- check is not enforced when within an instance body, since the -- RM requires such cases to be caught at run time. -- If the operand is a rewriting of an allocator no check is needed -- because there are no accessibility issues. if Nkind (Original_Node (N)) = N_Allocator then null; elsif Ekind (Target_Type) /= E_Anonymous_Access_Type then if Type_Access_Level (Opnd_Type) > Deepest_Type_Access_Level (Target_Type) then -- In an instance, this is a run-time check, but one we know -- will fail, so generate an appropriate warning. The raise -- will be generated by Expand_N_Type_Conversion. if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Conversion_Error_N ("cannot convert local pointer to non-local access type<<", Operand); Conversion_Error_N ("\Program_Error [<<", Operand); else Conversion_Error_N ("cannot convert local pointer to non-local access type", Operand); return False; end if; -- Special accessibility checks are needed in the case of access -- discriminants declared for a limited type. elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type and then not Is_Local_Anonymous_Access (Opnd_Type) then -- When the operand is a selected access discriminant the check -- needs to be made against the level of the object denoted by -- the prefix of the selected name (Object_Access_Level handles -- checking the prefix of the operand for this case). if Nkind (Operand) = N_Selected_Component and then Object_Access_Level (Operand) > Deepest_Type_Access_Level (Target_Type) then -- In an instance, this is a run-time check, but one we know -- will fail, so generate an appropriate warning. The raise -- will be generated by Expand_N_Type_Conversion. if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Conversion_Error_N ("cannot convert access discriminant to non-local " & "access type<<", Operand); Conversion_Error_N ("\Program_Error [<<", Operand); -- Real error if not in instance body else Conversion_Error_N ("cannot convert access discriminant to non-local " & "access type", Operand); return False; end if; end if; -- The case of a reference to an access discriminant from -- within a limited type declaration (which will appear as -- a discriminal) is always illegal because the level of the -- discriminant is considered to be deeper than any (nameable) -- access type. if Is_Entity_Name (Operand) and then not Is_Local_Anonymous_Access (Opnd_Type) and then Ekind_In (Entity (Operand), E_In_Parameter, E_Constant) and then Present (Discriminal_Link (Entity (Operand))) then Conversion_Error_N ("discriminant has deeper accessibility level than target", Operand); return False; end if; end if; end if; return True; -- General and anonymous access types elsif Ekind_In (Target_Type, E_General_Access_Type, E_Anonymous_Access_Type) and then Conversion_Check (Is_Access_Type (Opnd_Type) and then not Ekind_In (Opnd_Type, E_Access_Subprogram_Type, E_Access_Protected_Subprogram_Type), "must be an access-to-object type") then if Is_Access_Constant (Opnd_Type) and then not Is_Access_Constant (Target_Type) then Conversion_Error_N ("access-to-constant operand type not allowed", Operand); return False; end if; -- Check the static accessibility rule of 4.6(17). Note that the -- check is not enforced when within an instance body, since the RM -- requires such cases to be caught at run time. if Ekind (Target_Type) /= E_Anonymous_Access_Type or else Is_Local_Anonymous_Access (Target_Type) or else Nkind (Associated_Node_For_Itype (Target_Type)) = N_Object_Declaration then -- Ada 2012 (AI05-0149): Perform legality checking on implicit -- conversions from an anonymous access type to a named general -- access type. Such conversions are not allowed in the case of -- access parameters and stand-alone objects of an anonymous -- access type. The implicit conversion case is recognized by -- testing that Comes_From_Source is False and that it's been -- rewritten. The Comes_From_Source test isn't sufficient because -- nodes in inlined calls to predefined library routines can have -- Comes_From_Source set to False. (Is there a better way to test -- for implicit conversions???) if Ada_Version >= Ada_2012 and then not Comes_From_Source (N) and then N /= Original_Node (N) and then Ekind (Target_Type) = E_General_Access_Type and then Ekind (Opnd_Type) = E_Anonymous_Access_Type then if Is_Itype (Opnd_Type) then -- Implicit conversions aren't allowed for objects of an -- anonymous access type, since such objects have nonstatic -- levels in Ada 2012. if Nkind (Associated_Node_For_Itype (Opnd_Type)) = N_Object_Declaration then Conversion_Error_N ("implicit conversion of stand-alone anonymous " & "access object not allowed", Operand); return False; -- Implicit conversions aren't allowed for anonymous access -- parameters. The "not Is_Local_Anonymous_Access_Type" test -- is done to exclude anonymous access results. elsif not Is_Local_Anonymous_Access (Opnd_Type) and then Nkind_In (Associated_Node_For_Itype (Opnd_Type), N_Function_Specification, N_Procedure_Specification) then Conversion_Error_N ("implicit conversion of anonymous access formal " & "not allowed", Operand); return False; -- This is a case where there's an enclosing object whose -- to which the "statically deeper than" relationship does -- not apply (such as an access discriminant selected from -- a dereference of an access parameter). elsif Object_Access_Level (Operand) = Scope_Depth (Standard_Standard) then Conversion_Error_N ("implicit conversion of anonymous access value " & "not allowed", Operand); return False; -- In other cases, the level of the operand's type must be -- statically less deep than that of the target type, else -- implicit conversion is disallowed (by RM12-8.6(27.1/3)). elsif Type_Access_Level (Opnd_Type) > Deepest_Type_Access_Level (Target_Type) then Conversion_Error_N ("implicit conversion of anonymous access value " & "violates accessibility", Operand); return False; end if; end if; elsif Type_Access_Level (Opnd_Type) > Deepest_Type_Access_Level (Target_Type) then -- In an instance, this is a run-time check, but one we know -- will fail, so generate an appropriate warning. The raise -- will be generated by Expand_N_Type_Conversion. if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Conversion_Error_N ("cannot convert local pointer to non-local access type<<", Operand); Conversion_Error_N ("\Program_Error [<<", Operand); -- If not in an instance body, this is a real error else -- Avoid generation of spurious error message if not Error_Posted (N) then Conversion_Error_N ("cannot convert local pointer to non-local access type", Operand); end if; return False; end if; -- Special accessibility checks are needed in the case of access -- discriminants declared for a limited type. elsif Ekind (Opnd_Type) = E_Anonymous_Access_Type and then not Is_Local_Anonymous_Access (Opnd_Type) then -- When the operand is a selected access discriminant the check -- needs to be made against the level of the object denoted by -- the prefix of the selected name (Object_Access_Level handles -- checking the prefix of the operand for this case). if Nkind (Operand) = N_Selected_Component and then Object_Access_Level (Operand) > Deepest_Type_Access_Level (Target_Type) then -- In an instance, this is a run-time check, but one we know -- will fail, so generate an appropriate warning. The raise -- will be generated by Expand_N_Type_Conversion. if In_Instance_Body then Error_Msg_Warn := SPARK_Mode /= On; Conversion_Error_N ("cannot convert access discriminant to non-local " & "access type<<", Operand); Conversion_Error_N ("\Program_Error [<<", Operand); -- If not in an instance body, this is a real error else Conversion_Error_N ("cannot convert access discriminant to non-local " & "access type", Operand); return False; end if; end if; -- The case of a reference to an access discriminant from -- within a limited type declaration (which will appear as -- a discriminal) is always illegal because the level of the -- discriminant is considered to be deeper than any (nameable) -- access type. if Is_Entity_Name (Operand) and then Ekind_In (Entity (Operand), E_In_Parameter, E_Constant) and then Present (Discriminal_Link (Entity (Operand))) then Conversion_Error_N ("discriminant has deeper accessibility level than target", Operand); return False; end if; end if; end if; -- In the presence of limited_with clauses we have to use nonlimited -- views, if available. Check_Limited : declare function Full_Designated_Type (T : Entity_Id) return Entity_Id; -- Helper function to handle limited views -------------------------- -- Full_Designated_Type -- -------------------------- function Full_Designated_Type (T : Entity_Id) return Entity_Id is Desig : constant Entity_Id := Designated_Type (T); begin -- Handle the limited view of a type if From_Limited_With (Desig) and then Has_Non_Limited_View (Desig) then return Available_View (Desig); else return Desig; end if; end Full_Designated_Type; -- Local Declarations Target : constant Entity_Id := Full_Designated_Type (Target_Type); Opnd : constant Entity_Id := Full_Designated_Type (Opnd_Type); Same_Base : constant Boolean := Base_Type (Target) = Base_Type (Opnd); -- Start of processing for Check_Limited begin if Is_Tagged_Type (Target) then return Valid_Tagged_Conversion (Target, Opnd); else if not Same_Base then Conversion_Error_NE ("target designated type not compatible with }", N, Base_Type (Opnd)); return False; -- Ada 2005 AI-384: legality rule is symmetric in both -- designated types. The conversion is legal (with possible -- constraint check) if either designated type is -- unconstrained. elsif Subtypes_Statically_Match (Target, Opnd) or else (Has_Discriminants (Target) and then (not Is_Constrained (Opnd) or else not Is_Constrained (Target))) then -- Special case, if Value_Size has been used to make the -- sizes different, the conversion is not allowed even -- though the subtypes statically match. if Known_Static_RM_Size (Target) and then Known_Static_RM_Size (Opnd) and then RM_Size (Target) /= RM_Size (Opnd) then Conversion_Error_NE ("target designated subtype not compatible with }", N, Opnd); Conversion_Error_NE ("\because sizes of the two designated subtypes differ", N, Opnd); return False; -- Normal case where conversion is allowed else return True; end if; else Error_Msg_NE ("target designated subtype not compatible with }", N, Opnd); return False; end if; end if; end Check_Limited; -- Access to subprogram types. If the operand is an access parameter, -- the type has a deeper accessibility that any master, and cannot be -- assigned. We must make an exception if the conversion is part of an -- assignment and the target is the return object of an extended return -- statement, because in that case the accessibility check takes place -- after the return. elsif Is_Access_Subprogram_Type (Target_Type) -- Note: this test of Opnd_Type is there to prevent entering this -- branch in the case of a remote access to subprogram type, which -- is internally represented as an E_Record_Type. and then Is_Access_Type (Opnd_Type) then if Ekind (Base_Type (Opnd_Type)) = E_Anonymous_Access_Subprogram_Type and then Is_Entity_Name (Operand) and then Ekind (Entity (Operand)) = E_In_Parameter and then (Nkind (Parent (N)) /= N_Assignment_Statement or else not Is_Entity_Name (Name (Parent (N))) or else not Is_Return_Object (Entity (Name (Parent (N))))) then Conversion_Error_N ("illegal attempt to store anonymous access to subprogram", Operand); Conversion_Error_N ("\value has deeper accessibility than any master " & "(RM 3.10.2 (13))", Operand); Error_Msg_NE ("\use named access type for& instead of access parameter", Operand, Entity (Operand)); end if; -- Check that the designated types are subtype conformant Check_Subtype_Conformant (New_Id => Designated_Type (Target_Type), Old_Id => Designated_Type (Opnd_Type), Err_Loc => N); -- Check the static accessibility rule of 4.6(20) if Type_Access_Level (Opnd_Type) > Deepest_Type_Access_Level (Target_Type) then Conversion_Error_N ("operand type has deeper accessibility level than target", Operand); -- Check that if the operand type is declared in a generic body, -- then the target type must be declared within that same body -- (enforces last sentence of 4.6(20)). elsif Present (Enclosing_Generic_Body (Opnd_Type)) then declare O_Gen : constant Node_Id := Enclosing_Generic_Body (Opnd_Type); T_Gen : Node_Id; begin T_Gen := Enclosing_Generic_Body (Target_Type); while Present (T_Gen) and then T_Gen /= O_Gen loop T_Gen := Enclosing_Generic_Body (T_Gen); end loop; if T_Gen /= O_Gen then Conversion_Error_N ("target type must be declared in same generic body " & "as operand type", N); end if; end; end if; return True; -- Remote access to subprogram types elsif Is_Remote_Access_To_Subprogram_Type (Target_Type) and then Is_Remote_Access_To_Subprogram_Type (Opnd_Type) then -- It is valid to convert from one RAS type to another provided -- that their specification statically match. -- Note: at this point, remote access to subprogram types have been -- expanded to their E_Record_Type representation, and we need to -- go back to the original access type definition using the -- Corresponding_Remote_Type attribute in order to check that the -- designated profiles match. pragma Assert (Ekind (Target_Type) = E_Record_Type); pragma Assert (Ekind (Opnd_Type) = E_Record_Type); Check_Subtype_Conformant (New_Id => Designated_Type (Corresponding_Remote_Type (Target_Type)), Old_Id => Designated_Type (Corresponding_Remote_Type (Opnd_Type)), Err_Loc => N); return True; -- If it was legal in the generic, it's legal in the instance elsif In_Instance_Body then return True; -- If both are tagged types, check legality of view conversions elsif Is_Tagged_Type (Target_Type) and then Is_Tagged_Type (Opnd_Type) then return Valid_Tagged_Conversion (Target_Type, Opnd_Type); -- Types derived from the same root type are convertible elsif Root_Type (Target_Type) = Root_Type (Opnd_Type) then return True; -- In an instance or an inlined body, there may be inconsistent views of -- the same type, or of types derived from a common root. elsif (In_Instance or In_Inlined_Body) and then Root_Type (Underlying_Type (Target_Type)) = Root_Type (Underlying_Type (Opnd_Type)) then return True; -- Special check for common access type error case elsif Ekind (Target_Type) = E_Access_Type and then Is_Access_Type (Opnd_Type) then Conversion_Error_N ("target type must be general access type!", N); Conversion_Error_NE -- CODEFIX ("add ALL to }!", N, Target_Type); return False; -- Here we have a real conversion error else Conversion_Error_NE ("invalid conversion, not compatible with }", N, Opnd_Type); return False; end if; end Valid_Conversion; end Sem_Res;
apple-oss-distributions/old_ncurses
Ada
36,713
adb
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding -- -- -- -- Terminal_Interface.Curses.Forms -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: Juergen Pfeifer <[email protected]> 1996 -- Version Control: -- $Revision: 1.1.1.1 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Ada.Unchecked_Deallocation; with Ada.Unchecked_Conversion; with Interfaces.C; use Interfaces.C; with Interfaces.C.Strings; use Interfaces.C.Strings; with Interfaces.C.Pointers; with Terminal_Interface.Curses.Aux; package body Terminal_Interface.Curses.Forms is use Terminal_Interface.Curses.Aux; type C_Field_Array is array (Natural range <>) of aliased Field; package F_Array is new Interfaces.C.Pointers (Natural, Field, C_Field_Array, Null_Field); ------------------------------------------------------------------------------ -- | -- | -- | -- subtype chars_ptr is Interfaces.C.Strings.chars_ptr; function FOS_2_CInt is new Ada.Unchecked_Conversion (Field_Option_Set, C_Int); function CInt_2_FOS is new Ada.Unchecked_Conversion (C_Int, Field_Option_Set); function FrmOS_2_CInt is new Ada.Unchecked_Conversion (Form_Option_Set, C_Int); function CInt_2_FrmOS is new Ada.Unchecked_Conversion (C_Int, Form_Option_Set); procedure Request_Name (Key : in Form_Request_Code; Name : out String) is function Form_Request_Name (Key : C_Int) return chars_ptr; pragma Import (C, Form_Request_Name, "form_request_name"); begin Fill_String (Form_Request_Name (C_Int (Key)), Name); end Request_Name; function Request_Name (Key : Form_Request_Code) return String is function Form_Request_Name (Key : C_Int) return chars_ptr; pragma Import (C, Form_Request_Name, "form_request_name"); begin return Fill_String (Form_Request_Name (C_Int (Key))); end Request_Name; ------------------------------------------------------------------------------ -- | -- | -- | -- | -- |===================================================================== -- | man page form_field_new.3x -- |===================================================================== -- | -- | -- | function Create (Height : Line_Count; Width : Column_Count; Top : Line_Position; Left : Column_Position; Off_Screen : Natural := 0; More_Buffers : Buffer_Number := Buffer_Number'First) return Field is function Newfield (H, W, T, L, O, M : C_Int) return Field; pragma Import (C, Newfield, "new_field"); Fld : constant Field := Newfield (C_Int (Height), C_Int (Width), C_Int (Top), C_Int (Left), C_Int (Off_Screen), C_Int (More_Buffers)); begin if Fld = Null_Field then raise Form_Exception; end if; return Fld; end Create; -- | -- | -- | procedure Delete (Fld : in out Field) is function Free_Field (Fld : Field) return C_Int; pragma Import (C, Free_Field, "free_field"); Res : Eti_Error; begin Res := Free_Field (Fld); if Res /= E_Ok then Eti_Exception (Res); end if; Fld := Null_Field; end Delete; -- | -- | -- | function Duplicate (Fld : Field; Top : Line_Position; Left : Column_Position) return Field is function Dup_Field (Fld : Field; Top : C_Int; Left : C_Int) return Field; pragma Import (C, Dup_Field, "dup_field"); F : constant Field := Dup_Field (Fld, C_Int (Top), C_Int (Left)); begin if F = Null_Field then raise Form_Exception; end if; return F; end Duplicate; -- | -- | -- | function Link (Fld : Field; Top : Line_Position; Left : Column_Position) return Field is function Lnk_Field (Fld : Field; Top : C_Int; Left : C_Int) return Field; pragma Import (C, Lnk_Field, "link_field"); F : constant Field := Lnk_Field (Fld, C_Int (Top), C_Int (Left)); begin if F = Null_Field then raise Form_Exception; end if; return F; end Link; -- | -- |===================================================================== -- | man page form_field_just.3x -- |===================================================================== -- | -- | -- | procedure Set_Justification (Fld : in Field; Just : in Field_Justification := None) is function Set_Field_Just (Fld : Field; Just : C_Int) return C_Int; pragma Import (C, Set_Field_Just, "set_field_just"); Res : constant Eti_Error := Set_Field_Just (Fld, C_Int (Field_Justification'Pos (Just))); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Justification; -- | -- | -- | function Get_Justification (Fld : Field) return Field_Justification is function Field_Just (Fld : Field) return C_Int; pragma Import (C, Field_Just, "field_just"); begin return Field_Justification'Val (Field_Just (Fld)); end Get_Justification; -- | -- |===================================================================== -- | man page form_field_buffer.3x -- |===================================================================== -- | -- | -- | procedure Set_Buffer (Fld : in Field; Buffer : in Buffer_Number := Buffer_Number'First; Str : in String) is type Char_Ptr is access all Interfaces.C.char; function Set_Fld_Buffer (Fld : Field; Bufnum : C_Int; S : Char_Ptr) return C_Int; pragma Import (C, Set_Fld_Buffer, "set_field_buffer"); Txt : char_array (0 .. Str'Length); Len : size_t; Res : Eti_Error; begin To_C (Str, Txt, Len); Res := Set_Fld_Buffer (Fld, C_Int (Buffer), Txt (Txt'First)'Access); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Buffer; -- | -- | -- | procedure Get_Buffer (Fld : in Field; Buffer : in Buffer_Number := Buffer_Number'First; Str : out String) is function Field_Buffer (Fld : Field; B : C_Int) return chars_ptr; pragma Import (C, Field_Buffer, "field_buffer"); begin Fill_String (Field_Buffer (Fld, C_Int (Buffer)), Str); end Get_Buffer; function Get_Buffer (Fld : in Field; Buffer : in Buffer_Number := Buffer_Number'First) return String is function Field_Buffer (Fld : Field; B : C_Int) return chars_ptr; pragma Import (C, Field_Buffer, "field_buffer"); begin return Fill_String (Field_Buffer (Fld, C_Int (Buffer))); end Get_Buffer; -- | -- | -- | procedure Set_Status (Fld : in Field; Status : in Boolean := True) is function Set_Fld_Status (Fld : Field; St : C_Int) return C_Int; pragma Import (C, Set_Fld_Status, "set_field_status"); Res : constant Eti_Error := Set_Fld_Status (Fld, Boolean'Pos (Status)); begin if Res /= E_Ok then raise Form_Exception; end if; end Set_Status; -- | -- | -- | function Changed (Fld : Field) return Boolean is function Field_Status (Fld : Field) return C_Int; pragma Import (C, Field_Status, "field_status"); Res : constant C_Int := Field_Status (Fld); begin if Res = Curses_False then return False; else return True; end if; end Changed; -- | -- | -- | procedure Set_Maximum_Size (Fld : in Field; Max : in Natural := 0) is function Set_Field_Max (Fld : Field; M : C_Int) return C_Int; pragma Import (C, Set_Field_Max, "set_max_field"); Res : constant Eti_Error := Set_Field_Max (Fld, C_Int (Max)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Maximum_Size; -- | -- |===================================================================== -- | man page form_field_opts.3x -- |===================================================================== -- | -- | -- | procedure Set_Options (Fld : in Field; Options : in Field_Option_Set) is function Set_Field_Opts (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Set_Field_Opts, "set_field_opts"); Opt : C_Int := FOS_2_CInt (Options); Res : Eti_Error; begin Res := Set_Field_Opts (Fld, Opt); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Options; -- | -- | -- | procedure Switch_Options (Fld : in Field; Options : in Field_Option_Set; On : Boolean := True) is function Field_Opts_On (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Field_Opts_On, "field_opts_on"); function Field_Opts_Off (Fld : Field; Opt : C_Int) return C_Int; pragma Import (C, Field_Opts_Off, "field_opts_off"); Err : Eti_Error; Opt : C_Int := FOS_2_CInt (Options); begin if On then Err := Field_Opts_On (Fld, Opt); else Err := Field_Opts_Off (Fld, Opt); end if; if Err /= E_Ok then Eti_Exception (Err); end if; end Switch_Options; -- | -- | -- | procedure Get_Options (Fld : in Field; Options : out Field_Option_Set) is function Field_Opts (Fld : Field) return C_Int; pragma Import (C, Field_Opts, "field_opts"); Res : C_Int := Field_Opts (Fld); begin Options := CInt_2_FOS (Res); end Get_Options; -- | -- | -- | function Get_Options (Fld : Field := Null_Field) return Field_Option_Set is Fos : Field_Option_Set; begin Get_Options (Fld, Fos); return Fos; end Get_Options; -- | -- |===================================================================== -- | man page form_field_attributes.3x -- |===================================================================== -- | -- | -- | procedure Set_Foreground (Fld : in Field; Fore : in Character_Attribute_Set := Normal_Video; Color : in Color_Pair := Color_Pair'First) is function Set_Field_Fore (Fld : Field; Attr : C_Chtype) return C_Int; pragma Import (C, Set_Field_Fore, "set_field_fore"); Ch : constant Attributed_Character := (Ch => Character'First, Color => Color, Attr => Fore); Res : constant Eti_Error := Set_Field_Fore (Fld, AttrChar_To_Chtype (Ch)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Foreground; -- | -- | -- | procedure Foreground (Fld : in Field; Fore : out Character_Attribute_Set) is function Field_Fore (Fld : Field) return C_Chtype; pragma Import (C, Field_Fore, "field_fore"); begin Fore := Chtype_To_AttrChar (Field_Fore (Fld)).Attr; end Foreground; procedure Foreground (Fld : in Field; Fore : out Character_Attribute_Set; Color : out Color_Pair) is function Field_Fore (Fld : Field) return C_Chtype; pragma Import (C, Field_Fore, "field_fore"); begin Fore := Chtype_To_AttrChar (Field_Fore (Fld)).Attr; Color := Chtype_To_AttrChar (Field_Fore (Fld)).Color; end Foreground; -- | -- | -- | procedure Set_Background (Fld : in Field; Back : in Character_Attribute_Set := Normal_Video; Color : in Color_Pair := Color_Pair'First) is function Set_Field_Back (Fld : Field; Attr : C_Chtype) return C_Int; pragma Import (C, Set_Field_Back, "set_field_back"); Ch : constant Attributed_Character := (Ch => Character'First, Color => Color, Attr => Back); Res : constant Eti_Error := Set_Field_Back (Fld, AttrChar_To_Chtype (Ch)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Background; -- | -- | -- | procedure Background (Fld : in Field; Back : out Character_Attribute_Set) is function Field_Back (Fld : Field) return C_Chtype; pragma Import (C, Field_Back, "field_back"); begin Back := Chtype_To_AttrChar (Field_Back (Fld)).Attr; end Background; procedure Background (Fld : in Field; Back : out Character_Attribute_Set; Color : out Color_Pair) is function Field_Back (Fld : Field) return C_Chtype; pragma Import (C, Field_Back, "field_back"); begin Back := Chtype_To_AttrChar (Field_Back (Fld)).Attr; Color := Chtype_To_AttrChar (Field_Back (Fld)).Color; end Background; -- | -- | -- | procedure Set_Pad_Character (Fld : in Field; Pad : in Character := Space) is function Set_Field_Pad (Fld : Field; Ch : C_Int) return C_Int; pragma Import (C, Set_Field_Pad, "set_field_pad"); Res : constant Eti_Error := Set_Field_Pad (Fld, C_Int (Character'Pos (Pad))); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Pad_Character; -- | -- | -- | procedure Pad_Character (Fld : in Field; Pad : out Character) is function Field_Pad (Fld : Field) return C_Int; pragma Import (C, Field_Pad, "field_pad"); begin Pad := Character'Val (Field_Pad (Fld)); end Pad_Character; -- | -- |===================================================================== -- | man page form_field_info.3x -- |===================================================================== -- | -- | -- | procedure Info (Fld : in Field; Lines : out Line_Count; Columns : out Column_Count; First_Row : out Line_Position; First_Column : out Column_Position; Off_Screen : out Natural; Additional_Buffers : out Buffer_Number) is type C_Int_Access is access all C_Int; function Fld_Info (Fld : Field; L, C, Fr, Fc, Os, Ab : C_Int_Access) return C_Int; pragma Import (C, Fld_Info, "field_info"); L, C, Fr, Fc, Os, Ab : aliased C_Int; Res : constant Eti_Error := Fld_Info (Fld, L'Access, C'Access, Fr'Access, Fc'Access, Os'Access, Ab'Access); begin if Res /= E_Ok then Eti_Exception (Res); else Lines := Line_Count (L); Columns := Column_Count (C); First_Row := Line_Position (Fr); First_Column := Column_Position (Fc); Off_Screen := Natural (Os); Additional_Buffers := Buffer_Number (Ab); end if; end Info; -- | -- | -- | procedure Dynamic_Info (Fld : in Field; Lines : out Line_Count; Columns : out Column_Count; Max : out Natural) is type C_Int_Access is access all C_Int; function Dyn_Info (Fld : Field; L, C, M : C_Int_Access) return C_Int; pragma Import (C, Dyn_Info, "dynamic_field_info"); L, C, M : aliased C_Int; Res : constant Eti_Error := Dyn_Info (Fld, L'Access, C'Access, M'Access); begin if Res /= E_Ok then Eti_Exception (Res); else Lines := Line_Count (L); Columns := Column_Count (C); Max := Natural (M); end if; end Dynamic_Info; -- | -- |===================================================================== -- | man page form_win.3x -- |===================================================================== -- | -- | -- | procedure Set_Window (Frm : in Form; Win : in Window) is function Set_Form_Win (Frm : Form; Win : Window) return C_Int; pragma Import (C, Set_Form_Win, "set_form_win"); Res : constant Eti_Error := Set_Form_Win (Frm, Win); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Window; -- | -- | -- | function Get_Window (Frm : Form) return Window is function Form_Win (Frm : Form) return Window; pragma Import (C, Form_Win, "form_win"); W : constant Window := Form_Win (Frm); begin return W; end Get_Window; -- | -- | -- | procedure Set_Sub_Window (Frm : in Form; Win : in Window) is function Set_Form_Sub (Frm : Form; Win : Window) return C_Int; pragma Import (C, Set_Form_Sub, "set_form_sub"); Res : constant Eti_Error := Set_Form_Sub (Frm, Win); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Sub_Window; -- | -- | -- | function Get_Sub_Window (Frm : Form) return Window is function Form_Sub (Frm : Form) return Window; pragma Import (C, Form_Sub, "form_sub"); W : constant Window := Form_Sub (Frm); begin return W; end Get_Sub_Window; -- | -- | -- | procedure Scale (Frm : in Form; Lines : out Line_Count; Columns : out Column_Count) is type C_Int_Access is access all C_Int; function M_Scale (Frm : Form; Yp, Xp : C_Int_Access) return C_Int; pragma Import (C, M_Scale, "scale_form"); X, Y : aliased C_Int; Res : constant Eti_Error := M_Scale (Frm, Y'Access, X'Access); begin if Res /= E_Ok then Eti_Exception (Res); end if; Lines := Line_Count (Y); Columns := Column_Count (X); end Scale; -- | -- |===================================================================== -- | man page menu_hook.3x -- |===================================================================== -- | -- | -- | procedure Set_Field_Init_Hook (Frm : in Form; Proc : in Form_Hook_Function) is function Set_Field_Init (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Field_Init, "set_field_init"); Res : constant Eti_Error := Set_Field_Init (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Field_Init_Hook; -- | -- | -- | procedure Set_Field_Term_Hook (Frm : in Form; Proc : in Form_Hook_Function) is function Set_Field_Term (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Field_Term, "set_field_term"); Res : constant Eti_Error := Set_Field_Term (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Field_Term_Hook; -- | -- | -- | procedure Set_Form_Init_Hook (Frm : in Form; Proc : in Form_Hook_Function) is function Set_Form_Init (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Form_Init, "set_form_init"); Res : constant Eti_Error := Set_Form_Init (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Form_Init_Hook; -- | -- | -- | procedure Set_Form_Term_Hook (Frm : in Form; Proc : in Form_Hook_Function) is function Set_Form_Term (Frm : Form; Proc : Form_Hook_Function) return C_Int; pragma Import (C, Set_Form_Term, "set_form_term"); Res : constant Eti_Error := Set_Form_Term (Frm, Proc); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Form_Term_Hook; -- | -- |===================================================================== -- | man page form_fields.3x -- |===================================================================== -- | -- | -- | procedure Redefine (Frm : in Form; Flds : in Field_Array_Access) is function Set_Frm_Fields (Frm : Form; Items : System.Address) return C_Int; pragma Import (C, Set_Frm_Fields, "set_form_fields"); Res : Eti_Error; begin pragma Assert (Flds (Flds'Last) = Null_Field); if Flds (Flds'Last) /= Null_Field then raise Form_Exception; else Res := Set_Frm_Fields (Frm, Flds (Flds'First)'Address); if Res /= E_Ok then Eti_Exception (Res); end if; end if; end Redefine; -- | -- | -- | function Fields (Frm : Form; Index : Positive) return Field is use F_Array; function C_Fields (Frm : Form) return Pointer; pragma Import (C, C_Fields, "form_fields"); P : Pointer := C_Fields (Frm); begin if P = null or else Index not in 1 .. Field_Count (Frm) then raise Form_Exception; else P := P + ptrdiff_t (C_Int (Index) - 1); return P.all; end if; end Fields; -- | -- | -- | function Field_Count (Frm : Form) return Natural is function Count (Frm : Form) return C_Int; pragma Import (C, Count, "field_count"); begin return Natural (Count (Frm)); end Field_Count; -- | -- | -- | procedure Move (Fld : in Field; Line : in Line_Position; Column : in Column_Position) is function Move (Fld : Field; L, C : C_Int) return C_Int; pragma Import (C, Move, "move_field"); Res : constant Eti_Error := Move (Fld, C_Int (Line), C_Int (Column)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Move; -- | -- |===================================================================== -- | man page form_new.3x -- |===================================================================== -- | -- | -- | function Create (Fields : Field_Array_Access) return Form is function NewForm (Fields : System.Address) return Form; pragma Import (C, NewForm, "new_form"); M : Form; begin pragma Assert (Fields (Fields'Last) = Null_Field); if Fields (Fields'Last) /= Null_Field then raise Form_Exception; else M := NewForm (Fields (Fields'First)'Address); if M = Null_Form then raise Form_Exception; end if; return M; end if; end Create; -- | -- | -- | procedure Delete (Frm : in out Form) is function Free (Frm : Form) return C_Int; pragma Import (C, Free, "free_form"); Res : constant Eti_Error := Free (Frm); begin if Res /= E_Ok then Eti_Exception (Res); end if; Frm := Null_Form; end Delete; -- | -- |===================================================================== -- | man page form_opts.3x -- |===================================================================== -- | -- | -- | procedure Set_Options (Frm : in Form; Options : in Form_Option_Set) is function Set_Form_Opts (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Set_Form_Opts, "set_form_opts"); Opt : C_Int := FrmOS_2_CInt (Options); Res : Eti_Error; begin Res := Set_Form_Opts (Frm, Opt); if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Options; -- | -- | -- | procedure Switch_Options (Frm : in Form; Options : in Form_Option_Set; On : Boolean := True) is function Form_Opts_On (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Form_Opts_On, "form_opts_on"); function Form_Opts_Off (Frm : Form; Opt : C_Int) return C_Int; pragma Import (C, Form_Opts_Off, "form_opts_off"); Err : Eti_Error; Opt : C_Int := FrmOS_2_CInt (Options); begin if On then Err := Form_Opts_On (Frm, Opt); else Err := Form_Opts_Off (Frm, Opt); end if; if Err /= E_Ok then Eti_Exception (Err); end if; end Switch_Options; -- | -- | -- | procedure Get_Options (Frm : in Form; Options : out Form_Option_Set) is function Form_Opts (Frm : Form) return C_Int; pragma Import (C, Form_Opts, "form_opts"); Res : C_Int := Form_Opts (Frm); begin Options := CInt_2_FrmOS (Res); end Get_Options; -- | -- | -- | function Get_Options (Frm : Form := Null_Form) return Form_Option_Set is Fos : Form_Option_Set; begin Get_Options (Frm, Fos); return Fos; end Get_Options; -- | -- |===================================================================== -- | man page form_post.3x -- |===================================================================== -- | -- | -- | procedure Post (Frm : in Form; Post : in Boolean := True) is function M_Post (Frm : Form) return C_Int; pragma Import (C, M_Post, "post_form"); function M_Unpost (Frm : Form) return C_Int; pragma Import (C, M_Unpost, "unpost_form"); Res : Eti_Error; begin if Post then Res := M_Post (Frm); else Res := M_Unpost (Frm); end if; if Res /= E_Ok then Eti_Exception (Res); end if; end Post; -- | -- |===================================================================== -- | man page form_cursor.3x -- |===================================================================== -- | -- | -- | procedure Position_Cursor (Frm : Form) is function Pos_Form_Cursor (Frm : Form) return C_Int; pragma Import (C, Pos_Form_Cursor, "pos_form_cursor"); Res : constant Eti_Error := Pos_Form_Cursor (Frm); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Position_Cursor; -- | -- |===================================================================== -- | man page form_data.3x -- |===================================================================== -- | -- | -- | function Data_Ahead (Frm : Form) return Boolean is function Ahead (Frm : Form) return C_Int; pragma Import (C, Ahead, "data_ahead"); Res : constant C_Int := Ahead (Frm); begin if Res = Curses_False then return False; else return True; end if; end Data_Ahead; -- | -- | -- | function Data_Behind (Frm : Form) return Boolean is function Behind (Frm : Form) return C_Int; pragma Import (C, Behind, "data_behind"); Res : constant C_Int := Behind (Frm); begin if Res = Curses_False then return False; else return True; end if; end Data_Behind; -- | -- |===================================================================== -- | man page form_driver.3x -- |===================================================================== -- | -- | -- | function Driver (Frm : Form; Key : Key_Code) return Driver_Result is function Frm_Driver (Frm : Form; Key : C_Int) return C_Int; pragma Import (C, Frm_Driver, "form_driver"); R : Eti_Error := Frm_Driver (Frm, C_Int (Key)); begin if R /= E_Ok then if R = E_Unknown_Command then return Unknown_Request; elsif R = E_Invalid_Field then return Invalid_Field; elsif R = E_Request_Denied then return Request_Denied; else Eti_Exception (R); return Form_Ok; end if; else return Form_Ok; end if; end Driver; -- | -- |===================================================================== -- | man page form_page.3x -- |===================================================================== -- | -- | -- | procedure Set_Current (Frm : in Form; Fld : in Field) is function Set_Current_Fld (Frm : Form; Fld : Field) return C_Int; pragma Import (C, Set_Current_Fld, "set_current_field"); Res : constant Eti_Error := Set_Current_Fld (Frm, Fld); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Current; -- | -- | -- | function Current (Frm : in Form) return Field is function Current_Fld (Frm : Form) return Field; pragma Import (C, Current_Fld, "current_field"); Fld : constant Field := Current_Fld (Frm); begin if Fld = Null_Field then raise Form_Exception; end if; return Fld; end Current; -- | -- | -- | procedure Set_Page (Frm : in Form; Page : in Page_Number := Page_Number'First) is function Set_Frm_Page (Frm : Form; Pg : C_Int) return C_Int; pragma Import (C, Set_Frm_Page, "set_form_page"); Res : constant Eti_Error := Set_Frm_Page (Frm, C_Int (Page)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_Page; -- | -- | -- | function Page (Frm : Form) return Page_Number is function Get_Page (Frm : Form) return C_Int; pragma Import (C, Get_Page, "form_page"); P : constant C_Int := Get_Page (Frm); begin if P < 0 then raise Form_Exception; else return Page_Number (P); end if; end Page; function Get_Index (Fld : Field) return Positive is function Get_Fieldindex (Fld : Field) return C_Int; pragma Import (C, Get_Fieldindex, "field_index"); Res : constant C_Int := Get_Fieldindex (Fld); begin if Res = Curses_Err then raise Form_Exception; end if; return Positive (Natural (Res) + Positive'First); end Get_Index; -- | -- |===================================================================== -- | man page form_new_page.3x -- |===================================================================== -- | -- | -- | procedure Set_New_Page (Fld : in Field; New_Page : in Boolean := True) is function Set_Page (Fld : Field; Flg : C_Int) return C_Int; pragma Import (C, Set_Page, "set_new_page"); Res : constant Eti_Error := Set_Page (Fld, Boolean'Pos (New_Page)); begin if Res /= E_Ok then Eti_Exception (Res); end if; end Set_New_Page; -- | -- | -- | function Is_New_Page (Fld : Field) return Boolean is function Is_New (Fld : Field) return C_Int; pragma Import (C, Is_New, "new_page"); Res : constant C_Int := Is_New (Fld); begin if Res = Curses_False then return False; else return True; end if; end Is_New_Page; procedure Free (FA : in out Field_Array_Access; Free_Fields : in Boolean := False) is procedure Release is new Ada.Unchecked_Deallocation (Field_Array, Field_Array_Access); begin if FA /= null and then Free_Fields then for I in FA'First .. (FA'Last - 1) loop if (FA (I) /= Null_Field) then Delete (FA (I)); end if; end loop; end if; Release (FA); end Free; -- |===================================================================== function Default_Field_Options return Field_Option_Set is begin return Get_Options (Null_Field); end Default_Field_Options; function Default_Form_Options return Form_Option_Set is begin return Get_Options (Null_Form); end Default_Form_Options; end Terminal_Interface.Curses.Forms;
HeisenbugLtd/cache-sim
Ada
6,297
ads
------------------------------------------------------------------------------ -- Copyright (C) 2012-2020 by Heisenbug Ltd. -- -- This work is free. You can redistribute it and/or modify it under the -- terms of the Do What The Fuck You Want To Public License, Version 2, -- as published by Sam Hocevar. See the LICENSE file for more details. -------------------------------------------------------------------------------- pragma License (Unrestricted); -------------------------------------------------------------------------------- -- -- Caches provides basic types for the implementation of simulating cache -- behaviour in computer systems. -- -- Here, the basic data types are declared. -- -- An abstract class is introduced which provides the interface to the usual -- operations expected for a cache (initialization, read, write, flush) plus -- some house-keeping methods (performance counter reset, information -- extraction and provision of an overall performance indicator). -- -------------------------------------------------------------------------------------------------------------------------------------------------------------- package Caches is pragma Preelaborate; -- Provide some basic constants. KI_BYTE : constant := 2 ** 10; MI_BYTE : constant := 2 ** 20; GI_BYTE : constant := 2 ** 30; -- Basic types representing addresses and indices. type Unsigned is range 0 .. 2 ** 32 - 1; type Address is new Unsigned; -- Counter for several purposes. type Count is new Unsigned; -- Representation of non-null bit lengths and their respective ranges. subtype Bit_Number is Natural range 0 .. 32; subtype Bytes is Unsigned range 2 ** Bit_Number'First .. 2 ** Bit_Number'Last - 1; -- Subtypes for maximum supported cache line lengths, associativity, and -- cache sizes. subtype Line_Length is Bytes range Bytes'First .. 1 * KI_BYTE; subtype Associativity is Bytes range Bytes'First .. 1 * KI_BYTE; subtype Full_Size is Bytes range Bytes'First .. 2 * GI_BYTE; -- Info about the dynamic behaviour of a specific cache (cache event -- counter). type Event_Info is record Reads : Count; Writes : Count; Lines_Fetched : Count; Lines_Flushed : Count; Hits : Count; Misses : Count; end record; -- Info about the static properties (configuration) of a cache. type Configuration is record Cache_Line : Line_Length; -- Length of a single cache line. Association : Associativity; -- Number of entries per slot. Num_Blocks : Full_Size; -- # of cache block. Cache_Size : Full_Size; -- Cache size. Speed_Factor : Long_Float; -- Speed factor compared to next level. end record; type Cache is abstract tagged limited private; type Cache_Ptr is access all Cache'Class; -- Primitive operation of all sort of caches. ----------------------------------------------------------------------------- -- Initialize -- -- Initializes the given cache. Result is a cold, empty cache. ----------------------------------------------------------------------------- procedure Initialize (This : in out Cache) is abstract; ----------------------------------------------------------------------------- -- Flush -- -- Flushes the given cache. Collected performance data is not erased. If -- Recursive is True, any connected sub-level cache will be flushed, too. ----------------------------------------------------------------------------- procedure Flush (This : in out Cache; Recursive : in Boolean := True) is abstract; ----------------------------------------------------------------------------- -- Reset -- -- Resets the performance data of the cache. It has no effect on the current -- cache's state. If Recursive is True, applies to any connected sub-level -- cache, too. ----------------------------------------------------------------------------- procedure Reset (This : in out Cache; Recursive : in Boolean := True) is abstract; ----------------------------------------------------------------------------- -- Read -- -- Simulates a read access to the given address. ----------------------------------------------------------------------------- procedure Read (This : in out Cache; Where : in Address) is abstract; ----------------------------------------------------------------------------- -- Write -- -- Simulates a write access to the given address. ----------------------------------------------------------------------------- procedure Write (This : in out Cache; Where : in Address) is abstract; ----------------------------------------------------------------------------- -- Perf_Index -- -- Returns a float value representing the performance of the cache This. If -- Recursive is True, any connected cache's performance value is added to -- the performance value after correcting it via the appropriate speed -- factor. ----------------------------------------------------------------------------- function Perf_Index (This : in Cache; Recursive : in Boolean := True) return Long_Float is abstract; -- Class wide operations ----------------------------------------------------------------------------- -- Info -- -- Returns the dynamic performance info record of the given cache. ----------------------------------------------------------------------------- function Info (This : in Cache'Class) return Event_Info; ----------------------------------------------------------------------------- -- Info -- -- Returns the static configuration info record of the given cache. ----------------------------------------------------------------------------- function Info (This : in Cache'Class) return Configuration; private type Cache is abstract tagged limited record Config : Configuration; Events : Event_Info; end record; end Caches;
BrickBot/Bound-T-H8-300
Ada
6,078
ads
-- Storage.Cell_Numbering (decl) -- -- Numbering cells in a cell-set consecutively, for purposes of -- using this subset of cells as indices in arrays. -- -- A component of the Bound-T Worst-Case Execution Time Tool. -- ------------------------------------------------------------------------------- -- Copyright (c) 1999 .. 2015 Tidorum Ltd -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, this -- list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright notice, -- this list of conditions and the following disclaimer in the documentation -- and/or other materials provided with the distribution. -- -- 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. -- -- Other modules (files) of this software composition should contain their -- own copyright statements, which may have different copyright and usage -- conditions. The above conditions apply to this file. ------------------------------------------------------------------------------- -- -- $Revision: 1.6 $ -- $Date: 2015/10/24 19:36:52 $ -- -- $Log: storage-cell_numbering.ads,v $ -- Revision 1.6 2015/10/24 19:36:52 niklas -- Moved to free licence. -- -- Revision 1.5 2009-10-07 19:26:10 niklas -- BT-CH-0183: Cell-sets are a tagged-type class. -- -- Revision 1.4 2007/04/18 18:34:39 niklas -- BT-CH-0057. -- -- Revision 1.3 2007/03/29 15:18:04 niklas -- BT-CH-0056. -- -- Revision 1.2 2005/02/16 21:11:49 niklas -- BT-CH-0002. -- -- Revision 1.1 2004/04/25 09:33:23 niklas -- First version. -- --:dbpool with GNAT.Debug_Pools; package Storage.Cell_Numbering is type Number_T is new Natural; -- -- A number assigned to a cell, except that zero is not assigned -- to any cell. Numbering starts at one. type Map_T is private; -- -- Assigns consecutive numbers of type Number_T, starting from 1, -- to a given subset of cells, and assigns no number to the other -- cells. -- -- The order of numbering may be arbitrary with respect to the -- indices (Cell_Index_T) of the cells, or it may be somehow -- related to the indices, for example numbering the cells in -- order of increasing index. This depends on the method used to -- traverse the set of cells when the numbering is created, which -- may in turn depend on the implementation of the cell-set. -- -- Objects of this type may contain dynamically assigned -- memory and should be Discarded (see below) when no longer -- needed. Not_Numbered : exception; -- -- Raised if there is a request for the number of a cell -- that is not in the subset of numbered cells under the -- given map. function Map (Cells : Cell_Set_T) return Map_T; -- -- The map that assigns consecutive numbers to all the Cells -- in the given set, and assigns no number to the other cells -- (including cells that are created afterwards). function Numbered (Cell : Cell_T; Under : Map_T) return Boolean; -- -- Whether the Cell is numbered Under a given map. function Number (Cell : Cell_T; Under : Map_T) return Number_T; -- -- The number of the given Cell, Under the given map. -- Raises Not_Numbered if the cell is not numbered. function First (Under : Map_T) return Number_T; function Last (Under : Map_T) return Number_T; -- -- The range of numbers assigned to cells Unde the given -- map is First(Under) .. Last (Under). procedure Discard (Map : in out Map_T); -- -- Discards the map, deallocating any dynamically allocated -- memory it uses. type List_T is array (Number_T range <>) of Cell_T; -- -- An inverse map from numbers to cells. function Inverse (Map : Map_T) return List_T; -- -- The inverse map, listing the cells in numbering order. -- If the result is L, then L'Range = First(Map) .. Last(Map) and -- for each N in L'Range, Number(Cell => L(N), Under => Map) = N. procedure Show (Map : in Map_T); -- -- Displays the cell numbering Map on standard output. private No_Number : constant Number_T := 0; -- -- The "number" given a cell that is has no number (is not -- in the subset of cells that are numbered). type Numbers_T is array (Cell_Index_T range <>) of Number_T; -- -- The number for each cell, or zero if no number assigned. type Numbers_Ref is access Numbers_T; --:dbpool Numbers_Pool : GNAT.Debug_Pools.Debug_Pool; --:dbpool for Numbers_Ref'Storage_Pool use Numbers_Pool; type Map_T is record Last : Number_T; Numbers : Numbers_Ref; end record; -- -- A numbering of cells, valid for cells with indices from -- Numbers'range. For other cells, no number is assigned. -- -- The number for a cell with index i is Numbers(i), unless -- this is No_Number which means that the cell is not -- numbered. -- -- The numbers in use are 1 .. Last. -- -- The numbering may be arbitrary with respect to the cell -- index, or may have some relationship to the cell index, -- for example numbering cells in ascending index order. end Storage.Cell_Numbering;
cktkw/synth
Ada
60,706
adb
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt with Ada.Strings.Hash; with Ada.Calendar.Formatting; with GNAT.Regpat; with GNAT.String_Split; with Signals; with Unix; package body PortScan is package ACF renames Ada.Calendar.Formatting; package RGX renames GNAT.Regpat; package GSS renames GNAT.String_Split; package SIG renames Signals; ------------------------------ -- scan_entire_ports_tree -- ------------------------------ function scan_entire_ports_tree (portsdir : String) return Boolean is good_scan : Boolean; using_screen : constant Boolean := Unix.screen_attached; begin -- tree must be already mounted in the scan slave. -- However, prescan works on the real ports tree, not the mount. if not prescanned then read_flavor_index; end if; scan_start := CAL.Clock; parallel_deep_scan (success => good_scan, show_progress => using_screen); scan_stop := CAL.Clock; return good_scan; end scan_entire_ports_tree; ------------------------ -- scan_single_port -- ------------------------ function scan_single_port (catport : String; always_build : Boolean; fatal : out Boolean) return Boolean is xports : constant String := JT.USS (PM.configuration.dir_buildbase) & ss_base & dir_ports; procedure dig (cursor : block_crate.Cursor); target : port_index; aborted : Boolean := False; indy500 : Boolean := False; uscatport : JT.Text := JT.SUS (catport); procedure dig (cursor : block_crate.Cursor) is new_target : port_index := block_crate.Element (cursor); begin if not aborted then if all_ports (new_target).scan_locked then -- We've already seen this (circular dependency) raise circular_logic; end if; if not all_ports (new_target).scanned then populate_port_data (new_target); all_ports (new_target).scan_locked := True; all_ports (new_target).blocked_by.Iterate (dig'Access); all_ports (new_target).scan_locked := False; if indy500 then TIO.Put_Line ("... backtrace " & get_catport (all_ports (new_target))); end if; end if; end if; exception when issue : nonexistent_port => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency could " & "not be located."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : bmake_execution => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because 'make' encounted " & "an error in the Makefile."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : make_garbage => aborted := True; TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted because dependency is malformed."); TIO.Put_Line (EX.Exception_Message (issue)); when issue : circular_logic => aborted := True; indy500 := True; TIO.Put_Line (LAT.LF & catport & " scan aborted because a circular dependency on " & get_catport (all_ports (new_target)) & " was detected."); when issue : others => aborted := True; declare why : constant String := obvious_problem (xports, get_catport (all_ports (new_target))); begin if why = "" then TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted for an unknown reason."); TIO.Put_Line (EX.Exception_Message (issue)); else TIO.Put_Line (LAT.LF & get_catport (all_ports (new_target)) & " scan aborted" & why); end if; end; end dig; begin fatal := False; if not AD.Exists (xports & "/" & JT.part_1 (catport, "@") & "/Makefile") then return False; end if; if not prescanned then read_flavor_index; end if; if ports_keys.Contains (Key => uscatport) then target := ports_keys.Element (Key => uscatport); else return False; end if; begin if all_ports (target).scanned then -- This can happen when a dependency is also on the build list. return True; else populate_port_data (target); all_ports (target).never_remote := always_build; end if; exception when issue : others => TIO.Put ("Encountered issue with " & catport & " or its dependencies" & LAT.LF & " => "); TIO.Put_Line (EX.Exception_Message (issue)); return False; end; all_ports (target).scan_locked := True; all_ports (target).blocked_by.Iterate (dig'Access); all_ports (target).scan_locked := False; if indy500 then TIO.Put_Line ("... backtrace " & catport); fatal := True; end if; return not aborted; end scan_single_port; -------------------------- -- set_build_priority -- -------------------------- procedure set_build_priority is begin iterate_reverse_deps; iterate_drill_down; end set_build_priority; ------------------------ -- reset_ports_tree -- ------------------------ procedure reset_ports_tree is PR : port_record_access; begin for k in dim_all_ports'Range loop PR := all_ports (k)'Access; PR.sequence_id := 0; PR.key_cursor := portkey_crate.No_Element; PR.jobs := 1; PR.ignore_reason := JT.blank; PR.port_version := JT.blank; PR.package_name := JT.blank; PR.pkg_dep_query := JT.blank; PR.ignored := False; PR.scanned := False; PR.rev_scanned := False; PR.unlist_failed := False; PR.work_locked := False; PR.scan_locked := False; PR.pkg_present := False; PR.remote_pkg := False; PR.never_remote := False; PR.deletion_due := False; PR.use_procfs := False; PR.use_linprocfs := False; PR.reverse_score := 0; PR.min_librun := 0; PR.librun.Clear; PR.blocks.Clear; PR.blocked_by.Clear; PR.all_reverse.Clear; PR.options.Clear; PR.flavors.Clear; end loop; ports_keys.Clear; rank_queue.Clear; lot_number := 1; lot_counter := 0; last_port := 0; prescanned := False; wipe_make_queue; for m in scanners'Range loop mq_progress (m) := 0; end loop; end reset_ports_tree; -- PRIVATE FUNCTIONS -- -------------------------- -- iterate_drill_down -- -------------------------- procedure iterate_drill_down is begin rank_queue.Clear; for port in port_index'First .. last_port loop if all_ports (port).scanned then drill_down (next_target => port, original_target => port); declare ndx : constant port_index := port_index (all_ports (port).reverse_score); QR : constant queue_record := (ap_index => port, reverse_score => ndx); begin rank_queue.Insert (New_Item => QR); end; end if; end loop; end iterate_drill_down; -------------------------- -- parallel_deep_scan -- -------------------------- procedure parallel_deep_scan (success : out Boolean; show_progress : Boolean) is finished : array (scanners) of Boolean := (others => False); combined_wait : Boolean := True; aborted : Boolean := False; task type scan (lot : scanners); task body scan is procedure populate (cursor : subqueue.Cursor); procedure abort_now (culprit, issue_msg, exmsg : String); procedure populate (cursor : subqueue.Cursor) is target_port : port_index := subqueue.Element (cursor); begin if not aborted then populate_port_data (target_port); mq_progress (lot) := mq_progress (lot) + 1; end if; exception when issue : nonexistent_port => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because dependency could not be located", exmsg => EX.Exception_Message (issue)); when issue : bmake_execution => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because 'make' encounted an error in the Makefile", exmsg => EX.Exception_Message (issue)); when issue : make_garbage => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "because dependency is malformed", exmsg => EX.Exception_Message (issue)); when issue : others => abort_now (culprit => get_catport (all_ports (target_port)), issue_msg => "for an unknown reason", exmsg => EX.Exception_Message (issue)); end populate; procedure abort_now (culprit, issue_msg, exmsg : String) is begin aborted := True; TIO.Put_Line (LAT.LF & "culprit: " & culprit); TIO.Put_Line (" Scan aborted " & issue_msg & "."); TIO.Put_Line (" " & exmsg); end abort_now; begin make_queue (lot).Iterate (populate'Access); finished (lot) := True; end scan; scan_01 : scan (lot => 1); scan_02 : scan (lot => 2); scan_03 : scan (lot => 3); scan_04 : scan (lot => 4); scan_05 : scan (lot => 5); scan_06 : scan (lot => 6); scan_07 : scan (lot => 7); scan_08 : scan (lot => 8); scan_09 : scan (lot => 9); scan_10 : scan (lot => 10); scan_11 : scan (lot => 11); scan_12 : scan (lot => 12); scan_13 : scan (lot => 13); scan_14 : scan (lot => 14); scan_15 : scan (lot => 15); scan_16 : scan (lot => 16); scan_17 : scan (lot => 17); scan_18 : scan (lot => 18); scan_19 : scan (lot => 19); scan_20 : scan (lot => 20); scan_21 : scan (lot => 21); scan_22 : scan (lot => 22); scan_23 : scan (lot => 23); scan_24 : scan (lot => 24); scan_25 : scan (lot => 25); scan_26 : scan (lot => 26); scan_27 : scan (lot => 27); scan_28 : scan (lot => 28); scan_29 : scan (lot => 29); scan_30 : scan (lot => 30); scan_31 : scan (lot => 31); scan_32 : scan (lot => 32); -- Expansion of cpu_range from 32 to 64 means 64 possible scanners scan_33 : scan (lot => 33); scan_34 : scan (lot => 34); scan_35 : scan (lot => 35); scan_36 : scan (lot => 36); scan_37 : scan (lot => 37); scan_38 : scan (lot => 38); scan_39 : scan (lot => 39); scan_40 : scan (lot => 40); scan_41 : scan (lot => 41); scan_42 : scan (lot => 42); scan_43 : scan (lot => 43); scan_44 : scan (lot => 44); scan_45 : scan (lot => 45); scan_46 : scan (lot => 46); scan_47 : scan (lot => 47); scan_48 : scan (lot => 48); scan_49 : scan (lot => 49); scan_50 : scan (lot => 50); scan_51 : scan (lot => 51); scan_52 : scan (lot => 52); scan_53 : scan (lot => 53); scan_54 : scan (lot => 54); scan_55 : scan (lot => 55); scan_56 : scan (lot => 56); scan_57 : scan (lot => 57); scan_58 : scan (lot => 58); scan_59 : scan (lot => 59); scan_60 : scan (lot => 60); scan_61 : scan (lot => 61); scan_62 : scan (lot => 62); scan_63 : scan (lot => 63); scan_64 : scan (lot => 64); begin TIO.Put_Line ("Scanning entire ports tree."); while combined_wait loop delay 1.0; if show_progress then TIO.Put (scan_progress); end if; combined_wait := False; for j in scanners'Range loop if not finished (j) then combined_wait := True; exit; end if; end loop; if SIG.graceful_shutdown_requested then aborted := True; end if; end loop; success := not aborted; if show_progress then TIO.Put (scan_progress); end if; end parallel_deep_scan; ----------------------- -- wipe_make_queue -- ----------------------- procedure wipe_make_queue is begin for j in scanners'Range loop make_queue (j).Clear; end loop; end wipe_make_queue; ------------------ -- drill_down -- ------------------ procedure drill_down (next_target : port_index; original_target : port_index) is PR : port_record_access := all_ports (next_target)'Access; procedure stamp_and_drill (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor); procedure slurp_scanned (cursor : block_crate.Cursor) is rev_id : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (rev_id) then all_ports (original_target).all_reverse.Insert (Key => rev_id, New_Item => rev_id); end if; end slurp_scanned; procedure stamp_and_drill (cursor : block_crate.Cursor) is pmc : port_index := block_crate.Element (Position => cursor); begin if not all_ports (original_target).all_reverse.Contains (pmc) then all_ports (original_target).all_reverse.Insert (Key => pmc, New_Item => pmc); end if; if pmc = original_target then declare top_port : constant String := get_catport (all_ports (original_target)); this_port : constant String := get_catport (all_ports (next_target)); begin raise circular_logic with top_port & " <=> " & this_port; end; end if; if not all_ports (pmc).rev_scanned then drill_down (next_target => pmc, original_target => pmc); end if; all_ports (pmc).all_reverse.Iterate (slurp_scanned'Access); end stamp_and_drill; begin if not PR.scanned then return; end if; if PR.rev_scanned then -- It is possible to get here if an earlier port scanned this port -- as a reverse dependencies return; end if; PR.blocks.Iterate (stamp_and_drill'Access); PR.reverse_score := port_index (PR.all_reverse.Length); PR.rev_scanned := True; end drill_down; ---------------------------- -- iterate_reverse_deps -- ----------------------------- procedure iterate_reverse_deps is madre : port_index; procedure set_reverse (cursor : block_crate.Cursor); procedure set_reverse (cursor : block_crate.Cursor) is begin -- Using conditional insert here causes a finalization error when -- the program exists. Reluctantly, do the condition check manually if not all_ports (block_crate.Element (cursor)).blocks.Contains (Key => madre) then all_ports (block_crate.Element (cursor)).blocks.Insert (Key => madre, New_Item => madre); end if; end set_reverse; begin for port in port_index'First .. last_port loop if all_ports (port).scanned then madre := port; all_ports (port).blocked_by.Iterate (set_reverse'Access); end if; end loop; end iterate_reverse_deps; -------------------- -- get_pkg_name -- -------------------- function get_pkg_name (origin : String) return String is function get_fullport return String; function get_fullport return String is begin -- if format is cat/port@something then -- return "cat/port FLAVOR=something" -- else -- return $catport if JT.contains (origin, "@") then return dir_ports & "/" & JT.part_1 (origin, "@") & " FLAVOR=" & JT.part_2 (origin, "@"); else return dir_ports & "/" & origin; end if; end get_fullport; fullport : constant String := get_fullport; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := ssroot & " " & chroot_make_program & " .MAKE.EXPAND_VARIABLES=yes -C " & fullport & " -VPKGFILE:T"; content : JT.Text; topline : JT.Text; status : Integer; begin -- Same command for both ports collection and pkgsrc content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with origin & " (return code =" & status'Img & ")"; end if; JT.nextline (lineblock => content, firstline => topline); return JT.USS (topline); end get_pkg_name; ---------------------------- -- populate_set_depends -- ---------------------------- procedure populate_set_depends (target : port_index; catport : String; line : JT.Text; dtype : dependency_type) is subs : GSS.Slice_Set; deps_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_deps : constant GSS.Slice_Number := GSS.Slice_Number (0); dirlen : constant Natural := dir_ports'Length; bracketed : Natural := 0; use type GSS.Slice_Number; begin if not fullpop or else JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " " & LAT.HT, Mode => GSS.Multiple); deps_found := GSS.Slice_Count (S => subs); if deps_found = zero_deps then return; end if; for j in 1 .. deps_found loop declare workdep : constant String := GSS.Slice (subs, j); fulldep : constant String (1 .. workdep'Length) := workdep; flen : constant Natural := fulldep'Length; colon : constant Natural := find_colon (fulldep); colon1 : constant Natural := colon + 1; DNE : Boolean := True; deprec : portkey_crate.Cursor; pkey : JT.Text; use type portkey_crate.Cursor; begin if colon < 2 then raise make_garbage with dtype'Img & ": " & JT.USS (trimline) & " (" & catport & ")"; end if; if flen > colon1 + dirlen + 1 and then fulldep (colon1 .. colon1 + dirlen) = dir_ports & "/" then pkey := scrub_phase (fulldep (colon + dirlen + 2 .. fulldep'Last)); elsif flen > colon1 + 5 and then fulldep (colon1 .. colon1 + 5) = "../../" then pkey := scrub_phase (fulldep (colon1 + 6 .. fulldep'Last)); else pkey := scrub_phase (fulldep (colon1 .. fulldep'Last)); end if; deprec := ports_keys.Find (pkey); if deprec = portkey_crate.No_Element then -- This dependency apparently does not exist. -- However, it could be flavored port that doesn't specify the flavor, so -- in this case, we have to look up the FIRST defined flavor (the default) -- The flavor order of the flavor index is therefore critical declare flport : port_index; begin if so_porthash.Contains (pkey) then flport := so_porthash.Element (pkey); deprec := all_ports (flport).key_cursor; if deprec /= portkey_crate.No_Element then DNE := False; end if; end if; end; if DNE then raise nonexistent_port with fulldep & " (required dependency of " & catport & ") does not exist."; end if; end if; declare depindex : port_index := portkey_crate.Element (deprec); begin if not all_ports (target).blocked_by.Contains (depindex) then all_ports (target).blocked_by.Insert (Key => depindex, New_Item => depindex); end if; if dtype in LR_set then if not all_ports (target).librun.Contains (depindex) then all_ports (target).librun.Insert (Key => depindex, New_Item => depindex); all_ports (target).min_librun := all_ports (target).min_librun + 1; case software_framework is when ports_collection => null; when pkgsrc => if fulldep (1) = '{' then bracketed := bracketed + 1; end if; end case; end if; end if; end; end; end loop; if bracketed > 0 and then all_ports (target).min_librun > 1 then declare newval : Integer := all_ports (target).min_librun - bracketed; begin if newval <= 1 then all_ports (target).min_librun := 1; else all_ports (target).min_librun := newval; end if; end; end if; end populate_set_depends; ---------------------------- -- populate_set_options -- ---------------------------- procedure populate_set_options (target : port_index; line : JT.Text; on : Boolean) is subs : GSS.Slice_Set; opts_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_opts : constant GSS.Slice_Number := GSS.Slice_Number (0); use type GSS.Slice_Number; begin if not fullpop or else JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " ", Mode => GSS.Multiple); opts_found := GSS.Slice_Count (S => subs); if opts_found = zero_opts then return; end if; for j in 1 .. opts_found loop declare opt : JT.Text := JT.SUS (GSS.Slice (subs, j)); begin if not all_ports (target).options.Contains (opt) then all_ports (target).options.Insert (Key => opt, New_Item => on); end if; end; end loop; end populate_set_options; -------------------------- -- populate_flavors -- -------------------------- procedure populate_flavors (target : port_index; line : JT.Text) is subs : GSS.Slice_Set; flav_found : GSS.Slice_Number; trimline : constant JT.Text := JT.trim (line); zero_flav : constant GSS.Slice_Number := GSS.Slice_Number (0); use type GSS.Slice_Number; begin if JT.IsBlank (trimline) then return; end if; GSS.Create (S => subs, From => JT.USS (trimline), Separators => " ", Mode => GSS.Multiple); flav_found := GSS.Slice_Count (S => subs); if flav_found = zero_flav then return; end if; for j in 1 .. flav_found loop declare flavor : JT.Text := JT.SUS (GSS.Slice (subs, j)); begin if not all_ports (target).flavors.Contains (flavor) then all_ports (target).flavors.Append (flavor); end if; end; end loop; end populate_flavors; -------------------------- -- populate_port_data -- -------------------------- procedure populate_port_data (target : port_index) is begin case software_framework is when ports_collection => populate_port_data_fpc (target); when pkgsrc => populate_port_data_nps (target); end case; end populate_port_data; ------------------------------ -- populate_port_data_fpc -- ------------------------------ procedure populate_port_data_fpc (target : port_index) is function get_fullport return String; catport : constant String := get_catport (all_ports (target)); function get_fullport return String is begin -- if format is cat/port@something then -- return "cat/port FLAVOR=something" -- else -- return $catport if JT.contains (catport, "@") then return dir_ports & "/" & JT.part_1 (catport, "@") & " FLAVOR=" & JT.part_2 (catport, "@"); else return dir_ports & "/" & catport; end if; end get_fullport; fullport : constant String := get_fullport; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := ssroot & " " & chroot_make_program & " -C " & fullport & " -VPKGVERSION -VPKGFILE:T -VMAKE_JOBS_NUMBER -VIGNORE" & " -VFETCH_DEPENDS -VEXTRACT_DEPENDS -VPATCH_DEPENDS" & " -VBUILD_DEPENDS -VLIB_DEPENDS -VRUN_DEPENDS" & " -VSELECTED_OPTIONS -VDESELECTED_OPTIONS -VUSE_LINUX" & " -VFLAVORS"; content : JT.Text; topline : JT.Text; status : Integer; type result_range is range 1 .. 14; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with catport & " (return code =" & status'Img & ")"; end if; for k in result_range loop JT.nextline (lineblock => content, firstline => topline); case k is when 1 => all_ports (target).port_version := topline; when 2 => all_ports (target).package_name := topline; when 3 => begin all_ports (target).jobs := builders (Integer'Value (JT.USS (topline))); exception when others => all_ports (target).jobs := PM.configuration.num_builders; end; when 4 => all_ports (target).ignore_reason := topline; all_ports (target).ignored := not JT.IsBlank (topline); when 5 => populate_set_depends (target, catport, topline, fetch); when 6 => populate_set_depends (target, catport, topline, extract); when 7 => populate_set_depends (target, catport, topline, patch); when 8 => populate_set_depends (target, catport, topline, build); when 9 => populate_set_depends (target, catport, topline, library); when 10 => populate_set_depends (target, catport, topline, runtime); when 11 => populate_set_options (target, topline, True); when 12 => populate_set_options (target, topline, False); when 13 => if not JT.IsBlank (JT.trim (topline)) then all_ports (target).use_linprocfs := True; end if; when 14 => populate_flavors (target, topline); end case; end loop; all_ports (target).scanned := True; if catport = "x11-toolkits/gnustep-gui" then all_ports (target).use_procfs := True; end if; if catport = "emulators/linux_base-c6" or else catport = "emulators/linux_base-f10" or else catport = "sysutils/htop" then all_ports (target).use_linprocfs := True; end if; exception when issue : others => EX.Reraise_Occurrence (issue); end populate_port_data_fpc; ------------------------------ -- populate_port_data_nps -- ------------------------------ procedure populate_port_data_nps (target : port_index) is catport : String := get_catport (all_ports (target)); fullport : constant String := dir_ports & "/" & catport; ssroot : constant String := chroot & JT.USS (PM.configuration.dir_buildbase) & ss_base; command : constant String := ssroot & " " & chroot_make_program & " -C " & fullport & " .MAKE.EXPAND_VARIABLES=yes " & " -VPKGVERSION -VPKGFILE:T -V_MAKE_JOBS:C/^-j//" & " -V_CBBH_MSGS -VTOOL_DEPENDS -VBUILD_DEPENDS -VDEPENDS" & " -VPKG_OPTIONS -VPKG_DISABLED_OPTIONS" & " -VEMUL_PLATFORMS"; content : JT.Text; topline : JT.Text; status : Integer; type result_range is range 1 .. 10; begin content := Unix.piped_command (command, status); if status /= 0 then raise bmake_execution with catport & " (return code =" & status'Img & ")"; end if; for k in result_range loop JT.nextline (lineblock => content, firstline => topline); case k is when 1 => all_ports (target).port_version := topline; when 2 => all_ports (target).package_name := topline; when 3 => if JT.IsBlank (topline) then all_ports (target).jobs := PM.configuration.num_builders; else begin all_ports (target).jobs := builders (Integer'Value (JT.USS (topline))); exception when others => all_ports (target).jobs := PM.configuration.num_builders; end; end if; when 4 => all_ports (target).ignore_reason := clean_up_pkgsrc_ignore_reason (JT.USS (topline)); all_ports (target).ignored := not JT.IsBlank (topline); when 5 => populate_set_depends (target, catport, topline, build); when 6 => populate_set_depends (target, catport, topline, build); when 7 => populate_set_depends (target, catport, topline, runtime); when 8 => populate_set_options (target, topline, True); when 9 => populate_set_options (target, topline, False); when 10 => if JT.contains (topline, "linux") then all_ports (target).use_linprocfs := True; end if; end case; end loop; all_ports (target).scanned := True; if catport = "x11/gnustep-gui" then all_ports (target).use_procfs := True; end if; if catport = "sysutils/htop" then all_ports (target).use_linprocfs := True; end if; exception when issue : others => EX.Reraise_Occurrence (issue); end populate_port_data_nps; ----------------- -- set_cores -- ----------------- procedure set_cores is number : constant Positive := Replicant.Platform.get_number_cpus; begin if number > Positive (cpu_range'Last) then number_cores := cpu_range'Last; else number_cores := cpu_range (number); end if; end set_cores; ----------------------- -- cores_available -- ----------------------- function cores_available return cpu_range is begin return number_cores; end cores_available; -------------------------- -- prescan_ports_tree -- -------------------------- procedure prescan_ports_tree (portsdir : String) is package sorter is new string_crate.Generic_Sorting ("<" => JT.SU."<"); procedure quick_scan (cursor : string_crate.Cursor); Search : AD.Search_Type; Dir_Ent : AD.Directory_Entry_Type; categories : string_crate.Vector; -- scan entire ports tree, and for each port hooked into the build, -- push an initial port_rec into the all_ports container procedure quick_scan (cursor : string_crate.Cursor) is category : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if AD.Exists (portsdir & "/" & category & "/Makefile") then grep_Makefile (portsdir => portsdir, category => category); else walk_all_subdirectories (portsdir => portsdir, category => category); end if; end quick_scan; begin AD.Start_Search (Search => Search, Directory => portsdir, Filter => (AD.Directory => True, others => False), Pattern => "[a-z]*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => Dir_Ent); declare category : constant String := AD.Simple_Name (Dir_Ent); good_directory : Boolean := True; begin case software_framework is when ports_collection => if category = "base" or else category = "distfiles" or else category = "packages" then good_directory := False; end if; when pkgsrc => if category = "bootstrap" or else category = "distfiles" or else category = "doc" or else category = "licenses" or else category = "mk" or else category = "packages" or else category = "regress" then good_directory := False; end if; end case; if good_directory then categories.Append (New_Item => JT.SUS (category)); end if; end; end loop; AD.End_Search (Search => Search); sorter.Sort (Container => categories); categories.Iterate (Process => quick_scan'Access); prescanned := True; end prescan_ports_tree; --------------------------------- -- tree_newer_than_reference -- --------------------------------- function tree_newer_than_reference (portsdir : String; reference : CAL.Time; valid : out Boolean) return Boolean is procedure quick_scan (cursor : string_crate.Cursor); Search : AD.Search_Type; Dir_Ent : AD.Directory_Entry_Type; categories : string_crate.Vector; top_modtime : CAL.Time; keep_going : Boolean := True; procedure quick_scan (cursor : string_crate.Cursor) is category : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if keep_going then keep_going := subdirectory_is_older (portsdir => portsdir, category => category, reference => reference); end if; end quick_scan; use type CAL.Time; begin valid := True; top_modtime := AD.Modification_Time (portsdir); if reference < top_modtime then return True; end if; AD.Start_Search (Search => Search, Directory => portsdir, Filter => (AD.Directory => True, others => False), Pattern => "[a-z]*"); while keep_going and then AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => Dir_Ent); declare category : constant String := AD.Simple_Name (Dir_Ent); good_directory : Boolean := True; begin case software_framework is when ports_collection => if category = "base" or else category = "distfiles" or else category = "packages" then good_directory := False; end if; when pkgsrc => if category = "bootstrap" or else category = "distfiles" or else category = "doc" or else category = "licenses" or else category = "mk" or else category = "packages" or else category = "regress" then good_directory := False; end if; end case; if good_directory then if reference < AD.Modification_Time (Dir_Ent) then keep_going := False; else categories.Append (New_Item => JT.SUS (category)); end if; end if; end; end loop; AD.End_Search (Search => Search); if not keep_going then return True; end if; categories.Iterate (Process => quick_scan'Access); return not keep_going; exception when others => valid := False; return False; end tree_newer_than_reference; ------------------ -- find_colon -- ------------------ function find_colon (Source : String) return Natural is result : Natural := 0; strlen : constant Natural := Source'Length; begin for j in 1 .. strlen loop if Source (j) = LAT.Colon then result := j; exit; end if; end loop; return result; end find_colon; ------------------- -- scrub_phase -- ------------------- function scrub_phase (Source : String) return JT.Text is reset : constant String (1 .. Source'Length) := Source; colon : constant Natural := find_colon (reset); begin if colon = 0 then return JT.SUS (reset); end if; return JT.SUS (reset (1 .. colon - 1)); end scrub_phase; -------------------------- -- determine_max_lots -- -------------------------- function get_max_lots return scanners is first_try : constant Positive := Positive (number_cores) * 3; begin if first_try > Positive (scanners'Last) then return scanners'Last; else return scanners (first_try); end if; end get_max_lots; --------------------- -- grep_Makefile -- --------------------- procedure grep_Makefile (portsdir, category : String) is archive : TIO.File_Type; matches : RGX.Match_Array (0 .. 1); pattern : constant String := "^SUBDIR[[:space:]]*[:+:]=[[:space:]]*([[:graph:]]*)"; regex : constant RGX.Pattern_Matcher := RGX.Compile (pattern); max_lots : constant scanners := get_max_lots; begin TIO.Open (File => archive, Mode => TIO.In_File, Name => portsdir & "/" & category & "/Makefile"); while not TIO.End_Of_File (File => archive) loop declare line : constant String := JT.trim (TIO.Get_Line (File => archive)); blank_rec : port_record; kc : portkey_crate.Cursor; success : Boolean; use type RGX.Match_Location; begin RGX.Match (Self => regex, Data => line, Matches => matches); if matches (0) /= RGX.No_Match then declare portkey : constant JT.Text := JT.SUS (category & '/' & line (matches (1).First .. matches (1).Last)); begin ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end; end if; end; end loop; TIO.Close (File => archive); end grep_Makefile; ------------------------------- -- walk_all_subdirectories -- ------------------------------- procedure walk_all_subdirectories (portsdir, category : String) is inner_search : AD.Search_Type; inner_dirent : AD.Directory_Entry_Type; max_lots : constant scanners := get_max_lots; begin AD.Start_Search (Search => inner_search, Directory => portsdir & "/" & category, Filter => (AD.Directory => True, others => False), Pattern => ""); while AD.More_Entries (Search => inner_search) loop AD.Get_Next_Entry (Search => inner_search, Directory_Entry => inner_dirent); declare portname : constant String := AD.Simple_Name (inner_dirent); portkey : constant JT.Text := JT.SUS (category & "/" & portname); kc : portkey_crate.Cursor; success : Boolean; begin if portname /= "." and then portname /= ".." then ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); last_port := lot_counter; all_ports (lot_counter).sequence_id := lot_counter; all_ports (lot_counter).key_cursor := kc; make_queue (lot_number).Append (lot_counter); lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end if; end; end loop; AD.End_Search (inner_search); end walk_all_subdirectories; ----------------------------- -- subdirectory_is_older -- ----------------------------- function subdirectory_is_older (portsdir, category : String; reference : CAL.Time) return Boolean is inner_search : AD.Search_Type; inner_dirent : AD.Directory_Entry_Type; already_newer : Boolean := False; use type CAL.Time; begin AD.Start_Search (Search => inner_search, Directory => portsdir & "/" & category, Filter => (others => True), Pattern => ""); while not already_newer and then AD.More_Entries (Search => inner_search) loop AD.Get_Next_Entry (Search => inner_search, Directory_Entry => inner_dirent); -- We're going to get "." and "..". It's faster to check them (always older) -- than convert to simple name and exclude them. if reference < AD.Modification_Time (inner_dirent) then already_newer := True; end if; end loop; AD.End_Search (inner_search); return not already_newer; end subdirectory_is_older; ----------------- -- port_hash -- ----------------- function port_hash (key : JT.Text) return AC.Hash_Type is begin return Ada.Strings.Hash (JT.USS (key)); end port_hash; ------------------ -- block_hash -- ------------------ function block_hash (key : port_index) return AC.Hash_Type is preresult : constant AC.Hash_Type := AC.Hash_Type (key); use type AC.Hash_Type; begin -- Equivalent to mod 128 return preresult and 2#1111111#; end block_hash; ------------------ -- block_ekey -- ------------------ function block_ekey (left, right : port_index) return Boolean is begin return left = right; end block_ekey; -------------------------------------- -- "<" function for ranking_crate -- -------------------------------------- function "<" (L, R : queue_record) return Boolean is begin if L.reverse_score = R.reverse_score then return R.ap_index > L.ap_index; end if; return L.reverse_score > R.reverse_score; end "<"; ------------------- -- get_catport -- ------------------- function get_catport (PR : port_record) return String is use type portkey_crate.Cursor; begin if PR.key_cursor = portkey_crate.No_Element then return "get_catport: invalid key_cursor"; end if; return JT.USS (portkey_crate.Key (PR.key_cursor)); end get_catport; --------------------- -- scan_progress -- --------------------- function scan_progress return String is type percent is delta 0.01 digits 5; complete : port_index := 0; pc : percent; begin for k in scanners'Range loop complete := complete + mq_progress (k); end loop; pc := percent (100.0 * Float (complete) / Float (last_port)); return " progress:" & pc'Img & "% " & LAT.CR; end scan_progress; ----------------------- -- obvious_problem -- ----------------------- function obvious_problem (portsdir, catport : String) return String is fullpath : constant String := portsdir & "/" & JT.part_1 (catport, "@"); begin if AD.Exists (fullpath) then declare Search : AD.Search_Type; dirent : AD.Directory_Entry_Type; has_contents : Boolean := False; begin AD.Start_Search (Search => Search, Directory => fullpath, Filter => (others => True), Pattern => "*"); while AD.More_Entries (Search => Search) loop AD.Get_Next_Entry (Search => Search, Directory_Entry => dirent); if AD.Simple_Name (dirent) /= "." and then AD.Simple_Name (dirent) /= ".." then has_contents := True; exit; end if; end loop; AD.End_Search (Search => Search); if not has_contents then return " (directory empty)"; end if; if AD.Exists (fullpath & "/Makefile") then return ""; else return " (Makefile missing)"; end if; end; else return " (port deleted)"; end if; end obvious_problem; ------------------------------------- -- clean_up_pkgsrc_ignore_reason -- ------------------------------------- function clean_up_pkgsrc_ignore_reason (dirty_string : String) return JT.Text is -- 1. strip out all double-quotation marks -- 2. strip out all single reverse solidus ("\") -- 3. condense contiguous spaces to a single space function strip_this_package_has_set (raw : String) return String; function strip_this_package_has_set (raw : String) return String is pattern : constant String := "This package has set "; begin if JT.contains (raw, pattern) then declare uno : String := JT.part_1 (raw, pattern); duo : String := JT.part_2 (raw, pattern); begin return strip_this_package_has_set (uno & duo); end; else return raw; end if; end strip_this_package_has_set; product : String (1 .. dirty_string'Length); dstx : Natural := 0; keep_it : Boolean; last_was_slash : Boolean := False; last_was_space : Boolean := False; begin for srcx in dirty_string'Range loop keep_it := True; case dirty_string (srcx) is when LAT.Quotation | LAT.LF => keep_it := False; when LAT.Reverse_Solidus => if not last_was_slash then keep_it := False; end if; last_was_slash := not last_was_slash; when LAT.Space => if last_was_space then keep_it := False; end if; last_was_space := True; last_was_slash := False; when others => last_was_space := False; last_was_slash := False; end case; if keep_it then dstx := dstx + 1; product (dstx) := dirty_string (srcx); end if; end loop; return JT.SUS (strip_this_package_has_set (product (1 .. dstx))); end clean_up_pkgsrc_ignore_reason; ----------------- -- timestamp -- ----------------- function timestamp (hack : CAL.Time; www_format : Boolean := False) return String is function MON (num : CAL.Month_Number) return String; function WKDAY (day : ACF.Day_Name) return String; function MON (num : CAL.Month_Number) return String is begin case num is when 1 => return "JAN"; when 2 => return "FEB"; when 3 => return "MAR"; when 4 => return "APR"; when 5 => return "MAY"; when 6 => return "JUN"; when 7 => return "JUL"; when 8 => return "AUG"; when 9 => return "SEP"; when 10 => return "OCT"; when 11 => return "NOV"; when 12 => return "DEC"; end case; end MON; function WKDAY (day : ACF.Day_Name) return String is begin case day is when ACF.Monday => return "Monday"; when ACF.Tuesday => return "Tuesday"; when ACF.Wednesday => return "Wednesday"; when ACF.Thursday => return "Thursday"; when ACF.Friday => return "Friday"; when ACF.Saturday => return "Saturday"; when ACF.Sunday => return "Sunday"; end case; end WKDAY; begin if www_format then return CAL.Day (hack)'Img & " " & MON (CAL.Month (hack)) & CAL.Year (hack)'Img & ", " & ACF.Image (hack)(11 .. 19) & " UTC"; end if; return WKDAY (ACF.Day_Of_Week (hack)) & "," & CAL.Day (hack)'Img & " " & MON (CAL.Month (hack)) & CAL.Year (hack)'Img & " at" & ACF.Image (hack)(11 .. 19) & " UTC"; end timestamp; ---------------------------- -- generate_ports_index -- ---------------------------- function generate_ports_index (index_file, portsdir : String) return Boolean is procedure add_flavor (cursor : string_crate.Cursor); procedure write_line (cursor : string_crate.Cursor); good_scan : Boolean; handle : TIO.File_Type; all_flavors : string_crate.Vector; basecatport : JT.Text; noprocs : constant REP.slave_options := (others => False); using_screen : constant Boolean := Unix.screen_attached; error_prefix : constant String := "Flavor index generation failed: "; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; procedure add_flavor (cursor : string_crate.Cursor) is line : JT.Text := basecatport; begin JT.SU.Append (line, "@"); JT.SU.Append (line, string_crate.Element (Position => cursor)); all_flavors.Append (line); end add_flavor; procedure write_line (cursor : string_crate.Cursor) is line : constant String := JT.USS (string_crate.Element (Position => cursor)); begin TIO.Put_Line (handle, line); end write_line; begin begin AD.Create_Path (index_path); exception when others => TIO.Put_Line (error_prefix & "could not create " & index_path); return False; end; TIO.Put_Line ("Regenerating flavor index: this may take a while ..."); prescan_ports_tree (portsdir); case software_framework is when ports_collection => REP.initialize (testmode => False, num_cores => cores_available); REP.launch_slave (id => scan_slave, opts => noprocs); fullpop := False; scan_start := CAL.Clock; parallel_deep_scan (success => good_scan, show_progress => using_screen); scan_stop := CAL.Clock; fullpop := True; REP.destroy_slave (id => scan_slave, opts => noprocs); REP.finalize; if not good_scan then TIO.Put_Line (error_prefix & "ports scan"); return False; end if; when pkgsrc => null; end case; begin for port in port_index'First .. last_port loop basecatport := portkey_crate.Key (all_ports (port).key_cursor); if not all_ports (port).flavors.Is_Empty then all_ports (port).flavors.Iterate (add_flavor'Access); else all_flavors.Append (basecatport); end if; end loop; TIO.Create (File => handle, Mode => TIO.Out_File, Name => index_full); all_flavors.Iterate (write_line'Access); TIO.Close (handle); exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; TIO.Put_Line (error_prefix & "writing out index"); return False; end; reset_ports_tree; return True; end generate_ports_index; -------------------------- -- read_flavor_index -- -------------------------- procedure read_flavor_index is handle : TIO.File_Type; max_lots : constant scanners := get_max_lots; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; begin so_porthash.Clear; so_serial.Clear; TIO.Open (File => handle, Mode => TIO.In_File, Name => index_full); while not TIO.End_Of_File (handle) loop declare line : constant String := JT.trim (TIO.Get_Line (handle)); baseport : JT.Text := JT.SUS (JT.part_1 (line, "@")); portkey : JT.Text := JT.SUS (line); blank_rec : port_record; kc : portkey_crate.Cursor; success : Boolean; begin ports_keys.Insert (Key => portkey, New_Item => lot_counter, Position => kc, Inserted => success); so_serial.Append (portkey); last_port := lot_counter; all_ports (last_port).sequence_id := last_port; all_ports (last_port).key_cursor := kc; make_queue (lot_number).Append (last_port); -- Map baseport name to first encounted flavor -- This is used to lookup default flavor when @ modifier is not provided if not so_porthash.Contains (baseport) then so_porthash.Insert (Key => baseport, New_Item => last_port); end if; end; lot_counter := lot_counter + 1; if lot_number = max_lots then lot_number := 1; else lot_number := lot_number + 1; end if; end loop; TIO.Close (handle); prescanned := True; exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; end read_flavor_index; ------------------------------------- -- load_index_for_store_origins -- ------------------------------------- procedure load_index_for_store_origins is handle : TIO.File_Type; index_full : constant String := index_path & "/" & JT.USS (PM.configuration.profile) & "-index"; ndx : port_id := 0; begin TIO.Open (File => handle, Mode => TIO.In_File, Name => index_full); while not TIO.End_Of_File (handle) loop declare portkey : JT.Text := JT.SUS (JT.trim (TIO.Get_Line (handle))); begin so_serial.Append (portkey); so_porthash.Insert (Key => portkey, New_Item => ndx); ndx := ndx + 1; end; end loop; TIO.Close (handle); exception when others => if TIO.Is_Open (handle) then TIO.Close (handle); end if; end load_index_for_store_origins; -------------------------------- -- clear_store_origin_data -- -------------------------------- procedure clear_store_origin_data is begin so_serial.Clear; so_porthash.Clear; end clear_store_origin_data; --------------------------- -- input_origin_valid -- --------------------------- function input_origin_valid (candidate : String) return Boolean is begin return so_porthash.Contains (JT.SUS (candidate)); end input_origin_valid; -------------------------------------- -- suggest_flavor_for_bad_origin -- -------------------------------------- procedure suggest_flavor_for_bad_origin (candidate : String) is procedure suggest (cursor : string_crate.Cursor); adjusted_candidate : String (1 .. candidate'Length + 1) := (others => ' '); pretext : Boolean := False; canlast : Natural := adjusted_candidate'Last; procedure suggest (cursor : string_crate.Cursor) is payload : constant String := JT.USS (string_crate.Element (Position => cursor)); begin if JT.leads (S => payload, fragment => adjusted_candidate (1 .. canlast)) then if not pretext then TIO.Put_Line ("Perhaps you intended one of the following port flavors?"); pretext := True; end if; TIO.Put_Line (" - " & payload); end if; end suggest; begin if JT.contains (candidate, "@") then declare catport : constant String := JT.part_1 (candidate, "@"); begin canlast := catport'Length + 1; adjusted_candidate (1 .. canlast) := catport & "@"; end; else adjusted_candidate := candidate & "@"; end if; TIO.Put_Line ("Error: port origin '" & candidate & "' is not recognized."); so_serial.Iterate (suggest'Access); end suggest_flavor_for_bad_origin; end PortScan;
AdaCore/langkit
Ada
2,432
adb
with Ada.Text_IO; use Ada.Text_IO; with GNAT.Source_Info; with Langkit_Support.Adalog.Main_Support; use Langkit_Support.Adalog.Main_Support; -- Copy of the dyn_scheduling test. The interest is to see that debug -- information in relation printing works correctly, i.e. that it is correctly -- shown when printing a relation. procedure Main is use T_Solver, Refs, Solver_Ifc; function S return String renames GNAT.Source_Info.Source_Location; function Is_Even (Val : Integer) return Boolean is (Val mod 2 = 0); function Is_Even (Var : Refs.Logic_Var; Dbg_String : String) return Relation is (Predicate (Var, Predicate (Is_Even'Access, "Is_Even"), Dbg_String)); X : constant Refs.Logic_Var := Create ("X"); Y : constant Refs.Logic_Var := Create ("Y"); Relations : constant array (Positive range <>) of Relation := (Unify (X, Y, Dbg_String => S) and Domain (X, (1, 2, 3), S), -- Simple dynamic scheduling: the second relation must be evaluated -- before the first one. R_All((Domain (X, (1, 2, 3), S), R_Any ((Domain (X, (10, 20)), Is_Even (Y, S)), S), Domain (Y, (1, 3, 5, 10), S)), S), -- The second AND relation (OR) cannot be evaluated completely, but it -- makes progress. R_All ((Is_Even (Y, S), Domain (X, (1, 2, 3), S)), S), -- Unsolvable equation: nothing provides a value for Y, but the equation -- still makes progress. R_All ((Is_Even (Y, S), Is_Even (X, S)), S), -- Likewise, but the equation makes no progress at all R_Any ((Is_Even (Y, S), Domain (X, (1, 2), S)), S), -- Likewise, but for ANY relations R_Any ((Is_Even (X, S), Is_Even (Y, S)), S), R_Any ((Is_Even (X, S), R_All ((Domain (X, (1, 2, 3), S), Is_Even (Y, S)), S)), S), R_All ((Domain (X, (1, 2, 3), S), Is_Even (Y, S), Domain (X, (1 => 2), S), Unify (X, Y, S)), S) -- Make sure that back-tracking, which happens for the second Member, -- properly resets the state so that the second evaluation of this -- second Member actually checks something. Without a proper reset, this -- stateful relation just yields Unsatisfied. ); begin for R of Relations loop Put_Line ((1 .. 72 => '=')); New_Line; Reset (X); Reset (Y); Solve_All (R); end loop; end Main;
xeenta/learning-ada
Ada
1,291
adb
with Ada.Text_IO; use Ada.Text_IO; procedure Thick_Hello is package Counter is type C_Type is mod 17; procedure Increment; procedure Increment (I : Integer); procedure Decrement; function Value return C_Type; private Cnt : C_Type := 0; end Counter; package body Counter is procedure Increment is begin Cnt := Cnt + 1; end Increment; procedure Increment (I : Integer) is begin Cnt := Cnt + C_Type (I mod C_Type'Modulus); end Increment; procedure Decrement is begin Cnt := Cnt - 1; end Decrement; function Value return C_Type is (Cnt); end Counter; package M is new Ada.Text_IO.Modular_IO (Counter.C_Type); use type Counter.C_Type; T : Counter.C_Type := 0; begin for I in Integer range 1 .. 120 loop if I rem 7 = 0 then Counter.Decrement; elsif I rem 12 = 0 then Counter.Decrement; elsif I rem 17 = 0 then Counter.Increment; elsif I rem 25 = 0 then Counter.Increment (I); end if; if T = Counter.Value then Counter.Increment; end if; M.Put (Counter.Value); New_Line; T := Counter.Value; end loop; end Thick_Hello;
landgraf/nanomsg-ada
Ada
1,706
ads
-- The MIT License (MIT) -- Copyright (c) 2015 Pavel Zhukov <[email protected]> -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all -- copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. with Aunit; use Aunit; with Aunit.Simple_Test_Cases; with Nanomsg.Socket; package Nanomsg.Test_Survey is type Clients_T is array (1 .. 10) of Nanomsg.Socket.Socket_T; type TC is new Simple_Test_Cases.Test_Case with record Server : Nanomsg.Socket.Socket_T; Clients : Clients_T; end record; overriding procedure Tear_Down (T : in out Tc); overriding procedure Run_Test (T : in out TC); overriding function Name (T : TC) return Message_String; end Nanomsg.Test_Survey;
reznikmm/matreshka
Ada
4,001
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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.ODF_Elements.Style.List_Level_Label_Alignment; package ODF.DOM.Elements.Style.List_Level_Label_Alignment.Internals is function Create (Node : Matreshka.ODF_Elements.Style.List_Level_Label_Alignment.Style_List_Level_Label_Alignment_Access) return ODF.DOM.Elements.Style.List_Level_Label_Alignment.ODF_Style_List_Level_Label_Alignment; function Wrap (Node : Matreshka.ODF_Elements.Style.List_Level_Label_Alignment.Style_List_Level_Label_Alignment_Access) return ODF.DOM.Elements.Style.List_Level_Label_Alignment.ODF_Style_List_Level_Label_Alignment; end ODF.DOM.Elements.Style.List_Level_Label_Alignment.Internals;
zhmu/ananas
Ada
2,872
ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- S Y S T E M . F O R E _ F I X E D _ 6 4 -- -- -- -- S p e c -- -- -- -- Copyright (C) 2020-2022, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- This package contains the routine used for the 'Fore attribute for ordinary -- fixed point types up to 64-bit small and mantissa. with Interfaces; with System.Arith_64; with System.Fore_F; package System.Fore_Fixed_64 is pragma Pure; subtype Int64 is Interfaces.Integer_64; package Impl is new Fore_F (Int64, Arith_64.Scaled_Divide64); function Fore_Fixed64 (Lo, Hi, Num, Den : Int64; Scale : Integer) return Natural renames Impl.Fore_Fixed; end System.Fore_Fixed_64;
reznikmm/matreshka
Ada
4,025
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 ODF.DOM.Smil_AttributeName_Attributes; package Matreshka.ODF_Smil.AttributeName_Attributes is type Smil_AttributeName_Attribute_Node is new Matreshka.ODF_Smil.Abstract_Smil_Attribute_Node and ODF.DOM.Smil_AttributeName_Attributes.ODF_Smil_AttributeName_Attribute with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Smil_AttributeName_Attribute_Node; overriding function Get_Local_Name (Self : not null access constant Smil_AttributeName_Attribute_Node) return League.Strings.Universal_String; end Matreshka.ODF_Smil.AttributeName_Attributes;
reznikmm/matreshka
Ada
4,717
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Visitors; with ODF.DOM.Form_Properties_Elements; package Matreshka.ODF_Form.Properties_Elements is type Form_Properties_Element_Node is new Matreshka.ODF_Form.Abstract_Form_Element_Node and ODF.DOM.Form_Properties_Elements.ODF_Form_Properties with null record; overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Form_Properties_Element_Node; overriding function Get_Local_Name (Self : not null access constant Form_Properties_Element_Node) return League.Strings.Universal_String; overriding procedure Enter_Node (Self : not null access Form_Properties_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Leave_Node (Self : not null access Form_Properties_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); overriding procedure Visit_Node (Self : not null access Form_Properties_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control); end Matreshka.ODF_Form.Properties_Elements;
reznikmm/matreshka
Ada
4,511
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Testsuite Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2013, Vadim Godunko <[email protected]> -- -- 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$ ------------------------------------------------------------------------------ -- Check whether regular expression compiler detect that expression use -- delimiters of different styles. ------------------------------------------------------------------------------ with League.Application; pragma Unreferenced (League.Application); -- Adding this unit to application closure activates system capabilities -- checks to select appropriate string handling implementation. with League.Regexps; with League.Strings; procedure Test_7 is procedure Do_Test (Pattern : Wide_Wide_String); ------------- -- Do_Test -- ------------- procedure Do_Test (Pattern : Wide_Wide_String) is P : constant League.Strings.Universal_String := League.Strings.To_Universal_String (Pattern); R : League.Regexps.Regexp_Pattern; pragma Unreferenced (R); -- It is expected that Compile will raise exception and R will never be -- assigned. begin R := League.Regexps.Compile (P); raise Program_Error; exception when Constraint_Error => null; end Do_Test; begin Do_Test ("\p{upper:]"); Do_Test ("[:upper}"); Do_Test ("\P{upper:]"); Do_Test ("[:upper}"); end Test_7;
stcarrez/dynamo
Ada
18,838
adb
------------------------------------------------------------------------------ -- -- -- ASIS-for-GNAT IMPLEMENTATION COMPONENTS -- -- -- -- A S I S . C L A U S E S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1995-2012, Free Software Foundation, Inc. -- -- -- -- ASIS-for-GNAT is free software; you can redistribute it and/or modify it -- -- under terms of the GNU General Public License as published by the Free -- -- Software Foundation; either version 2, or (at your option) any later -- -- version. ASIS-for-GNAT is distributed in the hope that it will be use- -- -- ful, but WITHOUT ANY WARRANTY; without even the implied warranty of MER- -- -- CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General -- -- Public License for more details. You should have received a copy of the -- -- GNU General Public License distributed with ASIS-for-GNAT; see file -- -- COPYING. If not, write to the Free Software Foundation, 51 Franklin -- -- Street, Fifth Floor, Boston, MA 02110-1301, USA. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the -- -- Software Engineering Laboratory of the Swiss Federal Institute of -- -- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the -- -- Scientific Research Computer Center of Moscow State University (SRCC -- -- MSU), Russia, with funding partially provided by grants from the Swiss -- -- National Science Foundation and the Swiss Academy of Engineering -- -- Sciences. ASIS-for-GNAT is now maintained by AdaCore -- -- (http://www.adacore.com). -- -- -- ------------------------------------------------------------------------------ with Asis.Errors; use Asis.Errors; with Asis.Exceptions; use Asis.Exceptions; with Asis.Set_Get; use Asis.Set_Get; with A4G.Mapping; use A4G.Mapping; with A4G.Vcheck; use A4G.Vcheck; with Atree; use Atree; with Namet; use Namet; with Nlists; use Nlists; with Sinfo; use Sinfo; with Snames; use Snames; package body Asis.Clauses is Package_Name : constant String := "Asis.Clauses."; ------------------ -- Clause_Names -- ------------------ function Clause_Names (Clause : Asis.Element) return Asis.Element_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; Result_List : List_Id; Result_Len : Natural := 1; Withed_Uname : Node_Id; begin Check_Validity (Clause, Package_Name & "Clause_Names"); if not (Arg_Kind = A_Use_Package_Clause or else Arg_Kind = A_Use_Type_Clause or else Arg_Kind = A_Use_All_Type_Clause or else -- Ada 2012 Arg_Kind = A_With_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Clause_Names", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); if Arg_Kind = A_With_Clause then -- first, computing the number of names listed in the argument -- with clause -- Note that we should skip implicit with cleause that may be added -- by front-end while not (Comes_From_Source (Arg_Node) and then Last_Name (Arg_Node)) loop if Comes_From_Source (Arg_Node) then Result_Len := Result_Len + 1; end if; Arg_Node := Next (Arg_Node); end loop; declare Result_List : Asis.Element_List (1 .. Result_Len); begin Arg_Node := Node (Clause); for I in 1 .. Result_Len loop Withed_Uname := Sinfo.Name (Arg_Node); Result_List (I) := Node_To_Element_New (Starting_Element => Clause, Node => Withed_Uname); Arg_Node := Next (Arg_Node); while Present (Arg_Node) and then not Comes_From_Source (Arg_Node) loop Arg_Node := Next (Arg_Node); end loop; end loop; return Result_List; end; else if Nkind (Arg_Node) = N_Use_Package_Clause then Result_List := Names (Arg_Node); else Result_List := Subtype_Marks (Arg_Node); end if; return N_To_E_List_New (List => Result_List, Starting_Element => Clause); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Clause_Names", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Clause_Names", Ex => Ex, Arg_Element => Clause); end Clause_Names; ------------------------------- -- Component_Clause_Position -- ------------------------------- function Component_Clause_Position (Clause : Asis.Component_Clause) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; begin Check_Validity (Clause, Package_Name & "Component_Clause_Position"); if not (Arg_Kind = A_Component_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Component_Clause_Position", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); return Node_To_Element_New (Node => Position (Arg_Node), Starting_Element => Clause); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Component_Clause_Position", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Component_Clause_Position", Ex => Ex, Arg_Element => Clause); end Component_Clause_Position; ---------------------------- -- Component_Clause_Range -- ---------------------------- function Component_Clause_Range (Clause : Asis.Component_Clause) return Asis.Discrete_Range is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; begin Check_Validity (Clause, Package_Name & "Component_Clause_Range"); if not (Arg_Kind = A_Component_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Component_Clause_Range", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); return Node_To_Element_New (Node => Arg_Node, Internal_Kind => A_Discrete_Simple_Expression_Range, Starting_Element => Clause); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Component_Clause_Range", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Component_Clause_Range", Ex => Ex, Arg_Element => Clause); end Component_Clause_Range; ----------------------- -- Component_Clauses -- ----------------------- function Component_Clauses (Clause : Asis.Representation_Clause; Include_Pragmas : Boolean := False) return Asis.Component_Clause_List is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; begin Check_Validity (Clause, Package_Name & "Component_Clauses"); if not (Arg_Kind = A_Record_Representation_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Component_Clauses", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); return N_To_E_List_New (List => Component_Clauses (Arg_Node), Include_Pragmas => Include_Pragmas, Starting_Element => Clause); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Component_Clauses", Argument => Clause, Bool_Par => Include_Pragmas); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Component_Clauses", Ex => Ex, Arg_Element => Clause, Bool_Par_ON => Include_Pragmas); end Component_Clauses; --------------------------- -- Mod_Clause_Expression -- --------------------------- function Mod_Clause_Expression (Clause : Asis.Representation_Clause) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; Mod_Clause_Node : Node_Id; begin Check_Validity (Clause, Package_Name & "Mod_Clause_Expression"); if not (Arg_Kind = A_Record_Representation_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Mod_Clause_Expression", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); Mod_Clause_Node := Next (Arg_Node); if Nkind (Mod_Clause_Node) = N_Attribute_Definition_Clause and then From_At_Mod (Mod_Clause_Node) then Mod_Clause_Node := Sinfo.Expression (Mod_Clause_Node); else Mod_Clause_Node := Empty; end if; if No (Mod_Clause_Node) then return Asis.Nil_Element; else return Node_To_Element_New (Node => Mod_Clause_Node, Starting_Element => Clause); end if; exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Mod_Clause_Expression", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Mod_Clause_Expression", Ex => Ex, Arg_Element => Clause); end Mod_Clause_Expression; -------------------------------------- -- Representation_Clause_Expression -- -------------------------------------- function Representation_Clause_Expression (Clause : Asis.Representation_Clause) return Asis.Expression is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; Result_Node : Node_Id; Result_Kind : Internal_Element_Kinds := Not_An_Element; begin Check_Validity (Clause, Package_Name & "Representation_Clause_Expression"); if not (Arg_Kind = An_Attribute_Definition_Clause or else Arg_Kind = An_Enumeration_Representation_Clause or else Arg_Kind = An_At_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Representation_Clause_Expression", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); if Nkind (Arg_Node) = N_Enumeration_Representation_Clause then Result_Node := Array_Aggregate (Arg_Node); if Present (Expressions (Result_Node)) then Result_Kind := A_Positional_Array_Aggregate; else Result_Kind := A_Named_Array_Aggregate; end if; else Result_Node := Sinfo.Expression (Arg_Node); end if; return Node_To_Element_New (Node => Result_Node, Internal_Kind => Result_Kind, Starting_Element => Clause); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Representation_Clause_Expression", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Representation_Clause_Expression", Ex => Ex, Arg_Element => Clause); end Representation_Clause_Expression; -------------------------------- -- Representation_Clause_Name -- -------------------------------- function Representation_Clause_Name (Clause : Asis.Clause) return Asis.Name is Arg_Kind : constant Internal_Element_Kinds := Int_Kind (Clause); Arg_Node : Node_Id; Result_Node : Node_Id; Result_Element : Element; Result_Kind : Internal_Element_Kinds := Not_An_Element; Attr_Des : Name_Id; -- needed for special processing of attribute definition clause begin Check_Validity (Clause, Package_Name & "Representation_Clause_Name"); if not (Arg_Kind = An_Attribute_Definition_Clause or else Arg_Kind = An_Enumeration_Representation_Clause or else Arg_Kind = A_Record_Representation_Clause or else Arg_Kind = An_At_Clause or else Arg_Kind = A_Component_Clause) then Raise_ASIS_Inappropriate_Element (Package_Name & "Representation_Clause_Name", Wrong_Kind => Arg_Kind); end if; Arg_Node := Node (Clause); if Nkind (Arg_Node) = N_Attribute_Definition_Clause then -- for An_Attribute_Definition_Clause argument we have to return -- as the result the Element of An_Attribute_Reference kind. -- The tree does not contain the structures for attribute reference -- in this case (and it should not, because, according to RM 95, -- there is no attribute reference in the syntax structure of -- an attribute definition clause, so we have to "emulate" -- the result Elemet of An_Attribute_Reference kind on the base -- of the same node -- first, we have to define the exact kind of the "artificial" -- attribute reference to be returned Attr_Des := Chars (Arg_Node); case Attr_Des is when Name_Address => Result_Kind := An_Address_Attribute; when Name_Alignment => Result_Kind := An_Alignment_Attribute; when Name_Bit_Order => Result_Kind := A_Bit_Order_Attribute; when Name_Component_Size => Result_Kind := A_Component_Size_Attribute; when Name_External_Tag => Result_Kind := An_External_Tag_Attribute; when Name_Input => Result_Kind := An_Input_Attribute; when Name_Machine_Radix => Result_Kind := A_Machine_Radix_Attribute; when Name_Output => Result_Kind := An_Output_Attribute; when Name_Read => Result_Kind := A_Read_Attribute; when Name_Size => Result_Kind := A_Size_Attribute; when Name_Small => Result_Kind := A_Small_Attribute; when Name_Storage_Size => Result_Kind := A_Storage_Size_Attribute; when Name_Storage_Pool => Result_Kind := A_Storage_Pool_Attribute; when Name_Write => Result_Kind := A_Write_Attribute; when others => -- "others" means Name_Object_Size and Name_Value_Size Result_Kind := An_Implementation_Defined_Attribute; end case; Result_Element := Clause; Set_Int_Kind (Result_Element, Result_Kind); return Result_Element; elsif Nkind (Arg_Node) = N_Component_Clause then Result_Node := Component_Name (Arg_Node); else Result_Node := Sinfo.Identifier (Arg_Node); end if; return Node_To_Element_New (Node => Result_Node, Starting_Element => Clause); exception when ASIS_Inappropriate_Element => raise; when ASIS_Failed => if Status_Indicator = Unhandled_Exception_Error then Add_Call_Information (Outer_Call => Package_Name & "Representation_Clause_Name", Argument => Clause); end if; raise; when Ex : others => Report_ASIS_Bug (Query_Name => Package_Name & "Representation_Clause_Name", Ex => Ex, Arg_Element => Clause); end Representation_Clause_Name; end Asis.Clauses;
Rodeo-McCabe/orka
Ada
1,559
ads
-- SPDX-License-Identifier: Apache-2.0 -- -- Copyright (c) 2017 onox <[email protected]> -- -- 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. private package Orka.Terminals is type Style is (Default, Bold, Dark, Italic, Underline, Blink, Reversed, Cross_Out); type Color is (Default, Grey, Red, Green, Yellow, Blue, Magenta, Cyan, White); function Colorize (Text : String; Foreground, Background : Color := Default; Attribute : Style := Default) return String; -- Colorize the given text with a foreground color, background color, -- and/or style using ANSI escape sequences function Time_Image return String; function Image (Value : Duration) return String with Pre => Value in -1000.0 .. 1000.0 or else raise Constraint_Error with Value'Image & " not within +/- 1000.0"; -- Return the image of the given duration with an appropriate suffix function Trim (Value : String) return String; function Strip_Line_Term (Value : String) return String; end Orka.Terminals;
MinimSecure/unum-sdk
Ada
834
adb
-- Copyright 2008-2016 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. package body Pck is procedure Do_Nothing (Val : in out Integer) is begin null; end Do_Nothing; end Pck;
rveenker/sdlada
Ada
937
adb
with SDL; with SDL.Error; with SDL.Log; with SDL.Versions; procedure Version is Linked_Version : SDL.Versions.Version; begin SDL.Log.Set (Category => SDL.Log.Application, Priority => SDL.Log.Debug); SDL.Versions.Linked_With (Info => Linked_Version); SDL.Log.Put_Debug ("Revision : " & SDL.Versions.Revision); SDL.Log.Put_Debug ("Linked with : " & SDL.Versions.Version_Level'Image (Linked_Version.Major) & "." & SDL.Versions.Version_Level'Image (Linked_Version.Minor) & "." & SDL.Versions.Version_Level'Image (Linked_Version.Patch)); SDL.Log.Put_Debug ("Compiled with : " & SDL.Versions.Version_Level'Image (SDL.Versions.Compiled_Major) & "." & SDL.Versions.Version_Level'Image (SDL.Versions.Compiled_Minor) & "." & SDL.Versions.Version_Level'Image (SDL.Versions.Compiled_Patch)); SDL.Finalise; end Version;
RREE/ada-util
Ada
25,786
adb
----------------------------------------------------------------------- -- util-serialize-mappers -- Serialize objects in various formats -- Copyright (C) 2010, 2011, 2012, 2014, 2017, 2018 Stephane Carrez -- Written by Stephane Carrez ([email protected]) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with System.Address_Image; with Util.Strings; with Ada.Tags; with Ada.Exceptions; with Ada.Unchecked_Deallocation; package body Util.Serialize.Mappers is -- The logger Log : constant Util.Log.Loggers.Logger := Util.Log.Loggers.Create ("Util.Serialize.Mappers", Util.Log.WARN_LEVEL); -- ----------------------- -- Execute the mapping operation on the object associated with the current context. -- The object is extracted from the context and the <b>Execute</b> operation is called. -- ----------------------- procedure Execute (Handler : in Mapper; Map : in Mapping'Class; Ctx : in out Util.Serialize.Contexts.Context'Class; Value : in Util.Beans.Objects.Object) is begin if Handler.Mapper /= null then Handler.Mapper.all.Execute (Map, Ctx, Value); end if; end Execute; function Is_Proxy (Controller : in Mapper) return Boolean is begin return Controller.Is_Proxy_Mapper; end Is_Proxy; -- ----------------------- -- Returns true if the mapper is a wildcard node (matches any element). -- ----------------------- function Is_Wildcard (Controller : in Mapper) return Boolean is begin return Controller.Is_Wildcard; end Is_Wildcard; -- ----------------------- -- Returns the mapping name. -- ----------------------- function Get_Name (Controller : in Mapper) return String is begin return Ada.Strings.Unbounded.To_String (Controller.Name); end Get_Name; -- ----------------------- -- Find the mapper associated with the given name. -- Returns null if there is no mapper. -- ----------------------- function Find_Mapper (Controller : in Mapper; Name : in String; Attribute : in Boolean := False) return Mapper_Access is use type Ada.Strings.Unbounded.Unbounded_String; Node : Mapper_Access := Controller.First_Child; Recurse : Boolean := True; Result : Mapper_Access := null; begin if Node = null and Controller.Mapper /= null then return Controller.Mapper.Find_Mapper (Name, Attribute); end if; while Node /= null loop if not Attribute and Node.Is_Wildcard then Result := Node.Find_Mapper (Name, Attribute); if Result /= null then return Result; else return Node; end if; end if; if Node.Name = Name then if (not Attribute and Node.Mapping = null) or else not Node.Mapping.Is_Attribute then return Node; end if; if Attribute and Node.Mapping.Is_Attribute then return Node; end if; end if; if Node.Is_Deep_Wildcard and not Attribute and Node.Mapper /= null and Recurse then Node := Node.Mapper.First_Child; Result := Node.Mapper; Recurse := False; else Node := Node.Next_Mapping; end if; end loop; return Result; end Find_Mapper; -- ----------------------- -- Find a path component representing a child mapper under <b>From</b> and -- identified by the given <b>Name</b>. If the mapper is not found, a new -- Mapper_Node is created. -- ----------------------- procedure Find_Path_Component (From : in out Mapper'Class; Name : in String; Root : in out Mapper_Access; Result : out Mapper_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access := From.First_Child; Previous : Mapper_Access := null; Wildcard : constant Boolean := Name = "*"; Deep_Wildcard : constant Boolean := Name = "**"; begin if Root = null and Deep_Wildcard then Root := Node; end if; if Node = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard or Deep_Wildcard; Result.Is_Deep_Wildcard := Deep_Wildcard; From.First_Child := Result; else loop if Node.Name = Name then Result := Node; exit; end if; if Node.Next_Mapping = null then Result := new Mapper; Result.Name := To_Unbounded_String (Name); Result.Is_Wildcard := Wildcard or Deep_Wildcard; Result.Is_Deep_Wildcard := Deep_Wildcard; if not Wildcard and not Deep_Wildcard then Result.Next_Mapping := Node; if Previous = null then From.First_Child := Result; else Previous.Next_Mapping := Result; end if; else Node.Next_Mapping := Result; end if; exit; end if; Previous := Node; Node := Node.Next_Mapping; end loop; end if; -- For deep wildcard mapping the mapping tree has to somehow redirect and use a -- root node (ie, the '**' node). Create a proxy node to point to that wildcard root. -- The wildcard nodes must be checked last and therefore appear at end of the mapping list. if Root /= null then Previous := Result; while Previous.Next_Mapping /= null loop Previous := Previous.Next_Mapping; end loop; if not Previous.Is_Wildcard and not Previous.Is_Deep_Wildcard then Node := new Mapper; Node.Name := To_Unbounded_String ("**"); Node.Is_Deep_Wildcard := True; Node.Mapper := Root; Previous.Next_Mapping := Node; end if; end if; end Find_Path_Component; -- ----------------------- -- Build the mapping tree that corresponds to the given <b>Path</b>. -- Each path component is represented by a <b>Mapper_Node</b> element. -- The node is created if it does not exists. -- ----------------------- procedure Build_Path (Into : in out Mapper'Class; Path : in String; Last_Pos : out Natural; Node : out Mapper_Access) is Pos : Natural; Root : Mapper_Access := null; begin Node := Into'Unchecked_Access; Last_Pos := Path'First; loop Pos := Util.Strings.Index (Source => Path, Char => '/', From => Last_Pos); if Pos = 0 then Node.Find_Path_Component (Name => Path (Last_Pos .. Path'Last), Root => Root, Result => Node); Last_Pos := Path'Last + 1; else Node.Find_Path_Component (Name => Path (Last_Pos .. Pos - 1), Root => Root, Result => Node); Last_Pos := Pos + 1; end if; exit when Last_Pos > Path'Last; end loop; end Build_Path; -- ----------------------- -- Add a mapping to associate the given <b>Path</b> to the mapper defined in <b>Map</b>. -- The <b>Path</b> string describes the matching node using a simplified XPath notation. -- Example: -- info/first_name matches: <info><first_name>...</first_name></info> -- info/a/b/name matches: <info><a><b><name>...</name></b></a></info> -- */a/b/name matches: <i><i><j><a><b><name>...</name></b></a></j></i></i> -- **/name matches: <i><name>...</name></i>, <b><c><name>...</name></c></b> -- ----------------------- procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapper_Access) is procedure Copy (To : in Mapper_Access; From : in Mapper_Access); procedure Add_Mapper (From, To : in Mapper_Access); function Find_Mapper (From : in Mapper_Access) return Mapper_Access; procedure Append (To : in Mapper_Access; Item : in Mapper_Access); -- For the support of deep wildcard mapping (**), we must map a proxy node mapper -- to the copy that was made. We maintain a small list of mapper pairs. -- The implementation is intended to be simple for now... type Mapper_Pair is record First : Mapper_Access; Second : Mapper_Access; end record; Node : Mapper_Access; Last_Pos : Natural; Mappers : array (1 .. 10) of Mapper_Pair; procedure Add_Mapper (From, To : in Mapper_Access) is begin for I in Mappers'Range loop if Mappers (I).First = null then Mappers (I).First := From; Mappers (I).Second := To; return; end if; end loop; Log.Error ("Too many wildcard mappers"); raise Mapping_Error with "Too many wildcard mapping, mapping is too complex!"; end Add_Mapper; function Find_Mapper (From : in Mapper_Access) return Mapper_Access is begin for I in Mappers'Range loop if Mappers (I).First = From then return Mappers (I).Second; end if; end loop; Log.Error ("Cannot find mapper {0}", System.Address_Image (From.all'Address)); return null; end Find_Mapper; procedure Append (To : in Mapper_Access; Item : in Mapper_Access) is Node : Mapper_Access := To.First_Child; begin if Node = null then To.First_Child := Item; else while Node.Next_Mapping /= null loop Node := Node.Next_Mapping; end loop; Node.Next_Mapping := Item; end if; end Append; procedure Copy (To : in Mapper_Access; From : in Mapper_Access) is N : Mapper_Access; Src : Mapper_Access := From; begin while Src /= null loop N := Src.Clone; N.Is_Clone := True; if N.Is_Deep_Wildcard then if N.Mapper /= null then N.Mapper := Find_Mapper (N.Mapper); else Add_Mapper (Src, N); end if; end if; Append (To, N); if Src.First_Child /= null then Copy (N, Src.First_Child); end if; Src := Src.Next_Mapping; end loop; end Copy; -- use type Util.Log.Level_Type; begin if Log.Get_Level >= Util.Log.INFO_LEVEL then Log.Info ("Mapping '{0}' for mapper {1}", Path, Ada.Tags.Expanded_Name (Map'Tag)); end if; -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapper /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Map.First_Child /= null then Copy (Node, Map.First_Child); else Node.Mapper := Map; end if; end Add_Mapping; procedure Add_Mapping (Into : in out Mapper; Path : in String; Map : in Mapping_Access) is use Ada.Strings.Unbounded; Node : Mapper_Access; Last_Pos : Natural; begin if Log.Get_Level >= Util.Log.INFO_LEVEL then Log.Info ("Mapping '{0}' for mapper {1}", Path, Ada.Tags.Expanded_Name (Map'Tag)); end if; -- Find or build the mapping tree. Into.Build_Path (Path, Last_Pos, Node); if Last_Pos < Path'Last then Log.Warn ("Ignoring the end of mapping path {0}", Path); end if; if Node.Mapping /= null then Log.Warn ("Overriding the mapping {0} for mapper X", Path); end if; if Length (Node.Name) = 0 then Log.Warn ("Mapped name is empty in mapping path {0}", Path); elsif Element (Node.Name, 1) = '@' then Delete (Node.Name, 1, 1); Map.Is_Attribute := True; else Map.Is_Attribute := False; end if; Node.Mapping := Map; Node.Mapper := Into'Unchecked_Access; end Add_Mapping; -- ----------------------- -- Clone the <b>Handler</b> instance and get a copy of that single object. -- ----------------------- function Clone (Handler : in Mapper) return Mapper_Access is Result : constant Mapper_Access := new Mapper; begin Result.Name := Handler.Name; Result.Mapper := Handler.Mapper; Result.Mapping := Handler.Mapping; Result.Is_Proxy_Mapper := Handler.Is_Proxy_Mapper; Result.Is_Clone := True; Result.Is_Wildcard := Handler.Is_Wildcard; Result.Is_Deep_Wildcard := Handler.Is_Deep_Wildcard; return Result; end Clone; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in Mapper; Name : in String; Value : in Util.Beans.Objects.Object; Attribute : in Boolean := False; Context : in out Util.Serialize.Contexts.Context'Class) is Map : constant Mapper_Access := Mapper'Class (Handler).Find_Mapper (Name, Attribute); begin if Map /= null and then Map.Mapping /= null and then Map.Mapper /= null then Map.Mapper.all.Execute (Map.Mapping.all, Context, Value); end if; end Set_Member; procedure Start_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Start_Object (Context, Name); end if; end Start_Object; procedure Finish_Object (Handler : in Mapper; Context : in out Util.Serialize.Contexts.Context'Class; Name : in String) is begin if Handler.Mapper /= null then Handler.Mapper.Finish_Object (Context, Name); end if; end Finish_Object; -- ----------------------- -- Dump the mapping tree on the logger using the INFO log level. -- ----------------------- procedure Dump (Handler : in Mapper'Class; Log : in Util.Log.Loggers.Logger'Class; Prefix : in String := "") is procedure Dump (Map : in Mapper'Class); -- ----------------------- -- Dump the mapping description -- ----------------------- procedure Dump (Map : in Mapper'Class) is Name : constant String := Ada.Strings.Unbounded.To_String (Map.Name); begin if Map.Mapping /= null and then Map.Mapping.Is_Attribute then Log.Info (" {0}@{1}", Prefix, Ada.Strings.Unbounded.To_String (Map.Mapping.Name)); else Log.Info (" {0}/{1}", Prefix, Name); Dump (Map, Log, Prefix & "/" & Name); end if; end Dump; begin Iterate (Handler, Dump'Access); end Dump; procedure Iterate (Controller : in Mapper; Process : not null access procedure (Map : in Mapper'Class)) is Node : Mapper_Access := Controller.First_Child; begin -- Pass 1: process the attributes first while Node /= null loop if Node.Mapping /= null and then Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; -- Pass 2: process the elements Node := Controller.First_Child; while Node /= null loop if Node.Mapping = null or else not Node.Mapping.Is_Attribute then Process.all (Node.all); end if; Node := Node.Next_Mapping; end loop; end Iterate; -- ----------------------- -- Finalize the object and release any mapping. -- ----------------------- overriding procedure Finalize (Controller : in out Mapper) is procedure Free is new Ada.Unchecked_Deallocation (Mapper'Class, Mapper_Access); procedure Free is new Ada.Unchecked_Deallocation (Mapping'Class, Mapping_Access); Node : Mapper_Access := Controller.First_Child; Next : Mapper_Access; begin Controller.First_Child := null; while Node /= null loop Next := Node.Next_Mapping; Free (Node); Node := Next; end loop; if not Controller.Is_Clone then Free (Controller.Mapping); else Controller.Mapping := null; end if; end Finalize; -- ------------------------------ -- Start a document. -- ------------------------------ procedure Start_Document (Stream : in out Processing) is Context : Element_Context_Access; begin Context_Stack.Clear (Stream.Stack); Context_Stack.Push (Stream.Stack); Context := Context_Stack.Current (Stream.Stack); Context.Active_Nodes (1) := Stream.Mapping_Tree'Unchecked_Access; end Start_Document; -- ------------------------------ -- Push the current context when entering in an element. -- ------------------------------ procedure Push (Handler : in out Processing) is begin Context_Stack.Push (Handler.Stack); end Push; -- ------------------------------ -- Pop the context and restore the previous context when leaving an element -- ------------------------------ procedure Pop (Handler : in out Processing) is begin Context_Stack.Pop (Handler.Stack); end Pop; function Find_Mapper (Handler : in Processing; Name : in String) return Util.Serialize.Mappers.Mapper_Access is pragma Unreferenced (Handler, Name); begin return null; end Find_Mapper; -- ------------------------------ -- Start a new object associated with the given name. This is called when -- the '{' is reached. The reader must be updated so that the next -- <b>Set_Member</b> procedure will associate the name/value pair on the -- new object. -- ------------------------------ procedure Start_Object (Handler : in out Processing; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); Next : Element_Context_Access; Pos : Positive; begin Log.Debug ("Start object {0}", Name); Context_Stack.Push (Handler.Stack); Next := Context_Stack.Current (Handler.Stack); if Current /= null then Pos := 1; -- Notify we are entering in the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); Child : Mappers.Mapper_Access; begin exit when Node = null; Child := Node.Find_Mapper (Name => Name); if Child = null and then Node.Is_Wildcard then Child := Node; end if; if Child /= null then Log.Debug ("{0} is matching {1}", Name, Child.Get_Name); Child.Start_Object (Handler, Name); Next.Active_Nodes (Pos) := Child; Pos := Pos + 1; end if; end; end loop; while Pos <= Next.Active_Nodes'Last loop Next.Active_Nodes (Pos) := null; Pos := Pos + 1; end loop; else Next.Active_Nodes (1) := Handler.Mapping_Tree.Find_Mapper (Name); end if; end Start_Object; -- ------------------------------ -- Finish an object associated with the given name. The reader must be -- updated to be associated with the previous object. -- ------------------------------ procedure Finish_Object (Handler : in out Processing; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Logger); begin Log.Debug ("Finish object {0}", Name); declare Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin if Current /= null then -- Notify we are leaving the given node for each active mapping. for I in Current.Active_Nodes'Range loop declare Node : constant Mappers.Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Finish_Object (Handler, Name); end; end loop; end if; end; Handler.Pop; end Finish_Object; procedure Start_Array (Handler : in out Processing; Name : in String; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Logger); begin Handler.Push; end Start_Array; procedure Finish_Array (Handler : in out Processing; Name : in String; Count : in Natural; Logger : in out Util.Log.Logging'Class) is pragma Unreferenced (Name, Count, Logger); begin Handler.Pop; end Finish_Array; -- ----------------------- -- Set the name/value pair on the current object. For each active mapping, -- find whether a rule matches our name and execute it. -- ----------------------- procedure Set_Member (Handler : in out Processing; Name : in String; Value : in Util.Beans.Objects.Object; Logger : in out Util.Log.Logging'Class; Attribute : in Boolean := False) is Current : constant Element_Context_Access := Context_Stack.Current (Handler.Stack); begin Log.Debug ("Set member {0}", Name); if Current /= null then -- Look each active mapping node. for I in Current.Active_Nodes'Range loop declare Node : constant Mapper_Access := Current.Active_Nodes (I); begin exit when Node = null; Node.Set_Member (Name => Name, Value => Value, Attribute => Attribute, Context => Handler); exception when E : Util.Serialize.Mappers.Field_Error => Logger.Error (Message => Ada.Exceptions.Exception_Message (E)); when E : Util.Serialize.Mappers.Field_Fatal_Error => Logger.Error (Message => Ada.Exceptions.Exception_Message (E)); raise; -- For other exception, report an error with the field name and value. when E : others => Logger.Error (Message => "Cannot set field '" & Name & "' to '" & Util.Beans.Objects.To_String (Value) & "': " & Ada.Exceptions.Exception_Message (E)); raise; end; end loop; end if; end Set_Member; procedure Add_Mapping (Handler : in out Processing; Path : in String; Mapper : in Util.Serialize.Mappers.Mapper_Access) is begin Handler.Mapping_Tree.Add_Mapping (Path, Mapper); end Add_Mapping; -- ------------------------------ -- Dump the mapping tree on the logger using the INFO log level. -- ------------------------------ procedure Dump (Handler : in Processing'Class; Logger : in Util.Log.Loggers.Logger'Class) is begin Util.Serialize.Mappers.Dump (Handler.Mapping_Tree, Logger, "Mapping "); end Dump; end Util.Serialize.Mappers;
charlie5/lace
Ada
571
ads
package freetype_c.FT_CharMapRec is type Item is record Face : access FT_FaceRec; Encoding : aliased FT_Encoding; Platform_Id : aliased FT_UShort; Encoding_Id : aliased FT_UShort; end record; type Item_array is array (C.Size_t range <>) of aliased FT_CharMapRec.Item; type Pointer is access all FT_CharMapRec.Item; type Pointer_array is array (C.Size_t range <>) of aliased FT_CharMapRec.Pointer; type pointer_Pointer is access all FT_CharMapRec.Pointer; end freetype_c.FT_CharMapRec;
reznikmm/matreshka
Ada
3,714
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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 XML.DOM.Attributes; package ODF.DOM.Draw_Marker_End_Attributes is pragma Preelaborate; type ODF_Draw_Marker_End_Attribute is limited interface and XML.DOM.Attributes.DOM_Attribute; type ODF_Draw_Marker_End_Attribute_Access is access all ODF_Draw_Marker_End_Attribute'Class with Storage_Size => 0; end ODF.DOM.Draw_Marker_End_Attributes;
msrLi/portingSources
Ada
1,295
ads
-- Copyright 2008-2014 Free Software Foundation, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. package Types is type Object_Int is interface; type Another_Int is interface; type Object_Root is abstract tagged record X : Natural; Y : Natural; end record; type Object is abstract new Object_Root and Object_Int and Another_Int with null record; function Ident (O : Object'Class) return Object'Class; procedure Do_Nothing (O : in out Object'Class); type Rectangle is new Object with record W : Natural; H : Natural; end record; type Circle is new Object with record R : Natural; end record; end Types;
sparre/Command-Line-Parser-Generator
Ada
611
ads
-- Copyright: JSA Research & Innovation <[email protected]> -- License: Beer Ware pragma License (Unrestricted); with Ada.Strings.Wide_Unbounded; package Command_Line_Parser_Generator is subtype Source_Text is Ada.Strings.Wide_Unbounded.Unbounded_Wide_String; function "+" (Item : in Source_Text) return Wide_String renames Ada.Strings.Wide_Unbounded.To_Wide_String; function "+" (Item : in Wide_String) return Source_Text renames Ada.Strings.Wide_Unbounded.To_Unbounded_Wide_String; function Trim (Item : in Wide_String) return Wide_String; end Command_Line_Parser_Generator;
reznikmm/matreshka
Ada
5,668
ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, Vadim Godunko <[email protected]> -- -- All rights reserved. -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions -- -- are met: -- -- -- -- * Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- -- -- * Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in the -- -- documentation and/or other materials provided with the distribution. -- -- -- -- * Neither the name of the Vadim Godunko, IE nor the names of its -- -- contributors may be used to endorse or promote products derived from -- -- this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ -- $Revision$ $Date$ ------------------------------------------------------------------------------ -- This file is generated, don't edit it. ------------------------------------------------------------------------------ -- An add variable value action is a write variable action for adding values -- to a variable. ------------------------------------------------------------------------------ limited with AMF.UML.Input_Pins; with AMF.UML.Write_Variable_Actions; package AMF.UML.Add_Variable_Value_Actions is pragma Preelaborate; type UML_Add_Variable_Value_Action is limited interface and AMF.UML.Write_Variable_Actions.UML_Write_Variable_Action; type UML_Add_Variable_Value_Action_Access is access all UML_Add_Variable_Value_Action'Class; for UML_Add_Variable_Value_Action_Access'Storage_Size use 0; not overriding function Get_Insert_At (Self : not null access constant UML_Add_Variable_Value_Action) return AMF.UML.Input_Pins.UML_Input_Pin_Access is abstract; -- Getter of AddVariableValueAction::insertAt. -- -- Gives the position at which to insert a new value or move an existing -- value in ordered variables. The types is UnlimitedINatural, but the -- value cannot be zero. This pin is omitted for unordered variables. not overriding procedure Set_Insert_At (Self : not null access UML_Add_Variable_Value_Action; To : AMF.UML.Input_Pins.UML_Input_Pin_Access) is abstract; -- Setter of AddVariableValueAction::insertAt. -- -- Gives the position at which to insert a new value or move an existing -- value in ordered variables. The types is UnlimitedINatural, but the -- value cannot be zero. This pin is omitted for unordered variables. not overriding function Get_Is_Replace_All (Self : not null access constant UML_Add_Variable_Value_Action) return Boolean is abstract; -- Getter of AddVariableValueAction::isReplaceAll. -- -- Specifies whether existing values of the variable should be removed -- before adding the new value. not overriding procedure Set_Is_Replace_All (Self : not null access UML_Add_Variable_Value_Action; To : Boolean) is abstract; -- Setter of AddVariableValueAction::isReplaceAll. -- -- Specifies whether existing values of the variable should be removed -- before adding the new value. end AMF.UML.Add_Variable_Value_Actions;
reznikmm/matreshka
Ada
7,141
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Style.Drawing_Page_Properties_Elements is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Elements.Element_L2_Parameters) return Style_Drawing_Page_Properties_Element_Node is begin return Self : Style_Drawing_Page_Properties_Element_Node do Matreshka.ODF_Style.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Style_Prefix); end return; end Create; ---------------- -- Enter_Node -- ---------------- overriding procedure Enter_Node (Self : not null access Style_Drawing_Page_Properties_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Enter_Style_Drawing_Page_Properties (ODF.DOM.Style_Drawing_Page_Properties_Elements.ODF_Style_Drawing_Page_Properties_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Enter_Node (Visitor, Control); end if; end Enter_Node; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Style_Drawing_Page_Properties_Element_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Drawing_Page_Properties_Element; end Get_Local_Name; ---------------- -- Leave_Node -- ---------------- overriding procedure Leave_Node (Self : not null access Style_Drawing_Page_Properties_Element_Node; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Visitor in ODF.DOM.Visitors.Abstract_ODF_Visitor'Class then ODF.DOM.Visitors.Abstract_ODF_Visitor'Class (Visitor).Leave_Style_Drawing_Page_Properties (ODF.DOM.Style_Drawing_Page_Properties_Elements.ODF_Style_Drawing_Page_Properties_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Leave_Node (Visitor, Control); end if; end Leave_Node; ---------------- -- Visit_Node -- ---------------- overriding procedure Visit_Node (Self : not null access Style_Drawing_Page_Properties_Element_Node; Iterator : in out XML.DOM.Visitors.Abstract_Iterator'Class; Visitor : in out XML.DOM.Visitors.Abstract_Visitor'Class; Control : in out XML.DOM.Visitors.Traverse_Control) is begin if Iterator in ODF.DOM.Iterators.Abstract_ODF_Iterator'Class then ODF.DOM.Iterators.Abstract_ODF_Iterator'Class (Iterator).Visit_Style_Drawing_Page_Properties (Visitor, ODF.DOM.Style_Drawing_Page_Properties_Elements.ODF_Style_Drawing_Page_Properties_Access (Self), Control); else Matreshka.DOM_Elements.Abstract_Element_Node (Self.all).Visit_Node (Iterator, Visitor, Control); end if; end Visit_Node; begin Matreshka.DOM_Documents.Register_Element (Matreshka.ODF_String_Constants.Style_URI, Matreshka.ODF_String_Constants.Drawing_Page_Properties_Element, Style_Drawing_Page_Properties_Element_Node'Tag); end Matreshka.ODF_Style.Drawing_Page_Properties_Elements;
AdaCore/gpr
Ada
14,443
adb
-- -- Copyright (C) 2022, AdaCore -- -- SPDX-License-Identifier: Apache-2.0 -- with Ada.Text_IO; with GNAT.OS_Lib; with GPR2.Containers; with GPR2.Message; with GPR2.Project.Attribute; with GPR2.Project.Attribute_Index; with GPR2.Project.Registry.Attribute; with GPR2.Project.Registry.Pack; package body GPR2_GNATCOLL_Projects is function Attribute_Value (Project : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : GPR2.Project.Attribute_Index.Object; Use_Extended : Boolean := False) return GPR2.Project.Attribute.Object; -- Internal Attribute_Value returning GPR2.Project.Attribute.Object. -- Single, List kinds and return type formating will be done by callers ------------------- -- Artifacts_Dir -- ------------------- function Artifacts_Dir (Project : GPR2.Project.View.Object) return GNATCOLL.VFS.Virtual_File is begin if Project.Is_Defined then if Project.Kind not in K_Configuration | K_Abstract and then Project.Object_Directory.Is_Defined then return GPR2.Path_Name.Virtual_File (Project.Object_Directory); elsif Project.Tree.Subdirs /= GPR2.No_Filename then return GPR2.Path_Name.Virtual_File (Project.Dir_Name.Compose (Project.Tree.Subdirs)); else return GPR2.Path_Name.Virtual_File (Project.Dir_Name); end if; else return GNATCOLL.VFS.No_File; end if; end Artifacts_Dir; --------------------- -- Attribute_Value -- --------------------- function Attribute_Value (Project : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : GPR2.Project.Attribute_Index.Object; Use_Extended : Boolean := False) return GPR2.Project.Attribute.Object is function Get_Attribute (View : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : GPR2.Project.Attribute_Index.Object := GPR2.Project.Attribute_Index.Undefined) return GPR2.Project.Attribute.Object; -- Get package's attribute value ------------------- -- Get_Attribute -- ------------------- function Get_Attribute (View : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : GPR2.Project.Attribute_Index.Object := GPR2.Project.Attribute_Index.Undefined) return GPR2.Project.Attribute.Object is Attribute : GPR2.Project.Attribute.Object; begin if View.Check_Attribute (Name => Name, Index => Index, Result => Attribute) then return Attribute; else return GPR2.Project.Attribute.Undefined; end if; end Get_Attribute; Attribute : GPR2.Project.Attribute.Object; -- Get_Attribute function return value begin if Project.Is_Defined then if Name.Pack /= Project_Level_Scope then -- Looking for a project's package's attribute if Project.Has_Package (Name => Name.Pack, Check_Extended => True) then Attribute := Get_Attribute (View => Project, Name => Name, Index => Index); end if; -- If not yet found look if required in extended list if not Attribute.Is_Defined and then Use_Extended and then Project.Is_Extending then declare Extended_Root : GPR2.Project.View.Object := Project.Extended_Root; begin while Extended_Root.Is_Defined loop if Extended_Root.Has_Package (Name => Name.Pack, Check_Extended => True) then Attribute := Get_Attribute (View => Extended_Root, Name => Name, Index => Index); end if; if not Attribute.Is_Defined and then Extended_Root.Is_Extending then -- Try extended of extended Extended_Root := Extended_Root.Extended_Root; else -- Exit the loop and look for configuration attribute Extended_Root := GPR2.Project.View.Undefined; end if; end loop; end; end if; -- If not yet found look for attribute in configuration view if not Attribute.Is_Defined and then Project.Tree.Has_Configuration and then Project.Tree.Configuration.Corresponding_View. Has_Package (Name => Name.Pack, Check_Extended => True) then Attribute := Get_Attribute (View => Project.Tree.Configuration.Corresponding_View, Name => Name, Index => Index); end if; else -- Look for attribute in view Attribute := Get_Attribute (View => Project, Name => Name, Index => Index); -- If not yet found look if required in extended list if not Attribute.Is_Defined and then Use_Extended and then Project.Is_Extending then declare Extended_Root : GPR2.Project.View.Object := Project.Extended_Root; begin while Extended_Root.Is_Defined loop Attribute := Get_Attribute (View => Extended_Root, Name => Name, Index => Index); if not Attribute.Is_Defined and then Extended_Root.Is_Extending then -- Try extended of extended Extended_Root := Extended_Root.Extended_Root; else -- Exit the loop and look for configuration attribute Extended_Root := GPR2.Project.View.Undefined; end if; end loop; end; end if; -- If not yet found look for attribute in configuration view if not Attribute.Is_Defined and then Project.Tree.Has_Configuration then Attribute := Get_Attribute (View => Project.Tree.Configuration.Corresponding_View, Name => Name, Index => Index); end if; end if; end if; return Attribute; end Attribute_Value; --------------------- -- Attribute_Value -- --------------------- function Attribute_Value (Project : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : String := ""; Default : String := ""; Use_Extended : Boolean := False) return String is begin if Name.Attr /= No_Attribute then declare Attribute : constant GPR2.Project.Attribute.Object := Attribute_Value (Project => Project, Name => Name, Index => (if Index = "" then GPR2.Project.Attribute_Index.Undefined else GPR2.Project.Attribute_Index.Create (Index)), Use_Extended => Use_Extended); use GPR2.Project.Registry.Attribute; begin if Attribute.Is_Defined and then Attribute.Kind = GPR2.Project.Registry.Attribute.Single then return Attribute.Value.Text; else return Default; end if; end; else return Default; end if; end Attribute_Value; --------------------- -- Attribute_Value -- --------------------- function Attribute_Value (Project : GPR2.Project.View.Object; Name : Q_Attribute_Id; Index : String := ""; Use_Extended : Boolean := False) return GNAT.Strings.String_List_Access is function List (Attribute : GPR2.Project.Attribute.Object) return GNAT.Strings.String_List_Access; -- convert attribute values to string list ---------- -- List -- ---------- function List (Attribute : GPR2.Project.Attribute.Object) return GNAT.Strings.String_List_Access is begin if Attribute.Is_Defined then declare List : constant GNAT.Strings.String_List_Access := new GNAT.Strings.String_List (1 .. Integer (Attribute.Count_Values)); I : Integer := 1; begin for Value of Attribute.Values loop List (I) := new String'(Value.Text); I := I + 1; end loop; return List; end; else return null; end if; end List; begin if Name.Attr /= No_Attribute then return List (Attribute_Value (Project => Project, Name => Name, Index => (if Index = "" then GPR2.Project.Attribute_Index.Undefined else GPR2.Project.Attribute_Index.Create (Index)), Use_Extended => Use_Extended)); else return null; end if; end Attribute_Value; ------------ -- Create -- ------------ function Create (Self : GPR2.Project.Tree.Object; Name : GNATCOLL.VFS.Filesystem_String; Project : GPR2.Project.View.Object'Class := GPR2.Project.View.Undefined; Use_Source_Path : Boolean := True; Use_Object_Path : Boolean := True) return GNATCOLL.VFS.Virtual_File is use GNATCOLL.VFS; begin if GNAT.OS_Lib.Is_Absolute_Path (+Name) then return GNATCOLL.VFS.Create (Full_Filename => Name); else declare Full_Path : constant GPR2.Path_Name.Object := Self.Get_File (Base_Name => GPR2.Path_Name.Create (GPR2.Filename_Type (Name), GPR2.Filename_Type (Name)).Simple_Name, View => GPR2.Project.View.Object (Project), Use_Source_Path => Use_Source_Path, Use_Object_Path => Use_Object_Path); begin if not Full_Path.Is_Defined then return GNATCOLL.VFS.Create (Full_Filename => Name); else return GNATCOLL.VFS.Create (Full_Filename => +String (Full_Path.Value)); end if; end; end if; end Create; --------------------- -- Output_Messages -- --------------------- procedure Output_Messages (Log : GPR2.Log.Object; Output_Warnings : Boolean := True; Output_Information : Boolean := False) is use GPR2.Log; Displayed : GPR2.Containers.Value_Set; begin for C in Log.Iterate (Information => Output_Information, Warning => Output_Warnings, Error => True, Read => True, Unread => True) loop declare use Ada.Text_IO; use GPR2.Message; Msg : constant GPR2.Log.Constant_Reference_Type := Log.Constant_Reference (C); Text : constant String := Msg.Format; Dummy : GPR2.Containers.Value_Type_Set.Cursor; Inserted : Boolean; begin Displayed.Insert (Text, Dummy, Inserted); if Inserted then Put_Line (File_Access' (case Msg.Level is when Information | Lint => Current_Output, when Warning | Error => Current_Error).all, Text); end if; end; end loop; end Output_Messages; ---------------------------- -- Register_New_Attribute -- ---------------------------- function Register_New_Attribute (Name : Q_Attribute_Id; Is_List : Boolean := False; Indexed : Boolean := False; Case_Sensitive_Index : Boolean := False) return String is begin if Name.Attr = No_Attribute then return "cannot register attribute without name for package " & Image (Name.Pack); end if; if Name.Pack /= Project_Level_Scope and then not GPR2.Project.Registry.Pack.Exists (Name.Pack) then GPR2.Project.Registry.Pack.Add (Name.Pack, GPR2.Project.Registry.Pack.Everywhere); end if; GPR2.Project.Registry.Attribute.Add (Name => Name, Index_Type => (if not Indexed then GPR2.Project.Registry.Attribute.No_Index elsif Case_Sensitive_Index then GPR2.Project.Registry.Attribute.Env_Var_Name_Index else GPR2.Project.Registry.Attribute.Unit_Index), Value => (if Is_List then GPR2.Project.Registry.Attribute.List else GPR2.Project.Registry.Attribute.Single), Value_Case_Sensitive => False, Is_Allowed_In => GPR2.Project.Registry.Attribute.Everywhere); return ""; exception when others => return "cannot register new attribute " & Image (Name.Attr) & " for package " & Image (Name.Pack); end Register_New_Attribute; end GPR2_GNATCOLL_Projects;
dshadrin/AProxy
Ada
4,451
adb
---------------------------------------- -- Copyright (C) 2019 Dmitriy Shadrin -- -- All rights reserved. -- ---------------------------------------- with Sax.Readers; use Sax.Readers; with Input_Sources.File; use Input_Sources.File; with Unicode.CES; with Sax.Attributes; with Sax.Utils; with Sax.Symbols; -------------------------------------------------------------------------------- package body ConfigTree.SaxParser is ----------------------------------------------------------------------------- type Reader is new Sax.Readers.Reader with record parent : NodePtr; current : NodePtr; end record; ----------------------------------------------------------------------------- procedure Start_Element (Handler : in out Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := ""; Atts : Sax.Attributes.Attributes'Class); ----------------------------------------------------------------------------- procedure End_Element (Handler : in out Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := ""); ----------------------------------------------------------------------------- procedure Characters (Handler : in out Reader; Ch : Unicode.CES.Byte_Sequence); ----------------------------------------------------------------------------- procedure Start_Element (Handler : in out Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := ""; Atts : Sax.Attributes.Attributes'Class) is temp : NodePtr := new Node; begin if Handler.current.childFirst = null then Handler.current.childFirst := temp; Handler.current.childLast := temp; else Handler.current.childLast.next := temp; temp.previous := Handler.current.childLast; Handler.current.childLast := temp; end if; temp.parent := Handler.current; Handler.parent := Handler.current; Handler.current := temp; Handler.current.name := Ada.Strings.Unbounded.To_Unbounded_String (Qname); end Start_Element; ----------------------------------------------------------------------------- procedure End_Element (Handler : in out Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := "") is x : Integer := 0; use type Ada.Strings.Unbounded.Unbounded_String; begin if Handler.current.name = Ada.Strings.Unbounded.To_Unbounded_String (Qname) then Handler.current := Handler.parent; Handler.parent := Handler.current.parent; else raise Program_Error; end if; end End_Element; ----------------------------------------------------------------------------- procedure Characters (Handler : in out Reader; Ch : Unicode.CES.Byte_Sequence) is use type Ada.Strings.Unbounded.Unbounded_String; begin Handler.current.data := Handler.current.data & Ada.Strings.Unbounded.To_Unbounded_String (Ch); end Characters; ----------------------------------------------------------------------------- procedure Parse (root : in out ConfigTree.NodePtr) is saxReader : Reader; input : File_Input; begin Set_Public_Id (input, "Configure file"); Set_System_Id (input, "proxy.xml"); Open ("proxy.xml", input); Set_Feature (saxReader, Namespace_Prefixes_Feature, False); Set_Feature (saxReader, Namespace_Feature, False); Set_Feature (saxReader, Validation_Feature, False); saxReader.parent := null; saxReader.current := root; Parse (saxReader, input); Close (input); end Parse; end ConfigTree.SaxParser;
reznikmm/matreshka
Ada
4,664
adb
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Open Document Toolkit -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2014, Vadim Godunko <[email protected]> -- -- 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.DOM_Documents; with Matreshka.ODF_String_Constants; with ODF.DOM.Iterators; with ODF.DOM.Visitors; package body Matreshka.ODF_Table.Acceptance_State_Attributes is ------------ -- Create -- ------------ overriding function Create (Parameters : not null access Matreshka.DOM_Attributes.Attribute_L2_Parameters) return Table_Acceptance_State_Attribute_Node is begin return Self : Table_Acceptance_State_Attribute_Node do Matreshka.ODF_Table.Constructors.Initialize (Self'Unchecked_Access, Parameters.Document, Matreshka.ODF_String_Constants.Table_Prefix); end return; end Create; -------------------- -- Get_Local_Name -- -------------------- overriding function Get_Local_Name (Self : not null access constant Table_Acceptance_State_Attribute_Node) return League.Strings.Universal_String is pragma Unreferenced (Self); begin return Matreshka.ODF_String_Constants.Acceptance_State_Attribute; end Get_Local_Name; begin Matreshka.DOM_Documents.Register_Attribute (Matreshka.ODF_String_Constants.Table_URI, Matreshka.ODF_String_Constants.Acceptance_State_Attribute, Table_Acceptance_State_Attribute_Node'Tag); end Matreshka.ODF_Table.Acceptance_State_Attributes;
AdaCore/libadalang
Ada
50,899
adb
------------------------------------------------------------------------------ -- G P S -- -- -- -- Copyright (C) 2001-2017, AdaCore -- -- -- -- This 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. This software 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. See the GNU General Public -- -- License for more details. You should have received a copy of the GNU -- -- General Public License distributed with this software; see file -- -- COPYING3. If not, go to http://www.gnu.org/licenses for a complete copy -- -- of the license. -- ------------------------------------------------------------------------------ with Ada.Characters.Handling; use Ada.Characters.Handling; with Ada.Strings.Equal_Case_Insensitive; use Ada.Strings; with Ada.Unchecked_Deallocation; with Generic_Views; with GNATCOLL.Arg_Lists; use GNATCOLL.Arg_Lists; with GNATCOLL.Scripts; use GNATCOLL.Scripts; with GNATCOLL.Traces; use GNATCOLL.Traces; with GNATCOLL.Utils; use GNATCOLL.Utils; with GNATCOLL.VFS; use GNATCOLL.VFS; with GNATCOLL.VFS.GtkAda; use GNATCOLL.VFS.GtkAda; with GNATCOLL.VFS_Utils; use GNATCOLL.VFS_Utils; with Gdk.RGBA; use Gdk.RGBA; with Gdk.Event; use Gdk.Event; with Glib; use Glib; with Glib.Convert; use Glib.Convert; with Glib.Object; use Glib.Object; with Glib_Values_Utils; use Glib_Values_Utils; with Gtk.Box; use Gtk.Box; with Gtk.Cell_Renderer_Text; use Gtk.Cell_Renderer_Text; with Gtk.Enums; use Gtk.Enums; with Gtk.Label; use Gtk.Label; with Gtk.Menu; use Gtk.Menu; with Gtk.Scrolled_Window; use Gtk.Scrolled_Window; with Gtk.Tree_Model; use Gtk.Tree_Model; with Gtk.Tree_Selection; use Gtk.Tree_Selection; with Gtk.Tree_Store; use Gtk.Tree_Store; with Gtk.Tree_View; use Gtk.Tree_View; with Gtk.Tree_View_Column; use Gtk.Tree_View_Column; with Gtkada.Handlers; use Gtkada.Handlers; with Gtkada.MDI; use Gtkada.MDI; with Commands.Interactive; use Commands, Commands.Interactive; with Default_Preferences; use Default_Preferences; with Extending_Projects_Editors; use Extending_Projects_Editors; with GPS.Intl; use GPS.Intl; with GPS.Kernel.Actions; use GPS.Kernel.Actions; with GPS.Kernel.Contexts; use GPS.Kernel.Contexts; with GPS.Kernel.Hooks; use GPS.Kernel.Hooks; with GPS.Kernel.MDI; use GPS.Kernel.MDI; with GPS.Kernel.Modules; use GPS.Kernel.Modules; with GPS.Kernel.Modules.UI; use GPS.Kernel.Modules.UI; with GPS.Kernel.Preferences; use GPS.Kernel.Preferences; with GPS.Kernel.Project; use GPS.Kernel.Project; with GPS.Kernel.Scripts; use GPS.Kernel.Scripts; with GUI_Utils; use GUI_Utils; with Language_Handlers; use Language_Handlers; with Project_Properties; use Project_Properties; with Projects; use Projects; with Remote; use Remote; with Switches_Editors; use Switches_Editors; with System; with Variable_Editors; use Variable_Editors; package body Project_Viewers is Me : constant Trace_Handle := Create ("Project_Viewers"); type Naming_Page is record Language : GNAT.Strings.String_Access; Creator : Naming_Scheme_Editor_Creator; end record; type Naming_Pages_Array is array (Natural range <>) of Naming_Page; type Naming_Pages_Array_Access is access Naming_Pages_Array; type Prj_Editor_Module_Id_Record is new Module_ID_Record with record Naming_Pages : Naming_Pages_Array_Access; end record; type Prj_Editor_Module_Id_Access is access all Prj_Editor_Module_Id_Record'Class; Prj_Editor_Module_ID : Prj_Editor_Module_Id_Access; -- Id for the project editor module Project_Switches_Name : constant String := "Project Switches"; Directory_Cst : aliased constant String := "directory"; Imported_Cst : aliased constant String := "imported"; Src_Path_Cst : aliased constant String := "sources"; Obj_Path_Cst : aliased constant String := "objects"; Name_Cst : aliased constant String := "name"; Path_Cst : aliased constant String := "path"; Add_Source_Dir_Cmd_Parameters : constant Cst_Argument_List := (1 => Directory_Cst'Access); Remove_Dep_Cmd_Parameters : constant GNATCOLL.Scripts.Cst_Argument_List := (1 => Imported_Cst'Access); Add_Predefined_Parameters : constant GNATCOLL.Scripts.Cst_Argument_List := (1 => Src_Path_Cst'Access, 2 => Obj_Path_Cst'Access); Rename_Cmd_Parameters : constant GNATCOLL.Scripts.Cst_Argument_List := (1 => Name_Cst'Access, 2 => Path_Cst'Access); Add_Dep_Cmd_Parameters : constant GNATCOLL.Scripts.Cst_Argument_List := (1 => Path_Cst'Access); Display_File_Name_Column : constant := 0; -- This columns contains the UTF8 representation of the file name File_Column : constant := 1; -- This column contains the file itself Compiler_Switches_Column : constant := 2; Compiler_Color_Column : constant := 3; type Project_Viewer_Record is new Generic_Views.View_Record with record Tree : Gtk.Tree_View.Gtk_Tree_View; Model : Gtk.Tree_Store.Gtk_Tree_Store; -- The actual contents of the viewer Default_Switches_Color : Gdk.RGBA.Gdk_RGBA; -- Color to use when displaying switches that are set at the project -- level, rather than file specific View_Changed_Blocked : Boolean := False; -- True if the hook for "project_view_changed" should be ignored Current_Project : Project_Type; -- The project to which the files currently in the viewer belong. This -- indicates which project file should be normalized when a modification -- takes place. Current_Dir : Virtual_File := No_File; -- The directory currently being shown end record; function Initialize (Viewer : access Project_Viewer_Record'Class) return Gtk_Widget; -- Create a new project viewer, and return the focus widget. -- Every time the selection in Explorer changes, the info displayed in -- the viewer is changed. type Files_Child_Record is new GPS_MDI_Child_Record with null record; overriding function Build_Context (Self : not null access Files_Child_Record; Event : Gdk.Event.Gdk_Event := null) return Selection_Context; package File_Views is new Generic_Views.Simple_Views (Formal_View_Record => Project_Viewer_Record, Module_Name => "File_Switches", View_Name => -"Switches editor", Formal_MDI_Child => Files_Child_Record, Initialize => Initialize, Reuse_If_Exist => True, Local_Toolbar => True, Areas => Gtkada.MDI.Central_Only, Group => Group_Default, Position => Position_Automatic); subtype Project_Viewer is File_Views.View_Access; use File_Views; procedure Show_Project (Viewer : access Project_Viewer_Record'Class; Project_Filter : Project_Type; Directory_Filter : Virtual_File := GNATCOLL.VFS.No_File); -- Shows all the direct source files of Project_Filter (ie not including -- imported projects, but including all source directories). -- This clears the list first. -- Directory_Filter should be used to limit the search path for the files. -- Only the files in Directory_Filter will be displayed. -- -- Project_Filter mustn't be No_Project. procedure Append_Line (Viewer : access Project_Viewer_Record'Class; File_Name : Virtual_File; Directory_Filter : Virtual_File := GNATCOLL.VFS.No_File); -- Append a new line in the current page of Viewer, for File_Name. -- The exact contents inserted depends on the current view. -- The file is automatically searched in all the source directories of -- Project_View. function Select_Row (Viewer : access Gtk_Widget_Record'Class; Event : Gdk_Event) return Boolean; -- Callback when a row/column has been selected in the clist type On_Context_Changed is new Context_Hooks_Function with null record; overriding procedure Execute (Self : On_Context_Changed; Kernel : not null access Kernel_Handle_Record'Class; Context : Selection_Context); -- Called every time the selection has changed in the tree procedure Explorer_Selection_Changed (Viewer : access Project_Viewer_Record'Class; Context : Selection_Context); -- Same as above, but work directly on a context type Save_All_Command is new Interactive_Command with null record; overriding function Execute (Command : access Save_All_Command; Context : Interactive_Command_Context) return Command_Return_Type; -- Save the project associated with the kernel, and all its imported -- projects. type Edit_File_Switches is new Interactive_Command with null record; overriding function Execute (Command : access Edit_File_Switches; Context : Interactive_Command_Context) return Command_Return_Type; -- Edit the switches for all the files selected in Viewer procedure Project_Command_Handler (Data : in out Callback_Data'Class; Command : String); -- Handle the interactive commands related to the project editor procedure Project_Static_Command_Handler (Data : in out Callback_Data'Class; Command : String); -- Handle static methods for the GPS.Project class procedure Update_Contents (Viewer : access Project_Viewer_Record'Class; Project : Project_Type; Directory : Virtual_File := GNATCOLL.VFS.No_File; File : Virtual_File := GNATCOLL.VFS.No_File); -- Update the contents of the viewer. -- Directory and File act as filters for the information that is displayed. procedure Project_Viewers_Set (Viewer : access Project_Viewer_Record'Class; Iter : Gtk_Tree_Iter); -- Set the contents of the line Iter in the model. It is assumed the file -- name has already been set on that line type On_Pref_Changed is new Preferences_Hooks_Function with record View : access Project_Viewer_Record'Class; end record; overriding procedure Execute (Self : On_Pref_Changed; Kernel : not null access Kernel_Handle_Record'Class; Pref : Preference); -- Hook called when the preferences change type On_Project_View_Changed is new Simple_Hooks_Function with null record; overriding procedure Execute (Self : On_Project_View_Changed; Kernel : not null access Kernel_Handle_Record'Class); -- Hook called when the project view changes ---------------------- -- Contextual menus -- ---------------------- type Save_Project_Command is new Interactive_Command with null record; overriding function Execute (Command : access Save_Project_Command; Context : Interactive_Command_Context) return Command_Return_Type; type Edit_Project_Source_Command is new Interactive_Command with null record; overriding function Execute (Command : access Edit_Project_Source_Command; Context : Interactive_Command_Context) return Command_Return_Type; ------------------------- -- Project_Viewers_Set -- ------------------------- procedure Project_Viewers_Set (Viewer : access Project_Viewer_Record'Class; Iter : Gtk_Tree_Iter) is procedure Internal (Tree, Iter : System.Address; Col2 : Gint; Value2 : String; Col3 : Gint; Value3 : Gdk_RGBA); pragma Import (C, Internal, "ada_gtk_tree_store_set_ptr_ptr"); File_Name : constant Virtual_File := Get_File (Viewer.Model, Iter, File_Column); Language : constant String := Get_Language_From_File (Get_Language_Handler (Viewer.Kernel), File_Name); Color : Gdk_RGBA; Value : String_List_Access; Is_Default : Boolean; begin Viewer.Current_Project.Switches (Compiler_Package, File_Name, Language, Value, Is_Default); if Is_Default then Color := Viewer.Default_Switches_Color; else Color := Black_RGBA; end if; Internal (Get_Object (Viewer.Model), Iter'Address, Compiler_Switches_Column, Locale_To_UTF8 (Argument_List_To_String (Value.all)) & ASCII.NUL, Compiler_Color_Column, Color); Free (Value); end Project_Viewers_Set; ----------------- -- Append_Line -- ----------------- procedure Append_Line (Viewer : access Project_Viewer_Record'Class; File_Name : Virtual_File; Directory_Filter : Virtual_File := GNATCOLL.VFS.No_File) is Iter : Gtk_Tree_Iter; begin if Directory_Filter = GNATCOLL.VFS.No_File or else Dir (File_Name) = Directory_Filter then Append (Viewer.Model, Iter, Null_Iter); Set_And_Clear (Viewer.Model, Iter, (Display_File_Name_Column, File_Column), (0 => As_String (File_Name.Display_Base_Name), 1 => As_File (File_Name))); Project_Viewers_Set (Viewer, Iter); end if; end Append_Line; ---------------- -- Select_Row -- ---------------- function Select_Row (Viewer : access Gtk_Widget_Record'Class; Event : Gdk_Event) return Boolean is V : constant Project_Viewer := Project_Viewer (Viewer); Iter : Gtk_Tree_Iter; begin if Get_Event_Type (Event) = Gdk_2button_Press and then Get_Button (Event) = 1 then Iter := Find_Iter_For_Event (V.Tree, Event); if Iter /= Null_Iter then if not Iter_Is_Selected (Get_Selection (V.Tree), Iter) then Unselect_All (Get_Selection (V.Tree)); Select_Iter (Get_Selection (V.Tree), Iter); end if; V.Kernel.Context_Changed (File_Views.Child_From_View (V).Build_Context); return Execute_Action (V.Kernel, Action => "edit switches for file", Error_Msg_In_Console => True); end if; end if; return False; end Select_Row; ------------- -- Execute -- ------------- overriding procedure Execute (Self : On_Project_View_Changed; Kernel : not null access Kernel_Handle_Record'Class) is pragma Unreferenced (Self); View : constant Project_Viewer := File_Views.Retrieve_View (Kernel); begin if not View.View_Changed_Blocked then View.Current_Project := Get_Project (Kernel); Show_Project (View, View.Current_Project); end if; end Execute; --------------------- -- Update_Contents -- --------------------- procedure Update_Contents (Viewer : access Project_Viewer_Record'Class; Project : Project_Type; Directory : Virtual_File := GNATCOLL.VFS.No_File; File : Virtual_File := GNATCOLL.VFS.No_File) is Child : constant MDI_Child := File_Views.Child_From_View (Viewer); Iter : Gtk_Tree_Iter; Path : Gtk_Tree_Path; begin -- If the context is invalid, keep the currently displayed lines, so -- that when a new MDI child is selected, the contents of the viewer is -- not necessarily reset. if Child /= null then if Directory = GNATCOLL.VFS.No_File then Set_Title (Child, Title => -"Editing switches for project " & Project.Name, Short_Title => Project_Switches_Name); else Set_Title (Child, Title => -"Editing switches for directory " & Directory.Display_Full_Name, Short_Title => Project_Switches_Name); end if; end if; Viewer.Current_Project := Project; if Viewer.Current_Project /= No_Project then Show_Project (Viewer, Viewer.Current_Project, Directory); end if; if File /= GNATCOLL.VFS.No_File then Iter := Get_Iter_First (Viewer.Model); while Iter /= Null_Iter loop if Get_File (Viewer.Model, Iter, File_Column) = File then Unselect_All (Get_Selection (Viewer.Tree)); Select_Iter (Get_Selection (Viewer.Tree), Iter); Path := Get_Path (Viewer.Model, Iter); Scroll_To_Cell (Viewer.Tree, Path, null, True, 0.5, 0.5); Path_Free (Path); exit; end if; Next (Viewer.Model, Iter); end loop; end if; end Update_Contents; -------------------------------- -- Explorer_Selection_Changed -- -------------------------------- procedure Explorer_Selection_Changed (Viewer : access Project_Viewer_Record'Class; Context : Selection_Context) is begin -- If the context is invalid, keep the currently displayed lines, so -- that when a new MDI child is selected, the contents of the viewer is -- not necessarily reset. if Has_File_Information (Context) then Update_Contents (Viewer, Project_Information (Context), Directory_Information (Context), File_Information (Context)); else Update_Contents (Viewer, Get_Project (Viewer.Kernel)); end if; end Explorer_Selection_Changed; ------------- -- Execute -- ------------- overriding procedure Execute (Self : On_Context_Changed; Kernel : not null access Kernel_Handle_Record'Class; Context : Selection_Context) is pragma Unreferenced (Self); View : constant Project_Viewer := File_Views.Retrieve_View (Kernel); Child : constant MDI_Child := Get_Focus_Child (Get_MDI (Kernel)); begin -- Do nothing if we forced the selection change ourselves. For instance, -- when a new switch editor is created in On_Edit_Switches, to avoid -- doing extra work. if Child = null or else Get_Widget (Child) /= Gtk_Widget (View) then Explorer_Selection_Changed (View, Context); end if; end Execute; ---------------- -- Initialize -- ---------------- function Initialize (Viewer : access Project_Viewer_Record'Class) return Gtk_Widget is Context : constant Selection_Context := Get_Current_Context (Viewer.Kernel); Column_Types : constant GType_Array := (Display_File_Name_Column => GType_String, File_Column => Get_Virtual_File_Type, Compiler_Switches_Column => GType_String, Compiler_Color_Column => Gdk.RGBA.Get_Type); Scrolled : Gtk_Scrolled_Window; Col : Gtk_Tree_View_Column; Render : Gtk_Cell_Renderer_Text; Col_Number : Gint; H : access On_Pref_Changed; pragma Unreferenced (Col_Number); begin Gtk.Box.Initialize_Hbox (Viewer); Gtk_New (Scrolled); Set_Policy (Scrolled, Policy_Automatic, Policy_Automatic); Add (Viewer, Scrolled); Gtk_New (Viewer.Model, Column_Types); Gtk_New (Viewer.Tree, Viewer.Model); Set_Mode (Get_Selection (Viewer.Tree), Selection_Multiple); Add (Scrolled, Viewer.Tree); Gtk_New (Col); Col_Number := Append_Column (Viewer.Tree, Col); Set_Title (Col, -"File"); Set_Resizable (Col, True); Set_Reorderable (Col, True); Gtk_New (Render); Pack_Start (Col, Render, False); Set_Sort_Column_Id (Col, Display_File_Name_Column); Add_Attribute (Col, Render, "text", Display_File_Name_Column); Clicked (Col); Gtk_New (Col); Col_Number := Append_Column (Viewer.Tree, Col); Set_Title (Col, -"Compiler switches"); Set_Resizable (Col, True); Set_Reorderable (Col, True); Gtk_New (Render); Pack_Start (Col, Render, False); Set_Sort_Column_Id (Col, Compiler_Switches_Column); Add_Attribute (Col, Render, "text", Compiler_Switches_Column); Add_Attribute (Col, Render, "foreground_rgba", Compiler_Color_Column); Setup_Contextual_Menu (Kernel => Viewer.Kernel, Event_On_Widget => Viewer.Tree); Return_Callback.Object_Connect (Viewer.Tree, Signal_Button_Press_Event, Return_Callback.To_Marshaller (Select_Row'Access), Viewer); Context_Changed_Hook.Add (new On_Context_Changed, Watch => Viewer); Project_View_Changed_Hook.Add (new On_Project_View_Changed, Watch => Viewer); H := new On_Pref_Changed; H.View := Viewer; Preferences_Changed_Hook.Add (H, Watch => Viewer); H.Execute (Viewer.Kernel, null); Show_All (Viewer); -- The initial contents of the viewer should be read immediately from -- the explorer, without forcing the user to do a new selection. if Context /= No_Context then Explorer_Selection_Changed (Viewer, Context); else Update_Contents (Viewer, Get_Project (Viewer.Kernel)); end if; return Gtk_Widget (Viewer.Tree); end Initialize; ------------- -- Execute -- ------------- overriding procedure Execute (Self : On_Pref_Changed; Kernel : not null access Kernel_Handle_Record'Class; Pref : Preference) is pragma Unreferenced (Kernel); View : constant Project_Viewer := Project_Viewer (Self.View); begin View.Default_Switches_Color := Default_Switches_Color.Get_Pref; -- ??? Do we need to change the model to reflect this change if View /= null then Set_Font_And_Colors (View, Fixed_Font => True, Pref => Pref); end if; end Execute; ------------------ -- Show_Project -- ------------------ procedure Show_Project (Viewer : access Project_Viewer_Record'Class; Project_Filter : Project_Type; Directory_Filter : Virtual_File := GNATCOLL.VFS.No_File) is Files : File_Array_Access := Project_Filter.Source_Files (Recursive => False); Same_Dir_And_Project : constant Boolean := (Viewer.Current_Project = Project_Filter and then Directory_Filter /= No_File and then Viewer.Current_Dir = Directory_Filter); Sorted : Gint; begin Viewer.Current_Project := Project_Filter; if Same_Dir_And_Project then return; end if; if Directory_Filter /= No_File then Viewer.Current_Dir := Directory_Filter; end if; Clear (Viewer.Model); Sorted := Freeze_Sort (Viewer.Model); Ref (Viewer.Model); -- Do not refresh while adding files Set_Model (Viewer.Tree, Null_Gtk_Tree_Model); for F in Files'Range loop Append_Line (Viewer, Files (F), Directory_Filter); end loop; Thaw_Sort (Viewer.Model, Sorted); Set_Model (Viewer.Tree, +Viewer.Model); Unref (Viewer.Model); Unchecked_Free (Files); end Show_Project; ------------- -- Execute -- ------------- overriding function Execute (Command : access Save_All_Command; Context : Interactive_Command_Context) return Command_Return_Type is Tmp : Boolean; Kernel : constant Kernel_Handle := Get_Kernel (Context.Context); pragma Unreferenced (Command, Tmp); begin Tmp := Save_Project (Kernel, Get_Project (Kernel), Recursive => True); return Commands.Success; end Execute; ------------- -- Execute -- ------------- overriding function Execute (Command : access Save_Project_Command; Context : Interactive_Command_Context) return Command_Return_Type is pragma Unreferenced (Command); Kernel : constant Kernel_Handle := Get_Kernel (Context.Context); Project : constant Project_Type := Project_Information (Context.Context); begin if Save_Project (Kernel, Project) then return Success; else return Failure; end if; end Execute; ------------- -- Execute -- ------------- overriding function Execute (Command : access Edit_Project_Source_Command; Context : Interactive_Command_Context) return Command_Return_Type is pragma Unreferenced (Command); Kernel : constant Kernel_Handle := Get_Kernel (Context.Context); Project : Project_Type; begin if Has_Project_Information (Context.Context) then Project := Project_Information (Context.Context); else Project := Kernel.Registry.Tree.Root_Project; end if; Open_File_Action_Hook.Run (Kernel, File => Project.Project_Path, Project => Project); return Success; end Execute; ------------------- -- Build_Context -- ------------------- overriding function Build_Context (Self : not null access Files_Child_Record; Event : Gdk.Event.Gdk_Event := null) return Selection_Context is V : constant Project_Viewer := Project_Viewer (GPS_MDI_Child (Self).Get_Actual_Widget); Iter : Gtk_Tree_Iter; Context : Selection_Context := GPS_MDI_Child_Record (Self.all).Build_Context (Event); begin Iter := Find_Iter_For_Event (V.Tree, Event); if Iter = Null_Iter then Set_File_Information (Context, Project => V.Current_Project); else if not Iter_Is_Selected (Get_Selection (V.Tree), Iter) then Unselect_All (Get_Selection (V.Tree)); Select_Iter (Get_Selection (V.Tree), Iter); end if; declare File_Name : constant Virtual_File := Get_File (V.Model, Iter, File_Column); begin Set_File_Information (Context, Files => (1 => File_Name), Project => V.Current_Project); end; end if; return Context; end Build_Context; ------------- -- Execute -- ------------- overriding function Execute (Command : access Edit_File_Switches; Context : Interactive_Command_Context) return Command_Return_Type is pragma Unreferenced (Command); V : constant Project_Viewer := File_Views.Retrieve_View (Get_Kernel (Context.Context)); Selection : Gtk_Tree_Selection; Length : Natural := 0; Iter : Gtk_Tree_Iter; begin if V = null then return Commands.Failure; end if; Selection := V.Tree.Get_Selection; Iter := V.Model.Get_Iter_First; while Iter /= Null_Iter loop if Iter_Is_Selected (Selection, Iter) then Length := Length + 1; end if; Next (V.Model, Iter); end loop; declare Names : File_Array (1 .. Length); N : Natural := Names'First; begin Iter := Get_Iter_First (V.Model); while Iter /= Null_Iter loop if Iter_Is_Selected (Selection, Iter) then Names (N) := Get_File (V.Model, Iter, File_Column); N := N + 1; end if; Next (V.Model, Iter); end loop; if Edit_Switches_For_Files (V.Kernel, V.Current_Project, Names) then -- Temporarily block the handlers so that the the editor is not -- cleared, or we would lose the selection V.View_Changed_Blocked := True; Recompute_View (V.Kernel); V.View_Changed_Blocked := False; Iter := Get_Iter_First (V.Model); while Iter /= Null_Iter loop if Iter_Is_Selected (Selection, Iter) then Project_Viewers_Set (V, Iter); end if; Next (V.Model, Iter); end loop; end if; end; return Commands.Success; end Execute; ------------------------------------ -- Project_Static_Command_Handler -- ------------------------------------ procedure Project_Static_Command_Handler (Data : in out Callback_Data'Class; Command : String) is function Remove_Redundant_Directories (Old_Path, New_Path : File_Array) return File_Array; -- Return New_Path after having removed the directories that have been -- found on Old_Path. ---------------------------------- -- Remove_Redundant_Directories -- ---------------------------------- function Remove_Redundant_Directories (Old_Path, New_Path : File_Array) return File_Array is Returned_Path : File_Array (1 .. New_Path'Length); Returned_Path_Length : Integer := 0; Found : Boolean; begin for J in New_Path'Range loop Found := False; for K in Old_Path'Range loop if New_Path (J) = Old_Path (K) then Found := True; exit; end if; end loop; if not Found then Returned_Path_Length := Returned_Path_Length + 1; Returned_Path (Returned_Path_Length) := New_Path (J); end if; end loop; return Returned_Path (1 .. Returned_Path_Length); end Remove_Redundant_Directories; Kernel : constant Kernel_Handle := Get_Kernel (Data); begin if Command = "add_predefined_paths" then Name_Parameters (Data, Add_Predefined_Parameters); declare Old_Src : constant File_Array := Get_Registry (Kernel).Environment.Predefined_Source_Path; Old_Obj : constant File_Array := Get_Registry (Kernel).Environment.Predefined_Object_Path; New_Src : constant File_Array := Remove_Redundant_Directories (Old_Src, From_Path (Nth_Arg (Data, 1, ""))); New_Obj : constant File_Array := Remove_Redundant_Directories (Old_Obj, From_Path (+Nth_Arg (Data, 2, ""))); begin if New_Src'Length /= 0 then Get_Registry (Kernel).Environment.Set_Predefined_Source_Path (New_Src & Old_Src); end if; if Old_Obj'Length /= 0 then Get_Registry (Kernel).Environment.Set_Predefined_Object_Path (New_Obj & Old_Obj); end if; end; end if; end Project_Static_Command_Handler; ----------------------------- -- Project_Command_Handler -- ----------------------------- procedure Project_Command_Handler (Data : in out Callback_Data'Class; Command : String) is procedure Set_Error_Tmp (Str : String); -- Set an error --------------- -- Set_Error -- --------------- procedure Set_Error_Tmp (Str : String) is begin Set_Error_Msg (Data, Str); end Set_Error_Tmp; Kernel : constant Kernel_Handle := Get_Kernel (Data); Project : constant Project_Type := Get_Data (Data, 1); begin if Command = "add_main_unit" then declare Args : GNAT.Strings.String_List (1 .. Number_Of_Arguments (Data) - 1); begin if not Is_Editable (Project) then Set_Error_Msg (Data, -"Project is not editable"); else for Index in 2 .. Number_Of_Arguments (Data) loop Args (Index - 1) := new String'(Nth_Arg (Data, Index)); end loop; Project.Set_Attribute (Scenario => Scenario_Variables (Kernel), Attribute => Main_Attribute, Values => Args, Prepend => True); Recompute_View (Kernel); Free (Args); end if; end; elsif Command = "rename" then Name_Parameters (Data, Rename_Cmd_Parameters); declare Name : constant String := Nth_Arg (Data, 2); Path : constant Filesystem_String := Nth_Arg (Data, 3, Project_Directory (Project).Full_Name); begin if not Is_Editable (Project) then Set_Error_Msg (Data, -"Project is not editable"); else Project.Rename_And_Move (New_Name => Name, Directory => Create (Path), Errors => Set_Error_Tmp'Unrestricted_Access); Project_Changed_Hook.Run (Kernel); end if; end; elsif Command = "remove_dependency" then Name_Parameters (Data, Remove_Dep_Cmd_Parameters); declare Project2 : constant Project_Type := Get_Data (Data, 2); begin if not Is_Editable (Project) then Set_Error_Msg (Data, -"Project is not editable"); else Remove_Imported_Project (Project, Project2); end if; end; elsif Command = "add_dependency" then Name_Parameters (Data, Add_Dep_Cmd_Parameters); declare Project2 : constant Filesystem_String := Normalize_Pathname (Name => Nth_Arg (Data, 2)); Relative : constant Boolean := Get_Paths_Type (Project) = Projects.Relative or else (Get_Paths_Type (Project) = From_Pref and then Generate_Relative_Paths.Get_Pref); Error : Import_Project_Error; pragma Unreferenced (Error); begin if not Is_Editable (Project) then Set_Error_Msg (Data, -"Project is not editable"); else Error := Get_Registry (Kernel).Tree.Add_Imported_Project (Project => Project, Imported_Project_Location => Create (Project2), Errors => Set_Error_Tmp'Unrestricted_Access, Use_Base_Name => False, Use_Relative_Path => Relative); end if; end; elsif Command = "add_source_dir" then Name_Parameters (Data, Add_Source_Dir_Cmd_Parameters); declare Dir : constant Virtual_File := Create (Normalize_Pathname (Nth_Arg (Data, 2), Directory => Full_Name (Project_Directory (Project)), Resolve_Links => False)); Dirs : GNAT.Strings.String_List (1 .. 1); Sources : constant File_Array := Project.Source_Dirs (Recursive => False); Found : Boolean := False; begin Ensure_Directory (Dir); Dirs (1) := new String'(+Dir.Full_Name); if not Is_Editable (Project) then Set_Error_Msg (Data, -"Project is not editable"); else for S in Sources'Range loop if Sources (S) = Dir then Found := True; exit; end if; end loop; if not Found then Project.Set_Attribute (Scenario => Scenario_Variables (Get_Kernel (Data)), Attribute => Source_Dirs_Attribute, Values => Dirs, Index => "", Prepend => True); end if; Free (Dirs); end if; end; elsif Command = "remove_source_dir" then Name_Parameters (Data, Add_Source_Dir_Cmd_Parameters); declare Dir : Virtual_File := Create (Nth_Arg (Data, 2), Get_Nickname (Build_Server)); Dirs : String_List_Access := Project.Attribute_Value (Source_Dirs_Attribute); Index : Natural := Dirs'Last; begin if not Is_Editable (Project) or else Dirs = null then Set_Error_Msg (Data, -"Project is not editable"); else if not Is_Absolute_Path (Dir) then Dir := Create_From_Base (Nth_Arg (Data, 2), Get_Current_Dir (Get_Nickname (Build_Server)).Full_Name.all); end if; for D in Dirs'Range loop declare Tested_Dir : Virtual_File := Create (+Dirs (D).all, Get_Nickname (Build_Server)); begin if not Is_Absolute_Path (Tested_Dir) then Tested_Dir := Create_From_Base (+Dirs (D).all, Get_Current_Dir (Get_Nickname (Build_Server)).Full_Name.all); end if; if Dir = Tested_Dir then Free (Dirs (D)); Dirs (D .. Dirs'Last - 1) := Dirs (D + 1 .. Dirs'Last); Index := Index - 1; end if; end; end loop; Project.Set_Attribute (Scenario => Scenario_Variables (Get_Kernel (Data)), Attribute => Source_Dirs_Attribute, Values => Dirs (Dirs'First .. Index), Index => ""); end if; Free (Dirs); end; end if; end Project_Command_Handler; ----------------------------------- -- Register_Naming_Scheme_Editor -- ----------------------------------- procedure Register_Naming_Scheme_Editor (Kernel : access GPS.Kernel.Kernel_Handle_Record'Class; Language : String; Creator : Naming_Scheme_Editor_Creator) is pragma Unreferenced (Kernel); procedure Unchecked_Free is new Ada.Unchecked_Deallocation (Naming_Pages_Array, Naming_Pages_Array_Access); Tmp : Naming_Pages_Array_Access; Lang : constant String := To_Lower (Language); begin if Prj_Editor_Module_ID /= null then if Prj_Editor_Module_ID.Naming_Pages = null then Prj_Editor_Module_ID.Naming_Pages := new Naming_Pages_Array'(1 => (new String'(Lang), Creator)); else Tmp := Prj_Editor_Module_ID.Naming_Pages; Prj_Editor_Module_ID.Naming_Pages := new Naming_Pages_Array' (Tmp.all & Naming_Page'(new String'(Lang), Creator)); Unchecked_Free (Tmp); end if; else Trace (Me, "Register_Naming_Scheme_Editor: module not registered"); end if; end Register_Naming_Scheme_Editor; ---------------------------- -- Get_Naming_Scheme_Page -- ---------------------------- function Get_Naming_Scheme_Page (Kernel : access GPS.Kernel.Kernel_Handle_Record'Class; Language : String) return Project_Editor_Page is Lang : constant String := To_Lower (Language); begin if Prj_Editor_Module_ID.Naming_Pages /= null then for Num in Prj_Editor_Module_ID.Naming_Pages'Range loop if Prj_Editor_Module_ID.Naming_Pages (Num).Language.all = Lang then return Prj_Editor_Module_ID.Naming_Pages (Num).Creator (Kernel, Language); end if; end loop; end if; return null; end Get_Naming_Scheme_Page; -------------------------------- -- Get_All_Naming_Scheme_Page -- -------------------------------- function Get_All_Naming_Scheme_Page (Kernel : access GPS.Kernel.Kernel_Handle_Record'Class) return Project_Editor_Page is Languages : GNAT.Strings.String_List := Known_Languages (Get_Language_Handler (Kernel)); Page : Project_Editor_Page; Result : access Project_Editor_Multi_Page_Record; begin Result := new Project_Editor_Multi_Page_Record; for L in Languages'Range loop Page := Get_Naming_Scheme_Page (Kernel, Languages (L).all); if Page /= null then Result.Add_Page (Page, To_Unbounded_String (Languages (L).all)); end if; end loop; Free (Languages); return Project_Editor_Page (Result); end Get_All_Naming_Scheme_Page; --------------------- -- Register_Module -- --------------------- procedure Register_Module (Kernel : access GPS.Kernel.Kernel_Handle_Record'Class) is Filter : Action_Filter; Filter2 : Action_Filter; begin Prj_Editor_Module_ID := new Prj_Editor_Module_Id_Record; Register_Module (Module => Module_ID (Prj_Editor_Module_ID), Kernel => Kernel, Module_Name => Project_Editor_Module_Name, Priority => Default_Priority); File_Views.Register_Module (Kernel); Filter := Lookup_Filter (Kernel, "Project only"); Filter2 := Lookup_Filter (Kernel, "Project only") and Lookup_Filter (Kernel, "Editable Project"); -- These two commands are doing the same work, but the second can be -- used in contextual menu since it is filtered. Register_Action (Kernel, "open Project Properties", Command => new Project_Properties_Editor_Command, Description => "Open the project properties editor", Icon_Name => "gps-edit-symbolic", Category => -"Views"); Register_Action (Kernel, "edit project properties", Command => new Project_Properties_Editor_Command, Description => "Open the project properties editor", Icon_Name => "gps-edit-symbolic", Filter => Filter2, -- editable project Category => -"Views"); Register_Action (Kernel, "save all projects", Command => new Save_All_Command, Category => -"Projects", Description => -"Save all modified projects to disk"); Register_Action (Kernel, "edit switches for file", new Edit_File_Switches, -"Edit the switches for the selected files", Icon_Name => "gps-edit-symbolic"); Register_Contextual_Menu (Kernel, Label => "Project/Properties", Action => "edit project properties"); Register_Action (Kernel, "save project", Command => new Save_Project_Command, Description => -"Save the selected project", Filter => Filter2, Category => -"Projects"); Register_Contextual_Menu (Kernel, Action => "save project", Label => "Project/Save project %p"); Register_Action (Kernel, "Edit project source file", Command => new Edit_Project_Source_Command, Description => -"Open an editor for the .gpr file of the current project", Filter => Filter, Category => -"Projects"); Register_Contextual_Menu (Kernel, Name => "Project/Edit source file", Action => "Edit project source file"); Register_Action (Kernel, Action_Add_Scenario_Variable, Command => new Add_Variable_Command, Icon_Name => "gps-add-symbolic", Description => -"Add a new scenario variable to the selected project", Category => -"Projects"); Register_Contextual_Menu (Kernel, Name => "Add scenario variable", Action => Action_Add_Scenario_Variable, Filter => Create (Module => Explorer_Module_Name) and Filter2, Label => "Project/Add scenario variable"); Register_Action (Kernel, "edit file switches", Command => new Edit_Switches_Command, Description => "Edit the compilation switches for the source files", Filter => Lookup_Filter (Kernel, "Project and file"), Category => -"Projects"); Register_Contextual_Menu (Kernel, Action => "edit file switches", Label => "Edit switches for %f"); Extending_Projects_Editors.Register_Contextual_Menus (Kernel); Kernel.Scripts.Register_Command ("add_main_unit", Minimum_Args => 1, Maximum_Args => Natural'Last, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); Kernel.Scripts.Register_Command ("remove_dependency", Minimum_Args => Remove_Dep_Cmd_Parameters'Length, Maximum_Args => Remove_Dep_Cmd_Parameters'Length, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); Kernel.Scripts.Register_Command ("add_dependency", Minimum_Args => 1, Maximum_Args => 1, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); Kernel.Scripts.Register_Command ("rename", Minimum_Args => 1, Maximum_Args => 2, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); Kernel.Scripts.Register_Command ("add_predefined_paths", Maximum_Args => 2, Class => Get_Project_Class (Kernel), Static_Method => True, Handler => Project_Static_Command_Handler'Access); Kernel.Scripts.Register_Command ("add_source_dir", Minimum_Args => Add_Source_Dir_Cmd_Parameters'Length, Maximum_Args => Add_Source_Dir_Cmd_Parameters'Length, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); Kernel.Scripts.Register_Command ("remove_source_dir", Minimum_Args => Add_Source_Dir_Cmd_Parameters'Length, Maximum_Args => Add_Source_Dir_Cmd_Parameters'Length, Class => Get_Project_Class (Kernel), Handler => Project_Command_Handler'Access); end Register_Module; ------------------- -- For_Each_Page -- ------------------- procedure For_Each_Page (Self : not null access Project_Editor_Multi_Page_Record; Callback : Page_Iterator_Callback) is begin for Descr of Self.Pages loop Callback (Descr.Page); end loop; end For_Each_Page; ------------- -- Destroy -- ------------- overriding procedure Destroy (Self : in out Project_Editor_Multi_Page_Record) is begin for Descr of Self.Pages loop Project_Viewers.Destroy (Descr.Page.all); end loop; end Destroy; ------------- -- In_List -- ------------- function In_List (Lang : String; List : GNAT.Strings.String_List) return Boolean is begin for L of List loop if Equal_Case_Insensitive (Lang, L.all) then return True; end if; end loop; return False; end In_List; -------------- -- Add_Page -- -------------- procedure Add_Page (Self : not null access Project_Editor_Multi_Page_Record; Page : not null access Project_Editor_Page_Record'Class; Title : Unbounded_String) is begin Self.Pages.Append ((Title => Title, Page => Project_Editor_Page (Page))); end Add_Page; ---------------- -- Initialize -- ---------------- overriding procedure Initialize (Self : not null access Project_Editor_Multi_Page_Record; Kernel : not null access Kernel_Handle_Record'Class; Read_Only : Boolean; Project : Project_Type := No_Project) is Label : Gtk_Label; begin Dialog_Utils.Initialize (Self); Gtk_New (Self.Notebook); Self.Append (Self.Notebook, Fill => True, Expand => True); for Descr of Self.Pages loop Gtk_New (Label, To_String (Descr.Title)); Descr.Page.Initialize (Kernel, Read_Only, Project); Self.Notebook.Append_Page (Descr.Page, Label); end loop; end Initialize; ------------------ -- Edit_Project -- ------------------ overriding function Edit_Project (Self : not null access Project_Editor_Multi_Page_Record; Project : Project_Type; Kernel : not null access Kernel_Handle_Record'Class; Languages : GNAT.Strings.String_List; Scenario_Variables : Scenario_Variable_Array) return Boolean is Changed : Boolean := False; begin for Descr of Self.Pages loop if Descr.Page.Is_Visible then Changed := Changed or Descr.Page.Edit_Project (Project, Kernel, Languages, Scenario_Variables); end if; end loop; return Changed; end Edit_Project; ---------------- -- Is_Visible -- ---------------- overriding function Is_Visible (Self : not null access Project_Editor_Multi_Page_Record; Languages : GNAT.Strings.String_List) return Boolean is Count : constant Gint := Self.Notebook.Get_N_Pages; Page : Project_Editor_Page; Visible : Boolean := False; begin for P in 0 .. Count - 1 loop Page := Project_Editor_Page (Self.Notebook.Get_Nth_Page (P)); if not Page.Is_Visible (Languages) then Page.Hide; else Visible := True; end if; end loop; return Visible; -- If at least one page is visible end Is_Visible; end Project_Viewers;
sparre/aYAML
Ada
2,527
adb
package body YAML.Object is overriding function Get (Item : in Instance; Name : in String) return Parent_Class is pragma Unreferenced (Item, Name); begin return raise Program_Error with "Not implemented yet."; end Get; overriding function Get (Item : in Instance; Index : in Positive) return Parent_Class is pragma Unreferenced (Item, Index); begin return raise Constraint_Error with "YAML.Object uses name-based look-up."; end Get; overriding function Get (Item : in Instance; Name : in String) return String is pragma Unreferenced (Item, Name); begin return raise Program_Error with "Not implemented yet."; end Get; overriding function Get (Item : in Instance; Index : in Positive) return String is pragma Unreferenced (Item, Index); begin return raise Constraint_Error with "YAML.Object uses name-based look-up."; end Get; overriding function Get (Item : in Instance; Name : in String; Default : in String) return String is pragma Unreferenced (Item, Name, Default); begin return raise Program_Error with "Not implemented yet."; end Get; overriding function Get (Item : in Instance; Index : in Positive; Default : in String) return String is pragma Unreferenced (Item, Index, Default); begin return raise Constraint_Error with "YAML.Object uses name-based look-up."; end Get; overriding function Has (Item : in Instance; Name : in String) return Boolean is pragma Unreferenced (Item, Name); begin return raise Program_Error with "Not implemented yet."; end Has; overriding function Has (Item : in Instance; Index : in Positive) return Boolean is pragma Unreferenced (Item, Index); begin return False; end Has; package body Parse is function Get (Item : in Instance; Name : in String) return Element_Type is begin return Value (Item.Get (Name => Name)); end Get; function Get (Item : in Instance; Name : in String; Default : in Element_Type) return Element_Type is begin return Value (Item.Get (Name => Name, Default => Image (Default))); end Get; end Parse; end YAML.Object;
tum-ei-rcs/StratoX
Ada
2,461
adb
-- Institution: Technische Universität München -- Department: Realtime Computer Systems (RCS) -- Project: StratoX -- -- Authors: Emanuel Regnath ([email protected]) with STM32.I2C; with STM32.Device; with HAL.I2C; --with HMC5883L.Register; -- @summary -- target-specific mapping for HIL of SPI package body HIL.I2C with SPARK_Mode => Off is --ADDR_HMC5883L : HAL.I2C.I2C_Address := HMC5883L.Register.HMC5883L_ADDRESS; procedure initialize is Config : constant STM32.I2C.I2C_Configuration := ( Clock_Speed => 100_000, Mode => STM32.I2C.I2C_Mode, Duty_Cycle => STM32.I2C.DutyCycle_2, Addressing_Mode => STM32.I2C.Addressing_Mode_7bit, Own_Address => 16#00#, General_Call_Enabled => False, Clock_Stretching_Enabled => True ); begin --STM32.I2C.Configure(STM32.Device.I2C_1, Config); null; end initialize; procedure write (Device : in Device_Type; Data : in Data_Type) is Status : HAL.I2C.I2C_Status; begin case (Device) is when UNKNOWN => null; -- when MAGNETOMETER => -- STM32.I2C.Master_Transmit(STM32.Device.I2C_1, ADDR_HMC5883L, HAL.I2C.I2C_Data( Data ), Status); end case; end write; procedure read (Device : in Device_Type; Data : out Data_Type) is Data_RX_I2C : HAL.I2C.I2C_Data(1 .. Data'Length); Status : HAL.I2C.I2C_Status; begin case (Device) is when UNKNOWN => null; -- when MAGNETOMETER => -- STM32.I2C.Master_Receive(STM32.Device.I2C_1, ADDR_HMC5883L, Data_RX_I2C, Status); -- Data := Data_Type( Data_RX_I2C); end case; end read; procedure transfer (Device : in Device_Type; Data_TX : in Data_Type; Data_RX : out Data_Type) is Data_RX_I2C : HAL.I2C.I2C_Data(1 .. Data_RX'Length); Status : HAL.I2C.I2C_Status; begin case (Device) is when UNKNOWN => null; -- when MAGNETOMETER => -- STM32.I2C.Master_Transmit(STM32.Device.I2C_1, ADDR_HMC5883L, HAL.I2C.I2C_Data( Data_TX ), Status); -- STM32.I2C.Master_Receive(STM32.Device.I2C_1, ADDR_HMC5883L, Data_RX_I2C, Status); -- Data_RX := Data_Type( Data_RX_I2C); end case; end transfer; end HIL.I2C;
stcarrez/swagger-ada
Ada
1,652
adb
-- ------------ EDIT NOTE ------------ -- REST API Validation -- API to validate -- This file was generated with openapi-generator. You can modify it to implement -- the client. After you modify this file, you should add the following line -- to the .openapi-generator-ignore file: -- -- src/testapi.ads -- -- Then, you can drop this edit note comment. -- ------------ EDIT NOTE ------------ with TestAPI.Clients; with TestAPI.Models; with Swagger; with Swagger.Credentials.OAuth; with Util.Http.Clients.Curl; with Ada.Text_IO; with Ada.Command_Line; with Ada.Calendar.Formatting; with Ada.Exceptions; procedure TestAPI.Client is use Ada.Text_IO; procedure Usage; Server : constant Swagger.UString := Swagger.To_UString ("http://localhost:8080/v2"); Arg_Count : constant Natural := Ada.Command_Line.Argument_Count; Arg : Positive := 1; procedure Usage is begin Put_Line ("Usage: TestAPI {params}..."); end Usage; begin if Arg_Count <= 1 then Usage; return; end if; Util.Http.Clients.Curl.Register; declare Command : constant String := Ada.Command_Line.Argument (Arg); Item : constant String := Ada.Command_Line.Argument (Arg + 1); Cred : aliased Swagger.Credentials.OAuth.OAuth2_Credential_Type; C : TestAPI.Clients.Client_Type; begin C.Set_Server (Server); C.Set_Credentials (Cred'Unchecked_Access); Arg := Arg + 2; exception when E : Constraint_Error => Put_Line ("Constraint error raised: " & Ada.Exceptions.Exception_Message (E)); end; end TestAPI.Client;