2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 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.*;
24 import org.apidesign.vm4brwsr.ByteCodeParser.AnnotationParser;
25 import org.apidesign.vm4brwsr.ByteCodeParser.BootMethodData;
26 import org.apidesign.vm4brwsr.ByteCodeParser.CPX2;
27 import org.apidesign.vm4brwsr.ByteCodeParser.ClassData;
28 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
29 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
30 import org.apidesign.vm4brwsr.ByteCodeParser.StackMapIterator;
31 import org.apidesign.vm4brwsr.ByteCodeParser.TrapData;
32 import org.apidesign.vm4brwsr.ByteCodeParser.TrapDataIterator;
34 /** Translator of the code inside class files to JavaScript.
36 * @author Jaroslav Tulach <jtulach@netbeans.org>
38 abstract class ByteCodeToJavaScript implements Appendable {
40 private final Appendable out;
41 private final StringArray classRefs = new StringArray();
42 private boolean outChanged;
43 private boolean callbacks;
45 protected ByteCodeToJavaScript(Appendable out) {
50 public final Appendable append(CharSequence csq) throws IOException {
57 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
58 out.append(csq, start, end);
64 public final Appendable append(char c) throws IOException {
70 /* Collects additional required resources.
72 * @param internalClassName classes that were referenced and should be loaded in order the
73 * generated JavaScript code works properly. The names are in internal
74 * JVM form so String is <code>java/lang/String</code>.
76 protected abstract boolean requireReference(String internalClassName);
79 * @param resourcePath name of resources to read
81 protected abstract void requireScript(String resourcePath) throws IOException;
83 protected abstract void requireResource(String resourcePath) throws IOException;
85 /** Allows subclasses to redefine what field a function representing a
86 * class gets assigned. By default it returns the suggested name followed
87 * by <code>" = "</code>;
89 * @param className suggested name of the class
91 /* protected */ String assignClass(String className) {
92 return className + " = ";
94 /* protected */ String accessClass(String classOperation) {
95 return classOperation;
98 final String accessClassFalse(String classOperation) {
99 if (mangleClassName(jc.getClassName()).equals(classOperation)) {
102 classRefs.addIfMissing(classOperation);
103 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
106 protected String accessField(String object, String[] fieldInfoName)
108 String mangledName = "_" + fieldInfoName[1];
109 return object + "." + mangledName;
112 protected String accessStaticMethod(
115 String[] fieldInfoName) throws IOException {
116 return object + "." + mangledName;
119 protected String accessVirtualMethod(
122 String[] fieldInfoName,
124 ) throws IOException {
125 return object + "." + mangledName + '(';
128 protected void declaredClass(ClassData classData, String mangledName)
132 protected void declaredField(FieldData fieldData,
134 String mangledName) throws IOException {
137 protected void declaredMethod(MethodData methodData,
139 String mangledName) throws IOException {
142 /** Prints out a debug message.
144 * @param msg the message
145 * @return true if the message has been printed
146 * @throws IOException
148 boolean debug(String msg) throws IOException {
154 * Converts a given class file to a JavaScript version.
156 * @param classFile input stream with code of the .class file
157 * @return the initialization code for this class, if any. Otherwise <code>null</code>
159 * @throws IOException if something goes wrong during read or write or translating
162 public String compile(InputStream classFile) throws IOException {
163 return compile(new ClassData(classFile));
166 protected String compile(ClassData classData) throws IOException {
168 final String cn = this.jc.getClassName();
170 return compileImpl(cn);
171 } catch (IOException ex) {
172 throw new IOException("Cannot compile " + cn + ":", ex);
176 private String compileImpl(final String cn) throws IOException {
177 this.callbacks = cn.endsWith("/$JsCallbacks$");
178 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
179 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
180 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
183 byte[] arrData = jc.findAnnotationData(true);
185 String[] arr = findAnnotation(arrData, jc,
186 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
187 "resource", "processByteCode"
190 if (!arr[0].isEmpty()) {
191 requireScript(arr[0]);
193 if ("0".equals(arr[1])) {
198 final String jsResource;
200 String[] arr = findAnnotation(arrData, jc,
201 "net.java.html.js.JavaScriptResource",
205 if (arr[0].startsWith("/")) {
208 int last = cn.lastIndexOf('/');
209 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
215 String[] proto = findAnnotation(arrData, jc,
216 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
217 "container", "prototype"
219 StringArray toInitilize = new StringArray();
220 final String className = className(jc);
221 append("\n\n").append(assignClass(className));
222 append("function ").append(className).append("() {");
224 append("\n var CLS = ").append(className).append(';');
225 append("\n if (!CLS.$class) {");
227 String sc = jc.getSuperClassName(); // with _
228 append("\n var pp = ").
229 append(accessClass(mangleClassName(sc))).append("(true);");
230 append("\n var p = CLS.prototype = pp;");
231 append("\n var c = p;");
232 append("\n var sprcls = pp.constructor.$class;");
234 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
235 if (proto[0] == null) {
238 append("\n var c = ").append(proto[0]).append(";");
239 append("\n var sprcls = null;");
241 for (FieldData v : jc.getFields()) {
243 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
244 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
248 append("\n CLS.fld_").append(v.getName()).append(initField(v));
249 append("\n m = c._").append(v.getName()).append(" = function (v) {")
250 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
251 .append(" = v; return CLS.fld_").
252 append(v.getName()).append("; };");
254 append("\n m = c._").append(v.getName()).append(" = function (v) {")
255 .append(" if (arguments.length == 1) this.fld_").
256 append(className).append('_').append(v.getName())
257 .append(" = v; return this.fld_").
258 append(className).append('_').append(v.getName())
262 declaredField(v, "c", "_" + v.getName());
264 for (MethodData m : jc.getMethods()) {
265 byte[] onlyArr = m.findAnnotationData(true);
266 if (javaScriptOnly(onlyArr)) continue;
272 mn = generateStaticMethod(destObject, m, toInitilize);
274 if (m.isConstructor()) {
276 mn = generateInstanceMethod(destObject, m);
279 mn = generateInstanceMethod(destObject, m);
282 declaredMethod(m, destObject, mn);
283 byte[] runAnno = m.findAnnotationData(false);
284 if (runAnno != null) {
285 append("\n m.anno = {");
286 generateAnno(jc, runAnno);
289 append("\n m.access = " + m.getAccess()).append(";");
290 append("\n m.cls = CLS;");
292 append("\n c.constructor = CLS;");
293 append("\n function ").append(className).append("fillInstOf(x) {");
294 String instOfName = "$instOf_" + className;
295 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
296 if (jc.isInterface()) {
297 for (MethodData m : jc.getMethods()) {
298 if ((m.getAccess() & ACC_ABSTRACT) == 0
299 && (m.getAccess() & ACC_STATIC) == 0
300 && (m.getAccess() & ACC_PRIVATE) == 0) {
301 final String mn = findMethodName(m, new StringBuilder());
302 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
306 for (String superInterface : jc.getSuperInterfaces()) {
307 String intrfc = mangleClassName(superInterface);
308 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
309 requireReference(superInterface);
312 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
313 append("\n ").append(className).append("fillInstOf(c);");
314 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
315 append("\n CLS.$class = 'temp';");
316 append("\n CLS.$class = ");
317 append(accessClass("java_lang_Class(true);"));
318 append("\n CLS.$class.jvmName = '").append(cn).append("';");
319 append("\n CLS.$class.superclass = sprcls;");
320 append("\n CLS.$class.interfaces = function() { return [");
322 boolean first = true;
323 for (String intrfc : jc.getSuperInterfaces()) {
327 requireReference(intrfc);
328 String mangledIface = mangleClassName(intrfc);
330 append(accessClass(mangledIface)).append("(false).constructor.$class");
335 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
336 append("\n CLS.$class.cnstr = CLS;");
337 byte[] classAnno = jc.findAnnotationData(false);
338 if (classAnno != null) {
339 append("\n CLS.$class.anno = {");
340 generateAnno(jc, classAnno);
343 for (String init : toInitilize.toArray()) {
344 append("\n ").append(init).append("();");
346 for (String ref : classRefs.toArray()) {
347 append("\n var refs_").append(ref).append(";");
351 if (jsResource != null) {
352 requireResource(jsResource);
356 append("\n if (arguments.length === 0) {");
357 append("\n if (!(this instanceof CLS)) {");
358 append("\n return new CLS();");
360 for (FieldData v : jc.getFields()) {
361 byte[] onlyArr = v.findAnnotationData(true);
362 if (javaScriptOnly(onlyArr)) continue;
364 append("\n this.fld_").
365 append(className).append('_').
366 append(v.getName()).append(initField(v));
369 append("\n return this;");
371 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
374 declaredClass(jc, className);
376 // StringBuilder sb = new StringBuilder();
377 // for (String init : toInitilize.toArray()) {
378 // sb.append("\n").append(init).append("();");
383 private boolean javaScriptOnly(byte[] anno) throws IOException {
384 String[] only = findAnnotation(anno, jc,
385 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
389 if (only[0] != null && only[1] != null) {
390 append("\n p.").append(only[0]).append(" = ")
391 .append(only[1]).append(";");
393 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
394 append("\n p['").append(only[0]).append("'] = p.")
395 .append(only[0]).append(";");
401 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
402 String jsb = javaScriptBody(destObject, m, true);
406 final String mn = findMethodName(m, new StringBuilder());
407 boolean defineProp = generateMethod(destObject, mn, m);
408 if (mn.equals("class__V")) {
410 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
412 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
418 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
419 String jsb = javaScriptBody(destObject, m, false);
423 final String mn = findMethodName(m, new StringBuilder());
424 generateMethod(destObject, mn, m);
428 private boolean generateMethod(String destObject, String name, MethodData m)
430 final StackMapIterator stackMapIterator = m.createStackMapIterator();
431 TrapDataIterator trap = m.getTrapDataIterator();
432 final LocalsMapper lmapper =
433 new LocalsMapper(stackMapIterator.getArguments());
436 "java/lang/Object".equals(jc.getClassName()) ||
437 "java/lang/reflect/Array".equals(jc.getClassName());
440 append("Object.defineProperty(").append(destObject).
441 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
443 append("m = ").append(destObject).append(".").append(name).append(" = function(");
445 lmapper.outputArguments(this, m.isStatic());
446 append(") {").append("\n");
448 final byte[] byteCodes = m.getCode();
449 if (byteCodes == null) {
450 if (debug(" throw 'no code found for ")) {
452 .append(jc.getClassName()).append('.')
453 .append(m.getName()).append("';\n");
463 final StackMapper smapper = new StackMapper();
466 append(" var ").append(" lcA0 = this;\n");
470 TrapData[] previousTrap = null;
471 boolean wide = false;
473 if (stackMapIterator.isEmpty()) {
479 append("\n var gt = 0;\n");
483 int topMostLabel = 0;
484 for (int i = 0; i < byteCodes.length; i++) {
487 stackMapIterator.advanceTo(i);
488 boolean changeInCatch = trap.advanceTo(i);
489 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
490 if (previousTrap != null) {
491 generateCatch(previousTrap, i, topMostLabel);
495 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
500 if (openBraces > 64) {
501 for (int c = 0; c < 64; c++) {
508 lastStackFrame = stackMapIterator.getFrameIndex();
509 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
510 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
511 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
513 changeInCatch = true;
515 debug(" /* " + i + " */ ");
517 if (changeInCatch && trap.useTry()) {
519 previousTrap = trap.current();
521 final int c = readUByte(byteCodes, i);
524 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
527 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
530 smapper.assign(this, VarType.LONG, lmapper.getL(0));
533 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
536 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
539 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
542 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
545 smapper.assign(this, VarType.LONG, lmapper.getL(1));
548 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
551 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
554 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
557 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
560 smapper.assign(this, VarType.LONG, lmapper.getL(2));
563 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
566 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
569 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
572 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
575 smapper.assign(this, VarType.LONG, lmapper.getL(3));
578 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
581 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
585 final int indx = wide ? readUShort(byteCodes, i++)
586 : readUByte(byteCodes, i);
588 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
593 final int indx = wide ? readUShort(byteCodes, i++)
594 : readUByte(byteCodes, i);
596 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
601 final int indx = wide ? readUShort(byteCodes, i++)
602 : readUByte(byteCodes, i);
604 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
609 final int indx = wide ? readUShort(byteCodes, i++)
610 : readUByte(byteCodes, i);
612 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
617 final int indx = wide ? readUShort(byteCodes, i++)
618 : readUByte(byteCodes, i);
620 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
625 final int indx = wide ? readUShort(byteCodes, i++)
626 : readUByte(byteCodes, i);
628 emit(smapper, this, "var @1 = @2;",
629 lmapper.setI(indx), smapper.popI());
634 final int indx = wide ? readUShort(byteCodes, i++)
635 : readUByte(byteCodes, i);
637 emit(smapper, this, "var @1 = @2;",
638 lmapper.setL(indx), smapper.popL());
643 final int indx = wide ? readUShort(byteCodes, i++)
644 : readUByte(byteCodes, i);
646 emit(smapper, this, "var @1 = @2;",
647 lmapper.setF(indx), smapper.popF());
652 final int indx = wide ? readUShort(byteCodes, i++)
653 : readUByte(byteCodes, i);
655 emit(smapper, this, "var @1 = @2;",
656 lmapper.setD(indx), smapper.popD());
661 final int indx = wide ? readUShort(byteCodes, i++)
662 : readUByte(byteCodes, i);
664 emit(smapper, this, "var @1 = @2;",
665 lmapper.setA(indx), smapper.popA());
669 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
672 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
675 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
678 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
681 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
684 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
687 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
690 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
693 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
696 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
699 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
702 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
705 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
708 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
711 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
714 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
717 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
720 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
723 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
726 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
729 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
732 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
735 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
738 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
741 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
744 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
747 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
750 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
753 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
756 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
759 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
762 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
765 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
766 smapper.getI(1), smapper.popI());
769 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
770 smapper.getL(1), smapper.popL());
773 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
776 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
779 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
780 smapper.getI(1), smapper.popI());
783 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
784 smapper.getL(1), smapper.popL());
787 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
790 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
793 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
796 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
799 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
802 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
805 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
808 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
811 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
814 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
817 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
820 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
823 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
826 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
829 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
832 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
835 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
838 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
842 final int varIndx = wide ? readUShort(byteCodes, i++)
843 : readUByte(byteCodes, i);
845 final int incrBy = wide ? readShort(byteCodes, i++)
849 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
851 emit(smapper, this, "@1 += @2;",
852 lmapper.getI(varIndx),
853 Integer.toString(incrBy));
858 emit(smapper, this, "return;");
861 emit(smapper, this, "return @1;", smapper.popI());
864 emit(smapper, this, "return @1;", smapper.popL());
867 emit(smapper, this, "return @1;", smapper.popF());
870 emit(smapper, this, "return @1;", smapper.popD());
873 emit(smapper, this, "return @1;", smapper.popA());
876 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
879 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
882 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
885 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
889 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
892 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
895 smapper.replace(this, VarType.DOUBLE, "@1",
899 smapper.replace(this, VarType.FLOAT, "@1",
903 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
907 smapper.replace(this, VarType.LONG, "(@1).toLong()",
911 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
915 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
918 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
922 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
924 case opc_aconst_null:
925 smapper.assign(this, VarType.REFERENCE, "null");
928 smapper.assign(this, VarType.INTEGER, "-1");
931 smapper.assign(this, VarType.INTEGER, "0");
934 smapper.assign(this, VarType.DOUBLE, "0");
937 smapper.assign(this, VarType.LONG, "0");
940 smapper.assign(this, VarType.FLOAT, "0");
943 smapper.assign(this, VarType.INTEGER, "1");
946 smapper.assign(this, VarType.LONG, "1");
949 smapper.assign(this, VarType.FLOAT, "1");
952 smapper.assign(this, VarType.DOUBLE, "1");
955 smapper.assign(this, VarType.INTEGER, "2");
958 smapper.assign(this, VarType.FLOAT, "2");
961 smapper.assign(this, VarType.INTEGER, "3");
964 smapper.assign(this, VarType.INTEGER, "4");
967 smapper.assign(this, VarType.INTEGER, "5");
970 int indx = readUByte(byteCodes, ++i);
971 String v = encodeConstant(indx);
972 int type = VarType.fromConstantType(jc.getTag(indx));
973 smapper.assign(this, type, v);
978 int indx = readUShortArg(byteCodes, i);
980 String v = encodeConstant(indx);
981 int type = VarType.fromConstantType(jc.getTag(indx));
982 if (type == VarType.LONG) {
983 final Long lv = new Long(v);
984 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
985 final int hi = (int)(lv.longValue() >> 32);
987 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
989 smapper.assign(this, VarType.LONG,
990 "0x" + Integer.toHexString(hi) + ".next32(0x" +
991 Integer.toHexString(low) + ")"
995 smapper.assign(this, type, v);
1000 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1004 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1005 smapper.popF(), smapper.popF(), smapper.pushI());
1009 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1010 smapper.popD(), smapper.popD(), smapper.pushI());
1013 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1014 "===", topMostLabel);
1017 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1018 "!==", topMostLabel);
1021 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1022 "==", topMostLabel);
1025 int indx = i + readShortArg(byteCodes, i);
1026 emitIf(smapper, this, "if ((@1) == 0) ",
1027 smapper.popI(), i, indx, topMostLabel);
1032 int indx = i + readShortArg(byteCodes, i);
1033 emitIf(smapper, this, "if ((@1) != 0) ",
1034 smapper.popI(), i, indx, topMostLabel);
1039 int indx = i + readShortArg(byteCodes, i);
1040 emitIf(smapper, this, "if ((@1) < 0) ",
1041 smapper.popI(), i, indx, topMostLabel);
1046 int indx = i + readShortArg(byteCodes, i);
1047 emitIf(smapper, this, "if ((@1) <= 0) ",
1048 smapper.popI(), i, indx, topMostLabel);
1053 int indx = i + readShortArg(byteCodes, i);
1054 emitIf(smapper, this, "if ((@1) > 0) ",
1055 smapper.popI(), i, indx, topMostLabel);
1060 int indx = i + readShortArg(byteCodes, i);
1061 emitIf(smapper, this, "if ((@1) >= 0) ",
1062 smapper.popI(), i, indx, topMostLabel);
1066 case opc_ifnonnull: {
1067 int indx = i + readShortArg(byteCodes, i);
1068 emitIf(smapper, this, "if ((@1) !== null) ",
1069 smapper.popA(), i, indx, topMostLabel);
1074 int indx = i + readShortArg(byteCodes, i);
1075 emitIf(smapper, this, "if ((@1) === null) ",
1076 smapper.popA(), i, indx, topMostLabel);
1081 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1082 "!=", topMostLabel);
1085 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1089 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1090 "<=", topMostLabel);
1093 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1097 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1098 ">=", topMostLabel);
1101 smapper.flush(this);
1102 int indx = i + readShortArg(byteCodes, i);
1103 goTo(this, i, indx, topMostLabel);
1107 case opc_lookupswitch: {
1108 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1111 case opc_tableswitch: {
1112 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1115 case opc_invokeinterface: {
1116 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1119 case opc_invokevirtual:
1120 i = invokeVirtualMethod(byteCodes, i, smapper);
1122 case opc_invokespecial:
1123 i = invokeStaticMethod(byteCodes, i, smapper, false);
1125 case opc_invokestatic:
1126 i = invokeStaticMethod(byteCodes, i, smapper, true);
1128 case opc_invokedynamic: {
1129 int indx = readUShortArg(byteCodes, i);
1130 println("invoke dynamic: " + indx);
1131 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1132 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1133 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1134 println(" type: " + methodHandle.cpx1);
1135 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1136 String mcn = mangleClassName(mi[0]);
1137 char[] returnType = {'V'};
1138 StringBuilder cnt = new StringBuilder();
1139 String mn = findMethodName(mi, cnt, returnType);
1140 StringBuilder sb = new StringBuilder();
1141 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1142 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1143 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1144 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1145 sb.append(" mn : ").append(mn).append("\n");
1146 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1147 throw new IOException(sb.toString());
1149 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1150 String type = jc.StringValue(nameAndType.cpx2);
1151 String object = accessClass(mcn) + "(false)";
1152 if (mn.startsWith("cons_")) {
1153 object += ".constructor";
1155 append("var metHan = ");
1156 append(accessStaticMethod(object, mn, mi));
1158 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1160 append(", '").append(mi[1]).append("', ");
1161 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1162 append(methodType).append("'").append(type).append("', null)");
1163 // if (numArguments > 0) {
1165 // for (int j = 1; j < numArguments; ++j) {
1171 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1177 int indx = readUShortArg(byteCodes, i);
1178 String ci = jc.getClassName(indx);
1179 emit(smapper, this, "var @1 = new @2;",
1180 smapper.pushA(), accessClass(mangleClassName(ci)));
1186 int atype = readUByte(byteCodes, ++i);
1187 generateNewArray(atype, smapper);
1189 case opc_anewarray: {
1190 int type = readUShortArg(byteCodes, i);
1192 generateANewArray(type, smapper);
1195 case opc_multianewarray: {
1196 int type = readUShortArg(byteCodes, i);
1198 i = generateMultiANewArray(type, byteCodes, i, smapper);
1201 case opc_arraylength:
1202 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1205 emit(smapper, this, "Array.at(@3, @2, @1);",
1206 smapper.popL(), smapper.popI(), smapper.popA());
1209 emit(smapper, this, "Array.at(@3, @2, @1);",
1210 smapper.popF(), smapper.popI(), smapper.popA());
1213 emit(smapper, this, "Array.at(@3, @2, @1);",
1214 smapper.popD(), smapper.popI(), smapper.popA());
1217 emit(smapper, this, "Array.at(@3, @2, @1);",
1218 smapper.popA(), smapper.popI(), smapper.popA());
1224 emit(smapper, this, "Array.at(@3, @2, @1);",
1225 smapper.popI(), smapper.popI(), smapper.popA());
1228 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1229 smapper.popI(), smapper.getA(0));
1232 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1233 smapper.popI(), smapper.getA(0));
1236 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1237 smapper.popI(), smapper.getA(0));
1240 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1241 smapper.popI(), smapper.getA(0));
1247 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1248 smapper.popI(), smapper.getA(0));
1256 final Variable v = smapper.get(0);
1257 if (smapper.isDirty()) {
1258 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1260 smapper.assign(this, v.getType(), v);
1265 final Variable vi1 = smapper.get(0);
1267 if (vi1.isCategory2()) {
1268 emit(smapper, this, "var @1 = @2;",
1269 smapper.pushT(vi1.getType()), vi1);
1271 final Variable vi2 = smapper.get(1);
1272 emit(smapper, this, "var @1 = @2, @3 = @4;",
1273 smapper.pushT(vi2.getType()), vi2,
1274 smapper.pushT(vi1.getType()), vi1);
1279 final Variable vi1 = smapper.pop(this);
1280 final Variable vi2 = smapper.pop(this);
1281 final Variable vo3 = smapper.pushT(vi1.getType());
1282 final Variable vo2 = smapper.pushT(vi2.getType());
1283 final Variable vo1 = smapper.pushT(vi1.getType());
1285 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1286 vo1, vi1, vo2, vi2, vo3, vo1);
1290 final Variable vi1 = smapper.pop(this);
1291 final Variable vi2 = smapper.pop(this);
1293 if (vi1.isCategory2()) {
1294 final Variable vo3 = smapper.pushT(vi1.getType());
1295 final Variable vo2 = smapper.pushT(vi2.getType());
1296 final Variable vo1 = smapper.pushT(vi1.getType());
1298 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1299 vo1, vi1, vo2, vi2, vo3, vo1);
1301 final Variable vi3 = smapper.pop(this);
1302 final Variable vo5 = smapper.pushT(vi2.getType());
1303 final Variable vo4 = smapper.pushT(vi1.getType());
1304 final Variable vo3 = smapper.pushT(vi3.getType());
1305 final Variable vo2 = smapper.pushT(vi2.getType());
1306 final Variable vo1 = smapper.pushT(vi1.getType());
1308 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1309 vo1, vi1, vo2, vi2, vo3, vi3);
1310 emit(smapper, this, " @1 = @2, @3 = @4;",
1311 vo4, vo1, vo5, vo2);
1316 final Variable vi1 = smapper.pop(this);
1317 final Variable vi2 = smapper.pop(this);
1319 if (vi2.isCategory2()) {
1320 final Variable vo3 = smapper.pushT(vi1.getType());
1321 final Variable vo2 = smapper.pushT(vi2.getType());
1322 final Variable vo1 = smapper.pushT(vi1.getType());
1324 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1325 vo1, vi1, vo2, vi2, vo3, vo1);
1327 final Variable vi3 = smapper.pop(this);
1328 final Variable vo4 = smapper.pushT(vi1.getType());
1329 final Variable vo3 = smapper.pushT(vi3.getType());
1330 final Variable vo2 = smapper.pushT(vi2.getType());
1331 final Variable vo1 = smapper.pushT(vi1.getType());
1333 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1334 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1339 final Variable vi1 = smapper.pop(this);
1340 final Variable vi2 = smapper.pop(this);
1342 if (vi1.isCategory2()) {
1343 if (vi2.isCategory2()) {
1344 final Variable vo3 = smapper.pushT(vi1.getType());
1345 final Variable vo2 = smapper.pushT(vi2.getType());
1346 final Variable vo1 = smapper.pushT(vi1.getType());
1348 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1349 vo1, vi1, vo2, vi2, vo3, vo1);
1351 final Variable vi3 = smapper.pop(this);
1352 final Variable vo4 = smapper.pushT(vi1.getType());
1353 final Variable vo3 = smapper.pushT(vi3.getType());
1354 final Variable vo2 = smapper.pushT(vi2.getType());
1355 final Variable vo1 = smapper.pushT(vi1.getType());
1357 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1358 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1361 final Variable vi3 = smapper.pop(this);
1363 if (vi3.isCategory2()) {
1364 final Variable vo5 = smapper.pushT(vi2.getType());
1365 final Variable vo4 = smapper.pushT(vi1.getType());
1366 final Variable vo3 = smapper.pushT(vi3.getType());
1367 final Variable vo2 = smapper.pushT(vi2.getType());
1368 final Variable vo1 = smapper.pushT(vi1.getType());
1370 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1371 vo1, vi1, vo2, vi2, vo3, vi3);
1372 emit(smapper, this, " @1 = @2, @3 = @4;",
1373 vo4, vo1, vo5, vo2);
1375 final Variable vi4 = smapper.pop(this);
1376 final Variable vo6 = smapper.pushT(vi2.getType());
1377 final Variable vo5 = smapper.pushT(vi1.getType());
1378 final Variable vo4 = smapper.pushT(vi4.getType());
1379 final Variable vo3 = smapper.pushT(vi3.getType());
1380 final Variable vo2 = smapper.pushT(vi2.getType());
1381 final Variable vo1 = smapper.pushT(vi1.getType());
1383 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1384 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1385 emit(smapper, this, " @1 = @2, @3 = @4;",
1386 vo5, vo1, vo6, vo2);
1392 final Variable vi1 = smapper.get(0);
1393 final Variable vi2 = smapper.get(1);
1395 if (vi1.getType() == vi2.getType()) {
1396 final Variable tmp = smapper.pushT(vi1.getType());
1398 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1403 smapper.pushT(vi1.getType());
1404 smapper.pushT(vi2.getType());
1409 smapper.assign(this, VarType.INTEGER,
1410 "(" + Integer.toString(byteCodes[++i]) + ")");
1413 smapper.assign(this, VarType.INTEGER,
1414 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1418 case opc_getfield: {
1419 int indx = readUShortArg(byteCodes, i);
1420 String[] fi = jc.getFieldInfoName(indx);
1421 final int type = VarType.fromFieldType(fi[2].charAt(0));
1422 final String mangleClass = mangleClassName(fi[0]);
1423 final String mangleClassAccess = accessClassFalse(mangleClass);
1424 smapper.replace(this, type, "@2.call(@1)",
1426 accessField(mangleClassAccess, fi)
1429 addReference(fi[0]);
1432 case opc_putfield: {
1433 int indx = readUShortArg(byteCodes, i);
1434 String[] fi = jc.getFieldInfoName(indx);
1435 final int type = VarType.fromFieldType(fi[2].charAt(0));
1436 final String mangleClass = mangleClassName(fi[0]);
1437 final String mangleClassAccess = accessClassFalse(mangleClass);
1438 emit(smapper, this, "@3.call(@2, @1);",
1441 accessField(mangleClassAccess, fi));
1443 addReference(fi[0]);
1446 case opc_getstatic: {
1447 int indx = readUShortArg(byteCodes, i);
1448 String[] fi = jc.getFieldInfoName(indx);
1449 final int type = VarType.fromFieldType(fi[2].charAt(0));
1450 String ac = accessClassFalse(mangleClassName(fi[0]));
1451 String af = accessField(ac, fi);
1452 smapper.assign(this, type, af + "()");
1454 addReference(fi[0]);
1457 case opc_putstatic: {
1458 int indx = readUShortArg(byteCodes, i);
1459 String[] fi = jc.getFieldInfoName(indx);
1460 final int type = VarType.fromFieldType(fi[2].charAt(0));
1461 emit(smapper, this, "@1._@2(@3);",
1462 accessClassFalse(mangleClassName(fi[0])), fi[1],
1463 smapper.popT(type));
1465 addReference(fi[0]);
1468 case opc_checkcast: {
1469 int indx = readUShortArg(byteCodes, i);
1470 generateCheckcast(indx, smapper);
1474 case opc_instanceof: {
1475 int indx = readUShortArg(byteCodes, i);
1476 generateInstanceOf(indx, smapper);
1481 final CharSequence v = smapper.popA();
1484 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1485 smapper.pushA(), v);
1489 case opc_monitorenter: {
1490 debug("/* monitor enter */");
1495 case opc_monitorexit: {
1496 debug("/* monitor exit */");
1507 emit(smapper, this, "throw 'unknown bytecode @1';",
1508 Integer.toString(c));
1512 generateByteCodeComment(prev, i, byteCodes);
1518 if (previousTrap != null) {
1519 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1524 while (openBraces-- > 0) {
1535 private int generateIf(StackMapper mapper, byte[] byteCodes,
1536 int i, final CharSequence v2, final CharSequence v1,
1537 final String test, int topMostLabel
1538 ) throws IOException {
1540 int indx = i + readShortArg(byteCodes, i);
1541 append("if ((").append(v1)
1542 .append(") ").append(test).append(" (")
1543 .append(v2).append(")) ");
1544 goTo(this, i, indx, topMostLabel);
1548 private int readInt4(byte[] byteCodes, int offset) {
1549 final int d = byteCodes[offset + 0] << 24;
1550 final int c = byteCodes[offset + 1] << 16;
1551 final int b = byteCodes[offset + 2] << 8;
1552 final int a = byteCodes[offset + 3];
1553 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1555 private static int readUByte(byte[] byteCodes, int offset) {
1556 return byteCodes[offset] & 0xff;
1559 private static int readUShort(byte[] byteCodes, int offset) {
1560 return ((byteCodes[offset] & 0xff) << 8)
1561 | (byteCodes[offset + 1] & 0xff);
1563 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1564 return readUShort(byteCodes, offsetInstruction + 1);
1567 private static int readShort(byte[] byteCodes, int offset) {
1568 int signed = byteCodes[offset];
1569 byte b0 = (byte)signed;
1570 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1572 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1573 return readShort(byteCodes, offsetInstruction + 1);
1576 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1578 Boolean count = null;
1579 boolean array = false;
1581 int firstPos = sig.length();
1582 while (i < descriptor.length()) {
1583 char ch = descriptor.charAt(i++);
1604 if (ch == 'J' || ch == 'D') {
1610 sig.insert(firstPos, ch);
1612 returnType[0] = '[';
1613 sig.insert(firstPos, "_3");
1622 returnType[0] = 'V';
1623 sig.insert(firstPos, 'V');
1626 int next = descriptor.indexOf(';', i);
1627 String realSig = mangleSig(descriptor, i - 1, next + 1);
1632 sig.append(realSig);
1635 sig.insert(firstPos, realSig);
1637 sig.insert(firstPos, "_3");
1639 returnType[0] = 'L';
1648 throw new IllegalStateException("Invalid char: " + ch);
1653 static String mangleSig(String sig) {
1654 return mangleSig(sig, 0, sig.length());
1657 private static String mangleMethodName(String name) {
1658 StringBuilder sb = new StringBuilder(name.length() * 2);
1659 int last = name.length();
1660 for (int i = 0; i < last; i++) {
1661 final char ch = name.charAt(i);
1663 case '_': sb.append("_1"); break;
1664 default: sb.append(ch); break;
1667 return sb.toString();
1669 private static String mangleSig(String txt, int first, int last) {
1670 StringBuilder sb = new StringBuilder((last - first) * 2);
1671 for (int i = first; i < last; i++) {
1672 final char ch = txt.charAt(i);
1674 case '/': sb.append('_'); break;
1675 case '_': sb.append("_1"); break;
1676 case ';': sb.append("_2"); break;
1677 case '[': sb.append("_3"); break;
1679 if (Character.isJavaIdentifierPart(ch)) {
1683 String hex = Integer.toHexString(ch).toLowerCase();
1684 for (int m = hex.length(); m < 4; m++) {
1692 return sb.toString();
1695 private static String mangleClassName(String name) {
1696 return mangleSig(name);
1699 private static String findMethodName(MethodData m, StringBuilder cnt) {
1700 StringBuilder name = new StringBuilder();
1701 if ("<init>".equals(m.getName())) { // NOI18N
1702 name.append("cons"); // NOI18N
1703 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1704 name.append("class"); // NOI18N
1706 name.append(mangleMethodName(m.getName()));
1709 countArgs(m.getInternalSig(), new char[1], name, cnt);
1710 return name.toString();
1713 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1714 StringBuilder name = new StringBuilder();
1715 String descr = mi[2];//mi.getDescriptor();
1717 if ("<init>".equals(nm)) { // NOI18N
1718 name.append("cons"); // NOI18N
1720 name.append(mangleMethodName(nm));
1722 countArgs(descr, returnType, name, cnt);
1723 return name.toString();
1726 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1727 throws IOException {
1728 int methodIndex = readUShortArg(byteCodes, i);
1729 String[] mi = jc.getFieldInfoName(methodIndex);
1730 char[] returnType = { 'V' };
1731 StringBuilder cnt = new StringBuilder();
1732 String mn = findMethodName(mi, cnt, returnType);
1734 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1735 final CharSequence[] vars = new CharSequence[numArguments];
1737 for (int j = numArguments - 1; j >= 0; --j) {
1738 vars[j] = mapper.popValue();
1742 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1743 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1745 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1746 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1748 if (vars[1] instanceof String) {
1749 String field = vars[1].toString();
1750 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1751 vars[1] = "c._" + field.substring(1, field.length() - 1);
1756 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1757 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1759 if (vars[1] instanceof String) {
1760 String field = vars[2].toString();
1761 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1762 vars[2] = "c._" + field.substring(1, field.length() - 1);
1767 if (returnType[0] != 'V') {
1770 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1774 final String in = mi[0];
1777 in.equals("org/apidesign/html/boot/spi/Fn") ||
1778 in.equals("org/netbeans/html/boot/spi/Fn")
1780 mcn = "java_lang_Class";
1782 mcn = mangleClassName(in);
1784 String object = accessClassFalse(mcn);
1785 if (mn.startsWith("cons_")) {
1786 object += ".constructor";
1788 append(accessStaticMethod(object, mn, mi));
1794 if (numArguments > 0) {
1796 for (int j = 1; j < numArguments; ++j) {
1806 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1807 throws IOException {
1808 int methodIndex = readUShortArg(byteCodes, i);
1809 String[] mi = jc.getFieldInfoName(methodIndex);
1810 char[] returnType = { 'V' };
1811 StringBuilder cnt = new StringBuilder();
1812 String mn = findMethodName(mi, cnt, returnType);
1814 final int numArguments = cnt.length() + 1;
1815 final CharSequence[] vars = new CharSequence[numArguments];
1817 for (int j = numArguments - 1; j >= 0; --j) {
1818 vars[j] = mapper.popValue();
1821 if (returnType[0] != 'V') {
1824 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1828 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1830 for (int j = 1; j < numArguments; ++j) {
1840 private void addReference(String cn) throws IOException {
1841 if (requireReference(cn)) {
1842 debug(" /* needs " + cn + " */");
1846 private void outType(String d, StringBuilder out) {
1848 while (d.charAt(0) == '[') {
1852 if (d.charAt(0) == 'L') {
1853 assert d.charAt(d.length() - 1) == ';';
1854 out.append(mangleClassName(d).substring(0, d.length() - 1));
1860 private String encodeConstant(int entryIndex) throws IOException {
1861 String[] classRef = { null };
1862 String s = jc.stringValue(entryIndex, classRef);
1863 if (classRef[0] != null) {
1864 if (classRef[0].startsWith("[")) {
1865 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1867 addReference(classRef[0]);
1868 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1874 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1875 byte[] arr = m.findAnnotationData(true);
1879 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1880 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1881 class P extends AnnotationParser {
1887 String[] args = new String[30];
1893 protected void visitAttr(String type, String attr, String at, String value) {
1894 if (type.equals(jvmType)) {
1895 if ("body".equals(attr)) {
1897 } else if ("args".equals(attr)) {
1898 args[cnt++] = value;
1900 throw new IllegalArgumentException(attr);
1903 if (type.equals(htmlType)) {
1905 if ("body".equals(attr)) {
1907 } else if ("args".equals(attr)) {
1908 args[cnt++] = value;
1909 } else if ("javacall".equals(attr)) {
1910 javacall = "1".equals(value);
1911 } else if ("wait4js".equals(attr)) {
1912 // ignore, we always invoke synchronously
1914 throw new IllegalArgumentException(attr);
1921 if (p.body == null) {
1924 StringBuilder cnt = new StringBuilder();
1925 final String mn = findMethodName(m, cnt);
1926 append("m = ").append(destObject).append(".").append(mn);
1927 append(" = function(");
1930 StringBuilder toValue = new StringBuilder();
1931 for (int i = 0; i < cnt.length(); i++) {
1933 space = outputArg(this, p.args, index);
1934 if (p.html4j && space.length() > 0) {
1935 toValue.append("\n ").append(p.args[index]).append(" = ")
1936 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1937 append(p.args[index]).append(");");
1941 append(") {").append("\n");
1942 append(toValue.toString());
1944 int lastSlash = jc.getClassName().lastIndexOf('/');
1945 final String pkg = jc.getClassName().substring(0, lastSlash);
1946 append(mangleCallbacks(pkg, p.body));
1947 requireReference(pkg + "/$JsCallbacks$");
1955 private static CharSequence mangleCallbacks(String pkgName, String body) {
1956 StringBuilder sb = new StringBuilder();
1959 int next = body.indexOf(".@", pos);
1961 sb.append(body.substring(pos));
1962 body = sb.toString();
1967 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1972 String refId = body.substring(ident, next);
1974 sb.append(body.substring(pos, ident));
1976 int sigBeg = body.indexOf('(', next);
1977 int sigEnd = body.indexOf(')', sigBeg);
1978 int colon4 = body.indexOf("::", next);
1979 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1980 throw new IllegalStateException("Malformed body " + body);
1982 String fqn = body.substring(next + 2, colon4);
1983 String method = body.substring(colon4 + 2, sigBeg);
1984 String params = body.substring(sigBeg, sigEnd + 1);
1986 int paramBeg = body.indexOf('(', sigEnd + 1);
1988 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
1989 sb.append(mangleJsCallbacks(fqn, method, params, false));
1990 sb.append("(").append(refId);
1991 if (body.charAt(paramBeg + 1) != ')') {
1999 int next = body.indexOf("@", pos);
2004 sb.append(body.substring(pos));
2008 sb = new StringBuilder();
2011 sb.append(body.substring(pos, next));
2013 int sigBeg = body.indexOf('(', next);
2014 int sigEnd = body.indexOf(')', sigBeg);
2015 int colon4 = body.indexOf("::", next);
2016 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2017 throw new IllegalStateException("Malformed body " + body);
2019 String fqn = body.substring(next + 1, colon4);
2020 String method = body.substring(colon4 + 2, sigBeg);
2021 String params = body.substring(sigBeg, sigEnd + 1);
2023 int paramBeg = body.indexOf('(', sigEnd + 1);
2025 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2026 sb.append(mangleJsCallbacks(fqn, method, params, true));
2032 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2033 if (params.startsWith("(")) {
2034 params = params.substring(1);
2036 if (params.endsWith(")")) {
2037 params = params.substring(0, params.length() - 1);
2039 StringBuilder sb = new StringBuilder();
2040 final String fqnu = fqn.replace('.', '_');
2041 final String rfqn = mangleClassName(fqnu);
2042 final String rm = mangleMethodName(method);
2045 StringBuilder pb = new StringBuilder();
2046 int len = params.length();
2048 while (indx < len) {
2049 char ch = params.charAt(indx);
2050 if (ch == '[' || ch == 'L') {
2051 int column = params.indexOf(';', indx) + 1;
2052 if (column > indx) {
2053 String real = params.substring(indx, column);
2054 if ("Ljava/lang/String;".equals(real)) {
2055 pb.append("Ljava/lang/String;");
2060 pb.append("Ljava/lang/Object;");
2067 srp = mangleSig(pb.toString());
2069 final String rp = mangleSig(params);
2070 final String mrp = mangleMethodName(rp);
2071 sb.append(rfqn).append("$").append(rm).
2072 append('$').append(mrp).append("__Ljava_lang_Object_2");
2074 sb.append('L').append(fqnu).append("_2");
2077 return sb.toString();
2080 private static String className(ClassData jc) {
2081 //return jc.getName().getInternalName().replace('/', '_');
2082 return mangleClassName(jc.getClassName());
2085 private static String[] findAnnotation(
2086 byte[] arr, ClassData cd, final String className,
2087 final String... attrNames
2088 ) throws IOException {
2092 final String[] values = new String[attrNames.length];
2093 final boolean[] found = { false };
2094 final String jvmType = "L" + className.replace('.', '/') + ";";
2095 AnnotationParser ap = new AnnotationParser(false, true) {
2097 protected void visitAttr(String type, String attr, String at, String value) {
2098 if (type.equals(jvmType)) {
2100 for (int i = 0; i < attrNames.length; i++) {
2101 if (attrNames[i].equals(attr)) {
2110 return found[0] ? values : null;
2113 private CharSequence initField(FieldData v) {
2114 final String is = v.getInternalSig();
2115 if (is.length() == 1) {
2116 switch (is.charAt(0)) {
2122 case 'I': return " = 0;";
2124 case 'D': return " = 0.0;";
2126 throw new IllegalStateException(is);
2132 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2133 AnnotationParser ap = new AnnotationParser(true, false) {
2134 int[] cnt = new int[32];
2138 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2139 final String slashType = attrType.substring(1, attrType.length() - 1);
2140 requireReference(slashType);
2142 if (cnt[depth]++ > 0) {
2146 append('"').append(attrType).append("\" : ");
2153 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2159 protected void visitValueStart(String attrName, char type) throws IOException {
2160 if (cnt[depth]++ > 0) {
2164 if (attrName != null) {
2165 append('"').append(attrName).append("\" : ");
2173 protected void visitValueEnd(String attrName, char type) throws IOException {
2181 protected void visitAttr(String type, String attr, String attrType, String value)
2182 throws IOException {
2183 if (attr == null && value == null) {
2190 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2191 throws IOException {
2192 final String slashType = attrType.substring(1, attrType.length() - 1);
2193 requireReference(slashType);
2195 final String cn = mangleClassName(slashType);
2196 append(accessClassFalse(cn))
2197 .append("['valueOf__L").
2199 append("_2Ljava_lang_String_2']('").
2207 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2208 final String name = args[indx];
2212 if (name.contains(",")) {
2213 throw new IOException("Wrong parameter with ',': " + name);
2219 final void emitNoFlush(
2221 final String format, final CharSequence... params
2222 ) throws IOException {
2223 emitImpl(this, format, params);
2225 static final void emit(
2227 final Appendable out,
2228 final String format, final CharSequence... params
2229 ) throws IOException {
2231 emitImpl(out, format, params);
2233 static void emitImpl(final Appendable out,
2234 final String format,
2235 final CharSequence... params) throws IOException {
2236 final int length = format.length();
2239 int paramOffset = format.indexOf('@');
2240 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2241 final char paramChar = format.charAt(paramOffset + 1);
2242 if ((paramChar >= '1') && (paramChar <= '9')) {
2243 final int paramIndex = paramChar - '0' - 1;
2245 out.append(format, processed, paramOffset);
2246 out.append(params[paramIndex]);
2249 processed = paramOffset + 1;
2252 paramOffset = format.indexOf('@', paramOffset + 1);
2255 out.append(format, processed, length);
2258 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2259 append("} catch (e) {\n");
2261 for (TrapData e : traps) {
2265 if (e.catch_cpx != 0) { //not finally
2266 final String classInternalName = jc.getClassName(e.catch_cpx);
2267 addReference(classInternalName);
2268 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2269 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2270 append("var stA0 = e;");
2271 goTo(this, current, e.handler_pc, topMostLabel);
2274 finallyPC = e.handler_pc;
2277 if (finallyPC == -1) {
2280 append("var stA0 = e;");
2281 goTo(this, current, finallyPC, topMostLabel);
2286 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2289 out.append("{ gt = 0; continue X_" + to + "; }");
2291 out.append("{ gt = " + to + "; continue X_0; }");
2294 out.append("{ gt = " + to + "; break IF; }");
2298 private static void emitIf(
2300 Appendable out, String pattern,
2302 int current, int to, int canBack
2303 ) throws IOException {
2305 emitImpl(out, pattern, param);
2306 goTo(out, current, to, canBack);
2309 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2312 case 4: jvmType = "[Z"; break;
2313 case 5: jvmType = "[C"; break;
2314 case 6: jvmType = "[F"; break;
2315 case 7: jvmType = "[D"; break;
2316 case 8: jvmType = "[B"; break;
2317 case 9: jvmType = "[S"; break;
2318 case 10: jvmType = "[I"; break;
2319 case 11: jvmType = "[J"; break;
2320 default: throw new IllegalStateException("Array type: " + atype);
2323 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2324 smapper.popI(), smapper.pushA(), jvmType);
2327 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2328 String typeName = jc.getClassName(type);
2329 String ref = "null";
2330 if (typeName.startsWith("[")) {
2331 typeName = "'[" + typeName + "'";
2333 ref = "vm." + mangleClassName(typeName);
2334 typeName = "'[L" + typeName + ";'";
2337 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2338 smapper.popI(), smapper.pushA(), typeName, ref);
2341 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2342 String typeName = jc.getClassName(type);
2343 int dim = readUByte(byteCodes, ++i);
2344 StringBuilder dims = new StringBuilder();
2346 for (int d = 0; d < dim; d++) {
2348 dims.insert(1, ",");
2350 dims.insert(1, smapper.popI());
2354 if (typeName.charAt(dim) == 'L') {
2355 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2358 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2359 dims.toString(), smapper.pushA(), typeName, fn
2364 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2365 int table = i / 4 * 4 + 4;
2366 int dflt = i + readInt4(byteCodes, table);
2368 int low = readInt4(byteCodes, table);
2370 int high = readInt4(byteCodes, table);
2372 final CharSequence swVar = smapper.popValue();
2373 smapper.flush(this);
2374 append("switch (").append(swVar).append(") {\n");
2375 while (low <= high) {
2376 int offset = i + readInt4(byteCodes, table);
2378 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2381 append(" default: ");
2382 goTo(this, i, dflt, topMostLabel);
2388 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2389 int table = i / 4 * 4 + 4;
2390 int dflt = i + readInt4(byteCodes, table);
2392 int n = readInt4(byteCodes, table);
2394 final CharSequence swVar = smapper.popValue();
2395 smapper.flush(this);
2396 append("switch (").append(swVar).append(") {\n");
2398 int cnstnt = readInt4(byteCodes, table);
2400 int offset = i + readInt4(byteCodes, table);
2402 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2404 append(" default: ");
2405 goTo(this, i, dflt, topMostLabel);
2411 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2412 String type = jc.getClassName(indx);
2413 if (!type.startsWith("[")) {
2415 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2416 smapper.popA(), smapper.pushI(),
2417 mangleClassName(type));
2420 while (type.charAt(cnt) == '[') {
2423 if (type.charAt(cnt) == 'L') {
2424 String component = type.substring(cnt + 1, type.length() - 1);
2425 requireReference(component);
2426 type = "vm." + mangleClassName(component);
2428 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2429 smapper.popA(), smapper.pushI(),
2434 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2435 smapper.popA(), smapper.pushI(), type
2441 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2442 String type = jc.getClassName(indx);
2443 if (!type.startsWith("[")) {
2444 emitNoFlush(smapper,
2445 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2446 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2449 while (type.charAt(cnt) == '[') {
2452 if (type.charAt(cnt) == 'L') {
2453 String component = type.substring(cnt + 1, type.length() - 1);
2454 requireReference(component);
2455 type = "vm." + mangleClassName(component);
2456 emitNoFlush(smapper,
2457 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2458 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2461 emitNoFlush(smapper,
2462 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2463 smapper.getT(0, VarType.REFERENCE, false), type
2469 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2470 for (int j = prev; j <= i; j++) {
2472 final int cc = readUByte(byteCodes, j);
2473 append(Integer.toString(cc));
2477 @JavaScriptBody(args = "msg", body = "")
2478 private static void println(String msg) {
2479 System.err.println(msg);