AdaCore / ada-spark-rfcs

Platform to submit RFCs for the Ada & SPARK languages
62 stars 28 forks source link

[feature] Allow a discriminant to constrain a scalar type in a record #72

Open WRidder opened 3 years ago

WRidder commented 3 years ago

Summary

Allow a discriminant to constrain a scalar type in a record. For related MR RFC, see: #68.

Motivation

An example of use:


   type ChangeList is array (Natural range <>) of CacheChange;
   protected type HistoryCache (CacheSize : Positive) is
      procedure add_change (a_change : in CacheChange);
      procedure remove_change (a_change : out CacheChange);
   private
      changes : ChangeList (1 .. CacheSize);
      count : Natural range 1 .. CacheSize := 0;
   end HistoryCache;

Using GNAT Community 2020 (20200818-93), the compiler will throw the following error: discriminant cannot constrain scalar type

Given that in ADA 2012 a composite type can be parameterized using a discrimant, a range (consisting of a bound based on a discriminant value) specified for a scalar field would result in a constant range declaration.

References:

Caveats and alternatives

As discussed in the Computer-programming-forum.com thread [1], a similar approach is employing the following construct:

  generic
    CacheSize : in POSITIVE;
  package HistoryCache is
    type count is Natural range 0 .. CacheSize;
    changes : ChangeList (1 .. CacheSize);
  end Queue;

Would love to hear some thoughts on this matter.