Annotated Ada Reference ManualLegal Information
Table of Contents   Index   References   Search   Previous   Next 

 4.6 Type Conversions

1
[Explicit type conversions, both value conversions and view conversions, are allowed between closely related types as defined below. This clause also defines rules for value and view conversions to a particular subtype of a type, both explicit ones and those implicit in other constructs. {subtype conversion: See type conversion} {type conversion} {conversion} {cast: See type conversion} ]{subtype conversion: See also implicit subtype conversion} {type conversion, implicit: See implicit subtype conversion}

Syntax

2
type_conversion ::= 
    subtype_mark(expression)
  | subtype_mark(name)
3
{target subtype (of a type_conversion)} The target subtype of a type_conversion is the subtype denoted by the subtype_mark. {operand (of a type_conversion)} The operand of a type_conversion is the expression or name within the parentheses; {operand type (of a type_conversion)} its type is the operand type.
4
{convertible} One type is convertible to a second type if a type_conversion with the first type as operand type and the second type as target type is legal according to the rules of this clause. Two types are convertible if each is convertible to the other. 
4.a
Ramification: Note that “convertible” is defined in terms of legality of the conversion. Whether the conversion would raise an exception at run time is irrelevant to this definition.
5/2
{8652/0017} {AI-00184-01} {AI-00330-01} {view conversion} {conversion (view)} A type_conversion whose operand is the name of an object is called a view conversion if both its target type and operand type are is tagged, or if it appears in a call as an actual parameter of mode out or in out; {value conversion} {conversion (value)} other type_conversions are called value conversions. {super: See view conversion}
5.a
Ramification: A view conversion to a tagged type can appear in any context that requires an object name, including in an object renaming, the prefix of a selected_component, and if the operand is a variable, on the left side of an assignment_statement. View conversions to other types only occur as actual parameters. Allowing view conversions of untagged types in all contexts seemed to incur an undue implementation burden.
5.b/2
{AI-00330-01} A type conversion appearing as an in out parameter in a generic instantiation is not a view conversion; the second part of the rule only applies to subprogram calls, not instantiations.

Name Resolution Rules

6
{expected type (type_conversion operand) [partial]} The operand of a type_conversion is expected to be of any type. 
6.a
Discussion: This replaces the "must be determinable" wording of Ada 83. This is equivalent to (but hopefully more intuitive than) saying that the operand of a type_conversion is a “complete context.” 
7
The operand of a view conversion is interpreted only as a name; the operand of a value conversion is interpreted as an expression
7.a
Reason: This formally resolves the syntactic ambiguity between the two forms of type_conversion, not that it really matters. 

Legality Rules

8/2
{AI95-00251-01} In a view conversion for an untagged type, the target type shall be convertible (back) to the operand type. {type conversion (numeric)} {conversion (numeric)} If the target type is a numeric type, then the operand type shall be a numeric type. 
8.a/2
Reason: Untagged view conversions appear only as [in] out parameters. Hence, the reverse conversion must be legal as well. The forward conversion must be legal even for an out parameter, because (for example) actual parameters of an access type are always copied in anyway.
Paragraphs 9 through 20 were reorganized and moved below. 
8.b/2
Discussion: {AI95-00251-01} The entire Legality Rules section has been reorganized to eliminate an unintentional incompatibility with Ada 83. In rare cases, a type conversion between two types related by derivation is not allowed by Ada 95, while it is allowed in Ada 83. The reorganization fixes this. Much of the wording of the legality section is unchanged, but it is reordered and reformatted. Because of the limitations of our tools, we had to delete and replace nearly the entire section. The text of Ada 95 paragraphs 8 through 12, 14, 15, 17, 19, 20, and 24 are unchanged (just moved); these are now 24.1 through 24.5, 24.12, 24.13, 24.17, 24.19, 24.20, and 8. 
9/2
{AI95-00251-01} {type conversion (array)} {conversion (array)} If the target type is an array type, then the operand type shall be an array type. Further: 
10/2
11/2
12/2
12.1/2
12.a.1/2
Reason: Without this rule, it is possible to violate the constrained status of aliased array components. Consider:
12.a.2/2
package P is
   type T is private;
   A : constant T;
   type A1 is array (1 .. 10) of aliased T;
   type A2 is array (1 .. 10) of T;
