Range Redesign: Empty Ranges

H. S. Teoh hsteoh at qfbox.info
Thu Mar 7 19:16:55 UTC 2024


On Thu, Mar 07, 2024 at 06:32:50PM +0000, Steven Schveighoffer via Digitalmars-d wrote:
[...]
> Sometimes, we are bitten by the fact that the array is the most common
> range, and behaves in a specific way. People depend on that mechanism
> without realizing it, and then sometime later, they decide to change
> the type to one that is very compatible with arrays, but offers some
> benefit (i.e. to remove an allocation). However, the new range type
> might behave in unexpected ways, *but still compiles*.

Over the past decade of working with D, this has repeatedly come up as
the weakness of a signature-constraint based approach to ducktyping. The
problem is that what the signature constraint requires (e.g.,
isInputRange) may only be a subset of what the function body assumes,
and there is no way to check this mechanically (signature constraints
are Turing-complete).

What ideally should happen is that whatever the code assumes should also
be declared in the function signature. So if a template takes a
parameter t of generic type T, and then goes and performs t++, then the
compiler should enforce that ++ is declared as part of the constraints
on T.  The C++ concepts approach is better in this respect, in that the
compiler can typecheck the function body and emit an error if it tries
to perform an operation on T that it didn't declare as part of its
signature constraint.  Barring implementing concepts in D, which is
unlikely to happen, the next best alternative is for the compiler to
enforce that any operation on T must have a corresponding check in the
signature constraint, and when this is not the case, it should, based on
the attempted operation, issue an error message with a suggested
addition to the sig constraint that would satisfy this requirement.

This doesn't fully solve the problem here, of course -- sometimes the
difference is semantic rather than something easily checkable by the
compiler, like subtle differences between built-in arrays and
user-defined arrays; in that case you're still up the creek without a
paddle.  But it's a step forward.


T

-- 
The trouble with TCP jokes is that it's like hearing the same joke over and over.


More information about the Digitalmars-d mailing list