-
Notifications
You must be signed in to change notification settings - Fork 0
Optimizer
RedScript includes a multi-pass optimizer that runs after lowering and before code generation. It reduces command count and eliminates redundant scoreboard operations.
Removes assignments to $tmp variables that are never read.
# Before
scoreboard players set $t0 rs 42
scoreboard players set $t1 rs 0 ← never used
scoreboard players operation X obj = $t0 rs
# After
scoreboard players set $t0 rs 42
scoreboard players operation X obj = $t0 rs
When a conditional branch's guard variable is set immediately before an unconditional execute, removes the intermediate variable.
# Before
scoreboard players set $cond rs 1
execute if score $cond rs matches 1.. run function ns:then
# After
function ns:then
Caches repeated scoreboard reads within the same block.
# Before
execute store result score $t0 rs run scoreboard players get player obj
... (10 operations later)
execute store result score $t8 rs run scoreboard players get player obj ← same read
# After
execute store result score $t0 rs run scoreboard players get player obj
scoreboard players operation $t8 rs = $t0 rs ← copy, no re-read
Hoists expressions that don't change in a loop to before the loop.
# Before (inside loop body)
scoreboard players set $const_10 rs 10 ← same every iteration
# After (hoisted above loop)
scoreboard players set $const_10 rs 10
[loop body runs N times without re-setting]
Merges consecutive setblock commands on the same block type into a single fill when they form an axis-aligned run.
# Before
setblock 0 64 0 minecraft:stone
setblock 1 64 0 minecraft:stone
setblock 2 64 0 minecraft:stone
setblock 3 64 0 minecraft:stone
# After
fill 0 64 0 3 64 0 minecraft:stone
Works for both the datapack and structure targets.
When a conditional block in a structure has only one branch, collapses the chain/conditional overhead.
View pass results with --stats:
redscript compile game.rs --stats
# Optimizer stats:
# dead stores removed: 12
# branch vars eliminated: 3
# CSE eliminations: 5
# LICM hoists: 2
# setblock→fill batches: 3 (saved 8 commands)
#
# Total: 89 commands → 71 commands (−20%)redscript compile game.rs --no-optimizeUseful for debugging to see the raw lowered output.