private
   type T (D : Integer := 0) is null record;
   A : constant T := (D => 1);
end P;
12.a.3/2
with P;
procedure Exam is
   X : P.A1;
   procedure S (Y : in out P.A2) is
   begin
      Y (1) := P.A;
   end;
begin
   S (P.A2 (X)); -- This call will change the discriminant of X (1),
                 -- so we cannot allow the conversion.
end;
13/2
 {AI95-00251-01} {type conversion (access)} {conversion (access)} If the target type is a general access type, then the operand type shall be an access-to-object type. Further: 
13.a/2
Discussion: The Legality Rules and Dynamic Semantics are worded so that a type_conversion T(X) (where T is an access type) is (almost) equivalent to the attribute_reference X.all'Access, where the result is of type T. The type_conversion accepts a null value, whereas the attribute_reference would raise Constraint_Error. 
14/2
14.a/2
Ramification: If the target type is an access-to-constant type, then the operand type can be access-to-constant or access-to-variable. 
15/2
16/2
16.a/2
Reason: These rules are designed to ensure that aliased array objects only need "dope" if their nominal subtype is unconstrained, but they can always have dope if required by the run-time model (since no sliding is permitted as part of access type conversion). By contrast, aliased discriminated objects will always need their discriminants stored with them, even if nominally constrained. (Here, we are assuming an implementation that represents an access value as a single pointer.) 
17/2
17.a/2
Ramification: The access parameter case is handled by a run-time check. Run-time checks are also done in instance bodies. 
18/2
 {AI95-00251-01} {type conversion (access)} {conversion (access)} If the target type is an access-to-subprogram type, then the operand type shall be an access-to-subprogram type. Further:
19/2
20/2
20.a/2
Reason: The reason it is illegal to convert from an access-to-subprogram type declared in a generic body to one declared outside that body is that in an implementation that shares generic bodies, procedures declared inside the generic need to have a different calling convention — they need an extra parameter pointing to the data declared in the current instance. For procedures declared in the spec, that's OK, because the compiler can know about them at compile time of the instantiation. 
21/2
 {AI95-00251-01} {type conversion (composite (non-array))} {conversion (composite (non-array))} If there is a type that is an ancestor of both the target type and the operand type, or both types are class-wide types, then at least one of the following rules shall apply: {type conversion (enumeration)} {conversion (enumeration)} If the target type is not included in any of the above four cases, there shall be a type that is an ancestor of both the target type and the operand type. Further, if the target type is tagged, then either: 
21.1/2
22
22.a
Ramification: This is a conversion toward the root, which is always safe. 
23/2
23.a
Ramification: This is a conversion of a class-wide type toward the leaves, which requires a tag check. See Dynamic Semantics.
23.b/2
{AI95-00251-01} These two rules imply that a conversion from an ancestor a parent type to a type extension is not permitted, as this would require specifying the values for additional components, in general, and changing the tag. An extension_aggregate has to be used instead, constructing a new value, rather than converting an existing value. However, a conversion from the class-wide type rooted at an ancestor the parent type is permitted; such a conversion just verifies that the operand's tag is a descendant of the target. 
23.1/2
23.c/2
Ramification: We allow converting any class-wide type T'Class to or from a class-wide interface type even if the specific type T does not have an appropriate interface ancestor, because some extension of T might have the needed ancestor. This is similar to a conversion of a class-wide type toward the leaves of the tree, and we need to be consistent. Of course, there is a run-time check that the actual object has the needed interface.
24/2
 {AI95-00251-01} If there is no type that is the ancestor of both the target type and the operand type, and they are not both class-wide types, one of the following rules shall apply: In a view conversion for an untagged type, the target type shall be convertible (back) to the operand type. 
