Simplification of @trusted
Walter Bright
newshound2 at digitalmars.com
Fri Jun 18 02:07:17 UTC 2021
On 6/17/2021 12:15 PM, Sönke Ludwig wrote:
> Am 16.06.2021 um 23:22 schrieb Walter Bright:
>> On 6/16/2021 6:09 AM, Sönke Ludwig wrote:
>>> There are 800 of these in vibe.d alone.
>>
>> That is concerning. But it isn't necessarily cause for redesigning @trusted.
>> For example, I removed (in aggregate) a great deal of unsafe allocation code
>> from the backend simply by moving all that code into one resizable array
>> abstraction.
>>
>> Piece by piece, I've been removing the unsafe code from the backend. There
>> really should be very, very little of it.
>
> Many of them are external functions that are `@system` when they shouldn't have
> to be:
> - `() @trusted { return
> typeid(string).getHash(&ln); }()));`
> - `() @trusted { return allocatorObject(GCAllocator.instance); } ();`
> - `() @trusted { GC.addRange(mem.ptr, ElemSlotSize); } ()`
> - `() @trusted { return sanitize(ustr); } ()`
> - `() @trusted { return logicalProcessorCount(); } ()`
> - ...
>
> It could be that nowadays a number of those has been made `@safe` already, I'd
> have to check one-by-one.
>
> Then there are OS/runtime functions that are not `@safe`, but need to be called
> from a `@safe` context:
>
> - `() @trusted { return mkstemps(templ.ptr, cast(int)suffix.length); } ();`
> - ```
> @trusted {
> scope (failure) assert(false);
> return CreateFileW(...);
> } ();
> ```
> - ...
>
> There is also quite some manual memory management that requires `@trusted`. Once
> we are there with ownership (and ten compiler versions ahead) those can be
> replaced by some kind custom reference type.
>
> Then there are some shortcut references as pointers that are necessary because
> `ref` can't be used for local symbols (lifetime analysis could solve this, too):
>
> - `auto slot = () @trusted { return &m_core.m_handles[h]; } ();`
>
> There are surely some places that can be refactored to push `@trusted` further
> down, but right now most of them can't in a meaningful way.
Things like logicalProcessorCount() surely can be @safe.
m_core.m_handles[h] looks like it needs encapsulation in a proper function that
takes m_core and h as arguments.
I got rid of a *lot* of memory management code in the back end by creating a
container type to do it and prevent a safe interface.
Unsafe system calls like CreateFileW() can be encapsulated with a wrapper that
presents a safe interface.
Yes, this is extra work. But it's good work. I bet you'll like the result! I
sure have when I've done it.
More information about the Digitalmars-d
mailing list