18. GNAT language extensions

The GNAT compiler implements a certain number of language extensions on top of the latest Ada standard, implementing its own extended superset of Ada.

There are two sets of language extensions:

  • The first is the curated set. The features in that set are features that we consider being worthy additions to the Ada language, and that we want to make available to users early on.

  • The second is the experimental set. It includes the first, but also experimental features, which are considered experimental because they’re still in an early prototyping phase. These features might be removed or heavily modified at any time.

18.1. How to activate the extended GNAT Ada superset

There are two ways to activate the extended GNAT Ada superset:

pragma Extensions_Allowed (On)

As a configuration pragma, you can either put it at the beginning of a source file, or in a .adc file corresponding to your project.

  • The -gnatX command-line option will activate the curated subset of extensions.

Attention

You can activate the experimental set of extensions in addition by using either the -gnatX0 command-line option, or the pragma Extensions_Allowed with All_Extensions as an argument. However, it is not recommended you use this subset for serious projects; it is only meant as a technology preview for use in playground experiments.

18.2. Curated Extensions

Features activated via -gnatX or pragma Extensions_Allowed (On).

18.2.1. Local Declarations Without Block

A basic_declarative_item may appear at the place of any statement. This avoids the heavy syntax of block_statements just to declare something locally.

The only valid kinds of declarations for now are object_declaration, object_renaming_declaration, use_package_clause, and use_type_clause.

For example:

if X > 5 then
   X := X + 1;

   Squared : constant Integer := X**2;

   X := X + Squared;
end if;

It is generally a good practice to declare local variables (or constants) with as short a lifetime as possible. However, introducing a declare block to accomplish this is a relatively heavy syntactic load along with a traditional extra level of indentation. The alternative syntax supported here allows declarations in any statement sequence. The lifetime of such local declarations is until the end of the enclosing construct. The same enclosing construct cannot contain several declarations of the same defining name; however, overriding symbols from higher-level scopes works similarly to the explicit declare block.

If the enclosing construct allows an exception handler (such as an accept statement, begin-except-end block or a subprogram body), declarations that appear at the place of a statement are not visible within the handler. Only declarations that precede the beginning of the construct with an exception handler would be visible in this handler.

Attention

