Non-techincal brain, is @safe by default good or not?
Johannes Loher
johannes.loher at fg4f.de
Thu May 28 11:07:16 UTC 2020
Am 28.05.20 um 12:28 schrieb Mathias LANG:
> ```
> import std.json;
>
> struct MyCustomType
> {
> public string toString () const @system { return null; }
> alias toString this;
> }
>
> void main () @system
> {
> JSONValue json;
> MyCustomType ilovedlang;
> json = ilovedlang;
> }
> ```
>
> Results in:
> ```
> /usr/local/opt/dmd/include/dlang/dmd/std/json.d(459): Error: @safe
> function std.json.JSONValue.assign!(MyCustomType).assign cannot call
> @system function foo.MyCustomType.toString
> foo.d(5): foo.MyCustomType.toString is declared here
> /usr/local/opt/dmd/include/dlang/dmd/std/json.d(593): Error: template
> instance std.json.JSONValue.assign!(MyCustomType) error instantiating
> foo.d(13): instantiated from here: opAssign!(MyCustomType)
> ```
>
Please file a bug report. `assign` is a template, it should not be
explicitly annotated with @safe but instead the attributes should be
inferred.
> ```
> import std.algorithm.mutation;
> struct S
> {
> void opPostMove(const ref S old) @system nothrow pure
> {
> int* ptr = cast(int*)42;
> *ptr = 42;
> }
> int a;
> }
> void main () @safe nothrow
> {
> S s1;
> s1.a = 41;
> S s2 = move(s1); // BOOM
> assert(s2.a == 42);
> }
> ```
>
> This compiles and crash just fine.
Again, please file a bug report. This is either a bug with @safe or
there is some @trusted in `move` (or one of the functions it calls) that
calls `opPostMove`.
Both of the examples you provide are bugs but I realize that there are
real examples of what you are trying to show. One situation where this
happens is if libraries have non-template functions that take a callback
as parameter. The library author has to make a decision whether to make
his function @safe, which requires all callbacks passed to it also to be
@safe, or to make it @system, which makes it unusable in @safe code,
even if it actually is safe because the callback that was passed is
@safe. @trusted allows both kinds of usages but is a really bad idea
because it allows unchecked @system code to be called from @safe code.
This is why some people in the community have suggested to allow
attribute inference also for non-template functions. That would solve
the issue might might be a better default than both @system and @safe.
However, I don't think anybody has thought that through completely yet.
Some people have voiced concerns regarding inheritance and .di files
(and probably more) but I think it might be possible to do this.
More information about the Digitalmars-d
mailing list