2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 /** Allows subclasses to redefine what field a function representing a
74 * class gets assigned. By default it returns the suggested name followed
75 * by <code>" = "</code>;
77 * @param className suggested name of the class
79 /* protected */ String assignClass(String className) {
80 return className + " = ";
82 /* protected */ String accessClass(String classOperation) {
83 return classOperation;
86 protected String accessField(String object, String mangledName,
87 String[] fieldInfoName) throws IOException {
88 return object + "." + mangledName;
91 protected String accessStaticMethod(
94 String[] fieldInfoName) throws IOException {
95 return object + "." + mangledName;
98 protected String accessVirtualMethod(
101 String[] fieldInfoName,
103 ) throws IOException {
104 return object + "." + mangledName + '(';
107 protected void declaredClass(ClassData classData, String mangledName)
111 protected void declaredField(FieldData fieldData,
113 String mangledName) throws IOException {
116 protected void declaredMethod(MethodData methodData,
118 String mangledName) throws IOException {
121 /** Prints out a debug message.
123 * @param msg the message
124 * @return true if the message has been printed
125 * @throws IOException
127 boolean debug(String msg) throws IOException {
133 * Converts a given class file to a JavaScript version.
135 * @param classFile input stream with code of the .class file
136 * @return the initialization code for this class, if any. Otherwise <code>null</code>
138 * @throws IOException if something goes wrong during read or write or translating
141 public String compile(InputStream classFile) throws IOException {
142 return compile(new ClassData(classFile));
145 protected String compile(ClassData classData) throws IOException {
147 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
148 if (jc.getMajor_version() < 50) {
149 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
150 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
153 byte[] arrData = jc.findAnnotationData(true);
155 String[] arr = findAnnotation(arrData, jc,
156 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
157 "resource", "processByteCode"
160 if (!arr[0].isEmpty()) {
161 requireScript(arr[0]);
163 if ("0".equals(arr[1])) {
169 String[] arr = findAnnotation(arrData, jc,
170 "net.java.html.js.JavaScriptResource",
174 if (arr[0].startsWith("/")) {
175 requireScript(arr[0]);
177 int last = jc.getClassName().lastIndexOf('/');
179 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
184 String[] proto = findAnnotation(arrData, jc,
185 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
186 "container", "prototype"
188 StringArray toInitilize = new StringArray();
189 final String className = className(jc);
190 append("\n\n").append(assignClass(className));
191 append("function ").append(className).append("() {");
193 append("\n var CLS = ").append(className).append(';');
194 append("\n if (!CLS.$class) {");
196 String sc = jc.getSuperClassName(); // with _
197 append("\n var pp = ").
198 append(accessClass(mangleClassName(sc))).append("(true);");
199 append("\n var p = CLS.prototype = pp;");
200 append("\n var c = p;");
201 append("\n var sprcls = pp.constructor.$class;");
203 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
204 if (proto[0] == null) {
207 append("\n var c = ").append(proto[0]).append(";");
208 append("\n var sprcls = null;");
210 for (FieldData v : jc.getFields()) {
212 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
213 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
217 append("\n CLS.fld_").append(v.getName()).append(initField(v));
218 append("\n m = c._").append(v.getName()).append(" = function (v) {")
219 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
220 .append(" = v; return CLS.fld_").
221 append(v.getName()).append("; };");
223 append("\n m = c._").append(v.getName()).append(" = function (v) {")
224 .append(" if (arguments.length == 1) this.fld_").
225 append(className).append('_').append(v.getName())
226 .append(" = v; return this.fld_").
227 append(className).append('_').append(v.getName())
231 declaredField(v, "c", "_" + v.getName());
233 for (MethodData m : jc.getMethods()) {
234 byte[] onlyArr = m.findAnnotationData(true);
235 if (javaScriptOnly(onlyArr)) continue;
241 mn = generateStaticMethod(destObject, m, toInitilize);
243 if (m.isConstructor()) {
245 mn = generateInstanceMethod(destObject, m);
248 mn = generateInstanceMethod(destObject, m);
251 declaredMethod(m, destObject, mn);
252 byte[] runAnno = m.findAnnotationData(false);
253 if (runAnno != null) {
254 append("\n m.anno = {");
255 generateAnno(jc, runAnno);
258 append("\n m.access = " + m.getAccess()).append(";");
259 append("\n m.cls = CLS;");
261 append("\n c.constructor = CLS;");
262 append("\n function ").append(className).append("fillInstOf(x) {");
263 String instOfName = "$instOf_" + className;
264 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
265 if (jc.isInterface()) {
266 for (MethodData m : jc.getMethods()) {
267 if ((m.getAccess() & ACC_ABSTRACT) == 0
268 && (m.getAccess() & ACC_STATIC) == 0
269 && (m.getAccess() & ACC_PRIVATE) == 0) {
270 final String mn = findMethodName(m, new StringBuilder());
272 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
273 append("\n } catch (ignore) {");
278 for (String superInterface : jc.getSuperInterfaces()) {
279 String intrfc = superInterface.replace('/', '_');
280 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
281 requireReference(superInterface);
285 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
286 append("\n ").append(className).append("fillInstOf(c);");
287 append("\n } catch (ignore) {");
289 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
290 append("\n CLS.$class = 'temp';");
291 append("\n CLS.$class = ");
292 append(accessClass("java_lang_Class(true);"));
293 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
294 append("\n CLS.$class.superclass = sprcls;");
295 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
296 append("\n CLS.$class.cnstr = CLS;");
297 byte[] classAnno = jc.findAnnotationData(false);
298 if (classAnno != null) {
299 append("\n CLS.$class.anno = {");
300 generateAnno(jc, classAnno);
303 for (String init : toInitilize.toArray()) {
304 append("\n ").append(init).append("();");
307 append("\n if (arguments.length === 0) {");
308 append("\n if (!(this instanceof CLS)) {");
309 append("\n return new CLS();");
311 for (FieldData v : jc.getFields()) {
312 byte[] onlyArr = v.findAnnotationData(true);
313 if (javaScriptOnly(onlyArr)) continue;
315 append("\n this.fld_").
316 append(className).append('_').
317 append(v.getName()).append(initField(v));
320 append("\n return this;");
322 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
325 declaredClass(jc, className);
327 // StringBuilder sb = new StringBuilder();
328 // for (String init : toInitilize.toArray()) {
329 // sb.append("\n").append(init).append("();");
334 private boolean javaScriptOnly(byte[] anno) throws IOException {
335 String[] only = findAnnotation(anno, jc,
336 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
340 if (only[0] != null && only[1] != null) {
341 append("\n p.").append(only[0]).append(" = ")
342 .append(only[1]).append(";");
344 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
345 append("\n p['").append(only[0]).append("'] = p.")
346 .append(only[0]).append(";");
352 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
353 String jsb = javaScriptBody(destObject, m, true);
357 final String mn = findMethodName(m, new StringBuilder());
358 boolean defineProp = generateMethod(destObject, mn, m);
359 if (mn.equals("class__V")) {
361 toInitilize.add(accessClass(className(jc)) + "(false)['" + mn + "']");
363 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
369 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
370 String jsb = javaScriptBody(destObject, m, false);
374 final String mn = findMethodName(m, new StringBuilder());
375 generateMethod(destObject, mn, m);
379 private boolean generateMethod(String destObject, String name, MethodData m)
381 final StackMapIterator stackMapIterator = m.createStackMapIterator();
382 TrapDataIterator trap = m.getTrapDataIterator();
383 final LocalsMapper lmapper =
384 new LocalsMapper(stackMapIterator.getArguments());
387 "java/lang/Object".equals(jc.getClassName()) ||
388 "java/lang/reflect/Array".equals(jc.getClassName());
391 append("Object.defineProperty(").append(destObject).
392 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
394 append("m = ").append(destObject).append(".").append(name).append(" = function(");
396 lmapper.outputArguments(this, m.isStatic());
397 append(") {").append("\n");
399 final byte[] byteCodes = m.getCode();
400 if (byteCodes == null) {
401 append(" throw 'no code found for ")
402 .append(jc.getClassName()).append('.')
403 .append(m.getName()).append("';\n");
412 final StackMapper smapper = new StackMapper();
415 append(" var ").append(" lcA0 = this;\n");
419 TrapData[] previousTrap = null;
420 boolean wide = false;
422 if (stackMapIterator.isEmpty()) {
428 append("\n var gt = 0;\n");
432 int topMostLabel = 0;
433 for (int i = 0; i < byteCodes.length; i++) {
436 stackMapIterator.advanceTo(i);
437 boolean changeInCatch = trap.advanceTo(i);
438 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
439 if (previousTrap != null) {
440 generateCatch(previousTrap, i, topMostLabel);
444 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
449 if (openBraces > 64) {
450 for (int c = 0; c < 64; c++) {
457 lastStackFrame = stackMapIterator.getFrameIndex();
458 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
459 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
460 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
462 changeInCatch = true;
464 debug(" /* " + i + " */ ");
466 if (changeInCatch && trap.useTry()) {
468 previousTrap = trap.current();
470 final int c = readUByte(byteCodes, i);
473 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
476 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
479 smapper.assign(this, VarType.LONG, lmapper.getL(0));
482 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
485 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
488 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
491 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
494 smapper.assign(this, VarType.LONG, lmapper.getL(1));
497 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
500 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
503 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
506 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
509 smapper.assign(this, VarType.LONG, lmapper.getL(2));
512 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
515 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
518 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
521 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
524 smapper.assign(this, VarType.LONG, lmapper.getL(3));
527 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
530 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
534 final int indx = wide ? readUShort(byteCodes, i++)
535 : readUByte(byteCodes, i);
537 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
542 final int indx = wide ? readUShort(byteCodes, i++)
543 : readUByte(byteCodes, i);
545 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
550 final int indx = wide ? readUShort(byteCodes, i++)
551 : readUByte(byteCodes, i);
553 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
558 final int indx = wide ? readUShort(byteCodes, i++)
559 : readUByte(byteCodes, i);
561 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
574 final int indx = wide ? readUShort(byteCodes, i++)
575 : readUByte(byteCodes, i);
577 emit(smapper, this, "var @1 = @2;",
578 lmapper.setI(indx), smapper.popI());
583 final int indx = wide ? readUShort(byteCodes, i++)
584 : readUByte(byteCodes, i);
586 emit(smapper, this, "var @1 = @2;",
587 lmapper.setL(indx), smapper.popL());
592 final int indx = wide ? readUShort(byteCodes, i++)
593 : readUByte(byteCodes, i);
595 emit(smapper, this, "var @1 = @2;",
596 lmapper.setF(indx), smapper.popF());
601 final int indx = wide ? readUShort(byteCodes, i++)
602 : readUByte(byteCodes, i);
604 emit(smapper, this, "var @1 = @2;",
605 lmapper.setD(indx), smapper.popD());
610 final int indx = wide ? readUShort(byteCodes, i++)
611 : readUByte(byteCodes, i);
613 emit(smapper, this, "var @1 = @2;",
614 lmapper.setA(indx), smapper.popA());
618 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
621 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
624 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
627 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
630 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
633 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
636 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
639 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
642 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
645 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
648 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
651 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
654 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
657 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
660 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
663 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
666 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
669 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
672 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
675 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
678 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
681 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
684 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
687 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
690 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
693 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
696 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
699 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
702 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
705 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
708 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
711 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
714 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
715 smapper.getI(1), smapper.popI());
718 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
719 smapper.getL(1), smapper.popL());
722 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
725 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
728 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
729 smapper.getI(1), smapper.popI());
732 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
733 smapper.getL(1), smapper.popL());
736 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
739 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
742 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
745 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
748 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
751 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
754 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
757 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
760 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
763 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
766 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
769 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
772 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
775 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
778 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
781 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
784 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
787 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
791 final int varIndx = wide ? readUShort(byteCodes, i++)
792 : readUByte(byteCodes, i);
794 final int incrBy = wide ? readShort(byteCodes, i++)
798 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
800 emit(smapper, this, "@1 += @2;",
801 lmapper.getI(varIndx),
802 Integer.toString(incrBy));
807 emit(smapper, this, "return;");
810 emit(smapper, this, "return @1;", smapper.popI());
813 emit(smapper, this, "return @1;", smapper.popL());
816 emit(smapper, this, "return @1;", smapper.popF());
819 emit(smapper, this, "return @1;", smapper.popD());
822 emit(smapper, this, "return @1;", smapper.popA());
825 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
828 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
831 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
834 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
838 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
841 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
844 smapper.replace(this, VarType.DOUBLE, "@1",
848 smapper.replace(this, VarType.FLOAT, "@1",
852 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
856 smapper.replace(this, VarType.LONG, "(@1).toLong()",
860 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
864 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
867 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
871 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
873 case opc_aconst_null:
874 smapper.assign(this, VarType.REFERENCE, "null");
877 smapper.assign(this, VarType.INTEGER, "-1");
880 smapper.assign(this, VarType.INTEGER, "0");
883 smapper.assign(this, VarType.DOUBLE, "0");
886 smapper.assign(this, VarType.LONG, "0");
889 smapper.assign(this, VarType.FLOAT, "0");
892 smapper.assign(this, VarType.INTEGER, "1");
895 smapper.assign(this, VarType.LONG, "1");
898 smapper.assign(this, VarType.FLOAT, "1");
901 smapper.assign(this, VarType.DOUBLE, "1");
904 smapper.assign(this, VarType.INTEGER, "2");
907 smapper.assign(this, VarType.FLOAT, "2");
910 smapper.assign(this, VarType.INTEGER, "3");
913 smapper.assign(this, VarType.INTEGER, "4");
916 smapper.assign(this, VarType.INTEGER, "5");
919 int indx = readUByte(byteCodes, ++i);
920 String v = encodeConstant(indx);
921 int type = VarType.fromConstantType(jc.getTag(indx));
922 smapper.assign(this, type, v);
927 int indx = readUShortArg(byteCodes, i);
929 String v = encodeConstant(indx);
930 int type = VarType.fromConstantType(jc.getTag(indx));
931 if (type == VarType.LONG) {
932 final Long lv = new Long(v);
933 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
934 final int hi = (int)(lv.longValue() >> 32);
936 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
938 smapper.assign(this, VarType.LONG,
939 "0x" + Integer.toHexString(hi) + ".next32(0x" +
940 Integer.toHexString(low) + ")"
944 smapper.assign(this, type, v);
949 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
953 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
957 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
960 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
961 "===", topMostLabel);
964 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
965 "!==", topMostLabel);
968 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
972 int indx = i + readShortArg(byteCodes, i);
973 emitIf(smapper, this, "if ((@1) == 0) ",
974 smapper.popI(), i, indx, topMostLabel);
979 int indx = i + readShortArg(byteCodes, i);
980 emitIf(smapper, this, "if ((@1) != 0) ",
981 smapper.popI(), i, indx, topMostLabel);
986 int indx = i + readShortArg(byteCodes, i);
987 emitIf(smapper, this, "if ((@1) < 0) ",
988 smapper.popI(), i, indx, topMostLabel);
993 int indx = i + readShortArg(byteCodes, i);
994 emitIf(smapper, this, "if ((@1) <= 0) ",
995 smapper.popI(), i, indx, topMostLabel);
1000 int indx = i + readShortArg(byteCodes, i);
1001 emitIf(smapper, this, "if ((@1) > 0) ",
1002 smapper.popI(), i, indx, topMostLabel);
1007 int indx = i + readShortArg(byteCodes, i);
1008 emitIf(smapper, this, "if ((@1) >= 0) ",
1009 smapper.popI(), i, indx, topMostLabel);
1013 case opc_ifnonnull: {
1014 int indx = i + readShortArg(byteCodes, i);
1015 emitIf(smapper, this, "if ((@1) !== null) ",
1016 smapper.popA(), i, indx, topMostLabel);
1021 int indx = i + readShortArg(byteCodes, i);
1022 emitIf(smapper, this, "if ((@1) === null) ",
1023 smapper.popA(), i, indx, topMostLabel);
1028 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1029 "!=", topMostLabel);
1032 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1036 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1037 "<=", topMostLabel);
1040 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1044 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1045 ">=", topMostLabel);
1048 smapper.flush(this);
1049 int indx = i + readShortArg(byteCodes, i);
1050 goTo(this, i, indx, topMostLabel);
1054 case opc_lookupswitch: {
1055 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1058 case opc_tableswitch: {
1059 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1062 case opc_invokeinterface: {
1063 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1066 case opc_invokevirtual:
1067 i = invokeVirtualMethod(byteCodes, i, smapper);
1069 case opc_invokespecial:
1070 i = invokeStaticMethod(byteCodes, i, smapper, false);
1072 case opc_invokestatic:
1073 i = invokeStaticMethod(byteCodes, i, smapper, true);
1075 case opc_invokedynamic: {
1076 int indx = readUShortArg(byteCodes, i);
1077 println("invoke dynamic: " + indx);
1078 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1079 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1080 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1081 println(" type: " + methodHandle.cpx1);
1082 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1083 String mcn = mangleClassName(mi[0]);
1084 char[] returnType = {'V'};
1085 StringBuilder cnt = new StringBuilder();
1086 String mn = findMethodName(mi, cnt, returnType);
1087 StringBuilder sb = new StringBuilder();
1088 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1089 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1090 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1091 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1092 sb.append(" mn : ").append(mn).append("\n");
1093 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1094 throw new IOException(sb.toString());
1096 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1097 String type = jc.StringValue(nameAndType.cpx2);
1098 String object = accessClass(mcn) + "(false)";
1099 if (mn.startsWith("cons_")) {
1100 object += ".constructor";
1102 append("var metHan = ");
1103 append(accessStaticMethod(object, mn, mi));
1105 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1107 append(", '").append(mi[1]).append("', ");
1108 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1109 append(methodType).append("'").append(type).append("', null)");
1110 // if (numArguments > 0) {
1112 // for (int j = 1; j < numArguments; ++j) {
1118 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1124 int indx = readUShortArg(byteCodes, i);
1125 String ci = jc.getClassName(indx);
1126 emit(smapper, this, "var @1 = new @2;",
1127 smapper.pushA(), accessClass(mangleClassName(ci)));
1133 int atype = readUByte(byteCodes, ++i);
1134 generateNewArray(atype, smapper);
1136 case opc_anewarray: {
1137 int type = readUShortArg(byteCodes, i);
1139 generateANewArray(type, smapper);
1142 case opc_multianewarray: {
1143 int type = readUShortArg(byteCodes, i);
1145 i = generateMultiANewArray(type, byteCodes, i, smapper);
1148 case opc_arraylength:
1149 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1152 emit(smapper, this, "Array.at(@3, @2, @1);",
1153 smapper.popL(), smapper.popI(), smapper.popA());
1156 emit(smapper, this, "Array.at(@3, @2, @1);",
1157 smapper.popF(), smapper.popI(), smapper.popA());
1160 emit(smapper, this, "Array.at(@3, @2, @1);",
1161 smapper.popD(), smapper.popI(), smapper.popA());
1164 emit(smapper, this, "Array.at(@3, @2, @1);",
1165 smapper.popA(), smapper.popI(), smapper.popA());
1171 emit(smapper, this, "Array.at(@3, @2, @1);",
1172 smapper.popI(), smapper.popI(), smapper.popA());
1175 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1176 smapper.popI(), smapper.getA(0));
1179 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1180 smapper.popI(), smapper.getA(0));
1183 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1184 smapper.popI(), smapper.getA(0));
1187 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1188 smapper.popI(), smapper.getA(0));
1194 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1195 smapper.popI(), smapper.getA(0));
1203 final Variable v = smapper.get(0);
1204 if (smapper.isDirty()) {
1205 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1207 smapper.assign(this, v.getType(), v);
1212 final Variable vi1 = smapper.get(0);
1214 if (vi1.isCategory2()) {
1215 emit(smapper, this, "var @1 = @2;",
1216 smapper.pushT(vi1.getType()), vi1);
1218 final Variable vi2 = smapper.get(1);
1219 emit(smapper, this, "var @1 = @2, @3 = @4;",
1220 smapper.pushT(vi2.getType()), vi2,
1221 smapper.pushT(vi1.getType()), vi1);
1226 final Variable vi1 = smapper.pop(this);
1227 final Variable vi2 = smapper.pop(this);
1228 final Variable vo3 = smapper.pushT(vi1.getType());
1229 final Variable vo2 = smapper.pushT(vi2.getType());
1230 final Variable vo1 = smapper.pushT(vi1.getType());
1232 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1233 vo1, vi1, vo2, vi2, vo3, vo1);
1237 final Variable vi1 = smapper.pop(this);
1238 final Variable vi2 = smapper.pop(this);
1240 if (vi1.isCategory2()) {
1241 final Variable vo3 = smapper.pushT(vi1.getType());
1242 final Variable vo2 = smapper.pushT(vi2.getType());
1243 final Variable vo1 = smapper.pushT(vi1.getType());
1245 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1246 vo1, vi1, vo2, vi2, vo3, vo1);
1248 final Variable vi3 = smapper.pop(this);
1249 final Variable vo5 = smapper.pushT(vi2.getType());
1250 final Variable vo4 = smapper.pushT(vi1.getType());
1251 final Variable vo3 = smapper.pushT(vi3.getType());
1252 final Variable vo2 = smapper.pushT(vi2.getType());
1253 final Variable vo1 = smapper.pushT(vi1.getType());
1255 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1256 vo1, vi1, vo2, vi2, vo3, vi3);
1257 emit(smapper, this, " @1 = @2, @3 = @4;",
1258 vo4, vo1, vo5, vo2);
1263 final Variable vi1 = smapper.pop(this);
1264 final Variable vi2 = smapper.pop(this);
1266 if (vi2.isCategory2()) {
1267 final Variable vo3 = smapper.pushT(vi1.getType());
1268 final Variable vo2 = smapper.pushT(vi2.getType());
1269 final Variable vo1 = smapper.pushT(vi1.getType());
1271 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1272 vo1, vi1, vo2, vi2, vo3, vo1);
1274 final Variable vi3 = smapper.pop(this);
1275 final Variable vo4 = smapper.pushT(vi1.getType());
1276 final Variable vo3 = smapper.pushT(vi3.getType());
1277 final Variable vo2 = smapper.pushT(vi2.getType());
1278 final Variable vo1 = smapper.pushT(vi1.getType());
1280 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1281 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1286 final Variable vi1 = smapper.pop(this);
1287 final Variable vi2 = smapper.pop(this);
1289 if (vi1.isCategory2()) {
1290 if (vi2.isCategory2()) {
1291 final Variable vo3 = smapper.pushT(vi1.getType());
1292 final Variable vo2 = smapper.pushT(vi2.getType());
1293 final Variable vo1 = smapper.pushT(vi1.getType());
1295 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1296 vo1, vi1, vo2, vi2, vo3, vo1);
1298 final Variable vi3 = smapper.pop(this);
1299 final Variable vo4 = smapper.pushT(vi1.getType());
1300 final Variable vo3 = smapper.pushT(vi3.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1305 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1308 final Variable vi3 = smapper.pop(this);
1310 if (vi3.isCategory2()) {
1311 final Variable vo5 = smapper.pushT(vi2.getType());
1312 final Variable vo4 = smapper.pushT(vi1.getType());
1313 final Variable vo3 = smapper.pushT(vi3.getType());
1314 final Variable vo2 = smapper.pushT(vi2.getType());
1315 final Variable vo1 = smapper.pushT(vi1.getType());
1317 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1318 vo1, vi1, vo2, vi2, vo3, vi3);
1319 emit(smapper, this, " @1 = @2, @3 = @4;",
1320 vo4, vo1, vo5, vo2);
1322 final Variable vi4 = smapper.pop(this);
1323 final Variable vo6 = smapper.pushT(vi2.getType());
1324 final Variable vo5 = smapper.pushT(vi1.getType());
1325 final Variable vo4 = smapper.pushT(vi4.getType());
1326 final Variable vo3 = smapper.pushT(vi3.getType());
1327 final Variable vo2 = smapper.pushT(vi2.getType());
1328 final Variable vo1 = smapper.pushT(vi1.getType());
1330 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1331 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1332 emit(smapper, this, " @1 = @2, @3 = @4;",
1333 vo5, vo1, vo6, vo2);
1339 final Variable vi1 = smapper.get(0);
1340 final Variable vi2 = smapper.get(1);
1342 if (vi1.getType() == vi2.getType()) {
1343 final Variable tmp = smapper.pushT(vi1.getType());
1345 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1350 smapper.pushT(vi1.getType());
1351 smapper.pushT(vi2.getType());
1356 smapper.assign(this, VarType.INTEGER,
1357 "(" + Integer.toString(byteCodes[++i]) + ")");
1360 smapper.assign(this, VarType.INTEGER,
1361 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1365 case opc_getfield: {
1366 int indx = readUShortArg(byteCodes, i);
1367 String[] fi = jc.getFieldInfoName(indx);
1368 final int type = VarType.fromFieldType(fi[2].charAt(0));
1369 final String mangleClass = mangleClassName(fi[0]);
1370 final String mangleClassAccess = accessClass(mangleClass);
1371 smapper.replace(this, type, "@2.call(@1)",
1373 accessField(mangleClassAccess + "(false)",
1379 case opc_putfield: {
1380 int indx = readUShortArg(byteCodes, i);
1381 String[] fi = jc.getFieldInfoName(indx);
1382 final int type = VarType.fromFieldType(fi[2].charAt(0));
1383 final String mangleClass = mangleClassName(fi[0]);
1384 final String mangleClassAccess = accessClass(mangleClass);
1385 emit(smapper, this, "@3.call(@2, @1);",
1388 accessField(mangleClassAccess + "(false)",
1393 case opc_getstatic: {
1394 int indx = readUShortArg(byteCodes, i);
1395 String[] fi = jc.getFieldInfoName(indx);
1396 final int type = VarType.fromFieldType(fi[2].charAt(0));
1397 String ac = accessClass(mangleClassName(fi[0]));
1398 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1399 smapper.assign(this, type, af + "()");
1401 addReference(fi[0]);
1404 case opc_putstatic: {
1405 int indx = readUShortArg(byteCodes, i);
1406 String[] fi = jc.getFieldInfoName(indx);
1407 final int type = VarType.fromFieldType(fi[2].charAt(0));
1408 emit(smapper, this, "@1(false)._@2(@3);",
1409 accessClass(mangleClassName(fi[0])), fi[1],
1410 smapper.popT(type));
1412 addReference(fi[0]);
1415 case opc_checkcast: {
1416 int indx = readUShortArg(byteCodes, i);
1417 generateCheckcast(indx, smapper);
1421 case opc_instanceof: {
1422 int indx = readUShortArg(byteCodes, i);
1423 generateInstanceOf(indx, smapper);
1428 final CharSequence v = smapper.popA();
1431 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1432 smapper.pushA(), v);
1436 case opc_monitorenter: {
1437 debug("/* monitor enter */");
1442 case opc_monitorexit: {
1443 debug("/* monitor exit */");
1454 emit(smapper, this, "throw 'unknown bytecode @1';",
1455 Integer.toString(c));
1459 generateByteCodeComment(prev, i, byteCodes);
1465 if (previousTrap != null) {
1466 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1471 while (openBraces-- > 0) {
1482 private int generateIf(StackMapper mapper, byte[] byteCodes,
1483 int i, final CharSequence v2, final CharSequence v1,
1484 final String test, int topMostLabel
1485 ) throws IOException {
1487 int indx = i + readShortArg(byteCodes, i);
1488 append("if ((").append(v1)
1489 .append(") ").append(test).append(" (")
1490 .append(v2).append(")) ");
1491 goTo(this, i, indx, topMostLabel);
1495 private int readInt4(byte[] byteCodes, int offset) {
1496 final int d = byteCodes[offset + 0] << 24;
1497 final int c = byteCodes[offset + 1] << 16;
1498 final int b = byteCodes[offset + 2] << 8;
1499 final int a = byteCodes[offset + 3];
1500 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1502 private static int readUByte(byte[] byteCodes, int offset) {
1503 return byteCodes[offset] & 0xff;
1506 private static int readUShort(byte[] byteCodes, int offset) {
1507 return ((byteCodes[offset] & 0xff) << 8)
1508 | (byteCodes[offset + 1] & 0xff);
1510 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1511 return readUShort(byteCodes, offsetInstruction + 1);
1514 private static int readShort(byte[] byteCodes, int offset) {
1515 int signed = byteCodes[offset];
1516 byte b0 = (byte)signed;
1517 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1519 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1520 return readShort(byteCodes, offsetInstruction + 1);
1523 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1525 Boolean count = null;
1526 boolean array = false;
1528 int firstPos = sig.length();
1529 while (i < descriptor.length()) {
1530 char ch = descriptor.charAt(i++);
1551 if (ch == 'J' || ch == 'D') {
1557 sig.insert(firstPos, ch);
1559 returnType[0] = '[';
1560 sig.insert(firstPos, "_3");
1569 returnType[0] = 'V';
1570 sig.insert(firstPos, 'V');
1573 int next = descriptor.indexOf(';', i);
1574 String realSig = mangleSig(descriptor, i - 1, next + 1);
1579 sig.append(realSig);
1582 sig.insert(firstPos, realSig);
1584 sig.insert(firstPos, "_3");
1586 returnType[0] = 'L';
1595 throw new IllegalStateException("Invalid char: " + ch);
1600 static String mangleSig(String sig) {
1601 return mangleSig(sig, 0, sig.length());
1604 private static String mangleMethodName(String name) {
1605 StringBuilder sb = new StringBuilder(name.length() * 2);
1606 int last = name.length();
1607 for (int i = 0; i < last; i++) {
1608 final char ch = name.charAt(i);
1610 case '_': sb.append("_1"); break;
1611 default: sb.append(ch); break;
1614 return sb.toString();
1616 private static String mangleSig(String txt, int first, int last) {
1617 StringBuilder sb = new StringBuilder((last - first) * 2);
1618 for (int i = first; i < last; i++) {
1619 final char ch = txt.charAt(i);
1621 case '/': sb.append('_'); break;
1622 case '_': sb.append("_1"); break;
1623 case ';': sb.append("_2"); break;
1624 case '[': sb.append("_3"); break;
1626 if (Character.isJavaIdentifierPart(ch)) {
1630 String hex = Integer.toHexString(ch).toLowerCase();
1631 for (int m = hex.length(); m < 4; m++) {
1639 return sb.toString();
1642 private static String mangleClassName(String name) {
1643 return mangleSig(name);
1646 private static String findMethodName(MethodData m, StringBuilder cnt) {
1647 StringBuilder name = new StringBuilder();
1648 if ("<init>".equals(m.getName())) { // NOI18N
1649 name.append("cons"); // NOI18N
1650 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1651 name.append("class"); // NOI18N
1653 name.append(mangleMethodName(m.getName()));
1656 countArgs(m.getInternalSig(), new char[1], name, cnt);
1657 return name.toString();
1660 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1661 StringBuilder name = new StringBuilder();
1662 String descr = mi[2];//mi.getDescriptor();
1664 if ("<init>".equals(nm)) { // NOI18N
1665 name.append("cons"); // NOI18N
1667 name.append(mangleMethodName(nm));
1669 countArgs(descr, returnType, name, cnt);
1670 return name.toString();
1673 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1674 throws IOException {
1675 int methodIndex = readUShortArg(byteCodes, i);
1676 String[] mi = jc.getFieldInfoName(methodIndex);
1677 char[] returnType = { 'V' };
1678 StringBuilder cnt = new StringBuilder();
1679 String mn = findMethodName(mi, cnt, returnType);
1681 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1682 final CharSequence[] vars = new CharSequence[numArguments];
1684 for (int j = numArguments - 1; j >= 0; --j) {
1685 vars[j] = mapper.popValue();
1688 if (returnType[0] != 'V') {
1691 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1695 final String in = mi[0];
1698 in.equals("org/apidesign/html/boot/spi/Fn") ||
1699 in.equals("org/netbeans/html/boot/spi/Fn")
1701 mcn = "java_lang_Class";
1703 mcn = mangleClassName(in);
1705 String object = accessClass(mcn) + "(false)";
1706 if (mn.startsWith("cons_")) {
1707 object += ".constructor";
1709 append(accessStaticMethod(object, mn, mi));
1715 if (numArguments > 0) {
1717 for (int j = 1; j < numArguments; ++j) {
1727 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1728 throws IOException {
1729 int methodIndex = readUShortArg(byteCodes, i);
1730 String[] mi = jc.getFieldInfoName(methodIndex);
1731 char[] returnType = { 'V' };
1732 StringBuilder cnt = new StringBuilder();
1733 String mn = findMethodName(mi, cnt, returnType);
1735 final int numArguments = cnt.length() + 1;
1736 final CharSequence[] vars = new CharSequence[numArguments];
1738 for (int j = numArguments - 1; j >= 0; --j) {
1739 vars[j] = mapper.popValue();
1742 if (returnType[0] != 'V') {
1744 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1748 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1750 for (int j = 1; j < numArguments; ++j) {
1760 private void addReference(String cn) throws IOException {
1761 if (requireReference(cn)) {
1762 debug(" /* needs " + cn + " */");
1766 private void outType(String d, StringBuilder out) {
1768 while (d.charAt(0) == '[') {
1772 if (d.charAt(0) == 'L') {
1773 assert d.charAt(d.length() - 1) == ';';
1774 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1780 private String encodeConstant(int entryIndex) throws IOException {
1781 String[] classRef = { null };
1782 String s = jc.stringValue(entryIndex, classRef);
1783 if (classRef[0] != null) {
1784 if (classRef[0].startsWith("[")) {
1785 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1787 addReference(classRef[0]);
1788 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1794 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1795 byte[] arr = m.findAnnotationData(true);
1799 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1800 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1801 class P extends AnnotationParser {
1807 String[] args = new String[30];
1813 protected void visitAttr(String type, String attr, String at, String value) {
1814 if (type.equals(jvmType)) {
1815 if ("body".equals(attr)) {
1817 } else if ("args".equals(attr)) {
1818 args[cnt++] = value;
1820 throw new IllegalArgumentException(attr);
1823 if (type.equals(htmlType)) {
1825 if ("body".equals(attr)) {
1827 } else if ("args".equals(attr)) {
1828 args[cnt++] = value;
1829 } else if ("javacall".equals(attr)) {
1830 javacall = "1".equals(value);
1831 } else if ("wait4js".equals(attr)) {
1832 // ignore, we always invoke synchronously
1834 throw new IllegalArgumentException(attr);
1841 if (p.body == null) {
1844 StringBuilder cnt = new StringBuilder();
1845 final String mn = findMethodName(m, cnt);
1846 append("m = ").append(destObject).append(".").append(mn);
1847 append(" = function(");
1850 StringBuilder toValue = new StringBuilder();
1851 for (int i = 0; i < cnt.length(); i++) {
1853 space = outputArg(this, p.args, index);
1854 if (p.html4j && space.length() > 0) {
1855 toValue.append("\n ").append(p.args[index]).append(" = ")
1856 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1857 append(p.args[index]).append(");");
1861 append(") {").append("\n");
1862 append(toValue.toString());
1864 int lastSlash = jc.getClassName().lastIndexOf('/');
1865 final String pkg = jc.getClassName().substring(0, lastSlash);
1866 append(mangleCallbacks(pkg, p.body));
1867 requireReference(pkg + "/$JsCallbacks$");
1875 private static CharSequence mangleCallbacks(String pkgName, String body) {
1876 StringBuilder sb = new StringBuilder();
1879 int next = body.indexOf(".@", pos);
1881 sb.append(body.substring(pos));
1882 body = sb.toString();
1887 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1892 String refId = body.substring(ident, next);
1894 sb.append(body.substring(pos, ident));
1896 int sigBeg = body.indexOf('(', next);
1897 int sigEnd = body.indexOf(')', sigBeg);
1898 int colon4 = body.indexOf("::", next);
1899 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1900 throw new IllegalStateException("Malformed body " + body);
1902 String fqn = body.substring(next + 2, colon4);
1903 String method = body.substring(colon4 + 2, sigBeg);
1904 String params = body.substring(sigBeg, sigEnd + 1);
1906 int paramBeg = body.indexOf('(', sigEnd + 1);
1908 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1909 sb.append(mangleJsCallbacks(fqn, method, params, false));
1910 sb.append("(").append(refId);
1911 if (body.charAt(paramBeg + 1) != ')') {
1919 int next = body.indexOf("@", pos);
1924 sb.append(body.substring(pos));
1928 sb = new StringBuilder();
1931 sb.append(body.substring(pos, next));
1933 int sigBeg = body.indexOf('(', next);
1934 int sigEnd = body.indexOf(')', sigBeg);
1935 int colon4 = body.indexOf("::", next);
1936 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1937 throw new IllegalStateException("Malformed body " + body);
1939 String fqn = body.substring(next + 1, colon4);
1940 String method = body.substring(colon4 + 2, sigBeg);
1941 String params = body.substring(sigBeg, sigEnd + 1);
1943 int paramBeg = body.indexOf('(', sigEnd + 1);
1945 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1946 sb.append(mangleJsCallbacks(fqn, method, params, true));
1952 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1953 if (params.startsWith("(")) {
1954 params = params.substring(1);
1956 if (params.endsWith(")")) {
1957 params = params.substring(0, params.length() - 1);
1959 StringBuilder sb = new StringBuilder();
1960 final String fqnu = fqn.replace('.', '_');
1961 final String rfqn = mangleClassName(fqnu);
1962 final String rm = mangleMethodName(method);
1965 StringBuilder pb = new StringBuilder();
1966 int len = params.length();
1968 while (indx < len) {
1969 char ch = params.charAt(indx);
1970 if (ch == '[' || ch == 'L') {
1971 pb.append("Ljava/lang/Object;");
1972 indx = params.indexOf(';', indx) + 1;
1978 srp = mangleSig(pb.toString());
1980 final String rp = mangleSig(params);
1981 final String mrp = mangleMethodName(rp);
1982 sb.append(rfqn).append("$").append(rm).
1983 append('$').append(mrp).append("__Ljava_lang_Object_2");
1985 sb.append('L').append(fqnu).append("_2");
1988 return sb.toString();
1991 private static String className(ClassData jc) {
1992 //return jc.getName().getInternalName().replace('/', '_');
1993 return mangleClassName(jc.getClassName());
1996 private static String[] findAnnotation(
1997 byte[] arr, ClassData cd, final String className,
1998 final String... attrNames
1999 ) throws IOException {
2003 final String[] values = new String[attrNames.length];
2004 final boolean[] found = { false };
2005 final String jvmType = "L" + className.replace('.', '/') + ";";
2006 AnnotationParser ap = new AnnotationParser(false, true) {
2008 protected void visitAttr(String type, String attr, String at, String value) {
2009 if (type.equals(jvmType)) {
2011 for (int i = 0; i < attrNames.length; i++) {
2012 if (attrNames[i].equals(attr)) {
2021 return found[0] ? values : null;
2024 private CharSequence initField(FieldData v) {
2025 final String is = v.getInternalSig();
2026 if (is.length() == 1) {
2027 switch (is.charAt(0)) {
2033 case 'I': return " = 0;";
2035 case 'D': return " = 0.0;";
2037 throw new IllegalStateException(is);
2043 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2044 AnnotationParser ap = new AnnotationParser(true, false) {
2045 int[] cnt = new int[32];
2049 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2050 final String slashType = attrType.substring(1, attrType.length() - 1);
2051 requireReference(slashType);
2053 if (cnt[depth]++ > 0) {
2057 append('"').append(attrType).append("\" : ");
2064 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2070 protected void visitValueStart(String attrName, char type) throws IOException {
2071 if (cnt[depth]++ > 0) {
2075 if (attrName != null) {
2076 append('"').append(attrName).append("\" : ");
2084 protected void visitValueEnd(String attrName, char type) throws IOException {
2092 protected void visitAttr(String type, String attr, String attrType, String value)
2093 throws IOException {
2094 if (attr == null && value == null) {
2101 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2102 throws IOException {
2103 final String slashType = attrType.substring(1, attrType.length() - 1);
2104 requireReference(slashType);
2106 final String cn = mangleClassName(slashType);
2107 append(accessClass(cn))
2108 .append("(false)['valueOf__L").
2110 append("_2Ljava_lang_String_2']('").
2118 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2119 final String name = args[indx];
2123 if (name.contains(",")) {
2124 throw new IOException("Wrong parameter with ',': " + name);
2130 final void emitNoFlush(
2132 final String format, final CharSequence... params
2133 ) throws IOException {
2134 emitImpl(this, format, params);
2136 static final void emit(
2138 final Appendable out,
2139 final String format, final CharSequence... params
2140 ) throws IOException {
2142 emitImpl(out, format, params);
2144 static void emitImpl(final Appendable out,
2145 final String format,
2146 final CharSequence... params) throws IOException {
2147 final int length = format.length();
2150 int paramOffset = format.indexOf('@');
2151 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2152 final char paramChar = format.charAt(paramOffset + 1);
2153 if ((paramChar >= '1') && (paramChar <= '9')) {
2154 final int paramIndex = paramChar - '0' - 1;
2156 out.append(format, processed, paramOffset);
2157 out.append(params[paramIndex]);
2160 processed = paramOffset + 1;
2163 paramOffset = format.indexOf('@', paramOffset + 1);
2166 out.append(format, processed, length);
2169 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2170 append("} catch (e) {\n");
2172 for (TrapData e : traps) {
2176 if (e.catch_cpx != 0) { //not finally
2177 final String classInternalName = jc.getClassName(e.catch_cpx);
2178 addReference(classInternalName);
2179 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2180 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2181 append("var stA0 = e;");
2182 goTo(this, current, e.handler_pc, topMostLabel);
2185 finallyPC = e.handler_pc;
2188 if (finallyPC == -1) {
2191 append("var stA0 = e;");
2192 goTo(this, current, finallyPC, topMostLabel);
2197 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2200 out.append("{ gt = 0; continue X_" + to + "; }");
2202 out.append("{ gt = " + to + "; continue X_0; }");
2205 out.append("{ gt = " + to + "; break IF; }");
2209 private static void emitIf(
2211 Appendable out, String pattern,
2213 int current, int to, int canBack
2214 ) throws IOException {
2216 emitImpl(out, pattern, param);
2217 goTo(out, current, to, canBack);
2220 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2223 case 4: jvmType = "[Z"; break;
2224 case 5: jvmType = "[C"; break;
2225 case 6: jvmType = "[F"; break;
2226 case 7: jvmType = "[D"; break;
2227 case 8: jvmType = "[B"; break;
2228 case 9: jvmType = "[S"; break;
2229 case 10: jvmType = "[I"; break;
2230 case 11: jvmType = "[J"; break;
2231 default: throw new IllegalStateException("Array type: " + atype);
2234 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2235 smapper.popI(), smapper.pushA(), jvmType);
2238 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2239 String typeName = jc.getClassName(type);
2240 String ref = "null";
2241 if (typeName.startsWith("[")) {
2242 typeName = "'[" + typeName + "'";
2244 ref = "vm." + mangleClassName(typeName);
2245 typeName = "'[L" + typeName + ";'";
2248 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2249 smapper.popI(), smapper.pushA(), typeName, ref);
2252 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2253 String typeName = jc.getClassName(type);
2254 int dim = readUByte(byteCodes, ++i);
2255 StringBuilder dims = new StringBuilder();
2257 for (int d = 0; d < dim; d++) {
2259 dims.insert(1, ",");
2261 dims.insert(1, smapper.popI());
2265 if (typeName.charAt(dim) == 'L') {
2266 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2269 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2270 dims.toString(), smapper.pushA(), typeName, fn
2275 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2276 int table = i / 4 * 4 + 4;
2277 int dflt = i + readInt4(byteCodes, table);
2279 int low = readInt4(byteCodes, table);
2281 int high = readInt4(byteCodes, table);
2283 final CharSequence swVar = smapper.popValue();
2284 smapper.flush(this);
2285 append("switch (").append(swVar).append(") {\n");
2286 while (low <= high) {
2287 int offset = i + readInt4(byteCodes, table);
2289 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2292 append(" default: ");
2293 goTo(this, i, dflt, topMostLabel);
2299 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2300 int table = i / 4 * 4 + 4;
2301 int dflt = i + readInt4(byteCodes, table);
2303 int n = readInt4(byteCodes, table);
2305 final CharSequence swVar = smapper.popValue();
2306 smapper.flush(this);
2307 append("switch (").append(swVar).append(") {\n");
2309 int cnstnt = readInt4(byteCodes, table);
2311 int offset = i + readInt4(byteCodes, table);
2313 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2315 append(" default: ");
2316 goTo(this, i, dflt, topMostLabel);
2322 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2323 String type = jc.getClassName(indx);
2324 if (!type.startsWith("[")) {
2326 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2327 smapper.popA(), smapper.pushI(),
2328 type.replace('/', '_'));
2331 while (type.charAt(cnt) == '[') {
2334 if (type.charAt(cnt) == 'L') {
2335 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2337 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2338 smapper.popA(), smapper.pushI(),
2343 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2344 smapper.popA(), smapper.pushI(), type
2350 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2351 String type = jc.getClassName(indx);
2352 if (!type.startsWith("[")) {
2353 emitNoFlush(smapper,
2354 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2355 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2358 while (type.charAt(cnt) == '[') {
2361 if (type.charAt(cnt) == 'L') {
2362 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2363 emitNoFlush(smapper,
2364 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2365 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2368 emitNoFlush(smapper,
2369 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2370 smapper.getT(0, VarType.REFERENCE, false), type
2376 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2377 for (int j = prev; j <= i; j++) {
2379 final int cc = readUByte(byteCodes, j);
2380 append(Integer.toString(cc));
2384 @JavaScriptBody(args = "msg", body = "")
2385 private static void println(String msg) {
2386 System.err.println(msg);