flint icon indicating copy to clipboard operation
flint copied to clipboard

Allow properties to have struct trait types

Open bearbin opened this issue 6 years ago • 4 comments

Part of #338

contract X {
  var money: Asset
}
....
func transfer(to: Asset, from: Asset) {

}
....
func foo() {
let x: Asset = Wei()
}

bearbin avatar Sep 17 '18 14:09 bearbin

I've thought about this a bit more and we need to discuss/work this out more before it can be implemented.

  • We would want to have some form of multi-trait union type that struct-trait-instances could conform to.
  • Due to the current IR implementation we would need to carry around the name of the actual implementation of a trait-instance so the correct function could be called, in a form of dynamic dispatch.

Also, we would need to change these areas in the code, at least:

  • Parsing and syntax form.
  • Matching function calls needs to take into account functions in trait-instances.
  • Type compatiblity of assignment to trait from struct conforming to trait.

bearbin avatar Sep 19 '18 15:09 bearbin

  • If you look at the asset traits proposal there is an example with specifying the type of RawType for an asset which is where RawType: Numeric & Comparable. This seems a sensible syntax to follow.
  • I think we do have to do that but to a lesser extent - We'd generate a function wrapper and function table to do the dispatching so:
struct trait X {
  func foo() 
}

struct Y: X {
  func foo() {}
}
struct Z: X {
  func foo() {}
}

would generate to:

selector$foo(x) {
  switch x {
    case 0x0dsad:
       Y$foo()
    case 0x00e:
      Z$foo()
  }
}

where x in this case would be done in the same manner as the main dispatcher is for the contracts as a whole.

DJRHails avatar Sep 19 '18 16:09 DJRHails

Your suggestion for the type annotation syntax seems sensible.

Can you explain the selector functions a bit more? What would the switch actually be switching on and how would we avoid having to store the actual type of a struct.

bearbin avatar Sep 19 '18 17:09 bearbin

We would have to pass around a reference of some sort to the actual struct - otherwise (as far as I'm aware) dynamic dispatch isn't possible. The x I was talking of switching on would be the Keccak hash of the type - however this could be added by the compiler in some cases. Only a few functions will require a pass around reference.

DJRHails avatar Sep 20 '18 11:09 DJRHails