Evolving past reference type patterns
Brian Goetz
brian.goetz at oracle.com
Fri Apr 15 21:36:26 UTC 2022
> * asking if something fits in the range of a byte or int; doing this
> by hand is annoying and error-prone
> * asking if casting from long to int would produce truncation; doing
> this by hand is annoying and error-prone
>
>
Here’s some real code I wrote recently that would benefit dramatically
from this:
|default CodeBuilder constantInstruction(int value) { return with(switch
(value) { case -1 -> ConstantInstruction.ofIntrinsic(Opcode.ICONST_M1);
case 0 -> ConstantInstruction.ofIntrinsic(Opcode.ICONST_0); case 1 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_1); case 2 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_2); case 3 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_3); case 4 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_4); case 5 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_5); default -> { if (value
>= -128 && value <= 127) { yield
ConstantInstruction.ofArgument(Opcode.BIPUSH, value); } else if (value
>= -32768 && value <= 32767) { yield
ConstantInstruction.ofArgument(Opcode.SIPUSH, value); } else { yield
ConstantInstruction.ofLoad(Opcode.LDC,
BytecodeHelpers.constantEntry(constantPool(), value)); } } }); } |
could become the less error-prone and uniform:
|default CodeBuilder constantInstruction(int value) { return with(switch
(value) { case -1 -> ConstantInstruction.ofIntrinsic(Opcode.ICONST_M1);
case 0 -> ConstantInstruction.ofIntrinsic(Opcode.ICONST_0); case 1 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_1); case 2 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_2); case 3 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_3); case 4 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_4); case 5 ->
ConstantInstruction.ofIntrinsic(Opcode.ICONST_5); case byte value ->
ConstantInstruction.ofArgument(Opcode.BIPUSH, value); case short value
-> ConstantInstruction.ofArgument(Opcode.SIPUSH, value); default ->
ConstantInstruction.ofLoad(Opcode.LDC,
BytecodeHelpers.constantEntry(constantPool(), value)); }); } |
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20220415/1f236acd/attachment.htm>
More information about the amber-spec-experts
mailing list