optimize when with const value (remove other choices from code)

This commit is contained in:
Irmen de Jong 2023-11-06 00:08:07 +01:00
parent 723ab54f97
commit efe4df92dc
2 changed files with 33 additions and 22 deletions

View File

@ -430,6 +430,27 @@ class StatementOptimizer(private val program: Program,
}
}
}
val constantValue = whenStmt.condition.constValue(program)?.number
if(constantValue!=null) {
// when condition is a constant
var matchingChoice: WhenChoice? = null
loop@ for(choice in whenStmt.choices) {
for(value in choice.values ?: emptyList()) {
if(value.constValue(program)?.number == constantValue) {
matchingChoice = choice
break@loop
}
}
}
if(matchingChoice==null)
matchingChoice = whenStmt.choices.singleOrNull { it.values==null }
if(matchingChoice!=null) {
// get rid of the whole when-statement and just leave the matching choice
return listOf(IAstModification.ReplaceNode(whenStmt, matchingChoice.statements, parent))
}
}
return noModifications
}

View File

@ -1,27 +1,17 @@
%import gfx2
%zeropage basicsafe
%option no_sysinit
%import textio
main {
sub start() {
gfx2.screen_mode(2)
const ubyte FOO = 0
const ubyte BAR = 1
gfx2.safe_circle(120, 140, 200, 1)
sys.wait(30)
gfx2.safe_circle(520, 140, 200, 1)
sys.wait(30)
gfx2.safe_circle(120, 340, 200, 1)
sys.wait(30)
gfx2.safe_circle(520, 340, 200, 1)
sys.wait(30)
gfx2.safe_disc(120, 140, 200, 1)
sys.wait(30)
gfx2.safe_disc(520, 140, 200, 1)
sys.wait(30)
gfx2.safe_disc(120, 340, 200, 1)
sys.wait(30)
gfx2.safe_disc(520, 340, 200, 1)
repeat {
}
sub start() {
when FOO+BAR {
1-> txt.print("path 1")
2-> txt.print("path 2")
else-> txt.print("path 3")
}
txt.nl()
}
}