24.a/2
This paragraph was deleted.Reason: Untagged view conversions appear only as [in] out parameters. Hence, the reverse conversion must be legal as well. The forward conversion must be legal even if an out parameter, because actual parameters of an access type are always copied in anyway. 
24.1/2
24.2/2
24.3/2
24.4/2
24.5/2
24.6/2
24.b/2
Reason: For unrelated array types, the component types could have different accessibility, and we had better not allow a conversion of a local type into a global type, in case the local type points at local objects. We don't need a check for other types of components; such components necessarily are for related types, and either have the same accessibility or (for access discriminants) cannot be changed so the discriminant check will prevent problems. 
24.7/2
24.c/2
Reason: We cannot allow conversions between unrelated limited types, as they may have different representations, and (since the types are limited), a copy cannot be made to reconcile the representations. 
24.8/2
24.d/2
Reason: {AI95-00363-01} We cannot allow a view conversion from an object with unaliased components to an object with aliased components, because that would effectively allow pointers to unaliased components. This rule was missing from Ada 95. 
24.9/2
24.e/2
Reason: {AI95-00246-01} We cannot allow view conversions between unrelated might-be-by-reference types, as they may have different representations, and a copy cannot be made to reconcile the representations. 
24.f/2
Ramification: These rules only apply to unrelated array conversions; different (weaker) rules apply to conversions between related types. 
24.10/2
24.g/2
Discussion: Such a conversion cannot be written explicitly, of course, but it can be implicit (see below). 
24.11/2
24.h/2
Discussion: The Legality Rules and Dynamic Semantics are worded so that a type_conversion T(X) (where T is an access type) is (almost) equivalent to the attribute_reference X.all'Access, where the result is of type T. The only difference is that the type_conversion accepts a null value, whereas the attribute_reference would raise Constraint_Error. 
24.12/2
24.i/2
Ramification: If the target type is an access-to-constant type, then the operand type can be access-to-constant or access-to-variable. 
24.13/2
24.14/2
24.15/2
24.16/2
24.j/2
Ramification: {AI95-00363-01} This does not require that types have a partial view in order to allow the conversion, simply that any partial view that does exist is unconstrained.
24.k/2
{AI95-00384-01} This allows conversions both ways (either subtype can be unconstrained); while Ada 95 only allowed the conversion if the target subtype is unconstrained. We generally want type conversions to be symmetric; which type is the target shouldn't matter for legality.
24.l/2
Reason: {AI95-00363-01} If the visible partial view is constrained, we do not allow conversion between unconstrained and constrained subtypes. This means that whether the full type had discriminants is not visible to clients of the partial view. 
24.m/2
Reason: These rules are designed to ensure that aliased array objects only need "dope" if their nominal subtype is unconstrained, but they can always have dope if required by the run-time model (since no sliding is permitted as part of access type conversion). By contrast, aliased discriminated objects will always need their discriminants stored with them, even if nominally constrained. (Here, we are assuming an implementation that represents an access value as a single pointer.) 
24.17/2
24.n/2
Ramification: The access parameter case is handled by a run-time check. Run-time checks are also done in instance bodies. 
24.18/2
24.o/2
Reason: This allows null to be converted to pool-specific types. Without it, null could be converted to general access types but not pool-specific ones, which would be too inconsistent. Remember that these rules only apply to unrelated types, so we don't have to talk about conversions to derived or other related types. 
24.19/2
24.20/2
24.21/2
24.p/2
Reason: The reason it is illegal to convert from an access-to-subprogram type declared in a generic body to one declared outside that body is that in an implementation that shares generic bodies, procedures declared inside the generic need to have a different calling convention — they need an extra parameter pointing to the data declared in the current instance. For procedures declared in the spec, that's OK, because the compiler can know about them at compile time of the instantiation. 

Static Semantics

25
A type_conversion that is a value conversion denotes the value that is the result of converting the value of the operand to the target subtype.
26
A type_conversion that is a view conversion denotes a view of the object denoted by the operand. This view is a variable of the target type if the operand denotes a variable; otherwise it is a constant of the target type.
27
{nominal subtype (associated with a type_conversion) [partial]} The nominal subtype of a type_conversion is its target subtype. 

Dynamic Semantics