Here are a couple of examples illustrating the scoping rules described above.

  1. Those declarations are not visible from the potential exception handler:

    begin
       A : Integer
       ...
    exception
       when others =>
           Put_Line (A'Image) --  ILLEGAL
    end;
    
  2. The following is legal

    declare
       A : Integer := 10;
    begin
       A : Integer := 12;
    end;
    

    because it is roughly expanded into

      declare
         A : Integer := 10;
      begin
         declare
            A : Integer := 12;
         begin
            ...
         end;
      end;
    
    And as such the second ``A`` declaration is hiding the first one.
    

18.2.2. Deep delta Aggregates

Ada 2022’s delta aggregates are extended to allow deep updates.

A delta aggregate may be used to specify new values for subcomponents of the copied base value, instead of only new values for direct components of the copied base value. This allows a more compact expression of updated values with a single delta aggregate, instead of multiple nested delta aggregates.

The syntax of delta aggregates in the extended version is the following:

18.2.2.1. Syntax

delta_aggregate ::= record_delta_aggregate | array_delta_aggregate

record_delta_aggregate ::=
  ( base_expression with delta record_subcomponent_association_list )

record_subcomponent_association_list ::=
  record_subcomponent_association {, record_subcomponent_association}

record_subcomponent_association ::=
  record_subcomponent_choice_list => expression

record_subcomponent_choice_list ::=
  record_subcomponent_choice {'|' record_subcomponent_choice}

record_subcomponent_choice ::=
    component_selector_name
  | record_subcomponent_choice (expression)
  | record_subcomponent_choice . component_selector_name

array_delta_aggregate ::=
    ( base_expression with delta array_component_association_list )
  | '[' base_expression with delta array_component_association_list ']'
  | ( base_expression with delta array_subcomponent_association_list )
  | '[' base_expression with delta array_subcomponent_association_list ']'

array_subcomponent_association_list ::=
  array_subcomponent_association {, array_subcomponent_association}

array_subcomponent_association ::=
  array_subcomponent_choice_list => expression

array_subcomponent_choice_list ::=
  array_subcomponent_choice {'|' array_subcomponent_choice}

array_subcomponent_choice ::=
    ( expression )
  | array_subcomponent_choice (expression)
  | array_subcomponent_choice . component_selector_name

18.2.2.2. Legality Rules

  1. For an array_delta_aggregate, the discrete_choice shall not be others.

  2. For an array_delta_aggregate, the dimensionality of the type of the delta_aggregate shall be 1.

  3. For an array_delta_aggregate, the base_expression and each expression in every array_component_association or array_subcomponent_association shall be of a nonlimited type.

  4. For a record_delta_aggregate, no record_subcomponent_choices that consists of only component_selector_names shall be the same or a prefix of another record_subcomponent_choice.

  5. For an array_subcomponent_choice or a record_subcomponent_choice the component_selector_name shall not be a subcomponent that depends on discriminants of an unconstrained record subtype with defaulted discriminants unless its prefix consists of only component_selector_names.

    [Rationale: As a result of this rule, accessing the subcomponent can only lead to a discriminant check failure if the subcomponent was not present in the object denoted by the base_expression, prior to any update.]

18.2.2.3. Dynamic Semantics

The evaluation of a delta_aggregate begins with the evaluation of the base_expression of the delta_aggregate; then that value is used to create and initialize the anonymous object of the aggregate. The bounds of the anonymous object of an array_delta_aggregate and the discriminants (if any) of the anonymous object of a record_delta_aggregate are those of the base_expression.

If a record_delta_aggregate is of a specific tagged type, its tag is that of the specific type; if it is of a class-wide type, its tag is that of the base_expression.

For a delta_aggregate, for each discrete_choice or each subcomponent associated with a record_subcomponent_associated, array_component_association or array_subcomponent_association (in the order given in the enclosing discrete_choice_list or subcomponent_association_list, respectively):

  • if the associated subcomponent belongs to a variant, a check is made that the values of the governing discriminants are such that the anonymous object has this component. The exception Constraint_Error is raised if this check fails.

  • if the associated subcomponent is a subcomponent of an array, then for each represented index value (in ascending order, if the discrete_choice represents a range):

    • the index value is converted to the index type of the array type.

    • a check is made that the index value belongs to the index range of the corresponding array part of the anonymous object; Constraint_Error is raised if this check fails.

    • the expression of the record_subcomponent_association, array_component_association or array_subcomponent_association is evaluated, converted to the nominal subtype of the associated subcomponent, and assigned to the corresponding subcomponent of the anonymous object.

18.2.2.4. Examples

 1declare
 2   type Point is record
 3      X, Y : Integer;
 4   end record;
 5
 6   type Segment is array (1 .. 2) of Point;
 7   type Triangle is array (1 .. 3) of Segment;
 8
 9   S : Segment := (1 .. 2 => (0, 0));
10   T : Triangle := (1 .. 3 => (1 .. 2 => (0, 0)));
11begin
12   S := (S with delta (1).X => 11, (2).Y => 12, (1).Y => 15);
13
14   pragma Assert (S (1).X = 11);
15   pragma Assert (S (2).Y = 12);
16   pragma Assert (S (1).Y = 15);
17
18   T := (T with delta (2)(1).Y => 18);
19   pragma Assert (T (2)(1).Y = 18);
20end;

18.2.3. Fixed lower bounds for array types and subtypes

Unconstrained array types and subtypes can be specified with a lower bound that is fixed to a certain value, by writing an index range that uses the syntax <lower-bound-expression> .. <>. This guarantees that all objects of the type or subtype will have the specified lower bound.

For example, a matrix type with fixed lower bounds of zero for each dimension can be declared by the following:

type Matrix is
  array (Natural range 0 .. <>, Natural range 0 .. <>) of Integer;

Objects of type Matrix declared with an index constraint must have index ranges starting at zero:

M1 : Matrix (0 .. 9, 0 .. 19);
M2 : Matrix (2 .. 11, 3 .. 22);  -- Warning about bounds; will raise CE

Similarly, a subtype of String can be declared that specifies the lower bound of objects of that subtype to be 1:

subtype String_1 is String (1 .. <>);

If a string slice is passed to a formal of subtype String_1 in a call to a subprogram S, the slice’s bounds will “slide” so that the lower bound is 1.

Within S, the lower bound of the formal is known to be 1, so, unlike a normal unconstrained String formal, there is no need to worry about accounting for other possible lower-bound values. Sliding of bounds also occurs in other contexts, such as for object declarations with an unconstrained subtype with fixed lower bound, as well as in subtype conversions.

Use of this feature increases safety by simplifying code, and can also improve the efficiency of indexing operations, since the compiler statically knows the lower bound of unconstrained array formals when the formal’s subtype has index ranges with static fixed lower bounds.

18.2.4. Prefixed-view notation for calls to primitive subprograms of untagged types

When operating on an untagged type, if it has any primitive operations, and the first parameter of an operation is of the type (or is an access parameter with an anonymous type that designates the type), you may invoke these operations using an object.op(...) notation, where the parameter that would normally be the first parameter is brought out front, and the remaining parameters (if any) appear within parentheses after the name of the primitive operation.

This same notation is already available for tagged types. This extension allows for untagged types. It is allowed for all primitive operations of the type independent of whether they were originally declared in a package spec, or were inherited and/or overridden as part of a derived type declaration occurring anywhere, so long as the first parameter is of the type, or an access parameter designating the type.

For example:

generic
   type Elem_Type is private;
package Vectors is
    type Vector is private;
    procedure Add_Element (V : in out Vector; Elem : Elem_Type);
    function Nth_Element (V : Vector; N : Positive) return Elem_Type;
    function Length (V : Vector) return Natural;
private
    function Capacity (V : Vector) return Natural;
       --  Return number of elements that may be added without causing
       --  any new allocation of space

    type Vector is ...
      with Type_Invariant => Vector.Length <= Vector.Capacity;
    ...
end Vectors;

package Int_Vecs is new Vectors(Integer);

V : Int_Vecs.Vector;
...
V.Add_Element(42);
V.Add_Element(-33);

pragma Assert (V.Length = 2);
pragma Assert (V.Nth_Element(1) = 42);

18.2.5. Expression defaults for generic formal functions

The declaration of a generic formal function is allowed to specify an expression as a default, using the syntax of an expression function.

Here is an example of this feature:

generic
   type T is private;
   with function Copy (Item : T) return T is (Item); -- Defaults to Item
package Stacks is

   type Stack is limited private;

   procedure Push (S : in out Stack; X : T); -- Calls Copy on X
   function Pop (S : in out Stack) return T; -- Calls Copy to return item

private
   -- ...
end Stacks;

If Stacks is instantiated with an explicit actual for Copy, then that will be called when Copy is called in the generic body. If the default is used (i.e. there is no actual corresponding to Copy), then calls to Copy in the instance will simply return Item.

18.2.6. String interpolation

The syntax for string literals is extended to support string interpolation. An interpolated string literal starts with f, immediately before the first double-quote character.

Within an interpolated string literal, an arbitrary expression, when enclosed in { ... }, is expanded at run time into the result of calling 'Image on the result of evaluating the expression enclosed by the brace characters, unless it is already a string or a single character.

Here is an example of this feature where the expressions Name and X + Y will be evaluated and included in the string.

procedure Test_Interpolation is
   X    : Integer := 12;
   Y    : Integer := 15;
   Name : String := "Leo";
begin
   Put_Line (f"The name is {Name} and the sum is {X + Y}.");
end Test_Interpolation;

This will print:

The name is Leo and the sum is 27.

In addition, an escape character (\) is provided for inserting certain standard control characters (such as \t for tabulation or \n for newline) or to escape characters with special significance to the interpolated string syntax, namely ", {, },and \ itself.

escaped_character

meaning

\a

ALERT

\b

BACKSPACE

\f

FORM FEED

\n

LINE FEED

\r

CARRIAGE RETURN

\t

CHARACTER TABULATION

\v

LINE TABULATION

\0

NUL

\\

\

\"

"

\{

{

\}

}

Note that, unlike normal string literals, doubled double-quote characters have no special significance. So to include a double-quote or a brace character in an interpolated string, they must be preceded by a \. Multiple interpolated strings are concatenated. For example:

Put_Line
  (f"X = {X} and Y = {Y} and X+Y = {X+Y};\n" &
   f" a double quote is \" and" &
   f" an open brace is \{");

This will print:

X = 12 and Y = 15 and X+Y = 27
a double quote is " and an open brace is {

18.2.7. Constrained attribute for generic objects

The Constrained attribute is permitted for objects of generic types. The result indicates whether the corresponding actual is constrained.

18.2.8. Static aspect on intrinsic functions

The Ada 202x Static aspect can be specified on Intrinsic imported functions and the compiler will evaluate some of these intrinsics statically, in particular the Shift_Left and Shift_Right intrinsics.

18.2.9. First Controlling Parameter

A new pragma/aspect, First_Controlling_Parameter, is introduced for tagged types, altering the semantics of primitive/controlling parameters. When a tagged type is marked with this aspect, only subprograms where the first parameter is of that type will be considered dispatching primitives. This pragma/aspect applies to the entire hierarchy, starting from the specified type, without affecting inherited primitives.

Here is an example of this feature:

package Example is
   type Root is tagged private;

   procedure P (V : Integer; V2 : Root);
   -- Primitive

   type Child is tagged private
     with First_Controlling_Parameter;

private
   type Root is tagged null record;
   type Child is new Root with null record;

   overriding
   procedure P (V : Integer; V2 : Child);
   -- Primitive

   procedure P2 (V : Integer; V2 : Child);
   -- NOT Primitive

   function F return Child; -- NOT Primitive

   function F2 (V : Child) return Child;
   -- Primitive, but only controlling on the first parameter
end Example;

Note that function F2 (V : Child) return Child; differs from F2 (V : Child) return Child'Class; in that the return type is a specific, definite type. This is also distinct from the legacy semantics, where further derivations with added fields would require overriding the function.

The option -gnatw_j, that you can pass to the compiler directly, enables warnings related to this new language feature. For instance, compiling the example above without this switch produces no warnings, but compiling it with -gnatw_j generates the following warning on the declaration of procedure P2:

warning: not a dispatching primitive of tagged type "Child"
warning: disallowed by First_Controlling_Parameter on "Child"

For generic formal tagged types, you can specify whether the type has the First_Controlling_Parameter aspect enabled:

generic
   type T is tagged private with First_Controlling_Parameter;
package T is
    type U is new T with null record;
    function Foo return U; -- Not a primitive
end T;

For tagged partial views, the value of the aspect must be consistent between the partial and full views:

package R is
   type T is tagged private;
...
private
   type T is tagged null record with First_Controlling_Parameter; -- ILLEGAL
end R;

Restricting the position of controlling parameter offers several advantages:

  • Simplification of the dispatching rules improves readability of Ada programs. One doesn’t need to analyze all subprogram parameters to understand if the given subprogram is a primitive of a certain tagged type.

  • A programmer is free to use any type, including class-wide types, on other parameters of a subprogram, without the need to consider possible effects of overriding a primitive or creating new one.

  • The result of a function is never a controlling result.

18.2.10. Unsigned_Base_Range aspect

A new pragma/aspect, Unsigned_Base_Range, is introduced to explicitly enforce the use of an unsigned base type for signed integer types. RM-3.5.4(9) mandates a symmetric base range for signed integer types. This requirement often requires the use of larger data types for arithmetic operations, potentially introducing undesirable run-time overhead and performance penalties, particularly in embedded systems. For instance, on a 64-bit architecture, a 64-bit multiplication can be performed with a single hardware instruction, whereas a 128-bit multiplication requires multiple instructions and intermediate steps.

Here is an example of this feature:

type Uns_64 is range 0 .. 2 ** 64 - 1
  with Size => 64,
       Unsigned_Base_Range => True;

It ensures that arithmetic operations of type Uns_64 are carried out using 64 bits.

18.2.11. Generalized Finalization

The Finalizable aspect can be applied to any record type, tagged or not, to specify that it provides the same level of control on the operations of initialization, finalization, and assignment of objects as the controlled types (see RM 7.6(2) for a high-level overview). The only restriction is that the record type must be a root type, in other words not a derived type.

The aspect additionally makes it possible to specify relaxed semantics for the finalization operations by means of the Relaxed_Finalization setting. Here is the archetypal example:

type T is record
  ...
end record
  with Finalizable => (Initialize           => Initialize,
                       Adjust               => Adjust,
                       Finalize             => Finalize,
                       Relaxed_Finalization => True);

procedure Adjust     (Obj : in out T);
procedure Finalize   (Obj : in out T);
procedure Initialize (Obj : in out T);

The three procedures must be primitive operations of T and have a single in out parameter. They need not be all specified by the aspect. If they are specified, they have the same dynamic semantics as for controlled types:

  • Initialize is called when an object of type T is declared without initialization expression.

  • Adjust is called after an object of type T is assigned a new value.

  • Finalize is called when an object of type T goes out of scope (for stack-allocated objects) or is deallocated (for heap-allocated objects). It is also called when the value is replaced by an assignment.

However, when Relaxed_Finalization is either True or not explicitly specified, the following differences are implemented relative to the semantics of controlled types:

  • The compiler has permission to perform no automatic finalization of heap-allocated objects: Finalize is only called when such an object is explicitly deallocated, or when the designated object is assigned a new value. As a consequence, no runtime support is needed for performing implicit deallocation. In particular, no per-object header data is needed for heap-allocated objects.

    Heap-allocated objects allocated through a nested access type will therefore not be deallocated either. The result is simply that memory will be leaked in this case.

  • The Adjust and Finalize procedures are automatically considered as having the No_Raise aspect specified for them. In particular, the compiler has permission to enforce none of the guarantees specified by the RM 7.6.1 (14/1) and subsequent subclauses.

Simple example of ref-counted type:

type T is record
   Value     : Integer;
   Ref_Count : Natural := 0;
end record;

procedure Inc_Ref (X : in out T);
procedure Dec_Ref (X : in out T);

type T_Access is access all T;

type T_Ref is record
   Value : T_Access;
end record
   with Finalizable => (Adjust   => Adjust,
                        Finalize => Finalize);

procedure Adjust (Ref : in out T_Ref) is
begin
   Inc_Ref (Ref.Value);
end Adjust;

procedure Finalize (Ref : in out T_Ref) is
begin
   Def_Ref (Ref.Value);
end Finalize;

Simple file handle that ensures resources are properly released:

package P is
   type File (<>) is limited private;

   function Open (Path : String) return File;

   procedure Close (F : in out File);

private
   type File is limited record
      Handle : ...;
   end record
      with Finalizable (Finalize => Close);
end P;

18.2.11.1. Finalizable tagged types

The aspect is inherited by derived types and the primitives may be overridden by the derivation. The compiler-generated calls to these operations are then dispatching whenever it makes sense, i.e. when the object in question is of a class-wide type and the class includes at least one finalizable tagged type.

18.2.11.2. Composite types

When a finalizable type is used as a component of a composite type, the latter becomes finalizable as well. The three primitives are derived automatically in order to call the primitives of their components. The dynamic semantics is the same as for controlled components of composite types.

18.2.11.3. Interoperability with controlled types

Finalizable types are fully interoperable with controlled types, in particular it is possible for a finalizable type to have a controlled component and vice versa, but the stricter dynamic semantics, in other words that of controlled types, is applied in this case.

18.3. Experimental Language Extensions

Features activated via -gnatX0 or pragma Extensions_Allowed (All_Extensions).

18.3.1. Conditional when constructs

This feature extends the use of when as a way to condition a control-flow related statement, to all control-flow related statements.

To do a conditional return in a procedure the following syntax should be used:

procedure P (Condition : Boolean) is
begin
   return when Condition;
end P;

This will return from the procedure if Condition is true.

When being used in a function the conditional part comes after the return value:

function Is_Null (I : Integer) return Boolean is
begin
   return True when I = 0;
   return False;
end;

In a similar way to the exit when a goto ... when can be employed:

procedure Low_Level_Optimized is
   Flags : Bitmapping;
begin
   Do_1 (Flags);
   goto Cleanup when Flags (1);

   Do_2 (Flags);
   goto Cleanup when Flags (32);

   --  ...

<<Cleanup>>
   --  ...
end;

To use a conditional raise construct:

procedure Foo is
begin
   raise Error when Imported_C_Func /= 0;
end;

An exception message can also be added:

procedure Foo is
begin
   raise Error with "Unix Error"
     when Imported_C_Func /= 0;
end;

18.3.2. Implicit With

This feature allows a standalone use clause in the context clause of a compilation unit to imply an implicit with of the same library unit where an equivalent with clause would be allowed.

use Ada.Text_IO;
procedure Main is
begin
   Put_Line ("Hello");
end;

18.3.3. Storage Model

This extends Storage Pools into a more efficient model allowing higher performance, easier integration with low footprint embedded run-times and copying data between different pools of memory. The latter is especially useful when working with distributed memory models, in particular to support interactions with GPU.

18.3.3.1. Aspect Storage_Model_Type

A Storage model is a type with a specified Storage_Model_Type aspect, e.g.:

type A_Model is null record
   with Storage_Model_Type (...);

Storage_Model_Type itself accepts six parameters:

  • Address_Type, the type of the address managed by this model. This has to be a scalar type or derived from System.Address.

  • Allocate, a procedure used for allocating memory in this model

  • Deallocate, a procedure used for deallocating memory in this model

  • Copy_To, a procedure used to copy memory from native memory to this model

  • Copy_From, a procedure used to copy memory from this model to native memory

  • Storage_Size, a function returning the amount of memory left

  • Null_Address, a value for the null address value

By default, Address_Type is System.Address, and the five subprograms perform native operations (e.g. the allocator is the native new allocator). Users can decide to specify one or more of these. When an Address_Type is specified to be other than System.Address, all of the subprograms have to be specified.

The prototypes of these procedures are as follows:

procedure Allocate
  (Model           : in out A_Model;
   Storage_Address : out Address_Type;
   Size            : Storage_Count;
   Alignment       : Storage_Count);

procedure Deallocate
  (Model           : in out A_Model;
   Storage_Address : out Address_Type;
   Size            : Storage_Count;
   Alignment       : Storage_Count);

procedure Copy_To
  (Model   : in out A_Model;
   Target  : Address_Type;
   Source  : System.Address;
   Size    : Storage_Count);

procedure Copy_From
  (Model  : in out A_Model;
   Target : System.Address;
   Source : Address_Type;
   Size   : Storage_Count);

function Storage_Size
  (Pool : A_Model)
   return Storage_Count;

Here’s an example of how this could be instantiated in the context of CUDA:

package CUDA_Memory is

   type CUDA_Storage_Model is null record
      with Storage_Model_Type => (
         Address_Type => CUDA_Address,
         Allocate     => CUDA_Allocate,
         Deallocate   => CUDA_Deallocate,
         Copy_To      => CUDA_Copy_To,
         Copy_From    => CUDA_Copy_From,
         Storage_Size => CUDA_Storage_Size,
         Null_Address => CUDA_Null_Address
      );

   type CUDA_Address is new System.Address;
   --  We're assuming for now same address size on host and device

   procedure CUDA_Allocate
     (Model           : in out CUDA_Storage_Model;
      Storage_Address : out CUDA_Address;
      Size            : Storage_Count;
      Alignment       : Storage_Count);

   procedure CUDA_Deallocate
     (Model           : in out CUDA_Storage_Model;
      Storage_Address : out CUDA_Address;
      Size            : Storage_Count;
      Alignment       : Storage_Count);

   procedure CUDA_Copy_To
     (Model  : in out CUDA_Storage_Model;
      Target : CUDA_Address;
      Source : System.Address;
      Size   : Storage_Count);

   procedure CUDA_Copy_From
     (Model   : in out CUDA_Storage_Model;
      Target  : System.Address;
      Source  : CUDA_Address;
      Size    : Storage_Count);

   function CUDA_Storage_Size
     (Pool : CUDA_Storage_Model)
      return Storage_Count return Storage_Count'Last;

   CUDA_Null_Address : constant CUDA_Address :=
      CUDA_Address (System.Null_Address);

   CUDA_Memory : CUDA_Storage_Model;

end CUDA_Memory;

18.3.3.2. Aspect Designated_Storage_Model

A new aspect, Designated_Storage_Model, allows to specify the memory model for the objects pointed by an access type. Under this aspect, allocations and deallocations will come from the specified memory model instead of the standard ones. In addition, if write operations are needed for initialization, or if there is a copy of the target object from and to a standard memory area, the Copy_To and Copy_From functions will be called. It allows to encompass the capabilities of storage pools, e.g.:

procedure Main is
   type Integer_Array is array (Integer range <>) of Integer;

   type Host_Array_Access is access all Integer_Array;
   type Device_Array_Access is access Integer_Array
      with Designated_Storage_Model => CUDA_Memory;

   procedure Free is new Unchecked_Deallocation
      (Host_Array_Type, Host_Array_Access);
   procedure Free is new Unchecked_Deallocation
      (Device_Array_Type, Device_Array_Access);

   Host_Array : Host_Array_Access := new Integer_Array (1 .. 10);

   Device_Array : Device_Array_Access := new Host_Array (1 .. 10);
   --  Calls CUDA_Storage_Model.Allocate to allocate the fat pointers and
   --  the bounds, then CUDA_Storage_Model.Copy_In to copy the values of the
   --  boundaries.
begin
   Host_Array.all := (others => 0);

   Device_Array.all := Host_Array.all;
   --  Calls CUDA_Storage_Model.Copy_To to write to the device array from the
   --  native memory.

   Host_Array.all := Device_Array.all;
   --  Calls CUDA_Storage_Model.Copy_From to read from the device array and
   --  write to native memory.

   Free (Host_Array);

   Free (Device_Array);
   --  Calls CUDA_Storage_Model.Deallocate;
end;

Taking 'Address of an object with a specific memory model returns an object of the type of the address for that memory category, which may be different from System.Address.

When copying is performed between two specific memory models, the native memory is used as a temporary between the two. E.g.:

type Foo_I is access Integer with Designated_Storage_Model => Foo;
type Bar_I is access Integer with Designated_Storage_Model => Bar;

  X : Foo_I := new Integer;
  Y : Bar_I := new Integer;
begin
  X.all := Y.all;

conceptually becomes:

  X : Foo_I := new Integer;
  T : Integer;
  Y : Bar_I := new Integer;
begin
  T := Y.all;
  X.all := T;

18.3.3.3. Legacy Storage Pools

Legacy Storage Pools are now replaced by a Storage_Model_Type. They are implemented as follows:

type Root_Storage_Pool is abstract
  new Ada.Finalization.Limited_Controlled with private
with Storage_Model_Type => (
   Allocate     => Allocate,
   Deallocate   => Deallocate,
   Storage_Size => Storage_Size
);
pragma Preelaborable_Initialization (Root_Storage_Pool);

procedure Allocate
  (Pool                     : in out Root_Storage_Pool;
   Storage_Address          : out System.Address;
   Size_In_Storage_Elements : System.Storage_Elements.Storage_Count;
   Alignment                : System.Storage_Elements.Storage_Count)
is abstract;

procedure Deallocate
  (Pool                     : in out Root_Storage_Pool;
   Storage_Address          : System.Address;
   Size_In_Storage_Elements : System.Storage_Elements.Storage_Count;
   Alignment                : System.Storage_Elements.Storage_Count)
is abstract;

function Storage_Size
  (Pool : Root_Storage_Pool)
   return System.Storage_Elements.Storage_Count
is abstract;

The legacy notation:

type My_Pools is new Root_Storage_Pool with record [...]

My_Pool_Instance : Storage_Model_Pool.Storage_Model :=
   My_Pools'(others => <>);

type Acc is access Integer_Array with Storage_Pool => My_Pool;

can still be accepted as a shortcut for the new syntax.

18.3.4. Attribute Super

The Super attribute can be applied to objects of tagged types in order to obtain a view conversion to the most immediate specific parent type.

It cannot be applied to objects of types without any ancestors.

type T1 is tagged null record;
procedure P (V : T1);

type T2 is new T1 with null record;

type T3 is new T2 with null record;
procedure P (V : T3);

procedure Call (
  V1 : T1'Class;
  V2 : T2'Class;
  V3 : T3'Class) is
begin
  V1'Super.P; --  Illegal call as T1 doesn't have any ancestors
  V2'Super.P; --  Equivalent to "T1 (V).P;", a nondispatching call
              --  to T1's primitive procedure P.
  V3'Super.P; --  Equivalent to "T2 (V).P;"; Since T2 doesn't
              --  override P, a nondispatching call to T1.P is
              --  executed.
end;

18.3.5. Simpler Accessibility Model

The goal of this feature is to simplify the accessibility rules by removing dynamic accessibility checks that are often difficult to understand and debug. The new rules eliminate the need for runtime accessibility checks by imposing more conservative legality rules when enabled via a new restriction (see RM 13.12), No_Dynamic_Accessibility_Checks, which prevents dangling reference problems at compile time.

This restriction has no effect on the user-visible behavior of a program when executed; the only effect of this restriction is to enable additional compile-time checks (described below) which ensure statically that Ada’s dynamic accessibility checks will not fail.

The feature can be activated with pragma Restrictions (No_Dynamic_Accessibility_Checks);. As a result, additional compile-time checks are performed; these checks pertain to stand-alone objects, subprogram parameters, and function results as described below.

The restriction may not be used in a unit compiled in pedantic Flare mode; see the description of the restriction in the GNAT Reference Manual.

All of the refined rules are compatible with the [use of anonymous access types in SPARK] (http://docs.adacore.com/spark2014-docs/html/lrm/declarations-and-types.html#access-types).

18.3.5.1. Stand-alone objects

Var        : access T := ...
Var_To_Cst : access constant T := ...
Cst        : constant access T := ...
Cst_To_Cst : constant access constant T := ...

In this section, we will refer to a stand-alone object of an anonymous access type as an SO.

When the restriction is in effect, the “statically deeper” relationship (see RM 3.10.2(4)) does apply to the type of a SO (contrary to RM 3.10.2(19.2)) and, for the purposes of compile-time checks, the accessibility level of the type of a SO is the accessibility level of that SO. This supports many common use-cases without the employment of Unchecked_Access while still removing the need for dynamic checks.

This statically disallows cases that would otherwise require a dynamic accessibility check, such as

type Ref is access all Integer;
Ptr : Ref;
Good : aliased Integer;

procedure Proc is
   Bad : aliased Integer;
   Stand_Alone : access Integer;
begin
   if <some condition> then
      Stand_Alone := Good'Access;
   else
      Stand_Alone := Bad'Access;
   end if;
   Ptr := Ref (Stand_Alone);
end Proc;

If a No_Dynamic_Accessibility_Checks restriction is in effect, then the otherwise-legal type conversion (the right-hand side of the assignment to Ptr) becomes a violation of the RM 4.6 rule “The accessibility level of the operand type shall not be statically deeper than that of the target type …”.

18.3.5.2. Subprogram parameters

procedure P (V : access T; X : access constant T);

In most cases (the exceptions are described below), a No_Dynamic_Accessibility_Checks restriction means that the “statically deeper” relationship does apply to the anonymous type of an access parameter specifying an access-to-object type (contrary to RM 3.10.2(19.1)) and, for purposes of compile-time “statically deeper” checks, the accessibility level of the type of such a parameter is the accessibility level of the parameter.

This change (at least as described so far) doesn’t affect the caller’s side, but on the callee’s side it means that object designated by a non-null parameter of an anonymous access type is treated as having the same accessibility level as a local object declared immediately within the called subprogram.

With the restriction in effect, the otherwise-legal type conversion in the following example becomes illegal:

type Ref is access all Integer;
Ptr : Ref;

procedure Proc (Param : access Integer) is
begin
   Ptr := Ref (Param);
end Proc;

The aforementioned exceptions have to do with return statements from functions that either return the given parameter (in the case of a function whose result type is an anonymous access type) or return the given parameter value as an access discriminant of the function result (or of some discriminated part thereof). More specifically, the “statically deeper” changes described above do not apply for purposes of checking the “shall not be statically deeper” rule for access discriminant parts of function results (RM 6.5(5.9)) or in determining the legality of an (implicit) type conversion from the anonymous access type of a parameter of a function to an anonymous access result type of that function. In order to prevent these rule relaxations from introducing the possibility of dynamic accessibility check failures, compensating compile-time checks are performed at the call site to prevent cases where including the value of an access parameter as part of a function result could make such check failures possible (specifically, the discriminant checks of RM 6.5(21) or, in the case of an anonymous access result type, the RM 4.6(48) check performed when converting to that result type). These compile-time checks are described in the next section.

From the callee’s perspective, the level of anonymous access formal parameters would be between the level of the subprogram and the level of the subprogram’s locals. This has the effect of formal parameters being treated as local to the callee except in:

  • Use as a function result

  • Use as a value for an access discriminant in result object

  • Use as an assignments between formal parameters

Note that with these more restricted rules we lose track of accessibility levels when assigned to local objects thus making (in the example below) the assignment to Node2.Link from Temp below compile-time illegal.

type Node is record
   Data : Integer;
   Link : access Node;
end record;

procedure Swap_Links (Node1, Node2 : in out Node) is
   Temp : constant access Node := Node1.Link; -- We lose the "association" to Node1
begin
   Node1.Link := Node2.Link; -- Allowed
   Node2.Link := Temp;       -- Not allowed
end;

function Identity (N : access Node) return access Node is
   Local : constant access Node := N;
begin
   if True then
      return N;              -- Allowed
   else
      return Local;          -- Not allowed
   end if;
end;

18.3.5.3. Function results

function Get (X : Rec) return access T;

If the result subtype of a function is either an anonymous access (sub)type, a class-wide (sub)type, an unconstrained subtype with an access discriminant, or a type with an unconstrained subcomponent subtype that has at least one access discriminant (this last case is only possible if the access discriminant has a default value), then we say that the function result type “might require an anonymous-access-part accessibility check”. If a function has an access parameter, or a parameter whose subtype “might require an anonymous-access-part accessibility check”, then we say that the each such parameter “might be used to pass in an anonymous-access value”. If the first of these conditions holds for the result subtype of a function and the second condition holds for at least one parameter that function, then it is possible that a call to that function could return a result that contains anonymous-access values that were passed in via the parameter.

Given a function call where the result type “might require an anonymous-access-part accessibility check” and a formal parameter of that function that “might be used to pass in an anonymous-access value”, either the type of that formal parameter is an anonymous access type or it is not. If it is, and if a No_Dynamic_Access_Checks restriction is in effect, then the accessibility level of the type of the actual parameter shall be statically known to not be deeper than that of the master of the call. If it isn’t, then the accessibility level of the actual parameter shall be statically known to not be deeper than that of the master of the call.

Function result example:

declare
   type T is record
      Comp : aliased Integer;
   end record;

   function Identity (Param : access Integer) return access Integer is
   begin
      return Param;        -- Legal
   end;

   function Identity_2 (Param : aliased Integer) return access Integer is
   begin
      return Param'Access; -- Legal
   end;

   X : access Integer;
begin
   X := Identity (X);      -- Legal
   declare
      Y : access Integer;
      Z : aliased Integer;
   begin
      X := Identity (Y);   -- Illegal since Y is too deep
      X := Identity_2 (Z); -- Illegal since Z is too deep
   end;
end;

In order to avoid having to expand the definition of “might be used to pass in an anonymous-access value” to include any parameter of a tagged type, the No_Dynamic_Access_Checks restriction also imposes a requirement that a type extension cannot include the explicit definition of an access discriminant.

Here is an example of one such case of an upward conversion which would lead to a memory leak:

declare
   type T is tagged null record;
   type T2 (Disc : access Integer) is new T with null record; -- Must be illegal

   function Identity (Param : aliased T'Class) return access Integer is
   begin
      return T2 (T'Class (Param)).Disc; -- Here P gets effectively returned and set to X
   end;

   X : access Integer;
begin
   declare
      P : aliased Integer;
      Y : T2 (P'Access);
   begin
      X := Identity (T'Class (Y)); -- Pass local variable P (via Y's discriminant),
                                 -- leading to a memory leak.
   end;
end;
```

Thus we need to make the following illegal to avoid such situations:

```ada
package Pkg1 is
   type T1 is tagged null record;
   function Func (X1 : T1) return access Integer is (null);
end;

package Pkg2 is
   type T2 (Ptr1, Ptr2 : access Integer) is new Pkg1.T1 with null record; -- Illegal
   ...
end;

In order to prevent upward conversions of anonymous function results (like below), we also would need to assure that the level of such a result (from the callee’s perspective) is statically deeper:

declare
   type Ref is access all Integer;
   Ptr : Ref;
   function Foo (Param : access Integer) return access Integer is
   begin
      return Result : access Integer := Param; do
         Ptr := Ref (Result); -- Not allowed
      end return;
   end;
begin
   declare
      Local : aliased Integer;
   begin
      Foo (Local'Access).all := 123;
   end;
end;

18.3.6. Case pattern matching

The selector for a case statement (but not for a case expression) may be of a composite type, subject to some restrictions (described below). Aggregate syntax is used for choices of such a case statement; however, in cases where a “normal” aggregate would require a discrete value, a discrete subtype may be used instead; box notation can also be used to match all values.

Consider this example:

type Rec is record
   F1, F2 : Integer;
end record;

procedure Caser_1 (X : Rec) is
begin
   case X is
      when (F1 => Positive, F2 => Positive) =>
         Do_This;
      when (F1 => Natural, F2 => <>) | (F1 => <>, F2 => Natural) =>
         Do_That;
      when others =>
          Do_The_Other_Thing;
   end case;
end Caser_1;

If Caser_1 is called and both components of X are positive, then Do_This will be called; otherwise, if either component is nonnegative then Do_That will be called; otherwise, Do_The_Other_Thing will be called.

In addition, pattern bindings are supported. This is a mechanism for binding a name to a component of a matching value for use within an alternative of a case statement. For a component association that occurs within a case choice, the expression may be followed by is <identifier>. In the special case of a “box” component association, the identifier may instead be provided within the box. Either of these indicates that the given identifier denotes (a constant view of) the matching subcomponent of the case selector.

Attention

Binding is not yet supported for arrays or subcomponents thereof.

Consider this example (which uses type Rec from the previous example):

procedure Caser_2 (X : Rec) is
begin
   case X is
      when (F1 => Positive is Abc, F2 => Positive) =>
         Do_This (Abc)
      when (F1 => Natural is N1, F2 => <N2>) |
           (F1 => <N2>, F2 => Natural is N1) =>
         Do_That (Param_1 => N1, Param_2 => N2);
      when others =>
         Do_The_Other_Thing;
   end case;
end Caser_2;

This example is the same as the previous one with respect to determining whether Do_This, Do_That, or Do_The_Other_Thing will be called. But for this version, Do_This takes a parameter and Do_That takes two parameters. If Do_This is called, the actual parameter in the call will be X.F1.

If Do_That is called, the situation is more complex because there are two choices for that alternative. If Do_That is called because the first choice matched (i.e., because X.F1 is nonnegative and either X.F1 or X.F2 is zero or negative), then the actual parameters of the call will be (in order) X.F1 and X.F2. If Do_That is called because the second choice matched (and the first one did not), then the actual parameters will be reversed.

Within the choice list for single alternative, each choice must define the same set of bindings and the component subtypes for for a given identifier must all statically match. Currently, the case of a binding for a nondiscrete component is not implemented.

If the set of values that match the choice(s) of an earlier alternative overlaps the corresponding set of a later alternative, then the first set shall be a proper subset of the second (and the later alternative will not be executed if the earlier alternative “matches”). All possible values of the composite type shall be covered. The composite type of the selector shall be an array or record type that is neither limited nor class-wide. Currently, a “when others =>” case choice is required; it is intended that this requirement will be relaxed at some point.

If a subcomponent’s subtype does not meet certain restrictions, then the only value that can be specified for that subcomponent in a case choice expression is a “box” component association (which matches all possible values for the subcomponent). This restriction applies if:

  • the component subtype is not a record, array, or discrete type; or

  • the component subtype is subject to a non-static constraint or has a predicate; or:

  • the component type is an enumeration type that is subject to an enumeration representation clause; or

  • the component type is a multidimensional array type or an array type with a nonstatic index subtype.

Support for casing on arrays (and on records that contain arrays) is currently subject to some restrictions. Non-positional array aggregates are not supported as (or within) case choices. Likewise for array type and subtype names. The current implementation exceeds compile-time capacity limits in some annoyingly common scenarios; the message generated in such cases is usually “Capacity exceeded in compiling case statement with composite selector type”.

18.3.7. Mutably Tagged Types with Size’Class Aspect

For a specific tagged nonformal type T that satisfies some conditions described later in this section, the universal-integer-valued type-related representation aspect Size'Class may be specified; any such specified aspect value shall be static.

Specifying this aspect imposes an upper bound on the sizes of all specific descendants of T (including T itself). T’Class (but not T) is then said to be a “mutably tagged” type - meaning that T’Class is a definite subtype and that the tag of a variable of type T’Class may be modified by assignment in some cases described later in this section. An inherited Size'Class aspect value may be overridden, but not with a larger value.

If the Size'Class aspect is specified for a type T, then every specific descendant of T (including T itself)

  • shall have a Size that does not exceed the specified value; and

  • shall have a (possibly inherited) Size'Class aspect that does not exceed the specified value; and

  • shall be undiscriminated; and

  • shall have no composite subcomponent whose subtype is subject to a nonstatic constraint; and

  • shall not have a tagged partial view other than a private extension; and

  • shall not be a descendant of an interface type; and

  • shall not have a statically deeper accessibility level than that of T.

If the Size'Class aspect is not specified for a type T (either explicitly or by inheritance), then it shall not be specified for any descendant of T.

Example:

type Root_Type is tagged null record with Size'Class => 16 * 8;

type Derived_Type is new Root_Type with record
   Stuff : Some_Type;
end record;  -- ERROR if Derived_Type exceeds 16 bytes

Because any subtype of a mutably tagged type is definite, it can be used as a component subtype for enclosing array or record types, as the subtype of a default-initialized stand-alone object, or as the subtype of an uninitialized allocator, as in this example:

Obj : Root_Type'Class;
type Array_of_Roots is array (Positive range <>) of Root_Type'Class;

Default initialization of an object of such a definite subtype proceeds as for the corresponding specific type, except that Program_Error is raised if the specific type is abstract. In particular, the initial tag of the object is that of the corresponding specific type.

There is a general design principle that if a type has a tagged partial view, then the type’s Size'Class aspect (or lack thereof) should be determinable by looking only at the partial view. That provides the motivation for the rules of the next two paragraphs.

If a type has a tagged partial view, then a Size'Class aspect specification may be provided only at the point of the partial view declaration (in other words, no such aspect specification may be provided when the full view of the type is declared). All of the above rules (in particular, the rule that an overriding Size'Class aspect value shall not be larger than the overridden inherited value) are also enforced when the full view (which may have a different ancestor type than that of the partial view) is declared. If a partial view for a type inherits a Size'Class aspect value and does not override that value with an explicit aspect specification, then the (static) aspect values inherited by the partial view and by the full view shall be equal.

An actual parameter of an instantiation whose corresponding formal parameter is a formal tagged private type shall not be either mutably tagged or the corresponding specific type of a mutably tagged type.

For the legality rules in this section, the RM 12.3(11) rule about legality checking in the visible part and formal part of an instance is extended (in the same way that it is extended in many other places in the RM) to include the private part of an instance.

An object (or a view thereof) of a tagged type is defined to be “tag-constrained” if it is

  • an object whose type is not mutably tagged; or

  • a constant object; or

  • a view conversion of a tag-constrained object; or

  • a view conversion to a type that is not a descendant of the operand’s type; or

  • a formal in out or out parameter whose corresponding actual parameter is tag-constrained; or

  • a dereference of an access value.

In the case of an assignment to a tagged variable that is not tag-constrained, no check is performed that the tag of the value of the expression is the same as that of the target (RM 5.2 notwithstanding). Instead, the tag of the target object becomes that of the source object of the assignment. Note that the tag of an object of a mutably tagged type MT will always be the tag of some specific type that is a descendant of MT. An assignment to a composite object similarly copies the tags of any subcomponents of the source object that have a mutably tagged type.

The Constrained attribute is defined for any name denoting an object of a mutably tagged type (RM 3.7.2 notwithstanding). In this case, the Constrained attribute yields the value True if the object is tag-constrained and False otherwise.

Renaming is not allowed (see RM 8.5.1) for a type conversion having an operand of a mutably tagged type MT and a target type TT such that TT (or its corresponding specific type if TT is class-wide) is not an ancestor of MT (this is sometimes called a “downward” conversion), nor for any part of such an object, nor for any slice of any part of such an object. This rule also applies in any context where a name is required to be one for which “renaming is allowed” (for example, see RM 12.4). [This is analogous to the way that renaming is not allowed for a discriminant-dependent component of an unconstrained variable.]

A name denoting a view of a variable of a mutably tagged type shall not occur as an operative constituent of the prefix of a name denoting a prefixed view of a callable entity, except as the callee name in a call to the callable entity. This disallows, for example, renaming such a prefixed view, passing the prefixed view name as a generic actual parameter, or using the prefixed view name as the prefix of an attribute.

The execution of a construct is erroneous if the construct has a constituent that is a name denoting a subcomponent of a tagged object and the object’s tag is changed by this execution between evaluating the name and the last use (within this execution) of the subcomponent denoted by the name. This is analogous to the RM 3.7.2(4) rule about discriminant-dependent subcomponents.

If the type of a formal parameter is a specific tagged type, then the execution of the call is erroneous if the tag of the actual is changed while the formal parameter exists (that is, before leaving the corresponding callable construct). This is analogous to the RM 6.4.1(18) rule about discriminated parameters.

18.3.8. No_Raise aspect

The No_Raise aspect can be applied to a subprogram to declare that this subprogram is not expected to raise an exception. Should an exception still be raised during the execution of the subprogram, it is caught at the end of this execution and Program_Error is propagated to the caller.

18.3.9. Inference of Dependent Types in Generic Instantiations

If a generic formal type T2 depends on another formal type T1, the actual for T1 can be inferred from the actual for T2. That is, you can give the actual for T2, and leave out the one for T1.

For example, Ada.Unchecked_Deallocation has two generic formals:

generic
   type Object (<>) is limited private;
   type Name is access Object;
procedure Ada.Unchecked_Deallocation (X : in out Name);

where Name depends on Object. With this language extension, you can leave out the actual for Object, as in:

type Integer_Access is access all Integer;

procedure Free is new Unchecked_Deallocation (Name => Integer_Access);

The compiler will infer that the actual type for Object is Integer. Note that named notation is always required when using inference.

The following inferences are allowed:

  • For a formal access type, the designated type can be inferred.

  • For a formal array type, the index type(s) and the component type can be inferred.

  • For a formal type with discriminants, the type(s) of the discriminants can be inferred.

Example for arrays:

generic
   type Element_Type is private;
   type Index_Type is (<>);
   type Array_Type is array (Index_Type range <>) of Element_Type;
package Array_Operations is
   ...
end Array_Operations;

...

type Int_Array is array (Positive range <>) of Integer;

package Int_Array_Operations is new Array_Operations (Array_Type => Int_Array);

The index and component types of Array_Type are inferred from Int_Array, so that the above instantiation is equivalent to the following standard-Ada instantiation:

package Int_Array_Operations is new Array_Operations
   (Element_Type => Integer,
      Index_Type   => Positive,
      Array_Type   => Int_Array);

18.3.10. External_Initialization Aspect

The External_Initialization aspect provides a feature similar to Rust’s include_bytes! and to C23’s #embed. It has the effect of initializing an object with the contents of a file specified by a file path.

Only string objects and objects of type Ada.Streams.Stream_Element_Array can be subject to the External_Initialization aspect.

Example:

with Ada.Streams;

package P is
   S : constant String with External_Initialization => "foo.txt";

   X : constant Ada.Streams.Stream_Element_Array with External_Initialization => "bar.bin";
end P;

External_Initialization aspect accepts the following parameters:

  • mandatory Path: the path the compiler uses to access the binary resource.

If Path is a relative path, it is interpreted relatively to the directory of the file that contains the aspect specification.

Attention

The maximum size of loaded files is limited to 231 bytes.

18.3.11. Finally construct

The finally keyword makes it possible to have a sequence of statements be executed when another sequence of statements is completed, whether normally or abnormally.

This feature is similar to the one with the same name in other languages such as Java.

Note that finally is a keyword but it is not a reserved word. This is a configuration that does not exist in standard Ada.

18.3.11.1. Syntax

handled_sequence_of_statements ::=
     sequence_of_statements
  [exception
     exception_handler
    {exception_handler}]
  [finally
    sequence_of_statements]

18.3.11.2. Legality Rules

Return statements in the sequence_of_statements attached to the finally that would cause control to be transferred outside the finally part are forbidden.

Goto & exit where the target is outside of the finally’s sequence_of_statements are forbidden

18.3.11.3. Dynamic Semantics

Statements in the optional sequence_of_statements contained in the finally branch will be executed unconditionally, after the main sequence_of_statements is executed, and after any potential exception_handler is executed.

If an exception is raised in the finally part, it cannot be caught by the exception_handler.

Abort/ATC (asynchronous transfer of control) cannot interrupt a finally block, nor prevent its execution, that is the finally block must be executed in full even if the containing task is aborted, or if the control is transferred out of the block.

18.3.12. Continue statement

The continue keyword makes it possible to stop execution of a loop iteration and continue with the next one. A continue statement has the same syntax (except “exit” is replaced with “continue”), static semantics, and legality rules as an exit statement. The difference is in the dynamic semantics: where an exit statement would cause a transfer of control that completes the (implicitly or explicitly) specified loop_statement, a continue statement would instead cause a transfer of control that completes only the current iteration of that loop_statement, like a goto statement targeting a label following the last statement in the sequence of statements of the specified loop_statement.

Note that continue is a keyword but it is not a reserved word. This is a configuration that does not exist in standard Ada.

18.3.13. Constructors

The Constructor extension makes it possible to declare subprograms that are responsible for building objects of a tagged type. A constructor is declared using attribute syntax, like the attribute subprograms described below, with a first parameter of mode in out of the type being constructed:

package P is
   type T is tagged record
      C : Integer := 0;
   end record;

   procedure T'Constructor (Self : in out T);
   --  Default parameterless constructor

   procedure T'Constructor (Self : in out T; Value : Integer);
   --  Parametric constructor
end P;

A tagged type that declares a constructor, or that is derived from a type that does, is said to be a by-constructor type. An object of a by-constructor type cannot come into existence without a constructor being called for it: declaring an object selects a constructor implicitly, and 'Make selects one explicitly.

A constructor does not replace default initialization, it follows it. The object is created, its components are initialized, and the constructor body then runs on the object so initialized. That is why a constructor is a procedure taking the object as an in out parameter rather than a function returning a value, and it is why a default value on a component is not made redundant by the presence of a constructor: it is the value the component starts from, which the constructor body may refine, and which it keeps if the constructor never assigns to it.

Which value a component starts from depends on whether the constructor’s Initialize aspect names it, described under Order of construction below.

type Root is tagged record
   V : Integer := 7;
   W : Integer := 3;
end record;

procedure Root'Constructor (Self : in out Root; Value : Integer);

procedure Root'Constructor (Self : in out Root; Value : Integer) is
begin
   Self.V := Self.V + Value;   --  Self.V is 7 here, not undefined
end Root'Constructor;

X : Root := Root'Make (100);   --  X.V is 107, and X.W is still 3

Constructors are not primitive operations and are never inherited. A constructor must be declared in the same scope as its type, as for any other attribute subprogram (see the legality rules in Attribute Subprograms).

18.3.13.1. Creating objects

A constructor is called implicitly when an object is declared, and may be called explicitly through the 'Make attribute of the type, which denotes a function with the same parameters as the constructor except for the first. Preceded by new, it allocates:

A : T;                       --  implicit call of the parameterless one
B : T := T'Make (42);        --  explicit call
C : T := A;                  --  implicit call of the copy constructor
D : T := T'Make (A);         --  explicit call of the copy constructor

type Acc is access all T'Class;

E : Acc := new T;            --  allocated, parameterless
F : Acc := new T'Make (7);   --  allocated, parametric

18.3.13.2. Default constructors

A by-constructor type provides, by default, a parameterless constructor and a by-copy constructor. Neither is provided unconditionally – the conditions are given below – and either can be removed from a type’s public view by declaring it abstract in the visible part of a package.

  • A parameterless constructor. The implicit one is provided only while the type declares no explicit constructor of its own: declaring any explicit constructor suppresses it.

    What matters from then on is whether some declared constructor can be called with no arguments, and a constructor whose formals after Self all have default expressions can be. Such a constructor is itself a parameterless constructor, even though it is explicit and takes formals:

    type T is tagged null record;
    procedure T'Constructor (Self : in out T; V : Integer);
    
    X : T;   --  error: no parameterless constructor for "T"
    
    type U is tagged null record;
    procedure U'Constructor (Self : in out U; V : Integer := 1);
    
    Y : U;             --  legal: V takes its default
    Z : U := U'Make;   --  likewise
    

    A derived type that declares none has a parameterless constructor only if its parent provides one, since the parent part of an object is always initialized by a constructor of the parent. A concrete type derived from a parent with no parameterless constructor can only be built by a constructor it declares itself, and declaring no constructor for it is an error.

  • A copy constructor: one whose second formal is an in parameter of the type itself, and whose remaining formals, if it has any, all have default expressions. It is available for a non-limited type, and a limited type has none at all – declaring one for a limited type is illegal, since a limited type cannot be copied.

    A constructor that does not match that profile is an ordinary constructor and not the copy constructor.

    type T is tagged record
       C : Integer := 1;
    end record;
    
    procedure T'Constructor (Self : in out T);
    --  the parameterless constructor
    
    procedure T'Constructor (Self : in out T; From : T);
    --  second formal is an "in" parameter of T and there are no others:
    --  this one IS the copy constructor
    
    procedure T'Constructor (Self : in out T; From : T; X : Integer);
    --  a third formal with no default: an ordinary constructor, and not
    --  the copy constructor
    
    A : T;
    B : T := A;   --  calls the two-formal constructor above
    

    Had the two-formal declaration been absent, the copy would still have been legal: the type would keep the implicit copy constructor and use that one, leaving the three-formal constructor unused.

It is the explicit constructors that are not inherited: a derived type does not acquire the constructors its parent declares. The defaults are a separate matter – a derived type that declares none of its own has a parameterless and a by-copy constructor synthesized for it, on the conditions given above, so it may well have constructors without declaring any.

What it does not have is the parent’s explicit profiles. Arguments matching one of them exactly are refused unless the derived type declares a constructor with that profile itself:

type Root is tagged null record;
procedure Root'Constructor (Self : in out Root; V1, V2 : Integer);

type Child is new Root with null record;
procedure Child'Constructor (Self : in out Child; V : Integer);

X : Child := Child'Make (1);     --  legal, Child's own constructor

Y : Child := Child'Make (1, 2);  --  error: no constructor matching
                                 --  given arguments for "Child" --
                                 --  Root's is not inherited

Since Root above declares an explicit constructor it has no parameterless one, so the body of Child'Constructor has to select a constructor of the parent with the Super aspect described below.

18.3.13.3. Order of construction

An object is built from the inside out. The constructors of components are called before the constructor of the object containing them, at every level of nesting, and the parent part of an object is always initialized by a constructor of the parent type before the constructor of the derived type runs.

The parameterless parent constructor is called, unless the Super aspect on the constructor body selects another. Where the parent has no parameterless constructor, Super is not optional.

Components may be given values that depend on the constructor’s own parameters using the Initialize aspect. An association there takes precedence over the component declaration’s default expression, which is then not used – and, since it is not used, not evaluated either, so any side effect it has does not take place. A component the aspect does not name is initialized from its declaration as usual:

type C is tagged record
   A : Integer := Print_And_Return ("A FROM RECORD");
   B : Integer := Print_And_Return ("B FROM RECORD");
end record;

procedure C'Constructor (Self : in out C);

procedure C'Constructor (Self : in out C; S : String)
  with Initialize => (A => Print_And_Return (S))
is
begin
   null;
end C'Constructor;

V1 : C := C'Make;                  --  prints A FROM RECORD, B FROM RECORD
V2 : C := C'Make ("ALTERNATE A");  --  prints ALTERNATE A, B FROM RECORD

Neither aspect may refer to the object being constructed, which does not yet exist when they are evaluated:

package D is
   type Root is tagged record
      R : Integer := 0;
   end record;
   procedure Root'Constructor (Self : in out Root);
   procedure Root'Constructor (Self : in out Root; V : Integer);

   type Child is new Root with record
      K : Integer := 0;
   end record;
   procedure Child'Constructor (Self : in out Child);
   procedure Child'Constructor (Self : in out Child; V : Integer);
end D;
package body D is
   procedure Root'Constructor (Self : in out Root) is
   begin
      Self.R := 1;
   end Root'Constructor;

   procedure Root'Constructor (Self : in out Root; V : Integer) is
   begin
      Self.R := V;
   end Root'Constructor;

   procedure Child'Constructor (Self : in out Child)
     with Super, Initialize => (K => 7)
   is
   begin
      null;
   end Child'Constructor;

   procedure Child'Constructor (Self : in out Child; V : Integer)
     with Super => (V), Initialize => (K => 8)
   is
   begin
      null;
   end Child'Constructor;
end D;

Child'Make gives R = 1 and K = 7: the bare with Super, carrying no parameter list, selects the parent’s parameterless constructor. That is what omitting the aspect altogether would have done too, so writing it is a way of saying explicitly which parent constructor is intended. Child'Make (42) gives R = 42 and K = 8, the parameter list selecting the parametric parent constructor and passing it the value the child was given.

A parameter list needs its parentheses even for a single parameter; omitting them is rejected.

A component of a by-constructor type must be given a value when that type provides no parameterless constructor, either by a default expression in its declaration or by the Initialize aspect of every constructor of the enclosing type.

18.3.13.4. Constructors and private types

The constructors available to a client of a package are those it can see. A constructor declared in the private part of a package must therefore not take away anything the public view of the type promised: declaring one where the public view shows no constructor at all, or replacing a default the public view does promise, is illegal.

package G is
   type T is tagged private;
private
   type T is tagged record
      C : Integer := 0;
   end record;

   procedure T'Constructor (Self : in out T);
   --  error: constructor cannot be declared in the private part,
   --  since the public view of "T" has no constructors
end G;

Adding a constructor whose profile the public view did not promise remains legal; only concealment is refused.

A default may be removed from the public view deliberately, by declaring it abstract in the visible part and completing it in the private part. The type can then be built only by code that sees the private part:

package E is
   type T is tagged private;

   procedure T'Constructor (Self : in out T) is abstract;
   procedure T'Constructor (Self : in out T; From : T) is abstract;
private
   type T is tagged record
      C : Integer := 0;
   end record;

   procedure T'Constructor (Self : in out T);
   procedure T'Constructor (Self : in out T; From : T);

   Inside : T;   --  legal, the private part sees the completions
end E;

An abstract constructor declared for a type must appear in the visible part of a package or generic package – it exists in order to be seen. That is a rule about the constructors of a type declaration. A generic formal constructor is a different thing: it is declared in the formal part of a generic, it states what an actual must provide rather than what a type has, and declaring it is abstract removes a requirement on the actual rather than removing a constructor. Such a formal has no completion anywhere. See Constructors and generics below.

A concrete declaration in the private part is then required, as in E above; omitting it is rejected. The effect of the idiom is therefore to hide a constructor: the constructor is denied to a client and remains available to the package itself and to its private part.

18.3.13.5. Constructors and generics

A generic formal tagged type carries requirements on the constructors its actual must provide, and those requirements are stated by declaring formal constructors for it, introduced by with as for a formal subprogram.

A formal type given no such indication requires an actual that provides both defaults. Declaring a formal constructor states a requirement of its own, in place of the parameterless one. Declaring a formal constructor is abstract removes the corresponding requirement rather than adding one:

generic
   type T1 is tagged private;
   --  Requires a parameterless and a by-copy constructor if T1 is
   --  by constructor.

   type T2 is tagged private;
   with procedure T2'Constructor (Self : in out T2; V : Integer);
   --  Requires a parametric constructor with this profile,
   --  and a by-copy constructor.

   type T3 is tagged private;
   with procedure T3'Constructor (Self : in out T3) is abstract;
   --  Requires a by-copy constructor only.

   type T4 is tagged private;
   with procedure T4'Constructor (Self : in out T4) is abstract;
   with procedure T4'Constructor (Self : in out T4; Src : T4) is abstract;
   --  Requires neither parameterless nor by-copy constructor.
package G is
end G;

The two kinds of requirement are checked differently against an actual that is not built by constructors:

  • A requirement for a default constructor – the parameterless and by-copy ones a formal type asks for when given no indication – is checked only when the actual is a by-constructor type. A tagged type that is not a by-constructor type is accepted, because such a type is created without constructors in the first place and there is nothing for the requirement to be checked against.

  • A requirement stated by an explicit formal constructor is checked against every actual. The actual must declare a constructor matching that profile, whatever kind of type it is.

So a tagged type with no constructors at all is an acceptable actual for T1, T3 and T4 above, whose requirements are all for defaults, and is not an acceptable actual for T2, which asks for a constructor taking an Integer:

type Plain is tagged null record;   --  no constructors at all

package I is new G (T1 => Plain, T2 => Plain, T3 => Plain, T4 => Plain);
--  error: actual for "T2" must provide a matching constructor
package Act is
   --  R1 provides both defaults
   type R1 is tagged null record;
   procedure R1'Constructor (Self : in out R1);
   procedure R1'Constructor (Self : in out R1; V : Integer);

   --  R2 declares a parametric constructor and removes the by-copy one
   type R2 is tagged null record;
   procedure R2'Constructor (Self : in out R2; V : Integer);
   procedure R2'Constructor (Self : in out R2; Src : R2) is abstract;
private
   procedure R2'Constructor (Self : in out R2; Src : R2);
end Act;
with G;
with Act; use Act;
package Inst is
   package I1 is new G (T1 => R1, T2 => R1, T3 => R1, T4 => R1);
   --  Legal throughout: R1 provides both defaults

   package I2 is new G (T1 => R2, T2 => R2, T3 => R2, T4 => R2);
   --  Of the four formals only T4 is satisfied:
   --    error: actual for "T1" must provide a parameterless constructor
   --    error: actual for "T2" must provide a by-copy constructor
   --    error: actual for "T3" must provide a by-copy constructor
end Inst;

What an actual provides is judged from where the instantiation stands, as for any other client. An instantiation written inside Act’s own private part sees the concrete completion of the by-copy constructor, so there only T1 is unsatisfied.

Matching a formal constructor with an actual requires mode conformance. Subtype conformance is not required, and could not be, since the profile of a generic formal subprogram is never subtype conformant with any other.

A formal constructor must be declared after the formal type it constructs, and after any formal type appearing in its profile; beyond that the formal types may be given in any order. A constructor cannot be declared by a generic instantiation, as for the other attribute subprograms:

procedure R'Constructor is new Gen_Ctor;
--  error: instantiation not allowed for constructors

18.3.13.6. Current Restrictions

The following uses of constructors are currently unimplemented, and are rejected by the compiler:

  • constructors for untagged types

  • constructors for types with discriminants

  • constructors for types that implement interface types

  • constructors for types with a predicate

  • aggregates of a by-constructor type

  • using a constructor as a function value, for instance as T'Make'Access or as a generic actual.

A constructor is declared for a first subtype, and is shared by every subtype of it; declaring one for a subtype is not a temporary restriction but a consequence of that, and is rejected.

18.3.14. Destructors

The Destructor extension adds a new finalization mechanism that significantly differs from standard Ada in how it interacts with type derivation.

New syntax is introduced to make it possible to define “destructors” for record types, tagged or untagged. Here’s a simple example:

package P is
   type T is record
      ...
   end record;

   procedure T'Destructor (X : in out T);
end P;
package body P is
   procedure T'Destructor (X : in out T) is
   begin
      ...
   end T'Destructor;
end P;

Like Finalize procedures, destructors are called on objects just before they are destroyed. But destructors are more flexible in how they can used with derived types. With standard Ada finalization, when you derive from a finalizable type, you must either inherit the Finalize procedure or override it completely.

Destructors work differently. You can define a destructor for a type derived from a parent type that also has a destructor, and then when objects of the derived type are finalized, both destructors will be called. For example:

type T1 is record
   ...
end record;

procedure T1'Destructor (X : in out T1);

type T2 is new T1;

procedure T2'Destructor (X : in out T2);

When an object of type T2 is finalized, there will be first a call to T2'Destructor, and then a call to T1'Destructor on the object.

18.3.15. Structural Generic Instantiation

The compiler implements a second kind of generic instantiation, called “structural”, alongside the traditional instantiation specified by the language, which is defined as follows: the structural instantiation of a generic unit on given actual parameters is the anonymous instantiation of the generic unit on the actual parameters done in the outermost scope where it would be legal to do an identical traditional instantiation.

There is at most one structural instantiation of a generic unit on given actual parameters done in a partition.

Structural generic instances (the product of structural instantiation) are implicitly created whenever a reference to them is made in a place where a name is accepted by the language.

18.3.15.1. Syntax

name ::= { set of productions specified in the RM }
         | structural_generic_instance_name

structural_generic_instance_name ::= name generic_actual_part

18.3.15.2. Legality Rules

The name in a structural_generic_instance_name shall denote a generic unit that is preelaborated. Note that, unlike in a traditional instantiation, there are no square brackets around the generic_actual_part in the second production, which means that it is mandatory and, therefore, that the generic unit shall have at least one generic formal parameter.

The generic unit shall not take a generic formal object of mode in out. If the generic unit takes a generic formal object of mode in, then the corresponding generic actual parameter shall be a static expression.

A structural_generic_instance_name for a generic package shall not be present in a library unit if the structural instance is also a library unit and has a semantic dependence on the former.

For a generic subprogram, if a local entity of the enclosing library-level package is used as an actual and the structural instance would have a semantic dependence on the package, the structural instantiation is automatically demoted to a local instantiation. In this case, several instances of the generic subprogram may be present in a single partition, unless whole-partition optimization is performed (e.g., via LTO).

18.3.15.3. Static Semantics

A structural_generic_instance_name denotes the instance that is the product of the structural instantiation of a generic unit on the specified actual parameters. This instance is unique to a partition, except when a generic subprogram instantiation is automatically demoted to a local instantiation as described under Legality Rules.

Example:

with Ada.Containers.Vectors;

procedure P is
   V : Ada.Containers.Vectors(Positive,Integer).Vector;

begin
   V.Append (1);
   V.Append (0);
   Ada.Containers.Vectors(Positive,Integer).Generic_Sorting("<").Sort (V);
end;

This procedure references two structural instantiations of two different generic units: Ada.Containers.Vectors(Positive,Integer) is the structural instance of the generic unit Ada.Containers.Vectors on Positive and Integer and Ada.Containers.Vectors(Positive,Integer).Generic_Sorting("<") is the structural instance of the nested generic unit Ada.Containers.Vectors(Positive,Integer).Generic_Sorting on "<".

Note that the following example is illegal:

with Ada.Containers.Vectors;

package Q is
   type T is record
      I : Integer;
   end record;

   V : Ada.Containers.Vectors(Positive,T).Vector;
end Q;

The reason is that Ada.Containers.Vectors, Positive and Q.T being library-level entities, the structural instance Ada.Containers.Vectors(Positive,T) is a library unit with a dependence on Q and, therefore, cannot be referenced from within Q. This restriction applies to structural instantiations of generic packages. The simple way out is to declare a traditional instantiation in this case:

with Ada.Containers.Vectors;

package Q is
   type T is record
      I : Integer;
   end record;

   package Vectors_Of_T is new Ada.Containers.Vectors(Positive,T);

   V : Vectors_Of_T.Vector;
end Q;

But the following example is legal:

with Ada.Containers.Vectors;

procedure P is
   type T is record
      I : Integer;
   end record;

   V : Ada.Containers.Vectors(Positive,T).Vector;
end;

because the structural instance Ada.Containers.Vectors(Positive,T) is not a library unit.

For generic subprograms, the restriction does not apply: if a local entity of a library-level package is used as an actual, the structural instantiation is automatically demoted to a local instantiation. For example:

with Ada.Unchecked_Deallocation;

package Q is
   type T is record
      I : Integer;
   end record;

   type T_Access is access T;
end Q;

package body Q is
   procedure Free_T (X : in out T_Access) is
   begin
      Ada.Unchecked_Deallocation(T, T_Access)(X);
   end Free_T;
end Q;

is legal: since T and T_Access are local entities of Q, the structural instantiation of Ada.Unchecked_Deallocation is demoted to a local instantiation rather than producing an error. Note that the uniqueness guarantee no longer holds in this case and several instances of the generic subprogram may be present in a single partition.

The first example can be rewritten in a less verbose manner:

with Ada.Containers.Vectors; use Ada.Containers.Vectors(Positive,Integer);

procedure P is
   V : Vector;

begin
   V.Append (1);
   V.Append (0);
   Generic_Sorting("<").Sort (V);
end;

Another example, which additionally uses the inference of dependent types:

with Ada.Unchecked_Deallocation;

procedure P is

   type Integer_Access is access all Integer;

   A : Integer_Access := new Integer'(1);

begin
   Ada.Unchecked_Deallocation(Name => Integer_Access) (A);
end;

18.3.16. Attribute Subprograms

This feature allows declaring subprograms that are associated with a named aspect or attribute of a given type, as an alternative to explicitly specifying the aspect or attribute for the type (using an aspect_specification or attribute_definition_clause), by defining the name of the subprogram using attribute syntax. In effect, this implicitly specifies the aspect or attribute for the type, and is intended to be semantically equivalent to using an explicit aspect specification, but without needing to give a specific name in the aspect and subprogram. This is allowed for the various aspects that denote subprograms (see below for the exact list of supported aspects).

Here is an example of the use of this feature for defining indexing functions for a container type and an integer-literal function for the container’s element type:

package My_Container is

   type Container is tagged ...;  -- Implicit indexing aspects

   type Element_Type is ...;      -- Implicit Integer_Literal aspect

   type Cursor_Type is ...;

   type Reference_Type is ...;

   function Container'Constant_Indexing (C : Container; Index : Positive)
     return Element_Type;

   function Container'Constant_Indexing (C : Container; Index : Cursor_Type)
     return Element_Type;

   function Container'Variable_Indexing
     (C : in out Container; Index : Positive)
      return Reference_Type;

   function Element_Type'Integer_Literal (S : String) return Element_Type;

end My_Container;

18.3.16.1. Syntax

defining_program_unit_name ::=
  [parent_unit_name . ]defining_identifier
| defining_attribute_subprogram_name

defining_attribute_subprogram_name ::=
  prefix'attribute_designator

18.3.16.2. Legality Rules

The prefix of a defining_attribute_subprogram_name shall be either a direct_name denoting a type (more properly, a first subtype) declared immediately within the scope where the associated subprogram is declared, or else an attribute name itself whose attribute_designator is Class and whose prefix denotes a type subject to the same declaration condition. A defining_program_unit_name that is a defining_attribute_subprogram_name may only be used to define the name of a subprogram that is neither a library subprogram nor a subprogram whose body is given by a body_stub (nor can it be used to define the name of a generic subprogram).

The attribute_designator given in a defining_attribute_subprogram_name shall name an aspect that is allowed to designate a subprogram. Specifically, it shall be one of the predefined aspects Constant_Indexing, Variable_Indexing, Default_Iterator, Integer_Literal, Real_Literal, String_Literal, Put_Image, Read, Write, Input, or Output, or else one of the implementation-defined aspects Constructor or Destructor. (Note that this feature is not supported for aspects that have elements that may designate a subprogram, such as the Aggregate aspect.)

If the prefix of a defining_attribute_subprogram_name is an attribute name whose attribute_designator is Class, then the attribute_designator of the defining_attribute_subprogram_name shall be the name of a stream attribute.

An attribute subprogram for a given type and aspect is subject to the same restrictions as would be imposed on a subprogram denoted by an explicit aspect_specification or attribute_definition_clause for that type and aspect. In particular, the profile of the subprogram must satisfy any expected profile defined for the aspect.

If a subprogram is declared using a defining_attribute_subprogram_name, then the type named in the attribute subprogram’s name shall not have an explicit aspect_specification that specifies the same aspect as that named by the subprogram, nor shall the type derive from an ancestor type that explicitly specifies that aspect. Similarly, an explicit aspect_specification shall not specify an aspect for a type that is derived from a type for which any attribute subprograms have been declared for the same aspect.

18.3.17. Alternative dispatching rules

GNAT provides a configuration pragma, Default_Dispatching_Calls, that enables dispatching rules that are different from and arguably more intuitive than standard Ada dispatching rules.

Let’s start with an introductory example. Consider the following program:

--  p.ads

package P is
   type Root is tagged null record;

   procedure Say_Hello (X : Root);

   function Name (X : Root) return String;

   type Leaf is new Root with null record;

   overriding
   function Name (X : Leaf) return String;
end P;

--  p.adb

with Ada.Text_IO; use Ada.Text_IO;

package body P is
   procedure Say_Hello (X : Root) is
   begin
      Put_Line ("Hello from " & X.Name);
   end Say_Hello;

   function Name (X : Root) return String is
   begin
      return "Root";
   end Name;

   function Name (X : Leaf) return String is
   begin
      return "Leaf";
   end Name;
end P;

--  main.adb

with P;

procedure Main is
   X : P.Leaf;
begin
   X.Say_Hello;
end Main;

The question is: what does this program print?

Programmers familiar with Java or C++ would likely expect the program to print “Hello from Leaf”. After all, there is only one object in play here, and its type is Leaf, so how could the Name primitive of Root be called?

The right answer is that the program prints “Hello from Root”. The important point is that the call to Name in Put_Line ("Hello from " & X.Name); is not dispatching. We can make it dispatching with an Ada idiom called “redispatching”:

Put_Line ("Hello from " & Root'Class (X).Name);

This extension makes it possible to make the first version dispatching by specifying pragma Default_Dispatching_Calls (On); at the beginning of an Ada file or in a configuration pragma file (e.g., gnat.adc). If pragma Default_Dispatching_Calls (On); is in a configuration pragma file, pragma Default_Dispatching_Calls (Off); can be used at the beginning of an Ada file to disable the alternative dispatching rules for this file. For example:

--  gnat.adc

pragma Default_Dispatching_Calls (On);

--  main.adb

pragma Default_Dispatching_Calls (Off);

procedure Main is
begin
   ...
end Main;

Default_Dispatching_Calls only affects calls to primitive subprograms. It has no effect on primitive definitions. For example:

--  p.ads

pragma Default_Dispatching_Calls (On);

package P is
   type Root is tagged null record;

   procedure Say_Hello (X : Root);

   type Leaf is new Root with null record;

   overriding
   procedure Say_Hello (X : Leaf);
end P;

--  p.adb

pragma Default_Dispatching_Calls (On);

with Ada.Text_IO; use Ada.Text_IO;

package body P is
   procedure Say_Hello (X : Root) is
   begin
      Put_Line ("Hello from Root");
   end Say_Hello;

   overriding
   procedure Say_Hello (X : Leaf) is
   begin
      Put_Line ("Hello from Leaf");
   end Say_Hello;
end P;

--  main.adb

with P; use P;

procedure Main is
   X : Leaf;
begin
   Say_Hello (Root (X));
end Main;

Here, Default_Dispatching_Calls is not active in Main so the call to Say_Hello is not implicitly dispatching and the program outputs “Hello from Root”. It doesn’t matter that Default_Dispatching_Calls is active in the spec and the body of P where Say_Hello is defined.

18.3.17.1. Nondispatching calls with 'Super

When Default_Dispatching_Calls is active, the only way to make a nondispatching call to a dispatching operation is to use the Super attribute. Any call that has at least one controlling argument that’s a reference to 'Super is treated as nondispatching. In the following example, Leaf’s Name primitive uses 'Super to call Root’s Name primitive:

--  p.ads

package P is
   type Root is tagged null record;

   procedure Say_Hello (X : Root);

   function Name (X : Root) return String;

   type Leaf is new Root with null record;

   overriding
   function Name (X : Leaf) return String;
end P;

--  p.adb

pragma Default_Dispatching_Calls (On);

with Ada.Text_IO; use Ada.Text_IO;

package body P is
   procedure Say_Hello (X : Root) is
   begin
      Put_Line ("Hello from " & X.Name);
   end Say_Hello;

   function Name (X : Root) return String is
   begin
      return "Root";
   end Name;

   function Name (X : Leaf) return String is
      S : constant String := "Child of " & X'Super.Name;
   begin
      return S;
   end Name;
end P;

--  main.adb

with P;

procedure Main is
   X : P.Leaf;
begin
   X.Say_Hello;
end Main;

This program prints “Hello from Child of Root”.

18.3.17.2. Interaction with generics

When using generics, it’s at the point of the generic definition that Default_Dispatching_Calls is taken into account, not at the point of the instantiation.

18.3.17.3. Dispatching assignments

In Ada, an assignment is dispatching when the left-hand side is class-wide and the right-hand side is tag-indeterminate. When pragma Default_Dispatching_Calls is active, this behavior is extended to all cases where the left-hand side is tagged and the right-hand side is tag-indeterminate.

For example:

--  p1.ads

package P1 is
   type Root is tagged null record;

   procedure Initialize (X : out Root);

   function Create return Root;
end P1;

--  p1.adb

pragma Default_Dispatching_Calls (On);

package body P1 is
   procedure Initialize (X : out Root) is
   begin
      --  pragma Default_Dispatching_Calls makes the next line equivalent to
      --
      --     Root'Class (X) := Create;
      X := Create;
   end Initialize;

   function Create return Root is
   begin
      return (null record);
   end Create;
end P1;

--  p2.ads

with P1;

package P2 is
   type Leaf is new P1.Root with null record;

   overriding
   function Create return Leaf;
end P2;

--  main.adb

with P2;

procedure Main is
   X : P2.Leaf;
begin
   P2.Initialize (X);
end Main;

The Create function that is called in this example is P2.Create.

18.3.17.4. Access-to-subprogram values

Default_Dispatching_Calls changes the semantics of the Access attribute when it’s applied to primitives of tagged types: the returned access-to-subprogram values implicitly dispatch on their controlling parameters. For example:

--  p.ads

package P is
   type Root is tagged null record;

   procedure Say_Hello (X : in out Root);

   type Acc is access procedure (X : in out Root);

   type Leaf is new Root with null record;

   overriding
   procedure Say_Hello (X : in out Leaf);
end P;

--  q.ads

with P; use P;

package Q is
   function Get_Procedure return Acc;
end Q;

--  q.adb

pragma Default_Dispatching_Calls (On);

package body Q is
   function Get_Procedure return Acc is
   begin
      --  Default_Dispatching_Calls is active here so the access-to-subprogram
      --  value we get is implicitly dispatching.
      return Say_Hello'Access;
   end Get_Procedure;
end Q;

--  main.adb

with P; use P;

with Q;

procedure Main is
   Proc : Acc := Q.Get_Procedure;

   X : Leaf;
begin
   --  pragma Default_Dispatching_Calls is not active here but the call is
   --  still implicitly dispatching because the access-to-subprogram value was
   --  created in the body of Q where the pragma is active.
   Proc (Root (X));
end Main;

It’s the Say_Hello primitive of Leaf that is called in this example.

Currently, such dispatching access-to-subprogram values are rejected when the attribute reference is contained in a library subprogram. This limitation will be lifted at some point.

Another limitation is that taking 'Access of a dispatching primitive of a type is only allowed after the type is frozen.

18.3.18. Attribute To_String

Ada defines the Image and Put_Image aspects and attributes (RM 4.10), together with the related Wide_Image and Wide_Wide_Image attributes. The To_String aspect and attribute is similar in many ways to a combination of the two. Depending on context, T'To_String refers either to a procedure (like Put_Image) or to a function (like Image). The 'Wide_To_String and 'Wide_Wide_To_String attributes, like the analogous wide forms of Image, each refer only to a function.

The most significant difference between To_String and the existing Image/Put_Image features is the support for user-configurable formatting, allowing images to be generated in formats such as JSON or XML. This is accomplished via an additional leading argument F of type Ada.Strings.Text_Formatters.Root_Formatter_Type'Class, where Ada.Strings.Text_Formatters is a new predefined package described in the Ada.Strings.Text_Formatters section below. The formatter provides a set of protocol operations (Open_Record, List_Component, Put_Integer_32, Put_Boolean, and so on) that the compiler-generated body calls to describe the structure of the value; a user-defined formatter may override these operations to produce any desired output format. The function forms have overloaded versions that differ only in the presence of a formatter argument; when no formatter is provided, Ada.Strings.Text_Formatters.Default_Formatter is used, which produces output similar in appearance to 'Image.

An aspect specification may be used to provide a user-defined To_String procedure for a type, just as one may be used to provide a user-defined Put_Image procedure. The To_String function forms ('To_String, 'Wide_To_String, 'Wide_Wide_To_String) are not directly user-specifiable; they are derived from the procedure form, just as 'Image is defined in terms of Put_Image.

As with Image, the prefix of the function-form attributes may be either a type or an object; the procedure form, like Put_Image, requires a type prefix.

A further difference from Put_Image is that a call to the procedure T'To_String, where T is a tagged type, is a dispatching call, regardless of whether the value has a specific or class-wide type. The To_String procedure corresponding to the specific type identified by the run-time tag of the value is therefore invoked. A call to Put_Image does not have this property. The 'Super attribute provides an escape hatch: writing V'Super as the value argument makes the call nondispatching, targeting the parent type’s To_String directly, in accordance with the existing semantics of 'Super.

Dispatching a T'To_String call through a class-wide type to a tagged type T whose definition was compiled without -gnatX0 produces output equivalent to T'Put_Image: the formatter argument is accepted but ignored, and the value is formatted using the default Ada-syntax representation. All types in a tagged-type hierarchy that should produce structured formatter output must be compiled with -gnatX0. Command lines that disagree about -gnatX0 across the types in a single tagged-type hierarchy are not detected or rejected; it is the user’s responsibility to keep such settings consistent across a partition.

18.3.18.1. Syntax

A call to the procedure form has the form:

T'To_String (F, S, V)

where T is a subtype mark, F is of type Ada.Strings.Text_Formatters.Root_Formatter_Type'Class, S is of type Ada.Strings.Text_Buffers.Root_Buffer_Type'Class, and V is of type T. The profile is the same as that of Put_Image (RM 4.10), with the addition of a leading in out argument F of type Ada.Strings.Text_Formatters.Root_Formatter_Type'Class.

The function forms correspond to Image, Wide_Image, and Wide_Wide_Image (RM 4.10), with the same prefix rules, and each have overloaded versions that differ only in the presence of a leading formatter argument F of type Ada.Strings.Text_Formatters.Root_Formatter_Type'Class:

V'To_String
V'To_String (F)
T'To_String (V)
T'To_String (F, V)
V'Wide_To_String
V'Wide_To_String (F)
T'Wide_To_String (V)
T'Wide_To_String (F, V)
V'Wide_Wide_To_String
V'Wide_Wide_To_String (F)
T'Wide_Wide_To_String (V)
T'Wide_Wide_To_String (F, V)

The corresponding implicit declarations are:

procedure T'To_String
  (F      : in out Ada.Strings.Text_Formatters.Root_Formatter_Type'Class;
   Buffer : in out Ada.Strings.Text_Buffers.Root_Buffer_Type'Class;
   Arg    : in T);

function T'To_String (Arg : in T) return String;
function T'To_String
  (F   : in out Ada.Strings.Text_Formatters.Root_Formatter_Type'Class;
   Arg : in T) return String;

function T'Wide_To_String (Arg : in T) return Wide_String;
function T'Wide_To_String
  (F   : in out Ada.Strings.Text_Formatters.Root_Formatter_Type'Class;
   Arg : in T) return Wide_String;

function T'Wide_Wide_To_String (Arg : in T) return Wide_Wide_String;
function T'Wide_Wide_To_String
  (F   : in out Ada.Strings.Text_Formatters.Root_Formatter_Type'Class;
   Arg : in T) return Wide_Wide_String;

18.3.18.2. Legality Rules

To_String is an operational aspect, like Put_Image (AARM 13.1(8.mm/1)), and is subject to the same specifiability restrictions as Put_Image (RM 4.10): it may be specified only for a specific noninterface type. The subtype of the value parameter V follows the same rules as the Arg parameter of Put_Image (RM 4.10): it is the first subtype of T for non-scalar T and the base subtype for scalar T. The subtype requirements for the Arg parameter of the procedure named in a To_String aspect specification are also the same as for a Put_Image aspect specification.

18.3.18.3. Dynamic Semantics

The function forms are defined in terms of the procedure form in the same way as Image is defined in terms of Put_Image (RM 4.10), using Ada.Strings.Text_Formatters.Default_Formatter when no explicit F is given, and returning a String, Wide_String, or Wide_Wide_String as appropriate.

A call to the procedure T'To_String, where T is a tagged type, is a dispatching call (unless V is a 'Super attribute reference, in which case it is nondispatching, in accordance with the existing semantics of 'Super): the procedure corresponding to the specific type identified by the run-time tag of V is invoked. A call to Put_Image does not have this property.

18.3.18.4. Default To_String Procedure

When no user-defined To_String procedure has been specified, a default procedure is generated by the compiler. For a type whose definition is compiled with -gnatX0, the default procedure visits all components in order, describing each part of the value by calling the appropriate operation of F (see Ada.Strings.Text_Formatters below); the output format is determined by the formatter.

For a type whose definition is compiled without -gnatX0, a fallback procedure is generated instead: the formatter argument is accepted but ignored, and the value is formatted using Put_Image, producing the default Ada-syntax representation.

For array types, the formatter is called with Open_Array, followed by List_Components (if no index type is an enumeration type) or List_Indexed_Components (if any index type is an enumeration type), followed by element traversal, followed by Close. For a dimension with a non-enumeration index type, each element’s To_String is called between List_First and List_Last, each carrying the dimension number. For a dimension with an enumeration index type, the order is instead List_First, the index value’s To_String, List_Last, then the element’s To_String: List_Last comes before the element rather than after it, giving the formatter enough information to produce, for example, a named-association representation.

For task types, the formatter is called with Open_Task, followed by a Put_UTF_8 call writing the runtime task identity, followed by any discriminants (each preceded by List_Discriminant and followed by the discriminant value’s To_String), followed by Close.

For protected types, a correct implementation would require a protected read-only action to snapshot all components, with the formatter calls made outside that action (because formatter and buffer operations are potentially blocking per RM 9.5.1(8)). This is not yet implemented; the current behavior falls back to Put_Image, writing (protected object) without reading any components.

18.3.18.5. Specifying To_String

A user-defined To_String procedure may be specified via an attribute definition clause:

procedure My_To_String
  (F : in out Ada.Strings.Text_Formatters.Root_Formatter_Type'Class;
   S : in out Ada.Strings.Text_Buffers.Root_Buffer_Type'Class;
   V : T);

for T'To_String use My_To_String;

or equivalently via an aspect specification on the type declaration:

type T is ...
  with To_String => My_To_String;

The specified procedure shall have the profile above: F and S class-wide, V of the specific subtype T (as for the Arg parameter of a user-specified Put_Image procedure, RM 4.10).

18.3.18.6. Ada.Strings.Text_Formatters

The predefined package Ada.Strings.Text_Formatters defines the abstract tagged type Root_Formatter_Type and its primitive operations, and the deferred constant Default_Formatter of type Root_Formatter_Type'Class. Default_Formatter produces a simple human-readable representation similar in appearance to 'Image, with the exception that no leading space is present for numeric values.

A given Root_Formatter_Type'Class object, like most Ada objects, is not task-safe: a caller sharing one formatter object across concurrent calls is responsible for synchronization.

The formatter protocol consists of the following groups of operations, each taking Self : in out Root_Formatter_Type as the controlling argument and Buffer : in out Root_Buffer_Type'Class as the output target. All operations also take a Format parameter of type Root_Formatter_Parameters'Class for future extensibility.

Scalar output

Each scalar operation receives a fully qualified Type_Name and the value. Put_Boolean takes a Boolean value. Put_Enumeration takes the result of T'Image as Value_Name and the result of T'Enum_Rep, widened to Long_Long_Long_Integer, as Value_Rep. Put_Integer_8/16/32/64, Put_Unsigned_8/16/32/64/128 take the integer value directly. Put_Float_32/64 takes the floating-point value. Put_Fixed_Point_8/16/32/64/128 takes the integer representation of the value together with the numerator and denominator of the type’s small, allowing the formatter to reconstruct the exact decimal value. Put_Address takes the address as a System.Address. Put_Access takes the raw storage elements of the access value. Put_Null_Access is called for a null access value; it takes only Type_Name, identifying the access type, with no representation to pass. Put_Big_Integer and Put_Big_Real are not yet defined; types with components of Ada.Numerics.Big_Numbers big-number types are not currently supported.

Record structure

Open_Record is called first with the fully qualified type name, followed by zero or more alternating calls to List_Discriminant or List_Component (each carrying the component name) and the corresponding value’s To_String. Close is called last. Task types use Open_Task in place of Open_Record, and include the runtime task identity via Put_UTF_8 before any discriminants. Open_Protected is reserved for a future correct implementation of protected-type To_String; see Default To_String Procedure.

Array structure

Open_Array is called first with the fully qualified type name. List_Components or List_Indexed_Components is then called to indicate whether index values will be provided with each element. List_First and List_Last each carry the dimension number (1-based); List_Last also carries Named, True when that dimension is enumeration-indexed. For a non-enumeration-indexed dimension, List_First and List_Last bracket the element’s To_String. For an enumeration-indexed dimension, the order is instead List_First, the index value’s To_String, List_Last, then the element’s To_String, so that List_Last can be used to emit a separator before the element rather than after it. Close is called last.

A dimension with a null range makes no List_First/List_Last calls of its own, nor any for the dimensions nested inside it. If that dimension is itself nested inside a non-null enumeration-indexed dimension, the enclosing index value is still shown, followed by a single further List_First call, with no matching List_Last, representing the resulting empty nested value. A non-enumeration- indexed dimension whose nested content is empty this way contributes nothing at that position, regardless of its own range.

String/character output

Put, Wide_Put, and Wide_Wide_Put write a String, Wide_String, or Wide_Wide_String directly to the buffer. Put_UTF_8 and Wide_Put_UTF_16 write UTF-encoded data.

Miscellaneous

New_Line requests a line break. Open is reserved for future use.