@system blocks and safer @trusted (ST) functions
jfondren
julian.fondren at gmail.com
Mon Jul 26 00:50:17 UTC 2021
On Monday, 26 July 2021 at 00:37:36 UTC, ag0aep6g wrote:
> What if favoriteNumber originally returns a ubyte, and
> favoriteElement takes an int[256]?
>
> ```d
> ubyte favoriteNumber() @safe { return 42; }
> int favoriteElement(ref int[256] array) @trusted
> {
> return array.ptr[favoriteNumber()];
> }
> ```
>
> To your reviewer, there's nothing wrong with favoriteElement,
> right?
>
> But later someone might change the return type of
> favoriteNumber to size_t and let it return 300. Badaboom:
> undefined behavior after touching @safe code.
That's a much more obviously program-affecting change though,
you're changing a function signature. It wouldn't make as
compelling an example of someone being surprised that they have
to review more than just a @safe function when that only that
function is changed.
If you do name the index type then you can do something like this
Nim translation of the Ada:
```nim
type
Array = array[50, int]
Index = range[0..49]
var myarray: Array
myarray[42] = 5
func favoriteNumber: Index = 42
func favoriteElement(arg: Array): int =
let i: Index = favoriteNumber()
return arg[i]
echo favoriteElement(myarray)
```
(But Nim disappoints here: if you change favoriteNumber to return
an int, and then change the number to 142, then Nim doesn't
complain at all about this code that assigns an int to a Index
variable.)
More information about the Digitalmars-d
mailing list