diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index c8ce789..817e97a 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -509,3 +509,9 @@ These ranges were formed before designing the characterization suite and should - Established that for interfaces carrying no implementation, the characterization is the shape: every member abstract and public, no superinterface, and the exact member set. That is enough to catch the two realistic failure modes, a stray default and a renamed accessor. - Noted that `IRedstonePart.scala` is misleadingly named and is not a marker-trait file. It carries six traits plus `RedstoneInteractions`, whose `MODULE$` is load-bearing, and was moved out of the low-risk group. - Noted a documentation gap, not addressed here: this log was last appended for the `TItemMultiPart` port. The eight ports between it and this entry — `TEdgePart`, `Saw`, both registries, `TileMultipart`, `TMultiPart`, `TickScheduler` and `BlockMultipart` — are recorded in `JAVA_MIGRATION_DIVERGENCES.md` but never made it here, so the "Current status" section above should be read with that in mind. +- Ported `MultipartHelper`, `MultipartHelper$` and `MultipartHelper$IPartTileConverter` to Java. All three are public-member- and descriptor-identical to the reference and the full emitted class list is unchanged, so this port neither added nor removed a class. +- Kept `MultipartHelper$` on the strength of a reflective string constant alone. It is not among the 17 `MODULE$` singletons read from bytecode and no jar links against it, but guidenh names it, and the inventory warns that removing a companion breaks such consumers invisibly. This is the opposite call to `IconHitEffects$`, which was dropped because nothing referenced it in bytecode or by name, and it establishes that the `MODULE$` list alone is not sufficient grounds to delete a companion. +- Found a reusable characterization technique: a class that cannot class-initialize headless is a probe for control flow. `MultipartSaveLoad` reflects into `TileEntity`'s static maps through `ObfMapping` and always throws under a plain JVM, so `createTileFromNBT` returning null rather than raising proves the id guard short-circuits before the `loadingWorld` assignment. Assert `LinkageError` rather than the exact type, because the first attempt raises `ExceptionInInitializerError` and later ones raise `NoClassDefFoundError`. +- Confirmed that erasure does not weaken `IPartTileConverter.convert`. The cast to `T` compiles away, but the `ClassCastException` a mismatched tile produces comes from the synthetic bridge on the subclass overriding `convertMulti(T)`, which is the same mechanism Scala's `asInstanceOf[T]` relied on. It is now pinned by a test, because the code reads as though the check was lost. +- Added five Forge server tests, doubling that suite, because most of this class cannot run headless. They cover tile construction through the ASM generator, the NBT round trip through the save/load hooks, `registerTileConverter` appending to a Scala `MutableList` from Java, and `sendDescPacket` against a loaded chunk. +- Dropped the two commented-out blocks the reference carried, the `PlayerInstance.playersInChunk` reflection and the multi-tile `sendDescPackets`, rather than reproducing dead Scala as dead Java. The reason they existed, a missing forge access transformer, is now in the class javadoc. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index c0e0318..7675283 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -897,3 +897,64 @@ random ticks. This is a recompiled-Scala-consumer break with no shipping consume - Public members, descriptors and the full emitted class list diffed against a reference jar built at `3e68e67`. - Random tick firing over time still needs a world and stays on the manual checklist, as does torch display-tick rendering and hollow-cover connection sizing. + +## 2026-08-15 — MultipartHelper Java port + +The NBT and description-packet entry point. Two of its statics are linked against by shipping jars, and guidenh +reflects on both `MultipartHelper` and `MultipartHelper$` by name. + +### Observable behavior + +No known divergence. The id guard still returns null before assigning `MultipartSaveLoad.loadingWorld`, so a tag that +is not a saved multipart still leaves the loading world untouched. `sendDescPacket` still resolves the chunk from the +tile's own coordinates and still sends nothing when `getDescPacket` returns null, which it does when the iterator +yields no `TileMultipart`. + +`createTileFromParts` now builds one `JavaConversions` wrapper and passes it to both `generateCompositeTile` and +`loadParts`, where the Scala applied the implicit conversion separately at each call site. Both wrappers were views +over the same `java.lang.Iterable`, so this is one allocation fewer and the same traversal. + +### Supported JVM API + +- `MultipartHelper` is public-member-identical and descriptor-identical to the reference, including + `createTileFromParts`'s `java.lang.Iterable` parameter, which is easy to misread as Scala's. +- `MultipartHelper$IPartTileConverter` is identical, including the `clazz()` accessor Scala generated for its `val`. +- `MultipartHelper$` keeps `MODULE$`, its private constructor and all four instance forwarders, identical. +- The full emitted class list is unchanged: nothing was added or removed. + +`MultipartHelper$` was kept deliberately. It is not among the 17 `MODULE$` singletons the inventory found read from +bytecode, and no jar links against it, but guidenh names it as a reflective string constant. The inventory warns that +removing a companion breaks those consumers even where no bytecode reference exists, so this one stays. This is the +opposite call to `IconHitEffects$`, which was dropped because nothing referenced it in bytecode *or* by name. + +### Differences that are not API + +- `MultipartHelper` gains a private constructor, as every converted Scala `object` has. +- `MultipartHelper$`'s class initializer loses its `ACC_PUBLIC` flag: Scala emits `public static {}`, `javac` emits + `static {}`. The JVM invokes `` implicitly and it cannot be named by any caller. +- `IPartTileConverter.convertMulti` returns `Collections.emptyList()` or `Collections.singletonList(part)` instead of a + `scala.collection.convert.Wrappers$SeqWrapper` over a Scala `Seq`. The declared type was always `java.lang.Iterable` + and no consumer implements or inspects the concrete type, so this is an implementation detail, and it removes a + wrapper allocation per converted tile. +- The two commented-out blocks the reference carried — the `PlayerInstance.playersInChunk` reflection and the + multi-tile `sendDescPackets` — are not reproduced as dead code. The reason they were removed, a missing forge access + transformer, is recorded in the class javadoc instead. + +### The cast in convert is still checked + +`convert(TileEntity)` calls `convertMulti((T) tile)`, and erasure turns that cast into `(TileEntity)`, which cannot +fail. The `ClassCastException` a mismatched tile produces comes from the synthetic bridge method on the *subclass* +that overrides `convertMulti(T)`, exactly as it did under Scala's `asInstanceOf[T]`. The mechanism is unchanged, and +`convertFailsOnATileTheConverterDoesNotAccept` pins it because it looks like erasure should have swallowed it. + +### Validation + +- Complete plain-JVM suite: 107 tests, 0 failures, 0 errors. +- Clean `spotlessApply checkstyleTest build`: passing. +- Java 8 Forge dedicated-server suite: 10 tests, 0 failures, 0 errors, 5 of them new for this port. They cover + everything the plain-JVM suite cannot reach: tile construction through the ASM generator, the NBT round trip through + the save/load hooks, `registerTileConverter` appending to a Scala `MutableList`, and `sendDescPacket` against a + loaded chunk. +- Public members, descriptors and the full emitted class list diffed against a reference jar built at `0fdf9e5`. +- What stays manual: a description packet actually arriving at a watching client. The functional test builds and sends + one with no players connected, so the wire format and the client's handling of it are still unasserted. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 3efb153..9ce977e 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -10,7 +10,7 @@ what breaks, and what is left. The other documents hold the reasoning. | `JAVA_MIGRATION_DIVERGENCES.md` | Every intentional difference from the reference, one entry per port | | `JAVA_MIGRATION_MANUAL_CHECKS.md` | What no automated test can cover, and must be checked by hand in a client | -Branch: `algent/java`. Base: `master`. 41 commits so far. +Branch: `algent/java`. Base: `master`. 43 commits so far. ## The one rule that matters @@ -56,7 +56,7 @@ awk -F'"' '/ ... }` needs an explicit `AbstractFunction1`. +**A companion object can be load-bearing without a single bytecode reference.** The inventory's 17 `MODULE$` list is +not the whole test — check the reflective string constants too. `MultipartHelper$` is in neither the `MODULE$` list nor +any consumer's constant pool as a type, but guidenh names it as a string, so it was kept. `IconHitEffects$` was in +neither and was dropped. Check both lists before deleting a companion. + +**Classes that cannot class-initialize headless make good probes.** `MultipartSaveLoad` reflects into `TileEntity`'s +static maps through `ObfMapping` and always throws under a plain JVM. That turns "did this branch reach the loader?" +into an assertion: returning normally proves the guard short-circuited, and `assertThrows(LinkageError.class, ...)` +proves the other branch did reach it. Use `LinkageError`, not the exact type — the first attempt raises +`ExceptionInInitializerError` and every later one raises `NoClassDefFoundError`, so test order would otherwise matter. + **Java 8 target.** No `List.of`, no `var`, no switch expressions in main or test sources. **Two test classes sharing global registry state** must guard their registrations, and the registries' error paths call @@ -149,14 +160,14 @@ All eight load-bearing `$class` helpers from the inventory, both registries, and `MultiPartRegistry`, `TileMultipart`, `TMultiPart`, `TickScheduler`, `BlockMultipart`. Plus the six marker interfaces: `TSlottedPart`, `IRandomDisplayTick`, `INeighborTileChange`, `TRandomUpdateTick`, -`ISidedHollowConnect`, `IMicroMaterialRender`. +`ISidedHollowConnect`, `IMicroMaterialRender`, and `MultipartHelper`. -62 Java files, 55 Scala files, ~6,733 Scala lines left (non-blank; that is the metric this figure has always used). +64 Java files, 54 Scala files, ~6,636 Scala lines left (non-blank; that is the metric this figure has always used). ## What is left, and in what order -**Low risk, good next steps.** `TileCache`, `MultipartHelper`, `PacketScheduler`, `ControlKeyModifier`, and the two -`package.scala` objects. +**Low risk, good next steps.** `TileCache`, `PacketScheduler`, `ControlKeyModifier`, and the two `package.scala` +objects. `IRedstonePart.scala` is misleadingly named and is **not** a marker-trait file. It holds six traits plus `RedstoneInteractions`, whose `MODULE$` is load-bearing, so it is its own piece of work at medium risk. diff --git a/src/main/scala/codechicken/multipart/MultipartHelper$.java b/src/main/scala/codechicken/multipart/MultipartHelper$.java new file mode 100644 index 0000000..17b4627 --- /dev/null +++ b/src/main/scala/codechicken/multipart/MultipartHelper$.java @@ -0,0 +1,31 @@ +package codechicken.multipart; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; + +/** + * Scala companion singleton, kept because guidenh reflects on this name as well as on MultipartHelper. Pure forwarders. + */ +public final class MultipartHelper$ { + + public static final MultipartHelper$ MODULE$ = new MultipartHelper$(); + + private MultipartHelper$() {} + + public TileEntity createTileFromNBT(World world, NBTTagCompound tag) { + return MultipartHelper.createTileFromNBT(world, tag); + } + + public void sendDescPacket(World world, TileEntity tile) { + MultipartHelper.sendDescPacket(world, tile); + } + + public void registerTileConverter(MultipartHelper.IPartTileConverter converter) { + MultipartHelper.registerTileConverter(converter); + } + + public TileMultipart createTileFromParts(Iterable parts) { + return MultipartHelper.createTileFromParts(parts); + } +} diff --git a/src/main/scala/codechicken/multipart/MultipartHelper.java b/src/main/scala/codechicken/multipart/MultipartHelper.java new file mode 100644 index 0000000..9ec27d8 --- /dev/null +++ b/src/main/scala/codechicken/multipart/MultipartHelper.java @@ -0,0 +1,115 @@ +package codechicken.multipart; + +import java.util.Arrays; +import java.util.Collections; + +import net.minecraft.nbt.NBTTagCompound; +import net.minecraft.tileentity.TileEntity; +import net.minecraft.world.World; +import net.minecraft.world.chunk.Chunk; + +import codechicken.lib.packet.PacketCustom; +import codechicken.multipart.handler.MultipartSPH; +import codechicken.multipart.handler.MultipartSaveLoad; +import scala.collection.JavaConversions; + +/** + * Static helper class for handling the unusual way that multipart tile entities load from nbt and send description + * packets. + *

