[swift-evolution] [Planning][Request] "constexpr" for Swift 5
David Sweeris
davesweeris at mac.com
Mon Jul 31 16:52:32 CDT 2017
On Jul 31, 2017, at 12:15 AM, Gor Gyolchanyan via swift-evolution <swift-evolution at swift.org> wrote:
>> On Jul 31, 2017, at 7:10 AM, John McCall via swift-evolution <swift-evolution at swift.org> wrote:
>>
>>> On Jul 30, 2017, at 11:43 PM, Daryle Walker <darylew at mac.com> wrote:
>>> The parameters for a fixed-size array type determine the type's size/stride, so how could the bounds not be needed during compile-time? The compiler can't layout objects otherwise.
>>
>> Swift is not C; it is perfectly capable of laying out objects at run time. It already has to do that for generic types and types with resilient members. That does, of course, have performance consequences, and those performance consequences might be unacceptable to you; but the fact that we can handle it means that we don't ultimately require a semantic concept of a constant expression, except inasmuch as we want to allow users to explicitly request guarantees about static layout.
>
> Doesn't this defeat the purpose of generic value parameters? We might as well use a regular parameter if there's no compile-time evaluation involved. In that case, fixed-sized arrays will be useless, because they'll be normal arrays with resizing disabled. As far as I know, the pinnacle of uses for fixed-size arrays is having a compile-time pre-allocated space of the necessary size (either literally at compile-time if that's a static variable, or added to the pre-computed offset of the stack pointer in case of a local variable).
Not at all... it'd let us use non-type parameters to affect a value's type... The classic example (or at least the one that I keep typing out whenever the topic comes up) is vector matrix math:
func * <T: Numeric, M: Integer, N: Integer, P: Integer> (lhs: Matrix<T, M, N>, rhs: Matrix<T, N, P>) -> Matrix<T, M, P> {
// no need to check if the dimensions at runtime because the type system turned dimension mismatches into a compile-time error
...
}
Sticking with the math theme, if you can make the variable's name (that is, your package's variable type, not a Swift var or let) part of its type, I suspect there's a trick you could do in a symbolic manipulation library involving simplifying equations (but I haven't thought it through enough to say for sure).
- Dave Sweeris
More information about the swift-evolution
mailing list