28
{evaluation (value conversion) [partial]} {corresponding value (of the target type of a conversion)} {conversion} For the evaluation of a type_conversion that is a value conversion, the operand is evaluated, and then the value of the operand is converted to a corresponding value of the target type, if any. {Range_Check [partial]} {check, language-defined (Range_Check)} {Constraint_Error (raised by failure of run-time check)} If there is no value of the target type that corresponds to the operand value, Constraint_Error is raised[; this can only happen on conversion to a modular type, and only when the operand value is outside the base range of the modular type.] Additional rules follow: 
29
30
31
32
32.a
Discussion: An integer type might have more bits of precision than a real type, so on conversion (of a large integer), some precision might be lost. 
33
33.a/2
Discussion: {AI95-00267-01} This was implementation defined in Ada 83. There seems no reason to preserve the nonportability in Ada 95. Round-away-from-zero is the conventional definition of rounding, and standard Fortran and COBOL both specify rounding away from zero, so for interoperability, it seems important to pick this. This is also the most easily “undone” by hand. Round-to-nearest-even is an alternative, but that is quite complicated if not supported by the hardware. In any case, this operation is not usually expected to be part of an inner loop, so predictability and portability are judged most important. A We anticipate that a floating point attribute function Unbiased_Rounding is will be provided (see A.5.3) for those applications that require round-to-nearest-even, and a floating point attribute function Machine_Rounding (also see A.5.3) is provided for those applications that require the highest possible performance. “Deterministic” rounding is required for static conversions to integer as well. See 4.9.
34
35
36
37
38
38.a
Discussion: Only nonnull index ranges are checked, per AI83-00313. 
39
39.a
Ramification: This applies whether or not the component is initialized. 
39.1/2
39.b/2
Reason: This check is needed for operands that are access parameters and in instance bodies. Other cases are handled by the legality rule given previously.
40
41
41.a
Ramification: This applies whether or not the component is initialized. 
42
42.a
Ramification: This check is certain to succeed if the operand type is itself covered by or descended from the target type. 
42.b
Proof: The fact that a type_conversion preserves the tag is stated officially in 3.9, “Tagged Types and Type Extensions
43
44
44.a
Ramification: It is a ramification of the rules for the discriminants of derived types that each discriminant of the result is covered either by this paragraph or the previous one. See 3.7
45
46
47
48
48.a
Ramification: This check is needed for operands that are access parameters and in instance bodies.
48.b
Note that this check can never fail for the implicit conversion to the anonymous type of an access parameter that is done when calling a subprogram with an access parameter. 
49/2
49.a/2
Ramification: A conversion to an anonymous access type happens implicitly as part of initializing or assigning to an anonymous access object an access discriminant or access parameter
49.b/2
This paragraph was deleted.Reason: {AI95-00231-01} As explained in 3.10, “Access Types”, it is important that a value of an anonymous access type can never be null. 
50
50.a
Ramification: The checks are certain to succeed if the target and operand designated subtypes statically match.
51/2
 {AI95-00231-01} {Range_Check [partial]} {check, language-defined (Range_Check)} {Discriminant_Check [partial]} {check, language-defined (Discriminant_Check)} {Index_Check [partial]} {check, language-defined (Index_Check)} {Access_Check [partial]} {check, language-defined (Access_Check)} After conversion of the value to the target type, if the target subtype is constrained, a check is performed that the value satisfies this constraint. If the target subtype excludes null, then a check is made that the value is not null. 
