allow when with byte 1,2,3 for word variables without having to cast the values to word explicitly

This commit is contained in:
Irmen de Jong 2023-03-09 22:15:56 +01:00
parent 9a36e8ba3b
commit e779a07bce
3 changed files with 31 additions and 1 deletions

View File

@ -375,6 +375,21 @@ class TypecastsAdder(val program: Program, val options: CompilationOptions, val
return noModifications
}
override fun after(whenChoice: WhenChoice, parent: Node): Iterable<IAstModification> {
if((parent as When).condition.inferType(program).isWords) {
val values = whenChoice.values
values?.toTypedArray()?.withIndex()?.forEach { (index, value) ->
val num = value.constValue(program)
if(num!=null && num.type in ByteDatatypes) {
val wordNum = NumericLiteral(if(num.type==DataType.UBYTE) DataType.UWORD else DataType.WORD, num.number, num.position)
wordNum.parent = num.parent
values[index] = wordNum
}
}
}
return noModifications
}
private fun addTypecastOrCastedValueModification(
modifications: MutableList<IAstModification>,
expressionToCast: Expression,

View File

@ -1001,4 +1001,19 @@ main {
compileText(VMTarget(), false, text, writeAssembly = true) shouldNotBe null
compileText(VMTarget(), true, text, writeAssembly = true) shouldNotBe null
}
test("byte when choices silently converted to word for convenience") {
var text="""
main {
sub start() {
uword z = 3
when z {
1-> z++
2-> z++
else -> z++
}
}
}"""
compileText(C64Target(), false, text, writeAssembly = false) shouldNotBe null
}
})

View File

@ -311,7 +311,7 @@ class TestProg8Parser: FunSpec( {
sub start() {
ubyte foo = 42
ubyte bar
when (foo) {
when foo {
23 -> bar = 'x'
42 -> bar = 'y'
else -> bar = 'z'