Yet another leak in the sinking ship of @safe

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Thu Feb 18 12:14:08 PST 2016


On 2/18/16 2:25 PM, H. S. Teoh via Digitalmars-d wrote:
> On Thu, Feb 18, 2016 at 01:58:24PM -0500, Steven Schveighoffer via Digitalmars-d wrote:
>> On 2/18/16 11:37 AM, H. S. Teoh via Digitalmars-d wrote:
>>> While @safe is a good idea in principle, the current implementation
>>> is rather lackluster.
>>
>> IMO, I think safe code should disallow casting that doesn't involve a
>> runtime function that verifies safety (such as casting an object to
>> another type, or invoking a @safe opCast), including casting array
>> types.
>
> But isn't casting from, say, long[] to int[] @safe? Last time I checked,
> druntime does actually convert .length correctly as well, so that
> converting, say, int[] to long[] won't let you overrun the array by
> accessing the last elements of the long[].

Probably. But there is always @trusted escapes. We are guaranteed 
@safety if we just disallow casting whatsoever.

It doesn't sit well with me that casting is a standard mechanism to use 
in @safe code. Casting is supposed to be a red flag. Even converting 
between object types, I think casting is just a terrible requirement.

Maybe it's too restrictive, I don't know. It's unlikely to happen in any 
case.

> But obviously casting Object[] to long[] would be a very bad idea, and
> should not be allowed in @safe. Scarily enough, this code currently
> compiles without any complaint from the compiler:
>
> 	void main() @safe
> 	{
> 		Object[] objs = [ new Object() ];
> 		long[] longs = cast(long[]) objs;
> 		longs[0] = 12345;
> 	}
>
> Yikes. Apparently you don't even need void[] to break @safe here. :-(

The difference here is that you have a cast. Casting to void[] doesn't 
require one.

>> And implicit casts to void[] should be disallowed.
>>
>> This would be a painful restriction, which is why I think it won't
>> happen :(
> [...]
>
> As far as I can tell, implicit casting to const(void)[] shouldn't be a
> cause for concern -- if all you can do with it is to read the data
> (e.g., a hexdump debugging function for printing out the byte
> representation of something), there shouldn't be any problems. It's when
> you write to the void[] that bad things begin to happen.

Possibly casting to const(T)[] should be OK for @safe code. But again, a 
conservative approach that disallows casts is what I would do. Note that 
you can't print out bytes from a void[], you would need a ubyte[].

-Steve


More information about the Digitalmars-d mailing list