Structural Types with MPS

  • 3
  • 29

Hi,

I'm trying to implement an editor for the roy language (or something close - depending on where I will end). Roy (http://roy.brianmckenna.org/) uses structural types. Here two objects have the same type if they have the same structure (the same properties with the same type). See below for an example.

type Person = {firstName: String, lastName: String}
let getName (x: Person) = x.firstName ++ " " ++ x.lastName 

console.log (getName {firstName: "Brian", lastName: "McKenna"})

// Won't compile:
// console.log (getName {})


I haven't found out how to do this with the MPS type system as I can only assign a type node to some expression. Any hints would be great.

Regards, Jan
Answered by Sascha Lißon
 
You need to use replacement rules. In the tuples language is a replacement rule called namedTuple_assignableTo_namedTuple:

replacement rule namedTuple_assignableTo_namedTuple

applicable for  concept = NamedTupleType as left <: concept = NamedTupleType as right

rule {
...
  foreach (node<> lp : left.parameterType; node<> rp : right.parameterType) {
    infer lp :<=: rp;
  }
...
}

This rule says, that one tuple (left) is a subtype of another tuple (right), if each value in the left tuple is a subtype of the value in the right tuple at the same position.
I tried to understand how the named tuples work (as I guess they are exactly what I want) but no success. Can anyone explain those to me?

You need to use replacement rules. In the tuples language is a replacement rule called namedTuple_assignableTo_namedTuple:

replacement rule namedTuple_assignableTo_namedTuple

applicable for  concept = NamedTupleType as left <: concept = NamedTupleType as right

rule {
...
  foreach (node<> lp : left.parameterType; node<> rp : right.parameterType) {
    infer lp :<=: rp;
  }
...
}

This rule says, that one tuple (left) is a subtype of another tuple (right), if each value in the left tuple is a subtype of the value in the right tuple at the same position.

comment
Thanks. Will try it out and maybe blog about it (if I get it working).