ballerina-spec icon indicating copy to clipboard operation
ballerina-spec copied to clipboard

String representations of a Type

Open hasithaa opened this issue 6 years ago • 3 comments

Description: A human-readable string representation of a type is mostly required for generating type-related error messages in both compile-time and runtime. There is a slight inconsistency in the current implementation when dealing with type descriptors vs. type definition.

type Person record {|
    string name;
    int age;
|};

public function main() {
    Person p = {name : "tom", age : 10};
    record {|
        string name;
        float age;      // <- Wrong type.
    |} q = p;   // Compilation error. 
}

Above code generates the following the compilation error.

incompatible types: expected '$anonType$0', found 'Person'

The developer can't figure out what went wrong here. We can improve the error message by providing the type information.

e.g.

// Option 1:
incompatible types: expected 'record {| string name; float age; |}', found 'Person'

// Options 2:
incompatible types: expected 'record {| string name; float age; |}', found 'record {| string name; int age; |}'

This raises a few questions:

  • That is the string representation of a type?
    • One possible solution is to use type descriptor like syntax.
  • Should we use type definition names if possible?
  • Should this be part of the spec?

hasithaa avatar Jul 23 '19 04:07 hasithaa

If you have a recursive type e.g.

type List record {
  int n;
  List? next;
};

you cannot write it without using a name.

jclark avatar Jul 23 '19 05:07 jclark

Yes, you are correct. One option is to refer type definitions using type name itself. i.e., List

hasithaa avatar Jul 23 '19 05:07 hasithaa

Some of the papers that I have read on semantic subtyping suggest based on their experience that in a case where you have a type S that is supposed to be a subtype of a type T, but fails to be, it is helpful to give an example of a value that it is in S but not in T.

jclark avatar Jul 25 '19 08:07 jclark