Temporary @trusted scope

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 18 16:48:56 UTC 2018


On 12/18/18 10:53 AM, H. S. Teoh wrote:
> On Tue, Dec 18, 2018 at 08:52:29AM -0500, Steven Schveighoffer via Digitalmars-d-learn wrote:
>> On 12/18/18 6:29 AM, Simen Kjærås wrote:
>>> On Tuesday, 18 December 2018 at 10:14:50 UTC, Per Nordlöw wrote:
>>>> What's the preferred way of creating a temporary @trusted scope
>>>> without writing a separate  function?
>>>
>>> Jonathan's idea might also be encapsulated in a function, just like
>>> assumeUnique in Phobos:
>>>
>>> import std.stdio;
>>>
>>> template unsafe(alias fn) {
>>>       @trusted auto unsafe(T...)(T args) {
>>>           return fn(args);
>>>       }
>>> }
>>>
>>> @system void fun(int n) {
>>>       writeln("foo!");
>>> }
>>>
>>> @safe unittest {
>>>       unsafe!({
>>>           fun(2);
>>>       });
>>>
>>>       unsafe!fun(2);
>>> }
>>
>> Wow, I really like this. The only real problem is that one generally
>> searches for @trusted when looking for unsafe code, but unsafe is
>> pretty obvious too. Also, args should be auto ref.
>>
>> Only thing better I can think of (for the second example) is to define
>> a prototype with the correct information, only with @trusted (and
>> specify the mangle). But any decent compiler should get rid of any
>> overhead there.
> [...]
> 
> I'm not so sure I like this. @trusted bits of code really should have a
> safe API that cannot be called in a way that breaks @safe. Being able to
> essentially "cast away" @safe for arbitrary bits of code seems to me to
> be a rather scary, underhanded way of undermining @safe.

You may not be realizing what the point of this is. Essentially, you 
replace your inline trusted lambda with this call.

It's just nicer syntax/usage without all the extra parentheses. Other 
than that, every usage of it would need as much scrutiny as a trusted 
lambda.

> OTOH, if your function is very large and only isolated bits are
> non- at safe, then a construct like this one could help, by making the code
> less noisy, and ensuring that the other parts of the code still remain
> @safe. (Though IMO in such cases the function may be better refactored
> to encapsulate away the @trusted bits in functions with safe APIs, and
> keep the @safe code all in one place.)

Yes, exactly. The point of trusted lambdas are so that only the parts 
you want to trust are actually trusted, the rest of the function is 
safe. It doesn't prevent you from having to locally verify that 
implementation leaks don't happen (for example, ()@trusted 
{free(ptr);}() can still leak dangling pointers out into the @safe 
portion), but it allows you to focus where your code is trusted.

For more details, see this: 
https://dlang.org/blog/2016/09/28/how-to-write-trusted-code-in-d/

-Steve


More information about the Digitalmars-d-learn mailing list