Simplification of @trusted
Ola Fosheim Grøstad
ola.fosheim.grostad at gmail.com
Thu Jun 17 11:16:47 UTC 2021
On Thursday, 17 June 2021 at 10:57:01 UTC, ag0aep6g wrote:
> The function you describe simply can't be @trusted. If you need
> to call a function with a zero-terminated string, and you
> cannot afford to check that the string is indeed
> zero-terminated, then you just can't guarantee safety. A
> function that is not guaranteed to be safe is @system, not
> @trusted.
That basically means that all interesting system level code is
@system, including all the code that calls it. That also means
that you prevent system level programmers from benefiting from
language safety checks!?
Here is the problem with that viewpoint, there is no way for the
function to prove that the memory it receives has not been freed.
So there is in fact no way for the function to ensure that it is
@trusted. That applies to @safe functions too. There has to be a
contract between caller and callee, those are the invariants that
the unsafe code (and safe code) depends on.
So I strongly disagree with the viewpoint that @trusted cannot
assume invariants to hold for the data it receives. That is
mandatory for all correct code of some complexity.
For instance, in order to make the dmd lexer @trusted you would
then require the lexer to do the allocation itself. If it accepts
a filebuffer allocated outside the lexer then there is no way for
the lexer to ensure that the sentinels (zeros at the end) are not
overwritten by other code.
That is an unreasonable restriction that makes @trusted and @safe
useless. The lexer should be allowed to assume that the
invariants of the filebuffer holds when it takes ownership of it.
It is difficult to prove without language level unique ownership,
but it is unreasonable to make the lexer and everything that
calls it @system, just because it accepts a filebuffer object.
> That's also not a valid @trusted function. "It's safe as long
> as [some condition that's not guaranteed by the language]"
> describes an @system function, not an @trusted one.
What are the invariants that are guaranteed by the language in a
multi-threaded program that calls C code?
What can you depend on?
Is it at all possible to write a performant 3D game that isn't
@system?
> If you want to be extra clever and exploit conditions that are
> not guaranteed by the language, then you either have to make
> sure inside the @trusted function that the conditions are
> actually met, or you settle for @system.
But that is the signature of a very high level language, not of a
system level language. In system level programming you cannot
have dynamic checks all over the place, except in debug builds.
> True system level programming is going to be @system in D. I
> don't think that's much of a surprise.
That makes Rust a much better option for people who cares about
safety. That is a problem.
More information about the Digitalmars-d
mailing list