ballerina-platform / ballerina-spec

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

Clarify the type handling method in Ballerina Binary Expressions #1262

Closed SasinduDilshara closed 1 year ago

SasinduDilshara commented 1 year ago

Please consider the following case,

xml a = "a" + "b" + xml ``; // No compile error

In here, Ballerina will first calculate the ("a" + "b"), for that additive operation and the contextual expected type is xml.

In the Ballerina spec, under the Additive Expressions section, It says

the static type of both operand expressions is a subtype of the same basic type, in which case the static type of the result will be this basic type

So according to that the addition between two strings under the xml as a contextual expected type is should be a compile time error.

In user point of view

xml a = "a" + "b" + xml ``;

This is a addition between xml and string which is allowed by the Ballerina.

What should be the correct behaviour?

Note that this will also applicable to the float f = 1 * 1 * 1.2; as well

jclark commented 1 year ago

The contextually expected type is a type that is passed down the expression tree and is used to determine the type of literals and of constructor expressions; there is not a requirement that the static type of an expression is a subtype of the contextually expected type (although that will usually be the case).

In this example:

xml a = "a" + "b" + xml ``;

the contextually expected type for "a" + "b" is xml, but the static type is string, because the static type of an addition of two strings is string. So this is the addition of a string and xml, which will result in a xml value.

The case of

float f = 1 * 1 * 1.2;

is quite different. Here all the numeric literals will have static type float, because of the contextually expected type being passed down.

jclark commented 1 year ago

The difference is that "x" always has type string, whereas 1 can have type int, decimal or float depending on the contextually expected type.