diff --git a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java
index 1274ecd40b0..7ec1855bc21 100644
--- a/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java
+++ b/maven/build-engine/src/main/java/com/codename1/builders/IPhoneBuilder.java
@@ -7385,6 +7385,28 @@ public void usesClassMethod(String cls, String method) {
throw new BuildException("Failed to update infoplist file", ex);
}
+ // ios.optimizationLevel: the clang level of the optimized configurations.
+ // See XcodeOptimizationLevel; the cloud builder does the same.
+ String optimizationLevel = request.getArg("ios.optimizationLevel", null);
+ if (optimizationLevel != null && optimizationLevel.trim().length() > 0) {
+ optimizationLevel = optimizationLevel.trim();
+ if (!XcodeOptimizationLevel.isValid(optimizationLevel)) {
+ throw new BuildException("ios.optimizationLevel must be one of 0, 1, 2, 3, s, z or fast, not "
+ + optimizationLevel);
+ }
+ try {
+ java.nio.file.Path pbxPath = new File(tmpFile, "dist/" + request.getMainClass()
+ + ".xcodeproj/project.pbxproj").toPath();
+ String before = new String(java.nio.file.Files.readAllBytes(pbxPath), "UTF-8");
+ String after = XcodeOptimizationLevel.apply(before, optimizationLevel);
+ if (!after.equals(before)) {
+ java.nio.file.Files.write(pbxPath, after.getBytes("UTF-8"));
+ }
+ } catch (IOException ex) {
+ throw new BuildException("Failed to apply ios.optimizationLevel", ex);
+ }
+ }
+
try {
normalizeAssetCatalogs(request);
} catch (Exception ex) {
diff --git a/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java b/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java
new file mode 100644
index 00000000000..24b3465965a
--- /dev/null
+++ b/maven/build-engine/src/main/java/com/codename1/builders/XcodeOptimizationLevel.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Codename One designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Codename One through http://www.codenameone.com/ if you
+ * need additional information or have any questions.
+ */
+package com.codename1.builders;
+
+/// The `ios.optimizationLevel` build hint: the clang optimization level of the
+/// generated project's optimized configurations.
+///
+/// Every `GCC_OPTIMIZATION_LEVEL` the project sets to something other than `0`
+/// is replaced, so Release (and any other optimized configuration) changes
+/// while Debug stays unoptimized. `z` is the one that matters in practice: the
+/// device runtime, whose thousands of generated interpreter shims pushed its
+/// executable past the App Store's 500 MB limit, builds with it. It is slower
+/// code, which an app that spends its time elsewhere never notices.
+///
+/// Editing the project, rather than asking the translator, means it works with
+/// whichever ParparVM produced the project.
+final class XcodeOptimizationLevel {
+ private static final String KEY = "GCC_OPTIMIZATION_LEVEL = ";
+
+ private XcodeOptimizationLevel() {
+ }
+
+ /// The levels clang accepts as `-O`.
+ static boolean isValid(String level) {
+ return "0".equals(level) || "1".equals(level) || "2".equals(level) || "3".equals(level)
+ || "s".equals(level) || "z".equals(level) || "fast".equals(level);
+ }
+
+ /// Returns the project text with every non-zero `GCC_OPTIMIZATION_LEVEL`
+ /// set to `level`.
+ static String apply(String pbx, String level) {
+ StringBuilder out = new StringBuilder(pbx.length());
+ int from = 0;
+ while (true) {
+ int at = pbx.indexOf(KEY, from);
+ if (at < 0) {
+ out.append(pbx, from, pbx.length());
+ return out.toString();
+ }
+ int valueStart = at + KEY.length();
+ int valueEnd = pbx.indexOf(';', valueStart);
+ if (valueEnd < 0) {
+ out.append(pbx, from, pbx.length());
+ return out.toString();
+ }
+ String value = pbx.substring(valueStart, valueEnd).trim();
+ out.append(pbx, from, valueStart);
+ out.append("0".equals(value) ? value : level);
+ from = valueEnd;
+ }
+ }
+}
diff --git a/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java b/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java
new file mode 100644
index 00000000000..15af907210b
--- /dev/null
+++ b/maven/build-engine/src/test/java/com/codename1/builders/XcodeOptimizationLevelTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2026, Codename One and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Codename One designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Codename One through http://www.codenameone.com/ if you
+ * need additional information or have any questions.
+ */
+package com.codename1.builders;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import org.junit.jupiter.api.Test;
+
+class XcodeOptimizationLevelTest {
+ private static final String PROJECT = "\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n"
+ + "\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1\";\n"
+ + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = 3;\n"
+ + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = s;\n";
+
+ @Test
+ void optimizedConfigurationsTakeTheLevelAndDebugStaysUnoptimized() {
+ assertEquals("\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n"
+ + "\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = \"DEBUG=1\";\n"
+ + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = z;\n"
+ + "\t\t\t\tGCC_OPTIMIZATION_LEVEL = z;\n",
+ XcodeOptimizationLevel.apply(PROJECT, "z"));
+ }
+
+ @Test
+ void applyingTwiceChangesNothing() {
+ String once = XcodeOptimizationLevel.apply(PROJECT, "z");
+ assertEquals(once, XcodeOptimizationLevel.apply(once, "z"));
+ }
+
+ @Test
+ void aProjectWithoutTheSettingIsUnchanged() {
+ String pbx = "\t\t\t\tSDKROOT = iphoneos;\n";
+ assertEquals(pbx, XcodeOptimizationLevel.apply(pbx, "z"));
+ }
+
+ @Test
+ void onlyClangLevelsAreValid() {
+ assertTrue(XcodeOptimizationLevel.isValid("z"));
+ assertTrue(XcodeOptimizationLevel.isValid("s"));
+ assertTrue(XcodeOptimizationLevel.isValid("3"));
+ assertTrue(XcodeOptimizationLevel.isValid("fast"));
+ assertFalse(XcodeOptimizationLevel.isValid("Oz"));
+ assertFalse(XcodeOptimizationLevel.isValid("4"));
+ assertFalse(XcodeOptimizationLevel.isValid(""));
+ }
+}
diff --git a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java
index d023e1f7d03..40376c34242 100644
--- a/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java
+++ b/maven/build-hint-catalog/src/main/java/com/codename1/build/shared/BuildHintsIos.java
@@ -652,6 +652,15 @@ static void register(List h) {
+ "on-device interpreter app (scripts/cn1-device-runtime). A regular app "
+ "leaves this false and gets a smaller binary."));
+ h.add(new Hint("ios.optimizationLevel")
+ .group(HintGroup.IOS)
+ .type(HintType.STRING)
+ .platform("ios")
+ .doc("The clang optimization level of the release build: 0, 1, 2, 3, s, z or fast. "
+ + "Debug builds stay unoptimized. Set z for an app whose executable is too "
+ + "large, such as the device runtime: the code is smaller and somewhat "
+ + "slower."));
+
h.add(new Hint("ios.featureScanExclude")
.group(HintGroup.IOS)
.type(HintType.STRING)
diff --git a/maven/javase/pom.xml b/maven/javase/pom.xml
index 83c27978d0e..79ba262899b 100644
--- a/maven/javase/pom.xml
+++ b/maven/javase/pom.xml
@@ -358,9 +358,17 @@
time from the iPhoneX.skin theme. -->
Generating foldable skins
+
diff --git a/scripts/cn1-device-runtime/INTERNALS.asciidoc b/scripts/cn1-device-runtime/INTERNALS.asciidoc
index 8bd8d34bb11..1a92bfcfd80 100644
--- a/scripts/cn1-device-runtime/INTERNALS.asciidoc
+++ b/scripts/cn1-device-runtime/INTERNALS.asciidoc
@@ -300,6 +300,14 @@ A generated shim overrides the framework method and asks the interpreter for it.
That's what the `super_` bridges on every shim are for: `super.paint(g)` from interpreted code is dispatched to `super_paint`, which is the only path to the framework implementation. The same applies to any `super.` call on a host superclass.
+=== Shim methods are a call, not a template
+
+Every shim overrides every method its class inherits, so the shims are most of the app: about 1,650 classes and 104,000 overrides. When each override carried its own argument array, its own `try`/`catch` and its own exception unwrapping, they averaged 2.3 KB of machine code each. Together they were two thirds of the executable and pushed it past the App Store's 500 MB limit. Each new framework method also grew every shim that inherits it.
+
+An override now calls a helper in the generated `InterpCalls` class, one helper per parameter shape (about 260 shapes cover the framework). It tests the result with `InterpCalls.miss` and calls `super` itself, because Java allows a `super` call only inside the subclass. Only a method that declares a checked exception keeps a handler, so that the exception reaches its caller by its own type. Keep new shim behavior in the helpers, not in the emitted method body.
+
+The device runtime also sets the `ios.optimizationLevel=z` build hint, so the whole iOS release build is compiled for size. The code is somewhat slower, which a development tool can afford.
+
=== Pushing an application, not a file
`cn1:push` sends the module's whole compiled tree with all of its source roots,
diff --git a/scripts/cn1-device-runtime/common/codenameone_settings.properties b/scripts/cn1-device-runtime/common/codenameone_settings.properties
index 2ea7edab2b0..2077b938a83 100644
--- a/scripts/cn1-device-runtime/common/codenameone_settings.properties
+++ b/scripts/cn1-device-runtime/common/codenameone_settings.properties
@@ -7,6 +7,9 @@
# builds; nothing here calls Play billing or FCM at runtime.
codename1.arg.android.useAndroidX=true
codename1.arg.ios.interpHost=true
+# Compiled for size: the interpreter shims are two thirds of the executable, and
+# at the default speed optimization it passed the App Store's 500 MB limit.
+codename1.arg.ios.optimizationLevel=z
# A pushed program gets the native theme its own ios.themeMode /
# ios.themeGeneration ask for, so every iOS native theme has to be in the
# bundle; the builder otherwise ships only the one this app's mode loads.
diff --git a/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java b/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java
index 38231453969..f582c5c80a9 100644
--- a/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java
+++ b/scripts/cn1-device-runtime/tools/src/main/java/com/codenameone/devruntime/tools/GenerateInterpShims.java
@@ -268,6 +268,7 @@ public static void main(String[] args) throws Exception {
writeNativeCapabilities(outDir, frameworkJar);
writeRegistry(outDir, generated, okClasses, ifaceShims, okInterfaces);
+ writeCallHelpers(outDir);
System.out.println("generated " + generated.size() + " class shims, "
+ ifaceShims.size() + " interface shims, " + skipped + " skipped, "
+ skippedByExclusion + " excluded, into " + outDir);
@@ -885,8 +886,8 @@ private static void emitInterfaceMethod(PrintWriter w, Method m, Class> target
}
w.println(" public " + typeName(ret) + " " + m.getName() + "(" + sig + ")"
+ throwsClause(m) + " {");
- emitDispatch(w, m, "$runtime.dispatch($interp, \"" + m.getName() + "\", \""
- + descriptorOf(params, ret) + "\", new Object[]{" + boxed + "})");
+ emitDispatch(w, m, helperCall("null", m.getName(), descriptorOf(params, ret),
+ params, boxed));
if (!m.isDefault()) {
// A stopped program's peer is still held by whatever registered it.
// Answering nothing is the point of detaching; throwing here would
@@ -1594,8 +1595,8 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted,
if (!alreadyEmitted.contains("toString()") && !sealed(target, "toString")) {
w.println(" @Override");
w.println(" public String toString() {");
- w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,");
- w.println(" \"toString\", \"()Ljava/lang/String;\", new Object[]{});");
+ w.println(" Object $r = " + helperCall("this", "toString", "()Ljava/lang/String;",
+ new Class>[0], new StringBuilder()) + ";");
w.println(" if (" + MISS + ") {");
w.println(" return super.toString();");
w.println(" }");
@@ -1606,12 +1607,12 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted,
if (!alreadyEmitted.contains("hashCode()") && !sealed(target, "hashCode")) {
w.println(" @Override");
w.println(" public int hashCode() {");
- w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,");
- w.println(" \"hashCode\", \"()I\", new Object[]{});");
+ w.println(" Object $r = " + helperCall("this", "hashCode", "()I",
+ new Class>[0], new StringBuilder()) + ";");
w.println(" if (" + MISS + ") {");
w.println(" return super.hashCode();");
w.println(" }");
- w.println(" return $r == null ? 0 : ((Number)$r).intValue();");
+ w.println(" return " + unbox(Integer.TYPE, "$r") + ";");
w.println(" }");
w.println();
}
@@ -1619,12 +1620,12 @@ private static void emitObjectMethods(PrintWriter w, Set alreadyEmitted,
&& !sealed(target, "equals")) {
w.println(" @Override");
w.println(" public boolean equals(Object a0) {");
- w.println(" Object $r = InterpRuntime.dispatchOrDeferred(this, $runtime, $interp,");
- w.println(" \"equals\", \"(Ljava/lang/Object;)Z\", new Object[]{a0});");
+ w.println(" Object $r = " + helperCall("this", "equals", "(Ljava/lang/Object;)Z",
+ new Class>[]{Object.class}, new StringBuilder("a0")) + ";");
w.println(" if (" + MISS + ") {");
w.println(" return super.equals(a0);");
w.println(" }");
- w.println(" return $r != null && ((Boolean)$r).booleanValue();");
+ w.println(" return " + unbox(Boolean.TYPE, "$r") + ";");
w.println(" }");
w.println();
}
@@ -1695,9 +1696,8 @@ private static void emitOverride(PrintWriter w, Method m, Map>
// constructor pushes before super() runs; the object has no state
// yet, exactly as Java dictates during that window, but the
// override runs rather than being silently skipped.
- emitDispatch(w, thrown, "InterpRuntime.dispatchOrDeferred(this, $runtime, $interp, \""
- + m.getName() + "\", \""
- + descriptorOf(params, ret) + "\", new Object[]{" + boxed + "})");
+ emitDispatch(w, thrown, helperCall("this", m.getName(), descriptorOf(params, ret),
+ params, boxed));
if (abstractMethod) {
// See zero(): a callback for a program that has been stopped.
w.println(" if ($r == InterpRuntime.DETACHED) {");
@@ -1747,8 +1747,7 @@ private static void emitOverride(PrintWriter w, Method m, Map>
* stopped. Both are handled by doing what the framework class would do on
* its own, which for anything with a body is calling it.
*/
- private static final String MISS =
- "$r == InterpRuntime.NOT_OVERRIDDEN || $r == InterpRuntime.DETACHED";
+ private static final String MISS = "InterpCalls.miss($r)";
/**
* The value a method returns when a callback arrives for a program that has
@@ -1771,14 +1770,16 @@ private static String zero(Class> t) {
}
private static String unbox(Class> t, String expr) {
- if (t == Boolean.TYPE) return "$r == null ? false : ((Boolean)" + expr + ").booleanValue()";
- if (t == Byte.TYPE) return "$r == null ? (byte)0 : ((Number)" + expr + ").byteValue()";
- if (t == Character.TYPE) return "$r == null ? (char)0 : ((Character)" + expr + ").charValue()";
- if (t == Short.TYPE) return "$r == null ? (short)0 : ((Number)" + expr + ").shortValue()";
- if (t == Integer.TYPE) return "$r == null ? 0 : ((Number)" + expr + ").intValue()";
- if (t == Long.TYPE) return "$r == null ? 0L : ((Number)" + expr + ").longValue()";
- if (t == Float.TYPE) return "$r == null ? 0f : ((Number)" + expr + ").floatValue()";
- if (t == Double.TYPE) return "$r == null ? 0d : ((Number)" + expr + ").doubleValue()";
+ // The null and wrapper handling lives once in the helper class; inline
+ // it was a branch and a cast per override, 104k times over.
+ if (t == Boolean.TYPE) return CALLS + ".z(" + expr + ")";
+ if (t == Byte.TYPE) return CALLS + ".b(" + expr + ")";
+ if (t == Character.TYPE) return CALLS + ".c(" + expr + ")";
+ if (t == Short.TYPE) return CALLS + ".s(" + expr + ")";
+ if (t == Integer.TYPE) return CALLS + ".i(" + expr + ")";
+ if (t == Long.TYPE) return CALLS + ".j(" + expr + ")";
+ if (t == Float.TYPE) return CALLS + ".f(" + expr + ")";
+ if (t == Double.TYPE) return CALLS + ".d(" + expr + ")";
return "(" + typeName(t) + ")" + expr;
}
@@ -1841,30 +1842,29 @@ private static void emitDispatch(PrintWriter w, Class>[] declared, String call
checked.add(e);
}
}
+ // The helper already rethrows an unchecked host throwable by its own
+ // type and anything else as the carrier, so a method that declares no
+ // checked exception needs no handler of its own -- which is nearly
+ // every method, and the try/catch was most of each override's code.
+ if (checked.isEmpty()) {
+ w.println(" Object $r = " + call + ";");
+ return;
+ }
+ // A declared checked exception is thrown by its own type, so an
+ // interpreted Row.getString() throwing IOException reaches the
+ // caller's catch (IOException). hostThrowable, not getThrown: a pushed
+ // exception class arrives as an InterpObject whose peer is the host
+ // exception, and only the peer can match a catch clause.
w.println(" Object $r;");
w.println(" try {");
w.println(" $r = " + call + ";");
w.println(" } catch (com.codename1.impl.interp.InterpThrowable $t) {");
- // hostThrowable, not getThrown: a pushed exception class arrives as an
- // InterpObject whose peer is the host exception, and only the peer can
- // match a catch clause.
w.println(" Throwable $thrown = $t.hostThrowable();");
for (Class> e : checked) {
w.println(" if ($thrown instanceof " + typeName(e) + ") {");
w.println(" throw (" + typeName(e) + ") $thrown;");
w.println(" }");
}
- // Unchecked ones need no throws clause to travel, and framework code
- // around a callback catches them by their own type: a pushed
- // `MyIllegalArgumentException extends IllegalArgumentException` has a
- // peer that *is* an IllegalArgumentException, and letting the
- // interpreter's carrier escape instead means that catch never runs.
- w.println(" if ($thrown instanceof RuntimeException) {");
- w.println(" throw (RuntimeException) $thrown;");
- w.println(" }");
- w.println(" if ($thrown instanceof Error) {");
- w.println(" throw (Error) $thrown;");
- w.println(" }");
w.println(" throw $t;");
w.println(" }");
}
@@ -2015,6 +2015,154 @@ private static String descriptorOf(Class> c) {
* and every interpreted {@code new} and every host call through a peer goes
* through here.
*/
+ /** The generated class every shim method dispatches through. */
+ private static final String CALLS = "InterpCalls";
+
+ /**
+ * Every parameter shape a shim method has used, by helper name. Sorted so
+ * that generating twice writes the same file.
+ */
+ private static final java.util.TreeMap[]> SHAPES =
+ new java.util.TreeMap[]>();
+
+ /**
+ * One letter per parameter: the primitive's descriptor, or {@code L} for
+ * any reference. References share a helper whatever their type, since the
+ * helper only boxes them into the argument array.
+ */
+ private static char shapeCode(Class> p) {
+ if (!p.isPrimitive()) {
+ return 'L';
+ }
+ return descriptorOf(p).charAt(0);
+ }
+
+ /**
+ * The call a shim method makes to ask the interpreter, recording the
+ * helper it needs.
+ *
+ * Every override used to carry its own argument array, its own
+ * try/catch and its own rethrow chain: 2.3 KB of machine code each, and
+ * one override per inherited method per shim -- 104k of them, two thirds
+ * of the executable. A helper per parameter shape holds all of that once
+ * (a few hundred shapes cover the whole framework), so an override is a
+ * call, a sentinel test and its own super call -- the one part Java only
+ * allows inside the subclass itself.
+ *
+ * @param shim {@code "this"} for a class shim, which has to reach the
+ * interpreter during its superclass constructor and so goes
+ * through {@code dispatchOrDeferred}; {@code "null"} for an
+ * interface shim, which calls {@code dispatch} directly as it
+ * always did.
+ */
+ private static String helperCall(String shim, String name, String descriptor,
+ Class>[] params, CharSequence args) {
+ StringBuilder key = new StringBuilder("d_");
+ Class>[] erased = new Class>[params.length];
+ for (int i = 0; i < params.length; i++) {
+ char code = shapeCode(params[i]);
+ key.append(code);
+ erased[i] = code == 'L' ? Object.class : params[i];
+ }
+ String helper = key.toString();
+ if (!SHAPES.containsKey(helper)) {
+ SHAPES.put(helper, erased);
+ }
+ return CALLS + "." + helper + "(" + shim + ", $runtime, $interp, \"" + name + "\", \""
+ + descriptor + "\"" + (args.length() == 0 ? "" : ", " + args) + ")";
+ }
+
+ /**
+ * Writes {@code InterpCalls}: the per-shape helpers {@link #helperCall}
+ * recorded, and the conversions every shim shares.
+ *
+ * It only uses what the runtime has always offered a shim --
+ * {@code dispatchOrDeferred}, {@code dispatch}, the two sentinels and
+ * {@code InterpThrowable.hostThrowable} -- so shims generated this way run
+ * on a framework built before it existed.
+ */
+ private static void writeCallHelpers(File dir) throws Exception {
+ PrintWriter w = new PrintWriter(new File(dir, CALLS + ".java"), "UTF-8");
+ try {
+ header(w);
+ w.println("package com.codenameone.devruntime.gen;");
+ w.println();
+ w.println("import com.codename1.impl.interp.InterpObject;");
+ w.println("import com.codename1.impl.interp.InterpRuntime;");
+ w.println("import com.codename1.impl.interp.InterpThrowable;");
+ w.println();
+ w.println("/** What every generated shim method shares: asking the interpreter. */");
+ w.println("public final class " + CALLS + " {");
+ w.println(" private " + CALLS + "() {");
+ w.println(" }");
+ w.println();
+ w.println(" /** The interpreter did not answer: not overridden, or the program is stopped. */");
+ w.println(" public static boolean miss(Object r) {");
+ w.println(" return r == InterpRuntime.NOT_OVERRIDDEN || r == InterpRuntime.DETACHED;");
+ w.println(" }");
+ w.println();
+ w.println(" /**");
+ w.println(" * Runs the interpreted method. An unchecked host throwable is rethrown by");
+ w.println(" * its own type, so framework code catching it by type still does; anything");
+ w.println(" * else travels as the carrier, for the caller to unwrap what it declares.");
+ w.println(" */");
+ w.println(" public static Object call(Object shim, InterpRuntime rt, InterpObject io,");
+ w.println(" String name, String descriptor, Object[] args) {");
+ w.println(" try {");
+ w.println(" return shim == null ? rt.dispatch(io, name, descriptor, args)");
+ w.println(" : InterpRuntime.dispatchOrDeferred(shim, rt, io, name, descriptor, args);");
+ w.println(" } catch (InterpThrowable t) {");
+ w.println(" Throwable thrown = t.hostThrowable();");
+ w.println(" if (thrown instanceof RuntimeException) {");
+ w.println(" throw (RuntimeException) thrown;");
+ w.println(" }");
+ w.println(" if (thrown instanceof Error) {");
+ w.println(" throw (Error) thrown;");
+ w.println(" }");
+ w.println(" throw t;");
+ w.println(" }");
+ w.println(" }");
+ w.println();
+ String[][] unboxers = {
+ {"z", "boolean", "r != null && ((Boolean) r).booleanValue()"},
+ {"b", "byte", "r == null ? (byte) 0 : ((Number) r).byteValue()"},
+ {"c", "char", "r == null ? (char) 0 : ((Character) r).charValue()"},
+ {"s", "short", "r == null ? (short) 0 : ((Number) r).shortValue()"},
+ {"i", "int", "r == null ? 0 : ((Number) r).intValue()"},
+ {"j", "long", "r == null ? 0L : ((Number) r).longValue()"},
+ {"f", "float", "r == null ? 0f : ((Number) r).floatValue()"},
+ {"d", "double", "r == null ? 0d : ((Number) r).doubleValue()"},
+ };
+ for (String[] u : unboxers) {
+ w.println(" public static " + u[1] + " " + u[0] + "(Object r) {");
+ w.println(" return " + u[2] + ";");
+ w.println(" }");
+ w.println();
+ }
+ for (Map.Entry[]> e : SHAPES.entrySet()) {
+ Class>[] params = e.getValue();
+ StringBuilder sig = new StringBuilder();
+ StringBuilder args = new StringBuilder();
+ for (int i = 0; i < params.length; i++) {
+ sig.append(", ").append(typeName(params[i])).append(" a").append(i);
+ if (i > 0) {
+ args.append(", ");
+ }
+ args.append("a").append(i);
+ }
+ w.println(" public static Object " + e.getKey()
+ + "(Object shim, InterpRuntime rt, InterpObject io, String name, String descriptor"
+ + sig + ") {");
+ w.println(" return call(shim, rt, io, name, descriptor, new Object[]{" + args + "});");
+ w.println(" }");
+ w.println();
+ }
+ w.println("}");
+ } finally {
+ w.close();
+ }
+ }
+
private static void writeRegistry(File dir, List shims, List> classes,
List ifaceShims, List> interfaces)
throws Exception {