51.a/2
Ramification: {AI95-00231-01} The first above check above is a Range_Check for scalar subtypes, a Discriminant_Check or Index_Check for access subtypes, and a Discriminant_Check for discriminated subtypes. The Length_Check for an array conversion is performed as part of the conversion to the target type. The check for exclusion of null is an Access_Check.
52
{evaluation (view conversion) [partial]} For the evaluation of a view conversion, the operand name is evaluated, and a new view of the object denoted by the operand is created, whose type is the target type; {Length_Check [partial]} {check, language-defined (Length_Check)} {Tag_Check [partial]} {check, language-defined (Tag_Check)} {Discriminant_Check [partial]} {check, language-defined (Discriminant_Check)} if the target type is composite, checks are performed as above for a value conversion.
53
The properties of this new view are as follows: 
54/1
55
56
56.a
Reason: This ensures that even an out parameter of an access type is initialized reasonably. 
57
{Program_Error (raised by failure of run-time check)} {Constraint_Error (raised by failure of run-time check)} If an Accessibility_Check fails, Program_Error is raised. Any other check associated with a conversion raises Constraint_Error if it fails.
58
Conversion to a type is the same as conversion to an unconstrained subtype of the type. 
58.a
Reason: This definition is needed because the semantics of various constructs involves converting to a type, whereas an explicit type_conversion actually converts to a subtype. For example, the evaluation of a range is defined to convert the values of the expressions to the type of the range. 
58.b
Ramification: A conversion to a scalar type, or, equivalently, to an unconstrained scalar subtype, can raise Constraint_Error if the value is outside the base range of the type.
NOTES
59
20  {implicit subtype conversion [distributed]} In addition to explicit type_conversions, type conversions are performed implicitly in situations where the expected type and the actual type of a construct differ, as is permitted by the type resolution rules (see 8.6). For example, an integer literal is of the type universal_integer, and is implicitly converted when assigned to a target of some specific integer type. Similarly, an actual parameter of a specific tagged type is implicitly converted when the corresponding formal parameter is of a class-wide type.
60
{implicit subtype conversion [distributed]} {Constraint_Error (raised by failure of run-time check)} Even when the expected and actual types are the same, implicit subtype conversions are performed to adjust the array bounds (if any) of an operand to match the desired target subtype, or to raise Constraint_Error if the (possibly adjusted) value does not satisfy the constraints of the target subtype.
61/2
21  {AI95-00230-01} A ramification of the overload resolution rules is that the operand of an (explicit) type_conversion cannot be the literal nullan allocator, an aggregate, a string_literal, a character_literal, or an attribute_reference for an Access or Unchecked_Access attribute. Similarly, such an expression enclosed by parentheses is not allowed. A qualified_expression (see 4.7) can be used instead of such a type_conversion.
62
22  The constraint of the target subtype has no effect for a type_conversion of an elementary type passed as an out parameter. Hence, it is recommended that the first subtype be specified as the target to minimize confusion (a similar recommendation applies to renaming and generic formal in out objects). 

Examples

63
Examples of numeric type conversion: 
64
Real(2*J)      --  value is converted to floating point
Integer(1.6)   --  value is 2
Integer(-0.4)  --  value is 0
65
Example of conversion between derived types: 
66
type A_Form is new B_Form;
67
X : A_Form;
Y : B_Form;
68
X := A_Form(Y);
Y := B_Form(X);  --  the reverse conversion 
69
Examples of conversions between array types: 
70
type Sequence is array (Integer range <>) of Integer;
subtype Dozen is Sequence(1 .. 12);
Ledger : array(1 .. 100) of Integer;
71
Sequence(Ledger)            --  bounds are those of Ledger
Sequence(Ledger(31 .. 42))  --  bounds are 31 and 42
Dozen(Ledger(31 .. 42))     --  bounds are those of Dozen 

Incompatibilities With Ada 83

71.a
{incompatibilities with Ada 83} A character_literal is not allowed as the operand of a type_conversion, since there are now two character types in package Standard.
71.b
The component subtypes have to statically match in an array conversion, rather than being checked for matching constraints at run time.
71.c
Because sliding of array bounds is now provided for operations where it was not in Ada 83, programs that used to raise Constraint_Error might now continue executing and produce a reasonable result. This is likely to fix more bugs than it creates. 

Extensions to Ada 83

