ballerina-platform / ballerina-lang

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

Unnecessary calls to `TypeChecker.checkCast` for compile time know subtypes #32018

Open manuranga opened 3 years ago

manuranga commented 3 years ago

Consider the following code.

const OFF = 0;
type Color "red" | "green" | "blue" | OFF;

function parseColor(string c) returns Color {
   if c is "r" {
       return "red";
   }
   else if c is "g" {
       return "green";
   }
   else if c is "b" {
       return "blue";
   }
   else if c is "0" {
       return OFF;
   }
   panic error("unexpected input : " + c);
}

In this there is no need to check each given constant (eg "red") is a subtype of Color since it's known at compile time.

manuranga commented 3 years ago

Generated bir looks like below

 %0 Color;
 %6 string;
…
 bb4 {
        %6 = ConstLoad green;
        %0 = <Color> %6;
        GOTO bb18;
}

If the %6's type is green backend can optimize this check, in the current state the backend can't do it without data analisis.

Therefore I am assigning this to frontend team, but some changes in runtime may also be needed.