@system blocks and safer @trusted (ST) functions

jfondren julian.fondren at gmail.com
Mon Jul 26 00:08:51 UTC 2021


On Sunday, 25 July 2021 at 17:47:40 UTC, Paul Backus wrote:
> ```d
> module example;
>
> size_t favoriteNumber() @safe { return 42; }
>
> int favoriteElement(ref int[50] array) @trusted
> {
>     // This is memory safe because we know favoriteNumber 
> returns 42
>     @system {
>         return array.ptr[favoriteNumber()];
>     }
> }
> ```

favoriteElement(), all on its own, has an unchecked type error: 
array is indexed by the int return value of favoriteNumber(), but 
int has a range outside of the 0..49 type of array's indices.

In Ada, array's index type would be specified in the code and 
you'd have to either perform a checked type conversion to use 
favoriteNumber() there, or you'd have to change favoriteNumber() 
to return the index type rather than an int.

```ada
with Ada.Text_IO; use Ada.Text_IO;

procedure FavElm is
    subtype Index is Integer range 0 .. 49;
    type Arg is array (Index) of Integer;

    function favoriteNumber return Index is (142);

    function favoriteElement(A : Arg) return Integer is
    begin
       return A (favoriteNumber);
    end favoriteElement;

    MyArray : Arg := (42 => 5, others => 0);
begin
    Put_Line (Natural'Image (favoriteElement (MyArray)));
end FavElm;
```

which compiles with a warning, and fails at runtime as promised:

```
favelm.adb:7:45: warning: value not in range of type "Index" 
defined at line 4
favelm.adb:7:45: warning: "Constraint_Error" will be raised at 
run time
```

In a language with dependent types (or the theorem-proving 
variant of Ada, SPARK) you could get a compile time error, 
including from functions that return statically unknown values 
that still have the wrong type, like getchar() as mentioned 
elsewhere.

In such languages the thing you *should* be doing, testing an 
int's range before using it as an index for an int[50] array, is 
a compile-time error to not do. You're not forced to check it at 
every index, but you have to check it at some point.

This kind of precision with types isn't so pleasant in D but the 
class of error is the same and it's something a reviewer could 
spot when initially checking this code in.


More information about the Digitalmars-d mailing list