Safety, undefined behavior, @safe, @trusted

dsimcha dsimcha at yahoo.com
Thu Nov 5 10:45:04 PST 2009


== Quote from Walter Bright (newshound1 at digitalmars.com)'s article
> Following the safe D discussions, I've had a bit of a change of mind.
> Time for a new strawman.
> Based on Andrei's and Cardelli's ideas, I propose that Safe D be defined
> as the subset of D that guarantees no undefined behavior. Implementation
> defined behavior (such as varying pointer sizes) is still allowed.
> Memory safety is a subset of this. Undefined behavior nicely covers
> things like casting away const and shared.
> Safety has a lot in common with function purity, which is set by an
> attribute and verified by the compiler. Purity is a subset of safety.
> Safety seems more and more to be a characteristic of a function, rather
> than a module or command line switch. To that end, I propose two new
> attributes:
> @safe
> @trusted
> A function marked as @safe cannot use any construct that could result in
> undefined behavior. An @safe function can only call other @safe
> functions or @trusted functions.
> A function marked as @trusted is assumed to be safe by the compiler, but
> is not checked. It can call any function.
> Functions not marked as @safe or @trusted can call any function.
> To mark an entire module as safe, add the line:
>     @safe:
> after the module statement. Ditto for marking the whole module as
> @trusted. An entire application can be checked for safety by making
> main() safe:
>      @safe int main() { ... }
> This proposal eliminates the need for command line switches, and
> versioning based on safety.

Vote++.  The thing I like about it is that, if you've got a well-debugged function
that does some well-encapsulated unsafe things (performance hacks, etc.) and needs
to be called by safe functions, safety doesn't become viral and force you to
reexamine the implementation of your well-encapsulated unsafe function.  On the
other hand if you've got a function that does non-encapsulated unsafe things that
the caller has to understand in order to use it properly (e.g. something like
GC.setAttr, which can make regions of memory unscanned by the GC), this should
*not* be callable from safe code no matter what.

As long as I know that safety isn't going to be viral and force me to modify code
that's got tons of performance hacks internally but has a safe interface (and as
long as getopt gets fixed), I'm actually starting to like SafeD.



More information about the Digitalmars-d mailing list