[JS IR] Optimize pattern-matching of enums into comparing their ordinals
For this code:
```
enum class Season {
WINTER,
SPRING,
SUMMER,
AUTUMN
}
fun bar1(x : Season) : String {
return when (x) {
Season.WINTER, Season.SPRING -> "winter_spring"
Season.SUMMER -> "summer"
else -> "autumn"
}
}
```
previously we generated this:
```
function foo(x) {
var tmp0_subject = x;
return (tmp0_subject.equals(Season_WINTER_getInstance())
? true
: tmp0_subject.equals(Season_SPRING_getInstance()))
? 'winter_spring'
: tmp0_subject.equals(Season_SUMMER_getInstance())
? 'summer'
: 'autumn';
}
```
And now we generated this:
```
function bar2(x) {
var tmp0_subject = x;
var tmp0 = tmp0_subject._get_ordinal__0_k$();
var tmp;
switch (tmp0) {
case 0:
case 1:
tmp = 'winter_spring';
break;
case 2:
tmp = 'summer';
break;
case 3:
tmp = 'autumn';
break;
default:
noWhenBranchMatchedException();
break;
}
return tmp;
}
```
This commit is contained in:
@@ -385,6 +385,12 @@ private val forLoopsLoweringPhase = makeBodyLoweringPhase(
|
||||
description = "[Optimization] For loops lowering"
|
||||
)
|
||||
|
||||
private val enumWhenPhase = makeJsModulePhase(
|
||||
::EnumWhenLowering,
|
||||
name = "EnumWhenLowering",
|
||||
description = "Replace `when` subjects of enum types with their ordinals"
|
||||
).toModuleLowering()
|
||||
|
||||
private val propertyLazyInitLoweringPhase = makeBodyLoweringPhase(
|
||||
::PropertyLazyInitLowering,
|
||||
name = "PropertyLazyInitLowering",
|
||||
@@ -832,6 +838,7 @@ private val loweringList = listOf<Lowering>(
|
||||
initializersCleanupLoweringPhase,
|
||||
kotlinNothingValueExceptionPhase,
|
||||
// Common prefix ends
|
||||
enumWhenPhase,
|
||||
enumEntryInstancesLoweringPhase,
|
||||
enumEntryInstancesBodyLoweringPhase,
|
||||
enumClassCreateInitializerLoweringPhase,
|
||||
|
||||
Reference in New Issue
Block a user