Unexpected range assignment behaviour

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jul 19 21:27:35 UTC 2024


On Friday, July 19, 2024 12:02:55 PM MDT H. S. Teoh via Digitalmars-d-learn 
wrote:
> On Fri, Jul 19, 2024 at 05:48:37PM +0000, Dennis via Digitalmars-d-learn 
wrote:
> > On Friday, 19 July 2024 at 17:20:22 UTC, matheus wrote:
> > > couldn't this case for example be caught during the compiling time?
> >
> > The RangeError is only thrown when at runtime, the key doesn't exist,
> > so that can't be caught. The real problem is implicit slicing of
> > static arrays, which I'm not a fan of, but removing it is a breaking
> > change. So perhaps Associative Arrays should be enhanced to create
> > keys on slice assignment.
>
> IMO, implicit slicing of static arrays ought to be killed with fire.
> This is not the first time it has caused problems.  In the past it used
> to cause issues with the implicit slice escaping the scope of the
> original static array, leading to dangling pointers and subsequent
> memory corruption / UB.  With -dip1000 the situation has somewhat
> improved, but not entirely. It still causes nasty surprises when a slice
> was implicitly taken where it was unexpected.  This case here is another
> example of the problems that it causes.

Very, very hot fire. :)

IIRC, Atila has indicated that he would like to kill implicit slicing of
static arrays (though that's going to require that we have actually started
doing Editions first), so we may end up finally getting rid of it. I don't
know how much convincing it will take for Walter though.

I actually brought this up with Walter years ago at one of the dconfs in
Berlin, suggesting that it was a big @safety mistake, but he preferred the
idea of improving the language to catch escaping over removing the implicit
slicing (which is probably part of why DIP 1000 and the related changes have
unfortunately become a thing).

Regardless of DIP 1000 though, IMHO, the implicit slicing just causes
confusion and invisible behavior simply so that you can avoid using an
explicit [] - and some of that isn't even related to bugs per se. For
instance, plenty of folks end up trying to pass a static array to a
range-based function and get confused when that doesn't work, since if the
function took a dynamic array, it would work (and that also makes it more
problematic to change a function so that it takes a range instead of a
dynamic array). It's one of those features that seems like it's a nice
usability improvement at first glance but which ultimately is a footgun.

And when you get a more complex example like the one in this thread, it's
that much worse, since even if you know enough to suspect that something
along those lines might be the problem, I bet that most of us would not
immediately come to that conclusion. It's just too subtle. And all to avoid
typing a couple of characters.

- Jonathan M Davis





More information about the Digitalmars-d-learn mailing list