refactor: port fluid handler trait to java

Preserve the exact generated interface and ordered fluid behavior.

Isolate FluidStack.amount access outside the transformed class. The transformer treats every field read as trait-owned state.
This commit is contained in:
Algent committed 2026-08-30 13:33:05 +02:00
1 parent cad4b1cef0
commit bf8c9c24b8
5 files changed
+242 -152

No files matched your search

+4 -3
View File
@@ -25,9 +25,10 @@ No trustworthy tool will produce a maintainable Java port automatically. A decom
The binary and source-level consumer audits, low-coupling Phase 3 queue, audit-derived immediate compatibility gate,
focused profile, first traversal optimization, complete redstone interaction helper unit, `MicroRecipe` port, and the
first three Java-trait ports are complete. `TPartialOcclusionTile` proved the no-field path, `TSlottedTile` proved state
and lifecycle rewriting, and `TRedstoneTile` removed the measured redstone allocation while retaining its exact runtime
interface. See `JAVA_MIGRATION_PROFILE.md`.
first five Java-trait ports are complete. `TPartialOcclusionTile` proved the no-field path, `TSlottedTile` proved state
and lifecycle rewriting, `TRedstoneTile` removed the measured redstone allocation, `TTileChangeTile` exercised mutable
state plus inherited access, and `TFluidHandlerTile` preserved ordered Forge fluid distribution. All retain their exact
runtime interfaces. See `JAVA_MIGRATION_PROFILE.md`.
That audit found and this branch has now repaired one existing regression: Schematica 1.12.6 reflects the original private
`MultiPartRegistry$` field `codechicken$multipart$MultiPartRegistry$$typeMap` and casts it to a Scala mutable map. The
+55
View File
@@ -1585,3 +1585,58 @@ fix, used here, is to type the shim parameters as `Object` so the cast is always
- Complete plain-JVM suite: 153 tests, 0 failures, 0 errors.
- Java 8 Forge dedicated-server suite: 54 tests, 0 failures, 0 errors.
- `INeighborTileChange` descriptors identical between the reference and ported dev jars.
## 2026-08-30 — TFluidHandlerTile Java-trait port
No frozen binary or audited source consumer names `TFluidHandlerTile` or its `$class` helper. The load-bearing surface
is Forge's `IFluidHandler`, which generated multipart tiles still implement with the same six fluid method
descriptors.
### Observable behavior
No known runtime divergence. Every generated tile receives a distinct `LinkedList`; `copyFrom` still shares that list
by identity only for another fluid tile. Fluid parts are appended in binding order, removal deletes the first equal
entry, and clear empties both the superclass part list and the existing tank list.
`getTankInfo` still visits every handler twice, first to size the result and then to flatten each returned array in
part order. Fill still passes a fresh copy with the decreasing remaining amount to every handler, including handlers
reached after the full quantity has been accepted. `canFill` and `canDrain` still stop at the first matching handler.
Both drain overloads still simulate every handler first, accept the first positive fluid and only later matching
fluids, and commit only accepted simulations when requested. The first accepted simulated stack remains the returned
object, with its amount replaced by the total. The stack overload still passes decreasing copies and leaves the
caller's stack unchanged.
### Generated ABI and raw input divergence
At Forge runtime `TFluidHandlerTile` remains a public interface extending exactly `IFluidHandler`, with no fields and
the same 16 abstract methods: ten behavior methods, the `tankList` getter and setter, and four super accessors. The
generated composite still owns and initializes a `LinkedList tankList` field, permits setter rebinding, and reuses its
class for equal trait sets.
The untransformed artifact changes from a Scala interface, `$class` helper, and eight `$$anonfun$` classes to one
concrete Java `TileMultipart` subclass plus package-private `TFluidHandlerTileAccess`. No shipping consumer references
the removed classes. The raw-dev-jar source-build limitation recorded for `TSlottedTile` applies unchanged.
### Transformer constraint
The Java-trait transformer rewrites every `GETFIELD` instruction as access to trait-owned state without checking the
instruction's owner. The first port therefore failed registration on the public `FluidStack.amount` field with
`key not found: amount`. `TFluidHandlerTileAccess` now owns those reads, writes, and amount-adjusted copies outside the
transformed class. It adds no public surface and requires no generator change.
### Performance boundary
Ordinary loops remove the eight Scala closure classes, but no representative workload in the retained profiler uses
multipart fluid distribution. This is a structural removal, not a throughput or allocation claim.
### Validation
- `TFluidHandlerTileFunctionalTest`: 7 Forge tests covering list lifecycle and identity, tank-info order, fill
distribution, capability short-circuiting, fluid matching, simulation, commit behavior, and both drain overloads.
- `ForgeEnvironmentSmokeTest.generatesAndCachesFluidHandlerTileClass`: exact 16-method runtime interface, parent
interface, generated field, distinct initialization, setter rebinding, and generated-class reuse.
- All eight tests passed against the untouched Scala trait first and pass unchanged after the port.
- Complete plain-JVM suite: 153 tests, 0 failures, 0 errors.
- Java 8 Forge dedicated-server suite: 62 tests, 0 failures, 0 errors.
- The frozen consumer inventory and audited source consumers contain no `TFluidHandlerTile` reference.
+18 -10
View File
@@ -12,7 +12,8 @@ what breaks, and what is left. The other documents hold the reasoning.
| `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client |
| `JAVA_MIGRATION_PROFILE.md` | The focused baseline, first measured result, findings, and exact rerun command |
Branch: `algent/java`. Base: `master`. 79 commits including the separate `TTileChangeTile` characterization and port.
Branch: `algent/java`. Base: `master`. 81 commits including separate characterization and port commits for
`TFluidHandlerTile`.
## The one rule that matters
@@ -66,7 +67,7 @@ awk -F'"' '/<testsuite /{t+=$4;f+=$8;e+=$10} END{print "tests="t" failures="f" e
grep -o 'tests="[0-9]*" skipped="[0-9]*" failures="[0-9]*" errors="[0-9]*"' run/server/junit-out/TEST-*.xml
```
Current baseline: **153 plain-JVM tests, 54 Forge server tests, all passing at their last completed runs.**
Current baseline: **153 plain-JVM tests, 62 Forge server tests, all passing at their last completed runs.**
### ABI diff against the reference
@@ -187,6 +188,11 @@ mistaken for trait-owned state, and an inherited virtual call takes a broken cas
coordinate, `partList`, and virtual `partMap` access in package-private `TRedstoneTileAccess`; use that pattern or fix
and characterize the generator before converting another trait with the same bytecode shape.
**Java traits also cannot directly read fields owned by method arguments.** The transformer rewrites every `GETFIELD`
as trait-owned state without checking its owner. `TFluidHandlerTile` therefore keeps `FluidStack.amount` reads and
writes in package-private `TFluidHandlerTileAccess`. A static helper outside the transformed class is enough when no
trait-to-superclass cast is involved.
**Type the access shim's parameters `Object`.** `TTileChangeTileAccess` first typed them as the trait itself and cast
to `TileMultipart` inside. Because the untransformed trait extends `TileMultipart`, javac elided the cast, and once
Forge rewrote the trait to an interface the verifier rejected the `getfield`. `TRedstoneTileAccess` only escapes this
@@ -204,7 +210,7 @@ All eight load-bearing `$class` helpers from the inventory, both registries, and
`TFacePart`, the `TIconHitEffects` unit, `TItemMultiPart`/`JItemMultiPart`, `TEdgePart`, `Saw`, `MicroMaterialRegistry`,
`MultiPartRegistry`, `TileMultipart`, `TMultiPart`, `TickScheduler`, `BlockMultipart`, the complete
`IRedstonePart`/`RedstoneInteractions` unit, `MicroRecipe`, and the `TPartialOcclusionTile`, `TSlottedTile`, and
`TRedstoneTile` Java-trait ports.
`TRedstoneTile`, `TTileChangeTile`, and `TFluidHandlerTile` Java-trait ports.
Plus the six marker interfaces: `TSlottedPart`, `IRandomDisplayTick`, `INeighborTileChange`, `TRandomUpdateTick`,
`ISidedHollowConnect`, `IMicroMaterialRender`, plus `MultipartHelper`, `TileCache`, `PacketScheduler` and the `ControlKeyModifer` pair.
@@ -219,7 +225,7 @@ across the port. It is also where the two shim constraints in the gotchas list w
`rayTraceAll`'s index production is now characterized, closing the gap the read-path cleanup left: the index written
into `ExtendedMOP.data` is what `reduceMOP` hands back to every click, activate, harvest and pick block.
86 Java files, 42 Scala files, ~5,676 Scala lines left (non-blank; that is the metric this figure has always used).
87 Java files, 41 Scala files, ~5,556 Scala lines left (non-blank; that is the metric this figure has always used).
## What is left, and in what order
@@ -281,6 +287,13 @@ methods, including public array getter/setter and five super accessors. Each til
copying shares the source array exactly as before; external array mutation plus `bindPart`, clear/removal behavior,
occupied-slot rejection, value equality, actual add/remove/move lifecycle, and generated-class caching are all green.
`TFluidHandlerTile` is now Java. Seven behavior tests freeze ordered tank binding, shared-list copying, removal and
clear behavior, flattened tank information, capability short-circuiting, decreasing fill copies, and both simulated
drain forms. Its generated runtime interface still extends exactly `IFluidHandler` and keeps the same 16 methods,
field initialization, setter rebinding, and class-cache behavior. No shipping consumer references its removed raw
`$class` or closure classes. A narrow access helper is required for `FluidStack.amount` because the transformer treats
all direct field reads inside a Java trait as trait-owned state.
**Medium.** The `handler` packages on both sides, `ItemMicroPart`,
`MicroblockPlacement`, `PlacementGrids`, `BlockMicroMaterial`, `MissingMicroMaterial`, `ConfigContent`,
`DefaultContent`.
@@ -289,12 +302,7 @@ occupied-slot rejection, value equality, actual add/remove/move lifecycle, and g
`multipart/scalatraits/`. The no-field, stateful, measured hot-query, and inherited-member cases are all complete
without a generator change.
`TFluidHandlerTile` is the next one to take. It and `TIInventoryTile` make **no** inherited field reads or virtual
calls — only `super.*` on overrides, with all state trait-owned — so neither needs an access shim, and `super.*` is
already proven by `TSlottedTile`'s five super accessors. `TFluidHandlerTile` has no external consumer surface, which
makes it the cheaper of the two.
Take `TIInventoryTile` after it. AE2's `CableBusPart.notifyNeighbors` does `tile() instanceof TIInventoryTile` then
Take `TIInventoryTile` next. AE2's `CableBusPart.notifyNeighbors` does `tile() instanceof TIInventoryTile` then
calls `rebuildSlotMap()`, so the runtime interface must keep that method public; freeze that plus the inventory-field
behavior first. Note it is `JInventoryTile`, the concrete class, that is registered — do not collapse the two, because
AE2 casts to the trait.
@@ -0,0 +1,165 @@
package codechicken.multipart.scalatraits;
import java.util.LinkedList;
import net.minecraftforge.common.util.ForgeDirection;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
import codechicken.multipart.TMultiPart;
import codechicken.multipart.TileMultipart;
/** Mixin implementation that distributes fluid handling among multipart tanks. */
public class TFluidHandlerTile extends TileMultipart implements IFluidHandler {
public LinkedList<IFluidHandler> tankList = new LinkedList<>();
@Override
public void copyFrom(TileMultipart that) {
super.copyFrom(that);
if (that instanceof TFluidHandlerTile) {
tankList = ((TFluidHandlerTile) that).tankList;
}
}
@Override
public void bindPart(TMultiPart part) {
super.bindPart(part);
if (part instanceof IFluidHandler) {
tankList.add((IFluidHandler) part);
}
}
@Override
public void partRemoved(TMultiPart part, int position) {
super.partRemoved(part, position);
if (part instanceof IFluidHandler) {
tankList.remove(part);
}
}
@Override
public void clearParts() {
super.clearParts();
tankList.clear();
}
@Override
public FluidTankInfo[] getTankInfo(ForgeDirection direction) {
int tankCount = 0;
for (IFluidHandler handler : tankList) {
tankCount += handler.getTankInfo(direction).length;
}
FluidTankInfo[] tanks = new FluidTankInfo[tankCount];
int index = 0;
for (IFluidHandler handler : tankList) {
for (FluidTankInfo tank : handler.getTankInfo(direction)) {
tanks[index++] = tank;
}
}
return tanks;
}
@Override
public int fill(ForgeDirection direction, FluidStack liquid, boolean doFill) {
int filled = 0;
int initial = TFluidHandlerTileAccess.amount(liquid);
for (IFluidHandler handler : tankList) {
FluidStack remaining = TFluidHandlerTileAccess.copy(liquid, initial - filled);
filled += handler.fill(direction, remaining, doFill);
}
return filled;
}
@Override
public boolean canFill(ForgeDirection direction, Fluid liquid) {
for (IFluidHandler handler : tankList) {
if (handler.canFill(direction, liquid)) {
return true;
}
}
return false;
}
@Override
public boolean canDrain(ForgeDirection direction, Fluid liquid) {
for (IFluidHandler handler : tankList) {
if (handler.canDrain(direction, liquid)) {
return true;
}
}
return false;
}
@Override
public FluidStack drain(ForgeDirection direction, int amount, boolean doDrain) {
FluidStack drained = null;
int drainedAmount = 0;
for (IFluidHandler handler : tankList) {
int remaining = amount - drainedAmount;
FluidStack result = handler.drain(direction, remaining, false);
if (result != null && TFluidHandlerTileAccess.amount(result) > 0
&& (drained == null || drained.isFluidEqual(result))) {
if (doDrain) {
handler.drain(direction, remaining, true);
}
if (drained == null) {
drained = result;
}
drainedAmount += TFluidHandlerTileAccess.amount(result);
}
}
if (drained != null) {
TFluidHandlerTileAccess.setAmount(drained, drainedAmount);
}
return drained;
}
@Override
public FluidStack drain(ForgeDirection direction, FluidStack liquid, boolean doDrain) {
int amount = TFluidHandlerTileAccess.amount(liquid);
FluidStack drained = null;
int drainedAmount = 0;
for (IFluidHandler handler : tankList) {
FluidStack remaining = TFluidHandlerTileAccess.copy(liquid, amount - drainedAmount);
FluidStack result = handler.drain(direction, remaining, false);
if (result != null && TFluidHandlerTileAccess.amount(result) > 0
&& (drained == null || drained.isFluidEqual(result))) {
if (doDrain) {
handler.drain(direction, remaining, true);
}
if (drained == null) {
drained = result;
}
drainedAmount += TFluidHandlerTileAccess.amount(result);
}
}
if (drained != null) {
TFluidHandlerTileAccess.setAmount(drained, drainedAmount);
}
return drained;
}
}
/** Keeps fields owned by method arguments outside the generated trait transformer. */
final class TFluidHandlerTileAccess {
private TFluidHandlerTileAccess() {}
static int amount(FluidStack stack) {
return stack.amount;
}
static void setAmount(FluidStack stack, int amount) {
stack.amount = amount;
}
static FluidStack copy(FluidStack stack, int amount) {
FluidStack copy = stack.copy();
copy.amount = amount;
return copy;
}
}
@@ -1,139 +0,0 @@
package codechicken.multipart.scalatraits
import net.minecraftforge.common.util.ForgeDirection
import codechicken.multipart.TMultiPart
import codechicken.multipart.TileMultipart
import net.minecraftforge.fluids.IFluidHandler
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fluids.FluidTankInfo
import net.minecraftforge.fluids.Fluid
import java.util.LinkedList
import scala.collection.JavaConversions._
/** Mixin trait implementation for parts implementing IFluidHandler. Distributes
* fluid manipulation among fluid handling parts.
*/
trait TFluidHandlerTile extends TileMultipart with IFluidHandler {
var tankList = new LinkedList[IFluidHandler]()
override def copyFrom(that: TileMultipart) {
super.copyFrom(that)
if (that.isInstanceOf[TFluidHandlerTile])
tankList = that.asInstanceOf[TFluidHandlerTile].tankList
}
override def bindPart(part: TMultiPart) {
super.bindPart(part)
if (part.isInstanceOf[IFluidHandler])
tankList += part.asInstanceOf[IFluidHandler]
}
override def partRemoved(part: TMultiPart, p: Int) {
super.partRemoved(part, p)
if (part.isInstanceOf[IFluidHandler])
tankList -= part.asInstanceOf[IFluidHandler]
}
override def clearParts() {
super.clearParts()
tankList.clear()
}
override def getTankInfo(dir: ForgeDirection): Array[FluidTankInfo] = {
var tankCount: Int = 0
tankList.foreach(t => tankCount += t.getTankInfo(dir).length)
val tanks = new Array[FluidTankInfo](tankCount)
var i = 0
tankList.foreach(p =>
p.getTankInfo(dir).foreach { t =>
tanks(i) = t
i += 1
}
)
return tanks
}
override def fill(
dir: ForgeDirection,
liquid: FluidStack,
doFill: Boolean
): Int = {
var filled = 0
val initial = liquid.amount
tankList.foreach(p =>
filled += p.fill(dir, copy(liquid, initial - filled), doFill)
)
return filled
}
override def canFill(dir: ForgeDirection, liquid: Fluid) =
tankList.find(_.canFill(dir, liquid)).isDefined
override def canDrain(dir: ForgeDirection, liquid: Fluid) =
tankList.find(_.canDrain(dir, liquid)).isDefined
private def copy(liquid: FluidStack, quantity: Int): FluidStack = {
val copy = liquid.copy
copy.amount = quantity
return copy
}
override def drain(
dir: ForgeDirection,
amount: Int,
doDrain: Boolean
): FluidStack = {
var drained: FluidStack = null
var d_amount = 0
tankList.foreach { p =>
val drain = amount - d_amount
val ret = p.drain(dir, drain, false)
if (
ret != null && ret.amount > 0 && (drained == null || drained
.isFluidEqual(ret))
) {
if (doDrain)
p.drain(dir, drain, true)
if (drained == null)
drained = ret
d_amount += ret.amount
}
}
if (drained != null)
drained.amount = d_amount
return drained
}
override def drain(
dir: ForgeDirection,
fluid: FluidStack,
doDrain: Boolean
): FluidStack = {
val amount = fluid.amount
var drained: FluidStack = null
var d_amount = 0
tankList.foreach { p =>
val drain = copy(fluid, amount - d_amount)
val ret = p.drain(dir, drain, false)
if (
ret != null && ret.amount > 0 && (drained == null || drained
.isFluidEqual(ret))
) {
if (doDrain)
p.drain(dir, drain, true)
if (drained == null)
drained = ret
d_amount += ret.amount
}
}
if (drained != null)
drained.amount = d_amount
return drained
}
}