[swift-dev] Advice for implementing "literal values as generic types"

Robert Widmann devteam.codafi at gmail.com
Wed Aug 30 10:01:36 CDT 2017


> On Aug 29, 2017, at 5:22 PM, David Sweeris via swift-dev <swift-dev at swift.org> wrote:
> 
> 
>> On Aug 29, 2017, at 1:49 PM, Slava Pestov <spestov at apple.com <mailto:spestov at apple.com>> wrote:
>> 
>> 
>>> On Aug 29, 2017, at 11:03 AM, David Sweeris via swift-dev <swift-dev at swift.org <mailto:swift-dev at swift.org>> wrote:
>>> 
>>> Hi everyone! I'm trying to implement literal values as generic types.
>> 
>> Can you briefly explain what you mean by this?
>> 
>> Are you referring to let-polymorphism, like
>> 
>> let fn = { $0 }
>> let f1: (Int) -> Int = fn
>> let f2: (Float) -> Float = fn
> 
> No, I mean so that a vector's or matrix's dimensions can be part of its type (strawman syntax and protocol name, but this is pretty much what I'll be trying to support, at least at first):
> struct Vector<T: ExpressibleByIntegerLiteral, L: IntegerLiteralExpr> {
>   var elements: [T]
>   init() {
>     elements = [T](repeating: 0, count: L)
>   }
> }
> 
> let vect = Vector<Int, 5>()
> 
> And, once that's working, I'm going to add support simple "type functions":
> func join <T, L1, L2> (_ lhs: Vector<T, L1>, _ rhs: Vector<T, L2>) -> Vector<T, L1 + L2 > {...}
> I think restricting the supported "type functions" to expressions that could be evaluated by the compiler's "constant folding" code would be a reasonable place to start, until we figure out what we want to do about "pure"/"constexpr" stuff... even just "+" for numeric and string literals, and "-" for numeric literals, seems like a reasonable starting goal, and I think that'd be simple enough to implement (famous last words, right?)... It's all academic until I get the simple cases working first, though.

Constant folding occurs too late in the compilation process for you to take advantage of it in the solver.  You’ll need to write your own evaluator and teach CSSimplify to invoke it during the type matching process.  I would start by adding a new kind of Type and TypeRepr that hold SequenceExpr nodes and a CanType that holds an APSInt representing the result of evaluating the expression. 

> 
> Anyway, I think it'll be worth writing up as a proposal, once it's working and I've figured out how to present these "literal types" to Swift's type system (I'd like to keep it as a literal of some sort, so that, say, `L` in this example could be used to set the value of any type that conforms to `ExpressibleByIntegerLiteral`).
> 
> - Dave Sweeris
> 
> _______________________________________________
> swift-dev mailing list
> swift-dev at swift.org
> https://lists.swift.org/mailman/listinfo/swift-dev

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-dev/attachments/20170830/3a3c71ef/attachment.html>


More information about the swift-dev mailing list