ballerina-platform / ballerina-spec

Ballerina Language and Platform Specifications
Other
167 stars 53 forks source link

Allow ambiguous contextually expected union types in structural constructors #1226

Closed Nadeeshan96 closed 1 year ago

Nadeeshan96 commented 1 year ago

Description:

Because the spec on the mapping constructor says

If the applicable contextually expected type is a union type descriptor, then any members of the union that are inconsistent with the field names specified in a specific-field in the mapping-constructor-expr will be ignored; it is a compile-time error if this does not leave a single mapping type descriptor, which is then used as the inherent type.

we do not allow the following.

type PetByAge record {
    int age;
    string nickname?;
};

type PetByType record {
    "Cat"|"Dog" pet_type;
    boolean hunts?;
};

type Pet PetByAge|PetByType;

public function main() {
     Pet dog = {"age": 4, "nickname": "Fido", "pet_type": "Dog", "hunts": true}; // compilation error: ambiguous type 'Pet'(BCE2523)
}

Like we have a first match policy to handle ambiguities in fromJsonWithType now https://github.com/ballerina-platform/ballerina-spec/issues/1088, are we going to consider handling ambiguities in structural constructors too, so that it will not give an ambiguity error during the compilation, like in the above case, and to choose the inherent type using some policy?

Suggested Labels:

Code sample that shows issue:

Related Issues:

jclark commented 1 year ago

are we going to consider handling ambiguities in structural constructors too, so that it will not give an ambiguity error during the compilation, like in the above case, and to choose the inherent type using some policy?

I have considered and rejected this idea.

The situation for a constructor and for fromJsonWithType is different. With fromJsonWithType, we have to do the best we can with the type we have (since that may come from JSON schema). With a constructor, it's simpler and more reliable for the user to be explicit about what they want.

Nadeeshan96 commented 1 year ago

Got it. Thanks!