+ * Multipart tile entities will all save themselves with the id "savedMultipart" which if normally loaded by minecraft, + * will create a dummy tile entity which just holds the NBT it was read from. These dummies are then converted to actual + * container tiles on the ChunkLoad event. The createTileFromNBT function should be used to construct a multipart tile + * from NBT without the ChunkLoad event. + *

+ * Multipart tile entities do not send description packets via the conventional means of one packet per tile when + * PlayerInstance calls for it, to do so would be terribly inefficient. Instead, the ChunkWatch event is used to batch + * all the describing data for a chunk into one packet which is compressed using relative positions. The sendDescPacket + * function should be used to send the description packet of a tile without a ChunkWatch event. + *

+ * An example of using this class to move blocks/tile entites around can be found at + * www.chickenbones.craftsaddle.org/Files/Other/ItemDevTool2.java + *

+ * The reference carried a commented-out sendDescPackets batching several tiles at once. It was removed for compilation + * until a PlayerInstance access transformer is pulled into forge, and is not reinstated here. + */ +public final class MultipartHelper { + + private MultipartHelper() {} + + public static TileEntity createTileFromNBT(World world, NBTTagCompound tag) { + if (!tag.getString("id").equals("savedMultipart")) { + return null; + } + + MultipartSaveLoad.loadingWorld_$eq(world); + return TileMultipart.createFromNBT(tag); + } + + /** + * Note. This method should only be used to send tiles that have been created on the server mid-game via an NBT load + * to clients. + */ + public static void sendDescPacket(World world, TileEntity tile) { + Chunk c = world.getChunkFromBlockCoords(tile.xCoord, tile.zCoord); + PacketCustom pkt = MultipartSPH.getDescPacket(c, Arrays.asList(tile).iterator()); + if (pkt != null) { + pkt.sendToChunk(world, c.xPosition, c.zPosition); + } + } + + public static void registerTileConverter(IPartTileConverter converter) { + MultipartSaveLoad.converters().$plus$eq(converter); + } + + public static TileMultipart createTileFromParts(Iterable parts) { + scala.collection.Iterable scalaParts = JavaConversions.iterableAsScalaIterable(parts); + TileMultipart tile = MultipartGenerator$.MODULE$.generateCompositeTile(null, scalaParts, false); + tile.loadParts(scalaParts); + return tile; + } + + /** Helper class for converting tile entities to multiparts on chunk load. */ + public abstract static class IPartTileConverter { + + private final Class clazz; + + public IPartTileConverter(Class clazz) { + this.clazz = clazz; + } + + public Class clazz() { + return clazz; + } + + /** + * @return true if this tile can be converted by this converter. If canConvert returns true, but convertMulti + * returns no parts, the tile will be deleted + */ + public boolean canConvert(TileEntity tile) { + return clazz.isInstance(tile); + } + + @SuppressWarnings("unchecked") + public Iterable convert(TileEntity tile) { + return convertMulti((T) tile); + } + + /** + * Convert the TileEntity into multiple parts + * + * @return An iterable list of parts or an empty list to delete the tile + */ + public Iterable convertMulti(T tile) { + TMultiPart part = convertOne(tile); + return part == null ? Collections.emptyList() : Collections.singletonList(part); + } + + /** + * Convert the TileEntity into a part + * + * @return The converted part, or null to delete the tile + */ + public abstract TMultiPart convertOne(T tile); + } +} diff --git a/src/main/scala/codechicken/multipart/MultipartHelper.scala b/src/main/scala/codechicken/multipart/MultipartHelper.scala deleted file mode 100644 index 6b85dc1..0000000 --- a/src/main/scala/codechicken/multipart/MultipartHelper.scala +++ /dev/null @@ -1,112 +0,0 @@ -package codechicken.multipart - -import net.minecraft.tileentity.TileEntity -import net.minecraft.nbt.NBTTagCompound -import net.minecraft.world.World -import codechicken.multipart.handler.MultipartSaveLoad -import com.google.common.collect.LinkedListMultimap -import scala.collection.JavaConversions._ -import scala.collection.JavaConverters._ -import codechicken.multipart.handler.MultipartSPH -import net.minecraft.world.WorldServer -import java.util.Arrays -import java.lang.Iterable - -/** Static helper class for handling the unusual way that multipart tile - * entities load from nbt and send description packets
Multipart tile - * entities will all save themselves with the id "savedMultipart" which if - * normally loaded by minecraft, will create a dummy tile entity which just - * holds the NBT it was read from. These dummies are then converted to actual - * container tiles on the ChunkLoad event. The createTileFromNBT function - * should be used to construct a multipart tile from NBT without the ChunkLoad - * event.
Multipart tile entities do not send description packets via the - * conventional means of one packet per tile when PlayerInstance calls for it, - * to do so would be terribly inefficient. Instead, the ChunkWatch event is - * used to batch all the describing data for a chunk into one packet which is - * compressed using relative positions. The sendDescPacket(s) functions should - * be used to send the description packet of a tile or tiles without a - * ChunkWatch event.
An example of using this class to move blocks/tile - * entites around can be found at - * www.chickenbones.craftsaddle.org/Files/Other/ItemDevTool2.java - */ -object MultipartHelper { - /*val f_playersInChunk = classOf[PlayerInstance].getDeclaredField( - new ObfMapping("net/minecraft/server/management/PlayerInstance", "playersInChunk", "Ljava/util/List;") - .toRuntime.s_name) - f_playersInChunk.setAccessible(true) - - def playersInChunk(inst:PlayerInstance) = f_playersInChunk.get(inst).asInstanceOf[List[_]]*/ - - def createTileFromNBT(world: World, tag: NBTTagCompound): TileEntity = { - if (!tag.getString("id").equals("savedMultipart")) - return null - - MultipartSaveLoad.loadingWorld = world - return TileMultipart.createFromNBT(tag) - } - - /** Note. This method should only be used to send tiles that have been created - * on the server mid-game via an NBT load to clients. - */ - def sendDescPacket(world: World, tile: TileEntity) { - val c = world.getChunkFromBlockCoords(tile.xCoord, tile.zCoord) - val pkt = MultipartSPH.getDescPacket(c, Arrays.asList(tile).iterator) - if (pkt != null) - pkt.sendToChunk(world, c.xPosition, c.zPosition) - } - - /* Removed for compilation until PlayerInstance access transformer is pulled in forge - def sendDescPackets(world:World, tiles:Iterable[TileEntity]) { - val map = LinkedListMultimap.create[Long, TileEntity]() - tiles.filter(_.isInstanceOf[TileMultipart]).foreach(t => map.put(t.xCoord.toLong<<32|t.zCoord, t)) - - val mgr = world.asInstanceOf[WorldServer].getPlayerManager - map.asMap.entrySet.foreach{e => - val coord = e.getKey - val c = world.getChunkFromBlockCoords((coord>>32).toInt, coord.toInt) - lazy val pkt = MultipartSPH.getDescPacket(c, e.getValue.iterator) - val inst = mgr.getOrCreateChunkWatcher(c.xPosition, c.zPosition, false) - if(!inst.playersWatchingChunk.isEmpty) - inst.sendToAllPlayersWatchingChunk(pkt.toPacket) - } - }*/ - - /** Helper class for converting tile entities to multiparts on chunk load - */ - abstract class IPartTileConverter[T <: TileEntity](val clazz: Class[T]) { - - /** @return - * true if this tile can be converted by this converter. If canConvert - * returns true, but convertMulti returns no parts, the tile will be - * deleted - */ - def canConvert(tile: TileEntity) = clazz.isInstance(tile) - - def convert(tile: TileEntity) = convertMulti(tile.asInstanceOf[T]) - - /** Convert the TileEntity into multiple parts - * @return - * An iterable list of parts or an empty list to delete the tile - */ - def convertMulti(tile: T): Iterable[TMultiPart] = convertOne(tile) match { - case null => Seq() - case p => Seq(p) - } - - /** Convert the TileEntity into a part - * @return - * The converted part, or null to delete the tile - */ - def convertOne(tile: T): TMultiPart - } - - def registerTileConverter(converter: IPartTileConverter[_]) { - MultipartSaveLoad.converters += converter - } - - def createTileFromParts(parts: Iterable[TMultiPart]) = { - val tile = MultipartGenerator.generateCompositeTile(null, parts, false) - tile.loadParts(parts) - tile - } -}