From 80edf9bd0113b1cc1f43afe890efcb5920ce9618 Mon Sep 17 00:00:00 2001 From: Algent Date: Tue, 1 Sep 2026 14:13:05 +0200 Subject: [PATCH] refactor: port config content to Java --- JAVA_MIGRATION.md | 8 + JAVA_MIGRATION_DIVERGENCES.md | 46 ++++ JAVA_MIGRATION_HANDOFF.md | 22 +- .../microblock/ConfigContent$.java | 226 ++++++++++++++++++ .../codechicken/microblock/ConfigContent.java | 35 +++ .../microblock/ConfigContent.scala | 177 -------------- 6 files changed, 328 insertions(+), 186 deletions(-) create mode 100644 src/main/scala/codechicken/microblock/ConfigContent$.java create mode 100644 src/main/scala/codechicken/microblock/ConfigContent.java delete mode 100644 src/main/scala/codechicken/microblock/ConfigContent.scala diff --git a/JAVA_MIGRATION.md b/JAVA_MIGRATION.md index 98a8a40..3df88c6 100644 --- a/JAVA_MIGRATION.md +++ b/JAVA_MIGRATION.md @@ -1087,3 +1087,11 @@ generated-trait compatibility work. Scala-runtime removal remains a later projec - A clean build passes all 222 plain-JVM tests and the Java 8 Forge server passes all 103 tests. Every callable public descriptor matches the reference; only three unreferenced Scala closure/anonymous classes disappear. `microblock/ConfigContent.scala` is next. +- Characterized `ConfigContent` against untouched Scala. Six plain-JVM cases freeze its facade, companion and exact + mutable-map field, config-file generation and parsing, alias/range semantics, malformed-line recovery, block + registration and IMC filtering/validation. +- Ported the facade and companion directly to Java. Both retained runtime classes and every callable public descriptor + match the reference; the seven Scala iteration/parser closure classes disappear. Public file helpers still throw the + original `IOException` instances without adding checked exceptions to their descriptors or source declarations. +- A clean build passes all 228 plain-JVM tests and the Java 8 Forge server passes all 103 tests. + `microblock/AngelicaCompat.scala` is next. diff --git a/JAVA_MIGRATION_DIVERGENCES.md b/JAVA_MIGRATION_DIVERGENCES.md index 9be416f..951ccce 100644 --- a/JAVA_MIGRATION_DIVERGENCES.md +++ b/JAVA_MIGRATION_DIVERGENCES.md @@ -2492,3 +2492,49 @@ contains no reference to them. - Clean reference/port jars retain the same five supported types; the three compiler artifacts above disappear, and raw `javap` comparison confirms identical callable public names/descriptors. - Client icon reload, material face rendering and Angelica shader overrides remain on the manual checklist. + +## 2026-09-01 — ConfigContent Java port + +The custom micro-material configuration loader is now a Java static facade and `MODULE$` companion. + +### Observable behavior + +No known runtime divergence. A missing `microblocks.cfg` still produces the same five-line default file. Existing +files still accept quoted unlocalized or registry names, add the `minecraft:` namespace only when neither `.` nor `:` +is present, default metadata to zero, expand comma lists and inclusive ascending ranges, leave descending ranges +empty, and replace earlier declarations for the same name. Invalid lines still log twice and do not stop later lines. + +Loading still consumes both the unlocalized-name and registry-name aliases before registration, registers their +metadata in that order, catches registration failures per metadata, and retains unmatched entries so each load can +warn about them. IMC still ignores other keys, requires the exact final `ItemStack` runtime type, checks block +registration before the `[0, 16)` metadata bound, and catches only duplicate-registration failures. + +The public `generateDefault` and `loadLines` methods retain the Scala source surface with no declared checked +exceptions while rethrowing the original `IOException` instance. `parse` alone catches those IO failures and logs +them, matching the reference rather than wrapping them. + +### ABI and reflection compatibility + +The retained runtime types are exactly `ConfigContent` and `ConfigContent$`. Both keep the same six callable public +methods and descriptors, and the companion keeps `MODULE$` plus the private final +`codechicken$microblock$ConfigContent$$nameMap: scala.collection.mutable.Map` field and its public mangled accessor. +The downstream inventory contains no ConfigContent member or reflective references, so no frozen consumer fixture is +needed. Accepted classfile-only differences are removed Scala signature/marker attributes, private Java constructors, +and the companion class initializer without Scala's `ACC_PUBLIC` flag. + +### Compiler artifacts + +Accepted divergence: `ConfigContent$$anonfun$handleIMC$1`, `ConfigContent$$anonfun$handleIMC$2`, +`ConfigContent$$anonfun$load$1`, `ConfigContent$$anonfun$load$1$$anonfun$1`, +`ConfigContent$$anonfun$load$1$$anonfun$apply$1`, `ConfigContent$$anonfun$load$2`, and +`ConfigContent$$anonfun$loadLine$1` disappear. Direct Java loops need none of these private implementation classes, +and the downstream inventory contains no references to them. + +### Validation + +- `ConfigContentCharacterizationTest`: 6 plain-JVM tests, unchanged from the Scala baseline. +- Clean complete plain-JVM suite: 228 tests, 0 failures, 0 errors. +- Java 8 Forge dedicated-server suite: 103 tests, 0 failures, 0 errors. +- Clean reference/port jars retain the same two supported types; the seven compiler artifacts above disappear, and + raw `javap` comparison confirms identical callable public names/descriptors. +- File parsing, registration and IMC behavior are automated; this port adds no new client-only manual check. diff --git a/JAVA_MIGRATION_HANDOFF.md b/JAVA_MIGRATION_HANDOFF.md index 2110a34..f8aa111 100644 --- a/JAVA_MIGRATION_HANDOFF.md +++ b/JAVA_MIGRATION_HANDOFF.md @@ -12,8 +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`. 122 commits including the API-cleanup plan and separate characterization and -port commits through `BlockMicroMaterial`. +Branch: `algent/java`. Base: `master`. 124 commits including the API-cleanup plan and separate characterization and +port commits through `ConfigContent`. ## The one rule that matters @@ -67,7 +67,7 @@ awk -F'"' '/> codechicken$microblock$ConfigContent$$nameMap = new HashMap<>(); + + private ConfigContent$() {} + + public Map> codechicken$microblock$ConfigContent$$nameMap() { + return codechicken$microblock$ConfigContent$$nameMap; + } + + public void parse(File cfgDir) { + File cfgFile = new File(cfgDir, "microblocks.cfg"); + try { + if (cfgFile.exists()) { + loadLinesIO(cfgFile); + } else { + generateDefaultIO(cfgFile); + } + } catch (IOException exception) { + MicroblockProxy.logger().error("Error parsing config", exception); + } + } + + public void generateDefault(File cfgFile) { + try { + generateDefaultIO(cfgFile); + } catch (IOException exception) { + throw ConfigContent$.rethrow(exception); + } + } + + public void loadLine(String line) { + if (line.startsWith("#") || line.length() < 3) { + return; + } + + if (line.charAt(0) != '"') { + throw new IllegalArgumentException("Line must begin with a quote"); + } + int secondQuote = line.indexOf('"', 1); + if (secondQuote < 0) { + throw new IllegalArgumentException("Unmatched quotes"); + } + + String name = line.substring(1, secondQuote); + if (!name.contains(".") && !name.contains(":")) { + name = "minecraft:" + name; + } + + List metadata = new ArrayList<>(); + metadata.add(0); + if (line.length() > secondQuote + 1) { + if (line.charAt(secondQuote + 1) != ':') { + throw new IllegalArgumentException("Name must be followed by a colon separator"); + } + + metadata.clear(); + for (String value : line.substring(secondQuote + 2).split(",")) { + if (value.contains("-")) { + String[] bounds = value.split("-"); + if (bounds.length != 2) { + throw new IllegalArgumentException("Invalid - separated range"); + } + int start = Integer.parseInt(bounds[0]); + int end = Integer.parseInt(bounds[1]); + if (start <= end) { + for (int current = start;; current++) { + metadata.add(current); + if (current == end) { + break; + } + } + } + } else { + metadata.add(Integer.parseInt(value)); + } + } + } + + codechicken$microblock$ConfigContent$$nameMap.put(name, JavaConversions.asScalaBuffer(metadata).toList()); + } + + public void loadLines(File cfgFile) { + try { + loadLinesIO(cfgFile); + } catch (IOException exception) { + throw ConfigContent$.rethrow(exception); + } + } + + public void load() { + java.util.Map> names = JavaConversions + .mutableMapAsJavaMap(codechicken$microblock$ConfigContent$$nameMap); + for (Object value : Block.blockRegistry) { + Block block = (Block) value; + List metadata = new ArrayList<>(); + addAll(metadata, names.remove(block.getUnlocalizedName())); + addAll(metadata, names.remove((String) Block.blockRegistry.getNameForObject(block))); + for (Object metaValue : metadata) { + int meta = (Integer) metaValue; + try { + BlockMicroMaterial.createAndRegister(block, meta); + } catch (IllegalStateException exception) { + MicroblockProxy.logger().error( + "Unable to register micro material: " + BlockMicroMaterial.materialKey(block, meta) + + "\n\t" + + exception.getMessage()); + } catch (Exception exception) { + MicroblockProxy.logger().error( + "Unable to register micro material: " + BlockMicroMaterial.materialKey(block, meta), + exception); + } + } + } + + for (Entry> entry : names.entrySet()) { + MicroblockProxy.logger().warn( + "Unable to add micro material for block with unlocalised name " + entry.getKey() + + " as it doesn't exist"); + } + } + + public void handleIMC(Seq messages) { + Iterator iterator = messages.iterator(); + while (iterator.hasNext()) { + IMCMessage message = iterator.next(); + if (!"microMaterial".equals(message.key)) { + continue; + } + + if (message.getMessageType() != ItemStack.class) { + imcError(message, "value is not an instanceof ItemStack"); + continue; + } + + ItemStack stack = message.getItemStackValue(); + if (!Block.blockRegistry.containsId(Item.getIdFromItem(stack.getItem()))) { + imcError(message, "Invalid Block: " + stack.getItem()); + } else if (stack.getItemDamage() < 0 || stack.getItemDamage() >= 16) { + imcError(message, "Invalid metadata: " + stack.getItemDamage()); + } else { + try { + BlockMicroMaterial + .createAndRegister(Block.getBlockFromItem(stack.getItem()), stack.getItemDamage()); + } catch (IllegalStateException exception) { + imcError( + message, + "Unable to register micro material: " + + BlockMicroMaterial + .materialKey(Block.getBlockFromItem(stack.getItem()), stack.getItemDamage()) + + "\n\t" + + exception.getMessage()); + } + } + } + } + + private static void generateDefaultIO(File cfgFile) throws IOException { + PrintWriter writer = new PrintWriter(cfgFile); + writer.println("#Configuration file for adding microblock materials for aesthetic blocks added by mods"); + writer.println("#Each line needs to be of the form :"); + writer.println( + "# is the unlocalised name or registry key of the block/item enclosed in quotes. NEI can help you find these"); + writer.println( + "# may be ommitted, in which case it defaults to 0, otherwise it can be a number, a comma separated list of numbers, or a dash separated range"); + writer.println("#Ex. \"dirt\" \"minecraft:planks\":3 \"iron_ore\":1,2,3,5 \"ThermalFoundation:Storage\":0-15"); + writer.close(); + } + + private void loadLinesIO(File cfgFile) throws IOException { + BufferedReader reader = new BufferedReader(new FileReader(cfgFile)); + String line; + do { + line = reader.readLine(); + if (line != null) { + try { + loadLine(line); + } catch (Exception exception) { + MicroblockProxy.logger().error("Invalid line in microblocks.cfg: " + line); + MicroblockProxy.logger().error(exception.getMessage()); + } + } + } while (line != null); + reader.close(); + } + + private static void addAll(List destination, Seq source) { + if (source != null) { + destination.addAll(JavaConversions.seqAsJavaList(source)); + } + } + + private static void imcError(IMCMessage message, String error) { + MicroblockProxy.logger().error("Invalid microblock IMC message from " + message.getSender() + ": " + error); + } + + @SuppressWarnings("unchecked") + private static RuntimeException rethrow(Throwable throwable) throws T { + throw (T) throwable; + } +} diff --git a/src/main/scala/codechicken/microblock/ConfigContent.java b/src/main/scala/codechicken/microblock/ConfigContent.java new file mode 100644 index 0000000..c55b5be --- /dev/null +++ b/src/main/scala/codechicken/microblock/ConfigContent.java @@ -0,0 +1,35 @@ +package codechicken.microblock; + +import java.io.File; + +import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage; +import scala.collection.Seq; + +public final class ConfigContent { + + private ConfigContent() {} + + public static void parse(File cfgDir) { + ConfigContent$.MODULE$.parse(cfgDir); + } + + public static void generateDefault(File cfgFile) { + ConfigContent$.MODULE$.generateDefault(cfgFile); + } + + public static void loadLine(String line) { + ConfigContent$.MODULE$.loadLine(line); + } + + public static void loadLines(File cfgFile) { + ConfigContent$.MODULE$.loadLines(cfgFile); + } + + public static void load() { + ConfigContent$.MODULE$.load(); + } + + public static void handleIMC(Seq messages) { + ConfigContent$.MODULE$.handleIMC(messages); + } +} diff --git a/src/main/scala/codechicken/microblock/ConfigContent.scala b/src/main/scala/codechicken/microblock/ConfigContent.scala deleted file mode 100644 index 5e9c3d6..0000000 --- a/src/main/scala/codechicken/microblock/ConfigContent.scala +++ /dev/null @@ -1,177 +0,0 @@ -package codechicken.microblock - -import java.io.File -import java.io.IOException -import java.io.PrintWriter -import java.io.BufferedReader -import java.io.FileReader -import scala.collection.mutable.{Map => MMap} -import net.minecraft.block.Block -import net.minecraft.item.Item -import java.lang.Exception -import codechicken.microblock.handler.MicroblockProxy -import cpw.mods.fml.common.event.FMLInterModComms.IMCMessage -import net.minecraft.item.ItemStack -import BlockMicroMaterial.createAndRegister -import BlockMicroMaterial.materialKey -import java.lang.{Iterable => JIterable} -import scala.collection.JavaConversions._ - -object ConfigContent { - private val nameMap = MMap[String, Seq[Int]]() - - def parse(cfgDir: File) { - val cfgFile = new File(cfgDir, "microblocks.cfg") - try { - if (!cfgFile.exists()) - generateDefault(cfgFile) - else - loadLines(cfgFile) - } catch { - case e: IOException => - MicroblockProxy.logger.error("Error parsing config", e) - } - } - - def generateDefault(cfgFile: File) { - val writer = new PrintWriter(cfgFile) - writer.println( - "#Configuration file for adding microblock materials for aesthetic blocks added by mods" - ) - writer.println("#Each line needs to be of the form :") - writer.println( - "# is the unlocalised name or registry key of the block/item enclosed in quotes. NEI can help you find these" - ) - writer.println( - "# may be ommitted, in which case it defaults to 0, otherwise it can be a number, a comma separated list of numbers, or a dash separated range" - ) - writer.println( - "#Ex. \"dirt\" \"minecraft:planks\":3 \"iron_ore\":1,2,3,5 \"ThermalFoundation:Storage\":0-15" - ) - writer.close() - } - - def loadLine(line: String) { - if (line.startsWith("#") || line.length < 3) - return - - if (line.charAt(0) != '\"') - throw new IllegalArgumentException("Line must begin with a quote") - val q2 = line.indexOf('\"', 1) - if (q2 < 0) - throw new IllegalArgumentException("Unmatched quotes") - - var name = line.substring(1, q2) - if (!name.contains('.') && !name.contains(':')) - name = "minecraft:" + name - - var meta = Seq(0) - if (line.length > q2 + 1) { - if (line.charAt(q2 + 1) != ':') - throw new IllegalArgumentException( - "Name must be followed by a colon separator" - ) - - meta = line.substring(q2 + 2).split(",").flatMap { s => - if (s.contains("-")) { - val split2 = s.split("-") - if (split2.length != 2) - throw new IllegalArgumentException("Invalid - separated range") - split2(0).toInt to split2(1).toInt - } else { - Seq(s.toInt) - } - } - } - - nameMap.put(name, meta) - } - - def loadLines(cfgFile: File) { - val reader = new BufferedReader(new FileReader(cfgFile)) - var s: String = null - do { - s = reader.readLine - if (s != null) { - try { - loadLine(s) - } catch { - case e: Exception => - MicroblockProxy.logger.error( - "Invalid line in microblocks.cfg: " + s - ) - MicroblockProxy.logger.error(e.getMessage) - } - } - } while (s != null) - reader.close() - } - - def load() { - for (block <- Block.blockRegistry.asInstanceOf[JIterable[Block]]) { - val metas = Seq( - block.getUnlocalizedName, - Block.blockRegistry.getNameForObject(block) - ).flatMap(nameMap.remove).flatten - metas.foreach { m => - try { - createAndRegister(block, m) - } catch { - case e: IllegalStateException => - MicroblockProxy.logger.error( - "Unable to register micro material: " + - materialKey(block, m) + "\n\t" + e.getMessage - ) - case e: Exception => - MicroblockProxy.logger.error( - "Unable to register micro material: " + materialKey(block, m), - e - ) - } - } - } - - nameMap.foreach(e => - MicroblockProxy.logger.warn( - "Unable to add micro material for block with unlocalised name " + e._1 + " as it doesn't exist" - ) - ) - } - - def handleIMC(messages: Seq[IMCMessage]) { - messages.filter(_.key == "microMaterial").foreach { msg => - def error(s: String) { - MicroblockProxy.logger.error( - "Invalid microblock IMC message from " + msg.getSender + ": " + s - ) - } - - if (msg.getMessageType != classOf[ItemStack]) - error("value is not an instanceof ItemStack") - else { - val stack = msg.getItemStackValue - if (!Block.blockRegistry.containsId(Item.getIdFromItem(stack.getItem))) - error("Invalid Block: " + stack.getItem) - else if (stack.getItemDamage < 0 || stack.getItemDamage >= 16) - error("Invalid metadata: " + stack.getItemDamage) - else { - try { - createAndRegister( - Block.getBlockFromItem(stack.getItem), - stack.getItemDamage - ) - } catch { - case e: IllegalStateException => - error( - "Unable to register micro material: " + - materialKey( - Block.getBlockFromItem(stack.getItem), - stack.getItemDamage - ) + "\n\t" + e.getMessage - ) - } - } - } - } - } -}