71.d
{extensions to Ada 83} A type_conversion is considered the name of an object in certain circumstances (such a type_conversion is called a view conversion). In particular, as in Ada 83, a type_conversion can appear as an in out or out actual parameter. In addition, if the target type is tagged and the operand is the name of an object, then so is the type_conversion, and it can be used as the prefix to a selected_component, in an object_renaming_declaration, etc.
71.e
We no longer require type-mark conformance between a parameter of the form of a type conversion, and the corresponding formal parameter. This had caused some problems for inherited subprograms (since there isn't really a type-mark for converted formals), as well as for renamings, formal subprograms, etc. See AI83-00245, AI83-00318, AI83-00547.
71.f
We now specify “deterministic” rounding from real to integer types when the value of the operand is exactly between two integers (rounding is away from zero in this case).
71.g
“Sliding” of array bounds (which is part of conversion to an array subtype) is performed in more cases in Ada 95 than in Ada 83. Sliding is not performed on the operand of a membership test, nor on the operand of a qualified_expression. It wouldn't make sense on a membership test, and we wish to retain a connection between subtype membership and subtype qualification. In general, a subtype membership test returns True if and only if a corresponding subtype qualification succeeds without raising an exception. Other operations that take arrays perform sliding. 

Wording Changes from Ada 83

71.h
We no longer explicitly list the kinds of things that are not allowed as the operand of a type_conversion, except in a NOTE.
71.i
The rules in this clause subsume the rules for "parameters of the form of a type conversion," and have been generalized to cover the use of a type conversion as a name.

Incompatibilities With Ada 95

71.j/2
{AI95-00246-01} {incompatibilities with Ada 95} Amendment Correction: Conversions between unrelated array types that are limited or (for view conversions) might be by-reference types are now illegal. The representations of two such arrays may differ, making the conversions impossible. We make the check here, because legality should not be based on representation properties. Such conversions are likely to be rare, anyway. There is a potential that this change would make a working program illegal (if the types have the same representation).
71.k/2
{AI95-00363-01} If a discriminated full type has a partial view (private type) that is constrained, we do not allow conversion between access-to-unconstrained and access-to-constrained subtypes designating the type. Ada 95 allowed this conversion and the declaration of various access subtypes, requiring that the designated object be constrained and thus making details of the implementation of the private type visible to the client of the private type. See 4.8 for more on this topic. 

Extensions to Ada 95

71.l/2
{AI95-00230-01} {extensions to Ada 95} Conversion rules for universal_access were defined. These allow the use of anonymous access values in equality tests (see 4.5.2), and also allow the use of null in type conversions and other contexts that do not provide a single expected type.
71.m/2
{AI95-00384-01} A type conversion from an access-to-discriminated and unconstrained object to an access-to-discriminated and constrained one is allowed. Ada 95 only allowed the reverse conversion, which was weird and asymmetric. Of course, a constraint check will be performed for this conversion. 

Wording Changes from Ada 95

71.n/2
{8652/0017} {AI95-00184-01} Corrigendum: Wording was added to ensure that view conversions are constrained, and that a tagged view conversion has a tagged object. Both rules are needed to avoid having a way to change the discriminants of a constrained object.
71.o/2
{8652/0008} {AI95-00168-01} Corrigendum: Wording was added to ensure that the aliased status of array components cannot change in a view conversion. This rule was needed to avoid having a way to change the discriminants of an aliased object. This rule was repealed later, as Ada 2005 allows changing the discriminants of an aliased object.
71.p/2
{AI95-00231-01} Wording was added to check subtypes that exclude null (see 3.10).
71.q/2
{AI95-00251-01} The organization of the legality rules was changed, both to make it clearer, and to eliminate an unintentional incompatibility with Ada 83. The old organization prevented type conversions between some types that were related by derivation (which Ada 83 always allowed).
71.r/2
{AI95-00330-01} Clarified that an untagged type conversion appearing as a generic actual parameter for a generic in out formal parameter is not a view conversion (and thus is illegal). This confirms the ACATS tests, so all implementations already follow this intepretation.
71.s/2
{AI95-00363-01} Rules added by the Corrigendum to eliminate problems with discriminants of aliased components changing were removed, as we now generally allow discriminants of aliased components to be changed.
71.t/2
{AI95-00392-01} Accessibility checks on conversions involving types with anonymous access components were added. These components have the level of the type, and conversions can be between types at different levels, which could cause dangling access values in the absence of such checks. 

Table of Contents   Index   References   Search   Previous   Next 
Ada-Europe Sponsored by Ada-Europe