id
int64
0
30.9k
extension
stringclasses
1 value
max_stars_count
int64
0
17k
max_stars_repo_name
stringlengths
7
106
max_stars_repo_path
stringlengths
5
136
text
stringlengths
9
1M
30,100
ada
5
DependableSystemsLab/Trident
llvm-2.9/test/FrontendAda/switch.adb
-- RUN: %llvmgcc -S %s function Switch (N : Integer) return Integer is begin case N is when Integer'First .. -1 => return -1; when 0 => return 0; when others => return 1; end case; end;
30,101
ada
1
brucegua/moocos
tools/scitools/conf/understand/ada/ada95/s-powtab.ads
<filename>tools/scitools/conf/understand/ada/ada95/s-powtab.ads ------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- S Y S T E M . P O W T E N _ T A B L E -- -- -- -- S p e c -- -- -- -- $Revision: 2 $ -- -- -- -- Copyright (c) 1992,1993,1994 NYU, All Rights Reserved -- -- -- -- The GNAT library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU Library General Public License as published by -- -- the Free Software Foundation; either version 2, or (at your option) any -- -- later version. The GNAT library is distributed in the hope that it will -- -- be useful, but WITHOUT ANY WARRANTY; without even the implied warranty -- -- of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- Library General Public License for more details. You should have -- -- received a copy of the GNU Library General Public License along with -- -- the GNAT library; see the file COPYING.LIB. If not, write to the Free -- -- Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. -- -- -- ------------------------------------------------------------------------------ -- This package provides a powers of ten table used for real conversions package System.Powten_Table is pragma Pure (Powten_Table); -- The number of entries in this table is chosen to be large enough to -- correspond to the number of decimal digits in a 128-bit integer. It -- seems unlikely that Long_Long_Integer will have more than 128-bits -- for some time to come! Powten : constant array (0 .. 40) of Long_Long_Float := (00 => 1.0E+00, 01 => 1.0E+01, 02 => 1.0E+02, 03 => 1.0E+03, 04 => 1.0E+04, 05 => 1.0E+05, 06 => 1.0E+06, 07 => 1.0E+07, 08 => 1.0E+08, 09 => 1.0E+09, 10 => 1.0E+10, 11 => 1.0E+11, 12 => 1.0E+12, 13 => 1.0E+13, 14 => 1.0E+14, 15 => 1.0E+15, 16 => 1.0E+16, 17 => 1.0E+17, 18 => 1.0E+18, 19 => 1.0E+19, 20 => 1.0E+20, 21 => 1.0E+21, 22 => 1.0E+22, 23 => 1.0E+23, 24 => 1.0E+24, 25 => 1.0E+25, 26 => 1.0E+26, 27 => 1.0E+27, 28 => 1.0E+28, 29 => 1.0E+29, 30 => 1.0E+30, 31 => 1.0E+31, 32 => 1.0E+32, 33 => 1.0E+33, 34 => 1.0E+34, 35 => 1.0E+35, 36 => 1.0E+36, 37 => 1.0E+37, 38 => 1.0E+38, 39 => 1.0E+39, 40 => 1.0E+40); end System.Powten_Table;
30,102
ada
24
svn2github/matreshka
source/amf/uml/amf-internals-uml_protocol_transitions.ads
------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Ada Modeling Framework -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2011-2012, <NAME> <<EMAIL>> -- -- 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.String_Collections; with AMF.UML.Behaviors; with AMF.UML.Classifiers.Collections; with AMF.UML.Constraints.Collections; with AMF.UML.Dependencies.Collections; with AMF.UML.Element_Imports.Collections; with AMF.UML.Named_Elements.Collections; with AMF.UML.Namespaces; with AMF.UML.Operations.Collections; with AMF.UML.Package_Imports.Collections; with AMF.UML.Packageable_Elements.Collections; with AMF.UML.Packages.Collections; with AMF.UML.Protocol_Transitions; with AMF.UML.Redefinable_Elements.Collections; with AMF.UML.Regions; with AMF.UML.State_Machines; with AMF.UML.String_Expressions; with AMF.UML.Transitions; with AMF.UML.Triggers.Collections; with AMF.UML.Vertexs; with AMF.Visitors; package AMF.Internals.UML_Protocol_Transitions is type UML_Protocol_Transition_Proxy is limited new AMF.Internals.UML_Named_Elements.UML_Named_Element_Proxy and AMF.UML.Protocol_Transitions.UML_Protocol_Transition with null record; overriding function Get_Post_Condition (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Constraints.UML_Constraint_Access; -- Getter of ProtocolTransition::postCondition. -- -- Specifies the post condition of the transition which is the condition -- that should be obtained once the transition is triggered. This post -- condition is part of the post condition of the operation connected to -- the transition. overriding procedure Set_Post_Condition (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Constraints.UML_Constraint_Access); -- Setter of ProtocolTransition::postCondition. -- -- Specifies the post condition of the transition which is the condition -- that should be obtained once the transition is triggered. This post -- condition is part of the post condition of the operation connected to -- the transition. overriding function Get_Pre_Condition (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Constraints.UML_Constraint_Access; -- Getter of ProtocolTransition::preCondition. -- -- Specifies the precondition of the transition. It specifies the -- condition that should be verified before triggering the transition. -- This guard condition added to the source state will be evaluated as -- part of the precondition of the operation referred by the transition if -- any. overriding procedure Set_Pre_Condition (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Constraints.UML_Constraint_Access); -- Setter of ProtocolTransition::preCondition. -- -- Specifies the precondition of the transition. It specifies the -- condition that should be verified before triggering the transition. -- This guard condition added to the source state will be evaluated as -- part of the precondition of the operation referred by the transition if -- any. overriding function Get_Referred (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Operations.Collections.Set_Of_UML_Operation; -- Getter of ProtocolTransition::referred. -- -- This association refers to the associated operation. It is derived from -- the operation of the call trigger when applicable. overriding function Get_Container (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Regions.UML_Region_Access; -- Getter of Transition::container. -- -- Designates the region that owns this transition. overriding procedure Set_Container (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Regions.UML_Region_Access); -- Setter of Transition::container. -- -- Designates the region that owns this transition. overriding function Get_Effect (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Behaviors.UML_Behavior_Access; -- Getter of Transition::effect. -- -- Specifies an optional behavior to be performed when the transition -- fires. overriding procedure Set_Effect (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Behaviors.UML_Behavior_Access); -- Setter of Transition::effect. -- -- Specifies an optional behavior to be performed when the transition -- fires. overriding function Get_Guard (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Constraints.UML_Constraint_Access; -- Getter of Transition::guard. -- -- A guard is a constraint that provides a fine-grained control over the -- firing of the transition. The guard is evaluated when an event -- occurrence is dispatched by the state machine. If the guard is true at -- that time, the transition may be enabled, otherwise, it is disabled. -- Guards should be pure expressions without side effects. Guard -- expressions with side effects are ill formed. overriding procedure Set_Guard (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Constraints.UML_Constraint_Access); -- Setter of Transition::guard. -- -- A guard is a constraint that provides a fine-grained control over the -- firing of the transition. The guard is evaluated when an event -- occurrence is dispatched by the state machine. If the guard is true at -- that time, the transition may be enabled, otherwise, it is disabled. -- Guards should be pure expressions without side effects. Guard -- expressions with side effects are ill formed. overriding function Get_Kind (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.UML_Transition_Kind; -- Getter of Transition::kind. -- -- Indicates the precise type of the transition. overriding procedure Set_Kind (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.UML_Transition_Kind); -- Setter of Transition::kind. -- -- Indicates the precise type of the transition. overriding function Get_Redefined_Transition (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Transitions.UML_Transition_Access; -- Getter of Transition::redefinedTransition. -- -- The transition that is redefined by this transition. overriding procedure Set_Redefined_Transition (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Transitions.UML_Transition_Access); -- Setter of Transition::redefinedTransition. -- -- The transition that is redefined by this transition. overriding function Get_Redefinition_Context (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Classifiers.UML_Classifier_Access; -- Getter of Transition::redefinitionContext. -- -- References the classifier in which context this element may be -- redefined. overriding function Get_Source (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Vertexs.UML_Vertex_Access; -- Getter of Transition::source. -- -- Designates the originating vertex (state or pseudostate) of the -- transition. overriding procedure Set_Source (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Vertexs.UML_Vertex_Access); -- Setter of Transition::source. -- -- Designates the originating vertex (state or pseudostate) of the -- transition. overriding function Get_Target (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Vertexs.UML_Vertex_Access; -- Getter of Transition::target. -- -- Designates the target vertex that is reached when the transition is -- taken. overriding procedure Set_Target (Self : not null access UML_Protocol_Transition_Proxy; To : AMF.UML.Vertexs.UML_Vertex_Access); -- Setter of Transition::target. -- -- Designates the target vertex that is reached when the transition is -- taken. overriding function Get_Trigger (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Triggers.Collections.Set_Of_UML_Trigger; -- Getter of Transition::trigger. -- -- Specifies the triggers that may fire the transition. overriding function Get_Element_Import (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Element_Imports.Collections.Set_Of_UML_Element_Import; -- Getter of Namespace::elementImport. -- -- References the ElementImports owned by the Namespace. overriding function Get_Imported_Member (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element; -- Getter of Namespace::importedMember. -- -- References the PackageableElements that are members of this Namespace -- as a result of either PackageImports or ElementImports. overriding function Get_Member (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element; -- Getter of Namespace::member. -- -- A collection of NamedElements identifiable within the Namespace, either -- by being owned or by being introduced by importing or inheritance. overriding function Get_Owned_Member (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element; -- Getter of Namespace::ownedMember. -- -- A collection of NamedElements owned by the Namespace. overriding function Get_Owned_Rule (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Constraints.Collections.Set_Of_UML_Constraint; -- Getter of Namespace::ownedRule. -- -- Specifies a set of Constraints owned by this Namespace. overriding function Get_Package_Import (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Package_Imports.Collections.Set_Of_UML_Package_Import; -- Getter of Namespace::packageImport. -- -- References the PackageImports owned by the Namespace. overriding function Get_Client_Dependency (Self : not null access constant UML_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transition_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 Get_Is_Leaf (Self : not null access constant UML_Protocol_Transition_Proxy) return Boolean; -- Getter of RedefinableElement::isLeaf. -- -- Indicates whether it is possible to further redefine a -- RedefinableElement. If the value is true, then it is not possible to -- further redefine the RedefinableElement. Note that this property is -- preserved through package merge operations; that is, the capability to -- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in -- the resulting RedefinableElement of a package merge operation where a -- RedefinableElement with isLeaf=false is merged with a matching -- RedefinableElement with isLeaf=true: the resulting RedefinableElement -- will have isLeaf=false. Default value is false. overriding procedure Set_Is_Leaf (Self : not null access UML_Protocol_Transition_Proxy; To : Boolean); -- Setter of RedefinableElement::isLeaf. -- -- Indicates whether it is possible to further redefine a -- RedefinableElement. If the value is true, then it is not possible to -- further redefine the RedefinableElement. Note that this property is -- preserved through package merge operations; that is, the capability to -- redefine a RedefinableElement (i.e., isLeaf=false) must be preserved in -- the resulting RedefinableElement of a package merge operation where a -- RedefinableElement with isLeaf=false is merged with a matching -- RedefinableElement with isLeaf=true: the resulting RedefinableElement -- will have isLeaf=false. Default value is false. overriding function Get_Redefined_Element (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Redefinable_Elements.Collections.Set_Of_UML_Redefinable_Element; -- Getter of RedefinableElement::redefinedElement. -- -- The redefinable element that is being redefined by this element. overriding function Get_Redefinition_Context (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Classifiers.Collections.Set_Of_UML_Classifier; -- Getter of RedefinableElement::redefinitionContext. -- -- References the contexts that this element may be redefined from. overriding function Referred (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Operations.Collections.Set_Of_UML_Operation; -- Operation ProtocolTransition::referred. -- -- Missing derivation for ProtocolTransition::/referred : Operation overriding function Containing_State_Machine (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.State_Machines.UML_State_Machine_Access; -- Operation Transition::containingStateMachine. -- -- The query containingStateMachine() returns the state machine that -- contains the transition either directly or transitively. overriding function Is_Consistent_With (Self : not null access constant UML_Protocol_Transition_Proxy; Redefinee : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean; -- Operation Transition::isConsistentWith. -- -- The query isConsistentWith() specifies that a redefining transition is -- consistent with a redefined transition provided that the redefining -- transition has the following relation to the redefined transition: A -- redefining transition redefines all properties of the corresponding -- redefined transition, except the source state and the trigger. overriding function Redefinition_Context (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Classifiers.UML_Classifier_Access; -- Operation Transition::redefinitionContext. -- -- The redefinition context of a transition is the nearest containing -- statemachine. overriding function Exclude_Collisions (Self : not null access constant UML_Protocol_Transition_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element; -- Operation Namespace::excludeCollisions. -- -- The query excludeCollisions() excludes from a set of -- PackageableElements any that would not be distinguishable from each -- other in this namespace. overriding function Get_Names_Of_Member (Self : not null access constant UML_Protocol_Transition_Proxy; Element : AMF.UML.Named_Elements.UML_Named_Element_Access) return AMF.String_Collections.Set_Of_String; -- Operation Namespace::getNamesOfMember. -- -- The query getNamesOfMember() takes importing into account. It gives -- back the set of names that an element would have in an importing -- namespace, either because it is owned, or if not owned then imported -- individually, or if not individually then from a package. -- The query getNamesOfMember() gives a set of all of the names that a -- member would have in a Namespace. In general a member can have multiple -- names in a Namespace if it is imported more than once with different -- aliases. The query takes account of importing. It gives back the set of -- names that an element would have in an importing namespace, either -- because it is owned, or if not owned then imported individually, or if -- not individually then from a package. overriding function Import_Members (Self : not null access constant UML_Protocol_Transition_Proxy; Imps : AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element; -- Operation Namespace::importMembers. -- -- The query importMembers() defines which of a set of PackageableElements -- are actually imported into the namespace. This excludes hidden ones, -- i.e., those which have names that conflict with names of owned members, -- and also excludes elements which would have the same name when imported. overriding function Imported_Member (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Packageable_Elements.Collections.Set_Of_UML_Packageable_Element; -- Operation Namespace::importedMember. -- -- The importedMember property is derived from the ElementImports and the -- PackageImports. References the PackageableElements that are members of -- this Namespace as a result of either PackageImports or ElementImports. overriding function Members_Are_Distinguishable (Self : not null access constant UML_Protocol_Transition_Proxy) return Boolean; -- Operation Namespace::membersAreDistinguishable. -- -- The Boolean query membersAreDistinguishable() determines whether all of -- the namespace's members are distinguishable within it. overriding function Owned_Member (Self : not null access constant UML_Protocol_Transition_Proxy) return AMF.UML.Named_Elements.Collections.Set_Of_UML_Named_Element; -- Operation Namespace::ownedMember. -- -- Missing derivation for Namespace::/ownedMember : NamedElement overriding function All_Owning_Packages (Self : not null access constant UML_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transition_Proxy) return AMF.UML.Namespaces.UML_Namespace_Access; -- Operation NamedElement::namespace. -- -- Missing derivation for NamedElement::/namespace : Namespace overriding function Is_Redefinition_Context_Valid (Self : not null access constant UML_Protocol_Transition_Proxy; Redefined : AMF.UML.Redefinable_Elements.UML_Redefinable_Element_Access) return Boolean; -- Operation RedefinableElement::isRedefinitionContextValid. -- -- The query isRedefinitionContextValid() specifies whether the -- redefinition contexts of this RedefinableElement are properly related -- to the redefinition contexts of the specified RedefinableElement to -- allow this element to redefine the other. By default at least one of -- the redefinition contexts of this element must be a specialization of -- at least one of the redefinition contexts of the specified element. overriding procedure Enter_Element (Self : not null access constant UML_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transition_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_Protocol_Transitions;
30,103
ada
0
djamal2727/Main-Bearing-Analytical-Model
Validation/pyFrame3DD-master/gcc-master/gcc/ada/libgnat/g-debpoo.adb
------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- G N A T . D E B U G _ P O O L S -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with GNAT.IO; use GNAT.IO; with System.CRTL; with System.Memory; use System.Memory; with System.Soft_Links; use System.Soft_Links; with System.Traceback_Entries; with GNAT.Debug_Utilities; use GNAT.Debug_Utilities; with GNAT.HTable; with GNAT.Traceback; use GNAT.Traceback; with Ada.Finalization; with Ada.Unchecked_Conversion; package body GNAT.Debug_Pools is Storage_Alignment : constant := Standard'Maximum_Alignment; -- Alignment enforced for all the memory chunks returned by Allocate, -- maximized to make sure that it will be compatible with all types. -- -- The addresses returned by the underlying low-level allocator (be it -- 'new' or a straight 'malloc') aren't guaranteed to be that much aligned -- on some targets, so we manage the needed alignment padding ourselves -- systematically. Use of a common value for every allocation allows -- significant simplifications in the code, nevertheless, for improved -- robustness and efficiency overall. -- We combine a few internal devices to offer the pool services: -- -- * A management header attached to each allocated memory block, located -- right ahead of it, like so: -- -- Storage Address returned by the pool, -- aligned on Storage_Alignment -- v -- +------+--------+--------------------- -- | ~~~~ | HEADER | USER DATA ... | -- +------+--------+--------------------- -- <----> -- alignment -- padding -- -- The alignment padding is required -- -- * A validity bitmap, which holds a validity bit for blocks managed by -- the pool. Enforcing Storage_Alignment on those blocks allows efficient -- validity management. -- -- * A list of currently used blocks. Max_Ignored_Levels : constant Natural := 10; -- Maximum number of levels that will be ignored in backtraces. This is so -- that we still have enough significant levels in the tracebacks returned -- to the user. -- -- The value 10 is chosen as being greater than the maximum callgraph -- in this package. Its actual value is not really relevant, as long as it -- is high enough to make sure we still have enough frames to return to -- the user after we have hidden the frames internal to this package. Disable : Boolean := False; -- This variable is used to avoid infinite loops, where this package would -- itself allocate memory and then call itself recursively, forever. Useful -- when System_Memory_Debug_Pool_Enabled is True. System_Memory_Debug_Pool_Enabled : Boolean := False; -- If True, System.Memory allocation uses Debug_Pool Allow_Unhandled_Memory : Boolean := False; -- If True, protects Deallocate against releasing memory allocated before -- System_Memory_Debug_Pool_Enabled was set. Traceback_Count : Byte_Count := 0; -- Total number of traceback elements --------------------------- -- Back Trace Hash Table -- --------------------------- -- This package needs to store one set of tracebacks for each allocation -- point (when was it allocated or deallocated). This would use too much -- memory, so the tracebacks are actually stored in a hash table, and -- we reference elements in this hash table instead. -- This hash-table will remain empty if the discriminant Stack_Trace_Depth -- for the pools is set to 0. -- This table is a global table, that can be shared among all debug pools -- with no problems. type Header is range 1 .. 1023; -- Number of elements in the hash-table type Tracebacks_Array_Access is access Tracebacks_Array; type Traceback_Kind is (Alloc, Dealloc, Indirect_Alloc, Indirect_Dealloc); type Traceback_Htable_Elem; type Traceback_Htable_Elem_Ptr is access Traceback_Htable_Elem; type Traceback_Htable_Elem is record Traceback : Tracebacks_Array_Access; Kind : Traceback_Kind; Count : Natural; -- Size of the memory allocated/freed at Traceback since last Reset call Total : Byte_Count; -- Number of chunk of memory allocated/freed at Traceback since last -- Reset call. Frees : Natural; -- Number of chunk of memory allocated at Traceback, currently freed -- since last Reset call. (only for Alloc & Indirect_Alloc elements) Total_Frees : Byte_Count; -- Size of the memory allocated at Traceback, currently freed since last -- Reset call. (only for Alloc & Indirect_Alloc elements) Next : Traceback_Htable_Elem_Ptr; end record; -- Subprograms used for the Backtrace_Htable instantiation procedure Set_Next (E : Traceback_Htable_Elem_Ptr; Next : Traceback_Htable_Elem_Ptr); pragma Inline (Set_Next); function Next (E : Traceback_Htable_Elem_Ptr) return Traceback_Htable_Elem_Ptr; pragma Inline (Next); function Get_Key (E : Traceback_Htable_Elem_Ptr) return Tracebacks_Array_Access; pragma Inline (Get_Key); function Hash (T : Tracebacks_Array_Access) return Header; pragma Inline (Hash); function Equal (K1, K2 : Tracebacks_Array_Access) return Boolean; -- Why is this not inlined??? -- The hash table for back traces package Backtrace_Htable is new GNAT.HTable.Static_HTable (Header_Num => Header, Element => Traceback_Htable_Elem, Elmt_Ptr => Traceback_Htable_Elem_Ptr, Null_Ptr => null, Set_Next => Set_Next, Next => Next, Key => Tracebacks_Array_Access, Get_Key => Get_Key, Hash => Hash, Equal => Equal); ----------------------- -- Allocations table -- ----------------------- type Allocation_Header; type Allocation_Header_Access is access Allocation_Header; type Traceback_Ptr_Or_Address is new System.Address; -- A type that acts as a C union, and is either a System.Address or a -- Traceback_Htable_Elem_Ptr. -- The following record stores extra information that needs to be -- memorized for each block allocated with the special debug pool. type Allocation_Header is record Allocation_Address : System.Address; -- Address of the block returned by malloc, possibly unaligned Block_Size : Storage_Offset; -- Needed only for advanced freeing algorithms (traverse all allocated -- blocks for potential references). This value is negated when the -- chunk of memory has been logically freed by the application. This -- chunk has not been physically released yet. Alloc_Traceback : Traceback_Htable_Elem_Ptr; -- ??? comment required Dealloc_Traceback : Traceback_Ptr_Or_Address; -- Pointer to the traceback for the allocation (if the memory chunk is -- still valid), or to the first deallocation otherwise. Make sure this -- is a thin pointer to save space. -- -- Dealloc_Traceback is also for blocks that are still allocated to -- point to the previous block in the list. This saves space in this -- header, and make manipulation of the lists of allocated pointers -- faster. Next : System.Address; -- Point to the next block of the same type (either allocated or -- logically freed) in memory. This points to the beginning of the user -- data, and does not include the header of that block. end record; function Header_Of (Address : System.Address) return Allocation_Header_Access; pragma Inline (Header_Of); -- Return the header corresponding to a previously allocated address function To_Address is new Ada.Unchecked_Conversion (Traceback_Ptr_Or_Address, System.Address); function To_Address is new Ada.Unchecked_Conversion (System.Address, Traceback_Ptr_Or_Address); function To_Traceback is new Ada.Unchecked_Conversion (Traceback_Ptr_Or_Address, Traceback_Htable_Elem_Ptr); function To_Traceback is new Ada.Unchecked_Conversion (Traceback_Htable_Elem_Ptr, Traceback_Ptr_Or_Address); Header_Offset : constant Storage_Count := (Allocation_Header'Object_Size / System.Storage_Unit); -- Offset, in bytes, from start of allocation Header to start of User -- data. The start of user data is assumed to be aligned at least as much -- as what the header type requires, so applying this offset yields a -- suitably aligned address as well. Extra_Allocation : constant Storage_Count := (Storage_Alignment - 1 + Header_Offset); -- Amount we need to secure in addition to the user data for a given -- allocation request: room for the allocation header plus worst-case -- alignment padding. ----------------------- -- Local subprograms -- ----------------------- function Align (Addr : Integer_Address) return Integer_Address; pragma Inline (Align); -- Return the next address aligned on Storage_Alignment from Addr. function Find_Or_Create_Traceback (Pool : Debug_Pool; Kind : Traceback_Kind; Size : Storage_Count; Ignored_Frame_Start : System.Address; Ignored_Frame_End : System.Address) return Traceback_Htable_Elem_Ptr; -- Return an element matching the current traceback (omitting the frames -- that are in the current package). If this traceback already existed in -- the htable, a pointer to this is returned to spare memory. Null is -- returned if the pool is set not to store tracebacks. If the traceback -- already existed in the table, the count is incremented so that -- Dump_Tracebacks returns useful results. All addresses up to, and -- including, an address between Ignored_Frame_Start .. Ignored_Frame_End -- are ignored. function Output_File (Pool : Debug_Pool) return File_Type; pragma Inline (Output_File); -- Returns file_type on which error messages have to be generated for Pool procedure Put_Line (File : File_Type; Depth : Natural; Traceback : Tracebacks_Array_Access; Ignored_Frame_Start : System.Address := System.Null_Address; Ignored_Frame_End : System.Address := System.Null_Address); -- Print Traceback to File. If Traceback is null, print the call_chain -- at the current location, up to Depth levels, ignoring all addresses -- up to the first one in the range: -- Ignored_Frame_Start .. Ignored_Frame_End procedure Stdout_Put (S : String); -- Wrapper for Put that ensures we always write to stdout instead of the -- current output file defined in GNAT.IO. procedure Stdout_Put_Line (S : String); -- Wrapper for Put_Line that ensures we always write to stdout instead of -- the current output file defined in GNAT.IO. procedure Print_Traceback (Output_File : File_Type; Prefix : String; Traceback : Traceback_Htable_Elem_Ptr); -- Output Prefix & Traceback & EOL. Print nothing if Traceback is null. procedure Print_Address (File : File_Type; Addr : Address); -- Output System.Address without using secondary stack. -- When System.Memory uses Debug_Pool, secondary stack cannot be used -- during Allocate calls, as some Allocate calls are done to -- register/initialize a secondary stack for a foreign thread. -- During these calls, the secondary stack is not available yet. package Validity is function Is_Handled (Storage : System.Address) return Boolean; pragma Inline (Is_Handled); -- Return True if Storage is the address of a block that the debug pool -- already had under its control. Used to allow System.Memory to use -- Debug_Pools function Is_Valid (Storage : System.Address) return Boolean; pragma Inline (Is_Valid); -- Return True if Storage is the address of a block that the debug pool -- has under its control, in which case Header_Of may be used to access -- the associated allocation header. procedure Set_Valid (Storage : System.Address; Value : Boolean); pragma Inline (Set_Valid); -- Mark the address Storage as being under control of the memory pool -- (if Value is True), or not (if Value is False). Validity_Count : Byte_Count := 0; -- Total number of validity elements end Validity; use Validity; procedure Set_Dead_Beef (Storage_Address : System.Address; Size_In_Storage_Elements : Storage_Count); -- Set the contents of the memory block pointed to by Storage_Address to -- the 16#DEADBEEF# pattern. If Size_In_Storage_Elements is not a multiple -- of the length of this pattern, the last instance may be partial. procedure Free_Physically (Pool : in out Debug_Pool); -- Start to physically release some memory to the system, until the amount -- of logically (but not physically) freed memory is lower than the -- expected amount in Pool. procedure Allocate_End; procedure Deallocate_End; procedure Dereference_End; -- These procedures are used as markers when computing the stacktraces, -- so that addresses in the debug pool itself are not reported to the user. Code_Address_For_Allocate_End : System.Address; Code_Address_For_Deallocate_End : System.Address; Code_Address_For_Dereference_End : System.Address; -- Taking the address of the above procedures will not work on some -- architectures (HPUX for instance). Thus we do the same thing that -- is done in a-except.adb, and get the address of labels instead. procedure Skip_Levels (Depth : Natural; Trace : Tracebacks_Array; Start : out Natural; Len : in out Natural; Ignored_Frame_Start : System.Address; Ignored_Frame_End : System.Address); -- Set Start .. Len to the range of values from Trace that should be output -- to the user. This range of values excludes any address prior to the -- first one in Ignored_Frame_Start .. Ignored_Frame_End (basically -- addresses internal to this package). Depth is the number of levels that -- the user is interested in. package STBE renames System.Traceback_Entries; function PC_For (TB_Entry : STBE.Traceback_Entry) return System.Address renames STBE.PC_For; type Scope_Lock is new Ada.Finalization.Limited_Controlled with null record; -- Used to handle Lock_Task/Unlock_Task calls overriding procedure Initialize (This : in out Scope_Lock); -- Lock task on initialization overriding procedure Finalize (This : in out Scope_Lock); -- Unlock task on finalization ---------------- -- Initialize -- ---------------- procedure Initialize (This : in out Scope_Lock) is pragma Unreferenced (This); begin Lock_Task.all; end Initialize; -------------- -- Finalize -- -------------- procedure Finalize (This : in out Scope_Lock) is pragma Unreferenced (This); begin Unlock_Task.all; end Finalize; ----------- -- Align -- ----------- function Align (Addr : Integer_Address) return Integer_Address is Factor : constant Integer_Address := Storage_Alignment; begin return ((Addr + Factor - 1) / Factor) * Factor; end Align; --------------- -- Header_Of -- --------------- function Header_Of (Address : System.Address) return Allocation_Header_Access is function Convert is new Ada.Unchecked_Conversion (System.Address, Allocation_Header_Access); begin return Convert (Address - Header_Offset); end Header_Of; -------------- -- Set_Next -- -------------- procedure Set_Next (E : Traceback_Htable_Elem_Ptr; Next : Traceback_Htable_Elem_Ptr) is begin E.Next := Next; end Set_Next; ---------- -- Next -- ---------- function Next (E : Traceback_Htable_Elem_Ptr) return Traceback_Htable_Elem_Ptr is begin return E.Next; end Next; ----------- -- Equal -- ----------- function Equal (K1, K2 : Tracebacks_Array_Access) return Boolean is use type Tracebacks_Array; begin return K1.all = K2.all; end Equal; ------------- -- Get_Key -- ------------- function Get_Key (E : Traceback_Htable_Elem_Ptr) return Tracebacks_Array_Access is begin return E.Traceback; end Get_Key; ---------- -- Hash -- ---------- function Hash (T : Tracebacks_Array_Access) return Header is Result : Integer_Address := 0; begin for X in T'Range loop Result := Result + To_Integer (PC_For (T (X))); end loop; return Header (1 + Result mod Integer_Address (Header'Last)); end Hash; ----------------- -- Output_File -- ----------------- function Output_File (Pool : Debug_Pool) return File_Type is begin if Pool.Errors_To_Stdout then return Standard_Output; else return Standard_Error; end if; end Output_File; ------------------- -- Print_Address -- ------------------- procedure Print_Address (File : File_Type; Addr : Address) is begin -- Warning: secondary stack cannot be used here. When System.Memory -- implementation uses Debug_Pool, Print_Address can be called during -- secondary stack creation for foreign threads. Put (File, Image_C (Addr)); end Print_Address; -------------- -- Put_Line -- -------------- procedure Put_Line (File : File_Type; Depth : Natural; Traceback : Tracebacks_Array_Access; Ignored_Frame_Start : System.Address := System.Null_Address; Ignored_Frame_End : System.Address := System.Null_Address) is procedure Print (Tr : Tracebacks_Array); -- Print the traceback to standard_output ----------- -- Print -- ----------- procedure Print (Tr : Tracebacks_Array) is begin for J in Tr'Range loop Print_Address (File, PC_For (Tr (J))); Put (File, ' '); end loop; Put (File, ASCII.LF); end Print; -- Start of processing for Put_Line begin if Traceback = null then declare Len : Natural; Start : Natural; Trace : aliased Tracebacks_Array (1 .. Depth + Max_Ignored_Levels); begin Call_Chain (Trace, Len); Skip_Levels (Depth => Depth, Trace => Trace, Start => Start, Len => Len, Ignored_Frame_Start => Ignored_Frame_Start, Ignored_Frame_End => Ignored_Frame_End); Print (Trace (Start .. Len)); end; else Print (Traceback.all); end if; end Put_Line; ----------------- -- Skip_Levels -- ----------------- procedure Skip_Levels (Depth : Natural; Trace : Tracebacks_Array; Start : out Natural; Len : in out Natural; Ignored_Frame_Start : System.Address; Ignored_Frame_End : System.Address) is begin Start := Trace'First; while Start <= Len and then (PC_For (Trace (Start)) < Ignored_Frame_Start or else PC_For (Trace (Start)) > Ignored_Frame_End) loop Start := Start + 1; end loop; Start := Start + 1; -- Just in case: make sure we have a traceback even if Ignore_Till -- wasn't found. if Start > Len then Start := 1; end if; if Len - Start + 1 > Depth then Len := Depth + Start - 1; end if; end Skip_Levels; ------------------------------ -- Find_Or_Create_Traceback -- ------------------------------ function Find_Or_Create_Traceback (Pool : Debug_Pool; Kind : Traceback_Kind; Size : Storage_Count; Ignored_Frame_Start : System.Address; Ignored_Frame_End : System.Address) return Traceback_Htable_Elem_Ptr is begin if Pool.Stack_Trace_Depth = 0 then return null; end if; declare Disable_Exit_Value : constant Boolean := Disable; Elem : Traceback_Htable_Elem_Ptr; Len : Natural; Start : Natural; Trace : aliased Tracebacks_Array (1 .. Integer (Pool.Stack_Trace_Depth) + Max_Ignored_Levels); begin Disable := True; Call_Chain (Trace, Len); Skip_Levels (Depth => Pool.Stack_Trace_Depth, Trace => Trace, Start => Start, Len => Len, Ignored_Frame_Start => Ignored_Frame_Start, Ignored_Frame_End => Ignored_Frame_End); -- Check if the traceback is already in the table Elem := Backtrace_Htable.Get (Trace (Start .. Len)'Unrestricted_Access); -- If not, insert it if Elem = null then Elem := new Traceback_Htable_Elem' (Traceback => new Tracebacks_Array'(Trace (Start .. Len)), Count => 1, Kind => Kind, Total => Byte_Count (Size), Frees => 0, Total_Frees => 0, Next => null); Traceback_Count := Traceback_Count + 1; Backtrace_Htable.Set (Elem); else Elem.Count := Elem.Count + 1; Elem.Total := Elem.Total + Byte_Count (Size); end if; Disable := Disable_Exit_Value; return Elem; exception when others => Disable := Disable_Exit_Value; raise; end; end Find_Or_Create_Traceback; -------------- -- Validity -- -------------- package body Validity is -- The validity bits of the allocated blocks are kept in a has table. -- Each component of the hash table contains the validity bits for a -- 16 Mbyte memory chunk. -- The reason the validity bits are kept for chunks of memory rather -- than in a big array is that on some 64 bit platforms, it may happen -- that two chunk of allocated data are very far from each other. Memory_Chunk_Size : constant Integer_Address := 2 ** 24; -- 16 MB Validity_Divisor : constant := Storage_Alignment * System.Storage_Unit; Max_Validity_Byte_Index : constant := Memory_Chunk_Size / Validity_Divisor; subtype Validity_Byte_Index is Integer_Address range 0 .. Max_Validity_Byte_Index - 1; type Byte is mod 2 ** System.Storage_Unit; type Validity_Bits_Part is array (Validity_Byte_Index) of Byte; type Validity_Bits_Part_Ref is access all Validity_Bits_Part; No_Validity_Bits_Part : constant Validity_Bits_Part_Ref := null; type Validity_Bits is record Valid : Validity_Bits_Part_Ref := No_Validity_Bits_Part; -- True if chunk of memory at this address is currently allocated Handled : Validity_Bits_Part_Ref := No_Validity_Bits_Part; -- True if chunk of memory at this address was allocated once after -- Allow_Unhandled_Memory was set to True. Used to know on Deallocate -- if chunk of memory should be handled a block allocated by this -- package. end record; type Validity_Bits_Ref is access all Validity_Bits; No_Validity_Bits : constant Validity_Bits_Ref := null; Max_Header_Num : constant := 1023; type Header_Num is range 0 .. Max_Header_Num - 1; function Hash (F : Integer_Address) return Header_Num; function Is_Valid_Or_Handled (Storage : System.Address; Valid : Boolean) return Boolean; pragma Inline (Is_Valid_Or_Handled); -- Internal implementation of Is_Valid and Is_Handled. -- Valid is used to select Valid or Handled arrays. package Validy_Htable is new GNAT.HTable.Simple_HTable (Header_Num => Header_Num, Element => Validity_Bits_Ref, No_Element => No_Validity_Bits, Key => Integer_Address, Hash => Hash, Equal => "="); -- Table to keep the validity and handled bit blocks for the allocated -- data. function To_Pointer is new Ada.Unchecked_Conversion (System.Address, Validity_Bits_Part_Ref); procedure Memset (A : Address; C : Integer; N : size_t); pragma Import (C, Memset, "memset"); ---------- -- Hash -- ---------- function Hash (F : Integer_Address) return Header_Num is begin return Header_Num (F mod Max_Header_Num); end Hash; ------------------------- -- Is_Valid_Or_Handled -- ------------------------- function Is_Valid_Or_Handled (Storage : System.Address; Valid : Boolean) return Boolean is Int_Storage : constant Integer_Address := To_Integer (Storage); begin -- The pool only returns addresses aligned on Storage_Alignment so -- anything off cannot be a valid block address and we can return -- early in this case. We actually have to since our data structures -- map validity bits for such aligned addresses only. if Int_Storage mod Storage_Alignment /= 0 then return False; end if; declare Block_Number : constant Integer_Address := Int_Storage / Memory_Chunk_Size; Ptr : constant Validity_Bits_Ref := Validy_Htable.Get (Block_Number); Offset : constant Integer_Address := (Int_Storage - (Block_Number * Memory_Chunk_Size)) / Storage_Alignment; Bit : constant Byte := 2 ** Natural (Offset mod System.Storage_Unit); begin if Ptr = No_Validity_Bits then return False; else if Valid then return (Ptr.Valid (Offset / System.Storage_Unit) and Bit) /= 0; else if Ptr.Handled = No_Validity_Bits_Part then return False; else return (Ptr.Handled (Offset / System.Storage_Unit) and Bit) /= 0; end if; end if; end if; end; end Is_Valid_Or_Handled; -------------- -- Is_Valid -- -------------- function Is_Valid (Storage : System.Address) return Boolean is begin return Is_Valid_Or_Handled (Storage => Storage, Valid => True); end Is_Valid; ----------------- -- Is_Handled -- ----------------- function Is_Handled (Storage : System.Address) return Boolean is begin return Is_Valid_Or_Handled (Storage => Storage, Valid => False); end Is_Handled; --------------- -- Set_Valid -- --------------- procedure Set_Valid (Storage : System.Address; Value : Boolean) is Int_Storage : constant Integer_Address := To_Integer (Storage); Block_Number : constant Integer_Address := Int_Storage / Memory_Chunk_Size; Ptr : Validity_Bits_Ref := Validy_Htable.Get (Block_Number); Offset : constant Integer_Address := (Int_Storage - (Block_Number * Memory_Chunk_Size)) / Storage_Alignment; Bit : constant Byte := 2 ** Natural (Offset mod System.Storage_Unit); procedure Set_Handled; pragma Inline (Set_Handled); -- if Allow_Unhandled_Memory set Handled bit in table. ----------------- -- Set_Handled -- ----------------- procedure Set_Handled is begin if Allow_Unhandled_Memory then if Ptr.Handled = No_Validity_Bits_Part then Ptr.Handled := To_Pointer (Alloc (size_t (Max_Validity_Byte_Index))); Memset (A => Ptr.Handled.all'Address, C => 0, N => size_t (Max_Validity_Byte_Index)); end if; Ptr.Handled (Offset / System.Storage_Unit) := Ptr.Handled (Offset / System.Storage_Unit) or Bit; end if; end Set_Handled; -- Start of processing for Set_Valid begin if Ptr = No_Validity_Bits then -- First time in this memory area: allocate a new block and put -- it in the table. if Value then Ptr := new Validity_Bits; Validity_Count := Validity_Count + 1; Ptr.Valid := To_Pointer (Alloc (size_t (Max_Validity_Byte_Index))); Validy_Htable.Set (Block_Number, Ptr); Memset (A => Ptr.Valid.all'Address, C => 0, N => size_t (Max_Validity_Byte_Index)); Ptr.Valid (Offset / System.Storage_Unit) := Bit; Set_Handled; end if; else if Value then Ptr.Valid (Offset / System.Storage_Unit) := Ptr.Valid (Offset / System.Storage_Unit) or Bit; Set_Handled; else Ptr.Valid (Offset / System.Storage_Unit) := Ptr.Valid (Offset / System.Storage_Unit) and (not Bit); end if; end if; end Set_Valid; end Validity; -------------- -- Allocate -- -------------- procedure Allocate (Pool : in out Debug_Pool; Storage_Address : out Address; Size_In_Storage_Elements : Storage_Count; Alignment : Storage_Count) is pragma Unreferenced (Alignment); -- Ignored, we always force Storage_Alignment type Local_Storage_Array is new Storage_Array (1 .. Size_In_Storage_Elements + Extra_Allocation); type Ptr is access Local_Storage_Array; -- On some systems, we might want to physically protect pages against -- writing when they have been freed (of course, this is expensive in -- terms of wasted memory). To do that, all we should have to do it to -- set the size of this array to the page size. See mprotect(). Current : Byte_Count; P : Ptr; Trace : Traceback_Htable_Elem_Ptr; Reset_Disable_At_Exit : Boolean := False; Lock : Scope_Lock; pragma Unreferenced (Lock); begin <<Allocate_Label>> if Disable then Storage_Address := System.CRTL.malloc (System.CRTL.size_t (Size_In_Storage_Elements)); return; end if; Reset_Disable_At_Exit := True; Disable := True; Pool.Alloc_Count := Pool.Alloc_Count + 1; -- If necessary, start physically releasing memory. The reason this is -- done here, although Pool.Logically_Deallocated has not changed above, -- is so that we do this only after a series of deallocations (e.g loop -- that deallocates a big array). If we were doing that in Deallocate, -- we might be physically freeing memory several times during the loop, -- which is expensive. if Pool.Logically_Deallocated > Byte_Count (Pool.Maximum_Logically_Freed_Memory) then Free_Physically (Pool); end if; -- Use standard (i.e. through malloc) allocations. This automatically -- raises Storage_Error if needed. We also try once more to physically -- release memory, so that even marked blocks, in the advanced scanning, -- are freed. Note that we do not initialize the storage array since it -- is not necessary to do so (however this will cause bogus valgrind -- warnings, which should simply be ignored). begin P := new Local_Storage_Array; exception when Storage_Error => Free_Physically (Pool); P := new Local_Storage_Array; end; -- Compute Storage_Address, aimed at receiving user data. We need room -- for the allocation header just ahead of the user data space plus -- alignment padding so Storage_Address is aligned on Storage_Alignment, -- like so: -- -- Storage_Address, aligned -- on Storage_Alignment -- v -- | ~~~~ | Header | User data ... | -- ^........^ -- Header_Offset -- -- Header_Offset is fixed so moving back and forth between user data -- and allocation header is straightforward. The value is also such -- that the header type alignment is honored when starting from -- Default_alignment. -- For the purpose of computing Storage_Address, we just do as if the -- header was located first, followed by the alignment padding: Storage_Address := To_Address (Align (To_Integer (P.all'Address) + Integer_Address (Header_Offset))); -- Computation is done in Integer_Address, not Storage_Offset, because -- the range of Storage_Offset may not be large enough. pragma Assert ((Storage_Address - System.Null_Address) mod Storage_Alignment = 0); pragma Assert (Storage_Address + Size_In_Storage_Elements <= P.all'Address + P'Length); Trace := Find_Or_Create_Traceback (Pool => Pool, Kind => Alloc, Size => Size_In_Storage_Elements, Ignored_Frame_Start => Allocate_Label'Address, Ignored_Frame_End => Code_Address_For_Allocate_End); pragma Warnings (Off); -- Turn warning on alignment for convert call off. We know that in fact -- this conversion is safe since P itself is always aligned on -- Storage_Alignment. Header_Of (Storage_Address).all := (Allocation_Address => P.all'Address, Alloc_Traceback => Trace, Dealloc_Traceback => To_Traceback (null), Next => Pool.First_Used_Block, Block_Size => Size_In_Storage_Elements); pragma Warnings (On); -- Link this block in the list of used blocks. This will be used to list -- memory leaks in Print_Info, and for the advanced schemes of -- Physical_Free, where we want to traverse all allocated blocks and -- search for possible references. -- We insert in front, since most likely we'll be freeing the most -- recently allocated blocks first (the older one might stay allocated -- for the whole life of the application). if Pool.First_Used_Block /= System.Null_Address then Header_Of (Pool.First_Used_Block).Dealloc_Traceback := To_Address (Storage_Address); end if; Pool.First_Used_Block := Storage_Address; -- Mark the new address as valid Set_Valid (Storage_Address, True); if Pool.Low_Level_Traces then Put (Output_File (Pool), "info: Allocated" & Storage_Count'Image (Size_In_Storage_Elements) & " bytes at "); Print_Address (Output_File (Pool), Storage_Address); Put (Output_File (Pool), " (physically:" & Storage_Count'Image (Local_Storage_Array'Length) & " bytes at "); Print_Address (Output_File (Pool), P.all'Address); Put (Output_File (Pool), "), at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Allocate_Label'Address, Code_Address_For_Deallocate_End); end if; -- Update internal data Pool.Allocated := Pool.Allocated + Byte_Count (Size_In_Storage_Elements); Current := Pool.Current_Water_Mark; if Current > Pool.High_Water then Pool.High_Water := Current; end if; Disable := False; exception when others => if Reset_Disable_At_Exit then Disable := False; end if; raise; end Allocate; ------------------ -- Allocate_End -- ------------------ -- DO NOT MOVE, this must be right after Allocate. This is similar to what -- is done in a-except, so that we can hide the traceback frames internal -- to this package procedure Allocate_End is begin <<Allocate_End_Label>> Code_Address_For_Allocate_End := Allocate_End_Label'Address; end Allocate_End; ------------------- -- Set_Dead_Beef -- ------------------- procedure Set_Dead_Beef (Storage_Address : System.Address; Size_In_Storage_Elements : Storage_Count) is Dead_Bytes : constant := 4; type Data is mod 2 ** (Dead_Bytes * 8); for Data'Size use Dead_Bytes * 8; Dead : constant Data := 16#DEAD_BEEF#; type Dead_Memory is array (1 .. Size_In_Storage_Elements / Dead_Bytes) of Data; type Mem_Ptr is access Dead_Memory; type Byte is mod 2 ** 8; for Byte'Size use 8; type Dead_Memory_Bytes is array (0 .. 2) of Byte; type Dead_Memory_Bytes_Ptr is access Dead_Memory_Bytes; function From_Ptr is new Ada.Unchecked_Conversion (System.Address, Mem_Ptr); function From_Ptr is new Ada.Unchecked_Conversion (System.Address, Dead_Memory_Bytes_Ptr); M : constant Mem_Ptr := From_Ptr (Storage_Address); M2 : Dead_Memory_Bytes_Ptr; Modulo : constant Storage_Count := Size_In_Storage_Elements mod Dead_Bytes; begin M.all := (others => Dead); -- Any bytes left (up to three of them) if Modulo /= 0 then M2 := From_Ptr (Storage_Address + M'Length * Dead_Bytes); M2 (0) := 16#DE#; if Modulo >= 2 then M2 (1) := 16#AD#; if Modulo >= 3 then M2 (2) := 16#BE#; end if; end if; end if; end Set_Dead_Beef; --------------------- -- Free_Physically -- --------------------- procedure Free_Physically (Pool : in out Debug_Pool) is type Byte is mod 256; type Byte_Access is access Byte; function To_Byte is new Ada.Unchecked_Conversion (System.Address, Byte_Access); type Address_Access is access System.Address; function To_Address_Access is new Ada.Unchecked_Conversion (System.Address, Address_Access); In_Use_Mark : constant Byte := 16#D#; Free_Mark : constant Byte := 16#F#; Total_Freed : Storage_Count := 0; procedure Reset_Marks; -- Unmark all the logically freed blocks, so that they are considered -- for physical deallocation procedure Mark (H : Allocation_Header_Access; A : System.Address; In_Use : Boolean); -- Mark the user data block starting at A. For a block of size zero, -- nothing is done. For a block with a different size, the first byte -- is set to either "D" (in use) or "F" (free). function Marked (A : System.Address) return Boolean; -- Return true if the user data block starting at A might be in use -- somewhere else procedure Mark_Blocks; -- Traverse all allocated blocks, and search for possible references -- to logically freed blocks. Mark them appropriately procedure Free_Blocks (Ignore_Marks : Boolean); -- Physically release blocks. Only the blocks that haven't been marked -- will be released, unless Ignore_Marks is true. ----------------- -- Free_Blocks -- ----------------- procedure Free_Blocks (Ignore_Marks : Boolean) is Header : Allocation_Header_Access; Tmp : System.Address := Pool.First_Free_Block; Next : System.Address; Previous : System.Address := System.Null_Address; begin while Tmp /= System.Null_Address and then not (Total_Freed > Pool.Minimum_To_Free and Pool.Logically_Deallocated < Byte_Count (Pool.Maximum_Logically_Freed_Memory)) loop Header := Header_Of (Tmp); -- If we know, or at least assume, the block is no longer -- referenced anywhere, we can free it physically. if Ignore_Marks or else not Marked (Tmp) then declare pragma Suppress (All_Checks); -- Suppress the checks on this section. If they are overflow -- errors, it isn't critical, and we'd rather avoid a -- Constraint_Error in that case. begin -- Note that block_size < zero for freed blocks Pool.Physically_Deallocated := Pool.Physically_Deallocated - Byte_Count (Header.Block_Size); Pool.Logically_Deallocated := Pool.Logically_Deallocated + Byte_Count (Header.Block_Size); Total_Freed := Total_Freed - Header.Block_Size; end; Next := Header.Next; if Pool.Low_Level_Traces then Put (Output_File (Pool), "info: Freeing physical memory " & Storage_Count'Image ((abs Header.Block_Size) + Extra_Allocation) & " bytes at "); Print_Address (Output_File (Pool), Header.Allocation_Address); Put_Line (Output_File (Pool), ""); end if; if System_Memory_Debug_Pool_Enabled then System.CRTL.free (Header.Allocation_Address); else System.Memory.Free (Header.Allocation_Address); end if; Set_Valid (Tmp, False); -- Remove this block from the list if Previous = System.Null_Address then Pool.First_Free_Block := Next; else Header_Of (Previous).Next := Next; end if; Tmp := Next; else Previous := Tmp; Tmp := Header.Next; end if; end loop; end Free_Blocks; ---------- -- Mark -- ---------- procedure Mark (H : Allocation_Header_Access; A : System.Address; In_Use : Boolean) is begin if H.Block_Size /= 0 then To_Byte (A).all := (if In_Use then In_Use_Mark else Free_Mark); end if; end Mark; ----------------- -- Mark_Blocks -- ----------------- procedure Mark_Blocks is Tmp : System.Address := Pool.First_Used_Block; Previous : System.Address; Last : System.Address; Pointed : System.Address; Header : Allocation_Header_Access; begin -- For each allocated block, check its contents. Things that look -- like a possible address are used to mark the blocks so that we try -- and keep them, for better detection in case of invalid access. -- This mechanism is far from being fool-proof: it doesn't check the -- stacks of the threads, doesn't check possible memory allocated not -- under control of this debug pool. But it should allow us to catch -- more cases. while Tmp /= System.Null_Address loop Previous := Tmp; Last := Tmp + Header_Of (Tmp).Block_Size; while Previous < Last loop -- ??? Should we move byte-per-byte, or consider that addresses -- are always aligned on 4-bytes boundaries ? Let's use the -- fastest for now. Pointed := To_Address_Access (Previous).all; if Is_Valid (Pointed) then Header := Header_Of (Pointed); -- Do not even attempt to mark blocks in use. That would -- screw up the whole application, of course. if Header.Block_Size < 0 then Mark (Header, Pointed, In_Use => True); end if; end if; Previous := Previous + System.Address'Size; end loop; Tmp := Header_Of (Tmp).Next; end loop; end Mark_Blocks; ------------ -- Marked -- ------------ function Marked (A : System.Address) return Boolean is begin return To_Byte (A).all = In_Use_Mark; end Marked; ----------------- -- Reset_Marks -- ----------------- procedure Reset_Marks is Current : System.Address := Pool.First_Free_Block; Header : Allocation_Header_Access; begin while Current /= System.Null_Address loop Header := Header_Of (Current); Mark (Header, Current, False); Current := Header.Next; end loop; end Reset_Marks; Lock : Scope_Lock; pragma Unreferenced (Lock); -- Start of processing for Free_Physically begin if Pool.Advanced_Scanning then -- Reset the mark for each freed block Reset_Marks; Mark_Blocks; end if; Free_Blocks (Ignore_Marks => not Pool.Advanced_Scanning); -- The contract is that we need to free at least Minimum_To_Free bytes, -- even if this means freeing marked blocks in the advanced scheme. if Total_Freed < Pool.Minimum_To_Free and then Pool.Advanced_Scanning then Pool.Marked_Blocks_Deallocated := True; Free_Blocks (Ignore_Marks => True); end if; end Free_Physically; -------------- -- Get_Size -- -------------- procedure Get_Size (Storage_Address : Address; Size_In_Storage_Elements : out Storage_Count; Valid : out Boolean) is Lock : Scope_Lock; pragma Unreferenced (Lock); begin Valid := Is_Valid (Storage_Address); Size_In_Storage_Elements := Storage_Count'First; if Is_Valid (Storage_Address) then declare Header : constant Allocation_Header_Access := Header_Of (Storage_Address); begin if Header.Block_Size >= 0 then Valid := True; Size_In_Storage_Elements := Header.Block_Size; else Valid := False; end if; end; else Valid := False; end if; end Get_Size; --------------------- -- Print_Traceback -- --------------------- procedure Print_Traceback (Output_File : File_Type; Prefix : String; Traceback : Traceback_Htable_Elem_Ptr) is begin if Traceback /= null then Put (Output_File, Prefix); Put_Line (Output_File, 0, Traceback.Traceback); end if; end Print_Traceback; ---------------- -- Deallocate -- ---------------- procedure Deallocate (Pool : in out Debug_Pool; Storage_Address : Address; Size_In_Storage_Elements : Storage_Count; Alignment : Storage_Count) is pragma Unreferenced (Alignment); Header : constant Allocation_Header_Access := Header_Of (Storage_Address); Previous : System.Address; Valid : Boolean; Header_Block_Size_Was_Less_Than_0 : Boolean := True; begin <<Deallocate_Label>> declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Valid := Is_Valid (Storage_Address); if Valid and then not (Header.Block_Size < 0) then Header_Block_Size_Was_Less_Than_0 := False; -- Some sort of codegen problem or heap corruption caused the -- Size_In_Storage_Elements to be wrongly computed. The code -- below is all based on the assumption that Header.all is not -- corrupted, such that the error is non-fatal. if Header.Block_Size /= Size_In_Storage_Elements and then Size_In_Storage_Elements /= Storage_Count'Last then Put_Line (Output_File (Pool), "error: Deallocate size " & Storage_Count'Image (Size_In_Storage_Elements) & " does not match allocate size " & Storage_Count'Image (Header.Block_Size)); end if; if Pool.Low_Level_Traces then Put (Output_File (Pool), "info: Deallocated" & Storage_Count'Image (Header.Block_Size) & " bytes at "); Print_Address (Output_File (Pool), Storage_Address); Put (Output_File (Pool), " (physically" & Storage_Count'Image (Header.Block_Size + Extra_Allocation) & " bytes at "); Print_Address (Output_File (Pool), Header.Allocation_Address); Put (Output_File (Pool), "), at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Deallocate_Label'Address, Code_Address_For_Deallocate_End); Print_Traceback (Output_File (Pool), " Memory was allocated at ", Header.Alloc_Traceback); end if; -- Remove this block from the list of used blocks Previous := To_Address (Header.Dealloc_Traceback); if Previous = System.Null_Address then Pool.First_Used_Block := Header_Of (Pool.First_Used_Block).Next; if Pool.First_Used_Block /= System.Null_Address then Header_Of (Pool.First_Used_Block).Dealloc_Traceback := To_Traceback (null); end if; else Header_Of (Previous).Next := Header.Next; if Header.Next /= System.Null_Address then Header_Of (Header.Next).Dealloc_Traceback := To_Address (Previous); end if; end if; -- Update the Alloc_Traceback Frees/Total_Frees members -- (if present) if Header.Alloc_Traceback /= null then Header.Alloc_Traceback.Frees := Header.Alloc_Traceback.Frees + 1; Header.Alloc_Traceback.Total_Frees := Header.Alloc_Traceback.Total_Frees + Byte_Count (Header.Block_Size); end if; Pool.Free_Count := Pool.Free_Count + 1; -- Update the header Header.all := (Allocation_Address => Header.Allocation_Address, Alloc_Traceback => Header.Alloc_Traceback, Dealloc_Traceback => To_Traceback (Find_Or_Create_Traceback (Pool, Dealloc, Header.Block_Size, Deallocate_Label'Address, Code_Address_For_Deallocate_End)), Next => System.Null_Address, Block_Size => -Header.Block_Size); if Pool.Reset_Content_On_Free then Set_Dead_Beef (Storage_Address, -Header.Block_Size); end if; Pool.Logically_Deallocated := Pool.Logically_Deallocated + Byte_Count (-Header.Block_Size); -- Link this free block with the others (at the end of the list, -- so that we can start releasing the older blocks first later on) if Pool.First_Free_Block = System.Null_Address then Pool.First_Free_Block := Storage_Address; Pool.Last_Free_Block := Storage_Address; else Header_Of (Pool.Last_Free_Block).Next := Storage_Address; Pool.Last_Free_Block := Storage_Address; end if; -- Do not physically release the memory here, but in Alloc. -- See comment there for details. end if; end; if not Valid then if Storage_Address = System.Null_Address then if Pool.Raise_Exceptions and then Size_In_Storage_Elements /= Storage_Count'Last then raise Freeing_Not_Allocated_Storage; else Put (Output_File (Pool), "error: Freeing Null_Address, at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Deallocate_Label'Address, Code_Address_For_Deallocate_End); return; end if; end if; if Allow_Unhandled_Memory and then not Is_Handled (Storage_Address) then System.CRTL.free (Storage_Address); return; end if; if Pool.Raise_Exceptions and then Size_In_Storage_Elements /= Storage_Count'Last then raise Freeing_Not_Allocated_Storage; else Put (Output_File (Pool), "error: Freeing not allocated storage, at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Deallocate_Label'Address, Code_Address_For_Deallocate_End); end if; elsif Header_Block_Size_Was_Less_Than_0 then if Pool.Raise_Exceptions then raise Freeing_Deallocated_Storage; else Put (Output_File (Pool), "error: Freeing already deallocated storage, at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Deallocate_Label'Address, Code_Address_For_Deallocate_End); Print_Traceback (Output_File (Pool), " Memory already deallocated at ", To_Traceback (Header.Dealloc_Traceback)); Print_Traceback (Output_File (Pool), " Memory was allocated at ", Header.Alloc_Traceback); end if; end if; end Deallocate; -------------------- -- Deallocate_End -- -------------------- -- DO NOT MOVE, this must be right after Deallocate -- See Allocate_End -- This is making assumptions about code order that may be invalid ??? procedure Deallocate_End is begin <<Deallocate_End_Label>> Code_Address_For_Deallocate_End := Deallocate_End_Label'Address; end Deallocate_End; ----------------- -- Dereference -- ----------------- procedure Dereference (Pool : in out Debug_Pool; Storage_Address : Address; Size_In_Storage_Elements : Storage_Count; Alignment : Storage_Count) is pragma Unreferenced (Alignment, Size_In_Storage_Elements); Valid : constant Boolean := Is_Valid (Storage_Address); Header : Allocation_Header_Access; begin -- Locking policy: we do not do any locking in this procedure. The -- tables are only read, not written to, and although a problem might -- appear if someone else is modifying the tables at the same time, this -- race condition is not intended to be detected by this storage_pool (a -- now invalid pointer would appear as valid). Instead, we prefer -- optimum performance for dereferences. <<Dereference_Label>> if not Valid then if Pool.Raise_Exceptions then raise Accessing_Not_Allocated_Storage; else Put (Output_File (Pool), "error: Accessing not allocated storage, at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Dereference_Label'Address, Code_Address_For_Dereference_End); end if; else Header := Header_Of (Storage_Address); if Header.Block_Size < 0 then if Pool.Raise_Exceptions then raise Accessing_Deallocated_Storage; else Put (Output_File (Pool), "error: Accessing deallocated storage, at "); Put_Line (Output_File (Pool), Pool.Stack_Trace_Depth, null, Dereference_Label'Address, Code_Address_For_Dereference_End); Print_Traceback (Output_File (Pool), " First deallocation at ", To_Traceback (Header.Dealloc_Traceback)); Print_Traceback (Output_File (Pool), " Initial allocation at ", Header.Alloc_Traceback); end if; end if; end if; end Dereference; --------------------- -- Dereference_End -- --------------------- -- DO NOT MOVE: this must be right after Dereference -- See Allocate_End -- This is making assumptions about code order that may be invalid ??? procedure Dereference_End is begin <<Dereference_End_Label>> Code_Address_For_Dereference_End := Dereference_End_Label'Address; end Dereference_End; ---------------- -- Print_Info -- ---------------- procedure Print_Info (Pool : Debug_Pool; Cumulate : Boolean := False; Display_Slots : Boolean := False; Display_Leaks : Boolean := False) is package Backtrace_Htable_Cumulate is new GNAT.HTable.Static_HTable (Header_Num => Header, Element => Traceback_Htable_Elem, Elmt_Ptr => Traceback_Htable_Elem_Ptr, Null_Ptr => null, Set_Next => Set_Next, Next => Next, Key => Tracebacks_Array_Access, Get_Key => Get_Key, Hash => Hash, Equal => Equal); -- This needs a comment ??? probably some of the ones below do too??? Current : System.Address; Data : Traceback_Htable_Elem_Ptr; Elem : Traceback_Htable_Elem_Ptr; Header : Allocation_Header_Access; K : Traceback_Kind; begin Put_Line ("Total allocated bytes : " & Byte_Count'Image (Pool.Allocated)); Put_Line ("Total logically deallocated bytes : " & Byte_Count'Image (Pool.Logically_Deallocated)); Put_Line ("Total physically deallocated bytes : " & Byte_Count'Image (Pool.Physically_Deallocated)); if Pool.Marked_Blocks_Deallocated then Put_Line ("Marked blocks were physically deallocated. This is"); Put_Line ("potentially dangerous, and you might want to run"); Put_Line ("again with a lower value of Minimum_To_Free"); end if; Put_Line ("Current Water Mark: " & Byte_Count'Image (Pool.Current_Water_Mark)); Put_Line ("High Water Mark: " & Byte_Count'Image (Pool.High_Water)); Put_Line (""); if Display_Slots then Data := Backtrace_Htable.Get_First; while Data /= null loop if Data.Kind in Alloc .. Dealloc then Elem := new Traceback_Htable_Elem' (Traceback => new Tracebacks_Array'(Data.Traceback.all), Count => Data.Count, Kind => Data.Kind, Total => Data.Total, Frees => Data.Frees, Total_Frees => Data.Total_Frees, Next => null); Backtrace_Htable_Cumulate.Set (Elem); if Cumulate then K := (if Data.Kind = Alloc then Indirect_Alloc else Indirect_Dealloc); -- Propagate the direct call to all its parents for T in Data.Traceback'First + 1 .. Data.Traceback'Last loop Elem := Backtrace_Htable_Cumulate.Get (Data.Traceback (T .. Data.Traceback'Last)'Unrestricted_Access); -- If not, insert it if Elem = null then Elem := new Traceback_Htable_Elem' (Traceback => new Tracebacks_Array' (Data.Traceback (T .. Data.Traceback'Last)), Count => Data.Count, Kind => K, Total => Data.Total, Frees => Data.Frees, Total_Frees => Data.Total_Frees, Next => null); Backtrace_Htable_Cumulate.Set (Elem); -- Properly take into account that the subprograms -- indirectly called might be doing either allocations -- or deallocations. This needs to be reflected in the -- counts. else Elem.Count := Elem.Count + Data.Count; if K = Elem.Kind then Elem.Total := Elem.Total + Data.Total; elsif Elem.Total > Data.Total then Elem.Total := Elem.Total - Data.Total; else Elem.Kind := K; Elem.Total := Data.Total - Elem.Total; end if; end if; end loop; end if; Data := Backtrace_Htable.Get_Next; end if; end loop; Put_Line ("List of allocations/deallocations: "); Data := Backtrace_Htable_Cumulate.Get_First; while Data /= null loop case Data.Kind is when Alloc => Put ("alloc (count:"); when Indirect_Alloc => Put ("indirect alloc (count:"); when Dealloc => Put ("free (count:"); when Indirect_Dealloc => Put ("indirect free (count:"); end case; Put (Natural'Image (Data.Count) & ", total:" & Byte_Count'Image (Data.Total) & ") "); for T in Data.Traceback'Range loop Put (Image_C (PC_For (Data.Traceback (T))) & ' '); end loop; Put_Line (""); Data := Backtrace_Htable_Cumulate.Get_Next; end loop; Backtrace_Htable_Cumulate.Reset; end if; if Display_Leaks then Put_Line (""); Put_Line ("List of not deallocated blocks:"); -- Do not try to group the blocks with the same stack traces -- together. This is done by the gnatmem output. Current := Pool.First_Used_Block; while Current /= System.Null_Address loop Header := Header_Of (Current); Put ("Size: " & Storage_Count'Image (Header.Block_Size) & " at: "); if Header.Alloc_Traceback /= null then for T in Header.Alloc_Traceback.Traceback'Range loop Put (Image_C (PC_For (Header.Alloc_Traceback.Traceback (T))) & ' '); end loop; end if; Put_Line (""); Current := Header.Next; end loop; end if; end Print_Info; ---------- -- Dump -- ---------- procedure Dump (Pool : Debug_Pool; Size : Positive; Report : Report_Type := All_Reports) is procedure Do_Report (Sort : Report_Type); -- Do a specific type of report --------------- -- Do_Report -- --------------- procedure Do_Report (Sort : Report_Type) is Elem : Traceback_Htable_Elem_Ptr; Bigger : Boolean; Grand_Total : Float; Max : array (1 .. Size) of Traceback_Htable_Elem_Ptr := (others => null); -- Sorted array for the biggest memory users Allocated_In_Pool : Byte_Count; -- safe thread Pool.Allocated Elem_Safe : Traceback_Htable_Elem; -- safe thread current elem.all; Max_M_Safe : Traceback_Htable_Elem; -- safe thread Max(M).all begin Put_Line (""); case Sort is when All_Reports | Memory_Usage => Put_Line (Size'Img & " biggest memory users at this time:"); Put_Line ("Results include bytes and chunks still allocated"); Grand_Total := Float (Pool.Current_Water_Mark); when Allocations_Count => Put_Line (Size'Img & " biggest number of live allocations:"); Put_Line ("Results include bytes and chunks still allocated"); Grand_Total := Float (Pool.Current_Water_Mark); when Sort_Total_Allocs => Put_Line (Size'Img & " biggest number of allocations:"); Put_Line ("Results include total bytes and chunks allocated,"); Put_Line ("even if no longer allocated - Deallocations are" & " ignored"); declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Allocated_In_Pool := Pool.Allocated; end; Grand_Total := Float (Allocated_In_Pool); when Marked_Blocks => Put_Line ("Special blocks marked by Mark_Traceback"); Grand_Total := 0.0; end case; declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Elem := Backtrace_Htable.Get_First; end; while Elem /= null loop declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Elem_Safe := Elem.all; end; -- Handle only alloc elememts if Elem_Safe.Kind = Alloc then -- Ignore small blocks (depending on the sorting criteria) to -- gain speed. if (Sort = Memory_Usage and then Elem_Safe.Total - Elem_Safe.Total_Frees >= 1_000) or else (Sort = Allocations_Count and then Elem_Safe.Count - Elem_Safe.Frees >= 1) or else (Sort = Sort_Total_Allocs and then Elem_Safe.Count > 1) or else (Sort = Marked_Blocks and then Elem_Safe.Total = 0) then if Sort = Marked_Blocks then Grand_Total := Grand_Total + Float (Elem_Safe.Count); end if; for M in Max'Range loop Bigger := Max (M) = null; if not Bigger then declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Max_M_Safe := Max (M).all; end; case Sort is when All_Reports | Memory_Usage => Bigger := Max_M_Safe.Total - Max_M_Safe.Total_Frees < Elem_Safe.Total - Elem_Safe.Total_Frees; when Allocations_Count => Bigger := Max_M_Safe.Count - Max_M_Safe.Frees < Elem_Safe.Count - Elem_Safe.Frees; when Marked_Blocks | Sort_Total_Allocs => Bigger := Max_M_Safe.Count < Elem_Safe.Count; end case; end if; if Bigger then Max (M + 1 .. Max'Last) := Max (M .. Max'Last - 1); Max (M) := Elem; exit; end if; end loop; end if; end if; declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Elem := Backtrace_Htable.Get_Next; end; end loop; if Grand_Total = 0.0 then Grand_Total := 1.0; end if; for M in Max'Range loop exit when Max (M) = null; declare type Percent is delta 0.1 range 0.0 .. 100.0; P : Percent; Total : Byte_Count; begin declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Max_M_Safe := Max (M).all; end; case Sort is when All_Reports | Allocations_Count | Memory_Usage => Total := Max_M_Safe.Total - Max_M_Safe.Total_Frees; when Sort_Total_Allocs => Total := Max_M_Safe.Total; when Marked_Blocks => Total := Byte_Count (Max_M_Safe.Count); end case; declare Normalized_Total : constant Float := Float (Total); -- In multi tasking configuration, memory deallocations -- during Do_Report processing can lead to Total > -- Grand_Total. As Percent requires Total <= Grand_Total begin if Normalized_Total > Grand_Total then P := 100.0; else P := Percent (100.0 * Normalized_Total / Grand_Total); end if; end; case Sort is when All_Reports | Allocations_Count | Memory_Usage => declare Count : constant Natural := Max_M_Safe.Count - Max_M_Safe.Frees; begin Put (P'Img & "%:" & Total'Img & " bytes in" & Count'Img & " chunks at"); end; when Sort_Total_Allocs => Put (P'Img & "%:" & Total'Img & " bytes in" & Max_M_Safe.Count'Img & " chunks at"); when Marked_Blocks => Put (P'Img & "%:" & Max_M_Safe.Count'Img & " chunks /" & Integer (Grand_Total)'Img & " at"); end case; end; for J in Max (M).Traceback'Range loop Put (" " & Image_C (PC_For (Max (M).Traceback (J)))); end loop; Put_Line (""); end loop; end Do_Report; -- Local variables Total_Freed : Byte_Count; -- safe thread pool logically & physically deallocated Traceback_Elements_Allocated : Byte_Count; -- safe thread Traceback_Count Validity_Elements_Allocated : Byte_Count; -- safe thread Validity_Count Ada_Allocs_Bytes : Byte_Count; -- safe thread pool Allocated Ada_Allocs_Chunks : Byte_Count; -- safe thread pool Alloc_Count Ada_Free_Chunks : Byte_Count; -- safe thread pool Free_Count -- Start of processing for Dump begin declare Lock : Scope_Lock; pragma Unreferenced (Lock); begin Total_Freed := Pool.Logically_Deallocated + Pool.Physically_Deallocated; Traceback_Elements_Allocated := Traceback_Count; Validity_Elements_Allocated := Validity_Count; Ada_Allocs_Bytes := Pool.Allocated; Ada_Allocs_Chunks := Pool.Alloc_Count; Ada_Free_Chunks := Pool.Free_Count; end; Put_Line ("Traceback elements allocated: " & Traceback_Elements_Allocated'Img); Put_Line ("Validity elements allocated: " & Validity_Elements_Allocated'Img); Put_Line (""); Put_Line ("Ada Allocs:" & Ada_Allocs_Bytes'Img & " bytes in" & Ada_Allocs_Chunks'Img & " chunks"); Put_Line ("Ada Free:" & Total_Freed'Img & " bytes in" & Ada_Free_Chunks'Img & " chunks"); Put_Line ("Ada Current watermark: " & Byte_Count'Image (Pool.Current_Water_Mark) & " in" & Byte_Count'Image (Ada_Allocs_Chunks - Ada_Free_Chunks) & " chunks"); Put_Line ("Ada High watermark: " & Pool.High_Water_Mark'Img); case Report is when All_Reports => for Sort in Report_Type loop if Sort /= All_Reports then Do_Report (Sort); end if; end loop; when others => Do_Report (Report); end case; end Dump; ----------------- -- Dump_Stdout -- ----------------- procedure Dump_Stdout (Pool : Debug_Pool; Size : Positive; Report : Report_Type := All_Reports) is procedure Internal is new Dump (Put_Line => Stdout_Put_Line, Put => Stdout_Put); -- Start of processing for Dump_Stdout begin Internal (Pool, Size, Report); end Dump_Stdout; ----------- -- Reset -- ----------- procedure Reset is Elem : Traceback_Htable_Elem_Ptr; Lock : Scope_Lock; pragma Unreferenced (Lock); begin Elem := Backtrace_Htable.Get_First; while Elem /= null loop Elem.Count := 0; Elem.Frees := 0; Elem.Total := 0; Elem.Total_Frees := 0; Elem := Backtrace_Htable.Get_Next; end loop; end Reset; ------------------ -- Storage_Size -- ------------------ function Storage_Size (Pool : Debug_Pool) return Storage_Count is pragma Unreferenced (Pool); begin return Storage_Count'Last; end Storage_Size; --------------------- -- High_Water_Mark -- --------------------- function High_Water_Mark (Pool : Debug_Pool) return Byte_Count is Lock : Scope_Lock; pragma Unreferenced (Lock); begin return Pool.High_Water; end High_Water_Mark; ------------------------ -- Current_Water_Mark -- ------------------------ function Current_Water_Mark (Pool : Debug_Pool) return Byte_Count is Lock : Scope_Lock; pragma Unreferenced (Lock); begin return Pool.Allocated - Pool.Logically_Deallocated - Pool.Physically_Deallocated; end Current_Water_Mark; ------------------------------ -- System_Memory_Debug_Pool -- ------------------------------ procedure System_Memory_Debug_Pool (Has_Unhandled_Memory : Boolean := True) is Lock : Scope_Lock; pragma Unreferenced (Lock); begin System_Memory_Debug_Pool_Enabled := True; Allow_Unhandled_Memory := Has_Unhandled_Memory; end System_Memory_Debug_Pool; --------------- -- Configure -- --------------- procedure Configure (Pool : in out Debug_Pool; Stack_Trace_Depth : Natural := Default_Stack_Trace_Depth; Maximum_Logically_Freed_Memory : SSC := Default_Max_Freed; Minimum_To_Free : SSC := Default_Min_Freed; Reset_Content_On_Free : Boolean := Default_Reset_Content; Raise_Exceptions : Boolean := Default_Raise_Exceptions; Advanced_Scanning : Boolean := Default_Advanced_Scanning; Errors_To_Stdout : Boolean := Default_Errors_To_Stdout; Low_Level_Traces : Boolean := Default_Low_Level_Traces) is Lock : Scope_Lock; pragma Unreferenced (Lock); begin Pool.Stack_Trace_Depth := Stack_Trace_Depth; Pool.Maximum_Logically_Freed_Memory := Maximum_Logically_Freed_Memory; Pool.Reset_Content_On_Free := Reset_Content_On_Free; Pool.Raise_Exceptions := Raise_Exceptions; Pool.Minimum_To_Free := Minimum_To_Free; Pool.Advanced_Scanning := Advanced_Scanning; Pool.Errors_To_Stdout := Errors_To_Stdout; Pool.Low_Level_Traces := Low_Level_Traces; end Configure; ---------------- -- Print_Pool -- ---------------- procedure Print_Pool (A : System.Address) is Storage : constant Address := A; Valid : constant Boolean := Is_Valid (Storage); Header : Allocation_Header_Access; begin -- We might get Null_Address if the call from gdb was done incorrectly. -- For instance, doing a "print_pool(my_var)" passes 0x0, instead of -- passing the value of my_var. if A = System.Null_Address then Put_Line (Standard_Output, "Memory not under control of the storage pool"); return; end if; if not Valid then Put_Line (Standard_Output, "Memory not under control of the storage pool"); else Header := Header_Of (Storage); Print_Address (Standard_Output, A); Put_Line (Standard_Output, " allocated at:"); Print_Traceback (Standard_Output, "", Header.Alloc_Traceback); if To_Traceback (Header.Dealloc_Traceback) /= null then Print_Address (Standard_Output, A); Put_Line (Standard_Output, " logically freed memory, deallocated at:"); Print_Traceback (Standard_Output, "", To_Traceback (Header.Dealloc_Traceback)); end if; end if; end Print_Pool; ----------------------- -- Print_Info_Stdout -- ----------------------- procedure Print_Info_Stdout (Pool : Debug_Pool; Cumulate : Boolean := False; Display_Slots : Boolean := False; Display_Leaks : Boolean := False) is procedure Internal is new Print_Info (Put_Line => Stdout_Put_Line, Put => Stdout_Put); -- Start of processing for Print_Info_Stdout begin Internal (Pool, Cumulate, Display_Slots, Display_Leaks); end Print_Info_Stdout; ------------------ -- Dump_Gnatmem -- ------------------ procedure Dump_Gnatmem (Pool : Debug_Pool; File_Name : String) is type File_Ptr is new System.Address; function fopen (Path : String; Mode : String) return File_Ptr; pragma Import (C, fopen); procedure fwrite (Ptr : System.Address; Size : size_t; Nmemb : size_t; Stream : File_Ptr); procedure fwrite (Str : String; Size : size_t; Nmemb : size_t; Stream : File_Ptr); pragma Import (C, fwrite); procedure fputc (C : Integer; Stream : File_Ptr); pragma Import (C, fputc); procedure fclose (Stream : File_Ptr); pragma Import (C, fclose); Address_Size : constant size_t := System.Address'Max_Size_In_Storage_Elements; -- Size in bytes of a pointer File : File_Ptr; Current : System.Address; Header : Allocation_Header_Access; Actual_Size : size_t; Num_Calls : Integer; Tracebk : Tracebacks_Array_Access; Dummy_Time : Duration := 1.0; begin File := fopen (File_Name & ASCII.NUL, "wb" & ASCII.NUL); fwrite ("GMEM DUMP" & ASCII.LF, 10, 1, File); fwrite (Ptr => Dummy_Time'Address, Size => Duration'Max_Size_In_Storage_Elements, Nmemb => 1, Stream => File); -- List of not deallocated blocks (see Print_Info) Current := Pool.First_Used_Block; while Current /= System.Null_Address loop Header := Header_Of (Current); Actual_Size := size_t (Header.Block_Size); if Header.Alloc_Traceback /= null then Tracebk := Header.Alloc_Traceback.Traceback; Num_Calls := Tracebk'Length; -- (Code taken from memtrack.adb in GNAT's sources) -- Logs allocation call using the format: -- 'A' <mem addr> <size chunk> <len backtrace> <addr1> ... <addrn> fputc (Character'Pos ('A'), File); fwrite (Current'Address, Address_Size, 1, File); fwrite (Ptr => Actual_Size'Address, Size => size_t'Max_Size_In_Storage_Elements, Nmemb => 1, Stream => File); fwrite (Ptr => Dummy_Time'Address, Size => Duration'Max_Size_In_Storage_Elements, Nmemb => 1, Stream => File); fwrite (Ptr => Num_Calls'Address, Size => Integer'Max_Size_In_Storage_Elements, Nmemb => 1, Stream => File); for J in Tracebk'First .. Tracebk'First + Num_Calls - 1 loop declare Ptr : System.Address := PC_For (Tracebk (J)); begin fwrite (Ptr'Address, Address_Size, 1, File); end; end loop; end if; Current := Header.Next; end loop; fclose (File); end Dump_Gnatmem; ---------------- -- Stdout_Put -- ---------------- procedure Stdout_Put (S : String) is begin Put (Standard_Output, S); end Stdout_Put; --------------------- -- Stdout_Put_Line -- --------------------- procedure Stdout_Put_Line (S : String) is begin Put_Line (Standard_Output, S); end Stdout_Put_Line; -- Package initialization begin Allocate_End; Deallocate_End; Dereference_End; end GNAT.Debug_Pools;
30,104
ada
80
thindil/steamsky
tests/ships-movement-test_data-tests.adb
<filename>tests/ships-movement-test_data-tests.adb -- This package has been generated automatically by GNATtest. -- You are allowed to add your code to the bodies of test routines. -- Such changes will be kept during further regeneration of this file. -- All code placed outside of test routine bodies will be lost. The -- code intended to set up and tear down the test environment should be -- placed into Ships.Movement.Test_Data. with AUnit.Assertions; use AUnit.Assertions; with System.Assertions; -- begin read only -- id:2.2/00/ -- -- This section can be used to add with clauses if necessary. -- -- end read only with Ada.Text_IO; use Ada.Text_IO; -- begin read only -- end read only package body Ships.Movement.Test_Data.Tests is -- begin read only -- id:2.2/01/ -- -- This section can be used to add global variables and other elements. -- -- end read only -- begin read only -- end read only -- begin read only function Wrap_Test_MoveShip_143def_3bb6cb (X, Y: Integer; Message: in out Unbounded_String) return Natural is begin declare Test_MoveShip_143def_3bb6cb_Result: constant Natural := GNATtest_Generated.GNATtest_Standard.Ships.Movement.MoveShip (X, Y, Message); begin return Test_MoveShip_143def_3bb6cb_Result; end; end Wrap_Test_MoveShip_143def_3bb6cb; -- end read only -- begin read only procedure Test_MoveShip_test_moveship(Gnattest_T: in out Test); procedure Test_MoveShip_143def_3bb6cb(Gnattest_T: in out Test) renames Test_MoveShip_test_moveship; -- id:2.2/143def44414090ef/MoveShip/1/0/test_moveship/ procedure Test_MoveShip_test_moveship(Gnattest_T: in out Test) is function MoveShip (X, Y: Integer; Message: in out Unbounded_String) return Natural renames Wrap_Test_MoveShip_143def_3bb6cb; -- end read only pragma Unreferenced(Gnattest_T); OldX: constant Natural := Player_Ship.Sky_X; OldY: constant Natural := Player_Ship.Sky_Y; Message: Unbounded_String; NewX, NewY: Natural := 0; begin Player_Ship.Speed := FULL_SPEED; if Player_Ship.Sky_X + 1 <= 1_024 then NewX := 1; end if; if Player_Ship.Sky_Y + 1 <= 1_024 then NewY := 1; end if; if MoveShip(NewX, NewY, Message) = 0 then Ada.Text_IO.Put_Line(To_String(Message)); end if; Assert (Player_Ship.Sky_X - NewX = OldX, "Failed to move player ship in X axis"); Assert (Player_Ship.Sky_Y - NewY = OldY, "Failed to move player ship in Y axis"); Player_Ship.Sky_X := OldX; Player_Ship.Sky_Y := OldY; Player_Ship.Speed := DOCKED; -- begin read only end Test_MoveShip_test_moveship; -- end read only -- begin read only function Wrap_Test_DockShip_bfbe82_875e5b (Docking: Boolean; Escape: Boolean := False) return String is begin declare Test_DockShip_bfbe82_875e5b_Result: constant String := GNATtest_Generated.GNATtest_Standard.Ships.Movement.DockShip (Docking, Escape); begin return Test_DockShip_bfbe82_875e5b_Result; end; end Wrap_Test_DockShip_bfbe82_875e5b; -- end read only -- begin read only procedure Test_DockShip_test_dockship(Gnattest_T: in out Test); procedure Test_DockShip_bfbe82_875e5b(Gnattest_T: in out Test) renames Test_DockShip_test_dockship; -- id:2.2/bfbe82e1179e6b20/DockShip/1/0/test_dockship/ procedure Test_DockShip_test_dockship(Gnattest_T: in out Test) is function DockShip (Docking: Boolean; Escape: Boolean := False) return String renames Wrap_Test_DockShip_bfbe82_875e5b; -- end read only pragma Unreferenced(Gnattest_T); Message: Unbounded_String; begin Message := To_Unbounded_String(DockShip(False)); Assert (Message = Null_Unbounded_String, "Failed to undock from the base."); Message := To_Unbounded_String(DockShip(True)); Assert(Message = Null_Unbounded_String, "Failed to dock to the base."); -- begin read only end Test_DockShip_test_dockship; -- end read only -- begin read only function Wrap_Test_ChangeShipSpeed_a103ef_17b968 (SpeedValue: Ship_Speed) return String is begin declare Test_ChangeShipSpeed_a103ef_17b968_Result: constant String := GNATtest_Generated.GNATtest_Standard.Ships.Movement.ChangeShipSpeed (SpeedValue); begin return Test_ChangeShipSpeed_a103ef_17b968_Result; end; end Wrap_Test_ChangeShipSpeed_a103ef_17b968; -- end read only -- begin read only procedure Test_ChangeShipSpeed_test_changeshipspeed (Gnattest_T: in out Test); procedure Test_ChangeShipSpeed_a103ef_17b968 (Gnattest_T: in out Test) renames Test_ChangeShipSpeed_test_changeshipspeed; -- id:2.2/a103efdf9c3f9d91/ChangeShipSpeed/1/0/test_changeshipspeed/ procedure Test_ChangeShipSpeed_test_changeshipspeed (Gnattest_T: in out Test) is function ChangeShipSpeed(SpeedValue: Ship_Speed) return String renames Wrap_Test_ChangeShipSpeed_a103ef_17b968; -- end read only pragma Unreferenced(Gnattest_T); Message: Unbounded_String; begin Player_Ship.Crew(2).Order := Pilot; Player_Ship.Crew(3).Order := Engineer; Message := To_Unbounded_String(ChangeShipSpeed(FULL_SPEED)); if Message /= Null_Unbounded_String then Ada.Text_IO.Put_Line(To_String(Message)); Assert(False, "Failed to change speed of docked ship."); end if; Player_Ship.Crew(2).Order := Pilot; Player_Ship.Crew(3).Order := Engineer; Message := To_Unbounded_String(DockShip(False)); if Message /= Null_Unbounded_String then Ada.Text_IO.Put_Line(To_String(Message)); Assert(False, "Failed to dock ship again."); end if; Player_Ship.Crew(2).Order := Pilot; Player_Ship.Crew(3).Order := Engineer; Message := To_Unbounded_String(ChangeShipSpeed(FULL_STOP)); if Message /= Null_Unbounded_String then Ada.Text_IO.Put_Line(To_String(Message)); Assert(False, "Failed to change speed of ship."); end if; Player_Ship.Crew(2).Order := Pilot; Player_Ship.Crew(3).Order := Engineer; Message := To_Unbounded_String(DockShip(True)); if Message /= Null_Unbounded_String then Ada.Text_IO.Put_Line(To_String(Message)); Assert(False, "Failed to dock ship again second time."); end if; -- begin read only end Test_ChangeShipSpeed_test_changeshipspeed; -- end read only -- begin read only function Wrap_Test_RealSpeed_da7fcb_f7fd56 (Ship: Ship_Record; InfoOnly: Boolean := False) return Natural is begin declare Test_RealSpeed_da7fcb_f7fd56_Result: constant Natural := GNATtest_Generated.GNATtest_Standard.Ships.Movement.RealSpeed (Ship, InfoOnly); begin return Test_RealSpeed_da7fcb_f7fd56_Result; end; end Wrap_Test_RealSpeed_da7fcb_f7fd56; -- end read only -- begin read only procedure Test_RealSpeed_test_realspeed(Gnattest_T: in out Test); procedure Test_RealSpeed_da7fcb_f7fd56(Gnattest_T: in out Test) renames Test_RealSpeed_test_realspeed; -- id:2.2/da7fcba60b6babad/RealSpeed/1/0/test_realspeed/ procedure Test_RealSpeed_test_realspeed(Gnattest_T: in out Test) is function RealSpeed (Ship: Ship_Record; InfoOnly: Boolean := False) return Natural renames Wrap_Test_RealSpeed_da7fcb_f7fd56; -- end read only pragma Unreferenced(Gnattest_T); begin Assert (RealSpeed(Player_Ship) = 0, "Failed to get speed of docked ship."); Player_Ship.Speed := FULL_SPEED; Assert (RealSpeed(Player_Ship) /= 0, "Failed to get speed of ship with full speed."); Player_Ship.Speed := DOCKED; Assert (RealSpeed(Player_Ship, True) /= 0, "Failed to get potential speed of docked ship."); -- begin read only end Test_RealSpeed_test_realspeed; -- end read only -- begin read only function Wrap_Test_CountFuelNeeded_db602d_18e85d return Integer is begin declare Test_CountFuelNeeded_db602d_18e85d_Result: constant Integer := GNATtest_Generated.GNATtest_Standard.Ships.Movement.CountFuelNeeded; begin return Test_CountFuelNeeded_db602d_18e85d_Result; end; end Wrap_Test_CountFuelNeeded_db602d_18e85d; -- end read only -- begin read only procedure Test_CountFuelNeeded_test_countfuelneeded (Gnattest_T: in out Test); procedure Test_CountFuelNeeded_db602d_18e85d (Gnattest_T: in out Test) renames Test_CountFuelNeeded_test_countfuelneeded; -- id:2.2/db602d4cda90f238/CountFuelNeeded/1/0/test_countfuelneeded/ procedure Test_CountFuelNeeded_test_countfuelneeded (Gnattest_T: in out Test) is function CountFuelNeeded return Integer renames Wrap_Test_CountFuelNeeded_db602d_18e85d; -- end read only pragma Unreferenced(Gnattest_T); begin Assert(CountFuelNeeded < 1, "Failed to count needed fuel to travel."); -- begin read only end Test_CountFuelNeeded_test_countfuelneeded; -- end read only -- begin read only procedure Wrap_Test_WaitInPlace_a6040e_d787da(Minutes: Positive) is begin GNATtest_Generated.GNATtest_Standard.Ships.Movement.WaitInPlace(Minutes); end Wrap_Test_WaitInPlace_a6040e_d787da; -- end read only -- begin read only procedure Test_WaitInPlace_test_waitinplace(Gnattest_T: in out Test); procedure Test_WaitInPlace_a6040e_d787da(Gnattest_T: in out Test) renames Test_WaitInPlace_test_waitinplace; -- id:2.2/a6040ed3f85f9963/WaitInPlace/1/0/test_waitinplace/ procedure Test_WaitInPlace_test_waitinplace(Gnattest_T: in out Test) is procedure WaitInPlace(Minutes: Positive) renames Wrap_Test_WaitInPlace_a6040e_d787da; -- end read only pragma Unreferenced(Gnattest_T); begin WaitInPlace(1); Assert(True, "This test can only crash."); -- begin read only end Test_WaitInPlace_test_waitinplace; -- end read only -- begin read only -- id:2.2/02/ -- -- This section can be used to add elaboration code for the global state. -- begin -- end read only null; -- begin read only -- end read only end Ships.Movement.Test_Data.Tests;
30,105
ada
0
damaki/Verhoeff
src/verhoeff.adb
<filename>src/verhoeff.adb<gh_stars>0 ------------------------------------------------------------------------------- -- Copyright (c) 2016 <NAME> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -- sell copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. ------------------------------------------------------------------------------- package body Verhoeff with SPARK_Mode => On is type Digit_Number is new Natural range 0 .. 9; D : constant array(Digit_Number, Digit_Number) of Digit_Number := ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 2, 3, 4, 0, 6, 7, 8, 9, 5), (2, 3, 4, 0, 1, 7, 8, 9, 5, 6), (3, 4, 0, 1, 2, 8, 9, 5, 6, 7), (4, 0, 1, 2, 3, 9, 5, 6, 7, 8), (5, 9, 8, 7, 6, 0, 4, 3, 2, 1), (6, 5, 9, 8, 7, 1, 0, 4, 3, 2), (7, 6, 5, 9, 8, 2, 1, 0, 4, 3), (8, 7, 6, 5, 9, 3, 2, 1, 0, 4), (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); Inv : constant array(Digit_Number) of Digit_Number := (0, 4, 3, 2, 1, 5, 6, 7, 8, 9); P : constant array(Digit_Number range 0 .. 7, Digit_Number) of Digit_Number := ((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (1, 5, 7, 6, 2, 8, 3, 0, 9, 4), (5, 8, 0, 3, 7, 9, 6, 1, 4, 2), (8, 9, 1, 6, 0, 4, 3, 5, 2, 7), (9, 4, 5, 3, 1, 2, 6, 8, 7, 0), (4, 2, 8, 6, 5, 7, 3, 9, 0, 1), (2, 7, 9, 3, 8, 0, 6, 4, 1, 5), (7, 0, 4, 6, 9, 1, 3, 2, 5, 8)); -- Check that Inv(Inv(j)) == j pragma Assert(for all J in Digit_Number => Inv(Inv(J)) = J); -- Check that D(j, Inv(j)) = 0 pragma Assert(for all J in Digit_Number => D(J, Inv(J)) = 0); -- Check that P(i+j, n) = P(i, P(j, n)) pragma Assert(for all I in Digit_Number => (for all J in Digit_Number => (for all N in Digit_Number => P((I+J) mod 8, N) = P(I mod 8, P(J mod 8, N)) ) ) ); function To_Digit_Number(Value : in Digit_Character) return Digit_Number is (Digit_Number(Digit_Character'Pos(Value) - Digit_Character'Pos('0'))) with Inline; function To_Digit_Character(Value : in Digit_Number) return Digit_Character is (Digit_Character'Val(Digit_Character'Pos('0') + Integer(Value))) with Inline; function Compute_Verhoeff(Seq : in String; Initial : in Digit_Character) return Digit_Number with Pre => (for all I in Seq'Range => (Seq(I) in Digit_Character)) is C : Digit_Number := To_Digit_Number(Initial); I : Natural := 0; X : Natural := Seq'Length; begin while X > 0 loop pragma Loop_Variant(Decreases => X); pragma Loop_Invariant((I+X) = Seq'Length); I := I + 1; X := X - 1; C := D(C, P(Digit_Number(I mod 8), To_Digit_Number(Seq(Seq'First + X)))); end loop; return C; end Compute_Verhoeff; function Check_Digit(Seq : in String) return Digit_Character is begin return To_Digit_Character(Inv(Compute_Verhoeff(Seq, '0'))); end Check_Digit; function Is_Valid(Seq : in String) return Boolean is begin return 0 = Compute_Verhoeff(Seq(Seq'First .. Seq'Last - 1), Seq(Seq'Last)); end Is_Valid; end Verhoeff;
30,106
ada
0
DrenfongWong/tkm-rpc
specs/ada/common/tkmrpc-request-ees.ads
<filename>specs/ada/common/tkmrpc-request-ees.ads package Tkmrpc.Request.Ees is end Tkmrpc.Request.Ees;
30,107
ada
0
caqg/linux-home
.emacs.d/elpa/wisi-3.1.3/sal-gen_bounded_definite_vectors-gen_refs.ads
<gh_stars>0 -- Abstract : -- -- Variable_Reference for parent. -- -- In a child package because it's not Spark, and Spark does not -- allow 'Spark_Mode => Off' on type declarations. -- -- Copyright (C) 2019 Free Software Foundation, Inc. -- -- This library is free software; you can redistribute it and/or modify it -- under terms of the GNU General Public License as published by the Free -- Software Foundation; either version 3, or (at your option) any later -- version. This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHAN- -- TABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- As a special exception under Section 7 of GPL version 3, you are granted -- additional permissions described in the GCC Runtime Library Exception, -- version 3.1, as published by the Free Software Foundation. pragma License (Modified_GPL); generic package SAL.Gen_Bounded_Definite_Vectors.Gen_Refs with Spark_Mode => Off is type Variable_Reference_Type (Element : not null access Element_Type) is private with Implicit_Dereference => Element; function Variable_Ref (Container : aliased in out Vector; Index : in Index_Type) return Variable_Reference_Type with Inline, Pre => Index in Index_Type'First .. Last_Index (Container); type Constant_Reference_Type (Element : not null access constant Element_Type) is private with Implicit_Dereference => Element; function Constant_Ref (Container : aliased in Vector; Index : in Index_Type) return Constant_Reference_Type with Inline, Pre => Index in Index_Type'First .. Last_Index (Container); private type Variable_Reference_Type (Element : not null access Element_Type) is record Dummy : Integer := raise Program_Error with "uninitialized reference"; end record; type Constant_Reference_Type (Element : not null access constant Element_Type) is record Dummy : Integer := raise Program_Error with "uninitialized reference"; end record; end SAL.Gen_Bounded_Definite_Vectors.Gen_Refs;
30,108
ada
204
spr93/whitakers-words
src/support_utils/support_utils-addons_package-target_entry_io.adb
-- WORDS, a Latin dictionary, by <NAME> (USAF, Retired) -- -- Copyright <NAME> (1936–2010) -- -- This is a free program, which means it is proper to copy it and pass -- it on to your friends. Consider it a developmental item for which -- there is no charge. However, just for form, it is Copyrighted -- (c). Permission is hereby freely given for any and all use of program -- and data. You can sell it as your own, but at least tell me. -- -- This version is distributed without obligation, but the developer -- would appreciate comments and suggestions. -- -- All parts of the WORDS system, source code and data files, are made freely -- available to anyone who wishes to use them, for whatever purpose. separate (Support_Utils.Addons_Package) package body Target_Entry_Io is use Noun_Entry_IO; use Pronoun_Entry_IO; use Propack_Entry_IO; use Adjective_Entry_IO; use Numeral_Entry_IO; use Adverb_Entry_IO; use Verb_Entry_IO; -- use KIND_ENTRY_IO; -- -- use NOUN_KIND_TYPE_IO; -- use PRONOUN_KIND_TYPE_IO; -- use INFLECTIONS_PACKAGE.INTEGER_IO; -- use VERB_KIND_TYPE_IO; Spacer : Character := ' '; Noun : Noun_Entry; Pronoun : Pronoun_Entry; Propack : Propack_Entry; Adjective : Adjective_Entry; Numeral : Numeral_Entry; Adverb : Adverb_Entry; Verb : Verb_Entry; -- NOUN_KIND : NOUN_KIND_TYPE; -- PRONOUN_KIND : PRONOUN_KIND_TYPE; -- PROPACK_KIND : PRONOUN_KIND_TYPE; -- NUMERAL_VALUE : NUMERAL_VALUE_TYPE; -- VERB_KIND : VERB_KIND_TYPE; --KIND : KIND_ENTRY; procedure Get (F : in File_Type; P : out Target_Entry) is Ps : Target_Pofs_Type := X; begin Get (F, Ps); Get (F, Spacer); case Ps is when N => Get (F, Noun); P := (N, Noun); when Pron => Get (F, Pronoun); P := (Pron, Pronoun); when Pack => Get (F, Propack); P := (Pack, Propack); when Adj => Get (F, Adjective); P := (Adj, Adjective); when Num => Get (F, Numeral); P := (Num, Numeral); when Adv => Get (F, Adverb); P := (Adv, Adverb); when V => Get (F, Verb); P := (V, Verb); when X => P := (Pofs => X); end case; return; end Get; procedure Get (P : out Target_Entry) is Ps : Target_Pofs_Type := X; begin Get (Ps); Get (Spacer); case Ps is when N => Get (Noun); P := (N, Noun); when Pron => Get (Pronoun); P := (Pron, Pronoun); when Pack => Get (Propack); P := (Pack, Propack); when Adj => Get (Adjective); P := (Adj, Adjective); when Num => Get (Numeral); P := (Num, Numeral); when Adv => Get (Adverb); P := (Adv, Adverb); when V => Get (Verb); P := (V, Verb); when X => P := (Pofs => X); end case; return; end Get; procedure Put (F : in File_Type; P : in Target_Entry) is C : constant Positive := Positive (Col (F)); begin Put (F, P.Pofs); Put (F, ' '); case P.Pofs is when N => Put (F, P.N); when Pron => Put (F, P.Pron); when Pack => Put (F, P.Pack); when Adj => Put (F, P.Adj); when Num => Put (F, P.Num); when Adv => Put (F, P.Adv); when V => Put (F, P.V); when others => null; end case; Put (F, String'((Integer (Col (F)) .. Target_Entry_Io.Default_Width + C - 1 => ' '))); return; end Put; procedure Put (P : in Target_Entry) is C : constant Positive := Positive (Col); begin Put (P.Pofs); Put (' '); case P.Pofs is when N => Put (P.N); when Pron => Put (P.Pron); when Pack => Put (P.Pack); when Adj => Put (P.Adj); when Num => Put (P.Num); when Adv => Put (P.Adv); when V => Put (P.V); when others => null; end case; Put (String'( (Integer (Col) .. Target_Entry_Io.Default_Width + C - 1 => ' '))); return; end Put; procedure Get (S : in String; P : out Target_Entry; Last : out Integer) is L : Integer := S'First - 1; Ps : Target_Pofs_Type := X; begin Get (S, Ps, L); L := L + 1; case Ps is when N => Get (S (L + 1 .. S'Last), Noun, Last); P := (N, Noun); when Pron => Get (S (L + 1 .. S'Last), Pronoun, Last); P := (Pron, Pronoun); when Pack => Get (S (L + 1 .. S'Last), Propack, Last); P := (Pack, Propack); when Adj => Get (S (L + 1 .. S'Last), Adjective, Last); P := (Adj, Adjective); when Num => Get (S (L + 1 .. S'Last), Numeral, Last); P := (Num, Numeral); when Adv => Get (S (L + 1 .. S'Last), Adverb, Last); P := (Adv, Adverb); when V => Get (S (L + 1 .. S'Last), Verb, Last); P := (V, Verb); when X => P := (Pofs => X); end case; return; end Get; procedure Put (S : out String; P : in Target_Entry) is L : Integer := S'First - 1; M : Integer := 0; begin M := L + Part_Of_Speech_Type_IO.Default_Width; Put (S (L + 1 .. M), P.Pofs); L := M + 1; S (L) := ' '; case P.Pofs is when N => M := L + Noun_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.N); when Pron => M := L + Pronoun_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.Pron); when Pack => M := L + Propack_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.Pack); when Adj => M := L + Adjective_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.Adj); when Num => M := L + Numeral_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.Num); when Adv => M := L + Adverb_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.Adv); when V => M := L + Verb_Entry_IO.Default_Width; Put (S (L + 1 .. M), P.V); when others => null; end case; S (M + 1 .. S'Last) := (others => ' '); end Put; end Target_Entry_Io;
30,109
ada
24
svn2github/matreshka
tools/segments_readers.adb
<gh_stars>10-100 ------------------------------------------------------------------------------ -- -- -- Matreshka Project -- -- -- -- Localization, Internationalization, Globalization for Ada -- -- -- -- Tools Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2009, <NAME> <<EMAIL>> -- -- 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 Ada.Text_IO; package body Segments_Readers is use Ada.Strings.Unbounded; LDML_Tag : constant String := "ldml"; Identity_Tag : constant String := "identity"; Version_Tag : constant String := "version"; Generation_Tag : constant String := "generation"; Language_Tag : constant String := "language"; Segmentations_Tag : constant String := "segmentations"; Segmentation_Tag : constant String := "segmentation"; Variables_Tag : constant String := "variables"; Variable_Tag : constant String := "variable"; Segment_Rules_Tag : constant String := "segmentRules"; Rule_Tag : constant String := "rule"; Id_Attribute : constant String := "id"; -- function "+" (Right : String) return Unbounded_String -- renames To_Unbounded_String; ---------------- -- Characters -- ---------------- overriding procedure Characters (Self : in out Segments_Reader; Ch : Unicode.CES.Byte_Sequence) is begin Append (Self.C, Ch); end Characters; ----------------- -- End_Element -- ----------------- overriding procedure End_Element (Self : in out Segments_Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := "") is begin if Local_Name = Variable_Tag or else Local_Name = Rule_Tag then Ada.Text_IO.Put_Line (To_String (Self.C)); end if; end End_Element; ------------------- -- Start_Element -- ------------------- overriding procedure Start_Element (Self : in out Segments_Reader; Namespace_URI : Unicode.CES.Byte_Sequence := ""; Local_Name : Unicode.CES.Byte_Sequence := ""; Qname : Unicode.CES.Byte_Sequence := ""; Attrs : Sax.Attributes.Attributes'Class) is begin if Local_Name = LDML_Tag then null; elsif Local_Name = Identity_Tag then null; elsif Local_Name = Version_Tag then null; elsif Local_Name = Generation_Tag then null; elsif Local_Name = Language_Tag then null; elsif Local_Name = Segmentations_Tag then null; elsif Local_Name = Segmentation_Tag then null; elsif Local_Name = Variables_Tag then null; elsif Local_Name = Variable_Tag then Ada.Text_IO.Put (Attrs.Get_Value (Id_Attribute) & " := "); Self.C := Null_Unbounded_String; elsif Local_Name = Segment_Rules_Tag then null; elsif Local_Name = Rule_Tag then Ada.Text_IO.Put (Attrs.Get_Value (Id_Attribute) & " => "); Self.C := Null_Unbounded_String; else Ada.Text_IO.Put_Line (Local_Name); raise Program_Error; end if; end Start_Element; end Segments_Readers;
30,110
ada
0
e3l6/SSMDev
gps.ads
<gh_stars>0 ------------------------------------------------------------------------------- -- GPS -- -- Copyright © 2016 <NAME> -- -- This code is available under the "MIT License". -- Please see the file COPYING in this distribution for license terms. -- -- Purpose: -- This package interfaces to the Adafruit Ultimate GPS Breakout v3 -- (https://www.adafruit.com/product/746) based on the MediaTek MT3339 -- chipset. ------------------------------------------------------------------------------- with Ada.Calendar; use Ada.Calendar; with Ada.Text_IO; use Ada.Text_IO; with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; with Ada.Float_Text_IO; use Ada.Float_Text_IO; package GPS is type Position_Type is record -- For latitude and longitude: positive values denote Northern and -- Eastern hemispheres, respectively; negative values denote -- Southern and Western hemispheres, respectively. Latitude : Float range -90.0 .. 90.0; Longitude : Float range -180.0 .. 180.0; Current_Time : Time; -- Universal Coordinated Time (UTC) end record; function Get_Position return Position_Type; end GPS;
30,111
ada
0
bracke/Meaning
source/RASCAL-WimpWindow.adb
<gh_stars>0 -------------------------------------------------------------------------------- -- -- -- Copyright (C) 2004, RISC OS Ada Library (RASCAL) developers. -- -- -- -- This library is free software; you can redistribute it and/or -- -- modify it under the terms of the GNU Lesser General Public -- -- License as published by the Free Software Foundation; either -- -- version 2.1 of the License, or (at your option) any later version. -- -- -- -- This library is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- -- Lesser General Public License for more details. -- -- -- -- You should have received a copy of the GNU Lesser General Public -- -- License along with this library; if not, write to the Free Software -- -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- -- -------------------------------------------------------------------------------- -- $Author$ -- $Date$ -- $Revision$ with Kernel; use Kernel; with Interfaces.C; use Interfaces.C; with Reporter; with RASCAL.Utility; use RASCAL.Utility; with RASCAL.Memory; use RASCAL.Memory; with RASCAL.OS; with RASCAL.Mode; package body RASCAL.WimpWindow is Wimp_Extend : constant := 16#400FB#; Wimp_GetWindowInfo : constant := 16#400CC#; Wimp_GetWindowState : constant := 16#400CB#; Wimp_GetWindowOutline : constant := 16#400E0#; Wimp_CreateWindow : constant := 16#400C1#; Wimp_DeleteWindow : constant := 16#400C3#; Wimp_OpenWindow : constant := 16#400C5#; Wimp_CloseWindow : constant := 16#400C6#; Wimp_SetExtent : constant := 16#400D7#; Wimp_SetCaretPosition : constant := 16#400D2#; Wimp_GetCaretPosition : constant := 16#400D3#; Wimp_RedrawWindow : constant := 16#400C8#; Wimp_UpdateWindow : constant := 16#400C9#; Wimp_GetRectangle : constant := 16#400CA#; Wimp_ForceRedraw : constant := 16#400D1#; -- procedure Open_WindowMax (Window : in Wimp_Handle_Type) is Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); Open : Wimp_OpenWindow_Type; begin Open.Visible_Area_Max_Y := Info.Visible_Area_Max_Y; Open.Visible_Area_Min_X := Info.Visible_Area_Min_X; Open.Visible_Area_Min_Y := Info.Visible_Area_Max_Y + Info.Work_Area_Min_Y; if Open.Visible_Area_Min_Y < 40 then Open.Visible_Area_Min_Y := 40; end if; Open.Visible_Area_Max_X := Info.Visible_Area_Min_X + Info.Work_Area_Max_X; Open.Window := Window; Open_Window (Open); end Open_WindowMax; -- procedure Open_WindowCentered (Window : in Wimp_Handle_Type) is right,top : Integer; width,height : Integer; x,y : Integer; Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); Open : Wimp_OpenWindow_Type; begin Right := Mode.Get_X_Resolution; Top := Mode.Get_Y_Resolution; width := Info.Visible_Area_Min_X - Info.Visible_Area_Max_X; height := Info.Visible_Area_Max_Y - Info.Visible_Area_Min_Y; x := (right - width) / 2 + width; y := (top - height) / 2 + height; Open.Visible_Area_Min_X := x; Open.Visible_Area_Min_Y := y - height; Open.Visible_Area_Max_X := x - width; Open.Visible_Area_Max_Y := y; Open.Window := Window; Open_Window (Open); end Open_WindowCentered; -- procedure Open_WindowAt (Window : in Wimp_Handle_Type; x : in Integer; y : in Integer) is width,height : Integer; Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); Open : Wimp_OpenWindow_Type; begin width := Info.Visible_Area_Min_X - Info.Visible_Area_Max_X; height := Info.Visible_Area_Max_Y - Info.Visible_Area_Min_Y; Open.Visible_Area_Min_X := x; Open.Visible_Area_Min_Y := y - height; Open.Visible_Area_Max_X := x - width; Open.Visible_Area_Max_Y := y; Open.Window := Window; Open_Window (Open); end Open_WindowAt; -- procedure Open_Window (Block : in Wimp_OpenWindow_Type) is Register : aliased Kernel.swi_regs; Error : oserror_access; begin Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.swi(Wimp_OpenWindow,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Open_Window: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Open_Window; -- procedure Close_Window (Window : in Wimp_Handle_Type) is Register : aliased Kernel.swi_regs; Error : oserror_access; begin Register.R(1) := Int (Window); Error := Kernel.swi(Wimp_CloseWindow,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Close_Window: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Close_Window; -- procedure Redraw_Window (Window : in Wimp_Handle_Type; Block : in out Wimp_RedrawInfo_Type; More : out Boolean) is Register : aliased Kernel.swi_regs; Error : oserror_access; begin Block.Window := Window; Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.SWI(Wimp_RedrawWindow,Register'Access,Register'Access); More := Error = null; end Redraw_Window; -- function Get_Rectangle (Block : in Wimp_RedrawInfo_Type) return Boolean is Register : aliased Kernel.swi_regs; Error : oserror_access; begin Register.R(0) := 0; Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.swi(Wimp_GetRectangle,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Rectangle: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Integer(Register.R(0)) /= 0; end Get_Rectangle; -- function Get_WindowOutline (Window : in Wimp_Handle_Type) return Wimp_WindowOutline_Type is Register : aliased Kernel.swi_regs; Error : oserror_access; Block : Wimp_WindowOutline_Type; begin Block.Window := Window; -- workaround for 32bit-bug Memory.PutWord(Integer(Window),Block'Address,0); Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.swi(Wimp_GetWindowOutline,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_WindowOutline: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Block; end Get_WindowOutline; -- function Get_WindowState (Window : in Wimp_Handle_Type) return Wimp_WindowState_Type is Register : aliased Kernel.swi_regs; Error : oserror_access; Block : Wimp_WindowState_Type; begin Block.Window := Window; -- workaround for 32bit-bug Memory.PutWord(Integer(Window),Block'Address,0); Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.swi(Wimp_GetWindowState,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_WindowState: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Block; end Get_WindowState; -- function Get_ParentWindow (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : oserror_access; Block : Wimp_WindowState_Type; begin Block.Window := Window; -- workaround for 32bit-bug Memory.PutWord(Integer(Window),Block'Address,0); Register.R(1) := Adr_To_Int(Block'Address); Register.R(2) := 16#4B534154#; Error := Kernel.swi(Wimp_GetWindowState,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_ParentWindow: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(3)); end Get_ParentWindow; -- function Get_AncestorWindow (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Child : Wimp_Handle_Type := Window; Parent : Wimp_Handle_Type; begin loop Parent := Get_ParentWindow(Child); -- Child has no parent if GetParent returns -1 exit when Integer(Parent) = -1; Child := Parent; end loop; return Child; end Get_AncestorWindow; -- function Get_WindowInfo(Window : in Wimp_Handle_Type; Icons : in Boolean := true) return Wimp_WindowInfo_Type is Register : aliased Kernel.swi_regs; Error : oserror_access; Icon_Nr : Integer := 0; NoIcons : Wimp_WindowInfo_Type (0); begin NoIcons.Window := Window; Register.R(1) := Adr_To_Int(NoIcons.Window'Address); Register.R(1) := Register.R(1) + 1; -- Set 'No icons' flag Error := Kernel.swi(Wimp_GetWindowInfo,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_WindowInfo (I): " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; if not Icons then return NoIcons; end if; Icon_Nr := NoIcons.Nr_Of_Icons_Initially; declare Block : Wimp_WindowInfo_Type(Icon_Nr); begin Block.Window := Window; Register.R(1) := Adr_To_Int(Block.Window'Address); Error := Kernel.swi(Wimp_GetWindowInfo,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_WindowInfo (II): " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Block; end; end Get_WindowInfo; -- function Get_External_WindowInfo (Window : in Wimp_Handle_Type) return Wimp_External_WindowInfo_Type is Register : aliased Kernel.swi_regs; Error : oserror_access; Info : Wimp_External_WindowInfo_Type; begin Info.Window := Window; Register.R(0) := 11; Register.R(1) := Adr_To_Int(Info'Address); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_External_WindowInfo: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Info; end Get_External_WindowInfo; -- function Get_Generic_WindowInfo return Wimp_External_WindowInfo_Type is begin return Get_External_WindowInfo(0); end Get_Generic_WindowInfo; -- procedure Get_WindowPosition (Window : in Wimp_Handle_Type; X_Pos : out Integer; Y_Pos : out Integer) is State : Wimp_WindowState_Type := WimpWindow.Get_WindowState (Window); begin X_Pos := State.Visible_Area_Min_X; Y_Pos := State.Visible_Area_Max_Y; end Get_WindowPosition; -- function Is_Open (Window : in Wimp_Handle_Type) return Boolean is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; Block : Wimp_WindowState_Type; begin Block.Window := Window; -- 32bit - bug workaround Memory.PutWord(Integer(Window),Block'Address,0); Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.SWI (Wimp_GetWindowState, Register'Access, Register'Access); return ((Block.Window_Flags and 2#10000000000000000#) > 0); end Is_Open; -- procedure Work_To_Screen (Window : in Wimp_Handle_Type; Work_X : in Integer; Work_Y : in Integer; Screen_X : out Integer; Screen_Y : out Integer) is Block : Wimp_WindowState_Type := Get_WindowState (Window); begin screen_x := work_x - (Block.Scroll_X_Offset - Block.Visible_Area_Min_X); screen_y := work_y - (Block.Scroll_Y_Offset - Block.Visible_Area_Max_Y); end Work_To_Screen; -- procedure Screen_To_Work (Window : in Wimp_Handle_Type; Screen_X : in Integer; Screen_Y : in Integer; Work_X : out Integer; Work_Y : out Integer) is Block : Wimp_WindowState_Type := Get_WindowState (Window); begin work_x := screen_x + (Block.Scroll_X_Offset - Block.Visible_Area_Min_X); work_y := screen_y + (Block.Scroll_Y_Offset - Block.Visible_Area_Max_Y); end Screen_To_Work; -- procedure Force_Redraw (Window : in Wimp_Handle_Type; Min_X : in Integer; Min_Y : in Integer; Max_X : in Integer; Max_Y : in Integer) is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := Int(Window); Register.R(1) := Int(Min_X); Register.R(2) := Int(Min_Y); Register.R(3) := Int(Max_X); Register.R(4) := Int(Max_Y); Error := Kernel.swi (Wimp_ForceRedraw, register'Access, register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.ForceRedraw: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Force_Redraw; -- procedure Force_RedrawAll is begin Force_Redraw (-1,0,0,9999,9999); end Force_RedrawAll; -- procedure Force_WindowRedraw (Window : in Wimp_Handle_Type) is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); begin Register.R(0) := Int(Window); Register.R(1) := Int(Info.Work_Area_Min_X); Register.R(2) := Int(Info.Work_Area_Min_Y); Register.R(3) := Int(Info.Work_Area_Max_X); Register.R(4) := Int(Info.Work_Area_Max_Y); Error := Kernel.swi (Wimp_ForceRedraw, register'Access, register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Force_WindowRedraw: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Force_WindowRedraw; -- function Get_WindowTitle (Window : in Wimp_Handle_Type) return String is Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); begin return To_Ada(Info.Title_Data.Title_Data); end Get_WindowTitle; -- function Get_Extent (Window : in Wimp_Handle_Type) return Wimp_WindowExtent_Type is Extent : Wimp_WindowExtent_Type; Info : Wimp_WindowInfo_Type(0) := Get_WindowInfo(Window,false); begin Extent.Work_Area_Min_X := Info.Work_Area_Min_X; Extent.Work_Area_Min_Y := Info.Work_Area_Min_Y; Extent.Work_Area_Max_X := Info.Work_Area_Max_X; Extent.Work_Area_Max_Y := Info.Work_Area_Max_Y; return Extent; end Get_Extent; -- procedure Set_Extent (Window : in Wimp_Handle_Type; Min_X : in Integer; Min_Y : in Integer; Max_X : in Integer; Max_Y : in Integer) is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; Extent : Wimp_WindowExtent_Type; begin Extent.Work_Area_Min_X := Min_X; Extent.Work_Area_Min_Y := Min_Y; Extent.Work_Area_Max_X := Max_X; Extent.Work_Area_Max_Y := Max_Y; Register.R(0) := Int(Window); Register.R(1) := Adr_To_Int(Extent'Address); Error := Kernel.swi (Wimp_SetExtent, Register'Access, Register'Access); if Error /= null then pragma Debug(Reporter.Report("WimpWindow.Set_Extent: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Set_Extent; -- procedure Delete_Window (Window : in Wimp_Handle_Type) is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; Block : Wimp_WindowOutline_Type; begin Block.Window := Window; Register.R(1) := Adr_To_Int(Block'Address); Error := Kernel.SWI (Wimp_DeleteWindow, Register'Access, Register'Access); if Error /= null then pragma Debug(Reporter.Report("WimpWindow.Delete_Window: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; end Delete_Window; -- function Get_Parent (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := 6; Register.R(1) := Int(Window); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Parent: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(1)); end Get_Parent; -- function Get_Top_ChildWindow (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := 7; Register.R(1) := Int(Window); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Top_ChildWindow: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(1)); end Get_Top_ChildWindow; -- function Get_Bottom_ChildWindow (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := 8; Register.R(1) := Int(Window); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Bottom_ChildWindow: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(1)); end Get_Bottom_ChildWindow; -- function Get_Sibling_Below (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := 9; Register.R(1) := Int(Window); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Sibling_Below: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(1)); end Get_Sibling_Below; -- function Get_Sibling_Above (Window : in Wimp_Handle_Type) return Wimp_Handle_Type is Register : aliased Kernel.swi_regs; Error : Kernel.oserror_access; begin Register.R(0) := 10; Register.R(1) := Int(Window); Error := Kernel.swi(Wimp_Extend,register'Access,register'Access); if Error /=null then pragma Debug(Reporter.Report("WimpWindow.Get_Sibling_Above: " & To_Ada(Error.ErrMess))); OS.Raise_Error(Error); end if; return Wimp_Handle_Type(Register.R(1)); end Get_Sibling_Above; -- function Count_Children (Window : in Wimp_Handle_Type) return Natural is Count : Natural := 0; Child : Wimp_Handle_Type; begin Child := Get_Top_ChildWindow(Window); while Child /= -1 loop Count := Count + 1; Child := Get_Sibling_Below (Child); end loop; return Count; end Count_Children; -- function Get_Children (Window : in Wimp_Handle_Type) return Child_List_Type is Count : constant Natural := Count_Children (Window); List : Child_List_Type (1..Count); Child : Wimp_Handle_Type; begin Child := Get_Top_ChildWindow(Window); for i in List'range loop List (i) := Child; Child := Get_Sibling_Below (Child); end loop; return List; end Get_Children; -- end RASCAL.WimpWindow;
30,112
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/timer_cancel.adb
-- { dg-do run } with Ada.Real_Time.Timing_Events; use Ada.Real_Time, Ada.Real_Time.Timing_Events; procedure Timer_Cancel is E : Timing_Event; C : Boolean; protected Dummy is procedure Trigger (Event : in out Timing_Event); end Dummy; protected body Dummy is procedure Trigger (Event : in out Timing_Event) is begin null; end Trigger; end Dummy; begin Set_Handler (E, Time_Last, Dummy.Trigger'Unrestricted_Access); if Time_Of_Event (E) /= Time_Last then raise Program_Error with "Event time not set correctly"; end if; Cancel_Handler (E, C); if not C then raise Program_Error with "Event triggered already"; end if; if Time_Of_Event (E) /= Time_First then raise Program_Error with "Event time not reset correctly"; end if; end Timer_Cancel;
30,113
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/volatile12.ads
package Volatile12 is type Arr is array (Integer range <>) of Integer with Volatile; procedure Proc (A : Arr); end Volatile12;
30,114
ada
0
reznikmm/gela
source/resolver/program-simple_resolvers.ads
-- SPDX-FileCopyrightText: 2020 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT ------------------------------------------------------------- with Program.Elements.Expressions; with Program.Elements.Identifiers; with Program.Cross_Reference_Updaters; private package Program.Simple_Resolvers is pragma Preelaborate; type Simple_Resolver is limited interface; type Simple_Resolver_Access is access all Simple_Resolver'Class with Storage_Size => 0; not overriding procedure Resolve_Identifier (Self : Simple_Resolver; Name : not null Program.Elements.Identifiers.Identifier_Access; Setter : not null Program.Cross_Reference_Updaters.Cross_Reference_Updater_Access) is abstract; procedure Resolve (Self : aliased in out Simple_Resolver'Class; Name : Program.Elements.Expressions.Expression_Access; Setter : not null Program.Cross_Reference_Updaters.Cross_Reference_Updater_Access); -- Resolve Name and call Setter.Set_Corresponding_Defining_Name end Program.Simple_Resolvers;
30,115
ada
6
jonashaggstrom/ada-canopen
tests/generic_collection_test.adb
with AUnit.Assertions; use AUnit.Assertions; with ACO.Utils.DS.Generic_Collection; with ACO.Utils.DS.Generic_Collection.Sorted; package body Generic_Collection_Test is pragma Assertion_Policy (Check); type Item_Type is new Character; subtype Test_Items is Item_Type range 'a' .. 'z'; package Collection_Pack is new ACO.Utils.DS.Generic_Collection (Item_Type => Item_Type, "=" => "="); Max_Size : constant := Test_Items'Pos(Test_Items'Last) - Test_Items'Pos(Test_Items'First) + 1; subtype Collection is Collection_Pack.Collection (Max_Size); package Sorted is type T is record Char : Character; Id : Natural; end record; function "=" (L : T; R : T) return Boolean is (L.Char = R.Char); package Collection_Pack is new ACO.Utils.DS.Generic_Collection (Item_Type => T, "=" => "="); function "<" (L : T; R : T) return Boolean is (L.Char < R.Char); package Pack is new Collection_Pack.Sorted ("<" => "<"); Max_Size : constant := 10; subtype Collection is Pack.Sorted_Collection (Max_Size); end Sorted; function Name (T : Test) return AUnit.Message_String is pragma Unreferenced (T); begin return AUnit.Format ("Data Structures: Generic (Sorted) Collection Test"); end Name; procedure Init_Test is C : Collection; begin Assert (C.Is_Empty, "Collection is not initially empty"); Assert (C.Length = 0, "Collection has not initially the length zero"); Assert (not C.Is_Full, "Collection is initially full"); Assert (C.Available = Max_Size, "Nof availables in collection incorrect"); for I in 1 .. C.Max_Size loop Assert (not C.Is_Valid_Index (I), "Empty collection has valid index"); end loop; end Init_Test; procedure Fill_And_Empty is C : Collection; L : Natural := 0; Loc : Natural; begin C.Clear; for I in Test_Items'Range loop C.Append (I); L := L + 1; Assert (C.Length = L, "Length incorrect"); Assert (C.Available = C.Max_Size - L, "Available incorrect"); Assert (C.Is_Valid_Index (L), "Index of added item invalid"); Assert (not C.Is_Valid_Index (L + 1), "Index of not added item valid"); Assert (C.Item_At (L) = I, "Added item incorrect"); Assert (C.Last = I, "Appended item not the last one"); Assert (C.First = Test_Items'First, "First item not the first added"); Assert (not C.Is_Empty, "Collection is empty after adding items"); Assert (C.Location (I) = L, "Location of added item incorrect"); end loop; Assert (C.Is_Full, "Collection not full after filling it"); for I in Test_Items'Range loop Loc := C.Location (I); C.Remove (Loc); L := L - 1; Assert (C.Length = L, "Length incorrect"); Assert (C.Available = C.Max_Size - L, "Available incorrect"); if not C.Is_Empty then Assert (C.Is_Valid_Index (Loc), "Front index invalid after removing front item"); Assert (C.First = Test_Items'Succ (I), "Item after removed not set as front item"); Assert (C.Last = Test_Items'Last, "Last item not kept"); else Assert (not C.Is_Valid_Index (Loc), "Front index valid when collection is empty"); end if; end loop; Assert (C.Is_Empty, "Not empty after removing all items"); end Fill_And_Empty; type Result (L : Natural) is record Description : String (1 .. L); Status : Boolean; end record; function Failed (Description : String) return Result is (Result'(L => Description'Length, Description => Description, Status => False)); function Success return Result is (Result'(L => 0, Description => "", Status => True)); type State_Array is array (Positive range <>) of Item_Type; function Check (C : in Collection'Class; State : in State_Array) return Result is First : Item_Type renames State (State'First); Last : Item_Type renames State (State'Last); Length : constant Natural := State'Length; begin if not (C.First = First) then return Failed ("First item incorrect"); end if; if not (C.Last = Last) then return Failed ("Last item incorrect"); end if; if not (C.Length = Length) then return Failed ("Incorrect length"); end if; if not (C.Available = C.Max_Size - Length) then return Failed ("Available incorrect"); end if; if not (if C.Length = 0 then C.Is_Empty else not C.Is_Empty) then return Failed ("Empty flag not consistent with length " & "Length =" & C.Length'Img & "=> Is_Empty = " & C.Is_Empty'Img); end if; if not (if C.Length = C.Max_Size then C.Is_Full else not C.Is_Full) then return Failed ("Full flag not consistent with length " & "Length =" & C.Length'Img & "=> Is_Full = " & C.Is_Full'Img); end if; for Index in 1 .. C.Max_Size loop if Index <= C.Length then if not (C.Is_Valid_Index (Index)) then return Failed ("Valid index reported as invalid"); end if; else if C.Is_Valid_Index (Index) then return Failed ("Invalid index reported as valid"); end if; end if; end loop; for Index in 1 .. C.Length loop if not (State (Index) = C.Item_At (Index)) then return Failed ("Item at index" & Index'Img & " does not match"); end if; end loop; return Success; end Check; procedure Insert is C : Collection; begin C.Insert ('a'); -- Insert front to empty declare S : constant Result := Check (C, (1 => 'a')); begin Assert (S.Status, S.Description); end; C.Insert ('b'); -- Insert front to non-empty declare S : constant Result := Check (C, ('b', 'a')); begin Assert (S.Status, S.Description); end; C.Clear; C.Insert ('a', Before => 1); -- Directed insert front to empty declare S : constant Result := Check (C, (1 => 'a')); begin Assert (S.Status, S.Description); end; C.Insert ('b', Before => 1); -- Directed insert front to non-empty declare S : constant Result := Check (C, ('b', 'a')); begin Assert (S.Status, S.Description); end; C.Insert ('c', Before => 2); -- Directed insert middle to non-empty declare S : constant Result := Check (C, ('b', 'c', 'a')); begin Assert (S.Status, S.Description); end; end Insert; procedure Append is C : Collection; begin C.Append ('a'); -- Append last to empty declare S : constant Result := Check (C, (1 => 'a')); begin Assert (S.Status, S.Description); end; C.Append ('b'); -- Append last to non-empty declare S : constant Result := Check (C, ('a', 'b')); begin Assert (S.Status, S.Description); end; C.Clear; C.Append ('a', After => 1); -- Directed append last to empty declare S : constant Result := Check (C, (1 => 'a')); begin Assert (S.Status, S.Description); end; C.Append ('b', After => 1); -- Directed append last to non-empty declare S : constant Result := Check (C, ('a', 'b')); begin Assert (S.Status, S.Description); end; C.Append ('c', After => 1); -- Directed append middle to non-empty declare S : constant Result := Check (C, ('a', 'c', 'b')); begin Assert (S.Status, S.Description); end; end Append; procedure Remove is C : Collection; begin C.Append ('a'); C.Append ('b'); C.Append ('c'); C.Append ('d'); C.Remove (2); -- Remove from middle declare S : constant Result := Check (C, ('a', 'c', 'd')); begin Assert (S.Status, S.Description); end; C.Remove (1); -- Remove from front declare S : constant Result := Check (C, ('c', 'd')); begin Assert (S.Status, S.Description); end; C.Remove (2); -- Remove from back declare S : constant Result := Check (C, (1 => 'c')); begin Assert (S.Status, S.Description); end; C.Remove (1); -- Remove last Assert (C.Is_Empty, "Not empty after removing last item"); end Remove; procedure Location is C : Collection; begin Assert (C.Location ('a') = Collection_Pack.No_Index, "Found in empty"); C.Append ('a'); -- a Assert (C.Location ('a') = 1, "Did not find location for size 1"); C.Append ('b'); -- ab Assert (C.Location ('b') = 2, "Did not find location for last"); C.Append ('c'); -- abc Assert (C.Location ('b') = 2, "Did not find location for middle"); C.Append ('c'); -- abcc Assert (C.Location ('c') = 3, "Did not find location for first duplicate"); end Location; procedure Replace is C : Collection; begin C.Append ('a'); C.Replace (1, 'b'); declare S : constant Result := Check (C, (1 => 'b')); begin Assert (S.Status, S.Description); end; C.Append ('c'); C.Replace (1, 'd'); declare S : constant Result := Check (C, ('d', 'c')); begin Assert (S.Status, S.Description); end; C.Replace (2, 'e'); declare S : constant Result := Check (C, ('d', 'e')); begin Assert (S.Status, S.Description); end; C.Append ('f'); C.Replace (2, 'g'); declare S : constant Result := Check (C, ('d', 'g', 'f')); begin Assert (S.Status, S.Description); end; end Replace; procedure Insert_Sorted is use type Sorted.T; C : Sorted.Collection; begin C.Insert (('a', 1)); -- a1 C.Insert (('c', 1)); -- a1c1 C.Insert (('b', 1)); -- a1b1c1 C.Insert (('b', 2)); -- a1b2b1c1 Assert (C.Item_At (1) = ('a', 1), ""); Assert (C.Item_At (2) = ('b', 2), ""); Assert (C.Item_At (3) = ('b', 1), ""); Assert (C.Item_At (4) = ('c', 1), ""); C.Clear; C.Insert (('a', 1)); -- a1 C.Insert (('c', 1), Before => 1); -- a1c1 C.Insert (('c', 2), Before => 2); -- a1c2c1 C.Insert (('c', 3), Before => 3); -- a1c2c3c1 Assert (C.Item_At (1) = ('a', 1), ""); Assert (C.Item_At (2) = ('c', 2), ""); Assert (C.Item_At (3) = ('c', 3), ""); Assert (C.Item_At (4) = ('c', 1), ""); end Insert_Sorted; procedure Append_Sorted is use type Sorted.T; C : Sorted.Collection; begin C.Append (('b', 1)); -- b1 C.Append (('a', 1)); -- a1b1 C.Append (('a', 2)); -- a1a2b1 C.Append (('a', 3)); -- a1a2a3b1 Assert (C.Item_At (1) = ('a', 1), ""); Assert (C.Item_At (2) = ('a', 2), ""); Assert (C.Item_At (3) = ('a', 3), ""); Assert (C.Item_At (4) = ('b', 1), ""); C.Clear; C.Append (('b', 1)); -- b1 C.Append (('a', 1), After => 1); -- a1b1 C.Append (('a', 2), After => 2); -- a1a2b1 C.Append (('a', 3), After => 1); -- a1a3a2b1 Assert (C.Item_At (1) = ('a', 1), ""); Assert (C.Item_At (2) = ('a', 3), ""); Assert (C.Item_At (3) = ('a', 2), ""); Assert (C.Item_At (4) = ('b', 1), ""); end Append_Sorted; procedure Replace_Sorted is use type Sorted.T; C : Sorted.Collection; begin C.Append (('b', 1)); C.Append (('c', 1)); C.Append (('c', 2)); C.Append (('c', 3)); C.Append (('d', 1)); -- b1 c1 c2 c3 d1 C.Replace (3, ('b', 0)); -- b1 b0 c1 c3 d1 Assert (C.Item_At (1) = ('b', 1), ""); Assert (C.Item_At (2) = ('b', 0), ""); Assert (C.Item_At (3) = ('c', 1), ""); Assert (C.Item_At (4) = ('c', 3), ""); Assert (C.Item_At (5) = ('d', 1), ""); C.Replace (3, ('d', 0)); -- b1 b0 c3 d0 d1 Assert (C.Item_At (1) = ('b', 1), ""); Assert (C.Item_At (2) = ('b', 0), ""); Assert (C.Item_At (3) = ('c', 3), ""); Assert (C.Item_At (4) = ('d', 0), ""); Assert (C.Item_At (5) = ('d', 1), ""); C.Replace (3, ('c', 0)); -- b1 b0 c0 d0 d1 Assert (C.Item_At (1) = ('b', 1), ""); Assert (C.Item_At (2) = ('b', 0), ""); Assert (C.Item_At (3) = ('c', 0), ""); Assert (C.Item_At (4) = ('d', 0), ""); Assert (C.Item_At (5) = ('d', 1), ""); end Replace_Sorted; procedure First_Empty is C : Collection; Tmp : Item_Type; pragma Unreferenced (Tmp); begin C.Clear; Tmp := C.First; end First_Empty; procedure Last_Empty is C : Collection; Tmp : Item_Type; pragma Unreferenced (Tmp); begin C.Clear; Tmp := C.Last; end Last_Empty; procedure Item_At_Empty is C : Collection; Tmp : Item_Type; pragma Unreferenced (Tmp); begin C.Clear; Tmp := C.Item_At (1); end Item_At_Empty; procedure Remove_Empty is C : Collection; begin C.Clear; C.Remove (1); end Remove_Empty; procedure Replace_Empty is C : Collection; begin C.Clear; C.Replace (1, 'x'); end Replace_Empty; procedure Fill (C : in out Collection) is begin while not C.Is_Full loop C.Append ('X'); end loop; end Fill; procedure Insert_Full is C : Collection; begin Fill (C); C.Insert ('X'); end Insert_Full; procedure Insert_Before_Full is C : Collection; begin Fill (C); C.Insert ('X', Before => 1); end Insert_Before_Full; procedure Append_Full is C : Collection; begin Fill (C); C.Append ('X'); end Append_Full; procedure Append_After_Full is C : Collection; begin Fill (C); C.Append ('X', After => 1); end Append_After_Full; procedure Preconditions is begin Assert_Exception (First_Empty'Access, "Expected an exception when accessing first item for empty"); Assert_Exception (Last_Empty'Access, "Expected an exception when accessing last item for empty"); Assert_Exception (Item_At_Empty'Access, "Expected an exception when accessing item for empty"); Assert_Exception (Remove_Empty'Access, "Expected an exception when removing item for empty"); Assert_Exception (Replace_Empty'Access, "Expected an exception when replacing item for empty"); Assert_Exception (Insert_Full'Access, "Expected an exception when inserting item to full"); Assert_Exception (Insert_Before_Full'Access, "Expected an exception when inserting item to full"); Assert_Exception (Append_Full'Access, "Expected an exception when appending item to full"); Assert_Exception (Append_After_Full'Access, "Expected an exception when appending item to full"); end Preconditions; procedure Run_Test (T : in out Test) is pragma Unreferenced (T); begin Init_Test; Fill_And_Empty; Insert; Append; Remove; Location; Replace; Preconditions; Insert_Sorted; Append_Sorted; Replace_Sorted; end Run_Test; end Generic_Collection_Test;
30,116
ada
0
jfouquart/synth
src/replicant-platform.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Replicant.Platform is -- returns platform-specific df command function df_command return String; -- platform-specific version of file command function file_type_command return String; -- Calculate both types of package ABI as a function of platform function determine_package_architecture return package_abi; -- Return platform-specific command for swapinfo function swapinfo_command return String; -- Return load averages (platform specific) function get_instant_load return Float; function get_5_minute_load return Float; -- Return value of ncpu (from syctl query) function get_number_cpus return Positive; -- Return true if file is executable (platform-specific) function file_is_executable (filename : String) return Boolean; -- Return true if file is dynamically linked (platform-specific) function dynamically_linked (base, filename : String) return Boolean; -- In order to do scanning in a clean environment prior to the true build -- Returns True on success function standalone_pkg8_install (id : builders) return Boolean; -- Required for building first pkg(8) and bmake(8) for pkgsrc -- They are just copies of hosts versions function host_pkgsrc_mk_install (id : builders) return Boolean; function host_pkgsrc_bmake_install (id : builders) return Boolean; function host_pkgsrc_digest_install (id : builders) return Boolean; function host_pkgsrc_pkg8_install (id : builders) return Boolean; -- Cache variables that spawn to get populated to extended make.conf procedure cache_port_variables (path_to_mm : String); -- Shell for interactive use function interactive_shell return String; private function isolate_arch_from_file_type (fileinfo : String) return filearch; -- Derived from /usr/bin/file -b <slave>/bin/sh function get_arch_from_bourne_shell return String; -- Get OSVERSION from <sys/param.h> function get_osversion_from_param_header return String; -- common logic for instant and 5-minute load average function load_core (instant_load : Boolean) return Float; -- equivalent to chmod 755 <fullpath> procedure set_file_as_executable (fullpath : String); end Replicant.Platform;
30,117
ada
0
fintatarta/pulsada
src/pulsada.ads
<filename>src/pulsada.ads with ada.Finalization; use ada; package Pulsada is type Sampling_Frequency is range 0 .. 1_000_000; type Sample_Type is mod 2 ** 16 with Size => 16; Max_Channel : constant := 32; type Channel_Index is range 1 .. Max_Channel; type Frame is array (Channel_Index range <>) of Sample_Type; type Frame_Block (<>) is new Finalization.Limited_Controlled with private; type Frame_Counter is new Positive; function New_Block (N_Channels : Channel_Index; N_Frames : Frame_Counter) return Frame_Block; function N_Frames (Item : Frame_Block) return Frame_Counter; function Get (Block : Frame_Block; N : Frame_Counter) return Frame; private type Block_Buffer is array (Positive range <>) of Sample_Type; type Block_Buffer_Access is access Block_Buffer; type Frame_Block is new Finalization.Limited_Controlled with record Data : Block_Buffer_Access; N_Frames : Frame_Counter; N_Channels : Channel_Index; end record; overriding procedure Finalize (Object : in out Frame_Block); function N_Frames (Item : Frame_Block) return Frame_Counter is (Item.N_Frames); end Pulsada;
30,118
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/discr5.adb
<filename>gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/discr5.adb -- { dg-do compile } procedure Discr5 is type Enum is (Ten, Twenty); for Enum use (10, 20); type Arr is array (Enum range <>) of Integer; type Rec (Discr: Enum := Ten) is record case Discr is when others => A: Arr (Ten .. Discr); end case; end record; begin null; end;
30,119
ada
80
enfoTek/tomato.linksys.e2000.nvram-mod
tools-src/gnu/gcc/gcc/ada/exp_pakd.ads
<gh_stars>10-100 ------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ P A K D -- -- -- -- S p e c -- -- -- -- $Revision$ -- -- -- Copyright (C) 1992-2001 Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, -- -- MA 02111-1307, USA. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ -- Expand routines for manipulation of packed arrays with Types; use Types; package Exp_Pakd is ------------------------------------- -- Implementation of Packed Arrays -- ------------------------------------- -- When a packed array (sub)type is frozen, we create a corresponding -- type that will be used to hold the bits of the packed value, and -- store the entity for this type in the Packed_Array_Type field of the -- E_Array_Type or E_Array_Subtype entity for the packed array. -- This packed array type has the name xxxPn, where xxx is the name -- of the packed type, and n is the component size. The expanded -- declaration declares a type that is one of the following: -- For an unconstrained array with component size 1,2,4 or any other -- odd component size. These are the cases in which we do not need -- to align the underlying array. -- type xxxPn is new Packed_Bytes1; -- For an unconstrained array with component size that is divisible -- by 2, but not divisible by 4 (other than 2 itself). These are the -- cases in which we can generate better code if the underlying array -- is 2-byte aligned (see System.Pack_14 in file s-pack14 for example). -- type xxxPn is new Packed_Bytes2; -- For an unconstrained array with component size that is divisible -- by 4, other than powers of 2 (which either come under the 1,2,4 -- exception above, or are not packed at all). These are cases where -- we can generate better code if the underlying array is 4-byte -- aligned (see System.Pack_20 in file s-pack20 for example). -- type xxxPn is new Packed_Bytes4; -- For a constrained array with a static index type where the number -- of bits does not exceed the size of Unsigned: -- type xxxPn is new Unsigned range 0 .. 2 ** nbits - 1; -- For a constrained array with a static index type where the number -- of bits is greater than the size of Unsigned, but does not exceed -- the size of Long_Long_Unsigned: -- type xxxPn is new Long_Long_Unsigned range 0 .. 2 ** nbits - 1; -- For all other constrained arrays, we use one of -- type xxxPn is new Packed_Bytes1 (0 .. m); -- type xxxPn is new Packed_Bytes2 (0 .. m); -- type xxxPn is new Packed_Bytes4 (0 .. m); -- where m is calculated (from the length of the original packed array) -- to hold the required number of bits, and the choice of the particular -- Packed_Bytes{1,2,4} type is made on the basis of alignment needs as -- described above for the unconstrained case. -- When a variable of packed array type is allocated, gigi will allocate -- the amount of space indicated by the corresponding packed array type. -- However, we do NOT attempt to rewrite the types of any references or -- to retype the variable itself, since this would cause all kinds of -- semantic problems in the front end (remember that expansion proceeds -- at the same time as analysis). -- For an indexed reference to a packed array, we simply convert the -- reference to the appropriate equivalent reference to the object -- of the packed array type (using unchecked conversion). -- In some cases (for internally generated types, and for the subtypes -- for record fields that depend on a discriminant), the corresponding -- packed type cannot be easily generated in advance. In these cases, -- we generate the required subtype on the fly at the reference point. -- For the modular case, any unused bits are initialized to zero, and -- all operations maintain these bits as zero (where necessary all -- unchecked conversions from corresponding array values require -- these bits to be clear, which is done automatically by gigi). -- For the array cases, there can be unused bits in the last byte, and -- these are neither initialized, nor treated specially in operations -- (i.e. it is allowable for these bits to be clobbered, e.g. by not). --------------------------- -- Endian Considerations -- --------------------------- -- The standard does not specify the way in which bits are numbered in -- a packed array. There are two reasonable rules for deciding this: -- Store the first bit at right end (low order) word. This means -- that the scaled subscript can be used directly as a right shift -- count (if we put bit 0 at the left end, then we need an extra -- subtract to compute the shift count. -- Layout the bits so that if the packed boolean array is overlaid on -- a record, using unchecked conversion, then bit 0 of the array is -- the same as the bit numbered bit 0 in a record representation -- clause applying to the record. For example: -- type Rec is record -- C : Bits4; -- D : Bits7; -- E : Bits5; -- end record; -- for Rec use record -- C at 0 range 0 .. 3; -- D at 0 range 4 .. 10; -- E at 0 range 11 .. 15; -- end record; -- type P16 is array (0 .. 15) of Boolean; -- pragma Pack (P16); -- Now if we use unchecked conversion to convert a value of the record -- type to the packed array type, according to this second criterion, -- we would expect field D to occupy bits 4..10 of the Boolean array. -- Although not required, this correspondence seems a highly desirable -- property, and is one that GNAT decides to guarantee. For a little -- endian machine, we can also meet the first requirement, but for a -- big endian machine, it will be necessary to store the first bit of -- a Boolean array in the left end (most significant) bit of the word. -- This may cost an extra instruction on some machines, but we consider -- that a worthwhile price to pay for the consistency. -- One more important point arises in the case where we have a constrained -- subtype of an unconstrained array. Take the case of 20-bits. For the -- unconstrained representation, we would use an array of bytes: -- Little-endian case -- 8-7-6-5-4-3-2-1 16-15-14-13-12-11-10-9 x-x-x-x-20-19-18-17 -- Big-endian case -- 1-2-3-4-5-6-7-8 9-10-11-12-13-14-15-16 17-18-19-20-x-x-x-x -- For the constrained case, we use a 20-bit modular value, but in -- general this value may well be stored in 32 bits. Let's look at -- what it looks like: -- Little-endian case -- x-x-x-x-x-x-x-x-x-x-x-x-20-19-18-17-...-10-9-8-7-6-5-4-3-2-1 -- which stored in memory looks like -- 8-7-...-2-1 16-15-...-10-9 x-x-x-x-20-19-18-17 x-x-x-x-x-x-x -- An important rule is that the constrained and unconstrained cases -- must have the same bit representation in memory, since we will often -- convert from one to the other (e.g. when calling a procedure whose -- formal is unconstrained). As we see, that criterion is met for the -- little-endian case above. Now let's look at the big-endian case: -- Big-endian case -- x-x-x-x-x-x-x-x-x-x-x-x-1-2-3-4-5-6-7-8-9-10-...-17-18-19-20 -- which stored in memory looks like -- x-x-x-x-x-x-x-x x-x-x-x-1-2-3-4 5-6-...11-12 13-14-...-19-20 -- That won't do, the representation value in memory is NOT the same in -- the constrained and unconstrained case. The solution is to store the -- modular value left-justified: -- 1-2-3-4-5-6-7-8-9-10-...-17-18-19-20-x-x-x-x-x-x-x-x-x-x-x -- which stored in memory looks like -- 1-2-...-7-8 9-10-...15-16 17-18-19-20-x-x-x-x x-x-x-x-x-x-x-x -- and now, we do indeed have the same representation. The special flag -- Is_Left_Justified_Modular is set in the modular type used as the -- packed array type in the big-endian case to ensure that this required -- left justification occurs. ----------------- -- Subprograms -- ----------------- procedure Create_Packed_Array_Type (Typ : Entity_Id); -- Typ is a array type or subtype to which pragma Pack applies. If the -- Packed_Array_Type field of Typ is already set, then the call has no -- effect, otherwise a suitable type or subtype is created and stored -- in the Packed_Array_Type field of Typ. This created type is an Itype -- so that Gigi will simply elaborate and freeze the type on first use -- (which is typically the definition of the corresponding array type). -- -- Note: although this routine is included in the expander package for -- packed types, it is actually called unconditionally from Freeze, -- whether or not expansion (and code generation) is enabled. We do this -- since we want gigi to be able to properly compute type charactersitics -- (for the Data Decomposition Annex of ASIS, and possible other future -- uses) even if code generation is not active. Strictly this means that -- this procedure is not part of the expander, but it seems appropriate -- to keep it together with the other expansion routines that have to do -- with packed array types. procedure Expand_Packed_Boolean_Operator (N : Node_Id); -- N is an N_Op_And, N_Op_Or or N_Op_Xor node whose operand type is a -- packed boolean array. This routine expands the appropriate operations -- to carry out the logical operation on the packed arrays. It handles -- both the modular and array representation cases. procedure Expand_Packed_Element_Reference (N : Node_Id); -- N is an N_Indexed_Component node whose prefix is a packed array. In -- the bit packed case, this routine can only be used for the expression -- evaluation case not the assignment case, since the result is not a -- variable. See Expand_Bit_Packed_Element_Set for how he assignment case -- is handled in the bit packed case. For the enumeration case, the result -- of this call is always a variable, so the call can be used for both the -- expression evaluation and assignment cases. procedure Expand_Bit_Packed_Element_Set (N : Node_Id); -- N is an N_Assignment_Statement node whose name is an indexed -- component of a bit-packed array. This procedure rewrites the entire -- assignment statement with appropriate code to set the referenced -- bits of the packed array type object. Note that this procedure is -- used only for the bit-packed case, not for the enumeration case. procedure Expand_Packed_Eq (N : Node_Id); -- N is an N_Op_Eq node where the operands are packed arrays whose -- representation is an array-of-bytes type (the case where a modular -- type is used for the representation does not require any special -- handling, because in the modular case, unused bits are zeroes. procedure Expand_Packed_Not (N : Node_Id); -- N is an N_Op_Not node where the operand is packed array of Boolean -- in standard representation (i.e. component size is one bit). This -- procedure expands the corresponding not operation. Note that the -- non-standard representation case is handled by using a loop through -- elements generated by the normal non-packed circuitry. function Involves_Packed_Array_Reference (N : Node_Id) return Boolean; -- N is the node for a name. This function returns true if the name -- involves a packed array reference. A node involves a packed array -- reference if it is itself an indexed compoment referring to a bit- -- packed array, or it is a selected component whose prefix involves -- a packed array reference. procedure Expand_Packed_Address_Reference (N : Node_Id); -- The node N is an attribute reference for the 'Address reference, where -- the prefix involves a packed array reference. This routine expands the -- necessary code for performing the address reference in this case. end Exp_Pakd;
30,120
ada
30
jscparker/math_packages
polynomial/clenshaw/clenshaw.adb
<gh_stars>10-100 ----------------------------------------------------------------------- -- package body Clenshaw. Generates functions from recurrance relations. -- Copyright (C) 2018 <NAME> -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. --------------------------------------------------------------------------- package body Clenshaw is Zero : constant Real := +0.0; ----------------- -- Evaluate_Qs -- ----------------- -- The recurrance relation for the Q's at X is easily written as matrix -- equation. In the following, f(X) is the given function for Q_0: -- -- Q(0) = Q_0(p,X); -- Q(1) = 0 + Alpha_1*Q_0; -- Q(2) = 0 + Alpha_2*Q_1 + Beta_2*Q_0; -- Q(3) = 0 + Alpha_3*Q_2 + Beta_3*Q_1; -- ... -- Q(N) = 0 + Alpha_N*Q_N-1 + Beta_N*Q_N-2 -- -- In matrix form, M*Q = (f(X), 0, 0, ...) , this becomes: -- -- | 1 0 0 0 | |Q(0)| | Q_0(p,X)| | C_0 | -- | E_1 1 0 0 | |Q(1)| = | 0 | = | C_1 | -- | B_2 E_2 1 0 | |Q(2)| | 0 | | C_2 | -- | 0 B_3 E_3 1 | |Q(3)| | 0 | | C_3 | -- -- where E_m = -Alpha_m, B_m = -Beta_m. -- -- So Q = M_inverse * C is the desired solution, but there may be numerical -- error in the calculation of M_inverse by back-substitution. The -- solution vector Q can be improved numerically by iterative refinement -- via Newton's method: -- -- Q_new = Q_old + M_inverse * (C - M*Q_old) -- -- where Q = M_inverse * C is the calculation of Q given at the top. -- procedure Evaluate_Qs (X : in Real; Q : in out Poly_Values; Max_Poly_ID : in Poly_ID_Type; P : in Real := 0.0; No_Of_Iterations : in Positive := 1) is Product, Del : Poly_Values; m : Poly_ID_Type; begin -- -- Step 0. Initialize excess values of Q to Zero. -- if Max_Poly_ID < Poly_ID_Type'Last then for m in Max_Poly_ID+1 .. Poly_ID_Type'Last loop Q(m) := Zero; end loop; end if; -- -- Step 0. Want zeroth order poly Q_0(p,X). No work to do. -- if Max_Poly_ID = Poly_ID_Type'First then m := Poly_ID_Type'First; Q(m) := Q_0(p,X); end if; -- -- Step 0b. Poly is 1st order. Almost no work to do. -- Don't do any iteration. -- if Max_Poly_ID = Poly_ID_Type'First + 1 then m := Poly_ID_Type'First; Q(m) := Q_0(p,X); m := Poly_ID_Type'First+1; Q(m) := Alpha(m,p,X) * Q(m-1); end if; -- -- Step 1. We now know that Max_Poly_ID > 1. -- Start by getting starting value of Q by solving M*Q = f. -- Use recurrence relation to get Q at X. -- Start with special formulas for the 1st two Q's: -- if Max_Poly_ID > Poly_ID_Type'First + 1 then m := Poly_ID_Type'First; Q(m) := Q_0(p,X); m := Poly_ID_Type'First+1; Q(m) := Alpha(m,p,X) * Q(m-1); for m in Poly_ID_Type'First+2..Max_Poly_ID loop Q(m) := Alpha(m,p,X) * Q(m-1) + Beta(m,p,X) * Q(m-2); end loop; -- -- Step 2. Improve Q numerically through Newton iteration. -- Q_new = Q_old + M_inverse * (C - M*Q_old) -- Iterate: for Iter in 2..No_Of_Iterations loop -- Get Product = M*Q_old: m := Poly_ID_Type'First; Product(m) := Q(m); m := Poly_ID_Type'First+1; Product(m) := Q(m) - Alpha(m,p,X)*Q(m-1); for m in Poly_ID_Type'First+2..Max_Poly_ID loop Product(m) := Q(m) - Alpha(m,p,X)*Q(m-1) - Beta(m,p,X)*Q(m-2); end loop; -- Get Residual = (Q_0(p,X), 0, ... , 0) - M*D_old. Reuse the -- array Product to hold the value of Residual: Product(Poly_ID_Type'First) := Zero; -- Residual is always exactly 0.0 here for m in Poly_ID_Type'First+1 .. Max_Poly_ID loop Product(m) := - Product(m); end loop; -- Get Del = M_inverse * (C - M*Q_old) = M_inverse * Product: m := Max_Poly_ID; Del(m) := Product(m); m := Max_Poly_ID - 1; Del(m) := Product(m) + Alpha(m,p,X)*Del(m-1); for m in Poly_ID_Type'First+2 .. Max_Poly_ID loop Del(m) := Product(m) + Alpha(m,p,X)*Del(m-1) + Beta(m,p,X)*Del(m-2); end loop; -- Get Q_new = Q_old + Del; for m in Poly_ID_Type'First..Max_Poly_ID loop Q(m) := Q(m) + Del(m); end loop; end loop Iterate; end if; end Evaluate_Qs; ------------- -- M_times -- ------------- -- M is Upper-Triangular. -- The elements of M are 1 down the diagonal, and -Alpha(m,p,X) and -- -Beta(m,p,X) down the the off-diagonals. -- function M_times (D : in Coefficients; X : in Real; P : in Real; Sum_Limit : in Poly_ID_Type) return Coefficients is Product : Coefficients; m : Poly_ID_Type; begin -- These inits are amazingly slow! for m in Sum_Limit .. Poly_ID_Type'Last loop Product(m) := Zero; end loop; -- Get Product = M*D: m := Sum_Limit; Product(m) := D(m); if Sum_Limit > Poly_ID_Type'First then m := Sum_Limit - 1; Product(m) := D(m) - Alpha(m+1,p,X)*D(m+1); end if; if Sum_Limit > Poly_ID_Type'First+1 then for m in Poly_ID_Type'First .. Sum_Limit-2 loop Product(m) := D(m) - Alpha(m+1,p,X)*D(m+1) - Beta(m+2,p,X)*D(m+2); end loop; end if; return Product; end M_times; pragma Inline (M_times); --------------------- -- M_inverse_times -- --------------------- -- M is Upper-Triangular so solution is by back-substitution. -- The elements of M are 1 down the diagonal, and -Alpha and -- -Beta down the off-diagonals. -- function M_inverse_times (C : in Coefficients; X : in Real; P : in Real; Sum_Limit : in Poly_ID_Type) return Coefficients is Result : Coefficients; m : Poly_ID_Type; begin -- These inits are amazingly slow! for m in Sum_Limit .. Poly_ID_Type'Last loop Result(m) := Zero; end loop; m := Sum_Limit; Result(m) := C(m); if Sum_Limit > Poly_ID_Type'First then m := Sum_Limit - 1; Result(m) := C(m) + Alpha(m+1,p,X) * Result(m+1); end if; if Sum_Limit > Poly_ID_Type'First+1 then for m in reverse Poly_ID_Type'First .. Sum_Limit-2 loop Result(m) := C(m) + Alpha(m+1,p,X) * Result(m+1) + Beta(m+2,p,X) * Result(m+2); end loop; end if; return Result; end M_inverse_times; pragma Inline (M_inverse_times); --------- -- Sum -- --------- -- This is easily written as matrix equation, with Sum = D(0): -- -- D_n = C_n; -- D_n-1 = C_n-1 + Alpha_n*D_n; -- D_n-2 = C_n-2 + Alpha_n-1*D_n-1 + Beta_n-2*D_n-2; -- ... -- D_1 = C_1 + Alpha_2*D_2 + Beta_3*D_3 -- D_0 = C_0 + Alpha_1*D_1 + Beta_2*D_2 -- -- In matrix form, M*D = C, this becomes: -- -- -- | 1 E_1 B_2 0 | |D(0) | | C(0) | -- | 0 1 E_2 B_3 | |D(1) | | C(1) | -- -- ... -- -- | 1 E_n-2 B_n-1 0 | |D(n-3)| = | C(n-3) | -- | 0 1 E_n-1 B_n | |D(n-2)| | C(n-2) | -- | 0 0 1 E_n | |D(n-1)| | C(n-1) | -- | 0 0 0 1 | |D(n) | | C(n) | -- -- where E_m = -Alpha_m, B_m = -Beta_m. -- -- Can attemp iterative refinement of D with Newton's -- method: -- D_new = D_old + M_inverse * (C - M*D_old) -- -- where D = M_inverse * C is the calculation of D given at the top. if the -- said calculation of D is numerically imperfect, then the iteration above -- will produce improved values of D. Of course, if the Coefficients of -- the polynomials C are numerically poor, then this effort may be wasted. -- function Sum (X : in Real; C : in Coefficients; Sum_Limit : in Poly_ID_Type; P : in Real := 0.0; No_Of_Iterations : in Positive := 1) return Real is Product, Del : Coefficients; -- initialized by M_inverse_times and M_times. D : Coefficients; -- initialized by M_inverse_times. Result : Real := Zero; begin -- -- Step 1. Getting starting value of D (D_old) by solving M*D = C. -- D := M_inverse_times (C, X, p, Sum_Limit); -- -- Step 2. Improve D numerically through Newton iteration. -- D_new = D_old + M_inverse * (C - M*D_old) -- Iterate: for k in 2..No_Of_Iterations loop -- Get Product = M*D_old: Product := M_times (D, X, p, Sum_Limit); -- Get Residual = C - M*D_old. Reuse the array Product -- to hold the value of Residual: for m in Poly_ID_Type'First..Sum_Limit loop Product(m) := C(m) - Product(m); end loop; -- Get Del = M_inverse * (A - M*D_old) = M_inverse * Product: Del := M_inverse_times (Product, X, p, Sum_Limit); -- Get D_new = D_old + Del; for m in Poly_ID_Type'First..Sum_Limit loop D(m) := D(m) + Del(m); end loop; end loop Iterate; Result := D(0) * Q_0 (p, X); return Result; end Sum; end Clenshaw;
30,121
ada
33
ytomino/drake
source/directories/machine-w64-mingw32/s-natcre.adb
with System.Zero_Terminated_WStrings; with C.winbase; with C.windef; with C.winnt; package body System.Native_Credentials is use type C.size_t; use type C.windef.WINBOOL; function User_Name return String is Result : aliased C.winnt.WCHAR_array (0 .. C.windef.MAX_PATH - 1); Length : aliased C.windef.DWORD := Result'Size; begin if C.winbase.GetUserName (Result (0)'Access, Length'Access) = C.windef.FALSE then raise Constraint_Error; -- ??? end if; return Zero_Terminated_WStrings.Value ( Result (0)'Access, C.size_t (Length) - 1); end User_Name; end System.Native_Credentials;
30,122
ada
12
TUM-EI-RCS/StratoX
tests/polymorphism/src/i2c_interface.ads
with HAL_Interface; use HAL_Interface; package I2C_Interface with SPARK_Mode --,Abstract_State => State is type I2C_Type is new Port_Type with record pin : Integer := 0; end record; overriding procedure configure(Port : I2C_Type; Config : Configuration_Type); overriding procedure write (Port : I2C_Type; Address : Address_Type; Data : Data_Type) ; --with Global => (In_Out => State); overriding function read (Port : I2C_Type; Address : Address_Type) return Data_Type; end I2C_Interface;
30,123
ada
0
Fabien-Chouteau/libriscv
examples/simulator/src/gdb_remote-agent.ads
<filename>examples/simulator/src/gdb_remote-agent.ads<gh_stars>0 package GDB_Remote.Agent is subtype Address is Unsigned_64; type Instance (Buffer_Size : Buffer_Lenght_Type := 256) is abstract tagged limited private; subtype Class is Instance'Class; type Ptr is access all Class; procedure Send_To_Host (This : in out Instance; C : Character) is abstract; type Event_Kind is (None, Got_Packet, Got_Ack, Got_Nack, Got_An_Interrupt); type Event (Kind : Event_Kind := None) is record case Kind is when Got_Packet => P : Packet; when None | Got_Ack | Got_Nack | Got_An_Interrupt => null; end case; end record; function Received (This : in out Instance; C : Character) return Event; function Next_Field (This : in out Instance) return String; function Next_Data (This : in out Instance; Success : out Boolean) return Unsigned_8; -- Return the next octet of the binary data in a packet procedure Ack (This : in out Instance); procedure Nack (This : in out Instance); procedure Send_Packet (This : in out Instance; Data : String); procedure Start_Packet (This : in out Instance); procedure Push_Data (This : in out Instance; Data : String); generic type T is mod <>; procedure Push_Mod (This : in out Instance; Data : T); procedure End_Packet (This : in out Instance); private type State_Kind is (Waiting_For_Ack, Waiting_For_Start, Receiving_Packet, Checksum); type Instance (Buffer_Size : Buffer_Lenght_Type := 256) is abstract tagged limited record Buffer : String (1 .. Buffer_Size); Char_Count : Natural := 0; Field_Cursor : Natural := 0; Checksum : Unsigned_8; Checksum_Str : String (1 .. 2); Checksum_Str_Count : Natural := 0; State : State_Kind := Waiting_For_Ack; Data_Fmt : Data_Format := Binary; Tx_Checksum : Unsigned_8; end record; function Checksum_OK (This : Instance) return Boolean; end GDB_Remote.Agent;
30,124
ada
1
annexi-strayline/ASAP-Unicode
unicode-utf8_stream_decoder-codec.ads
------------------------------------------------------------------------------ -- -- -- Unicode Utilities -- -- UTF-8 Stream Decoder -- -- -- -- ------------------------------------------------------------------------ -- -- -- -- Copyright (C) 2019, ANNEXI-STRAYLINE Trans-Human Ltd. -- -- All rights reserved. -- -- -- -- Original Contributors: -- -- * <NAME> (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. -- -- -- ------------------------------------------------------------------------------ -- Formally verified codec private package Unicode.UTF8_Stream_Decoder.Codec with Pure, SPARK_Mode => On is pragma Assertion_Policy (Ignore); pragma Assert (Stream_Element'Modulus = 2**8); -- Re-assertion for the encompasing package, to help the SPARK tools subtype Sequence_Index is Stream_Element_Offset range 1 .. 4; type Sequence_Array is array (Sequence_Index range <>) of Stream_Element; -- A restricted analogue to Stream_Element_Array which is digestible by the -- SPARK tools - used internally for the various sequence validation/ -- processing steps. type Decode_Status is (Success, Short_Load, -- Additional bytes required Bad_Sequence, -- 1. First octet was illegal (RFS3629) -- 2. First octet was invalid (encoded more than 3 -- continuation bytes -- 3. Expected continuation bytes were invalid -- (not in 2#10_000000# .. 2#10_111111) -- not properly marked as continuation bytes Overlong, -- An illegal overlong condition was found. Codepoint_Excursion); -- The encoded sequence is not a legal Unicode -- codepoint procedure Try_Decode (Sequence : in Sequence_Array; Last : out Sequence_Index; Continuation_Bytes: out Stream_Element_Count; Result : out Wide_Wide_Character; Status : out Decode_Status) with Inline => True, -- For performance, and since this package is not -- embedded in the parent package because it SPARK_Mode -- can only be applied to library-level packages Global => null, Post => ((Continuation_Bytes in 0 .. 3) and then (if Status = Success then Last = Sequence'First + Continuation_Bytes and then (for all Octet of Sequence(Sequence'First .. Last) => Octet not in 16#C0# | 16#C1# | 16#F5# .. 16#FF#) -- STD63/RFC3629 Section 1 - Prohibited octets -- in any UTF-8 text and then (case Continuation_Bytes is when 0 => Wide_Wide_Character'Pos (Result) in 16#000000# .. 16#00007F#, when 1 => Wide_Wide_Character'Pos (Result) in 16#000080# .. 16#0007FF#, when 2 => Wide_Wide_Character'Pos (Result) in 16#000800# .. 16#00D7FF# | 16#00E000# .. 16#00FDCF# | 16#00FDF0# .. 16#00FFFD#, -- IETF STD63/RFC3629 Section 3: -- UTF-16 "surrogate pairs" -- (U+D800 .. U+DFFF) are prohibited -- -- Unicode Corrigendum #9 - Noncharacter -- codepoints: -- U+FDD0 .. U+FDEF -- U+nFFFE + U+nFFFF when 3 => Wide_Wide_Character'Pos (Result) in 16#010000# .. 16#01FFFD# | 16#020000# .. 16#02FFFD# | 16#030000# .. 16#03FFFD# | 16#040000# .. 16#04FFFD# | 16#050000# .. 16#05FFFD# | 16#060000# .. 16#06FFFD# | 16#070000# .. 16#07FFFD# | 16#080000# .. 16#08FFFD# | 16#090000# .. 16#09FFFD# | 16#0A0000# .. 16#0AFFFD# | 16#0B0000# .. 16#0BFFFD# | 16#0C0000# .. 16#0CFFFD# | 16#0D0000# .. 16#0DFFFD# | 16#0E0000# .. 16#0EFFFD# | 16#0F0000# .. 16#0FFFFD# | 16#100000# .. 16#10FFFD#, -- U+10000 .. U+10FFFF except for: -- Unicode Corrigendum #9 - Noncharacter -- codepoints: -- U+nFFFE + U+nFFFF when others => -- There are no others False) elsif Status = Short_Load then Sequence'Length = 0 or else Continuation_Bytes in 1 .. 3 else Result = Unicode_Replacement_Character and then (if Sequence'Length > 0 then Last in Sequence'Range else Last = Sequence_Index'First))); -- Used by the non-spark portions to implement -- a very efficient two-step process -- Try_Decode attempts to decode a Character, and indicates the reson for -- failure if not successful. Indented to be called from full Ada, this -- procedure carries the full contract of a correct decoding result in the -- postcondtion which has been fully verified. -- -- Try_Decode is invoked by the Decode_Next subprograms in the parent -- package end Unicode.UTF8_Stream_Decoder.Codec;
30,125
ada
1
ForYouEyesOnly/Space-Convoy
Sources/Globe_3d/gl/gl-buffer-indices.ads
with GL.Buffer.general; pragma Elaborate_All (GL.Buffer.general); with GL.Geometry; package GL.Buffer.indices is new GL.Buffer.general (base_object => GL.Buffer.element_array_Object, index => GL.positive_uInt, element => GL.geometry.vertex_Id, element_array => GL.geometry.vertex_Id_Array);
30,126
ada
2
reznikmm/webdriver
source/webdriver-remote-executors.adb
<gh_stars>1-10 -- Copyright (c) 2017 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with AWS.Response; with League.JSON.Documents; separate (WebDriver.Remote) package body Executors is ------------- -- Execute -- ------------- not overriding function Execute (Self : access HTTP_Command_Executor; Command : Remote.Command) return Response is Reply : AWS.Response.Data; JSON : League.JSON.Documents.JSON_Document; begin case Command.Method is when Get => AWS.Client.Get (Self.Server, URI => Command.Path.To_UTF_8_String, Result => Reply); when Post => declare Text : constant League.Strings.Universal_String := Command.Parameters.To_JSON_Document.To_JSON; begin AWS.Client.Post (Self.Server, URI => Command.Path.To_UTF_8_String, Data => Text.To_UTF_8_String, Content_Type => "application/json; charset=utf-8", Result => Reply); end; end case; JSON := League.JSON.Documents.From_JSON (AWS.Response.Message_Body (Reply)); return (Session_Id => League.Strings.Empty_Universal_String, -- FIXME State => League.Strings.Empty_Universal_String, -- FIXME Status => 0, -- FIXME Value => JSON.To_JSON_Object); end Execute; end Executors;
30,127
ada
4
Alex-Gamper/Ada-Grammar
Win32.ads
<gh_stars>1-10 -------------------------------------------------------------------------------- -- -- -- Copyright (c) 2018 <NAME>, All Rights Reserved. -- -- -- -- This program is free software: you can redistribute it and/or modify -- -- it under the terms of the GNU General Public License as published by -- -- the Free Software Foundation, either version 3 of the License, or -- -- (at your option) any later version. -- -- -- -- This program is distributed in the hope that it will be useful, -- -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- -- GNU General Public License for more details. -- -- -- -- You should have received a copy of the GNU General Public License -- -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- -- -------------------------------------------------------------------------------- with Interfaces.C; use Interfaces.C; with System; use System; -------------------------------------------------------------------------------- package Win32 is -- Character Types type CHAR is new Interfaces.C.char; type LPSTR is access all CHAR; type LPCSTR is access constant CHAR; -- Integer Types type INT is new Interfaces.C.int; type BOOL is new INT; -- Unsigned Integer Types type DWORD is new Interfaces.C.unsigned_long; type LPDWORD is access all DWORD; -- Handle Types type HANDLE_Type is null record; type HANDLE is access HANDLE_Type; subtype HINSTANCE is HANDLE; subtype HMODULE is HANDLE; type LPVOID is new System.Address; type SECURITY_ATTRIBUTES is record nLength : DWORD; lpSecurityDescriptor : LPVOID; bInheritHandle : BOOL; end record; type LPSECURITY_ATTRIBUTES is access all SECURITY_ATTRIBUTES; -- Conversion Functions function Addr (S : String) return LPSTR; function Addr (S : String) return LPCSTR; -- Imports function GetModuleFileName(h_Module : HMODULE; lpFilename : LPSTR; nSize : DWORD ) return DWORD; procedure OutputDebugString(OutputString : LPSTR); function CreateEvent (lpEventAttributes : LPSECURITY_ATTRIBUTES; bManualReset : BOOL; bInitialState : BOOL; lpName : LPCSTR) return HANDLE; function SetEvent (hEvent : HANDLE) return BOOL; function WaitForSingleObject (hHandle : HANDLE; dwMilliseconds : DWORD) return DWORD; function CloseHandle (hObject : HANDLE) return BOOL; pragma Import (Stdcall , GetModuleFileName , "GetModuleFileNameA"); pragma import (stdcall , OutputDebugString , "OutputDebugStringA"); pragma import (stdcall , CreateEvent , "CreateEventA"); pragma import (stdcall , SetEvent , "SetEvent"); pragma import (stdcall , CloseHandle , "CloseHandle"); pragma import (stdcall , WaitForSingleObject , "WaitForSingleObject"); end Win32;
30,128
ada
0
Letractively/ada-security
src/security-permissions.adb
<filename>src/security-permissions.adb ----------------------------------------------------------------------- -- security-permissions -- Definition of permissions -- Copyright (C) 2010, 2011 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Containers.Indefinite_Hashed_Maps; with Ada.Strings.Hash; with Util.Log.Loggers; -- The <b>Security.Permissions</b> package defines the different permissions that can be -- checked by the access control manager. package body Security.Permissions is use Util.Log; -- ------------------------------ -- Permission Manager -- ------------------------------ -- The logger Log : constant Loggers.Logger := Loggers.Create ("Security.Permissions"); -- A global map to translate a string to a permission index. package Permission_Maps is new Ada.Containers.Indefinite_Hashed_Maps (Key_Type => String, Element_Type => Permission_Index, Hash => Ada.Strings.Hash, Equivalent_Keys => "=", "=" => "="); protected type Global_Index is -- Get the permission index function Get_Permission_Index (Name : in String) return Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index); private Map : Permission_Maps.Map; Next_Index : Permission_Index := Permission_Index'First; end Global_Index; protected body Global_Index is function Get_Permission_Index (Name : in String) return Permission_Index is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then return Permission_Maps.Element (Pos); else raise Invalid_Name with "There is no permission '" & Name & "'"; end if; end Get_Permission_Index; -- Get the last permission index registered in the global permission map. function Get_Last_Permission_Index return Permission_Index is begin return Next_Index; end Get_Last_Permission_Index; procedure Add_Permission (Name : in String; Index : out Permission_Index) is Pos : constant Permission_Maps.Cursor := Map.Find (Name); begin if Permission_Maps.Has_Element (Pos) then Index := Permission_Maps.Element (Pos); else Index := Next_Index; Log.Debug ("Creating permission index {1} for {0}", Name, Permission_Index'Image (Index)); Map.Insert (Name, Index); Next_Index := Next_Index + 1; end if; end Add_Permission; end Global_Index; Permission_Indexes : Global_Index; -- ------------------------------ -- Get the permission index associated with the name. -- ------------------------------ function Get_Permission_Index (Name : in String) return Permission_Index is begin return Permission_Indexes.Get_Permission_Index (Name); end Get_Permission_Index; -- ------------------------------ -- Get the last permission index registered in the global permission map. -- ------------------------------ function Get_Last_Permission_Index return Permission_Index is begin return Permission_Indexes.Get_Last_Permission_Index; end Get_Last_Permission_Index; -- ------------------------------ -- Add the permission name and allocate a unique permission index. -- ------------------------------ procedure Add_Permission (Name : in String; Index : out Permission_Index) is begin Permission_Indexes.Add_Permission (Name, Index); end Add_Permission; package body Definition is P : Permission_Index; function Permission return Permission_Index is begin return P; end Permission; begin Add_Permission (Name => Name, Index => P); end Definition; end Security.Permissions;
30,129
ada
19
jrcarter/Ada_GUI
ada_gui-gnoga-colors.ads
-- Ada_GUI implementation based on Gnoga. Adapted 2021 -- -- -- GNOGA - The GNU Omnificent GUI for Ada -- -- -- -- G N O G A . T Y P E S . C O L O R S -- -- -- -- S p e c -- -- -- -- -- -- Copyright (C) 2015 <NAME> -- -- -- -- This library is free software; you can redistribute it and/or modify -- -- it under terms of the GNU General Public License as published by the -- -- Free Software Foundation; either version 3, or (at your option) any -- -- later version. This library is distributed in the hope that it will be -- -- useful, but WITHOUT ANY WARRANTY; without even the implied warranty of -- -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are -- -- granted additional permissions described in the GCC Runtime Library -- -- Exception, version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- For more information please go to http://www.gnoga.com -- ------------------------------------------------------------------------------ package Ada_GUI.Gnoga.Colors is type Color_Enumeration is (Alice_Blue, Antique_White, Aqua, Aquamarine, Azure, Beige, Bisque, Black, Blanched_Almond, Blue, Blue_Violet, Brown, Burly_Wood, Cadet_Blue, Chartreuse, Chocolate, Coral, Cornflower_Blue, Cornsilk, Crimson, Cyan, Dark_Blue, Dark_Cyan, Dark_Golden_Rod, Dark_Gray, Dark_Green, Dark_Grey, Dark_Khaki, Dark_Magenta, Dark_Olive_Green, Dark_Orange, Dark_Orchid, Dark_Red, Dark_Salmon, Dark_Sea_Green, Dark_Slate_Blue, Dark_Slate_Gray, Dark_Slate_Grey, Dark_Turquoise, Dark_Violet, DeepPink, Deep_Sky_Blue, Dim_Gray, Dim_Grey, Dodger_Blue, Fire_Brick, Floral_White, Forest_Green, Fuchsia, Gainsboro, Ghost_White, Gold_Deep_Sky_Blue, Golden_Rod, Gray, Green, Green_Yellow, Grey, Honey_Dew, Hot_Pink, Indian_Red, Indigo, Ivory, Khaki, Lavender, Lavender_Blush, Lawn_Green, Lemon_Chiffon, Light_Blue, Light_Coral, Light_Cyan, Light_Golden_Rod_Yellow, Light_Gray, Light_Green, Light_Grey, Light_Pink, Light_Salmon, Light_Sea_Green, Light_Sky_Blue, Light_Slate_Gray, Light_Slate_Grey, Light_Steel_Blue, Light_Yellow, Lime, Lime_Green, Linen, Magenta, Maroon, Medium_Aqua_Marine, Medium_Blue, Medium_Orchid, Medium_Purple, Medium_Sea_Green, Medium_Slate_Blue, Medium_Spring_Green, Medium_Turquoise, Medium_Violet_Red, Midnight_Blue, Mint_Cream, Misty_Rose, Moccasin, Navajo_White, Navy, Old_Lace, Olive, Olive_Drab, Orange, Orange_Red, Orchid, Pale_Golden_Rod, Pale_Green, Pale_Turquoise, Pale_Violet_Red, Papaya_Whip, Peach_Puff, Peru, Pink, Plum, Powder_Blue, Purple, Red, Rosy_Brown, Royal_Blue, Saddle_Brown, Salmon, Sandy_Brown, Sea_Green, Sea_Shell, Sienna, Silver, Sky_Blue, Slate_Blue, Slate_Gray, Slate_Grey, Snow, Spring_Green, Steel_Blue, Tan, Teal, Thistle, Tomato, Turquoise, Violet, Wheat, White, White_Smoke, Yellow, Yellow_Green); Color_Error : exception; function To_String (Value : Color_Enumeration) return String; -- Returns color name function To_RGBA (Value : Color_Enumeration) return RGBA_Type; -- Returns color RGBA_Type function To_Color_Enumeration (Value : RGBA_Type) return Color_Enumeration; -- Returns Color_Enumeration if it exists else raises Color_Error exception function To_Color_Enumeration (Value : String) return Color_Enumeration; -- Returns Color_Enumeration if it exists else raises Color_Error exception end Ada_GUI.Gnoga.Colors;
30,130
ada
7
Fabien-Chouteau/coffee-clock
GUI_test/src/utils.adb
<reponame>Fabien-Chouteau/coffee-clock with Screen_Interface; use Screen_Interface; with Giza.Events; use Giza.Events; with Giza.GUI; use Giza.GUI; package body Utils is task body Touch_Screen is TS, Prev : Touch_State; Evt : constant Click_Event_Ref := new Click_Event; Released_Evt : constant Click_Released_Event_Ref := new Click_Released_Event; begin Prev.Touch_Detected := False; loop TS := Get_Touch_State; if TS.Touch_Detected /= Prev.Touch_Detected then if TS.Touch_Detected then Evt.Pos.X := TS.X; Evt.Pos.Y := TS.Y; Emit (Event_Not_Null_Ref (Evt)); else Emit (Event_Not_Null_Ref (Released_Evt)); end if; end if; Prev := TS; end loop; end Touch_Screen; end Utils;
30,131
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/gnat.dg/unchecked_convert9.adb
<reponame>best08618/asylo -- { dg-do compile } -- { dg-options "-O -fdump-rtl-final" } package body Unchecked_Convert9 is procedure Proc is L : Unsigned_32 := 16#55557777#; begin Var := Conv (L); end; end Unchecked_Convert9; -- { dg-final { scan-rtl-dump-times "set \\(mem/v" 1 "final" } }
30,132
ada
0
JCGobbi/Nucleo-STM32G474RE
bb-runtimes/runtimes/ravenscar-full-stm32g474/gnat/a-stbuut.adb
<filename>bb-runtimes/runtimes/ravenscar-full-stm32g474/gnat/a-stbuut.adb ------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- ADA.STRINGS.TEXT_BUFFERS.UTILS -- -- -- -- B o d y -- -- -- -- Copyright (C) 2020-2021, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- -- -- -- -- -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Ada.Strings.Text_Buffers.Utils is procedure Put_7bit (Buffer : in out Root_Buffer_Type'Class; Item : Character_7) is begin Put (Buffer, (1 => Item)); end Put_7bit; procedure Put_Character (Buffer : in out Root_Buffer_Type'Class; Item : Character) is begin Put (Buffer, (1 => Item)); end Put_Character; procedure Put_Wide_Character (Buffer : in out Root_Buffer_Type'Class; Item : Wide_Character) is begin Wide_Put (Buffer, (1 => Item)); end Put_Wide_Character; procedure Put_Wide_Wide_Character (Buffer : in out Root_Buffer_Type'Class; Item : Wide_Wide_Character) is begin Wide_Wide_Put (Buffer, (1 => Item)); end Put_Wide_Wide_Character; procedure Put_UTF_8_Lines (Buffer : in out Root_Buffer_Type'Class; Item : UTF_8_Lines) is begin Put (Buffer, Item); end Put_UTF_8_Lines; function Column (Buffer : Root_Buffer_Type'Class) return Positive is begin return Buffer.UTF_8_Column; end Column; procedure Tab_To_Column (Buffer : in out Root_Buffer_Type'Class; Column : Positive) is begin Put (Buffer, String'(1 .. Column - Utils.Column (Buffer) => ' ')); end Tab_To_Column; end Ada.Strings.Text_Buffers.Utils;
30,133
ada
0
My-Colaborations/ada-ado
src/postgresql/pq-perfect_hash.adb
<gh_stars>0 -- Generated by gperfhash with Util.Strings.Transforms; with Interfaces; use Interfaces; package body PQ.Perfect_Hash is P : constant array (0 .. 11) of Natural := (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13); T1 : constant array (0 .. 11) of Unsigned_16 := (458, 26, 756, 54, 156, 452, 817, 805, 671, 438, 702, 309); T2 : constant array (0 .. 11) of Unsigned_16 := (535, 198, 250, 162, 35, 640, 58, 730, 487, 363, 193, 648); G : constant array (0 .. 832) of Unsigned_16 := (366, 0, 96, 0, 0, 0, 0, 0, 0, 108, 0, 248, 367, 192, 0, 119, 0, 3, 259, 0, 31, 230, 0, 0, 0, 0, 0, 202, 0, 0, 243, 0, 0, 0, 0, 7, 104, 0, 0, 0, 0, 0, 322, 0, 0, 279, 0, 0, 301, 0, 290, 169, 0, 211, 44, 0, 0, 134, 0, 0, 358, 200, 309, 0, 69, 410, 0, 0, 0, 0, 0, 8, 305, 0, 0, 0, 228, 0, 0, 0, 46, 302, 0, 0, 0, 0, 288, 0, 0, 0, 0, 0, 74, 339, 0, 90, 0, 0, 0, 0, 0, 0, 0, 0, 0, 163, 0, 0, 0, 0, 0, 103, 0, 0, 267, 68, 0, 0, 83, 0, 0, 0, 0, 0, 381, 71, 0, 261, 249, 204, 96, 278, 0, 0, 0, 0, 0, 117, 41, 0, 156, 339, 0, 0, 0, 0, 13, 0, 0, 0, 98, 0, 0, 0, 0, 2, 73, 0, 30, 69, 272, 0, 26, 0, 0, 220, 0, 20, 0, 127, 0, 0, 0, 0, 0, 199, 0, 148, 37, 340, 0, 0, 0, 0, 0, 56, 0, 0, 0, 0, 136, 0, 65, 146, 301, 16, 0, 200, 0, 0, 0, 0, 0, 223, 111, 0, 0, 0, 0, 0, 0, 275, 319, 6, 0, 200, 0, 0, 0, 28, 225, 0, 0, 152, 13, 325, 256, 92, 0, 33, 235, 0, 307, 276, 187, 0, 37, 0, 0, 163, 324, 94, 0, 406, 0, 0, 132, 0, 0, 0, 0, 0, 0, 0, 0, 53, 0, 0, 313, 239, 105, 365, 0, 0, 0, 0, 120, 0, 0, 373, 403, 100, 227, 0, 0, 100, 376, 0, 0, 0, 0, 90, 0, 0, 150, 0, 41, 0, 0, 0, 88, 242, 0, 94, 0, 0, 0, 0, 0, 299, 101, 256, 0, 217, 0, 0, 0, 54, 261, 0, 0, 135, 24, 145, 236, 371, 67, 0, 0, 69, 0, 166, 0, 0, 0, 61, 91, 0, 80, 413, 269, 0, 0, 0, 0, 268, 228, 30, 111, 229, 243, 267, 236, 0, 0, 40, 414, 42, 0, 401, 305, 0, 33, 0, 171, 342, 287, 130, 0, 348, 0, 338, 320, 290, 139, 0, 0, 205, 248, 0, 0, 243, 56, 0, 214, 0, 0, 0, 0, 0, 249, 0, 0, 48, 117, 381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 17, 358, 0, 270, 0, 401, 109, 94, 0, 0, 0, 0, 0, 7, 0, 5, 173, 0, 0, 343, 116, 0, 284, 0, 0, 51, 381, 79, 312, 146, 154, 217, 0, 0, 0, 0, 32, 23, 120, 0, 156, 0, 21, 0, 217, 237, 0, 151, 365, 0, 0, 0, 258, 378, 0, 387, 0, 34, 116, 0, 13, 212, 115, 0, 0, 406, 0, 0, 333, 0, 1, 0, 256, 0, 0, 0, 0, 23, 283, 218, 407, 27, 0, 4, 0, 0, 260, 0, 82, 115, 18, 363, 0, 226, 112, 237, 132, 62, 0, 0, 0, 0, 143, 296, 43, 285, 131, 16, 386, 0, 129, 0, 96, 0, 0, 79, 388, 30, 390, 0, 404, 0, 0, 100, 130, 0, 0, 381, 1, 341, 0, 52, 0, 173, 0, 0, 103, 352, 0, 0, 145, 363, 0, 0, 0, 49, 251, 201, 0, 182, 375, 382, 0, 97, 284, 121, 0, 3, 0, 0, 267, 0, 1, 336, 0, 0, 405, 243, 127, 68, 0, 0, 299, 0, 0, 0, 0, 25, 0, 169, 0, 103, 0, 277, 24, 0, 102, 0, 337, 253, 0, 0, 0, 0, 281, 36, 0, 308, 337, 88, 0, 0, 0, 0, 107, 359, 310, 0, 0, 0, 104, 0, 0, 35, 114, 0, 0, 37, 175, 232, 0, 336, 158, 288, 0, 0, 269, 0, 0, 90, 134, 0, 0, 367, 0, 281, 0, 346, 252, 62, 0, 358, 0, 317, 389, 0, 254, 0, 67, 165, 398, 0, 0, 0, 167, 0, 0, 94, 0, 45, 389, 0, 0, 307, 0, 344, 0, 0, 144, 174, 0, 75, 0, 0, 381, 0, 4, 74, 303, 188, 0, 21, 379, 0, 0, 0, 0, 0, 258, 270, 310, 353, 0, 185, 91, 353, 108, 0, 295, 56, 365, 341, 108, 19, 0, 0, 0, 0, 96, 266, 0, 0, 285, 211, 0, 104, 0, 0, 298, 0, 74, 71, 0, 108, 0, 0, 48, 47, 294, 349, 0, 160, 130, 0, 320, 277, 0, 0, 0, 386, 233, 268, 413, 153, 12, 26, 0, 222, 293, 45, 0, 267, 249, 47, 0, 0, 265, 257, 0, 0, 0, 377, 0, 0, 150, 0, 279, 192, 0, 287, 0, 169, 273, 276, 38, 79, 90, 218, 0, 378, 0, 0, 0, 386, 367, 0, 149, 0, 278, 0, 295, 106, 321, 334, 107, 165, 31, 0, 366, 316, 0, 0, 0, 296, 0, 191, 71, 36, 0, 0, 0, 0, 0, 376, 0, 243, 84, 349, 349, 0, 0, 0, 0, 0, 413, 0, 69, 374, 215, 0, 265, 274, 47, 245, 63, 110, 379); function Hash (S : String) return Natural is F : constant Natural := S'First - 1; L : constant Natural := S'Length; F1, F2 : Natural := 0; J : Natural; begin for K in P'Range loop exit when L < P (K); J := Character'Pos (S (P (K) + F)); F1 := (F1 + Natural (T1 (K)) * J) mod 833; F2 := (F2 + Natural (T2 (K)) * J) mod 833; end loop; return (Natural (G (F1)) + Natural (G (F2))) mod 416; end Hash; -- Returns true if the string <b>S</b> is a keyword. function Is_Keyword (S : in String) return Boolean is K : constant String := Util.Strings.Transforms.To_Upper_Case (S); H : constant Natural := Hash (K); begin return Keywords (H).all = K; end Is_Keyword; end PQ.Perfect_Hash;
30,134
ada
33
ytomino/drake
source/machine-w64-mingw32/s-stack.adb
<reponame>ytomino/drake<filename>source/machine-w64-mingw32/s-stack.adb with Ada.Unchecked_Conversion; package body System.Stack is pragma Suppress (All_Checks); -- implementation procedure Get ( TEB : C.winnt.struct_TEB_ptr := C.winnt.NtCurrentTeb; Top, Bottom : out Address) is function Cast is new Ada.Unchecked_Conversion ( C.winnt.struct_TEB_ptr, C.winnt.NT_TIB_ptr); TIB : constant C.winnt.NT_TIB_ptr := Cast (TEB); begin Top := Address (TIB.StackLimit); Bottom := Address (TIB.StackBase); end Get; end System.Stack;
30,135
ada
6
jonashaggstrom/ada-canopen
src/aco-protocols-error_control-slaves.ads
package ACO.Protocols.Error_Control.Slaves is type Slave (Id : ACO.Messages.Node_Nr; Od : not null access ACO.OD.Object_Dictionary'Class) is new EC with private; private type Slave (Id : ACO.Messages.Node_Nr; Od : not null access ACO.OD.Object_Dictionary'Class) is new EC (Id, Od) with null record; end ACO.Protocols.Error_Control.Slaves;
30,136
ada
1
LaudateCorpus1/RosettaCodeData
Task/Hickerson-series-of-almost-integers/Ada/hickerson-series-of-almost-integers.ada
with Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions; procedure Almost_Integers is type Real is new Long_Long_Float; package Real_IO is new Ada.Text_IO.Float_IO (Real); package Integer_IO is new Ada.Text_IO.Integer_IO (Integer); function Faculty (N : in Long_Long_Integer) return Long_Long_Integer is (if N < 2 then N else N * Faculty (N - 1)); function Hickerson (N : in Integer) return Real is package Math is new Ada.Numerics.Generic_Elementary_Functions (Real); LN2 : constant Real := Math.Log (2.0, Base => Ada.Numerics.E); Numerator : constant Real := Real (Faculty (Long_Long_Integer (N))); Denominator : constant Real := 2.0 * LN2 ** (N + 1); begin return Numerator / Denominator; end Hickerson; function Is_Almost_Integer (N : Real) return Boolean is Image : String (1 .. 100); begin Real_IO.Put (Image, N, Exp => 0, Aft => 2); pragma Assert (Image (Image'Last - 2) = '.'); case Image (Image'Last - 1) is when '0' | '9' => return True; when others => return False; end case; end Is_Almost_Integer; use Ada.Text_IO; Placeholder : String := " n h(n) almost"; Image_N : String renames Placeholder ( 1 .. 2); Image_H : String renames Placeholder ( 4 .. 31); Image_A : String renames Placeholder (34 .. 39); begin Put_Line (Placeholder); Image_N := (others => '-'); Image_H := (others => '-'); Image_A := (others => '-'); Put_Line (Placeholder); for N in 1 .. 17 loop declare H : constant Real := Hickerson (N); I : constant Boolean := Is_Almost_Integer (H); begin Integer_IO.Put (Image_N, N); Real_IO.Put (Image_H, H, Exp => 0, Aft => 4); Image_A := (if I then "TRUE " else "FALSE"); Put_Line (Placeholder); end; end loop; end Almost_Integers;
30,137
ada
2
stcarrez/bbox-ada-api
tools/druss-commands-devices.adb
<gh_stars>1-10 ----------------------------------------------------------------------- -- druss-commands-devices -- Print information about the devices -- Copyright (C) 2017, 2018, 2019, 2021 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Properties; with Bbox.API; with Druss.Gateways; package body Druss.Commands.Devices is -- ------------------------------ -- Execute the wifi 'status' command to print the Wifi current status. -- ------------------------------ procedure Do_List (Command : in Command_Type; Args : in Argument_List'Class; Selector : in Device_Selector_Type; Context : in out Context_Type) is pragma Unreferenced (Command, Args); procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; procedure Box_Status (Gateway : in out Druss.Gateways.Gateway_Type) is procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String); procedure Print_Device (Manager : in Util.Properties.Manager; Name : in String) is Link : constant String := Manager.Get (Name & ".link", ""); Kind : constant String := Manager.Get (Name & ".devicetype", ""); begin case Selector is when DEVICE_ALL => null; when DEVICE_ACTIVE => if Manager.Get (Name & ".active", "") = "0" then return; end if; when DEVICE_INACTIVE => if Manager.Get (Name & ".active", "") = "1" then return; end if; end case; Console.Start_Row; Console.Print_Field (F_BBOX_IP_ADDR, Gateway.Ip); Console.Print_Field (F_IP_ADDR, Manager.Get (Name & ".ipaddress", "")); Console.Print_Field (F_ETHERNET, Manager.Get (Name & ".macaddress", "")); Console.Print_Field (F_HOSTNAME, Manager.Get (Name & ".hostname", "")); -- Console.Print_Field (F_ACTIVE, Manager.Get (Name & ".active", "")); Console.Print_Field (F_DEVTYPE, (if Kind = "STB" then "STB" else "")); if Link = "Ethernet" then Console.Print_Field (F_LINK, Link & " port " & Manager.Get (Name & ".ethernet.logicalport", "")); else Console.Print_Field (F_LINK, Link & " RSSI " & Manager.Get (Name & ".wireless.rssi0", "")); end if; Console.End_Row; end Print_Device; begin Gateway.Refresh; Bbox.API.Iterate (Gateway.Hosts, "hosts.list", Print_Device'Access); end Box_Status; begin Console.Start_Title; Console.Print_Title (F_BBOX_IP_ADDR, "Bbox IP", 16); Console.Print_Title (F_IP_ADDR, "Device IP", 16); Console.Print_Title (F_ETHERNET, "Ethernet", 20); Console.Print_Title (F_HOSTNAME, "Hostname", 28); Console.Print_Title (F_DEVTYPE, "Type", 6); -- Console.Print_Title (F_ACTIVE, "Active", 8); Console.Print_Title (F_LINK, "Link", 18); Console.End_Title; Druss.Gateways.Iterate (Context.Gateways, Gateways.ITER_ENABLE, Box_Status'Access); end Do_List; -- ------------------------------ -- Execute a status command to report information about the Bbox. -- ------------------------------ overriding procedure Execute (Command : in out Command_Type; Name : in String; Args : in Argument_List'Class; Context : in out Context_Type) is pragma Unreferenced (Name); begin if Args.Get_Count > 1 then Context.Console.Notice (N_USAGE, "Too many arguments to the command"); Druss.Commands.Driver.Usage (Args, Context); elsif Args.Get_Count = 0 then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "all" then Command.Do_List (Args, DEVICE_ALL, Context); elsif Args.Get_Argument (1) = "active" then Command.Do_List (Args, DEVICE_ACTIVE, Context); elsif Args.Get_Argument (1) = "inactive" then Command.Do_List (Args, DEVICE_INACTIVE, Context); else Context.Console.Notice (N_USAGE, "Invalid argument: " & Args.Get_Argument (1)); Druss.Commands.Driver.Usage (Args, Context); end if; end Execute; -- ------------------------------ -- Write the help associated with the command. -- ------------------------------ overriding procedure Help (Command : in out Command_Type; Name : in String; Context : in out Context_Type) is pragma Unreferenced (Command); Console : constant Druss.Commands.Consoles.Console_Access := Context.Console; begin Console.Notice (N_HELP, "devices: Print information about the devices"); Console.Notice (N_HELP, "Usage: devices [all | active | inactive]"); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " List the devices that are known by the Bbox."); Console.Notice (N_HELP, ""); Console.Notice (N_HELP, " all List all the devices"); Console.Notice (N_HELP, " active List the active devices (the default)"); Console.Notice (N_HELP, " inative List the inactive devices"); end Help; end Druss.Commands.Devices;
30,138
ada
10
jrmarino/libsodium-ada
examples/hash_password/demo_ada.adb
with Sodium.Functions; use Sodium.Functions; with Ada.Text_IO; use Ada.Text_IO; procedure Demo_Ada is password : constant String := "<PASSWORD>"; salt : constant String := "<PASSWORD>"; begin if not initialize_sodium_library then Put_Line ("Initialization failed"); return; end if; Put_Line ("password: " & password); declare passkey : constant String := Derive_Password_Key (password => password, salt => salt); hash : constant Any_Hash := Generate_Password_Hash (criticality => highly_sensitive, password => password); begin Put_Line ("pass key: " & As_Hexidecimal (passkey)); Put_Line ("hash: " & hash); if Password_Hash_Matches (hash => hash, password => password) then Put_Line ("Hash verification passed"); else Put_Line ("Hash verification failed"); end if; end; end Demo_Ada;
30,139
ada
33
ytomino/drake
source/numerics/a-nlcoar.ads
<gh_stars>10-100 pragma License (Unrestricted); with Ada.Numerics.Generic_Complex_Arrays; with Ada.Numerics.Long_Complex_Types; with Ada.Numerics.Long_Real_Arrays; package Ada.Numerics.Long_Complex_Arrays is new Generic_Complex_Arrays (Long_Real_Arrays, Long_Complex_Types); pragma Pure (Ada.Numerics.Long_Complex_Arrays);
30,140
ada
32
persan/AdaYaml
src/annotation_processor/implementation/yaml-events-context.ads
<filename>src/annotation_processor/implementation/yaml-events-context.ads -- part of AdaYaml, (c) 2017 <NAME> -- released under the terms of the MIT license, see the file "copying.txt" private with Ada.Containers.Hashed_Maps; with Yaml.Events.Store; package Yaml.Events.Context is type Reference is tagged private; type Cursor is private; type Local_Scope_Cursor is private; type Generated_Store_Cursor is private; type Symbol_Cursor is private; type Location_Type is (Generated, Local, Document, Stream, External, None); function Create (External : Store.Reference := Store.New_Store) return Reference; function External_Store (Object : Reference) return Store.Accessor; function Stream_Store (Object : Reference) return Store.Accessor; function Document_Store (Object : Reference) return Store.Accessor; function Transformed_Store (Object : Reference) return Store.Accessor; function Local_Store (Object : Reference; Position : Local_Scope_Cursor) return Store.Accessor; function Local_Store_Ref (Object : Reference; Position : Local_Scope_Cursor) return Store.Optional_Reference; function Generated_Store (Object : Reference; Position : Generated_Store_Cursor) return Store.Accessor; function Generated_Store_Ref (Object : Reference; Position : Generated_Store_Cursor) return Store.Optional_Reference; function Position (Object : Reference; Alias : Text.Reference) return Cursor; function Location (Position : Cursor) return Location_Type; procedure Create_Local_Store (Object : Reference; Position : out Local_Scope_Cursor); procedure Create_Local_Symbol_Scope (Object : Reference; Position : out Local_Scope_Cursor); procedure Release_Local_Store (Object : Reference; Position : Local_Scope_Cursor); procedure Create_Generated_Store (Object : Reference; Position : out Generated_Store_Cursor); procedure Release_Generated_Store (Object : Reference; Position : Generated_Store_Cursor); procedure Create_Symbol (Object : Reference; Scope : Local_Scope_Cursor; Name : Text.Reference; Position : out Symbol_Cursor); procedure Update_Symbol (Object : Reference; Scope : Local_Scope_Cursor; Position : Symbol_Cursor; New_Value : Cursor); function Symbol_Name (Position : Symbol_Cursor) return Text.Reference; No_Element : constant Cursor; No_Local_Store : constant Local_Scope_Cursor; function Is_Anchored (Pos : Cursor) return Boolean; function Retrieve (Pos : Cursor) return Store.Stream_Reference with Pre => Pos /= No_Element; function First (Pos : Cursor) return Event with Pre => Pos /= No_Element; function Exists_In_Ouput (Position : Cursor) return Boolean; procedure Set_Exists_In_Output (Position : in out Cursor); procedure Get_Store_And_Cursor (Position : Cursor; Target : out Store.Optional_Reference; Element_Position : out Events.Store.Element_Cursor); function To_Cursor (Object : Reference; Parent : Store.Optional_Reference; Element_Position : Events.Store.Element_Cursor) return Cursor; private type Cursor is record Target : Store.Optional_Reference; Anchored_Position : Events.Store.Anchor_Cursor; Element_Position : Events.Store.Element_Cursor; Target_Location : Location_Type; end record; package Symbol_Tables is new Ada.Containers.Hashed_Maps (Text.Reference, Cursor, Text.Hash, Text."="); type Symbol_Table_Pointer is access Symbol_Tables.Map; type Local_Scope is record Events : Store.Optional_Reference; Symbols : Symbol_Table_Pointer; end record; type Scope_Array is array (Positive range <>) of Local_Scope; type Scope_Array_Pointer is access Scope_Array; type Data_Array is array (Positive range <>) of Store.Optional_Reference; type Data_Array_Pointer is access Data_Array; type Instance is limited new Refcount_Base with record Generated_Data : Data_Array_Pointer; Document_Data, Stream_Data, External_Data, Transformed_Data : Store.Reference; Local_Scopes : Scope_Array_Pointer := null; Local_Scope_Count, Generated_Data_Count : Natural := 0; end record; type Instance_Access is access all Instance; overriding procedure Finalize (Object : in out Instance); type Local_Scope_Cursor is new Natural; type Generated_Store_Cursor is new Natural; type Symbol_Cursor is new Symbol_Tables.Cursor; type Reference is new Ada.Finalization.Controlled with record Data : not null Instance_Access := raise Constraint_Error with "uninitialized context instance!"; end record; overriding procedure Adjust (Object : in out Reference); overriding procedure Finalize (Object : in out Reference); No_Element : constant Cursor := (Target => Store.Null_Reference, Element_Position => Events.Store.No_Element, Anchored_Position => Events.Store.No_Anchor, Target_Location => None); No_Local_Store : constant Local_Scope_Cursor := 0; end Yaml.Events.Context;
30,141
ada
33
ytomino/drake
source/strings/a-wchla1.ads
<filename>source/strings/a-wchla1.ads pragma License (Unrestricted); -- extended unit, not in RM package Ada.Wide_Characters.Latin_1 is -- Wide_Character version of Ada.Characters.Latin_1. pragma Pure; -- Control characters: NUL : constant Wide_Character := Wide_Character'Val (0); SOH : constant Wide_Character := Wide_Character'Val (1); STX : constant Wide_Character := Wide_Character'Val (2); ETX : constant Wide_Character := Wide_Character'Val (3); EOT : constant Wide_Character := Wide_Character'Val (4); ENQ : constant Wide_Character := Wide_Character'Val (5); ACK : constant Wide_Character := Wide_Character'Val (6); BEL : constant Wide_Character := Wide_Character'Val (7); BS : constant Wide_Character := Wide_Character'Val (8); HT : constant Wide_Character := Wide_Character'Val (9); LF : constant Wide_Character := Wide_Character'Val (10); VT : constant Wide_Character := Wide_Character'Val (11); FF : constant Wide_Character := Wide_Character'Val (12); CR : constant Wide_Character := Wide_Character'Val (13); SO : constant Wide_Character := Wide_Character'Val (14); SI : constant Wide_Character := Wide_Character'Val (15); DLE : constant Wide_Character := Wide_Character'Val (16); DC1 : constant Wide_Character := Wide_Character'Val (17); DC2 : constant Wide_Character := Wide_Character'Val (18); DC3 : constant Wide_Character := Wide_Character'Val (19); DC4 : constant Wide_Character := Wide_Character'Val (20); NAK : constant Wide_Character := Wide_Character'Val (21); SYN : constant Wide_Character := Wide_Character'Val (22); ETB : constant Wide_Character := Wide_Character'Val (23); CAN : constant Wide_Character := Wide_Character'Val (24); EM : constant Wide_Character := Wide_Character'Val (25); SUB : constant Wide_Character := Wide_Character'Val (26); ESC : constant Wide_Character := Wide_Character'Val (27); FS : constant Wide_Character := Wide_Character'Val (28); GS : constant Wide_Character := Wide_Character'Val (29); RS : constant Wide_Character := Wide_Character'Val (30); US : constant Wide_Character := Wide_Character'Val (31); -- ISO 646 graphic characters: Space : constant Wide_Character := Wide_Character'Val (32); -- ' ' Exclamation : constant Wide_Character := Wide_Character'Val (33); -- '!' Quotation : constant Wide_Character := Wide_Character'Val (34); -- '"' Number_Sign : constant Wide_Character := Wide_Character'Val (35); -- '#' Dollar_Sign : constant Wide_Character := Wide_Character'Val (36); -- '$' Percent_Sign : constant Wide_Character := Wide_Character'Val (37); -- '%' Ampersand : constant Wide_Character := Wide_Character'Val (38); -- '&' Apostrophe : constant Wide_Character := Wide_Character'Val (39); -- ''' Left_Parenthesis : constant Wide_Character := Wide_Character'Val (40); -- '(' Right_Parenthesis : constant Wide_Character := Wide_Character'Val (41); -- ')' Asterisk : constant Wide_Character := Wide_Character'Val (42); -- '*' Plus_Sign : constant Wide_Character := Wide_Character'Val (43); -- '+' Comma : constant Wide_Character := Wide_Character'Val (44); -- ',' Hyphen : constant Wide_Character := Wide_Character'Val (45); -- '-' Minus_Sign : Wide_Character renames Hyphen; Full_Stop : constant Wide_Character := Wide_Character'Val (46); -- '.' Solidus : constant Wide_Character := Wide_Character'Val (47); -- '/' -- Decimal digits '0' though '9' are at positions 48 through 57 Colon : constant Wide_Character := Wide_Character'Val (58); -- ':' Semicolon : constant Wide_Character := Wide_Character'Val (59); -- ';' Less_Than_Sign : constant Wide_Character := Wide_Character'Val (60); -- '<' Equals_Sign : constant Wide_Character := Wide_Character'Val (61); -- '=' Greater_Than_Sign : constant Wide_Character := Wide_Character'Val (62); -- '>' Question : constant Wide_Character := Wide_Character'Val (63); -- '?' Commercial_At : constant Wide_Character := Wide_Character'Val (64); -- '@' -- Letters 'A' through 'Z' are at positions 65 through 90 Left_Square_Bracket : constant Wide_Character := Wide_Character'Val (91); -- '[' Reverse_Solidus : constant Wide_Character := Wide_Character'Val (92); -- '\' Right_Square_Bracket : constant Wide_Character := Wide_Character'Val (93); -- ']' Circumflex : constant Wide_Character := Wide_Character'Val (94); -- '^' Low_Line : constant Wide_Character := Wide_Character'Val (95); -- '_' Grave : constant Wide_Character := Wide_Character'Val (96); -- '`' LC_A : constant Wide_Character := Wide_Character'Val (97); -- 'a' LC_B : constant Wide_Character := Wide_Character'Val (98); -- 'b' LC_C : constant Wide_Character := Wide_Character'Val (99); -- 'c' LC_D : constant Wide_Character := Wide_Character'Val (100); -- 'd' LC_E : constant Wide_Character := Wide_Character'Val (101); -- 'e' LC_F : constant Wide_Character := Wide_Character'Val (102); -- 'f' LC_G : constant Wide_Character := Wide_Character'Val (103); -- 'g' LC_H : constant Wide_Character := Wide_Character'Val (104); -- 'h' LC_I : constant Wide_Character := Wide_Character'Val (105); -- 'i' LC_J : constant Wide_Character := Wide_Character'Val (106); -- 'j' LC_K : constant Wide_Character := Wide_Character'Val (107); -- 'k' LC_L : constant Wide_Character := Wide_Character'Val (108); -- 'l' LC_M : constant Wide_Character := Wide_Character'Val (109); -- 'm' LC_N : constant Wide_Character := Wide_Character'Val (110); -- 'n' LC_O : constant Wide_Character := Wide_Character'Val (111); -- 'o' LC_P : constant Wide_Character := Wide_Character'Val (112); -- 'p' LC_Q : constant Wide_Character := Wide_Character'Val (113); -- 'q' LC_R : constant Wide_Character := Wide_Character'Val (114); -- 'r' LC_S : constant Wide_Character := Wide_Character'Val (115); -- 's' LC_T : constant Wide_Character := Wide_Character'Val (116); -- 't' LC_U : constant Wide_Character := Wide_Character'Val (117); -- 'u' LC_V : constant Wide_Character := Wide_Character'Val (118); -- 'v' LC_W : constant Wide_Character := Wide_Character'Val (119); -- 'w' LC_X : constant Wide_Character := Wide_Character'Val (120); -- 'x' LC_Y : constant Wide_Character := Wide_Character'Val (121); -- 'y' LC_Z : constant Wide_Character := Wide_Character'Val (122); -- 'z' Left_Curly_Bracket : constant Wide_Character := Wide_Character'Val (123); -- '{' Vertical_Line : constant Wide_Character := Wide_Character'Val (124); -- '|' Right_Curly_Bracket : constant Wide_Character := Wide_Character'Val (125); -- '}' Tilde : constant Wide_Character := Wide_Character'Val (126); -- '~' DEL : constant Wide_Character := Wide_Character'Val (127); -- ISO 6429 control characters: IS4 : Wide_Character renames FS; IS3 : Wide_Character renames GS; IS2 : Wide_Character renames RS; IS1 : Wide_Character renames US; Reserved_128 : constant Wide_Character := Wide_Character'Val (128); Reserved_129 : constant Wide_Character := Wide_Character'Val (129); BPH : constant Wide_Character := Wide_Character'Val (130); NBH : constant Wide_Character := Wide_Character'Val (131); Reserved_132 : constant Wide_Character := Wide_Character'Val (132); NEL : constant Wide_Character := Wide_Character'Val (133); SSA : constant Wide_Character := Wide_Character'Val (134); ESA : constant Wide_Character := Wide_Character'Val (135); HTS : constant Wide_Character := Wide_Character'Val (136); HTJ : constant Wide_Character := Wide_Character'Val (137); VTS : constant Wide_Character := Wide_Character'Val (138); PLD : constant Wide_Character := Wide_Character'Val (139); PLU : constant Wide_Character := Wide_Character'Val (140); RI : constant Wide_Character := Wide_Character'Val (141); SS2 : constant Wide_Character := Wide_Character'Val (142); SS3 : constant Wide_Character := Wide_Character'Val (143); DCS : constant Wide_Character := Wide_Character'Val (144); PU1 : constant Wide_Character := Wide_Character'Val (145); PU2 : constant Wide_Character := Wide_Character'Val (146); STS : constant Wide_Character := Wide_Character'Val (147); CCH : constant Wide_Character := Wide_Character'Val (148); MW : constant Wide_Character := Wide_Character'Val (149); SPA : constant Wide_Character := Wide_Character'Val (150); EPA : constant Wide_Character := Wide_Character'Val (151); SOS : constant Wide_Character := Wide_Character'Val (152); Reserved_153 : constant Wide_Character := Wide_Character'Val (153); SCI : constant Wide_Character := Wide_Character'Val (154); CSI : constant Wide_Character := Wide_Character'Val (155); ST : constant Wide_Character := Wide_Character'Val (156); OSC : constant Wide_Character := Wide_Character'Val (157); PM : constant Wide_Character := Wide_Character'Val (158); APC : constant Wide_Character := Wide_Character'Val (159); -- Other graphic characters: -- Character positions 160 (16#A0#) .. 175 (16#AF#): No_Break_Space : constant Wide_Character := Wide_Character'Val (160); -- ' ' NBSP : Wide_Character renames No_Break_Space; Inverted_Exclamation : constant Wide_Character := Wide_Character'Val (161); -- '¡' Cent_Sign : constant Wide_Character := Wide_Character'Val (162); -- '¢' Pound_Sign : constant Wide_Character := Wide_Character'Val (163); -- '£' Currency_Sign : constant Wide_Character := Wide_Character'Val (164); -- '¤' Yen_Sign : constant Wide_Character := Wide_Character'Val (165); -- '¥' Broken_Bar : constant Wide_Character := Wide_Character'Val (166); -- '¦' Section_Sign : constant Wide_Character := Wide_Character'Val (167); -- '§' Diaeresis : constant Wide_Character := Wide_Character'Val (168); -- '¨' Copyright_Sign : constant Wide_Character := Wide_Character'Val (169); -- '©' Feminine_Ordinal_Indicator : constant Wide_Character := Wide_Character'Val (170); -- 'ª' Left_Angle_Quotation : constant Wide_Character := Wide_Character'Val (171); -- '«' Not_Sign : constant Wide_Character := Wide_Character'Val (172); -- '¬' Soft_Hyphen : constant Wide_Character := Wide_Character'Val (173); -- ' ' Registered_Trade_Mark_Sign : constant Wide_Character := Wide_Character'Val (174); -- '®' Macron : constant Wide_Character := Wide_Character'Val (175); -- '¯' -- Character positions 176 (16#B0#) .. 191 (16#BF#): Degree_Sign : constant Wide_Character := Wide_Character'Val (176); -- '°' Ring_Above : Wide_Character renames Degree_Sign; Plus_Minus_Sign : constant Wide_Character := Wide_Character'Val (177); -- '±' Superscript_Two : constant Wide_Character := Wide_Character'Val (178); -- '²' Superscript_Three : constant Wide_Character := Wide_Character'Val (179); -- '³' Acute : constant Wide_Character := Wide_Character'Val (180); -- '´' Micro_Sign : constant Wide_Character := Wide_Character'Val (181); -- 'µ' Pilcrow_Sign : constant Wide_Character := Wide_Character'Val (182); -- '¶' Paragraph_Sign : Wide_Character renames Pilcrow_Sign; Middle_Dot : constant Wide_Character := Wide_Character'Val (183); -- '·' Cedilla : constant Wide_Character := Wide_Character'Val (184); -- '¸' Superscript_One : constant Wide_Character := Wide_Character'Val (185); -- '¹' Masculine_Ordinal_Indicator : constant Wide_Character := Wide_Character'Val (186); -- 'º' Right_Angle_Quotation : constant Wide_Character := Wide_Character'Val (187); -- '»' Fraction_One_Quarter : constant Wide_Character := Wide_Character'Val (188); -- '¼' Fraction_One_Half : constant Wide_Character := Wide_Character'Val (189); -- '½' Fraction_Three_Quarters : constant Wide_Character := Wide_Character'Val (190); -- '¾' Inverted_Question : constant Wide_Character := Wide_Character'Val (191); -- '¿' -- Character positions 192 (16#C0#) .. 207 (16#CF#): UC_A_Grave : constant Wide_Character := Wide_Character'Val (192); -- 'À' UC_A_Acute : constant Wide_Character := Wide_Character'Val (193); -- 'Á' UC_A_Circumflex : constant Wide_Character := Wide_Character'Val (194); -- 'Â' UC_A_Tilde : constant Wide_Character := Wide_Character'Val (195); -- 'Ã' UC_A_Diaeresis : constant Wide_Character := Wide_Character'Val (196); -- 'Ä' UC_A_Ring : constant Wide_Character := Wide_Character'Val (197); -- 'Å' UC_AE_Diphthong : constant Wide_Character := Wide_Character'Val (198); -- 'Æ' UC_C_Cedilla : constant Wide_Character := Wide_Character'Val (199); -- 'Ç' UC_E_Grave : constant Wide_Character := Wide_Character'Val (200); -- 'È' UC_E_Acute : constant Wide_Character := Wide_Character'Val (201); -- 'É' UC_E_Circumflex : constant Wide_Character := Wide_Character'Val (202); -- 'Ê' UC_E_Diaeresis : constant Wide_Character := Wide_Character'Val (203); -- 'Ë' UC_I_Grave : constant Wide_Character := Wide_Character'Val (204); -- 'Ì' UC_I_Acute : constant Wide_Character := Wide_Character'Val (205); -- 'Í' UC_I_Circumflex : constant Wide_Character := Wide_Character'Val (206); -- 'Î' UC_I_Diaeresis : constant Wide_Character := Wide_Character'Val (207); -- 'Ï' -- Character positions 208 (16#D0#) .. 223 (16#DF#): UC_Icelandic_Eth : constant Wide_Character := Wide_Character'Val (208); -- 'Ð' UC_N_Tilde : constant Wide_Character := Wide_Character'Val (209); -- 'Ñ' UC_O_Grave : constant Wide_Character := Wide_Character'Val (210); -- 'Ò' UC_O_Acute : constant Wide_Character := Wide_Character'Val (211); -- 'Ó' UC_O_Circumflex : constant Wide_Character := Wide_Character'Val (212); -- 'Ô' UC_O_Tilde : constant Wide_Character := Wide_Character'Val (213); -- 'Õ' UC_O_Diaeresis : constant Wide_Character := Wide_Character'Val (214); -- 'Ö' Multiplication_Sign : constant Wide_Character := Wide_Character'Val (215); -- '×' UC_O_Oblique_Stroke : constant Wide_Character := Wide_Character'Val (216); -- 'Ø' UC_U_Grave : constant Wide_Character := Wide_Character'Val (217); -- 'Ù' UC_U_Acute : constant Wide_Character := Wide_Character'Val (218); -- 'Ú' UC_U_Circumflex : constant Wide_Character := Wide_Character'Val (219); -- 'Û' UC_U_Diaeresis : constant Wide_Character := Wide_Character'Val (220); -- 'Ü' UC_Y_Acute : constant Wide_Character := Wide_Character'Val (221); -- 'Ý' UC_Icelandic_Thorn : constant Wide_Character := Wide_Character'Val (222); -- 'Þ' LC_German_Sharp_S : constant Wide_Character := Wide_Character'Val (223); -- 'ß' -- Character positions 224 (16#E0#) .. 239 (16#EF#): LC_A_Grave : constant Wide_Character := Wide_Character'Val (224); -- 'à' LC_A_Acute : constant Wide_Character := Wide_Character'Val (225); -- 'á' LC_A_Circumflex : constant Wide_Character := Wide_Character'Val (226); -- 'â' LC_A_Tilde : constant Wide_Character := Wide_Character'Val (227); -- 'ã' LC_A_Diaeresis : constant Wide_Character := Wide_Character'Val (228); -- 'ä' LC_A_Ring : constant Wide_Character := Wide_Character'Val (229); -- 'å' LC_AE_Diphthong : constant Wide_Character := Wide_Character'Val (230); -- 'æ' LC_C_Cedilla : constant Wide_Character := Wide_Character'Val (231); -- 'ç' LC_E_Grave : constant Wide_Character := Wide_Character'Val (232); -- 'è' LC_E_Acute : constant Wide_Character := Wide_Character'Val (233); -- 'é' LC_E_Circumflex : constant Wide_Character := Wide_Character'Val (234); -- 'ê' LC_E_Diaeresis : constant Wide_Character := Wide_Character'Val (235); -- 'ë' LC_I_Grave : constant Wide_Character := Wide_Character'Val (236); -- 'ì' LC_I_Acute : constant Wide_Character := Wide_Character'Val (237); -- 'í' LC_I_Circumflex : constant Wide_Character := Wide_Character'Val (238); -- 'î' LC_I_Diaeresis : constant Wide_Character := Wide_Character'Val (239); -- 'ï' -- Character positions 240 (16#F0#) .. 255 (16#FF#): LC_Icelandic_Eth : constant Wide_Character := Wide_Character'Val (240); -- 'ð' LC_N_Tilde : constant Wide_Character := Wide_Character'Val (241); -- 'ñ' LC_O_Grave : constant Wide_Character := Wide_Character'Val (242); -- 'ò' LC_O_Acute : constant Wide_Character := Wide_Character'Val (243); -- 'ó' LC_O_Circumflex : constant Wide_Character := Wide_Character'Val (244); -- 'ô' LC_O_Tilde : constant Wide_Character := Wide_Character'Val (245); -- 'õ' LC_O_Diaeresis : constant Wide_Character := Wide_Character'Val (246); -- 'ö' Division_Sign : constant Wide_Character := Wide_Character'Val (247); -- '÷'; LC_O_Oblique_Stroke : constant Wide_Character := Wide_Character'Val (248); -- 'ø' LC_U_Grave : constant Wide_Character := Wide_Character'Val (249); -- 'ù' LC_U_Acute : constant Wide_Character := Wide_Character'Val (250); -- 'ú' LC_U_Circumflex : constant Wide_Character := Wide_Character'Val (251); -- 'û'; LC_U_Diaeresis : constant Wide_Character := Wide_Character'Val (252); -- 'ü' LC_Y_Acute : constant Wide_Character := Wide_Character'Val (253); -- 'ý' LC_Icelandic_Thorn : constant Wide_Character := Wide_Character'Val (254); -- 'þ' LC_Y_Diaeresis : constant Wide_Character := Wide_Character'Val (255); -- 'ÿ' end Ada.Wide_Characters.Latin_1;
30,142
ada
0
My-Colaborations/ada-ado
src/ado-schemas.ads
<reponame>My-Colaborations/ada-ado ----------------------------------------------------------------------- -- ado-schemas -- Database Schemas -- Copyright (C) 2009, 2010, 2018 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Finalization; with Ada.Containers; with Util.Strings; with ADO.Configs; package ADO.Schemas is type Column_Index is new Natural range 0 .. ADO.Configs.MAX_COLUMNS; type Member_Names is array (Column_Index range <>) of Util.Strings.Name_Access; type Class_Mapping (Count : Column_Index) is tagged limited record Table : Util.Strings.Name_Access; Members : Member_Names (1 .. Count); end record; type Class_Mapping_Access is access constant Class_Mapping'Class; -- Get the hash value associated with the class mapping. function Hash (Mapping : Class_Mapping_Access) return Ada.Containers.Hash_Type; -- Get the Ada type mapping for the column type Column_Type is ( T_UNKNOWN, -- Boolean column T_BOOLEAN, T_TINYINT, T_SMALLINT, T_INTEGER, T_LONG_INTEGER, T_FLOAT, T_DOUBLE, T_DECIMAL, T_ENUM, T_SET, T_TIME, T_YEAR, T_DATE, T_DATE_TIME, T_TIMESTAMP, T_CHAR, T_VARCHAR, T_BLOB, T_NULL ); -- ------------------------------ -- Column Representation -- ------------------------------ -- Describes a column in a table. type Column_Definition is private; -- Get the column name function Get_Name (Column : Column_Definition) return String; -- Get the column type function Get_Type (Column : Column_Definition) return Column_Type; -- Get the default column value function Get_Default (Column : Column_Definition) return String; -- Get the column collation (for string based columns) function Get_Collation (Column : Column_Definition) return String; -- Check whether the column can be null function Is_Null (Column : Column_Definition) return Boolean; -- Check whether the column is an unsigned number function Is_Unsigned (Column : Column_Definition) return Boolean; -- Returns true if the column can hold a binary string function Is_Binary (Column : Column_Definition) return Boolean; -- Returns true if the column is a primary key. function Is_Primary (Column : Column_Definition) return Boolean; -- Get the column length function Get_Size (Column : Column_Definition) return Natural; -- ------------------------------ -- Column iterator -- ------------------------------ type Column_Cursor is private; -- Returns true if the iterator contains more column function Has_Element (Cursor : Column_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Column_Cursor); -- Get the current column definition function Element (Cursor : Column_Cursor) return Column_Definition; -- ------------------------------ -- Table Representation -- ------------------------------ -- Describes a table in the database. The table contains a list -- of columns described by Column_Definition. type Table_Definition is private; -- Get the table name function Get_Name (Table : Table_Definition) return String; -- Get the column iterator function Get_Columns (Table : Table_Definition) return Column_Cursor; -- Find the column having the given name function Find_Column (Table : Table_Definition; Name : String) return Column_Definition; -- ------------------------------ -- Table iterator -- ------------------------------ type Table_Cursor is private; -- Returns true if the iterator contains more tables function Has_Element (Cursor : Table_Cursor) return Boolean; -- Move to the next column procedure Next (Cursor : in out Table_Cursor); -- Get the current table definition function Element (Cursor : Table_Cursor) return Table_Definition; -- ------------------------------ -- Database Schema -- ------------------------------ type Schema_Definition is limited private; -- Find a table knowing its name function Find_Table (Schema : Schema_Definition; Name : String) return Table_Definition; function Get_Tables (Schema : Schema_Definition) return Table_Cursor; private use Ada.Strings.Unbounded; type Column; type Column_Definition is access all Column; type Table; type Table_Definition is access all Table; type Schema; type Schema_Access is access all Schema; type Schema_Definition is new Ada.Finalization.Limited_Controlled with record Schema : Schema_Access; end record; procedure Finalize (Schema : in out Schema_Definition); type Column_Cursor is record Current : Column_Definition; end record; type Table_Cursor is record Current : Table_Definition; end record; type Column is record Next_Column : Column_Definition; Table : Table_Definition; Name : Unbounded_String; Default : Unbounded_String; Collation : Unbounded_String; Col_Type : Column_Type := T_VARCHAR; Size : Natural := 0; Is_Null : Boolean := False; Is_Binary : Boolean := False; Is_Unsigned : Boolean := False; Is_Primary : Boolean := False; end record; type Table is record Name : Unbounded_String; First_Column : Column_Definition; Next_Table : Table_Definition; end record; type Schema is record -- Tables : Table_Definition; First_Table : Table_Definition; end record; end ADO.Schemas;
30,143
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c5/c58006a.ada
-- C58006A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT IF THE EVALUATION OF A RETURN STATEMENT'S EXPRESSION -- RAISES AN EXCEPTION, THE EXCEPTION CAN BE HANDLED WITHIN THE BODY OF -- THE FUNCTION. -- RM 05/11/81 -- SPS 10/26/82 -- SPS 3/8/83 -- JBG 9/13/83 WITH REPORT; PROCEDURE C58006A IS USE REPORT; BEGIN TEST( "C58006A" , "CHECK THAT EXCEPTION RAISED BY A RETURN" & " STATEMENT CAN BE HANDLED LOCALLY" ); DECLARE SUBTYPE I1 IS INTEGER RANGE -10..90; SUBTYPE I2 IS INTEGER RANGE 1..10; FUNCTION FN1( X : I1 ) RETURN I2 IS BEGIN RETURN 0; EXCEPTION WHEN CONSTRAINT_ERROR => COMMENT ("EXCEPTION RAISED - F1"); RETURN 1; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED - FN1"); END FN1; FUNCTION FN2( X : I1 ) RETURN I2 IS BEGIN RETURN X + IDENT_INT(0); EXCEPTION WHEN CONSTRAINT_ERROR => COMMENT ("EXCEPTION RAISED - F2"); RETURN 1; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED - FN2"); END FN2; FUNCTION FN3( X : I1 ) RETURN I2 IS HUNDRED : INTEGER RANGE -100..100 := IDENT_INT(100); BEGIN RETURN HUNDRED; EXCEPTION WHEN CONSTRAINT_ERROR => COMMENT ("EXCEPTION RAISED - F3"); RETURN 1; WHEN OTHERS => FAILED ("WRONG EXCEPTION RAISED - FN3"); END FN3; BEGIN BEGIN IF FN1( 0 ) /= IDENT_INT(1) THEN FAILED ("NO EXCEPTION RAISED - FN1( 0 )"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION PROPAGATED - FN1( 0 )"); END; BEGIN IF FN2( 0 ) /= IDENT_INT(1) THEN FAILED ("NO EXCEPTION RAISED - FN2( 0 )"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION PROPAGATED - FN2( 0 )"); END; BEGIN IF FN2(11 ) /= IDENT_INT(1) THEN FAILED ("NO EXCEPTION RAISED - FN2(11 )"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION PROPAGATED - FN2(11 )"); END; BEGIN IF FN3( 0 ) /= IDENT_INT(1) THEN FAILED ("NO EXCEPTION RAISED - FN3( 0 )"); END IF; EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION PROPAGATED - FN3( 0 )"); END; END; RESULT; END C58006A;
30,144
ada
19
jquorning/ada-security
src/security-policies-urls.ads
<reponame>jquorning/ada-security ----------------------------------------------------------------------- -- security-policies-urls -- URL security policy -- Copyright (C) 2010, 2011, 2012, 2017, 2018, 2019 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Containers.Hashed_Maps; with Ada.Containers.Vectors; with Util.Refs; with Util.Strings; with Util.Serialize.Mappers; with GNAT.Regexp; with Security.Contexts; -- == URL Security Policy == -- The `Security.Policies.Urls` implements a security policy intended to be used -- in web servers. It allows to protect an URL by defining permissions that must be granted -- for a user to get access to the URL. A typical example is a web server that has a set of -- administration pages, these pages should be accessed by users having some admin permission. -- -- === Policy creation === -- An instance of the `URL_Policy` must be created and registered in the policy manager. -- Get or declare the following variables: -- -- Manager : Security.Policies.Policy_Manager; -- Policy : Security.Policies.Urls.URL_Policy_Access; -- -- Create the URL policy and register it in the policy manager as follows: -- -- Policy := new URL_Policy; -- Manager.Add_Policy (Policy.all'Access); -- -- === Policy Configuration === -- Once the URL policy is registered, the policy manager can read and process the following -- XML configuration: -- -- <policy-rules> -- <url-policy id='1'> -- <permission>create-workspace</permission> -- <permission>admin</permission> -- <url-pattern>/workspace/create</url-pattern> -- <url-pattern>/workspace/setup/*</url-pattern> -- </url-policy> -- ... -- </policy-rules> -- -- This policy gives access to the URL that match one of the URL pattern if the -- security context has the permission `create-workspace` or `admin`. -- These two permissions are checked according to another security policy. -- The XML configuration can define several `url-policy`. They are checked in -- the order defined in the XML. In other words, the first `url-policy` that matches -- the URL is used to verify the permission. -- -- The `url-policy` definition can contain several `permission`. -- The first permission that is granted gives access to the URL. -- -- === Checking for permission === -- To check a URL permission, you must declare a `URL_Permission` object with the URL. -- -- URL : constant String := ...; -- Perm : constant Policies.URLs.URL_Permission (URL'Length) -- := URL_Permission '(Len => URI'Length, URL => URL); -- -- Then, we can check the permission: -- -- Result : Boolean := Security.Contexts.Has_Permission (Perm); -- package Security.Policies.URLs is NAME : constant String := "URL-Policy"; package P_URL is new Security.Permissions.Definition ("url"); -- ------------------------------ -- URL Permission -- ------------------------------ -- Represents a permission to access a given URL. type URL_Permission (Len : Natural) is new Permissions.Permission (P_URL.Permission) with record URL : String (1 .. Len); end record; -- ------------------------------ -- URL policy -- ------------------------------ type URL_Policy is new Policy with private; type URL_Policy_Access is access all URL_Policy'Class; Invalid_Name : exception; -- Get the policy name. overriding function Get_Name (From : in URL_Policy) return String; -- Returns True if the user has the permission to access the given URI permission. function Has_Permission (Manager : in URL_Policy; Context : in Contexts.Security_Context'Class; Permission : in URL_Permission'Class) return Boolean; -- Grant the permission to access to the given <b>URI</b> to users having the <b>To</b> -- permissions. procedure Grant_URI_Permission (Manager : in out URL_Policy; URI : in String; To : in String); -- Initialize the permission manager. overriding procedure Initialize (Manager : in out URL_Policy); -- Finalize the permission manager. overriding procedure Finalize (Manager : in out URL_Policy); -- Setup the XML parser to read the <b>policy</b> description. overriding procedure Prepare_Config (Policy : in out URL_Policy; Mapper : in out Util.Serialize.Mappers.Processing); -- Get the URL policy associated with the given policy manager. -- Returns the URL policy instance or null if it was not registered in the policy manager. function Get_URL_Policy (Manager : in Security.Policies.Policy_Manager'Class) return URL_Policy_Access; private use Util.Strings; -- The <b>Access_Rule</b> represents a list of permissions to verify to grant -- access to the resource. To make it simple, the user must have one of the -- permission from the list. Each permission will refer to a specific permission -- controller. type Access_Rule (Count : Natural) is new Util.Refs.Ref_Entity with record Permissions : Permission_Index_Array (1 .. Count); end record; type Access_Rule_Access is access all Access_Rule; package Access_Rule_Refs is new Util.Refs.Indefinite_References (Element_Type => Access_Rule, Element_Access => Access_Rule_Access); subtype Access_Rule_Ref is Access_Rule_Refs.Ref; -- Find the access rule of the policy that matches the given URI. -- Returns the No_Rule value (disable access) if no rule is found. function Find_Access_Rule (Manager : in URL_Policy; URI : in String) return Access_Rule_Ref; -- The <b>Policy</b> defines the access rules that are applied on a given -- URL, set of URLs or files. type Policy is record Id : Natural; Pattern : GNAT.Regexp.Regexp; Rule : Access_Rule_Ref; end record; -- The <b>Policy_Vector</b> represents the whole permission policy. The order of -- policy in the list is important as policies can override each other. package Policy_Vector is new Ada.Containers.Vectors (Index_Type => Positive, Element_Type => Policy); package Rules_Maps is new Ada.Containers.Hashed_Maps (Key_Type => String_Ref, Element_Type => Access_Rule_Ref, Hash => Hash, Equivalent_Keys => Equivalent_Keys, "=" => Access_Rule_Refs."="); type Rules is new Util.Refs.Ref_Entity with record Map : Rules_Maps.Map; end record; type Rules_Access is access all Rules; package Rules_Ref is new Util.Refs.References (Rules, Rules_Access); package Atomic_Rules_Ref is new Rules_Ref.IR.Atomic; type Rules_Ref_Access is access Atomic_Rules_Ref.Atomic_Ref; type Controller_Access_Array_Access is access all Controller_Access_Array; type URL_Policy is new Security.Policies.Policy with record Cache : Rules_Ref_Access; Policies : Policy_Vector.Vector; Id : Natural := 0; Permissions : Util.Beans.Objects.Vectors.Vector; Patterns : Util.Beans.Objects.Vectors.Vector; end record; end Security.Policies.URLs;
30,145
ada
33
ytomino/drake
source/s-shaloc.ads
<reponame>ytomino/drake pragma License (Unrestricted); -- implementation unit package System.Shared_Locking is pragma Preelaborate; -- no-operation procedure Nop is null; type Enter_Handler is access procedure; pragma Favor_Top_Level (Enter_Handler); Enter_Hook : not null Enter_Handler := Nop'Access; procedure Enter; type Leave_Handler is access procedure; pragma Favor_Top_Level (Leave_Handler); Leave_Hook : not null Leave_Handler := Nop'Access; procedure Leave; end System.Shared_Locking;
30,146
ada
2
AdaCore/style_checker
testsuite/tests/NA17-007__first_line_comment/comment-ko-1.adb
<reponame>AdaCore/style_checker<filename>testsuite/tests/NA17-007__first_line_comment/comment-ko-1.adb -- Copyright (C) 2006, AdaCore -- with Ada.Command_Line; use Ada.Command_Line; with ALI; use ALI; with Csets; with Gnatvsn; with Hostparm; with Makeutl; use Makeutl; with MLib.Tgt; use MLib.Tgt; with Namet; use Namet; with Opt; use Opt; with Osint; use Osint; with Osint.M; use Osint.M; with Prj; use Prj; with Prj.Com; with Prj.Env; with Prj.Ext; with Prj.Pars; with Prj.Util; use Prj.Util; with Snames; with System; with Table; with Types; use Types; with GNAT.Directory_Operations; use GNAT.Directory_Operations; with GNAT.IO; use GNAT.IO; with GNAT.OS_Lib; use GNAT.OS_Lib; package body Clean is Initialized : Boolean := False; -- Set to True by the first call to Initialize. -- To avoid reinitialization of some packages. -- Suffixes of various files Assembly_Suffix : constant String := ".s"; ALI_Suffix : constant String := ".ali"; Tree_Suffix : constant String := ".adt"; Object_Suffix : constant String := Get_Object_Suffix.all; Debug_Suffix : String := ".dg"; -- Changed to "_dg" for VMS in the body of the package Repinfo_Suffix : String := ".rep"; -- Changed to "_rep" for VMS in the body of the package B_Start : String := "b~"; -- Prefix of binder generated file. -- Changed to "b$" for VMS in the body of the package. Object_Directory_Path : String_Access := null; -- The path name of the object directory, set with switch -D Do_Nothing : Boolean := False; -- Set to True when switch -n is specified. -- When True, no file is deleted. gnatclean only lists the files that -- would have been deleted if the switch -n had not been specified. File_Deleted : Boolean := False; -- Set to True if at least one file has been deleted Copyright_Displayed : Boolean := False; Usage_Displayed : Boolean := False; Project_File_Name : String_Access := null; Main_Project : Prj.Project_Id := Prj.No_Project; All_Projects : Boolean := False; -- Packages of project files where unknown attributes are errors. Naming_String : aliased String := "naming"; Builder_String : aliased String := "builder"; Compiler_String : aliased String := "compiler"; Binder_String : aliased String := "binder"; Linker_String : aliased String := "linker"; Gnatmake_Packages : aliased String_List := (Naming_String 'Access, Builder_String 'Access, Compiler_String 'Access, Binder_String 'Access, Linker_String 'Access); Packages_To_Check_By_Gnatmake : constant String_List_Access := Gnatmake_Packages'Access; package Processed_Projects is new Table.Table (Table_Component_Type => Project_Id, Table_Index_Type => Natural, Table_Low_Bound => 0, Table_Initial => 10, Table_Increment => 10, Table_Name => "Clean.Processed_Projects"); -- Table to keep track of what project files have been processed, when -- switch -r is specified. package Sources is new Table.Table (Table_Component_Type => File_Name_Type, Table_Index_Type => Natural, Table_Low_Bound => 0, Table_Initial => 10, Table_Increment => 10, Table_Name => "Clean.Processed_Projects"); -- Table to store all the source files of a library unit: spec, body and -- subunits, to detect .dg files and delete them. ---------------------------- -- Queue (Q) manipulation -- ---------------------------- procedure Init_Q; -- Must be called to initialize the Q procedure Insert_Q (Lib_File : File_Name_Type); -- If Lib_File is not marked, inserts it at the end of Q and mark it function Empty_Q return Boolean; -- Returns True if Q is empty. procedure Extract_From_Q (Lib_File : out File_Name_Type); -- Extracts the first element from the Q. Q_Front : Natural; -- Points to the first valid element in the Q. package Q is new Table.Table ( Table_Component_Type => File_Name_Type, Table_Index_Type => Natural, Table_Low_Bound => 0, Table_Initial => 4000, Table_Increment => 100, Table_Name => "Clean.Q"); -- This is the actual queue ----------------------------- -- Other local subprograms -- ----------------------------- procedure Add_Source_Dir (N : String); -- Call Add_Src_Search_Dir. -- Output one line when in verbose mode. procedure Add_Source_Directories is new Prj.Env.For_All_Source_Dirs (Action => Add_Source_Dir); procedure Add_Object_Dir (N : String); -- Call Add_Lib_Search_Dir. -- Output one line when in verbose mode. procedure Add_Object_Directories is new Prj.Env.For_All_Object_Dirs (Action => Add_Object_Dir); function ALI_File_Name (Source : Name_Id) return String; -- Returns the name of the ALI file corresponding to Source function Assembly_File_Name (Source : Name_Id) return String; -- Returns the assembly file name corresponding to Source procedure Clean_Archive (Project : Project_Id); -- Delete a global archive or a fake library project archive and the -- dependency file, if they exist. procedure Clean_Directory (Dir : Name_Id); -- Delete all regular files in a library directory or in a library -- interface dir. procedure Clean_Executables; -- Do the cleaning work when no project file is specified procedure Clean_Project (Project : Project_Id); -- Do the cleaning work when a project file is specified. -- This procedure calls itself recursively when there are several -- project files in the tree rooted at the main project file and switch -r -- has been specified. function Debug_File_Name (Source : Name_Id) return String; -- Name of the expanded source file corresponding to Source procedure Delete (In_Directory : String; File : String); -- Delete one file, or list the file name if switch -n is specified procedure Delete_Binder_Generated_Files (Dir : String; Source : Name_Id); -- Delete the binder generated file in directory Dir for Source, if they -- exist: for Unix these are b~<source>.ads, b~<source>.adb, -- b~<source>.ali and b~<source>.o. procedure Display_Copyright; -- Display the Copyright notice. -- If called several times, display the Copyright notice only the first -- time. procedure Initialize; -- Call the necessary package initializations function Object_File_Name (Source : Name_Id) return String; -- Returns the object file name corresponding to Source procedure Parse_Cmd_Line; -- Parse the command line function Repinfo_File_Name (Source : Name_Id) return String; -- Returns the repinfo file name corresponding to Source function Tree_File_Name (Source : Name_Id) return String; -- Returns the tree file name corresponding to Source function In_Extension_Chain (Of_Project : Project_Id; Prj : Project_Id) return Boolean; -- Returns True iff Prj is an extension of Of_Project or if Of_Project is -- an extension of Prj. procedure Usage; -- Display the usage. -- If called several times, the usage is displayed only the first time. -------------------- -- Add_Object_Dir -- -------------------- procedure Add_Object_Dir (N : String) is begin Add_Lib_Search_Dir (N); if Opt.Verbose_Mode then Put ("Adding object directory """); Put (N); Put ("""."); New_Line; end if; end Add_Object_Dir; -------------------- -- Add_Source_Dir -- -------------------- procedure Add_Source_Dir (N : String) is begin Add_Src_Search_Dir (N); if Opt.Verbose_Mode then Put ("Adding source directory """); Put (N); Put ("""."); New_Line; end if; end Add_Source_Dir; ------------------- -- ALI_File_Name -- ------------------- function ALI_File_Name (Source : Name_Id) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the ALI suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & ALI_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- ALI suffix. return Src & ALI_Suffix; end ALI_File_Name; ------------------------ -- Assembly_File_Name -- ------------------------ function Assembly_File_Name (Source : Name_Id) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the assembly suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Assembly_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- assembly suffix. return Src & Assembly_Suffix; end Assembly_File_Name; ------------------- -- Clean_Archive -- ------------------- procedure Clean_Archive (Project : Project_Id) is Current_Dir : constant Dir_Name_Str := Get_Current_Dir; Data : constant Project_Data := Projects.Table (Project); Archive_Name : constant String := "lib" & Get_Name_String (Data.Name) & '.' & Archive_Ext; -- The name of the archive file for this project Archive_Dep_Name : constant String := "lib" & Get_Name_String (Data.Name) & ".deps"; -- The name of the archive dependency file for this project Obj_Dir : constant String := Get_Name_String (Data.Object_Directory); begin Change_Dir (Obj_Dir); if Is_Regular_File (Archive_Name) then Delete (Obj_Dir, Archive_Name); end if; if Is_Regular_File (Archive_Dep_Name) then Delete (Obj_Dir, Archive_Dep_Name); end if; Change_Dir (Current_Dir); end Clean_Archive; --------------------- -- Clean_Directory -- --------------------- procedure Clean_Directory (Dir : Name_Id) is Directory : constant String := Get_Name_String (Dir); Current : constant Dir_Name_Str := Get_Current_Dir; Direc : Dir_Type; Name : String (1 .. 200); Last : Natural; procedure Set_Writable (Name : System.Address); pragma Import (C, Set_Writable, "__gnat_set_writable"); begin Change_Dir (Directory); Open (Direc, "."); -- For each regular file in the directory, if switch -n has not been -- specified, make it writable and delete the file. loop Read (Direc, Name, Last); exit when Last = 0; if Is_Regular_File (Name (1 .. Last)) then if not Do_Nothing then Name (Last + 1) := ASCII.NUL; Set_Writable (Name (1)'Address); end if; Delete (Directory, Name (1 .. Last)); end if; end loop; Close (Direc); -- Restore the initial working directory Change_Dir (Current); end Clean_Directory; ----------------------- -- Clean_Executables -- ----------------------- procedure Clean_Executables is Main_Source_File : File_Name_Type; -- Current main source Main_Lib_File : File_Name_Type; -- ALI file of the current main Lib_File : File_Name_Type; -- Current ALI file Full_Lib_File : File_Name_Type; -- Full name of the current ALI file Text : Text_Buffer_Ptr; The_ALI : ALI_Id; begin Init_Q; -- It does not really matter if there is or not an object file -- corresponding to an ALI file: if there is one, it will be deleted. Opt.Check_Object_Consistency := False; -- Proceed each executable one by one. Each source is marked as it is -- processed, so common sources between executables will not be -- processed several times. for N_File in 1 .. Osint.Number_Of_Files loop Main_Source_File := Next_Main_Source; Main_Lib_File := Osint.Lib_File_Name (Main_Source_File, Current_File_Index); Insert_Q (Main_Lib_File); while not Empty_Q loop Sources.Set_Last (0); Extract_From_Q (Lib_File); Full_Lib_File := Osint.Full_Lib_File_Name (Lib_File); -- If we have existing ALI file that is not read-only, process it if Full_Lib_File /= No_File and then not Is_Readonly_Library (Full_Lib_File) then Text := Read_Library_Info (Lib_File); if Text /= null then The_ALI := Scan_ALI (Lib_File, Text, Ignore_ED => False, Err => True); Free (Text); -- If no error was produced while loading this ALI file, -- insert into the queue all the unmarked withed sources. if The_ALI /= No_ALI_Id then for J in ALIs.Table (The_ALI).First_Unit .. ALIs.Table (The_ALI).Last_Unit loop Sources.Increment_Last; Sources.Table (Sources.Last) := ALI.Units.Table (J).Sfile; for K in ALI.Units.Table (J).First_With .. ALI.Units.Table (J).Last_With loop Insert_Q (Withs.Table (K).Afile); end loop; end loop; -- Look for subunits and put them in the Sources table for J in ALIs.Table (The_ALI).First_Sdep .. ALIs.Table (The_ALI).Last_Sdep loop if Sdep.Table (J).Subunit_Name /= No_Name then Sources.Increment_Last; Sources.Table (Sources.Last) := Sdep.Table (J).Sfile; end if; end loop; end if; end if; -- Now delete all existing files corresponding to this ALI file declare Obj_Dir : constant String := Dir_Name (Get_Name_String (Full_Lib_File)); Obj : constant String := Object_File_Name (Lib_File); Adt : constant String := Tree_File_Name (Lib_File); Asm : constant String := Assembly_File_Name (Lib_File); begin Delete (Obj_Dir, Get_Name_String (Lib_File)); if Is_Regular_File (Obj_Dir & Dir_Separator & Obj) then Delete (Obj_Dir, Obj); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Adt) then Delete (Obj_Dir, Adt); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Asm) then Delete (Obj_Dir, Asm); end if; -- Delete expanded source files (.dg) and/or repinfo files -- (.rep) if any for J in 1 .. Sources.Last loop declare Deb : constant String := Debug_File_Name (Sources.Table (J)); Rep : constant String := Repinfo_File_Name (Sources.Table (J)); begin if Is_Regular_File (Obj_Dir & Dir_Separator & Deb) then Delete (Obj_Dir, Deb); end if; if Is_Regular_File (Obj_Dir & Dir_Separator & Rep) then Delete (Obj_Dir, Rep); end if; end; end loop; end; end if; end loop; -- Delete the executable, if it exists, and the binder generated -- files, if any. if not Compile_Only then declare Source : constant Name_Id := Strip_Suffix (Main_Lib_File); Executable : constant String := Get_Name_String (Executable_Name (Source)); begin if Is_Regular_File (Executable) then Delete ("", Executable); end if; Delete_Binder_Generated_Files (Get_Current_Dir, Source); end; end if; end loop; end Clean_Executables; ------------------- -- Clean_Project -- ------------------- procedure Clean_Project (Project : Project_Id) is Main_Source_File : File_Name_Type; -- Name of executable on the command line without directory info Executable : Name_Id; -- Name of the executable file Current_Dir : constant Dir_Name_Str := Get_Current_Dir; Data : constant Project_Data := Projects.Table (Project); U_Data : Prj.Com.Unit_Data; File_Name1 : Name_Id; Index1 : Int; File_Name2 : Name_Id; Index2 : Int; Lib_File : File_Name_Type; Source_Id : Other_Source_Id; Source : Other_Source; Global_Archive : Boolean := False; use Prj.Com; begin -- Check that we don't specify executable on the command line for -- a main library project. if Project = Main_Project and then Osint.Number_Of_Files /= 0 and then Data.Library then Osint.Fail ("Cannot specify executable(s) for a Library Project File"); end if; if Verbose_Mode then Put ("Cleaning project """); Put (Get_Name_String (Data.Name)); Put_Line (""""); end if; -- Add project to the list of proceesed projects Processed_Projects.Increment_Last; Processed_Projects.Table (Processed_Projects.Last) := Project; if Data.Object_Directory /= No_Name then declare Obj_Dir : constant String := Get_Name_String (Data.Object_Directory); begin Change_Dir (Obj_Dir); -- First, deal with Ada -- Look through the units to find those that are either immediate -- sources or inherited sources of the project. if Data.Languages (Lang_Ada) then for Unit in 1 .. Prj.Com.Units.Last loop U_Data := Prj.Com.Units.Table (Unit); File_Name1 := No_Name; File_Name2 := No_Name; -- If either the spec or the body is a source of the -- project, check for the corresponding ALI file in the -- object directory. if In_Extension_Chain (U_Data.File_Names (Body_Part).Project, Project) or else In_Extension_Chain (U_Data.File_Names (Specification).Project, Project) then File_Name1 := U_Data.File_Names (Body_Part).Name; Index1 := U_Data.File_Names (Body_Part).Index; File_Name2 := U_Data.File_Names (Specification).Name; Index2 := U_Data.File_Names (Specification).Index; -- If there is no body file name, then there may be only -- a spec. if File_Name1 = No_Name then File_Name1 := File_Name2; Index1 := Index2; File_Name2 := No_Name; Index2 := 0; end if; end if; -- If there is either a spec or a body, look for files -- in the object directory. if File_Name1 /= No_Name then Lib_File := Osint.Lib_File_Name (File_Name1, Index1); declare Asm : constant String := Assembly_File_Name (Lib_File); ALI : constant String := ALI_File_Name (Lib_File); Obj : constant String := Object_File_Name (Lib_File); Adt : constant String := Tree_File_Name (Lib_File); Deb : constant String := Debug_File_Name (File_Name1); Rep : constant String := Repinfo_File_Name (File_Name1); Del : Boolean := True; begin -- If the ALI file exists and is read-only, no file -- is deleted. if Is_Regular_File (ALI) then if Is_Writable_File (ALI) then Delete (Obj_Dir, ALI); else Del := False; if Verbose_Mode then Put ('"'); Put (Obj_Dir); if Obj_Dir (Obj_Dir'Last) /= Dir_Separator then Put (Dir_Separator); end if; Put (ALI); Put_Line (""" is read-only"); end if; end if; end if; if Del then -- Object file if Is_Regular_File (Obj) then Delete (Obj_Dir, Obj); end if; -- Assembly file if Is_Regular_File (Asm) then Delete (Obj_Dir, Asm); end if; -- Tree file if Is_Regular_File (Adt) then Delete (Obj_Dir, Adt); end if; -- First expanded source file if Is_Regular_File (Deb) then Delete (Obj_Dir, Deb); end if; -- Repinfo file if Is_Regular_File (Rep) then Delete (Obj_Dir, Rep); end if; -- Second expanded source file if File_Name2 /= No_Name then declare Deb : constant String := Debug_File_Name (File_Name2); Rep : constant String := Repinfo_File_Name (File_Name2); begin if Is_Regular_File (Deb) then Delete (Obj_Dir, Deb); end if; if Is_Regular_File (Rep) then Delete (Obj_Dir, Rep); end if; end; end if; end if; end; end if; end loop; end if; -- Check if a global archive and it dependency file could have -- been created and, if they exist, delete them. if Project = Main_Project and then not Data.Library then Global_Archive := False; for Proj in 1 .. Projects.Last loop if Projects.Table (Proj).Other_Sources_Present then Global_Archive := True; exit; end if; end loop; if Global_Archive then Clean_Archive (Project); end if; end if; if Data.Other_Sources_Present then -- There is non-Ada code: delete the object files and -- the dependency files if they exist. Source_Id := Data.First_Other_Source; while Source_Id /= No_Other_Source loop Source := Other_Sources.Table (Source_Id); if Is_Regular_File (Get_Name_String (Source.Object_Name)) then Delete (Obj_Dir, Get_Name_String (Source.Object_Name)); end if; if Is_Regular_File (Get_Name_String (Source.Dep_Name)) then Delete (Obj_Dir, Get_Name_String (Source.Dep_Name)); end if; Source_Id := Source.Next; end loop; -- If it is a library with only non Ada sources, delete -- the fake archive and the dependency file, if they exist. if Data.Library and then not Data.Languages (Lang_Ada) then Clean_Archive (Project); end if; end if; end; end if; -- If this is a library project, clean the library directory, the -- interface copy dir and, for a Stand-Alone Library, the binder -- generated files of the library. -- The directories are cleaned only if switch -c is not specified. if Data.Library then if not Compile_Only then Clean_Directory (Data.Library_Dir); if Data.Library_Src_Dir /= No_Name and then Data.Library_Src_Dir /= Data.Library_Dir then Clean_Directory (Data.Library_Src_Dir); end if; end if; if Data.Standalone_Library and then Data.Object_Directory /= No_Name then Delete_Binder_Generated_Files (Get_Name_String (Data.Object_Directory), Data.Library_Name); end if; end if; if Verbose_Mode then New_Line; end if; -- If switch -r is specified, call Clean_Project recursively for the -- imported projects and the project being extended. if All_Projects then declare Imported : Project_List := Data.Imported_Projects; Element : Project_Element; Process : Boolean; begin -- For each imported project, call Clean_Project if the project -- has not been processed already. while Imported /= Empty_Project_List loop Element := Project_Lists.Table (Imported); Imported := Element.Next; Process := True; for J in Processed_Projects.First .. Processed_Projects.Last loop if Element.Project = Processed_Projects.Table (J) then Process := False; exit; end if; end loop; if Process then Clean_Project (Element.Project); end if; end loop; -- If this project extends another project, call Clean_Project for -- the project being extended. It is guaranteed that it has not -- called before, because no other project may import or extend -- this project. if Data.Extends /= No_Project then Clean_Project (Data.Extends); end if; end; end if; -- For the main project, delete the executables and the -- binder generated files. -- The executables are deleted only if switch -c is not specified. if Project = Main_Project and then Data.Exec_Directory /= No_Name then declare Exec_Dir : constant String := Get_Name_String (Data.Exec_Directory); begin Change_Dir (Exec_Dir); for N_File in 1 .. Osint.Number_Of_Files loop Main_Source_File := Next_Main_Source; if not Compile_Only then Executable := Executable_Of (Main_Project, Main_Source_File, Current_File_Index); if Is_Regular_File (Get_Name_String (Executable)) then Delete (Exec_Dir, Get_Name_String (Executable)); end if; end if; if Data.Object_Directory /= No_Name then Delete_Binder_Generated_Files (Get_Name_String (Data.Object_Directory), Strip_Suffix (Main_Source_File)); end if; end loop; end; end if; -- Change back to previous directory Change_Dir (Current_Dir); end Clean_Project; --------------------- -- Debug_File_Name -- --------------------- function Debug_File_Name (Source : Name_Id) return String is begin return Get_Name_String (Source) & Debug_Suffix; end Debug_File_Name; ------------ -- Delete -- ------------ procedure Delete (In_Directory : String; File : String) is Full_Name : String (1 .. In_Directory'Length + File'Length + 1); Last : Natural := 0; Success : Boolean; begin -- Indicate that at least one file is deleted or is to be deleted File_Deleted := True; -- Build the path name of the file to delete Last := In_Directory'Length; Full_Name (1 .. Last) := In_Directory; if Last > 0 and then Full_Name (Last) /= Directory_Separator then Last := Last + 1; Full_Name (Last) := Directory_Separator; end if; Full_Name (Last + 1 .. Last + File'Length) := File; Last := Last + File'Length; -- If switch -n was used, simply output the path name if Do_Nothing then Put_Line (Full_Name (1 .. Last)); -- Otherwise, delete the file else Delete_File (Full_Name (1 .. Last), Success); if not Success then Put ("Warning: """); Put (Full_Name (1 .. Last)); Put_Line (""" could not be deleted"); elsif Verbose_Mode or else not Quiet_Output then Put (""""); Put (Full_Name (1 .. Last)); Put_Line (""" has been deleted"); end if; end if; end Delete; ----------------------------------- -- Delete_Binder_Generated_Files -- ----------------------------------- procedure Delete_Binder_Generated_Files (Dir : String; Source : Name_Id) is Source_Name : constant String := Get_Name_String (Source); Current : constant String := Get_Current_Dir; Last : constant Positive := B_Start'Length + Source_Name'Length; File_Name : String (1 .. Last + 4); begin Change_Dir (Dir); -- Build the file name (before the extension) File_Name (1 .. B_Start'Length) := B_Start; File_Name (B_Start'Length + 1 .. Last) := Source_Name; -- Spec File_Name (Last + 1 .. Last + 4) := ".ads"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- Body File_Name (Last + 1 .. Last + 4) := ".adb"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- ALI file File_Name (Last + 1 .. Last + 4) := ".ali"; if Is_Regular_File (File_Name (1 .. Last + 4)) then Delete (Dir, File_Name (1 .. Last + 4)); end if; -- Object file File_Name (Last + 1 .. Last + Object_Suffix'Length) := Object_Suffix; if Is_Regular_File (File_Name (1 .. Last + Object_Suffix'Length)) then Delete (Dir, File_Name (1 .. Last + Object_Suffix'Length)); end if; -- Change back to previous directory Change_Dir (Current); end Delete_Binder_Generated_Files; ----------------------- -- Display_Copyright -- ----------------------- procedure Display_Copyright is begin if not Copyright_Displayed then Copyright_Displayed := True; Put_Line ("GNATCLEAN " & Gnatvsn.Gnat_Version_String & " Copyright 2003-2005 Free Software Foundation, Inc."); end if; end Display_Copyright; ------------- -- Empty_Q -- ------------- function Empty_Q return Boolean is begin return Q_Front >= Q.Last; end Empty_Q; -------------------- -- Extract_From_Q -- -------------------- procedure Extract_From_Q (Lib_File : out File_Name_Type) is Lib : constant File_Name_Type := Q.Table (Q_Front); begin Q_Front := Q_Front + 1; Lib_File := Lib; end Extract_From_Q; --------------- -- Gnatclean -- --------------- procedure Gnatclean is begin -- Do the necessary initializations Initialize; -- Parse the command line, getting the switches and the executable names Parse_Cmd_Line; if Verbose_Mode then Display_Copyright; end if; if Project_File_Name /= null then -- A project file was specified by a -P switch if Opt.Verbose_Mode then New_Line; Put ("Parsing Project File """); Put (Project_File_Name.all); Put_Line ("""."); New_Line; end if; -- Set the project parsing verbosity to whatever was specified -- by a possible -vP switch. Prj.Pars.Set_Verbosity (To => Prj.Com.Current_Verbosity); -- Parse the project file. If there is an error, Main_Project -- will still be No_Project. Prj.Pars.Parse (Project => Main_Project, Project_File_Name => Project_File_Name.all, Packages_To_Check => Packages_To_Check_By_Gnatmake, Process_Languages => All_Languages); if Main_Project = No_Project then Fail ("""" & Project_File_Name.all & """ processing failed"); end if; if Opt.Verbose_Mode then New_Line; Put ("Parsing of Project File """); Put (Project_File_Name.all); Put (""" is finished."); New_Line; end if; -- We add the source directories and the object directories -- to the search paths. Add_Source_Directories (Main_Project); Add_Object_Directories (Main_Project); end if; Osint.Add_Default_Search_Dirs; -- If a project file was specified, but no executable name, put all -- the mains of the project file (if any) as if there were on the -- command line. if Main_Project /= No_Project and then Osint.Number_Of_Files = 0 then declare Value : String_List_Id := Projects.Table (Main_Project).Mains; Main : String_Element; begin while Value /= Prj.Nil_String loop Main := String_Elements.Table (Value); Osint.Add_File (File_Name => Get_Name_String (Main.Value), Index => Main.Index); Value := Main.Next; end loop; end; end if; -- If neither a project file nor an executable were specified, -- output the usage and exit. if Main_Project = No_Project and then Osint.Number_Of_Files = 0 then Usage; return; end if; if Verbose_Mode then New_Line; end if; if Main_Project /= No_Project then -- If a project file has been specified, call Clean_Project with the -- project id of this project file, after resetting the list of -- processed projects. Processed_Projects.Init; Clean_Project (Main_Project); else -- If no project file has been specified, the work is done in -- Clean_Executables. Clean_Executables; end if; -- In verbose mode, if Delete has not been called, indicate that -- no file needs to be deleted. if Verbose_Mode and (not File_Deleted) then New_Line; if Do_Nothing then Put_Line ("No file needs to be deleted"); else Put_Line ("No file has been deleted"); end if; end if; end Gnatclean; ------------------------ -- In_Extension_Chain -- ------------------------ function In_Extension_Chain (Of_Project : Project_Id; Prj : Project_Id) return Boolean is Data : Project_Data; begin if Of_Project = Prj then return True; end if; Data := Projects.Table (Of_Project); while Data.Extends /= No_Project loop if Data.Extends = Prj then return True; end if; Data := Projects.Table (Data.Extends); end loop; Data := Projects.Table (Prj); while Data.Extends /= No_Project loop if Data.Extends = Of_Project then return True; end if; Data := Projects.Table (Data.Extends); end loop; return False; end In_Extension_Chain; ------------ -- Init_Q -- ------------ procedure Init_Q is begin Q_Front := Q.First; Q.Set_Last (Q.First); end Init_Q; ---------------- -- Initialize -- ---------------- procedure Initialize is begin if not Initialized then Initialized := True; -- Initialize some packages Csets.Initialize; Namet.Initialize; Snames.Initialize; Prj.Initialize; end if; -- Reset global variables Free (Object_Directory_Path); Do_Nothing := False; File_Deleted := False; Copyright_Displayed := False; Usage_Displayed := False; Free (Project_File_Name); Main_Project := Prj.No_Project; All_Projects := False; end Initialize; -------------- -- Insert_Q -- -------------- procedure Insert_Q (Lib_File : File_Name_Type) is begin -- Do not insert an empty name or an already marked source if Lib_File /= No_Name and then not Is_Marked (Lib_File) then Q.Table (Q.Last) := Lib_File; Q.Increment_Last; -- Mark the source that has been just added to the Q Mark (Lib_File); end if; end Insert_Q; ---------------------- -- Object_File_Name -- ---------------------- function Object_File_Name (Source : Name_Id) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the Object suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Object_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- ALI suffix. return Src & Object_Suffix; end Object_File_Name; -------------------- -- Parse_Cmd_Line -- -------------------- procedure Parse_Cmd_Line is Source_Index : Int := 0; Index : Positive := 1; Last : constant Natural := Argument_Count; begin while Index <= Last loop declare Arg : constant String := Argument (Index); procedure Bad_Argument; -- Signal bad argument ------------------ -- Bad_Argument -- ------------------ procedure Bad_Argument is begin Fail ("invalid argument """, Arg, """"); end Bad_Argument; begin if Arg'Length /= 0 then if Arg (1) = '-' then if Arg'Length = 1 then Bad_Argument; end if; case Arg (2) is when 'a' => if Arg'Length < 4 or else Arg (3) /= 'O' then Bad_Argument; end if; Add_Lib_Search_Dir (Arg (3 .. Arg'Last)); when 'c' => Compile_Only := True; when 'D' => if Object_Directory_Path /= null then Fail ("duplicate -D switch"); elsif Project_File_Name /= null then Fail ("-P and -D cannot be used simultaneously"); end if; if Arg'Length > 2 then declare Dir : constant String := Arg (3 .. Arg'Last); begin if not Is_Directory (Dir) then Fail (Dir, " is not a directory"); else Add_Lib_Search_Dir (Dir); end if; end; else if Index = Last then Fail ("no directory specified after -D"); end if; Index := Index + 1; declare Dir : constant String := Argument (Index); begin if not Is_Directory (Dir) then Fail (Dir, " is not a directory"); else Add_Lib_Search_Dir (Dir); end if; end; end if; when 'F' => Full_Path_Name_For_Brief_Errors := True; when 'h' => Usage; when 'i' => if Arg'Length = 2 then Bad_Argument; end if; Source_Index := 0; for J in 3 .. Arg'Last loop if Arg (J) not in '0' .. '9' then Bad_Argument; end if; Source_Index := (20 * Source_Index) + (Character'Pos (Arg (J)) - Character'Pos ('0')); end loop; when 'I' => if Arg = "-I-" then Opt.Look_In_Primary_Dir := False; else if Arg'Length = 2 then Bad_Argument; end if; Add_Lib_Search_Dir (Arg (3 .. Arg'Last)); end if; when 'n' => Do_Nothing := True; when 'P' => if Project_File_Name /= null then Fail ("multiple -P switches"); elsif Object_Directory_Path /= null then Fail ("-D and -P cannot be used simultaneously"); end if; if Arg'Length > 2 then declare Prj : constant String := Arg (3 .. Arg'Last); begin if Prj'Length > 1 and then Prj (Prj'First) = '=' then Project_File_Name := new String' (Prj (Prj'First + 1 .. Prj'Last)); else Project_File_Name := new String'(Prj); end if; end; else if Index = Last then Fail ("no project specified after -P"); end if; Index := Index + 1; Project_File_Name := new String'(Argument (Index)); end if; when 'q' => Quiet_Output := True; when 'r' => All_Projects := True; when 'v' => if Arg = "-v" then Verbose_Mode := True; elsif Arg = "-vP0" then Prj.Com.Current_Verbosity := Prj.Default; elsif Arg = "-vP1" then Prj.Com.Current_Verbosity := Prj.Medium; elsif Arg = "-vP2" then Prj.Com.Current_Verbosity := Prj.High; else Bad_Argument; end if; when 'X' => if Arg'Length = 2 then Bad_Argument; end if; declare Ext_Asgn : constant String := Arg (3 .. Arg'Last); Start : Positive := Ext_Asgn'First; Stop : Natural := Ext_Asgn'Last; Equal_Pos : Natural; OK : Boolean := True; begin if Ext_Asgn (Start) = '"' then if Ext_Asgn (Stop) = '"' then Start := Start + 1; Stop := Stop - 1; else OK := False; end if; end if; Equal_Pos := Start; while Equal_Pos <= Stop and then Ext_Asgn (Equal_Pos) /= '=' loop Equal_Pos := Equal_Pos + 1; end loop; if Equal_Pos = Start or else Equal_Pos > Stop then OK := False; end if; if OK then Prj.Ext.Add (External_Name => Ext_Asgn (Start .. Equal_Pos - 1), Value => Ext_Asgn (Equal_Pos + 1 .. Stop)); else Fail ("illegal external assignment '", Ext_Asgn, "'"); end if; end; when others => Bad_Argument; end case; else Add_File (Arg, Source_Index); end if; end if; end; Index := Index + 1; end loop; end Parse_Cmd_Line; ----------------------- -- Repinfo_File_Name -- ----------------------- function Repinfo_File_Name (Source : Name_Id) return String is begin return Get_Name_String (Source) & Repinfo_Suffix; end Repinfo_File_Name; -------------------- -- Tree_File_Name -- -------------------- function Tree_File_Name (Source : Name_Id) return String is Src : constant String := Get_Name_String (Source); begin -- If the source name has an extension, then replace it with -- the tree suffix. for Index in reverse Src'First + 1 .. Src'Last loop if Src (Index) = '.' then return Src (Src'First .. Index - 1) & Tree_Suffix; end if; end loop; -- If there is no dot, or if it is the first character, just add the -- tree suffix. return Src & Tree_Suffix; end Tree_File_Name; ----------- -- Usage -- ----------- procedure Usage is begin if not Usage_Displayed then Usage_Displayed := True; Display_Copyright; Put_Line ("Usage: gnatclean [switches] {[-innn] name}"); New_Line; Put_Line (" names is one or more file names from which " & "the .adb or .ads suffix may be omitted"); Put_Line (" names may be omitted if -P<project> is specified"); New_Line; Put_Line (" -c Only delete compiler generated files"); Put_Line (" -D dir Specify dir as the object library"); Put_Line (" -F Full project path name " & "in brief error messages"); Put_Line (" -h Display this message"); Put_Line (" -innn Index of unit in source for following names"); Put_Line (" -n Nothing to do: only list files to delete"); Put_Line (" -Pproj Use GNAT Project File proj"); Put_Line (" -q Be quiet/terse"); Put_Line (" -r Clean all projects recursively"); Put_Line (" -v Verbose mode"); Put_Line (" -vPx Specify verbosity when parsing " & "GNAT Project Files"); Put_Line (" -Xnm=val Specify an external reference " & "for GNAT Project Files"); New_Line; Put_Line (" -aOdir Specify ALI/object files search path"); Put_Line (" -Idir Like -aOdir"); Put_Line (" -I- Don't look for source/library files " & "in the default directory"); New_Line; end if; end Usage; begin if Hostparm.OpenVMS then Debug_Suffix (Debug_Suffix'First) := '_'; Repinfo_Suffix (Repinfo_Suffix'First) := '_'; B_Start (B_Start'Last) := '$'; end if; end Clean;
30,147
ada
1
bracke/websitegenerator
src/generator.adb
<filename>src/generator.adb pragma Ada_2012; with Ada.Directories; with Ada.Text_IO; with Ada.Strings.Fixed; with Ada.Characters.Handling; with Generator.Frontmatter; with Generator.Rssfeed; with Generator.Sitemap; with Ada.Text_IO.Text_Streams; with Ada.Streams; with Ada.Streams.Stream_IO; with Ada.Numerics.Discrete_Random; with Progress_Indicators.Spinners; with Version; with Globals; package body Generator is use Ada.Directories; use Ada.Text_IO; use Progress_Indicators.Spinners; package CH renames Ada.Characters.Handling; package CC renames Ada.Characters.Conversions; package DIR renames Ada.Directories; subtype Die is Integer range 1 .. 256; subtype Dice is Integer range 2 * Die'First .. 2 * Die'Last; package Random_Integer is new Ada.Numerics.Discrete_Random (Die); use Random_Integer; function "<" (Left, Right : Document) return Boolean is begin return Left.Basename < Right.Basename; end "<"; function Find (List : Document_Container.List; Name : XString) return Cursor is begin for aDocument in List.Iterate loop if Element (aDocument).Basename = Name then return aDocument; end if; end loop; return No_Element; end Find; ------------------ -- Process_File -- ------------------ procedure Process_File (List : out Document_Container.List; Filepath : String; Targetpath : String; Linkpath : String) is Extension : constant String := CH.To_Upper (DIR.Extension (Filepath)); begin if Extension = "MD" or else Extension = "MARKDOWN" then List.Append ( Generator.Frontmatter.Read (Filepath, Targetpath, Linkpath) ); declare Filein : Ada.Streams.Stream_IO.File_Type; Fileout : Ada.Text_IO.File_Type; begin null; -- Ada.Streams.Stream_IO.Open -- (Filein, Ada.Streams.Stream_IO.In_File, Filepath); -- Ada.Text_IO.Create -- (Fileout, Ada.Text_IO.Out_File,Targetpath); -- Renderer.Set_Output -- (Ada.Text_IO.Text_Streams.Stream(Fileout)); -- Generator.Markdown.To_HTML (Filein); end; elsif Extension = "HTML" or else Extension = "HTM" then List.Append ( Generator.Frontmatter.Read (Filepath, Targetpath, Linkpath) ); elsif Extension = "TMPLT" then List.Append ( Generator.Frontmatter.Read (Filepath, Targetpath, Linkpath) ); else if DIR.Exists (Targetpath) then DIR.Delete_File (Targetpath); end if; Copy_File (Filepath, Targetpath); end if; end Process_File; ----------------------- -- Process_Directory -- ----------------------- procedure Process_Directory (List : out Document_Container.List; Source_Directory : String; Target_Directory : String; LinkpathIn : String) is Linkpath : constant String := Ada.Strings.Fixed.Trim (LinkpathIn, Slash, Slash); Dir : Directory_Entry_Type; Dir_Search : Search_Type; begin if Exists (Source_Directory) then Start_Search (Search => Dir_Search, Directory => Source_Directory, Pattern => "*"); loop Get_Next_Entry (Dir_Search, Dir); if Simple_Name (Dir) /= "." and then Simple_Name (Dir) /= ".." then declare Name : constant String := Simple_Name (Dir); Fullname : constant String := Full_Name (Dir); Targetname : constant String := Compose (Target_Directory, Name); Basename : constant String := Base_Name (Fullname); Process : constant Boolean := Name /= "." and Name /= ".." and Ada.Strings.Fixed.Head (Name, 1) /= "_"; begin if Process then if Debug then Ada.Text_IO.Put_Line (Fullname); end if; if Kind (Dir) = Ordinary_File then Process_File ( List, Fullname, Targetname, Linkpath & "/" & Basename & ".html"); else if not Exists (Targetname) then Create_Directory (Targetname); end if; Process_Directory ( List, Fullname, Targetname, Linkpath & "/" & Name); end if; end if; end; end if; exit when not More_Entries (Dir_Search); end loop; End_Search (Dir_Search); end if; end Process_Directory; function Get_Nav_Links ( Document : Cursor; List : Document_Container.List) return Translate_Set is Set : Translate_Set; P : Cursor := Previous (Document); N : Cursor := Next (Document); begin if P = No_Element then P := Last (List); end if; Insert (Set, Assoc ("previouslink", CC.To_String (To_String (Element (P).Linkpath)))); if N = No_Element then N := First (List); end if; Insert (Set, Assoc ("nextlink", CC.To_String (To_String (Element (N).Linkpath)))); return Set; end Get_Nav_Links; procedure Process_Documents ( List : Document_Container.List; Set : Translate_Set; Layoutfolder : String; Source_Directory : String; Targetpath : String) is begin for Document in List.Iterate loop if Debug then Ada.Text_IO.Put_Line ( CC.To_String ( To_String ( Element (Document).Targetpath)) ); end if; if Length (Element (Document).Layout) > 0 then declare Name : constant String := CC.To_String ( To_String (Element (Document).Layout) ); Base_Name : constant String := DIR.Base_Name (Name); Extension : constant String := DIR.Extension (Name); Layoutfile : constant String := DIR.Compose (Layoutfolder, Base_Name, Extension); Combined_Set : Translate_Set; Filename : constant String := CC.To_String ( To_String (Element (Document).Targetpath) ); begin Insert (Combined_Set, Set); Insert (Combined_Set, Element (Document).T); Insert (Combined_Set, Get_Nav_Links (Document, List)); if DIR.Exists (Layoutfile) then declare F : File_Type; Template : constant String := Templates_Parser.Parse (Layoutfile, Combined_Set); begin if Exists (Filename) then Delete_File (Filename); end if; Create (F, Mode => Out_File, Name => Filename); Put (F, Template); Close (F); end; else Ada.Text_IO.Put_Line ("Layoutfile " & Layoutfile & " does not exist"); end if; end; else Ada.Text_IO.Put_Line ("Layout for " & CC.To_String (To_String ( Element (Document).Filepath)) & " is not defined" ); end if; end loop; end Process_Documents; function Create_Vector ( List : Document_Container.List; Prefix : String) return Translate_Set is Set : Translate_Set; Pagepath : Tag; Pagename : Tag; Pageexcerpt : Tag; begin for Document of List loop declare Name : constant String := Read_From_Set (Document.T, "title"); Base_Name : constant String := CC.To_String (To_String (Document.Basename)); Excerpt : constant String := Read_From_Set (Document.T, "title"); begin Pagepath := Pagepath & Ada.Strings.Fixed.Trim ( CC.To_String (To_String (Document.Linkpath)), Slash, Slash); Pageexcerpt := Pageexcerpt & Excerpt; if Name'Length > 0 then Pagename := Pagename & Name; else Pagename := Pagename & Base_Name; end if; end; end loop; Insert (Set, Assoc (Prefix & "path", Pagepath)); Insert (Set, Assoc (Prefix & "name", Pagename)); Insert (Set, Assoc (Prefix & "excerpt", Pageexcerpt)); return Set; end Create_Vector; function Read_From_Set ( Set : Translate_Set; Token : String) return String is Assoc : constant Association := Get (Set, Token); begin if Assoc /= Null_Association then return Get (Assoc); end if; return ""; end Read_From_Set; ----------- -- Start -- ----------- procedure Start ( Source_Directory : String; Target_Directory : String) is Config_Path : constant String := DIR.Compose (Source_Directory, Globals.Site_Configuration_Name); Layoutfolder : constant String := Compose (Source_Directory, Globals.Layout_Folder_Name); Blog_Source_Directory : constant String := Compose (Source_Directory, Globals.Posts_Source_Folder_Name); Blog_Target_Directory : constant String := Compose (Target_Directory, Globals.Blog_Target_Folder_Name); Documents : Document_Container.List; Posts : Document_Container.List; Set : Translate_Set; Site_Set : Translate_Set; G : Random_Integer.Generator; D : Dice; Indicator : Spinner := Make; Index: Cursor := No_Element; begin Ada.Text_IO.Put (Value (Indicator)); Site_Set := Null_Set; if Exists (Config_Path) then Generator.Frontmatter.Read_Content (Config_Path, Site_Set); else Ada.Text_IO.Put_Line ("No site configuration found at " & Config_Path); end if; -- Copy static files and directories and create List of pages. Process_Directory (Documents, Source_Directory, Target_Directory, ""); Sort (Documents); Index := Find (Documents, To_XString ("index")); if Index /= No_Element then Prepend (Documents, Element (Index)); Delete (Documents, Index); end if; -- Process blog if Exists (Blog_Source_Directory) then -- Copy static files and directories and create List of pages. if not Exists (Blog_Target_Directory) then Create_Directory (Blog_Target_Directory); end if; Process_Directory (Posts, Blog_Source_Directory, Blog_Target_Directory, Globals.Blog_Target_Folder_Name); end if; Sort (Posts); Insert (Set, Create_Vector (Documents, "page")); Insert (Set, Create_Vector (Posts, "post")); Insert (Set, Site_Set); Insert (Set, Assoc ("meta_generator_link", Version.Link)); Insert (Set, Assoc ("meta_generator", Version.Name)); Insert (Set, Assoc ("meta_generator_version", Version.Current)); Reset (G); D := Random (G); Insert (Set, Assoc ("meta_cachebuster", Ada.Strings.Fixed.Trim (D'Image, Ada.Strings.Both))); -- Create RSS feed Insert (Set, Assoc ("atomfeedurl", Generator.Rssfeed.Create (Posts, Target_Directory, Site_Set)) ); -- Create RSS feed Insert (Set, Assoc ("sitemapurl", Generator.Sitemap.Create (Posts, Documents, Target_Directory, Site_Set)) ); -- Process non-static files Process_Documents (Documents, Set, Layoutfolder, Source_Directory, Target_Directory); Process_Documents (Posts, Set, Layoutfolder, Blog_Source_Directory, Blog_Target_Directory); Disable_All; Ada.Text_IO.Put (Value (Indicator)); end Start; end Generator;
30,148
ada
1
LaudateCorpus1/RosettaCodeData
Task/Averages-Mode/Ada/averages-mode-2.ada
with Ada.Containers.Indefinite_Vectors; package body Mode is -- map Count to Elements package Count_Vectors is new Ada.Containers.Indefinite_Vectors (Element_Type => Element_Array, Index_Type => Positive); procedure Add (To : in out Count_Vectors.Vector; Item : Element_Type) is use type Count_Vectors.Cursor; Position : Count_Vectors.Cursor := To.First; Found : Boolean := False; begin while not Found and then Position /= Count_Vectors.No_Element loop declare Elements : Element_Array := Count_Vectors.Element (Position); begin for I in Elements'Range loop if Elements (I) = Item then Found := True; end if; end loop; end; if not Found then Position := Count_Vectors.Next (Position); end if; end loop; if Position /= Count_Vectors.No_Element then -- element found, remove it and insert to next count declare New_Position : Count_Vectors.Cursor := Count_Vectors.Next (Position); begin -- remove from old position declare Old_Elements : Element_Array := Count_Vectors.Element (Position); New_Elements : Element_Array (1 .. Old_Elements'Length - 1); New_Index : Positive := New_Elements'First; begin for I in Old_Elements'Range loop if Old_Elements (I) /= Item then New_Elements (New_Index) := Old_Elements (I); New_Index := New_Index + 1; end if; end loop; To.Replace_Element (Position, New_Elements); end; -- new position not already there? if New_Position = Count_Vectors.No_Element then declare New_Array : Element_Array (1 .. 1) := (1 => Item); begin To.Append (New_Array); end; else -- add to new position declare Old_Elements : Element_Array := Count_Vectors.Element (New_Position); New_Elements : Element_Array (1 .. Old_Elements'Length + 1); begin New_Elements (1 .. Old_Elements'Length) := Old_Elements; New_Elements (New_Elements'Last) := Item; To.Replace_Element (New_Position, New_Elements); end; end if; end; else -- element not found, add to count 1 Position := To.First; if Position = Count_Vectors.No_Element then declare New_Array : Element_Array (1 .. 1) := (1 => Item); begin To.Append (New_Array); end; else declare Old_Elements : Element_Array := Count_Vectors.Element (Position); New_Elements : Element_Array (1 .. Old_Elements'Length + 1); begin New_Elements (1 .. Old_Elements'Length) := Old_Elements; New_Elements (New_Elements'Last) := Item; To.Replace_Element (Position, New_Elements); end; end if; end if; end Add; function Get_Mode (Set : Element_Array) return Element_Array is Counts : Count_Vectors.Vector; begin for I in Set'Range loop Add (Counts, Set (I)); end loop; return Counts.Last_Element; end Get_Mode; end Mode;
30,149
ada
3
vasil-sd/ada-tlsf
tlsf/src/old/tlsf-mem_block_size.ads
<reponame>vasil-sd/ada-tlsf<gh_stars>1-10 with TLSF.Config; use TLSF.Config; private package TLSF.Mem_Block_Size with SPARK_Mode is type Size is mod 2 ** Max_Block_Size_Log2 with Size => Max_Block_Size_Log2; use type SSE.Storage_Count; use type SSE.Integer_Address; function Align ( Sz : Size) return Size with Pre => Sz <= Size'Last - Align_Size, Post => Sz <= Align'Result and Align'Result mod Align_Size = 0; function Align ( Sz : SSE.Storage_Count ) return Size with Pre => Sz <= SSE.Storage_Count (Size'Last - Align_Size), Post => (Sz <= SSE.Storage_Count (Align'Result) and Align'Result mod Align_Size = 0); function Align ( Addr : System.Address) return System.Address with Pre => SSE.To_Integer (Addr) <= SSE.Integer_Address'Last - Align_Size, Post => (SSE.To_Integer (Addr) <= SSE.To_Integer (Align'Result) and SSE.To_Integer (Align'Result) mod Align_Size = 0); function Align ( Sc : SSE.Storage_Count) return SSE.Storage_Count with Pre => Sc <= SSE.Storage_Count'Last - Align_Size, Post => Sc <= Align'Result and Align'Result mod Align_Size = 0; function "+" (A : System.Address; B : Size) return System.Address; function "-" (A : System.Address; B : Size) return System.Address; end TLSF.Mem_Block_Size;
30,150
ada
0
djamal2727/Main-Bearing-Analytical-Model
Validation/pyFrame3DD-master/gcc-master/gcc/ada/exp_disp.adb
<reponame>djamal2727/Main-Bearing-Analytical-Model ------------------------------------------------------------------------------ -- -- -- GNAT COMPILER COMPONENTS -- -- -- -- E X P _ D I S P -- -- -- -- B o d y -- -- -- -- Copyright (C) 1992-2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING3. If not, go to -- -- http://www.gnu.org/licenses for a complete copy of the license. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Atree; use Atree; with Checks; use Checks; with Debug; use Debug; with Einfo; use Einfo; with Elists; use Elists; with Errout; use Errout; with Expander; use Expander; with Exp_Atag; use Exp_Atag; with Exp_Ch6; use Exp_Ch6; with Exp_CG; use Exp_CG; with Exp_Dbug; use Exp_Dbug; with Exp_Tss; use Exp_Tss; with Exp_Util; use Exp_Util; with Freeze; use Freeze; with Ghost; use Ghost; with Itypes; use Itypes; with Layout; use Layout; with Nlists; use Nlists; with Nmake; use Nmake; with Namet; use Namet; with Opt; use Opt; with Output; use Output; with Restrict; use Restrict; with Rident; use Rident; with Rtsfind; use Rtsfind; with Sem; use Sem; with Sem_Aux; use Sem_Aux; with Sem_Ch6; use Sem_Ch6; with Sem_Ch7; use Sem_Ch7; with Sem_Ch8; use Sem_Ch8; with Sem_Disp; use Sem_Disp; with Sem_Eval; use Sem_Eval; with Sem_Res; use Sem_Res; with Sem_Type; use Sem_Type; with Sem_Util; use Sem_Util; with Sinfo; use Sinfo; with Sinput; use Sinput; with Snames; use Snames; with Stand; use Stand; with Stringt; use Stringt; with SCIL_LL; use SCIL_LL; with Tbuild; use Tbuild; package body Exp_Disp is ----------------------- -- Local Subprograms -- ----------------------- function Default_Prim_Op_Position (E : Entity_Id) return Uint; -- Ada 2005 (AI-251): Returns the fixed position in the dispatch table -- of the default primitive operations. function Has_DT (Typ : Entity_Id) return Boolean; pragma Inline (Has_DT); -- Returns true if we generate a dispatch table for tagged type Typ function Is_Predefined_Dispatching_Alias (Prim : Entity_Id) return Boolean; -- Returns true if Prim is not a predefined dispatching primitive but it is -- an alias of a predefined dispatching primitive (i.e. through a renaming) function New_Value (From : Node_Id) return Node_Id; -- From is the original Expression. New_Value is equivalent to a call to -- Duplicate_Subexpr with an explicit dereference when From is an access -- parameter. function Original_View_In_Visible_Part (Typ : Entity_Id) return Boolean; -- Check if the type has a private view or if the public view appears in -- the visible part of a package spec. function Prim_Op_Kind (Prim : Entity_Id; Typ : Entity_Id) return Node_Id; -- Ada 2005 (AI-345): Determine the primitive operation kind of Prim -- according to its type Typ. Return a reference to an RE_Prim_Op_Kind -- enumeration value. function Tagged_Kind (T : Entity_Id) return Node_Id; -- Ada 2005 (AI-345): Determine the tagged kind of T and return a reference -- to an RE_Tagged_Kind enumeration value. ---------------------- -- Apply_Tag_Checks -- ---------------------- procedure Apply_Tag_Checks (Call_Node : Node_Id) is Loc : constant Source_Ptr := Sloc (Call_Node); Ctrl_Arg : constant Node_Id := Controlling_Argument (Call_Node); Ctrl_Typ : constant Entity_Id := Base_Type (Etype (Ctrl_Arg)); Param_List : constant List_Id := Parameter_Associations (Call_Node); Subp : Entity_Id; CW_Typ : Entity_Id; Param : Node_Id; Typ : Entity_Id; Eq_Prim_Op : Entity_Id := Empty; begin if No_Run_Time_Mode then Error_Msg_CRT ("tagged types", Call_Node); return; end if; -- Apply_Tag_Checks is called directly from the semantics, so we -- need a check to see whether expansion is active before proceeding. -- In addition, there is no need to expand the call when compiling -- under restriction No_Dispatching_Calls; the semantic analyzer has -- previously notified the violation of this restriction. if not Expander_Active or else Restriction_Active (No_Dispatching_Calls) then return; end if; -- Set subprogram. If this is an inherited operation that was -- overridden, the body that is being called is its alias. Subp := Entity (Name (Call_Node)); if Present (Alias (Subp)) and then Is_Inherited_Operation (Subp) and then No (DTC_Entity (Subp)) then Subp := Alias (Subp); end if; -- Definition of the class-wide type and the tagged type -- If the controlling argument is itself a tag rather than a tagged -- object, then use the class-wide type associated with the subprogram's -- controlling type. This case can occur when a call to an inherited -- primitive has an actual that originated from a default parameter -- given by a tag-indeterminate call and when there is no other -- controlling argument providing the tag (AI-239 requires dispatching). -- This capability of dispatching directly by tag is also needed by the -- implementation of AI-260 (for the generic dispatching constructors). if Ctrl_Typ = RTE (RE_Tag) or else (RTE_Available (RE_Interface_Tag) and then Ctrl_Typ = RTE (RE_Interface_Tag)) then CW_Typ := Class_Wide_Type (Find_Dispatching_Type (Subp)); -- Class_Wide_Type is applied to the expressions used to initialize -- CW_Typ, to ensure that CW_Typ always denotes a class-wide type, since -- there are cases where the controlling type is resolved to a specific -- type (such as for designated types of arguments such as CW'Access). elsif Is_Access_Type (Ctrl_Typ) then CW_Typ := Class_Wide_Type (Designated_Type (Ctrl_Typ)); else CW_Typ := Class_Wide_Type (Ctrl_Typ); end if; Typ := Find_Specific_Type (CW_Typ); if not Is_Limited_Type (Typ) then Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq); end if; -- Dispatching call to C++ primitive if Is_CPP_Class (Typ) then null; -- Dispatching call to Ada primitive elsif Present (Param_List) then -- Generate the Tag checks when appropriate Param := First_Actual (Call_Node); while Present (Param) loop -- No tag check with itself if Param = Ctrl_Arg then null; -- No tag check for parameter whose type is neither tagged nor -- access to tagged (for access parameters) elsif No (Find_Controlling_Arg (Param)) then null; -- No tag check for function dispatching on result if the -- Tag given by the context is this one elsif Find_Controlling_Arg (Param) = Ctrl_Arg then null; -- "=" is the only dispatching operation allowed to get operands -- with incompatible tags (it just returns false). We use -- Duplicate_Subexpr_Move_Checks instead of calling Relocate_Node -- because the value will be duplicated to check the tags. elsif Subp = Eq_Prim_Op then null; -- No check in presence of suppress flags elsif Tag_Checks_Suppressed (Etype (Param)) or else (Is_Access_Type (Etype (Param)) and then Tag_Checks_Suppressed (Designated_Type (Etype (Param)))) then null; -- Optimization: no tag checks if the parameters are identical elsif Is_Entity_Name (Param) and then Is_Entity_Name (Ctrl_Arg) and then Entity (Param) = Entity (Ctrl_Arg) then null; -- Now we need to generate the Tag check else -- Generate code for tag equality check -- Perhaps should have Checks.Apply_Tag_Equality_Check??? Insert_Action (Ctrl_Arg, Make_Implicit_If_Statement (Call_Node, Condition => Make_Op_Ne (Loc, Left_Opnd => Make_Selected_Component (Loc, Prefix => New_Value (Ctrl_Arg), Selector_Name => New_Occurrence_Of (First_Tag_Component (Typ), Loc)), Right_Opnd => Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (Typ, New_Value (Param)), Selector_Name => New_Occurrence_Of (First_Tag_Component (Typ), Loc))), Then_Statements => New_List (New_Constraint_Error (Loc)))); end if; Next_Actual (Param); end loop; end if; end Apply_Tag_Checks; ------------------------ -- Building_Static_DT -- ------------------------ function Building_Static_DT (Typ : Entity_Id) return Boolean is Root_Typ : Entity_Id := Root_Type (Typ); Static_DT : Boolean; begin -- Handle private types if Present (Full_View (Root_Typ)) then Root_Typ := Full_View (Root_Typ); end if; Static_DT := Building_Static_Dispatch_Tables and then Is_Library_Level_Tagged_Type (Typ) -- If the type is derived from a CPP class we cannot statically -- build the dispatch tables because we must inherit primitives -- from the CPP side. and then not Is_CPP_Class (Root_Typ); if not Static_DT then Check_Restriction (Static_Dispatch_Tables, Typ); end if; return Static_DT; end Building_Static_DT; ---------------------------------- -- Building_Static_Secondary_DT -- ---------------------------------- function Building_Static_Secondary_DT (Typ : Entity_Id) return Boolean is Full_Typ : Entity_Id := Typ; Root_Typ : Entity_Id := Root_Type (Typ); Static_DT : Boolean; begin -- Handle private types if Present (Full_View (Typ)) then Full_Typ := Full_View (Typ); end if; if Present (Full_View (Root_Typ)) then Root_Typ := Full_View (Root_Typ); end if; Static_DT := Building_Static_DT (Full_Typ) and then not Is_Interface (Full_Typ) and then Has_Interfaces (Full_Typ) and then (Full_Typ = Root_Typ or else not Is_Variable_Size_Record (Etype (Full_Typ))); if not Static_DT and then not Is_Interface (Full_Typ) and then Has_Interfaces (Full_Typ) then Check_Restriction (Static_Dispatch_Tables, Typ); end if; return Static_DT; end Building_Static_Secondary_DT; ---------------------------------- -- Build_Static_Dispatch_Tables -- ---------------------------------- procedure Build_Static_Dispatch_Tables (N : Entity_Id) is Target_List : List_Id; procedure Build_Dispatch_Tables (List : List_Id); -- Build the static dispatch table of tagged types found in the list of -- declarations. The generated nodes are added at the end of Target_List procedure Build_Package_Dispatch_Tables (N : Node_Id); -- Build static dispatch tables associated with package declaration N --------------------------- -- Build_Dispatch_Tables -- --------------------------- procedure Build_Dispatch_Tables (List : List_Id) is D : Node_Id; begin D := First (List); while Present (D) loop -- Handle nested packages and package bodies recursively. The -- generated code is placed on the Target_List established for -- the enclosing compilation unit. if Nkind (D) = N_Package_Declaration then Build_Package_Dispatch_Tables (D); elsif Nkind (D) = N_Package_Body then Build_Dispatch_Tables (Declarations (D)); elsif Nkind (D) = N_Package_Body_Stub and then Present (Library_Unit (D)) then Build_Dispatch_Tables (Declarations (Proper_Body (Unit (Library_Unit (D))))); -- Handle full type declarations and derivations of library level -- tagged types elsif Nkind (D) in N_Full_Type_Declaration | N_Derived_Type_Definition and then Is_Library_Level_Tagged_Type (Defining_Entity (D)) and then Ekind (Defining_Entity (D)) /= E_Record_Subtype and then not Is_Private_Type (Defining_Entity (D)) then -- We do not generate dispatch tables for the internal types -- created for a type extension with unknown discriminants -- The needed information is shared with the source type, -- See Expand_N_Record_Extension. if Is_Underlying_Record_View (Defining_Entity (D)) or else (not Comes_From_Source (Defining_Entity (D)) and then Has_Unknown_Discriminants (Etype (Defining_Entity (D))) and then not Comes_From_Source (First_Subtype (Defining_Entity (D)))) then null; else Insert_List_After_And_Analyze (Last (Target_List), Make_DT (Defining_Entity (D))); end if; -- Handle private types of library level tagged types. We must -- exchange the private and full-view to ensure the correct -- expansion. If the full view is a synchronized type ignore -- the type because the table will be built for the corresponding -- record type, that has its own declaration. elsif (Nkind (D) = N_Private_Type_Declaration or else Nkind (D) = N_Private_Extension_Declaration) and then Present (Full_View (Defining_Entity (D))) then declare E1 : constant Entity_Id := Defining_Entity (D); E2 : constant Entity_Id := Full_View (E1); begin if Is_Library_Level_Tagged_Type (E2) and then Ekind (E2) /= E_Record_Subtype and then not Is_Concurrent_Type (E2) then Exchange_Declarations (E1); Insert_List_After_And_Analyze (Last (Target_List), Make_DT (E1)); Exchange_Declarations (E2); end if; end; end if; Next (D); end loop; end Build_Dispatch_Tables; ----------------------------------- -- Build_Package_Dispatch_Tables -- ----------------------------------- procedure Build_Package_Dispatch_Tables (N : Node_Id) is Spec : constant Node_Id := Specification (N); Id : constant Entity_Id := Defining_Entity (N); Vis_Decls : constant List_Id := Visible_Declarations (Spec); Priv_Decls : constant List_Id := Private_Declarations (Spec); begin Push_Scope (Id); if Present (Priv_Decls) then Build_Dispatch_Tables (Vis_Decls); Build_Dispatch_Tables (Priv_Decls); elsif Present (Vis_Decls) then Build_Dispatch_Tables (Vis_Decls); end if; Pop_Scope; end Build_Package_Dispatch_Tables; -- Start of processing for Build_Static_Dispatch_Tables begin if not Expander_Active or else not Tagged_Type_Expansion then return; end if; if Nkind (N) = N_Package_Declaration then declare Spec : constant Node_Id := Specification (N); Vis_Decls : constant List_Id := Visible_Declarations (Spec); Priv_Decls : constant List_Id := Private_Declarations (Spec); begin if Present (Priv_Decls) and then Is_Non_Empty_List (Priv_Decls) then Target_List := Priv_Decls; elsif not Present (Vis_Decls) then Target_List := New_List; Set_Private_Declarations (Spec, Target_List); else Target_List := Vis_Decls; end if; Build_Package_Dispatch_Tables (N); end; else pragma Assert (Nkind (N) = N_Package_Body); Target_List := Declarations (N); Build_Dispatch_Tables (Target_List); end if; end Build_Static_Dispatch_Tables; ------------------------------ -- Convert_Tag_To_Interface -- ------------------------------ function Convert_Tag_To_Interface (Typ : Entity_Id; Expr : Node_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Expr); Anon_Type : Entity_Id; Result : Node_Id; begin pragma Assert (Is_Class_Wide_Type (Typ) and then Is_Interface (Typ) and then ((Nkind (Expr) = N_Selected_Component and then Is_Tag (Entity (Selector_Name (Expr)))) or else (Nkind (Expr) = N_Function_Call and then RTE_Available (RE_Displace) and then Entity (Name (Expr)) = RTE (RE_Displace)))); Anon_Type := Create_Itype (E_Anonymous_Access_Type, Expr); Set_Directly_Designated_Type (Anon_Type, Typ); Set_Etype (Anon_Type, Anon_Type); Set_Can_Never_Be_Null (Anon_Type); -- Decorate the size and alignment attributes of the anonymous access -- type, as required by the back end. Layout_Type (Anon_Type); if Nkind (Expr) = N_Selected_Component and then Is_Tag (Entity (Selector_Name (Expr))) then Result := Make_Explicit_Dereference (Loc, Unchecked_Convert_To (Anon_Type, Make_Attribute_Reference (Loc, Prefix => Expr, Attribute_Name => Name_Address))); else Result := Make_Explicit_Dereference (Loc, Unchecked_Convert_To (Anon_Type, Expr)); end if; return Result; end Convert_Tag_To_Interface; ------------------- -- CPP_Num_Prims -- ------------------- function CPP_Num_Prims (Typ : Entity_Id) return Nat is CPP_Typ : Entity_Id; Tag_Comp : Entity_Id; begin if not Is_Tagged_Type (Typ) or else not Is_CPP_Class (Root_Type (Typ)) then return 0; else CPP_Typ := Enclosing_CPP_Parent (Typ); Tag_Comp := First_Tag_Component (CPP_Typ); -- If number of primitives already set in the tag component, use it if Present (Tag_Comp) and then DT_Entry_Count (Tag_Comp) /= No_Uint then return UI_To_Int (DT_Entry_Count (Tag_Comp)); -- Otherwise, count the primitives of the enclosing CPP type else declare Count : Nat := 0; Elmt : Elmt_Id; begin Elmt := First_Elmt (Primitive_Operations (CPP_Typ)); while Present (Elmt) loop Count := Count + 1; Next_Elmt (Elmt); end loop; return Count; end; end if; end if; end CPP_Num_Prims; ------------------------------ -- Default_Prim_Op_Position -- ------------------------------ function Default_Prim_Op_Position (E : Entity_Id) return Uint is TSS_Name : TSS_Name_Type; begin Get_Name_String (Chars (E)); TSS_Name := TSS_Name_Type (Name_Buffer (Name_Len - TSS_Name'Length + 1 .. Name_Len)); if Chars (E) = Name_uSize then return Uint_1; elsif TSS_Name = TSS_Stream_Read then return Uint_2; elsif TSS_Name = TSS_Stream_Write then return Uint_3; elsif TSS_Name = TSS_Stream_Input then return Uint_4; elsif TSS_Name = TSS_Stream_Output then return Uint_5; elsif Chars (E) = Name_Op_Eq then return Uint_6; elsif Chars (E) = Name_uAssign then return Uint_7; elsif TSS_Name = TSS_Deep_Adjust then return Uint_8; elsif TSS_Name = TSS_Deep_Finalize then return Uint_9; elsif TSS_Name = TSS_Put_Image then return Uint_10; -- In VM targets unconditionally allow obtaining the position associated -- with predefined interface primitives since in these platforms any -- tagged type has these primitives. elsif Ada_Version >= Ada_2005 or else not Tagged_Type_Expansion then if Chars (E) = Name_uDisp_Asynchronous_Select then return Uint_11; elsif Chars (E) = Name_uDisp_Conditional_Select then return Uint_12; elsif Chars (E) = Name_uDisp_Get_Prim_Op_Kind then return Uint_13; elsif Chars (E) = Name_uDisp_Get_Task_Id then return Uint_14; elsif Chars (E) = Name_uDisp_Requeue then return Uint_15; elsif Chars (E) = Name_uDisp_Timed_Select then return Uint_16; end if; end if; raise Program_Error; end Default_Prim_Op_Position; ---------------------- -- Elab_Flag_Needed -- ---------------------- function Elab_Flag_Needed (Typ : Entity_Id) return Boolean is begin return Ada_Version >= Ada_2005 and then not Is_Interface (Typ) and then Has_Interfaces (Typ) and then not Building_Static_DT (Typ); end Elab_Flag_Needed; ----------------------------- -- Expand_Dispatching_Call -- ----------------------------- procedure Expand_Dispatching_Call (Call_Node : Node_Id) is Loc : constant Source_Ptr := Sloc (Call_Node); Call_Typ : constant Entity_Id := Etype (Call_Node); Ctrl_Arg : constant Node_Id := Controlling_Argument (Call_Node); Ctrl_Typ : constant Entity_Id := Base_Type (Etype (Ctrl_Arg)); Param_List : constant List_Id := Parameter_Associations (Call_Node); Subp : Entity_Id; CW_Typ : Entity_Id; New_Call : Node_Id; New_Call_Name : Node_Id; New_Params : List_Id := No_List; Param : Node_Id; Res_Typ : Entity_Id; Subp_Ptr_Typ : Entity_Id; Subp_Typ : Entity_Id; Typ : Entity_Id; Eq_Prim_Op : Entity_Id := Empty; Controlling_Tag : Node_Id; procedure Build_Class_Wide_Check; -- If the denoted subprogram has a class-wide precondition, generate a -- check using that precondition before the dispatching call, because -- this is the only class-wide precondition that applies to the call. function New_Value (From : Node_Id) return Node_Id; -- From is the original Expression. New_Value is equivalent to a call -- to Duplicate_Subexpr with an explicit dereference when From is an -- access parameter. ---------------------------- -- Build_Class_Wide_Check -- ---------------------------- procedure Build_Class_Wide_Check is function Replace_Formals (N : Node_Id) return Traverse_Result; -- Replace occurrences of the formals of the subprogram by the -- corresponding actuals in the call, given that this check is -- performed outside of the body of the subprogram. -- If the dispatching call appears in the same scope as the -- declaration of the dispatching subprogram (for example in -- the expression of a local expression function), the spec -- has not been analyzed yet, in which case we use the Chars -- field to recognize intended occurrences of the formals. --------------------- -- Replace_Formals -- --------------------- function Replace_Formals (N : Node_Id) return Traverse_Result is A : Node_Id; F : Entity_Id; begin if Is_Entity_Name (N) then F := First_Formal (Subp); A := First_Actual (Call_Node); if Present (Entity (N)) and then Is_Formal (Entity (N)) then while Present (F) loop if F = Entity (N) then Rewrite (N, New_Copy_Tree (A)); -- If the formal is class-wide, and thus not a -- controlling argument, preserve its type because -- it may appear in a nested call with a class-wide -- parameter. if Is_Class_Wide_Type (Etype (F)) then Set_Etype (N, Etype (F)); -- Conversely, if this is a controlling argument -- (in a dispatching call in the condition) that is a -- dereference, the source is an access-to-class-wide -- type, so preserve the dispatching nature of the -- call in the rewritten condition. elsif Nkind (Parent (N)) = N_Explicit_Dereference and then Is_Controlling_Actual (Parent (N)) then Set_Controlling_Argument (Parent (Parent (N)), Parent (N)); end if; exit; end if; Next_Formal (F); Next_Actual (A); end loop; -- If the node is not analyzed, recognize occurrences of a -- formal by name, as would be done when resolving the aspect -- expression in the context of the subprogram. elsif not Analyzed (N) and then Nkind (N) = N_Identifier and then No (Entity (N)) then while Present (F) loop if Chars (N) = Chars (F) then Rewrite (N, New_Copy_Tree (A)); return Skip; end if; Next_Formal (F); Next_Actual (A); end loop; end if; end if; return OK; end Replace_Formals; procedure Update is new Traverse_Proc (Replace_Formals); -- Local variables Str_Loc : constant String := Build_Location_String (Loc); Cond : Node_Id; Msg : Node_Id; Prec : Node_Id; -- Start of processing for Build_Class_Wide_Check begin -- Locate class-wide precondition, if any if Present (Contract (Subp)) and then Present (Pre_Post_Conditions (Contract (Subp))) then Prec := Pre_Post_Conditions (Contract (Subp)); while Present (Prec) loop exit when Pragma_Name (Prec) = Name_Precondition and then Class_Present (Prec); Prec := Next_Pragma (Prec); end loop; if No (Prec) or else Is_Ignored (Prec) then return; end if; -- The expression for the precondition is analyzed within the -- generated pragma. The message text is the last parameter of -- the generated pragma, indicating source of precondition. Cond := New_Copy_Tree (Expression (First (Pragma_Argument_Associations (Prec)))); Update (Cond); -- Build message indicating the failed precondition and the -- dispatching call that caused it. Msg := Expression (Last (Pragma_Argument_Associations (Prec))); Name_Len := 0; Append (Global_Name_Buffer, Strval (Msg)); Append (Global_Name_Buffer, " in dispatching call at "); Append (Global_Name_Buffer, Str_Loc); Msg := Make_String_Literal (Loc, Name_Buffer (1 .. Name_Len)); Insert_Action (Call_Node, Make_If_Statement (Loc, Condition => Make_Op_Not (Loc, Cond), Then_Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Raise_Assert_Failure), Loc), Parameter_Associations => New_List (Msg))))); end if; end Build_Class_Wide_Check; --------------- -- New_Value -- --------------- function New_Value (From : Node_Id) return Node_Id is Res : constant Node_Id := Duplicate_Subexpr (From); begin if Is_Access_Type (Etype (From)) then return Make_Explicit_Dereference (Sloc (From), Prefix => Res); else return Res; end if; end New_Value; -- Local variables New_Node : Node_Id; SCIL_Node : Node_Id := Empty; SCIL_Related_Node : Node_Id := Call_Node; -- Start of processing for Expand_Dispatching_Call begin if No_Run_Time_Mode then Error_Msg_CRT ("tagged types", Call_Node); return; end if; -- Expand_Dispatching_Call is called directly from the semantics, so we -- only proceed if the expander is active. if not Expander_Active -- And there is no need to expand the call if we are compiling under -- restriction No_Dispatching_Calls; the semantic analyzer has -- previously notified the violation of this restriction. or else Restriction_Active (No_Dispatching_Calls) -- No action needed if the dispatching call has been already expanded or else Is_Expanded_Dispatching_Call (Name (Call_Node)) then return; end if; -- Set subprogram. If this is an inherited operation that was -- overridden, the body that is being called is its alias. Subp := Entity (Name (Call_Node)); if Present (Alias (Subp)) and then Is_Inherited_Operation (Subp) and then No (DTC_Entity (Subp)) then Subp := Alias (Subp); end if; Build_Class_Wide_Check; -- Definition of the class-wide type and the tagged type -- If the controlling argument is itself a tag rather than a tagged -- object, then use the class-wide type associated with the subprogram's -- controlling type. This case can occur when a call to an inherited -- primitive has an actual that originated from a default parameter -- given by a tag-indeterminate call and when there is no other -- controlling argument providing the tag (AI-239 requires dispatching). -- This capability of dispatching directly by tag is also needed by the -- implementation of AI-260 (for the generic dispatching constructors). if Ctrl_Typ = RTE (RE_Tag) or else (RTE_Available (RE_Interface_Tag) and then Ctrl_Typ = RTE (RE_Interface_Tag)) then CW_Typ := Class_Wide_Type (Find_Dispatching_Type (Subp)); -- Class_Wide_Type is applied to the expressions used to initialize -- CW_Typ, to ensure that CW_Typ always denotes a class-wide type, since -- there are cases where the controlling type is resolved to a specific -- type (such as for designated types of arguments such as CW'Access). elsif Is_Access_Type (Ctrl_Typ) then CW_Typ := Class_Wide_Type (Designated_Type (Ctrl_Typ)); else CW_Typ := Class_Wide_Type (Ctrl_Typ); end if; Typ := Find_Specific_Type (CW_Typ); if not Is_Limited_Type (Typ) then Eq_Prim_Op := Find_Prim_Op (Typ, Name_Op_Eq); end if; -- Dispatching call to C++ primitive. Create a new parameter list -- with no tag checks. New_Params := New_List; if Is_CPP_Class (Typ) then Param := First_Actual (Call_Node); while Present (Param) loop Append_To (New_Params, Relocate_Node (Param)); Next_Actual (Param); end loop; -- Dispatching call to Ada primitive elsif Present (Param_List) then Apply_Tag_Checks (Call_Node); Param := First_Actual (Call_Node); while Present (Param) loop -- Cases in which we may have generated run-time checks. Note that -- we strip any qualification from Param before comparing with the -- already-stripped controlling argument. if Unqualify (Param) = Ctrl_Arg or else Subp = Eq_Prim_Op then Append_To (New_Params, Duplicate_Subexpr_Move_Checks (Param)); elsif Nkind (Parent (Param)) /= N_Parameter_Association or else not Is_Accessibility_Actual (Parent (Param)) then Append_To (New_Params, Relocate_Node (Param)); end if; Next_Actual (Param); end loop; end if; -- Generate the appropriate subprogram pointer type if Etype (Subp) = Typ then Res_Typ := CW_Typ; else Res_Typ := Etype (Subp); end if; Subp_Typ := Create_Itype (E_Subprogram_Type, Call_Node); Subp_Ptr_Typ := Create_Itype (E_Access_Subprogram_Type, Call_Node); Set_Etype (Subp_Typ, Res_Typ); Set_Returns_By_Ref (Subp_Typ, Returns_By_Ref (Subp)); Set_Convention (Subp_Typ, Convention (Subp)); -- Notify gigi that the designated type is a dispatching primitive Set_Is_Dispatch_Table_Entity (Subp_Typ); -- Create a new list of parameters which is a copy of the old formal -- list including the creation of a new set of matching entities. declare Old_Formal : Entity_Id := First_Formal (Subp); New_Formal : Entity_Id; Last_Formal : Entity_Id := Empty; begin if Present (Old_Formal) then New_Formal := New_Copy (Old_Formal); Set_First_Entity (Subp_Typ, New_Formal); Param := First_Actual (Call_Node); loop Set_Scope (New_Formal, Subp_Typ); -- Change all the controlling argument types to be class-wide -- to avoid a recursion in dispatching. if Is_Controlling_Formal (New_Formal) then Set_Etype (New_Formal, Etype (Param)); end if; -- If the type of the formal is an itype, there was code here -- introduced in 1998 in revision 1.46, to create a new itype -- by copy. This seems useless, and in fact leads to semantic -- errors when the itype is the completion of a type derived -- from a private type. Last_Formal := New_Formal; Next_Formal (Old_Formal); exit when No (Old_Formal); Link_Entities (New_Formal, New_Copy (Old_Formal)); Next_Entity (New_Formal); Next_Actual (Param); end loop; Unlink_Next_Entity (New_Formal); Set_Last_Entity (Subp_Typ, Last_Formal); end if; -- Now that the explicit formals have been duplicated, any extra -- formals needed by the subprogram must be duplicated; we know -- that extra formals are available because they were added when -- the tagged type was frozen (see Expand_Freeze_Record_Type). pragma Assert (Is_Frozen (Typ)); -- Warning: The addition of the extra formals cannot be performed -- here invoking Create_Extra_Formals since we must ensure that all -- the extra formals of the pointer type and the target subprogram -- match (and for functions that return a tagged type the profile of -- the built subprogram type always returns a class-wide type, which -- may affect the addition of some extra formals). if Present (Last_Formal) and then Present (Extra_Formal (Last_Formal)) then Old_Formal := Extra_Formal (Last_Formal); New_Formal := New_Copy (Old_Formal); Set_Scope (New_Formal, Subp_Typ); Set_Extra_Formal (Last_Formal, New_Formal); Set_Extra_Formals (Subp_Typ, New_Formal); if Ekind (Subp) = E_Function and then Present (Extra_Accessibility_Of_Result (Subp)) and then Extra_Accessibility_Of_Result (Subp) = Old_Formal then Set_Extra_Accessibility_Of_Result (Subp_Typ, New_Formal); end if; Old_Formal := Extra_Formal (Old_Formal); while Present (Old_Formal) loop Set_Extra_Formal (New_Formal, New_Copy (Old_Formal)); New_Formal := Extra_Formal (New_Formal); Set_Scope (New_Formal, Subp_Typ); if Ekind (Subp) = E_Function and then Present (Extra_Accessibility_Of_Result (Subp)) and then Extra_Accessibility_Of_Result (Subp) = Old_Formal then Set_Extra_Accessibility_Of_Result (Subp_Typ, New_Formal); end if; Old_Formal := Extra_Formal (Old_Formal); end loop; end if; end; -- Complete description of pointer type, including size information, as -- must be done with itypes to prevent order-of-elaboration anomalies -- in gigi. Set_Etype (Subp_Ptr_Typ, Subp_Ptr_Typ); Set_Directly_Designated_Type (Subp_Ptr_Typ, Subp_Typ); Set_Convention (Subp_Ptr_Typ, Convention (Subp_Typ)); Layout_Type (Subp_Ptr_Typ); -- If the controlling argument is a value of type Ada.Tag or an abstract -- interface class-wide type then use it directly. Otherwise, the tag -- must be extracted from the controlling object. if Ctrl_Typ = RTE (RE_Tag) or else (RTE_Available (RE_Interface_Tag) and then Ctrl_Typ = RTE (RE_Interface_Tag)) then Controlling_Tag := Duplicate_Subexpr (Ctrl_Arg); -- Extract the tag from an unchecked type conversion. Done to avoid -- the expansion of additional code just to obtain the value of such -- tag because the current management of interface type conversions -- generates in some cases this unchecked type conversion with the -- tag of the object (see Expand_Interface_Conversion). elsif Nkind (Ctrl_Arg) = N_Unchecked_Type_Conversion and then (Etype (Expression (Ctrl_Arg)) = RTE (RE_Tag) or else (RTE_Available (RE_Interface_Tag) and then Etype (Expression (Ctrl_Arg)) = RTE (RE_Interface_Tag))) then Controlling_Tag := Duplicate_Subexpr (Expression (Ctrl_Arg)); -- Ada 2005 (AI-251): Abstract interface class-wide type elsif Is_Interface (Ctrl_Typ) and then Is_Class_Wide_Type (Ctrl_Typ) then Controlling_Tag := Duplicate_Subexpr (Ctrl_Arg); elsif Is_Access_Type (Ctrl_Typ) then Controlling_Tag := Make_Selected_Component (Loc, Prefix => Make_Explicit_Dereference (Loc, Duplicate_Subexpr_Move_Checks (Ctrl_Arg)), Selector_Name => New_Occurrence_Of (DTC_Entity (Subp), Loc)); else Controlling_Tag := Make_Selected_Component (Loc, Prefix => Duplicate_Subexpr_Move_Checks (Ctrl_Arg), Selector_Name => New_Occurrence_Of (DTC_Entity (Subp), Loc)); end if; -- Handle dispatching calls to predefined primitives if Is_Predefined_Dispatching_Operation (Subp) or else Is_Predefined_Dispatching_Alias (Subp) then Build_Get_Predefined_Prim_Op_Address (Loc, Tag_Node => Controlling_Tag, Position => DT_Position (Subp), New_Node => New_Node); -- Handle dispatching calls to user-defined primitives else Build_Get_Prim_Op_Address (Loc, Typ => Underlying_Type (Find_Dispatching_Type (Subp)), Tag_Node => Controlling_Tag, Position => DT_Position (Subp), New_Node => New_Node); end if; New_Call_Name := Unchecked_Convert_To (Subp_Ptr_Typ, New_Node); -- Generate the SCIL node for this dispatching call. Done now because -- attribute SCIL_Controlling_Tag must be set after the new call name -- is built to reference the nodes that will see the SCIL backend -- (because Build_Get_Prim_Op_Address generates an unchecked type -- conversion which relocates the controlling tag node). if Generate_SCIL then SCIL_Node := Make_SCIL_Dispatching_Call (Sloc (Call_Node)); Set_SCIL_Entity (SCIL_Node, Typ); Set_SCIL_Target_Prim (SCIL_Node, Subp); -- Common case: the controlling tag is the tag of an object -- (for example, obj.tag) if Nkind (Controlling_Tag) = N_Selected_Component then Set_SCIL_Controlling_Tag (SCIL_Node, Controlling_Tag); -- Handle renaming of selected component elsif Nkind (Controlling_Tag) = N_Identifier and then Nkind (Parent (Entity (Controlling_Tag))) = N_Object_Renaming_Declaration and then Nkind (Name (Parent (Entity (Controlling_Tag)))) = N_Selected_Component then Set_SCIL_Controlling_Tag (SCIL_Node, Name (Parent (Entity (Controlling_Tag)))); -- If the controlling tag is an identifier, the SCIL node references -- the corresponding object or parameter declaration elsif Nkind (Controlling_Tag) = N_Identifier and then Nkind (Parent (Entity (Controlling_Tag))) in N_Object_Declaration | N_Parameter_Specification then Set_SCIL_Controlling_Tag (SCIL_Node, Parent (Entity (Controlling_Tag))); -- If the controlling tag is a dereference, the SCIL node references -- the corresponding object or parameter declaration elsif Nkind (Controlling_Tag) = N_Explicit_Dereference and then Nkind (Prefix (Controlling_Tag)) = N_Identifier and then Nkind (Parent (Entity (Prefix (Controlling_Tag)))) in N_Object_Declaration | N_Parameter_Specification then Set_SCIL_Controlling_Tag (SCIL_Node, Parent (Entity (Prefix (Controlling_Tag)))); -- For a direct reference of the tag of the type the SCIL node -- references the internal object declaration containing the tag -- of the type. elsif Nkind (Controlling_Tag) = N_Attribute_Reference and then Attribute_Name (Controlling_Tag) = Name_Tag then Set_SCIL_Controlling_Tag (SCIL_Node, Parent (Node (First_Elmt (Access_Disp_Table (Entity (Prefix (Controlling_Tag))))))); -- Interfaces are not supported. For now we leave the SCIL node -- decorated with the Controlling_Tag. More work needed here??? elsif Is_Interface (Etype (Controlling_Tag)) then Set_SCIL_Controlling_Tag (SCIL_Node, Controlling_Tag); else pragma Assert (False); null; end if; end if; if Nkind (Call_Node) = N_Function_Call then New_Call := Make_Function_Call (Loc, Name => New_Call_Name, Parameter_Associations => New_Params); -- If this is a dispatching "=", we must first compare the tags so -- we generate: x.tag = y.tag and then x = y if Subp = Eq_Prim_Op then Param := First_Actual (Call_Node); New_Call := Make_And_Then (Loc, Left_Opnd => Make_Op_Eq (Loc, Left_Opnd => Make_Selected_Component (Loc, Prefix => New_Value (Param), Selector_Name => New_Occurrence_Of (First_Tag_Component (Typ), Loc)), Right_Opnd => Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (Typ, New_Value (Next_Actual (Param))), Selector_Name => New_Occurrence_Of (First_Tag_Component (Typ), Loc))), Right_Opnd => New_Call); SCIL_Related_Node := Right_Opnd (New_Call); end if; else New_Call := Make_Procedure_Call_Statement (Loc, Name => New_Call_Name, Parameter_Associations => New_Params); end if; -- Register the dispatching call in the call graph nodes table Register_CG_Node (Call_Node); Rewrite (Call_Node, New_Call); -- Associate the SCIL node of this dispatching call if Generate_SCIL then Set_SCIL_Node (SCIL_Related_Node, SCIL_Node); end if; -- Suppress all checks during the analysis of the expanded code to avoid -- the generation of spurious warnings under ZFP run-time. Analyze_And_Resolve (Call_Node, Call_Typ, Suppress => All_Checks); end Expand_Dispatching_Call; --------------------------------- -- Expand_Interface_Conversion -- --------------------------------- procedure Expand_Interface_Conversion (N : Node_Id) is function Underlying_Record_Type (Typ : Entity_Id) return Entity_Id; -- Return the underlying record type of Typ ---------------------------- -- Underlying_Record_Type -- ---------------------------- function Underlying_Record_Type (Typ : Entity_Id) return Entity_Id is E : Entity_Id := Typ; begin -- Handle access types if Is_Access_Type (E) then E := Directly_Designated_Type (E); end if; -- Handle class-wide types. This conversion can appear explicitly in -- the source code. Example: I'Class (Obj) if Is_Class_Wide_Type (E) then E := Root_Type (E); end if; -- If the target type is a tagged synchronized type, the dispatch -- table info is in the corresponding record type. if Is_Concurrent_Type (E) then E := Corresponding_Record_Type (E); end if; -- Handle private types E := Underlying_Type (E); -- Handle subtypes return Base_Type (E); end Underlying_Record_Type; -- Local variables Loc : constant Source_Ptr := Sloc (N); Etyp : constant Entity_Id := Etype (N); Operand : constant Node_Id := Expression (N); Operand_Typ : Entity_Id := Etype (Operand); Func : Node_Id; Iface_Typ : constant Entity_Id := Underlying_Record_Type (Etype (N)); Iface_Tag : Entity_Id; Is_Static : Boolean; -- Start of processing for Expand_Interface_Conversion begin -- Freeze the entity associated with the target interface to have -- available the attribute Access_Disp_Table. Freeze_Before (N, Iface_Typ); -- Ada 2005 (AI-345): Handle synchronized interface type derivations if Is_Concurrent_Type (Operand_Typ) then Operand_Typ := Base_Type (Corresponding_Record_Type (Operand_Typ)); end if; -- No displacement of the pointer to the object needed when the type of -- the operand is not an interface type and the interface is one of -- its parent types (since they share the primary dispatch table). declare Opnd : Entity_Id := Operand_Typ; begin if Is_Access_Type (Opnd) then Opnd := Designated_Type (Opnd); end if; Opnd := Underlying_Record_Type (Opnd); if not Is_Interface (Opnd) and then Is_Ancestor (Iface_Typ, Opnd, Use_Full_View => True) then return; end if; -- When the type of the operand and the target interface type match, -- it is generally safe to skip generating code to displace the -- pointer to the object to reference the secondary dispatch table -- associated with the target interface type. The exception to this -- general rule is when the underlying object of the type conversion -- is an object built by means of a dispatching constructor (since in -- such case the expansion of the constructor call is a direct call -- to an object primitive, i.e. without thunks, and the expansion of -- the constructor call adds an explicit conversion to the target -- interface type to force the displacement of the pointer to the -- object to reference the corresponding secondary dispatch table -- (cf. Make_DT and Expand_Dispatching_Constructor_Call)). -- At this stage we cannot identify whether the underlying object is -- a BIP object and hence we cannot skip generating the code to try -- displacing the pointer to the object. However, under configurable -- runtime it is safe to skip generating code to displace the pointer -- to the object, because generic dispatching constructors are not -- supported. if Opnd = Iface_Typ and then not RTE_Available (RE_Displace) then return; end if; end; -- Evaluate if we can statically displace the pointer to the object declare Opnd_Typ : constant Node_Id := Underlying_Record_Type (Operand_Typ); begin Is_Static := not Is_Interface (Opnd_Typ) and then Interface_Present_In_Ancestor (Typ => Opnd_Typ, Iface => Iface_Typ) and then (Etype (Opnd_Typ) = Opnd_Typ or else not Is_Variable_Size_Record (Etype (Opnd_Typ))); end; if not Tagged_Type_Expansion then return; -- A static conversion to an interface type that is not class-wide is -- curious but legal if the interface operation is a null procedure. -- If the operation is abstract it will be rejected later. elsif Is_Static and then Is_Interface (Etype (N)) and then not Is_Class_Wide_Type (Etype (N)) and then Comes_From_Source (N) then Rewrite (N, Unchecked_Convert_To (Etype (N), N)); Analyze (N); return; end if; if not Is_Static then -- Give error if configurable run-time and Displace not available if not RTE_Available (RE_Displace) then Error_Msg_CRT ("dynamic interface conversion", N); return; end if; -- Handle conversion of access-to-class-wide interface types. Target -- can be an access to an object or an access to another class-wide -- interface (see -1- and -2- in the following example): -- type Iface1_Ref is access all Iface1'Class; -- type Iface2_Ref is access all Iface1'Class; -- Acc1 : Iface1_Ref := new ... -- Obj : Obj_Ref := Obj_Ref (Acc); -- 1 -- Acc2 : Iface2_Ref := Iface2_Ref (Acc); -- 2 if Is_Access_Type (Operand_Typ) then Rewrite (N, Unchecked_Convert_To (Etype (N), Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Displace), Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (RTE (RE_Address), Relocate_Node (Expression (N))), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Iface_Typ))), Loc))))); Analyze (N); return; end if; Rewrite (N, Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Displace), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => Relocate_Node (Expression (N)), Attribute_Name => Name_Address), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Iface_Typ))), Loc)))); Analyze (N); -- If target is a class-wide interface, change the type of the data -- returned by IW_Convert to indicate this is a dispatching call. declare New_Itype : Entity_Id; begin New_Itype := Create_Itype (E_Anonymous_Access_Type, N); Set_Etype (New_Itype, New_Itype); Set_Directly_Designated_Type (New_Itype, Etyp); Rewrite (N, Make_Explicit_Dereference (Loc, Prefix => Unchecked_Convert_To (New_Itype, Relocate_Node (N)))); Analyze (N); Freeze_Itype (New_Itype, N); return; end; end if; Iface_Tag := Find_Interface_Tag (Operand_Typ, Iface_Typ); pragma Assert (Present (Iface_Tag)); -- Keep separate access types to interfaces because one internal -- function is used to handle the null value (see following comments) if not Is_Access_Type (Etype (N)) then -- Statically displace the pointer to the object to reference the -- component containing the secondary dispatch table. Rewrite (N, Convert_Tag_To_Interface (Class_Wide_Type (Iface_Typ), Make_Selected_Component (Loc, Prefix => Relocate_Node (Expression (N)), Selector_Name => New_Occurrence_Of (Iface_Tag, Loc)))); else -- Build internal function to handle the case in which the actual is -- null. If the actual is null returns null because no displacement -- is required; otherwise performs a type conversion that will be -- expanded in the code that returns the value of the displaced -- actual. That is: -- function Func (O : Address) return Iface_Typ is -- type Op_Typ is access all Operand_Typ; -- Aux : Op_Typ := To_Op_Typ (O); -- begin -- if O = Null_Address then -- return null; -- else -- return Iface_Typ!(Aux.Iface_Tag'Address); -- end if; -- end Func; declare Desig_Typ : Entity_Id; Fent : Entity_Id; New_Typ_Decl : Node_Id; Stats : List_Id; begin Desig_Typ := Etype (Expression (N)); if Is_Access_Type (Desig_Typ) then Desig_Typ := Available_View (Directly_Designated_Type (Desig_Typ)); end if; if Is_Concurrent_Type (Desig_Typ) then Desig_Typ := Base_Type (Corresponding_Record_Type (Desig_Typ)); end if; New_Typ_Decl := Make_Full_Type_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'T'), Type_Definition => Make_Access_To_Object_Definition (Loc, All_Present => True, Null_Exclusion_Present => False, Constant_Present => False, Subtype_Indication => New_Occurrence_Of (Desig_Typ, Loc))); Stats := New_List ( Make_Simple_Return_Statement (Loc, Unchecked_Convert_To (Etype (N), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => Unchecked_Convert_To (Defining_Identifier (New_Typ_Decl), Make_Identifier (Loc, Name_uO)), Selector_Name => New_Occurrence_Of (Iface_Tag, Loc)), Attribute_Name => Name_Address)))); -- If the type is null-excluding, no need for the null branch. -- Otherwise we need to check for it and return null. if not Can_Never_Be_Null (Etype (N)) then Stats := New_List ( Make_If_Statement (Loc, Condition => Make_Op_Eq (Loc, Left_Opnd => Make_Identifier (Loc, Name_uO), Right_Opnd => New_Occurrence_Of (RTE (RE_Null_Address), Loc)), Then_Statements => New_List ( Make_Simple_Return_Statement (Loc, Make_Null (Loc))), Else_Statements => Stats)); end if; Fent := Make_Temporary (Loc, 'F'); Func := Make_Subprogram_Body (Loc, Specification => Make_Function_Specification (Loc, Defining_Unit_Name => Fent, Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc))), Result_Definition => New_Occurrence_Of (Etype (N), Loc)), Declarations => New_List (New_Typ_Decl), Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stats)); -- Place function body before the expression containing the -- conversion. We suppress all checks because the body of the -- internally generated function already takes care of the case -- in which the actual is null; therefore there is no need to -- double check that the pointer is not null when the program -- executes the alternative that performs the type conversion). Insert_Action (N, Func, Suppress => All_Checks); if Is_Access_Type (Etype (Expression (N))) then -- Generate: Func (Address!(Expression)) Rewrite (N, Make_Function_Call (Loc, Name => New_Occurrence_Of (Fent, Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (RTE (RE_Address), Relocate_Node (Expression (N)))))); else -- Generate: Func (Operand_Typ!(Expression)'Address) Rewrite (N, Make_Function_Call (Loc, Name => New_Occurrence_Of (Fent, Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => Unchecked_Convert_To (Operand_Typ, Relocate_Node (Expression (N))), Attribute_Name => Name_Address)))); end if; end; end if; Analyze (N); end Expand_Interface_Conversion; ------------------------------ -- Expand_Interface_Actuals -- ------------------------------ procedure Expand_Interface_Actuals (Call_Node : Node_Id) is Actual : Node_Id; Actual_Dup : Node_Id; Actual_Typ : Entity_Id; Anon : Entity_Id; Conversion : Node_Id; Formal : Entity_Id; Formal_Typ : Entity_Id; Subp : Entity_Id; Formal_DDT : Entity_Id := Empty; -- initialize to prevent warning Actual_DDT : Entity_Id := Empty; -- initialize to prevent warning begin -- This subprogram is called directly from the semantics, so we need a -- check to see whether expansion is active before proceeding. if not Expander_Active then return; end if; -- Call using access to subprogram with explicit dereference if Nkind (Name (Call_Node)) = N_Explicit_Dereference then Subp := Etype (Name (Call_Node)); -- Call using selected component elsif Nkind (Name (Call_Node)) = N_Selected_Component then Subp := Entity (Selector_Name (Name (Call_Node))); -- Call using direct name else Subp := Entity (Name (Call_Node)); end if; -- Ada 2005 (AI-251): Look for interface type formals to force "this" -- displacement Formal := First_Formal (Subp); Actual := First_Actual (Call_Node); while Present (Formal) loop Formal_Typ := Etype (Formal); if Has_Non_Limited_View (Formal_Typ) then Formal_Typ := Non_Limited_View (Formal_Typ); end if; if Ekind (Formal_Typ) = E_Record_Type_With_Private then Formal_Typ := Full_View (Formal_Typ); end if; if Is_Access_Type (Formal_Typ) then Formal_DDT := Directly_Designated_Type (Formal_Typ); if Has_Non_Limited_View (Formal_DDT) then Formal_DDT := Non_Limited_View (Formal_DDT); end if; end if; Actual_Typ := Etype (Actual); if Has_Non_Limited_View (Actual_Typ) then Actual_Typ := Non_Limited_View (Actual_Typ); end if; if Is_Access_Type (Actual_Typ) then Actual_DDT := Directly_Designated_Type (Actual_Typ); if Has_Non_Limited_View (Actual_DDT) then Actual_DDT := Non_Limited_View (Actual_DDT); end if; end if; if Is_Interface (Formal_Typ) and then Is_Class_Wide_Type (Formal_Typ) then -- No need to displace the pointer if the type of the actual -- coincides with the type of the formal. if Actual_Typ = Formal_Typ then null; -- No need to displace the pointer if the interface type is a -- parent of the type of the actual because in this case the -- interface primitives are located in the primary dispatch table. elsif Is_Ancestor (Formal_Typ, Actual_Typ, Use_Full_View => True) then null; -- Implicit conversion to the class-wide formal type to force the -- displacement of the pointer. else -- Normally, expansion of actuals for calls to build-in-place -- functions happens as part of Expand_Actuals, but in this -- case the call will be wrapped in a conversion and soon after -- expanded further to handle the displacement for a class-wide -- interface conversion, so if this is a BIP call then we need -- to handle it now. if Is_Build_In_Place_Function_Call (Actual) then Make_Build_In_Place_Call_In_Anonymous_Context (Actual); end if; Conversion := Convert_To (Formal_Typ, Relocate_Node (Actual)); Rewrite (Actual, Conversion); Analyze_And_Resolve (Actual, Formal_Typ); end if; -- Access to class-wide interface type elsif Is_Access_Type (Formal_Typ) and then Is_Interface (Formal_DDT) and then Is_Class_Wide_Type (Formal_DDT) and then Interface_Present_In_Ancestor (Typ => Actual_DDT, Iface => Etype (Formal_DDT)) then -- Handle attributes 'Access and 'Unchecked_Access if Nkind (Actual) = N_Attribute_Reference and then (Attribute_Name (Actual) = Name_Access or else Attribute_Name (Actual) = Name_Unchecked_Access) then -- This case must have been handled by the analysis and -- expansion of 'Access. The only exception is when types -- match and no further expansion is required. pragma Assert (Base_Type (Etype (Prefix (Actual))) = Base_Type (Formal_DDT)); null; -- No need to displace the pointer if the type of the actual -- coincides with the type of the formal. elsif Actual_DDT = Formal_DDT then null; -- No need to displace the pointer if the interface type is -- a parent of the type of the actual because in this case the -- interface primitives are located in the primary dispatch table. elsif Is_Ancestor (Formal_DDT, Actual_DDT, Use_Full_View => True) then null; else Actual_Dup := Relocate_Node (Actual); if From_Limited_With (Actual_Typ) then -- If the type of the actual parameter comes from a limited -- with_clause and the nonlimited view is already available, -- we replace the anonymous access type by a duplicate -- declaration whose designated type is the nonlimited view. if Has_Non_Limited_View (Actual_DDT) then Anon := New_Copy (Actual_Typ); if Is_Itype (Anon) then Set_Scope (Anon, Current_Scope); end if; Set_Directly_Designated_Type (Anon, Non_Limited_View (Actual_DDT)); Set_Etype (Actual_Dup, Anon); end if; end if; Conversion := Convert_To (Formal_Typ, Actual_Dup); Rewrite (Actual, Conversion); Analyze_And_Resolve (Actual, Formal_Typ); end if; end if; Next_Actual (Actual); Next_Formal (Formal); end loop; end Expand_Interface_Actuals; ---------------------------- -- Expand_Interface_Thunk -- ---------------------------- procedure Expand_Interface_Thunk (Prim : Node_Id; Thunk_Id : out Entity_Id; Thunk_Code : out Node_Id; Iface : Entity_Id) is Loc : constant Source_Ptr := Sloc (Prim); Actuals : constant List_Id := New_List; Decl : constant List_Id := New_List; Formals : constant List_Id := New_List; Target : constant Entity_Id := Ultimate_Alias (Prim); Decl_1 : Node_Id; Decl_2 : Node_Id; Expr : Node_Id; Formal : Node_Id; Ftyp : Entity_Id; Iface_Formal : Node_Id := Empty; -- initialize to prevent warning Is_Predef_Op : constant Boolean := Is_Predefined_Dispatching_Operation (Prim) or else Is_Predefined_Dispatching_Operation (Target); New_Arg : Node_Id; Offset_To_Top : Node_Id; Target_Formal : Entity_Id; begin Thunk_Id := Empty; Thunk_Code := Empty; -- No thunk needed if the primitive has been eliminated if Is_Eliminated (Target) then return; -- In case of primitives that are functions without formals and a -- controlling result there is no need to build the thunk. elsif not Present (First_Formal (Target)) then pragma Assert (Ekind (Target) = E_Function and then Has_Controlling_Result (Target)); return; end if; -- Duplicate the formals of the Target primitive. In the thunk, the type -- of the controlling formal is the covered interface type (instead of -- the target tagged type). Done to avoid problems with discriminated -- tagged types because, if the controlling type has discriminants with -- default values, then the type conversions done inside the body of -- the thunk (after the displacement of the pointer to the base of the -- actual object) generate code that modify its contents. -- Note: This special management is not done for predefined primitives -- because they don't have available the Interface_Alias attribute (see -- Sem_Ch3.Add_Internal_Interface_Entities). if not Is_Predef_Op then Iface_Formal := First_Formal (Interface_Alias (Prim)); end if; Formal := First_Formal (Target); while Present (Formal) loop Ftyp := Etype (Formal); -- Use the interface type as the type of the controlling formal (see -- comment above). if not Is_Controlling_Formal (Formal) then Ftyp := Etype (Formal); Expr := New_Copy_Tree (Expression (Parent (Formal))); -- For predefined primitives the controlling type of the thunk is -- the interface type passed by the caller (since they don't have -- available the Interface_Alias attribute; see comment above). elsif Is_Predef_Op then Ftyp := Iface; Expr := Empty; else Ftyp := Etype (Iface_Formal); Expr := Empty; -- Sanity check performed to ensure the proper controlling type -- when the thunk has exactly one controlling parameter and it -- comes first. In such case the GCC backend reuses the C++ -- thunks machinery which perform a computation equivalent to -- the code generated by the expander; for other cases the GCC -- backend translates the expanded code unmodified. However, as -- a generalization, the check is performed for all controlling -- types. if Is_Access_Type (Ftyp) then pragma Assert (Base_Type (Designated_Type (Ftyp)) = Iface); null; else Ftyp := Base_Type (Ftyp); pragma Assert (Ftyp = Iface); end if; end if; Append_To (Formals, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Sloc (Formal), Chars => Chars (Formal)), In_Present => In_Present (Parent (Formal)), Out_Present => Out_Present (Parent (Formal)), Parameter_Type => New_Occurrence_Of (Ftyp, Loc), Expression => Expr)); if not Is_Predef_Op then Next_Formal (Iface_Formal); end if; Next_Formal (Formal); end loop; Target_Formal := First_Formal (Target); Formal := First (Formals); while Present (Formal) loop -- If the parent is a constrained discriminated type, then the -- primitive operation will have been defined on a first subtype. -- For proper matching with controlling type, use base type. if Ekind (Target_Formal) = E_In_Parameter and then Ekind (Etype (Target_Formal)) = E_Anonymous_Access_Type then Ftyp := Base_Type (Directly_Designated_Type (Etype (Target_Formal))); else Ftyp := Base_Type (Etype (Target_Formal)); end if; -- For concurrent types, the relevant information is found in the -- Corresponding_Record_Type, rather than the type entity itself. if Is_Concurrent_Type (Ftyp) then Ftyp := Corresponding_Record_Type (Ftyp); end if; if Ekind (Target_Formal) = E_In_Parameter and then Ekind (Etype (Target_Formal)) = E_Anonymous_Access_Type and then Is_Controlling_Formal (Target_Formal) then -- Generate: -- type T is access all <<type of the target formal>> -- S : Storage_Offset := Storage_Offset!(Formal) -- + Offset_To_Top (address!(Formal)) Decl_2 := Make_Full_Type_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'T'), Type_Definition => Make_Access_To_Object_Definition (Loc, All_Present => True, Null_Exclusion_Present => False, Constant_Present => False, Subtype_Indication => New_Occurrence_Of (Ftyp, Loc))); New_Arg := Unchecked_Convert_To (RTE (RE_Address), New_Occurrence_Of (Defining_Identifier (Formal), Loc)); if not RTE_Available (RE_Offset_To_Top) then Offset_To_Top := Build_Offset_To_Top (Loc, New_Arg); else Offset_To_Top := Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Offset_To_Top), Loc), Parameter_Associations => New_List (New_Arg)); end if; Decl_1 := Make_Object_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'S'), Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Storage_Offset), Loc), Expression => Make_Op_Add (Loc, Left_Opnd => Unchecked_Convert_To (RTE (RE_Storage_Offset), New_Occurrence_Of (Defining_Identifier (Formal), Loc)), Right_Opnd => Offset_To_Top)); Append_To (Decl, Decl_2); Append_To (Decl, Decl_1); -- Reference the new actual. Generate: -- T!(S) Append_To (Actuals, Unchecked_Convert_To (Defining_Identifier (Decl_2), New_Occurrence_Of (Defining_Identifier (Decl_1), Loc))); elsif Is_Controlling_Formal (Target_Formal) then -- Generate: -- S1 : Storage_Offset := Storage_Offset!(Formal'Address) -- + Offset_To_Top (Formal'Address) -- S2 : Addr_Ptr := Addr_Ptr!(S1) New_Arg := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Defining_Identifier (Formal), Loc), Attribute_Name => Name_Address); if not RTE_Available (RE_Offset_To_Top) then Offset_To_Top := Build_Offset_To_Top (Loc, New_Arg); else Offset_To_Top := Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Offset_To_Top), Loc), Parameter_Associations => New_List (New_Arg)); end if; Decl_1 := Make_Object_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'S'), Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Storage_Offset), Loc), Expression => Make_Op_Add (Loc, Left_Opnd => Unchecked_Convert_To (RTE (RE_Storage_Offset), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Defining_Identifier (Formal), Loc), Attribute_Name => Name_Address)), Right_Opnd => Offset_To_Top)); Decl_2 := Make_Object_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'S'), Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Addr_Ptr), Loc), Expression => Unchecked_Convert_To (RTE (RE_Addr_Ptr), New_Occurrence_Of (Defining_Identifier (Decl_1), Loc))); Append_To (Decl, Decl_1); Append_To (Decl, Decl_2); -- Reference the new actual, generate: -- Target_Formal (S2.all) Append_To (Actuals, Unchecked_Convert_To (Ftyp, Make_Explicit_Dereference (Loc, New_Occurrence_Of (Defining_Identifier (Decl_2), Loc)))); -- Ensure proper matching of access types. Required to avoid -- reporting spurious errors. elsif Is_Access_Type (Etype (Target_Formal)) then Append_To (Actuals, Unchecked_Convert_To (Base_Type (Etype (Target_Formal)), New_Occurrence_Of (Defining_Identifier (Formal), Loc))); -- No special management required for this actual else Append_To (Actuals, New_Occurrence_Of (Defining_Identifier (Formal), Loc)); end if; Next_Formal (Target_Formal); Next (Formal); end loop; Thunk_Id := Make_Temporary (Loc, 'T'); -- Note: any change to this symbol name needs to be coordinated -- with GNATcoverage, as that tool relies on it to identify -- thunks and exclude them from source coverage analysis. Set_Ekind (Thunk_Id, Ekind (Prim)); Set_Is_Thunk (Thunk_Id); Set_Convention (Thunk_Id, Convention (Prim)); Set_Needs_Debug_Info (Thunk_Id, Needs_Debug_Info (Target)); Set_Thunk_Entity (Thunk_Id, Target); -- Procedure case if Ekind (Target) = E_Procedure then Thunk_Code := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => Thunk_Id, Parameter_Specifications => Formals), Declarations => Decl, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Target, Loc), Parameter_Associations => Actuals)))); -- Function case else pragma Assert (Ekind (Target) = E_Function); declare Result_Def : Node_Id; Call_Node : Node_Id; begin Call_Node := Make_Function_Call (Loc, Name => New_Occurrence_Of (Target, Loc), Parameter_Associations => Actuals); if not Is_Interface (Etype (Prim)) then Result_Def := New_Copy (Result_Definition (Parent (Target))); -- Thunk of function returning a class-wide interface object. No -- extra displacement needed since the displacement is generated -- in the return statement of Prim. Example: -- type Iface is interface ... -- function F (O : Iface) return Iface'Class; -- type T is new ... and Iface with ... -- function F (O : T) return Iface'Class; elsif Is_Class_Wide_Type (Etype (Prim)) then Result_Def := New_Occurrence_Of (Etype (Prim), Loc); -- Thunk of function returning an interface object. Displacement -- needed. Example: -- type Iface is interface ... -- function F (O : Iface) return Iface; -- type T is new ... and Iface with ... -- function F (O : T) return T; else Result_Def := New_Occurrence_Of (Class_Wide_Type (Etype (Prim)), Loc); -- Adding implicit conversion to force the displacement of -- the pointer to the object to reference the corresponding -- secondary dispatch table. Call_Node := Make_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (Class_Wide_Type (Etype (Prim)), Loc), Expression => Relocate_Node (Call_Node)); end if; Thunk_Code := Make_Subprogram_Body (Loc, Specification => Make_Function_Specification (Loc, Defining_Unit_Name => Thunk_Id, Parameter_Specifications => Formals, Result_Definition => Result_Def), Declarations => Decl, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => New_List ( Make_Simple_Return_Statement (Loc, Call_Node)))); end; end if; end Expand_Interface_Thunk; -------------------------- -- Has_CPP_Constructors -- -------------------------- function Has_CPP_Constructors (Typ : Entity_Id) return Boolean is E : Entity_Id; begin -- Look for the constructor entities E := Next_Entity (Typ); while Present (E) loop if Ekind (E) = E_Function and then Is_Constructor (E) then return True; end if; Next_Entity (E); end loop; return False; end Has_CPP_Constructors; ------------ -- Has_DT -- ------------ function Has_DT (Typ : Entity_Id) return Boolean is begin return not Is_Interface (Typ) and then not Restriction_Active (No_Dispatching_Calls); end Has_DT; ---------------------------------- -- Is_Expanded_Dispatching_Call -- ---------------------------------- function Is_Expanded_Dispatching_Call (N : Node_Id) return Boolean is begin return Nkind (N) in N_Subprogram_Call and then Nkind (Name (N)) = N_Explicit_Dereference and then Is_Dispatch_Table_Entity (Etype (Name (N))); end Is_Expanded_Dispatching_Call; ------------------------------------- -- Is_Predefined_Dispatching_Alias -- ------------------------------------- function Is_Predefined_Dispatching_Alias (Prim : Entity_Id) return Boolean is begin return not Is_Predefined_Dispatching_Operation (Prim) and then Present (Alias (Prim)) and then Is_Predefined_Dispatching_Operation (Ultimate_Alias (Prim)); end Is_Predefined_Dispatching_Alias; ---------------------------------------- -- Make_Disp_Asynchronous_Select_Body -- ---------------------------------------- -- For interface types, generate: -- procedure _Disp_Asynchronous_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- B : out System.Storage_Elements.Dummy_Communication_Block; -- F : out Boolean) -- is -- begin -- F := False; -- C := Ada.Tags.POK_Function; -- end _Disp_Asynchronous_Select; -- For protected types, generate: -- procedure _Disp_Asynchronous_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- B : out System.Storage_Elements.Dummy_Communication_Block; -- F : out Boolean) -- is -- I : Integer := -- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S)); -- Bnn : System.Tasking.Protected_Objects.Operations. -- Communication_Block; -- begin -- System.Tasking.Protected_Objects.Operations.Protected_Entry_Call -- (T._object'Access, -- System.Tasking.Protected_Objects.Protected_Entry_Index (I), -- P, -- System.Tasking.Asynchronous_Call, -- Bnn); -- B := System.Storage_Elements.Dummy_Communication_Block (Bnn); -- end _Disp_Asynchronous_Select; -- For task types, generate: -- procedure _Disp_Asynchronous_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- B : out System.Storage_Elements.Dummy_Communication_Block; -- F : out Boolean) -- is -- I : Integer := -- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S)); -- begin -- System.Tasking.Rendezvous.Task_Entry_Call -- (T._task_id, -- System.Tasking.Task_Entry_Index (I), -- P, -- System.Tasking.Asynchronous_Call, -- F); -- end _Disp_Asynchronous_Select; function Make_Disp_Asynchronous_Select_Body (Typ : Entity_Id) return Node_Id is Com_Block : Entity_Id; Conc_Typ : Entity_Id := Empty; Decls : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (Typ); Obj_Ref : Node_Id; Stmts : constant List_Id := New_List; Tag_Node : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- Null body is generated for interface types if Is_Interface (Typ) then return Make_Subprogram_Body (Loc, Specification => Make_Disp_Asynchronous_Select_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List ( Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))))); end if; if Is_Concurrent_Record_Type (Typ) then Conc_Typ := Corresponding_Concurrent_Type (Typ); -- Generate: -- I : Integer := -- Ada.Tags.Get_Entry_Index (Ada.Tags.Tag! (<type>VP), S); -- where I will be used to capture the entry index of the primitive -- wrapper at position S. if Tagged_Type_Expansion then Tag_Node := Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc)); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI), Object_Definition => New_Occurrence_Of (Standard_Integer, Loc), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc), Parameter_Associations => New_List (Tag_Node, Make_Identifier (Loc, Name_uS))))); if Ekind (Conc_Typ) = E_Protected_Type then -- Generate: -- Bnn : Communication_Block; Com_Block := Make_Temporary (Loc, 'B'); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Com_Block, Object_Definition => New_Occurrence_Of (RTE (RE_Communication_Block), Loc))); -- Build T._object'Access for calls below Obj_Ref := Make_Attribute_Reference (Loc, Attribute_Name => Name_Unchecked_Access, Prefix => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uObject))); case Corresponding_Runtime_Package (Conc_Typ) is when System_Tasking_Protected_Objects_Entries => -- Generate: -- Protected_Entry_Call -- (T._object'Access, -- Object -- Protected_Entry_Index! (I), -- E -- P, -- Uninterpreted_Data -- Asynchronous_Call, -- Mode -- Bnn); -- Communication_Block -- where T is the protected object, I is the entry index, P -- is the wrapped parameters and B is the name of the -- communication block. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Protected_Entry_Call), Loc), Parameter_Associations => New_List ( Obj_Ref, Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Protected_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block New_Occurrence_Of -- Asynchronous_Call (RTE (RE_Asynchronous_Call), Loc), New_Occurrence_Of -- comm block (Com_Block, Loc)))); when others => raise Program_Error; end case; -- Generate: -- B := Dummy_Communication_Block (Bnn); Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uB), Expression => Make_Unchecked_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Dummy_Communication_Block), Loc), Expression => New_Occurrence_Of (Com_Block, Loc)))); -- Generate: -- F := False; Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))); else pragma Assert (Ekind (Conc_Typ) = E_Task_Type); -- Generate: -- Task_Entry_Call -- (T._task_id, -- Acceptor -- Task_Entry_Index! (I), -- E -- P, -- Uninterpreted_Data -- Asynchronous_Call, -- Mode -- F); -- Rendezvous_Successful -- where T is the task object, I is the entry index, P is the -- wrapped parameters and F is the status flag. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Task_Entry_Call), Loc), Parameter_Associations => New_List ( Make_Selected_Component (Loc, -- T._task_id Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block New_Occurrence_Of -- Asynchronous_Call (RTE (RE_Asynchronous_Call), Loc), Make_Identifier (Loc, Name_uF)))); -- status flag end if; else -- Ensure that the statements list is non-empty Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))); end if; return Make_Subprogram_Body (Loc, Specification => Make_Disp_Asynchronous_Select_Spec (Typ), Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stmts)); end Make_Disp_Asynchronous_Select_Body; ---------------------------------------- -- Make_Disp_Asynchronous_Select_Spec -- ---------------------------------------- function Make_Disp_Asynchronous_Select_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); B_Id : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uB); Def_Id : constant Entity_Id := Make_Defining_Identifier (Loc, Name_uDisp_Asynchronous_Select); Params : constant List_Id := New_List; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- T : in out Typ; -- Object parameter -- S : Integer; -- Primitive operation slot -- P : Address; -- Wrapped parameters -- B : out Dummy_Communication_Block; -- Communication block dummy -- F : out Boolean; -- Status flag -- The B parameter may be left uninitialized Set_Warnings_Off (B_Id); Append_List_To (Params, New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT), Parameter_Type => New_Occurrence_Of (Typ, Loc), In_Present => True, Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => B_Id, Parameter_Type => New_Occurrence_Of (RTE (RE_Dummy_Communication_Block), Loc), Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc), Out_Present => True))); return Make_Procedure_Specification (Loc, Defining_Unit_Name => Def_Id, Parameter_Specifications => Params); end Make_Disp_Asynchronous_Select_Spec; --------------------------------------- -- Make_Disp_Conditional_Select_Body -- --------------------------------------- -- For interface types, generate: -- procedure _Disp_Conditional_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- begin -- F := False; -- C := Ada.Tags.POK_Function; -- end _Disp_Conditional_Select; -- For protected types, generate: -- procedure _Disp_Conditional_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- I : Integer; -- Bnn : System.Tasking.Protected_Objects.Operations. -- Communication_Block; -- begin -- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag (<Typ>VP, S)); -- if C = Ada.Tags.POK_Procedure -- or else C = Ada.Tags.POK_Protected_Procedure -- or else C = Ada.Tags.POK_Task_Procedure -- then -- F := True; -- return; -- end if; -- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S)); -- System.Tasking.Protected_Objects.Operations.Protected_Entry_Call -- (T.object'Access, -- System.Tasking.Protected_Objects.Protected_Entry_Index (I), -- P, -- System.Tasking.Conditional_Call, -- Bnn); -- F := not Cancelled (Bnn); -- end _Disp_Conditional_Select; -- For task types, generate: -- procedure _Disp_Conditional_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- I : Integer; -- begin -- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP, S)); -- System.Tasking.Rendezvous.Task_Entry_Call -- (T._task_id, -- System.Tasking.Task_Entry_Index (I), -- P, -- System.Tasking.Conditional_Call, -- F); -- end _Disp_Conditional_Select; function Make_Disp_Conditional_Select_Body (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Blk_Nam : Entity_Id; Conc_Typ : Entity_Id := Empty; Decls : constant List_Id := New_List; Obj_Ref : Node_Id; Stmts : constant List_Id := New_List; Tag_Node : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- Null body is generated for interface types if Is_Interface (Typ) then return Make_Subprogram_Body (Loc, Specification => Make_Disp_Conditional_Select_Spec (Typ), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List (Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))))); end if; if Is_Concurrent_Record_Type (Typ) then Conc_Typ := Corresponding_Concurrent_Type (Typ); -- Generate: -- I : Integer; -- where I will be used to capture the entry index of the primitive -- wrapper at position S. Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI), Object_Definition => New_Occurrence_Of (Standard_Integer, Loc))); -- Generate: -- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag! (<type>VP), S); -- if C = POK_Procedure -- or else C = POK_Protected_Procedure -- or else C = POK_Task_Procedure; -- then -- F := True; -- return; -- end if; Build_Common_Dispatching_Select_Statements (Typ, Stmts); -- Generate: -- Bnn : Communication_Block; -- where Bnn is the name of the communication block used in the -- call to Protected_Entry_Call. Blk_Nam := Make_Temporary (Loc, 'B'); Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Blk_Nam, Object_Definition => New_Occurrence_Of (RTE (RE_Communication_Block), Loc))); -- Generate: -- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag! (<type>VP), S); -- I is the entry index and S is the dispatch table slot if Tagged_Type_Expansion then Tag_Node := Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc)); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uI), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc), Parameter_Associations => New_List ( Tag_Node, Make_Identifier (Loc, Name_uS))))); if Ekind (Conc_Typ) = E_Protected_Type then Obj_Ref := -- T._object'Access Make_Attribute_Reference (Loc, Attribute_Name => Name_Unchecked_Access, Prefix => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uObject))); case Corresponding_Runtime_Package (Conc_Typ) is when System_Tasking_Protected_Objects_Entries => -- Generate: -- Protected_Entry_Call -- (T._object'Access, -- Object -- Protected_Entry_Index! (I), -- E -- P, -- Uninterpreted_Data -- Conditional_Call, -- Mode -- Bnn); -- Block -- where T is the protected object, I is the entry index, P -- are the wrapped parameters and Bnn is the name of the -- communication block. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Protected_Entry_Call), Loc), Parameter_Associations => New_List ( Obj_Ref, Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Protected_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block New_Occurrence_Of -- Conditional_Call (RTE (RE_Conditional_Call), Loc), New_Occurrence_Of -- Bnn (Blk_Nam, Loc)))); when System_Tasking_Protected_Objects_Single_Entry => -- If we are compiling for a restricted run-time, the call -- uses the simpler form. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Protected_Single_Entry_Call), Loc), Parameter_Associations => New_List ( Obj_Ref, Make_Attribute_Reference (Loc, Prefix => Make_Identifier (Loc, Name_uP), Attribute_Name => Name_Address), New_Occurrence_Of (RTE (RE_Conditional_Call), Loc)))); when others => raise Program_Error; end case; -- Generate: -- F := not Cancelled (Bnn); -- where F is the success flag. The status of Cancelled is negated -- in order to match the behavior of the version for task types. Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => Make_Op_Not (Loc, Right_Opnd => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Cancelled), Loc), Parameter_Associations => New_List ( New_Occurrence_Of (Blk_Nam, Loc)))))); else pragma Assert (Ekind (Conc_Typ) = E_Task_Type); -- Generate: -- Task_Entry_Call -- (T._task_id, -- Acceptor -- Task_Entry_Index! (I), -- E -- P, -- Uninterpreted_Data -- Conditional_Call, -- Mode -- F); -- Rendezvous_Successful -- where T is the task object, I is the entry index, P are the -- wrapped parameters and F is the status flag. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Task_Entry_Call), Loc), Parameter_Associations => New_List ( Make_Selected_Component (Loc, -- T._task_id Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block New_Occurrence_Of -- Conditional_Call (RTE (RE_Conditional_Call), Loc), Make_Identifier (Loc, Name_uF)))); -- status flag end if; else -- Initialize out parameters Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))); Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uC), Expression => New_Occurrence_Of (RTE (RE_POK_Function), Loc))); end if; return Make_Subprogram_Body (Loc, Specification => Make_Disp_Conditional_Select_Spec (Typ), Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stmts)); end Make_Disp_Conditional_Select_Body; --------------------------------------- -- Make_Disp_Conditional_Select_Spec -- --------------------------------------- function Make_Disp_Conditional_Select_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Def_Id : constant Node_Id := Make_Defining_Identifier (Loc, Name_uDisp_Conditional_Select); Params : constant List_Id := New_List; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- T : in out Typ; -- Object parameter -- S : Integer; -- Primitive operation slot -- P : Address; -- Wrapped parameters -- C : out Prim_Op_Kind; -- Call kind -- F : out Boolean; -- Status flag Append_List_To (Params, New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT), Parameter_Type => New_Occurrence_Of (Typ, Loc), In_Present => True, Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC), Parameter_Type => New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc), Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc), Out_Present => True))); return Make_Procedure_Specification (Loc, Defining_Unit_Name => Def_Id, Parameter_Specifications => Params); end Make_Disp_Conditional_Select_Spec; ------------------------------------- -- Make_Disp_Get_Prim_Op_Kind_Body -- ------------------------------------- function Make_Disp_Get_Prim_Op_Kind_Body (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Tag_Node : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); if Is_Interface (Typ) then return Make_Subprogram_Body (Loc, Specification => Make_Disp_Get_Prim_Op_Kind_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List (Make_Null_Statement (Loc)))); end if; -- Generate: -- C := get_prim_op_kind (tag! (<type>VP), S); -- where C is the out parameter capturing the call kind and S is the -- dispatch table slot number. if Tagged_Type_Expansion then Tag_Node := Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc)); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; return Make_Subprogram_Body (Loc, Specification => Make_Disp_Get_Prim_Op_Kind_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List ( Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uC), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Get_Prim_Op_Kind), Loc), Parameter_Associations => New_List ( Tag_Node, Make_Identifier (Loc, Name_uS))))))); end Make_Disp_Get_Prim_Op_Kind_Body; ------------------------------------- -- Make_Disp_Get_Prim_Op_Kind_Spec -- ------------------------------------- function Make_Disp_Get_Prim_Op_Kind_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Def_Id : constant Node_Id := Make_Defining_Identifier (Loc, Name_uDisp_Get_Prim_Op_Kind); Params : constant List_Id := New_List; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- T : in out Typ; -- Object parameter -- S : Integer; -- Primitive operation slot -- C : out Prim_Op_Kind; -- Call kind Append_List_To (Params, New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT), Parameter_Type => New_Occurrence_Of (Typ, Loc), In_Present => True, Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC), Parameter_Type => New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc), Out_Present => True))); return Make_Procedure_Specification (Loc, Defining_Unit_Name => Def_Id, Parameter_Specifications => Params); end Make_Disp_Get_Prim_Op_Kind_Spec; -------------------------------- -- Make_Disp_Get_Task_Id_Body -- -------------------------------- function Make_Disp_Get_Task_Id_Body (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Ret : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); if Is_Concurrent_Record_Type (Typ) and then Ekind (Corresponding_Concurrent_Type (Typ)) = E_Task_Type then -- Generate: -- return To_Address (_T._task_id); Ret := Make_Simple_Return_Statement (Loc, Expression => Make_Unchecked_Type_Conversion (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Address), Loc), Expression => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)))); -- A null body is constructed for non-task types else -- Generate: -- return Null_Address; Ret := Make_Simple_Return_Statement (Loc, Expression => New_Occurrence_Of (RTE (RE_Null_Address), Loc)); end if; return Make_Subprogram_Body (Loc, Specification => Make_Disp_Get_Task_Id_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List (Ret))); end Make_Disp_Get_Task_Id_Body; -------------------------------- -- Make_Disp_Get_Task_Id_Spec -- -------------------------------- function Make_Disp_Get_Task_Id_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); return Make_Function_Specification (Loc, Defining_Unit_Name => Make_Defining_Identifier (Loc, Name_uDisp_Get_Task_Id), Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT), Parameter_Type => New_Occurrence_Of (Typ, Loc))), Result_Definition => New_Occurrence_Of (RTE (RE_Address), Loc)); end Make_Disp_Get_Task_Id_Spec; ---------------------------- -- Make_Disp_Requeue_Body -- ---------------------------- function Make_Disp_Requeue_Body (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Conc_Typ : Entity_Id := Empty; Stmts : constant List_Id := New_List; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- Null body is generated for interface types and non-concurrent -- tagged types. if Is_Interface (Typ) or else not Is_Concurrent_Record_Type (Typ) then return Make_Subprogram_Body (Loc, Specification => Make_Disp_Requeue_Spec (Typ), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List (Make_Null_Statement (Loc)))); end if; Conc_Typ := Corresponding_Concurrent_Type (Typ); if Ekind (Conc_Typ) = E_Protected_Type then -- Generate statements: -- if F then -- System.Tasking.Protected_Objects.Operations. -- Requeue_Protected_Entry -- (Protection_Entries_Access (P), -- O._object'Unchecked_Access, -- Protected_Entry_Index (I), -- A); -- else -- System.Tasking.Protected_Objects.Operations. -- Requeue_Task_To_Protected_Entry -- (O._object'Unchecked_Access, -- Protected_Entry_Index (I), -- A); -- end if; if Restriction_Active (No_Entry_Queue) then Append_To (Stmts, Make_Null_Statement (Loc)); else Append_To (Stmts, Make_If_Statement (Loc, Condition => Make_Identifier (Loc, Name_uF), Then_Statements => New_List ( -- Call to Requeue_Protected_Entry Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Requeue_Protected_Entry), Loc), Parameter_Associations => New_List ( Make_Unchecked_Type_Conversion (Loc, -- PEA (P) Subtype_Mark => New_Occurrence_Of ( RTE (RE_Protection_Entries_Access), Loc), Expression => Make_Identifier (Loc, Name_uP)), Make_Attribute_Reference (Loc, -- O._object'Acc Attribute_Name => Name_Unchecked_Access, Prefix => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uO), Selector_Name => Make_Identifier (Loc, Name_uObject))), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Protected_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uA)))), -- abort status Else_Statements => New_List ( -- Call to Requeue_Task_To_Protected_Entry Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Requeue_Task_To_Protected_Entry), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, -- O._object'Acc Attribute_Name => Name_Unchecked_Access, Prefix => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uO), Selector_Name => Make_Identifier (Loc, Name_uObject))), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Protected_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uA)))))); -- abort status end if; else pragma Assert (Is_Task_Type (Conc_Typ)); -- Generate: -- if F then -- System.Tasking.Rendezvous.Requeue_Protected_To_Task_Entry -- (Protection_Entries_Access (P), -- O._task_id, -- Task_Entry_Index (I), -- A); -- else -- System.Tasking.Rendezvous.Requeue_Task_Entry -- (O._task_id, -- Task_Entry_Index (I), -- A); -- end if; Append_To (Stmts, Make_If_Statement (Loc, Condition => Make_Identifier (Loc, Name_uF), Then_Statements => New_List ( -- Call to Requeue_Protected_To_Task_Entry Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Requeue_Protected_To_Task_Entry), Loc), Parameter_Associations => New_List ( Make_Unchecked_Type_Conversion (Loc, -- PEA (P) Subtype_Mark => New_Occurrence_Of (RTE (RE_Protection_Entries_Access), Loc), Expression => Make_Identifier (Loc, Name_uP)), Make_Selected_Component (Loc, -- O._task_id Prefix => Make_Identifier (Loc, Name_uO), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uA)))), -- abort status Else_Statements => New_List ( -- Call to Requeue_Task_Entry Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Requeue_Task_Entry), Loc), Parameter_Associations => New_List ( Make_Selected_Component (Loc, -- O._task_id Prefix => Make_Identifier (Loc, Name_uO), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uA)))))); -- abort status end if; -- Even though no declarations are needed in both cases, we allocate -- a list for entities added by Freeze. return Make_Subprogram_Body (Loc, Specification => Make_Disp_Requeue_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stmts)); end Make_Disp_Requeue_Body; ---------------------------- -- Make_Disp_Requeue_Spec -- ---------------------------- function Make_Disp_Requeue_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- O : in out Typ; - Object parameter -- F : Boolean; - Protected (True) / task (False) flag -- P : Address; - Protection_Entries_Access value -- I : Entry_Index - Index of entry call -- A : Boolean - Abort flag -- Note that the Protection_Entries_Access value is represented as a -- System.Address in order to avoid dragging in the tasking runtime -- when compiling sources without tasking constructs. return Make_Procedure_Specification (Loc, Defining_Unit_Name => Make_Defining_Identifier (Loc, Name_uDisp_Requeue), Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, -- O Defining_Identifier => Make_Defining_Identifier (Loc, Name_uO), Parameter_Type => New_Occurrence_Of (Typ, Loc), In_Present => True, Out_Present => True), Make_Parameter_Specification (Loc, -- F Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc)), Make_Parameter_Specification (Loc, -- P Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)), Make_Parameter_Specification (Loc, -- I Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, -- A Defining_Identifier => Make_Defining_Identifier (Loc, Name_uA), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc)))); end Make_Disp_Requeue_Spec; --------------------------------- -- Make_Disp_Timed_Select_Body -- --------------------------------- -- For interface types, generate: -- procedure _Disp_Timed_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- D : Duration; -- M : Integer; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- begin -- F := False; -- C := Ada.Tags.POK_Function; -- end _Disp_Timed_Select; -- For protected types, generate: -- procedure _Disp_Timed_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- D : Duration; -- M : Integer; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- I : Integer; -- begin -- C := Ada.Tags.Get_Prim_Op_Kind (Ada.Tags.Tag (<Typ>VP), S); -- if C = Ada.Tags.POK_Procedure -- or else C = Ada.Tags.POK_Protected_Procedure -- or else C = Ada.Tags.POK_Task_Procedure -- then -- F := True; -- return; -- end if; -- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP), S); -- System.Tasking.Protected_Objects.Operations. -- Timed_Protected_Entry_Call -- (T._object'Access, -- System.Tasking.Protected_Objects.Protected_Entry_Index (I), -- P, -- D, -- M, -- F); -- end _Disp_Timed_Select; -- For task types, generate: -- procedure _Disp_Timed_Select -- (T : in out <Typ>; -- S : Integer; -- P : System.Address; -- D : Duration; -- M : Integer; -- C : out Ada.Tags.Prim_Op_Kind; -- F : out Boolean) -- is -- I : Integer; -- begin -- I := Ada.Tags.Get_Entry_Index (Ada.Tags.Tag (<Typ>VP), S); -- System.Tasking.Rendezvous.Timed_Task_Entry_Call -- (T._task_id, -- System.Tasking.Task_Entry_Index (I), -- P, -- D, -- M, -- F); -- end _Disp_Time_Select; function Make_Disp_Timed_Select_Body (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Conc_Typ : Entity_Id := Empty; Decls : constant List_Id := New_List; Obj_Ref : Node_Id; Stmts : constant List_Id := New_List; Tag_Node : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- Null body is generated for interface types if Is_Interface (Typ) then return Make_Subprogram_Body (Loc, Specification => Make_Disp_Timed_Select_Spec (Typ), Declarations => New_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, New_List ( Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))))); end if; if Is_Concurrent_Record_Type (Typ) then Conc_Typ := Corresponding_Concurrent_Type (Typ); -- Generate: -- I : Integer; -- where I will be used to capture the entry index of the primitive -- wrapper at position S. Append_To (Decls, Make_Object_Declaration (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uI), Object_Definition => New_Occurrence_Of (Standard_Integer, Loc))); -- Generate: -- C := Get_Prim_Op_Kind (tag! (<type>VP), S); -- if C = POK_Procedure -- or else C = POK_Protected_Procedure -- or else C = POK_Task_Procedure; -- then -- F := True; -- return; -- end if; Build_Common_Dispatching_Select_Statements (Typ, Stmts); -- Generate: -- I := Get_Entry_Index (tag! (<type>VP), S); -- I is the entry index and S is the dispatch table slot if Tagged_Type_Expansion then Tag_Node := Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc)); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uI), Expression => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Get_Entry_Index), Loc), Parameter_Associations => New_List ( Tag_Node, Make_Identifier (Loc, Name_uS))))); -- Protected case if Ekind (Conc_Typ) = E_Protected_Type then -- Build T._object'Access Obj_Ref := Make_Attribute_Reference (Loc, Attribute_Name => Name_Unchecked_Access, Prefix => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uObject))); -- Normal case, No_Entry_Queue restriction not active. In this -- case we generate: -- Timed_Protected_Entry_Call -- (T._object'access, -- Protected_Entry_Index! (I), -- P, D, M, F); -- where T is the protected object, I is the entry index, P are -- the wrapped parameters, D is the delay amount, M is the delay -- mode and F is the status flag. -- Historically, there was also an implementation for single -- entry protected types (in s-tposen). However, it was removed -- by also testing for no No_Select_Statements restriction in -- Exp_Utils.Corresponding_Runtime_Package. This simplified the -- implementation of s-tposen.adb and provided consistency between -- all versions of System.Tasking.Protected_Objects.Single_Entry -- (s-tposen*.adb). case Corresponding_Runtime_Package (Conc_Typ) is when System_Tasking_Protected_Objects_Entries => Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Timed_Protected_Entry_Call), Loc), Parameter_Associations => New_List ( Obj_Ref, Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Protected_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block Make_Identifier (Loc, Name_uD), -- delay Make_Identifier (Loc, Name_uM), -- delay mode Make_Identifier (Loc, Name_uF)))); -- status flag when others => raise Program_Error; end case; -- Task case else pragma Assert (Ekind (Conc_Typ) = E_Task_Type); -- Generate: -- Timed_Task_Entry_Call ( -- T._task_id, -- Task_Entry_Index! (I), -- P, -- D, -- M, -- F); -- where T is the task object, I is the entry index, P are the -- wrapped parameters, D is the delay amount, M is the delay -- mode and F is the status flag. Append_To (Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Timed_Task_Entry_Call), Loc), Parameter_Associations => New_List ( Make_Selected_Component (Loc, -- T._task_id Prefix => Make_Identifier (Loc, Name_uT), Selector_Name => Make_Identifier (Loc, Name_uTask_Id)), Make_Unchecked_Type_Conversion (Loc, -- entry index Subtype_Mark => New_Occurrence_Of (RTE (RE_Task_Entry_Index), Loc), Expression => Make_Identifier (Loc, Name_uI)), Make_Identifier (Loc, Name_uP), -- parameter block Make_Identifier (Loc, Name_uD), -- delay Make_Identifier (Loc, Name_uM), -- delay mode Make_Identifier (Loc, Name_uF)))); -- status flag end if; else -- Initialize out parameters Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uF), Expression => New_Occurrence_Of (Standard_False, Loc))); Append_To (Stmts, Make_Assignment_Statement (Loc, Name => Make_Identifier (Loc, Name_uC), Expression => New_Occurrence_Of (RTE (RE_POK_Function), Loc))); end if; return Make_Subprogram_Body (Loc, Specification => Make_Disp_Timed_Select_Spec (Typ), Declarations => Decls, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Stmts)); end Make_Disp_Timed_Select_Body; --------------------------------- -- Make_Disp_Timed_Select_Spec -- --------------------------------- function Make_Disp_Timed_Select_Spec (Typ : Entity_Id) return Node_Id is Loc : constant Source_Ptr := Sloc (Typ); Def_Id : constant Node_Id := Make_Defining_Identifier (Loc, Name_uDisp_Timed_Select); Params : constant List_Id := New_List; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- T : in out Typ; -- Object parameter -- S : Integer; -- Primitive operation slot -- P : Address; -- Wrapped parameters -- D : Duration; -- Delay -- M : Integer; -- Delay Mode -- C : out Prim_Op_Kind; -- Call kind -- F : out Boolean; -- Status flag Append_List_To (Params, New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uT), Parameter_Type => New_Occurrence_Of (Typ, Loc), In_Present => True, Out_Present => True), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uS), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uP), Parameter_Type => New_Occurrence_Of (RTE (RE_Address), Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uD), Parameter_Type => New_Occurrence_Of (Standard_Duration, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uM), Parameter_Type => New_Occurrence_Of (Standard_Integer, Loc)), Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uC), Parameter_Type => New_Occurrence_Of (RTE (RE_Prim_Op_Kind), Loc), Out_Present => True))); Append_To (Params, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uF), Parameter_Type => New_Occurrence_Of (Standard_Boolean, Loc), Out_Present => True)); return Make_Procedure_Specification (Loc, Defining_Unit_Name => Def_Id, Parameter_Specifications => Params); end Make_Disp_Timed_Select_Spec; ------------- -- Make_DT -- ------------- -- The frontend supports two models for expanding dispatch tables -- associated with library-level defined tagged types: statically and -- non-statically allocated dispatch tables. In the former case the object -- containing the dispatch table is constant and it is initialized by means -- of a positional aggregate. In the latter case, the object containing -- the dispatch table is a variable which is initialized by means of -- assignments. -- In case of locally defined tagged types, the object containing the -- object containing the dispatch table is always a variable (instead of a -- constant). This is currently required to give support to late overriding -- of primitives. For example: -- procedure Example is -- package Pkg is -- type T1 is tagged null record; -- procedure Prim (O : T1); -- end Pkg; -- type T2 is new Pkg.T1 with null record; -- procedure Prim (X : T2) is -- late overriding -- begin -- ... -- ... -- end; -- WARNING: This routine manages Ghost regions. Return statements must be -- replaced by gotos which jump to the end of the routine and restore the -- Ghost mode. function Make_DT (Typ : Entity_Id; N : Node_Id := Empty) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Max_Predef_Prims : constant Int := UI_To_Int (Intval (Expression (Parent (RTE (RE_Max_Predef_Prims))))); DT_Decl : constant Elist_Id := New_Elmt_List; DT_Aggr : constant Elist_Id := New_Elmt_List; -- Entities marked with attribute Is_Dispatch_Table_Entity Dummy_Object : Entity_Id := Empty; -- Extra nonexistent object of type Typ internally used to compute the -- offset to the components that reference secondary dispatch tables. -- Used to compute the offset of components located at fixed position. procedure Check_Premature_Freezing (Subp : Entity_Id; Tagged_Type : Entity_Id; Typ : Entity_Id); -- Verify that all untagged types in the profile of a subprogram are -- frozen at the point the subprogram is frozen. This enforces the rule -- on RM 13.14 (14) as modified by AI05-019. At the point a subprogram -- is frozen, enough must be known about it to build the activation -- record for it, which requires at least that the size of all -- parameters be known. Controlling arguments are by-reference, -- and therefore the rule only applies to untagged types. Typical -- violation of the rule involves an object declaration that freezes a -- tagged type, when one of its primitive operations has a type in its -- profile whose full view has not been analyzed yet. More complex cases -- involve composite types that have one private unfrozen subcomponent. -- Move this check to sem??? procedure Export_DT (Typ : Entity_Id; DT : Entity_Id; Index : Nat := 0); -- Export the dispatch table DT of tagged type Typ. Required to generate -- forward references and statically allocate the table. For primary -- dispatch tables Index is 0; for secondary dispatch tables the value -- of index must match the Suffix_Index value assigned to the table by -- Make_Tags when generating its unique external name, and it is used to -- retrieve from the Dispatch_Table_Wrappers list associated with Typ -- the external name generated by Import_DT. procedure Make_Secondary_DT (Typ : Entity_Id; Iface : Entity_Id; Iface_Comp : Node_Id; Suffix_Index : Int; Num_Iface_Prims : Nat; Iface_DT_Ptr : Entity_Id; Predef_Prims_Ptr : Entity_Id; Build_Thunks : Boolean; Result : List_Id); -- Ada 2005 (AI-251): Expand the declarations for a Secondary Dispatch -- Table of Typ associated with Iface. Each abstract interface of Typ -- has two secondary dispatch tables: one containing pointers to thunks -- and another containing pointers to the primitives covering the -- interface primitives. The former secondary table is generated when -- Build_Thunks is True, and provides common support for dispatching -- calls through interface types; the latter secondary table is -- generated when Build_Thunks is False, and provides support for -- Generic Dispatching Constructors that dispatch calls through -- interface types. When constructing this latter table the value of -- Suffix_Index is -1 to indicate that there is no need to export such -- table when building statically allocated dispatch tables; a positive -- value of Suffix_Index must match the Suffix_Index value assigned to -- this secondary dispatch table by Make_Tags when its unique external -- name was generated. function Number_Of_Predefined_Prims (Typ : Entity_Id) return Nat; -- Returns the number of predefined primitives of Typ ------------------------------ -- Check_Premature_Freezing -- ------------------------------ procedure Check_Premature_Freezing (Subp : Entity_Id; Tagged_Type : Entity_Id; Typ : Entity_Id) is Comp : Entity_Id; function Is_Actual_For_Formal_Incomplete_Type (T : Entity_Id) return Boolean; -- In Ada 2012, if a nested generic has an incomplete formal type, -- the actual may be (and usually is) a private type whose completion -- appears later. It is safe to build the dispatch table in this -- case, gigi will have full views available. ------------------------------------------ -- Is_Actual_For_Formal_Incomplete_Type -- ------------------------------------------ function Is_Actual_For_Formal_Incomplete_Type (T : Entity_Id) return Boolean is Gen_Par : Entity_Id; F : Node_Id; begin if not Is_Generic_Instance (Current_Scope) or else not Used_As_Generic_Actual (T) then return False; else Gen_Par := Generic_Parent (Parent (Current_Scope)); end if; F := First (Generic_Formal_Declarations (Unit_Declaration_Node (Gen_Par))); while Present (F) loop if Ekind (Defining_Identifier (F)) = E_Incomplete_Type then return True; end if; Next (F); end loop; return False; end Is_Actual_For_Formal_Incomplete_Type; -- Start of processing for Check_Premature_Freezing begin -- Note that if the type is a (subtype of) a generic actual, the -- actual will have been frozen by the instantiation. if Present (N) and then Is_Private_Type (Typ) and then No (Full_View (Typ)) and then not Is_Generic_Type (Typ) and then not Is_Tagged_Type (Typ) and then not Is_Frozen (Typ) and then not Is_Generic_Actual_Type (Typ) then Error_Msg_Sloc := Sloc (Subp); Error_Msg_NE ("declaration must appear after completion of type &", N, Typ); Error_Msg_NE ("\which is an untagged type in the profile of " & "primitive operation & declared#", N, Subp); else Comp := Private_Component (Typ); if not Is_Tagged_Type (Typ) and then Present (Comp) and then not Is_Frozen (Comp) and then not Is_Actual_For_Formal_Incomplete_Type (Comp) then Error_Msg_Sloc := Sloc (Subp); Error_Msg_Node_2 := Subp; Error_Msg_Name_1 := Chars (Tagged_Type); Error_Msg_NE ("declaration must appear after completion of type &", N, Comp); Error_Msg_NE ("\which is a component of untagged type& in the profile " & "of primitive & of type % that is frozen by the " & "declaration ", N, Typ); end if; end if; end Check_Premature_Freezing; --------------- -- Export_DT -- --------------- procedure Export_DT (Typ : Entity_Id; DT : Entity_Id; Index : Nat := 0) is Count : Nat; Elmt : Elmt_Id; begin Set_Is_Statically_Allocated (DT); Set_Is_True_Constant (DT); Set_Is_Exported (DT); Count := 0; Elmt := First_Elmt (Dispatch_Table_Wrappers (Typ)); while Count /= Index loop Next_Elmt (Elmt); Count := Count + 1; end loop; pragma Assert (Related_Type (Node (Elmt)) = Typ); Get_External_Name (Node (Elmt)); Set_Interface_Name (DT, Make_String_Literal (Loc, Strval => String_From_Name_Buffer)); -- Ensure proper Sprint output of this implicit importation Set_Is_Internal (DT); Set_Is_Public (DT); end Export_DT; ----------------------- -- Make_Secondary_DT -- ----------------------- procedure Make_Secondary_DT (Typ : Entity_Id; Iface : Entity_Id; Iface_Comp : Node_Id; Suffix_Index : Int; Num_Iface_Prims : Nat; Iface_DT_Ptr : Entity_Id; Predef_Prims_Ptr : Entity_Id; Build_Thunks : Boolean; Result : List_Id) is Loc : constant Source_Ptr := Sloc (Typ); Exporting_Table : constant Boolean := Building_Static_DT (Typ) and then Suffix_Index > 0; Iface_DT : constant Entity_Id := Make_Temporary (Loc, 'T'); Predef_Prims : constant Entity_Id := Make_Temporary (Loc, 'R'); DT_Constr_List : List_Id; DT_Aggr_List : List_Id; Empty_DT : Boolean := False; Nb_Prim : Nat; New_Node : Node_Id; OSD : Entity_Id; OSD_Aggr_List : List_Id; Prim : Entity_Id; Prim_Elmt : Elmt_Id; Prim_Ops_Aggr_List : List_Id; begin -- Handle cases in which we do not generate statically allocated -- dispatch tables. if not Building_Static_DT (Typ) then Set_Ekind (Predef_Prims, E_Variable); Set_Ekind (Iface_DT, E_Variable); -- Statically allocated dispatch tables and related entities are -- constants. else Set_Ekind (Predef_Prims, E_Constant); Set_Is_Statically_Allocated (Predef_Prims); Set_Is_True_Constant (Predef_Prims); Set_Ekind (Iface_DT, E_Constant); Set_Is_Statically_Allocated (Iface_DT); Set_Is_True_Constant (Iface_DT); end if; -- Calculate the number of slots of the dispatch table. If the number -- of primitives of Typ is 0 we reserve a dummy single entry for its -- DT because at run time the pointer to this dummy entry will be -- used as the tag. if Num_Iface_Prims = 0 then Empty_DT := True; Nb_Prim := 1; else Nb_Prim := Num_Iface_Prims; end if; -- Generate: -- Predef_Prims : Address_Array (1 .. Default_Prim_Ops_Count) := -- (predef-prim-op-thunk-1'address, -- predef-prim-op-thunk-2'address, -- ... -- predef-prim-op-thunk-n'address); -- Create the thunks associated with the predefined primitives and -- save their entity to fill the aggregate. declare Nb_P_Prims : constant Nat := Number_Of_Predefined_Prims (Typ); Prim_Table : array (Nat range 1 .. Nb_P_Prims) of Entity_Id; Decl : Node_Id; Thunk_Id : Entity_Id; Thunk_Code : Node_Id; begin Prim_Ops_Aggr_List := New_List; Prim_Table := (others => Empty); if Building_Static_DT (Typ) then Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if Is_Predefined_Dispatching_Operation (Prim) and then not Is_Abstract_Subprogram (Prim) and then not Is_Eliminated (Prim) and then not Generate_SCIL and then not Present (Prim_Table (UI_To_Int (DT_Position (Prim)))) then if not Build_Thunks then Prim_Table (UI_To_Int (DT_Position (Prim))) := Alias (Prim); else Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code, Iface); if Present (Thunk_Id) then Append_To (Result, Thunk_Code); Prim_Table (UI_To_Int (DT_Position (Prim))) := Thunk_Id; end if; end if; end if; Next_Elmt (Prim_Elmt); end loop; end if; for J in Prim_Table'Range loop if Present (Prim_Table (J)) then New_Node := Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim_Table (J), Loc), Attribute_Name => Name_Unrestricted_Access)); else New_Node := Make_Null (Loc); end if; Append_To (Prim_Ops_Aggr_List, New_Node); end loop; New_Node := Make_Aggregate (Loc, Expressions => Prim_Ops_Aggr_List); -- Remember aggregates initializing dispatch tables Append_Elmt (New_Node, DT_Aggr); Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'S'), Subtype_Indication => New_Occurrence_Of (RTE (RE_Address_Array), Loc)); Append_To (Result, Decl); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Predef_Prims, Constant_Present => Building_Static_DT (Typ), Aliased_Present => True, Object_Definition => New_Occurrence_Of (Defining_Identifier (Decl), Loc), Expression => New_Node)); end; -- Generate -- OSD : Ada.Tags.Object_Specific_Data (Nb_Prims) := -- (OSD_Table => (1 => <value>, -- ... -- N => <value>)); -- for OSD'Alignment use Address'Alignment; -- Iface_DT : Dispatch_Table (Nb_Prims) := -- ([ Signature => <sig-value> ], -- Tag_Kind => <tag_kind-value>, -- Predef_Prims => Predef_Prims'Address, -- Offset_To_Top => 0, -- OSD => OSD'Address, -- Prims_Ptr => (prim-op-1'address, -- prim-op-2'address, -- ... -- prim-op-n'address)); -- Stage 3: Initialize the discriminant and the record components DT_Constr_List := New_List; DT_Aggr_List := New_List; -- Nb_Prim Append_To (DT_Constr_List, Make_Integer_Literal (Loc, Nb_Prim)); Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, Nb_Prim)); -- Signature if RTE_Record_Component_Available (RE_Signature) then Append_To (DT_Aggr_List, New_Occurrence_Of (RTE (RE_Secondary_DT), Loc)); end if; -- Tag_Kind if RTE_Record_Component_Available (RE_Tag_Kind) then Append_To (DT_Aggr_List, Tagged_Kind (Typ)); end if; -- Predef_Prims Append_To (DT_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Predef_Prims, Loc), Attribute_Name => Name_Address)); -- Interface component located at variable offset; the value of -- Offset_To_Top will be set by the init subprogram. if No (Dummy_Object) or else Is_Variable_Size_Record (Etype (Scope (Iface_Comp))) then Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0)); -- Interface component located at fixed offset else Append_To (DT_Aggr_List, Make_Op_Minus (Loc, Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (Dummy_Object, Loc), Selector_Name => New_Occurrence_Of (Iface_Comp, Loc)), Attribute_Name => Name_Position))); end if; -- Generate the Object Specific Data table required to dispatch calls -- through synchronized interfaces. if Empty_DT or else Is_Abstract_Type (Typ) or else Is_Controlled (Typ) or else Restriction_Active (No_Dispatching_Calls) or else not Is_Limited_Type (Typ) or else not Has_Interfaces (Typ) or else not Build_Thunks or else not RTE_Record_Component_Available (RE_OSD_Table) then -- No OSD table required Append_To (DT_Aggr_List, New_Occurrence_Of (RTE (RE_Null_Address), Loc)); else OSD_Aggr_List := New_List; declare Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id; Prim : Entity_Id; Prim_Alias : Entity_Id; Prim_Elmt : Elmt_Id; E : Entity_Id; Count : Nat := 0; Pos : Nat; begin Prim_Table := (others => Empty); Prim_Alias := Empty; Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if Present (Interface_Alias (Prim)) and then Find_Dispatching_Type (Interface_Alias (Prim)) = Iface then Prim_Alias := Interface_Alias (Prim); E := Ultimate_Alias (Prim); Pos := UI_To_Int (DT_Position (Prim_Alias)); if Present (Prim_Table (Pos)) then pragma Assert (Prim_Table (Pos) = E); null; else Prim_Table (Pos) := E; Append_To (OSD_Aggr_List, Make_Component_Association (Loc, Choices => New_List ( Make_Integer_Literal (Loc, DT_Position (Prim_Alias))), Expression => Make_Integer_Literal (Loc, DT_Position (Alias (Prim))))); Count := Count + 1; end if; end if; Next_Elmt (Prim_Elmt); end loop; pragma Assert (Count = Nb_Prim); end; OSD := Make_Temporary (Loc, 'I'); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => OSD, Constant_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Object_Specific_Data), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, Nb_Prim)))), Expression => Make_Aggregate (Loc, Component_Associations => New_List ( Make_Component_Association (Loc, Choices => New_List ( New_Occurrence_Of (RTE_Record_Component (RE_OSD_Num_Prims), Loc)), Expression => Make_Integer_Literal (Loc, Nb_Prim)), Make_Component_Association (Loc, Choices => New_List ( New_Occurrence_Of (RTE_Record_Component (RE_OSD_Table), Loc)), Expression => Make_Aggregate (Loc, Component_Associations => OSD_Aggr_List)))))); Append_To (Result, Make_Attribute_Definition_Clause (Loc, Name => New_Occurrence_Of (OSD, Loc), Chars => Name_Alignment, Expression => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (RTE (RE_Integer_Address), Loc), Attribute_Name => Name_Alignment))); -- In secondary dispatch tables the Typeinfo component contains -- the address of the Object Specific Data (see a-tags.ads). Append_To (DT_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (OSD, Loc), Attribute_Name => Name_Address)); end if; -- Initialize the table of primitive operations Prim_Ops_Aggr_List := New_List; if Empty_DT then Append_To (Prim_Ops_Aggr_List, Make_Null (Loc)); elsif Is_Abstract_Type (Typ) or else not Building_Static_DT (Typ) then for J in 1 .. Nb_Prim loop Append_To (Prim_Ops_Aggr_List, Make_Null (Loc)); end loop; else declare CPP_Nb_Prims : constant Nat := CPP_Num_Prims (Typ); E : Entity_Id; Prim_Pos : Nat; Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id; Thunk_Code : Node_Id; Thunk_Id : Entity_Id; begin Prim_Table := (others => Empty); Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); E := Ultimate_Alias (Prim); Prim_Pos := UI_To_Int (DT_Position (E)); -- Do not reference predefined primitives because they are -- located in a separate dispatch table; skip abstract and -- eliminated primitives; skip primitives located in the C++ -- part of the dispatch table because their slot is set by -- the IC routine. if not Is_Predefined_Dispatching_Operation (Prim) and then Present (Interface_Alias (Prim)) and then not Is_Abstract_Subprogram (Alias (Prim)) and then not Is_Eliminated (Alias (Prim)) and then (not Is_CPP_Class (Root_Type (Typ)) or else Prim_Pos > CPP_Nb_Prims) and then Find_Dispatching_Type (Interface_Alias (Prim)) = Iface -- Generate the code of the thunk only if the abstract -- interface type is not an immediate ancestor of -- Tagged_Type. Otherwise the DT associated with the -- interface is the primary DT. and then not Is_Ancestor (Iface, Typ, Use_Full_View => True) then if not Build_Thunks then Prim_Pos := UI_To_Int (DT_Position (Interface_Alias (Prim))); Prim_Table (Prim_Pos) := Alias (Prim); else Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code, Iface); if Present (Thunk_Id) then Prim_Pos := UI_To_Int (DT_Position (Interface_Alias (Prim))); Prim_Table (Prim_Pos) := Thunk_Id; Append_To (Result, Thunk_Code); end if; end if; end if; Next_Elmt (Prim_Elmt); end loop; for J in Prim_Table'Range loop if Present (Prim_Table (J)) then New_Node := Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim_Table (J), Loc), Attribute_Name => Name_Unrestricted_Access)); else New_Node := Make_Null (Loc); end if; Append_To (Prim_Ops_Aggr_List, New_Node); end loop; end; end if; New_Node := Make_Aggregate (Loc, Expressions => Prim_Ops_Aggr_List); Append_To (DT_Aggr_List, New_Node); -- Remember aggregates initializing dispatch tables Append_Elmt (New_Node, DT_Aggr); -- Note: Secondary dispatch tables are declared constant only if -- we can compute their offset field by means of the extra dummy -- object; otherwise they cannot be declared constant and the -- Offset_To_Top component is initialized by the IP routine. Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Iface_DT, Aliased_Present => True, Constant_Present => Building_Static_Secondary_DT (Typ), Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => DT_Constr_List)), Expression => Make_Aggregate (Loc, Expressions => DT_Aggr_List))); if Exporting_Table then Export_DT (Typ, Iface_DT, Suffix_Index); -- Generate code to create the pointer to the dispatch table -- Iface_DT_Ptr : Tag := Tag!(DT.Prims_Ptr'Address); -- Note: This declaration is not added here if the table is exported -- because in such case Make_Tags has already added this declaration. else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Iface_DT_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Interface_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Interface_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (Iface_DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); end if; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Predef_Prims_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Address), Loc), Expression => Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (Iface_DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Predef_Prims), Loc)), Attribute_Name => Name_Address))); -- Remember entities containing dispatch tables Append_Elmt (Predef_Prims, DT_Decl); Append_Elmt (Iface_DT, DT_Decl); end Make_Secondary_DT; -------------------------------- -- Number_Of_Predefined_Prims -- -------------------------------- function Number_Of_Predefined_Prims (Typ : Entity_Id) return Nat is Nb_Predef_Prims : Nat := 0; begin if not Generate_SCIL then declare Prim : Entity_Id; Prim_Elmt : Elmt_Id; Pos : Nat; begin Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if Is_Predefined_Dispatching_Operation (Prim) and then not Is_Abstract_Subprogram (Prim) then Pos := UI_To_Int (DT_Position (Prim)); if Pos > Nb_Predef_Prims then Nb_Predef_Prims := Pos; end if; end if; Next_Elmt (Prim_Elmt); end loop; end; end if; pragma Assert (Nb_Predef_Prims <= Max_Predef_Prims); return Nb_Predef_Prims; end Number_Of_Predefined_Prims; -- Local variables Elab_Code : constant List_Id := New_List; Result : constant List_Id := New_List; Tname : constant Name_Id := Chars (Typ); -- When pragmas Discard_Names and No_Tagged_Streams simultaneously apply -- we initialize the Expanded_Name and the External_Tag of this tagged -- type with an empty string. This is useful to avoid exposing entity -- names at binary level. It can be done when both pragmas apply because -- (1) Discard_Names allows initializing Expanded_Name with an -- implementation defined value (Ada RM Section C.5 (7/2)). -- (2) External_Tag (combined with Internal_Tag) is used for object -- streaming and No_Tagged_Streams inhibits the generation of -- streams. Discard_Names : constant Boolean := Present (No_Tagged_Streams_Pragma (Typ)) and then (Global_Discard_Names or else Einfo.Discard_Names (Typ)); -- The following name entries are used by Make_DT to generate a number -- of entities related to a tagged type. These entities may be generated -- in a scope other than that of the tagged type declaration, and if -- the entities for two tagged types with the same name happen to be -- generated in the same scope, we have to take care to use different -- names. This is achieved by means of a unique serial number appended -- to each generated entity name. Name_DT : constant Name_Id := New_External_Name (Tname, 'T', Suffix_Index => -1); Name_Exname : constant Name_Id := New_External_Name (Tname, 'E', Suffix_Index => -1); Name_HT_Link : constant Name_Id := New_External_Name (Tname, 'H', Suffix_Index => -1); Name_Predef_Prims : constant Name_Id := New_External_Name (Tname, 'R', Suffix_Index => -1); Name_SSD : constant Name_Id := New_External_Name (Tname, 'S', Suffix_Index => -1); Name_TSD : constant Name_Id := New_External_Name (Tname, 'B', Suffix_Index => -1); Saved_GM : constant Ghost_Mode_Type := Ghost_Mode; Saved_IGR : constant Node_Id := Ignored_Ghost_Region; -- Save the Ghost-related attributes to restore on exit AI : Elmt_Id; AI_Tag_Elmt : Elmt_Id; AI_Tag_Comp : Elmt_Id; DT : Entity_Id; DT_Aggr_List : List_Id; DT_Constr_List : List_Id; DT_Ptr : Entity_Id; Exname : Entity_Id; HT_Link : Entity_Id; ITable : Node_Id; I_Depth : Nat := 0; Iface_Table_Node : Node_Id; Name_ITable : Name_Id; Nb_Prim : Nat := 0; New_Node : Node_Id; Num_Ifaces : Nat := 0; Parent_Typ : Entity_Id; Predef_Prims : Entity_Id; Prim : Entity_Id; Prim_Elmt : Elmt_Id; Prim_Ops_Aggr_List : List_Id; SSD : Entity_Id; Suffix_Index : Int; Typ_Comps : Elist_Id; Typ_Ifaces : Elist_Id; TSD : Entity_Id; TSD_Aggr_List : List_Id; TSD_Tags_List : List_Id; -- Start of processing for Make_DT begin pragma Assert (Is_Frozen (Typ)); -- The tagged type being processed may be subject to pragma Ghost. Set -- the mode now to ensure that any nodes generated during dispatch table -- creation are properly marked as Ghost. Set_Ghost_Mode (Typ); -- Handle cases in which there is no need to build the dispatch table if Has_Dispatch_Table (Typ) or else No (Access_Disp_Table (Typ)) or else Is_CPP_Class (Typ) then goto Leave; elsif No_Run_Time_Mode then Error_Msg_CRT ("tagged types", Typ); goto Leave; elsif not RTE_Available (RE_Tag) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Node (First_Elmt (Access_Disp_Table (Typ))), Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Constant_Present => True, Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc)))); Analyze_List (Result, Suppress => All_Checks); Error_Msg_CRT ("tagged types", Typ); goto Leave; end if; -- Ensure that the value of Max_Predef_Prims defined in a-tags is -- correct. Valid values are 10 under configurable runtime or 16 -- with full runtime. if RTE_Available (RE_Interface_Data) then if Max_Predef_Prims /= 16 then Error_Msg_N ("run-time library configuration error", Typ); goto Leave; end if; else if Max_Predef_Prims /= 10 then Error_Msg_N ("run-time library configuration error", Typ); Error_Msg_CRT ("tagged types", Typ); goto Leave; end if; end if; DT := Make_Defining_Identifier (Loc, Name_DT); Exname := Make_Defining_Identifier (Loc, Name_Exname); HT_Link := Make_Defining_Identifier (Loc, Name_HT_Link); Predef_Prims := Make_Defining_Identifier (Loc, Name_Predef_Prims); SSD := Make_Defining_Identifier (Loc, Name_SSD); TSD := Make_Defining_Identifier (Loc, Name_TSD); -- Initialize Parent_Typ handling private types Parent_Typ := Etype (Typ); if Present (Full_View (Parent_Typ)) then Parent_Typ := Full_View (Parent_Typ); end if; -- Ensure that all the primitives are frozen. This is only required when -- building static dispatch tables --- the primitives must be frozen to -- be referenced (otherwise we have problems with the backend). It is -- not a requirement with nonstatic dispatch tables because in this case -- we generate now an empty dispatch table; the extra code required to -- register the primitives in the slots will be generated later --- when -- each primitive is frozen (see Freeze_Subprogram). if Building_Static_DT (Typ) then declare Saved_FLLTT : constant Boolean := Freezing_Library_Level_Tagged_Type; Formal : Entity_Id; Frnodes : List_Id; Prim : Entity_Id; Prim_Elmt : Elmt_Id; begin Freezing_Library_Level_Tagged_Type := True; Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); Frnodes := Freeze_Entity (Prim, Typ); -- We disable this check for abstract subprograms, given that -- they cannot be called directly and thus the state of their -- untagged formals is of no concern. The RM is unclear in any -- case concerning the need for this check, and this topic may -- go back to the ARG. if not Is_Abstract_Subprogram (Prim) then Formal := First_Formal (Prim); while Present (Formal) loop Check_Premature_Freezing (Prim, Typ, Etype (Formal)); Next_Formal (Formal); end loop; Check_Premature_Freezing (Prim, Typ, Etype (Prim)); end if; if Present (Frnodes) then Append_List_To (Result, Frnodes); end if; Next_Elmt (Prim_Elmt); end loop; Freezing_Library_Level_Tagged_Type := Saved_FLLTT; end; end if; if not Is_Interface (Typ) and then Has_Interfaces (Typ) then declare Cannot_Have_Null_Disc : Boolean := False; Dummy_Object_Typ : constant Entity_Id := Typ; Name_Dummy_Object : constant Name_Id := New_External_Name (Tname, 'P', Suffix_Index => -1); begin Dummy_Object := Make_Defining_Identifier (Loc, Name_Dummy_Object); -- Define the extra object imported and constant to avoid linker -- errors (since this object is never declared). Required because -- we implement RM 13.3(19) for exported and imported (variable) -- objects by making them volatile. Set_Is_Imported (Dummy_Object); Set_Ekind (Dummy_Object, E_Constant); Set_Is_True_Constant (Dummy_Object); Set_Related_Type (Dummy_Object, Typ); -- The scope must be set now to call Get_External_Name Set_Scope (Dummy_Object, Current_Scope); Get_External_Name (Dummy_Object); Set_Interface_Name (Dummy_Object, Make_String_Literal (Loc, Strval => String_From_Name_Buffer)); -- Ensure proper Sprint output of this implicit importation Set_Is_Internal (Dummy_Object); if not Has_Discriminants (Dummy_Object_Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Dummy_Object, Constant_Present => True, Object_Definition => New_Occurrence_Of (Dummy_Object_Typ, Loc))); else declare Constr_List : constant List_Id := New_List; Discrim : Node_Id; begin Discrim := First_Discriminant (Dummy_Object_Typ); while Present (Discrim) loop if Is_Discrete_Type (Etype (Discrim)) then Append_To (Constr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Etype (Discrim), Loc), Attribute_Name => Name_First)); else pragma Assert (Is_Access_Type (Etype (Discrim))); Cannot_Have_Null_Disc := Cannot_Have_Null_Disc or else Can_Never_Be_Null (Etype (Discrim)); Append_To (Constr_List, Make_Null (Loc)); end if; Next_Discriminant (Discrim); end loop; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Dummy_Object, Constant_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (Dummy_Object_Typ, Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => Constr_List)))); end; end if; -- Given that the dummy object will not be declared at run time, -- analyze its declaration with expansion disabled and warnings -- and error messages ignored. Expander_Mode_Save_And_Set (False); Ignore_Errors_Enable := Ignore_Errors_Enable + 1; Analyze (Last (Result), Suppress => All_Checks); Ignore_Errors_Enable := Ignore_Errors_Enable - 1; Expander_Mode_Restore; end; end if; -- Ada 2005 (AI-251): Build the secondary dispatch tables if Has_Interfaces (Typ) then Collect_Interface_Components (Typ, Typ_Comps); -- Each secondary dispatch table is assigned an unique positive -- suffix index; such value also corresponds with the location of -- its entity in the Dispatch_Table_Wrappers list (see Make_Tags). -- Note: This value must be kept sync with the Suffix_Index values -- generated by Make_Tags Suffix_Index := 1; AI_Tag_Elmt := Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))); AI_Tag_Comp := First_Elmt (Typ_Comps); while Present (AI_Tag_Comp) loop pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'P')); -- Build the secondary table containing pointers to thunks Make_Secondary_DT (Typ => Typ, Iface => Base_Type (Related_Type (Node (AI_Tag_Comp))), Iface_Comp => Node (AI_Tag_Comp), Suffix_Index => Suffix_Index, Num_Iface_Prims => UI_To_Int (DT_Entry_Count (Node (AI_Tag_Comp))), Iface_DT_Ptr => Node (AI_Tag_Elmt), Predef_Prims_Ptr => Node (Next_Elmt (AI_Tag_Elmt)), Build_Thunks => True, Result => Result); -- Skip secondary dispatch table referencing thunks to predefined -- primitives. Next_Elmt (AI_Tag_Elmt); pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'Y')); -- Secondary dispatch table referencing user-defined primitives -- covered by this interface. Next_Elmt (AI_Tag_Elmt); pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'D')); -- Build the secondary table containing pointers to primitives -- (used to give support to Generic Dispatching Constructors). Make_Secondary_DT (Typ => Typ, Iface => Base_Type (Related_Type (Node (AI_Tag_Comp))), Iface_Comp => Node (AI_Tag_Comp), Suffix_Index => -1, Num_Iface_Prims => UI_To_Int (DT_Entry_Count (Node (AI_Tag_Comp))), Iface_DT_Ptr => Node (AI_Tag_Elmt), Predef_Prims_Ptr => Node (Next_Elmt (AI_Tag_Elmt)), Build_Thunks => False, Result => Result); -- Skip secondary dispatch table referencing predefined primitives Next_Elmt (AI_Tag_Elmt); pragma Assert (Has_Suffix (Node (AI_Tag_Elmt), 'Z')); Suffix_Index := Suffix_Index + 1; Next_Elmt (AI_Tag_Elmt); Next_Elmt (AI_Tag_Comp); end loop; end if; -- Get the _tag entity and number of primitives of its dispatch table DT_Ptr := Node (First_Elmt (Access_Disp_Table (Typ))); Nb_Prim := UI_To_Int (DT_Entry_Count (First_Tag_Component (Typ))); if Generate_SCIL then Nb_Prim := 0; end if; Set_Is_Statically_Allocated (DT, Is_Library_Level_Tagged_Type (Typ)); Set_Is_Statically_Allocated (SSD, Is_Library_Level_Tagged_Type (Typ)); Set_Is_Statically_Allocated (TSD, Is_Library_Level_Tagged_Type (Typ)); Set_Is_Statically_Allocated (Predef_Prims, Is_Library_Level_Tagged_Type (Typ)); -- In case of locally defined tagged type we declare the object -- containing the dispatch table by means of a variable. Its -- initialization is done later by means of an assignment. This is -- required to generate its External_Tag. if not Building_Static_DT (Typ) then -- Generate: -- DT : No_Dispatch_Table_Wrapper; -- DT_Ptr : Tag := !Tag (DT.NDT_Prims_Ptr'Address); if not Has_DT (Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => False, Object_Definition => New_Occurrence_Of (RTE (RE_No_Dispatch_Table_Wrapper), Loc))); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT_Ptr, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Constant_Present => True, Expression => Unchecked_Convert_To (RTE (RE_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_NDT_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); Set_Is_Statically_Allocated (DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); -- Generate the SCIL node for the previous object declaration -- because it has a tag initialization. if Generate_SCIL then New_Node := Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result))); Set_SCIL_Entity (New_Node, Typ); Set_SCIL_Node (Last (Result), New_Node); goto Leave_SCIL; -- Gnat2scil has its own implementation of dispatch tables, -- different than what is being implemented here. Generating -- further dispatch table initialization code would just -- cause gnat2scil to generate useless Scil which CodePeer -- would waste time and space analyzing, so we skip it. end if; -- Generate: -- DT : Dispatch_Table_Wrapper (Nb_Prim); -- DT_Ptr : Tag := !Tag (DT.Prims_Ptr'Address); else -- If the tagged type has no primitives we add a dummy slot -- whose address will be the tag of this type. if Nb_Prim = 0 then DT_Constr_List := New_List (Make_Integer_Literal (Loc, 1)); else DT_Constr_List := New_List (Make_Integer_Literal (Loc, Nb_Prim)); end if; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => False, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => DT_Constr_List)))); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT_Ptr, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Constant_Present => True, Expression => Unchecked_Convert_To (RTE (RE_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); Set_Is_Statically_Allocated (DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); -- Generate the SCIL node for the previous object declaration -- because it has a tag initialization. if Generate_SCIL then New_Node := Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result))); Set_SCIL_Entity (New_Node, Typ); Set_SCIL_Node (Last (Result), New_Node); goto Leave_SCIL; -- Gnat2scil has its own implementation of dispatch tables, -- different than what is being implemented here. Generating -- further dispatch table initialization code would just -- cause gnat2scil to generate useless Scil which CodePeer -- would waste time and space analyzing, so we skip it. end if; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Node (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))), Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Address), Loc), Expression => Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Predef_Prims), Loc)), Attribute_Name => Name_Address))); end if; end if; -- Generate: Expanded_Name : constant String := ""; if Discard_Names then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Exname, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, ""))); -- Generate: Exname : constant String := full_qualified_name (typ); -- The type itself may be an anonymous parent type, so use the first -- subtype to have a user-recognizable name. else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Exname, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, Fully_Qualified_Name_String (First_Subtype (Typ))))); end if; Set_Is_Statically_Allocated (Exname); Set_Is_True_Constant (Exname); -- Declare the object used by Ada.Tags.Register_Tag if RTE_Available (RE_Register_Tag) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => HT_Link, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Expression => New_Occurrence_Of (RTE (RE_No_Tag), Loc))); end if; -- Generate code to create the storage for the type specific data object -- with enough space to store the tags of the ancestors plus the tags -- of all the implemented interfaces (as described in a-tags.adb). -- TSD : Type_Specific_Data (I_Depth) := -- (Idepth => I_Depth, -- Access_Level => Type_Access_Level (Typ), -- Alignment => Typ'Alignment, -- Expanded_Name => Cstring_Ptr!(Exname'Address)) -- External_Tag => Cstring_Ptr!(Exname'Address)) -- HT_Link => HT_Link'Address, -- Transportable => <<boolean-value>>, -- Is_Abstract => <<boolean-value>>, -- Needs_Finalization => <<boolean-value>>, -- [ Size_Func => Size_Prim'Access, ] -- [ Interfaces_Table => <<access-value>>, ] -- [ SSD => SSD_Table'Address ] -- Tags_Table => (0 => null, -- 1 => Parent'Tag -- ...); TSD_Aggr_List := New_List; -- Idepth: Count ancestors to compute the inheritance depth. For private -- extensions, always go to the full view in order to compute the real -- inheritance depth. declare Current_Typ : Entity_Id; Parent_Typ : Entity_Id; begin I_Depth := 0; Current_Typ := Typ; loop Parent_Typ := Etype (Current_Typ); if Is_Private_Type (Parent_Typ) then Parent_Typ := Full_View (Base_Type (Parent_Typ)); end if; exit when Parent_Typ = Current_Typ; I_Depth := I_Depth + 1; Current_Typ := Parent_Typ; end loop; end; Append_To (TSD_Aggr_List, Make_Integer_Literal (Loc, I_Depth)); -- Access_Level Append_To (TSD_Aggr_List, Make_Integer_Literal (Loc, Type_Access_Level (Typ))); -- Alignment -- For CPP types we cannot rely on the value of 'Alignment provided -- by the backend to initialize this TSD field. if Convention (Typ) = Convention_CPP or else Is_CPP_Class (Root_Type (Typ)) then Append_To (TSD_Aggr_List, Make_Integer_Literal (Loc, 0)); else Append_To (TSD_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Alignment)); end if; -- Expanded_Name Append_To (TSD_Aggr_List, Unchecked_Convert_To (RTE (RE_Cstring_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Exname, Loc), Attribute_Name => Name_Address))); -- External_Tag of a local tagged type -- <typ>A : constant String := -- "Internal tag at 16#tag-addr#: <full-name-of-typ>"; -- The reason we generate this strange name is that we do not want to -- enter local tagged types in the global hash table used to compute -- the Internal_Tag attribute for two reasons: -- 1. It is hard to avoid a tasking race condition for entering the -- entry into the hash table. -- 2. It would cause a storage leak, unless we rig up considerable -- mechanism to remove the entry from the hash table on exit. -- So what we do is to generate the above external tag name, where the -- hex address is the address of the local dispatch table (i.e. exactly -- the value we want if Internal_Tag is computed from this string). -- Of course this value will only be valid if the tagged type is still -- in scope, but it clearly must be erroneous to compute the internal -- tag of a tagged type that is out of scope. -- We don't do this processing if an explicit external tag has been -- specified. That's an odd case for which we have already issued a -- warning, where we will not be able to compute the internal tag. if not Discard_Names and then not Is_Library_Level_Entity (Typ) and then not Has_External_Tag_Rep_Clause (Typ) then declare Exname : constant Entity_Id := Make_Defining_Identifier (Loc, Chars => New_External_Name (Tname, 'A')); Full_Name : constant String_Id := Fully_Qualified_Name_String (First_Subtype (Typ)); Str1_Id : String_Id; Str2_Id : String_Id; begin -- Generate: -- Str1 = "Internal tag at 16#"; Start_String; Store_String_Chars ("Internal tag at 16#"); Str1_Id := End_String; -- Generate: -- Str2 = "#: <type-full-name>"; Start_String; Store_String_Chars ("#: "); Store_String_Chars (Full_Name); Str2_Id := End_String; -- Generate: -- Exname : constant String := -- Str1 & Address_Image (Tag) & Str2; if RTE_Available (RE_Address_Image) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Exname, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_Op_Concat (Loc, Left_Opnd => Make_String_Literal (Loc, Str1_Id), Right_Opnd => Make_Op_Concat (Loc, Left_Opnd => Make_Function_Call (Loc, Name => New_Occurrence_Of (RTE (RE_Address_Image), Loc), Parameter_Associations => New_List ( Unchecked_Convert_To (RTE (RE_Address), New_Occurrence_Of (DT_Ptr, Loc)))), Right_Opnd => Make_String_Literal (Loc, Str2_Id))))); -- Generate: -- Exname : constant String := Str1 & Str2; else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Exname, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_Op_Concat (Loc, Left_Opnd => Make_String_Literal (Loc, Str1_Id), Right_Opnd => Make_String_Literal (Loc, Str2_Id)))); end if; New_Node := Unchecked_Convert_To (RTE (RE_Cstring_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Exname, Loc), Attribute_Name => Name_Address)); end; -- External tag of a library-level tagged type: Check for a definition -- of External_Tag. The clause is considered only if it applies to this -- specific tagged type, as opposed to one of its ancestors. -- If the type is an unconstrained type extension, we are building the -- dispatch table of its anonymous base type, so the external tag, if -- any was specified, must be retrieved from the first subtype. Go to -- the full view in case the clause is in the private part. else declare Def : constant Node_Id := Get_Attribute_Definition_Clause (Underlying_Type (First_Subtype (Typ)), Attribute_External_Tag); Old_Val : String_Id; New_Val : String_Id; E : Entity_Id; begin if not Present (Def) or else Entity (Name (Def)) /= First_Subtype (Typ) then New_Node := Unchecked_Convert_To (RTE (RE_Cstring_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Exname, Loc), Attribute_Name => Name_Address)); else Old_Val := Strval (Expr_Value_S (Expression (Def))); -- For the rep clause "for <typ>'external_tag use y" generate: -- <typ>A : constant string := y; -- -- <typ>A'Address is used to set the External_Tag component -- of the TSD -- Create a new nul terminated string if it is not already if String_Length (Old_Val) > 0 and then Get_String_Char (Old_Val, String_Length (Old_Val)) = 0 then New_Val := Old_Val; else Start_String (Old_Val); Store_String_Char (Get_Char_Code (ASCII.NUL)); New_Val := End_String; end if; E := Make_Defining_Identifier (Loc, New_External_Name (Chars (Typ), 'A')); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => E, Constant_Present => True, Object_Definition => New_Occurrence_Of (Standard_String, Loc), Expression => Make_String_Literal (Loc, New_Val))); New_Node := Unchecked_Convert_To (RTE (RE_Cstring_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (E, Loc), Attribute_Name => Name_Address)); end if; end; end if; Append_To (TSD_Aggr_List, New_Node); -- HT_Link if RTE_Available (RE_Register_Tag) then Append_To (TSD_Aggr_List, Unchecked_Convert_To (RTE (RE_Tag_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (HT_Link, Loc), Attribute_Name => Name_Address))); elsif RTE_Record_Component_Available (RE_HT_Link) then Append_To (TSD_Aggr_List, Unchecked_Convert_To (RTE (RE_Tag_Ptr), New_Occurrence_Of (RTE (RE_Null_Address), Loc))); end if; -- Transportable: Set for types that can be used in remote calls -- with respect to E.4(18) legality rules. declare Transportable : Entity_Id; begin Transportable := Boolean_Literals (Is_Pure (Typ) or else Is_Shared_Passive (Typ) or else ((Is_Remote_Types (Typ) or else Is_Remote_Call_Interface (Typ)) and then Original_View_In_Visible_Part (Typ)) or else not Comes_From_Source (Typ)); Append_To (TSD_Aggr_List, New_Occurrence_Of (Transportable, Loc)); end; -- Is_Abstract (Ada 2012: AI05-0173). This functionality is not -- available in the HIE runtime. if RTE_Record_Component_Available (RE_Is_Abstract) then declare Is_Abstract : Entity_Id; begin Is_Abstract := Boolean_Literals (Is_Abstract_Type (Typ)); Append_To (TSD_Aggr_List, New_Occurrence_Of (Is_Abstract, Loc)); end; end if; -- Needs_Finalization: Set if the type is controlled or has controlled -- components. declare Needs_Fin : Entity_Id; begin Needs_Fin := Boolean_Literals (Needs_Finalization (Typ)); Append_To (TSD_Aggr_List, New_Occurrence_Of (Needs_Fin, Loc)); end; -- Size_Func if RTE_Record_Component_Available (RE_Size_Func) then -- Initialize this field to Null_Address if we are not building -- static dispatch tables static or if the size function is not -- available. In the former case we cannot initialize this field -- until the function is frozen and registered in the dispatch -- table (see Register_Primitive). if not Building_Static_DT (Typ) or else not Has_DT (Typ) then Append_To (TSD_Aggr_List, Unchecked_Convert_To (RTE (RE_Size_Ptr), New_Occurrence_Of (RTE (RE_Null_Address), Loc))); else declare Prim_Elmt : Elmt_Id; Prim : Entity_Id; Size_Comp : Node_Id := Empty; begin Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if Chars (Prim) = Name_uSize then Prim := Ultimate_Alias (Prim); if Is_Abstract_Subprogram (Prim) then Size_Comp := Unchecked_Convert_To (RTE (RE_Size_Ptr), New_Occurrence_Of (RTE (RE_Null_Address), Loc)); else Size_Comp := Unchecked_Convert_To (RTE (RE_Size_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim, Loc), Attribute_Name => Name_Unrestricted_Access)); end if; exit; end if; Next_Elmt (Prim_Elmt); end loop; pragma Assert (Present (Size_Comp)); Append_To (TSD_Aggr_List, Size_Comp); end; end if; end if; -- Interfaces_Table (required for AI-405) if RTE_Record_Component_Available (RE_Interfaces_Table) then -- Count the number of interface types implemented by Typ Collect_Interfaces (Typ, Typ_Ifaces); AI := First_Elmt (Typ_Ifaces); while Present (AI) loop Num_Ifaces := Num_Ifaces + 1; Next_Elmt (AI); end loop; if Num_Ifaces = 0 then Iface_Table_Node := Make_Null (Loc); -- Generate the Interface_Table object else declare TSD_Ifaces_List : constant List_Id := New_List; Elmt : Elmt_Id; Offset_To_Top : Node_Id; Sec_DT_Tag : Node_Id; Dummy_Object_Ifaces_List : Elist_Id := No_Elist; Dummy_Object_Ifaces_Comp_List : Elist_Id := No_Elist; Dummy_Object_Ifaces_Tag_List : Elist_Id := No_Elist; -- Interfaces information of the dummy object begin -- Collect interfaces information if we need to compute the -- offset to the top using the dummy object. if Present (Dummy_Object) then Collect_Interfaces_Info (Typ, Ifaces_List => Dummy_Object_Ifaces_List, Components_List => Dummy_Object_Ifaces_Comp_List, Tags_List => Dummy_Object_Ifaces_Tag_List); end if; AI := First_Elmt (Typ_Ifaces); while Present (AI) loop if Is_Ancestor (Node (AI), Typ, Use_Full_View => True) then Sec_DT_Tag := New_Occurrence_Of (DT_Ptr, Loc); else Elmt := Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))); pragma Assert (Has_Thunks (Node (Elmt))); while Is_Tag (Node (Elmt)) and then not Is_Ancestor (Node (AI), Related_Type (Node (Elmt)), Use_Full_View => True) loop pragma Assert (Has_Thunks (Node (Elmt))); Next_Elmt (Elmt); pragma Assert (Has_Thunks (Node (Elmt))); Next_Elmt (Elmt); pragma Assert (not Has_Thunks (Node (Elmt))); Next_Elmt (Elmt); pragma Assert (not Has_Thunks (Node (Elmt))); Next_Elmt (Elmt); end loop; pragma Assert (Ekind (Node (Elmt)) = E_Constant and then not Has_Thunks (Node (Next_Elmt (Next_Elmt (Elmt))))); Sec_DT_Tag := New_Occurrence_Of (Node (Next_Elmt (Next_Elmt (Elmt))), Loc); end if; -- Use the dummy object to compute Offset_To_Top of -- components located at fixed position. if Present (Dummy_Object) then declare Iface : constant Node_Id := Node (AI); Iface_Comp : Node_Id := Empty; Iface_Comp_Elmt : Elmt_Id; Iface_Elmt : Elmt_Id; begin Iface_Elmt := First_Elmt (Dummy_Object_Ifaces_List); Iface_Comp_Elmt := First_Elmt (Dummy_Object_Ifaces_Comp_List); while Present (Iface_Elmt) loop if Node (Iface_Elmt) = Iface then Iface_Comp := Node (Iface_Comp_Elmt); exit; end if; Next_Elmt (Iface_Elmt); Next_Elmt (Iface_Comp_Elmt); end loop; pragma Assert (Present (Iface_Comp)); if not Is_Variable_Size_Record (Etype (Scope (Iface_Comp))) then Offset_To_Top := Make_Op_Minus (Loc, Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (Dummy_Object, Loc), Selector_Name => New_Occurrence_Of (Iface_Comp, Loc)), Attribute_Name => Name_Position)); else Offset_To_Top := Make_Integer_Literal (Loc, 0); end if; end; else Offset_To_Top := Make_Integer_Literal (Loc, 0); end if; Append_To (TSD_Ifaces_List, Make_Aggregate (Loc, Expressions => New_List ( -- Iface_Tag Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Node (AI)))), Loc)), -- Static_Offset_To_Top New_Occurrence_Of (Standard_True, Loc), -- Offset_To_Top_Value Offset_To_Top, -- Offset_To_Top_Func Make_Null (Loc), -- Secondary_DT Unchecked_Convert_To (RTE (RE_Tag), Sec_DT_Tag)))); Next_Elmt (AI); end loop; Name_ITable := New_External_Name (Tname, 'I'); ITable := Make_Defining_Identifier (Loc, Name_ITable); Set_Is_Statically_Allocated (ITable, Is_Library_Level_Tagged_Type (Typ)); -- The table of interfaces is constant if we are building a -- static dispatch table; otherwise is not constant because -- its slots are filled at run time by the IP routine. Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => ITable, Aliased_Present => True, Constant_Present => Building_Static_Secondary_DT (Typ), Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Interface_Data), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, Num_Ifaces)))), Expression => Make_Aggregate (Loc, Expressions => New_List ( Make_Integer_Literal (Loc, Num_Ifaces), Make_Aggregate (Loc, TSD_Ifaces_List))))); Iface_Table_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (ITable, Loc), Attribute_Name => Name_Unchecked_Access); end; end if; Append_To (TSD_Aggr_List, Iface_Table_Node); end if; -- Generate the Select Specific Data table for synchronized types that -- implement synchronized interfaces. The size of the table is -- constrained by the number of non-predefined primitive operations. if RTE_Record_Component_Available (RE_SSD) then if Ada_Version >= Ada_2005 and then Has_DT (Typ) and then Is_Concurrent_Record_Type (Typ) and then Has_Interfaces (Typ) and then Nb_Prim > 0 and then not Is_Abstract_Type (Typ) and then not Is_Controlled (Typ) and then not Restriction_Active (No_Dispatching_Calls) and then not Restriction_Active (No_Select_Statements) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => SSD, Aliased_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of ( RTE (RE_Select_Specific_Data), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, Nb_Prim)))))); Append_To (Result, Make_Attribute_Definition_Clause (Loc, Name => New_Occurrence_Of (SSD, Loc), Chars => Name_Alignment, Expression => Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (RTE (RE_Integer_Address), Loc), Attribute_Name => Name_Alignment))); -- This table is initialized by Make_Select_Specific_Data_Table, -- which calls Set_Entry_Index and Set_Prim_Op_Kind. Append_To (TSD_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (SSD, Loc), Attribute_Name => Name_Unchecked_Access)); else Append_To (TSD_Aggr_List, Make_Null (Loc)); end if; end if; -- Initialize the table of ancestor tags. In case of interface types -- this table is not needed. TSD_Tags_List := New_List; -- If we are not statically allocating the dispatch table then we must -- fill position 0 with null because we still have not generated the -- tag of Typ. if not Building_Static_DT (Typ) or else Is_Interface (Typ) then Append_To (TSD_Tags_List, Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc))); -- Otherwise we can safely reference the tag else Append_To (TSD_Tags_List, New_Occurrence_Of (DT_Ptr, Loc)); end if; -- Fill the rest of the table with the tags of the ancestors declare Current_Typ : Entity_Id; Parent_Typ : Entity_Id; Pos : Nat; begin Pos := 1; Current_Typ := Typ; loop Parent_Typ := Etype (Current_Typ); if Is_Private_Type (Parent_Typ) then Parent_Typ := Full_View (Base_Type (Parent_Typ)); end if; exit when Parent_Typ = Current_Typ; if Is_CPP_Class (Parent_Typ) then -- The tags defined in the C++ side will be inherited when -- the object is constructed (Exp_Ch3.Build_Init_Procedure) Append_To (TSD_Tags_List, Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc))); else Append_To (TSD_Tags_List, New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Parent_Typ))), Loc)); end if; Pos := Pos + 1; Current_Typ := Parent_Typ; end loop; pragma Assert (Pos = I_Depth + 1); end; Append_To (TSD_Aggr_List, Make_Aggregate (Loc, Expressions => TSD_Tags_List)); -- Build the TSD object Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => TSD, Aliased_Present => True, Constant_Present => Building_Static_DT (Typ), Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of ( RTE (RE_Type_Specific_Data), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => New_List ( Make_Integer_Literal (Loc, I_Depth)))), Expression => Make_Aggregate (Loc, Expressions => TSD_Aggr_List))); Set_Is_True_Constant (TSD, Building_Static_DT (Typ)); -- Initialize or declare the dispatch table object if not Has_DT (Typ) then DT_Constr_List := New_List; DT_Aggr_List := New_List; -- Typeinfo New_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (TSD, Loc), Attribute_Name => Name_Address); Append_To (DT_Constr_List, New_Node); Append_To (DT_Aggr_List, New_Copy (New_Node)); Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0)); -- In case of locally defined tagged types we have already declared -- and uninitialized object for the dispatch table, which is now -- initialized by means of the following assignment: -- DT := (TSD'Address, 0); if not Building_Static_DT (Typ) then Append_To (Result, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (DT, Loc), Expression => Make_Aggregate (Loc, DT_Aggr_List))); -- In case of library level tagged types we declare and export now -- the constant object containing the dummy dispatch table. There -- is no need to declare the tag here because it has been previously -- declared by Make_Tags -- DT : aliased constant No_Dispatch_Table := -- (NDT_TSD => TSD'Address; -- NDT_Prims_Ptr => 0); else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_No_Dispatch_Table_Wrapper), Loc), Expression => Make_Aggregate (Loc, DT_Aggr_List))); Export_DT (Typ, DT); end if; -- Common case: Typ has a dispatch table -- Generate: -- Predef_Prims : Address_Array (1 .. Default_Prim_Ops_Count) := -- (predef-prim-op-1'address, -- predef-prim-op-2'address, -- ... -- predef-prim-op-n'address); -- DT : Dispatch_Table (Nb_Prims) := -- (Signature => <sig-value>, -- Tag_Kind => <tag_kind-value>, -- Predef_Prims => Predef_Prims'First'Address, -- Offset_To_Top => 0, -- TSD => TSD'Address; -- Prims_Ptr => (prim-op-1'address, -- prim-op-2'address, -- ... -- prim-op-n'address)); -- for DT'Alignment use Address'Alignment else declare Nb_P_Prims : constant Nat := Number_Of_Predefined_Prims (Typ); Prim_Table : array (Nat range 1 .. Nb_P_Prims) of Entity_Id; Decl : Node_Id; E : Entity_Id; begin Prim_Ops_Aggr_List := New_List; Prim_Table := (others => Empty); if Building_Static_DT (Typ) then Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if Is_Predefined_Dispatching_Operation (Prim) and then not Is_Abstract_Subprogram (Prim) and then not Is_Eliminated (Prim) and then not Generate_SCIL and then not Present (Prim_Table (UI_To_Int (DT_Position (Prim)))) then E := Ultimate_Alias (Prim); pragma Assert (not Is_Abstract_Subprogram (E)); Prim_Table (UI_To_Int (DT_Position (Prim))) := E; end if; Next_Elmt (Prim_Elmt); end loop; end if; for J in Prim_Table'Range loop if Present (Prim_Table (J)) then New_Node := Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim_Table (J), Loc), Attribute_Name => Name_Unrestricted_Access)); else New_Node := Make_Null (Loc); end if; Append_To (Prim_Ops_Aggr_List, New_Node); end loop; New_Node := Make_Aggregate (Loc, Expressions => Prim_Ops_Aggr_List); Decl := Make_Subtype_Declaration (Loc, Defining_Identifier => Make_Temporary (Loc, 'S'), Subtype_Indication => New_Occurrence_Of (RTE (RE_Address_Array), Loc)); Append_To (Result, Decl); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Predef_Prims, Aliased_Present => True, Constant_Present => Building_Static_DT (Typ), Object_Definition => New_Occurrence_Of (Defining_Identifier (Decl), Loc), Expression => New_Node)); -- Remember aggregates initializing dispatch tables Append_Elmt (New_Node, DT_Aggr); end; -- Stage 1: Initialize the discriminant and the record components DT_Constr_List := New_List; DT_Aggr_List := New_List; -- Num_Prims. If the tagged type has no primitives we add a dummy -- slot whose address will be the tag of this type. if Nb_Prim = 0 then New_Node := Make_Integer_Literal (Loc, 1); else New_Node := Make_Integer_Literal (Loc, Nb_Prim); end if; Append_To (DT_Constr_List, New_Node); Append_To (DT_Aggr_List, New_Copy (New_Node)); -- Signature if RTE_Record_Component_Available (RE_Signature) then Append_To (DT_Aggr_List, New_Occurrence_Of (RTE (RE_Primary_DT), Loc)); end if; -- Tag_Kind if RTE_Record_Component_Available (RE_Tag_Kind) then Append_To (DT_Aggr_List, Tagged_Kind (Typ)); end if; -- Predef_Prims Append_To (DT_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Predef_Prims, Loc), Attribute_Name => Name_Address)); -- Offset_To_Top Append_To (DT_Aggr_List, Make_Integer_Literal (Loc, 0)); -- Typeinfo Append_To (DT_Aggr_List, Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (TSD, Loc), Attribute_Name => Name_Address)); -- Stage 2: Initialize the table of user-defined primitive operations Prim_Ops_Aggr_List := New_List; if Nb_Prim = 0 then Append_To (Prim_Ops_Aggr_List, Make_Null (Loc)); elsif not Building_Static_DT (Typ) then for J in 1 .. Nb_Prim loop Append_To (Prim_Ops_Aggr_List, Make_Null (Loc)); end loop; else declare CPP_Nb_Prims : constant Nat := CPP_Num_Prims (Typ); E : Entity_Id; Prim : Entity_Id; Prim_Elmt : Elmt_Id; Prim_Pos : Nat; Prim_Table : array (Nat range 1 .. Nb_Prim) of Entity_Id; begin Prim_Table := (others => Empty); Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- Retrieve the ultimate alias of the primitive for proper -- handling of renamings and eliminated primitives. E := Ultimate_Alias (Prim); -- If the alias is not a primitive operation then Prim does -- not rename another primitive, but rather an operation -- declared elsewhere (e.g. in another scope) and therefore -- Prim is a new primitive. if No (Find_Dispatching_Type (E)) then E := Prim; end if; Prim_Pos := UI_To_Int (DT_Position (E)); -- Skip predefined primitives because they are located in a -- separate dispatch table. if not Is_Predefined_Dispatching_Operation (Prim) and then not Is_Predefined_Dispatching_Operation (E) -- Skip entities with attribute Interface_Alias because -- those are only required to build secondary dispatch -- tables. and then not Present (Interface_Alias (Prim)) -- Skip abstract and eliminated primitives and then not Is_Abstract_Subprogram (E) and then not Is_Eliminated (E) -- For derivations of CPP types skip primitives located in -- the C++ part of the dispatch table because their slots -- are initialized by the IC routine. and then (not Is_CPP_Class (Root_Type (Typ)) or else Prim_Pos > CPP_Nb_Prims) -- Skip ignored Ghost subprograms as those will be removed -- from the executable. and then not Is_Ignored_Ghost_Entity (E) then pragma Assert (UI_To_Int (DT_Position (Prim)) <= Nb_Prim); Prim_Table (UI_To_Int (DT_Position (Prim))) := E; end if; Next_Elmt (Prim_Elmt); end loop; for J in Prim_Table'Range loop if Present (Prim_Table (J)) then New_Node := Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim_Table (J), Loc), Attribute_Name => Name_Unrestricted_Access)); else New_Node := Make_Null (Loc); end if; Append_To (Prim_Ops_Aggr_List, New_Node); end loop; end; end if; New_Node := Make_Aggregate (Loc, Expressions => Prim_Ops_Aggr_List); Append_To (DT_Aggr_List, New_Node); -- Remember aggregates initializing dispatch tables Append_Elmt (New_Node, DT_Aggr); -- In case of locally defined tagged types we have already declared -- and uninitialized object for the dispatch table, which is now -- initialized by means of an assignment. if not Building_Static_DT (Typ) then Append_To (Result, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (DT, Loc), Expression => Make_Aggregate (Loc, DT_Aggr_List))); -- In case of library level tagged types we declare now and export -- the constant object containing the dispatch table. else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => DT_Constr_List)), Expression => Make_Aggregate (Loc, DT_Aggr_List))); Export_DT (Typ, DT); end if; end if; -- Initialize the table of ancestor tags if not building static -- dispatch table if not Building_Static_DT (Typ) and then not Is_Interface (Typ) and then not Is_CPP_Class (Typ) then Append_To (Result, Make_Assignment_Statement (Loc, Name => Make_Indexed_Component (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (TSD, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Tags_Table), Loc)), Expressions => New_List (Make_Integer_Literal (Loc, 0))), Expression => New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc))); end if; -- Inherit the dispatch tables of the parent. There is no need to -- inherit anything from the parent when building static dispatch tables -- because the whole dispatch table (including inherited primitives) has -- been already built. if Building_Static_DT (Typ) then null; -- If the ancestor is a CPP_Class type we inherit the dispatch tables -- in the init proc, and we don't need to fill them in here. elsif Is_CPP_Class (Parent_Typ) then null; -- Otherwise we fill in the dispatch tables here else if Typ /= Parent_Typ and then not Is_Interface (Typ) and then not Restriction_Active (No_Dispatching_Calls) then -- Inherit the dispatch table if not Is_Interface (Typ) and then not Is_Interface (Parent_Typ) and then not Is_CPP_Class (Parent_Typ) then declare Nb_Prims : constant Int := UI_To_Int (DT_Entry_Count (First_Tag_Component (Parent_Typ))); begin Append_To (Elab_Code, Build_Inherit_Predefined_Prims (Loc, Old_Tag_Node => New_Occurrence_Of (Node (Next_Elmt (First_Elmt (Access_Disp_Table (Parent_Typ)))), Loc), New_Tag_Node => New_Occurrence_Of (Node (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))), Loc), Num_Predef_Prims => Number_Of_Predefined_Prims (Parent_Typ))); if Nb_Prims /= 0 then Append_To (Elab_Code, Build_Inherit_Prims (Loc, Typ => Typ, Old_Tag_Node => New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Parent_Typ))), Loc), New_Tag_Node => New_Occurrence_Of (DT_Ptr, Loc), Num_Prims => Nb_Prims)); end if; end; end if; -- Inherit the secondary dispatch tables of the ancestor if not Is_CPP_Class (Parent_Typ) then declare Sec_DT_Ancestor : Elmt_Id := Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Parent_Typ)))); Sec_DT_Typ : Elmt_Id := Next_Elmt (Next_Elmt (First_Elmt (Access_Disp_Table (Typ)))); procedure Copy_Secondary_DTs (Typ : Entity_Id); -- Local procedure required to climb through the ancestors -- and copy the contents of all their secondary dispatch -- tables. ------------------------ -- Copy_Secondary_DTs -- ------------------------ procedure Copy_Secondary_DTs (Typ : Entity_Id) is E : Entity_Id; Iface : Elmt_Id; begin -- Climb to the ancestor (if any) handling private types if Present (Full_View (Etype (Typ))) then if Full_View (Etype (Typ)) /= Typ then Copy_Secondary_DTs (Full_View (Etype (Typ))); end if; elsif Etype (Typ) /= Typ then Copy_Secondary_DTs (Etype (Typ)); end if; if Present (Interfaces (Typ)) and then not Is_Empty_Elmt_List (Interfaces (Typ)) then Iface := First_Elmt (Interfaces (Typ)); E := First_Entity (Typ); while Present (E) and then Present (Node (Sec_DT_Ancestor)) and then Ekind (Node (Sec_DT_Ancestor)) = E_Constant loop if Is_Tag (E) and then Chars (E) /= Name_uTag then declare Num_Prims : constant Int := UI_To_Int (DT_Entry_Count (E)); begin if not Is_Interface (Etype (Typ)) then -- Inherit first secondary dispatch table Append_To (Elab_Code, Build_Inherit_Predefined_Prims (Loc, Old_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Next_Elmt (Sec_DT_Ancestor)), Loc)), New_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Next_Elmt (Sec_DT_Typ)), Loc)), Num_Predef_Prims => Number_Of_Predefined_Prims (Parent_Typ))); if Num_Prims /= 0 then Append_To (Elab_Code, Build_Inherit_Prims (Loc, Typ => Node (Iface), Old_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Sec_DT_Ancestor), Loc)), New_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Sec_DT_Typ), Loc)), Num_Prims => Num_Prims)); end if; end if; Next_Elmt (Sec_DT_Ancestor); Next_Elmt (Sec_DT_Typ); -- Skip the secondary dispatch table of -- predefined primitives Next_Elmt (Sec_DT_Ancestor); Next_Elmt (Sec_DT_Typ); if not Is_Interface (Etype (Typ)) then -- Inherit second secondary dispatch table Append_To (Elab_Code, Build_Inherit_Predefined_Prims (Loc, Old_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Next_Elmt (Sec_DT_Ancestor)), Loc)), New_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Next_Elmt (Sec_DT_Typ)), Loc)), Num_Predef_Prims => Number_Of_Predefined_Prims (Parent_Typ))); if Num_Prims /= 0 then Append_To (Elab_Code, Build_Inherit_Prims (Loc, Typ => Node (Iface), Old_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Sec_DT_Ancestor), Loc)), New_Tag_Node => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (Node (Sec_DT_Typ), Loc)), Num_Prims => Num_Prims)); end if; end if; end; Next_Elmt (Sec_DT_Ancestor); Next_Elmt (Sec_DT_Typ); -- Skip the secondary dispatch table of -- predefined primitives Next_Elmt (Sec_DT_Ancestor); Next_Elmt (Sec_DT_Typ); Next_Elmt (Iface); end if; Next_Entity (E); end loop; end if; end Copy_Secondary_DTs; begin if Present (Node (Sec_DT_Ancestor)) and then Ekind (Node (Sec_DT_Ancestor)) = E_Constant then -- Handle private types if Present (Full_View (Typ)) then Copy_Secondary_DTs (Full_View (Typ)); else Copy_Secondary_DTs (Typ); end if; end if; end; end if; end if; end if; -- Generate code to check if the external tag of this type is the same -- as the external tag of some other declaration. -- Check_TSD (TSD'Unrestricted_Access); -- This check is a consequence of AI05-0113-1/06, so it officially -- applies to Ada 2005 (and Ada 2012). It might be argued that it is -- a desirable check to add in Ada 95 mode, but we hesitate to make -- this change, as it would be incompatible, and could conceivably -- cause a problem in existing Ada 95 code. -- We check for No_Run_Time_Mode here, because we do not want to pick -- up the RE_Check_TSD entity and call it in No_Run_Time mode. -- We cannot perform this check if the generation of its expanded name -- was discarded. if not No_Run_Time_Mode and then not Discard_Names and then Ada_Version >= Ada_2005 and then RTE_Available (RE_Check_TSD) and then not Duplicated_Tag_Checks_Suppressed (Typ) then Append_To (Elab_Code, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Check_TSD), Loc), Parameter_Associations => New_List ( Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (TSD, Loc), Attribute_Name => Name_Unchecked_Access)))); end if; -- Generate code to register the Tag in the External_Tag hash table for -- the pure Ada type only. -- Register_Tag (Dt_Ptr); -- Skip this action in the following cases: -- 1) if Register_Tag is not available. -- 2) in No_Run_Time mode. -- 3) if Typ is not defined at the library level (this is required -- to avoid adding concurrency control to the hash table used -- by the run-time to register the tags). if not No_Run_Time_Mode and then Is_Library_Level_Entity (Typ) and then RTE_Available (RE_Register_Tag) then Append_To (Elab_Code, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Register_Tag), Loc), Parameter_Associations => New_List (New_Occurrence_Of (DT_Ptr, Loc)))); end if; if not Is_Empty_List (Elab_Code) then Append_List_To (Result, Elab_Code); end if; -- Populate the two auxiliary tables used for dispatching asynchronous, -- conditional and timed selects for synchronized types that implement -- a limited interface. Skip this step in Ravenscar profile or when -- general dispatching is forbidden. if Ada_Version >= Ada_2005 and then Is_Concurrent_Record_Type (Typ) and then Has_Interfaces (Typ) and then not Restriction_Active (No_Dispatching_Calls) and then not Restriction_Active (No_Select_Statements) then Append_List_To (Result, Make_Select_Specific_Data_Table (Typ)); end if; -- Remember entities containing dispatch tables Append_Elmt (Predef_Prims, DT_Decl); Append_Elmt (DT, DT_Decl); Analyze_List (Result, Suppress => All_Checks); Set_Has_Dispatch_Table (Typ); -- Mark entities containing dispatch tables. Required by the backend to -- handle them properly. if Has_DT (Typ) then declare Elmt : Elmt_Id; begin -- Object declarations Elmt := First_Elmt (DT_Decl); while Present (Elmt) loop Set_Is_Dispatch_Table_Entity (Node (Elmt)); pragma Assert (Ekind (Etype (Node (Elmt))) = E_Array_Subtype or else Ekind (Etype (Node (Elmt))) = E_Record_Subtype); Set_Is_Dispatch_Table_Entity (Etype (Node (Elmt))); Next_Elmt (Elmt); end loop; -- Aggregates initializing dispatch tables Elmt := First_Elmt (DT_Aggr); while Present (Elmt) loop Set_Is_Dispatch_Table_Entity (Etype (Node (Elmt))); Next_Elmt (Elmt); end loop; end; end if; <<Leave_SCIL>> -- Register the tagged type in the call graph nodes table Register_CG_Node (Typ); <<Leave>> Restore_Ghost_Region (Saved_GM, Saved_IGR); return Result; end Make_DT; ------------------------------------- -- Make_Select_Specific_Data_Table -- ------------------------------------- function Make_Select_Specific_Data_Table (Typ : Entity_Id) return List_Id is Assignments : constant List_Id := New_List; Loc : constant Source_Ptr := Sloc (Typ); Conc_Typ : Entity_Id; Decls : List_Id := No_List; Prim : Entity_Id; Prim_Als : Entity_Id; Prim_Elmt : Elmt_Id; Prim_Pos : Uint; Nb_Prim : Nat := 0; type Examined_Array is array (Int range <>) of Boolean; function Find_Entry_Index (E : Entity_Id) return Uint; -- Given an entry, find its index in the visible declarations of the -- corresponding concurrent type of Typ. ---------------------- -- Find_Entry_Index -- ---------------------- function Find_Entry_Index (E : Entity_Id) return Uint is Index : Uint := Uint_1; Subp_Decl : Entity_Id; begin if Present (Decls) and then not Is_Empty_List (Decls) then Subp_Decl := First (Decls); while Present (Subp_Decl) loop if Nkind (Subp_Decl) = N_Entry_Declaration then if Defining_Identifier (Subp_Decl) = E then return Index; end if; Index := Index + 1; end if; Next (Subp_Decl); end loop; end if; return Uint_0; end Find_Entry_Index; -- Local variables Tag_Node : Node_Id; -- Start of processing for Make_Select_Specific_Data_Table begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); if Present (Corresponding_Concurrent_Type (Typ)) then Conc_Typ := Corresponding_Concurrent_Type (Typ); if Present (Full_View (Conc_Typ)) then Conc_Typ := Full_View (Conc_Typ); end if; if Ekind (Conc_Typ) = E_Protected_Type then Decls := Visible_Declarations (Protected_Definition ( Parent (Conc_Typ))); else pragma Assert (Ekind (Conc_Typ) = E_Task_Type); Decls := Visible_Declarations (Task_Definition ( Parent (Conc_Typ))); end if; end if; -- Count the non-predefined primitive operations Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if not (Is_Predefined_Dispatching_Operation (Prim) or else Is_Predefined_Dispatching_Alias (Prim)) then Nb_Prim := Nb_Prim + 1; end if; Next_Elmt (Prim_Elmt); end loop; declare Examined : Examined_Array (1 .. Nb_Prim) := (others => False); begin Prim_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- Look for primitive overriding an abstract interface subprogram if Present (Interface_Alias (Prim)) and then not Is_Ancestor (Find_Dispatching_Type (Interface_Alias (Prim)), Typ, Use_Full_View => True) and then not Examined (UI_To_Int (DT_Position (Alias (Prim)))) then Prim_Pos := DT_Position (Alias (Prim)); pragma Assert (UI_To_Int (Prim_Pos) <= Nb_Prim); Examined (UI_To_Int (Prim_Pos)) := True; -- Set the primitive operation kind regardless of subprogram -- type. Generate: -- Ada.Tags.Set_Prim_Op_Kind (DT_Ptr, <position>, <kind>); if Tagged_Type_Expansion then Tag_Node := New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; Append_To (Assignments, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Set_Prim_Op_Kind), Loc), Parameter_Associations => New_List ( Tag_Node, Make_Integer_Literal (Loc, Prim_Pos), Prim_Op_Kind (Alias (Prim), Typ)))); -- Retrieve the root of the alias chain Prim_Als := Ultimate_Alias (Prim); -- In the case of an entry wrapper, set the entry index if Ekind (Prim) = E_Procedure and then Is_Primitive_Wrapper (Prim_Als) and then Ekind (Wrapped_Entity (Prim_Als)) = E_Entry then -- Generate: -- Ada.Tags.Set_Entry_Index -- (DT_Ptr, <position>, <index>); if Tagged_Type_Expansion then Tag_Node := New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc); else Tag_Node := Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Typ, Loc), Attribute_Name => Name_Tag); end if; Append_To (Assignments, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (RTE (RE_Set_Entry_Index), Loc), Parameter_Associations => New_List ( Tag_Node, Make_Integer_Literal (Loc, Prim_Pos), Make_Integer_Literal (Loc, Find_Entry_Index (Wrapped_Entity (Prim_Als)))))); end if; end if; Next_Elmt (Prim_Elmt); end loop; end; return Assignments; end Make_Select_Specific_Data_Table; --------------- -- Make_Tags -- --------------- function Make_Tags (Typ : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (Typ); Result : constant List_Id := New_List; procedure Import_DT (Tag_Typ : Entity_Id; DT : Entity_Id; Is_Secondary_DT : Boolean); -- Import the dispatch table DT of tagged type Tag_Typ. Required to -- generate forward references and statically allocate the table. For -- primary dispatch tables that require no dispatch table generate: -- DT : static aliased constant Non_Dispatch_Table_Wrapper; -- pragma Import (Ada, DT); -- Otherwise generate: -- DT : static aliased constant Dispatch_Table_Wrapper (Nb_Prim); -- pragma Import (Ada, DT); --------------- -- Import_DT -- --------------- procedure Import_DT (Tag_Typ : Entity_Id; DT : Entity_Id; Is_Secondary_DT : Boolean) is DT_Constr_List : List_Id; Nb_Prim : Nat; begin Set_Is_Imported (DT); Set_Ekind (DT, E_Constant); Set_Related_Type (DT, Typ); -- The scope must be set now to call Get_External_Name Set_Scope (DT, Current_Scope); Get_External_Name (DT); Set_Interface_Name (DT, Make_String_Literal (Loc, Strval => String_From_Name_Buffer)); -- Ensure proper Sprint output of this implicit importation Set_Is_Internal (DT); -- Save this entity to allow Make_DT to generate its exportation Append_Elmt (DT, Dispatch_Table_Wrappers (Typ)); -- No dispatch table required if not Is_Secondary_DT and then not Has_DT (Tag_Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_No_Dispatch_Table_Wrapper), Loc))); else -- Calculate the number of primitives of the dispatch table and -- the size of the Type_Specific_Data record. Nb_Prim := UI_To_Int (DT_Entry_Count (First_Tag_Component (Tag_Typ))); -- If the tagged type has no primitives we add a dummy slot whose -- address will be the tag of this type. if Nb_Prim = 0 then DT_Constr_List := New_List (Make_Integer_Literal (Loc, 1)); else DT_Constr_List := New_List (Make_Integer_Literal (Loc, Nb_Prim)); end if; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT, Aliased_Present => True, Constant_Present => True, Object_Definition => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Dispatch_Table_Wrapper), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, Constraints => DT_Constr_List)))); end if; end Import_DT; -- Local variables Tname : constant Name_Id := Chars (Typ); AI_Tag_Comp : Elmt_Id; DT : Node_Id := Empty; DT_Ptr : Node_Id; Predef_Prims_Ptr : Node_Id; Iface_DT : Node_Id := Empty; Iface_DT_Ptr : Node_Id; New_Node : Node_Id; Suffix_Index : Int; Typ_Name : Name_Id; Typ_Comps : Elist_Id; -- Start of processing for Make_Tags begin pragma Assert (No (Access_Disp_Table (Typ))); Set_Access_Disp_Table (Typ, New_Elmt_List); -- If the elaboration of this tagged type needs a boolean flag then -- define now its entity. It is initialized to True to indicate that -- elaboration is still pending; set to False by the IP routine. -- TypFxx : boolean := True; if Elab_Flag_Needed (Typ) then Set_Access_Disp_Table_Elab_Flag (Typ, Make_Defining_Identifier (Loc, Chars => New_External_Name (Tname, 'F'))); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Access_Disp_Table_Elab_Flag (Typ), Object_Definition => New_Occurrence_Of (Standard_Boolean, Loc), Expression => New_Occurrence_Of (Standard_True, Loc))); end if; -- 1) Generate the primary tag entities -- Primary dispatch table containing user-defined primitives DT_Ptr := Make_Defining_Identifier (Loc, New_External_Name (Tname, 'P')); Set_Etype (DT_Ptr, RTE (RE_Tag)); Append_Elmt (DT_Ptr, Access_Disp_Table (Typ)); -- Minimum decoration Set_Ekind (DT_Ptr, E_Variable); Set_Related_Type (DT_Ptr, Typ); -- Notify back end that the types are associated with a dispatch table Set_Is_Dispatch_Table_Entity (RTE (RE_Prim_Ptr)); Set_Is_Dispatch_Table_Entity (RTE (RE_Predef_Prims_Table_Ptr)); -- For CPP types there is no need to build the dispatch tables since -- they are imported from the C++ side. If the CPP type has an IP then -- we declare now the variable that will store the copy of the C++ tag. -- If the CPP type is an interface, we need the variable as well because -- it becomes the pointer to the corresponding secondary table. if Is_CPP_Class (Typ) then if Has_CPP_Constructors (Typ) or else Is_Interface (Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT_Ptr, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc)))); Set_Is_Statically_Allocated (DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); end if; -- Ada types else -- Primary dispatch table containing predefined primitives Predef_Prims_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Tname, 'Y')); Set_Etype (Predef_Prims_Ptr, RTE (RE_Address)); Append_Elmt (Predef_Prims_Ptr, Access_Disp_Table (Typ)); -- Import the forward declaration of the Dispatch Table wrapper -- record (Make_DT will take care of exporting it). if Building_Static_DT (Typ) then Set_Dispatch_Table_Wrappers (Typ, New_Elmt_List); DT := Make_Defining_Identifier (Loc, Chars => New_External_Name (Tname, 'T')); Import_DT (Typ, DT, Is_Secondary_DT => False); if Has_DT (Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); -- Generate the SCIL node for the previous object declaration -- because it has a tag initialization. if Generate_SCIL then New_Node := Make_SCIL_Dispatch_Table_Tag_Init (Sloc (Last (Result))); Set_SCIL_Entity (New_Node, Typ); Set_SCIL_Node (Last (Result), New_Node); end if; Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Predef_Prims_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Address), Loc), Expression => Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Predef_Prims), Loc)), Attribute_Name => Name_Address))); -- No dispatch table required else Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => DT_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_NDT_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); end if; Set_Is_True_Constant (DT_Ptr); Set_Is_Statically_Allocated (DT_Ptr); end if; end if; -- 2) Generate the secondary tag entities -- Collect the components associated with secondary dispatch tables if Has_Interfaces (Typ) then Collect_Interface_Components (Typ, Typ_Comps); -- For each interface type we build a unique external name associated -- with its secondary dispatch table. This name is used to declare an -- object that references this secondary dispatch table, whose value -- will be used for the elaboration of Typ objects, and also for the -- elaboration of objects of types derived from Typ that do not -- override the primitives of this interface type. Suffix_Index := 1; -- Note: The value of Suffix_Index must be in sync with the values of -- Suffix_Index in secondary dispatch tables generated by Make_DT. if Is_CPP_Class (Typ) then AI_Tag_Comp := First_Elmt (Typ_Comps); while Present (AI_Tag_Comp) loop Get_Secondary_DT_External_Name (Typ, Related_Type (Node (AI_Tag_Comp)), Suffix_Index); Typ_Name := Name_Find; -- Declare variables to store copy of the C++ secondary tags Iface_DT_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'P')); Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag)); Set_Ekind (Iface_DT_Ptr, E_Variable); Set_Is_Tag (Iface_DT_Ptr); Set_Has_Thunks (Iface_DT_Ptr); Set_Related_Type (Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp))); Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ)); Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Iface_DT_Ptr, Object_Definition => New_Occurrence_Of (RTE (RE_Interface_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Interface_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc)))); Set_Is_Statically_Allocated (Iface_DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); Next_Elmt (AI_Tag_Comp); end loop; -- This is not a CPP_Class type else AI_Tag_Comp := First_Elmt (Typ_Comps); while Present (AI_Tag_Comp) loop Get_Secondary_DT_External_Name (Typ, Related_Type (Node (AI_Tag_Comp)), Suffix_Index); Typ_Name := Name_Find; if Building_Static_DT (Typ) then Iface_DT := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'T')); Import_DT (Tag_Typ => Related_Type (Node (AI_Tag_Comp)), DT => Iface_DT, Is_Secondary_DT => True); end if; -- Secondary dispatch table referencing thunks to user-defined -- primitives covered by this interface. Iface_DT_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'P')); Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag)); Set_Ekind (Iface_DT_Ptr, E_Constant); Set_Is_Tag (Iface_DT_Ptr); Set_Has_Thunks (Iface_DT_Ptr); Set_Is_Statically_Allocated (Iface_DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); Set_Is_True_Constant (Iface_DT_Ptr); Set_Related_Type (Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp))); Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ)); if Building_Static_DT (Typ) then Append_To (Result, Make_Object_Declaration (Loc, Defining_Identifier => Iface_DT_Ptr, Constant_Present => True, Object_Definition => New_Occurrence_Of (RTE (RE_Interface_Tag), Loc), Expression => Unchecked_Convert_To (RTE (RE_Interface_Tag), Make_Attribute_Reference (Loc, Prefix => Make_Selected_Component (Loc, Prefix => New_Occurrence_Of (Iface_DT, Loc), Selector_Name => New_Occurrence_Of (RTE_Record_Component (RE_Prims_Ptr), Loc)), Attribute_Name => Name_Address)))); end if; -- Secondary dispatch table referencing thunks to predefined -- primitives. Iface_DT_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'Y')); Set_Etype (Iface_DT_Ptr, RTE (RE_Address)); Set_Ekind (Iface_DT_Ptr, E_Constant); Set_Is_Tag (Iface_DT_Ptr); Set_Has_Thunks (Iface_DT_Ptr); Set_Is_Statically_Allocated (Iface_DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); Set_Is_True_Constant (Iface_DT_Ptr); Set_Related_Type (Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp))); Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ)); -- Secondary dispatch table referencing user-defined primitives -- covered by this interface. Iface_DT_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'D')); Set_Etype (Iface_DT_Ptr, RTE (RE_Interface_Tag)); Set_Ekind (Iface_DT_Ptr, E_Constant); Set_Is_Tag (Iface_DT_Ptr); Set_Is_Statically_Allocated (Iface_DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); Set_Is_True_Constant (Iface_DT_Ptr); Set_Related_Type (Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp))); Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ)); -- Secondary dispatch table referencing predefined primitives Iface_DT_Ptr := Make_Defining_Identifier (Loc, Chars => New_External_Name (Typ_Name, 'Z')); Set_Etype (Iface_DT_Ptr, RTE (RE_Address)); Set_Ekind (Iface_DT_Ptr, E_Constant); Set_Is_Tag (Iface_DT_Ptr); Set_Is_Statically_Allocated (Iface_DT_Ptr, Is_Library_Level_Tagged_Type (Typ)); Set_Is_True_Constant (Iface_DT_Ptr); Set_Related_Type (Iface_DT_Ptr, Related_Type (Node (AI_Tag_Comp))); Append_Elmt (Iface_DT_Ptr, Access_Disp_Table (Typ)); Next_Elmt (AI_Tag_Comp); end loop; end if; end if; -- 3) At the end of Access_Disp_Table, if the type has user-defined -- primitives, we add the entity of an access type declaration that -- is used by Build_Get_Prim_Op_Address to expand dispatching calls -- through the primary dispatch table. if UI_To_Int (DT_Entry_Count (First_Tag_Component (Typ))) = 0 then Analyze_List (Result); -- Generate: -- subtype Typ_DT is Address_Array (1 .. Nb_Prims); -- type Typ_DT_Acc is access Typ_DT; else declare Name_DT_Prims : constant Name_Id := New_External_Name (Tname, 'G'); Name_DT_Prims_Acc : constant Name_Id := New_External_Name (Tname, 'H'); DT_Prims : constant Entity_Id := Make_Defining_Identifier (Loc, Name_DT_Prims); DT_Prims_Acc : constant Entity_Id := Make_Defining_Identifier (Loc, Name_DT_Prims_Acc); begin Append_To (Result, Make_Subtype_Declaration (Loc, Defining_Identifier => DT_Prims, Subtype_Indication => Make_Subtype_Indication (Loc, Subtype_Mark => New_Occurrence_Of (RTE (RE_Address_Array), Loc), Constraint => Make_Index_Or_Discriminant_Constraint (Loc, New_List ( Make_Range (Loc, Low_Bound => Make_Integer_Literal (Loc, 1), High_Bound => Make_Integer_Literal (Loc, DT_Entry_Count (First_Tag_Component (Typ))))))))); Append_To (Result, Make_Full_Type_Declaration (Loc, Defining_Identifier => DT_Prims_Acc, Type_Definition => Make_Access_To_Object_Definition (Loc, Subtype_Indication => New_Occurrence_Of (DT_Prims, Loc)))); Append_Elmt (DT_Prims_Acc, Access_Disp_Table (Typ)); -- Analyze the resulting list and suppress the generation of the -- Init_Proc associated with the above array declaration because -- this type is never used in object declarations. It is only used -- to simplify the expansion associated with dispatching calls. Analyze_List (Result); Set_Suppress_Initialization (Base_Type (DT_Prims)); -- Disable backend optimizations based on assumptions about the -- aliasing status of objects designated by the access to the -- dispatch table. Required to handle dispatch tables imported -- from C++. Set_No_Strict_Aliasing (Base_Type (DT_Prims_Acc)); -- Add the freezing nodes of these declarations; required to avoid -- generating these freezing nodes in wrong scopes (for example in -- the IC routine of a derivation of Typ). -- What is an "IC routine"? Is "init_proc" meant here??? Append_List_To (Result, Freeze_Entity (DT_Prims, Typ)); Append_List_To (Result, Freeze_Entity (DT_Prims_Acc, Typ)); -- Mark entity of dispatch table. Required by the back end to -- handle them properly. Set_Is_Dispatch_Table_Entity (DT_Prims); end; end if; -- Mark entities of dispatch table. Required by the back end to handle -- them properly. if Present (DT) then Set_Is_Dispatch_Table_Entity (DT); Set_Is_Dispatch_Table_Entity (Etype (DT)); end if; if Present (Iface_DT) then Set_Is_Dispatch_Table_Entity (Iface_DT); Set_Is_Dispatch_Table_Entity (Etype (Iface_DT)); end if; if Is_CPP_Class (Root_Type (Typ)) then Set_Ekind (DT_Ptr, E_Variable); else Set_Ekind (DT_Ptr, E_Constant); end if; Set_Is_Tag (DT_Ptr); Set_Related_Type (DT_Ptr, Typ); return Result; end Make_Tags; --------------- -- New_Value -- --------------- function New_Value (From : Node_Id) return Node_Id is Res : constant Node_Id := Duplicate_Subexpr (From); begin if Is_Access_Type (Etype (From)) then return Make_Explicit_Dereference (Sloc (From), Prefix => Res); else return Res; end if; end New_Value; ----------------------------------- -- Original_View_In_Visible_Part -- ----------------------------------- function Original_View_In_Visible_Part (Typ : Entity_Id) return Boolean is Scop : constant Entity_Id := Scope (Typ); begin -- The scope must be a package if not Is_Package_Or_Generic_Package (Scop) then return False; end if; -- A type with a private declaration has a private view declared in -- the visible part. if Has_Private_Declaration (Typ) then return True; end if; return List_Containing (Parent (Typ)) = Visible_Declarations (Package_Specification (Scop)); end Original_View_In_Visible_Part; ------------------ -- Prim_Op_Kind -- ------------------ function Prim_Op_Kind (Prim : Entity_Id; Typ : Entity_Id) return Node_Id is Full_Typ : Entity_Id := Typ; Loc : constant Source_Ptr := Sloc (Prim); Prim_Op : Entity_Id; begin -- Retrieve the original primitive operation Prim_Op := Ultimate_Alias (Prim); if Ekind (Typ) = E_Record_Type and then Present (Corresponding_Concurrent_Type (Typ)) then Full_Typ := Corresponding_Concurrent_Type (Typ); end if; -- When a private tagged type is completed by a concurrent type, -- retrieve the full view. if Is_Private_Type (Full_Typ) then Full_Typ := Full_View (Full_Typ); end if; if Ekind (Prim_Op) = E_Function then -- Protected function if Ekind (Full_Typ) = E_Protected_Type then return New_Occurrence_Of (RTE (RE_POK_Protected_Function), Loc); -- Task function elsif Ekind (Full_Typ) = E_Task_Type then return New_Occurrence_Of (RTE (RE_POK_Task_Function), Loc); -- Regular function else return New_Occurrence_Of (RTE (RE_POK_Function), Loc); end if; else pragma Assert (Ekind (Prim_Op) = E_Procedure); if Ekind (Full_Typ) = E_Protected_Type then -- Protected entry if Is_Primitive_Wrapper (Prim_Op) and then Ekind (Wrapped_Entity (Prim_Op)) = E_Entry then return New_Occurrence_Of (RTE (RE_POK_Protected_Entry), Loc); -- Protected procedure else return New_Occurrence_Of (RTE (RE_POK_Protected_Procedure), Loc); end if; elsif Ekind (Full_Typ) = E_Task_Type then -- Task entry if Is_Primitive_Wrapper (Prim_Op) and then Ekind (Wrapped_Entity (Prim_Op)) = E_Entry then return New_Occurrence_Of (RTE (RE_POK_Task_Entry), Loc); -- Task "procedure". These are the internally Expander-generated -- procedures (task body for instance). else return New_Occurrence_Of (RTE (RE_POK_Task_Procedure), Loc); end if; -- Regular procedure else return New_Occurrence_Of (RTE (RE_POK_Procedure), Loc); end if; end if; end Prim_Op_Kind; ------------------------ -- Register_Primitive -- ------------------------ function Register_Primitive (Loc : Source_Ptr; Prim : Entity_Id) return List_Id is DT_Ptr : Entity_Id; Iface_Prim : Entity_Id; Iface_Typ : Entity_Id; Iface_DT_Ptr : Entity_Id; Iface_DT_Elmt : Elmt_Id; L : constant List_Id := New_List; Pos : Uint; Tag : Entity_Id; Tag_Typ : Entity_Id; Thunk_Id : Entity_Id; Thunk_Code : Node_Id; begin pragma Assert (not Restriction_Active (No_Dispatching_Calls)); -- Do not register in the dispatch table eliminated primitives if not RTE_Available (RE_Tag) or else Is_Eliminated (Ultimate_Alias (Prim)) or else Generate_SCIL then return L; end if; if not Present (Interface_Alias (Prim)) then Tag_Typ := Scope (DTC_Entity (Prim)); Pos := DT_Position (Prim); Tag := First_Tag_Component (Tag_Typ); if Is_Predefined_Dispatching_Operation (Prim) or else Is_Predefined_Dispatching_Alias (Prim) then DT_Ptr := Node (Next_Elmt (First_Elmt (Access_Disp_Table (Tag_Typ)))); Append_To (L, Build_Set_Predefined_Prim_Op_Address (Loc, Tag_Node => New_Occurrence_Of (DT_Ptr, Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim, Loc), Attribute_Name => Name_Unrestricted_Access)))); -- Register copy of the pointer to the 'size primitive in the TSD if Chars (Prim) = Name_uSize and then RTE_Record_Component_Available (RE_Size_Func) then DT_Ptr := Node (First_Elmt (Access_Disp_Table (Tag_Typ))); Append_To (L, Build_Set_Size_Function (Loc, Tag_Node => New_Occurrence_Of (DT_Ptr, Loc), Size_Func => Prim)); end if; else pragma Assert (Pos /= Uint_0 and then Pos <= DT_Entry_Count (Tag)); -- Skip registration of primitives located in the C++ part of the -- dispatch table. Their slot is set by the IC routine. if not Is_CPP_Class (Root_Type (Tag_Typ)) or else Pos > CPP_Num_Prims (Tag_Typ) then DT_Ptr := Node (First_Elmt (Access_Disp_Table (Tag_Typ))); Append_To (L, Build_Set_Prim_Op_Address (Loc, Typ => Tag_Typ, Tag_Node => New_Occurrence_Of (DT_Ptr, Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Prim, Loc), Attribute_Name => Name_Unrestricted_Access)))); end if; end if; -- Ada 2005 (AI-251): Primitive associated with an interface type -- Generate the code of the thunk only if the interface type is not an -- immediate ancestor of Typ; otherwise the dispatch table associated -- with the interface is the primary dispatch table and we have nothing -- else to do here. else Tag_Typ := Find_Dispatching_Type (Alias (Prim)); Iface_Typ := Find_Dispatching_Type (Interface_Alias (Prim)); pragma Assert (Is_Interface (Iface_Typ)); -- No action needed for interfaces that are ancestors of Typ because -- their primitives are located in the primary dispatch table. if Is_Ancestor (Iface_Typ, Tag_Typ, Use_Full_View => True) then return L; -- No action needed for primitives located in the C++ part of the -- dispatch table. Their slot is set by the IC routine. elsif Is_CPP_Class (Root_Type (Tag_Typ)) and then DT_Position (Alias (Prim)) <= CPP_Num_Prims (Tag_Typ) and then not Is_Predefined_Dispatching_Operation (Prim) and then not Is_Predefined_Dispatching_Alias (Prim) then return L; end if; Expand_Interface_Thunk (Prim, Thunk_Id, Thunk_Code, Iface_Typ); if not Is_Ancestor (Iface_Typ, Tag_Typ, Use_Full_View => True) and then Present (Thunk_Code) then -- Generate the code necessary to fill the appropriate entry of -- the secondary dispatch table of Prim's controlling type with -- Thunk_Id's address. Iface_DT_Elmt := Find_Interface_ADT (Tag_Typ, Iface_Typ); Iface_DT_Ptr := Node (Iface_DT_Elmt); pragma Assert (Has_Thunks (Iface_DT_Ptr)); Iface_Prim := Interface_Alias (Prim); Pos := DT_Position (Iface_Prim); Tag := First_Tag_Component (Iface_Typ); Prepend_To (L, Thunk_Code); if Is_Predefined_Dispatching_Operation (Prim) or else Is_Predefined_Dispatching_Alias (Prim) then Append_To (L, Build_Set_Predefined_Prim_Op_Address (Loc, Tag_Node => New_Occurrence_Of (Node (Next_Elmt (Iface_DT_Elmt)), Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Thunk_Id, Loc), Attribute_Name => Name_Unrestricted_Access)))); Next_Elmt (Iface_DT_Elmt); Next_Elmt (Iface_DT_Elmt); Iface_DT_Ptr := Node (Iface_DT_Elmt); pragma Assert (not Has_Thunks (Iface_DT_Ptr)); Append_To (L, Build_Set_Predefined_Prim_Op_Address (Loc, Tag_Node => New_Occurrence_Of (Node (Next_Elmt (Iface_DT_Elmt)), Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Alias (Prim), Loc), Attribute_Name => Name_Unrestricted_Access)))); else pragma Assert (Pos /= Uint_0 and then Pos <= DT_Entry_Count (Tag)); Append_To (L, Build_Set_Prim_Op_Address (Loc, Typ => Iface_Typ, Tag_Node => New_Occurrence_Of (Iface_DT_Ptr, Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Thunk_Id, Loc), Attribute_Name => Name_Unrestricted_Access)))); Next_Elmt (Iface_DT_Elmt); Next_Elmt (Iface_DT_Elmt); Iface_DT_Ptr := Node (Iface_DT_Elmt); pragma Assert (not Has_Thunks (Iface_DT_Ptr)); Append_To (L, Build_Set_Prim_Op_Address (Loc, Typ => Iface_Typ, Tag_Node => New_Occurrence_Of (Iface_DT_Ptr, Loc), Position => Pos, Address_Node => Unchecked_Convert_To (RTE (RE_Prim_Ptr), Make_Attribute_Reference (Loc, Prefix => New_Occurrence_Of (Ultimate_Alias (Prim), Loc), Attribute_Name => Name_Unrestricted_Access)))); end if; end if; end if; return L; end Register_Primitive; ------------------------- -- Set_All_DT_Position -- ------------------------- procedure Set_All_DT_Position (Typ : Entity_Id) is function In_Predef_Prims_DT (Prim : Entity_Id) return Boolean; -- Returns True if Prim is located in the dispatch table of -- predefined primitives procedure Validate_Position (Prim : Entity_Id); -- Check that position assigned to Prim is completely safe (it has not -- been assigned to a previously defined primitive operation of Typ). ------------------------ -- In_Predef_Prims_DT -- ------------------------ function In_Predef_Prims_DT (Prim : Entity_Id) return Boolean is begin -- Predefined primitives if Is_Predefined_Dispatching_Operation (Prim) then return True; -- Renamings of predefined primitives elsif Present (Alias (Prim)) and then Is_Predefined_Dispatching_Operation (Ultimate_Alias (Prim)) then if Chars (Ultimate_Alias (Prim)) /= Name_Op_Eq then return True; -- An overriding operation that is a user-defined renaming of -- predefined equality inherits its slot from the overridden -- operation. Otherwise it is treated as a predefined op and -- occupies the same predefined slot as equality. A call to it is -- transformed into a call to its alias, which is the predefined -- equality op. A dispatching call thus uses the proper slot if -- operation is further inherited and called with class-wide -- arguments. else return not Comes_From_Source (Prim) or else No (Overridden_Operation (Prim)); end if; -- User-defined primitives else return False; end if; end In_Predef_Prims_DT; ----------------------- -- Validate_Position -- ----------------------- procedure Validate_Position (Prim : Entity_Id) is Op_Elmt : Elmt_Id; Op : Entity_Id; begin -- Aliased primitives are safe if Present (Alias (Prim)) then return; end if; Op_Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Op_Elmt) loop Op := Node (Op_Elmt); -- No need to check against itself if Op = Prim then null; -- Primitive operations covering abstract interfaces are -- allocated later elsif Present (Interface_Alias (Op)) then null; -- Predefined dispatching operations are completely safe. They -- are allocated at fixed positions in a separate table. elsif Is_Predefined_Dispatching_Operation (Op) or else Is_Predefined_Dispatching_Alias (Op) then null; -- Aliased subprograms are safe elsif Present (Alias (Op)) then null; elsif DT_Position (Op) = DT_Position (Prim) and then not Is_Predefined_Dispatching_Operation (Op) and then not Is_Predefined_Dispatching_Operation (Prim) and then not Is_Predefined_Dispatching_Alias (Op) and then not Is_Predefined_Dispatching_Alias (Prim) then -- Handle aliased subprograms declare Op_1 : Entity_Id; Op_2 : Entity_Id; begin Op_1 := Op; loop if Present (Overridden_Operation (Op_1)) then Op_1 := Overridden_Operation (Op_1); elsif Present (Alias (Op_1)) then Op_1 := Alias (Op_1); else exit; end if; end loop; Op_2 := Prim; loop if Present (Overridden_Operation (Op_2)) then Op_2 := Overridden_Operation (Op_2); elsif Present (Alias (Op_2)) then Op_2 := Alias (Op_2); else exit; end if; end loop; if Op_1 /= Op_2 then raise Program_Error; end if; end; end if; Next_Elmt (Op_Elmt); end loop; end Validate_Position; -- Local variables Parent_Typ : constant Entity_Id := Etype (Typ); First_Prim : constant Elmt_Id := First_Elmt (Primitive_Operations (Typ)); The_Tag : constant Entity_Id := First_Tag_Component (Typ); Adjusted : Boolean := False; Finalized : Boolean := False; Count_Prim : Nat; DT_Length : Nat; Nb_Prim : Nat; Prim : Entity_Id; Prim_Elmt : Elmt_Id; -- Start of processing for Set_All_DT_Position begin pragma Assert (Present (First_Tag_Component (Typ))); -- Set the DT_Position for each primitive operation. Perform some sanity -- checks to avoid building inconsistent dispatch tables. -- First stage: Set DTC entity of all the primitive operations. This is -- required to properly read the DT_Position attribute in latter stages. Prim_Elmt := First_Prim; Count_Prim := 0; while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- Predefined primitives have a separate dispatch table if not In_Predef_Prims_DT (Prim) then Count_Prim := Count_Prim + 1; end if; Set_DTC_Entity_Value (Typ, Prim); -- Clear any previous value of the DT_Position attribute. In this -- way we ensure that the final position of all the primitives is -- established by the following stages of this algorithm. Set_DT_Position_Value (Prim, No_Uint); Next_Elmt (Prim_Elmt); end loop; declare Fixed_Prim : array (Int range 0 .. Count_Prim) of Boolean := (others => False); E : Entity_Id; procedure Handle_Inherited_Private_Subprograms (Typ : Entity_Id); -- Called if Typ is declared in a nested package or a public child -- package to handle inherited primitives that were inherited by Typ -- in the visible part, but whose declaration was deferred because -- the parent operation was private and not visible at that point. procedure Set_Fixed_Prim (Pos : Nat); -- Sets to true an element of the Fixed_Prim table to indicate -- that this entry of the dispatch table of Typ is occupied. ------------------------------------------ -- Handle_Inherited_Private_Subprograms -- ------------------------------------------ procedure Handle_Inherited_Private_Subprograms (Typ : Entity_Id) is Op_List : Elist_Id; Op_Elmt : Elmt_Id; Op_Elmt_2 : Elmt_Id; Prim_Op : Entity_Id; Parent_Subp : Entity_Id; begin Op_List := Primitive_Operations (Typ); Op_Elmt := First_Elmt (Op_List); while Present (Op_Elmt) loop Prim_Op := Node (Op_Elmt); -- Search primitives that are implicit operations with an -- internal name whose parent operation has a normal name. if Present (Alias (Prim_Op)) and then Find_Dispatching_Type (Alias (Prim_Op)) /= Typ and then not Comes_From_Source (Prim_Op) and then Is_Internal_Name (Chars (Prim_Op)) and then not Is_Internal_Name (Chars (Alias (Prim_Op))) then Parent_Subp := Alias (Prim_Op); -- Check if the type has an explicit overriding for this -- primitive. Op_Elmt_2 := Next_Elmt (Op_Elmt); while Present (Op_Elmt_2) loop if Chars (Node (Op_Elmt_2)) = Chars (Parent_Subp) and then Type_Conformant (Prim_Op, Node (Op_Elmt_2)) then Set_DT_Position_Value (Prim_Op, DT_Position (Parent_Subp)); Set_DT_Position_Value (Node (Op_Elmt_2), DT_Position (Parent_Subp)); Set_Fixed_Prim (UI_To_Int (DT_Position (Prim_Op))); goto Next_Primitive; end if; Next_Elmt (Op_Elmt_2); end loop; end if; <<Next_Primitive>> Next_Elmt (Op_Elmt); end loop; end Handle_Inherited_Private_Subprograms; -------------------- -- Set_Fixed_Prim -- -------------------- procedure Set_Fixed_Prim (Pos : Nat) is begin pragma Assert (Pos <= Count_Prim); Fixed_Prim (Pos) := True; exception when Constraint_Error => raise Program_Error; end Set_Fixed_Prim; begin -- In case of nested packages and public child package it may be -- necessary a special management on inherited subprograms so that -- the dispatch table is properly filled. if Ekind (Scope (Scope (Typ))) = E_Package and then Scope (Scope (Typ)) /= Standard_Standard and then ((Is_Derived_Type (Typ) and then not Is_Private_Type (Typ)) or else (Nkind (Parent (Typ)) = N_Private_Extension_Declaration and then Is_Generic_Type (Typ))) and then In_Open_Scopes (Scope (Etype (Typ))) and then Is_Base_Type (Typ) then Handle_Inherited_Private_Subprograms (Typ); end if; -- Second stage: Register fixed entries Nb_Prim := 0; Prim_Elmt := First_Prim; while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- Predefined primitives have a separate table and all its -- entries are at predefined fixed positions. if In_Predef_Prims_DT (Prim) then if Is_Predefined_Dispatching_Operation (Prim) then Set_DT_Position_Value (Prim, Default_Prim_Op_Position (Prim)); else pragma Assert (Present (Alias (Prim))); Set_DT_Position_Value (Prim, Default_Prim_Op_Position (Ultimate_Alias (Prim))); end if; -- Overriding primitives of ancestor abstract interfaces elsif Present (Interface_Alias (Prim)) and then Is_Ancestor (Find_Dispatching_Type (Interface_Alias (Prim)), Typ, Use_Full_View => True) then pragma Assert (DT_Position (Prim) = No_Uint and then Present (DTC_Entity (Interface_Alias (Prim)))); E := Interface_Alias (Prim); Set_DT_Position_Value (Prim, DT_Position (E)); pragma Assert (DT_Position (Alias (Prim)) = No_Uint or else DT_Position (Alias (Prim)) = DT_Position (E)); Set_DT_Position_Value (Alias (Prim), DT_Position (E)); Set_Fixed_Prim (UI_To_Int (DT_Position (Prim))); -- Overriding primitives must use the same entry as the overridden -- primitive. Note that the Alias of the operation is set when the -- operation is declared by a renaming, in which case it is not -- overriding. If it renames another primitive it will use the -- same dispatch table slot, but if it renames an operation in a -- nested package it's a new primitive and will have its own slot. elsif not Present (Interface_Alias (Prim)) and then Present (Alias (Prim)) and then Chars (Prim) = Chars (Alias (Prim)) and then Nkind (Unit_Declaration_Node (Prim)) /= N_Subprogram_Renaming_Declaration then declare Par_Type : constant Entity_Id := Find_Dispatching_Type (Alias (Prim)); begin if Present (Par_Type) and then Par_Type /= Typ and then Is_Ancestor (Par_Type, Typ, Use_Full_View => True) and then Present (DTC_Entity (Alias (Prim))) then E := Alias (Prim); Set_DT_Position_Value (Prim, DT_Position (E)); if not Is_Predefined_Dispatching_Alias (E) then Set_Fixed_Prim (UI_To_Int (DT_Position (E))); end if; end if; end; end if; Next_Elmt (Prim_Elmt); end loop; -- Third stage: Fix the position of all the new primitives. Entries -- associated with primitives covering interfaces are handled in a -- latter round. Prim_Elmt := First_Prim; while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- Skip primitives previously set entries if DT_Position (Prim) /= No_Uint then null; -- Primitives covering interface primitives are handled later elsif Present (Interface_Alias (Prim)) then null; else -- Take the next available position in the DT loop Nb_Prim := Nb_Prim + 1; pragma Assert (Nb_Prim <= Count_Prim); exit when not Fixed_Prim (Nb_Prim); end loop; Set_DT_Position_Value (Prim, UI_From_Int (Nb_Prim)); Set_Fixed_Prim (Nb_Prim); end if; Next_Elmt (Prim_Elmt); end loop; end; -- Fourth stage: Complete the decoration of primitives covering -- interfaces (that is, propagate the DT_Position attribute from -- the aliased primitive) Prim_Elmt := First_Prim; while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); if DT_Position (Prim) = No_Uint and then Present (Interface_Alias (Prim)) then pragma Assert (Present (Alias (Prim)) and then Find_Dispatching_Type (Alias (Prim)) = Typ); -- Check if this entry will be placed in the primary DT if Is_Ancestor (Find_Dispatching_Type (Interface_Alias (Prim)), Typ, Use_Full_View => True) then pragma Assert (DT_Position (Alias (Prim)) /= No_Uint); Set_DT_Position_Value (Prim, DT_Position (Alias (Prim))); -- Otherwise it will be placed in the secondary DT else pragma Assert (DT_Position (Interface_Alias (Prim)) /= No_Uint); Set_DT_Position_Value (Prim, DT_Position (Interface_Alias (Prim))); end if; end if; Next_Elmt (Prim_Elmt); end loop; -- Generate listing showing the contents of the dispatch tables. This -- action is done before some further static checks because in case of -- critical errors caused by a wrong dispatch table we need to see the -- contents of such table. if Debug_Flag_ZZ then Write_DT (Typ); end if; -- Final stage: Ensure that the table is correct plus some further -- verifications concerning the primitives. Prim_Elmt := First_Prim; DT_Length := 0; while Present (Prim_Elmt) loop Prim := Node (Prim_Elmt); -- At this point all the primitives MUST have a position in the -- dispatch table. if DT_Position (Prim) = No_Uint then raise Program_Error; end if; -- Calculate real size of the dispatch table if not In_Predef_Prims_DT (Prim) and then UI_To_Int (DT_Position (Prim)) > DT_Length then DT_Length := UI_To_Int (DT_Position (Prim)); end if; -- Ensure that the assigned position to non-predefined dispatching -- operations in the dispatch table is correct. if not Is_Predefined_Dispatching_Operation (Prim) and then not Is_Predefined_Dispatching_Alias (Prim) then Validate_Position (Prim); end if; if Chars (Prim) = Name_Finalize then Finalized := True; end if; if Chars (Prim) = Name_Adjust then Adjusted := True; end if; -- An abstract operation cannot be declared in the private part for a -- visible abstract type, because it can't be overridden outside this -- package hierarchy. For explicit declarations this is checked at -- the point of declaration, but for inherited operations it must be -- done when building the dispatch table. -- Ada 2005 (AI-251): Primitives associated with interfaces are -- excluded from this check because interfaces must be visible in -- the public and private part (RM 7.3 (7.3/2)) -- We disable this check in Relaxed_RM_Semantics mode, to accommodate -- legacy Ada code. if not Relaxed_RM_Semantics and then Is_Abstract_Type (Typ) and then Is_Abstract_Subprogram (Prim) and then Present (Alias (Prim)) and then not Is_Interface (Find_Dispatching_Type (Ultimate_Alias (Prim))) and then not Present (Interface_Alias (Prim)) and then Is_Derived_Type (Typ) and then In_Private_Part (Current_Scope) and then List_Containing (Parent (Prim)) = Private_Declarations (Package_Specification (Current_Scope)) and then Original_View_In_Visible_Part (Typ) then -- We exclude Input and Output stream operations because -- Limited_Controlled inherits useless Input and Output stream -- operations from Root_Controlled, which can never be overridden. -- Move this check to sem??? if not Is_TSS (Prim, TSS_Stream_Input) and then not Is_TSS (Prim, TSS_Stream_Output) then Error_Msg_NE ("abstract inherited private operation&" & " must be overridden (RM 3.9.3(10))", Parent (Typ), Prim); end if; end if; Next_Elmt (Prim_Elmt); end loop; -- Additional check if Is_Controlled (Typ) then if not Finalized then Error_Msg_N ("controlled type has no explicit Finalize method??", Typ); elsif not Adjusted then Error_Msg_N ("controlled type has no explicit Adjust method??", Typ); end if; end if; -- Set the final size of the Dispatch Table Set_DT_Entry_Count (The_Tag, UI_From_Int (DT_Length)); -- The derived type must have at least as many components as its parent -- (for root types Etype points to itself and the test cannot fail). if DT_Entry_Count (The_Tag) < DT_Entry_Count (First_Tag_Component (Parent_Typ)) then raise Program_Error; end if; end Set_All_DT_Position; -------------------------- -- Set_CPP_Constructors -- -------------------------- procedure Set_CPP_Constructors (Typ : Entity_Id) is function Gen_Parameters_Profile (E : Entity_Id) return List_Id; -- Duplicate the parameters profile of the imported C++ constructor -- adding the "this" pointer to the object as the additional first -- parameter under the usual form _Init : in out Typ. ---------------------------- -- Gen_Parameters_Profile -- ---------------------------- function Gen_Parameters_Profile (E : Entity_Id) return List_Id is Loc : constant Source_Ptr := Sloc (E); Parms : List_Id; P : Node_Id; begin Parms := New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uInit), In_Present => True, Out_Present => True, Parameter_Type => New_Occurrence_Of (Typ, Loc))); if Present (Parameter_Specifications (Parent (E))) then P := First (Parameter_Specifications (Parent (E))); while Present (P) loop Append_To (Parms, Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Chars => Chars (Defining_Identifier (P))), Parameter_Type => New_Copy_Tree (Parameter_Type (P)), Expression => New_Copy_Tree (Expression (P)))); Next (P); end loop; end if; return Parms; end Gen_Parameters_Profile; -- Local variables Loc : Source_Ptr; E : Entity_Id; Found : Boolean := False; IP : Entity_Id; IP_Body : Node_Id; P : Node_Id; Parms : List_Id; Covers_Default_Constructor : Entity_Id := Empty; -- Start of processing for Set_CPP_Constructor begin pragma Assert (Is_CPP_Class (Typ)); -- Look for the constructor entities E := Next_Entity (Typ); while Present (E) loop if Ekind (E) = E_Function and then Is_Constructor (E) then Found := True; Loc := Sloc (E); Parms := Gen_Parameters_Profile (E); IP := Make_Defining_Identifier (Loc, Make_Init_Proc_Name (Typ)); -- Case 1: Constructor of untagged type -- If the C++ class has no virtual methods then the matching Ada -- type is an untagged record type. In such case there is no need -- to generate a wrapper of the C++ constructor because the _tag -- component is not available. if not Is_Tagged_Type (Typ) then Discard_Node (Make_Subprogram_Declaration (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => IP, Parameter_Specifications => Parms))); Set_Init_Proc (Typ, IP); Set_Is_Imported (IP); Set_Is_Constructor (IP); Set_Interface_Name (IP, Interface_Name (E)); Set_Convention (IP, Convention_CPP); Set_Is_Public (IP); Set_Has_Completion (IP); -- Case 2: Constructor of a tagged type -- In this case we generate the IP routine as a wrapper of the -- C++ constructor because IP must also save a copy of the _tag -- generated in the C++ side. The copy of the _tag is used by -- Build_CPP_Init_Procedure to elaborate derivations of C++ types. -- Generate: -- procedure IP (_init : in out Typ; ...) is -- procedure ConstructorP (_init : in out Typ; ...); -- pragma Import (ConstructorP); -- begin -- ConstructorP (_init, ...); -- if Typ._tag = null then -- Typ._tag := _init._tag; -- end if; -- end IP; else declare Body_Stmts : constant List_Id := New_List; Constructor_Id : Entity_Id; Constructor_Decl_Node : Node_Id; Init_Tags_List : List_Id; begin Constructor_Id := Make_Temporary (Loc, 'P'); Constructor_Decl_Node := Make_Subprogram_Declaration (Loc, Make_Procedure_Specification (Loc, Defining_Unit_Name => Constructor_Id, Parameter_Specifications => Parms)); Set_Is_Imported (Constructor_Id); Set_Is_Constructor (Constructor_Id); Set_Interface_Name (Constructor_Id, Interface_Name (E)); Set_Convention (Constructor_Id, Convention_CPP); Set_Is_Public (Constructor_Id); Set_Has_Completion (Constructor_Id); -- Build the init procedure as a wrapper of this constructor Parms := Gen_Parameters_Profile (E); -- Invoke the C++ constructor declare Actuals : constant List_Id := New_List; begin P := First (Parms); while Present (P) loop Append_To (Actuals, New_Occurrence_Of (Defining_Identifier (P), Loc)); Next (P); end loop; Append_To (Body_Stmts, Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Constructor_Id, Loc), Parameter_Associations => Actuals)); end; -- Initialize copies of C++ primary and secondary tags Init_Tags_List := New_List; declare Tag_Elmt : Elmt_Id; Tag_Comp : Node_Id; begin Tag_Elmt := First_Elmt (Access_Disp_Table (Typ)); Tag_Comp := First_Tag_Component (Typ); while Present (Tag_Elmt) and then Is_Tag (Node (Tag_Elmt)) loop -- Skip the following assertion with primary tags -- because Related_Type is not set on primary tag -- components. pragma Assert (Tag_Comp = First_Tag_Component (Typ) or else Related_Type (Node (Tag_Elmt)) = Related_Type (Tag_Comp)); Append_To (Init_Tags_List, Make_Assignment_Statement (Loc, Name => New_Occurrence_Of (Node (Tag_Elmt), Loc), Expression => Make_Selected_Component (Loc, Prefix => Make_Identifier (Loc, Name_uInit), Selector_Name => New_Occurrence_Of (Tag_Comp, Loc)))); Tag_Comp := Next_Tag_Component (Tag_Comp); Next_Elmt (Tag_Elmt); end loop; end; Append_To (Body_Stmts, Make_If_Statement (Loc, Condition => Make_Op_Eq (Loc, Left_Opnd => New_Occurrence_Of (Node (First_Elmt (Access_Disp_Table (Typ))), Loc), Right_Opnd => Unchecked_Convert_To (RTE (RE_Tag), New_Occurrence_Of (RTE (RE_Null_Address), Loc))), Then_Statements => Init_Tags_List)); IP_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => IP, Parameter_Specifications => Parms), Declarations => New_List (Constructor_Decl_Node), Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Body_Stmts, Exception_Handlers => No_List)); Discard_Node (IP_Body); Set_Init_Proc (Typ, IP); end; end if; -- If this constructor has parameters and all its parameters have -- defaults then it covers the default constructor. The semantic -- analyzer ensures that only one constructor with defaults covers -- the default constructor. if Present (Parameter_Specifications (Parent (E))) and then Needs_No_Actuals (E) then Covers_Default_Constructor := IP; end if; end if; Next_Entity (E); end loop; -- If there are no constructors, mark the type as abstract since we -- won't be able to declare objects of that type. if not Found then Set_Is_Abstract_Type (Typ); end if; -- Handle constructor that has all its parameters with defaults and -- hence it covers the default constructor. We generate a wrapper IP -- which calls the covering constructor. if Present (Covers_Default_Constructor) then declare Body_Stmts : List_Id; begin Loc := Sloc (Covers_Default_Constructor); Body_Stmts := New_List ( Make_Procedure_Call_Statement (Loc, Name => New_Occurrence_Of (Covers_Default_Constructor, Loc), Parameter_Associations => New_List ( Make_Identifier (Loc, Name_uInit)))); IP := Make_Defining_Identifier (Loc, Make_Init_Proc_Name (Typ)); IP_Body := Make_Subprogram_Body (Loc, Specification => Make_Procedure_Specification (Loc, Defining_Unit_Name => IP, Parameter_Specifications => New_List ( Make_Parameter_Specification (Loc, Defining_Identifier => Make_Defining_Identifier (Loc, Name_uInit), Parameter_Type => New_Occurrence_Of (Typ, Loc)))), Declarations => No_List, Handled_Statement_Sequence => Make_Handled_Sequence_Of_Statements (Loc, Statements => Body_Stmts, Exception_Handlers => No_List)); Discard_Node (IP_Body); Set_Init_Proc (Typ, IP); end; end if; -- If the CPP type has constructors then it must import also the default -- C++ constructor. It is required for default initialization of objects -- of the type. It is also required to elaborate objects of Ada types -- that are defined as derivations of this CPP type. if Has_CPP_Constructors (Typ) and then No (Init_Proc (Typ)) then Error_Msg_N ("??default constructor must be imported from C++", Typ); end if; end Set_CPP_Constructors; --------------------------- -- Set_DT_Position_Value -- --------------------------- procedure Set_DT_Position_Value (Prim : Entity_Id; Value : Uint) is begin Set_DT_Position (Prim, Value); -- Propagate the value to the wrapped subprogram (if one is present) if Ekind (Prim) in E_Function | E_Procedure and then Is_Primitive_Wrapper (Prim) and then Present (Wrapped_Entity (Prim)) and then Is_Dispatching_Operation (Wrapped_Entity (Prim)) then Set_DT_Position (Wrapped_Entity (Prim), Value); end if; end Set_DT_Position_Value; -------------------------- -- Set_DTC_Entity_Value -- -------------------------- procedure Set_DTC_Entity_Value (Tagged_Type : Entity_Id; Prim : Entity_Id) is begin if Present (Interface_Alias (Prim)) and then Is_Interface (Find_Dispatching_Type (Interface_Alias (Prim))) then Set_DTC_Entity (Prim, Find_Interface_Tag (T => Tagged_Type, Iface => Find_Dispatching_Type (Interface_Alias (Prim)))); else Set_DTC_Entity (Prim, First_Tag_Component (Tagged_Type)); end if; -- Propagate the value to the wrapped subprogram (if one is present) if Ekind (Prim) in E_Function | E_Procedure and then Is_Primitive_Wrapper (Prim) and then Present (Wrapped_Entity (Prim)) and then Is_Dispatching_Operation (Wrapped_Entity (Prim)) then Set_DTC_Entity (Wrapped_Entity (Prim), DTC_Entity (Prim)); end if; end Set_DTC_Entity_Value; ----------------- -- Tagged_Kind -- ----------------- function Tagged_Kind (T : Entity_Id) return Node_Id is Conc_Typ : Entity_Id; Loc : constant Source_Ptr := Sloc (T); begin pragma Assert (Is_Tagged_Type (T) and then RTE_Available (RE_Tagged_Kind)); -- Abstract kinds if Is_Abstract_Type (T) then if Is_Limited_Record (T) then return New_Occurrence_Of (RTE (RE_TK_Abstract_Limited_Tagged), Loc); else return New_Occurrence_Of (RTE (RE_TK_Abstract_Tagged), Loc); end if; -- Concurrent kinds elsif Is_Concurrent_Record_Type (T) then Conc_Typ := Corresponding_Concurrent_Type (T); if Present (Full_View (Conc_Typ)) then Conc_Typ := Full_View (Conc_Typ); end if; if Ekind (Conc_Typ) = E_Protected_Type then return New_Occurrence_Of (RTE (RE_TK_Protected), Loc); else pragma Assert (Ekind (Conc_Typ) = E_Task_Type); return New_Occurrence_Of (RTE (RE_TK_Task), Loc); end if; -- Regular tagged kinds else if Is_Limited_Record (T) then return New_Occurrence_Of (RTE (RE_TK_Limited_Tagged), Loc); else return New_Occurrence_Of (RTE (RE_TK_Tagged), Loc); end if; end if; end Tagged_Kind; -------------- -- Write_DT -- -------------- procedure Write_DT (Typ : Entity_Id) is Elmt : Elmt_Id; Prim : Node_Id; begin -- Protect this procedure against wrong usage. Required because it will -- be used directly from GDB if not (Typ <= Last_Node_Id) or else not Is_Tagged_Type (Typ) then Write_Str ("wrong usage: Write_DT must be used with tagged types"); Write_Eol; return; end if; Write_Int (Int (Typ)); Write_Str (": "); Write_Name (Chars (Typ)); if Is_Interface (Typ) then Write_Str (" is interface"); end if; Write_Eol; Elmt := First_Elmt (Primitive_Operations (Typ)); while Present (Elmt) loop Prim := Node (Elmt); Write_Str (" - "); -- Indicate if this primitive will be allocated in the primary -- dispatch table or in a secondary dispatch table associated -- with an abstract interface type if Present (DTC_Entity (Prim)) then if Etype (DTC_Entity (Prim)) = RTE (RE_Tag) then Write_Str ("[P] "); else Write_Str ("[s] "); end if; end if; -- Output the node of this primitive operation and its name Write_Int (Int (Prim)); Write_Str (": "); if Is_Predefined_Dispatching_Operation (Prim) then Write_Str ("(predefined) "); end if; -- Prefix the name of the primitive with its corresponding tagged -- type to facilitate seeing inherited primitives. if Present (Alias (Prim)) then Write_Name (Chars (Find_Dispatching_Type (Ultimate_Alias (Prim)))); else Write_Name (Chars (Typ)); end if; Write_Str ("."); Write_Name (Chars (Prim)); -- Indicate if this primitive has an aliased primitive if Present (Alias (Prim)) then Write_Str (" (alias = "); Write_Int (Int (Alias (Prim))); -- If the DTC_Entity attribute is already set we can also output -- the name of the interface covered by this primitive (if any). if Ekind (Alias (Prim)) in E_Function | E_Procedure and then Present (DTC_Entity (Alias (Prim))) and then Is_Interface (Scope (DTC_Entity (Alias (Prim)))) then Write_Str (" from interface "); Write_Name (Chars (Scope (DTC_Entity (Alias (Prim))))); end if; if Present (Interface_Alias (Prim)) then Write_Str (", AI_Alias of "); if Is_Null_Interface_Primitive (Interface_Alias (Prim)) then Write_Str ("null primitive "); end if; Write_Name (Chars (Find_Dispatching_Type (Interface_Alias (Prim)))); Write_Char (':'); Write_Int (Int (Interface_Alias (Prim))); end if; Write_Str (")"); end if; -- Display the final position of this primitive in its associated -- (primary or secondary) dispatch table. if Present (DTC_Entity (Prim)) and then DT_Position (Prim) /= No_Uint then Write_Str (" at #"); Write_Int (UI_To_Int (DT_Position (Prim))); end if; if Is_Abstract_Subprogram (Prim) then Write_Str (" is abstract;"); -- Check if this is a null primitive elsif Comes_From_Source (Prim) and then Ekind (Prim) = E_Procedure and then Null_Present (Parent (Prim)) then Write_Str (" is null;"); end if; if Is_Eliminated (Ultimate_Alias (Prim)) then Write_Str (" (eliminated)"); end if; if Is_Imported (Prim) and then Convention (Prim) = Convention_CPP then Write_Str (" (C++)"); end if; Write_Eol; Next_Elmt (Elmt); end loop; end Write_DT; end Exp_Disp;
30,151
ada
2
morbos/Ada_Drivers_Library
arch/ARM/STM32/svd/stm32l0x3/stm32_svd-firewall.ads
-- This spec has been automatically generated from STM32L0x3.svd pragma Restrictions (No_Elaboration_Code); pragma Ada_2012; pragma Style_Checks (Off); with HAL; with System; package STM32_SVD.Firewall is pragma Preelaborate; --------------- -- Registers -- --------------- subtype FIREWALL_CSSA_ADD_Field is HAL.UInt16; -- Code segment start address type FIREWALL_CSSA_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- code segment start address ADD : FIREWALL_CSSA_ADD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CSSA_Register use record Reserved_0_7 at 0 range 0 .. 7; ADD at 0 range 8 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIREWALL_CSL_LENG_Field is HAL.UInt14; -- Code segment length type FIREWALL_CSL_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- code segment length LENG : FIREWALL_CSL_LENG_Field := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CSL_Register use record Reserved_0_7 at 0 range 0 .. 7; LENG at 0 range 8 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype FIREWALL_NVDSSA_ADD_Field is HAL.UInt16; -- Non-volatile data segment start address type FIREWALL_NVDSSA_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- Non-volatile data segment start address ADD : FIREWALL_NVDSSA_ADD_Field := 16#0#; -- unspecified Reserved_24_31 : HAL.UInt8 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_NVDSSA_Register use record Reserved_0_7 at 0 range 0 .. 7; ADD at 0 range 8 .. 23; Reserved_24_31 at 0 range 24 .. 31; end record; subtype FIREWALL_NVDSL_LENG_Field is HAL.UInt14; -- Non-volatile data segment length type FIREWALL_NVDSL_Register is record -- unspecified Reserved_0_7 : HAL.UInt8 := 16#0#; -- Non-volatile data segment length LENG : FIREWALL_NVDSL_LENG_Field := 16#0#; -- unspecified Reserved_22_31 : HAL.UInt10 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_NVDSL_Register use record Reserved_0_7 at 0 range 0 .. 7; LENG at 0 range 8 .. 21; Reserved_22_31 at 0 range 22 .. 31; end record; subtype FIREWALL_VDSSA_ADD_Field is HAL.UInt10; -- Volatile data segment start address type FIREWALL_VDSSA_Register is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Volatile data segment start address ADD : FIREWALL_VDSSA_ADD_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_VDSSA_Register use record Reserved_0_5 at 0 range 0 .. 5; ADD at 0 range 6 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; subtype FIREWALL_VDSL_LENG_Field is HAL.UInt10; -- Volatile data segment length type FIREWALL_VDSL_Register is record -- unspecified Reserved_0_5 : HAL.UInt6 := 16#0#; -- Non-volatile data segment length LENG : FIREWALL_VDSL_LENG_Field := 16#0#; -- unspecified Reserved_16_31 : HAL.UInt16 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_VDSL_Register use record Reserved_0_5 at 0 range 0 .. 5; LENG at 0 range 6 .. 15; Reserved_16_31 at 0 range 16 .. 31; end record; -- Configuration register type FIREWALL_CR_Register is record -- Firewall pre alarm FPA : Boolean := False; -- Volatile data shared VDS : Boolean := False; -- Volatile data execution VDE : Boolean := False; -- unspecified Reserved_3_31 : HAL.UInt29 := 16#0#; end record with Volatile_Full_Access, Size => 32, Bit_Order => System.Low_Order_First; for FIREWALL_CR_Register use record FPA at 0 range 0 .. 0; VDS at 0 range 1 .. 1; VDE at 0 range 2 .. 2; Reserved_3_31 at 0 range 3 .. 31; end record; ----------------- -- Peripherals -- ----------------- -- Firewall type Firewall_Peripheral is record -- Code segment start address FIREWALL_CSSA : aliased FIREWALL_CSSA_Register; -- Code segment length FIREWALL_CSL : aliased FIREWALL_CSL_Register; -- Non-volatile data segment start address FIREWALL_NVDSSA : aliased FIREWALL_NVDSSA_Register; -- Non-volatile data segment length FIREWALL_NVDSL : aliased FIREWALL_NVDSL_Register; -- Volatile data segment start address FIREWALL_VDSSA : aliased FIREWALL_VDSSA_Register; -- Volatile data segment length FIREWALL_VDSL : aliased FIREWALL_VDSL_Register; -- Configuration register FIREWALL_CR : aliased FIREWALL_CR_Register; end record with Volatile; for Firewall_Peripheral use record FIREWALL_CSSA at 16#0# range 0 .. 31; FIREWALL_CSL at 16#4# range 0 .. 31; FIREWALL_NVDSSA at 16#8# range 0 .. 31; FIREWALL_NVDSL at 16#C# range 0 .. 31; FIREWALL_VDSSA at 16#10# range 0 .. 31; FIREWALL_VDSL at 16#14# range 0 .. 31; FIREWALL_CR at 16#20# range 0 .. 31; end record; -- Firewall Firewall_Periph : aliased Firewall_Peripheral with Import, Address => System'To_Address (16#40011C00#); end STM32_SVD.Firewall;
30,152
ada
1
Fabien-Chouteau/samd51-hal
src/drivers/sercom_u2201/sam-sercom-i2c.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2020, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with HAL.I2C; use HAL.I2C; with HAL; use HAL; package SAM.SERCOM.I2C is type I2C_Device is new SERCOM_Device and HAL.I2C.I2C_Port with private; procedure Configure (This : in out I2C_Device; Baud : UInt8) with Pre => not This.Enabled and then not This.Configured, Post => not This.Enabled and then This.Configured; -- Configure SERCOM in I2C Master mode. -- DMA -- function Data_Address (This : I2C_Device) return System.Address; -- return the address of the data register for DMA transfer configuration ------------- -- HAL.I2C -- ------------- overriding procedure Master_Transmit (This : in out I2C_Device; Addr : I2C_Address; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000); overriding procedure Master_Receive (This : in out I2C_Device; Addr : I2C_Address; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000); overriding procedure Mem_Write (This : in out I2C_Device; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000); overriding procedure Mem_Read (This : in out I2C_Device; Addr : I2C_Address; Mem_Addr : UInt16; Mem_Addr_Size : I2C_Memory_Address_Size; Data : out I2C_Data; Status : out I2C_Status; Timeout : Natural := 1000); private type I2C_Device is new SERCOM_Device and HAL.I2C.I2C_Port with record Do_Stop_Sequence : Boolean := True; end record; procedure Wait_Sync (This : in out I2C_Device); procedure Wait_Bus (This : in out I2C_Device); function Send_Addr (This : in out I2C_Device; Addr : UInt11) return I2C_Status; procedure Cmd_Stop (This : in out I2C_Device); procedure Cmd_Read (This : in out I2C_Device); procedure Cmd_Nack (This : in out I2C_Device); function Bus_Status (This : I2C_Device) return I2C_Status; end SAM.SERCOM.I2C;
30,153
ada
0
daemonl/openapi-codegen
snapshot/Ada/server-spec.ada
-- Swagger Petstore -- This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. -- ------------ EDIT NOTE ------------ -- This file was generated with swagger-codegen. You can modify it to implement -- the server. After you modify this file, you should add the following line -- to the .swagger-codegen-ignore file: -- -- src/IO.OpenAPI-servers.ads -- -- Then, you can drop this edit note comment. -- ------------ EDIT NOTE ------------ with IO.OpenAPI.Model.Default; with Swagger.Servers; with IO.OpenAPI.Api.Models; with IO.OpenAPI.Api.Skeletons; package IO.OpenAPI.Api.Servers is use IO.OpenAPI.Api.Models; type Server_Type is limited new IO.OpenAPI.Api.Skeletons.Server_Type with null record; -- Add a new pet to the store overriding procedure addPet (Server : in out Server_Type; body : in object; Context : in out Swagger.Servers.Context_Type); -- Update an existing pet overriding procedure updatePet (Server : in out Server_Type; body : in object; Context : in out Swagger.Servers.Context_Type); -- Finds Pets by status overriding procedure findPetsByStatus (Server : in out Server_Type; status : in array; Result : out array; Context : in out Swagger.Servers.Context_Type); -- Finds Pets by tags overriding procedure findPetsByTags (Server : in out Server_Type; tags : in array; Result : out array; Context : in out Swagger.Servers.Context_Type); -- Find pet by ID overriding procedure getPetById (Server : in out Server_Type; petId : in integer; Result : out Pet; Context : in out Swagger.Servers.Context_Type); -- Updates a pet in the store with form data overriding procedure updatePetWithForm (Server : in out Server_Type; petId : in integer; body : in object; Context : in out Swagger.Servers.Context_Type); -- Deletes a pet overriding procedure deletePet (Server : in out Server_Type; petId : in integer; api_key : in string; Context : in out Swagger.Servers.Context_Type); -- uploads an image overriding procedure uploadFile (Server : in out Server_Type; petId : in integer; body : in string; Result : out ApiResponse; Context : in out Swagger.Servers.Context_Type); -- Returns pet inventories by status overriding procedure getInventory (Server : in out Server_Type ; Result : out object; Context : in out Swagger.Servers.Context_Type); -- Place an order for a pet overriding procedure placeOrder (Server : in out Server_Type; body : in object; Result : out Order; Context : in out Swagger.Servers.Context_Type); -- Find purchase order by ID overriding procedure getOrderById (Server : in out Server_Type; orderId : in integer; Result : out Order; Context : in out Swagger.Servers.Context_Type); -- Delete purchase order by ID overriding procedure deleteOrder (Server : in out Server_Type; orderId : in integer; Context : in out Swagger.Servers.Context_Type); -- Create user overriding procedure createUser (Server : in out Server_Type; body : in object; Context : in out Swagger.Servers.Context_Type); -- Creates list of users with given input array overriding procedure createUsersWithArrayInput (Server : in out Server_Type; body : in array; Context : in out Swagger.Servers.Context_Type); -- Creates list of users with given input array overriding procedure createUsersWithListInput (Server : in out Server_Type; body : in array; Context : in out Swagger.Servers.Context_Type); -- Logs user into the system overriding procedure loginUser (Server : in out Server_Type; username : in string; password : in string; Result : out string; Context : in out Swagger.Servers.Context_Type); -- Logs out current logged in user session overriding procedure logoutUser (Server : in out Server_Type ; Context : in out Swagger.Servers.Context_Type); -- Get user by user name overriding procedure getUserByName (Server : in out Server_Type; username : in string; Result : out User; Context : in out Swagger.Servers.Context_Type); -- Updated user overriding procedure updateUser (Server : in out Server_Type; username : in string; body : in object; Context : in out Swagger.Servers.Context_Type); -- Delete user overriding procedure deleteUser (Server : in out Server_Type; username : in string; Context : in out Swagger.Servers.Context_Type); package Server_Impl is new IO.OpenAPI.Api.Skeletons.Shared_Instance (Server_Type); end IO.OpenAPI.Api.Servers;
30,154
ada
0
optikos/oasis
source/nodes/program-nodes-ordinary_fixed_point_types.adb
<gh_stars>0 -- Copyright (c) 2019 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- package body Program.Nodes.Ordinary_Fixed_Point_Types is function Create (Delta_Token : not null Program.Lexical_Elements .Lexical_Element_Access; Delta_Expression : not null Program.Elements.Expressions .Expression_Access; Real_Range : not null Program.Elements.Real_Range_Specifications .Real_Range_Specification_Access) return Ordinary_Fixed_Point_Type is begin return Result : Ordinary_Fixed_Point_Type := (Delta_Token => Delta_Token, Delta_Expression => Delta_Expression, Real_Range => Real_Range, Enclosing_Element => null) do Initialize (Result); end return; end Create; function Create (Delta_Expression : not null Program.Elements.Expressions .Expression_Access; Real_Range : not null Program.Elements.Real_Range_Specifications .Real_Range_Specification_Access; Is_Part_Of_Implicit : Boolean := False; Is_Part_Of_Inherited : Boolean := False; Is_Part_Of_Instance : Boolean := False) return Implicit_Ordinary_Fixed_Point_Type is begin return Result : Implicit_Ordinary_Fixed_Point_Type := (Delta_Expression => Delta_Expression, Real_Range => Real_Range, 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 Delta_Expression (Self : Base_Ordinary_Fixed_Point_Type) return not null Program.Elements.Expressions.Expression_Access is begin return Self.Delta_Expression; end Delta_Expression; overriding function Real_Range (Self : Base_Ordinary_Fixed_Point_Type) return not null Program.Elements.Real_Range_Specifications .Real_Range_Specification_Access is begin return Self.Real_Range; end Real_Range; overriding function Delta_Token (Self : Ordinary_Fixed_Point_Type) return not null Program.Lexical_Elements.Lexical_Element_Access is begin return Self.Delta_Token; end Delta_Token; overriding function Is_Part_Of_Implicit (Self : Implicit_Ordinary_Fixed_Point_Type) return Boolean is begin return Self.Is_Part_Of_Implicit; end Is_Part_Of_Implicit; overriding function Is_Part_Of_Inherited (Self : Implicit_Ordinary_Fixed_Point_Type) return Boolean is begin return Self.Is_Part_Of_Inherited; end Is_Part_Of_Inherited; overriding function Is_Part_Of_Instance (Self : Implicit_Ordinary_Fixed_Point_Type) return Boolean is begin return Self.Is_Part_Of_Instance; end Is_Part_Of_Instance; procedure Initialize (Self : aliased in out Base_Ordinary_Fixed_Point_Type'Class) is begin Set_Enclosing_Element (Self.Delta_Expression, Self'Unchecked_Access); Set_Enclosing_Element (Self.Real_Range, Self'Unchecked_Access); null; end Initialize; overriding function Is_Ordinary_Fixed_Point_Type_Element (Self : Base_Ordinary_Fixed_Point_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Ordinary_Fixed_Point_Type_Element; overriding function Is_Type_Definition_Element (Self : Base_Ordinary_Fixed_Point_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Type_Definition_Element; overriding function Is_Definition_Element (Self : Base_Ordinary_Fixed_Point_Type) return Boolean is pragma Unreferenced (Self); begin return True; end Is_Definition_Element; overriding procedure Visit (Self : not null access Base_Ordinary_Fixed_Point_Type; Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is begin Visitor.Ordinary_Fixed_Point_Type (Self); end Visit; overriding function To_Ordinary_Fixed_Point_Type_Text (Self : aliased in out Ordinary_Fixed_Point_Type) return Program.Elements.Ordinary_Fixed_Point_Types .Ordinary_Fixed_Point_Type_Text_Access is begin return Self'Unchecked_Access; end To_Ordinary_Fixed_Point_Type_Text; overriding function To_Ordinary_Fixed_Point_Type_Text (Self : aliased in out Implicit_Ordinary_Fixed_Point_Type) return Program.Elements.Ordinary_Fixed_Point_Types .Ordinary_Fixed_Point_Type_Text_Access is pragma Unreferenced (Self); begin return null; end To_Ordinary_Fixed_Point_Type_Text; end Program.Nodes.Ordinary_Fixed_Point_Types;
30,155
ada
0
DrenfongWong/tkm-rpc
specs/ada/server/ees/tkmrpc-operation_handlers-ees-esa_acquire.ads
<reponame>DrenfongWong/tkm-rpc<filename>specs/ada/server/ees/tkmrpc-operation_handlers-ees-esa_acquire.ads<gh_stars>0 with Tkmrpc.Request; with Tkmrpc.Response; package Tkmrpc.Operation_Handlers.Ees.Esa_Acquire is procedure Handle (Req : Request.Data_Type; Res : out Response.Data_Type); -- Handler for the esa_acquire operation. end Tkmrpc.Operation_Handlers.Ees.Esa_Acquire;
30,156
ada
1
LaudateCorpus1/RosettaCodeData
Task/Non-decimal-radices-Convert/Ada/non-decimal-radices-convert.ada
with Ada.Text_Io; use Ada.Text_Io; with Ada.Strings.Fixed; With Ada.Strings.Unbounded; procedure Number_Base_Conversion is Max_Base : constant := 36; subtype Base_Type is Integer range 2..Max_Base; Num_Digits : constant String := "0123456789abcdefghijklmnopqrstuvwxyz"; Invalid_Digit : exception; function To_Decimal(Value : String; Base : Base_Type) return Integer is use Ada.Strings.Fixed; Result : Integer := 0; Decimal_Value : Integer; Radix_Offset : Natural := 0; begin for I in reverse Value'range loop Decimal_Value := Index(Num_Digits, Value(I..I)) - 1; if Decimal_Value < 0 then raise Invalid_Digit; end if; Result := Result + (Base**Radix_Offset * Decimal_Value); Radix_Offset := Radix_Offset + 1; end loop; return Result; end To_Decimal; function To_Base(Value : Natural; Base : Base_Type) return String is use Ada.Strings.Unbounded; Result : Unbounded_String := Null_Unbounded_String; Temp : Natural := Value; Base_Digit : String(1..1); begin if Temp = 0 then return "0"; end if; while Temp > 0 loop Base_Digit(1) := Num_Digits((Temp mod Base) + 1); if Result = Null_Unbounded_String then Append(Result, Base_Digit); else Insert(Source => Result, Before => 1, New_Item => Base_Digit); end if; Temp := Temp / Base; end loop; return To_String(Result); end To_Base; begin Put_Line("26 converted to base 16 is " & To_Base(26, 16)); Put_line("1a (base 16) is decimal" & Integer'image(To_Decimal("1a", 16))); end Number_Base_Conversion;
30,157
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/ada/a-crbtgo.adb
------------------------------------------------------------------------------ -- -- -- GNAT LIBRARY COMPONENTS -- -- -- -- ADA.CONTAINERS.RED_BLACK_TREES.GENERIC_OPERATIONS -- -- -- -- B o d y -- -- -- -- Copyright (C) 2004-2016, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- This unit was originally developed by <NAME>. -- ------------------------------------------------------------------------------ -- The references below to "CLR" refer to the following book, from which -- several of the algorithms here were adapted: -- Introduction to Algorithms -- by <NAME>, <NAME>, <NAME> -- Publisher: The MIT Press (June 18, 1990) -- ISBN: 0262031418 with System; use type System.Address; package body Ada.Containers.Red_Black_Trees.Generic_Operations is pragma Warnings (Off, "variable ""Busy*"" is not referenced"); pragma Warnings (Off, "variable ""Lock*"" is not referenced"); -- See comment in Ada.Containers.Helpers ----------------------- -- Local Subprograms -- ----------------------- procedure Delete_Fixup (Tree : in out Tree_Type; Node : Node_Access); procedure Delete_Swap (Tree : in out Tree_Type; Z, Y : Node_Access); procedure Left_Rotate (Tree : in out Tree_Type; X : Node_Access); procedure Right_Rotate (Tree : in out Tree_Type; Y : Node_Access); -- Why is all the following code commented out ??? -- --------------------- -- -- Check_Invariant -- -- --------------------- -- procedure Check_Invariant (Tree : Tree_Type) is -- Root : constant Node_Access := Tree.Root; -- -- function Check (Node : Node_Access) return Natural; -- -- ----------- -- -- Check -- -- ----------- -- -- function Check (Node : Node_Access) return Natural is -- begin -- if Node = null then -- return 0; -- end if; -- -- if Color (Node) = Red then -- declare -- L : constant Node_Access := Left (Node); -- begin -- pragma Assert (L = null or else Color (L) = Black); -- null; -- end; -- -- declare -- R : constant Node_Access := Right (Node); -- begin -- pragma Assert (R = null or else Color (R) = Black); -- null; -- end; -- -- declare -- NL : constant Natural := Check (Left (Node)); -- NR : constant Natural := Check (Right (Node)); -- begin -- pragma Assert (NL = NR); -- return NL; -- end; -- end if; -- -- declare -- NL : constant Natural := Check (Left (Node)); -- NR : constant Natural := Check (Right (Node)); -- begin -- pragma Assert (NL = NR); -- return NL + 1; -- end; -- end Check; -- -- -- Start of processing for Check_Invariant -- -- begin -- if Root = null then -- pragma Assert (Tree.First = null); -- pragma Assert (Tree.Last = null); -- pragma Assert (Tree.Length = 0); -- null; -- -- else -- pragma Assert (Color (Root) = Black); -- pragma Assert (Tree.Length > 0); -- pragma Assert (Tree.Root /= null); -- pragma Assert (Tree.First /= null); -- pragma Assert (Tree.Last /= null); -- pragma Assert (Parent (Tree.Root) = null); -- pragma Assert ((Tree.Length > 1) -- or else (Tree.First = Tree.Last -- and Tree.First = Tree.Root)); -- pragma Assert (Left (Tree.First) = null); -- pragma Assert (Right (Tree.Last) = null); -- -- declare -- L : constant Node_Access := Left (Root); -- R : constant Node_Access := Right (Root); -- NL : constant Natural := Check (L); -- NR : constant Natural := Check (R); -- begin -- pragma Assert (NL = NR); -- null; -- end; -- end if; -- end Check_Invariant; ------------------ -- Delete_Fixup -- ------------------ procedure Delete_Fixup (Tree : in out Tree_Type; Node : Node_Access) is -- CLR p274 X : Node_Access := Node; W : Node_Access; begin while X /= Tree.Root and then Color (X) = Black loop if X = Left (Parent (X)) then W := Right (Parent (X)); if Color (W) = Red then Set_Color (W, Black); Set_Color (Parent (X), Red); Left_Rotate (Tree, Parent (X)); W := Right (Parent (X)); end if; if (Left (W) = null or else Color (Left (W)) = Black) and then (Right (W) = null or else Color (Right (W)) = Black) then Set_Color (W, Red); X := Parent (X); else if Right (W) = null or else Color (Right (W)) = Black then -- As a condition for setting the color of the left child to -- black, the left child access value must be non-null. A -- truth table analysis shows that if we arrive here, that -- condition holds, so there's no need for an explicit test. -- The assertion is here to document what we know is true. pragma Assert (Left (W) /= null); Set_Color (Left (W), Black); Set_Color (W, Red); Right_Rotate (Tree, W); W := Right (Parent (X)); end if; Set_Color (W, Color (Parent (X))); Set_Color (Parent (X), Black); Set_Color (Right (W), Black); Left_Rotate (Tree, Parent (X)); X := Tree.Root; end if; else pragma Assert (X = Right (Parent (X))); W := Left (Parent (X)); if Color (W) = Red then Set_Color (W, Black); Set_Color (Parent (X), Red); Right_Rotate (Tree, Parent (X)); W := Left (Parent (X)); end if; if (Left (W) = null or else Color (Left (W)) = Black) and then (Right (W) = null or else Color (Right (W)) = Black) then Set_Color (W, Red); X := Parent (X); else if Left (W) = null or else Color (Left (W)) = Black then -- As a condition for setting the color of the right child -- to black, the right child access value must be non-null. -- A truth table analysis shows that if we arrive here, that -- condition holds, so there's no need for an explicit test. -- The assertion is here to document what we know is true. pragma Assert (Right (W) /= null); Set_Color (Right (W), Black); Set_Color (W, Red); Left_Rotate (Tree, W); W := Left (Parent (X)); end if; Set_Color (W, Color (Parent (X))); Set_Color (Parent (X), Black); Set_Color (Left (W), Black); Right_Rotate (Tree, Parent (X)); X := Tree.Root; end if; end if; end loop; Set_Color (X, Black); end Delete_Fixup; --------------------------- -- Delete_Node_Sans_Free -- --------------------------- procedure Delete_Node_Sans_Free (Tree : in out Tree_Type; Node : Node_Access) is -- CLR p273 X, Y : Node_Access; Z : constant Node_Access := Node; pragma Assert (Z /= null); begin TC_Check (Tree.TC); -- Why are these all commented out ??? -- pragma Assert (Tree.Length > 0); -- pragma Assert (Tree.Root /= null); -- pragma Assert (Tree.First /= null); -- pragma Assert (Tree.Last /= null); -- pragma Assert (Parent (Tree.Root) = null); -- pragma Assert ((Tree.Length > 1) -- or else (Tree.First = Tree.Last -- and then Tree.First = Tree.Root)); -- pragma Assert ((Left (Node) = null) -- or else (Parent (Left (Node)) = Node)); -- pragma Assert ((Right (Node) = null) -- or else (Parent (Right (Node)) = Node)); -- pragma Assert (((Parent (Node) = null) and then (Tree.Root = Node)) -- or else ((Parent (Node) /= null) and then -- ((Left (Parent (Node)) = Node) -- or else (Right (Parent (Node)) = Node)))); if Left (Z) = null then if Right (Z) = null then if Z = Tree.First then Tree.First := Parent (Z); end if; if Z = Tree.Last then Tree.Last := Parent (Z); end if; if Color (Z) = Black then Delete_Fixup (Tree, Z); end if; pragma Assert (Left (Z) = null); pragma Assert (Right (Z) = null); if Z = Tree.Root then pragma Assert (Tree.Length = 1); pragma Assert (Parent (Z) = null); Tree.Root := null; elsif Z = Left (Parent (Z)) then Set_Left (Parent (Z), null); else pragma Assert (Z = Right (Parent (Z))); Set_Right (Parent (Z), null); end if; else pragma Assert (Z /= Tree.Last); X := Right (Z); if Z = Tree.First then Tree.First := Min (X); end if; if Z = Tree.Root then Tree.Root := X; elsif Z = Left (Parent (Z)) then Set_Left (Parent (Z), X); else pragma Assert (Z = Right (Parent (Z))); Set_Right (Parent (Z), X); end if; Set_Parent (X, Parent (Z)); if Color (Z) = Black then Delete_Fixup (Tree, X); end if; end if; elsif Right (Z) = null then pragma Assert (Z /= Tree.First); X := Left (Z); if Z = Tree.Last then Tree.Last := Max (X); end if; if Z = Tree.Root then Tree.Root := X; elsif Z = Left (Parent (Z)) then Set_Left (Parent (Z), X); else pragma Assert (Z = Right (Parent (Z))); Set_Right (Parent (Z), X); end if; Set_Parent (X, Parent (Z)); if Color (Z) = Black then Delete_Fixup (Tree, X); end if; else pragma Assert (Z /= Tree.First); pragma Assert (Z /= Tree.Last); Y := Next (Z); pragma Assert (Left (Y) = null); X := Right (Y); if X = null then if Y = Left (Parent (Y)) then pragma Assert (Parent (Y) /= Z); Delete_Swap (Tree, Z, Y); Set_Left (Parent (Z), Z); else pragma Assert (Y = Right (Parent (Y))); pragma Assert (Parent (Y) = Z); Set_Parent (Y, Parent (Z)); if Z = Tree.Root then Tree.Root := Y; elsif Z = Left (Parent (Z)) then Set_Left (Parent (Z), Y); else pragma Assert (Z = Right (Parent (Z))); Set_Right (Parent (Z), Y); end if; Set_Left (Y, Left (Z)); Set_Parent (Left (Y), Y); Set_Right (Y, Z); Set_Parent (Z, Y); Set_Left (Z, null); Set_Right (Z, null); declare Y_Color : constant Color_Type := Color (Y); begin Set_Color (Y, Color (Z)); Set_Color (Z, Y_Color); end; end if; if Color (Z) = Black then Delete_Fixup (Tree, Z); end if; pragma Assert (Left (Z) = null); pragma Assert (Right (Z) = null); if Z = Right (Parent (Z)) then Set_Right (Parent (Z), null); else pragma Assert (Z = Left (Parent (Z))); Set_Left (Parent (Z), null); end if; else if Y = Left (Parent (Y)) then pragma Assert (Parent (Y) /= Z); Delete_Swap (Tree, Z, Y); Set_Left (Parent (Z), X); Set_Parent (X, Parent (Z)); else pragma Assert (Y = Right (Parent (Y))); pragma Assert (Parent (Y) = Z); Set_Parent (Y, Parent (Z)); if Z = Tree.Root then Tree.Root := Y; elsif Z = Left (Parent (Z)) then Set_Left (Parent (Z), Y); else pragma Assert (Z = Right (Parent (Z))); Set_Right (Parent (Z), Y); end if; Set_Left (Y, Left (Z)); Set_Parent (Left (Y), Y); declare Y_Color : constant Color_Type := Color (Y); begin Set_Color (Y, Color (Z)); Set_Color (Z, Y_Color); end; end if; if Color (Z) = Black then Delete_Fixup (Tree, X); end if; end if; end if; Tree.Length := Tree.Length - 1; end Delete_Node_Sans_Free; ----------------- -- Delete_Swap -- ----------------- procedure Delete_Swap (Tree : in out Tree_Type; Z, Y : Node_Access) is pragma Assert (Z /= Y); pragma Assert (Parent (Y) /= Z); Y_Parent : constant Node_Access := Parent (Y); Y_Color : constant Color_Type := Color (Y); begin Set_Parent (Y, Parent (Z)); Set_Left (Y, Left (Z)); Set_Right (Y, Right (Z)); Set_Color (Y, Color (Z)); if Tree.Root = Z then Tree.Root := Y; elsif Right (Parent (Y)) = Z then Set_Right (Parent (Y), Y); else pragma Assert (Left (Parent (Y)) = Z); Set_Left (Parent (Y), Y); end if; if Right (Y) /= null then Set_Parent (Right (Y), Y); end if; if Left (Y) /= null then Set_Parent (Left (Y), Y); end if; Set_Parent (Z, Y_Parent); Set_Color (Z, Y_Color); Set_Left (Z, null); Set_Right (Z, null); end Delete_Swap; -------------------- -- Generic_Adjust -- -------------------- procedure Generic_Adjust (Tree : in out Tree_Type) is N : constant Count_Type := Tree.Length; Root : constant Node_Access := Tree.Root; use type Helpers.Tamper_Counts; begin -- If the counts are nonzero, execution is technically erroneous, but -- it seems friendly to allow things like concurrent "=" on shared -- constants. Zero_Counts (Tree.TC); if N = 0 then pragma Assert (Root = null); return; end if; Tree.Root := null; Tree.First := null; Tree.Last := null; Tree.Length := 0; Tree.Root := Copy_Tree (Root); Tree.First := Min (Tree.Root); Tree.Last := Max (Tree.Root); Tree.Length := N; end Generic_Adjust; ------------------- -- Generic_Clear -- ------------------- procedure Generic_Clear (Tree : in out Tree_Type) is Root : Node_Access := Tree.Root; begin TC_Check (Tree.TC); Tree := (First => null, Last => null, Root => null, Length => 0, TC => <>); Delete_Tree (Root); end Generic_Clear; ----------------------- -- Generic_Copy_Tree -- ----------------------- function Generic_Copy_Tree (Source_Root : Node_Access) return Node_Access is Target_Root : Node_Access := Copy_Node (Source_Root); P, X : Node_Access; begin if Right (Source_Root) /= null then Set_Right (Node => Target_Root, Right => Generic_Copy_Tree (Right (Source_Root))); Set_Parent (Node => Right (Target_Root), Parent => Target_Root); end if; P := Target_Root; X := Left (Source_Root); while X /= null loop declare Y : constant Node_Access := Copy_Node (X); begin Set_Left (Node => P, Left => Y); Set_Parent (Node => Y, Parent => P); if Right (X) /= null then Set_Right (Node => Y, Right => Generic_Copy_Tree (Right (X))); Set_Parent (Node => Right (Y), Parent => Y); end if; P := Y; X := Left (X); end; end loop; return Target_Root; exception when others => Delete_Tree (Target_Root); raise; end Generic_Copy_Tree; ------------------------- -- Generic_Delete_Tree -- ------------------------- procedure Generic_Delete_Tree (X : in out Node_Access) is Y : Node_Access; pragma Warnings (Off, Y); begin while X /= null loop Y := Right (X); Generic_Delete_Tree (Y); Y := Left (X); Free (X); X := Y; end loop; end Generic_Delete_Tree; ------------------- -- Generic_Equal -- ------------------- function Generic_Equal (Left, Right : Tree_Type) return Boolean is begin if Left.Length /= Right.Length then return False; end if; -- If the containers are empty, return a result immediately, so as to -- not manipulate the tamper bits unnecessarily. if Left.Length = 0 then return True; end if; declare Lock_Left : With_Lock (Left.TC'Unrestricted_Access); Lock_Right : With_Lock (Right.TC'Unrestricted_Access); L_Node : Node_Access := Left.First; R_Node : Node_Access := Right.First; begin while L_Node /= null loop if not Is_Equal (L_Node, R_Node) then return False; end if; L_Node := Next (L_Node); R_Node := Next (R_Node); end loop; end; return True; end Generic_Equal; ----------------------- -- Generic_Iteration -- ----------------------- procedure Generic_Iteration (Tree : Tree_Type) is procedure Iterate (P : Node_Access); ------------- -- Iterate -- ------------- procedure Iterate (P : Node_Access) is X : Node_Access := P; begin while X /= null loop Iterate (Left (X)); Process (X); X := Right (X); end loop; end Iterate; -- Start of processing for Generic_Iteration begin Iterate (Tree.Root); end Generic_Iteration; ------------------ -- Generic_Move -- ------------------ procedure Generic_Move (Target, Source : in out Tree_Type) is begin if Target'Address = Source'Address then return; end if; TC_Check (Source.TC); Clear (Target); Target := Source; Source := (First => null, Last => null, Root => null, Length => 0, TC => <>); end Generic_Move; ------------------ -- Generic_Read -- ------------------ procedure Generic_Read (Stream : not null access Root_Stream_Type'Class; Tree : in out Tree_Type) is N : Count_Type'Base; Node, Last_Node : Node_Access; begin Clear (Tree); Count_Type'Base'Read (Stream, N); pragma Assert (N >= 0); if N = 0 then return; end if; Node := Read_Node (Stream); pragma Assert (Node /= null); pragma Assert (Color (Node) = Red); Set_Color (Node, Black); Tree.Root := Node; Tree.First := Node; Tree.Last := Node; Tree.Length := 1; for J in Count_Type range 2 .. N loop Last_Node := Node; pragma Assert (Last_Node = Tree.Last); Node := Read_Node (Stream); pragma Assert (Node /= null); pragma Assert (Color (Node) = Red); Set_Right (Node => Last_Node, Right => Node); Tree.Last := Node; Set_Parent (Node => Node, Parent => Last_Node); Rebalance_For_Insert (Tree, Node); Tree.Length := Tree.Length + 1; end loop; end Generic_Read; ------------------------------- -- Generic_Reverse_Iteration -- ------------------------------- procedure Generic_Reverse_Iteration (Tree : Tree_Type) is procedure Iterate (P : Node_Access); ------------- -- Iterate -- ------------- procedure Iterate (P : Node_Access) is X : Node_Access := P; begin while X /= null loop Iterate (Right (X)); Process (X); X := Left (X); end loop; end Iterate; -- Start of processing for Generic_Reverse_Iteration begin Iterate (Tree.Root); end Generic_Reverse_Iteration; ------------------- -- Generic_Write -- ------------------- procedure Generic_Write (Stream : not null access Root_Stream_Type'Class; Tree : Tree_Type) is procedure Process (Node : Node_Access); pragma Inline (Process); procedure Iterate is new Generic_Iteration (Process); ------------- -- Process -- ------------- procedure Process (Node : Node_Access) is begin Write_Node (Stream, Node); end Process; -- Start of processing for Generic_Write begin Count_Type'Base'Write (Stream, Tree.Length); Iterate (Tree); end Generic_Write; ----------------- -- Left_Rotate -- ----------------- procedure Left_Rotate (Tree : in out Tree_Type; X : Node_Access) is -- CLR p266 Y : constant Node_Access := Right (X); pragma Assert (Y /= null); begin Set_Right (X, Left (Y)); if Left (Y) /= null then Set_Parent (Left (Y), X); end if; Set_Parent (Y, Parent (X)); if X = Tree.Root then Tree.Root := Y; elsif X = Left (Parent (X)) then Set_Left (Parent (X), Y); else pragma Assert (X = Right (Parent (X))); Set_Right (Parent (X), Y); end if; Set_Left (Y, X); Set_Parent (X, Y); end Left_Rotate; --------- -- Max -- --------- function Max (Node : Node_Access) return Node_Access is -- CLR p248 X : Node_Access := Node; Y : Node_Access; begin loop Y := Right (X); if Y = null then return X; end if; X := Y; end loop; end Max; --------- -- Min -- --------- function Min (Node : Node_Access) return Node_Access is -- CLR p248 X : Node_Access := Node; Y : Node_Access; begin loop Y := Left (X); if Y = null then return X; end if; X := Y; end loop; end Min; ---------- -- Next -- ---------- function Next (Node : Node_Access) return Node_Access is begin -- CLR p249 if Node = null then return null; end if; if Right (Node) /= null then return Min (Right (Node)); end if; declare X : Node_Access := Node; Y : Node_Access := Parent (Node); begin while Y /= null and then X = Right (Y) loop X := Y; Y := Parent (Y); end loop; return Y; end; end Next; -------------- -- Previous -- -------------- function Previous (Node : Node_Access) return Node_Access is begin if Node = null then return null; end if; if Left (Node) /= null then return Max (Left (Node)); end if; declare X : Node_Access := Node; Y : Node_Access := Parent (Node); begin while Y /= null and then X = Left (Y) loop X := Y; Y := Parent (Y); end loop; return Y; end; end Previous; -------------------------- -- Rebalance_For_Insert -- -------------------------- procedure Rebalance_For_Insert (Tree : in out Tree_Type; Node : Node_Access) is -- CLR p.268 X : Node_Access := Node; pragma Assert (X /= null); pragma Assert (Color (X) = Red); Y : Node_Access; begin while X /= Tree.Root and then Color (Parent (X)) = Red loop if Parent (X) = Left (Parent (Parent (X))) then Y := Right (Parent (Parent (X))); if Y /= null and then Color (Y) = Red then Set_Color (Parent (X), Black); Set_Color (Y, Black); Set_Color (Parent (Parent (X)), Red); X := Parent (Parent (X)); else if X = Right (Parent (X)) then X := Parent (X); Left_Rotate (Tree, X); end if; Set_Color (Parent (X), Black); Set_Color (Parent (Parent (X)), Red); Right_Rotate (Tree, Parent (Parent (X))); end if; else pragma Assert (Parent (X) = Right (Parent (Parent (X)))); Y := Left (Parent (Parent (X))); if Y /= null and then Color (Y) = Red then Set_Color (Parent (X), Black); Set_Color (Y, Black); Set_Color (Parent (Parent (X)), Red); X := Parent (Parent (X)); else if X = Left (Parent (X)) then X := Parent (X); Right_Rotate (Tree, X); end if; Set_Color (Parent (X), Black); Set_Color (Parent (Parent (X)), Red); Left_Rotate (Tree, Parent (Parent (X))); end if; end if; end loop; Set_Color (Tree.Root, Black); end Rebalance_For_Insert; ------------------ -- Right_Rotate -- ------------------ procedure Right_Rotate (Tree : in out Tree_Type; Y : Node_Access) is X : constant Node_Access := Left (Y); pragma Assert (X /= null); begin Set_Left (Y, Right (X)); if Right (X) /= null then Set_Parent (Right (X), Y); end if; Set_Parent (X, Parent (Y)); if Y = Tree.Root then Tree.Root := X; elsif Y = Left (Parent (Y)) then Set_Left (Parent (Y), X); else pragma Assert (Y = Right (Parent (Y))); Set_Right (Parent (Y), X); end if; Set_Right (X, Y); Set_Parent (Y, X); end Right_Rotate; --------- -- Vet -- --------- function Vet (Tree : Tree_Type; Node : Node_Access) return Boolean is begin if Node = null then return True; end if; if Parent (Node) = Node or else Left (Node) = Node or else Right (Node) = Node then return False; end if; if Tree.Length = 0 or else Tree.Root = null or else Tree.First = null or else Tree.Last = null then return False; end if; if Parent (Tree.Root) /= null then return False; end if; if Left (Tree.First) /= null then return False; end if; if Right (Tree.Last) /= null then return False; end if; if Tree.Length = 1 then if Tree.First /= Tree.Last or else Tree.First /= Tree.Root then return False; end if; if Node /= Tree.First then return False; end if; if Parent (Node) /= null or else Left (Node) /= null or else Right (Node) /= null then return False; end if; return True; end if; if Tree.First = Tree.Last then return False; end if; if Tree.Length = 2 then if Tree.First /= Tree.Root and then Tree.Last /= Tree.Root then return False; end if; if Tree.First /= Node and then Tree.Last /= Node then return False; end if; end if; if Left (Node) /= null and then Parent (Left (Node)) /= Node then return False; end if; if Right (Node) /= null and then Parent (Right (Node)) /= Node then return False; end if; if Parent (Node) = null then if Tree.Root /= Node then return False; end if; elsif Left (Parent (Node)) /= Node and then Right (Parent (Node)) /= Node then return False; end if; return True; end Vet; end Ada.Containers.Red_Black_Trees.Generic_Operations;
30,158
ada
35
arc-aosp/external_libncurses
Ada95/samples/sample-menu_demo-handler.adb
------------------------------------------------------------------------------ -- -- -- GNAT ncurses Binding Samples -- -- -- -- Sample.Menu_Demo.Handler -- -- -- -- B O D Y -- -- -- ------------------------------------------------------------------------------ -- Copyright (c) 1998,2004 Free Software Foundation, Inc. -- -- -- -- Permission is hereby granted, free of charge, to any person obtaining a -- -- copy of this software and associated documentation files (the -- -- "Software"), to deal in the Software without restriction, including -- -- without limitation the rights to use, copy, modify, merge, publish, -- -- distribute, distribute with modifications, sublicense, and/or sell -- -- copies of the Software, and to permit persons to whom the Software is -- -- furnished to do so, subject to the following conditions: -- -- -- -- The above copyright notice and this permission notice shall be included -- -- in all copies or substantial portions of the Software. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- -- IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -- -- DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -- -- OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR -- -- THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- -- -- Except as contained in this notice, the name(s) of the above copyright -- -- holders shall not be used in advertising or otherwise to promote the -- -- sale, use or other dealings in this Software without prior written -- -- authorization. -- ------------------------------------------------------------------------------ -- Author: <NAME>, 1996 -- Version Control -- $Revision: 1.15 $ -- $Date: 2004/08/21 21:37:00 $ -- Binding Version 01.00 ------------------------------------------------------------------------------ with Sample.Menu_Demo.Aux; with Sample.Manifest; use Sample.Manifest; with Terminal_Interface.Curses.Mouse; use Terminal_Interface.Curses.Mouse; package body Sample.Menu_Demo.Handler is package Aux renames Sample.Menu_Demo.Aux; procedure Drive_Me (M : in Menu; Title : in String := "") is L : Line_Count; C : Column_Count; Y : Line_Position; X : Column_Position; begin Aux.Geometry (M, L, C, Y, X); Drive_Me (M, Y, X, Title); end Drive_Me; procedure Drive_Me (M : in Menu; Lin : in Line_Position; Col : in Column_Position; Title : in String := "") is Mask : Event_Mask := No_Events; Old : Event_Mask; Pan : Panel := Aux.Create (M, Title, Lin, Col); V : Cursor_Visibility := Invisible; begin -- We are only interested in Clicks with the left button Register_Reportable_Events (Left, All_Clicks, Mask); Old := Start_Mouse (Mask); Set_Cursor_Visibility (V); loop declare K : Key_Code := Aux.Get_Request (M, Pan); R : constant Driver_Result := Driver (M, K); begin case R is when Menu_Ok => null; when Unknown_Request => declare I : constant Item := Current (M); O : Item_Option_Set; begin if K = Key_Mouse then K := SELECT_ITEM; end if; Get_Options (I, O); if K = SELECT_ITEM and then not O.Selectable then Beep; else if My_Driver (M, K, Pan) then exit; end if; end if; end; when others => Beep; end case; end; end loop; End_Mouse (Old); Aux.Destroy (M, Pan); end Drive_Me; end Sample.Menu_Demo.Handler;
30,159
ada
0
mstewartgallus/linted
src/ada-core/src/linted-poller.ads
<filename>src/ada-core/src/linted-poller.ads -- Copyright 2016,2017 <NAME> -- -- 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 Linted.IO_Pool; with Linted.KOs; with Linted.Triggers; package Linted.Poller is subtype Event is Linted.IO_Pool.Poller_Event; subtype Event_Type is Linted.IO_Pool.Poller_Event_Type; subtype Event_Set is Linted.IO_Pool.Poller_Event_Set; Readable : Event_Type renames Linted.IO_Pool.Readable; Writable : Event_Type renames Linted.IO_Pool.Writable; subtype Future is Linted.IO_Pool.Poll_Future; function Future_Is_Live (F : Future) return Boolean renames IO_Pool.Poll_Future_Is_Live; procedure Poll (Object : Linted.KOs.KO; Events : Event_Set; Signaller : Triggers.Signaller; F : out Future) renames IO_Pool.Poll; procedure Poll_Wait (F : in out Future; E : out Event) renames IO_Pool.Poll_Wait; procedure Poll_Poll (F : in out Future; E : out Event; Init : out Boolean) renames IO_Pool.Poll_Poll; end Linted.Poller;
30,160
ada
0
ytomino/gnat4drake
s-fileio.adb
<reponame>ytomino/gnat4drake package body System.File_IO is procedure Check_File_Open (File : File_Control_Block.AFCB_Ptr) is begin raise Program_Error; -- unimplemented end Check_File_Open; end System.File_IO;
30,161
ada
36
rewriting/tom
src/tom/library/sl/ada/visitfailurepackage.adb
with Ada.Text_IO; use Ada.Text_IO; package body VisitFailurePackage is procedure RaiseVisitFailure(msg: String) is begin put_line(msg); raise VisitFailure; end RaiseVisitFailure; end VisitFailurePackage;
30,162
ada
15
mgrojo/adalib
ada-containers-generic_constrained_array_sort.ads
-- Standard Ada library specification -- Copyright (c) 2003-2018 <NAME> <<EMAIL>> -- Copyright (c) 2004-2016 AXE Consultants -- Copyright (c) 2004, 2005, 2006 Ada-Europe -- Copyright (c) 2000 The MITRE Corporation, Inc. -- Copyright (c) 1992, 1993, 1994, 1995 Intermetrics, Inc. -- SPDX-License-Identifier: BSD-3-Clause and LicenseRef-AdaReferenceManual --------------------------------------------------------------------------- generic type Index_Type is (<>); type Element_Type is private; type Array_Type is array (Index_Type) of Element_Type; with function "<" (Left : in Element_Type; Right : in Element_Type) return Boolean is <>; procedure Ada.Containers.Generic_Constrained_Array_Sort (Container : in out Array_Type); pragma Pure (Ada.Containers.Generic_Constrained_Array_Sort);
30,163
ada
0
strenkml/EE368
memsim-master/src/memory-prefetch.ads
<filename>memsim-master/src/memory-prefetch.ads with Memory.Container; use Memory.Container; package Memory.Prefetch is type Prefetch_Type is new Container_Type with private; type Prefetch_Pointer is access all Prefetch_Type'Class; function Create_Prefetch(mem : access Memory_Type'Class; stride : Address_Type := 1) return Prefetch_Pointer; function Random_Prefetch(next : access Memory_Type'Class; generator : Distribution_Type; max_cost : Cost_Type) return Memory_Pointer; overriding function Clone(mem : Prefetch_Type) return Memory_Pointer; overriding procedure Permute(mem : in out Prefetch_Type; generator : in Distribution_Type; max_cost : in Cost_Type); overriding procedure Reset(mem : in out Prefetch_Type; context : in Natural); overriding procedure Read(mem : in out Prefetch_Type; address : in Address_Type; size : in Positive); overriding procedure Write(mem : in out Prefetch_Type; address : in Address_Type; size : in Positive); overriding procedure Idle(mem : in out Prefetch_Type; cycles : in Time_Type); overriding function Get_Time(mem : Prefetch_Type) return Time_Type; overriding function To_String(mem : Prefetch_Type) return Unbounded_String; overriding function Get_Cost(mem : Prefetch_Type) return Cost_Type; overriding procedure Generate(mem : in Prefetch_Type; sigs : in out Unbounded_String; code : in out Unbounded_String); private type Prefetch_Type is new Container_Type with record pending : Time_Type := 0; stride : Address_Type := 1; end record; end Memory.Prefetch;
30,164
ada
3
rogermc2/GA_Ada
example_2.2/src/graphic_data.adb
<reponame>rogermc2/GA_Ada<gh_stars>1-10 with Ada.Containers.Doubly_Linked_Lists; with Ada.Text_IO; use Ada.Text_IO; with GL.Attributes; with GL.Culling; with GL.Objects.Buffers; with GL.Objects.Programs; with GL.Objects.Vertex_Arrays; with GL.Rasterization; with GL.Toggles; with GL.Types.Colors; with GL.Uniforms; with GL_Enums_Feedback; with GL_Util; with Maths; with GA_Draw; with GLUT_API; with Multivectors; package body Graphic_Data is use GL.Types; type Feedback is record Token : GL_Enums_Feedback.Feed_Back_Token; Vertex_1X : Float; Vertex_1Y : Float; Vertex_1Z : Float; Vertex_2X : Float; Vertex_2Y : Float; Vertex_2Z : Float; Vertex_3X : Float; Vertex_3Y : Float; Vertex_3Z : Float; end record; -- Buffer for OpenGL feedback package Buffer_Package is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Feedback); type Buffer_List is new Buffer_Package.List with null record; package Indices_Package is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Integer); type Indices_List is new Indices_Package.List with null record; package Vertices_Package is new Ada.Containers.Doubly_Linked_Lists (Element_Type => Multivectors.Vector); type Vertices_List is new Vertices_Package.List with null record; procedure Get_GLUT_Model_2D (Render_Program : GL.Objects.Programs.Program; Model_Name : Ada.Strings.Unbounded.Unbounded_String; Model_Rotor : Multivectors.Rotor) is use GL_Enums_Feedback; use GL.Types.Singles; Screen_Width : constant Float := 1600.0; MV_Matrix_ID : GL.Uniforms.Uniform; Projection_Matrix_ID : GL.Uniforms.Uniform; Colour_Location : GL.Uniforms.Uniform; Model_View_Matrix : GL.Types.Singles.Matrix4 := GL.Types.Singles.Identity4; Translation_Matrix : Singles.Matrix4; Projection_Matrix : Singles.Matrix4; Feedback_Buffer : GL.Objects.Buffers.Buffer; Feedback_Array_Object : GL.Objects.Vertex_Arrays.Vertex_Array_Object; Indices : Indices_List; Colour : constant GL.Types.Colors.Color := (0.0, 0.0, 0.0, 0.0); Num_Vertices : Integer; G_Vertices_2D : Vertices_List; Index : Integer := 0; begin -- DONT cull faces (we will do this ourselves!) GL.Toggles.Disable (GL.Toggles.Cull_Face); -- fill all polygons (otherwise they get turned into LINES GL.Rasterization.Set_Polygon_Mode (GL.Rasterization.Fill); -- setup projection & transform for the model: -- glFrustum (-(float)g_viewportWidth / screenWidth, (float)g_viewportWidth / screenWidth, -- -(float)g_viewportHeight / screenWidth, (float)g_viewportHeight / screenWidth, -- 1.0, 100.0); GA_Draw.Init_Projection_Matrix (Projection_Matrix, 1.0, 100.0); Translation_Matrix := Maths.Translation_Matrix ((0.0, 0.0, -10.0)); GL_Util.Rotor_GL_Multiply (Model_Rotor, Model_View_Matrix); Model_View_Matrix := Translation_Matrix * Model_View_Matrix; GA_Draw.Graphic_Shader_Locations (Render_Program, MV_Matrix_ID, Projection_Matrix_ID, Colour_Location); GL.Uniforms.Set_Single (MV_Matrix_ID, Model_View_Matrix); GL.Uniforms.Set_Single (Projection_Matrix_ID, Projection_Matrix); -- buffer for OpenGL feedback, format will be: -- GL_POLYGON_TOKEN -- n (= 3) -- vertex 0 x, vertex 0 y -- vertex 1 x, vertex 1 y -- vertex 2 x, vertex 2 y -- GL_POLYGON_TOKEN etc etc -- std::vector<GLfloat> buffer(300000); // more than enough for the GLUT primitives -- switch into feedback mode: -- glFeedbackBuffer((GLsizei)buffer.size(), GL_2D, &(buffer[0])); -- glRenderMode(GL_FEEDBACK); Feedback_Buffer.Initialize_Id; Feedback_Array_Object.Bind; GL.Objects.Buffers.Transform_Feedback_Buffer.Bind (Feedback_Buffer); -- GL.Attributes.Enable_Vertex_Attrib_Array (0); GL.Objects.Programs.Begin_Transform_Feedback (Triangles); -- Render model if Model_Name = "teapot" then Solid_Teapot (1.0); elsif Model_Name = "cube" then Solid_Cube (1.0); elsif Model_Name = "sphere" then Solid_Sphere (1.0, 16, 8); elsif Model_Name = "cone" then Solid_Cone (1.0, 2.0, 16, 8); elsif Model_Name = "torus" then Solid_Torus (0.5, 1.0, 8, 16); elsif Model_Name = "dodecahedron" then Solid_Dodecahedron; elsif Model_Name = "octahedron" then Solid_Octahedron; elsif Model_Name = "tetrahedron" then Solid_Tetrahedron; elsif Model_Name = "icosahedron" then Solid_Icosahedron; end if; GL.Objects.Programs.End_Transform_Feedback; -- GL.Attributes.Disable_Vertex_Attrib_Array (0); -- int nbFeedback = glRenderMode(GL_RENDER); -- -- // parse the feedback buffer: -- g_polygons2D.clear(); -- g_vertices2D.clear(); while idx < nbFeedback loop -- check for polygon: if buffer (idx) /= Polygon_Token then raise GLUT_Read_Exception with "Graphic_Data.Get_GLUT_Model_2D Error parsing the feedback buffer!"; else idx := idx + 1; -- number of vertices (3) Num_Vertices := (int)buffer[idx]; idx := idx + 1; -- std::vector<int> vtxIdx(n); -- Get vertices: -- Maybe todo later: don't duplicate identical vertices . . . for index in 1 .. Num_Vertices loop -- vtxIdx[i] = (int)g_vertices2D.size(); Indices.Append (g_vertices2D.size) g_vertices2D.push_back(_vector(buffer[idx] * e1 + buffer[idx+1] * e2)); idx := idx + 2; end loop; g_polygons2D.push_back(vtxIdx); end if; end loop; -- if (g_prevStatisticsModelName != modelName) -- { -- printf("Model: %s, #polygons: %d, #vertices: %d\n", modelName.c_str(), g_polygons2D.size(), g_vertices2D.size()); -- g_prevStatisticsModelName = modelName; -- } exception when anError : others => Put_Line ("An exception occurred in Graphic_Data.Get_GLUT_Model_2D."); raise; end Get_GLUT_Model_2D; -- ------------------------------------------------------------------------- procedure Solid_Cube (Size : Float) is begin GLUT_API.GLUT_Solid_Cube (Double (Size)); end Solid_Cube; -- ------------------------------------------------------------------------- procedure Solid_Cone (Base, Height : Float; Slices, Stacks : Integer) is begin GLUT_API.GLUT_Solid_Cone (Double (Base), Double (Height), Int (Slices), Int (Stacks)); end Solid_Cone; -- ------------------------------------------------------------------------- procedure Solid_Dodecahedron is begin GLUT_API.GLUT_Solid_Dodecahedron; end Solid_Dodecahedron; -- ------------------------------------------------------------------------- procedure Solid_Icosahedron is begin GLUT_API.GLUT_Solid_Icosahedron; end Solid_Icosahedron; -- ------------------------------------------------------------------------- procedure Solid_Octahedron is begin GLUT_API.GLUT_Solid_Octahedron; end Solid_Octahedron; -- ------------------------------------------------------------------------- procedure Solid_Sphere (Radius : Float; Slices, Stacks : Integer) is begin GLUT_API.GLUT_Solid_Sphere (Double (Radius), Int (Slices), Int (Stacks)); end Solid_Sphere; -- ------------------------------------------------------------------------- procedure Solid_Teapot (Size : Float) is begin GLUT_API.GLUT_Solid_Teapot (Double (Size)); end Solid_Teapot; -- ------------------------------------------------------------------------- procedure Solid_Tetrahedron is begin GLUT_API.GLUT_Solid_Tetrahedron; end Solid_Tetrahedron; -- ------------------------------------------------------------------------- procedure Solid_Torus (Inner_Radius, Outer_Radius : Float; Sides, Rings : Integer) is begin GLUT_API.GLUT_Solid_Torus (Double (Inner_Radius), Double (Outer_Radius), Int (Sides), Int (Rings)); end Solid_Torus; -- ------------------------------------------------------------------------- end Graphic_Data;
30,165
ada
0
DrenfongWong/tkm-rpc
specs/ada/server/ike/tkmrpc-operation_handlers-ike-ae_reset.adb
<filename>specs/ada/server/ike/tkmrpc-operation_handlers-ike-ae_reset.adb with Tkmrpc.Servers.Ike; with Tkmrpc.Results; with Tkmrpc.Request.Ike.Ae_Reset.Convert; with Tkmrpc.Response.Ike.Ae_Reset.Convert; package body Tkmrpc.Operation_Handlers.Ike.Ae_Reset is ------------------------------------------------------------------------- procedure Handle (Req : Request.Data_Type; Res : out Response.Data_Type) is Specific_Req : Request.Ike.Ae_Reset.Request_Type; Specific_Res : Response.Ike.Ae_Reset.Response_Type; begin Specific_Res := Response.Ike.Ae_Reset.Null_Response; Specific_Req := Request.Ike.Ae_Reset.Convert.From_Request (S => Req); if Specific_Req.Data.Ae_Id'Valid then Servers.Ike.Ae_Reset (Result => Specific_Res.Header.Result, Ae_Id => Specific_Req.Data.Ae_Id); Res := Response.Ike.Ae_Reset.Convert.To_Response (S => Specific_Res); else Res.Header.Result := Results.Invalid_Parameter; end if; end Handle; end Tkmrpc.Operation_Handlers.Ike.Ae_Reset;
30,166
ada
6
godunko/adagl
sources/glew/opengl-generic_buffers.adb
------------------------------------------------------------------------------ -- -- -- Ada binding for OpenGL/WebGL -- -- -- -- Runtime Library Component -- -- -- ------------------------------------------------------------------------------ -- -- -- Copyright © 2018, <NAME> <<EMAIL>> -- -- 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. -- -- -- ------------------------------------------------------------------------------ with System; with OpenGL.Contexts.Internals; with GLEW; use GLEW; with Interfaces.C; package body OpenGL.Generic_Buffers is use type GLFW.GLFWwindow_Access; type GLuint_Access is access all GLuint with Convention => C; Map : constant array (OpenGL.Buffer_Type) of OpenGL.GLenum := (OpenGL.Vertex => GLEW.ARRAY_BUFFER, OpenGL.Index => GLEW.ELEMENT_ARRAY_BUFFER); -------------- -- Allocate -- -------------- procedure Allocate (Self : in out OpenGL_Buffer'Class; Data : Element_Array) is use type Interfaces.C.ptrdiff_t; begin if Self.Context = null or Self.Context /= OpenGL.Contexts.Internals.Current_GLFW_Context then -- Buffer was not created or created for another context. return; end if; glBufferData (Map (Self.Buffer_Type), Data'Size / 8, Data'Address, STATIC_DRAW); end Allocate; ---------- -- Bind -- ---------- function Bind (Self : in out OpenGL_Buffer'Class) return Boolean is begin if Self.Context = null or Self.Context /= OpenGL.Contexts.Internals.Current_GLFW_Context then -- Buffer was not created or created for another context. return False; end if; glBindBuffer (Map (Self.Buffer_Type), Self.Buffer); return True; end Bind; ---------- -- Bind -- ---------- procedure Bind (Self : in out OpenGL_Buffer'Class) is begin if not Self.Bind then raise Program_Error; end if; end Bind; ------------ -- Create -- ------------ function Create (Self : in out OpenGL_Buffer'Class) return Boolean is use type Interfaces.C.unsigned; begin if Self.Context = null then Self.Context := OpenGL.Contexts.Internals.Current_GLFW_Context; if Self.Context = null then return False; end if; end if; if Self.Buffer = 0 then glGenBuffers (1, Self.Buffer'Unchecked_Access); if Self.Buffer = 0 then Self.Context := null; return False; end if; end if; return True; end Create; ------------ -- Create -- ------------ procedure Create (Self : in out OpenGL_Buffer'Class) is begin if not Self.Create then raise Program_Error; end if; end Create; ------------ -- Stride -- ------------ function Stride return System.Storage_Elements.Storage_Count is use type System.Storage_Elements.Storage_Offset; begin return Element_Array'Component_Size / System.Storage_Unit; end Stride; end OpenGL.Generic_Buffers;
30,167
ada
3
stcarrez/ada-css
src/css-core.ads
----------------------------------------------------------------------- -- css-core -- Core CSS API definition -- Copyright (C) 2017 <NAME> -- Written by <NAME> (<EMAIL>) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- with Util.Strings; with Util.Refs; with Util.Log.Locations; private with CSS.Comments; private with Ada.Finalization; private with Ada.Strings.Unbounded; private with Ada.Containers.Hashed_Maps; -- The API implemented by the <tt>CSS.Core</tt> package and child packages try to -- follow the IDL specification defined in the W3C CSS Object Model (CSSOM) -- (See https://drafts.csswg.org/cssom/ or https://www.w3.org/TR/2016/WD-cssom-1-20160317/) package CSS.Core is type CSSProperty_Name is access all String; subtype CSSProperty_Value is CSSProperty_Name; subtype Location is Util.Log.Locations.Line_Info; use type Util.Log.Locations.Line_Info; -- Get the line number. function Get_Line (Loc : in Location) return Natural renames Util.Log.Locations.Line; -- Get a printable representation of the source file name and line number. function To_String (Loc : in Location) return String; -- The StyleSheet interface represents an abstract, base style sheet. -- See CSSOM: 5.1.1. The StyleSheet Interface type Stylesheet is tagged limited private; type Stylesheet_Access is access all Stylesheet'Class; -- Returns the CSS type ("text/css"). function Get_Type (Sheet : in Stylesheet) return String; -- Get the parent CSS stylesheet if there is one or return null. function Get_Parent (Sheet : in Stylesheet) return Stylesheet_Access; -- Get the source file information. function Get_File_Info (Sheet : in Stylesheet) return Util.Log.Locations.File_Info_Access; -- Get the href attribute (stylesheet location). function Get_Href (Sheet : in Stylesheet) return String; -- Set the href attribute representing the stylesheet location. procedure Set_Href (Sheet : in out Stylesheet; Href : in String); function Create_Property_Name (Sheet : in Stylesheet; Name : in String) return CSSProperty_Name; -- Create a location record to represent a CSS source position. function Create_Location (Sheet : in Stylesheet_Access; Line : in Natural; Column : in Natural) return Location; type CSSRule_Type is (STYLE_RULE, CHARSET_RULE, IMPORT_RULE, MEDIA_RULE, FONT_FACE_RULE, PAGE_RULE, MARGIN_RULE, NAMESPACE_RULE); -- The CSSRule interface represents an abstract, base CSS style rule. -- Each distinct CSS style rule type is represented by a distinct interface that inherits -- from this interface. -- See CSSOM: Section 5.4.2. The CSSRule Interface type CSSRule is abstract new Util.Refs.Ref_Entity with private; type CSSRule_Access is access all CSSRule'Class; -- Get the type that identifies the rule. function Get_Type (Rule : in CSSRule) return CSSRule_Type is abstract; -- Get the parent rule. Returns null when there is no parent. function Get_Parent (Rule : in CSSRule) return CSSRule_Access; -- Get the stylesheet. function Get_Stylesheet (Rule : in CSSRule) return Stylesheet_Access; -- Get the location of the rule. function Get_Location (Rule : in CSSRule) return Location; private type String_Access is access all String; package String_Map is new Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access, Element_Type => CSSProperty_Name, Hash => Util.Strings.Hash, Equivalent_Keys => Util.Strings.Equivalent_Keys); type String_Map_Access is access all String_Map.Map; type Stylesheet is new Ada.Finalization.Limited_Controlled with record Loc : Location; Parent : Stylesheet_Access; File : Util.Log.Locations.File_Info_Access; Href : Ada.Strings.Unbounded.Unbounded_String; Strings : String_Map_Access := new String_Map.Map; Comments : CSS.Comments.CSSComment_List; end record; overriding procedure Finalize (Sheet : in out Stylesheet); type CSSRule is abstract new Util.Refs.Ref_Entity with record Loc : Location; Sheet : Stylesheet_Access; Parent : CSSRule_Access; Comments : CSS.Comments.CSSComment_List; end record; -- Set the source code location. procedure Set_Location (Rule : in out CSSRule'Class; Line : in Natural; Column : in Natural; Sheet : in Stylesheet_Access); end CSS.Core;
30,168
ada
1
selroc/Renaissance-Ada
src/libraries/Rejuvenation_Lib/src/rejuvenation-pretty_print.adb
with Ada.Assertions; use Ada.Assertions; with Interfaces.C; use Interfaces.C; with Rejuvenation; use Rejuvenation; with Rejuvenation.File_Utils; use Rejuvenation.File_Utils; with Rejuvenation.Indentation; use Rejuvenation.Indentation; with Rejuvenation.Navigation; use Rejuvenation.Navigation; with Rejuvenation.Nested; use Rejuvenation.Nested; with Rejuvenation.Node_Locations; use Rejuvenation.Node_Locations; with Rejuvenation.String_Utils; use Rejuvenation.String_Utils; package body Rejuvenation.Pretty_Print is procedure Surround_Node_By_Pretty_Print_Section (T_R : in out Text_Rewrite'Class; Node : Ada_Node'Class) is function Predicate (Node : Ada_Node'Class) return Boolean; function Predicate (Node : Ada_Node'Class) return Boolean -- workaround for https://gt3-prod-1.adacore.com/#/tickets/UB17-034 -- not only look for node on separate lines, -- but also require a particular kind is begin return Node.Kind in Ada_Stmt | Ada_Stmt_List | Ada_Basic_Decl | Ada_Compilation_Unit and then Node_On_Separate_Lines (Node); end Predicate; Ctx : constant Ada_Node := Get_Reflexive_Ancestor (Node, Predicate'Access); begin T_R.Prepend (Ctx, Pretty_Print_On, Before => Trivia_On_Same_Line); T_R.Append (Ctx, Pretty_Print_Off, After => Trivia_On_Same_Line); end Surround_Node_By_Pretty_Print_Section; procedure Turn_Pretty_Printing_Initially_Off (T_R : in out Text_Rewrite_Unit) is Unit : constant Analysis_Unit := T_R.Get_Unit; begin T_R.Prepend (Unit.Root, Pretty_Print_Off, All_Trivia, Unit.Get_Charset); end Turn_Pretty_Printing_Initially_Off; procedure Turn_Pretty_Printing_Initially_Off (Filename : String) is Original_Content : constant String := Get_String_From_File (Filename); begin Write_String_To_File (Pretty_Print_Off & Original_Content, Filename); end Turn_Pretty_Printing_Initially_Off; procedure Remove_Cr_Cr_Lf (Filename : String); procedure Remove_Cr_Cr_Lf (Filename : String) -- repair gnatpp screwed up -- see https://gt3-prod-1.adacore.com/#/tickets/U617-042 is Contents : constant String := Get_String_From_File (Filename); Final_Contents : constant String := Replace_All (Contents, ASCII.CR & ASCII.CR & ASCII.LF, ASCII.CR & ASCII.LF); begin Write_String_To_File (Final_Contents, Filename); end Remove_Cr_Cr_Lf; procedure Remove_Nested_Pretty_Print_Flags (Filename : String); procedure Remove_Nested_Pretty_Print_Flags (Filename : String) is Contents : constant String := Get_String_From_File (Filename); Final_Contents : constant String := Remove_Nested_Flags (Contents, Pretty_Print_On, Pretty_Print_Off, 1); begin Write_String_To_File (Final_Contents, Filename); end Remove_Nested_Pretty_Print_Flags; procedure Pretty_Print_Sections (Filename : String; Projectname : String) is function Sys (Arg : char_array) return Integer; pragma Import (C, Sys, "system"); Command : constant String := "gnatpp" & " -P " & Projectname & " --pp-on=" & Flag_On & " --pp-off=" & Flag_Off & " " & Filename; Ret_Val : Integer; begin Remove_Nested_Pretty_Print_Flags (Filename); declare Original_Content : constant String := Get_String_From_File (Filename); Original_Last_Char : constant Character := Original_Content (Original_Content'Last); begin Ret_Val := Sys (To_C (Command)); Assert (Check => Ret_Val = 0, Message => "System call to gnatpp returned " & Ret_Val'Image); declare Current_Content : constant String := Get_String_From_File (Filename); Current_Last_Char : constant Character := Current_Content (Current_Content'Last); begin if Current_Last_Char /= Original_Last_Char then -- correct GNATPP bug (additional LF at end of file) Write_String_To_File (Current_Content (Current_Content'First .. Current_Content'Last - 1), Filename); end if; end; end; Remove_Cr_Cr_Lf (Filename); end Pretty_Print_Sections; procedure Remove_Pretty_Print_Flags (Filename : String) is Contents : constant String := Get_String_From_File (Filename); New_Contents : constant String := Replace_All (Replace_All (Replace_All (Replace_All (Contents, Pretty_Print_On, ""), Alt_Pretty_Print_On, ""), Pretty_Print_Off, ""), Alt_Pretty_Print_Off, ""); begin Write_String_To_File (New_Contents, Filename); end Remove_Pretty_Print_Flags; end Rejuvenation.Pretty_Print;
30,169
ada
0
PyllrNL/Project_Euler_Solutions
Ada/problem_15/problem_15.ads
with Test_Solution; use Test_Solution; package problem_15 is type Int128 is range -2**127 .. 2**127 - 1; function Solution_1 return Int128; procedure Test_Solution_1; function Get_Solutions return Solution_Case; end problem_15;
30,170
ada
0
persan/a-cups
src/gen/cups-netinet_in_h.ads
pragma Ada_2005; pragma Style_Checks (Off); with Interfaces.C; use Interfaces.C; with CUPS.stdint_h; with CUPS.bits_sockaddr_h; with CUPS.bits_socket_h; with System; with CUPS.unistd_h; private package CUPS.netinet_in_h is -- unsupported macro: IPPROTO_IP IPPROTO_IP -- unsupported macro: IPPROTO_ICMP IPPROTO_ICMP -- unsupported macro: IPPROTO_IGMP IPPROTO_IGMP -- unsupported macro: IPPROTO_IPIP IPPROTO_IPIP -- unsupported macro: IPPROTO_TCP IPPROTO_TCP -- unsupported macro: IPPROTO_EGP IPPROTO_EGP -- unsupported macro: IPPROTO_PUP IPPROTO_PUP -- unsupported macro: IPPROTO_UDP IPPROTO_UDP -- unsupported macro: IPPROTO_IDP IPPROTO_IDP -- unsupported macro: IPPROTO_TP IPPROTO_TP -- unsupported macro: IPPROTO_DCCP IPPROTO_DCCP -- unsupported macro: IPPROTO_IPV6 IPPROTO_IPV6 -- unsupported macro: IPPROTO_RSVP IPPROTO_RSVP -- unsupported macro: IPPROTO_GRE IPPROTO_GRE -- unsupported macro: IPPROTO_ESP IPPROTO_ESP -- unsupported macro: IPPROTO_AH IPPROTO_AH -- unsupported macro: IPPROTO_MTP IPPROTO_MTP -- unsupported macro: IPPROTO_BEETPH IPPROTO_BEETPH -- unsupported macro: IPPROTO_ENCAP IPPROTO_ENCAP -- unsupported macro: IPPROTO_PIM IPPROTO_PIM -- unsupported macro: IPPROTO_COMP IPPROTO_COMP -- unsupported macro: IPPROTO_SCTP IPPROTO_SCTP -- unsupported macro: IPPROTO_UDPLITE IPPROTO_UDPLITE -- unsupported macro: IPPROTO_MPLS IPPROTO_MPLS -- unsupported macro: IPPROTO_RAW IPPROTO_RAW -- unsupported macro: IPPROTO_HOPOPTS IPPROTO_HOPOPTS -- unsupported macro: IPPROTO_ROUTING IPPROTO_ROUTING -- unsupported macro: IPPROTO_FRAGMENT IPPROTO_FRAGMENT -- unsupported macro: IPPROTO_ICMPV6 IPPROTO_ICMPV6 -- unsupported macro: IPPROTO_NONE IPPROTO_NONE -- unsupported macro: IPPROTO_DSTOPTS IPPROTO_DSTOPTS -- unsupported macro: IPPROTO_MH IPPROTO_MH -- arg-macro: function IN_CLASSA ((((in_addr_t)(a)) and 16#80000000#) = 0 -- return (((in_addr_t)(a)) and 16#80000000#) = 0; IN_CLASSA_NET : constant := 16#ff000000#; -- netinet/in.h:167 IN_CLASSA_NSHIFT : constant := 24; -- netinet/in.h:168 -- unsupported macro: IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) IN_CLASSA_MAX : constant := 128; -- netinet/in.h:170 -- arg-macro: function IN_CLASSB ((((in_addr_t)(a)) and 16#c0000000#) = 16#80000000# -- return (((in_addr_t)(a)) and 16#c0000000#) = 16#80000000#; IN_CLASSB_NET : constant := 16#ffff0000#; -- netinet/in.h:173 IN_CLASSB_NSHIFT : constant := 16; -- netinet/in.h:174 -- unsupported macro: IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) IN_CLASSB_MAX : constant := 65536; -- netinet/in.h:176 -- arg-macro: function IN_CLASSC ((((in_addr_t)(a)) and 16#e0000000#) = 16#c0000000# -- return (((in_addr_t)(a)) and 16#e0000000#) = 16#c0000000#; IN_CLASSC_NET : constant := 16#ffffff00#; -- netinet/in.h:179 IN_CLASSC_NSHIFT : constant := 8; -- netinet/in.h:180 -- unsupported macro: IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) -- arg-macro: function IN_CLASSD ((((in_addr_t)(a)) and 16#f0000000#) = 16#e0000000# -- return (((in_addr_t)(a)) and 16#f0000000#) = 16#e0000000#; -- arg-macro: procedure IN_MULTICAST IN_CLASSD(a) -- IN_CLASSD(a) -- arg-macro: function IN_EXPERIMENTAL ((((in_addr_t)(a)) and 16#e0000000#) = 16#e0000000# -- return (((in_addr_t)(a)) and 16#e0000000#) = 16#e0000000#; -- arg-macro: function IN_BADCLASS ((((in_addr_t)(a)) and 16#f0000000#) = 16#f0000000# -- return (((in_addr_t)(a)) and 16#f0000000#) = 16#f0000000#; -- unsupported macro: INADDR_ANY ((in_addr_t) 0x00000000) -- unsupported macro: INADDR_BROADCAST ((in_addr_t) 0xffffffff) -- unsupported macro: INADDR_NONE ((in_addr_t) 0xffffffff) IN_LOOPBACKNET : constant := 127; -- netinet/in.h:197 -- unsupported macro: INADDR_LOOPBACK ((in_addr_t) 0x7f000001) -- unsupported macro: INADDR_UNSPEC_GROUP ((in_addr_t) 0xe0000000) -- unsupported macro: INADDR_ALLHOSTS_GROUP ((in_addr_t) 0xe0000001) -- unsupported macro: INADDR_ALLRTRS_GROUP ((in_addr_t) 0xe0000002) -- unsupported macro: INADDR_MAX_LOCAL_GROUP ((in_addr_t) 0xe00000ff) -- unsupported macro: s6_addr __in6_u.__u6_addr8 -- unsupported macro: s6_addr16 __in6_u.__u6_addr16 -- unsupported macro: s6_addr32 __in6_u.__u6_addr32 -- unsupported macro: IN6ADDR_ANY_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } } -- unsupported macro: IN6ADDR_LOOPBACK_INIT { { { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1 } } } INET_ADDRSTRLEN : constant := 16; -- netinet/in.h:234 INET6_ADDRSTRLEN : constant := 46; -- netinet/in.h:235 -- arg-macro: function IP_MSFILTER_SIZE (sizeof (struct ip_msfilter) - sizeof (struct in_addr) + (numsrc) * sizeof (struct in_addr) -- return sizeof (struct ip_msfilter) - sizeof (struct in_addr) + (numsrc) * sizeof (struct in_addr); -- arg-macro: function GROUP_FILTER_SIZE (sizeof (struct group_filter) - sizeof (struct sockaddr_storage) + ((numsrc) * sizeof (struct sockaddr_storage)) -- return sizeof (struct group_filter) - sizeof (struct sockaddr_storage) + ((numsrc) * sizeof (struct sockaddr_storage)); -- arg-macro: function IN6_IS_ADDR_UNSPECIFIED (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = 0; }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = 0; }); -- arg-macro: function IN6_IS_ADDR_LOOPBACK (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = htonl (1); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then __a.s6_addr32(3) = htonl (1); }); -- arg-macro: function IN6_IS_ADDR_LINKLOCAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fe800000#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fe800000#); }); -- arg-macro: function IN6_IS_ADDR_SITELOCAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fec00000#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); (__a.s6_addr32(0) and htonl (16#ffc00000#)) = htonl (16#fec00000#); }); -- arg-macro: function IN6_IS_ADDR_V4MAPPED (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = htonl (16#ffff#); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = htonl (16#ffff#); }); -- arg-macro: function IN6_IS_ADDR_V4COMPAT (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then ntohl (__a.s6_addr32(3)) > 1; }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); __a.s6_addr32(0) = 0 and then __a.s6_addr32(1) = 0 and then __a.s6_addr32(2) = 0 and then ntohl (__a.s6_addr32(3)) > 1; }); -- arg-macro: function IN6_ARE_ADDR_EQUAL (__extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); const struct in6_addr *__b := (const struct in6_addr *) (b); __a.s6_addr32(0) = __b.s6_addr32(0) and then __a.s6_addr32(1) = __b.s6_addr32(1) and then __a.s6_addr32(2) = __b.s6_addr32(2) and then __a.s6_addr32(3) = __b.s6_addr32(3); }) -- return __extension__ ({ const struct in6_addr *__a := (const struct in6_addr *) (a); const struct in6_addr *__b := (const struct in6_addr *) (b); __a.s6_addr32(0) = __b.s6_addr32(0) and then __a.s6_addr32(1) = __b.s6_addr32(1) and then __a.s6_addr32(2) = __b.s6_addr32(2) and then __a.s6_addr32(3) = __b.s6_addr32(3); }); -- arg-macro: function IN6_IS_ADDR_MULTICAST (((const uint8_t *) (a))(0) = 16#ff# -- return ((const uint8_t *) (a))(0) = 16#ff#; -- arg-macro: function IN6_IS_ADDR_MC_NODELOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#1#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#1#); -- arg-macro: function IN6_IS_ADDR_MC_LINKLOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#2#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#2#); -- arg-macro: function IN6_IS_ADDR_MC_SITELOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#5#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#5#); -- arg-macro: function IN6_IS_ADDR_MC_ORGLOCAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#8#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#8#); -- arg-macro: function IN6_IS_ADDR_MC_GLOBAL (IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#e#) -- return IN6_IS_ADDR_MULTICAST(a) and then ((((const uint8_t *) (a))(1) and 16#f#) = 16#e#); -- Copyright (C) 1991-2016 Free Software Foundation, Inc. -- This file is part of the GNU C Library. -- The GNU C Library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- The GNU C Library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- You should have received a copy of the GNU Lesser General Public -- License along with the GNU C Library; if not, see -- <http://www.gnu.org/licenses/>. -- Internet address. subtype in_addr_t is CUPS.stdint_h.uint32_t; -- netinet/in.h:30 type in_addr is record s_addr : aliased in_addr_t; -- netinet/in.h:33 end record; pragma Convention (C_Pass_By_Copy, in_addr); -- netinet/in.h:31 -- Get system-specific definitions. -- Standard well-defined IP protocols. -- Dummy protocol for TCP. -- Internet Control Message Protocol. -- Internet Group Management Protocol. -- IPIP tunnels (older KA9Q tunnels use 94). -- Transmission Control Protocol. -- Exterior Gateway Protocol. -- PUP protocol. -- User Datagram Protocol. -- XNS IDP protocol. -- SO Transport Protocol Class 4. -- Datagram Congestion Control Protocol. -- IPv6 header. -- Reservation Protocol. -- General Routing Encapsulation. -- encapsulating security payload. -- authentication header. -- Multicast Transport Protocol. -- IP option pseudo header for BEET. -- Encapsulation Header. -- Protocol Independent Multicast. -- Compression Header Protocol. -- Stream Control Transmission Protocol. -- UDP-Lite protocol. -- MPLS in IP. -- Raw IP packets. -- If __USE_KERNEL_IPV6_DEFS is defined then the user has included the kernel -- network headers first and we should use those ABI-identical definitions -- instead of our own. -- IPv6 Hop-by-Hop options. -- IPv6 routing header. -- IPv6 fragmentation header. -- ICMPv6. -- IPv6 no next header. -- IPv6 destination options. -- IPv6 mobility header. -- Type to represent a port. subtype in_port_t is CUPS.stdint_h.uint16_t; -- netinet/in.h:119 -- Standard well-known ports. -- Echo service. -- Discard transmissions service. -- System status service. -- Time of day service. -- Network status service. -- File Transfer Protocol. -- Telnet protocol. -- Simple Mail Transfer Protocol. -- Timeserver service. -- Domain Name Service. -- Internet Whois service. -- Trivial File Transfer Protocol. -- Finger service. -- SUPDUP protocol. -- execd service. -- rlogind service. -- UDP ports. -- Ports less than this value are reserved for privileged processes. -- Ports greater this value are reserved for (non-privileged) servers. -- Definitions of the bits in an Internet address integer. -- On subnets, host and network parts are found according to -- the subnet mask, not these masks. -- Address to accept any incoming messages. -- Address to send to all hosts. -- Address indicating an error return. -- Network number for local host loopback. -- Address to loopback in software to local host. -- Defines for Multicast INADDR. -- IPv6 address type in6_addr; type in6_addr_uu_u6_addr8_array is array (0 .. 15) of aliased CUPS.stdint_h.uint8_t; type in6_addr_uu_u6_addr16_array is array (0 .. 7) of aliased CUPS.stdint_h.uint16_t; type in6_addr_uu_u6_addr32_array is array (0 .. 3) of aliased CUPS.stdint_h.uint32_t; type anon_32 (discr : unsigned := 0) is record case discr is when 0 => uu_u6_addr8 : aliased in6_addr_uu_u6_addr8_array; -- netinet/in.h:215 when 1 => uu_u6_addr16 : aliased in6_addr_uu_u6_addr16_array; -- netinet/in.h:217 when others => uu_u6_addr32 : aliased in6_addr_uu_u6_addr32_array; -- netinet/in.h:218 end case; end record; pragma Convention (C_Pass_By_Copy, anon_32); pragma Unchecked_Union (anon_32);type in6_addr is record uu_in6_u : aliased anon_32; -- netinet/in.h:220 end record; pragma Convention (C_Pass_By_Copy, in6_addr); -- netinet/in.h:211 -- :: in6addr_any : aliased in6_addr; -- netinet/in.h:229 pragma Import (C, in6addr_any, "in6addr_any"); -- ::1 in6addr_loopback : aliased in6_addr; -- netinet/in.h:230 pragma Import (C, in6addr_loopback, "in6addr_loopback"); -- Structure describing an Internet socket address. type sockaddr_in_sin_zero_array is array (0 .. 7) of aliased unsigned_char; type sockaddr_in is record sin_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- netinet/in.h:241 sin_port : aliased in_port_t; -- netinet/in.h:242 sin_addr : aliased in_addr; -- netinet/in.h:243 sin_zero : aliased sockaddr_in_sin_zero_array; -- netinet/in.h:249 end record; pragma Convention (C_Pass_By_Copy, sockaddr_in); -- netinet/in.h:239 -- Port number. -- Internet address. -- Pad to size of `struct sockaddr'. -- Ditto, for IPv6. type sockaddr_in6 is record sin6_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- netinet/in.h:256 sin6_port : aliased in_port_t; -- netinet/in.h:257 sin6_flowinfo : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:258 sin6_addr : aliased in6_addr; -- netinet/in.h:259 sin6_scope_id : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:260 end record; pragma Convention (C_Pass_By_Copy, sockaddr_in6); -- netinet/in.h:254 -- Transport layer port # -- IPv6 flow information -- IPv6 address -- IPv6 scope-id -- IPv4 multicast request. -- IP multicast address of group. type ip_mreq is record imr_multiaddr : aliased in_addr; -- netinet/in.h:269 imr_interface : aliased in_addr; -- netinet/in.h:272 end record; pragma Convention (C_Pass_By_Copy, ip_mreq); -- netinet/in.h:266 -- Local IP address of interface. -- IP multicast address of group. type ip_mreq_source is record imr_multiaddr : aliased in_addr; -- netinet/in.h:278 imr_interface : aliased in_addr; -- netinet/in.h:281 imr_sourceaddr : aliased in_addr; -- netinet/in.h:284 end record; pragma Convention (C_Pass_By_Copy, ip_mreq_source); -- netinet/in.h:275 -- IP address of source. -- IP address of interface. -- Likewise, for IPv6. -- IPv6 multicast address of group type ipv6_mreq is record ipv6mr_multiaddr : aliased in6_addr; -- netinet/in.h:293 ipv6mr_interface : aliased unsigned; -- netinet/in.h:296 end record; pragma Convention (C_Pass_By_Copy, ipv6_mreq); -- netinet/in.h:290 -- Address data. -- Structure large enough to hold any socket address (with the historical -- exception of AF_UNIX). -- Address family, etc. subtype sockaddr_storage_uu_ss_padding_array is Interfaces.C.char_array (0 .. 117); type sockaddr_storage is record ss_family : aliased CUPS.bits_sockaddr_h.sa_family_t; -- bits/socket.h:168 uu_ss_padding : aliased sockaddr_storage_uu_ss_padding_array; -- bits/socket.h:169 uu_ss_align : aliased unsigned_long; -- bits/socket.h:170 end record; pragma Convention (C_Pass_By_Copy, sockaddr_storage); -- bits/socket.h:166 -- local interface -- Multicast group request. -- Interface index. type group_req is record gr_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:305 gr_group : aliased sockaddr_storage; -- netinet/in.h:308 end record; pragma Convention (C_Pass_By_Copy, group_req); -- netinet/in.h:302 -- Group address. -- Interface index. type group_source_req is record gsr_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:314 gsr_group : aliased sockaddr_storage; -- netinet/in.h:317 gsr_source : aliased sockaddr_storage; -- netinet/in.h:320 end record; pragma Convention (C_Pass_By_Copy, group_source_req); -- netinet/in.h:311 -- Group address. -- Source address. -- Full-state filter operations. -- IP multicast address of group. type ip_msfilter_imsf_slist_array is array (0 .. 0) of aliased in_addr; type ip_msfilter is record imsf_multiaddr : aliased in_addr; -- netinet/in.h:328 imsf_interface : aliased in_addr; -- netinet/in.h:331 imsf_fmode : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:334 imsf_numsrc : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:337 imsf_slist : aliased ip_msfilter_imsf_slist_array; -- netinet/in.h:339 end record; pragma Convention (C_Pass_By_Copy, ip_msfilter); -- netinet/in.h:325 -- Local IP address of interface. -- Filter mode. -- Number of source addresses. -- Source addresses. -- Interface index. type group_filter_gf_slist_array is array (0 .. 0) of aliased sockaddr_storage; type group_filter is record gf_interface : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:349 gf_group : aliased sockaddr_storage; -- netinet/in.h:352 gf_fmode : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:355 gf_numsrc : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:358 gf_slist : aliased group_filter_gf_slist_array; -- netinet/in.h:360 end record; pragma Convention (C_Pass_By_Copy, group_filter); -- netinet/in.h:346 -- Group address. -- Filter mode. -- Number of source addresses. -- Source addresses. -- Functions to convert between host and network byte order. -- Please note that these functions normally take `unsigned long int' or -- `unsigned short int' values as arguments and also return them. But -- this was a short-sighted decision since on different systems the types -- may have different representations but the values are always the same. function ntohl (uu_netlong : CUPS.stdint_h.uint32_t) return CUPS.stdint_h.uint32_t; -- netinet/in.h:376 pragma Import (C, ntohl, "ntohl"); function ntohs (uu_netshort : CUPS.stdint_h.uint16_t) return CUPS.stdint_h.uint16_t; -- netinet/in.h:377 pragma Import (C, ntohs, "ntohs"); function htonl (uu_hostlong : CUPS.stdint_h.uint32_t) return CUPS.stdint_h.uint32_t; -- netinet/in.h:379 pragma Import (C, htonl, "htonl"); function htons (uu_hostshort : CUPS.stdint_h.uint16_t) return CUPS.stdint_h.uint16_t; -- netinet/in.h:381 pragma Import (C, htons, "htons"); -- Get machine dependent optimized versions of byte swapping functions. -- We can optimize calls to the conversion functions. Either nothing has -- to be done or we are using directly the byte-swapping functions which -- often can be inlined. -- The host byte order is the same as network byte order, -- so these functions are all just identity. -- Bind socket to a privileged IP port. function bindresvport (uu_sockfd : int; uu_sock_in : access sockaddr_in) return int; -- netinet/in.h:503 pragma Import (C, bindresvport, "bindresvport"); -- The IPv6 version of this function. function bindresvport6 (uu_sockfd : int; uu_sock_in : access sockaddr_in6) return int; -- netinet/in.h:506 pragma Import (C, bindresvport6, "bindresvport6"); -- Forward declaration. -- IPv6 packet information. -- src/dst IPv6 address type in6_pktinfo is record ipi6_addr : aliased in6_addr; -- netinet/in.h:539 ipi6_ifindex : aliased unsigned; -- netinet/in.h:540 end record; pragma Convention (C_Pass_By_Copy, in6_pktinfo); -- netinet/in.h:537 -- send/recv interface index -- IPv6 MTU information. -- dst address including zone ID type ip6_mtuinfo is record ip6m_addr : aliased sockaddr_in6; -- netinet/in.h:546 ip6m_mtu : aliased CUPS.stdint_h.uint32_t; -- netinet/in.h:547 end record; pragma Convention (C_Pass_By_Copy, ip6_mtuinfo); -- netinet/in.h:544 -- path MTU in host byte order -- Obsolete hop-by-hop and Destination Options Processing (RFC 2292). function inet6_option_space (uu_nbytes : int) return int; -- netinet/in.h:552 pragma Import (C, inet6_option_space, "inet6_option_space"); function inet6_option_init (uu_bp : System.Address; uu_cmsgp : System.Address; uu_type : int) return int; -- netinet/in.h:554 pragma Import (C, inet6_option_init, "inet6_option_init"); function inet6_option_append (uu_cmsg : access CUPS.bits_socket_h.cmsghdr; uu_typep : access CUPS.stdint_h.uint8_t; uu_multx : int; uu_plusy : int) return int; -- netinet/in.h:556 pragma Import (C, inet6_option_append, "inet6_option_append"); function inet6_option_alloc (uu_cmsg : access CUPS.bits_socket_h.cmsghdr; uu_datalen : int; uu_multx : int; uu_plusy : int) return access CUPS.stdint_h.uint8_t; -- netinet/in.h:559 pragma Import (C, inet6_option_alloc, "inet6_option_alloc"); function inet6_option_next (uu_cmsg : access constant CUPS.bits_socket_h.cmsghdr; uu_tptrp : System.Address) return int; -- netinet/in.h:562 pragma Import (C, inet6_option_next, "inet6_option_next"); function inet6_option_find (uu_cmsg : access constant CUPS.bits_socket_h.cmsghdr; uu_tptrp : System.Address; uu_type : int) return int; -- netinet/in.h:565 pragma Import (C, inet6_option_find, "inet6_option_find"); -- Hop-by-Hop and Destination Options Processing (RFC 3542). function inet6_opt_init (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:571 pragma Import (C, inet6_opt_init, "inet6_opt_init"); function inet6_opt_append (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_type : CUPS.stdint_h.uint8_t; uu_len : CUPS.unistd_h.socklen_t; uu_align : CUPS.stdint_h.uint8_t; uu_databufp : System.Address) return int; -- netinet/in.h:572 pragma Import (C, inet6_opt_append, "inet6_opt_append"); function inet6_opt_finish (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int) return int; -- netinet/in.h:575 pragma Import (C, inet6_opt_finish, "inet6_opt_finish"); function inet6_opt_set_val (uu_databuf : System.Address; uu_offset : int; uu_val : System.Address; uu_vallen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:577 pragma Import (C, inet6_opt_set_val, "inet6_opt_set_val"); function inet6_opt_next (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_typep : access CUPS.stdint_h.uint8_t; uu_lenp : access CUPS.unistd_h.socklen_t; uu_databufp : System.Address) return int; -- netinet/in.h:579 pragma Import (C, inet6_opt_next, "inet6_opt_next"); function inet6_opt_find (uu_extbuf : System.Address; uu_extlen : CUPS.unistd_h.socklen_t; uu_offset : int; uu_type : CUPS.stdint_h.uint8_t; uu_lenp : access CUPS.unistd_h.socklen_t; uu_databufp : System.Address) return int; -- netinet/in.h:582 pragma Import (C, inet6_opt_find, "inet6_opt_find"); function inet6_opt_get_val (uu_databuf : System.Address; uu_offset : int; uu_val : System.Address; uu_vallen : CUPS.unistd_h.socklen_t) return int; -- netinet/in.h:585 pragma Import (C, inet6_opt_get_val, "inet6_opt_get_val"); -- Routing Header Option (RFC 3542). function inet6_rth_space (uu_type : int; uu_segments : int) return CUPS.unistd_h.socklen_t; -- netinet/in.h:590 pragma Import (C, inet6_rth_space, "inet6_rth_space"); function inet6_rth_init (uu_bp : System.Address; uu_bp_len : CUPS.unistd_h.socklen_t; uu_type : int; uu_segments : int) return System.Address; -- netinet/in.h:591 pragma Import (C, inet6_rth_init, "inet6_rth_init"); function inet6_rth_add (uu_bp : System.Address; uu_addr : access constant in6_addr) return int; -- netinet/in.h:593 pragma Import (C, inet6_rth_add, "inet6_rth_add"); function inet6_rth_reverse (uu_in : System.Address; uu_out : System.Address) return int; -- netinet/in.h:594 pragma Import (C, inet6_rth_reverse, "inet6_rth_reverse"); function inet6_rth_segments (uu_bp : System.Address) return int; -- netinet/in.h:595 pragma Import (C, inet6_rth_segments, "inet6_rth_segments"); function inet6_rth_getaddr (uu_bp : System.Address; uu_index : int) return access in6_addr; -- netinet/in.h:596 pragma Import (C, inet6_rth_getaddr, "inet6_rth_getaddr"); -- Multicast source filter support. -- Get IPv4 source filter. function getipv4sourcefilter (uu_s : int; uu_interface_addr : in_addr; uu_group : in_addr; uu_fmode : access CUPS.stdint_h.uint32_t; uu_numsrc : access CUPS.stdint_h.uint32_t; uu_slist : access in_addr) return int; -- netinet/in.h:603 pragma Import (C, getipv4sourcefilter, "getipv4sourcefilter"); -- Set IPv4 source filter. function setipv4sourcefilter (uu_s : int; uu_interface_addr : in_addr; uu_group : in_addr; uu_fmode : CUPS.stdint_h.uint32_t; uu_numsrc : CUPS.stdint_h.uint32_t; uu_slist : access constant in_addr) return int; -- netinet/in.h:609 pragma Import (C, setipv4sourcefilter, "setipv4sourcefilter"); -- Get source filter. function getsourcefilter (uu_s : int; uu_interface_addr : CUPS.stdint_h.uint32_t; uu_group : access constant CUPS.bits_socket_h.sockaddr; uu_grouplen : CUPS.unistd_h.socklen_t; uu_fmode : access CUPS.stdint_h.uint32_t; uu_numsrc : access CUPS.stdint_h.uint32_t; uu_slist : access sockaddr_storage) return int; -- netinet/in.h:617 pragma Import (C, getsourcefilter, "getsourcefilter"); -- Set source filter. function setsourcefilter (uu_s : int; uu_interface_addr : CUPS.stdint_h.uint32_t; uu_group : access constant CUPS.bits_socket_h.sockaddr; uu_grouplen : CUPS.unistd_h.socklen_t; uu_fmode : CUPS.stdint_h.uint32_t; uu_numsrc : CUPS.stdint_h.uint32_t; uu_slist : access constant sockaddr_storage) return int; -- netinet/in.h:624 pragma Import (C, setsourcefilter, "setsourcefilter"); end CUPS.netinet_in_h;
30,171
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/c4/c41401a.ada
-- C41401A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT CONSTRAINT_ERROR IS RAISED IF THE PREFIX OF THE FOLLOWING -- ATTRIBUTES HAS THE VALUE NULL: -- A) 'CALLABLE AND 'TERMINATED FOR A TASK TYPE. -- B) 'FIRST, 'FIRST(N), 'LAST, 'LAST(N), 'LENGTH, 'LENGTH(N), -- 'RANGE, AND 'RANGE(N) FOR AN ARRAY TYPE. -- TBN 10/2/86 -- EDS 07/14/98 AVOID OPTIMIZATION WITH REPORT; USE REPORT; PROCEDURE C41401A IS SUBTYPE INT IS INTEGER RANGE 1 .. 10; TASK TYPE TT IS ENTRY E; END TT; TYPE ACC_TT IS ACCESS TT; TYPE NULL_ARR1 IS ARRAY (2 .. 1) OF INTEGER; TYPE ARRAY1 IS ARRAY (INT RANGE <>) OF INTEGER; TYPE NULL_ARR2 IS ARRAY (3 .. 1, 2 .. 1) OF INTEGER; TYPE ARRAY2 IS ARRAY (INT RANGE <>, INT RANGE <>) OF INTEGER; TYPE ACC_NULL1 IS ACCESS NULL_ARR1; TYPE ACC_ARR1 IS ACCESS ARRAY1; TYPE ACC_NULL2 IS ACCESS NULL_ARR2; TYPE ACC_ARR2 IS ACCESS ARRAY2; PTR_TT : ACC_TT; PTR_ARA1: ACC_NULL1; PTR_ARA2 : ACC_ARR1 (1 .. 4); PTR_ARA3 : ACC_NULL2; PTR_ARA4 : ACC_ARR2 (1 .. 2, 2 .. 4); BOOL_VAR : BOOLEAN := FALSE; INT_VAR : INTEGER := 1; TASK BODY TT IS BEGIN ACCEPT E; END TT; BEGIN TEST ("C41401A", "CHECK THAT CONSTRAINT_ERROR IS RAISED IF THE " & "PREFIX HAS A VALUE OF NULL FOR THE FOLLOWING " & "ATTRIBUTES: 'CALLABLE, 'TERMINATED, 'FIRST, " & "'LAST, 'LENGTH, AND 'RANGE"); BEGIN IF EQUAL (3, 2) THEN PTR_TT := NEW TT; END IF; BOOL_VAR := IDENT_BOOL(PTR_TT'CALLABLE); FAILED ("CONSTRAINT_ERROR NOT RAISED - 1 " & BOOLEAN'IMAGE(BOOL_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 2"); END; BEGIN IF EQUAL (1, 3) THEN PTR_TT := NEW TT; END IF; BOOL_VAR := IDENT_BOOL(PTR_TT'TERMINATED); FAILED ("CONSTRAINT_ERROR NOT RAISED - 3 " & BOOLEAN'IMAGE(BOOL_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 4"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA1'FIRST); FAILED ("CONSTRAINT_ERROR NOT RAISED - 5 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 6"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA2'LAST); FAILED ("CONSTRAINT_ERROR NOT RAISED - 7 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 8"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA1'LENGTH); FAILED ("CONSTRAINT_ERROR NOT RAISED - 9 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 10"); END; BEGIN DECLARE A : ARRAY1 (PTR_ARA2'RANGE); BEGIN A (1) := IDENT_INT(1); FAILED ("CONSTRAINT_ERROR NOT RAISED - 11 " & INTEGER'IMAGE(A(1))); EXCEPTION WHEN OTHERS => FAILED ("CONSTRAINT_ERROR NOT RAISED - 11 "); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 12"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA3'FIRST(2)); FAILED ("CONSTRAINT_ERROR NOT RAISED - 13 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 14"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA4'LAST(2)); FAILED ("CONSTRAINT_ERROR NOT RAISED - 15 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 16"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA3'LENGTH(2)); FAILED ("CONSTRAINT_ERROR NOT RAISED - 17 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 18"); END; BEGIN DECLARE A : ARRAY1 (PTR_ARA4'RANGE(2)); BEGIN A (1) := IDENT_INT(1); FAILED ("CONSTRAINT_ERROR NOT RAISED - 19 " & INTEGER'IMAGE(A(1))); EXCEPTION WHEN OTHERS => FAILED ("CONSTRAINT_ERROR NOT RAISED - 19 "); END; EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 20"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA4'LAST(1)); FAILED ("CONSTRAINT_ERROR NOT RAISED - 21 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 22"); END; BEGIN INT_VAR := IDENT_INT(PTR_ARA3'LENGTH(1)); FAILED ("CONSTRAINT_ERROR NOT RAISED - 23 " & INTEGER'IMAGE(INT_VAR)); EXCEPTION WHEN CONSTRAINT_ERROR => NULL; WHEN OTHERS => FAILED ("UNEXPECTED EXCEPTION RAISED - 24"); END; RESULT; END C41401A;
30,172
ada
1
vidkidz/crossbridge
llvm-gcc-4.2-2.9/gcc/ada/a-ststio.ads
------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- A D A . S T R E A M S . S T R E A M _ I O -- -- -- -- S p e c -- -- -- -- Copyright (C) 1992-2006, Free Software Foundation, Inc. -- -- -- -- This specification is derived from the Ada Reference Manual for use with -- -- GNAT. The copyright notice above, and the license provisions that follow -- -- apply solely to the contents of the part following the private keyword. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 2, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License -- -- for more details. You should have received a copy of the GNU General -- -- Public License distributed with GNAT; see file COPYING. If not, write -- -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, -- -- Boston, MA 02110-1301, USA. -- -- -- -- As a special exception, if other files instantiate generics from this -- -- unit, or you link this unit with other files to produce an executable, -- -- this unit does not by itself cause the resulting executable to be -- -- covered by the GNU General Public License. This exception does not -- -- however invalidate any other reasons why the executable file might be -- -- covered by the GNU Public License. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ with Ada.IO_Exceptions; with System.File_Control_Block; package Ada.Streams.Stream_IO is type Stream_Access is access all Root_Stream_Type'Class; type File_Type is limited private; type File_Mode is (In_File, Out_File, Append_File); -- The following representation clause allows the use of unchecked -- conversion for rapid translation between the File_Mode type -- used in this package and System.File_IO. for File_Mode use (In_File => 0, -- System.File_IO.File_Mode'Pos (In_File) Out_File => 2, -- System.File_IO.File_Mode'Pos (Out_File) Append_File => 3); -- System.File_IO.File_Mode'Pos (Append_File) type Count is new Stream_Element_Offset range 0 .. Stream_Element_Offset'Last; subtype Positive_Count is Count range 1 .. Count'Last; -- Index into file, in stream elements --------------------- -- File Management -- --------------------- procedure Create (File : in out File_Type; Mode : File_Mode := Out_File; Name : String := ""; Form : String := ""); procedure Open (File : in out File_Type; Mode : File_Mode; Name : String; Form : String := ""); procedure Close (File : in out File_Type); procedure Delete (File : in out File_Type); procedure Reset (File : in out File_Type; Mode : File_Mode); procedure Reset (File : in out File_Type); function Mode (File : File_Type) return File_Mode; function Name (File : File_Type) return String; function Form (File : File_Type) return String; function Is_Open (File : File_Type) return Boolean; function End_Of_File (File : File_Type) return Boolean; function Stream (File : File_Type) return Stream_Access; ----------------------------- -- Input-Output Operations -- ----------------------------- procedure Read (File : File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset; From : Positive_Count); procedure Read (File : File_Type; Item : out Stream_Element_Array; Last : out Stream_Element_Offset); procedure Write (File : File_Type; Item : Stream_Element_Array; To : Positive_Count); procedure Write (File : File_Type; Item : Stream_Element_Array); ---------------------------------------- -- Operations on Position within File -- ---------------------------------------- procedure Set_Index (File : File_Type; To : Positive_Count); function Index (File : File_Type) return Positive_Count; function Size (File : File_Type) return Count; procedure Set_Mode (File : in out File_Type; Mode : File_Mode); -- Note: The parameter file is IN OUT in the RM, but this is clearly -- an oversight, and was intended to be IN, see AI95-00057. procedure Flush (File : File_Type); ---------------- -- Exceptions -- ---------------- Status_Error : exception renames IO_Exceptions.Status_Error; Mode_Error : exception renames IO_Exceptions.Mode_Error; Name_Error : exception renames IO_Exceptions.Name_Error; Use_Error : exception renames IO_Exceptions.Use_Error; Device_Error : exception renames IO_Exceptions.Device_Error; End_Error : exception renames IO_Exceptions.End_Error; Data_Error : exception renames IO_Exceptions.Data_Error; private package FCB renames System.File_Control_Block; ----------------------------- -- Stream_IO Control Block -- ----------------------------- type Operation is (Op_Read, Op_Write, Op_Other); -- Type used to record last operation (to optimize sequential operations) type Stream_AFCB is new FCB.AFCB with record Index : Count := 1; -- Current Index value File_Size : Stream_Element_Offset := -1; -- Cached value of File_Size, so that we do not keep recomputing it -- when not necessary (otherwise End_Of_File becomes gruesomely slow). -- A value of minus one means that there is no cached value. Last_Op : Operation := Op_Other; -- Last operation performed on file, used to avoid unnecessary -- repositioning between successive read or write operations. Update_Mode : Boolean := False; -- Set if the mode is changed from write to read or vice versa. -- Indicates that the file has been reopened in update mode. end record; type File_Type is access all Stream_AFCB; function AFCB_Allocate (Control_Block : Stream_AFCB) return FCB.AFCB_Ptr; procedure AFCB_Close (File : access Stream_AFCB); procedure AFCB_Free (File : access Stream_AFCB); procedure Read (File : in out Stream_AFCB; Item : out Ada.Streams.Stream_Element_Array; Last : out Ada.Streams.Stream_Element_Offset); -- Read operation used when Stream_IO file is treated directly as Stream procedure Write (File : in out Stream_AFCB; Item : Ada.Streams.Stream_Element_Array); -- Write operation used when Stream_IO file is treated directly as Stream end Ada.Streams.Stream_IO;
30,173
ada
12
TUM-EI-RCS/StratoX
software/unittest/estimator/src/logger.adb
with Ada.Text_IO; package body logger with Refined_State => (LogState => null) is procedure init(status : out Init_Error_Code) is null; procedure Start_SDLog is null; function Image (level : Log_Level) return String is begin case level is when SENSOR => return "S: "; when ERROR => return "E: "; when WARN => return "W: "; when INFO => return "I: "; when DEBUG => return "D: "; when TRACE => return "T: "; end case; end Image; procedure log(msg_level : Log_Level; message : Message_Type) is begin if msg_level = WARN or msg_level = INFO or msg_level = DEBUG then Ada.Text_IO.Put_Line (Image (msg_level) & message); end if; end log; procedure log_console (msg_level : Log_Level; message : Message_Type) is begin log (msg_level, message); end log_console; procedure log_sd (msg_level : Log_Level; message : ULog.Message) is null; procedure log_ulog(level : Log_Level; msg : ULog.Message) is null; procedure set_Log_Level(level : Log_Level) is null; package body Adapter is procedure init_adapter(status : out Init_Error_Code) is null; procedure write(message : Message_Type) is null; end Adapter; end logger;
30,174
ada
0
djamal2727/Main-Bearing-Analytical-Model
Validation/pyFrame3DD-master/gcc-master/gcc/ada/libgnat/a-stobbu.adb
<gh_stars>0 ------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME COMPONENTS -- -- -- -- ADA.STRINGS.TEXT_OUTPUT.BIT_BUCKETS -- -- -- -- B o d y -- -- -- -- Copyright (C) 2020, Free Software Foundation, Inc. -- -- -- -- GNAT is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNAT was originally developed by the GNAT team at New York University. -- -- Extensive contributions were provided by Ada Core Technologies Inc. -- -- -- ------------------------------------------------------------------------------ package body Ada.Strings.Text_Output.Bit_Buckets is type Bit_Bucket_Type is new Sink with null record; overriding procedure Full_Method (S : in out Bit_Bucket_Type); overriding procedure Flush_Method (S : in out Bit_Bucket_Type); The_Bit_Bucket : aliased Bit_Bucket_Type (Chunk_Length => Default_Chunk_Length); function Bit_Bucket return Sink_Access is (The_Bit_Bucket'Access); overriding procedure Full_Method (S : in out Bit_Bucket_Type) renames Flush_Method; overriding procedure Flush_Method (S : in out Bit_Bucket_Type) is begin S.Last := 0; end Flush_Method; begin The_Bit_Bucket.Indent_Amount := 0; The_Bit_Bucket.Cur_Chunk := The_Bit_Bucket.Initial_Chunk'Access; end Ada.Strings.Text_Output.Bit_Buckets;
30,175
ada
5
Kidev/DemoAdaPhysics2D
src/adaphysics2ddemo.adb
<filename>src/adaphysics2ddemo.adb with Entities; use Entities; with Rectangles; with Worlds; with Materials; with Vectors2D; use Vectors2D; with Renderer; use Renderer; with DemoLogic; use DemoLogic; with Utils; use Utils; package body AdaPhysics2DDemo is procedure Start(This : in out Menu) is SCeiling, SFloor, SRight, SLeft : EntityClassAcc; EAir, EWater : EntityClassAcc; W1 : Worlds.World; VecZero : constant Vec2D := (0.0, 0.0); Vec1, Vec2 : Vec2D; MaxEnt : constant Natural := 32; -- max ents + envs. 0 = unlimited fps : constant Float := 30.0; dt : constant Float := 1.0 / fps; cd : constant Integer := 10; -- * dt | cooldown Cue : VisualCue; -- if true, the world will no longer update Frozen : Boolean := False; Cooldown : Integer := 0; Tick : Integer := 0; begin -- Clears the calling menu This.Free; -- Ceiling Vec1 := Vec2D'(x => 10.0, y => 0.0); Vec2 := Vec2D'(x => 220.0, y => 10.0); SCeiling := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.STATIC); -- Floor Vec1 := Vec2D'(x => 0.0, y => 310.0); Vec2 := Vec2D'(x => 240.0, y => 10.0); SFloor := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.STATIC); -- Right wall Vec1 := Vec2D'(x => 230.0, y => 0.0); Vec2 := Vec2D'(x => 10.0, y => 310.0); SRight := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.STATIC); -- Left wall Vec1 := Vec2D'(x => 0.0, y => 0.0); Vec2 := Vec2D'(x => 10.0, y => 310.0); SLeft := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.STATIC); -- Top vacuum env Vec1 := Vec2D'(x => 10.0, y => 10.0); Vec2 := Vec2D'(x => 220.0, y => 250.0); EAir := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.AIR); -- Bottom water env Vec1 := Vec2D'(x => 10.0, y => 250.0); Vec2 := Vec2D'(x => 220.0, y => 60.0); EWater := Rectangles.Create(Vec1, VecZero, VecZero, Vec2, Materials.WATER); W1.Init(dt, MaxEnt); W1.SetInvalidChecker(InvalidEnt'Access); W1.SetMaxSpeed((500.0, 500.0)); W1.AddEnvironment(EAir); W1.AddEnvironment(EWater); W1.AddEntity(SCeiling); W1.AddEntity(SFloor); W1.AddEntity(SRight); W1.AddEntity(SLeft); Clear(True); loop if Cooldown > 0 then Cooldown := Cooldown - 1; end if; if not Frozen then Tick := Tick + 1; -- update the world for one tick (dt) W1.Step(Worlds.Step_Normal); end if; -- clear buffer for next render Clear(False); -- gets the user inputs and updates the world accordingly if Inputs(W1, Frozen, Cooldown, Cue) then Cooldown := cd; -- reset cooldown end if; -- Exit when the menu quit was selected exit when Cue.X < 0; -- renders Render(W1, Cue); end loop; W1.Free; end Start; end AdaPhysics2DDemo;
30,176
ada
60
RREE/ada-util
src/sys/serialize/util-serialize-io-csv.adb
----------------------------------------------------------------------- -- util-serialize-io-csv -- CSV Serialization Driver -- Copyright (C) 2011, 2015, 2016, 2017, 2021 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Characters.Latin_1; with Ada.IO_Exceptions; with Ada.Containers; with Util.Strings; with Util.Dates.ISO8601; package body Util.Serialize.IO.CSV is -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Stream : in out Output_Stream; Separator : in Character) is begin Stream.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Enable or disable the double quotes by default for strings. -- ------------------------------ procedure Set_Quotes (Stream : in out Output_Stream; Enable : in Boolean) is begin Stream.Quote := Enable; end Set_Quotes; -- ------------------------------ -- Write the value as a CSV cell. Special characters are escaped using the CSV -- escape rules. -- ------------------------------ procedure Write_Cell (Stream : in out Output_Stream; Value : in String) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ('"'); end if; for I in Value'Range loop if Value (I) = '"' then Stream.Write (""""""); else Stream.Write (Value (I)); end if; end loop; if Stream.Quote then Stream.Write ('"'); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Integer) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; Stream.Write (Util.Strings.Image (Value)); end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Boolean) is begin if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Value then Stream.Write ("true"); else Stream.Write ("false"); end if; end Write_Cell; procedure Write_Cell (Stream : in out Output_Stream; Value : in Util.Beans.Objects.Object) is use Util.Beans.Objects; begin case Util.Beans.Objects.Get_Type (Value) is when TYPE_NULL => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Stream.Quote then Stream.Write ("""null"""); else Stream.Write ("null"); end if; when TYPE_BOOLEAN => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; if Util.Beans.Objects.To_Boolean (Value) then Stream.Write ("true"); else Stream.Write ("false"); end if; when TYPE_INTEGER => if Stream.Column > 1 then Stream.Write (Stream.Separator); end if; Stream.Column := Stream.Column + 1; -- Stream.Write ('"'); Stream.Write (Util.Beans.Objects.To_Long_Long_Integer (Value)); -- Stream.Write ('"'); when others => Stream.Write_Cell (Util.Beans.Objects.To_String (Value)); end case; end Write_Cell; -- ------------------------------ -- Start a new row. -- ------------------------------ procedure New_Row (Stream : in out Output_Stream) is begin while Stream.Column < Stream.Max_Columns loop Stream.Write (Stream.Separator); Stream.Column := Stream.Column + 1; end loop; Stream.Write (ASCII.CR); Stream.Write (ASCII.LF); Stream.Column := 1; Stream.Row := Stream.Row + 1; end New_Row; -- ----------------------- -- Write the attribute name/value pair. -- ----------------------- overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Wide_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; overriding procedure Write_Attribute (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Attribute; procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Util.Beans.Objects.Object) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; -- ----------------------- -- Write the entity value. -- ----------------------- overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Wide_Entity (Stream : in out Output_Stream; Name : in String; Value : in Wide_Wide_String) is begin null; end Write_Wide_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Boolean) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Integer) is pragma Unreferenced (Name); begin Stream.Write_Cell (Value); end Write_Entity; overriding procedure Write_Entity (Stream : in out Output_Stream; Name : in String; Value : in Ada.Calendar.Time) is begin Stream.Write_Entity (Name, Util.Dates.ISO8601.Image (Value, Util.Dates.ISO8601.SUBSECOND)); end Write_Entity; overriding procedure Write_Long_Entity (Stream : in out Output_Stream; Name : in String; Value : in Long_Long_Integer) is begin null; end Write_Long_Entity; overriding procedure Write_Enum_Entity (Stream : in out Output_Stream; Name : in String; Value : in String) is begin Stream.Write_Entity (Name, Value); end Write_Enum_Entity; -- ------------------------------ -- Write the attribute with a null value. -- ------------------------------ overriding procedure Write_Null_Attribute (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Entity (Name, ""); end Write_Null_Attribute; -- ------------------------------ -- Write an entity with a null value. -- ------------------------------ procedure Write_Null_Entity (Stream : in out Output_Stream; Name : in String) is begin Stream.Write_Null_Attribute (Name); end Write_Null_Entity; -- ------------------------------ -- Get the header name for the given column. -- If there was no header line, build a default header for the column. -- ------------------------------ function Get_Header_Name (Handler : in Parser; Column : in Column_Type) return String is use type Ada.Containers.Count_Type; Default_Header : constant String := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Result : String (1 .. 10); N, R : Natural; Pos : Positive := Result'Last; begin if Handler.Headers.Length >= Ada.Containers.Count_Type (Column) then return Handler.Headers.Element (Positive (Column)); end if; N := Natural (Column - 1); loop R := N mod 26; N := N / 26; Result (Pos) := Default_Header (R + 1); exit when N = 0; Pos := Pos - 1; end loop; return Result (Pos .. Result'Last); end Get_Header_Name; -- ------------------------------ -- Set the cell value at the given row and column. -- The default implementation finds the column header name and -- invokes <b>Write_Entity</b> with the header name and the value. -- ------------------------------ procedure Set_Cell (Handler : in out Parser; Value : in String; Row : in Row_Type; Column : in Column_Type) is use Ada.Containers; begin if Row = 0 then -- Build the headers table. declare Missing : constant Integer := Integer (Column) - Integer (Handler.Headers.Length); begin if Missing > 0 then Handler.Headers.Set_Length (Handler.Headers.Length + Count_Type (Missing)); end if; Handler.Headers.Replace_Element (Positive (Column), Value); end; else declare Name : constant String := Handler.Get_Header_Name (Column); begin -- Detect a new row. Close the current object and start a new one. if Handler.Row /= Row then if Row > 1 then Handler.Sink.Finish_Object ("", Handler); else Handler.Sink.Start_Array ("", Handler); end if; Handler.Sink.Start_Object ("", Handler); end if; Handler.Row := Row; Handler.Sink.Set_Member (Name, Util.Beans.Objects.To_Object (Value), Handler); end; end if; end Set_Cell; -- ------------------------------ -- Set the field separator. The default field separator is the comma (','). -- ------------------------------ procedure Set_Field_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Separator := Separator; end Set_Field_Separator; -- ------------------------------ -- Get the field separator. -- ------------------------------ function Get_Field_Separator (Handler : in Parser) return Character is begin return Handler.Separator; end Get_Field_Separator; -- ------------------------------ -- Set the comment separator. When a comment separator is defined, a line which starts -- with the comment separator will be ignored. The row number will not be incremented. -- ------------------------------ procedure Set_Comment_Separator (Handler : in out Parser; Separator : in Character) is begin Handler.Comment := Separator; end Set_Comment_Separator; -- ------------------------------ -- Get the comment separator. Returns ASCII.NUL if comments are not supported. -- ------------------------------ function Get_Comment_Separator (Handler : in Parser) return Character is begin return Handler.Comment; end Get_Comment_Separator; -- ------------------------------ -- Setup the CSV parser and mapper to use the default column header names. -- When activated, the first row is assumed to contain the first item to de-serialize. -- ------------------------------ procedure Set_Default_Headers (Handler : in out Parser; Mode : in Boolean := True) is begin Handler.Use_Default_Headers := Mode; end Set_Default_Headers; -- ------------------------------ -- Parse the stream using the CSV parser. -- Call <b>Set_Cell</b> for each cell that has been parsed indicating the row and -- column numbers as well as the cell value. -- ------------------------------ overriding procedure Parse (Handler : in out Parser; Stream : in out Util.Streams.Buffered.Input_Buffer_Stream'Class; Sink : in out Reader'Class) is use Ada.Strings.Unbounded; C : Character; Token : Unbounded_String; Column : Column_Type := 1; Row : Row_Type := 0; In_Quote_Token : Boolean := False; In_Escape : Boolean := False; Ignore_Row : Boolean := False; begin if Handler.Use_Default_Headers then Row := 1; end if; Handler.Headers.Clear; Handler.Sink := Sink'Unchecked_Access; loop Stream.Read (Char => C); if C = Ada.Characters.Latin_1.CR or C = Ada.Characters.Latin_1.LF then if C = Ada.Characters.Latin_1.LF then Handler.Line_Number := Handler.Line_Number + 1; end if; if not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); elsif Column > 1 or else Length (Token) > 0 then Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Row := Row + 1; Column := 1; In_Quote_Token := False; In_Escape := False; end if; else Ignore_Row := False; end if; elsif C = Handler.Separator and not Ignore_Row then if In_Quote_Token and not In_Escape then Append (Token, C); else Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Set_Unbounded_String (Token, ""); Column := Column + 1; In_Quote_Token := False; In_Escape := False; end if; elsif C = '"' and not Ignore_Row then if In_Quote_Token then In_Escape := True; elsif In_Escape then Append (Token, C); In_Escape := False; elsif Ada.Strings.Unbounded.Length (Token) = 0 then In_Quote_Token := True; else Append (Token, C); end if; elsif C = Handler.Comment and Handler.Comment /= ASCII.NUL and Column = 1 and Length (Token) = 0 then Ignore_Row := True; elsif not Ignore_Row then Append (Token, C); In_Escape := False; end if; end loop; exception when Ada.IO_Exceptions.Data_Error => Parser'Class (Handler).Set_Cell (To_String (Token), Row, Column); Handler.Sink := null; return; end Parse; -- ------------------------------ -- Get the current location (file and line) to report an error message. -- ------------------------------ overriding function Get_Location (Handler : in Parser) return String is begin return Util.Strings.Image (Handler.Line_Number); end Get_Location; end Util.Serialize.IO.CSV;
30,177
ada
65
vdh-anssi/ewok-kernel
src/syscalls/ewok-syscalls-exiting.adb
<reponame>vdh-anssi/ewok-kernel<filename>src/syscalls/ewok-syscalls-exiting.adb<gh_stars>10-100 -- -- Copyright 2018 The wookey project team <<EMAIL>> -- - <NAME> -- - <NAME> -- - <NAME> -- - <NAME> -- - <NAME> -- -- 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 ewok.tasks; use ewok.tasks; with ewok.devices_shared; use ewok.devices_shared; with ewok.dma_shared; use ewok.dma_shared; with ewok.devices; with ewok.dma; with ewok.debug; package body ewok.syscalls.exiting with spark_mode => off is package TSK renames ewok.tasks; procedure svc_exit (caller_id : in ewok.tasks_shared.t_task_id; mode : in ewok.tasks_shared.t_task_mode) is begin if mode = TASK_MODE_ISRTHREAD then #if CONFIG_SCHED_SUPPORT_FISR declare current_state : constant t_task_state := ewok.tasks.get_state (caller_id, TASK_MODE_MAINTHREAD); begin if current_state = TASK_STATE_RUNNABLE or current_state = TASK_STATE_IDLE then ewok.tasks.set_state (caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FORCED); end if; end; #end if; ewok.tasks.set_state (caller_id, TASK_MODE_ISRTHREAD, TASK_STATE_ISR_DONE); -- Main thread mode else -- FIXME: we should also clean resources (devices, DMA, IPCs, ISRs...) -- This means: -- * unlock task waiting for this task to respond to IPC, returning BUSY -- * disabling all registered interrupts (NVIC) -- * disabling all EXTIs -- * cleaning DMA registered streams & reseting them -- * deregistering devices -- * deregistering GPIOs -- * zeroing data regions -- Most of those actions should be handled by each component unregister() -- call (or equivalent) -- All waiting events of the softirq input queue for this task should also be -- cleaned (they also can be cleaned as they are treated by softirqd) ewok.tasks.set_state (caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FINISHED); end if; end svc_exit; -- Deallocate registered devices and DMA streams in order -- to avoid user ISRs (potentially faulty) triggered by -- interrupts. -- TODO: the appropriate action should be chosen at compile time -- (ie. DO_NOTHING, RESET, FREEZE...) procedure svc_panic (caller_id : in ewok.tasks_shared.t_task_id) is dev_id : ewok.devices_shared.t_device_id; ok : boolean; begin -- Release registered devices for dev_descriptor in TSK.tasks_list(caller_id).devices'range loop dev_id := TSK.tasks_list(caller_id).devices(dev_descriptor).device_id; if dev_id /= ID_DEV_UNUSED then -- Unmounting the device if TSK.is_mounted (caller_id, dev_descriptor) then TSK.unmount_device (caller_id, dev_descriptor, ok); if not ok then raise program_error; -- Should never happen end if; end if; -- Removing it from the task's list of used devices TSK.remove_device (caller_id, dev_descriptor); -- Release GPIOs, EXTIs and interrupts ewok.devices.release_device (caller_id, dev_id, ok); if not ok then raise program_error; -- Should never happen end if; end if; end loop; -- Release DMA streams for dma_descriptor in TSK.tasks_list(caller_id).dma_id'range loop if TSK.tasks_list(caller_id).dma_id(dma_descriptor) /= ID_DMA_UNUSED then ewok.dma.release_stream (caller_id, TSK.tasks_list(caller_id).dma_id(dma_descriptor), ok); if not ok then raise program_error; -- Should never happen end if; end if; end loop; -- FIXME: maybe we should also clean IPCs ? ewok.tasks.set_state (caller_id, TASK_MODE_ISRTHREAD, TASK_STATE_ISR_DONE); ewok.tasks.set_state (caller_id, TASK_MODE_MAINTHREAD, TASK_STATE_FINISHED); debug.log (debug.ALERT, ewok.tasks.tasks_list(caller_id).name & " voluntary panic!"); end svc_panic; end ewok.syscalls.exiting;
30,178
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/cb/cb3003a.ada
<gh_stars>1-10 -- CB3003A.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- CHECK THAT THE NON-SPECIFIC RAISE STATEMENT PROPAGATES THE EXCEPTION -- FOR FURTHER PROCESSING(HANDLING) IN ANOTHER HANDLER. -- *** NOTE: This test has been modified since ACVC version 1.11 to -- 9X -- *** remove incompatibilities associated with the transition -- 9X -- *** to Ada 9X. -- 9X -- *** -- 9X -- DCB 04/01/80 -- JRK 11/19/80 -- SPS 11/2/82 -- MRM 03/30/93 REMOVED NUMERIC_ERROR FOR 9X COMPATIBILITY WITH REPORT; PROCEDURE CB3003A IS USE REPORT; FLOW_COUNT : INTEGER := 0; E1,E2 : EXCEPTION; BEGIN TEST("CB3003A","CHECK THAT THE NON-SPECIFIC RAISE STATEMENT" & " PROPAGATES THE ERROR FOR FURTHER HANDLING IN ANOTHER" & " HANDLER"); ------------------------------------------------------- BEGIN BEGIN BEGIN FLOW_COUNT := FLOW_COUNT + 1; RAISE E1; FAILED("EXCEPTION NOT RAISED (CASE 1)"); EXCEPTION WHEN OTHERS => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 1; " & "INNER)"); END; EXCEPTION -- A HANDLER SPECIFIC TO THE RAISED EXCEPTION (E1). WHEN E1 => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 1; OUTER)"); WHEN OTHERS => FAILED("WRONG EXCEPTION RAISED (CASE 1)"); END; EXCEPTION WHEN E1 => FLOW_COUNT := FLOW_COUNT + 1; WHEN OTHERS => FAILED("WRONG EXCEPTION PASSED (CASE 1)"); END; ------------------------------------------------------- BEGIN BEGIN BEGIN FLOW_COUNT := FLOW_COUNT + 1; RAISE E1; FAILED("EXCEPTION NOT RAISED (CASE 2)"); EXCEPTION WHEN OTHERS => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 2; " & "INNER)"); END; EXCEPTION -- A HANDLER FOR SEVERAL EXCEPTIONS INCLUDING THE ONE RAISED. WHEN CONSTRAINT_ERROR => FAILED("WRONG EXCEPTION RAISED (CONSTRAINT_ERROR)"); WHEN E2 => FAILED("WRONG EXCEPTION RAISED (E2)"); WHEN PROGRAM_ERROR | E1 | TASKING_ERROR => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 2; OUTER)"); WHEN STORAGE_ERROR => FAILED("WRONG EXCEPTION RAISED (STORAGE_ERROR)"); WHEN OTHERS => FAILED("WRONG EXCEPTION RAISED (OTHERS)"); END; EXCEPTION WHEN E1 => FLOW_COUNT := FLOW_COUNT + 1; WHEN OTHERS => FAILED("WRONG EXCEPTION PASSED (CASE 2)"); END; ------------------------------------------------------- BEGIN BEGIN BEGIN FLOW_COUNT := FLOW_COUNT + 1; RAISE E1; FAILED("EXCEPTION NOT RAISED (CASE 3)"); EXCEPTION WHEN OTHERS => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 3; " & "INNER)"); END; EXCEPTION -- A NON-SPECIFIC HANDLER. WHEN CONSTRAINT_ERROR | E2 => FAILED("WRONG EXCEPTION RAISED " & "(CONSTRAINT_ERROR | E2)"); WHEN OTHERS => FLOW_COUNT := FLOW_COUNT + 1; RAISE; FAILED("EXCEPTION NOT RERAISED (CASE 3; OUTER)"); END; EXCEPTION WHEN E1 => FLOW_COUNT := FLOW_COUNT + 1; WHEN OTHERS => FAILED("WRONG EXCEPTION PASSED (CASE 3)"); END; ------------------------------------------------------- IF FLOW_COUNT /= 12 THEN FAILED("INCORRECT FLOW_COUNT VALUE"); END IF; RESULT; END CB3003A;
30,179
ada
15
AdaCore/training_material
courses/spark_for_ada_programmers/labs/answers/130_state_abstractions/refined/a_stack.adb
package body A_Stack with SPARK_Mode, -- The_Stack is actually refined into three constituents Refined_State => (The_Stack => (P, V, M)) is subtype Pointer_T is Integer range 0 .. Stack_Size; subtype Index_T is Pointer_T range 1 .. Pointer_T'Last; P : Pointer_T := 0; V : array (Index_T) of Item := (others => Item'First); M : Integer := 0; function Is_Empty return Boolean is (P = 0) with Refined_Global => P; function Is_Full return Boolean is (P = Stack_Size) with Refined_Global => P; function Top return Item is (V (P)) with Refined_Global => (P, V); ---------- -- Push -- ---------- procedure Push (It : in Item) with Refined_Global => (In_Out => (P, V, M)) is begin P := P + 1; V (P) := It; M := Integer'Max (P, M); end Push; --------- -- Pop -- --------- procedure Pop (It : out Item) with Refined_Global => (In_Out => P, Input => V) is begin It := V (P); P := P - 1; end Pop; function Utilization return Integer is (M) with Refined_Global => M; end A_Stack;
30,180
ada
30
jscparker/math_packages
polynomial/spline/tridiagonal_lu.ads
<reponame>jscparker/math_packages -- package Tridiagonal_LU -- -- The package implements Crout's method for LU decomposition of -- tri-diagonal matrices. Matrix A is input in the form of three -- diagonals: the central diagonal of A, indexed by 0, and the -- two side diagonals indexed by -1 and 1. -- -- The LU form of A can then be used to solve simultaneous linear -- equations of the form A * X = B. The column vector B is input -- into procedure Solve, and the solution is returned as X. generic type Real is digits <>; type Index is range <>; package Tridiagonal_LU is type Diagonal is array(Index) of Real; D : constant := 1; type DiagonalID is range -D..D; -- The lower diagonal is the -1; The upper diagonal is the +1. type Matrix is array(DiagonalID) of Diagonal; -- Row major form is appropriate for Matrix*ColumnVector -- operations, which dominate the algorithm in procedure -- Solve. -- The lower diagonal is the -1; The upper diagonal is the +1. procedure LU_Decompose (A : in out Matrix; Index_Start : in Index := Index'First; Index_Finish : in Index := Index'Last); -- In the output matrix A, the lower triangular matrix L is stored -- in the lower triangular region of A, and the upper, U, is stored -- in the upper triangular region of A. -- The diagonal of U is assumed to be entirely 1.0, hence the output -- matrix A stores the diagonal elements of L along its diagonal. -- The matrix to be decomposed is (M X M) where -- M = Index_Finish - Index'First + 1. The Matrix A will be much larger -- if Index'Last > Index_Finish, but all values of A with row or column -- greater than Index_Finish are ignored. subtype Column is Diagonal; procedure Solve (X : out Column; A : in Matrix; B : in Column; Index_Start : in Index := Index'First; Index_Finish : in Index := Index'Last); -- Solve for X in the equation A X = B. The matrix A is input -- in LU form. Its top triangular part is U, and its lower triangular -- is L, where L*U = A. The diagonal elements of A hold the diagonal -- elements of U, not L. The diagonal elements of L are assumed to -- equal 1.0. The output of LU_Decompose is in suitable form for "Solve". matrix_is_singular : exception; Epsilon : Real := 16.0 * Real'Safe_Small; Set_Zero_Valued_Pivots_To_Epsilon : constant Boolean := False; -- If set to true then the pivot is given the value -- epsilon, and no exception is raised when matrix is singular. end Tridiagonal_LU;
30,181
ada
1
charlie5/lace-alire
3-mid/opengl/source/lean/geometry/opengl-geometry-colored_textured.adb
with openGL.Shader, openGL.Buffer.general, openGL.Program, openGL.Attribute, openGL.Texture, openGL.Palette, openGL.Tasks, openGL.Errors, GL.Binding, GL.lean, GL.Pointers, System, Interfaces.C.Strings, System.storage_Elements; package body openGL.Geometry.colored_textured is use GL.lean, GL.Pointers, Interfaces; ----------- -- Globals -- vertex_Shader : aliased Shader.item; fragment_Shader : aliased Shader.item; the_Program : openGL.Program.view; white_Texture : openGL.Texture.Object; Name_1 : constant String := "Site"; Name_2 : constant String := "Color"; Name_3 : constant String := "Coords"; Attribute_1_Name : aliased C.char_array := C.to_C (Name_1); Attribute_2_Name : aliased C.char_array := C.to_C (Name_2); Attribute_3_Name : aliased C.char_array := C.to_C (Name_3); Attribute_1_Name_ptr : aliased constant C.strings.chars_ptr := C.strings.to_chars_ptr (Attribute_1_Name'Access); Attribute_2_Name_ptr : aliased constant C.strings.chars_ptr := C.strings.to_chars_ptr (Attribute_2_Name'Access); Attribute_3_Name_ptr : aliased constant C.strings.chars_ptr := C.strings.to_chars_ptr (Attribute_3_Name'Access); --------- -- Forge -- type Geometry_view is access all Geometry.colored_textured.item'Class; function new_Geometry return access Geometry.colored_textured.item'Class is use System, System.storage_Elements; use type openGL.Program.view; Self : constant Geometry_view := new Geometry.colored_textured.item; begin Tasks.check; if the_Program = null then -- Define the shaders and program. declare use Palette, Attribute.Forge; Sample : Vertex; Attribute_1 : Attribute.view; Attribute_2 : Attribute.view; Attribute_3 : Attribute.view; white_Image : constant Image := (1 .. 2 => (1 .. 2 => +White)); begin white_Texture := openGL.Texture.Forge.to_Texture (white_Image); vertex_Shader .define (Shader.Vertex, "assets/opengl/shader/colored_textured.vert"); fragment_Shader.define (Shader.Fragment, "assets/opengl/shader/colored_textured.frag"); the_Program := new openGL.Program.item; the_Program.define (vertex_Shader 'Access, fragment_Shader'Access); the_Program.enable; Attribute_1 := new_Attribute (Name => Name_1, gl_Location => the_Program.attribute_Location (Name_1), Size => 3, data_Kind => Attribute.GL_FLOAT, Stride => colored_textured.Vertex'Size / 8, Offset => 0, Normalized => False); Attribute_2 := new_Attribute (Name => Name_2, gl_Location => the_Program.attribute_Location (Name_2), Size => 4, data_Kind => Attribute.GL_UNSIGNED_BYTE, Stride => colored_textured.Vertex'Size / 8, Offset => Sample.Color.Primary.Red'Address - Sample.Site (1) 'Address, Normalized => True); Attribute_3 := new_Attribute (Name => Name_3, gl_Location => the_Program.attribute_Location (Name_3), Size => 2, data_Kind => attribute.GL_FLOAT, Stride => Colored_textured.Vertex'Size / 8, Offset => Sample.Coords.S'Address - Sample.Site (1)'Address, Normalized => False); the_Program.add (Attribute_1); the_Program.add (Attribute_2); the_Program.add (Attribute_3); glBindAttribLocation (program => the_Program.gl_Program, index => the_Program.Attribute (named => Name_1).gl_Location, name => +Attribute_1_Name_ptr); Errors.log; glBindAttribLocation (program => the_Program.gl_Program, index => the_Program.Attribute (named => Name_2).gl_Location, name => +Attribute_2_Name_ptr); Errors.log; glBindAttribLocation (program => the_Program.gl_Program, index => the_Program.Attribute (named => Name_3).gl_Location, name => +Attribute_3_Name_ptr); Errors.log; end; end if; Self.Program_is (the_Program.all'Access); return Self; end new_Geometry; ---------- -- Vertex -- function is_Transparent (Self : in Vertex_array) return Boolean is function get_Color (Index : in long_Index_t) return rgba_Color is (Self (Index).Color); function my_Transparency is new get_Transparency (any_Index_t => long_Index_t, get_Color => get_Color); begin return my_Transparency (Count => Self'Length); end is_Transparent; -------------- -- Attributes -- package openGL_Buffer_of_geometry_Vertices is new Buffer.general (base_Object => Buffer.array_Object, Index => long_Index_t, Element => Vertex, Element_Array => Vertex_array); procedure Vertices_are (Self : in out Item; Now : in Vertex_array) is use openGL_Buffer_of_geometry_Vertices.Forge; begin Self.Vertices := new openGL_Buffer_of_geometry_Vertices.Object' (to_Buffer (Now, usage => Buffer.static_Draw)); Self.is_Transparent := is_Transparent (Now); -- Set the bounds. -- declare function get_Site (Index : in long_Index_t) return Vector_3 is (Now (Index).Site); function bounding_Box is new get_Bounds (long_Index_t, get_Site); begin Self.Bounds_are (bounding_Box (count => Now'Length)); end; end Vertices_are; overriding procedure Indices_are (Self : in out Item; Now : in Indices; for_Facia : in Positive) is begin raise Error with "TODO"; end Indices_are; overriding procedure enable_Texture (Self : in Item) is use GL, GL.Binding, openGL.Texture; begin Tasks.check; glActiveTexture (gl.GL_TEXTURE0); Errors.log; if Self.Texture = openGL.Texture.null_Object then enable (white_Texture); else enable (Self.Texture); end if; end enable_Texture; end openGL.Geometry.colored_textured;
30,182
ada
9
AntonMeep/parse_args
src/parse_args-generic_discrete_options.ads
-- parse_args-generic_discrete_option.ads -- A simple command line option parser -- Copyright (c) 2015, <NAME> -- -- Permission to use, copy, modify, and/or distribute this software for any -- purpose with or without fee is hereby granted, provided that the above -- copyright notice and this permission notice appear in all copies. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -- OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. pragma Profile(No_Implementation_Extensions); with Parse_Args.Generic_Options; generic type Element is (<>); Fallback_Default : Element; with procedure Valid (Arg : in Element; Result : in out Boolean) is null; package Parse_Args.Generic_Discrete_Options is package Inner is new Parse_Args.Generic_Options(Element => Element, Fallback_Default => Fallback_Default, Value => Element'Value, Image => Element'Image, Valid => Valid); subtype Element_Option is Inner.Element_Option; function Image (O : in Element_Option) return String renames Inner.Image; function Value (O : in Element_Option) return Element renames Inner.Value; function Value(A : in Argument_Parser; Name : in String) return Element renames Inner.Value; function Make_Option(Default : in Element := Fallback_Default) return Option_Ptr renames Inner.Make_Option; end Parse_Args.Generic_Discrete_Options;
30,183
ada
192
rocher/Ada_Drivers_Library
middleware/src/BLE/bluetooth_low_energy-packets.ads
<filename>middleware/src/BLE/bluetooth_low_energy-packets.ads<gh_stars>100-1000 ------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ with System; with Interfaces; package Bluetooth_Low_Energy.Packets is type BLE_Packet is private; function Memory_Address (This : BLE_Packet) return System.Address; -- Return memory address of the radio data to be transmitted procedure Set_Header (This : in out BLE_Packet; Header : UInt8); procedure Push (This : in out BLE_Packet; Data : UInt8); procedure Push (This : in out BLE_Packet; Data : Interfaces.Integer_8); procedure Push (This : in out BLE_Packet; Data : UInt16); procedure Push (This : in out BLE_Packet; Data : UInt32); procedure Push (This : in out BLE_Packet; Data : UInt8_Array); procedure Push_UUID (This : in out BLE_Packet; UUID : BLE_UUID); private BLE_PACKET_MIC_SIZE : constant := 4; -- Size of Message integrity check (MIC) field BLE_PACKET_MAX_PAYLOAD : constant := 37; -- Maximum size of BLE payload (without header, MIC or CRC) type BLE_Data is array (1 .. BLE_PACKET_MAX_PAYLOAD + BLE_PACKET_MIC_SIZE) of UInt8 with Pack; -- BLE Payload plus optional MIC field type BLE_Packet is record Header : UInt8; Packet_Length : UInt8 := 0; Data : BLE_Data; end record with Pack; end Bluetooth_Low_Energy.Packets;
30,184
ada
2
corentingay/ada_epita
project/adl/arch/ARM/Nordic/drivers/nrf51-gpio-tasks_and_events.ads
------------------------------------------------------------------------------ -- -- -- Copyright (C) 2016, AdaCore -- -- -- -- Redistribution and use in source and binary forms, with or without -- -- modification, are permitted provided that the following conditions are -- -- met: -- -- 1. Redistributions of source code must retain the above copyright -- -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- -- notice, this list of conditions and the following disclaimer in -- -- the documentation and/or other materials provided with the -- -- distribution. -- -- 3. Neither the name of the copyright holder nor the names of its -- -- contributors may be used to endorse or promote products derived -- -- from this software without specific prior written permission. -- -- -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -- -- HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -- -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- ------------------------------------------------------------------------------ package nRF51.GPIO.Tasks_And_Events is type GPIOTE_Channel is range 0 .. 3; procedure Disable (Chan : GPIOTE_Channel); type Event_Polarity is (Rising_Edge, Falling_Edge, Any_Change); procedure Enable_Event (Chan : GPIOTE_Channel; GPIO_Pin : GPIO_Pin_Index; Polarity : Event_Polarity); -- When GPIO_Pin value changes the event associated with Chan is raised type Task_Action is (Set_Pin, Clear_Pin, Toggle_Pin); type Init_Value is (Init_Set, Init_Clear); procedure Enable_Task (Chan : GPIOTE_Channel; GPIO_Pin : GPIO_Pin_Index; Action : Task_Action; Initial_Value : Init_Value); -- When the tasks associated with Chan is triggered, Action (Set, Clear, -- Toggle) is applied to GPIO_Pin. end nRF51.GPIO.Tasks_And_Events;
30,185
ada
0
optikos/oasis
source/oasis/program-elements-simple_return_statements.ads
<filename>source/oasis/program-elements-simple_return_statements.ads -- Copyright (c) 2019 <NAME> <<EMAIL>> -- -- SPDX-License-Identifier: MIT -- License-Filename: LICENSE ------------------------------------------------------------- with Program.Elements.Statements; with Program.Lexical_Elements; with Program.Elements.Expressions; package Program.Elements.Simple_Return_Statements is pragma Pure (Program.Elements.Simple_Return_Statements); type Simple_Return_Statement is limited interface and Program.Elements.Statements.Statement; type Simple_Return_Statement_Access is access all Simple_Return_Statement'Class with Storage_Size => 0; not overriding function Expression (Self : Simple_Return_Statement) return Program.Elements.Expressions.Expression_Access is abstract; type Simple_Return_Statement_Text is limited interface; type Simple_Return_Statement_Text_Access is access all Simple_Return_Statement_Text'Class with Storage_Size => 0; not overriding function To_Simple_Return_Statement_Text (Self : aliased in out Simple_Return_Statement) return Simple_Return_Statement_Text_Access is abstract; not overriding function Return_Token (Self : Simple_Return_Statement_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; not overriding function Semicolon_Token (Self : Simple_Return_Statement_Text) return not null Program.Lexical_Elements.Lexical_Element_Access is abstract; end Program.Elements.Simple_Return_Statements;
30,186
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/testsuite/ada/acats/tests/ce/ce2401b.ada
-- CE2401B.ADA -- Grant of Unlimited Rights -- -- Under contracts F33600-87-D-0337, F33600-84-D-0280, MDA903-79-C-0687, -- F08630-91-C-0015, and DCA100-97-D-0025, the U.S. Government obtained -- unlimited rights in the software and documentation contained herein. -- Unlimited rights are defined in DFAR 252.227-7013(a)(19). By making -- this public release, the Government intends to confer upon all -- recipients unlimited rights equal to those held by the Government. -- These rights include rights to use, duplicate, release or disclose the -- released technical data and computer software in whole or in part, in -- any manner and for any purpose whatsoever, and to have or permit others -- to do so. -- -- DISCLAIMER -- -- ALL MATERIALS OR INFORMATION HEREIN RELEASED, MADE AVAILABLE OR -- DISCLOSED ARE AS IS. THE GOVERNMENT MAKES NO EXPRESS OR IMPLIED -- WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING THE CONDITIONS OF THE -- SOFTWARE, DOCUMENTATION OR OTHER INFORMATION RELEASED, MADE AVAILABLE -- OR DISCLOSED, OR THE OWNERSHIP, MERCHANTABILITY, OR FITNESS FOR A -- PARTICULAR PURPOSE OF SAID MATERIAL. --* -- OBJECTIVE: -- CHECK READ (WITH AND WITHOUT PARAMETER FROM), WRITE (WITH -- AND WITHOUT PARAMETER TO), SET_INDEX, INDEX, SIZE, AND -- END_OF_FILE FOR DIRECT FILES WITH ELEMENT_TYPES BOOLEAN, -- ACCESS, AND ENUMERATED. -- APPLICABILITY CRITERIA: -- THIS TEST IS ONLY APPLICABLE TO IMPLEMENTATIONS WHICH SUPPORT -- DIRECT FILES. -- HISTORY: -- ABW 08/18/82 -- SPS 09/15/82 -- SPS 11/09/82 -- JBG 02/22/84 CHANGE TO .ADA TEST. -- EG 05/16/85 -- TBN 11/04/86 REVISED TEST TO OUTPUT A NON_APPLICABLE -- RESULT WHEN FILES ARE NOT SUPPORTED. -- DWC 08/07/87 ISOLATED EXCEPTIONS. WITH REPORT; USE REPORT; WITH DIRECT_IO; PROCEDURE CE2401B IS END_SUBTEST : EXCEPTION; BEGIN TEST ("CE2401B", "CHECK READ, WRITE, SET_INDEX " & "INDEX, SIZE, AND END_OF_FILE FOR " & "DIRECT FILES FOR BOOLEAN, ACCESS " & "AND ENUMERATION TYPES"); DECLARE PACKAGE DIR_BOOL IS NEW DIRECT_IO (BOOLEAN); USE DIR_BOOL; FILE_BOOL : FILE_TYPE; BEGIN BEGIN CREATE (FILE_BOOL, INOUT_FILE, LEGAL_FILE_NAME); EXCEPTION WHEN USE_ERROR | NAME_ERROR => NOT_APPLICABLE ("USE_ERROR | NAME_ERROR RAISED " & "ON CREATE - BOOLEAN"); RAISE END_SUBTEST; WHEN OTHERS => FAILED ("UNEXPECTED ERROR RAISED ON " & "CREATE - BOOLEAN"); RAISE END_SUBTEST; END; DECLARE BOOL : BOOLEAN := IDENT_BOOL (TRUE); ITEM_BOOL : BOOLEAN; ONE_BOOL : POSITIVE_COUNT := 1; TWO_BOOL : POSITIVE_COUNT := 2; BEGIN BEGIN WRITE (FILE_BOOL,BOOL); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "BOOLEAN - 1"); END; BEGIN WRITE (FILE_BOOL,BOOL,TWO_BOOL); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "BOOLEAN - 2"); END; BEGIN IF SIZE (FILE_BOOL) /= TWO_BOOL THEN FAILED ("SIZE FOR TYPE BOOLEAN"); END IF; IF NOT END_OF_FILE (FILE_BOOL) THEN FAILED ("WRONG END_OF_FILE VALUE FOR " & "BOOLEAN"); END IF; SET_INDEX (FILE_BOOL,ONE_BOOL); IF INDEX (FILE_BOOL) /= ONE_BOOL THEN FAILED ("WRONG INDEX VALUE FOR TYPE BOOLEAN"); END IF; END; CLOSE (FILE_BOOL); BEGIN OPEN (FILE_BOOL, IN_FILE, LEGAL_FILE_NAME); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("OPEN FOR IN_FILE MODE " & "NOT SUPPORTED - 1"); RAISE END_SUBTEST; END; BEGIN READ (FILE_BOOL,ITEM_BOOL); IF ITEM_BOOL /= BOOL THEN FAILED ("INCORRECT BOOLEAN VALUE READ - 1"); END IF; EXCEPTION WHEN OTHERS => FAILED ("READ WITHOUT FROM FOR " & "TYPE BOOLEAN"); END; BEGIN READ (FILE_BOOL,ITEM_BOOL,ONE_BOOL); IF ITEM_BOOL /= BOOL THEN FAILED ("INCORRECT BOOLEAN VALUE READ - 2"); END IF; EXCEPTION WHEN OTHERS => FAILED ("READ WITH FROM FOR BOOLEAN"); END; END; BEGIN DELETE (FILE_BOOL); EXCEPTION WHEN USE_ERROR => NULL; END; EXCEPTION WHEN END_SUBTEST => NULL; END; DECLARE TYPE ENUMERATED IS (ONE,TWO,THREE); PACKAGE DIR_ENUM IS NEW DIRECT_IO (ENUMERATED); USE DIR_ENUM; FILE_ENUM : FILE_TYPE; BEGIN BEGIN CREATE (FILE_ENUM, INOUT_FILE, LEGAL_FILE_NAME(2)); EXCEPTION WHEN USE_ERROR | NAME_ERROR => NOT_APPLICABLE ("USE_ERROR | NAME_ERROR RAISED " & "ON CREATE - ENUMERATED"); RAISE END_SUBTEST; WHEN OTHERS => FAILED ("UNEXPECTED ERROR RAISED ON " & "CREATE - ENUMERATED"); RAISE END_SUBTEST; END; DECLARE ENUM : ENUMERATED := (THREE); ITEM_ENUM : ENUMERATED; ONE_ENUM : POSITIVE_COUNT := 1; TWO_ENUM : POSITIVE_COUNT := 2; BEGIN BEGIN WRITE (FILE_ENUM,ENUM); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "ENUMERATED - 1"); END; BEGIN WRITE (FILE_ENUM,ENUM,TWO_ENUM); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "ENUMERATED - 2"); END; BEGIN IF SIZE (FILE_ENUM) /= TWO_ENUM THEN FAILED ("SIZE FOR TYPE ENUMERATED"); END IF; IF NOT END_OF_FILE (FILE_ENUM) THEN FAILED ("WRONG END_OF_FILE VALUE FOR TYPE " & "ENUMERATED"); END IF; SET_INDEX (FILE_ENUM,ONE_ENUM); IF INDEX (FILE_ENUM) /= ONE_ENUM THEN FAILED ("WRONG INDEX VALUE FOR TYPE " & "ENUMERATED"); END IF; END; CLOSE (FILE_ENUM); BEGIN OPEN (FILE_ENUM, IN_FILE, LEGAL_FILE_NAME(2)); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("OPEN FOR IN_FILE MODE " & "NOT SUPPORTED - 2"); RAISE END_SUBTEST; END; BEGIN READ (FILE_ENUM,ITEM_ENUM); IF ITEM_ENUM /= ENUM THEN FAILED ("INCORRECT ENUM VALUE READ - 1"); END IF; EXCEPTION WHEN OTHERS => FAILED ("READ WITHOUT FROM FOR ENUMERATED"); END; BEGIN READ (FILE_ENUM,ITEM_ENUM,ONE_ENUM); IF ITEM_ENUM /= ENUM THEN FAILED ("INCORRECT ENUM VALUE READ - 2"); END IF; EXCEPTION WHEN OTHERS => FAILED ("READ WITH FROM FOR " & "TYPE ENUMERATED"); END; END; BEGIN DELETE (FILE_ENUM); EXCEPTION WHEN USE_ERROR => NULL; END; EXCEPTION WHEN END_SUBTEST => NULL; END; DECLARE TYPE ACC_INT IS ACCESS INTEGER; PACKAGE DIR_ACC IS NEW DIRECT_IO (ACC_INT); USE DIR_ACC; FILE_ACC : FILE_TYPE; BEGIN BEGIN CREATE (FILE_ACC, INOUT_FILE, LEGAL_FILE_NAME(3)); EXCEPTION WHEN USE_ERROR | NAME_ERROR => NOT_APPLICABLE ("USE_ERROR | NAME_ERROR RAISED " & "ON CREATE - ACCESS"); RAISE END_SUBTEST; END; DECLARE ACC : ACC_INT := NEW INTEGER'(33); ITEM_ACC : ACC_INT; ONE_ACC : POSITIVE_COUNT := 1; TWO_ACC : POSITIVE_COUNT := 2; BEGIN BEGIN WRITE (FILE_ACC,ACC); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "ACCESS - 1"); END; BEGIN WRITE (FILE_ACC,ACC,TWO_ACC); EXCEPTION WHEN OTHERS => FAILED ("EXCEPTION RAISED ON WRITE FOR " & "ACCESS - 2"); END; BEGIN IF SIZE (FILE_ACC) /= TWO_ACC THEN FAILED ("SIZE FOR TYPE ACCESS"); END IF; IF NOT END_OF_FILE (FILE_ACC) THEN FAILED ("WRONG END_OF_FILE VALUE FOR ACCESS"); END IF; SET_INDEX (FILE_ACC,ONE_ACC); IF INDEX (FILE_ACC) /= ONE_ACC THEN FAILED ("WRONG INDEX VALUE FOR TYPE ACCESS"); END IF; END; CLOSE (FILE_ACC); BEGIN OPEN (FILE_ACC, IN_FILE, LEGAL_FILE_NAME(3)); EXCEPTION WHEN USE_ERROR => NOT_APPLICABLE ("OPEN FOR IN_FILE NOT " & "SUPPORTED - 3"); RAISE END_SUBTEST; END; BEGIN READ (FILE_ACC,ITEM_ACC); EXCEPTION WHEN OTHERS => FAILED ("READ WITHOUT FROM FOR ACCESS"); END; BEGIN READ (FILE_ACC,ITEM_ACC,ONE_ACC); EXCEPTION WHEN OTHERS => FAILED ("READ WITH FROM FOR ACCESS"); END; END; BEGIN DELETE (FILE_ACC); EXCEPTION WHEN USE_ERROR => NULL; END; EXCEPTION WHEN END_SUBTEST => NULL; END; RESULT; END CE2401B;
30,187
ada
286
auzkok/libagar
ada/core/agar-error.adb
<filename>ada/core/agar-error.adb ------------------------------------------------------------------------------ -- AGAR CORE LIBRARY -- -- A G A R . E R R O R -- -- B o d y -- -- -- -- Copyright (c) 2018-2019, <NAME> (<EMAIL>) -- -- Copyright (c) 2010, coreland (<EMAIL>) -- -- -- -- Permission to use, copy, modify, and/or distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ package body Agar.Error is function Get_Error return String is begin return C.To_Ada (CS.Value (AG_GetError)); end; procedure Set_Error (Message : in String) is Ch_Message : aliased C.char_array := C.To_C (Message); begin AG_SetErrorS (Message => CS.To_Chars_Ptr (Ch_Message'Unchecked_Access)); end; procedure Fatal_Error (Message : in String) is Ch_Message : aliased C.char_array := C.To_C (Message); begin AG_FatalError (Message => CS.To_Chars_Ptr (Ch_Message'Unchecked_Access)); end; -- -- Proxy procedure to call error callback from C code. -- Error_Callback_Fn : Error_Callback_Access := null; procedure Error_Callback_Proxy (Message : CS.chars_ptr) with Convention => C; procedure Error_Callback_Proxy (Message : CS.chars_ptr) is begin if Error_Callback_Fn /= null then Error_Callback_Fn.all (C.To_Ada (CS.Value (Message))); end if; end; procedure Set_Fatal_Callback (Callback : Error_Callback_Access) is begin Error_Callback_Fn := Callback; AG_SetFatalCallback (Error_Callback_Proxy'Access); end; end Agar.Error;
30,188
ada
2
AdaCore/style_checker
testsuite/tests/NA17-007__Ada_units/gnat95_config/has_05.adb
<reponame>AdaCore/style_checker -- An Ada source file which is supposed to be Ada95 only, but has -- some Ada 2005 code in it. procedure Has_05 is begin -- Introduce a deliberate Ada 2005 construct to verify that -- the style_checker uses -gnat05, and that the compiler -- therefore flags this as a violation. raise Constraint_Error with "Bad Message"; end Has_05;
30,189
ada
1
TNO/Rejuvenation-Ada
workshop/src/prefix_notation.ads
package Prefix_Notation is type My_Type is tagged private; procedure Operator_Zero (X : My_Type); procedure Operator_One (X : My_Type; A : Integer); private type My_Type is tagged null record; procedure Operator_Zero (X : My_Type) is null; procedure Operator_One (X : My_Type; A : Integer) is null; end Prefix_Notation;
30,190
ada
7
best08618/asylo
gcc-gcc-7_3_0-release/gcc/ada/s-tporft.adb
<reponame>best08618/asylo<gh_stars>1-10 ------------------------------------------------------------------------------ -- -- -- GNAT RUN-TIME LIBRARY (GNARL) COMPONENTS -- -- -- -- SYSTEM.TASK_PRIMITIVES.OPERATIONS.REGISTER_FOREIGN_THREAD -- -- -- -- B o d y -- -- -- -- Copyright (C) 2002-2016, Free Software Foundation, Inc. -- -- -- -- GNARL is free software; you can redistribute it and/or modify it under -- -- terms of the GNU General Public License as published by the Free Soft- -- -- ware Foundation; either version 3, or (at your option) any later ver- -- -- sion. GNAT is distributed in the hope that it will be useful, but WITH- -- -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY -- -- or FITNESS FOR A PARTICULAR PURPOSE. -- -- -- -- As a special exception under Section 7 of GPL version 3, you are granted -- -- additional permissions described in the GCC Runtime Library Exception, -- -- version 3.1, as published by the Free Software Foundation. -- -- -- -- You should have received a copy of the GNU General Public License and -- -- a copy of the GCC Runtime Library Exception along with this program; -- -- see the files COPYING3 and COPYING.RUNTIME respectively. If not, see -- -- <http://www.gnu.org/licenses/>. -- -- -- -- GNARL was developed by the GNARL team at Florida State University. -- -- Extensive contributions were provided by Ada Core Technologies, Inc. -- -- -- ------------------------------------------------------------------------------ with System.Task_Info; -- Use for Unspecified_Task_Info with System.Soft_Links; -- used to initialize TSD for a C thread, in function Self with System.Multiprocessors; separate (System.Task_Primitives.Operations) function Register_Foreign_Thread (Thread : Thread_Id) return Task_Id is Local_ATCB : aliased Ada_Task_Control_Block (0); Self_Id : Task_Id; Succeeded : Boolean; begin -- This section is tricky. We must not call anything that might require -- an ATCB, until the new ATCB is in place. In order to get an ATCB -- immediately, we fake one, so that it is then possible to e.g allocate -- memory (which might require accessing self). -- Record this as the Task_Id for the thread Local_ATCB.Common.LL.Thread := Thread; Local_ATCB.Common.Current_Priority := System.Priority'First; Specific.Set (Local_ATCB'Unchecked_Access); -- It is now safe to use an allocator Self_Id := new Ada_Task_Control_Block (0); -- Finish initialization Lock_RTS; System.Tasking.Initialize_ATCB (Self_Id, null, Null_Address, Null_Task, Foreign_Task_Elaborated'Access, System.Priority'First, System.Multiprocessors.Not_A_Specific_CPU, null, Task_Info.Unspecified_Task_Info, 0, 0, Self_Id, Succeeded); Unlock_RTS; pragma Assert (Succeeded); Self_Id.Master_of_Task := 0; Self_Id.Master_Within := Self_Id.Master_of_Task + 1; for L in Self_Id.Entry_Calls'Range loop Self_Id.Entry_Calls (L).Self := Self_Id; Self_Id.Entry_Calls (L).Level := L; end loop; Self_Id.Common.State := Runnable; Self_Id.Awake_Count := 1; Self_Id.Common.Task_Image (1 .. 14) := "foreign thread"; Self_Id.Common.Task_Image_Len := 14; -- Since this is not an ordinary Ada task, we will start out undeferred Self_Id.Deferral_Level := 0; -- We do not provide an alternate stack for foreign threads Self_Id.Common.Task_Alternate_Stack := Null_Address; System.Soft_Links.Create_TSD (Self_Id.Common.Compiler_Data); Enter_Task (Self_Id); return Self_Id; end Register_Foreign_Thread;
30,191
ada
1
faelys/natools-web
src/natools-web-simple_pages.adb
------------------------------------------------------------------------------ -- Copyright (c) 2014-2019, <NAME> -- -- -- -- Permission to use, copy, modify, and distribute this software for any -- -- purpose with or without fee is hereby granted, provided that the above -- -- copyright notice and this permission notice appear in all copies. -- -- -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -- -- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -- -- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -- -- ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -- -- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -- -- ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -- -- OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. -- ------------------------------------------------------------------------------ with Natools.S_Expressions.Atom_Ref_Constructors; with Natools.S_Expressions.Enumeration_IO; with Natools.S_Expressions.File_Readers; with Natools.S_Expressions.Interpreter_Loop; with Natools.S_Expressions.Templates.Dates; with Natools.Static_Maps.Web.Simple_Pages; with Natools.Web.Error_Pages; with Natools.Web.Exchanges; with Natools.Web.Fallback_Render; package body Natools.Web.Simple_Pages is package Template_Components is type Enum is (Unknown, Comment_List, Comment_Path_Prefix, Comment_Path_Suffix, Comments, Elements); package IO is new Natools.S_Expressions.Enumeration_IO.Typed_IO (Enum); end Template_Components; Expiration_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!expire"); Publication_Date_Key : constant S_Expressions.Atom := S_Expressions.To_Atom ("!publish"); procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom); function Comment_Path_Override (Template : in Page_Template; Override : in S_Expressions.Lockable.Descriptor'Class) return S_Expressions.Atom_Refs.Immutable_Reference; procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Set_Component (Object : in out Page_Template; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class); procedure Read_Page is new S_Expressions.Interpreter_Loop (Page_Data, Page_Template, Execute); procedure Render_Page is new S_Expressions.Interpreter_Loop (Sites.Exchange, Page_Data, Render, Append); procedure Update_Template is new S_Expressions.Interpreter_Loop (Page_Template, Meaningless_Type, Set_Component); --------------------------- -- Page Data Constructor -- --------------------------- procedure Execute (Data : in out Page_Data; Context : in Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is package Components renames Natools.Static_Maps.Web.Simple_Pages; begin case Components.To_Component (S_Expressions.To_String (Name)) is when Components.Error => Log (Severities.Error, "Unknown page component """ & S_Expressions.To_String (Name) & '"'); when Components.Comment_List => if Context.Comments.Is_Empty then Data.Comment_List.Set (Arguments); else declare Template : S_Expressions.Caches.Cursor := Context.Comments.Value; begin Data.Comment_List.Set (Template, Arguments, Comment_Path_Override (Context, Arguments)); end; end if; when Components.Dates => Containers.Set_Dates (Data.Dates, Arguments); when Components.Elements => Containers.Add_Expressions (Data.Elements, Arguments); when Components.Maps => Data.Maps := String_Tables.Create (Arguments); when Components.Tags => Tags.Append (Data.Tags, Arguments); end case; end Execute; ------------------- -- Page Renderer -- ------------------- procedure Append (Exchange : in out Sites.Exchange; Page : in Page_Data; Data : in S_Expressions.Atom) is pragma Unreferenced (Page); begin Exchange.Append (Data); end Append; procedure Render (Exchange : in out Sites.Exchange; Page : in Page_Data; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is use type S_Expressions.Events.Event; procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class); procedure Render_Date (Log_Error : in Boolean); procedure Re_Enter (Exchange : in out Sites.Exchange; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Page); end Re_Enter; procedure Render_Date (Log_Error : in Boolean) is begin if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Cursor : constant Containers.Date_Maps.Cursor := Page.Dates.Find (Arguments.Current_Atom); begin if not Containers.Date_Maps.Has_Element (Cursor) then if Log_Error then Log (Severities.Error, "Unable to find date """ & S_Expressions.To_String (Arguments.Current_Atom) & """ in page date map"); end if; return; end if; Arguments.Next; declare Item : constant Containers.Date := Containers.Date_Maps.Element (Cursor); begin S_Expressions.Templates.Dates.Render (Exchange, Arguments, Item.Time, Item.Offset); end; end; end if; end Render_Date; package Commands renames Natools.Static_Maps.Web.Simple_Pages; begin case Commands.To_Command (S_Expressions.To_String (Name)) is when Commands.Unknown_Command => Fallback_Render (Exchange, Name, Arguments, "simple page", Re_Enter'Access, Page.Elements); when Commands.Comment_List => Comments.Render (Exchange, Page.Comment_List, Arguments); when Commands.Date => Render_Date (True); when Commands.My_Tags => if Arguments.Current_Event = S_Expressions.Events.Add_Atom then declare Prefix : constant S_Expressions.Atom := Arguments.Current_Atom; begin Arguments.Next; Tags.Render (Exchange, Page.Tags, Exchange.Site.Get_Tags, Prefix, Arguments); end; end if; when Commands.If_No_Date => if Arguments.Current_Event = S_Expressions.Events.Add_Atom and then not Page.Dates.Contains (Arguments.Current_Atom) then Arguments.Next; Render_Page (Arguments, Exchange, Page); end if; when Commands.Maps => String_Tables.Render (Exchange, Page.Maps, Arguments); when Commands.Optional_Date => Render_Date (False); when Commands.Path => Exchange.Append (Page.Web_Path.Query); when Commands.Tags => Tags.Render (Exchange, Exchange.Site.Get_Tags, Arguments, Page.Tags); end case; end Render; ------------------------- -- Page_Data Interface -- ------------------------- not overriding procedure Get_Element (Data : in Page_Data; Name : in S_Expressions.Atom; Element : out S_Expressions.Caches.Cursor; Found : out Boolean) is Cursor : constant Containers.Expression_Maps.Cursor := Data.Elements.Find (Name); begin Found := Containers.Expression_Maps.Has_Element (Cursor); if Found then Element := Containers.Expression_Maps.Element (Cursor); end if; end Get_Element; ----------------------------- -- Page_Template Interface -- ----------------------------- function Comment_Path_Override (Template : in Page_Template; Override : in S_Expressions.Lockable.Descriptor'Class) return S_Expressions.Atom_Refs.Immutable_Reference is use type S_Expressions.Atom; use type S_Expressions.Events.Event; Name_Override : constant Boolean := Override.Current_Event = S_Expressions.Events.Add_Atom; Name : constant S_Expressions.Atom := (if Name_Override then Override.Current_Atom elsif not Template.Name.Is_Empty then Template.Name.Query else S_Expressions.Null_Atom); begin if Template.Comment_Path_Prefix.Is_Empty or else (not Name_Override and then Template.Name.Is_Empty) then return S_Expressions.Atom_Refs.Null_Immutable_Reference; else return S_Expressions.Atom_Ref_Constructors.Create (Template.Comment_Path_Prefix.Query & Name & (if Template.Comment_Path_Suffix.Is_Empty then S_Expressions.Null_Atom else Template.Comment_Path_Suffix.Query)); end if; end Comment_Path_Override; procedure Set_Comments (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Object.Comments := (Is_Empty => False, Value => S_Expressions.Caches.Conditional_Move (Expression)); end Set_Comments; procedure Set_Comment_Path_Prefix (Object : in out Page_Template; Prefix : in S_Expressions.Atom) is begin if Prefix'Length > 0 then Object.Comment_Path_Prefix := S_Expressions.Atom_Ref_Constructors.Create (Prefix); else Object.Comment_Path_Prefix.Reset; end if; end Set_Comment_Path_Prefix; procedure Set_Comment_Path_Suffix (Object : in out Page_Template; Suffix : in S_Expressions.Atom) is begin if Suffix'Length > 0 then Object.Comment_Path_Suffix := S_Expressions.Atom_Ref_Constructors.Create (Suffix); else Object.Comment_Path_Suffix.Reset; end if; end Set_Comment_Path_Suffix; procedure Set_Component (Object : in out Page_Template; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class; Known_Component : out Boolean) is use type S_Expressions.Events.Event; begin Known_Component := True; case Template_Components.IO.Value (Name, Template_Components.Unknown) is when Template_Components.Unknown => Known_Component := False; when Template_Components.Comment_List | Template_Components.Comments => Set_Comments (Object, Arguments); when Template_Components.Comment_Path_Prefix => Set_Comment_Path_Prefix (Object, (if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Arguments.Current_Atom else S_Expressions.Null_Atom)); when Template_Components.Comment_Path_Suffix => Set_Comment_Path_Suffix (Object, (if Arguments.Current_Event = S_Expressions.Events.Add_Atom then Arguments.Current_Atom else S_Expressions.Null_Atom)); when Template_Components.Elements => Set_Elements (Object, Arguments); end case; end Set_Component; procedure Set_Component (Object : in out Page_Template; Context : in Meaningless_Type; Name : in S_Expressions.Atom; Arguments : in out S_Expressions.Lockable.Descriptor'Class) is pragma Unreferenced (Context); Known_Component : Boolean; begin Set_Component (Object, Name, Arguments, Known_Component); if not Known_Component then Log (Severities.Error, "Unknown simple page template component """ & S_Expressions.To_String (Name) & '"'); end if; end Set_Component; procedure Set_Elements (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Containers.Set_Expressions (Object.Elements, Expression); end Set_Elements; procedure Update (Object : in out Page_Template; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Update_Template (Expression, Object, Meaningless_Value); end Update; ---------------------- -- Public Interface -- ---------------------- function Create (Expression : in out S_Expressions.Lockable.Descriptor'Class; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data; Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Page.Self := Tags.Visible_Access (Page); Page.Elements := Template.Elements; Read_Page (Expression, Page.all, Actual_Template); return Result; end Create; function Create (File_Path, Web_Path : in S_Expressions.Atom_Refs.Immutable_Reference; Template : in Page_Template := Default_Template; Name : in S_Expressions.Atom := S_Expressions.Null_Atom) return Page_Ref is Page : constant Data_Refs.Data_Access := new Page_Data' (File_Path => File_Path, Web_Path => Web_Path, Elements => Template.Elements, Tags => <>, Self => null, Comment_List | Dates | Maps => <>); Result : constant Page_Ref := (Ref => Data_Refs.Create (Page)); Actual_Template : Page_Template := Template; begin Page.Self := Tags.Visible_Access (Page); Actual_Template.Name := (if Name'Length > 0 then S_Expressions.Atom_Ref_Constructors.Create (Name) else S_Expressions.Atom_Refs.Null_Immutable_Reference); Create_Page : declare Reader : Natools.S_Expressions.File_Readers.S_Reader := Natools.S_Expressions.File_Readers.Reader (S_Expressions.To_String (File_Path.Query)); begin Read_Page (Reader, Page.all, Actual_Template); end Create_Page; return Result; end Create; procedure Get_Lifetime (Page : in Page_Ref; Publication : out Ada.Calendar.Time; Has_Publication : out Boolean; Expiration : out Ada.Calendar.Time; Has_Expiration : out Boolean) is Accessor : constant Data_Refs.Accessor := Page.Ref.Query; Cursor : Containers.Date_Maps.Cursor; begin Cursor := Accessor.Dates.Find (Expiration_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Expiration := True; Expiration := Containers.Date_Maps.Element (Cursor).Time; else Has_Expiration := False; end if; Cursor := Accessor.Dates.Find (Publication_Date_Key); if Containers.Date_Maps.Has_Element (Cursor) then Has_Publication := True; Publication := Containers.Date_Maps.Element (Cursor).Time; else Has_Publication := False; end if; end Get_Lifetime; procedure Register (Page : in Page_Ref; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is begin Time_Check : declare use type Ada.Calendar.Time; Now : constant Ada.Calendar.Time := Ada.Calendar.Clock; Publication : Ada.Calendar.Time; Has_Publication : Boolean; Expiration : Ada.Calendar.Time; Has_Expiration : Boolean; begin Get_Lifetime (Page, Publication, Has_Publication, Expiration, Has_Expiration); if Has_Publication and then Publication >= Now then Sites.Expire_At (Builder, Publication); return; end if; if Has_Expiration then if Expiration < Now then return; else Sites.Expire_At (Builder, Expiration); end if; end if; end Time_Check; if Path'Length > 0 then Sites.Insert (Builder, Path, Page); end if; Sites.Insert (Builder, Page.Get_Tags, Page); Load_Comments : declare Mutator : constant Data_Refs.Mutator := Page.Ref.Update; begin Mutator.Comment_List.Load (Builder, Mutator.Self, Mutator.Web_Path); end Load_Comments; end Register; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Ref; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object.Ref.Query.Data.all); end Render; overriding procedure Render (Exchange : in out Sites.Exchange; Object : in Page_Data; Expression : in out S_Expressions.Lockable.Descriptor'Class) is begin Render_Page (Expression, Exchange, Object); end Render; overriding procedure Respond (Object : in out Page_Ref; Exchange : in out Sites.Exchange; Extra_Path : in S_Expressions.Atom) is use type S_Expressions.Offset; begin if Extra_Path'Length = 9 and then S_Expressions.To_String (Extra_Path) = "/comments" then Object.Ref.Update.Comment_List.Respond (Exchange, Extra_Path (Extra_Path'First + 9 .. Extra_Path'Last)); return; end if; if Extra_Path'Length > 0 then return; end if; declare Accessor : constant Data_Refs.Accessor := Object.Ref.Query; Expression : S_Expressions.Caches.Cursor; begin Check_Method : declare use Exchanges; Allowed : Boolean; begin Error_Pages.Check_Method (Exchange, (GET, HEAD), Allowed); if not Allowed then return; end if; end Check_Method; Expression := Exchange.Site.Get_Template (Accessor.Data.Elements, Expression, Exchange.Site.Default_Template, Lookup_Element => True, Lookup_Template => True, Lookup_Name => True); Render_Page (Expression, Exchange, Accessor.Data.all); end; end Respond; ----------------------- -- Page Constructors -- ----------------------- function Create (File : in S_Expressions.Atom) return Sites.Page_Loader'Class is begin return Loader'(File_Path => S_Expressions.Atom_Ref_Constructors.Create (File)); end Create; overriding procedure Load (Object : in out Loader; Builder : in out Sites.Site_Builder; Path : in S_Expressions.Atom) is Page : constant Page_Ref := Create (Object.File_Path, S_Expressions.Atom_Ref_Constructors.Create (Path)); begin Register (Page, Builder, Path); end Load; procedure Register_Loader (Site : in out Sites.Site) is begin Site.Register ("simple-page", Create'Access); end Register_Loader; end Natools.Web.Simple_Pages;
30,192
ada
33
ytomino/drake
source/image/required/s-widllu.ads
pragma License (Unrestricted); -- implementation unit required by compiler with System.Unsigned_Types; package System.Wid_LLU is pragma Pure; -- required for Modular'Width by compiler (s-widllu.ads) function Width_Long_Long_Unsigned ( Lo, Hi : Unsigned_Types.Long_Long_Unsigned) return Natural; end System.Wid_LLU;
30,193
ada
0
eyeonechi/invalid-behaviour-conservative-analysis
src/instruction.adb
with Debug; use Debug; with Ada.Numerics.Discrete_Random; with Ada.Characters.Latin_1; use Ada.Characters.Latin_1; package body Instruction is package Random_OpCode is new Ada.Numerics.Discrete_Random (OpCode); package Random_Reg is new Ada.Numerics.Discrete_Random (Reg); package Random_Offset is new Ada.Numerics.Discrete_Random (Offset); OpCodeG : Random_OpCode.Generator; RegG : Random_Reg.Generator; OffsetG : Random_Offset.Generator; procedure Init is begin Random_OpCode.Reset(OpcodeG); Random_Reg.Reset(RegG); Random_Offset.Reset(OffsetG); end Init; procedure GenerateRandomInstr(Inst : out Instr) is Op : OpCode := Random_OpCode.Random(OpCodeG); R1 : Reg := Random_Reg.Random(RegG); R2 : Reg := Random_Reg.Random(RegG); R3 : Reg := Random_Reg.Random(RegG); Offs : Offset := Random_Offset.Random(OffsetG); begin case Op is when ADD => Inst := (Op => ADD, AddRd => R1, AddRs1 => R2, AddRs2 => R3); return; when SUB => Inst := (Op => SUB, SubRd => R1, SubRs1 => R2, SubRs2 => R3); return; when MUL => Inst := (Op => MUL, MulRd => R1, MulRs1 => R2, MulRs2 => R3); return; when DIV => Inst := (Op => DIV, DivRd => R1, DivRs1 => R2, DivRs2 => R3); return; when RET => Inst := (Op => RET, RetRs => R1); return; when LDR => Inst := (Op => LDR, LdrRd => R1, LdrRs => R2, LdrOffs => Offs); return; when STR => Inst := (Op => STR, StrRa => R1, StrOffs => Offs, StrRb => R2); return; when MOV => Inst := (Op => MOV, MovRd => R1, MovOffs => Offs); return; when JMP => Inst := (Op => JMP, JmpOffs => Offs); return; when JZ => Inst := (Op => JZ, JzRa => R1, JzOffs => Offs); return; when NOP => Inst := (OP => NOP); end case; end GenerateRandomInstr; procedure PutReg(R : in Reg) is begin Put("R"); Put(Item => Integer(R)); end PutReg; procedure PutOffset(Offs : in Offset) is begin Put(Item => Integer(Offs)); end PutOffset; procedure DebugPrintInstr(Inst : in Instr) with SPARK_Mode is begin Put(Instruction.OpCode'Image(Inst.Op)); case Inst.Op is when ADD => Put(HT); PutReg(Inst.AddRd); Put(HT); PutReg(Inst.AddRs1); Put(HT); PutReg(Inst.AddRs2); return; when SUB => Put(HT); PutReg(Inst.SubRd); Put(HT); PutReg(Inst.SubRs1); Put(HT); PutReg(Inst.SubRs2); return; when MUL => Put(HT); PutReg(Inst.MulRd); Put(HT); PutReg(Inst.MulRs1); Put(HT); PutReg(Inst.MulRs2); return; when DIV => Put(HT); PutReg(Inst.DivRd); Put(HT); PutReg(Inst.DivRs1); Put(HT); PutReg(Inst.DivRs2); return; when RET => Put(HT); PutReg(Inst.RetRs); return; when LDR => Put(HT); PutReg(Inst.LdrRd); Put(HT); PutReg(Inst.LdrRs); Put(HT); PutOffset(Inst.LdrOffs); return; when STR => Put(HT); PutReg(Inst.StrRa); Put(HT); PutOffset(Inst.StrOffs); Put(HT); PutReg(Inst.StrRb); return; when MOV => Put(HT); PutReg(Inst.MovRd); Put(HT); PutOffset(Inst.MovOffs); return; when JMP => Put(HT); PutOffset(Inst.JmpOffs); return; when JZ => Put(HT); PutReg(Inst.JzRa); Put(HT); PutOffset(Inst.JzOffs); return; when NOP => return; end case; end DebugPrintInstr; end Instruction;
30,194
ada
1
stcarrez/helios
src/linux/helios-monitor-ifnet.ads
----------------------------------------------------------------------- -- helios-monitor-ifnet -- Linux network interface monitor -- Copyright (C) 2017 <NAME> -- Written by <NAME> (<EMAIL>) -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. ----------------------------------------------------------------------- package Helios.Monitor.Ifnet is type Stat_Type is (RX_BYTES, RX_PACKETS, RX_ERRS, RX_DROP, RX_FIFO, RX_FRAME, RX_COMPRESS, RX_MULTICAST, TX_BYTES, TX_PACKETS, TX_ERRS, TX_DROP, TX_FIFO, TX_COLLS, TX_CARRIER, TX_COMPRESSED); type Stat_Definition_Array is array (Stat_Type) of Schemas.Definition_Type_Access; type Interface_Definition_Type is new Schemas.Definition_Type with record Stats : Stat_Definition_Array; end record; type Interface_Definition_Type_Access is access all Interface_Definition_Type'Class; type Agent_Type is new Helios.Monitor.Agent_Type with null record; -- Start the agent and build the definition tree. overriding procedure Start (Agent : in out Agent_Type; Config : in Util.Properties.Manager); -- Collect the values in the snapshot. overriding procedure Collect (Agent : in out Agent_Type; Values : in out Datas.Snapshot_Type); -- Make a new interface definition for the given interface name. procedure Make_Interface (Agent : in out Agent_Type; Name : in String; Interfaces : in String; Filter : in String); end Helios.Monitor.Ifnet;
30,195
ada
13
c-jullien/lelisp
GELL/Cbenchmarks/ben.adb
:r -float 32 -symbol 4 -string 5 -cons 24 -heap 512
30,196
ada
10
LionelDraghi/smk
src/smk-files-put.adb
<reponame>LionelDraghi/smk<filename>src/smk-files-put.adb -- ----------------------------------------------------------------------------- -- smk, the smart make (http://lionel.draghi.free.fr/smk/) -- © 2018, 2019 <NAME> <<EMAIL>> -- SPDX-License-Identifier: APSL-2.0 -- ----------------------------------------------------------------------------- -- 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 Smk.Settings; -- ----------------------------------------------------------------------------- procedure Smk.Files.Put (File_List : File_Lists.Map; Prefix : String := ""; Print_Sources : Boolean := False; Print_Targets : Boolean := False; Print_Unused : Boolean := False) is use File_Lists; use Smk.Settings; begin for F in File_List.Iterate loop if not (Settings.Filter_Sytem_Files and Is_System (File_List (F))) then if (Print_Sources and then Is_Source (File_List (F))) or else (Print_Targets and then Is_Target (File_List (F))) or else (Print_Unused and then Is_Unused (File_List (F))) then Put_File_Description (Name => Key (F), File => File_List (F), Prefix => Prefix); end if; end if; end loop; end Smk.Files.Put;
30,197
ada
0
balintsoos/LearnAda
gyak/gyak6/B1/duplication.ads
generic type Elem is private; type Index is (<>); type Tomb is array (Index range <>) of Elem; function Duplication (T: in out Tomb) return Boolean;
30,198
ada
18
kraileth/ravenadm
src/signals.ads
-- This file is covered by the Internet Software Consortium (ISC) License -- Reference: ../License.txt package Signals is -- Returns True if Interrupt signal (control-C) has been detected function graceful_shutdown_requested return Boolean; -- Enable exception handlers to initiate a shutdown upon detecting an issue procedure initiate_shutdown; private control_q_break : Boolean := False; end Signals;
30,199
ada
12
jquorning/ada-asf
src/asf-components-widgets-panels.adb
<reponame>jquorning/ada-asf<filename>src/asf-components-widgets-panels.adb<gh_stars>10-100 ----------------------------------------------------------------------- -- components-widgets-panels -- Collapsible panels -- Copyright (C) 2013, 2017 <NAME> -- Written by <NAME> (<EMAIL>) -- -- 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.Beans.Objects; with ASF.Components.Base; package body ASF.Components.Widgets.Panels is procedure Render_Action_Icon (Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Name : in String); procedure Render_Action_Icon (Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Name : in String) is begin Writer.Start_Element ("a"); Writer.Write_Attribute ("href", "#"); Writer.Write_Attribute ("class", "ui-panel-icon ui-corner-all ui-state-default"); Writer.Start_Element ("span"); Writer.Write_Attribute ("class", Name); Writer.End_Element ("span"); Writer.End_Element ("a"); end Render_Action_Icon; -- ------------------------------ -- Render the panel header. -- ------------------------------ procedure Render_Header (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Header : Util.Beans.Objects.Object; Header_Facet : ASF.Components.Base.UIComponent_Access; Closable : constant Boolean := UI.Get_Attribute (CLOSABLE_ATTR_NAME, Context); Toggleable : constant Boolean := UI.Get_Attribute (TOGGLEABLE_ATTR_NAME, Context); begin Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-header ui-widget-header"); Header := UI.Get_Attribute (Name => HEADER_ATTR_NAME, Context => Context); if not Util.Beans.Objects.Is_Empty (Header) then Writer.Start_Element ("span"); Writer.Write_Text (Header); Writer.End_Element ("span"); end if; -- If there is a header facet, render it now. Header_Facet := UI.Get_Facet (HEADER_FACET_NAME); if Header_Facet /= null then Header_Facet.Encode_All (Context); end if; if Closable then Render_Action_Icon (Writer, "ui-icon ui-icon-closethick"); end if; if Toggleable then Render_Action_Icon (Writer, "ui-icon ui-icon-minusthick"); end if; Writer.End_Element ("div"); -- Write the javascript to support the close and toggle actions. if Closable or Toggleable then Writer.Queue_Script ("$(""#"); Writer.Queue_Script (UI.Get_Client_Id); Writer.Queue_Script (""").panel();"); end if; end Render_Header; -- ------------------------------ -- Render the panel footer. -- ------------------------------ procedure Render_Footer (UI : in UIPanel; Writer : in out ASF.Contexts.Writer.Response_Writer'Class; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is use type ASF.Components.Base.UIComponent_Access; Footer : Util.Beans.Objects.Object; Footer_Facet : ASF.Components.Base.UIComponent_Access; Has_Footer : Boolean; begin Footer_Facet := UI.Get_Facet (FOOTER_FACET_NAME); Footer := UI.Get_Attribute (Name => FOOTER_ATTR_NAME, Context => Context); Has_Footer := Footer_Facet /= null or else not Util.Beans.Objects.Is_Empty (Footer); if Has_Footer then Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-footer ui-widget-footer"); end if; if not Util.Beans.Objects.Is_Empty (Footer) then Writer.Write_Text (Footer); end if; -- If there is a footer facet, render it now. if Footer_Facet /= null then Footer_Facet.Encode_All (Context); end if; if Has_Footer then Writer.End_Element ("div"); end if; end Render_Footer; -- ------------------------------ -- Render the panel header and prepare for the panel content. -- ------------------------------ overriding procedure Encode_Begin (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.Start_Element ("div"); Writer.Write_Attribute ("id", UI.Get_Client_Id); declare use Util.Beans.Objects; Style : constant Object := UI.Get_Attribute (Context, "style"); Class : constant Object := UI.Get_Attribute (Context, "styleClass"); begin if not Util.Beans.Objects.Is_Null (Class) then Writer.Write_Attribute ("class", To_String (Class) & " ui-panel ui-widget ui-corner-all"); else Writer.Write_Attribute ("class", "ui-panel ui-widget ui-corner-all"); end if; if not Is_Null (Style) then Writer.Write_Attribute ("style", Style); end if; end; UIPanel'Class (UI).Render_Header (Writer.all, Context); Writer.Start_Element ("div"); Writer.Write_Attribute ("class", "ui-panel-content ui-widget-content"); end if; end Encode_Begin; -- ------------------------------ -- Render the panel footer. -- ------------------------------ overriding procedure Encode_End (UI : in UIPanel; Context : in out ASF.Contexts.Faces.Faces_Context'Class) is Writer : constant Contexts.Writer.Response_Writer_Access := Context.Get_Response_Writer; begin if UI.Is_Rendered (Context) then Writer.End_Element ("div"); UIPanel'Class (UI).Render_Footer (Writer.all, Context); Writer.End_Element ("div"); end if; end Encode_End; end ASF.Components.Widgets.Panels;