Is possible in Ada a discontinuous subtype definition?

Viewed 123

Let's suppose I have the following constants in order to define a subtype that only admits valid values within its range definition:

type Unsigned_4_T is mod 2**4;

valid_1   : constant Unsigned_4_T := 0;
valid_2   : constant Unsigned_4_T := 1;
invalid_1 : constant Unsigned_4_T := 2;
valid_3   : constant Unsigned_4_T := 3;

Now, I would like to define a subtype VALID_VALUES_T of Unsigned_4_T in a way that it only accepts the valid values using the constants valid_1, valid_2 and valid_3.

I have been trying to achieve that using a Static_Predicate but, when I declare a variable of the wanted subtype and I assign the invalid_1 value, there is no constraint nor compilation error as I expected.

1 Answers

The AdaCore compiler requires you to enable assertions to generate the exception you need. Compile your program with the -gnata flag.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Exceptions; use Ada.Exceptions;
with System.Assertions; use System.Assertions;

procedure Main is
   type Unsigned is mod 2**4;
   subtype discontinuous is Unsigned with
     Static_Predicate => discontinuous in 0 | 1 | 3;
   Num : discontinuous;
begin
   for I in Unsigned'Range loop
      Num := I;
      Put_Line(Num'Image);
   end loop;
exception
   when E :Assert_Failure =>
      Put_Line("Invalid value assigned to Num: " & Exception_Message(E));
end Main;

The output of the program is:

    
 0
 1
Invalid value assigned to Num: Static_Predicate failed at main.adb:12
Related