Are contracts intended for verifying @safety;
Somebody via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Nov 7 12:38:00 PST 2016
On Monday, 7 November 2016 at 20:24:25 UTC, Jonathan M Davis
wrote:
>
> 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.
>
All pure functions which a programmer, save for a blackhat
perhaps, has any reason to use are @safe with correct arguments.
So we would have no use for @safe when we have @pure, were that
argument about arguments wise to follow. So I agree with you that
they definitely would be a bad idea without contracts. However,
with contracts, as you said, it is less clear.
> 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
I reckon you meant marking the calling function @safe?
More information about the Digitalmars-d-learn
mailing list