Are contracts intended for verifying @safety;

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Nov 7 12:24:25 PST 2016


On Monday, November 07, 2016 17:30:09 Somebody via Digitalmars-d-learn 
wrote:
> void moveFrom(int[] a, in int[] b) @trusted in{
>      assert(a.length >= b.length);
> } body {
>      memmove(cast(void*)a.ptr, cast(void*)b.ptr, b.length *
> int.sizeof);
> }
>
> Is this ok? And if not, how should it be done, preferably without
> changing the condition or memmove call?

That's a matter of debate. What you're saying is that the contract for the
function requires certain conditions be true for the function arguments, and
if they are true, then the function is @safe. And that's legitimate. But at
the same time, it doesn't absolutely guarantee @safety, because if the
caller passes arguments that violate the contract, and the function is
compiled with -release, then unsafe things will occur. So, you could mark
the function as @system, and then make it clear in the documentation that
the function's @safety depends on the function's arguments meeting the
pre-condition. So, the caller then knows when they can mark the call as
being @trusted.

There have been several discussions about @trusted over the last couple of
years (both in the newsgroup and on github), and I don't know what the
official stance on this sort of thing currently is. I know that at one
point, it was argued that @trusted functions were @safe so long as their
arguments were valid, but then you get stuff like

auto foo(int* arr, size_t index) @trusted
{
    return *(arr + index);
}

or

auto foo(int* arr, size_t length) @trusted
{
    return arr[0 .. length];
}

or

auto foo(int[], size_t index) @trusted
{
    return *(arr.ptr + index);
}

and it doesn't seem like a good idea to me to mark functions like that as
@trusted. It's too much like you're trying to have array indexing be marked
as @trusted while circumventing the array bounds checks without any
guarantee that the values are going to be valid.

So, while I don't know what the official stance is, I'd suggest having the
function be @trusted and having the documentation make it clear what the
preconditions are so that the calling function can be marked @trusted.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list