ballerina-platform / ballerina-lang

The Ballerina Programming Language
https://ballerina.io/
Apache License 2.0
3.59k stars 740 forks source link

Int variable length array cannot be cast to json fixed length array #36433

Open rdulmina opened 2 years ago

rdulmina commented 2 years ago

Description:

Consider the below sample causing compile-time error

public function main() {
    int[] e = [1, 2, 3];
    json[3] e2 = <json[3]>e; // error incompatible types: 'int[]' cannot be cast to 'json[3]'
}

This sample should panic at runtime

MaryamZi commented 1 year ago

The current behaviour is correct.

A type-cast-expr is evaluated by first evaluating expression resulting in a value v. Let T be the type described by type-descriptor. If v belongs T, then the result of the type-cast-expr is v. Otherwise, if T includes shapes from exactly one basic numeric type N and v belongs to another basic numeric type, then let n be NumericConvert(N, v); if n is not an error and n belongs to T, then the result of the type-cast-expr is n. Otherwise, the evaluation of the type-cast-expr completes abruptly with a panic.

Here, the value is an open array that currently holds three integers. So it does not belong to json[3].

From https://ballerina.io/spec/lang/master/#section_5.1.2

a value belongs to a type if it looks like the type, and it will necessarily continue to look like the type no matter how the value is mutated.

MaryamZi commented 1 year ago

Sorry, I misunderstood the error to be a runtime error. This should compile but panic at runtime.